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
This commit is contained in:
1 parent
b5ac0b3e2d
commit
1363cc1189
8 files changed
+574
-518
No files matched your search
@@ -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<ReturnType<LocalApi["persistence"]["getSavedEnvironmentRegistry"]>>,
|
||||
) => {
|
||||
writeBrowserSavedEnvironmentRegistry(records);
|
||||
},
|
||||
getSavedEnvironmentSecret: async (
|
||||
environmentId: Parameters<LocalApi["persistence"]["getSavedEnvironmentSecret"]>[0],
|
||||
) => readBrowserSavedEnvironmentSecret(environmentId),
|
||||
setSavedEnvironmentSecret: async (
|
||||
environmentId: Parameters<LocalApi["persistence"]["setSavedEnvironmentSecret"]>[0],
|
||||
secret: Parameters<LocalApi["persistence"]["setSavedEnvironmentSecret"]>[1],
|
||||
) => writeBrowserSavedEnvironmentSecret(environmentId, secret),
|
||||
removeSavedEnvironmentSecret: async (
|
||||
environmentId: Parameters<LocalApi["persistence"]["removeSavedEnvironmentSecret"]>[0],
|
||||
) => {
|
||||
removeBrowserSavedEnvironmentSecret(environmentId);
|
||||
},
|
||||
},
|
||||
} as unknown as LocalApi;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
const { __resetLocalApiForTests } = await import("./localApi");
|
||||
await __resetLocalApiForTests();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function resetLocalApiForTest(): Promise<void> {
|
||||
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();
|
||||
|
||||
@@ -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<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] : [],
|
||||
),
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
import { ensureLocalApi } from "./localApi";
|
||||
export {
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
|
||||
} from "./clientPersistenceStorage";
|
||||
|
||||
export async function readPersistedClientSettings(): Promise<ClientSettings | null> {
|
||||
if (hasDesktopBridge()) {
|
||||
return getDesktopBridge().getClientSettings();
|
||||
}
|
||||
|
||||
return readBrowserClientSettings();
|
||||
return ensureLocalApi().persistence.getClientSettings();
|
||||
}
|
||||
|
||||
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;
|
||||
await ensureLocalApi().persistence.setClientSettings(settings);
|
||||
}
|
||||
|
||||
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,
|
||||
}));
|
||||
return ensureLocalApi().persistence.getSavedEnvironmentRegistry();
|
||||
}
|
||||
|
||||
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;
|
||||
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(records);
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
return ensureLocalApi().persistence.getSavedEnvironmentSecret(environmentId);
|
||||
}
|
||||
|
||||
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;
|
||||
return ensureLocalApi().persistence.setSavedEnvironmentSecret(environmentId, secret);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
await ensureLocalApi().persistence.removeSavedEnvironmentSecret(environmentId);
|
||||
}
|
||||
@@ -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<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 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<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 function readBrowserSavedEnvironmentRegistry(): ReadonlyArray<PersistedSavedEnvironmentRecord> {
|
||||
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<PersistedSavedEnvironmentRecord>,
|
||||
): 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,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import type {
|
||||
import { create } from "zustand";
|
||||
|
||||
import {
|
||||
migrateBrowserSavedEnvironmentRegistryToDesktopPersistence,
|
||||
readPersistedSavedEnvironmentRegistry,
|
||||
readPersistedSavedEnvironmentSecret,
|
||||
removePersistedSavedEnvironmentSecret,
|
||||
@@ -82,11 +81,7 @@ async function hydrateSavedEnvironmentRegistry(): Promise<void> {
|
||||
|
||||
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);
|
||||
|
||||
@@ -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<void> {
|
||||
|
||||
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,
|
||||
|
||||
@@ -137,6 +137,26 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
|
||||
return testGlobal.window;
|
||||
}
|
||||
|
||||
function createLocalStorageStub(): Storage {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
removeItem: (key) => {
|
||||
store.delete(key);
|
||||
},
|
||||
clear: () => {
|
||||
store.clear();
|
||||
},
|
||||
key: (index) => [...store.keys()][index] ?? null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
|
||||
return {
|
||||
getLocalEnvironmentBootstrap: () => null,
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -184,6 +184,17 @@ export interface LocalApi {
|
||||
position?: { x: number; y: number },
|
||||
) => Promise<T | null>;
|
||||
};
|
||||
persistence: {
|
||||
getClientSettings: () => Promise<ClientSettings | null>;
|
||||
setClientSettings: (settings: ClientSettings) => Promise<void>;
|
||||
getSavedEnvironmentRegistry: () => Promise<readonly PersistedSavedEnvironmentRecord[]>;
|
||||
setSavedEnvironmentRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Promise<void>;
|
||||
getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<string | null>;
|
||||
setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise<boolean>;
|
||||
removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<void>;
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
refreshProviders: () => Promise<ServerProviderUpdatedPayload>;
|
||||
|
||||
Reference in new issue
Block a user