@devries-cameron20 / t3code-1 / commits / 7847ec9386
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): preserve queued project settings changes (#35741)

Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Alex Southwell committed Nov 14, 2026 at 18:01 UTC 7847ec93866bd8e00689e1ff0087f4ce0a67a07d
3 files changed +277 -26
apps/web/src/components/settings/scopedSettings.test.ts
+125
@@ -5,6 +5,7 @@ import {
5 ProjectId,
6 ProviderInstanceId,
7 type ServerSettings,
8 + type ServerSettingsPatch,
9 } from "@t3tools/contracts";
10 import { describe, expect, it, vi } from "vite-plus/test";
11 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
@@ -13,6 +14,7 @@ import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
14
15 import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
16 import {
17 + createScopedSettingsWriter,
18 persistScopedSettingsPatch,
19 planProjectOverridesClear,
20 planScopedSettingsClear,
@@ -565,6 +567,129 @@ describe("scoped settings writes", () => {
567 ]);
568 expect(persistServer).toHaveBeenCalledTimes(4);
569 });
570 +
571 + describe("rapid project saves on one environment", () => {
572 + const saving = (initial: ServerSettings) => {
573 + let stored = initial;
574 + const persistServer = vi.fn(async ({ input }: { input: { patch: ServerSettingsPatch } }) => {
575 + stored = applyServerSettingsPatch(stored, input.patch);
576 + return { _tag: "Success" as const, value: stored };
577 + });
578 + return { persistServer, stored: () => stored };
579 + };
580 +
581 + // regression: #18426 rapid project saves rebuilt overrides from a copy that trailed them
582 + it("keeps every edit and reset while the client's copy trails its saves", async () => {
583 + let copy: ServerSettings = {
584 + ...DEFAULT_SERVER_SETTINGS,
585 + projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } },
586 + };
587 + const host = saving(copy);
588 + // No config push arrives, so the client's copy stays as it was before the first save.
589 + const write = createScopedSettingsWriter(() => copy);
590 + const save = (plan: Parameters<typeof write>[1]) =>
591 + write([environment("Server", { settings: copy })], plan, host.persistServer, vi.fn());
592 + await Promise.all([
593 + save((current) => planScopedSettingsPatch(checkout, current, { defaultAutoPull: true })),
594 + save((current) => planScopedSettingsClear(checkout, current, ["enableAgentBrowserAccess"])),
595 + save((current) =>
596 + planScopedSettingsPatch(checkout, current, { removeAgentCreditsOnMerge: true }),
597 + ),
598 + ]);
599 + expect(host.stored().projectSettingsOverrides[projectId]).toEqual({
600 + defaultAutoPull: true,
601 + removeAgentCreditsOnMerge: true,
602 + });
603 + // The first save's push arrives late, after the newer saves have finished.
604 + copy = (await host.persistServer.mock.results[0]!.value).value;
605 + await save((current) =>
606 + planScopedSettingsPatch(checkout, current, { defaultThreadEnvMode: "worktree" }),
607 + );
608 + expect(host.stored().projectSettingsOverrides[projectId]).toEqual({
609 + defaultAutoPull: true,
610 + removeAgentCreditsOnMerge: true,
611 + defaultThreadEnvMode: "worktree",
612 + });
613 + });
614 +
615 + it.each(["remote", "previous save"] as const)(
616 + "keeps the current base when a %s push arrives during a save",
617 + async (push) => {
618 + let copy: ServerSettings = DEFAULT_SERVER_SETTINGS;
619 + const host = saving(copy);
620 + const write = createScopedSettingsWriter(() => copy);
621 + const edit = (patch: ServerSettingsPatch) =>
622 + write(
623 + [environment("Server", { settings: copy })],
624 + (current) => planScopedSettingsPatch(checkout, current, patch),
625 + host.persistServer,
626 + vi.fn(),
627 + );
628 + await edit({ defaultAutoPull: true });
629 + const previous = host.stored();
630 + const persist = host.persistServer.getMockImplementation()!;
631 + host.persistServer.mockImplementationOnce(async (request) => {
632 + const response = await persist(request);
633 + if (push === "remote") {
634 + await persist({
635 + input: {
636 + patch: {
637 + projectSettingsOverrides: {
638 + [projectId]: { enableAgentBrowserAccess: false },
639 + },
640 + },
641 + },
642 + });
643 + copy = host.stored();
644 + } else {
645 + copy = { ...previous };
646 + }
647 + return response;
648 + });
649 + await edit({ removeAgentCreditsOnMerge: true });
650 + await edit({ defaultThreadEnvMode: "worktree" });
651 + expect(host.stored().projectSettingsOverrides[projectId]).toEqual(
652 + push === "remote"
653 + ? { enableAgentBrowserAccess: false, defaultThreadEnvMode: "worktree" }
654 + : {
655 + defaultAutoPull: true,
656 + removeAgentCreditsOnMerge: true,
657 + defaultThreadEnvMode: "worktree",
658 + },
659 + );
660 + },
661 + );
662 +
663 + it("plans from a copy that changed after the last save, and saves again after a failure", async () => {
664 + let copy: ServerSettings = DEFAULT_SERVER_SETTINGS;
665 + const host = saving(copy);
666 + const write = createScopedSettingsWriter(() => copy);
667 + const edit = (patch: ServerSettingsPatch) =>
668 + write(
669 + [environment("Server", { settings: copy })],
670 + (current) => planScopedSettingsPatch(checkout, current, patch),
671 + host.persistServer,
672 + vi.fn(),
673 + );
674 + host.persistServer.mockRejectedValueOnce(new Error("Disconnected"));
675 + expect((await edit({ defaultAutoPull: true })).failedEnvironments).toMatchObject([
676 + { message: "Disconnected" },
677 + ]);
678 + expect((await edit({ defaultAutoPull: true })).savedEnvironmentCount).toBe(1);
679 + // Another client replaces the override, and its push reaches this client.
680 + await host.persistServer({
681 + input: {
682 + patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } },
683 + },
684 + });
685 + copy = host.stored();
686 + await edit({ removeAgentCreditsOnMerge: true });
687 + expect(host.stored().projectSettingsOverrides[projectId]).toEqual({
688 + enableAgentBrowserAccess: false,
689 + removeAgentCreditsOnMerge: true,
690 + });
691 + });
692 + });
693 });
694
695 describe("scoped settings mixed values", () => {
apps/web/src/components/settings/scopedSettings.ts
+130 -19
@@ -451,36 +451,147 @@ function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | un
451 );
452 }
453
454 +type ScopedSettingsPlan = ReturnType<typeof planScopedSettingsPatch>;
455 +
456 +type ScopedSettingsPersistServer = (input: {
457 + environmentId: EnvironmentId;
458 + input: { patch: ServerSettingsPatch };
459 +}) => Promise<{
460 + readonly _tag: "Success" | "Failure";
461 + readonly cause?: Cause.Cause<unknown>;
462 + readonly value?: ServerSettings;
463 +}>;
464 +
465 export async function persistScopedSettingsPatch(
455 - plan: ReturnType<typeof planScopedSettingsPatch>,
456 - persistServer: (input: {
457 - environmentId: EnvironmentId;
458 - input: { patch: ServerSettingsPatch };
459 - }) => Promise<{
460 - readonly _tag: "Success" | "Failure";
461 - readonly cause?: Cause.Cause<unknown>;
462 - readonly value?: ServerSettings;
466 + plan: ScopedSettingsPlan,
467 + persistServer: ScopedSettingsPersistServer,
468 + persistClient: (patch: ClientSettingsPatch) => void,
469 +) {
470 + return persistScopedSettingsPlan(
471 + plan,
472 + async (write) => ({
473 + write,
474 + result: await persistServer({
475 + environmentId: write.environmentId,
476 + input: { patch: write.patch },
477 + }),
478 + }),
479 + persistClient,
480 + );
481 +}
482 +
483 +const OWN_ECHO_LIMIT = 8;
484 +
485 +/**
486 + * Project overrides are whole entries built from this client's copy of the settings, and that
487 + * copy hears about a save only when the server pushes it back. So saves to one environment run
488 + * one at a time, each planned as it starts from the newest settings this client holds: the
489 + * previous save's response, unless an independently changed copy has arrived.
490 + */
491 +export function createScopedSettingsWriter(
492 + readSettings: (environmentId: EnvironmentId) => ServerSettings | null,
493 +) {
494 + const queues = new Map<EnvironmentId, Promise<unknown>>();
495 + const responses = new Map<
496 + EnvironmentId,
497 + {
498 + readonly settings: ServerSettings;
499 + readonly copy: ServerSettings;
500 + readonly saved: readonly ServerSettings[];
501 + }
502 + >();
503 + return (
504 + environments: readonly ScopedSettingsEnvironment[],
505 + plan: (environments: readonly ScopedSettingsEnvironment[]) => ScopedSettingsPlan,
506 + persistServer: ScopedSettingsPersistServer,
507 + persistClient: (patch: ClientSettingsPatch) => void,
508 + ) =>
509 + persistScopedSettingsPlan(
510 + plan(environments),
511 + (planned) => {
512 + const { environmentId } = planned;
513 + const save = (queues.get(environmentId) ?? Promise.resolve()).then(async () => {
514 + const copy = readSettings(environmentId);
515 + const response = responses.get(environmentId);
516 + // A copy equal to one of our earlier responses is a delayed echo, older than the latest.
517 + const isOwnEcho = (settings: ServerSettings) =>
518 + response?.saved.some((saved) => Equal.equals(saved, settings)) === true;
519 + const continues =
520 + copy !== null && response !== undefined && (response.copy === copy || isOwnEcho(copy));
521 + const settings = continues ? response.settings : copy;
522 + const replanned =
523 + settings === null ? null : plan(withSettings(environments, environmentId, settings));
524 + const write =
525 + replanned?.serverWrites.find((next) => next.environmentId === environmentId) ?? planned;
526 + const result = await persistServer({ environmentId, input: { patch: write.patch } });
527 + const savedCopy = readSettings(environmentId);
528 + if (result._tag === "Success" && result.value !== undefined && savedCopy !== null) {
529 + // A changed copy may be a newer remote push or the delayed echo of our previous save.
530 + if (
531 + savedCopy === copy ||
532 + Equal.equals(savedCopy, settings) ||
533 + Equal.equals(savedCopy, result.value) ||
534 + isOwnEcho(savedCopy)
535 + ) {
536 + responses.set(environmentId, {
537 + settings: result.value,
538 + copy: savedCopy,
539 + saved: [...(continues ? response.saved : []), result.value].slice(-OWN_ECHO_LIMIT),
540 + });
541 + } else {
542 + responses.delete(environmentId);
543 + }
544 + }
545 + return { write, result };
546 + });
547 + queues.set(
548 + environmentId,
549 + save.catch(() => undefined),
550 + );
551 + return save;
552 + },
553 + persistClient,
554 + );
555 +}
556 +
557 +function withSettings(
558 + environments: readonly ScopedSettingsEnvironment[],
559 + environmentId: EnvironmentId,
560 + settings: ServerSettings,
561 +) {
562 + return environments.map((environment) =>
563 + environment.environmentId === environmentId && environment.serverConfig
564 + ? { ...environment, serverConfig: { ...environment.serverConfig, settings } }
565 + : environment,
566 + );
567 +}
568 +
569 +async function persistScopedSettingsPlan(
570 + plan: ScopedSettingsPlan,
571 + persistWrite: (write: ScopedServerWrite) => Promise<{
572 + readonly write: ScopedServerWrite;
573 + readonly result: Awaited<ReturnType<ScopedSettingsPersistServer>>;
574 }>,
575 persistClient: (patch: ClientSettingsPatch) => void,
576 ) {
577 if (plan.hasClientWrite) persistClient(plan.clientPatch);
467 - const results = await Promise.allSettled(
468 - plan.serverWrites.map(({ environmentId, patch }) =>
469 - persistServer({ environmentId, input: { patch } }),
470 - ),
578 + const results = await Promise.allSettled(plan.serverWrites.map(persistWrite));
579 + // A queued write is replanned before it is sent, so judge the write that was sent.
580 + const writes = results.map((result, index) =>
581 + result.status === "fulfilled" ? result.value.write : plan.serverWrites[index]!,
582 );
583 const saved = (index: number) => {
584 const result = results[index];
585 return (
586 result?.status === "fulfilled" &&
476 - result.value._tag === "Success" &&
477 - droppedSettingKeys(plan.serverWrites[index]!, result.value.value).length === 0
587 + result.value.result._tag === "Success" &&
588 + droppedSettingKeys(writes[index]!, result.value.result.value).length === 0
589 );
590 };
480 - const failedEnvironments = plan.serverWrites.flatMap((environment, index) => {
591 + const failedEnvironments = writes.flatMap((environment, index) => {
592 if (saved(index)) return [];
593 const result = results[index];
483 - if (result?.status === "fulfilled" && result.value._tag === "Success") {
594 + if (result?.status === "fulfilled" && result.value.result._tag === "Success") {
595 return [
596 {
597 ...environment,
@@ -491,8 +602,8 @@ export async function persistScopedSettingsPatch(
602 const error: unknown =
603 result?.status === "rejected"
604 ? result.reason
494 - : result?.status === "fulfilled" && result.value.cause
495 - ? Cause.squash(result.value.cause)
605 + : result?.status === "fulfilled" && result.value.result.cause
606 + ? Cause.squash(result.value.result.cause)
607 : undefined;
608 return [
609 {
@@ -504,7 +615,7 @@ export async function persistScopedSettingsPatch(
615 },
616 ];
617 });
507 - const savedEnvironments = plan.serverWrites.filter((_, index) => saved(index));
618 + const savedEnvironments = writes.filter((_, index) => saved(index));
619 return {
620 failedEnvironments,
621 savedEnvironments,
apps/web/src/components/settings/useScopedSettings.ts
+22 -7
@@ -15,12 +15,13 @@ import {
15 } from "@t3tools/contracts";
16
17 import { persistClientSettingsPatch, useMergedSettings } from "../../hooks/useSettings";
18 +import { readEnvironment } from "../../state/environments";
19 import { serverEnvironment } from "../../state/server";
20 import { useAtomCommand } from "../../state/use-atom-command";
21 import { toastManager } from "../ui/toast";
22 import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
23 import {
23 - persistScopedSettingsPatch,
24 + createScopedSettingsWriter,
25 planProjectOverridesClear,
26 planScopedSettingsClear,
27 planScopedSettingsPatch,
@@ -30,6 +31,10 @@ import {
31 type ScopedSettingsPatch,
32 } from "./scopedSettings";
33
34 +const writeScopedSettings = createScopedSettingsWriter(
35 + (environmentId) => readEnvironment(environmentId)?.serverConfig?.settings ?? null,
36 +);
37 +
38 export function useScopedSettings<T = UnifiedSettings>(
39 selector?: (settings: UnifiedSettings) => T,
40 ): T {
@@ -49,7 +54,12 @@ export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[])
54
55 function useRunScopedPlan() {
56 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
52 - return (plan: ReturnType<typeof planScopedSettingsPatch>, onFailed?: () => void) => {
57 + return (
58 + environments: Parameters<typeof writeScopedSettings>[0],
59 + planner: Parameters<typeof writeScopedSettings>[1],
60 + onFailed?: () => void,
61 + ) => {
62 + const plan = planner(environments);
63 if (plan.unavailableReason) {
64 toastManager.add({
65 type: "warning",
@@ -59,8 +69,9 @@ function useRunScopedPlan() {
69 onFailed?.();
70 return;
71 }
62 - void persistScopedSettingsPatch(
63 - plan,
72 + void writeScopedSettings(
73 + environments,
74 + planner,
75 async (request) => {
76 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
77 (scope) => !readEnvironmentScope(request.environmentId, scope),
@@ -102,7 +113,11 @@ export function useUpdateScopedSettings() {
113 const run = useRunScopedPlan();
114 /** `onFailed` runs when any target rejects or drops the patch, so a draft can fall back. */
115 return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) =>
105 - run(planScopedSettingsPatch(scope, environments, patch, { deviceOnly }), options?.onFailed);
116 + run(
117 + environments,
118 + (current) => planScopedSettingsPatch(scope, current, patch, { deviceOnly }),
119 + options?.onFailed,
120 + );
121 }
122
123 export function useClearScopedSettings() {
@@ -110,7 +125,7 @@ export function useClearScopedSettings() {
125 const run = useRunScopedPlan();
126 return (keys: readonly ProjectScopedServerSettingKey[]) => {
127 if (context === null) return;
113 - run(planScopedSettingsClear(context.scope, context.environments, keys));
128 + run(context.environments, (current) => planScopedSettingsClear(context.scope, current, keys));
129 };
130 }
131
@@ -122,7 +137,7 @@ export function useClearProjectOverrides() {
137 keys: readonly ProjectScopedServerSettingKey[],
138 ) => {
139 if (context === null) return;
125 - run(planProjectOverridesClear(context.environments, entries, keys));
140 + run(context.environments, (current) => planProjectOverridesClear(current, entries, keys));
141 };
142 }
143