Skip to content
TypeScript

fix(mobile): report rejected shared settings writes (#9356)

Julius Marmingef7a23f07894d
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
index df933f727b3..b8222511374 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
@@ -1,5 +1,7 @@
// @vitest-environment jsdom
import { DEFAULT_SERVER_SETTINGS, type ServerSettingsPatch } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import { AsyncResult } from "effect/reactivity";
import type { ReactNode } from "react";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
@@ -10,15 +12,45 @@ const { Children, mocks } = vi.hoisted(() => ({
mocks: {
branchNaming: { onChange: (_patch: ServerSettingsPatch) => {} },
updateSettings: vi.fn(),
+ alert: vi.fn(),
+ targets: [] as ReturnType<typeof environment>[],
+ projectSelected: false,
},
}));
-vi.mock("react-native", () => ({ View: Children }));
+vi.mock("react-native", () => ({
+ View: Children,
+ Alert: { alert: mocks.alert },
+ Pressable: ({
+ children,
+ disabled,
+ onPress,
+ accessibilityLabel,
+ }: {
+ children?: ReactNode;
+ disabled?: boolean;
+ onPress: () => void;
+ accessibilityLabel?: string;
+ }) => (
+ <button disabled={disabled} onClick={onPress} aria-label={accessibilityLabel}>
+ {children}
+ </button>
+ ),
+}));
+vi.mock("@effect/atom-react", () => ({
+ useAtomValue: () => AsyncResult.success({}),
+ useAtomSet: () => () => {},
+}));
+vi.mock("../../state/preferences", () => ({
+ mobilePreferencesAtom: {},
+ updateMobilePreferencesAtom: {},
+}));
+vi.mock("./components/AutoSettleDaysField", () => ({ AutoSettleDaysField: () => null }));
vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) }));
vi.mock("../../state/session", () => ({
readEnvironmentScope: () => true,
- useEnvironmentsWithScope: () => new Set(["local"]),
+ useEnvironmentsWithScope: () => new Set(mocks.targets.map((target) => target.environmentId)),
}));
vi.mock("../../state/server", () => ({ serverEnvironment: { updateSettings: {} } }));
vi.mock("../../state/use-atom-command", () => ({
@@ -35,11 +67,29 @@ vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({
vi.mock("./components/DatabaseStorageNotice", () => ({ DatabaseStorageNotice: () => null }));
vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children }));
vi.mock("./components/SettingsChoiceRow", () => ({ SettingsChoiceRow: () => null }));
-vi.mock("./components/SettingsSwitchRow", () => ({ SettingsSwitchRow: () => null }));
-vi.mock("./components/SettingsRow", () => ({ SettingsRow: () => null }));
-vi.mock("./components/SettingsProjectOverridesSection", () => ({
- SettingsProjectOverridesSection: () => null,
+vi.mock("./components/SettingsSwitchRow", () => ({
+ SettingsSwitchRow: ({
+ label,
+ value,
+ disabled,
+ onValueChange,
+ }: {
+ label: string;
+ value: boolean | null;
+ disabled?: boolean;
+ onValueChange: (value: boolean) => void;
+ }) => (
+ <button
+ role="switch"
+ aria-checked={value ?? "mixed"}
+ disabled={disabled}
+ onClick={() => onValueChange(!value)}
+ >
+ {label}
+ </button>
+ ),
}));
+vi.mock("./components/SettingsRow", () => ({ SettingsRow: () => null }));
vi.mock("./components/BranchNamingSettings", () => ({
BranchNamingSettings: (props: { onChange: (patch: ServerSettingsPatch) => void }) => {
mocks.branchNaming.onChange = props.onChange;
@@ -48,28 +98,85 @@ vi.mock("./components/BranchNamingSettings", () => ({
}));
vi.mock("./settings-environment-filter", () => ({
useSettingsEnvironmentFilter: () => ({
- selectedTargets: [
+ selectedTargets: mocks.targets,
+ projectGroups: [
{
- environmentId: "local",
- serverConfig: {
- settings: DEFAULT_SERVER_SETTINGS,
- environment: { capabilities: { projectSettingsOverrides: true } },
- },
+ key: "project",
+ label: "Project",
+ members: mocks.targets.map((target) => ({
+ project: { environmentId: target.environmentId, id: "project" },
+ })),
},
],
- projectGroups: [],
- selectedProjectKey: null,
+ selectedProjectKey: mocks.projectSelected ? "project" : null,
}),
}));
import { SettingsEnvironmentSourceControlRouteScreen } from "./SettingsServerControlsRouteScreen";
+import { SettingsThreadsRouteScreen } from "./SettingsThreadsRouteScreen";
+
+function environment(environmentId: string, label: string) {
+ return {
+ environmentId,
+ label,
+ connection: { phase: "connected" },
+ serverConfig: {
+ settings: {
+ ...DEFAULT_SERVER_SETTINGS,
+ defaultAutoPull: false,
+ sidebarAutoSettleOnMerge: false,
+ },
+ environment: {
+ capabilities: { projectSettingsOverrides: true, threadAutoSettlement: true },
+ },
+ },
+ };
+}
+
+function button(label: string) {
+ const result = Array.from(container.querySelectorAll("button")).find(
+ (element) => element.textContent === label || element.getAttribute("aria-label") === label,
+ );
+ if (!result) throw new Error(`Missing button: ${label}`);
+ return result;
+}
+
+function expectFailures() {
+ const messages = mocks.alert.mock.calls
+ .map(([title, message]) => `${title}\n${message}`)
+ .join("\n");
+ expect.soft(messages).toMatch(/Alpha(?:(?!Beta)[\s\S])*Permission denied/);
+ expect.soft(messages).toMatch(/Beta(?:(?!Alpha)[\s\S])*Disk full/);
+ expect.soft(messages).not.toContain("Healthy");
+}
+
+function failTwoEnvironments() {
+ mocks.targets = [
+ environment("healthy", "Healthy"),
+ environment("alpha", "Alpha"),
+ environment("beta", "Beta"),
+ ];
+ mocks.updateSettings.mockImplementation(async ({ environmentId }: { environmentId: string }) =>
+ environmentId === "healthy"
+ ? AsyncResult.success(undefined)
+ : AsyncResult.failure(
+ Cause.fail(new Error(environmentId === "alpha" ? "Permission denied" : "Disk full")),
+ ),
+ );
+}
let root: Root;
+let container: HTMLDivElement;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
- root = createRoot(document.createElement("div"));
+ container = document.createElement("div");
+ root = createRoot(container);
+ mocks.targets = [environment("local", "Local")];
+ mocks.projectSelected = false;
+ mocks.alert.mockReset();
mocks.updateSettings.mockReset();
+ mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
});
afterEach(() => {
@@ -78,11 +185,8 @@ afterEach(() => {
describe("SettingsServerControlsRouteScreen", () => {
it("sends a draft saved during a pending write once that write settles", async () => {
- let settle = () => {};
- mocks.updateSettings.mockImplementationOnce(
- () => new Promise<void>((resolve) => (settle = resolve)),
- );
- mocks.updateSettings.mockResolvedValue(undefined);
+ const pending = Promise.withResolvers<AsyncResult.Success<void>>();
+ mocks.updateSettings.mockReturnValueOnce(pending.promise);
act(() => root.render(<SettingsEnvironmentSourceControlRouteScreen />));
act(() => mocks.branchNaming.onChange({ branchNamingMode: "custom" }));
@@ -90,7 +194,7 @@ describe("SettingsServerControlsRouteScreen", () => {
act(() => mocks.branchNaming.onChange({ branchNameInstructions: "Use issue IDs." }));
expect(mocks.updateSettings).toHaveBeenCalledOnce();
- await act(async () => settle());
+ await act(async () => pending.resolve(AsyncResult.success(undefined)));
expect(mocks.updateSettings).toHaveBeenCalledTimes(2);
expect(mocks.updateSettings).toHaveBeenLastCalledWith({
@@ -101,3 +205,111 @@ describe("SettingsServerControlsRouteScreen", () => {
});
});
});
+
+describe.each([
+ {
+ name: "source control",
+ Screen: SettingsEnvironmentSourceControlRouteScreen,
+ label: "Automatically pull",
+ key: "defaultAutoPull",
+ },
+ {
+ name: "thread behavior",
+ Screen: SettingsThreadsRouteScreen,
+ label: "Auto-settle merged threads",
+ key: "sidebarAutoSettleOnMerge",
+ },
+] as const)("$name shared settings", ({ Screen, label, key }) => {
+ it("identifies each failed environment and reason, then allows a subscription-driven retry", async () => {
+ failTwoEnvironments();
+ const pending = Promise.withResolvers<AsyncResult.Success<void>>();
+ mocks.updateSettings.mockReturnValueOnce(pending.promise);
+ act(() => root.render(<Screen />));
+
+ act(() => button(label).click());
+ expect(button(label).disabled).toBe(true);
+ await act(async () => pending.resolve(AsyncResult.success(undefined)));
+
+ expectFailures();
+ expect(mocks.updateSettings.mock.calls.map(([input]) => input.environmentId)).toEqual([
+ "healthy",
+ "alpha",
+ "beta",
+ ]);
+ expect(button(label).disabled).toBe(false);
+ expect(button(label).getAttribute("aria-checked")).toBe("false");
+
+ mocks.alert.mockClear();
+ mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
+ await act(async () => button(label).click());
+ expect(mocks.updateSettings).toHaveBeenCalledTimes(6);
+ expect(mocks.alert).not.toHaveBeenCalled();
+ expect(button(label).getAttribute("aria-checked")).toBe("false");
+
+ mocks.targets = mocks.targets.map((target) => ({
+ ...target,
+ serverConfig: {
+ ...target.serverConfig,
+ settings: { ...target.serverConfig.settings, [key]: true },
+ },
+ }));
+ act(() => root.render(<Screen />));
+ expect(button(label).getAttribute("aria-checked")).toBe("true");
+ });
+
+ it("reports failed project resets and keeps overrides visible until a successful retry is received", async () => {
+ failTwoEnvironments();
+ mocks.projectSelected = true;
+ mocks.targets = mocks.targets.map((target) => ({
+ ...target,
+ serverConfig: {
+ ...target.serverConfig,
+ settings: {
+ ...target.serverConfig.settings,
+ projectSettingsOverrides: { project: { [key]: true } },
+ },
+ },
+ }));
+ act(() => root.render(<Screen />));
+
+ await act(async () => button("Use environment defaults").click());
+
+ expectFailures();
+ expect(button(label).getAttribute("aria-checked")).toBe("true");
+ expect(button("Use environment defaults").disabled).toBe(false);
+
+ mocks.alert.mockClear();
+ mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
+ await act(async () => button("Use environment defaults").click());
+ expect(mocks.updateSettings).toHaveBeenCalledTimes(6);
+ expect(mocks.alert).not.toHaveBeenCalled();
+ expect(button(label).getAttribute("aria-checked")).toBe("true");
+
+ mocks.targets = mocks.targets.map((target) => ({
+ ...target,
+ serverConfig: {
+ ...target.serverConfig,
+ settings: { ...target.serverConfig.settings, projectSettingsOverrides: {} },
+ },
+ }));
+ act(() => root.render(<Screen />));
+ expect(button(label).getAttribute("aria-checked")).toBe("false");
+ expect(container.textContent).not.toContain("Use defaults");
+ });
+
+ it("does not alert for an interrupted write and releases the controls for retry", async () => {
+ const pending = Promise.withResolvers<AsyncResult.Failure<void>>();
+ mocks.updateSettings.mockReturnValueOnce(pending.promise);
+ act(() => root.render(<Screen />));
+
+ act(() => button(label).click());
+ expect(button(label).disabled).toBe(true);
+ await act(async () => pending.resolve(AsyncResult.failure(Cause.interrupt(1))));
+
+ expect(mocks.alert).not.toHaveBeenCalled();
+ expect(button(label).disabled).toBe(false);
+ await act(async () => button(label).click());
+ expect(mocks.updateSettings).toHaveBeenCalledTimes(2);
+ expect(mocks.alert).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
index 8ca4bb410e3..c4e82fbe93e 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
@@ -18,8 +18,6 @@ import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { RUNTIME_MODE_CHOICES } from "../threads/thread-settings-options";
-import { serverEnvironment } from "../../state/server";
-import { useAtomCommand } from "../../state/use-atom-command";
import { SettingsScreen } from "./components/SettingsScreen";
import {
AndroidSettingsEnvironmentFilter,
@@ -32,6 +30,7 @@ import { SettingsSection } from "./components/SettingsSection";
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
+import { useSettingsWriter } from "./useSettingsWriter";
import {
planMobileScopedSettingsClear,
planMobileScopedSettingsPatch,
@@ -172,10 +171,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
const isMixed = (key: keyof ServerSettings) =>
reference === null ||
displayTargets.some((entry) => entry.settings[key] !== reference.settings[key]);
- const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
- label: "environment settings update",
- reportFailure: true,
- });
+ const writeSettings = useSettingsWriter();
const write = (patch: ServerSettingsPatch) => {
if (writeInFlight.current) {
const queued = queuedPatch.current;
@@ -197,11 +193,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
writeInFlight.current = true;
setPendingTargets(targets);
setPendingWrites((count) => count + 1);
- void Promise.allSettled(
- writes.map((entry) =>
- updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
- ),
- ).finally(() => {
+ void writeSettings(targets, writes).finally(() => {
writeInFlight.current = false;
setPendingTargets(null);
setPendingWrites((count) => count - 1);
@@ -225,11 +217,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
writeInFlight.current = true;
setPendingTargets(targets);
setPendingWrites((count) => count + 1);
- void Promise.allSettled(
- writes.map((entry) =>
- updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
- ),
- ).finally(() => {
+ void writeSettings(targets, writes).finally(() => {
writeInFlight.current = false;
// Resending a draft over these pre-clear targets would undo the clear.
queuedPatch.current = null;
diff --git a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx
index dea74b2cd5b..d023e5c57e3 100644
--- a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx
@@ -12,8 +12,6 @@ import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";
import { AppText as Text } from "../../components/ui/AppText";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
-import { serverEnvironment } from "../../state/server";
-import { useAtomCommand } from "../../state/use-atom-command";
import { SettingsSection } from "./components/SettingsSection";
import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
@@ -24,6 +22,7 @@ import {
} from "./components/SettingsEnvironmentFilterHeader";
import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync";
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
+import { useSettingsWriter } from "./useSettingsWriter";
import {
planMobileScopedSettingsClear,
planMobileScopedSettingsPatch,
@@ -67,10 +66,7 @@ function AutoSettleSettingsRows() {
const [pendingTargets, setPendingTargets] = useState<
readonly ScopedMobileSettingsTarget[] | null
>(null);
- const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
- label: "server settings update",
- reportFailure: true,
- });
+ const writeSettings = useSettingsWriter();
const syncEnvironments = selectedTargets.filter(supportsSharedSettingsSync);
const syncTargets = resolveMobileSettingsTargets(
@@ -107,11 +103,7 @@ function AutoSettleSettingsRows() {
writeInFlight.current = true;
setPendingTargets(syncTargets);
setPendingWrites((count) => count + 1);
- void Promise.allSettled(
- writes.map((entry) =>
- updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
- ),
- ).finally(() => {
+ void writeSettings(syncTargets, writes).finally(() => {
writeInFlight.current = false;
setPendingTargets(null);
setPendingWrites((count) => count - 1);
@@ -161,11 +153,7 @@ function AutoSettleSettingsRows() {
writeInFlight.current = true;
setPendingTargets(syncTargets);
setPendingWrites((count) => count + 1);
- void Promise.allSettled(
- writes.map((entry) =>
- updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
- ),
- ).finally(() => {
+ void writeSettings(syncTargets, writes).finally(() => {
writeInFlight.current = false;
setPendingTargets(null);
setPendingWrites((count) => count - 1);
diff --git a/apps/mobile/src/features/settings/useSettingsWriter.ts b/apps/mobile/src/features/settings/useSettingsWriter.ts
new file mode 100644
index 00000000000..aebd453c2ce
--- /dev/null
+++ b/apps/mobile/src/features/settings/useSettingsWriter.ts
@@ -0,0 +1,44 @@
+import type { EnvironmentId, ServerSettingsPatch } from "@t3tools/contracts";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+
+import * as Dialog from "../../components/ui/Dialog";
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import type { ScopedMobileSettingsTarget } from "./settings-scoped-server";
+
+export function useSettingsWriter() {
+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
+ label: "environment settings update",
+ reportFailure: true,
+ });
+
+ return async (
+ targets: readonly ScopedMobileSettingsTarget[],
+ writes: readonly {
+ readonly environmentId: EnvironmentId;
+ readonly patch: ServerSettingsPatch;
+ }[],
+ ) => {
+ const outcomes = await Promise.all(
+ writes.map(async (entry) => {
+ const result = await updateSettings({
+ environmentId: entry.environmentId,
+ input: { patch: entry.patch },
+ });
+ if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return null;
+ const label =
+ targets.find((target) => target.environment.environmentId === entry.environmentId)
+ ?.environment.label ?? entry.environmentId;
+ const error = squashAtomCommandFailure(result);
+ return `${label}: ${error instanceof Error ? error.message : String(error)}`;
+ }),
+ );
+ const failures = outcomes.filter((outcome) => outcome !== null);
+ if (failures.length > 0) {
+ Dialog.alert("Could not save settings", failures.join("\n\n"));
+ }
+ };
+}