Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions apps/mobile/src/features/pull-requests/usePullRequestFeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ export function usePullRequestFeed() {
targets: new Map(environmentIds.map((id) => [id, {}])),
}),
);
void writeSettings(
[],
void writeSettings([], () =>
environmentIds.map((environmentId) => ({
environmentId,
patch: { hiddenPullRequests: { [key]: url } },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,15 @@ vi.mock("react-native", () => ({
</button>
),
}));
vi.mock("@effect/atom-react", () => ({
useAtomValue: () => AsyncResult.success({}),
useAtomSet: () => () => {},
}));
vi.mock("@effect/atom-react", async () => {
const { createContext } = await import("react");
return {
// The settings writer reads the cached configs, empty here.
RegistryContext: createContext({ get: () => new Map() }),
useAtomValue: () => AsyncResult.success({}),
useAtomSet: () => () => {},
};
});
vi.mock("../../state/preferences", () => ({
mobilePreferencesAtom: {},
updateMobilePreferencesAtom: {},
Expand All @@ -59,7 +64,10 @@ vi.mock("../../state/session", () => ({
.filter((environmentId) => !mocks.readOnly.has(environmentId)),
),
}));
vi.mock("../../state/server", () => ({ serverEnvironment: { updateSettings: {} } }));
vi.mock("../../state/server", () => ({
environmentServerConfigsAtom: {},
serverEnvironment: { updateSettings: {} },
}));
vi.mock("../pull-requests/usePullRequestFeed", () => ({
usePullRequestFeed: () => ({
hiddenUrls: [],
Expand Down Expand Up @@ -127,6 +135,9 @@ vi.mock("./components/SettingsSwitchRow", () => ({
),
}));
vi.mock("./components/SettingsRow", () => ({ SettingsRow: () => null }));
vi.mock("./components/PullRequestFeedRulesSection", () => ({
PullRequestFeedRulesSection: () => null,
}));
vi.mock("./components/BranchNamingSettings", () => ({
BranchNamingSettings: (props: { onChange: (patch: ServerSettingsPatch) => void }) => {
mocks.branchNaming.onChange = props.onChange;
Expand Down Expand Up @@ -197,8 +208,11 @@ describe("SettingsServerControlsRouteScreen", () => {
mocks.updateSettings.mockReturnValueOnce(pending.promise);
act(() => root.render(<SettingsWorktreesRouteScreen />));

act(() => mocks.branchNaming.onChange({ branchNamingMode: "custom" }));
act(() => mocks.branchNaming.onChange({ branchNameInstructions: "Use issue IDs." }));
// Saves start on the settings writer's queue, a microtask after the change.
await act(async () => mocks.branchNaming.onChange({ branchNamingMode: "custom" }));
await act(async () =>
mocks.branchNaming.onChange({ branchNameInstructions: "Use issue IDs." }),
);
expect(mocks.updateSettings).toHaveBeenCalledOnce();

await act(async () => pending.resolve(AsyncResult.success(undefined)));
Expand All @@ -222,8 +236,8 @@ describe("SettingsServerControlsRouteScreen", () => {
(button) => button.textContent === label,
)!;

act(() => toggle("Agent browser access").click());
act(() => toggle("Auto-settle merged threads").click());
await act(async () => toggle("Agent browser access").click());
await act(async () => toggle("Auto-settle merged threads").click());

// Both rewrite the whole project override, so a second write planned now would drop the first.
expect(mocks.updateSettings).toHaveBeenCalledOnce();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { SettingsSection } from "./components/SettingsSection";
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
import { SourceControlSignInSection } from "./components/SourceControlSignInSection";
import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";
import { PullRequestFeedRulesSection } from "./components/PullRequestFeedRulesSection";
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
import { useSettingsWriter } from "./useSettingsWriter";
import {
Expand Down Expand Up @@ -181,14 +182,15 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
const environmentMenu = useSettingsEnvironmentMenu();
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();
const { selectedTargets, selectedIds, projectGroups, selectedProjectKey } =
useSettingsEnvironmentFilter();
const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);
const writableEnvironments = useEnvironmentsWithScope(selectedTargets, AuthSettingsWriteScope);
const projectSelected = selectedProjectKey !== null;
const targets = resolveMobileSettingsTargets(
selectedTargets,
projectSelected ? (selectedProject?.members.map((member) => member.project) ?? []) : null,
);
const members = projectSelected
? (selectedProject?.members.map((member) => member.project) ?? [])
: null;
const targets = resolveMobileSettingsTargets(selectedTargets, members);
const [pendingWrites, setPendingWrites] = useState(0);
const writeInFlight = useRef(false);
// Closing views can save after controls disable; queue those patches behind the pending write.
Expand Down Expand Up @@ -234,7 +236,13 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
writeInFlight.current = true;
setPendingTargets(targets);
setPendingWrites((count) => count + 1);
void writeSettings(targets, writes).finally(() => {
void writeSettings(selectedTargets, (current) =>
planServerSettingsWrites(
resolveMobileSettingsTargets(current, members),
projectSelected,
patch,
),
).finally(() => {
writeInFlight.current = false;
setPendingTargets(null);
setPendingWrites((count) => count - 1);
Expand All @@ -258,7 +266,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
writeInFlight.current = true;
setPendingTargets(targets);
setPendingWrites((count) => count + 1);
void writeSettings(targets, writes).finally(() => {
const keys = PAGE_PROJECT_KEYS[props.page];
void writeSettings(selectedTargets, (current) =>
planMobileScopedSettingsClear(resolveMobileSettingsTargets(current, members), keys),
).finally(() => {
writeInFlight.current = false;
// Resending a draft over these pre-clear targets would undo the clear.
queuedPatch.current = null;
Expand Down Expand Up @@ -295,11 +306,17 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
>
{!hasConnectedSelection || reference === null ? (
<Text className="px-2 text-base text-foreground-muted">
{projectSelected
? "Select a project with a checkout on a connected environment."
: "Use the filter above to select a connected environment."}
</Text>
<>
<Text className="px-2 text-base text-foreground-muted">
{projectSelected
? "Select a project with a checkout on a connected environment."
: "Use the filter above to select a connected environment."}
</Text>
{/* Cached rules stay readable; each row says what needs a connection. */}
{props.page === "source-control" && !projectSelected ? (
<PullRequestFeedRulesSection selectedIds={selectedIds} targets={selectedTargets} />
) : null}
</>
) : (
<>
<ManagedPolicyNotice targets={targets} />
Expand Down Expand Up @@ -483,6 +500,12 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
))}
</SettingsSection>
) : null}
{projectSelected ? null : (
<PullRequestFeedRulesSection
selectedIds={selectedIds}
targets={selectedTargets}
/>
)}
{projectSelected || feed.hiddenUrls.length === 0 ? null : (
<SettingsSection
title="Hidden pull requests"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import { useAtomValue } from "@effect/atom-react";
import {
PULL_REQUEST_FEED_RULES,
pullRequestFeedRuleRows,
pullRequestFeedRuleTargets,
type PullRequestFeedRuleRow,
} from "@t3tools/client-runtime/pull-request-feed";
import { AuthSettingsWriteScope, type EnvironmentId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";

import { SymbolView } from "../../../components/ui/AppSymbol";
import { AppText as Text } from "../../../components/ui/AppText";
import { Menu } from "../../../components/ui/Menu";
import { useProjects } from "../../../state/entities";
import { useEnvironments } from "../../../state/environments";
import { environmentServerConfigsAtom } from "../../../state/server";
import { useEnvironmentsWithScope } from "../../../state/session";
import {
planMobileFeedRuleReset,
planMobileScopedSettingsPatch,
resolveMobileSettingsTargets,
} from "../settings-scoped-server";
import type { SettingsTarget } from "../settings-environment-filter";
import { useSettingsWriter } from "../useSettingsWriter";
import { SettingsSection } from "./SettingsSection";

const DEFAULT_ACTION = "default";

/**
* Every repository's feed rule; a pick applies to every writable copy of the repository. It reads
* cached settings, so it stays useful while environments are offline.
*/
export function PullRequestFeedRulesSection(props: {
readonly selectedIds: ReadonlySet<EnvironmentId> | null;
readonly targets: readonly SettingsTarget[];
}) {
const { environments } = useEnvironments();
const configs = useAtomValue(environmentServerConfigsAtom);
const projects = useProjects();
const writeSettings = useSettingsWriter();
const writable = useEnvironmentsWithScope(props.targets, AuthSettingsWriteScope);
const environmentOf = (environmentId: EnvironmentId) => {
const environment = environments.find((candidate) => candidate.environmentId === environmentId);
const config = configs.get(environmentId);
if (!environment || !config) return undefined;
return {
label: environment.label,
settings: config.settings,
connected: environment.connection.phase === "connected",
capable: config.environment.capabilities.pullRequestFeed === true,
writeGranted: writable.has(environmentId),
managedPolicy: config.managedPolicy,
};
};
const rows = pullRequestFeedRuleRows(
projects.filter(
(project) => props.selectedIds === null || props.selectedIds.has(project.environmentId),
),
environmentOf,
);
if (rows.length === 0) return null;

type Row = (typeof rows)[number];
const pick = (row: Row, action: string) => {
const reset = action === DEFAULT_ACTION;
const rule = PULL_REQUEST_FEED_RULES.find((option) => option.value === action)?.value;
if (!reset && rule === undefined) return;
const picked = reset ? null : rule!;
// A reset covers every writable copy: one may still have an earlier pick in flight.
const members =
picked === null
? row.copies.flatMap((copy) => (copy.access === "writable" ? [copy.project] : []))
: pullRequestFeedRuleTargets(row, picked);
if (members.length === 0) return;
// The copies are chosen now; each save rebuilds their entries from the settings it starts
// from, so a save queued behind another keeps that one's keys.
void writeSettings(props.targets, (current) => {
const targets = resolveMobileSettingsTargets(current, members);
return picked === null
? planMobileFeedRuleReset(targets)
: planMobileScopedSettingsPatch(targets, true, { pullRequestFeed: picked });
});
};

return (
<SettingsSection
title="Repository feed rules"
footer="A rule picked here applies to every copy of the repository that this connection can change."
>
{rows.map((row, index) => (
<RuleRow
key={row.key}
row={row}
separated={index > 0}
disabled={row.copies.every((copy) => copy.access !== "writable")}
onPick={(action) => pick(row, action)}
/>
))}
</SettingsSection>
);
}

function RuleRow<Project>(props: {
readonly row: PullRequestFeedRuleRow<Project>;
readonly separated: boolean;
readonly disabled: boolean;
readonly onPick: (action: string) => void;
}) {
const { row } = props;
const value =
PULL_REQUEST_FEED_RULES.find((option) => option.value === row.rule)?.label ??
(row.known ? "Differs" : "Unavailable");
const content = (
<Pressable
accessibilityRole="button"
accessibilityLabel={`${row.name}, ${value}`}
accessibilityState={{ disabled: props.disabled }}
disabled={props.disabled}
className={
props.separated
? "min-h-14 gap-0.5 border-t border-border-subtle px-4 py-3 active:opacity-70"
: "min-h-14 gap-0.5 px-4 py-3 active:opacity-70"
}
>
<View className="flex-row items-center gap-3">
<Text textRole="body" className="min-w-0 flex-1 text-foreground" numberOfLines={1}>
{row.name}
</Text>
<Text textRole="footnote" className="text-foreground-muted" numberOfLines={1}>
{value}
</Text>
{props.disabled ? null : (
<SymbolView
name="chevron.down"
size={14}
tintColorClassName="accent-chevron"
type="monochrome"
/>
)}
</View>
<Text textRole="footnote" className="text-foreground-muted" numberOfLines={1}>
{row.covers}
</Text>
{row.status ? (
<Text textRole="footnote" className="text-foreground-muted">
{row.status}
</Text>
) : null}
</Pressable>
);
if (props.disabled) return content;
return (
<Menu
actions={[
...PULL_REQUEST_FEED_RULES.map((option) => ({
id: option.value,
title: option.label,
state: row.rule === option.value ? ("on" as const) : ("off" as const),
})),
...(row.canReset ? [{ id: DEFAULT_ACTION, title: "Use the default rule" }] : []),
]}
onPressAction={({ nativeEvent }) => props.onPick(nativeEvent.event)}
>
{content}
</Menu>
);
}
41 changes: 41 additions & 0 deletions apps/mobile/src/features/settings/settings-scoped-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { SettingsTarget } from "./settings-environment-filter";
import {
managedSettingReason,
planMobileScopedSettingsClear,
planMobileFeedRuleReset,
planMobileScopedSettingsPatch,
resolveMobileSettingsTargets,
uniformMobileSetting,
Expand Down Expand Up @@ -164,6 +165,46 @@ describe("mobile project settings scope", () => {
});
});

describe("mobile feed rule reset", () => {
it("keeps a copy whose override has not shown up queued, and clears it once it has", () => {
const hidden: ServerSettings = {
...DEFAULT_SERVER_SETTINGS,
projectSettingsOverrides: {
[firstProject]: { pullRequestFeed: "hidden", defaultAutoPull: true },
},
};
const members = [
{ environmentId: firstId, id: firstProject },
{ environmentId: secondId, id: secondProject },
];
const plan = (second: ServerSettings) =>
planMobileFeedRuleReset(
resolveMobileSettingsTargets(
[environment(firstId, hidden), environment(secondId, second)],
members,
),
);
// The second server has not shown the earlier pick yet.
expect(plan({ ...DEFAULT_SERVER_SETTINGS, projectSettingsOverrides: {} })).toEqual([
{
environmentId: firstId,
patch: { projectSettingsOverrides: { [firstProject]: { defaultAutoPull: true } } },
},
{ environmentId: secondId, patch: {} },
]);
// Its queued save is planned again from the earlier save's response.
expect(
plan({
...DEFAULT_SERVER_SETTINGS,
projectSettingsOverrides: { [secondProject]: { pullRequestFeed: "hidden" } },
})[1],
).toEqual({
environmentId: secondId,
patch: { projectSettingsOverrides: { [secondProject]: null } },
});
});
});

describe("managed settings across environments", () => {
it("names the manager when any selected environment locks the setting", () => {
const managed = {
Expand Down
Loading