Compare commits

...
Author SHA1 Message Date
Julius MarmingeandClaude Fable 5 34edc08178 refactor(relay): vendor alchemy's Drizzle.MySQL runtime client
alchemy-run/alchemy#1063 shipped SQL.MySQL + Drizzle.MySQL upstream, but
the latest published release (2.0.0-beta.67, cut 2026-08-01) predates the
merge. Vendor the implementation verbatim (URL parsing into discrete
fields since mysql2's URI path ignores poolConfig, workerd-detected
disableEval + disablePreparedStatements defaults) with the upstream call
shape, so adopting the next alchemy release is delete-the-file plus a
one-line import swap in worker.ts.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-04 12:50:24 +02:00
Julius MarmingeandClaude Fable 5 b46842d790 refactor(relay): generate mysql migrations manually per the alchemy drizzle guide
alchemy's Drizzle.Schema auto-generation is Postgres-only (drizzle-kit has
no programmatic mysql API), so follow the documented MySQL pattern: a
drizzle.config.ts + `drizzle-kit generate`, with migrations checked in and
the database/branch resources pointed at the static migrations/mysql dir.
This also makes RelayMysqlDatabase's props identical to the provisioning
PR, so the cutover deploy no-ops on the database itself.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-04 01:07:19 +02:00
Julius MarmingeandClaude Fable 5 7d4b7d42b8 feat(relay): cut the relay database over from PlanetScale Postgres to Vitess
Ports the relay to PlanetScale's Vitess (MySQL) product:

- schema on drizzle mysql-core; indexed text columns become varchar(255)
  (InnoDB cannot uniquely index unbounded TEXT)
- Vitess stack resources (MySQLDatabase/MySQLBranch/MySQLPassword) with
  Hyperdrive fed from the runtime password's mysql origin; the retired
  Postgres database + role stay in the prod stack until the cutover has
  soaked, so rollback is a revert of this PR
- local Drizzle MySql runtime helper on @effect/sql-mysql2 +
  drizzle-orm/effect-mysql2 (discrete Hyperdrive fields so mysql2 gets
  disableEval for Workers; prepared statements off for Hyperdrive)
- MySQL has no RETURNING / ON CONFLICT: repositories move to
  INSERT IGNORE / ON DUPLICATE KEY UPDATE with affectedRows checks,
  excluded.* becomes values(*), jsonb ->> 'phase' becomes JSON path
- checked-in mysql baseline migration + operational runbook for the
  DMS data migration (docs/operations/relay-postgres-to-vitess-migration.md)

Stacked on relay/provision-vitess-db, which creates the empty database
ahead of this cutover.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-04 01:07:19 +02:00
Julius MarmingeandClaude Fable 5 394dead432 feat(relay): provision the Vitess database ahead of the Postgres cutover
Phase 1 of the relay Postgres -> Vitess migration: create the
t3coderelay-vitess MySQL database in the prod stack and apply the
checked-in baseline schema via the alchemy migration runner, while the
worker keeps running on Postgres. This lets DMS replicate production
data into the target before the cutover PR flips Hyperdrive.

See docs/operations/relay-postgres-to-vitess-migration.md (cutover PR)
for the full runbook.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-04 01:06:09 +02:00
Mike OlsonandJulius Marminge 6f04a5cffb fix(desktop): Niri/Hyprland - Linux secret storage backend (#2916)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-03 22:02:47 +02:00
maria 30c9622806 fix(web): polish interface spacing (#5252) 2026-08-02 23:35:04 -04:00
Julius Marminge 69dfb7f09a fix(desktop): claim the t3code:// scheme default on Linux at startup (#5054) 2026-08-02 21:53:37 +00:00
Theo Browne e60821f0e0 feat: fold legacy models into separate menus (#5190) 2026-08-02 00:45:05 -07:00
Theo BrowneandClaude 64bf016191 fix(server): stop npx service updates from silently leaving the old server running (#5217)
Co-authored-by: Claude <[email protected]>
2026-08-01 22:42:39 -07:00
84 changed files with 4365 additions and 420 deletions

No files matched your search

+41 -2
View File
@@ -9,6 +9,7 @@ import * as Crypto from "effect/Crypto";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
@@ -17,7 +18,9 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -220,20 +223,49 @@ const startup = Effect.gen(function* () {
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
const clerk = yield* DesktopClerk.DesktopClerk;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const updates = yield* DesktopUpdates.DesktopUpdates;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* shellEnvironment.installIntoProcess;
const hasCommandLinePasswordStore =
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
const linuxElectronOptions =
environment.platform === "linux" && !hasCommandLinePasswordStore
? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
: preReadyElectronOptions.linux;
if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
if (
linuxElectronOptions.passwordStore !== null ||
preReadyElectronOptions.linux?.passwordStore !== null
) {
yield* electronApp.removeCommandLineSwitch("password-store");
}
if (linuxElectronOptions.passwordStore !== null) {
yield* electronApp.appendCommandLineSwitch(
"password-store",
linuxElectronOptions.passwordStore,
);
}
}
const userDataPath = yield* appIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
yield* desktopSettings.load;
if (environment.platform === "linux") {
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
if (linuxElectronOptions !== null) {
yield* logStartupInfo("linux password store configured", {
passwordStore: hasCommandLinePasswordStore
? "command-line"
: (linuxElectronOptions.passwordStore ?? "electron-default"),
xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
});
}
yield* appIdentity.configure;
@@ -245,9 +277,16 @@ const startup = Effect.gen(function* () {
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
);
yield* logStartupInfo("app ready");
if (environment.platform === "linux") {
const selectedBackend = yield* safeStorage.selectedStorageBackend;
yield* logStartupInfo("safe storage ready", {
backend: Option.getOrElse(selectedBackend, () => "unknown"),
});
}
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* updates.configure;
yield* linuxUrlHandler.register;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
@@ -64,6 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}),
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
+1
View File
@@ -35,6 +35,7 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
export const DesktopConfig = Config.all({
appDataDirectory: trimmedString("APPDATA"),
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
xdgDataHome: trimmedString("XDG_DATA_HOME"),
t3Home: trimmedString("T3CODE_HOME"),
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
@@ -39,6 +39,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
return decoded.slice("encrypted:".length);
});
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -0,0 +1,121 @@
// @effect-diagnostics nodeBuiltinImport:off - tests use POSIX path joining to match the Linux startup boundary.
import * as NodePath from "node:path";
import { assert, describe, it } from "@effect/vitest";
import {
resolveEarlyLinuxElectronOptions,
resolveEarlyLinuxPasswordStorePreference,
} from "./DesktopEarlyElectronStartup.ts";
describe("DesktopEarlyElectronStartup", () => {
const joinPath = NodePath.posix.join;
it("reads the persisted linux password-store preference before Electron is ready", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/home/user/.t3-test" },
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
},
});
assert.equal(preference, "kwallet6");
});
it("accepts JSONC in the early desktop settings file", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/home/user/.t3-test" },
homeDirectory: "/home/user",
joinPath,
readFileString: () => `{
// manually edited setting
"linuxPasswordStore": "gnome-libsecret",
}`,
});
assert.equal(preference, "gnome-libsecret");
});
it("falls back to auto when the early settings document is missing or invalid", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {},
homeDirectory: "/home/user",
joinPath,
readFileString: () => {
throw new Error("missing");
},
});
assert.equal(preference, "auto");
});
it("preserves absolute root paths when resolving early settings", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/" },
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
},
});
assert.equal(preference, "kwallet6");
});
it("resolves the early linux Electron switches", () => {
const options = resolveEarlyLinuxElectronOptions({
env: {
T3CODE_HOME: "/home/user/.t3-test",
XDG_CURRENT_DESKTOP: "niri",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "auto" });
},
});
assert.deepEqual(options, {
linuxWmClass: "t3code-dev",
passwordStore: "gnome-libsecret",
});
});
it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet" });
},
});
assert.equal(preference, "kwallet");
});
it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {
T3CODE_HOME: " ",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" });
},
});
assert.equal(preference, "gnome-libsecret");
});
});
@@ -0,0 +1,90 @@
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
DEFAULT_LINUX_PASSWORD_STORE,
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
type LinuxPasswordStoreSwitch,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
import {
resolveDesktopBaseDir,
resolveDesktopStateDir,
type JoinPath,
} from "./DesktopStatePaths.ts";
interface EarlyDesktopSettingsInput {
readonly env: NodeJS.ProcessEnv;
readonly homeDirectory: string;
readonly joinPath: JoinPath;
readonly readFileString: (path: string) => string;
}
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
export interface EarlyLinuxElectronOptions {
readonly linuxWmClass: string;
readonly passwordStore: LinuxPasswordStoreSwitch | null;
}
const trimNonEmpty = (value: string | undefined): string | null => {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : null;
};
const EarlyDesktopSettingsJson = fromLenientJson(
Schema.Struct({
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
}),
);
const decodeEarlyDesktopSettingsJson = Schema.decodeSync(EarlyDesktopSettingsJson);
const isDevelopmentEnvironment = (env: NodeJS.ProcessEnv): boolean =>
trimNonEmpty(env.VITE_DEV_SERVER_URL) !== null;
function resolveEarlyDesktopSettingsPath(input: {
readonly env: NodeJS.ProcessEnv;
readonly homeDirectory: string;
readonly joinPath: JoinPath;
}): string {
const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME);
const baseDir = resolveDesktopBaseDir({
homeDirectory: input.homeDirectory,
joinPath: input.joinPath,
t3Home,
});
const stateDir = resolveDesktopStateDir({
baseDir,
isDevelopment: isDevelopmentEnvironment(input.env),
joinPath: input.joinPath,
t3Home,
});
return input.joinPath(stateDir, "desktop-settings.json");
}
export function resolveEarlyLinuxPasswordStorePreference(
input: EarlyDesktopSettingsInput,
): LinuxPasswordStorePreference {
const settingsPath = resolveEarlyDesktopSettingsPath(input);
try {
const parsed = decodeEarlyDesktopSettingsJson(input.readFileString(settingsPath));
return normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore);
} catch {
return DEFAULT_LINUX_PASSWORD_STORE;
}
}
export function resolveEarlyLinuxElectronOptions(
input: EarlyLinuxElectronOptionsInput,
): EarlyLinuxElectronOptions {
const preference = resolveEarlyLinuxPasswordStorePreference(input);
return {
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
passwordStore: resolveLinuxPasswordStoreSwitch({
preference,
env: input.env,
}),
};
}
+19 -5
View File
@@ -13,6 +13,7 @@ import * as Path from "effect/Path";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
export interface MakeDesktopEnvironmentInput {
@@ -66,6 +67,8 @@ export class DesktopEnvironment extends Context.Service<
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly linuxApplicationsDir: string;
readonly appImagePath: Option.Option<string>;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
@@ -147,8 +150,11 @@ 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 configuredBaseDir = config.t3Home;
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
const baseDir = resolveDesktopBaseDir({
homeDirectory,
joinPath: path.join,
t3Home: config.t3Home,
});
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const branding = resolveDesktopAppBranding({
@@ -156,12 +162,18 @@ const make = Effect.fn("desktop.environment.make")(function* (
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = path.join(
const stateDir = resolveDesktopStateDir({
baseDir,
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
);
isDevelopment,
joinPath: path.join,
t3Home: config.t3Home,
});
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const linuxApplicationsDir = path.join(
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
"applications",
);
const resourcesPath = input.resourcesPath;
return DesktopEnvironment.of({
@@ -205,6 +217,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
),
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
linuxApplicationsDir,
appImagePath: config.appImagePath,
userDataDirName,
legacyUserDataDirName,
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
@@ -35,6 +35,7 @@ describe("DesktopLifecycle", () => {
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: (listener) =>
Effect.acquireRelease(
Effect.sync(() => {
@@ -0,0 +1,229 @@
import { assert, describe, it } from "@effect/vitest";
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 PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
interface RecordedRegistration {
readonly directories: string[];
readonly files: Array<{ readonly path: string; readonly content: string }>;
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
}
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
DesktopEnvironment.DesktopEnvironment.of({
platform: "linux",
isPackaged: true,
isDevelopment: false,
displayName: "T3 Code (Alpha)",
linuxWmClass: "t3code",
linuxApplicationsDir: "/home/alice/.local/share/applications",
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
...overrides,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
const mockProcess = (exitCode: number) =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const makeHandlerLayer = (
recorded: RecordedRegistration,
input: {
readonly environment?: Record<string, unknown>;
readonly xdgMimeExitCode?: number;
readonly writeError?: PlatformError.PlatformError;
} = {},
) =>
DesktopLinuxUrlHandler.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
FileSystem.layerNoop({
makeDirectory: (path) =>
Effect.sync(() => {
recorded.directories.push(path);
}),
writeFileString: (path, content) =>
input.writeError
? Effect.fail(input.writeError)
: Effect.sync(() => {
recorded.files.push({ path, content });
}),
}),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
recorded.commands.push({
command: childProcess.command,
args: childProcess.args,
});
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
}),
),
),
),
);
const runRegister = (
recorded: RecordedRegistration,
input: Parameters<typeof makeHandlerLayer>[1] = {},
) =>
Effect.gen(function* () {
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
yield* handler.register;
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
const emptyRecording = (): RecordedRegistration => ({
directories: [],
files: [],
commands: [],
});
describe("DesktopLinuxUrlHandler", () => {
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
displayName: "T3 Code (Nightly)",
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
scheme: "t3code",
});
assert.include(entry, "[Desktop Entry]");
assert.include(entry, "Name=T3 Code (Nightly)");
// Exec composes both escaping layers: a literal backslash becomes four
// backslashes in the file, a quote three characters, a dollar sign two
// backslashes plus the sign.
assert.include(
entry,
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
);
assert.include(entry, "NoDisplay=true");
assert.notInclude(entry, "StartupWMClass=");
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
});
it("carries structured context on registration errors", () => {
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme: "t3code",
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
cause: new Error("boom"),
});
assert.equal(
writeError.message,
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
);
assert.equal(
writeError.desktopEntryPath,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
);
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme: "t3code",
exitCode: 4,
});
assert.equal(
exitError.message,
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
);
});
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded);
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
assert.equal(recorded.files.length, 1);
assert.equal(
recorded.files[0]?.path,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
);
assert.include(
recorded.files[0]?.content,
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
);
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
assert.deepEqual(recorded.commands, [
{
command: "xdg-mime",
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
},
]);
});
});
it.effect("falls back to the process executable outside an AppImage", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
assert.include(
recorded.files[0]?.content,
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
);
});
});
it.effect("does nothing on other platforms or unpackaged builds", () => {
const nonLinux = emptyRecording();
const unpackaged = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
for (const recorded of [nonLinux, unpackaged]) {
assert.deepEqual(recorded.directories, []);
assert.deepEqual(recorded.files, []);
assert.deepEqual(recorded.commands, []);
}
});
});
it.effect("never fails startup when registration cannot complete", () => {
const xdgMimeFailed = emptyRecording();
const writeFailed = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
yield* runRegister(writeFailed, {
writeError: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFileString",
description: "read-only filesystem",
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
}),
});
assert.equal(xdgMimeFailed.files.length, 1);
assert.deepEqual(writeFailed.commands, []);
});
});
});
@@ -0,0 +1,191 @@
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 Schema from "effect/Schema";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
// Linux ships as an AppImage, so the .desktop entry users end up with is
// created by whatever integration tool they use (AppImageLauncher names it
// appimagekit_<hash>-….desktop) and its filename is not under our control.
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
// setDesktopName, which cannot match those files — so the browser keeps
// prompting "Choose an application" for every OAuth callback. Instead, write
// our own handler entry pointing at the current AppImage and claim the
// scheme default via xdg-mime, exactly what the file manager's "set as
// default" checkbox would record in mimeapps.list.
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
"DesktopLinuxUrlHandlerRegistrationError",
{
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
scheme: Schema.String,
desktopEntryPath: Schema.optionalKey(Schema.String),
exitCode: Schema.optionalKey(Schema.Number),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
}
}
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
const escapeDesktopEntryString = (value: string): string =>
value
.replaceAll("\\", "\\\\")
.replaceAll("\n", "\\n")
.replaceAll("\r", "\\r")
.replaceAll("\t", "\\t");
// Exec values are unescaped twice by implementations: first the general
// string-value rules, then the Exec quoting rules — so writing composes the
// layers in reverse. The argument is double-quoted with reserved characters
// backslash-escaped and literal percent signs doubled (field codes), and the
// general string escaping is applied on top: a literal backslash ends up as
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
export function escapeDesktopEntryExecArgument(value: string): string {
const quoted = value
.replaceAll("\\", () => "\\\\")
.replaceAll("`", () => "\\`")
.replaceAll("$", () => "\\$")
.replaceAll('"', () => '\\"')
.replaceAll("%", () => "%%");
return escapeDesktopEntryString(`"${quoted}"`);
}
// The AppImage integration entry owns the window identity and icon. This
// hidden URL-only entry must not compete with it for StartupWMClass matching.
export function renderUrlHandlerDesktopEntry(input: {
readonly displayName: string;
readonly execTarget: string;
readonly scheme: string;
}): string {
return [
"[Desktop Entry]",
"Type=Application",
`Name=${escapeDesktopEntryString(input.displayName)}`,
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
"Terminal=false",
"NoDisplay=true",
"StartupNotify=false",
`MimeType=x-scheme-handler/${input.scheme};`,
"",
].join("\n");
}
export class DesktopLinuxUrlHandler extends Context.Service<
DesktopLinuxUrlHandler,
{
readonly register: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
const desktopEntryPath = environment.path.join(
environment.linuxApplicationsDir,
URL_HANDLER_DESKTOP_ENTRY_NAME,
);
const writeDesktopEntry = Effect.gen(function* () {
// Inside the mounted AppImage, process.execPath points at a transient
// /tmp/.mount_* path — the handler must launch the AppImage itself.
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
yield* fileSystem.writeFileString(
desktopEntryPath,
renderUrlHandlerDesktopEntry({
displayName: environment.displayName,
execTarget,
scheme,
}),
);
}).pipe(
Effect.mapError(
(cause) =>
new DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme,
desktopEntryPath,
cause,
}),
),
);
const setDefaultHandler = Effect.scoped(
Effect.gen(function* () {
const command = ChildProcess.make(
"xdg-mime",
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
{
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
);
const handle = yield* spawner.spawn(command);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) {
return yield* new DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme,
exitCode: Number(exitCode),
});
}
}),
).pipe(
Effect.mapError((error) =>
isRegistrationError(error)
? error
: new DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme,
cause: error,
}),
),
);
const register = Effect.gen(function* () {
if (environment.platform !== "linux" || !environment.isPackaged) {
return;
}
yield* writeDesktopEntry;
yield* setDefaultHandler;
yield* logInfo("registered URL scheme handler", { scheme });
}).pipe(
// Registration is best-effort: a missing xdg-mime or read-only home must
// never block startup — the OS chooser remains as fallback.
Effect.catch((error) =>
logWarning("URL scheme handler registration failed", {
scheme,
step: error.step,
message: error.message,
...(error.desktopEntryPath === undefined
? {}
: { desktopEntryPath: error.desktopEntryPath }),
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
}),
),
Effect.withSpan("desktop.linuxUrlHandler.register"),
);
return DesktopLinuxUrlHandler.of({ register });
});
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
@@ -0,0 +1,130 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
() => ({
appendSwitchMock: vi.fn(),
getSwitchValueMock: vi.fn(),
hasSwitchMock: vi.fn(),
registerSchemesMock: vi.fn(),
}),
);
vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
getSwitchValue: getSwitchValueMock,
hasSwitch: hasSwitchMock,
},
},
protocol: {
registerSchemesAsPrivileged: registerSchemesMock,
},
}));
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
describe("DesktopPreReadyPlatform", () => {
beforeEach(() => {
appendSwitchMock.mockReset();
getSwitchValueMock.mockReset();
hasSwitchMock.mockReset();
registerSchemesMock.mockReset();
});
it("reads an explicit Electron command-line switch value", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: (switchName) => switchName === "password-store",
getSwitchValue: (switchName) => {
assert.equal(switchName, "password-store");
return "basic";
},
},
"password-store",
);
assert.equal(value, "basic");
});
it("treats valueless Electron command-line switches as absent", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: () => true,
getSwitchValue: () => "",
},
"password-store",
);
assert.isNull(value);
});
it("returns null for missing Electron command-line switches", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: () => false,
getSwitchValue: () => {
throw new Error("Unexpected switch value read.");
},
},
"password-store",
);
assert.isNull(value);
});
it.effect(
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
() =>
Effect.gen(function* () {
class ClerkShaped extends Context.Service<ClerkShaped, { readonly ready: true }>()(
"@t3tools/desktop/app/DesktopPreReadyPlatform.test/ClerkShaped",
) {}
const events: Array<string> = [];
registerSchemesMock.mockImplementation(() => {
events.push("pre-ready");
});
const preReadyLayer = DesktopPreReadyPlatform.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
);
const clerkShapedLayer = Layer.effect(
ClerkShaped,
Effect.promise(() => Promise.resolve()).pipe(
Effect.map(() => {
events.push("clerk");
return { ready: true as const };
}),
),
);
const runtimeLayer = clerkShapedLayer.pipe(
Layer.flatMap((clerkContext) => Layer.succeedContext(clerkContext)),
Layer.provideMerge(preReadyLayer),
);
const result = yield* Effect.all({
clerk: ClerkShaped,
preReady: DesktopPreReadyPlatform.DesktopPreReadyElectronOptions,
}).pipe(Effect.provide(runtimeLayer));
assert.deepEqual(result, {
clerk: { ready: true },
preReady: {
linux: null,
linuxPasswordStoreCommandLine: null,
},
});
assert.deepEqual(events, ["pre-ready", "clerk"]);
assert.equal(registerSchemesMock.mock.calls.length, 1);
assert.equal(appendSwitchMock.mock.calls.length, 0);
}),
);
});
@@ -0,0 +1,74 @@
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
export interface DesktopPreReadyCommandLineReader {
readonly hasSwitch: (switchName: string) => boolean;
readonly getSwitchValue: (switchName: string) => string;
}
export function readCommandLineSwitchValue(
commandLine: DesktopPreReadyCommandLineReader,
switchName: string,
): string | null {
if (!commandLine.hasSwitch(switchName)) {
return null;
}
const value = commandLine.getSwitchValue(switchName).trim();
return value.length > 0 ? value : null;
}
export const resolveEarlyLinuxElectronOptionsFromProcess =
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
env: process.env,
homeDirectory: NodeOS.homedir(),
joinPath: NodePath.posix.join,
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
});
export class DesktopPreReadyElectronOptions extends Context.Service<
DesktopPreReadyElectronOptions,
{
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
readonly linuxPasswordStoreCommandLine: string | null;
}
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
const linuxPasswordStoreCommandLine =
platform === "linux"
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
: null;
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
if (linux !== null) {
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
}
}
return { linux, linuxPasswordStoreCommandLine };
});
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
// observe app readiness before scheme privileges and command-line switches exist.
export const layer = Layer.mergeAll(
ElectronProtocol.layerSchemePrivileges,
Layer.effect(DesktopPreReadyElectronOptions, make),
);
+32
View File
@@ -0,0 +1,32 @@
import * as Option from "effect/Option";
export type JoinPath = (first: string, ...segments: string[]) => string;
function normalizeConfiguredBaseDir(t3Home: Option.Option<string>): Option.Option<string> {
if (Option.isNone(t3Home)) {
return Option.none();
}
const trimmed = t3Home.value.trim();
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
}
export function resolveDesktopBaseDir(input: {
readonly homeDirectory: string;
readonly joinPath: JoinPath;
readonly t3Home: Option.Option<string>;
}): string {
return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () =>
input.joinPath(input.homeDirectory, ".t3"),
);
}
export function resolveDesktopStateDir(input: {
readonly baseDir: string;
readonly isDevelopment: boolean;
readonly joinPath: JoinPath;
readonly t3Home: Option.Option<string>;
}): string {
const useDevSubdir =
input.isDevelopment && Option.isNone(normalizeConfiguredBaseDir(input.t3Home));
return input.joinPath(input.baseDir, useDevSubdir ? "dev" : "userdata");
}
@@ -14,6 +14,7 @@ const {
quitMock,
relaunchMock,
removeListenerMock,
removeSwitchMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
@@ -34,6 +35,7 @@ const {
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
removeSwitchMock: vi.fn(),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
@@ -52,6 +54,7 @@ vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
removeSwitch: removeSwitchMock,
},
dock: {
setIcon: setDockIconMock,
@@ -89,6 +92,7 @@ describe("ElectronApp", () => {
quitMock.mockClear();
relaunchMock.mockClear();
removeListenerMock.mockClear();
removeSwitchMock.mockClear();
setPathMock.mockClear();
});
@@ -178,4 +182,13 @@ describe("ElectronApp", () => {
]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("removes command-line switches through the service", () =>
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.removeCommandLineSwitch("password-store");
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
});
+5
View File
@@ -69,6 +69,7 @@ export class ElectronApp extends Context.Service<
readonly onBeforeQuitForUpdate: (
listener: () => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly removeCommandLineSwitch: (switchName: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
@@ -191,6 +192,10 @@ export const make = ElectronApp.of({
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
}),
).pipe(Effect.asVoid),
removeCommandLineSwitch: (switchName) =>
Effect.sync(() => {
Electron.app.commandLine.removeSwitch(switchName);
}),
on: addScopedAppListener,
});
@@ -105,6 +105,38 @@ function withContentSecurityPolicy(response: Response, policy: string): Response
});
}
/**
* Must run synchronously during process bootstrap, before Electron emits `ready`.
*/
export function registerDesktopSchemePrivilegesSync(): void {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_PRODUCTION_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
{
scheme: DESKTOP_DEVELOPMENT_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}
const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
);
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
async function proxyRequest(
request: Request,
targetOrigin: URL,
@@ -1,9 +1,11 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
const electronSafeStorageErrorFields = {
cause: Schema.Defect(),
@@ -60,24 +62,39 @@ export class ElectronSafeStorage extends Context.Service<
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
readonly selectedStorageBackend: Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
export const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
}),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
}),
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
}),
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
}),
selectedStorageBackend: Effect.sync(() => {
if (platform !== "linux") {
return Option.none();
}
try {
return Option.fromNullishOr(Electron.safeStorage.getSelectedStorageBackend());
} catch {
return Option.none();
}
}),
});
});
export const layer = Layer.succeed(ElectronSafeStorage, make);
export const layer = Layer.effect(ElectronSafeStorage, make);
+203
View File
@@ -0,0 +1,203 @@
import { describe, expect, it } from "vite-plus/test";
import {
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
resolveLinuxSecretStorageUnavailableMessage,
} from "./linuxSecretStorage.ts";
const autoSwitch = (env: NodeJS.ProcessEnv) =>
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
describe("linuxSecretStorage", () => {
it("preserves explicit supported password-store preferences", () => {
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
});
it("falls back to auto for missing or unsupported preferences", () => {
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
});
it("uses explicit preferences instead of the auto heuristic", () => {
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
).toBe(preference);
// An explicit preference also wins where auto would have stayed out of the way.
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
).toBe(preference);
}
});
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
});
it("does not force a password-store for desktops Electron already recognizes", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
}
});
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
});
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
expect(autoSwitch({})).toBe("gnome-libsecret");
});
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
});
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("overrides KDE sessions identified only by legacy variables", () => {
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
// basic text for the rest. Either way these are the variables a previous session leaves behind,
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
for (const session of [
"kde",
"kde-plasma",
"kde4",
"plasma",
"plasmawayland",
"plasmawayland-dev",
"plasmax11",
"plasmax11-dev",
]) {
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
}
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
expect(
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
).toBe("gnome-libsecret");
// A previous KDE session left these behind; the compositor running now is not KDE.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
expect(
autoSwitch({
XDG_CURRENT_DESKTOP: "Hyprland",
XDG_SESSION_DESKTOP: "KDE",
KDE_SESSION_VERSION: "6",
}),
).toBe("gnome-libsecret");
});
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "gnome-libsecret",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet6",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet",
selectedBackend: "gnome-libsecret",
env: {},
}),
).toContain("KWallet");
});
it("uses KWallet remediation wording for KDE-looking sessions", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "kwallet6",
env: {},
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { DESKTOP_SESSION: "plasmawayland" },
}),
).toContain("KWallet");
// A desktop name outranks a bare KDE marker when choosing the wording.
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
}),
).toContain("GNOME Keyring");
});
});
+178
View File
@@ -0,0 +1,178 @@
export type LinuxPasswordStorePreference =
| "auto"
| "gnome-libsecret"
| "kwallet"
| "kwallet5"
| "kwallet6";
export type LinuxPasswordStoreSwitch = Exclude<LinuxPasswordStorePreference, "auto">;
export const DEFAULT_LINUX_PASSWORD_STORE: LinuxPasswordStorePreference = "auto";
// Chromium matches XDG_CURRENT_DESKTOP values case-sensitively and returns on the first value it
// recognizes, so these stay exact literals and are scanned in order. Omitting a real desktop fails
// safe: we force gnome-libsecret, which is the backend Chromium selects for all of these anyway.
const ELECTRON_LIBSECRET_DESKTOPS = new Set([
"Deepin",
"GNOME",
"Pantheon",
"UKUI",
"Unity",
"X-Cinnamon",
"XFCE",
]);
// Chromium selects a KWallet generation for KDE from KDE_SESSION_VERSION, so it needs no help.
const ELECTRON_KDE_DESKTOP = "KDE";
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
const KDE_NAME_PREFIXES = ["kde", "plasma"];
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
export function normalizeLinuxPasswordStorePreference(
value: unknown,
): LinuxPasswordStorePreference {
return value === "gnome-libsecret" ||
value === "kwallet" ||
value === "kwallet5" ||
value === "kwallet6"
? value
: DEFAULT_LINUX_PASSWORD_STORE;
}
// Auto mode asks one question: will Electron select a real keyring on its own? If so, stay out of
// the way, which is how canonical KDE sessions keep the KWallet generation Chromium picks for them.
// Otherwise force gnome-libsecret, because the alternative is basic text, which is barely
// encryption at all. Forcing never guesses a KWallet generation; a KDE session that needs a
// specific one sets linuxPasswordStore explicitly.
export function resolveLinuxPasswordStoreSwitch(input: {
readonly preference: LinuxPasswordStorePreference;
readonly env: NodeJS.ProcessEnv;
}): LinuxPasswordStoreSwitch | null {
if (input.preference !== "auto") {
return input.preference;
}
return electronSelectsProtectedBackend(input.env) ? null : "gnome-libsecret";
}
// Only an exact XDG_CURRENT_DESKTOP literal proves Electron will protect the session. Chromium can
// also reach a real backend through DESKTOP_SESSION and the legacy KDE markers, but those are the
// variables a previous session leaves behind, and trusting them is what let stale hints suppress
// the forced backend before. Forcing where Chromium would have chosen libsecret is harmless, since
// it lands on the same backend.
function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
for (const name of splitDesktopNameList(env.XDG_CURRENT_DESKTOP)) {
const trimmed = name.trim();
if (trimmed.length === 0) {
continue;
}
if (trimmed === ELECTRON_KDE_DESKTOP || ELECTRON_LIBSECRET_DESKTOPS.has(trimmed)) {
return true;
}
if (ELECTRON_UNPROTECTED_DESKTOPS.has(trimmed)) {
return false;
}
}
return false;
}
export function resolveLinuxSecretStorageUnavailableMessage(input: {
readonly configuredPreference: LinuxPasswordStorePreference;
readonly selectedBackend: string | null;
readonly env: NodeJS.ProcessEnv;
}): string {
if (input.configuredPreference === "gnome-libsecret") {
return getGnomeKeyringRemediationMessage();
}
if (
input.configuredPreference === "kwallet" ||
input.configuredPreference === "kwallet5" ||
input.configuredPreference === "kwallet6"
) {
return getKWalletRemediationMessage();
}
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
if (backend === "gnome-libsecret") {
return getGnomeKeyringRemediationMessage();
}
if (
backend === "kwallet" ||
backend === "kwallet5" ||
backend === "kwallet6" ||
looksLikeKdeSession(input.env)
) {
return getKWalletRemediationMessage();
}
return getGnomeKeyringRemediationMessage();
}
function getGnomeKeyringRemediationMessage(): string {
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
}
function getKWalletRemediationMessage(): string {
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
}
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
// rather than an unprotected credential store.
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
if (currentDesktopNames.length > 0) {
return currentDesktopNames.some(isKdeDesktopName);
}
const legacyNames = legacyDesktopNames(env);
if (legacyNames.length > 0) {
return legacyNames.some(isKdeDesktopName);
}
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
}
function isKdeDesktopName(name: string): boolean {
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
}
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
const normalized = normalizeDesktopName(entry);
return normalized ? [normalized] : [];
});
}
function nonEmptyDesktopNames(value: string | undefined): string[] {
return splitDesktopNameList(value).flatMap((entry) => {
const normalized = normalizeDesktopName(entry);
return normalized ? [normalized] : [];
});
}
function isSet(value: string | undefined): boolean {
return Boolean(value?.trim());
}
function isAffirmativeFlag(value: string | undefined): boolean {
const normalized = value?.trim().toLowerCase();
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
}
function splitDesktopNameList(value: string | undefined): string[] {
return value?.split(":") ?? [];
}
function normalizeDesktopName(value: string | undefined): string | null {
const normalized = value?.trim().toLowerCase();
return normalized && normalized.length > 0 ? normalized : null;
}
function normalizeSelectedStorageBackend(value: string | null): string | null {
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
return normalized && normalized.length > 0 ? normalized : null;
}
+14 -7
View File
@@ -43,12 +43,14 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
import * as DesktopObservability from "./app/DesktopObservability.ts";
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
@@ -181,6 +183,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopLinuxUrlHandler.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
@@ -195,16 +198,20 @@ const desktopClerkLayer = DesktopClerk.layer.pipe(
Layer.provideMerge(ElectronApp.layer),
);
const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
);
// Acquire strict pre-ready setup before Clerk, whose userData resolution can
// yield and let Electron emit ready.
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
),
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
),
Layer.provideMerge(DesktopPreReadyPlatform.layer),
);
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
@@ -11,6 +11,9 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({
linuxPasswordStore: Schema.optionalKey(
Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]),
),
mainWindowBounds: Schema.optionalKey(
Schema.NullOr(
Schema.Struct({
@@ -102,6 +105,7 @@ describe("DesktopSettings", () => {
assert.deepEqual(
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
{
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -121,6 +125,7 @@ describe("DesktopSettings", () => {
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
linuxPasswordStore: "gnome-libsecret",
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
@@ -129,6 +134,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "gnome-libsecret",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -235,6 +241,7 @@ describe("DesktopSettings", () => {
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -268,6 +275,44 @@ describe("DesktopSettings", () => {
),
);
it.effect(
"normalizes unsupported linux password-store values without dropping other settings",
() =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.desktopSettingsPath,
`{
"linuxPasswordStore": "unsupported-store",
"serverExposureMode": "network-accessible",
"tailscaleServeEnabled": true,
"tailscaleServePort": 8443,
"updateChannel": "nightly",
"updateChannelConfiguredByUser": true
}\n`,
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
);
it.effect("persists sparse desktop settings documents", () =>
withSettings(
Effect.gen(function* () {
@@ -300,6 +345,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -327,6 +373,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -353,6 +400,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -16,10 +16,16 @@ import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import {
DEFAULT_LINUX_PASSWORD_STORE,
normalizeLinuxPasswordStorePreference,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
export interface DesktopSettings {
readonly linuxPasswordStore: LinuxPasswordStorePreference;
readonly mainWindowBounds: DesktopWindowBounds | null;
readonly mainWindowMaximized: boolean;
readonly serverExposureMode: DesktopServerExposureMode;
@@ -67,6 +73,7 @@ export const DEFAULT_MAIN_WINDOW_SIZE = {
} as const;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE,
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -87,6 +94,7 @@ const DesktopWindowBoundsDocument = Schema.Struct({
});
const DesktopSettingsDocument = Schema.Struct({
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
@@ -216,6 +224,7 @@ function normalizeDesktopSettingsDocument(
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
return {
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
mainWindowBounds,
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
serverExposureMode:
@@ -238,6 +247,9 @@ function toDesktopSettingsDocument(
): DesktopSettingsDocument {
const document: Mutable<DesktopSettingsDocument> = {};
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
document.linuxPasswordStore = settings.linuxPasswordStore;
}
if (settings.mainWindowBounds !== null) {
document.mainWindowBounds = settings.mainWindowBounds;
}
@@ -86,6 +86,7 @@ function makeSafeStorageLayer(input: {
}
return Effect.succeed(decoded.slice("enc:".length));
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -1,3 +1,4 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -90,7 +91,7 @@ function runShellEnvironment(input: {
}).pipe(
Effect.provide(
DesktopShellEnvironment.layer.pipe(
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
),
),
);
@@ -243,6 +244,65 @@ describe("DesktopShellEnvironment", () => {
}),
);
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
XDG_CURRENT_DESKTOP: "wrong-launcher",
XDG_SESSION_DESKTOP: "wrong-launcher",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
XDG_CURRENT_DESKTOP: "KDE",
XDG_SESSION_DESKTOP: "KDE",
XDG_SESSION_TYPE: "wayland",
}),
});
assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
assert.equal(env.XDG_SESSION_TYPE, "wayland");
}),
);
it.effect("overrides stale dbus session addresses from the login shell", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/usr/bin",
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
}),
});
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
}),
);
it("resolves dbus runtime dir candidates with existence checks", () => {
const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
uid: 1000,
exists: (path) => path === "/run/user/1000/bus",
});
assert.equal(busPath, "unix:path=/run/user/1000/bus");
});
it.effect("logs command failures with safe probe context and the exact cause", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/bash",
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
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 Schema from "effect/Schema";
@@ -68,12 +69,19 @@ export class DesktopShellEnvironment extends Context.Service<
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_CURRENT_DESKTOP",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
"WAYLAND_DISPLAY",
] as const;
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
@@ -92,6 +100,47 @@ const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";"
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
const linuxRuntimeDirCandidates = (
env: NodeJS.ProcessEnv,
uid: number | undefined,
): ReadonlyArray<string> => {
const candidates: string[] = [];
const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
if (Option.isSome(fromEnv)) {
candidates.push(normalizeRuntimeDir(fromEnv.value));
}
if (uid !== undefined) {
candidates.push(`/run/user/${uid}`);
}
return candidates.filter((candidate) => candidate.length > 0);
};
function resolveDefaultLinuxDbusSessionBusPath(input: {
readonly env: NodeJS.ProcessEnv;
readonly uid: number | undefined;
readonly exists?: (path: string) => boolean;
}): string | null {
for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
const busPath = `${runtimeDir}/bus`;
if (input.exists === undefined || input.exists(busPath)) {
return busPath;
}
}
return null;
}
export function resolveDefaultLinuxDbusSessionBusAddress(input: {
readonly env: NodeJS.ProcessEnv;
readonly exists: (path: string) => boolean;
readonly uid: number | undefined;
}): string | null {
const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
}
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
const normalized = entry.trim().replace(/^"+|"+$/g, "");
return platform === "win32" ? normalized.toLowerCase() : normalized;
@@ -356,7 +405,12 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
): Effect.fn.Return<
void,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
> {
const fileSystem = yield* FileSystem.FileSystem;
const shellEnvironment: EnvironmentPatch = {};
for (const shell of listLoginShellCandidates(config)) {
@@ -383,23 +437,54 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
const shellPreferredEnvNames = [
"DBUS_SESSION_BUS_ADDRESS",
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
] as const;
for (const name of shellPreferredEnvNames) {
if (shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
for (const name of [
"DISPLAY",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"WAYLAND_DISPLAY",
] as const) {
if (!config.env[name] && shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
if (
config.platform === "linux" &&
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
) {
for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
const dbusSessionBusPath = `${runtimeDir}/bus`;
const busExists = yield* fileSystem
.exists(dbusSessionBusPath)
.pipe(Effect.orElseSucceed(() => false));
if (busExists) {
config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
break;
}
}
}
},
);
const installShellEnvironment = (
config: ShellEnvironmentConfig,
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
if (config.platform === "win32") {
return installWindowsEnvironment(config);
}
@@ -411,6 +496,7 @@ const installShellEnvironment = (
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
installShellEnvironment({
@@ -418,6 +504,7 @@ export const make = Effect.gen(function* () {
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
);
@@ -43,6 +43,7 @@ function makeElectronAppLayer(
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
@@ -46,6 +46,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
@@ -43,7 +43,7 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
@@ -543,27 +543,7 @@ export function NewTaskDraftScreen(props: {
);
const modelMenuActions = useMemo(
() =>
flow.providerGroups.map((group) => ({
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: group.models.find(
(model) =>
flow.selectedModel &&
model.selection.instanceId === flow.selectedModel.instanceId &&
model.selection.model === flow.selectedModel.model,
)?.label,
subactions: group.models.map((option) => ({
id: `model:${option.key}`,
title: option.label,
state:
flow.selectedModel &&
option.selection.instanceId === flow.selectedModel.instanceId &&
option.selection.model === flow.selectedModel.model
? ("on" as const)
: undefined,
})),
})),
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
@@ -53,7 +53,7 @@ import {
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import {
@@ -606,25 +606,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() =>
providerGroups.map((group) => ({
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: group.models.find(
(model) =>
model.selection.instanceId === currentModelSelection.instanceId &&
model.selection.model === currentModelSelection.model,
)?.label,
subactions: group.models.map((option) => ({
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === currentModelSelection.instanceId &&
option.selection.model === currentModelSelection.model
? ("on" as const)
: undefined,
})),
})),
() => buildModelMenuActions(providerGroups, currentModelSelection),
[providerGroups, currentModelSelection],
);
+84 -1
View File
@@ -2,9 +2,92 @@ import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
import { buildModelOptions, resolveSelectableModelSelection } from "./modelOptions";
import {
buildModelMenuActions,
buildModelOptions,
groupByProvider,
resolveSelectableModelSelection,
} from "./modelOptions";
describe("mobile model options", () => {
it("folds legacy models into a provider-scoped menu", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{
slug: "gpt-5.6-sol",
name: "GPT-5.6 Sol",
isCustom: false,
capabilities: null,
},
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null);
expect(actions).toMatchObject([
{
title: "Codex",
subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }],
},
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }],
},
]);
});
it("omits an empty provider menu when every model is legacy", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
expect(
buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null),
).toMatchObject([
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4" }],
},
]);
});
it("normalizes a legacy fallback selection against current capabilities", () => {
const config = {
providers: [
+54
View File
@@ -3,6 +3,7 @@ import type {
ModelSelection,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionDescriptors,
@@ -16,6 +17,7 @@ export type ModelOption = {
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly isLegacy: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -105,6 +107,7 @@ export function buildModelOptions(
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
isLegacy: model.isLegacy === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -135,6 +138,7 @@ export function buildModelOptions(
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
isLegacy: false,
capabilities: null,
selection: fallbackModelSelection,
});
@@ -164,3 +168,53 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
models: group.models,
}));
}
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
return {
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === selectedModel?.instanceId &&
option.selection.model === selectedModel.model
? "on"
: undefined,
};
}
export function buildModelMenuActions(
groups: ReadonlyArray<ProviderGroup>,
selectedModel: ModelSelection | null,
): MenuAction[] {
return groups.flatMap((group) => {
const currentModels = group.models.filter((model) => !model.isLegacy);
const legacyModels = group.models.filter((model) => model.isLegacy);
const selected = group.models.find(
(model) =>
model.selection.instanceId === selectedModel?.instanceId &&
model.selection.model === selectedModel.model,
);
return [
...(currentModels.length > 0
? [
{
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
...(legacyModels.length > 0
? [
{
id: `legacy-models:${group.providerKey}`,
title: `${group.providerLabel} legacy models`,
subtitle: selected?.isLegacy ? selected.label : undefined,
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
];
});
}
+17 -2
View File
@@ -33,6 +33,7 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
platform: NodeJS.Platform = "linux",
usePinnedLauncher = false,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -44,6 +45,10 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3");
yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
yield* fs.writeFileString(runtime.entryPath, "export {};\n");
yield* fs.writeFileString(
path.join(path.dirname(runtime.entryPath), "service-launcher.mjs"),
"export const source = 'pinned runtime';\n",
);
yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
const commands: string[] = [];
@@ -69,8 +74,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
cliVersion: "1.2.3",
host: {
execPath: "/usr/bin/node",
cliEntryPath: path.join(home, "bin.mjs"),
launcherSourcePath: sourceLauncher,
...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
},
}).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, runner),
@@ -109,6 +113,17 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("copies the launcher from the prepared pinned runtime", () =>
Effect.gen(function* () {
const { service, fs } = yield* makeHarness("linux", true);
const plan = yield* service.install;
expect(yield* fs.readFileString(plan.launcherPath)).toBe(
"export const source = 'pinned runtime';\n",
);
}),
);
it.effect("restarts an installed service when repair fails", () =>
Effect.gen(function* () {
const { service, commands, control } = yield* makeHarness();
+5 -13
View File
@@ -1,8 +1,4 @@
import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -138,7 +134,6 @@ export class BootService extends Context.Service<
export interface BootServiceHost {
readonly execPath: string;
readonly cliEntryPath: string;
readonly launcherSourcePath?: string;
}
@@ -148,26 +143,23 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
readonly cliVersion: string;
readonly host?: BootServiceHost;
}) {
const hostArguments = yield* HostProcessArguments;
const hostExecPath = yield* HostProcessExecutablePath;
const platform = yield* HostProcessPlatform;
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const host = input.host ?? {
execPath: hostExecPath,
cliEntryPath: hostArguments[1] ?? "",
};
const host = input.host ?? { execPath: hostExecPath };
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const logPath = path.join(input.logsDir, "boot-service.log");
const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
const launcherSourcePath =
host.launcherSourcePath ?? path.join(path.dirname(host.cliEntryPath), SERVICE_LAUNCHER_FILE);
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
const launcherSourcePath =
host.launcherSourcePath ??
path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
const writeDurably = (filePath: string, contents: string) =>
Effect.scoped(
Effect.gen(function* () {
@@ -9,11 +9,27 @@ import * as Schema from "effect/Schema";
import {
buildClaudeCapabilitiesProbeQueryOptions,
CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
isLegacyClaudeModel,
probeClaudeCapabilities,
} from "./ClaudeProvider.ts";
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
it("keeps only the Claude 5 family out of legacy models", () => {
assert.deepStrictEqual(
["claude-fable-5", "claude-opus-5", "claude-sonnet-5", "claude-opus-4-8"].map((model) => [
model,
isLegacyClaudeModel(model),
]),
[
["claude-fable-5", false],
["claude-opus-5", false],
["claude-sonnet-5", false],
["claude-opus-4-8", true],
],
);
});
it("isolates Claude capability probes without dropping workspace setting sources", () => {
const abortController = new AbortController();
const options = buildClaudeCapabilitiesProbeQueryOptions({
@@ -56,7 +56,13 @@ const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
const CURRENT_CLAUDE_MODELS = new Set(["claude-fable-5", "claude-opus-5", "claude-sonnet-5"]);
export function isLegacyClaudeModel(model: string): boolean {
return !CURRENT_CLAUDE_MODELS.has(model);
}
const CLAUDE_MODEL_CATALOG: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-fable-5",
name: "Claude Fable 5",
@@ -309,6 +315,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = CLAUDE_MODEL_CATALOG.map((model) =>
isLegacyClaudeModel(model.slug) ? { ...model, isLegacy: true } : model,
);
function supportsClaudeOpus5(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
}
@@ -1,6 +1,25 @@
import { assert, it } from "@effect/vitest";
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
import {
applyPreferredCodexDefaultModel,
isLegacyCodexModel,
mapCodexModelCapabilities,
} from "./CodexProvider.ts";
it("keeps only the GPT-5.6 Codex family out of legacy models", () => {
assert.deepStrictEqual(
["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol", "gpt-5.4"].map((model) => [
model,
isLegacyCodexModel(model),
]),
[
["gpt-5.6-luna", false],
["gpt-5.6-terra", false],
["gpt-5.6-sol", false],
["gpt-5.4", true],
],
);
});
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
@@ -62,6 +62,11 @@ const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
};
const DEFAULT_SERVICE_TIER_ID = "default";
const CURRENT_CODEX_MODELS = new Set(["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol"]);
export function isLegacyCodexModel(model: string): boolean {
return !CURRENT_CODEX_MODELS.has(model);
}
function reasoningEffortLabel(reasoningEffort: string): string {
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
@@ -190,6 +195,7 @@ function parseCodexModelListResponse(
name: toDisplayName(model),
isCustom: false,
...(model.isDefault ? { isDefault: true } : {}),
...(isLegacyCodexModel(model.model) ? { isLegacy: true } : {}),
capabilities: mapCodexModelCapabilities(model),
}));
}
+1 -1
View File
@@ -304,7 +304,7 @@ export const BranchToolbar = memo(function BranchToolbar({
if (!hasActiveThread || !activeProject) return null;
return (
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 px-1 pt-5 pb-1">
<div className="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1">
{isMobile ? (
<MobileRunContextSelector
envLocked={envLocked}
+1 -1
View File
@@ -5643,7 +5643,7 @@ function ChatViewContent(props: ChatViewProps) {
/>
);
const panelLayoutControls = (
<div className="workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]">
<div className="workspace-titlebar-controls z-50 mr-px gap-1 [-webkit-app-region:no-drag]">
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
<RightPanelMaximizeControl
maximized={rightPanelMaximized}
@@ -1693,7 +1693,7 @@ export default function GitActionsControl({
render={
<Button
aria-disabled="true"
className="cursor-not-allowed rounded-e-none border-e-0 opacity-64 before:rounded-e-none"
className="cursor-not-allowed rounded-e-none border-e-0 ps-[8.5px] opacity-64 before:rounded-e-none"
size="xs"
variant="outline"
/>
@@ -1715,6 +1715,7 @@ export default function GitActionsControl({
<Button
variant="outline"
size="xs"
className="ps-[8.5px]"
disabled={isGitActionRunning || quickAction.disabled}
onClick={runQuickAction}
>
+2 -2
View File
@@ -2674,7 +2674,7 @@ export default function SidebarV2() {
render={
<SidebarMenuButton
aria-label="Filter threads by project"
className="min-w-0 flex-1 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
className="min-w-0 flex-1 ps-[calc(var(--sidebar-row-content-inset)-1px)] focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
/>
}
>
@@ -2765,7 +2765,7 @@ export default function SidebarV2() {
</SidebarGroup>
}
>
<SidebarGroup className="px-[var(--sidebar-content-inset)] pb-1 pt-0">
<SidebarGroup className="ps-[calc(var(--sidebar-content-inset)+1px)] pe-[var(--sidebar-content-inset)] pb-1 pt-0">
{isSearchingThreads ? (
threadSearchResults.length > 0 ? (
<TooltipProvider
@@ -3104,7 +3104,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{/* Bottom toolbar */}
{isComposerCollapsedMobile ? null : activePendingApproval ? (
<div className="flex items-center justify-end gap-2 px-2.5 pb-2.5 sm:px-3 sm:pb-3">
<div className="flex items-center justify-end gap-2 px-3 pb-3 sm:px-4 sm:pb-4">
<ComposerPendingApprovalActions
requestId={activePendingApproval.requestId}
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
@@ -3116,7 +3116,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
data-chat-composer-footer="true"
data-chat-composer-footer-compact={isComposerFooterCompact ? "true" : "false"}
className={cn(
"flex min-w-0 flex-nowrap items-center justify-between gap-2 overflow-visible px-2.5 pb-2.5 sm:px-3 sm:pb-3",
"flex min-w-0 flex-nowrap items-center justify-between gap-2 overflow-visible px-3 pb-3 sm:px-4 sm:pb-4",
pendingUserInputs.length > 0 && "pt-2",
isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0",
showMobilePendingAnswerActions && "hidden sm:flex",
@@ -3145,6 +3145,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
instanceEntries={providerInstanceEntries}
keybindings={keybindings}
modelOptionsByInstance={modelOptionsByInstance}
triggerClassName="-ms-px ps-0"
terminalOpen={terminalOpen}
open={isComposerModelPickerOpen}
{...(composerProviderState.modelPickerIconClassName
@@ -21,7 +21,7 @@ export function ContextWindowMeter(props: {
const normalizedPercentage = Math.max(0, Math.min(100, usage.usedPercentage ?? 0));
const radius = 9.75;
const circumference = 2 * Math.PI * radius;
const dashOffset = circumference - (normalizedPercentage / 100) * circumference;
const dashOffset = circumference * (1 - normalizedPercentage / 100);
const totalProcessedTokens = usage.totalProcessedTokens ?? null;
const showTotalProcessed = totalProcessedTokens !== null && totalProcessedTokens > 0;
const isOverloaded = normalizedPercentage > 90;
@@ -73,7 +73,7 @@ export function ContextWindowMeter(props: {
strokeLinecap="round"
strokeDasharray={circumference}
strokeDashoffset={dashOffset}
className="transition-[stroke-dashoffset] duration-500 ease-out motion-reduce:transition-none"
className="transition-[stroke-dashoffset,stroke] duration-500 ease-out motion-reduce:transition-none"
/>
</svg>
</span>
@@ -84,9 +84,10 @@ export function ContextWindowMeter(props: {
tooltipStyle
side="top"
align="end"
className="dropdown-glass w-64 max-w-none border-0! bg-secondary! p-0 shadow-none! before:hidden"
viewportClassName="p-0"
className="w-64 max-w-none text-left whitespace-normal"
>
<div className="flex flex-col gap-2 p-3">
<div className="flex flex-col gap-2 p-[var(--floating-content-inset)]">
<div className="flex items-center justify-between gap-3">
<div className="font-medium text-muted-foreground text-xs">Context Window</div>
{usage.maxTokens !== null && usedPercentage ? (
@@ -12,6 +12,7 @@ import { Button } from "../ui/button";
import { Kbd } from "../ui/kbd";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { cn } from "~/lib/utils";
import { modelPickerModelKey } from "./modelPickerKeys";
export const ModelListRow = memo(function ModelListRow(props: {
index: number;
@@ -46,7 +47,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
<ComboboxItem
hideIndicator
index={props.index}
value={`${props.instanceId}:${props.model.slug}`}
value={modelPickerModelKey(props.instanceId, props.model.slug)}
disabled={Boolean(props.disabledReason)}
contentClassName="flex w-full items-center gap-3"
className={cn(
@@ -6,12 +6,24 @@ import {
import { resolveSelectableModel } from "@t3tools/shared/model";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
import { SearchIcon } from "lucide-react";
import { ChevronRightIcon, SearchIcon } from "lucide-react";
import { ModelListRow } from "./ModelListRow";
import { ModelPickerSidebar } from "./ModelPickerSidebar";
import {
modelPickerLegacySectionKey,
modelPickerModelKey,
parseModelPickerLegacySectionKey,
parseModelPickerModelKey,
} from "./modelPickerKeys";
import { isModelPickerNewModel } from "./modelPickerModelHighlights";
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxListVirtualized } from "../ui/combobox";
import {
Combobox,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxListVirtualized,
} from "../ui/combobox";
import { ModelEsque } from "./providerIconUtils";
import {
modelPickerJumpCommandForIndex,
@@ -39,6 +51,7 @@ type ModelPickerItem = {
instanceDisplayName: string;
instanceAccentColor?: string | undefined;
continuationGroupKey?: string | undefined;
isLegacy?: boolean | undefined;
};
const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
@@ -47,20 +60,6 @@ function ModelListSeparator() {
return <div className="h-0.5" />;
}
// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs
// can contain colons (e.g. some vendor model ids), so we only split on the
// first colon — anything after that is the slug.
function splitInstanceModelKey(key: string): { instanceId: ProviderInstanceId; slug: string } {
const colonIndex = key.indexOf(":");
if (colonIndex === -1) {
return { instanceId: key as ProviderInstanceId, slug: "" };
}
return {
instanceId: key.slice(0, colonIndex) as ProviderInstanceId,
slug: key.slice(colonIndex + 1),
};
}
export const ModelPickerContent = memo(function ModelPickerContent(props: {
/** The instance currently selected in the composer (combobox "value"). */
activeInstanceId: ProviderInstanceId;
@@ -117,6 +116,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
return favorites.length > 0 ? "favorites" : props.activeInstanceId;
},
);
const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
() =>
new Set<ProviderInstanceId>(
modelOptionsByInstance
.get(props.activeInstanceId)
?.some((model) => model.slug === props.model && model.isLegacy)
? [props.activeInstanceId]
: [],
),
);
const keybindings = useMemo<ResolvedKeybindingsConfig>(
() => providedKeybindings ?? [],
[providedKeybindings],
@@ -211,6 +220,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
name: model.name,
...(model.shortName ? { shortName: model.shortName } : {}),
...(model.subProvider ? { subProvider: model.subProvider } : {}),
...(model.isLegacy ? { isLegacy: true } : {}),
instanceId,
driverKind: entry.driverKind,
instanceDisplayName: entry.displayName,
@@ -366,6 +376,45 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
selectedInstanceId,
]);
const legacySection = useMemo(() => {
if (isSearching || selectedInstanceId === "favorites") {
return null;
}
const currentModels = filteredModels.filter((model) => !model.isLegacy);
const legacyModels = filteredModels.filter((model) => model.isLegacy);
if (legacyModels.length === 0) {
return null;
}
return {
key: modelPickerLegacySectionKey(selectedInstanceId),
currentModels,
legacyModels,
isExpanded: expandedLegacyInstances.has(selectedInstanceId),
};
}, [expandedLegacyInstances, filteredModels, isSearching, selectedInstanceId]);
const visibleModels = useMemo(() => {
if (!legacySection) {
return filteredModels;
}
return [
...legacySection.currentModels,
...(legacySection.isExpanded ? legacySection.legacyModels : []),
];
}, [filteredModels, legacySection]);
const toggleLegacySection = useCallback((instanceId: ProviderInstanceId) => {
setExpandedLegacyInstances((expanded) => {
const next = new Set(expanded);
if (next.has(instanceId)) {
next.delete(instanceId);
} else {
next.add(instanceId);
}
return next;
});
}, []);
const handleModelSelect = useCallback(
(modelSlug: string, instanceId: ProviderInstanceId) => {
if (getModelDisabledReason?.(instanceId, modelSlug)) {
@@ -410,7 +459,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
>();
let selectableModelIndex = 0;
for (const model of filteredModels) {
for (const model of visibleModels) {
if (getModelDisabledReason?.(model.instanceId, model.slug)) {
continue;
}
@@ -418,27 +467,44 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
if (!jumpCommand) {
return mapping;
}
mapping.set(`${model.instanceId}:${model.slug}`, jumpCommand);
mapping.set(modelPickerModelKey(model.instanceId, model.slug), jumpCommand);
selectableModelIndex += 1;
}
return mapping;
}, [filteredModels, getModelDisabledReason]);
}, [getModelDisabledReason, visibleModels]);
const modelJumpModelKeys = useMemo(
() => [...modelJumpCommandByKey.keys()],
[modelJumpCommandByKey],
);
const allModelKeys = useMemo(
(): string[] => flatModels.map((model) => `${model.instanceId}:${model.slug}`),
const allItemKeys = useMemo(
(): string[] => [
...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
...new Set(
flatModels
.filter((model) => model.isLegacy)
.map((model) => modelPickerLegacySectionKey(model.instanceId)),
),
],
[flatModels],
);
const filteredModelKeys = useMemo(
(): string[] => filteredModels.map((model) => `${model.instanceId}:${model.slug}`),
[filteredModels],
);
const filteredItemKeys = useMemo((): string[] => {
const modelKeys = visibleModels.map((model) =>
modelPickerModelKey(model.instanceId, model.slug),
);
if (!legacySection) {
return modelKeys;
}
modelKeys.splice(legacySection.currentModels.length, 0, legacySection.key);
return modelKeys;
}, [legacySection, visibleModels]);
const filteredModelByKey = useMemo(
(): ReadonlyMap<string, ModelPickerItem> =>
new Map(filteredModels.map((model) => [`${model.instanceId}:${model.slug}`, model] as const)),
[filteredModels],
new Map(
visibleModels.map(
(model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
),
),
[visibleModels],
);
const updateModelListScrollFades = useCallback(() => {
const scrollElement = modelListRef.current?.getScrollableNode();
@@ -495,10 +561,13 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
if (!targetModelKey) {
return;
}
const { instanceId, slug } = splitInstanceModelKey(targetModelKey);
const model = parseModelPickerModelKey(targetModelKey);
if (!model) {
return;
}
event.preventDefault();
event.stopPropagation();
handleModelSelect(slug, instanceId);
handleModelSelect(model.slug, model.instanceId);
};
window.addEventListener("keydown", onWindowKeyDown, true);
@@ -510,7 +579,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
useLayoutEffect(() => {
setShowTopScrollFade(false);
setShowBottomScrollFade(filteredModelKeys.length > 5);
setShowBottomScrollFade(filteredItemKeys.length > 5);
let nestedFrame = 0;
const frame = window.requestAnimationFrame(() => {
updateModelListScrollFades();
@@ -520,7 +589,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
window.cancelAnimationFrame(frame);
window.cancelAnimationFrame(nestedFrame);
};
}, [filteredModelKeys, updateModelListScrollFades]);
}, [filteredItemKeys, updateModelListScrollFades]);
return (
<TooltipProvider delay={0}>
@@ -548,13 +617,13 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
{/* Main content area */}
<Combobox
inline
items={allModelKeys}
filteredItems={filteredModelKeys}
items={allItemKeys}
filteredItems={filteredItemKeys}
filter={null}
autoHighlight
open
virtualized
value={`${props.activeInstanceId}:${props.model}`}
value={modelPickerModelKey(props.activeInstanceId, props.model)}
onItemHighlighted={(modelKey, eventDetails) => {
highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
@@ -568,8 +637,15 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
if (typeof modelKey !== "string") {
return;
}
const { instanceId, slug } = splitInstanceModelKey(modelKey);
handleModelSelect(slug, instanceId);
const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);
if (legacyInstanceId) {
toggleLegacySection(legacyInstanceId);
return;
}
const model = parseModelPickerModelKey(modelKey);
if (model) {
handleModelSelect(model.slug, model.instanceId);
}
}}
>
<div
@@ -605,10 +681,17 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
).preventBaseUIHandler?.();
e.preventDefault();
e.stopPropagation();
const { instanceId, slug } = splitInstanceModelKey(
const legacyInstanceId = parseModelPickerLegacySectionKey(
highlightedModelKeyRef.current,
);
handleModelSelect(slug, instanceId);
if (legacyInstanceId) {
toggleLegacySection(legacyInstanceId);
return;
}
const model = parseModelPickerModelKey(highlightedModelKeyRef.current);
if (model) {
handleModelSelect(model.slug, model.instanceId);
}
return;
}
e.stopPropagation();
@@ -626,10 +709,35 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
<ComboboxListVirtualized className="size-full min-w-0 p-0 not-empty:p-0">
<LegendList<string>
ref={modelListRef}
data={filteredModelKeys}
data={filteredItemKeys}
extraData={favoritesSet}
keyExtractor={(modelKey) => modelKey}
renderItem={({ item: modelKey, index }) => {
if (legacySection?.key === modelKey) {
return (
<ComboboxItem
hideIndicator
index={index}
value={modelKey}
aria-expanded={legacySection.isExpanded}
className="group w-full cursor-pointer rounded-md px-2 py-2"
contentClassName="flex w-full items-center gap-3"
>
<div className="min-w-0 flex-1 text-left">
<div className="text-xs font-medium leading-snug">Legacy models</div>
<div className="mt-1 text-xs font-normal leading-snug text-muted-foreground/70">
{legacySection.legacyModels.length} models
</div>
</div>
<ChevronRightIcon
className={cn(
"size-4 transition-transform",
legacySection.isExpanded && "rotate-90",
)}
/>
</ComboboxItem>
);
}
const model = filteredModelByKey.get(modelKey);
if (!model) {
return null;
@@ -645,8 +753,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
driverKind={model.driverKind}
providerDisplayName={model.instanceDisplayName}
providerAccentColor={model.instanceAccentColor}
isFavorite={favoritesSet.has(modelKey)}
isSelected={modelKey === `${props.activeInstanceId}:${props.model}`}
isFavorite={favoritesSet.has(
providerModelKey(model.instanceId, model.slug),
)}
isSelected={
modelKey === modelPickerModelKey(props.activeInstanceId, props.model)
}
showProvider
preferShortName={!isLocked}
useTriggerLabel={false}
@@ -657,7 +769,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
/>
);
}}
estimatedItemSize={60}
estimatedItemSize={52}
drawDistance={480}
recycleItems
contentContainerClassName="pl-2 pr-px"
@@ -260,6 +260,7 @@ export const OpenInPicker = memo(function OpenInPicker({
<Group aria-label="Open in editor">
<Button
aria-label={compact ? "Open file in preferred editor" : undefined}
className="ps-[8.5px]"
size="xs"
variant="outline"
disabled={!preferredEditor || !openInCwd}
@@ -0,0 +1,31 @@
import { ProviderInstanceId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
modelPickerLegacySectionKey,
modelPickerModelKey,
parseModelPickerLegacySectionKey,
parseModelPickerModelKey,
} from "./modelPickerKeys";
describe("model picker item keys", () => {
it("keeps model and legacy section keys distinct for colliding instance names", () => {
const modelKey = modelPickerModelKey(ProviderInstanceId.make("legacy-models"), "codex");
const sectionKey = modelPickerLegacySectionKey(ProviderInstanceId.make("codex"));
expect(modelKey).not.toBe(sectionKey);
expect(parseModelPickerLegacySectionKey(modelKey)).toBeNull();
expect(parseModelPickerModelKey(modelKey)).toEqual({
instanceId: "legacy-models",
slug: "codex",
});
});
it("round-trips arbitrary strings without throwing", () => {
const instanceId = ProviderInstanceId.make("custom");
const slug = "model:\udfff";
const key = modelPickerModelKey(instanceId, slug);
expect(parseModelPickerModelKey(key)).toEqual({ instanceId, slug });
});
});
@@ -0,0 +1,47 @@
import type { ProviderInstanceId } from "@t3tools/contracts";
const MODEL_KEY_PREFIX = "model:";
const LEGACY_SECTION_KEY_PREFIX = "legacy-models:";
export function modelPickerModelKey(instanceId: ProviderInstanceId, slug: string): string {
return `${MODEL_KEY_PREFIX}${instanceId.length}:${instanceId}${slug}`;
}
export function parseModelPickerModelKey(
key: string,
): { instanceId: ProviderInstanceId; slug: string } | null {
if (!key.startsWith(MODEL_KEY_PREFIX)) {
return null;
}
const encoded = key.slice(MODEL_KEY_PREFIX.length);
const separatorIndex = encoded.indexOf(":");
if (separatorIndex === -1) {
return null;
}
const instanceIdLengthText = encoded.slice(0, separatorIndex);
if (!/^\d+$/.test(instanceIdLengthText)) {
return null;
}
const instanceIdLength = Number(instanceIdLengthText);
const value = encoded.slice(separatorIndex + 1);
if (!Number.isSafeInteger(instanceIdLength) || instanceIdLength > value.length) {
return null;
}
return {
instanceId: value.slice(0, instanceIdLength) as ProviderInstanceId,
slug: value.slice(instanceIdLength),
};
}
export function modelPickerLegacySectionKey(instanceId: ProviderInstanceId): string {
return `${LEGACY_SECTION_KEY_PREFIX}${instanceId}`;
}
export function parseModelPickerLegacySectionKey(key: string): ProviderInstanceId | null {
return key.startsWith(LEGACY_SECTION_KEY_PREFIX)
? (key.slice(LEGACY_SECTION_KEY_PREFIX.length) as ProviderInstanceId)
: null;
}
@@ -26,6 +26,7 @@ export type ModelEsque = {
name: string;
shortName?: string | undefined;
subProvider?: string | undefined;
isLegacy?: boolean | undefined;
};
function escapeRegExp(value: string): string {
@@ -248,6 +248,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
</p>
) : null}
<SidebarMenu
className="ps-px"
id={isSearching && hasResults ? "settings-search-results" : undefined}
role={isSearching && hasResults ? "listbox" : undefined}
aria-label={isSearching && hasResults ? "Settings search results" : undefined}
+18
View File
@@ -55,6 +55,24 @@ function settingsWithProviderInstances(): UnifiedSettings {
}
describe("instance-scoped model selection", () => {
it("preserves server-provided legacy model metadata", () => {
const baseProvider = provider({
instanceId: "claudeAgent",
models: ["claude-opus-4-8"],
});
const providers = [
{
...baseProvider,
models: [{ ...baseProvider.models[0]!, isLegacy: true }],
},
];
const stock = deriveProviderInstanceEntries(providers)[0]!;
expect(getAppModelOptionsForInstance(settingsWithProviderInstances(), stock)[0]?.isLegacy).toBe(
true,
);
});
it("keeps custom models on the provider instance that declared them", () => {
const providers = [
provider({
+2
View File
@@ -76,6 +76,7 @@ export interface AppModelOption {
subProvider?: string;
isCustom: boolean;
isDefault?: boolean;
isLegacy?: boolean;
}
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
@@ -87,6 +88,7 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
if (model.shortName) option.shortName = model.shortName;
if (model.subProvider) option.subProvider = model.subProvider;
if (model.isDefault) option.isDefault = true;
if (model.isLegacy) option.isLegacy = true;
return option;
}
@@ -0,0 +1,170 @@
# Relay: PlanetScale Postgres → PlanetScale Vitess (MySQL) data migration
This runbook covers the one-time migration of the production relay database from PlanetScale
Postgres (`t3coderelay`, `us-west`, PS_20) to PlanetScale Vitess/MySQL (`t3coderelay-vitess`).
Everything infrastructural lives in IaC across three PRs; only the data replication itself is an
operational task:
| Phase | PR | What it does |
| ------------ | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1. Provision | `relay/provision-vitess-db` | Adds `RelayMysqlDatabase` to the prod stack. Deploying it creates the empty Vitess database and applies `migrations/mysql/…_baseline` via the alchemy migration runner (bookkeeping in `relay_migrations` included). The worker keeps running on Postgres. |
| 2. Replicate | — (operational) | One AWS DMS task copies data Postgres → PlanetScale directly and keeps CDC running. |
| 3. Cutover | the migration PR | Ports the worker to mysql (schema, driver, repos) and flips Hyperdrive's origin to the Vitess runtime password. The Postgres database + role **stay in the stack** for rollback. |
| 4. Teardown | follow-up PR after soak | Removes `RelayPostgresDatabase`/`RelayPostgresRuntimeRole` and `migrations/postgres` from the stack (the retained database is orphaned, then deleted in the console). |
The relay dataset is small, so the data phase follows PlanetScale's
[small-database Postgres → PlanetScale guide](https://planetscale.com/docs/vitess/imports/postgres-planetscale-migration-guide):
a single DMS task, no Aurora intermediate, no import tool. (The
[larger-database guide](https://planetscale.com/docs/vitess/imports/postgres-mysql-planetscale-migration-guide)
adds those hops only for fast imports of big datasets.) If even a DMS task feels like overkill, the
"dump-and-load" appendix trades it for a ~15-minute write freeze and no AWS at all.
## 0. Preconditions
- [ ] AWS account with DMS permissions and the AWS CLI authenticated (only needed for the DMS
path). A host with `psql` and `mysql` clients for verification.
- [ ] Source Postgres must expose logical replication for DMS: `logical_replication = 1` and
`pglogical` in `shared_preload_libraries`. These are managed settings on PlanetScale
Postgres — confirm/enable them in the console (Settings → Parameters) or via support before
scheduling anything.
- [ ] Verify the narrowed column bounds hold in production data. The MySQL schema turns several
indexed `text` columns into `varchar(255)` (InnoDB cannot uniquely index unbounded TEXT):
```sql
-- run against the Postgres prod branch; every max must be <= 255
select max(length(push_token)), max(length(push_to_start_token)) from relay_mobile_devices;
select max(length(activity_push_token)) from relay_live_activities;
select max(length(hostname)), max(length(tunnel_name)) from relay_managed_endpoint_allocations;
select max(length(environment_public_key)) from relay_environment_links;
select max(length(environment_public_key)) from relay_environment_credentials;
select max(length(environment_public_key)) from relay_agent_activity_rows;
```
If anything exceeds 255, widen the column in `infra/relay/src/persistence/schema.ts` and
regenerate the baseline migration first.
- [ ] No relay schema changes land while the migration is in flight.
## 1. Land and deploy the provisioning PR
Merge `relay/provision-vitess-db` (or deploy it to `prod` manually). The deploy creates
`t3coderelay-vitess` (`us-west`, PS_20), applies the checked-in baseline schema, and records it in
`relay_migrations` — nothing manual, no `pscale` involved. The worker is untouched and still runs
on Postgres.
Afterwards, confirm in the console that **safe migrations is OFF** on `main` (it is off by default
for non-imported databases): alchemy applies DDL over a direct connection, not deploy requests, and
future `migrations/mysql/*` files fail to apply while it is on.
The only non-IaC credential in this whole flow: DMS needs to authenticate against the target, so
mint a short-lived password for it (this is a migration-time secret, not infrastructure — it
expires on its own and never enters the stack):
```sh
pscale password create t3coderelay-vitess main dms-import --role readwriter --ttl 604800
```
## 2. Replicate with a single DMS task
Use PlanetScale's [postgres-planetscale scripts](https://github.com/planetscale/postgres-planetscale)
(review before running):
```sh
sh import.sh --identifier "T3RelayPgToVitess" \
--source "${PG_USER}:${PG_PASSWORD}@${PG_HOST}/${PG_DB}/public" \
--target "${PS_USER}:${PS_PASSWORD}@${PS_HOST}/t3coderelay-vitess"
```
Two things to check in the task configuration before starting it:
- **Target prep mode must be `DO_NOTHING`** (or at most `TRUNCATE_BEFORE_LOAD`). DMS's default
`DROP_AND_CREATE` would replace the deploy-created tables with DMS's own inferred types and drop
the indexes/varchar bounds the relay depends on.
- **Exclude `relay_migrations` from the table mappings.** The source table tracks the _Postgres_
migration files; copying it would clobber the MySQL bookkeeping written by the provisioning
deploy.
DMS handles the type conversions (`jsonb → json`, `boolean → tinyint(1)` as `t/f → 1/0`,
`integer → int`; all timestamps are ISO-8601 varchars and pass through). Resource provisioning
takes ~20 minutes; the copy itself is quick at our size. After the full load, CDC keeps the target
in sync. Verify row counts per table:
```sql
select 'relay_mobile_devices', count(*) from relay_mobile_devices
union all select 'relay_live_activities', count(*) from relay_live_activities
union all select 'relay_environment_links', count(*) from relay_environment_links
union all select 'relay_environment_credentials', count(*) from relay_environment_credentials
union all select 'relay_managed_endpoint_allocations', count(*) from relay_managed_endpoint_allocations
union all select 'relay_managed_tunnel_limits', count(*) from relay_managed_tunnel_limits
union all select 'relay_agent_activity_rows', count(*) from relay_agent_activity_rows
union all select 'relay_delivery_attempts', count(*) from relay_delivery_attempts
union all select 'relay_dpop_proofs', count(*) from relay_dpop_proofs;
```
Watch the task's CloudWatch logs for conversion errors. Leave CDC running until cutover.
## 3. Land the cutover PR
1. Pick a low-traffic window. The relay's writes are retry-friendly (device registrations,
activity upserts, APNs bookkeeping), but anything written to Postgres between "stop DMS" and
"new worker live" is lost — at our volume that window is seconds to a couple of minutes.
2. Stop the DMS task (CDC drained first: task statistics show no pending changes).
3. Merge the migration PR (CI deploys `prod` on push to `main`), or deploy manually:
```sh
vp run --filter t3code-relay deploy -- --stage prod
```
The deploy:
- keeps owning the Postgres database + runtime role (unchanged, still in the stack);
- updates `RelayMysqlDatabase` in place (same resource id as the provisioning PR; only
`migrationsDir` moves to the mysql schema resource) and applies nothing — the baseline is
already recorded in `relay_migrations`;
- creates the runtime password (`RelayMysqlRuntimePassword`, role `readwriter`) and points the
existing Hyperdrive config at the MySQL origin — this is the actual cutover.
4. Smoke-test: link an environment, register a device from the mobile app, confirm agent activity
rows appear, and watch worker traces (Axiom `relay.*` spans) for
`SqlError`/`EffectDrizzleQueryError`.
## 4. Rollback
Revert the cutover PR (or redeploy the previous `main` commit). Because the Postgres database and
role never left the stack, that deploy only flips Hyperdrive back to the Postgres origin — no
re-provisioning, no data steps. Writes made while Vitess was primary are lost (nothing replicates
back to Postgres); decide based on how long the new stack was live. The DMS task can be restarted
afterwards to re-sync for another attempt (with `TRUNCATE_BEFORE_LOAD`, since the target now has
stale rows).
## 5. Soak
Run on Vitess for an agreed period (suggest ≥1 week) before destroying anything. The Postgres
database keeps costing its cluster size during soak — that's the price of the rollback path.
## 6. Land the teardown PR
1. Tear down the DMS resources: `sh cleanup.sh --identifier "T3RelayPgToVitess"` (the `dms-import`
password has expired on its own).
2. Take a final PlanetScale Postgres backup.
3. The teardown PR removes the `RelayPostgresDatabase`/`RelayPostgresRuntimeRole` block from
`infra/relay/src/db.ts` and deletes `infra/relay/migrations/postgres/`. Deploying it orphans the
retained database (Alchemy stops managing it; nothing is deleted).
4. Delete the `t3coderelay` Postgres database in the PlanetScale console.
5. Ask developers to redeploy personal stages: the next `deploy` replaces their Postgres
branch/role resources with Vitess branch/password resources automatically.
## Appendix: dump-and-load (no DMS at all)
For the current data volume the DMS task can be replaced by a short write freeze:
1. Land + deploy the provisioning PR (step 1; skip the DMS password).
2. Freeze relay writes (announce a maintenance window; seconds-to-minutes of 5xx on
registration/link endpoints is acceptable — clients retry).
3. Copy data table-by-table: `pg_dump --data-only --column-inserts` per table, transform to
MySQL-compatible inserts (`t/f → 1/0` for booleans; JSON and ISO-timestamp varchars pass
through; adjust identifier quoting), and load with `mysql` using a short-TTL `pscale password`.
At these sizes a small script or `pgloader` both work.
4. Verify row counts (query in step 2 above), then land the cutover PR (step 3) and smoke-test.
Same rollback caveat: once traffic lands on Vitess, writes are not mirrored back to Postgres.
+7 -5
View File
@@ -40,7 +40,9 @@ credential, or authorization behavior.
APNs delivery, and queue processing.
- [`src/auth`](./src/auth) contains relay token and DPoP proof handling.
- [`src/persistence/schema.ts`](./src/persistence/schema.ts) defines persisted relay state. Keep
schema and migration changes together.
schema and migration changes together: after editing the schema, run
`pnpm exec drizzle-kit generate` (see [`drizzle.config.ts`](./drizzle.config.ts)) and commit the
new `migrations/mysql/` directory — MySQL migrations are generated manually, not by the deploy.
Shared request and response schemas live in
[`packages/contracts/src/relay.ts`](../../packages/contracts/src/relay.ts). Shared client-side relay
@@ -89,10 +91,10 @@ file from the relay directory. Runtime secrets include Clerk and APNs credential
the configured API and tunnel DNS zones as retained Cloudflare resources. Personal stages reference
the production-owned zones.
The `prod` Alchemy stage owns the retained PlanetScale database and is the shared hosted relay for
stable and nightly clients. Every other stage references that database and provisions an isolated
PlanetScale branch and runtime role for local development, so deploy `prod` before creating
developer stages:
The `prod` Alchemy stage owns the retained PlanetScale database (Vitess/MySQL) and is the shared
hosted relay for stable and nightly clients. Every other stage references that database and
provisions an isolated PlanetScale branch and runtime password for local development, so deploy
`prod` before creating developer stages:
```sh
vp run --filter t3code-relay deploy -- --stage prod
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from "drizzle-kit";
// MySQL migrations are generated manually and checked in (alchemy's
// Drizzle.Schema auto-generation is Postgres-only). After changing
// src/persistence/schema.ts run `pnpm exec drizzle-kit generate` and commit
// the new migrations/mysql/<timestamp>_*/ directory; deploys apply it.
export default defineConfig({
schema: "./src/persistence/schema.ts",
out: "./migrations/mysql",
dialect: "mysql",
});
@@ -0,0 +1,127 @@
CREATE TABLE `relay_agent_activity_rows` (
`environment_id` varchar(191) NOT NULL,
`environment_public_key` varchar(255) NOT NULL,
`thread_id` varchar(191) NOT NULL,
`state_json` json NOT NULL,
`updated_at` varchar(64) NOT NULL,
`created_at` varchar(64) NOT NULL,
CONSTRAINT PRIMARY KEY(`environment_id`,`environment_public_key`,`thread_id`)
);
--> statement-breakpoint
CREATE TABLE `relay_delivery_attempts` (
`id` varchar(36) PRIMARY KEY,
`created_at` varchar(64) NOT NULL,
`user_id` varchar(255),
`environment_id` varchar(191),
`thread_id` varchar(191),
`device_id` varchar(255),
`kind` varchar(64) NOT NULL,
`source_job_id` varchar(64),
`token_suffix` varchar(16),
`apns_status` int,
`apns_reason` text,
`apns_id` varchar(128),
`transport_error` text,
CONSTRAINT `idx_relay_delivery_attempts_source_job` UNIQUE INDEX(`source_job_id`)
);
--> statement-breakpoint
CREATE TABLE `relay_dpop_proofs` (
`thumbprint` varchar(128) NOT NULL,
`jti` varchar(255) NOT NULL,
`iat` int NOT NULL,
`expires_at` varchar(64) NOT NULL,
`created_at` varchar(64) NOT NULL,
CONSTRAINT PRIMARY KEY(`thumbprint`,`jti`)
);
--> statement-breakpoint
CREATE TABLE `relay_environment_credentials` (
`credential_id` varchar(64) PRIMARY KEY,
`environment_id` varchar(191) NOT NULL,
`environment_public_key` varchar(255) NOT NULL,
`credential_hash` varchar(191) NOT NULL,
`revoked_at` varchar(64),
`created_at` varchar(64) NOT NULL,
`updated_at` varchar(64) NOT NULL,
CONSTRAINT `idx_relay_environment_credentials_hash` UNIQUE INDEX(`credential_hash`)
);
--> statement-breakpoint
CREATE TABLE `relay_environment_links` (
`user_id` varchar(191) NOT NULL,
`environment_id` varchar(191) NOT NULL,
`environment_label` text NOT NULL DEFAULT ('T3 Environment'),
`environment_public_key` varchar(255) NOT NULL,
`endpoint_http_base_url` text NOT NULL,
`endpoint_ws_base_url` text NOT NULL,
`endpoint_provider_kind` varchar(32) NOT NULL,
`notifications_enabled` boolean NOT NULL DEFAULT true,
`live_activities_enabled` boolean NOT NULL DEFAULT true,
`managed_tunnels_enabled` boolean NOT NULL DEFAULT false,
`created_by_device_id` varchar(191),
`revoked_at` varchar(64),
`created_at` varchar(64) NOT NULL,
`updated_at` varchar(64) NOT NULL,
CONSTRAINT PRIMARY KEY(`user_id`,`environment_id`)
);
--> statement-breakpoint
CREATE TABLE `relay_live_activities` (
`user_id` varchar(255) NOT NULL,
`device_id` varchar(255) NOT NULL,
`activity_push_token` varchar(255),
`remote_start_queued_at` varchar(64),
`remote_started_at` varchar(64),
`ended_at` varchar(64),
`last_aggregate_json` json,
`last_live_activity_delivery_at` varchar(64),
`created_at` varchar(64) NOT NULL,
`updated_at` varchar(64) NOT NULL,
CONSTRAINT PRIMARY KEY(`user_id`,`device_id`),
CONSTRAINT `idx_relay_live_activities_activity_push_token` UNIQUE INDEX(`activity_push_token`)
);
--> statement-breakpoint
CREATE TABLE `relay_managed_endpoint_allocations` (
`user_id` varchar(191) NOT NULL,
`environment_id` varchar(191) NOT NULL,
`hostname` varchar(255) NOT NULL,
`tunnel_id` varchar(191),
`tunnel_name` varchar(255) NOT NULL,
`dns_record_id` varchar(191),
`ready_at` varchar(64),
`created_at` varchar(64) NOT NULL,
`updated_at` varchar(64) NOT NULL,
CONSTRAINT PRIMARY KEY(`user_id`,`environment_id`),
CONSTRAINT `idx_relay_managed_endpoint_allocations_hostname` UNIQUE INDEX(`hostname`),
CONSTRAINT `idx_relay_managed_endpoint_allocations_tunnel_name` UNIQUE INDEX(`tunnel_name`)
);
--> statement-breakpoint
CREATE TABLE `relay_managed_tunnel_limits` (
`user_id` varchar(191) PRIMARY KEY,
`max_tunnels` int NOT NULL,
`created_at` varchar(64) NOT NULL,
`updated_at` varchar(64) NOT NULL
);
--> statement-breakpoint
CREATE TABLE `relay_mobile_devices` (
`user_id` varchar(255) NOT NULL,
`device_id` varchar(255) NOT NULL,
`label` text NOT NULL DEFAULT ('iOS device'),
`platform` varchar(16) NOT NULL,
`ios_major_version` int NOT NULL,
`app_version` varchar(64),
`bundle_id` varchar(255),
`aps_environment` varchar(16),
`push_token` varchar(255),
`push_to_start_token` varchar(255),
`preferences_json` json NOT NULL,
`created_at` varchar(64) NOT NULL,
`updated_at` varchar(64) NOT NULL,
CONSTRAINT PRIMARY KEY(`user_id`,`device_id`),
CONSTRAINT `idx_relay_mobile_devices_push_token` UNIQUE INDEX(`push_token`),
CONSTRAINT `idx_relay_mobile_devices_push_to_start_token` UNIQUE INDEX(`push_to_start_token`)
);
--> statement-breakpoint
CREATE INDEX `idx_relay_agent_activity_rows_updated` ON `relay_agent_activity_rows` (`updated_at`);--> statement-breakpoint
CREATE INDEX `idx_relay_delivery_attempts_environment` ON `relay_delivery_attempts` (`environment_id`,`thread_id`,`created_at`);--> statement-breakpoint
CREATE INDEX `idx_relay_dpop_proofs_expires_at` ON `relay_dpop_proofs` (`expires_at`);--> statement-breakpoint
CREATE INDEX `idx_relay_environment_credentials_environment` ON `relay_environment_credentials` (`environment_id`,`revoked_at`);--> statement-breakpoint
CREATE INDEX `idx_relay_environment_credentials_environment_key` ON `relay_environment_credentials` (`environment_id`,`environment_public_key`,`revoked_at`);--> statement-breakpoint
CREATE INDEX `idx_relay_environment_links_environment` ON `relay_environment_links` (`environment_id`,`revoked_at`);
File diff suppressed because it is too large. Load diff
+1
View File
@@ -10,6 +10,7 @@
},
"dependencies": {
"@clerk/backend": "catalog:",
"@effect/sql-mysql2": "catalog:",
"@effect/sql-pg": "catalog:",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
@@ -24,7 +24,7 @@ describe("AgentActivityRows", () => {
const failingDb = {
insert: () => ({
values: () => ({
onConflictDoUpdate: () => Effect.fail(cause),
onDuplicateKeyUpdate: () => Effect.fail(cause),
}),
}),
delete: () => ({
@@ -134,12 +134,7 @@ export const make = Effect.gen(function* () {
updatedAt: input.state.updatedAt,
createdAt: DateTime.formatIso(now),
})
.onConflictDoUpdate({
target: [
relayAgentActivityRows.environmentId,
relayAgentActivityRows.environmentPublicKey,
relayAgentActivityRows.threadId,
],
.onDuplicateKeyUpdate({
set: {
stateJson,
updatedAt: input.state.updatedAt,
@@ -191,7 +186,7 @@ export const make = Effect.gen(function* () {
.delete(relayAgentActivityRows)
.where(
and(
sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`,
sql`${relayAgentActivityRows.stateJson} ->> '$.phase' IN ('completed', 'failed')`,
lt(relayAgentActivityRows.updatedAt, input.updatedBefore),
),
)
@@ -60,22 +60,16 @@ describe("DeliveryAttempts", () => {
it.effect("claims signed queue source jobs before APNs delivery", () => {
const insertedValues: Array<Record<string, unknown>> = [];
const conflictTargets: Array<unknown> = [];
const fakeDb = {
insert: (table: unknown) => {
expect(table).toBe(relayDeliveryAttempts);
return {
values: (values: Record<string, unknown>) => {
insertedValues.push(values);
return {
onConflictDoNothing: (config: { readonly target: unknown }) => {
conflictTargets.push(config.target);
return {
returning: () => Effect.succeed([{ id: values.id }]),
};
},
};
},
ignore: () => ({
values: (values: Record<string, unknown>) => {
insertedValues.push(values);
return Effect.succeed({ affectedRows: 1 });
},
}),
};
},
} as unknown as RelayDb.RelayDb["Service"];
@@ -93,7 +87,6 @@ describe("DeliveryAttempts", () => {
});
expect(claimed).toBe("claimed");
expect(conflictTargets).toEqual([relayDeliveryAttempts.sourceJobId]);
expect(insertedValues[0]).toMatchObject({
kind: "push_notification",
sourceJobId: "job-1",
@@ -113,10 +106,8 @@ describe("DeliveryAttempts", () => {
it.effect("reports completed source jobs when the durable claim already exists", () => {
const fakeDb = {
insert: () => ({
values: () => ({
onConflictDoNothing: () => ({
returning: () => Effect.succeed([]),
}),
ignore: () => ({
values: () => Effect.succeed({ affectedRows: 0 }),
}),
}),
select: () => ({
@@ -163,10 +154,8 @@ describe("DeliveryAttempts", () => {
it.effect("reports in-flight source jobs while an active claim lease exists", () => {
const fakeDb = {
insert: () => ({
values: () => ({
onConflictDoNothing: () => ({
returning: () => Effect.succeed([]),
}),
ignore: () => ({
values: () => Effect.succeed({ affectedRows: 0 }),
}),
}),
select: () => ({
@@ -214,10 +203,8 @@ describe("DeliveryAttempts", () => {
const updatedValues: Array<Record<string, unknown>> = [];
const fakeDb = {
insert: () => ({
values: () => ({
onConflictDoNothing: () => ({
returning: () => Effect.succeed([]),
}),
ignore: () => ({
values: () => Effect.succeed({ affectedRows: 0 }),
}),
}),
select: () => ({
@@ -240,9 +227,7 @@ describe("DeliveryAttempts", () => {
set: (values: Record<string, unknown>) => {
updatedValues.push(values);
return {
where: () => ({
returning: () => Effect.succeed([{ id: "attempt-1" }]),
}),
where: () => Effect.succeed({ affectedRows: 1 }),
};
},
}),
@@ -325,14 +310,10 @@ describe("DeliveryAttempts", () => {
const cause = new Error("database unavailable");
const fakeDb = {
insert: () => ({
values: (values: Record<string, unknown>) =>
values.kind === "record"
? Effect.fail(cause)
: {
onConflictDoNothing: () => ({
returning: () => Effect.fail(cause),
}),
},
values: () => Effect.fail(cause),
ignore: () => ({
values: () => Effect.fail(cause),
}),
}),
update: () => ({
set: () => ({
@@ -8,6 +8,7 @@ import * as Crypto from "effect/Crypto";
import * as Schema from "effect/Schema";
import * as RelayDb from "../db.ts";
import { affectedRows } from "../persistence/mysqlResult.ts";
import { relayDeliveryAttempts } from "../persistence/schema.ts";
export class DeliveryAttemptRecordPersistenceError extends Schema.TaggedErrorClass<DeliveryAttemptRecordPersistenceError>()(
@@ -148,12 +149,14 @@ export const make = Effect.gen(function* () {
const id = yield* crypto.randomUUIDv4;
const now = yield* DateTime.now;
const createdAt = DateTime.formatIso(now);
// INSERT IGNORE: the only unique constraint a fresh UUID row can hit
// is idx_relay_delivery_attempts_source_job, so an ignored insert
// means the source job is already claimed.
const inserted = yield* db
.insert(relayDeliveryAttempts)
.values(insertValues(input, id, createdAt))
.onConflictDoNothing({ target: relayDeliveryAttempts.sourceJobId })
.returning({ id: relayDeliveryAttempts.id });
if (inserted.length > 0) {
.ignore()
.values(insertValues(input, id, createdAt));
if (affectedRows(inserted) > 0) {
return "claimed";
}
@@ -198,9 +201,8 @@ export const make = Effect.gen(function* () {
isNull(relayDeliveryAttempts.apnsId),
isNull(relayDeliveryAttempts.transportError),
),
)
.returning({ id: relayDeliveryAttempts.id });
return reclaimed.length > 0 ? "claimed" : "in_flight";
);
return affectedRows(reclaimed) > 0 ? "claimed" : "in_flight";
}).pipe(
Effect.mapError(
(cause) =>
+14 -14
View File
@@ -1,7 +1,7 @@
import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
import { describe, expect, it } from "@effect/vitest";
import type { SQL } from "drizzle-orm";
import { PgDialect } from "drizzle-orm/pg-core";
import { MySqlDialect } from "drizzle-orm/mysql-core";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -35,7 +35,7 @@ describe("Devices", () => {
const updateSets: Array<Record<string, unknown>> = [];
const updateConditions: Array<SQL> = [];
const insertedValues: Array<Record<string, unknown>> = [];
const dialect = new PgDialect();
const dialect = new MySqlDialect();
const fakeDb = {
update: (table: unknown) => {
@@ -64,9 +64,9 @@ describe("Devices", () => {
insertedValues.push(values);
calls.push("insert.values");
return {
onConflictDoUpdate: (config: unknown) => {
onDuplicateKeyUpdate: (config: unknown) => {
expect(config).toBeDefined();
calls.push("insert.onConflictDoUpdate");
calls.push("insert.onDuplicateKeyUpdate");
return Effect.void;
},
};
@@ -88,7 +88,7 @@ describe("Devices", () => {
"update.where",
"insert",
"insert.values",
"insert.onConflictDoUpdate",
"insert.onDuplicateKeyUpdate",
]);
expect(updateSets).toEqual([
expect.objectContaining({ pushToken: null }),
@@ -96,11 +96,11 @@ describe("Devices", () => {
]);
expect(updateConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([
{
sql: '"relay_mobile_devices"."push_token" = $1',
sql: "`relay_mobile_devices`.`push_token` = ?",
params: ["apns-device-token"],
},
{
sql: '"relay_mobile_devices"."push_to_start_token" = $1',
sql: "`relay_mobile_devices`.`push_to_start_token` = ?",
params: ["push-to-start-token"],
},
]);
@@ -122,7 +122,7 @@ describe("Devices", () => {
it.effect("unregisters APNs state only for the current user device", () => {
const calls: Array<string> = [];
const deleteConditions: Array<SQL> = [];
const dialect = new PgDialect();
const dialect = new MySqlDialect();
const fakeDb = {
delete: (table: unknown) => {
@@ -151,14 +151,14 @@ describe("Devices", () => {
expect(deleteConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([
{
sql:
'(("relay_live_activities"."user_id" = $1) and ' +
'("relay_live_activities"."device_id" = $2))',
"((`relay_live_activities`.`user_id` = ?) and " +
"(`relay_live_activities`.`device_id` = ?))",
params: ["user-2", "device-1"],
},
{
sql:
'(("relay_mobile_devices"."user_id" = $1) and ' +
'("relay_mobile_devices"."device_id" = $2))',
"((`relay_mobile_devices`.`user_id` = ?) and " +
"(`relay_mobile_devices`.`device_id` = ?))",
params: ["user-2", "device-1"],
},
]);
@@ -168,7 +168,7 @@ describe("Devices", () => {
});
it.effect("lists safe notification state without exposing APNs tokens", () => {
const dialect = new PgDialect();
const dialect = new MySqlDialect();
let condition: SQL | null = null;
const fakeDb = {
select: () => ({
@@ -200,7 +200,7 @@ describe("Devices", () => {
expect(condition).not.toBeNull();
expect(dialect.sqlToQuery(condition!)).toEqual({
sql: '"relay_mobile_devices"."user_id" = $1',
sql: "`relay_mobile_devices`.`user_id` = ?",
params: ["user-2"],
});
expect(listed).toEqual([
+7 -7
View File
@@ -138,23 +138,23 @@ export const make = Effect.gen(function* () {
createdAt: updatedAt,
updatedAt,
})
.onConflictDoUpdate({
target: [relayMobileDevices.userId, relayMobileDevices.deviceId],
.onDuplicateKeyUpdate({
set: {
platform: registration.platform,
label: registration.label,
iosMajorVersion: registration.iosMajorVersion,
appVersion: registration.appVersion ?? null,
// Preserve routing from newer app builds when an older build
// re-registers without these fields.
bundleId: sql`coalesce(excluded.bundle_id, ${relayMobileDevices.bundleId})`,
// re-registers without these fields. `values(col)` is MySQL's
// spelling of Postgres' `excluded.col`.
bundleId: sql`coalesce(values(bundle_id), ${relayMobileDevices.bundleId})`,
apsEnvironment: sql`coalesce(
excluded.aps_environment,
values(aps_environment),
${relayMobileDevices.apsEnvironment}
)`,
pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`,
pushToken: sql`coalesce(values(push_token), ${relayMobileDevices.pushToken})`,
pushToStartToken: sql`coalesce(
excluded.push_to_start_token,
values(push_to_start_token),
${relayMobileDevices.pushToStartToken}
)`,
preferencesJson: registration.preferences,
@@ -4,7 +4,7 @@ import type {
} from "@t3tools/contracts/relay";
import { describe, expect, it } from "@effect/vitest";
import type { SQL } from "drizzle-orm";
import { PgDialect } from "drizzle-orm/pg-core";
import { MySqlDialect } from "drizzle-orm/mysql-core";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -49,7 +49,7 @@ describe("LiveActivities", () => {
const conflictConfigs: Array<{
readonly set?: Record<string, unknown>;
}> = [];
const dialect = new PgDialect();
const dialect = new MySqlDialect();
const fakeDb = {
update: (table: unknown) => {
@@ -78,10 +78,10 @@ describe("LiveActivities", () => {
insertedValues.push(values);
calls.push("insert.values");
return {
onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {
onDuplicateKeyUpdate: (config: { readonly set?: Record<string, unknown> }) => {
expect(config).toBeDefined();
conflictConfigs.push(config);
calls.push("insert.onConflictDoUpdate");
calls.push("insert.onDuplicateKeyUpdate");
return Effect.void;
},
};
@@ -100,7 +100,7 @@ describe("LiveActivities", () => {
"update.where",
"insert",
"insert.values",
"insert.onConflictDoUpdate",
"insert.onDuplicateKeyUpdate",
]);
expect(updateSets).toEqual([
expect.objectContaining({
@@ -111,7 +111,7 @@ describe("LiveActivities", () => {
]);
expect(updateConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([
{
sql: '"relay_live_activities"."activity_push_token" = $1',
sql: "`relay_live_activities`.`activity_push_token` = ?",
params: ["activity-push-token"],
},
]);
@@ -150,6 +150,7 @@ describe("LiveActivities", () => {
const conflictConfigs: Array<{
readonly set?: Record<string, unknown>;
}> = [];
const dialect = new MySqlDialect();
const fakeDb = {
insert: (table: unknown) => {
@@ -158,7 +159,7 @@ describe("LiveActivities", () => {
values: (values: Record<string, unknown>) => {
insertedValues.push(values);
return {
onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {
onDuplicateKeyUpdate: (config: { readonly set?: Record<string, unknown> }) => {
conflictConfigs.push(config);
return Effect.void;
},
@@ -187,10 +188,13 @@ describe("LiveActivities", () => {
]);
expect(conflictConfigs[0]?.set).toEqual(
expect.objectContaining({
endedAt: relayLiveActivities.endedAt,
lastLiveActivityDeliveryAt: "2026-05-25T00:00:10.000Z",
}),
);
expect(dialect.sqlToQuery(conflictConfigs[0]?.set?.endedAt as SQL)).toEqual({
sql: "`relay_live_activities`.`ended_at`",
params: [],
});
}).pipe(
Effect.provide(
LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
@@ -203,7 +207,7 @@ describe("LiveActivities", () => {
const fakeDb = {
insert: () => ({
values: () => ({
onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {
onDuplicateKeyUpdate: (config: { readonly set?: Record<string, unknown> }) => {
conflictConfigs.push(config);
return Effect.void;
},
@@ -261,7 +265,7 @@ describe("LiveActivities", () => {
set: () => ({ where: () => Effect.fail(cause) }),
}),
insert: () => ({
values: () => ({ onConflictDoUpdate: () => Effect.fail(cause) }),
values: () => ({ onDuplicateKeyUpdate: () => Effect.fail(cause) }),
}),
select: () => ({
from: () => ({
@@ -166,8 +166,7 @@ export const make = Effect.gen(function* () {
createdAt: updatedAt,
updatedAt,
})
.onConflictDoUpdate({
target: [relayLiveActivities.userId, relayLiveActivities.deviceId],
.onDuplicateKeyUpdate({
set: {
activityPushToken: registration.activityPushToken,
remoteStartQueuedAt: null,
@@ -277,8 +276,7 @@ export const make = Effect.gen(function* () {
createdAt: input.deliveredAt,
updatedAt: input.deliveredAt,
})
.onConflictDoUpdate({
target: [relayLiveActivities.userId, relayLiveActivities.deviceId],
.onDuplicateKeyUpdate({
set: {
// A delivered start begins a NEW activity generation: the stored
// update token belongs to the previous activity (dead once a new
@@ -298,7 +296,7 @@ export const make = Effect.gen(function* () {
? input.deliveredAt
: sql`coalesce(
${relayLiveActivities.remoteStartedAt},
excluded.remote_started_at
values(remote_started_at)
)`,
remoteStartQueuedAt: null,
endedAt:
@@ -306,7 +304,7 @@ export const make = Effect.gen(function* () {
? null
: input.kind === "live_activity_end"
? input.deliveredAt
: relayLiveActivities.endedAt,
: sql`${relayLiveActivities.endedAt}`,
lastAggregateJson: aggregateJson,
lastLiveActivityDeliveryAt: input.deliveredAt,
updatedAt: input.deliveredAt,
@@ -341,12 +339,11 @@ export const make = Effect.gen(function* () {
createdAt: input.queuedAt,
updatedAt: input.queuedAt,
})
.onConflictDoUpdate({
target: [relayLiveActivities.userId, relayLiveActivities.deviceId],
.onDuplicateKeyUpdate({
set: {
remoteStartQueuedAt: sql`coalesce(
${relayLiveActivities.remoteStartQueuedAt},
excluded.remote_start_queued_at
values(remote_start_queued_at)
)`,
endedAt: null,
updatedAt: input.queuedAt,
+7 -18
View File
@@ -23,19 +23,13 @@ describe("DpopProofReplay", () => {
expect(table).toBe(relayDpopProofs);
calls.push("insert");
return {
values: (values: (typeof insertedValues)[number]) => {
insertedValues.push(values);
calls.push("insert.values");
ignore: () => {
calls.push("insert.ignore");
return {
onConflictDoNothing: () => {
calls.push("insert.onConflictDoNothing");
return {
returning: (selection: unknown) => {
expect(selection).toBeDefined();
calls.push("insert.returning");
return Effect.succeed([{ jti: values.jti }]);
},
};
values: (values: (typeof insertedValues)[number]) => {
insertedValues.push(values);
calls.push("insert.values");
return Effect.succeed({ affectedRows: 1 });
},
};
},
@@ -53,12 +47,7 @@ describe("DpopProofReplay", () => {
});
expect(consumed).toBe(true);
expect(calls).toEqual([
"insert",
"insert.values",
"insert.onConflictDoNothing",
"insert.returning",
]);
expect(calls).toEqual(["insert", "insert.ignore", "insert.values"]);
expect(insertedValues).toMatchObject([
{
thumbprint: "thumbprint",
+3 -3
View File
@@ -8,6 +8,7 @@ import { lt } from "drizzle-orm";
import { verifyDpopProof } from "@t3tools/shared/dpop";
import * as RelayDb from "../db.ts";
import { affectedRows } from "../persistence/mysqlResult.ts";
import { relayDpopProofs } from "../persistence/schema.ts";
export class DpopProofReplayPersistenceError extends Schema.TaggedErrorClass<DpopProofReplayPersistenceError>()(
@@ -55,6 +56,7 @@ const make = Effect.gen(function* () {
const createdAt = DateTime.formatIso(yield* DateTime.now);
const inserted = yield* db
.insert(relayDpopProofs)
.ignore()
.values({
thumbprint: input.thumbprint,
jti: input.jti,
@@ -62,8 +64,6 @@ const make = Effect.gen(function* () {
expiresAt: DateTime.formatIso(input.expiresAt),
createdAt,
})
.onConflictDoNothing()
.returning({ jti: relayDpopProofs.jti })
.pipe(
Effect.mapError(
(cause) =>
@@ -76,7 +76,7 @@ const make = Effect.gen(function* () {
}),
),
);
return inserted.length > 0;
return affectedRows(inserted) > 0;
},
);
@@ -62,19 +62,14 @@ function makeDpopProof(input: {
function layer(
insert: (
values: DpopProofInsertValues,
) => Effect.Effect<ReadonlyArray<{ readonly jti: string }>, { _tag: string }>,
) => Effect.Effect<{ readonly affectedRows: number }, { _tag: string }>,
) {
const fakeDb = {
insert: (table: unknown) => {
expect(table).toBe(relayDpopProofs);
return {
values: (values: DpopProofInsertValues) => ({
onConflictDoNothing: () => ({
returning: (selection: unknown) => {
expect(selection).toBeDefined();
return insert(values);
},
}),
ignore: () => ({
values: (values: DpopProofInsertValues) => insert(values),
}),
};
},
@@ -88,10 +83,10 @@ function consumeEachProofOnce() {
Effect.sync(() => {
const key = `${values.thumbprint}:${values.jti}`;
if (consumed.has(key)) {
return [];
return { affectedRows: 0 };
}
consumed.add(key);
return [{ jti: values.jti }];
return { affectedRows: 1 };
});
}
+50 -22
View File
@@ -1,10 +1,9 @@
import type { PgClient } from "@effect/sql-pg/PgClient";
import type { MysqlClient } from "@effect/sql-mysql2/MysqlClient";
import * as Cloudflare from "alchemy/Cloudflare";
import * as Drizzle from "alchemy/Drizzle";
import * as Planetscale from "alchemy/Planetscale";
import * as Alchemy from "alchemy";
import * as RemovalPolicy from "alchemy/RemovalPolicy";
import type { EffectPgDatabase } from "drizzle-orm/effect-postgres";
import type { EffectMysql2Database } from "drizzle-orm/effect-mysql2";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -13,8 +12,8 @@ import { relayDatabaseMode } from "./dbConfig.ts";
export class RelayDb extends Context.Service<
RelayDb,
EffectPgDatabase & {
readonly $client: PgClient;
EffectMysql2Database & {
readonly $client: MysqlClient;
}
>()("t3code-relay/db/RelayDb") {}
@@ -35,50 +34,79 @@ export class RelayTransactions extends Context.Service<
);
}
// Unlike Postgres, alchemy has no automatic Drizzle.Schema generation for
// MySQL (drizzle-kit exposes no programmatic mysql API): migrations are
// generated manually with `pnpm exec drizzle-kit generate` (drizzle.config.ts)
// and checked in; deploys apply whatever is committed here.
const mysqlMigrationsDir = "migrations/mysql";
export const PlanetscaleDatabase = Effect.gen(function* () {
const { stage } = yield* Alchemy.Stack;
const schema = yield* Drizzle.Schema("RelaySchema", {
schema: "./src/persistence/schema.ts",
out: "./migrations/postgres",
dialect: "postgres",
});
const mode = relayDatabaseMode(stage);
// The retired Postgres database stays in the stack (prod only) until the
// Vitess cutover has soaked: prod must own BOTH databases while DMS
// replicates data across and while rollback (redeploying the previous
// commit, which flips Hyperdrive back to this role's origin) is still on
// the table. The migrations dir is the frozen checked-in history — every
// file is already recorded in relay_migrations, so deploys no-op against
// it. Remove this block together with migrations/postgres once the old
// database is decommissioned
// (docs/operations/relay-postgres-to-vitess-migration.md).
if (mode === "shared-database") {
const postgresDatabase = yield* Planetscale.PostgresDatabase("RelayPostgresDatabase", {
name: "t3coderelay",
region: { slug: "us-west" },
clusterSize: "PS_20",
migrationsDir: "migrations/postgres",
migrationsTable: "relay_migrations",
replicas: 2,
}).pipe(RemovalPolicy.retain());
yield* Planetscale.PostgresRole("RelayPostgresRuntimeRole", {
database: postgresDatabase,
inheritedRoles: ["pg_read_all_data", "pg_write_all_data"],
});
}
const database =
mode === "shared-database"
? yield* Planetscale.PostgresDatabase("RelayPostgresDatabase", {
name: "t3coderelay",
? // Same resource + props as the provisioning PR that created this
// database (with its baseline already applied) ahead of the cutover,
// so this deploy no-ops on the database itself.
yield* Planetscale.MySQLDatabase("RelayMysqlDatabase", {
name: "t3coderelay-vitess",
region: { slug: "us-west" },
clusterSize: "PS_20",
migrationsDir: schema.out,
migrationsDir: mysqlMigrationsDir,
migrationsTable: "relay_migrations",
replicas: 2,
}).pipe(RemovalPolicy.retain())
: yield* Planetscale.PostgresDatabase.ref("RelayPostgresDatabase", {
: yield* Planetscale.MySQLDatabase.ref("RelayMysqlDatabase", {
stage: "prod",
});
const branch =
mode === "stage-branch"
? yield* Planetscale.PostgresBranch("RelayPostgresBranch", {
? yield* Planetscale.MySQLBranch("RelayMysqlBranch", {
database,
migrationsDir: schema.out,
isProduction: false,
migrationsDir: mysqlMigrationsDir,
migrationsTable: "relay_migrations",
})
: undefined;
const runtimeRole = yield* Planetscale.PostgresRole("RelayPostgresRuntimeRole", {
const runtimePassword = yield* Planetscale.MySQLPassword("RelayMysqlRuntimePassword", {
database,
...(branch ? { branch } : {}),
inheritedRoles: ["pg_read_all_data", "pg_write_all_data"],
role: "readwriter",
});
return { branch, database, runtimeRole };
return { branch, database, runtimePassword };
});
export const RelayHyperdrive = Effect.gen(function* () {
const { runtimeRole } = yield* PlanetscaleDatabase;
const { runtimePassword } = yield* PlanetscaleDatabase;
return yield* Cloudflare.Hyperdrive.Connection("RelayHyperdrive", {
origin: runtimeRole.origin,
origin: runtimePassword.origin,
caching: {
disabled: true,
},
@@ -1,6 +1,6 @@
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
import { describe, expect, it } from "@effect/vitest";
import { PgDialect } from "drizzle-orm/pg-core";
import { MySqlDialect } from "drizzle-orm/mysql-core";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -87,11 +87,11 @@ describe("EnvironmentCredentials", () => {
expect(error).not.toHaveProperty("token");
expect(whereConditions).toHaveLength(1);
const query = new PgDialect().sqlToQuery(whereConditions[0] as never);
const query = new MySqlDialect().sqlToQuery(whereConditions[0] as never);
expect(query.sql).toContain("exists");
expect(query.sql).toContain('"relay_environment_links"."environment_id"');
expect(query.sql).toContain('"relay_environment_links"."environment_public_key"');
expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
expect(query.sql).toContain("`relay_environment_links`.`environment_id`");
expect(query.sql).toContain("`relay_environment_links`.`environment_public_key`");
expect(query.sql).toContain("`relay_environment_links`.`revoked_at` is null");
}).pipe(
Effect.provide(
EnvironmentCredentials.layer.pipe(
@@ -168,13 +168,13 @@ describe("EnvironmentCredentials", () => {
staleCredentialRevocations[0]?.values.updatedAt,
);
const query = new PgDialect().sqlToQuery(staleCredentialRevocations[0]?.condition as never);
expect(query.sql).toContain('"relay_environment_credentials"."environment_id" = $1');
expect(query.sql).toContain(
'"relay_environment_credentials"."environment_public_key" = $2',
const query = new MySqlDialect().sqlToQuery(
staleCredentialRevocations[0]?.condition as never,
);
expect(query.sql).toContain('"relay_environment_credentials"."credential_id" <> $3');
expect(query.sql).toContain('"relay_environment_credentials"."revoked_at" is null');
expect(query.sql).toContain("`relay_environment_credentials`.`environment_id` = ?");
expect(query.sql).toContain("`relay_environment_credentials`.`environment_public_key` = ?");
expect(query.sql).toContain("`relay_environment_credentials`.`credential_id` <> ?");
expect(query.sql).toContain("`relay_environment_credentials`.`revoked_at` is null");
expect(query.params).toEqual(["env_test", "environment-public-key", credentialId]);
}).pipe(
Effect.provide(
@@ -199,12 +199,7 @@ describe("EnvironmentCredentials", () => {
return {
where: (condition: unknown) => {
whereConditions.push(condition);
return {
returning: (selection: unknown) => {
expect(selection).toBeDefined();
return Effect.succeed([{ credentialId: "credential-1" }]);
},
};
return Effect.succeed({ affectedRows: 1 });
},
};
},
@@ -224,14 +219,14 @@ describe("EnvironmentCredentials", () => {
expect(updateValues[0]?.revokedAt).toEqual(updateValues[0]?.updatedAt);
expect(whereConditions).toHaveLength(1);
const query = new PgDialect().sqlToQuery(whereConditions[0] as never);
expect(query.sql).toContain('"relay_environment_credentials"."environment_id" = $1');
expect(query.sql).toContain('"relay_environment_credentials"."environment_public_key" = $2');
expect(query.sql).toContain('"relay_environment_credentials"."revoked_at" is null');
const query = new MySqlDialect().sqlToQuery(whereConditions[0] as never);
expect(query.sql).toContain("`relay_environment_credentials`.`environment_id` = ?");
expect(query.sql).toContain("`relay_environment_credentials`.`environment_public_key` = ?");
expect(query.sql).toContain("`relay_environment_credentials`.`revoked_at` is null");
expect(query.sql).toContain("not exists");
expect(query.sql).toContain('"relay_environment_links"."environment_id" = $3');
expect(query.sql).toContain('"relay_environment_links"."environment_public_key" = $4');
expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
expect(query.sql).toContain("`relay_environment_links`.`environment_id` = ?");
expect(query.sql).toContain("`relay_environment_links`.`environment_public_key` = ?");
expect(query.sql).toContain("`relay_environment_links`.`revoked_at` is null");
expect(query.params).toEqual([
"env_test",
"environment-public-key",
@@ -7,9 +7,10 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { and, eq, exists, isNull, ne, notExists } from "drizzle-orm";
import { QueryBuilder } from "drizzle-orm/pg-core";
import { QueryBuilder } from "drizzle-orm/mysql-core";
import * as RelayDb from "../db.ts";
import { affectedRows } from "../persistence/mysqlResult.ts";
import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persistence/schema.ts";
export class EnvironmentCredentialCreatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialCreatePersistenceError>()(
@@ -245,7 +246,7 @@ const make = Effect.gen(function* () {
)(function* (input) {
yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
const revokedAt = DateTime.formatIso(yield* DateTime.now);
const rows = yield* db
const revoked = yield* db
.update(relayEnvironmentCredentials)
.set({
revokedAt,
@@ -270,9 +271,6 @@ const make = Effect.gen(function* () {
),
),
)
.returning({
credentialId: relayEnvironmentCredentials.credentialId,
})
.pipe(
Effect.mapError(
(cause) =>
@@ -282,7 +280,7 @@ const make = Effect.gen(function* () {
}),
),
);
return rows.length > 0;
return affectedRows(revoked) > 0;
}),
});
});
@@ -1,7 +1,7 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { PgDialect } from "drizzle-orm/pg-core";
import { MySqlDialect } from "drizzle-orm/mysql-core";
import * as RelayDb from "../db.ts";
import { relayEnvironmentLinks } from "../persistence/schema.ts";
@@ -102,11 +102,11 @@ describe("EnvironmentLinks", () => {
expect(yield* links.listUsersForEnvironment({ environmentId: "env-1" })).toEqual([]);
expect(whereConditions).toHaveLength(1);
const query = new PgDialect().sqlToQuery(whereConditions[0] as never);
expect(query.sql).toContain('"relay_environment_links"."environment_id" = $1');
expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
expect(query.sql).toContain('"relay_environment_links"."notifications_enabled" = $2');
expect(query.sql).toContain('"relay_environment_links"."live_activities_enabled" = $3');
const query = new MySqlDialect().sqlToQuery(whereConditions[0] as never);
expect(query.sql).toContain("`relay_environment_links`.`environment_id` = ?");
expect(query.sql).toContain("`relay_environment_links`.`revoked_at` is null");
expect(query.sql).toContain("`relay_environment_links`.`notifications_enabled` = ?");
expect(query.sql).toContain("`relay_environment_links`.`live_activities_enabled` = ?");
expect(query.sql).toContain(" or ");
expect(query.params).toEqual(["env-1", true, true]);
}).pipe(
@@ -128,12 +128,7 @@ describe("EnvironmentLinks", () => {
return {
where: (condition: unknown) => {
whereConditions.push(condition);
return {
returning: (selection: unknown) => {
expect(selection).toBeDefined();
return Effect.succeed([{ environmentId: "env-1" }]);
},
};
return Effect.succeed({ affectedRows: 1 });
},
};
},
@@ -154,11 +149,11 @@ describe("EnvironmentLinks", () => {
expect(typeof updateValues[0]?.revokedAt).toBe("string");
expect(whereConditions).toHaveLength(1);
const dialect = new PgDialect();
const dialect = new MySqlDialect();
const query = dialect.sqlToQuery(whereConditions[0] as never);
expect(query.sql).toContain('"relay_environment_links"."user_id" = $1');
expect(query.sql).toContain('"relay_environment_links"."environment_id" = $2');
expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
expect(query.sql).toContain("`relay_environment_links`.`user_id` = ?");
expect(query.sql).toContain("`relay_environment_links`.`environment_id` = ?");
expect(query.sql).toContain("`relay_environment_links`.`revoked_at` is null");
expect(query.params).toEqual(["user-1", "env-1"]);
}).pipe(
Effect.provide(
@@ -12,6 +12,7 @@ import * as Schema from "effect/Schema";
import { and, eq, isNull, or } from "drizzle-orm";
import * as RelayDb from "../db.ts";
import { affectedRows } from "../persistence/mysqlResult.ts";
import { relayEnvironmentLinks } from "../persistence/schema.ts";
export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord {
@@ -191,8 +192,7 @@ const make = Effect.gen(function* () {
createdAt: now,
updatedAt: now,
})
.onConflictDoUpdate({
target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
.onDuplicateKeyUpdate({
set: {
environmentPublicKey: proof.environmentPublicKey,
environmentLabel: proof.descriptor.label,
@@ -401,7 +401,7 @@ const make = Effect.gen(function* () {
"relay.environment_id": input.environmentId,
});
const revokedAt = DateTime.formatIso(yield* DateTime.now);
const rows = yield* db
const revoked = yield* db
.update(relayEnvironmentLinks)
.set({
revokedAt,
@@ -414,7 +414,6 @@ const make = Effect.gen(function* () {
isNull(relayEnvironmentLinks.revokedAt),
),
)
.returning({ environmentId: relayEnvironmentLinks.environmentId })
.pipe(
Effect.mapError(
(cause) =>
@@ -425,7 +424,7 @@ const make = Effect.gen(function* () {
}),
),
);
return rows.length > 0;
return affectedRows(revoked) > 0;
}),
});
});
@@ -19,9 +19,7 @@ describe("ManagedEndpointAllocations", () => {
set: (values: { readonly updatedAt: string }) => {
claimedAt = values.updatedAt;
return {
where: () => ({
returning: () => Effect.succeed([{ userId: "user-1" }]),
}),
where: () => Effect.succeed({ affectedRows: 1 }),
};
},
};
@@ -46,9 +44,7 @@ describe("ManagedEndpointAllocations", () => {
delete: (table: unknown) => {
expect(table).toBe(relayManagedEndpointAllocations);
return {
where: () => ({
returning: () => Effect.succeed([]),
}),
where: () => Effect.succeed({ affectedRows: 0 }),
};
},
} as unknown as RelayDb.RelayDb["Service"];
@@ -102,10 +98,8 @@ describe("ManagedEndpointAllocations", () => {
insert: (table: unknown) => {
expect(table).toBe(relayManagedEndpointAllocations);
return {
values: () => ({
onConflictDoNothing: () => ({
returning: () => Effect.succeed([]),
}),
ignore: () => ({
values: () => Effect.succeed({ affectedRows: 0 }),
}),
};
},
@@ -8,6 +8,7 @@ import * as Schema from "effect/Schema";
import * as RelayDb from "../db.ts";
import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts";
import { affectedRows } from "../persistence/mysqlResult.ts";
import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
export interface ManagedEndpointAllocation {
@@ -194,15 +195,17 @@ export const make = Effect.gen(function* () {
input: ReserveManagedEndpointAllocationInput,
) {
const now = DateTime.formatIso(yield* DateTime.now);
const inserted = yield* db
// INSERT IGNORE swallows any unique-index conflict (allocation key,
// hostname, tunnel name), like the untargeted ON CONFLICT DO NOTHING
// did on Postgres; the read-back below resolves whichever row won.
yield* db
.insert(relayManagedEndpointAllocations)
.ignore()
.values({
...input,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing()
.returning(allocationSelection)
.pipe(
Effect.mapError(
(cause) =>
@@ -215,25 +218,23 @@ export const make = Effect.gen(function* () {
),
);
const allocation =
inserted[0] ??
(yield* db
.select(allocationSelection)
.from(relayManagedEndpointAllocations)
.where(whereAllocation(input))
.limit(1)
.pipe(
Effect.map((rows) => rows[0]),
Effect.mapError(
(cause) =>
new ManagedEndpointAllocationPersistenceError({
operation: "reserve",
stage: "database-request",
...input,
cause,
}),
),
));
const allocation = yield* db
.select(allocationSelection)
.from(relayManagedEndpointAllocations)
.where(whereAllocation(input))
.limit(1)
.pipe(
Effect.map((rows) => rows[0]),
Effect.mapError(
(cause) =>
new ManagedEndpointAllocationPersistenceError({
operation: "reserve",
stage: "database-request",
...input,
cause,
}),
),
);
if (allocation === undefined) {
return yield* new ManagedEndpointAllocationPersistenceError({
@@ -327,9 +328,8 @@ export const make = Effect.gen(function* () {
eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),
),
)
.returning({ userId: relayManagedEndpointAllocations.userId })
.pipe(
Effect.map((rows) => rows.length > 0),
Effect.map((result) => affectedRows(result) > 0),
Effect.mapError(
(cause) =>
new ManagedEndpointAllocationPersistenceError({
@@ -357,9 +357,8 @@ export const make = Effect.gen(function* () {
eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),
),
)
.returning({ userId: relayManagedEndpointAllocations.userId })
.pipe(
Effect.map((rows) => rows.length > 0),
Effect.map((result) => affectedRows(result) > 0),
Effect.mapError(
(cause) =>
new ManagedEndpointAllocationPersistenceError({
@@ -402,9 +401,8 @@ export const make = Effect.gen(function* () {
eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),
),
)
.returning({ userId: relayManagedEndpointAllocations.userId })
.pipe(
Effect.map((rows) => rows.length > 0),
Effect.map((result) => affectedRows(result) > 0),
Effect.mapError(
(cause) =>
new ManagedEndpointAllocationPersistenceError({
+146
View File
@@ -0,0 +1,146 @@
// @effect-diagnostics anyUnknownInErrorContext:off unsafeEffectTypeAssertion:off preferSchemaOverJson:off globalErrorInEffectFailure:off globalErrorInEffectCatch:off - vendored alchemy code, kept verbatim; alchemy owns these idioms.
// Vendored from alchemy-run/alchemy#1063 (src/SQL/MySQL.ts + src/Drizzle/MySQL.ts,
// merge commit 5ae3df20df): Drizzle.MySQL landed upstream after alchemy
// 2.0.0-beta.67 was cut, so no published release carries it yet. Delete this
// file and import `Drizzle.MySQL` from "alchemy/Drizzle" once the workspace
// moves to a release that contains it.
import * as MysqlClient from "@effect/sql-mysql2/MysqlClient";
import { makeExecutionMemo } from "alchemy/Runtime/ExecutionMemo";
import { proxyChain } from "alchemy/Util/proxy-chain";
import type { AnyRelations, EmptyRelations } from "drizzle-orm";
import type { EffectMysql2Database } from "drizzle-orm/effect-mysql2";
import * as MySqlDrizzle from "drizzle-orm/effect-mysql2";
import type { EffectDrizzleMySqlConfig } from "drizzle-orm/mysql-core/effect/utils";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
/**
* Options for the MySQL client: `@effect/sql-mysql2`'s client configuration,
* with `url` widened to also accept an Effect (e.g. a Hyperdrive connection
* string, which resolves from the Worker environment at runtime).
*/
export type MySQLConfig<E = never, R = never> = Omit<MysqlClient.MysqlClientConfig, "url"> & {
readonly url: Redacted.Redacted<string> | Effect.Effect<Redacted.Redacted<string>, E, R>;
};
const isWorkerd = () =>
(globalThis as { navigator?: { userAgent?: string } }).navigator?.userAgent ===
"Cloudflare-Workers" || "WebSocketPair" in globalThis;
// Query-string params are JSON-parsed into poolConfig entries (mysql2's own
// URI convention), so `mysql://...?ssl={"rejectUnauthorized":true}` works.
const parseMySQLUrl = (url: Redacted.Redacted<string>) =>
Effect.try({
try: () => {
const u = new URL(Redacted.value(url));
const poolConfig: Record<string, unknown> = {};
for (const [key, value] of u.searchParams) {
try {
poolConfig[key] = JSON.parse(value);
} catch {
poolConfig[key] = value;
}
}
const database = decodeURIComponent(u.pathname.replace(/^\//, ""));
return {
host: u.hostname,
port: u.port === "" ? 3306 : Number(u.port),
database: database === "" ? undefined : database,
username: u.username === "" ? undefined : decodeURIComponent(u.username),
password: u.password === "" ? undefined : Redacted.make(decodeURIComponent(u.password)),
poolConfig: poolConfig as MysqlClient.MysqlClientConfig["poolConfig"],
};
},
catch: (cause) => new Error(`SQL.MySQL: failed to parse connection url: ${cause}`),
}).pipe(Effect.orDie);
/**
* Resolve a {@link MySQLConfig} into the `MysqlClientConfig` handed to
* `@effect/sql-mysql2`. The `url` is parsed into discrete connection fields
* (mysql2's URI code path ignores `poolConfig`), and on workerd the defaults
* flip to `poolConfig.disableEval` (no runtime codegen in the isolate) and
* `disablePreparedStatements` (Hyperdrive's MySQL proxy has no
* `COM_STMT_PREPARE`). Explicit config fields always win over parsed /
* detected values.
*/
export const resolveMySQLConfig = <E = never, R = never>(
config: MySQLConfig<E, R>,
): Effect.Effect<MysqlClient.MysqlClientConfig, E, R> =>
Effect.gen(function* () {
const { url, ...overrides } = config;
const resolved = Effect.isEffect(url) ? yield* url : url;
const parsed = yield* parseMySQLUrl(resolved);
const workerd = yield* Effect.sync(isWorkerd);
return {
...overrides,
host: overrides.host ?? parsed.host,
port: overrides.port ?? parsed.port,
database: overrides.database ?? parsed.database,
username: overrides.username ?? parsed.username,
password: overrides.password ?? parsed.password,
poolConfig: {
...(workerd ? { disableEval: true } : {}),
...parsed.poolConfig,
...overrides.poolConfig,
},
disablePreparedStatements: overrides.disablePreparedStatements ?? workerd,
} satisfies MysqlClient.MysqlClientConfig;
});
/**
* Open a Drizzle/MySQL database from a connection URL using the
* `drizzle-orm/effect-mysql2` integration.
*
* ```typescript
* const conn = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
* const db = yield* DrizzleMysql.MySQL(conn.connectionString, { relations });
*
* fetch: Effect.gen(function* () {
* const rows = yield* db.select().from(users);
* });
* ```
*
* The pool opens on the first query of an execution, is reused for every
* query in it, and closes when the event settles (see
* {@link makeExecutionMemo}); plan/deploy never connect. Workers defaults
* ({@link resolveMySQLConfig}) are overridden via `config.client`.
*
* @binding
*/
export const MySQL = <TRelations extends AnyRelations = EmptyRelations, E = never, R = never>(
connectionString: Effect.Effect<Redacted.Redacted<string>, E, R>,
config?: EffectDrizzleMySqlConfig<TRelations> & {
/**
* Overrides for the underlying `@effect/sql-mysql2` client — pool
* options (e.g. `poolConfig.ssl` for a direct TLS connection),
* `disablePreparedStatements`, `maxConnections`, and friends.
*/
readonly client?: Omit<MySQLConfig, "url">;
},
) =>
Effect.map(
makeExecutionMemo(
Effect.gen(function* () {
const { client, ...drizzleConfig } = config ?? {};
const mysqlCtx = yield* Layer.build(
MysqlClient.layer(yield* resolveMySQLConfig({ ...client, url: connectionString })),
);
return yield* MySqlDrizzle.makeWithDefaults(
drizzleConfig as EffectDrizzleMySqlConfig<TRelations>,
).pipe(Effect.provideContext(mysqlCtx));
}),
),
(db) =>
proxyChain<
EffectMysql2Database<TRelations> & {
$client: MysqlClient.MysqlClient;
}
>(
db as Effect.Effect<
EffectMysql2Database<TRelations> & {
$client: MysqlClient.MysqlClient;
}
>,
),
);
@@ -0,0 +1,17 @@
/**
* drizzle's effect-mysql2 driver yields the mysql2 `ResultSetHeader` for
* INSERT/UPDATE/DELETE statements, but types the result as a row array.
* Normalize to the affected-row count; MySQL has no `RETURNING`, so this
* replaces the Postgres `RETURNING`-based "did this statement match" checks.
*/
export const affectedRows = (result: unknown): number => {
if (
typeof result === "object" &&
result !== null &&
"affectedRows" in result &&
typeof (result as { affectedRows: unknown }).affectedRows === "number"
) {
return (result as { affectedRows: number }).affectedRows;
}
return 0;
};
+32 -28
View File
@@ -6,29 +6,33 @@ import type {
import {
boolean,
index,
integer,
jsonb,
pgTable,
int,
json,
mysqlTable,
primaryKey,
text,
uniqueIndex,
varchar,
} from "drizzle-orm/pg-core";
} from "drizzle-orm/mysql-core";
export const relayMobileDevices = pgTable(
// InnoDB cannot index TEXT columns without a prefix length, so every column
// that participates in an index or primary key is a bounded VARCHAR here
// (push/activity tokens, hostnames, tunnel names, environment public keys).
export const relayMobileDevices = mysqlTable(
"relay_mobile_devices",
{
userId: varchar("user_id", { length: 255 }).notNull(),
deviceId: varchar("device_id", { length: 255 }).notNull(),
label: text("label").notNull().default("iOS device"),
platform: varchar("platform", { length: 16 }).notNull().$type<"ios">(),
iosMajorVersion: integer("ios_major_version").notNull(),
iosMajorVersion: int("ios_major_version").notNull(),
appVersion: varchar("app_version", { length: 64 }),
bundleId: varchar("bundle_id", { length: 255 }),
apsEnvironment: varchar("aps_environment", { length: 16 }).$type<"sandbox" | "production">(),
pushToken: text("push_token"),
pushToStartToken: text("push_to_start_token"),
preferencesJson: jsonb("preferences_json").notNull().$type<RelayAgentAwarenessPreferences>(),
pushToken: varchar("push_token", { length: 255 }),
pushToStartToken: varchar("push_to_start_token", { length: 255 }),
preferencesJson: json("preferences_json").notNull().$type<RelayAgentAwarenessPreferences>(),
createdAt: varchar("created_at", { length: 64 }).notNull(),
updatedAt: varchar("updated_at", { length: 64 }).notNull(),
},
@@ -39,16 +43,16 @@ export const relayMobileDevices = pgTable(
],
);
export const relayLiveActivities = pgTable(
export const relayLiveActivities = mysqlTable(
"relay_live_activities",
{
userId: varchar("user_id", { length: 255 }).notNull(),
deviceId: varchar("device_id", { length: 255 }).notNull(),
activityPushToken: text("activity_push_token"),
activityPushToken: varchar("activity_push_token", { length: 255 }),
remoteStartQueuedAt: varchar("remote_start_queued_at", { length: 64 }),
remoteStartedAt: varchar("remote_started_at", { length: 64 }),
endedAt: varchar("ended_at", { length: 64 }),
lastAggregateJson: jsonb("last_aggregate_json").$type<RelayAgentActivityAggregateState>(),
lastAggregateJson: json("last_aggregate_json").$type<RelayAgentActivityAggregateState>(),
lastLiveActivityDeliveryAt: varchar("last_live_activity_delivery_at", { length: 64 }),
createdAt: varchar("created_at", { length: 64 }).notNull(),
updatedAt: varchar("updated_at", { length: 64 }).notNull(),
@@ -59,13 +63,13 @@ export const relayLiveActivities = pgTable(
],
);
export const relayEnvironmentLinks = pgTable(
export const relayEnvironmentLinks = mysqlTable(
"relay_environment_links",
{
userId: varchar("user_id", { length: 191 }).notNull(),
environmentId: varchar("environment_id", { length: 191 }).notNull(),
environmentLabel: text("environment_label").notNull().default("T3 Environment"),
environmentPublicKey: text("environment_public_key").notNull(),
environmentPublicKey: varchar("environment_public_key", { length: 255 }).notNull(),
endpointHttpBaseUrl: text("endpoint_http_base_url").notNull(),
endpointWsBaseUrl: text("endpoint_ws_base_url").notNull(),
endpointProviderKind: varchar("endpoint_provider_kind", { length: 32 }).notNull(),
@@ -83,14 +87,14 @@ export const relayEnvironmentLinks = pgTable(
],
);
export const relayManagedEndpointAllocations = pgTable(
export const relayManagedEndpointAllocations = mysqlTable(
"relay_managed_endpoint_allocations",
{
userId: varchar("user_id", { length: 191 }).notNull(),
environmentId: varchar("environment_id", { length: 191 }).notNull(),
hostname: text("hostname").notNull(),
hostname: varchar("hostname", { length: 255 }).notNull(),
tunnelId: varchar("tunnel_id", { length: 191 }),
tunnelName: text("tunnel_name").notNull(),
tunnelName: varchar("tunnel_name", { length: 255 }).notNull(),
dnsRecordId: varchar("dns_record_id", { length: 191 }),
readyAt: varchar("ready_at", { length: 64 }),
createdAt: varchar("created_at", { length: 64 }).notNull(),
@@ -103,19 +107,19 @@ export const relayManagedEndpointAllocations = pgTable(
],
);
export const relayManagedTunnelLimits = pgTable("relay_managed_tunnel_limits", {
export const relayManagedTunnelLimits = mysqlTable("relay_managed_tunnel_limits", {
userId: varchar("user_id", { length: 191 }).primaryKey(),
maxTunnels: integer("max_tunnels").notNull(),
maxTunnels: int("max_tunnels").notNull(),
createdAt: varchar("created_at", { length: 64 }).notNull(),
updatedAt: varchar("updated_at", { length: 64 }).notNull(),
});
export const relayEnvironmentCredentials = pgTable(
export const relayEnvironmentCredentials = mysqlTable(
"relay_environment_credentials",
{
credentialId: varchar("credential_id", { length: 64 }).primaryKey(),
environmentId: varchar("environment_id", { length: 191 }).notNull(),
environmentPublicKey: text("environment_public_key").notNull(),
environmentPublicKey: varchar("environment_public_key", { length: 255 }).notNull(),
credentialHash: varchar("credential_hash", { length: 191 }).notNull(),
revokedAt: varchar("revoked_at", { length: 64 }),
createdAt: varchar("created_at", { length: 64 }).notNull(),
@@ -132,13 +136,13 @@ export const relayEnvironmentCredentials = pgTable(
],
);
export const relayAgentActivityRows = pgTable(
export const relayAgentActivityRows = mysqlTable(
"relay_agent_activity_rows",
{
environmentId: varchar("environment_id", { length: 191 }).notNull(),
environmentPublicKey: text("environment_public_key").notNull(),
environmentPublicKey: varchar("environment_public_key", { length: 255 }).notNull(),
threadId: varchar("thread_id", { length: 191 }).notNull(),
stateJson: jsonb("state_json").notNull().$type<RelayAgentActivityState>(),
stateJson: json("state_json").notNull().$type<RelayAgentActivityState>(),
updatedAt: varchar("updated_at", { length: 64 }).notNull(),
createdAt: varchar("created_at", { length: 64 }).notNull(),
},
@@ -148,7 +152,7 @@ export const relayAgentActivityRows = pgTable(
],
);
export const relayDeliveryAttempts = pgTable(
export const relayDeliveryAttempts = mysqlTable(
"relay_delivery_attempts",
{
id: varchar("id", { length: 36 }).primaryKey(),
@@ -160,7 +164,7 @@ export const relayDeliveryAttempts = pgTable(
kind: varchar("kind", { length: 64 }).notNull(),
sourceJobId: varchar("source_job_id", { length: 64 }),
tokenSuffix: varchar("token_suffix", { length: 16 }),
apnsStatus: integer("apns_status"),
apnsStatus: int("apns_status"),
apnsReason: text("apns_reason"),
apnsId: varchar("apns_id", { length: 128 }),
transportError: text("transport_error"),
@@ -175,12 +179,12 @@ export const relayDeliveryAttempts = pgTable(
],
);
export const relayDpopProofs = pgTable(
export const relayDpopProofs = mysqlTable(
"relay_dpop_proofs",
{
thumbprint: varchar("thumbprint", { length: 128 }).notNull(),
jti: varchar("jti", { length: 255 }).notNull(),
iat: integer("iat").notNull(),
iat: int("iat").notNull(),
expiresAt: varchar("expires_at", { length: 64 }).notNull(),
createdAt: varchar("created_at", { length: 64 }).notNull(),
},
+2 -2
View File
@@ -1,6 +1,5 @@
import * as Alchemy from "alchemy";
import * as Cloudflare from "alchemy/Cloudflare";
import * as Drizzle from "alchemy/Drizzle";
import * as Config from "effect/Config";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
@@ -44,6 +43,7 @@ import * as EnvironmentLinks from "./environments/EnvironmentLinks.ts";
import * as ManagedEndpointAllocations from "./environments/ManagedEndpointAllocations.ts";
import * as LiveActivities from "./agentActivity/LiveActivities.ts";
import * as RelayDb from "./db.ts";
import * as DrizzleMysql from "./persistence/drizzleMysql.ts";
import { RelayApnsDeliveryDeadLetterQueue, RelayApnsDeliveryQueue } from "./queues.ts";
import * as RelayConfiguration from "./Config.ts";
import * as AgentActivityPublisher from "./agentActivity/AgentActivityPublisher.ts";
@@ -143,7 +143,7 @@ export const ApiLive = Api.make(
const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey;
const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey;
const hyperdrive = yield* Cloudflare.Hyperdrive.Connect(yield* RelayDb.RelayHyperdrive);
const db = yield* Drizzle.Postgres(hyperdrive.connectionString);
const db = yield* DrizzleMysql.MySQL(hyperdrive.connectionString);
const managedEndpointTunnelBinding = yield* Cloudflare.Tunnel.ReadWriteTunnel();
// Keep Worker custom-domain reconciliation ordered after API zone provisioning.
+24
View File
@@ -73,6 +73,30 @@ describe("ServerProvider", () => {
expect(parsed.continuation?.groupKey).toBe("codex:home:/Users/julius/.codex");
});
it("decodes optional legacy model metadata", () => {
const parsed = decodeServerProvider({
instanceId: "codex",
driver: "codex",
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-04-10T00:00:00.000Z",
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
});
expect(parsed.models[0]?.isLegacy).toBe(true);
});
});
describe("server config forward compatibility", () => {
+1
View File
@@ -68,6 +68,7 @@ export const ServerProviderModel = Schema.Struct({
subProvider: Schema.optional(TrimmedNonEmptyString),
isCustom: Schema.Boolean,
isDefault: Schema.optional(Schema.Boolean),
isLegacy: Schema.optional(Schema.Boolean),
capabilities: Schema.NullOr(ModelCapabilities),
});
export type ServerProviderModel = typeof ServerProviderModel.Type;
+48 -7
View File
@@ -52,6 +52,7 @@ overrides:
'@effect/platform-bun': 4.0.0-beta.102
'@effect/platform-node': 4.0.0-beta.102
'@effect/platform-node-shared': 4.0.0-beta.102
'@effect/sql-mysql2': 4.0.0-beta.102
'@effect/sql-pg': 4.0.0-beta.102
'@effect/sql-sqlite-bun': 4.0.0-beta.102
'@effect/vitest': 4.0.0-beta.102
@@ -664,6 +665,9 @@ importers:
'@clerk/backend':
specifier: 3.14.0
version: 3.14.0([email protected]([email protected]))([email protected])
'@effect/sql-mysql2':
specifier: 4.0.0-beta.102
version: 4.0.0-beta.102(@types/[email protected])([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))
'@effect/sql-pg':
specifier: 4.0.0-beta.102
version: 4.0.0-beta.102([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))
@@ -684,10 +688,10 @@ importers:
version: link:../../packages/shared
alchemy:
specifier: 2.0.0-beta.65
version: 2.0.0-beta.65(249551d75ad3792c0b22cd2754b25266)
version: 2.0.0-beta.65(eead4ef14d62793c7a40bd378b7ab471)
drizzle-orm:
specifier: 1.0.0-rc.4
version: 1.0.0-rc.4(@cloudflare/[email protected])(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@libsql/[email protected]([email protected])([email protected]))([email protected])([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@types/[email protected]))([email protected])([email protected])
version: 1.0.0-rc.4(6d7372add232cae10a536adca115d034)
effect:
specifier: 4.0.0-beta.102
version: 4.0.0-beta.102(patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)
@@ -1978,6 +1982,11 @@ packages:
peerDependencies:
effect: 4.0.0-beta.102
'@effect/[email protected]':
resolution: {integrity: sha512-dLt7NG0pBHvWvEvwjACEdZfLt32VHg7wZU2qOsS8HiYZcm+NZrv2Bkdqm+GRwWqcGxV1Q125wld8seXC+YN7CQ==}
peerDependencies:
effect: 4.0.0-beta.102
'@effect/[email protected]':
resolution: {integrity: sha512-02a+fNfECWCZIZcgHl7OLQN2jZj42gq90EdwdnvR3KA6GLGypY02swABS4zFtaW9H80rTa0ukqVnTdcO/DT5GQ==}
peerDependencies:
@@ -6159,7 +6168,7 @@ packages:
'@cloudflare/workers-types': '>=4'
'@effect/sql-d1': '>=4.0.0-beta.83 || >=4.0.0'
'@effect/sql-libsql': '>=4.0.0-beta.83 || >=4.0.0'
'@effect/sql-mysql2': '>=4.0.0-beta.83 || >=4.0.0'
'@effect/sql-mysql2': 4.0.0-beta.102
'@effect/sql-pg': 4.0.0-beta.102
'@effect/sql-pglite': '>=4.0.0-beta.83 || >=4.0.0'
'@effect/sql-sqlite-bun': 4.0.0-beta.102
@@ -8270,6 +8279,12 @@ packages:
peerDependencies:
'@types/node': 24.12.4
[email protected]:
resolution: {integrity: sha512-fxh3HpQ8vJtu/Mmnd4Xsur19jGjHGzRLMxptiDtOkbX7EVBgnafGSGDx1WGGVmJLClVh2LeeBMMo24IFv8wCyQ==}
engines: {node: '>= 8.0'}
peerDependencies:
'@types/node': 24.12.4
[email protected]:
resolution: {integrity: sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==}
engines: {node: '>=8.0.0'}
@@ -9525,6 +9540,10 @@ packages:
resolution: {integrity: sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw==}
engines: {bun: '>=1.0.0', deno: '>=2.0.0', node: '>=12.0.0'}
[email protected]:
resolution: {integrity: sha512-4toX5E1fQbBrpfXidaHnF0669nkAdETeIPTs2SUjxxD7RRIs9ICG4gtpmfc68JCEKehsdwLFqBu9VlQqZ1P1gg==}
engines: {bun: '>=1.0.0', deno: '>=2.0.0', node: '>=12.0.0'}
[email protected]:
resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==}
engines: {node: '>=10'}
@@ -11817,6 +11836,13 @@ snapshots:
'@cloudflare/workers-types': 5.20260726.1
effect: 4.0.0-beta.102(patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)
'@effect/[email protected](@types/[email protected])([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))':
dependencies:
effect: 4.0.0-beta.102(patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)
mysql2: 3.23.2(@types/[email protected])
transitivePeerDependencies:
- '@types/node'
'@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))':
dependencies:
effect: 4.0.0-beta.102(patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)
@@ -15371,7 +15397,7 @@ snapshots:
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
[email protected](249551d75ad3792c0b22cd2754b25266):
[email protected](eead4ef14d62793c7a40bd378b7ab471):
dependencies:
'@alchemy.run/node-utils': 0.0.5
'@aws-sdk/credential-providers': 3.1062.0
@@ -15416,7 +15442,7 @@ snapshots:
'@effect/platform-node': 4.0.0-beta.102(patch_hash=cae7efcda6fd29f4db2efd357cb7dc6c41cb6adc957901d437e13ed1f3c017f0)([email protected])([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))([email protected])([email protected])
'@effect/sql-pg': 4.0.0-beta.102([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))
drizzle-kit: 1.0.0-rc.4
drizzle-orm: 1.0.0-rc.4(@cloudflare/[email protected])(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@libsql/[email protected]([email protected])([email protected]))([email protected])([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@types/[email protected]))([email protected])([email protected])
drizzle-orm: 1.0.0-rc.4(6d7372add232cae10a536adca115d034)
vite: '@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])'
ws: 8.21.0([email protected])([email protected])
transitivePeerDependencies:
@@ -16439,17 +16465,18 @@ snapshots:
get-tsconfig: 4.14.0
jiti: 2.7.0
[email protected](@cloudflare/[email protected])(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@effect/[email protected]([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)))(@libsql/[email protected]([email protected])([email protected]))([email protected])([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@types/[email protected]))([email protected])([email protected]):
[email protected](6d7372add232cae10a536adca115d034):
optionalDependencies:
'@cloudflare/workers-types': 4.20260604.1
'@effect/sql-d1': 4.0.0-beta.101([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))
'@effect/sql-mysql2': 4.0.0-beta.102(@types/[email protected])([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))
'@effect/sql-pg': 4.0.0-beta.102([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))
'@effect/sql-sqlite-bun': 4.0.0-beta.102([email protected](patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488))
'@libsql/client': 0.17.3([email protected])([email protected])
bun-types: 1.3.14
effect: 4.0.0-beta.102(patch_hash=71215759e1ac0a7f65d7b75d816986687ae6c3a6cba02d928d184ca71790d488)
expo-sqlite: 56.0.5([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
mysql2: 3.22.4(@types/[email protected])
mysql2: 3.23.2(@types/[email protected])
pg: 8.21.0
zod: 4.4.3
@@ -19123,6 +19150,18 @@ snapshots:
named-placeholders: 1.1.6
sql-escaper: 1.3.3
[email protected](@types/[email protected]):
dependencies:
'@types/node': 24.12.4
aws-ssl-profiles: 1.1.2
denque: 2.1.0
generate-function: 2.3.1
iconv-lite: 0.7.2
long: 5.3.2
lru.min: 1.1.4
named-placeholders: 1.1.6
sql-escaper: 1.5.1
[email protected]:
dependencies:
lru.min: 1.1.4
@@ -20781,6 +20820,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
escape-string-regexp: 2.0.0
+3
View File
@@ -35,6 +35,7 @@ catalog:
"@effect/platform-bun": 4.0.0-beta.102
"@effect/platform-node": 4.0.0-beta.102
"@effect/platform-node-shared": 4.0.0-beta.102
"@effect/sql-mysql2": 4.0.0-beta.102
"@effect/sql-pg": 4.0.0-beta.102
"@effect/sql-sqlite-bun": 4.0.0-beta.102
"@effect/tsgo": 0.13.2
@@ -69,6 +70,7 @@ minimumReleaseAgeExclude:
- "@effect/[email protected]"
- "@effect/[email protected]"
- "@effect/[email protected]"
- "@effect/[email protected]"
- "@effect/[email protected]"
- "@effect/[email protected]"
- "@effect/[email protected]"
@@ -93,6 +95,7 @@ overrides:
"@effect/platform-bun": "catalog:"
"@effect/platform-node": "catalog:"
"@effect/platform-node-shared": "catalog:"
"@effect/sql-mysql2": "catalog:"
"@effect/sql-pg": "catalog:"
"@effect/sql-sqlite-bun": "catalog:"
"@effect/vitest": "catalog:"