The best way to control Claude Code, Codex and more from any computer or phone
perf(web): settings hooks compile with the React Compiler (#20474)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 18:46 UTC
8316dfb6192596faedcb472d3aba80597efaa6ad
2 files changed
+219
-244
apps/web/reactCompiledFiles.ts
+1
@@ -49,4 +49,5 @@ export const REACT_COMPILED_FILES = [
49
"apps/web/src/components/pullRequest/PullRequestCodeTab.tsx",
50
"apps/web/src/hooks/useLocalStorage.ts",
51
"apps/web/src/hooks/useTheme.ts",
52
+ "apps/web/src/hooks/useSettings.ts",
53
] as const;
apps/web/src/hooks/useSettings.ts
+218
-244
@@ -1,4 +1,4 @@
1
-import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore, use } from "react";
1
+import { useEffect, useRef, useSyncExternalStore, use } from "react";
2
import { RegistryContext, useAtomValue } from "@effect/atom-react";
3
import {
4
DEFAULT_SERVER_SETTINGS,
@@ -330,25 +330,29 @@ export function useMigrateModelPreferences(
330
}, [clientSettings, environmentId, hydrated, migrate, settings]);
331
}
332
333
+// A hook of its own so callers passing an inline selector still get one merged
334
+// object per settings change instead of one per render.
335
+function useMergedEnvironmentSettings(
336
+ serverSettings: ServerSettings,
337
+ clientSettings: ClientSettings,
338
+): UnifiedSettings {
339
+ "use memo";
340
+ return mergeEnvironmentSettings(serverSettings, clientSettings);
341
+}
342
+
343
function useMergedSettings<T>(
344
serverSettings: ServerSettings,
345
selector: ((settings: UnifiedSettings) => T) | undefined,
346
): T {
337
- const clientSettings = useClientSettingsValue();
338
-
339
- const merged = useMemo<UnifiedSettings>(
340
- () => mergeEnvironmentSettings(serverSettings, clientSettings),
341
- [clientSettings, serverSettings],
342
- );
343
-
344
- return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
347
+ const merged = useMergedEnvironmentSettings(serverSettings, useClientSettingsValue());
348
+ return selector ? selector(merged) : (merged as T);
349
}
350
351
export function useClientSettings<T = ClientSettings>(
352
selector?: (settings: ClientSettings) => T,
353
): T {
354
const settings = useClientSettingsValue();
351
- return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
355
+ return selector ? selector(settings) : (settings as T);
356
}
357
358
export function resolveEnvironmentIdentificationMode(input: {
@@ -409,24 +413,21 @@ export function useUpdateEnvironmentModelPreferences(environmentId: EnvironmentI
413
environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
414
);
415
const save = useAtomCommand(serverEnvironment.updateSettings, "model preferences update");
412
- return useCallback(
413
- async (patch: ServerSettingsPatch) => {
414
- if (!environmentId || !settings) return;
415
- let prepared: ServerSettingsPatch;
416
- try {
417
- prepared = await prepareModelPreferencesPatch(settings, patch);
418
- } catch {
419
- toastManager.add({
420
- type: "error",
421
- title: "Model preferences not saved",
422
- description: "Could not load saved model preferences. Try again.",
423
- });
424
- return;
425
- }
426
- return save({ environmentId, input: { patch: prepared } });
427
- },
428
- [environmentId, save, settings],
429
- );
416
+ return async (patch: ServerSettingsPatch) => {
417
+ if (!environmentId || !settings) return;
418
+ let prepared: ServerSettingsPatch;
419
+ try {
420
+ prepared = await prepareModelPreferencesPatch(settings, patch);
421
+ } catch {
422
+ toastManager.add({
423
+ type: "error",
424
+ title: "Model preferences not saved",
425
+ description: "Could not load saved model preferences. Try again.",
426
+ });
427
+ return;
428
+ }
429
+ return save({ environmentId, input: { patch: prepared } });
430
+ };
431
}
432
433
/** Send the desired state so two clients adding a favorite do not cancel each other. */
@@ -436,68 +437,61 @@ export function useToggleEnvironmentModelFavorite(environmentId: EnvironmentId |
437
new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(),
438
);
439
const save = useUpdateEnvironmentModelPreferences(environmentId);
439
- return useCallback(
440
- async (provider: ProviderInstanceId, model: string) => {
441
- if (!environmentId) return;
442
- const settingsAtom = serverEnvironment.settingsValueAtom(environmentId);
443
- const settings = registry.get(settingsAtom);
444
- if (!settings) return;
445
- if (settings.favorites === null) {
446
- try {
447
- await ensureClientSettingsHydrated();
448
- } catch {
449
- toastManager.add({
450
- type: "error",
451
- title: "Favorites not saved",
452
- description: "Could not load saved model preferences. Try again.",
453
- });
454
- return;
455
- }
456
- }
457
- const currentSettings = registry.get(settingsAtom) ?? settings;
458
- const favorites = resolveModelPreferences(currentSettings, getClientSettings()).favorites;
459
- const key = JSON.stringify([environmentId, provider, model]);
460
- const previous = pendingFavorites.current.get(key);
461
- // Keep the acknowledged choice until the config stream catches up with the RPC reply.
462
- const previousFavorite =
463
- previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
464
- ? previous.favorite
465
- : favorites.some(
466
- (favorite) => favorite.provider === provider && favorite.model === model,
467
- );
468
- const pending = {
469
- favorite: !previousFavorite,
470
- settings: currentSettings,
471
- pending: true,
472
- };
473
- pendingFavorites.current.set(key, pending);
440
+ return async (provider: ProviderInstanceId, model: string) => {
441
+ if (!environmentId) return;
442
+ const settingsAtom = serverEnvironment.settingsValueAtom(environmentId);
443
+ const settings = registry.get(settingsAtom);
444
+ if (!settings) return;
445
+ if (settings.favorites === null) {
446
try {
475
- const result = await save({
476
- setModelFavorites: [{ provider, model, favorite: pending.favorite }],
447
+ await ensureClientSettingsHydrated();
448
+ } catch {
449
+ toastManager.add({
450
+ type: "error",
451
+ title: "Favorites not saved",
452
+ description: "Could not load saved model preferences. Try again.",
453
});
478
- if (
479
- result &&
480
- AsyncResult.isSuccess(result) &&
481
- registry.get(settingsAtom)?.favorites === currentSettings.favorites
482
- ) {
483
- pending.pending = false;
484
- }
485
- } finally {
486
- if (pending.pending && pendingFavorites.current.get(key) === pending) {
487
- if (
488
- previous &&
489
- !previous.pending &&
490
- registry.get(settingsAtom)?.favorites === previous.settings.favorites
491
- ) {
492
- pendingFavorites.current.set(key, previous);
493
- } else {
494
- pendingFavorites.current.delete(key);
495
- }
496
- }
454
+ return;
455
}
498
- },
499
- [environmentId, registry, save],
500
- );
456
+ }
457
+ const currentSettings = registry.get(settingsAtom) ?? settings;
458
+ const favorites = resolveModelPreferences(currentSettings, getClientSettings()).favorites;
459
+ const key = JSON.stringify([environmentId, provider, model]);
460
+ const previous = pendingFavorites.current.get(key);
461
+ // Keep the acknowledged choice until the config stream catches up with the RPC reply.
462
+ const previousFavorite =
463
+ previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
464
+ ? previous.favorite
465
+ : favorites.some((favorite) => favorite.provider === provider && favorite.model === model);
466
+ const pending = {
467
+ favorite: !previousFavorite,
468
+ settings: currentSettings,
469
+ pending: true,
470
+ };
471
+ pendingFavorites.current.set(key, pending);
472
+ // save settles into a result and never rejects, so the rollback below always runs.
473
+ const result = await save({
474
+ setModelFavorites: [{ provider, model, favorite: pending.favorite }],
475
+ });
476
+ if (
477
+ result &&
478
+ AsyncResult.isSuccess(result) &&
479
+ registry.get(settingsAtom)?.favorites === currentSettings.favorites
480
+ ) {
481
+ pending.pending = false;
482
+ }
483
+ if (pending.pending && pendingFavorites.current.get(key) === pending) {
484
+ if (
485
+ previous &&
486
+ !previous.pending &&
487
+ registry.get(settingsAtom)?.favorites === previous.settings.favorites
488
+ ) {
489
+ pendingFavorites.current.set(key, previous);
490
+ } else {
491
+ pendingFavorites.current.delete(key);
492
+ }
493
+ }
494
+ };
495
}
496
497
const noEnvironmentSettingsAtom = Atom.make<ServerSettings | null>(null);
@@ -508,10 +502,7 @@ export function useEnvironmentModelPreferences(environmentId: EnvironmentId | nu
502
);
503
const legacy = useClientSettingsValue();
504
useMigrateModelPreferences(environmentId, settings);
511
- return useMemo(
512
- () => resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy),
513
- [legacy, settings],
514
- );
505
+ return resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy);
506
}
507
508
export function useEnvironmentSettings<T = UnifiedSettings>(
@@ -527,14 +518,11 @@ export function usePersistEnvironmentProviderInstanceMutation(environmentId: Env
518
const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
519
reportFailure: false,
520
});
530
- return useCallback(
531
- (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) =>
532
- mutateProviderInstance({
533
- environmentId,
534
- input: { patch, providerInstanceMutation },
535
- }),
536
- [environmentId, mutateProviderInstance],
537
- );
521
+ return (providerInstanceMutation: ProviderInstanceMutation, patch: ServerSettingsPatch = {}) =>
522
+ mutateProviderInstance({
523
+ environmentId,
524
+ input: { patch, providerInstanceMutation },
525
+ });
526
}
527
528
export function usePrimarySettings<T = UnifiedSettings>(
@@ -564,24 +552,20 @@ export function usePrimarySettingsAvailable(): boolean {
552
553
function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<EnvironmentId> {
554
const { environments } = useEnvironments();
567
- const writableTargetsAtom = useMemo(
568
- () =>
569
- Atom.make((get) =>
570
- environments.filter(supportsSharedSettingsSync).flatMap((environment) => {
571
- const result = get(environmentSession.sessionStateAtom(environment.environmentId));
572
- // A cold grant must not drop a shared edit. The server authorizes the
573
- // write; mismatch suggestions still wait for a confirmed grant.
574
- if (includePending && result._tag === "Initial") {
575
- return [environment.environmentId];
576
- }
577
- const session =
578
- result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
579
- return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
580
- ? [environment.environmentId]
581
- : [];
582
- }),
583
- ),
584
- [environments, includePending],
555
+ const writableTargetsAtom = Atom.make((get) =>
556
+ environments.filter(supportsSharedSettingsSync).flatMap((environment) => {
557
+ const result = get(environmentSession.sessionStateAtom(environment.environmentId));
558
+ // A cold grant must not drop a shared edit. The server authorizes the
559
+ // write; mismatch suggestions still wait for a confirmed grant.
560
+ if (includePending && result._tag === "Initial") {
561
+ return [environment.environmentId];
562
+ }
563
+ const session =
564
+ result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
565
+ return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
566
+ ? [environment.environmentId]
567
+ : [];
568
+ }),
569
);
570
return useAtomValue(writableTargetsAtom);
571
}
@@ -593,142 +577,134 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
577
reportFailure: false,
578
});
579
const { environments } = useEnvironments();
596
- const persistServerSettings = useCallback(
597
- async (request: Parameters<typeof persist>[0]) => {
598
- const result = await persist(request);
599
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
600
- const label =
601
- environments.find((environment) => environment.environmentId === request.environmentId)
602
- ?.label ?? request.environmentId;
603
- const error = squashAtomCommandFailure(result);
604
- toastManager.add({
605
- type: "error",
606
- title: "Setting not saved",
607
- description: `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
608
- });
609
- }
610
- return result;
611
- },
612
- [environments, persist],
613
- );
580
+ const persistServerSettings = async (request: Parameters<typeof persist>[0]) => {
581
+ const result = await persist(request);
582
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
583
+ const label =
584
+ environments.find((environment) => environment.environmentId === request.environmentId)
585
+ ?.label ?? request.environmentId;
586
+ const error = squashAtomCommandFailure(result);
587
+ toastManager.add({
588
+ type: "error",
589
+ title: "Setting not saved",
590
+ description: `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
591
+ });
592
+ }
593
+ return result;
594
+ };
595
const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);
615
- const updateSettings = useCallback(
616
- (patch: UnifiedSettingsPatch) => {
617
- const { serverPatch, clientPatch } = splitPatch(patch);
618
-
619
- const canWriteServerPatch =
620
- environmentId === null ||
621
- requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
622
- readEnvironmentScope(environmentId, scope),
623
- );
624
- if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {
596
+ const updateSettings = (patch: UnifiedSettingsPatch) => {
597
+ const { serverPatch, clientPatch } = splitPatch(patch);
598
+
599
+ const canWriteServerPatch =
600
+ environmentId === null ||
601
+ requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
602
+ readEnvironmentScope(environmentId, scope),
603
+ );
604
+ if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {
605
+ toastManager.add({
606
+ type: "warning",
607
+ title: "Setting not saved",
608
+ description: `This connection lacks permission to change settings on ${environments.find((target) => target.environmentId === environmentId)?.label ?? "the selected environment"}.`,
609
+ });
610
+ }
611
+ if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {
612
+ const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
613
+ // Dropping the write silently leaves the control looking saved.
614
+ const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>
615
toastManager.add({
616
type: "warning",
617
title: "Setting not saved",
628
- description: `This connection lacks permission to change settings on ${environments.find((target) => target.environmentId === environmentId)?.label ?? "the selected environment"}.`,
618
+ description,
619
});
630
- }
631
- if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {
632
- const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
633
- // Dropping the write silently leaves the control looking saved.
634
- const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>
635
- toastManager.add({
636
- type: "warning",
637
- title: "Setting not saved",
638
- description,
620
+ if (Object.keys(localPatch).length > 0) {
621
+ if (environmentId) {
622
+ void persistServerSettings({
623
+ environmentId,
624
+ input: { patch: localPatch },
625
});
640
- if (Object.keys(localPatch).length > 0) {
641
- if (environmentId) {
642
- void persistServerSettings({
643
- environmentId,
644
- input: { patch: localPatch },
645
- });
646
- } else {
647
- warnUnsaved();
648
- }
626
+ } else {
627
+ warnUnsaved();
628
}
650
- if (Object.keys(sharedPatch).length > 0) {
651
- const sourceSettings = environments.find(
652
- (target) => target.environmentId === environmentId,
653
- )?.serverConfig?.settings;
654
- const targets = new Set(sharedSettingsSyncTargetIds);
655
- if (environmentId) {
656
- targets.add(environmentId);
629
+ }
630
+ if (Object.keys(sharedPatch).length > 0) {
631
+ const sourceSettings = environments.find((target) => target.environmentId === environmentId)
632
+ ?.serverConfig?.settings;
633
+ const targets = new Set(sharedSettingsSyncTargetIds);
634
+ if (environmentId) {
635
+ targets.add(environmentId);
636
+ }
637
+ const writes: Array<Parameters<typeof persist>[0]> = [];
638
+ const deniedLabels: string[] = [];
639
+ for (const targetId of targets) {
640
+ const target = environments.find((candidate) => candidate.environmentId === targetId);
641
+ const targetPatch = filterSharedServerPatch(
642
+ sharedPatch,
643
+ target?.serverConfig?.environment.capabilities,
644
+ target?.serverConfig?.settings,
645
+ sourceSettings,
646
+ targetId === environmentId,
647
+ );
648
+ if (Object.keys(targetPatch).length === 0) continue;
649
+ const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));
650
+ if (
651
+ session._tag !== "Initial" &&
652
+ !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>
653
+ readEnvironmentScope(targetId, scope),
654
+ )
655
+ ) {
656
+ deniedLabels.push(target?.label ?? targetId);
657
+ continue;
658
}
658
- const writes: Array<Parameters<typeof persist>[0]> = [];
659
- const deniedLabels: string[] = [];
660
- for (const targetId of targets) {
661
- const target = environments.find((candidate) => candidate.environmentId === targetId);
662
- const targetPatch = filterSharedServerPatch(
663
- sharedPatch,
664
- target?.serverConfig?.environment.capabilities,
665
- target?.serverConfig?.settings,
666
- sourceSettings,
667
- targetId === environmentId,
668
- );
669
- if (Object.keys(targetPatch).length === 0) continue;
670
- const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));
671
- if (
672
- session._tag !== "Initial" &&
673
- !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>
674
- readEnvironmentScope(targetId, scope),
675
- )
676
- ) {
677
- deniedLabels.push(target?.label ?? targetId);
678
- continue;
679
- }
680
- writes.push({
681
- environmentId: targetId,
682
- input: { patch: targetPatch },
659
+ writes.push({
660
+ environmentId: targetId,
661
+ input: { patch: targetPatch },
662
+ });
663
+ }
664
+ if (writes.length === 0) {
665
+ warnUnsaved(
666
+ deniedLabels.length > 0
667
+ ? `This connection lacks permission to change settings on ${deniedLabels.join(", ")}.`
668
+ : targets.size > 0
669
+ ? "Update older servers to save this setting."
670
+ : undefined,
671
+ );
672
+ } else {
673
+ void Promise.all(
674
+ writes.map(async (request) => ({
675
+ label:
676
+ environments.find((target) => target.environmentId === request.environmentId)
677
+ ?.label ?? request.environmentId,
678
+ result: await persist(request),
679
+ })),
680
+ ).then((outcomes) => {
681
+ const failures = outcomes.flatMap(({ label, result }) => {
682
+ if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];
683
+ const error = squashAtomCommandFailure(result);
684
+ return [
685
+ `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
686
+ ];
687
});
684
- }
685
- if (writes.length === 0) {
686
- warnUnsaved(
687
- deniedLabels.length > 0
688
- ? `This connection lacks permission to change settings on ${deniedLabels.join(", ")}.`
689
- : targets.size > 0
690
- ? "Update older servers to save this setting."
691
- : undefined,
692
- );
693
- } else {
694
- void Promise.all(
695
- writes.map(async (request) => ({
696
- label:
697
- environments.find((target) => target.environmentId === request.environmentId)
698
- ?.label ?? request.environmentId,
699
- result: await persist(request),
700
- })),
701
- ).then((outcomes) => {
702
- const failures = outcomes.flatMap(({ label, result }) => {
703
- if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];
704
- const error = squashAtomCommandFailure(result);
705
- return [
706
- `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
707
- ];
708
- });
709
- if (failures.length === 0) return;
710
- const saved = outcomes
711
- .filter(({ result }) => result._tag === "Success")
712
- .map(({ label }) => label);
713
- toastManager.add({
714
- type: "error",
715
- title:
716
- saved.length > 0 ? "Setting saved on some environments" : "Setting not saved",
717
- description: [
718
- ...failures,
719
- ...(saved.length > 0 ? [`Saved on ${saved.join(", ")}.`] : []),
720
- ].join("\n"),
721
- });
688
+ if (failures.length === 0) return;
689
+ const saved = outcomes
690
+ .filter(({ result }) => result._tag === "Success")
691
+ .map(({ label }) => label);
692
+ toastManager.add({
693
+ type: "error",
694
+ title: saved.length > 0 ? "Setting saved on some environments" : "Setting not saved",
695
+ description: [
696
+ ...failures,
697
+ ...(saved.length > 0 ? [`Saved on ${saved.join(", ")}.`] : []),
698
+ ].join("\n"),
699
});
723
- }
700
+ });
701
}
702
}
726
- if (Object.keys(clientPatch).length > 0) {
727
- void persistClientSettingsPatch(clientPatch);
728
- }
729
- },
730
- [environmentId, environments, persist, persistServerSettings, sharedSettingsSyncTargetIds],
731
- );
703
+ }
704
+ if (Object.keys(clientPatch).length > 0) {
705
+ void persistClientSettingsPatch(clientPatch);
706
+ }
707
+ };
708
709
return updateSettings;
710
}
@@ -742,9 +718,7 @@ export function useUpdatePrimarySettings() {
718
}
719
720
export function useUpdateClientSettings() {
745
- return useCallback((patch: ClientSettingsPatch) => {
746
- return persistClientSettingsPatch(patch);
747
- }, []);
721
+ return (patch: ClientSettingsPatch) => persistClientSettingsPatch(patch);
722
}
723
724
export function __resetClientSettingsPersistenceForTests(): void {