The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { useRef, useSyncExternalStore, use } from "react"; |
| 3 | import { useSyncExternalStoreWithSelector } from "use-sync-external-store/with-selector"; |
| 4 | import { RegistryContext, useAtomValue } from "@effect/atom-react"; |
| 5 | import { |
| 6 | DEFAULT_SERVER_SETTINGS, |
| 7 | AuthSettingsWriteScope, |
| 8 | requiredScopesForServerSettingsPatch, |
| 9 | type EnvironmentId, |
| 10 | type ProviderInstanceMutation, |
| 11 | type ProviderInstanceId, |
| 12 | ServerSettings, |
| 13 | type ServerSettingsPatch, |
| 14 | sessionGrantsScope, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import { |
| 17 | type ClientSettingsPatch, |
| 18 | type ClientSettings, |
| 19 | DEFAULT_CLIENT_SETTINGS, |
| 20 | type EnvironmentIdentificationMode, |
| 21 | type UnifiedSettings, |
| 22 | } from "@t3tools/contracts/settings"; |
| 23 | import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; |
| 24 | import { |
| 25 | isAtomCommandInterrupted, |
| 26 | runAtomCommand, |
| 27 | squashAtomCommandFailure, |
| 28 | } from "@t3tools/client-runtime/state/runtime"; |
| 29 | import { |
| 30 | filterSharedServerPatch, |
| 31 | splitSharedServerPatch, |
| 32 | supportsSharedSettingsSync, |
| 33 | } from "@t3tools/client-runtime/state/shared-settings"; |
| 34 | import { ensureLocalApi } from "~/localApi"; |
| 35 | import { subscribeBrowserClientSettingsWrites } from "~/clientPersistenceStorage"; |
| 36 | import { |
| 37 | getThemeDefinition, |
| 38 | getThemePreviewSidebarArtwork, |
| 39 | resolveThemeHalf, |
| 40 | subscribeToThemePreview, |
| 41 | themeAllowsSidebarArtwork, |
| 42 | } from "~/themePalette"; |
| 43 | import { |
| 44 | modelPreferencesMigrationPatch, |
| 45 | resolveModelPreferences, |
| 46 | } from "@t3tools/shared/serverSettings"; |
| 47 | import * as Equal from "effect/Equal"; |
| 48 | import * as Struct from "effect/Struct"; |
| 49 | import * as Option from "effect/Option"; |
| 50 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 51 | import { toastManager } from "~/components/ui/toast"; |
| 52 | import { isHostedStaticApp } from "~/hostedPairing"; |
| 53 | import { environmentCatalog } from "~/connection/catalog"; |
| 54 | import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server"; |
| 55 | import { useEnvironments, usePrimaryEnvironment } from "~/state/environments"; |
| 56 | import { useAtomCommand } from "~/state/use-atom-command"; |
| 57 | import { useTheme } from "./useTheme"; |
| 58 | import { msg } from "gt-react"; |
| 59 | import { m } from "~/i18n/messages"; |
| 60 | import { |
| 61 | environmentSession, |
| 62 | environmentSessionStatesAtom, |
| 63 | readEnvironmentScope, |
| 64 | useEnvironmentScope, |
| 65 | } from "~/state/session"; |
| 66 | import { environmentIdsKey } from "~/state/environmentAtomList"; |
| 67 | import { appAtomRegistry } from "~/rpc/atomRegistry"; |
| 68 | |
| 69 | const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]"; |
| 70 | |
| 71 | type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch; |
| 72 | |
| 73 | const clientSettingsListeners = new Set<() => void>(); |
| 74 | const clientSettingsHydrationListeners = new Set<() => void>(); |
| 75 | type ClientSettingsHydrationStatus = "pending" | "ready" | "failed" | "retrying"; |
| 76 | let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS; |
| 77 | let clientSettingsHydrationStatus: ClientSettingsHydrationStatus = "pending"; |
| 78 | let clientSettingsHydrationPromise: Promise<void> | null = null; |
| 79 | let clientSettingsHydrationGeneration = 0; |
| 80 | let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve(); |
| 81 | let deferredClientSettingsPatchCount = 0; |
| 82 | let unsubscribeOtherTabClientSettings: (() => void) | null = null; |
| 83 | |
| 84 | function emitClientSettingsChange() { |
| 85 | for (const listener of clientSettingsListeners) { |
| 86 | listener(); |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | function emitClientSettingsHydrationChange() { |
| 91 | for (const listener of clientSettingsHydrationListeners) { |
| 92 | listener(); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | function getClientSettingsSnapshot(): ClientSettings { |
| 97 | return clientSettingsSnapshot; |
| 98 | } |
| 99 | |
| 100 | function replaceClientSettingsSnapshot(settings: ClientSettings): void { |
| 101 | clientSettingsSnapshot = settings; |
| 102 | emitClientSettingsChange(); |
| 103 | } |
| 104 | |
| 105 | function setClientSettingsHydrationStatus(nextStatus: ClientSettingsHydrationStatus): void { |
| 106 | if (clientSettingsHydrationStatus === nextStatus) { |
| 107 | return; |
| 108 | } |
| 109 | clientSettingsHydrationStatus = nextStatus; |
| 110 | emitClientSettingsHydrationChange(); |
| 111 | } |
| 112 | |
| 113 | export function subscribeClientSettings(listener: () => void): () => void { |
| 114 | clientSettingsListeners.add(listener); |
| 115 | void hydrateClientSettings().catch(() => undefined); |
| 116 | return () => { |
| 117 | clientSettingsListeners.delete(listener); |
| 118 | }; |
| 119 | } |
| 120 | |
| 121 | export function getClientSettingsHydratedSnapshot(): boolean { |
| 122 | return clientSettingsHydrationStatus === "ready"; |
| 123 | } |
| 124 | |
| 125 | function getClientSettingsHydrationStatusSnapshot(): ClientSettingsHydrationStatus { |
| 126 | return clientSettingsHydrationStatus; |
| 127 | } |
| 128 | |
| 129 | export function subscribeClientSettingsHydration(listener: () => void): () => void { |
| 130 | clientSettingsHydrationListeners.add(listener); |
| 131 | void hydrateClientSettings().catch(() => undefined); |
| 132 | return () => { |
| 133 | clientSettingsHydrationListeners.delete(listener); |
| 134 | }; |
| 135 | } |
| 136 | |
| 137 | async function hydrateClientSettings(): Promise<void> { |
| 138 | if (clientSettingsHydrationStatus === "ready") { |
| 139 | return; |
| 140 | } |
| 141 | if (clientSettingsHydrationPromise) { |
| 142 | return clientSettingsHydrationPromise; |
| 143 | } |
| 144 | |
| 145 | const hydrationGeneration = clientSettingsHydrationGeneration; |
| 146 | setClientSettingsHydrationStatus( |
| 147 | clientSettingsHydrationStatus === "failed" || clientSettingsHydrationStatus === "retrying" |
| 148 | ? "retrying" |
| 149 | : "pending", |
| 150 | ); |
| 151 | const nextHydration = (async () => { |
| 152 | try { |
| 153 | const persistedSettings = await ensureLocalApi().persistence.getClientSettings(); |
| 154 | if (hydrationGeneration !== clientSettingsHydrationGeneration) { |
| 155 | return; |
| 156 | } |
| 157 | if (persistedSettings) { |
| 158 | replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings }); |
| 159 | } |
| 160 | unsubscribeOtherTabClientSettings ??= subscribeBrowserClientSettingsWrites( |
| 161 | refreshClientSettingsFromOtherTab, |
| 162 | ); |
| 163 | setClientSettingsHydrationStatus("ready"); |
| 164 | } catch (error) { |
| 165 | if (hydrationGeneration === clientSettingsHydrationGeneration) { |
| 166 | setClientSettingsHydrationStatus("failed"); |
| 167 | } |
| 168 | console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, { |
| 169 | operation: "hydrate", |
| 170 | ...safeErrorLogAttributes(error), |
| 171 | }); |
| 172 | throw error; |
| 173 | } |
| 174 | })(); |
| 175 | |
| 176 | const hydrationPromise = nextHydration.finally(() => { |
| 177 | if (clientSettingsHydrationPromise === hydrationPromise) { |
| 178 | clientSettingsHydrationPromise = null; |
| 179 | } |
| 180 | }); |
| 181 | clientSettingsHydrationPromise = hydrationPromise; |
| 182 | |
| 183 | return clientSettingsHydrationPromise; |
| 184 | } |
| 185 | |
| 186 | function refreshClientSettingsFromOtherTab(): void { |
| 187 | void enqueueClientSettingsPersistence(async () => { |
| 188 | const persistedSettings = await ensureLocalApi().persistence.getClientSettings(); |
| 189 | if (persistedSettings) { |
| 190 | replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings }); |
| 191 | } |
| 192 | }).catch((error) => { |
| 193 | console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} refresh failed`, { |
| 194 | operation: "refresh", |
| 195 | ...safeErrorLogAttributes(error), |
| 196 | }); |
| 197 | }); |
| 198 | } |
| 199 | |
| 200 | const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> => |
| 201 | ensureLocalApi().persistence.setClientSettings(settings); |
| 202 | |
| 203 | function enqueueClientSettingsPersistence<A>(work: () => Promise<A>): Promise<A> { |
| 204 | const result = clientSettingsPersistenceQueue.then(work); |
| 205 | clientSettingsPersistenceQueue = result.then( |
| 206 | () => undefined, |
| 207 | () => undefined, |
| 208 | ); |
| 209 | return result; |
| 210 | } |
| 211 | |
| 212 | export function persistClientSettingsPatch( |
| 213 | patch: ClientSettingsPatch, |
| 214 | persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence, |
| 215 | ): Promise<void> { |
| 216 | // Patches queued before hydration must publish before newer optimistic patches. |
| 217 | const deferPatch = |
| 218 | clientSettingsHydrationStatus !== "ready" || deferredClientSettingsPatchCount > 0; |
| 219 | if (deferPatch) { |
| 220 | deferredClientSettingsPatchCount += 1; |
| 221 | } else { |
| 222 | replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch }); |
| 223 | } |
| 224 | return enqueueClientSettingsPersistence(async () => { |
| 225 | if (deferPatch) { |
| 226 | try { |
| 227 | if (clientSettingsHydrationStatus !== "ready") { |
| 228 | await hydrateClientSettings(); |
| 229 | } |
| 230 | } finally { |
| 231 | deferredClientSettingsPatchCount -= 1; |
| 232 | } |
| 233 | } |
| 234 | // Also reapplies an optimistic patch that a refresh from another tab replaced. |
| 235 | const current = getClientSettingsSnapshot(); |
| 236 | if ( |
| 237 | !Object.entries(patch).every(([key, value]) => current[key as keyof ClientSettings] === value) |
| 238 | ) { |
| 239 | replaceClientSettingsSnapshot({ ...current, ...patch }); |
| 240 | } |
| 241 | await persist(getClientSettingsSnapshot()); |
| 242 | }).catch((error) => { |
| 243 | console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, { |
| 244 | operation: "persist", |
| 245 | ...safeErrorLogAttributes(error), |
| 246 | }); |
| 247 | }); |
| 248 | } |
| 249 | |
| 250 | /** Reapply to newer snapshots after pending writes to avoid losing concurrent changes. */ |
| 251 | export async function persistClientSettingsUpdate( |
| 252 | update: (current: ClientSettings) => ClientSettings, |
| 253 | persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence, |
| 254 | ): Promise<ClientSettings> { |
| 255 | return enqueueClientSettingsPersistence(async () => { |
| 256 | if (clientSettingsHydrationStatus !== "ready") { |
| 257 | await hydrateClientSettings(); |
| 258 | } |
| 259 | for (;;) { |
| 260 | const current = getClientSettingsSnapshot(); |
| 261 | const next = update(current); |
| 262 | await persist(next); |
| 263 | if (getClientSettingsSnapshot() === current) { |
| 264 | replaceClientSettingsSnapshot(next); |
| 265 | return next; |
| 266 | } |
| 267 | } |
| 268 | }); |
| 269 | } |
| 270 | |
| 271 | const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields)); |
| 272 | |
| 273 | function splitPatch(patch: UnifiedSettingsPatch): { |
| 274 | serverPatch: ServerSettingsPatch; |
| 275 | clientPatch: ClientSettingsPatch; |
| 276 | } { |
| 277 | const serverPatch: Record<string, unknown> = {}; |
| 278 | const clientPatch: Record<string, unknown> = {}; |
| 279 | for (const [key, value] of Object.entries(patch)) { |
| 280 | if (SERVER_SETTINGS_KEYS.has(key)) { |
| 281 | serverPatch[key] = value; |
| 282 | } else { |
| 283 | clientPatch[key] = value; |
| 284 | } |
| 285 | } |
| 286 | return { |
| 287 | serverPatch: serverPatch as ServerSettingsPatch, |
| 288 | clientPatch: clientPatch as ClientSettingsPatch, |
| 289 | }; |
| 290 | } |
| 291 | |
| 292 | export function getClientSettings(): ClientSettings { |
| 293 | return getClientSettingsSnapshot(); |
| 294 | } |
| 295 | |
| 296 | export function isClientSettingsHydrated(): boolean { |
| 297 | return getClientSettingsHydratedSnapshot(); |
| 298 | } |
| 299 | |
| 300 | /** Failed reads reject and remain retryable so defaults cannot overwrite saved preferences. */ |
| 301 | export function ensureClientSettingsHydrated(): Promise<void> { |
| 302 | return hydrateClientSettings(); |
| 303 | } |
| 304 | |
| 305 | export function useClientSettingsHydrated(): boolean { |
| 306 | return useSyncExternalStore( |
| 307 | subscribeClientSettingsHydration, |
| 308 | getClientSettingsHydratedSnapshot, |
| 309 | () => false, |
| 310 | ); |
| 311 | } |
| 312 | |
| 313 | export function useClientSettingsHydrationStatus(): ClientSettingsHydrationStatus { |
| 314 | return useSyncExternalStore( |
| 315 | subscribeClientSettingsHydration, |
| 316 | getClientSettingsHydrationStatusSnapshot, |
| 317 | () => "pending", |
| 318 | ); |
| 319 | } |
| 320 | |
| 321 | const getDefaultClientSettings = () => DEFAULT_CLIENT_SETTINGS; |
| 322 | const selectWholeClientSettings = (settings: ClientSettings) => settings; |
| 323 | |
| 324 | /** Structurally equal selections retain their reference and skip rendering. */ |
| 325 | export function useClientSettings<T = ClientSettings>( |
| 326 | selector?: (settings: ClientSettings) => T, |
| 327 | ): T { |
| 328 | return useSyncExternalStoreWithSelector( |
| 329 | subscribeClientSettings, |
| 330 | getClientSettingsSnapshot, |
| 331 | getDefaultClientSettings, |
| 332 | selector ?? (selectWholeClientSettings as (settings: ClientSettings) => T), |
| 333 | Equal.equals, |
| 334 | ); |
| 335 | } |
| 336 | |
| 337 | export function mergeEnvironmentSettings( |
| 338 | serverSettings: ServerSettings, |
| 339 | clientSettings: ClientSettings, |
| 340 | ): UnifiedSettings { |
| 341 | // Older untyped adapters can return retired client keys; server values must win. |
| 342 | return { |
| 343 | ...clientSettings, |
| 344 | ...serverSettings, |
| 345 | ...resolveModelPreferences(serverSettings, clientSettings), |
| 346 | }; |
| 347 | } |
| 348 | |
| 349 | const selectLegacyModelPreferences = (settings: ClientSettings) => ({ |
| 350 | favorites: settings.favorites, |
| 351 | providerModelPreferences: settings.providerModelPreferences, |
| 352 | }); |
| 353 | |
| 354 | // Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites. |
| 355 | const attemptedMigrationGenerations = new Map<EnvironmentId, number>(); |
| 356 | |
| 357 | const modelPreferencesMigrationTargetsAtom = Atom.make((get) => |
| 358 | [...get(environmentCatalog.catalogValueAtom).entries.keys()].flatMap((environmentId) => { |
| 359 | const generation = Option.match( |
| 360 | AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), |
| 361 | { |
| 362 | onNone: () => null, |
| 363 | onSome: (connection) => (connection.phase === "connected" ? connection.generation : null), |
| 364 | }, |
| 365 | ); |
| 366 | const settings = get(serverEnvironment.settingsValueAtom(environmentId)); |
| 367 | return generation === null || settings === null |
| 368 | ? [] |
| 369 | : [{ environmentId, generation, settings }]; |
| 370 | }), |
| 371 | ).pipe(Atom.withLabel("web-model-preferences-migration-targets")); |
| 372 | |
| 373 | function migrateModelPreferences(): void { |
| 374 | if (clientSettingsHydrationStatus !== "ready") return; |
| 375 | for (const { environmentId, generation, settings } of appAtomRegistry.get( |
| 376 | modelPreferencesMigrationTargetsAtom, |
| 377 | )) { |
| 378 | if (attemptedMigrationGenerations.get(environmentId) === generation) continue; |
| 379 | const patch = modelPreferencesMigrationPatch(settings, clientSettingsSnapshot); |
| 380 | if (!patch) continue; |
| 381 | attemptedMigrationGenerations.set(environmentId, generation); |
| 382 | void runAtomCommand( |
| 383 | appAtomRegistry, |
| 384 | serverEnvironment.updateSettings, |
| 385 | { environmentId, input: { patch } }, |
| 386 | { reportFailure: false }, |
| 387 | ); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | /** Moves this client's legacy model preferences onto each server, once per connection. */ |
| 392 | export function startModelPreferencesMigration(): () => void { |
| 393 | const unsubscribes = [ |
| 394 | appAtomRegistry.subscribe(modelPreferencesMigrationTargetsAtom, migrateModelPreferences), |
| 395 | subscribeClientSettings(migrateModelPreferences), |
| 396 | subscribeClientSettingsHydration(migrateModelPreferences), |
| 397 | ]; |
| 398 | migrateModelPreferences(); |
| 399 | return () => { |
| 400 | for (const unsubscribe of unsubscribes) unsubscribe(); |
| 401 | }; |
| 402 | } |
| 403 | |
| 404 | export function useMergedSettings<T = UnifiedSettings>( |
| 405 | serverSettings: ServerSettings, |
| 406 | selector?: (settings: UnifiedSettings) => T, |
| 407 | ): T { |
| 408 | return useClientSettings((clientSettings) => { |
| 409 | const merged = mergeEnvironmentSettings(serverSettings, clientSettings); |
| 410 | return selector ? selector(merged) : (merged as T); |
| 411 | }); |
| 412 | } |
| 413 | |
| 414 | function resolveEnvironmentIdentificationMode(input: { |
| 415 | mode: EnvironmentIdentificationMode; |
| 416 | settingsHydrated: boolean; |
| 417 | paletteThemeActive?: boolean; |
| 418 | paletteThemeAllowsArtwork?: boolean; |
| 419 | }): EnvironmentIdentificationMode { |
| 420 | if (!input.settingsHydrated) return "none"; |
| 421 | const isArtwork = input.mode !== "pill" && input.mode !== "none"; |
| 422 | return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && isArtwork |
| 423 | ? "pill" |
| 424 | : input.mode; |
| 425 | } |
| 426 | |
| 427 | export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode { |
| 428 | const settingsHydrated = useClientSettingsHydrated(); |
| 429 | const mode = useClientSettings((settings) => settings.environmentIdentificationMode); |
| 430 | const { resolvedTheme, theme, themeHalves } = useTheme(); |
| 431 | const previewSidebarArtwork = useSyncExternalStore( |
| 432 | subscribeToThemePreview, |
| 433 | getThemePreviewSidebarArtwork, |
| 434 | () => null, |
| 435 | ); |
| 436 | const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme); |
| 437 | const activeThemeDefinition = getThemeDefinition(activeTheme); |
| 438 | return resolveEnvironmentIdentificationMode({ |
| 439 | mode, |
| 440 | settingsHydrated, |
| 441 | paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null, |
| 442 | paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme), |
| 443 | }); |
| 444 | } |
| 445 | |
| 446 | export async function prepareModelPreferencesPatch( |
| 447 | settings: ServerSettings, |
| 448 | patch: ServerSettingsPatch, |
| 449 | ): Promise<ServerSettingsPatch> { |
| 450 | if (settings.favorites === null || settings.providerModelPreferences === null) { |
| 451 | await ensureClientSettingsHydrated(); |
| 452 | } |
| 453 | return { ...modelPreferencesMigrationPatch(settings, getClientSettings()), ...patch }; |
| 454 | } |
| 455 | |
| 456 | export function useUpdateEnvironmentModelPreferences(environmentId: EnvironmentId | null) { |
| 457 | const settings = useAtomValue( |
| 458 | environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom, |
| 459 | ); |
| 460 | const save = useAtomCommand(serverEnvironment.updateSettings, "model preferences update"); |
| 461 | return async (patch: ServerSettingsPatch) => { |
| 462 | if (!environmentId || !settings) return; |
| 463 | let prepared: ServerSettingsPatch; |
| 464 | try { |
| 465 | prepared = await prepareModelPreferencesPatch(settings, patch); |
| 466 | } catch { |
| 467 | toastManager.add({ |
| 468 | type: "error", |
| 469 | title: m(msg("Model preferences not saved")), |
| 470 | description: m(msg("Could not load saved model preferences. Try again.")), |
| 471 | }); |
| 472 | return; |
| 473 | } |
| 474 | return save({ environmentId, input: { patch: prepared } }); |
| 475 | }; |
| 476 | } |
| 477 | |
| 478 | /** Send the desired state so two clients adding a favorite do not cancel each other. */ |
| 479 | export function useToggleEnvironmentModelFavorite(environmentId: EnvironmentId | null) { |
| 480 | const registry = use(RegistryContext); |
| 481 | const pendingFavorites = useRef( |
| 482 | new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(), |
| 483 | ); |
| 484 | const save = useUpdateEnvironmentModelPreferences(environmentId); |
| 485 | return async (provider: ProviderInstanceId, model: string) => { |
| 486 | if (!environmentId) return; |
| 487 | const settingsAtom = serverEnvironment.settingsValueAtom(environmentId); |
| 488 | const settings = registry.get(settingsAtom); |
| 489 | if (!settings) return; |
| 490 | if (settings.favorites === null) { |
| 491 | try { |
| 492 | await ensureClientSettingsHydrated(); |
| 493 | } catch { |
| 494 | toastManager.add({ |
| 495 | type: "error", |
| 496 | title: m(msg("Favorites not saved")), |
| 497 | description: m(msg("Could not load saved model preferences. Try again.")), |
| 498 | }); |
| 499 | return; |
| 500 | } |
| 501 | } |
| 502 | const currentSettings = registry.get(settingsAtom) ?? settings; |
| 503 | const favorites = resolveModelPreferences(currentSettings, getClientSettings()).favorites; |
| 504 | const key = JSON.stringify([environmentId, provider, model]); |
| 505 | const previous = pendingFavorites.current.get(key); |
| 506 | // Keep the acknowledged choice until the config stream catches up with the RPC reply. |
| 507 | const previousFavorite = |
| 508 | previous && (previous.pending || previous.settings.favorites === currentSettings.favorites) |
| 509 | ? previous.favorite |
| 510 | : favorites.some((favorite) => favorite.provider === provider && favorite.model === model); |
| 511 | const pending = { |
| 512 | favorite: !previousFavorite, |
| 513 | settings: currentSettings, |
| 514 | pending: true, |
| 515 | }; |
| 516 | pendingFavorites.current.set(key, pending); |
| 517 | const result = await save({ |
| 518 | setModelFavorites: [{ provider, model, favorite: pending.favorite }], |
| 519 | }); |
| 520 | if ( |
| 521 | result && |
| 522 | AsyncResult.isSuccess(result) && |
| 523 | registry.get(settingsAtom)?.favorites === currentSettings.favorites |
| 524 | ) { |
| 525 | pending.pending = false; |
| 526 | } |
| 527 | if (pending.pending && pendingFavorites.current.get(key) === pending) { |
| 528 | if ( |
| 529 | previous && |
| 530 | !previous.pending && |
| 531 | registry.get(settingsAtom)?.favorites === previous.settings.favorites |
| 532 | ) { |
| 533 | pendingFavorites.current.set(key, previous); |
| 534 | } else { |
| 535 | pendingFavorites.current.delete(key); |
| 536 | } |
| 537 | } |
| 538 | }; |
| 539 | } |
| 540 | |
| 541 | const noEnvironmentSettingsAtom = Atom.make<ServerSettings | null>(null); |
| 542 | |
| 543 | export function useEnvironmentModelPreferences(environmentId: EnvironmentId | null) { |
| 544 | const settings = useAtomValue( |
| 545 | environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom, |
| 546 | ); |
| 547 | const legacy = useClientSettings(selectLegacyModelPreferences); |
| 548 | return resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy); |
| 549 | } |
| 550 | |
| 551 | export function useEnvironmentSettings<T = UnifiedSettings>( |
| 552 | environmentId: EnvironmentId, |
| 553 | selector?: (settings: UnifiedSettings) => T, |
| 554 | ): T { |
| 555 | const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId)); |
| 556 | return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector); |
| 557 | } |
| 558 | |
| 559 | export function usePersistEnvironmentProviderInstanceMutation(environmentId: EnvironmentId) { |
| 560 | const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, { |
| 561 | reportFailure: false, |
| 562 | }); |
| 563 | return (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) => |
| 564 | mutateProviderInstance({ |
| 565 | environmentId, |
| 566 | input: { patch, providerInstanceMutation }, |
| 567 | }); |
| 568 | } |
| 569 | |
| 570 | export function usePrimarySettings<T = UnifiedSettings>( |
| 571 | selector?: (settings: UnifiedSettings) => T, |
| 572 | ): T { |
| 573 | const settings = useAtomValue(primaryServerSettingsAtom); |
| 574 | return useMergedSettings(settings, selector); |
| 575 | } |
| 576 | |
| 577 | export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE = msg( |
| 578 | "This setting is saved on a server, and the hosted app is not anchored to one. Change it from the desktop app or from the server's own address.", |
| 579 | ); |
| 580 | |
| 581 | /** Hosted clients have no primary: usePrimarySettings reads defaults and cannot write. */ |
| 582 | export function usePrimarySettingsAvailable(): boolean { |
| 583 | const primaryEnvironment = usePrimaryEnvironment(); |
| 584 | return primaryEnvironment !== null || !isHostedStaticApp(); |
| 585 | } |
| 586 | |
| 587 | function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> { |
| 588 | const { environments } = useEnvironments(); |
| 589 | const targetIds = environments |
| 590 | .filter(supportsSharedSettingsSync) |
| 591 | .map(({ environmentId }) => environmentId); |
| 592 | const results = useAtomValue(environmentSessionStatesAtom(environmentIdsKey(targetIds))); |
| 593 | return targetIds.flatMap((environmentId, index) => { |
| 594 | const result = results[index]!; |
| 595 | // Let the server authorize shared edits with cold grants; suggestions still need confirmed grants. |
| 596 | if (includePending && result._tag === "Initial") { |
| 597 | return [environmentId]; |
| 598 | } |
| 599 | const session = result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null); |
| 600 | return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope) |
| 601 | ? [environmentId] |
| 602 | : []; |
| 603 | }); |
| 604 | } |
| 605 | |
| 606 | function deniedSettingsDescription(environmentLabel: string | null | undefined): string { |
| 607 | return environmentLabel == null |
| 608 | ? m(msg("This connection lacks permission to change settings on the selected environment.")) |
| 609 | : m( |
| 610 | msg("This connection lacks permission to change settings on {environments}.", { |
| 611 | environments: environmentLabel, |
| 612 | }), |
| 613 | ); |
| 614 | } |
| 615 | |
| 616 | function useUpdateSettingsTarget(environmentId: EnvironmentId | null) { |
| 617 | useEnvironmentScope(environmentId, AuthSettingsWriteScope); |
| 618 | const persist = useAtomCommand(serverEnvironment.updateSettings, { |
| 619 | label: "server settings update", |
| 620 | reportFailure: false, |
| 621 | }); |
| 622 | const { environments } = useEnvironments(); |
| 623 | const persistServerSettings = async ( |
| 624 | request: Parameters<typeof persist>[0], |
| 625 | onFailed?: () => void, |
| 626 | ) => { |
| 627 | const result = await persist(request); |
| 628 | if (result._tag === "Failure") onFailed?.(); |
| 629 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 630 | const label = |
| 631 | environments.find((environment) => environment.environmentId === request.environmentId) |
| 632 | ?.label ?? request.environmentId; |
| 633 | const error = squashAtomCommandFailure(result); |
| 634 | toastManager.add({ |
| 635 | type: "error", |
| 636 | title: m(msg("Setting not saved")), |
| 637 | description: m( |
| 638 | msg("Could not save on {label}: {error}", { |
| 639 | label, |
| 640 | error: |
| 641 | (error instanceof Error ? thrownErrorMessage(error, m) : null) ?? |
| 642 | m(msg("The save failed. Try reconnecting and saving again.")), |
| 643 | }), |
| 644 | ), |
| 645 | }); |
| 646 | } |
| 647 | return result; |
| 648 | }; |
| 649 | const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true); |
| 650 | const updateSettings = ( |
| 651 | patch: UnifiedSettingsPatch, |
| 652 | options?: { readonly onFailed?: () => void; readonly onSaved?: () => void }, |
| 653 | ) => { |
| 654 | const { serverPatch, clientPatch } = splitPatch(patch); |
| 655 | |
| 656 | const canWriteServerPatch = |
| 657 | environmentId === null || |
| 658 | requiredScopesForServerSettingsPatch(serverPatch).every((scope) => |
| 659 | readEnvironmentScope(environmentId, scope), |
| 660 | ); |
| 661 | if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) { |
| 662 | options?.onFailed?.(); |
| 663 | toastManager.add({ |
| 664 | type: "warning", |
| 665 | title: m(msg("Setting not saved")), |
| 666 | description: deniedSettingsDescription( |
| 667 | environments.find((target) => target.environmentId === environmentId)?.label, |
| 668 | ), |
| 669 | }); |
| 670 | } |
| 671 | if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) { |
| 672 | const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch); |
| 673 | // Dropping the write silently leaves the control looking saved. |
| 674 | const warnUnsaved = (description = m(PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE)) => { |
| 675 | options?.onFailed?.(); |
| 676 | return toastManager.add({ |
| 677 | type: "warning", |
| 678 | title: m(msg("Setting not saved")), |
| 679 | description, |
| 680 | }); |
| 681 | }; |
| 682 | if (Object.keys(localPatch).length > 0) { |
| 683 | if (environmentId) { |
| 684 | void persistServerSettings( |
| 685 | { environmentId, input: { patch: localPatch } }, |
| 686 | options?.onFailed, |
| 687 | ).then((result) => { |
| 688 | if (result._tag === "Success") options?.onSaved?.(); |
| 689 | }); |
| 690 | } else { |
| 691 | warnUnsaved(); |
| 692 | } |
| 693 | } |
| 694 | if (Object.keys(sharedPatch).length > 0) { |
| 695 | const sourceSettings = environments.find((target) => target.environmentId === environmentId) |
| 696 | ?.serverConfig?.settings; |
| 697 | const targets = new Set(sharedSettingsSyncTargetIds); |
| 698 | if (environmentId) { |
| 699 | targets.add(environmentId); |
| 700 | } |
| 701 | const writes: Array<Parameters<typeof persist>[0]> = []; |
| 702 | const deniedLabels: string[] = []; |
| 703 | for (const targetId of targets) { |
| 704 | const target = environments.find((candidate) => candidate.environmentId === targetId); |
| 705 | const targetPatch = filterSharedServerPatch( |
| 706 | sharedPatch, |
| 707 | target?.serverConfig?.settings, |
| 708 | sourceSettings, |
| 709 | targetId === environmentId, |
| 710 | ); |
| 711 | if (Object.keys(targetPatch).length === 0) continue; |
| 712 | const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId)); |
| 713 | if ( |
| 714 | session._tag !== "Initial" && |
| 715 | !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) => |
| 716 | readEnvironmentScope(targetId, scope), |
| 717 | ) |
| 718 | ) { |
| 719 | deniedLabels.push(target?.label ?? targetId); |
| 720 | continue; |
| 721 | } |
| 722 | writes.push({ |
| 723 | environmentId: targetId, |
| 724 | input: { patch: targetPatch }, |
| 725 | }); |
| 726 | } |
| 727 | if (writes.length === 0) { |
| 728 | warnUnsaved( |
| 729 | deniedLabels.length > 0 |
| 730 | ? m( |
| 731 | msg("This connection lacks permission to change settings on {environments}.", { |
| 732 | environments: deniedLabels.join(", "), |
| 733 | }), |
| 734 | ) |
| 735 | : targets.size > 0 |
| 736 | ? m(msg("Update older servers to save this setting.")) |
| 737 | : undefined, |
| 738 | ); |
| 739 | } else { |
| 740 | void Promise.all( |
| 741 | writes.map(async (request) => ({ |
| 742 | label: |
| 743 | environments.find((target) => target.environmentId === request.environmentId) |
| 744 | ?.label ?? request.environmentId, |
| 745 | result: await persist(request), |
| 746 | })), |
| 747 | ).then((outcomes) => { |
| 748 | if ( |
| 749 | deniedLabels.length > 0 || |
| 750 | outcomes.some(({ result }) => result._tag === "Failure") |
| 751 | ) { |
| 752 | options?.onFailed?.(); |
| 753 | } |
| 754 | const failures = outcomes.flatMap(({ label, result }) => { |
| 755 | if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return []; |
| 756 | const error = squashAtomCommandFailure(result); |
| 757 | return [ |
| 758 | m( |
| 759 | msg("Could not save on {label}: {error}", { |
| 760 | label, |
| 761 | error: |
| 762 | (error instanceof Error ? thrownErrorMessage(error, m) : null) ?? |
| 763 | m(msg("The save failed. Try reconnecting and saving again.")), |
| 764 | }), |
| 765 | ), |
| 766 | ]; |
| 767 | }); |
| 768 | if ( |
| 769 | deniedLabels.length === 0 && |
| 770 | outcomes.every(({ result }) => result._tag === "Success") |
| 771 | ) { |
| 772 | options?.onSaved?.(); |
| 773 | } |
| 774 | if (failures.length === 0) return; |
| 775 | const saved = outcomes |
| 776 | .filter(({ result }) => result._tag === "Success") |
| 777 | .map(({ label }) => label); |
| 778 | toastManager.add({ |
| 779 | type: "error", |
| 780 | title: |
| 781 | saved.length > 0 |
| 782 | ? m(msg("Setting saved on some environments")) |
| 783 | : m(msg("Setting not saved")), |
| 784 | description: [ |
| 785 | ...failures, |
| 786 | ...(saved.length > 0 |
| 787 | ? [m(msg("Saved on {environments}.", { environments: saved.join(", ") }))] |
| 788 | : []), |
| 789 | ].join("\n"), |
| 790 | }); |
| 791 | }); |
| 792 | } |
| 793 | } |
| 794 | } |
| 795 | if (Object.keys(clientPatch).length > 0) { |
| 796 | void persistClientSettingsPatch(clientPatch); |
| 797 | } |
| 798 | }; |
| 799 | |
| 800 | return updateSettings; |
| 801 | } |
| 802 | |
| 803 | export function useUpdateEnvironmentSettings(environmentId: EnvironmentId | null) { |
| 804 | return useUpdateSettingsTarget(environmentId); |
| 805 | } |
| 806 | |
| 807 | export function useUpdatePrimarySettings() { |
| 808 | return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null); |
| 809 | } |
| 810 | |
| 811 | export function updateClientSettings(patch: ClientSettingsPatch): Promise<void> { |
| 812 | return persistClientSettingsPatch(patch); |
| 813 | } |
| 814 | |
| 815 | export function __resetClientSettingsPersistenceForTests(): void { |
| 816 | clientSettingsHydrationGeneration += 1; |
| 817 | clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS; |
| 818 | clientSettingsHydrationStatus = "pending"; |
| 819 | clientSettingsHydrationPromise = null; |
| 820 | clientSettingsPersistenceQueue = Promise.resolve(); |
| 821 | deferredClientSettingsPatchCount = 0; |
| 822 | unsubscribeOtherTabClientSettings?.(); |
| 823 | unsubscribeOtherTabClientSettings = null; |
| 824 | clientSettingsListeners.clear(); |
| 825 | clientSettingsHydrationListeners.clear(); |
| 826 | } |
| 827 | |
| 828 | export function __setClientSettingsForTests(settings: ClientSettings): void { |
| 829 | clientSettingsHydrationGeneration += 1; |
| 830 | clientSettingsSnapshot = settings; |
| 831 | clientSettingsHydrationStatus = "ready"; |
| 832 | clientSettingsHydrationPromise = null; |
| 833 | } |