Handle saved environment credential persistence failures
- Roll back saved environment metadata when bearer token persistence fails - Catch local API persistence errors during registry upserts - Remove legacy local settings migration bootstrap
This commit is contained in:
1 parent
110fc3eca1
commit
af1fd868ba
7 files changed
+158
-182
No files matched your search
@@ -68,4 +68,24 @@ describe("environment runtime catalog stores", () => {
|
||||
|
||||
expect(useSavedEnvironmentRuntimeStore.getState().byId).toEqual({});
|
||||
});
|
||||
|
||||
it("does not throw when local api lookup fails during registry persistence", async () => {
|
||||
vi.unstubAllGlobals();
|
||||
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const { __resetLocalApiForTests } = await import("../../localApi");
|
||||
await __resetLocalApiForTests();
|
||||
|
||||
expect(() =>
|
||||
useSavedEnvironmentRegistryStore.getState().upsert({
|
||||
environmentId: EnvironmentId.makeUnsafe("environment-1"),
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
}),
|
||||
).not.toThrow();
|
||||
|
||||
expect(errorSpy).toHaveBeenCalledWith("[SAVED_ENVIRONMENTS] persist failed", expect.any(Error));
|
||||
});
|
||||
});
|
||||
@@ -56,15 +56,19 @@ function valuesOfSavedEnvironmentRegistry(
|
||||
function persistSavedEnvironmentRegistryState(
|
||||
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
|
||||
): void {
|
||||
void ensureLocalApi()
|
||||
.persistence.setSavedEnvironmentRegistry(
|
||||
valuesOfSavedEnvironmentRegistry(byId).map((record) =>
|
||||
toPersistedSavedEnvironmentRecord(record),
|
||||
),
|
||||
)
|
||||
.catch((error) => {
|
||||
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
|
||||
});
|
||||
try {
|
||||
void ensureLocalApi()
|
||||
.persistence.setSavedEnvironmentRegistry(
|
||||
valuesOfSavedEnvironmentRegistry(byId).map((record) =>
|
||||
toPersistedSavedEnvironmentRecord(record),
|
||||
),
|
||||
)
|
||||
.catch((error) => {
|
||||
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
function replaceSavedEnvironmentRegistryState(
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockResolveRemotePairingTarget = vi.fn();
|
||||
const mockFetchRemoteEnvironmentDescriptor = vi.fn();
|
||||
const mockBootstrapRemoteBearerSession = vi.fn();
|
||||
const mockPersistSavedEnvironmentRecord = vi.fn();
|
||||
const mockWriteSavedEnvironmentBearerToken = vi.fn();
|
||||
const mockSetSavedEnvironmentRegistry = vi.fn();
|
||||
const mockUpsert = vi.fn();
|
||||
const mockListSavedEnvironmentRecords = vi.fn();
|
||||
|
||||
vi.mock("../remote/target", () => ({
|
||||
resolveRemotePairingTarget: mockResolveRemotePairingTarget,
|
||||
}));
|
||||
|
||||
vi.mock("../remote/api", () => ({
|
||||
bootstrapRemoteBearerSession: mockBootstrapRemoteBearerSession,
|
||||
fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor,
|
||||
fetchRemoteSessionState: vi.fn(),
|
||||
resolveRemoteWebSocketConnectionUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/localApi", () => ({
|
||||
ensureLocalApi: () => ({
|
||||
persistence: {
|
||||
setSavedEnvironmentRegistry: mockSetSavedEnvironmentRegistry,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("./catalog", () => ({
|
||||
getSavedEnvironmentRecord: vi.fn(),
|
||||
hasSavedEnvironmentRegistryHydrated: vi.fn(),
|
||||
listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
|
||||
persistSavedEnvironmentRecord: mockPersistSavedEnvironmentRecord,
|
||||
readSavedEnvironmentBearerToken: vi.fn(),
|
||||
removeSavedEnvironmentBearerToken: vi.fn(),
|
||||
useSavedEnvironmentRegistryStore: {
|
||||
getState: () => ({
|
||||
upsert: mockUpsert,
|
||||
remove: vi.fn(),
|
||||
markConnected: vi.fn(),
|
||||
}),
|
||||
},
|
||||
useSavedEnvironmentRuntimeStore: {
|
||||
getState: () => ({
|
||||
ensure: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
}),
|
||||
},
|
||||
waitForSavedEnvironmentRegistryHydration: vi.fn(),
|
||||
writeSavedEnvironmentBearerToken: mockWriteSavedEnvironmentBearerToken,
|
||||
}));
|
||||
|
||||
vi.mock("./connection", () => ({
|
||||
createEnvironmentConnection: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("addSavedEnvironment", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
mockResolveRemotePairingTarget.mockReturnValue({
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
credential: "pairing-code",
|
||||
});
|
||||
mockFetchRemoteEnvironmentDescriptor.mockResolvedValue({
|
||||
environmentId: EnvironmentId.makeUnsafe("environment-1"),
|
||||
label: "Remote environment",
|
||||
});
|
||||
mockBootstrapRemoteBearerSession.mockResolvedValue({
|
||||
sessionToken: "bearer-token",
|
||||
role: "owner",
|
||||
});
|
||||
mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined);
|
||||
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
|
||||
mockSetSavedEnvironmentRegistry.mockResolvedValue(undefined);
|
||||
mockListSavedEnvironmentRecords.mockReturnValue([]);
|
||||
});
|
||||
|
||||
it("rolls back persisted metadata when bearer token persistence fails", async () => {
|
||||
const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
|
||||
|
||||
await expect(
|
||||
addSavedEnvironment({
|
||||
label: "Remote environment",
|
||||
host: "remote.example.com",
|
||||
pairingCode: "123456",
|
||||
}),
|
||||
).rejects.toThrow("Unable to persist saved environment credentials.");
|
||||
|
||||
expect(mockPersistSavedEnvironmentRecord).toHaveBeenCalledTimes(1);
|
||||
expect(mockWriteSavedEnvironmentBearerToken).toHaveBeenCalledWith(
|
||||
EnvironmentId.makeUnsafe("environment-1"),
|
||||
"bearer-token",
|
||||
);
|
||||
expect(mockSetSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
|
||||
expect(mockUpsert).not.toHaveBeenCalled();
|
||||
|
||||
await resetEnvironmentServiceForTests();
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
markPromotedDraftThreadsByRef,
|
||||
useComposerDraftStore,
|
||||
} from "~/composerDraftStore";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
import { collectActiveTerminalThreadIds } from "~/lib/terminalStateCleanup";
|
||||
import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects";
|
||||
import { projectQueryKeys } from "~/lib/projectReactQuery";
|
||||
@@ -614,7 +615,23 @@ export async function addSavedEnvironment(input: {
|
||||
};
|
||||
|
||||
await persistSavedEnvironmentRecord(record);
|
||||
await writeSavedEnvironmentBearerToken(environmentId, bearerSession.sessionToken);
|
||||
const didPersistBearerToken = await writeSavedEnvironmentBearerToken(
|
||||
environmentId,
|
||||
bearerSession.sessionToken,
|
||||
);
|
||||
if (!didPersistBearerToken) {
|
||||
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
|
||||
listSavedEnvironmentRecords().map((entry) => ({
|
||||
environmentId: entry.environmentId,
|
||||
label: entry.label,
|
||||
httpBaseUrl: entry.httpBaseUrl,
|
||||
wsBaseUrl: entry.wsBaseUrl,
|
||||
createdAt: entry.createdAt,
|
||||
lastConnectedAt: entry.lastConnectedAt,
|
||||
})),
|
||||
);
|
||||
throw new Error("Unable to persist saved environment credentials.");
|
||||
}
|
||||
await ensureSavedEnvironmentConnection(record, {
|
||||
bearerToken: bearerSession.sessionToken,
|
||||
role: bearerSession.role,
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildLegacyClientSettingsMigrationPatch } from "./useSettings";
|
||||
|
||||
describe("buildLegacyClientSettingsMigrationPatch", () => {
|
||||
it("migrates archive confirmation from legacy local settings", () => {
|
||||
expect(
|
||||
buildLegacyClientSettingsMigrationPatch({
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
}),
|
||||
).toEqual({
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -10,29 +10,18 @@
|
||||
* store.
|
||||
*/
|
||||
import { useCallback, useMemo, useSyncExternalStore } from "react";
|
||||
import {
|
||||
ServerSettings,
|
||||
ServerSettingsPatch,
|
||||
ModelSelection,
|
||||
ThreadEnvMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServerSettings, ServerSettingsPatch } from "@t3tools/contracts";
|
||||
import {
|
||||
type ClientSettings,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
DEFAULT_UNIFIED_SETTINGS,
|
||||
SidebarProjectSortOrder,
|
||||
SidebarThreadSortOrder,
|
||||
TimestampFormat,
|
||||
UnifiedSettings,
|
||||
} from "@t3tools/contracts/settings";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
import { normalizeCustomModelSlugs } from "~/modelSelection";
|
||||
import { Predicate, Schema, Struct } from "effect";
|
||||
import { DeepMutable } from "effect/Types";
|
||||
import { Struct } from "effect";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
|
||||
|
||||
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
|
||||
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
|
||||
|
||||
const clientSettingsListeners = new Set<() => void>();
|
||||
@@ -188,144 +177,3 @@ export function useUpdateSettings() {
|
||||
resetSettings,
|
||||
};
|
||||
}
|
||||
|
||||
// ── One-time migration from localStorage ─────────────────────────────
|
||||
|
||||
export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<string, unknown>) {
|
||||
const patch: DeepMutable<ServerSettingsPatch> = {};
|
||||
|
||||
if (Predicate.isBoolean(legacySettings.enableAssistantStreaming)) {
|
||||
patch.enableAssistantStreaming = legacySettings.enableAssistantStreaming;
|
||||
}
|
||||
|
||||
if (Schema.is(ThreadEnvMode)(legacySettings.defaultThreadEnvMode)) {
|
||||
patch.defaultThreadEnvMode = legacySettings.defaultThreadEnvMode;
|
||||
}
|
||||
|
||||
if (Schema.is(ModelSelection)(legacySettings.textGenerationModelSelection)) {
|
||||
patch.textGenerationModelSelection = legacySettings.textGenerationModelSelection;
|
||||
}
|
||||
|
||||
if (typeof legacySettings.codexBinaryPath === "string") {
|
||||
patch.providers ??= {};
|
||||
patch.providers.codex ??= {};
|
||||
patch.providers.codex.binaryPath = legacySettings.codexBinaryPath;
|
||||
}
|
||||
|
||||
if (typeof legacySettings.codexHomePath === "string") {
|
||||
patch.providers ??= {};
|
||||
patch.providers.codex ??= {};
|
||||
patch.providers.codex.homePath = legacySettings.codexHomePath;
|
||||
}
|
||||
|
||||
if (Array.isArray(legacySettings.customCodexModels)) {
|
||||
patch.providers ??= {};
|
||||
patch.providers.codex ??= {};
|
||||
patch.providers.codex.customModels = normalizeCustomModelSlugs(
|
||||
legacySettings.customCodexModels,
|
||||
new Set<string>(),
|
||||
"codex",
|
||||
);
|
||||
}
|
||||
|
||||
if (Predicate.isString(legacySettings.claudeBinaryPath)) {
|
||||
patch.providers ??= {};
|
||||
patch.providers.claudeAgent ??= {};
|
||||
patch.providers.claudeAgent.binaryPath = legacySettings.claudeBinaryPath;
|
||||
}
|
||||
|
||||
if (Array.isArray(legacySettings.customClaudeModels)) {
|
||||
patch.providers ??= {};
|
||||
patch.providers.claudeAgent ??= {};
|
||||
patch.providers.claudeAgent.customModels = normalizeCustomModelSlugs(
|
||||
legacySettings.customClaudeModels,
|
||||
new Set<string>(),
|
||||
"claudeAgent",
|
||||
);
|
||||
}
|
||||
|
||||
return patch;
|
||||
}
|
||||
|
||||
export function buildLegacyClientSettingsMigrationPatch(
|
||||
legacySettings: Record<string, unknown>,
|
||||
): Partial<DeepMutable<ClientSettings>> {
|
||||
const patch: Partial<DeepMutable<ClientSettings>> = {};
|
||||
|
||||
if (Predicate.isBoolean(legacySettings.confirmThreadArchive)) {
|
||||
patch.confirmThreadArchive = legacySettings.confirmThreadArchive;
|
||||
}
|
||||
|
||||
if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) {
|
||||
patch.confirmThreadDelete = legacySettings.confirmThreadDelete;
|
||||
}
|
||||
|
||||
if (Predicate.isBoolean(legacySettings.diffWordWrap)) {
|
||||
patch.diffWordWrap = legacySettings.diffWordWrap;
|
||||
}
|
||||
|
||||
if (Schema.is(SidebarProjectSortOrder)(legacySettings.sidebarProjectSortOrder)) {
|
||||
patch.sidebarProjectSortOrder = legacySettings.sidebarProjectSortOrder;
|
||||
}
|
||||
|
||||
if (Schema.is(SidebarThreadSortOrder)(legacySettings.sidebarThreadSortOrder)) {
|
||||
patch.sidebarThreadSortOrder = legacySettings.sidebarThreadSortOrder;
|
||||
}
|
||||
|
||||
if (Schema.is(TimestampFormat)(legacySettings.timestampFormat)) {
|
||||
patch.timestampFormat = legacySettings.timestampFormat;
|
||||
}
|
||||
|
||||
return patch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call once on app startup.
|
||||
* If the legacy localStorage key exists, migrate its values to the new server
|
||||
* and client storage formats, then remove the legacy key so this only runs once.
|
||||
*/
|
||||
export function migrateLocalSettingsToServer(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
|
||||
if (!raw) return;
|
||||
|
||||
try {
|
||||
const old = JSON.parse(raw);
|
||||
if (!Predicate.isObject(old)) return;
|
||||
|
||||
// Migrate server-relevant keys via RPC
|
||||
const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
|
||||
if (Object.keys(serverPatch).length > 0) {
|
||||
const api = ensureLocalApi();
|
||||
void api.server.updateSettings(serverPatch);
|
||||
}
|
||||
|
||||
// Migrate client-only keys to the new localStorage key
|
||||
const clientPatch = buildLegacyClientSettingsMigrationPatch(old);
|
||||
if (Object.keys(clientPatch).length > 0) {
|
||||
void (async () => {
|
||||
const current =
|
||||
(await ensureLocalApi().persistence.getClientSettings()) ?? 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);
|
||||
} finally {
|
||||
// Remove the legacy key regardless to keep migration one-shot behavior.
|
||||
localStorage.removeItem(OLD_SETTINGS_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
export function __resetClientSettingsPersistenceForTests(): void {
|
||||
clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
clientSettingsHydrated = false;
|
||||
clientSettingsHydrationPromise = null;
|
||||
clientSettingsListeners.clear();
|
||||
}
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
} from "../rpc/serverState";
|
||||
import { useStore } from "../store";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
|
||||
import { syncBrowserChromeTheme } from "../hooks/useTheme";
|
||||
import {
|
||||
ensureEnvironmentConnectionBootstrapped,
|
||||
@@ -213,7 +212,6 @@ function EventRouter() {
|
||||
|
||||
updatePrimaryEnvironmentDescriptor(payload.environment);
|
||||
setActiveEnvironmentId(payload.environment.environmentId);
|
||||
migrateLocalSettingsToServer();
|
||||
void (async () => {
|
||||
await ensureEnvironmentConnectionBootstrapped(payload.environment.environmentId);
|
||||
if (disposedRef.current) {
|
||||
|
||||
Reference in new issue
Block a user