From 1363cc1189e5ec4f47a680f9bd3c5ffaf8fd9e67 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 9 Apr 2026 18:56:57 -0700 Subject: [PATCH] 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 --- apps/web/src/clientPersistence.test.ts | 232 ++++-------- apps/web/src/clientPersistence.ts | 361 +------------------ apps/web/src/clientPersistenceStorage.ts | 266 ++++++++++++++ apps/web/src/environments/runtime/catalog.ts | 7 +- apps/web/src/hooks/useSettings.ts | 13 +- apps/web/src/localApi.test.ts | 149 +++++++- apps/web/src/localApi.ts | 53 +++ packages/contracts/src/ipc.ts | 11 + 8 files changed, 574 insertions(+), 518 deletions(-) create mode 100644 apps/web/src/clientPersistenceStorage.ts diff --git a/apps/web/src/clientPersistence.test.ts b/apps/web/src/clientPersistence.test.ts index 0e43f8b17b..a67fb641c6 100644 --- a/apps/web/src/clientPersistence.test.ts +++ b/apps/web/src/clientPersistence.test.ts @@ -1,16 +1,23 @@ -import { EnvironmentId, type ClientSettings, type DesktopBridge } from "@t3tools/contracts"; +import { EnvironmentId, type ClientSettings, type LocalApi } 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"; +import { + readBrowserClientSettings, + readBrowserSavedEnvironmentRegistry, + readBrowserSavedEnvironmentSecret, + removeBrowserSavedEnvironmentSecret, + writeBrowserClientSettings, + writeBrowserSavedEnvironmentRegistry, + writeBrowserSavedEnvironmentSecret, +} from "./clientPersistenceStorage"; const testEnvironmentId = EnvironmentId.makeUnsafe("environment-1"); @@ -47,20 +54,61 @@ function getTestWindow(): Window & typeof globalThis { const localStorage = createLocalStorageStub(); const testWindow = { localStorage, + location: { + origin: "http://localhost:3000", + }, } as Window & typeof globalThis; vi.stubGlobal("window", testWindow); vi.stubGlobal("localStorage", localStorage); return testWindow; } -afterEach(() => { +function installBrowserPersistenceApi(windowForTest: Window & typeof globalThis): void { + windowForTest.nativeApi = { + persistence: { + getClientSettings: async () => readBrowserClientSettings(), + setClientSettings: async (settings: ClientSettings) => { + writeBrowserClientSettings(settings); + }, + getSavedEnvironmentRegistry: async () => readBrowserSavedEnvironmentRegistry(), + setSavedEnvironmentRegistry: async ( + records: Awaited>, + ) => { + writeBrowserSavedEnvironmentRegistry(records); + }, + getSavedEnvironmentSecret: async ( + environmentId: Parameters[0], + ) => readBrowserSavedEnvironmentSecret(environmentId), + setSavedEnvironmentSecret: async ( + environmentId: Parameters[0], + secret: Parameters[1], + ) => writeBrowserSavedEnvironmentSecret(environmentId, secret), + removeSavedEnvironmentSecret: async ( + environmentId: Parameters[0], + ) => { + removeBrowserSavedEnvironmentSecret(environmentId); + }, + }, + } as unknown as LocalApi; +} + +afterEach(async () => { + const { __resetLocalApiForTests } = await import("./localApi"); + await __resetLocalApiForTests(); vi.unstubAllGlobals(); vi.restoreAllMocks(); }); +async function resetLocalApiForTest(): Promise { + const { __resetLocalApiForTests } = await import("./localApi"); + await __resetLocalApiForTests(); +} + describe("clientPersistence", () => { it("reads and writes client settings in browser storage mode", async () => { - getTestWindow(); + const testWindow = getTestWindow(); + installBrowserPersistenceApi(testWindow); + await resetLocalApiForTest(); await writePersistedClientSettings(clientSettings); @@ -69,25 +117,19 @@ describe("clientPersistence", () => { 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, - }, - }, - }, - }), - ); + installBrowserPersistenceApi(testWindow); + await resetLocalApiForTest(); + writeBrowserSavedEnvironmentRegistry([ + { + environmentId: testEnvironmentId, + label: "Remote environment", + httpBaseUrl: "https://remote.example.com/", + wsBaseUrl: "wss://remote.example.com/", + createdAt: "2026-04-09T00:00:00.000Z", + lastConnectedAt: null, + }, + ]); + writeBrowserSavedEnvironmentSecret(testEnvironmentId, "bearer-token"); await expect(readPersistedSavedEnvironmentSecret(testEnvironmentId)).resolves.toBe( "bearer-token", @@ -95,7 +137,9 @@ describe("clientPersistence", () => { }); it("preserves browser-mode secrets when the secret is written before metadata", async () => { - getTestWindow(); + const testWindow = getTestWindow(); + installBrowserPersistenceApi(testWindow); + await resetLocalApiForTest(); await writePersistedSavedEnvironmentSecret(testEnvironmentId, "bearer-token"); await writePersistedSavedEnvironmentRegistry([ @@ -114,136 +158,20 @@ describe("clientPersistence", () => { ); }); - 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"); + testWindow.nativeApi = { + persistence: { + getClientSettings: async () => clientSettings, + setClientSettings: async () => undefined, + getSavedEnvironmentRegistry: async () => [], + setSavedEnvironmentRegistry: async () => undefined, + getSavedEnvironmentSecret: async () => null, + setSavedEnvironmentSecret: async () => true, + removeSavedEnvironmentSecret: async () => undefined, }, - 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; + } as unknown as LocalApi; + await resetLocalApiForTest(); await expect(readPersistedClientSettings()).resolves.toEqual(clientSettings); expect(testWindow.localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY)).toBeNull(); diff --git a/apps/web/src/clientPersistence.ts b/apps/web/src/clientPersistence.ts index 1e68663eb1..37da48fcff 100644 --- a/apps/web/src/clientPersistence.ts +++ b/apps/web/src/clientPersistence.ts @@ -1,386 +1,49 @@ 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; - readonly secretsById?: Record; -} - -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 { - 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, -): 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] : [], - ), - ), - }, - }); -} +import { ensureLocalApi } from "./localApi"; +export { + CLIENT_SETTINGS_STORAGE_KEY, + SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, +} from "./clientPersistenceStorage"; export async function readPersistedClientSettings(): Promise { - if (hasDesktopBridge()) { - return getDesktopBridge().getClientSettings(); - } - - return readBrowserClientSettings(); + return ensureLocalApi().persistence.getClientSettings(); } export async function writePersistedClientSettings(settings: ClientSettings): Promise { - if (hasDesktopBridge()) { - await getDesktopBridge().setClientSettings(settings); - return; - } - - writeBrowserClientSettings(settings); -} - -export async function migrateBrowserClientSettingsToDesktopPersistence(): Promise { - 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; + await ensureLocalApi().persistence.setClientSettings(settings); } export async function readPersistedSavedEnvironmentRegistry(): Promise< ReadonlyArray > { - 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, - })); + return ensureLocalApi().persistence.getSavedEnvironmentRegistry(); } export async function writePersistedSavedEnvironmentRegistry( records: ReadonlyArray, ): Promise { - 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 -> { - 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; + await ensureLocalApi().persistence.setSavedEnvironmentRegistry(records); } export async function readPersistedSavedEnvironmentSecret( environmentId: EnvironmentId, ): Promise { - 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 - ); + return ensureLocalApi().persistence.getSavedEnvironmentSecret(environmentId); } export async function writePersistedSavedEnvironmentSecret( environmentId: EnvironmentId, secret: string, ): Promise { - 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; + return ensureLocalApi().persistence.setSavedEnvironmentSecret(environmentId, secret); } export async function removePersistedSavedEnvironmentSecret( environmentId: EnvironmentId, ): Promise { - 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, - }, - }); + await ensureLocalApi().persistence.removeSavedEnvironmentSecret(environmentId); } diff --git a/apps/web/src/clientPersistenceStorage.ts b/apps/web/src/clientPersistenceStorage.ts new file mode 100644 index 0000000000..e2f1ab29c4 --- /dev/null +++ b/apps/web/src/clientPersistenceStorage.ts @@ -0,0 +1,266 @@ +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; + readonly secretsById?: Record; +} + +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 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, + }; +} + +export 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; + } +} + +export 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 { + 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, +): 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 function readBrowserSavedEnvironmentRegistry(): ReadonlyArray { + return readBrowserSavedEnvironmentRecordsWithSecrets().map((record) => ({ + environmentId: record.environmentId, + label: record.label, + httpBaseUrl: record.httpBaseUrl, + wsBaseUrl: record.wsBaseUrl, + createdAt: record.createdAt, + lastConnectedAt: record.lastConnectedAt, + })); +} + +export function writeBrowserSavedEnvironmentRegistry( + records: ReadonlyArray, +): void { + 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 function readBrowserSavedEnvironmentSecret(environmentId: EnvironmentId): string | null { + 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 function writeBrowserSavedEnvironmentSecret( + environmentId: EnvironmentId, + secret: string, +): boolean { + 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 function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentId): void { + 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, + }, + }); +} diff --git a/apps/web/src/environments/runtime/catalog.ts b/apps/web/src/environments/runtime/catalog.ts index 3f3a6cc372..a8cbcbb9b9 100644 --- a/apps/web/src/environments/runtime/catalog.ts +++ b/apps/web/src/environments/runtime/catalog.ts @@ -9,7 +9,6 @@ import type { import { create } from "zustand"; import { - migrateBrowserSavedEnvironmentRegistryToDesktopPersistence, readPersistedSavedEnvironmentRegistry, readPersistedSavedEnvironmentSecret, removePersistedSavedEnvironmentSecret, @@ -82,11 +81,7 @@ async function hydrateSavedEnvironmentRegistry(): Promise { const nextHydration = (async () => { try { - const migratedRecords = await migrateBrowserSavedEnvironmentRegistryToDesktopPersistence(); - const persistedRecords = - migratedRecords.length > 0 - ? migratedRecords - : await readPersistedSavedEnvironmentRegistry(); + const persistedRecords = await readPersistedSavedEnvironmentRegistry(); replaceSavedEnvironmentRegistryState(persistedRecords); } catch (error) { console.error("[SAVED_ENVIRONMENTS] hydrate failed", error); diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index 4cd19e58e3..2462dc1ec6 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -25,11 +25,7 @@ import { TimestampFormat, UnifiedSettings, } from "@t3tools/contracts/settings"; -import { - migrateBrowserClientSettingsToDesktopPersistence, - readPersistedClientSettings, - writePersistedClientSettings, -} from "~/clientPersistence"; +import { readPersistedClientSettings, writePersistedClientSettings } from "~/clientPersistence"; import { ensureLocalApi } from "~/localApi"; import { normalizeCustomModelSlugs } from "~/modelSelection"; import { Predicate, Schema, Struct } from "effect"; @@ -78,8 +74,7 @@ async function hydrateClientSettings(): Promise { const nextHydration = (async () => { try { - const migratedSettings = await migrateBrowserClientSettingsToDesktopPersistence(); - const persistedSettings = migratedSettings ?? (await readPersistedClientSettings()); + const persistedSettings = await readPersistedClientSettings(); if (persistedSettings) { replaceClientSettingsSnapshot(persistedSettings); } @@ -309,9 +304,7 @@ export function migrateLocalSettingsToServer(): void { const clientPatch = buildLegacyClientSettingsMigrationPatch(old); if (Object.keys(clientPatch).length > 0) { void (async () => { - const migratedSettings = await migrateBrowserClientSettingsToDesktopPersistence(); - const current = - migratedSettings ?? (await readPersistedClientSettings()) ?? DEFAULT_CLIENT_SETTINGS; + const current = (await readPersistedClientSettings()) ?? DEFAULT_CLIENT_SETTINGS; persistClientSettings({ ...current, ...clientPatch, diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index 7e0366b4c6..bd04cabfaa 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -137,6 +137,26 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn return testGlobal.window; } +function createLocalStorageStub(): Storage { + const store = new Map(); + 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 { return { getLocalEnvironmentBootstrap: () => null, @@ -249,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(() => { @@ -470,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(); + }); }); diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts index 2a51f10297..8fe17f4a89 100644 --- a/apps/web/src/localApi.ts +++ b/apps/web/src/localApi.ts @@ -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, diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index fae0e2d0f9..31e8693805 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -184,6 +184,17 @@ export interface LocalApi { position?: { x: number; y: number }, ) => Promise; }; + persistence: { + getClientSettings: () => Promise; + setClientSettings: (settings: ClientSettings) => Promise; + getSavedEnvironmentRegistry: () => Promise; + setSavedEnvironmentRegistry: ( + records: readonly PersistedSavedEnvironmentRecord[], + ) => Promise; + getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise; + setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise; + removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise; + }; server: { getConfig: () => Promise; refreshProviders: () => Promise;