Compare commits

...
Author SHA1 Message Date
Cursor Agent 7a848c2ecd fix: merge persisted settings with current snapshot during hydration
Prevent hydrateClientSettings from unconditionally overwriting in-memory
state with stale persisted data. If the snapshot changed while hydration
was in-flight (e.g. user toggled a setting), the persisted values are
now merged underneath the current snapshot, matching the merge strategy
already used in replaceSavedEnvironmentRegistryState.
2026-04-10 03:20:08 +00:00
Julius Marminge af019da240 Merge branch 'main' into t3code/client-persistence-layer 2026-04-09 20:13:13 -07:00
Julius Marminge f751e9d5a1 Format runtime catalog test import 2026-04-09 20:09:38 -07:00
Julius Marminge 45c8899c02 Infer missing client environment URLs from one another
- Allow primary environment config to derive HTTP or WS base URLs when only one is set
- Preserve saved environment records during registry hydration
- Pass VITE_HTTP_URL through dev runner and Vite define
2026-04-09 20:02:26 -07:00
Julius Marminge 184de87e91 Reset client settings persistence in test teardown
- add a test-only reset helper for cached settings state
- clear client settings persistence when resetting the local API
2026-04-09 19:46:46 -07:00
Julius Marminge af1fd868ba Handle saved environment credential persistence failures
- Roll back saved environment metadata when bearer token persistence fails
- Catch local API persistence errors during registry upserts
- Remove legacy local settings migration bootstrap
2026-04-09 19:33:24 -07:00
Julius Marminge 110fc3eca1 Persist saved environments inline with records
- Store bearer tokens on saved environment records in web and desktop
- Preserve secrets when rewriting registry entries
- Add coverage for the new persistence flow
2026-04-09 19:21:41 -07:00
Julius Marminge e56b58c60e Route web persistence through the local API bridge
- Remove the clientPersistence wrapper layer
- Read and write settings and saved environments via ensureLocalApi()
- Refresh persistence tests to cover the new storage and hydration paths
2026-04-09 19:03:32 -07:00
Julius Marminge 1363cc1189 Refactor client persistence through local API
- Move browser storage helpers into a dedicated module
- Route client settings and saved environment persistence through `localApi`
- Update hydration and tests for the new persistence path
2026-04-09 18:56:57 -07:00
Julius Marminge b5ac0b3e2d Consolidate saved environment secret storage
- Store encrypted bearer tokens alongside the saved-environment registry
- Preserve secrets when rewriting registry metadata
- Update desktop IPC paths and coverage
2026-04-09 18:44:23 -07:00
Julius Marminge f51a46b46b Preserve persisted settings and secrets on hydration failures
- Keep existing secrets when encryption is unavailable
- Treat malformed secrets files as empty instead of crashing
- Fix client settings hydration state resets for repeated loads
2026-04-09 18:36:02 -07:00
Julius Marminge 5331bd2f45 Persist client settings and saved environment secrets
- Add desktop IPC-backed persistence for client settings
- Migrate browser-stored environments and tokens to desktop storage
- Keep web settings/runtime code on the shared persistence layer
2026-04-09 18:13:23 -07:00
25 changed files with 1673 additions and 277 deletions

No files matched your search

+234
View File
@@ -0,0 +1,234 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
EnvironmentId,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import {
readClientSettings,
readSavedEnvironmentRegistry,
readSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
type DesktopSecretStorage,
} from "./clientPersistence";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
});
function makeTempPath(fileName: string): string {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
tempDirectories.push(directory);
return path.join(directory, fileName);
}
function makeSecretStorage(available: boolean): DesktopSecretStorage {
return {
isEncryptionAvailable: () => available,
encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
decryptString: (value) => {
const decoded = value.toString("utf8");
if (!decoded.startsWith("enc:")) {
throw new Error("invalid secret");
}
return decoded.slice("enc:".length);
},
};
}
const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
};
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
};
describe("clientPersistence", () => {
it("persists and reloads client settings", () => {
const settingsPath = makeTempPath("client-settings.json");
writeClientSettings(settingsPath, clientSettings);
expect(readClientSettings(settingsPath)).toEqual(clientSettings);
});
it("persists and reloads saved environment metadata", () => {
const registryPath = makeTempPath("saved-environments.json");
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
});
it("persists encrypted saved environment secrets when encryption is available", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
}),
).toBe(true);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
records: [
{
...savedRegistryRecord,
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
},
],
});
});
it("preserves existing secrets when encryption is unavailable", () => {
const registryPath = makeTempPath("saved-environments.json");
const availableSecretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: availableSecretStorage,
});
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "next-token",
secretStorage: makeSecretStorage(false),
}),
).toBe(false);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: availableSecretStorage,
}),
).toBe("bearer-token");
});
it("removes saved environment secrets", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
removeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
});
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBeNull();
});
it("treats malformed secrets documents as empty", () => {
const registryPath = makeTempPath("saved-environments.json");
fs.writeFileSync(registryPath, "{}\n", "utf8");
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: makeSecretStorage(true),
}),
).toBeNull();
expect(() =>
removeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
}),
).not.toThrow();
});
it("returns false when writing a secret without metadata", () => {
const registryPath = makeTempPath("saved-environments.json");
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: makeSecretStorage(true),
}),
).toBe(false);
});
it("preserves encrypted secrets when metadata is rewritten", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
});
});
+216
View File
@@ -0,0 +1,216 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { Predicate } from "effect";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
}
interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
readonly encryptedBearerToken?: string;
}
interface SavedEnvironmentRegistryDocument {
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
}
export interface DesktopSecretStorage {
readonly isEncryptionAvailable: () => boolean;
readonly encryptString: (value: string) => Buffer;
readonly decryptString: (value: Buffer) => string;
}
function readJsonFile<T>(filePath: string): T | null {
try {
if (!FS.existsSync(filePath)) {
return null;
}
return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
} catch {
return null;
}
}
function writeJsonFile(filePath: string, value: unknown): void {
const directory = Path.dirname(filePath);
const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
FS.mkdirSync(directory, { recursive: true });
FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
FS.renameSync(tempPath, filePath);
}
function isPersistedSavedEnvironmentStorageRecord(
value: unknown,
): value is PersistedSavedEnvironmentStorageRecord {
return (
Predicate.isObject(value) &&
typeof value.environmentId === "string" &&
typeof value.label === "string" &&
typeof value.httpBaseUrl === "string" &&
typeof value.wsBaseUrl === "string" &&
typeof value.createdAt === "string" &&
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
);
}
function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
if (!Predicate.isObject(parsed)) {
return { records: [] };
}
return {
records: Array.isArray(parsed.records)
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
: [],
};
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
}
export function readSavedEnvironmentRegistry(
registryPath: string,
): readonly PersistedSavedEnvironmentRecord[] {
return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
toPersistedSavedEnvironmentRecord(record),
);
}
export function writeSavedEnvironmentRegistry(
registryPath: string,
records: readonly PersistedSavedEnvironmentRecord[],
): void {
const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
const encryptedBearerTokenById = new Map(
currentDocument.records.flatMap((record) =>
record.encryptedBearerToken
? [[record.environmentId, record.encryptedBearerToken] as const]
: [],
),
);
writeJsonFile(registryPath, {
records: records.map((record) => {
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
return encryptedBearerToken
? {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
}
: record;
}),
} satisfies SavedEnvironmentRegistryDocument);
}
export function readSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
readonly secretStorage: DesktopSecretStorage;
}): string | null {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
const encoded = document.records.find(
(record) => record.environmentId === input.environmentId,
)?.encryptedBearerToken;
if (!encoded) {
return null;
}
if (!input.secretStorage.isEncryptionAvailable()) {
return null;
}
try {
return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
} catch {
return null;
}
}
export function writeSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
readonly secret: string;
readonly secretStorage: DesktopSecretStorage;
}): boolean {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
if (!input.secretStorage.isEncryptionAvailable()) {
return false;
}
let found = false;
writeJsonFile(input.registryPath, {
records: document.records.map((record) => {
if (record.environmentId !== input.environmentId) {
return record;
}
found = true;
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
} satisfies PersistedSavedEnvironmentStorageRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
}
export function removeSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
}): void {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
if (
!document.records.some(
(record) =>
record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
)
) {
return;
}
writeJsonFile(input.registryPath, {
records: document.records.map((record) => {
if (record.environmentId !== input.environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
} satisfies SavedEnvironmentRegistryDocument);
}
+109
View File
@@ -14,14 +14,17 @@ import {
nativeImage,
nativeTheme,
protocol,
safeStorage,
shell,
} from "electron";
import type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect";
import type {
ClientSettings,
DesktopTheme,
DesktopServerExposureMode,
DesktopServerExposureState,
PersistedSavedEnvironmentRecord,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
DesktopUpdateState,
@@ -38,6 +41,15 @@ import {
setDesktopServerExposurePreference,
writeDesktopSettings,
} from "./desktopSettings";
import {
readClientSettings,
readSavedEnvironmentRegistry,
readSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
} from "./clientPersistence";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { resolveDesktopServerExposure } from "./serverExposure";
@@ -71,11 +83,20 @@ const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -204,6 +225,14 @@ function getDesktopServerExposureState(): DesktopServerExposureState {
};
}
function getDesktopSecretStorage() {
return {
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
encryptString: (value: string) => safeStorage.encryptString(value),
decryptString: (value: Buffer) => safeStorage.decryptString(value),
} as const;
}
function resolveAdvertisedHostOverride(): string | undefined {
const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim();
return override && override.length > 0 ? override : undefined;
@@ -1349,6 +1378,86 @@ function registerIpcHandlers(): void {
} as const;
});
ipcMain.removeHandler(GET_CLIENT_SETTINGS_CHANNEL);
ipcMain.handle(GET_CLIENT_SETTINGS_CHANNEL, async () => readClientSettings(CLIENT_SETTINGS_PATH));
ipcMain.removeHandler(SET_CLIENT_SETTINGS_CHANNEL);
ipcMain.handle(SET_CLIENT_SETTINGS_CHANNEL, async (_event, rawSettings: unknown) => {
if (typeof rawSettings !== "object" || rawSettings === null) {
throw new Error("Invalid client settings payload.");
}
writeClientSettings(CLIENT_SETTINGS_PATH, rawSettings as ClientSettings);
});
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
ipcMain.handle(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async () =>
readSavedEnvironmentRegistry(SAVED_ENVIRONMENT_REGISTRY_PATH),
);
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
ipcMain.handle(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async (_event, rawRecords: unknown) => {
if (!Array.isArray(rawRecords)) {
throw new Error("Invalid saved environment registry payload.");
}
writeSavedEnvironmentRegistry(
SAVED_ENVIRONMENT_REGISTRY_PATH,
rawRecords as readonly PersistedSavedEnvironmentRecord[],
);
});
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
ipcMain.handle(
GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
async (_event, rawEnvironmentId: unknown) => {
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
return null;
}
return readSavedEnvironmentSecret({
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
environmentId: rawEnvironmentId,
secretStorage: getDesktopSecretStorage(),
});
},
);
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
ipcMain.handle(
SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
async (_event, rawEnvironmentId: unknown, rawSecret: unknown) => {
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
throw new Error("Invalid saved environment id.");
}
if (typeof rawSecret !== "string" || rawSecret.trim().length === 0) {
throw new Error("Invalid saved environment secret.");
}
return writeSavedEnvironmentSecret({
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
environmentId: rawEnvironmentId,
secret: rawSecret,
secretStorage: getDesktopSecretStorage(),
});
},
);
ipcMain.removeHandler(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL);
ipcMain.handle(
REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
async (_event, rawEnvironmentId: unknown) => {
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
return;
}
removeSavedEnvironmentSecret({
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
environmentId: rawEnvironmentId,
});
},
);
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
+18
View File
@@ -13,6 +13,13 @@ const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
@@ -24,6 +31,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getClientSettings: () => ipcRenderer.invoke(GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) => ipcRenderer.invoke(SET_CLIENT_SETTINGS_CHANNEL, settings),
getSavedEnvironmentRegistry: () => ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
@@ -0,0 +1,80 @@
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
const testEnvironmentId = EnvironmentId.makeUnsafe("environment-1");
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: testEnvironmentId,
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
};
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => {
store.clear();
},
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
};
}
function getTestWindow(): Window & typeof globalThis {
const localStorage = createLocalStorageStub();
const testWindow = {
localStorage,
} as Window & typeof globalThis;
vi.stubGlobal("window", testWindow);
vi.stubGlobal("localStorage", localStorage);
return testWindow;
}
afterEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("clientPersistenceStorage", () => {
it("stores browser secrets inline with the saved environment record", async () => {
const testWindow = getTestWindow();
const {
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
readBrowserSavedEnvironmentRegistry,
readBrowserSavedEnvironmentSecret,
writeBrowserSavedEnvironmentRegistry,
writeBrowserSavedEnvironmentSecret,
} = await import("./clientPersistenceStorage");
writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]);
expect(writeBrowserSavedEnvironmentSecret(testEnvironmentId, "bearer-token")).toBe(true);
writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]);
expect(readBrowserSavedEnvironmentRegistry()).toEqual([savedRegistryRecord]);
expect(readBrowserSavedEnvironmentSecret(testEnvironmentId)).toBe("bearer-token");
expect(
JSON.parse(testWindow.localStorage.getItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY)!),
).toEqual({
version: 1,
records: [
{
...savedRegistryRecord,
bearerToken: "bearer-token",
},
],
});
});
});
+194
View File
@@ -0,0 +1,194 @@
import {
ClientSettingsSchema,
EnvironmentId,
type ClientSettings,
type EnvironmentId as EnvironmentIdValue,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
environmentId: EnvironmentId,
label: Schema.String,
httpBaseUrl: Schema.String,
wsBaseUrl: Schema.String,
createdAt: Schema.String,
lastConnectedAt: Schema.NullOr(Schema.String),
bearerToken: Schema.optionalKey(Schema.String),
});
type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type;
const BrowserSavedEnvironmentRegistryDocumentSchema = Schema.Struct({
version: Schema.optionalKey(Schema.Number),
records: Schema.optionalKey(Schema.Array(BrowserSavedEnvironmentRecordSchema)),
});
type BrowserSavedEnvironmentRegistryDocument =
typeof BrowserSavedEnvironmentRegistryDocumentSchema.Type;
function hasWindow(): boolean {
return typeof window !== "undefined";
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
}
export function readBrowserClientSettings(): ClientSettings | null {
if (!hasWindow()) {
return null;
}
try {
return getLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, ClientSettingsSchema);
} catch {
return null;
}
}
export function writeBrowserClientSettings(settings: ClientSettings): void {
if (!hasWindow()) {
return;
}
setLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, settings, ClientSettingsSchema);
}
function readBrowserSavedEnvironmentRegistryDocument(): BrowserSavedEnvironmentRegistryDocument {
if (!hasWindow()) {
return {};
}
try {
const parsed = getLocalStorageItem(
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
BrowserSavedEnvironmentRegistryDocumentSchema,
);
return parsed ?? {};
} catch {
return {};
}
}
function writeBrowserSavedEnvironmentRegistryDocument(
document: BrowserSavedEnvironmentRegistryDocument,
): void {
if (!hasWindow()) {
return;
}
setLocalStorageItem(
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
document,
BrowserSavedEnvironmentRegistryDocumentSchema,
);
}
function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray<BrowserSavedEnvironmentRecord> {
return readBrowserSavedEnvironmentRegistryDocument().records ?? [];
}
function writeBrowserSavedEnvironmentRecords(
records: ReadonlyArray<BrowserSavedEnvironmentRecord>,
): void {
writeBrowserSavedEnvironmentRegistryDocument({
version: 1,
records,
});
}
export function readBrowserSavedEnvironmentRegistry(): ReadonlyArray<PersistedSavedEnvironmentRecord> {
return readBrowserSavedEnvironmentRecordsWithSecrets().map((record) =>
toPersistedSavedEnvironmentRecord(record),
);
}
export function writeBrowserSavedEnvironmentRegistry(
records: ReadonlyArray<PersistedSavedEnvironmentRecord>,
): void {
const existing = new Map(
readBrowserSavedEnvironmentRecordsWithSecrets().map(
(record) => [record.environmentId, record] as const,
),
);
writeBrowserSavedEnvironmentRecords(
records.map((record) => {
const bearerToken = existing.get(record.environmentId)?.bearerToken;
return bearerToken
? {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
bearerToken,
}
: toPersistedSavedEnvironmentRecord(record);
}),
);
}
export function readBrowserSavedEnvironmentSecret(
environmentId: EnvironmentIdValue,
): string | null {
return (
readBrowserSavedEnvironmentRecordsWithSecrets().find(
(record) => record.environmentId === environmentId,
)?.bearerToken ?? null
);
}
export function writeBrowserSavedEnvironmentSecret(
environmentId: EnvironmentIdValue,
secret: string,
): boolean {
const document = readBrowserSavedEnvironmentRegistryDocument();
const records = document.records ?? [];
let found = false;
writeBrowserSavedEnvironmentRegistryDocument({
version: document.version ?? 1,
records: records.map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
found = true;
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
bearerToken: secret,
} satisfies BrowserSavedEnvironmentRecord;
}),
});
return found;
}
export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentIdValue): void {
const document = readBrowserSavedEnvironmentRegistryDocument();
writeBrowserSavedEnvironmentRegistryDocument({
version: document.version ?? 1,
records: (document.records ?? []).map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
});
}
@@ -17,6 +17,9 @@ vi.mock("../editorPreferences", () => ({
}));
vi.mock("../localApi", () => ({
ensureLocalApi: vi.fn(() => {
throw new Error("ensureLocalApi not implemented in browser test");
}),
readLocalApi: readLocalApiMock,
}));
@@ -126,6 +126,9 @@ vi.mock("~/lib/gitStatusState", () => ({
}));
vi.mock("~/localApi", () => ({
ensureLocalApi: vi.fn(() => {
throw new Error("ensureLocalApi not implemented in browser test");
}),
readLocalApi: vi.fn(() => null),
}));
@@ -113,6 +113,9 @@ vi.mock("~/environmentApi", () => ({
}));
vi.mock("~/localApi", () => ({
ensureLocalApi: vi.fn(() => {
throw new Error("ensureLocalApi not implemented in browser test");
}),
readLocalApi: readLocalApiMock,
}));
@@ -282,6 +282,13 @@ const createDesktopBridgeStub = (overrides?: {
wsBaseUrl: "ws://127.0.0.1:3773",
bootstrapToken: "desktop-bootstrap-token",
}),
getClientSettings: vi.fn().mockResolvedValue(null),
setClientSettings: vi.fn().mockResolvedValue(undefined),
getSavedEnvironmentRegistry: vi.fn().mockResolvedValue([]),
setSavedEnvironmentRegistry: vi.fn().mockResolvedValue(undefined),
getSavedEnvironmentSecret: vi.fn().mockResolvedValue(null),
setSavedEnvironmentSecret: vi.fn().mockResolvedValue(true),
removeSavedEnvironmentSecret: vi.fn().mockResolvedValue(undefined),
getServerExposureState: vi.fn().mockResolvedValue(
overrides?.serverExposureState ?? {
mode: "local-only",
@@ -110,6 +110,32 @@ describe("environmentBootstrap", () => {
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
});
it("derives the websocket url when only VITE_HTTP_URL is configured", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
expect(getPrimaryKnownEnvironment()?.target).toEqual({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
});
});
it("derives the http url when only VITE_WS_URL is configured", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
expect(getPrimaryKnownEnvironment()?.target).toEqual({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
});
});
it("uses the current origin as the descriptor base for local dev environments", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
+23 -7
View File
@@ -16,6 +16,15 @@ function normalizeBaseUrl(rawValue: string): string {
return new URL(rawValue, window.location.origin).toString();
}
function swapBaseUrlProtocol(
rawValue: string,
nextProtocol: "http:" | "https:" | "ws:" | "wss:",
): string {
const url = new URL(normalizeBaseUrl(rawValue));
url.protocol = nextProtocol;
return url.toString();
}
function normalizeHostname(hostname: string): string {
return hostname
.trim()
@@ -54,22 +63,29 @@ function resolveHttpRequestBaseUrl(httpBaseUrl: string): string {
}
function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null {
const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim();
const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim();
const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim() || undefined;
const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim() || undefined;
if (!configuredHttpBaseUrl && !configuredWsBaseUrl) {
return null;
}
if (!configuredHttpBaseUrl || !configuredWsBaseUrl) {
throw new Error("Configured primary environments require both VITE_HTTP_URL and VITE_WS_URL.");
}
const resolvedHttpBaseUrl =
configuredHttpBaseUrl ??
(configuredWsBaseUrl?.startsWith("wss:")
? swapBaseUrlProtocol(configuredWsBaseUrl, "https:")
: swapBaseUrlProtocol(configuredWsBaseUrl!, "http:"));
const resolvedWsBaseUrl =
configuredWsBaseUrl ??
(configuredHttpBaseUrl?.startsWith("https:")
? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:")
: swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:"));
return {
source: "configured",
target: {
httpBaseUrl: normalizeBaseUrl(configuredHttpBaseUrl),
wsBaseUrl: normalizeBaseUrl(configuredWsBaseUrl),
httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl),
wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl),
},
};
}
@@ -1,17 +1,43 @@
import { EnvironmentId } from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import {
EnvironmentId,
type LocalApi,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
resetSavedEnvironmentRegistryStoreForTests,
resetSavedEnvironmentRuntimeStoreForTests,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
waitForSavedEnvironmentRegistryHydration,
} from "./catalog";
describe("environment runtime catalog stores", () => {
afterEach(() => {
beforeEach(async () => {
vi.stubGlobal("window", {
nativeApi: {
persistence: {
getClientSettings: async () => null,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: async () => [],
setSavedEnvironmentRegistry: async () => undefined,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
},
} satisfies Pick<LocalApi, "persistence">,
});
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
});
afterEach(async () => {
resetSavedEnvironmentRegistryStoreForTests();
resetSavedEnvironmentRuntimeStoreForTests();
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
vi.unstubAllGlobals();
});
it("resets the saved environment registry store state", () => {
@@ -22,7 +48,6 @@ describe("environment runtime catalog stores", () => {
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
bearerToken: "token",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
});
@@ -48,4 +73,69 @@ describe("environment runtime catalog stores", () => {
expect(useSavedEnvironmentRuntimeStore.getState().byId).toEqual({});
});
it("does not throw when local api lookup fails during registry persistence", async () => {
vi.unstubAllGlobals();
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
expect(() =>
useSavedEnvironmentRegistryStore.getState().upsert({
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
}),
).not.toThrow();
expect(errorSpy).toHaveBeenCalledWith("[SAVED_ENVIRONMENTS] persist failed", expect.any(Error));
});
it("does not let stale hydration overwrite records added while hydration is in flight", async () => {
let resolveRegistryRead: () => void = () => {
throw new Error("Registry read resolver was not initialized.");
};
vi.stubGlobal("window", {
nativeApi: {
persistence: {
getClientSettings: async () => null,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: () =>
new Promise<readonly PersistedSavedEnvironmentRecord[]>((resolve) => {
resolveRegistryRead = () => resolve([]);
}),
setSavedEnvironmentRegistry: async () => undefined,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
},
} satisfies Pick<LocalApi, "persistence">,
});
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
const hydrationPromise = waitForSavedEnvironmentRegistryHydration();
const environmentId = EnvironmentId.makeUnsafe("environment-1");
const record = {
environmentId,
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
} as const;
useSavedEnvironmentRegistryStore.getState().upsert(record);
resolveRegistryRead();
await hydrationPromise;
expect(useSavedEnvironmentRegistryStore.getState().byId[environmentId]).toEqual(record);
});
});
+158 -68
View File
@@ -3,22 +3,19 @@ import type {
AuthSessionRole,
EnvironmentId,
ExecutionEnvironmentDescriptor,
PersistedSavedEnvironmentRecord,
ServerConfig,
} from "@t3tools/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "../../lib/storage";
import { ensureLocalApi } from "../../localApi";
import { getPrimaryKnownEnvironment } from "../primary";
const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
export interface SavedEnvironmentRecord {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly wsBaseUrl: string;
readonly httpBaseUrl: string;
readonly bearerToken: string;
readonly createdAt: string;
readonly lastConnectedAt: string | null;
}
@@ -34,62 +31,133 @@ interface SavedEnvironmentRegistryStore extends SavedEnvironmentRegistryState {
readonly reset: () => void;
}
function createSavedEnvironmentRegistryStorage() {
return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined);
let savedEnvironmentRegistryHydrated = false;
let savedEnvironmentRegistryHydrationPromise: Promise<void> | null = null;
function toPersistedSavedEnvironmentRecord(
record: SavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
}
export const useSavedEnvironmentRegistryStore = create<SavedEnvironmentRegistryStore>()(
persist(
(set) => ({
byId: {},
upsert: (record) =>
set((state) => ({
byId: {
...state.byId,
[record.environmentId]: record,
},
})),
remove: (environmentId) =>
set((state) => {
const { [environmentId]: _removed, ...remaining } = state.byId;
return {
byId: remaining,
};
}),
markConnected: (environmentId, connectedAt) =>
set((state) => {
const existing = state.byId[environmentId];
if (!existing) {
return state;
}
return {
byId: {
...state.byId,
[environmentId]: {
...existing,
lastConnectedAt: connectedAt,
},
},
};
}),
reset: () =>
set({
byId: {},
}),
}),
{
name: SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
version: 1,
storage: createJSONStorage(createSavedEnvironmentRegistryStorage),
partialize: (state) => ({
byId: state.byId,
}),
function valuesOfSavedEnvironmentRegistry(
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
): ReadonlyArray<SavedEnvironmentRecord> {
return Object.values(byId) as ReadonlyArray<SavedEnvironmentRecord>;
}
function persistSavedEnvironmentRegistryState(
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
): void {
try {
void ensureLocalApi()
.persistence.setSavedEnvironmentRegistry(
valuesOfSavedEnvironmentRegistry(byId).map((record) =>
toPersistedSavedEnvironmentRecord(record),
),
)
.catch((error) => {
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
});
} catch (error) {
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
}
}
function replaceSavedEnvironmentRegistryState(
records: ReadonlyArray<SavedEnvironmentRecord>,
): void {
const currentById = useSavedEnvironmentRegistryStore.getState().byId;
const hydratedById = Object.fromEntries(records.map((record) => [record.environmentId, record]));
useSavedEnvironmentRegistryStore.setState({
byId: {
...hydratedById,
...currentById,
},
),
);
});
}
async function hydrateSavedEnvironmentRegistry(): Promise<void> {
if (savedEnvironmentRegistryHydrated) {
return;
}
if (savedEnvironmentRegistryHydrationPromise) {
return savedEnvironmentRegistryHydrationPromise;
}
const nextHydration = (async () => {
try {
const persistedRecords = await ensureLocalApi().persistence.getSavedEnvironmentRegistry();
replaceSavedEnvironmentRegistryState(persistedRecords);
} catch (error) {
console.error("[SAVED_ENVIRONMENTS] hydrate failed", error);
} finally {
savedEnvironmentRegistryHydrated = true;
}
})();
const hydrationPromise = nextHydration.finally(() => {
if (savedEnvironmentRegistryHydrationPromise === hydrationPromise) {
savedEnvironmentRegistryHydrationPromise = null;
}
});
savedEnvironmentRegistryHydrationPromise = hydrationPromise;
return savedEnvironmentRegistryHydrationPromise;
}
export const useSavedEnvironmentRegistryStore = create<SavedEnvironmentRegistryStore>()((set) => ({
byId: {},
upsert: (record) =>
set((state) => {
const byId = {
...state.byId,
[record.environmentId]: record,
};
persistSavedEnvironmentRegistryState(byId);
return { byId };
}),
remove: (environmentId) =>
set((state) => {
const { [environmentId]: _removed, ...remaining } = state.byId;
persistSavedEnvironmentRegistryState(remaining);
return {
byId: remaining,
};
}),
markConnected: (environmentId, connectedAt) =>
set((state) => {
const existing = state.byId[environmentId];
if (!existing) {
return state;
}
const byId = {
...state.byId,
[environmentId]: {
...existing,
lastConnectedAt: connectedAt,
},
};
persistSavedEnvironmentRegistryState(byId);
return { byId };
}),
reset: () => {
persistSavedEnvironmentRegistryState({});
set({
byId: {},
});
},
}));
export function hasSavedEnvironmentRegistryHydrated(): boolean {
return useSavedEnvironmentRegistryStore.persist.hasHydrated();
return savedEnvironmentRegistryHydrated;
}
export function waitForSavedEnvironmentRegistryHydration(): Promise<void> {
@@ -97,17 +165,7 @@ export function waitForSavedEnvironmentRegistryHydration(): Promise<void> {
return Promise.resolve();
}
return new Promise((resolve) => {
const unsubscribe = useSavedEnvironmentRegistryStore.persist.onFinishHydration(() => {
unsubscribe();
resolve();
});
if (hasSavedEnvironmentRegistryHydrated()) {
unsubscribe();
resolve();
}
});
return hydrateSavedEnvironmentRegistry();
}
export function listSavedEnvironmentRecords(): ReadonlyArray<SavedEnvironmentRecord> {
@@ -150,7 +208,39 @@ export function resolveEnvironmentHttpUrl(input: {
}
export function resetSavedEnvironmentRegistryStoreForTests() {
useSavedEnvironmentRegistryStore.getState().reset();
savedEnvironmentRegistryHydrated = false;
savedEnvironmentRegistryHydrationPromise = null;
useSavedEnvironmentRegistryStore.setState({ byId: {} });
}
export async function persistSavedEnvironmentRecord(record: SavedEnvironmentRecord): Promise<void> {
const byId = {
...useSavedEnvironmentRegistryStore.getState().byId,
[record.environmentId]: record,
};
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
valuesOfSavedEnvironmentRegistry(byId).map((entry) => toPersistedSavedEnvironmentRecord(entry)),
);
}
export async function readSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
): Promise<string | null> {
return ensureLocalApi().persistence.getSavedEnvironmentSecret(environmentId);
}
export async function writeSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
bearerToken: string,
): Promise<boolean> {
return ensureLocalApi().persistence.setSavedEnvironmentSecret(environmentId, bearerToken);
}
export async function removeSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
): Promise<void> {
await ensureLocalApi().persistence.removeSavedEnvironmentSecret(environmentId);
}
export type SavedEnvironmentConnectionState = "connecting" | "connected" | "disconnected" | "error";
@@ -0,0 +1,105 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mockResolveRemotePairingTarget = vi.fn();
const mockFetchRemoteEnvironmentDescriptor = vi.fn();
const mockBootstrapRemoteBearerSession = vi.fn();
const mockPersistSavedEnvironmentRecord = vi.fn();
const mockWriteSavedEnvironmentBearerToken = vi.fn();
const mockSetSavedEnvironmentRegistry = vi.fn();
const mockUpsert = vi.fn();
const mockListSavedEnvironmentRecords = vi.fn();
vi.mock("../remote/target", () => ({
resolveRemotePairingTarget: mockResolveRemotePairingTarget,
}));
vi.mock("../remote/api", () => ({
bootstrapRemoteBearerSession: mockBootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState: vi.fn(),
resolveRemoteWebSocketConnectionUrl: vi.fn(),
}));
vi.mock("~/localApi", () => ({
ensureLocalApi: () => ({
persistence: {
setSavedEnvironmentRegistry: mockSetSavedEnvironmentRegistry,
},
}),
}));
vi.mock("./catalog", () => ({
getSavedEnvironmentRecord: vi.fn(),
hasSavedEnvironmentRegistryHydrated: vi.fn(),
listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
persistSavedEnvironmentRecord: mockPersistSavedEnvironmentRecord,
readSavedEnvironmentBearerToken: vi.fn(),
removeSavedEnvironmentBearerToken: vi.fn(),
useSavedEnvironmentRegistryStore: {
getState: () => ({
upsert: mockUpsert,
remove: vi.fn(),
markConnected: vi.fn(),
}),
},
useSavedEnvironmentRuntimeStore: {
getState: () => ({
ensure: vi.fn(),
patch: vi.fn(),
clear: vi.fn(),
}),
},
waitForSavedEnvironmentRegistryHydration: vi.fn(),
writeSavedEnvironmentBearerToken: mockWriteSavedEnvironmentBearerToken,
}));
vi.mock("./connection", () => ({
createEnvironmentConnection: vi.fn(),
}));
describe("addSavedEnvironment", () => {
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
mockResolveRemotePairingTarget.mockReturnValue({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
credential: "pairing-code",
});
mockFetchRemoteEnvironmentDescriptor.mockResolvedValue({
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
});
mockBootstrapRemoteBearerSession.mockResolvedValue({
sessionToken: "bearer-token",
role: "owner",
});
mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined);
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
mockSetSavedEnvironmentRegistry.mockResolvedValue(undefined);
mockListSavedEnvironmentRecords.mockReturnValue([]);
});
it("rolls back persisted metadata when bearer token persistence fails", async () => {
const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
await expect(
addSavedEnvironment({
label: "Remote environment",
host: "remote.example.com",
pairingCode: "123456",
}),
).rejects.toThrow("Unable to persist saved environment credentials.");
expect(mockPersistSavedEnvironmentRecord).toHaveBeenCalledTimes(1);
expect(mockWriteSavedEnvironmentBearerToken).toHaveBeenCalledWith(
EnvironmentId.makeUnsafe("environment-1"),
"bearer-token",
);
expect(mockSetSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
expect(mockUpsert).not.toHaveBeenCalled();
await resetEnvironmentServiceForTests();
});
});
+49 -6
View File
@@ -23,6 +23,7 @@ import {
markPromotedDraftThreadsByRef,
useComposerDraftStore,
} from "~/composerDraftStore";
import { ensureLocalApi } from "~/localApi";
import { collectActiveTerminalThreadIds } from "~/lib/terminalStateCleanup";
import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects";
import { projectQueryKeys } from "~/lib/projectReactQuery";
@@ -39,10 +40,14 @@ import {
getSavedEnvironmentRecord,
hasSavedEnvironmentRegistryHydrated,
listSavedEnvironmentRecords,
persistSavedEnvironmentRecord,
readSavedEnvironmentBearerToken,
removeSavedEnvironmentBearerToken,
type SavedEnvironmentRecord,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
waitForSavedEnvironmentRegistryHydration,
writeSavedEnvironmentBearerToken,
} from "./catalog";
import { createEnvironmentConnection, type EnvironmentConnection } from "./connection";
import {
@@ -306,7 +311,10 @@ function createPrimaryEnvironmentClient(
return createWsRpcClient(new WsTransport(wsBaseUrl));
}
function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClient {
function createSavedEnvironmentClient(
record: SavedEnvironmentRecord,
bearerToken: string,
): WsRpcClient {
useSavedEnvironmentRuntimeStore.getState().ensure(record.environmentId);
return createWsRpcClient(
@@ -315,7 +323,7 @@ function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClie
resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken: record.bearerToken,
bearerToken,
}),
{
onAttempt: () => {
@@ -341,6 +349,7 @@ function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClie
async function refreshSavedEnvironmentMetadata(
record: SavedEnvironmentRecord,
bearerToken: string,
client: WsRpcClient,
roleHint?: AuthSessionRole | null,
configHint?: ServerConfig | null,
@@ -349,7 +358,7 @@ async function refreshSavedEnvironmentMetadata(
configHint ? Promise.resolve(configHint) : client.server.getConfig(),
fetchRemoteSessionState({
httpBaseUrl: record.httpBaseUrl,
bearerToken: record.bearerToken,
bearerToken,
}),
]);
@@ -408,6 +417,7 @@ async function ensureSavedEnvironmentConnection(
record: SavedEnvironmentRecord,
options?: {
readonly client?: WsRpcClient;
readonly bearerToken?: string;
readonly role?: AuthSessionRole | null;
readonly serverConfig?: ServerConfig | null;
},
@@ -417,7 +427,20 @@ async function ensureSavedEnvironmentConnection(
return existing;
}
const client = options?.client ?? createSavedEnvironmentClient(record);
const bearerToken =
options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId));
if (!bearerToken) {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
authState: "requires-auth",
role: null,
connectionState: "disconnected",
lastError: "Saved environment is missing its saved credential. Pair it again.",
lastErrorAt: isoNow(),
});
throw new Error("Saved environment is missing its saved credential.");
}
const client = options?.client ?? createSavedEnvironmentClient(record, bearerToken);
const knownEnvironment = createKnownEnvironment({
id: record.environmentId,
label: record.label,
@@ -435,7 +458,7 @@ async function ensureSavedEnvironmentConnection(
},
client,
refreshMetadata: async () => {
await refreshSavedEnvironmentMetadata(record, client);
await refreshSavedEnvironmentMetadata(record, bearerToken, client);
},
onConfigSnapshot: (config) => {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
@@ -456,6 +479,7 @@ async function ensureSavedEnvironmentConnection(
try {
await refreshSavedEnvironmentMetadata(
record,
bearerToken,
client,
options?.role ?? null,
options?.serverConfig ?? null,
@@ -552,6 +576,7 @@ export async function reconnectSavedEnvironment(environmentId: EnvironmentId): P
export async function removeSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
useSavedEnvironmentRegistryStore.getState().remove(environmentId);
await removeSavedEnvironmentBearerToken(environmentId);
await disconnectSavedEnvironment(environmentId);
}
@@ -585,12 +610,30 @@ export async function addSavedEnvironment(input: {
label: input.label.trim() || descriptor.label,
wsBaseUrl: resolvedTarget.wsBaseUrl,
httpBaseUrl: resolvedTarget.httpBaseUrl,
bearerToken: bearerSession.sessionToken,
createdAt: isoNow(),
lastConnectedAt: isoNow(),
};
await persistSavedEnvironmentRecord(record);
const didPersistBearerToken = await writeSavedEnvironmentBearerToken(
environmentId,
bearerSession.sessionToken,
);
if (!didPersistBearerToken) {
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
listSavedEnvironmentRecords().map((entry) => ({
environmentId: entry.environmentId,
label: entry.label,
httpBaseUrl: entry.httpBaseUrl,
wsBaseUrl: entry.wsBaseUrl,
createdAt: entry.createdAt,
lastConnectedAt: entry.lastConnectedAt,
})),
);
throw new Error("Unable to persist saved environment credentials.");
}
await ensureSavedEnvironmentConnection(record, {
bearerToken: bearerSession.sessionToken,
role: bearerSession.role,
});
useSavedEnvironmentRegistryStore.getState().upsert(record);
-16
View File
@@ -1,16 +0,0 @@
import { describe, expect, it } from "vitest";
import { buildLegacyClientSettingsMigrationPatch } from "./useSettings";
describe("buildLegacyClientSettingsMigrationPatch", () => {
it("migrates archive confirmation from legacy local settings", () => {
expect(
buildLegacyClientSettingsMigrationPatch({
confirmThreadArchive: true,
confirmThreadDelete: false,
}),
).toEqual({
confirmThreadArchive: true,
confirmThreadDelete: false,
});
});
});
+104 -172
View File
@@ -9,33 +9,94 @@
* write. The hook transparently routes reads/writes to the correct backing
* store.
*/
import { useCallback, useMemo } from "react";
import {
ServerSettings,
ServerSettingsPatch,
ModelSelection,
ThreadEnvMode,
} from "@t3tools/contracts";
import { useCallback, useMemo, useSyncExternalStore } from "react";
import { ServerSettings, ServerSettingsPatch } from "@t3tools/contracts";
import {
type ClientSettings,
ClientSettingsSchema,
DEFAULT_CLIENT_SETTINGS,
DEFAULT_UNIFIED_SETTINGS,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
TimestampFormat,
UnifiedSettings,
} from "@t3tools/contracts/settings";
import { ensureLocalApi } from "~/localApi";
import { useLocalStorage } from "./useLocalStorage";
import { normalizeCustomModelSlugs } from "~/modelSelection";
import { Predicate, Schema, Struct } from "effect";
import { DeepMutable } from "effect/Types";
import { Struct } from "effect";
import { deepMerge } from "@t3tools/shared/Struct";
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
const clientSettingsListeners = new Set<() => void>();
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
let clientSettingsHydrated = false;
let clientSettingsHydrationPromise: Promise<void> | null = null;
function emitClientSettingsChange() {
for (const listener of clientSettingsListeners) {
listener();
}
}
function getClientSettingsSnapshot(): ClientSettings {
return clientSettingsSnapshot;
}
function replaceClientSettingsSnapshot(settings: ClientSettings): void {
clientSettingsSnapshot = settings;
emitClientSettingsChange();
}
function subscribeClientSettings(listener: () => void): () => void {
clientSettingsListeners.add(listener);
void hydrateClientSettings();
return () => {
clientSettingsListeners.delete(listener);
};
}
async function hydrateClientSettings(): Promise<void> {
if (clientSettingsHydrated) {
return;
}
if (clientSettingsHydrationPromise) {
return clientSettingsHydrationPromise;
}
const nextHydration = (async () => {
const snapshotBeforeHydration = clientSettingsSnapshot;
try {
const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
if (persistedSettings) {
const currentSnapshot = clientSettingsSnapshot;
if (currentSnapshot !== snapshotBeforeHydration) {
replaceClientSettingsSnapshot({ ...persistedSettings, ...currentSnapshot });
} else {
replaceClientSettingsSnapshot(persistedSettings);
}
}
} catch (error) {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
} finally {
clientSettingsHydrated = true;
}
})();
const hydrationPromise = nextHydration.finally(() => {
if (clientSettingsHydrationPromise === hydrationPromise) {
clientSettingsHydrationPromise = null;
}
});
clientSettingsHydrationPromise = hydrationPromise;
return clientSettingsHydrationPromise;
}
function persistClientSettings(settings: ClientSettings): void {
replaceClientSettingsSnapshot(settings);
void ensureLocalApi()
.persistence.setClientSettings(settings)
.catch((error) => {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, error);
});
}
// ── Key sets for routing patches ─────────────────────────────────────
@@ -69,10 +130,10 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
const serverSettings = useServerSettings();
const [clientSettings] = useLocalStorage(
CLIENT_SETTINGS_STORAGE_KEY,
DEFAULT_CLIENT_SETTINGS,
ClientSettingsSchema,
const clientSettings = useSyncExternalStore(
subscribeClientSettings,
getClientSettingsSnapshot,
() => DEFAULT_CLIENT_SETTINGS,
);
const merged = useMemo<UnifiedSettings>(
@@ -90,34 +151,28 @@ export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings)
* Returns an updater that routes each key to the correct backing store.
*
* Server keys are optimistically patched in atom-backed server state, then
* persisted via RPC. Client keys go straight to localStorage.
* persisted via RPC. Client keys go through client persistence.
*/
export function useUpdateSettings() {
const [, setClientSettings] = useLocalStorage(
CLIENT_SETTINGS_STORAGE_KEY,
DEFAULT_CLIENT_SETTINGS,
ClientSettingsSchema,
);
const updateSettings = useCallback((patch: Partial<UnifiedSettings>) => {
const { serverPatch, clientPatch } = splitPatch(patch);
const updateSettings = useCallback(
(patch: Partial<UnifiedSettings>) => {
const { serverPatch, clientPatch } = splitPatch(patch);
if (Object.keys(serverPatch).length > 0) {
const currentServerConfig = getServerConfig();
if (currentServerConfig) {
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
if (Object.keys(serverPatch).length > 0) {
const currentServerConfig = getServerConfig();
if (currentServerConfig) {
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
}
if (Object.keys(clientPatch).length > 0) {
setClientSettings((prev) => ({ ...prev, ...clientPatch }));
}
},
[setClientSettings],
);
if (Object.keys(clientPatch).length > 0) {
persistClientSettings({
...getClientSettingsSnapshot(),
...clientPatch,
});
}
}, []);
const resetSettings = useCallback(() => {
updateSettings(DEFAULT_UNIFIED_SETTINGS);
@@ -129,132 +184,9 @@ export function useUpdateSettings() {
};
}
// ── One-time migration from localStorage ─────────────────────────────
export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<string, unknown>) {
const patch: DeepMutable<ServerSettingsPatch> = {};
if (Predicate.isBoolean(legacySettings.enableAssistantStreaming)) {
patch.enableAssistantStreaming = legacySettings.enableAssistantStreaming;
}
if (Schema.is(ThreadEnvMode)(legacySettings.defaultThreadEnvMode)) {
patch.defaultThreadEnvMode = legacySettings.defaultThreadEnvMode;
}
if (Schema.is(ModelSelection)(legacySettings.textGenerationModelSelection)) {
patch.textGenerationModelSelection = legacySettings.textGenerationModelSelection;
}
if (typeof legacySettings.codexBinaryPath === "string") {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.binaryPath = legacySettings.codexBinaryPath;
}
if (typeof legacySettings.codexHomePath === "string") {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.homePath = legacySettings.codexHomePath;
}
if (Array.isArray(legacySettings.customCodexModels)) {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.customModels = normalizeCustomModelSlugs(
legacySettings.customCodexModels,
new Set<string>(),
"codex",
);
}
if (Predicate.isString(legacySettings.claudeBinaryPath)) {
patch.providers ??= {};
patch.providers.claudeAgent ??= {};
patch.providers.claudeAgent.binaryPath = legacySettings.claudeBinaryPath;
}
if (Array.isArray(legacySettings.customClaudeModels)) {
patch.providers ??= {};
patch.providers.claudeAgent ??= {};
patch.providers.claudeAgent.customModels = normalizeCustomModelSlugs(
legacySettings.customClaudeModels,
new Set<string>(),
"claudeAgent",
);
}
return patch;
}
export function buildLegacyClientSettingsMigrationPatch(
legacySettings: Record<string, unknown>,
): Partial<DeepMutable<ClientSettings>> {
const patch: Partial<DeepMutable<ClientSettings>> = {};
if (Predicate.isBoolean(legacySettings.confirmThreadArchive)) {
patch.confirmThreadArchive = legacySettings.confirmThreadArchive;
}
if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) {
patch.confirmThreadDelete = legacySettings.confirmThreadDelete;
}
if (Predicate.isBoolean(legacySettings.diffWordWrap)) {
patch.diffWordWrap = legacySettings.diffWordWrap;
}
if (Schema.is(SidebarProjectSortOrder)(legacySettings.sidebarProjectSortOrder)) {
patch.sidebarProjectSortOrder = legacySettings.sidebarProjectSortOrder;
}
if (Schema.is(SidebarThreadSortOrder)(legacySettings.sidebarThreadSortOrder)) {
patch.sidebarThreadSortOrder = legacySettings.sidebarThreadSortOrder;
}
if (Schema.is(TimestampFormat)(legacySettings.timestampFormat)) {
patch.timestampFormat = legacySettings.timestampFormat;
}
return patch;
}
/**
* Call once on app startup.
* If the legacy localStorage key exists, migrate its values to the new server
* and client storage formats, then remove the legacy key so this only runs once.
*/
export function migrateLocalSettingsToServer(): void {
if (typeof window === "undefined") return;
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
if (!raw) return;
try {
const old = JSON.parse(raw);
if (!Predicate.isObject(old)) return;
// Migrate server-relevant keys via RPC
const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
if (Object.keys(serverPatch).length > 0) {
const api = ensureLocalApi();
void api.server.updateSettings(serverPatch);
}
// Migrate client-only keys to the new localStorage key
const clientPatch = buildLegacyClientSettingsMigrationPatch(old);
if (Object.keys(clientPatch).length > 0) {
const existing = localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY);
const current = existing ? (JSON.parse(existing) as Record<string, unknown>) : {};
localStorage.setItem(
CLIENT_SETTINGS_STORAGE_KEY,
JSON.stringify({ ...current, ...clientPatch }),
);
}
} catch (error) {
console.error("[MIGRATION] Error migrating local settings:", error);
} finally {
// Remove the legacy key regardless to keep migration one-shot behavior.
localStorage.removeItem(OLD_SETTINGS_KEY);
}
export function __resetClientSettingsPersistenceForTests(): void {
clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
clientSettingsHydrated = false;
clientSettingsHydrationPromise = null;
clientSettingsListeners.clear();
}
+155 -1
View File
@@ -137,9 +137,36 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
return testGlobal.window;
}
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => {
store.clear();
},
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
};
}
function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
return {
getLocalEnvironmentBootstrap: () => null,
getClientSettings: async () => null,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: async () => [],
setSavedEnvironmentRegistry: async () => undefined,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
getServerExposureState: async () => ({
mode: "local-only",
endpointUrl: null,
@@ -242,7 +269,12 @@ beforeEach(() => {
terminalEventListeners.clear();
orchestrationEventListeners.clear();
gitStatusListeners.clear();
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
const testWindow = getWindowForTest();
Reflect.deleteProperty(testWindow, "desktopBridge");
Object.defineProperty(testWindow, "localStorage", {
configurable: true,
value: createLocalStorageStub(),
});
});
afterEach(() => {
@@ -463,4 +495,126 @@ describe("wsApi", () => {
await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
});
it("reads and writes persistence through the desktop bridge when available", async () => {
const getClientSettings = vi.fn().mockResolvedValue({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
const setClientSettings = vi.fn().mockResolvedValue(undefined);
const getSavedEnvironmentRegistry = vi.fn().mockResolvedValue([]);
const setSavedEnvironmentRegistry = vi.fn().mockResolvedValue(undefined);
const getSavedEnvironmentSecret = vi.fn().mockResolvedValue("bearer-token");
const setSavedEnvironmentSecret = vi.fn().mockResolvedValue(true);
const removeSavedEnvironmentSecret = vi.fn().mockResolvedValue(undefined);
getWindowForTest().desktopBridge = makeDesktopBridge({
getClientSettings,
setClientSettings,
getSavedEnvironmentRegistry,
setSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
setSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
});
const { createLocalApi } = await import("./localApi");
const api = createLocalApi(rpcClientMock as never);
await api.persistence.getClientSettings();
await api.persistence.setClientSettings({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await api.persistence.getSavedEnvironmentRegistry();
await api.persistence.setSavedEnvironmentRegistry([]);
await api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local"));
await api.persistence.setSavedEnvironmentSecret(
EnvironmentId.makeUnsafe("environment-local"),
"bearer-token",
);
await api.persistence.removeSavedEnvironmentSecret(
EnvironmentId.makeUnsafe("environment-local"),
);
expect(getClientSettings).toHaveBeenCalledWith();
expect(setClientSettings).toHaveBeenCalledWith({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
expect(getSavedEnvironmentRegistry).toHaveBeenCalledWith();
expect(setSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
expect(getSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
expect(setSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local", "bearer-token");
expect(removeSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
});
it("falls back to browser storage for persistence when the desktop bridge is missing", async () => {
const { createLocalApi } = await import("./localApi");
const api = createLocalApi(rpcClientMock as never);
await api.persistence.setClientSettings({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await api.persistence.setSavedEnvironmentRegistry([
{
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Primary",
httpBaseUrl: "http://localhost:3000",
wsBaseUrl: "ws://localhost:3000",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
},
]);
await api.persistence.setSavedEnvironmentSecret(
EnvironmentId.makeUnsafe("environment-local"),
"bearer-token",
);
await expect(api.persistence.getClientSettings()).resolves.toEqual({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await expect(api.persistence.getSavedEnvironmentRegistry()).resolves.toEqual([
{
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Primary",
httpBaseUrl: "http://localhost:3000",
wsBaseUrl: "ws://localhost:3000",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
},
]);
await expect(
api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local")),
).resolves.toBe("bearer-token");
await api.persistence.removeSavedEnvironmentSecret(
EnvironmentId.makeUnsafe("environment-local"),
);
await expect(
api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local")),
).resolves.toBeNull();
});
});
+55
View File
@@ -14,6 +14,15 @@ import {
} from "./environments/runtime";
import { type WsRpcClient } from "./rpc/wsRpcClient";
import { showContextMenuFallback } from "./contextMenuFallback";
import {
readBrowserClientSettings,
readBrowserSavedEnvironmentRegistry,
readBrowserSavedEnvironmentSecret,
removeBrowserSavedEnvironmentSecret,
writeBrowserClientSettings,
writeBrowserSavedEnvironmentRegistry,
writeBrowserSavedEnvironmentSecret,
} from "./clientPersistenceStorage";
let cachedApi: LocalApi | undefined;
@@ -56,6 +65,50 @@ export function createLocalApi(rpcClient: WsRpcClient): LocalApi {
return showContextMenuFallback(items, position);
},
},
persistence: {
getClientSettings: async () => {
if (window.desktopBridge) {
return window.desktopBridge.getClientSettings();
}
return readBrowserClientSettings();
},
setClientSettings: async (settings) => {
if (window.desktopBridge) {
return window.desktopBridge.setClientSettings(settings);
}
writeBrowserClientSettings(settings);
},
getSavedEnvironmentRegistry: async () => {
if (window.desktopBridge) {
return window.desktopBridge.getSavedEnvironmentRegistry();
}
return readBrowserSavedEnvironmentRegistry();
},
setSavedEnvironmentRegistry: async (records) => {
if (window.desktopBridge) {
return window.desktopBridge.setSavedEnvironmentRegistry(records);
}
writeBrowserSavedEnvironmentRegistry(records);
},
getSavedEnvironmentSecret: async (environmentId) => {
if (window.desktopBridge) {
return window.desktopBridge.getSavedEnvironmentSecret(environmentId);
}
return readBrowserSavedEnvironmentSecret(environmentId);
},
setSavedEnvironmentSecret: async (environmentId, secret) => {
if (window.desktopBridge) {
return window.desktopBridge.setSavedEnvironmentSecret(environmentId, secret);
}
return writeBrowserSavedEnvironmentSecret(environmentId, secret);
},
removeSavedEnvironmentSecret: async (environmentId) => {
if (window.desktopBridge) {
return window.desktopBridge.removeSavedEnvironmentSecret(environmentId);
}
removeBrowserSavedEnvironmentSecret(environmentId);
},
},
server: {
getConfig: rpcClient.server.getConfig,
refreshProviders: rpcClient.server.refreshProviders,
@@ -89,6 +142,8 @@ export function ensureLocalApi(): LocalApi {
export async function __resetLocalApiForTests() {
cachedApi = undefined;
const { __resetClientSettingsPersistenceForTests } = await import("./hooks/useSettings");
__resetClientSettingsPersistenceForTests();
await resetEnvironmentServiceForTests();
resetGitStatusStateForTests();
resetRequestLatencyStateForTests();
-2
View File
@@ -31,7 +31,6 @@ import {
} from "../rpc/serverState";
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { syncBrowserChromeTheme } from "../hooks/useTheme";
import {
ensureEnvironmentConnectionBootstrapped,
@@ -213,7 +212,6 @@ function EventRouter() {
updatePrimaryEnvironmentDescriptor(payload.environment);
setActiveEnvironmentId(payload.environment.environmentId);
migrateLocalSettingsToServer();
void (async () => {
await ensureEnvironmentConnectionBootstrapped(payload.environment.environmentId);
if (disposedRef.current) {
+2
View File
@@ -7,6 +7,7 @@ import pkg from "./package.json" with { type: "json" };
const port = Number(process.env.PORT ?? 5733);
const host = process.env.HOST?.trim() || "localhost";
const configuredHttpUrl = process.env.VITE_HTTP_URL?.trim();
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
@@ -58,6 +59,7 @@ export default defineConfig({
include: ["@pierre/diffs", "@pierre/diffs/react", "@pierre/diffs/worker/worker.js"],
},
define: {
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
"import.meta.env.APP_VERSION": JSON.stringify(pkg.version),
+31 -1
View File
@@ -49,8 +49,9 @@ import type {
OrchestrationEvent,
OrchestrationReadModel,
} from "./orchestration";
import type { EnvironmentId } from "./baseSchemas";
import { EditorId } from "./editor";
import { ServerSettings, ServerSettingsPatch } from "./settings";
import { ClientSettings, ServerSettings, ServerSettingsPatch } from "./settings";
export interface ContextMenuItem<T extends string = string> {
id: T;
@@ -112,6 +113,15 @@ export interface DesktopEnvironmentBootstrap {
bootstrapToken?: string;
}
export interface PersistedSavedEnvironmentRecord {
environmentId: EnvironmentId;
label: string;
wsBaseUrl: string;
httpBaseUrl: string;
createdAt: string;
lastConnectedAt: string | null;
}
export type DesktopServerExposureMode = "local-only" | "network-accessible";
export interface DesktopServerExposureState {
@@ -122,6 +132,15 @@ export interface DesktopServerExposureState {
export interface DesktopBridge {
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
getClientSettings: () => Promise<ClientSettings | null>;
setClientSettings: (settings: ClientSettings) => Promise<void>;
getSavedEnvironmentRegistry: () => Promise<readonly PersistedSavedEnvironmentRecord[]>;
setSavedEnvironmentRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Promise<void>;
getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<string | null>;
setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise<boolean>;
removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<void>;
getServerExposureState: () => Promise<DesktopServerExposureState>;
setServerExposureMode: (mode: DesktopServerExposureMode) => Promise<DesktopServerExposureState>;
pickFolder: () => Promise<string | null>;
@@ -165,6 +184,17 @@ export interface LocalApi {
position?: { x: number; y: number },
) => Promise<T | null>;
};
persistence: {
getClientSettings: () => Promise<ClientSettings | null>;
setClientSettings: (settings: ClientSettings) => Promise<void>;
getSavedEnvironmentRegistry: () => Promise<readonly PersistedSavedEnvironmentRecord[]>;
setSavedEnvironmentRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Promise<void>;
getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<string | null>;
setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise<boolean>;
removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<void>;
};
server: {
getConfig: () => Promise<ServerConfig>;
refreshProviders: () => Promise<ServerProviderUpdatedPayload>;
+2
View File
@@ -84,6 +84,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.T3CODE_HOME, resolve("/tmp/custom-t3"));
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_HTTP_URL, "http://localhost:4222");
assert.equal(env.VITE_WS_URL, "ws://localhost:4222");
assert.equal(env.T3CODE_NO_BROWSER, "1");
assert.equal(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD, "0");
@@ -183,6 +184,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.VITE_DEV_SERVER_URL, "http://127.0.0.1:5733");
assert.equal(env.HOST, "127.0.0.1");
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:4222");
assert.equal(env.T3CODE_MODE, undefined);
assert.equal(env.T3CODE_NO_BROWSER, undefined);
assert.equal(env.T3CODE_HOST, undefined);
+2
View File
@@ -159,9 +159,11 @@ export function createDevRunnerEnv({
if (!isDesktopMode) {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
} else {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
delete output.T3CODE_MODE;
delete output.T3CODE_NO_BROWSER;