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
This commit is contained in:
Julius Marminge committed 2026-04-09 18:13:23 -07:00
1 parent 65d797c13e
commit 5331bd2f45
13 files changed
+1349 -112

No files matched your search

+161
View File
@@ -0,0 +1,161 @@
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 secretsPath = makeTempPath("saved-environment-secrets.json");
const secretStorage = makeSecretStorage(true);
expect(
writeSavedEnvironmentSecret({
secretsPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
}),
).toBe(true);
expect(
readSavedEnvironmentSecret({
secretsPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
});
it("drops persisted secrets when encryption is unavailable", () => {
const secretsPath = makeTempPath("saved-environment-secrets.json");
const availableSecretStorage = makeSecretStorage(true);
writeSavedEnvironmentSecret({
secretsPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: availableSecretStorage,
});
expect(
writeSavedEnvironmentSecret({
secretsPath,
environmentId: savedRegistryRecord.environmentId,
secret: "next-token",
secretStorage: makeSecretStorage(false),
}),
).toBe(false);
expect(
readSavedEnvironmentSecret({
secretsPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: availableSecretStorage,
}),
).toBeNull();
});
it("removes saved environment secrets", () => {
const secretsPath = makeTempPath("saved-environment-secrets.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentSecret({
secretsPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
removeSavedEnvironmentSecret({
secretsPath,
environmentId: savedRegistryRecord.environmentId,
});
expect(
readSavedEnvironmentSecret({
secretsPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBeNull();
});
});
+123
View File
@@ -0,0 +1,123 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
}
interface SavedEnvironmentRegistryDocument {
readonly records: readonly PersistedSavedEnvironmentRecord[];
}
interface SavedEnvironmentSecretsDocument {
readonly byId: Readonly<Record<string, string>>;
}
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 readSecretsDocument(filePath: string): SavedEnvironmentSecretsDocument {
return readJsonFile<SavedEnvironmentSecretsDocument>(filePath) ?? { byId: {} };
}
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 readJsonFile<SavedEnvironmentRegistryDocument>(registryPath)?.records ?? [];
}
export function writeSavedEnvironmentRegistry(
registryPath: string,
records: readonly PersistedSavedEnvironmentRecord[],
): void {
writeJsonFile(registryPath, { records } satisfies SavedEnvironmentRegistryDocument);
}
export function readSavedEnvironmentSecret(input: {
readonly secretsPath: string;
readonly environmentId: string;
readonly secretStorage: DesktopSecretStorage;
}): string | null {
const encoded = readSecretsDocument(input.secretsPath).byId[input.environmentId];
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 secretsPath: string;
readonly environmentId: string;
readonly secret: string;
readonly secretStorage: DesktopSecretStorage;
}): boolean {
const document = readSecretsDocument(input.secretsPath);
const { [input.environmentId]: _previous, ...remaining } = document.byId;
if (!input.secretStorage.isEncryptionAvailable()) {
writeJsonFile(input.secretsPath, { byId: remaining } satisfies SavedEnvironmentSecretsDocument);
return false;
}
writeJsonFile(input.secretsPath, {
byId: {
...remaining,
[input.environmentId]: input.secretStorage.encryptString(input.secret).toString("base64"),
},
} satisfies SavedEnvironmentSecretsDocument);
return true;
}
export function removeSavedEnvironmentSecret(input: {
readonly secretsPath: string;
readonly environmentId: string;
}): void {
const document = readSecretsDocument(input.secretsPath);
if (!(input.environmentId in document.byId)) {
return;
}
const { [input.environmentId]: _removed, ...remaining } = document.byId;
writeJsonFile(input.secretsPath, { byId: remaining } satisfies SavedEnvironmentSecretsDocument);
}
+110
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,21 @@ 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 SAVED_ENVIRONMENT_SECRETS_PATH = Path.join(STATE_DIR, "saved-environment-secrets.json");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -204,6 +226,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;
@@ -1343,6 +1373,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({
secretsPath: SAVED_ENVIRONMENT_SECRETS_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({
secretsPath: SAVED_ENVIRONMENT_SECRETS_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({
secretsPath: SAVED_ENVIRONMENT_SECRETS_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),
+251
View File
@@ -0,0 +1,251 @@
import { EnvironmentId, type ClientSettings, type DesktopBridge } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
CLIENT_SETTINGS_STORAGE_KEY,
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
migrateBrowserSavedEnvironmentRegistryToDesktopPersistence,
readPersistedClientSettings,
readPersistedSavedEnvironmentSecret,
writePersistedClientSettings,
writePersistedSavedEnvironmentRegistry,
writePersistedSavedEnvironmentSecret,
} from "./clientPersistence";
const testEnvironmentId = EnvironmentId.makeUnsafe("environment-1");
const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
};
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.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("clientPersistence", () => {
it("reads and writes client settings in browser storage mode", async () => {
getTestWindow();
await writePersistedClientSettings(clientSettings);
await expect(readPersistedClientSettings()).resolves.toEqual(clientSettings);
});
it("reads saved environment bearer tokens from browser storage mode", async () => {
const testWindow = getTestWindow();
testWindow.localStorage.setItem(
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
JSON.stringify({
version: 1,
state: {
byId: {
[testEnvironmentId]: {
environmentId: testEnvironmentId,
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
bearerToken: "bearer-token",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
},
},
},
}),
);
await expect(readPersistedSavedEnvironmentSecret(testEnvironmentId)).resolves.toBe(
"bearer-token",
);
});
it("preserves browser-mode secrets when the secret is written before metadata", async () => {
getTestWindow();
await writePersistedSavedEnvironmentSecret(testEnvironmentId, "bearer-token");
await writePersistedSavedEnvironmentRegistry([
{
environmentId: testEnvironmentId,
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
},
]);
await expect(readPersistedSavedEnvironmentSecret(testEnvironmentId)).resolves.toBe(
"bearer-token",
);
});
it("migrates saved environment metadata and tokens into desktop persistence", async () => {
const testWindow = getTestWindow();
const setSavedEnvironmentRegistry = vi.fn().mockResolvedValue(undefined);
const setSavedEnvironmentSecret = vi.fn().mockResolvedValue(true);
testWindow.localStorage.setItem(
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
JSON.stringify({
version: 1,
state: {
byId: {
[testEnvironmentId]: {
environmentId: testEnvironmentId,
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
bearerToken: "bearer-token",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
},
},
},
}),
);
testWindow.desktopBridge = {
getLocalEnvironmentBootstrap: () => null,
getClientSettings: async () => null,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: async () => [],
setSavedEnvironmentRegistry,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret,
removeSavedEnvironmentSecret: async () => undefined,
getServerExposureState: async () => ({
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
}),
setServerExposureMode: async () => ({
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
}),
pickFolder: async () => null,
confirm: async () => true,
setTheme: async () => undefined,
showContextMenu: async () => null,
openExternal: async () => true,
onMenuAction: () => () => undefined,
getUpdateState: async () => {
throw new Error("not implemented");
},
checkForUpdate: async () => {
throw new Error("not implemented");
},
downloadUpdate: async () => {
throw new Error("not implemented");
},
installUpdate: async () => {
throw new Error("not implemented");
},
onUpdateState: () => () => undefined,
} satisfies DesktopBridge;
await expect(migrateBrowserSavedEnvironmentRegistryToDesktopPersistence()).resolves.toEqual([
{
environmentId: testEnvironmentId,
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",
},
]);
expect(setSavedEnvironmentRegistry).toHaveBeenCalledWith([
{
environmentId: testEnvironmentId,
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",
},
]);
expect(setSavedEnvironmentSecret).toHaveBeenCalledWith(testEnvironmentId, "bearer-token");
});
it("can read client settings through the desktop bridge", async () => {
const testWindow = getTestWindow();
testWindow.desktopBridge = {
getLocalEnvironmentBootstrap: () => null,
getClientSettings: async () => clientSettings,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: async () => [],
setSavedEnvironmentRegistry: async () => undefined,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
getServerExposureState: async () => ({
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
}),
setServerExposureMode: async () => ({
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
}),
pickFolder: async () => null,
confirm: async () => true,
setTheme: async () => undefined,
showContextMenu: async () => null,
openExternal: async () => true,
onMenuAction: () => () => undefined,
getUpdateState: async () => {
throw new Error("not implemented");
},
checkForUpdate: async () => {
throw new Error("not implemented");
},
downloadUpdate: async () => {
throw new Error("not implemented");
},
installUpdate: async () => {
throw new Error("not implemented");
},
onUpdateState: () => () => undefined,
} satisfies DesktopBridge;
await expect(readPersistedClientSettings()).resolves.toEqual(clientSettings);
expect(testWindow.localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY)).toBeNull();
});
});
+386
View File
@@ -0,0 +1,386 @@
import {
ClientSettingsSchema,
type ClientSettings,
type EnvironmentId,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { Predicate, Schema } from "effect";
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
interface BrowserSavedEnvironmentRecord extends PersistedSavedEnvironmentRecord {
readonly bearerToken?: string;
}
interface BrowserSavedEnvironmentRegistryState {
readonly byId?: Record<string, BrowserSavedEnvironmentRecord>;
readonly secretsById?: Record<string, string>;
}
interface BrowserSavedEnvironmentRegistryDocument {
readonly state?: BrowserSavedEnvironmentRegistryState;
readonly version?: number;
}
const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
const encodeClientSettings = Schema.encodeSync(Schema.fromJsonString(ClientSettingsSchema));
function hasWindow(): boolean {
return typeof window !== "undefined";
}
function hasDesktopBridge(): boolean {
return hasWindow() && window.desktopBridge !== undefined;
}
function getDesktopBridge() {
if (!hasDesktopBridge()) {
throw new Error("Desktop persistence is unavailable.");
}
const desktopBridge = window.desktopBridge;
if (!desktopBridge) {
throw new Error("Desktop persistence is unavailable.");
}
return desktopBridge;
}
function readJson(rawValue: string | null): unknown {
if (!rawValue) {
return null;
}
try {
return JSON.parse(rawValue);
} catch {
return null;
}
}
function isPersistedSavedEnvironmentRecord(
value: unknown,
): value is PersistedSavedEnvironmentRecord & { readonly bearerToken?: unknown } {
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")
);
}
function normalizePersistedSavedEnvironmentRecord(
value: unknown,
): PersistedSavedEnvironmentRecord | null {
if (!isPersistedSavedEnvironmentRecord(value)) {
return null;
}
return {
environmentId: value.environmentId,
label: value.label,
httpBaseUrl: value.httpBaseUrl,
wsBaseUrl: value.wsBaseUrl,
createdAt: value.createdAt,
lastConnectedAt: value.lastConnectedAt,
};
}
function readBrowserClientSettings(): ClientSettings | null {
if (!hasWindow()) {
return null;
}
try {
const raw = window.localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY);
return raw ? decodeClientSettings(JSON.parse(raw)) : null;
} catch {
return null;
}
}
function writeBrowserClientSettings(settings: ClientSettings): void {
if (!hasWindow()) {
return;
}
window.localStorage.setItem(CLIENT_SETTINGS_STORAGE_KEY, encodeClientSettings(settings));
}
function readBrowserSavedEnvironmentRegistryDocument(): BrowserSavedEnvironmentRegistryDocument {
if (!hasWindow()) {
return {};
}
const raw = window.localStorage.getItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY);
const parsed = readJson(raw);
return Predicate.isObject(parsed) ? (parsed as BrowserSavedEnvironmentRegistryDocument) : {};
}
function writeBrowserSavedEnvironmentRegistryDocument(
document: BrowserSavedEnvironmentRegistryDocument,
): void {
if (!hasWindow()) {
return;
}
window.localStorage.setItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, JSON.stringify(document));
}
function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray<BrowserSavedEnvironmentRecord> {
const state = readBrowserSavedEnvironmentRegistryDocument().state;
const byId = state?.byId ?? {};
const secretsById = state?.secretsById ?? {};
return Object.values(byId).flatMap((record) => {
const normalizedRecord = normalizePersistedSavedEnvironmentRecord(record);
if (!normalizedRecord) {
return [];
}
const bearerToken =
typeof secretsById[normalizedRecord.environmentId] === "string" &&
secretsById[normalizedRecord.environmentId]
? secretsById[normalizedRecord.environmentId]
: typeof record.bearerToken === "string" && record.bearerToken.length > 0
? record.bearerToken
: null;
return [
{
...normalizedRecord,
...(bearerToken ? { bearerToken } : {}),
} satisfies BrowserSavedEnvironmentRecord,
];
});
}
function writeBrowserSavedEnvironmentRecords(
records: ReadonlyArray<BrowserSavedEnvironmentRecord>,
): void {
writeBrowserSavedEnvironmentRegistryDocument({
version: 1,
state: {
byId: Object.fromEntries(records.map((record) => [record.environmentId, record])),
secretsById: Object.fromEntries(
records.flatMap((record) =>
record.bearerToken ? [[record.environmentId, record.bearerToken] as const] : [],
),
),
},
});
}
export async function readPersistedClientSettings(): Promise<ClientSettings | null> {
if (hasDesktopBridge()) {
return getDesktopBridge().getClientSettings();
}
return readBrowserClientSettings();
}
export async function writePersistedClientSettings(settings: ClientSettings): Promise<void> {
if (hasDesktopBridge()) {
await getDesktopBridge().setClientSettings(settings);
return;
}
writeBrowserClientSettings(settings);
}
export async function migrateBrowserClientSettingsToDesktopPersistence(): Promise<ClientSettings | null> {
if (!hasDesktopBridge()) {
return null;
}
const desktopBridge = getDesktopBridge();
const persisted = await desktopBridge.getClientSettings();
if (persisted) {
return persisted;
}
const browserSettings = readBrowserClientSettings();
if (!browserSettings) {
return null;
}
await desktopBridge.setClientSettings(browserSettings);
return browserSettings;
}
export async function readPersistedSavedEnvironmentRegistry(): Promise<
ReadonlyArray<PersistedSavedEnvironmentRecord>
> {
if (hasDesktopBridge()) {
return getDesktopBridge().getSavedEnvironmentRegistry();
}
return readBrowserSavedEnvironmentRecordsWithSecrets().map((record) => ({
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
}));
}
export async function writePersistedSavedEnvironmentRegistry(
records: ReadonlyArray<PersistedSavedEnvironmentRecord>,
): Promise<void> {
if (hasDesktopBridge()) {
await getDesktopBridge().setSavedEnvironmentRegistry(records);
return;
}
const document = readBrowserSavedEnvironmentRegistryDocument();
const directSecretsById = document.state?.secretsById ?? {};
const existing = new Map(
readBrowserSavedEnvironmentRecordsWithSecrets().map(
(record) => [record.environmentId, record] as const,
),
);
writeBrowserSavedEnvironmentRecords(
records.map((record) => ({
...record,
...((existing.get(record.environmentId)?.bearerToken ??
directSecretsById[record.environmentId])
? {
bearerToken:
existing.get(record.environmentId)?.bearerToken ??
directSecretsById[record.environmentId],
}
: {}),
})),
);
}
export async function migrateBrowserSavedEnvironmentRegistryToDesktopPersistence(): Promise<
ReadonlyArray<PersistedSavedEnvironmentRecord>
> {
if (!hasDesktopBridge()) {
return [];
}
const desktopBridge = getDesktopBridge();
const persisted = await desktopBridge.getSavedEnvironmentRegistry();
if (persisted.length > 0) {
return persisted;
}
const browserRecords = readBrowserSavedEnvironmentRecordsWithSecrets();
if (browserRecords.length === 0) {
return [];
}
const metadata = browserRecords.map((record) => ({
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
}));
await desktopBridge.setSavedEnvironmentRegistry(metadata);
await Promise.all(
browserRecords.map(async (record) => {
if (!record.bearerToken) {
return;
}
await desktopBridge.setSavedEnvironmentSecret(record.environmentId, record.bearerToken);
}),
);
return metadata;
}
export async function readPersistedSavedEnvironmentSecret(
environmentId: EnvironmentId,
): Promise<string | null> {
if (hasDesktopBridge()) {
return getDesktopBridge().getSavedEnvironmentSecret(environmentId);
}
const state = readBrowserSavedEnvironmentRegistryDocument().state;
const directSecret = state?.secretsById?.[environmentId];
if (typeof directSecret === "string" && directSecret.length > 0) {
return directSecret;
}
return (
readBrowserSavedEnvironmentRecordsWithSecrets().find(
(record) => record.environmentId === environmentId,
)?.bearerToken ?? null
);
}
export async function writePersistedSavedEnvironmentSecret(
environmentId: EnvironmentId,
secret: string,
): Promise<boolean> {
if (hasDesktopBridge()) {
return getDesktopBridge().setSavedEnvironmentSecret(environmentId, secret);
}
const document = readBrowserSavedEnvironmentRegistryDocument();
const state = document.state ?? {};
const byId = state.byId ?? {};
const existingRecord = byId[environmentId];
writeBrowserSavedEnvironmentRegistryDocument({
version: document.version ?? 1,
state: {
byId: existingRecord
? {
...byId,
[environmentId]: {
...existingRecord,
bearerToken: secret,
},
}
: byId,
secretsById: {
...state.secretsById,
[environmentId]: secret,
},
},
});
return true;
}
export async function removePersistedSavedEnvironmentSecret(
environmentId: EnvironmentId,
): Promise<void> {
if (hasDesktopBridge()) {
await getDesktopBridge().removeSavedEnvironmentSecret(environmentId);
return;
}
const document = readBrowserSavedEnvironmentRegistryDocument();
const state = document.state ?? {};
const byId = { ...state.byId };
const existingRecord = byId[environmentId];
const nextById = existingRecord
? {
...byId,
[environmentId]: {
environmentId: existingRecord.environmentId,
label: existingRecord.label,
httpBaseUrl: existingRecord.httpBaseUrl,
wsBaseUrl: existingRecord.wsBaseUrl,
createdAt: existingRecord.createdAt,
lastConnectedAt: existingRecord.lastConnectedAt,
},
}
: byId;
const { [environmentId]: _removed, ...remainingSecrets } = state.secretsById ?? {};
writeBrowserSavedEnvironmentRegistryDocument({
version: document.version ?? 1,
state: {
byId: nextById,
secretsById: remainingSecrets,
},
});
}
@@ -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",
@@ -22,7 +22,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,
});
+137 -67
View File
@@ -3,22 +3,26 @@ 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 {
migrateBrowserSavedEnvironmentRegistryToDesktopPersistence,
readPersistedSavedEnvironmentRegistry,
readPersistedSavedEnvironmentSecret,
removePersistedSavedEnvironmentSecret,
writePersistedSavedEnvironmentRegistry,
writePersistedSavedEnvironmentSecret,
} from "../../clientPersistence";
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 +38,117 @@ 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: {},
}),
function persistSavedEnvironmentRegistryState(
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
): void {
void writePersistedSavedEnvironmentRegistry(
Object.values(byId).map((record) => toPersistedSavedEnvironmentRecord(record)),
).catch((error) => {
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
});
}
function replaceSavedEnvironmentRegistryState(
records: ReadonlyArray<SavedEnvironmentRecord>,
): void {
useSavedEnvironmentRegistryStore.setState({
byId: Object.fromEntries(records.map((record) => [record.environmentId, record])),
});
}
async function hydrateSavedEnvironmentRegistry(): Promise<void> {
if (savedEnvironmentRegistryHydrated) {
return;
}
if (savedEnvironmentRegistryHydrationPromise) {
return savedEnvironmentRegistryHydrationPromise;
}
const nextHydration = (async () => {
try {
const migratedRecords = await migrateBrowserSavedEnvironmentRegistryToDesktopPersistence();
const persistedRecords =
migratedRecords.length > 0
? migratedRecords
: await readPersistedSavedEnvironmentRegistry();
replaceSavedEnvironmentRegistryState(persistedRecords);
} catch (error) {
console.error("[SAVED_ENVIRONMENTS] hydrate failed", error);
} finally {
savedEnvironmentRegistryHydrated = true;
}
})();
savedEnvironmentRegistryHydrationPromise = nextHydration.finally(() => {
if (savedEnvironmentRegistryHydrationPromise === nextHydration) {
savedEnvironmentRegistryHydrationPromise = null;
}
});
return savedEnvironmentRegistryHydrationPromise;
}
export const useSavedEnvironmentRegistryStore = create<SavedEnvironmentRegistryStore>()((set) => ({
byId: {},
upsert: (record) =>
set((state) => {
const byId = {
...state.byId,
[record.environmentId]: record,
};
persistSavedEnvironmentRegistryState(byId);
return { byId };
}),
{
name: SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
version: 1,
storage: createJSONStorage(createSavedEnvironmentRegistryStorage),
partialize: (state) => ({
byId: state.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 +156,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,9 +199,30 @@ export function resolveEnvironmentHttpUrl(input: {
}
export function resetSavedEnvironmentRegistryStoreForTests() {
savedEnvironmentRegistryHydrated = false;
savedEnvironmentRegistryHydrationPromise = null;
useSavedEnvironmentRegistryStore.getState().reset();
}
export async function readSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
): Promise<string | null> {
return readPersistedSavedEnvironmentSecret(environmentId);
}
export async function writeSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
bearerToken: string,
): Promise<boolean> {
return writePersistedSavedEnvironmentSecret(environmentId, bearerToken);
}
export async function removeSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
): Promise<void> {
await removePersistedSavedEnvironmentSecret(environmentId);
}
export type SavedEnvironmentConnectionState = "connecting" | "connected" | "disconnected" | "error";
export type SavedEnvironmentAuthState = "authenticated" | "requires-auth" | "unknown";
+30 -6
View File
@@ -39,10 +39,13 @@ import {
getSavedEnvironmentRecord,
hasSavedEnvironmentRegistryHydrated,
listSavedEnvironmentRecords,
readSavedEnvironmentBearerToken,
removeSavedEnvironmentBearerToken,
type SavedEnvironmentRecord,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
waitForSavedEnvironmentRegistryHydration,
writeSavedEnvironmentBearerToken,
} from "./catalog";
import { createEnvironmentConnection, type EnvironmentConnection } from "./connection";
import {
@@ -306,7 +309,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 +321,7 @@ function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClie
resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken: record.bearerToken,
bearerToken,
}),
{
onAttempt: () => {
@@ -341,6 +347,7 @@ function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClie
async function refreshSavedEnvironmentMetadata(
record: SavedEnvironmentRecord,
bearerToken: string,
client: WsRpcClient,
roleHint?: AuthSessionRole | null,
configHint?: ServerConfig | null,
@@ -349,7 +356,7 @@ async function refreshSavedEnvironmentMetadata(
configHint ? Promise.resolve(configHint) : client.server.getConfig(),
fetchRemoteSessionState({
httpBaseUrl: record.httpBaseUrl,
bearerToken: record.bearerToken,
bearerToken,
}),
]);
@@ -408,6 +415,7 @@ async function ensureSavedEnvironmentConnection(
record: SavedEnvironmentRecord,
options?: {
readonly client?: WsRpcClient;
readonly bearerToken?: string;
readonly role?: AuthSessionRole | null;
readonly serverConfig?: ServerConfig | null;
},
@@ -417,7 +425,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 +456,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 +477,7 @@ async function ensureSavedEnvironmentConnection(
try {
await refreshSavedEnvironmentMetadata(
record,
bearerToken,
client,
options?.role ?? null,
options?.serverConfig ?? null,
@@ -552,6 +574,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 +608,13 @@ 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 writeSavedEnvironmentBearerToken(environmentId, bearerSession.sessionToken);
await ensureSavedEnvironmentConnection(record, {
bearerToken: bearerSession.sessionToken,
role: bearerSession.role,
});
useSavedEnvironmentRegistryStore.getState().upsert(record);
+99 -37
View File
@@ -9,7 +9,7 @@
* write. The hook transparently routes reads/writes to the correct backing
* store.
*/
import { useCallback, useMemo } from "react";
import { useCallback, useMemo, useSyncExternalStore } from "react";
import {
ServerSettings,
ServerSettingsPatch,
@@ -18,7 +18,6 @@ import {
} from "@t3tools/contracts";
import {
type ClientSettings,
ClientSettingsSchema,
DEFAULT_CLIENT_SETTINGS,
DEFAULT_UNIFIED_SETTINGS,
SidebarProjectSortOrder,
@@ -26,16 +25,80 @@ import {
TimestampFormat,
UnifiedSettings,
} from "@t3tools/contracts/settings";
import {
migrateBrowserClientSettingsToDesktopPersistence,
readPersistedClientSettings,
writePersistedClientSettings,
} from "~/clientPersistence";
import { ensureLocalApi } from "~/localApi";
import { useLocalStorage } from "./useLocalStorage";
import { normalizeCustomModelSlugs } from "~/modelSelection";
import { Predicate, Schema, Struct } from "effect";
import { DeepMutable } from "effect/Types";
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 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 (clientSettingsHydrationPromise) {
return clientSettingsHydrationPromise;
}
const nextHydration = (async () => {
try {
const migratedSettings = await migrateBrowserClientSettingsToDesktopPersistence();
const persistedSettings = migratedSettings ?? (await readPersistedClientSettings());
if (persistedSettings) {
replaceClientSettingsSnapshot(persistedSettings);
}
} catch (error) {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
}
})();
clientSettingsHydrationPromise = nextHydration.finally(() => {
if (clientSettingsHydrationPromise === nextHydration) {
clientSettingsHydrationPromise = null;
}
});
return clientSettingsHydrationPromise;
}
function persistClientSettings(settings: ClientSettings): void {
replaceClientSettingsSnapshot(settings);
void writePersistedClientSettings(settings).catch((error) => {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, error);
});
}
// ── Key sets for routing patches ─────────────────────────────────────
@@ -69,10 +132,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 +153,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);
@@ -244,12 +301,17 @@ export function migrateLocalSettingsToServer(): void {
// 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 }),
);
void (async () => {
const migratedSettings = await migrateBrowserClientSettingsToDesktopPersistence();
const current =
migratedSettings ?? (await readPersistedClientSettings()) ?? DEFAULT_CLIENT_SETTINGS;
persistClientSettings({
...current,
...clientPatch,
});
})().catch((error) => {
console.error("[MIGRATION] Error persisting migrated client settings:", error);
});
}
} catch (error) {
console.error("[MIGRATION] Error migrating local settings:", error);
+7
View File
@@ -140,6 +140,13 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
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,
+20 -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>;