diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts index c1507bb12f1f7..5b734bea3f893 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts @@ -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 } }, diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx index 3dedcc600721f..ccd9c6a8102e1 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx @@ -36,10 +36,15 @@ vi.mock("react-native", () => ({ ), })); -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: {}, @@ -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: [], @@ -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; @@ -197,8 +208,11 @@ describe("SettingsServerControlsRouteScreen", () => { mocks.updateSettings.mockReturnValueOnce(pending.promise); act(() => root.render()); - 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))); @@ -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(); diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 4a3d6f8995784..85efea4dac885 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -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 { @@ -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. @@ -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); @@ -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; @@ -295,11 +306,17 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }} > {!hasConnectedSelection || reference === null ? ( - - {projectSelected - ? "Select a project with a checkout on a connected environment." - : "Use the filter above to select a connected environment."} - + <> + + {projectSelected + ? "Select a project with a checkout on a connected environment." + : "Use the filter above to select a connected environment."} + + {/* Cached rules stay readable; each row says what needs a connection. */} + {props.page === "source-control" && !projectSelected ? ( + + ) : null} + > ) : ( <> @@ -483,6 +500,12 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { ))} ) : null} + {projectSelected ? null : ( + + )} {projectSelected || feed.hiddenUrls.length === 0 ? null : ( | 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 ( + + {rows.map((row, index) => ( + 0} + disabled={row.copies.every((copy) => copy.access !== "writable")} + onPick={(action) => pick(row, action)} + /> + ))} + + ); +} + +function RuleRow(props: { + readonly row: PullRequestFeedRuleRow; + 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 = ( + + + + {row.name} + + + {value} + + {props.disabled ? null : ( + + )} + + + {row.covers} + + {row.status ? ( + + {row.status} + + ) : null} + + ); + if (props.disabled) return content; + return ( + ({ + 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} + + ); +} diff --git a/apps/mobile/src/features/settings/settings-scoped-server.test.ts b/apps/mobile/src/features/settings/settings-scoped-server.test.ts index 4af458c8c2f5e..7fd0facfecc0d 100644 --- a/apps/mobile/src/features/settings/settings-scoped-server.test.ts +++ b/apps/mobile/src/features/settings/settings-scoped-server.test.ts @@ -10,6 +10,7 @@ import type { SettingsTarget } from "./settings-environment-filter"; import { managedSettingReason, planMobileScopedSettingsClear, + planMobileFeedRuleReset, planMobileScopedSettingsPatch, resolveMobileSettingsTargets, uniformMobileSetting, @@ -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 = { diff --git a/apps/mobile/src/features/settings/settings-scoped-server.ts b/apps/mobile/src/features/settings/settings-scoped-server.ts index 2e16dc73a0ad7..193aa1223886a 100644 --- a/apps/mobile/src/features/settings/settings-scoped-server.ts +++ b/apps/mobile/src/features/settings/settings-scoped-server.ts @@ -132,3 +132,27 @@ export function planMobileScopedSettingsClear( patch: { projectSettingsOverrides } as ServerSettingsPatch, })); } + +/** + * A feed rule reset plans every given copy's environment. A copy whose settings show no override + * gets an empty patch: it keeps a place in that environment's save queue, and when its turn comes + * it is planned again from the save before it, which may hold the override this reset must clear. + * The settings writer sends nothing for a patch that is still empty. + */ +export function planMobileFeedRuleReset(targets: readonly ScopedMobileSettingsTarget[]) { + const overridden = targets.filter( + (target) => + target.projectId !== null && + target.environment.serverConfig.settings.projectSettingsOverrides[target.projectId] + ?.pullRequestFeed !== undefined, + ); + const writes = planMobileScopedSettingsClear(overridden, ["pullRequestFeed"]); + const waiting = [ + ...new Set( + targets + .map((target) => target.environment.environmentId) + .filter((environmentId) => !writes.some((write) => write.environmentId === environmentId)), + ), + ].map((environmentId) => ({ environmentId, patch: {} as ServerSettingsPatch })); + return [...writes, ...waiting]; +} diff --git a/apps/mobile/src/features/settings/useSettingsWriter.ts b/apps/mobile/src/features/settings/useSettingsWriter.ts index 20fa58a5a144d..0fd2f6e149c9f 100644 --- a/apps/mobile/src/features/settings/useSettingsWriter.ts +++ b/apps/mobile/src/features/settings/useSettingsWriter.ts @@ -1,48 +1,92 @@ -import type { EnvironmentId, ServerSettingsPatch } from "@t3tools/contracts"; +import { RegistryContext } from "@effect/atom-react"; import { - isAtomCommandInterrupted, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; + createScopedSettingsWriter, + type ScopedSettingsPlan, +} from "@t3tools/client-runtime/settings-writer"; +import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId, ServerSettingsPatch } from "@t3tools/contracts"; +import { use } from "react"; import * as Dialog from "../../components/ui/Dialog"; -import { serverEnvironment } from "../../state/server"; +import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; -import type { ScopedMobileSettingsTarget } from "./settings-scoped-server"; +import type { SettingsTarget } from "./settings-environment-filter"; + +type SettingsWrite = { readonly environmentId: EnvironmentId; readonly patch: ServerSettingsPatch }; +type SettingsWriter = ReturnType>; + +// One writer per registry, so every Settings screen's saves to an environment share one queue. +const writers = new WeakMap(); export function useSettingsWriter() { const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { label: "environment settings update", reportFailure: true, }); + const registry = use(RegistryContext); + let writer = writers.get(registry); + if (writer === undefined) { + writer = createScopedSettingsWriter( + (environmentId) => + registry.get(environmentServerConfigsAtom).get(environmentId)?.settings ?? null, + ); + writers.set(registry, writer); + } + const write = writer; - /** Resolves to the environments that did not save, interrupted ones included. */ + /** + * The server replaces a project's override entry whole, so each save is planned again from the + * newest settings this device holds when it starts, the previous save's response included. + * Resolves to the environments that did not save, interrupted ones included. + */ return async ( - targets: readonly ScopedMobileSettingsTarget[], - writes: readonly { - readonly environmentId: EnvironmentId; - readonly patch: ServerSettingsPatch; - }[], + environments: readonly SettingsTarget[], + plan: (environments: readonly SettingsTarget[]) => readonly SettingsWrite[], ) => { - const failed: EnvironmentId[] = []; - const outcomes = await Promise.all( - writes.map(async (entry) => { - const result = await updateSettings({ - environmentId: entry.environmentId, - input: { patch: entry.patch }, - }); - if (result._tag === "Failure") failed.push(entry.environmentId); - 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)}`; + // A single-key write, such as hiding a pull request, may name an environment it was not given. + const unknown = new Set(); + const toPlan = (current: readonly SettingsTarget[]): ScopedSettingsPlan => ({ + clientPatch: {}, + hasClientWrite: false, + unavailableReason: null, + serverWrites: plan(current).flatMap((entry) => { + const environment = current.find( + (candidate) => candidate.environmentId === entry.environmentId, + ); + const previous = + environment?.serverConfig.settings ?? + registry.get(environmentServerConfigsAtom).get(entry.environmentId)?.settings; + if (previous === undefined) { + unknown.add(entry.environmentId); + return []; + } + return [ + { + environmentId: entry.environmentId, + label: environment?.label ?? entry.environmentId, + patch: entry.patch, + previous, + }, + ]; }), + }); + const interrupted = new Set(); + const { failedEnvironments } = await write( + environments, + toPlan, + async (request) => { + const result = await updateSettings(request); + if (isAtomCommandInterrupted(result)) interrupted.add(request.environmentId); + return result; + }, + () => {}, + ); + const failures = failedEnvironments.flatMap((failure) => + interrupted.has(failure.environmentId) ? [] : [`${failure.label}: ${failure.message}`], ); - const failures = outcomes.filter((outcome) => outcome !== null); if (failures.length > 0) { Dialog.alert("Could not save settings", failures.join("\n\n")); } - return failed; + return [...failedEnvironments.map((failure) => failure.environmentId), ...unknown]; }; } diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index 68f047e13acd7..792ad1fcadc71 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -5,6 +5,9 @@ import { isPullRequestHidden, PULL_REQUEST_FEED_RULES, pullRequestFeedRule, + pullRequestFeedRuleRows, + pullRequestFeedRuleTargets, + type PullRequestFeedRuleRow, pullRequestProjectHidesRepository, pullRequestRepositoryHidden, pullRequestRepositoryRules, @@ -12,6 +15,7 @@ import { import { AuthSettingsWriteScope, type ContextMenuItem, + isManagedSettingPath, type EnvironmentId, type ProjectId, type PullRequestFeedRule, @@ -22,7 +26,7 @@ import { useStableCallback } from "~/hooks/useStableCallback"; import { readLocalApi } from "~/localApi"; import { useProjects } from "~/state/entities"; import { useEnvironments } from "~/state/environments"; -import { readEnvironmentScope } from "~/state/session"; +import { useEnvironmentsWithScope } from "~/state/session"; import { applyPendingScopedWrites, @@ -30,6 +34,7 @@ import { pendingScopedWritesAtom, planEnvironmentSettingsPatch, planProjectOverridePatch, + planProjectOverridesClear, } from "../settings/scopedSettings"; import { useRunScopedPlan } from "../settings/useScopedSettings"; import { runPullRequestLinkAction } from "./pullRequestLinkContextMenu"; @@ -48,6 +53,8 @@ export function usePullRequestFeed() { const pendingWrites = useAtomValue(pendingScopedWritesAtom); const environments = applyPendingScopedWrites(known, pendingWrites); const runPlan = useRunScopedPlan(); + // Subscribed, so a grant that loads after the first render unlocks its writes. + const writeGranted = useEnvironmentsWithScope(known, AuthSettingsWriteScope); const settingsOf = (environmentId: EnvironmentId) => environments.find((environment) => environment.environmentId === environmentId)?.serverConfig ?.settings; @@ -61,8 +68,15 @@ export function usePullRequestFeed() { /** Older servers drop these settings, and a standard pairing cannot write settings. */ const canWrite = (environmentId: EnvironmentId) => environments.find((environment) => environment.environmentId === environmentId)?.serverConfig - ?.environment.capabilities.pullRequestFeed === true && - readEnvironmentScope(environmentId, AuthSettingsWriteScope); + ?.environment.capabilities.pullRequestFeed === true && writeGranted.has(environmentId); + /** A policy lock refuses the rule, project overrides included. */ + const canWriteRule = (environmentId: EnvironmentId) => + canWrite(environmentId) && + !isManagedSettingPath( + environments.find((environment) => environment.environmentId === environmentId)?.serverConfig + ?.managedPolicy, + "pullRequestFeed", + ); const connected = new Set( environments.flatMap((environment) => isConnectedWithConfig(environment) ? [environment.environmentId] : [], @@ -129,18 +143,56 @@ export function usePullRequestFeed() { const key = repositoryKeyOf(own); if (key) { return scope.filter( - (candidate) => repositoryKeyOf(candidate) === key && canWrite(candidate.environmentId), + (candidate) => repositoryKeyOf(candidate) === key && canWriteRule(candidate.environmentId), ); } - return canWrite(own.environmentId) ? [own] : []; + return canWriteRule(own.environmentId) ? [own] : []; }; - const setProjectRule = (members: ReturnType, rule: PullRequestFeedRule) => { + const setProjectRule = (members: ReadonlyArray, rule: PullRequestFeedRule) => { runPlan(environments, (current) => planProjectOverridePatch(current, members, { pullRequestFeed: rule }), ); }; + /** One row per repository in these environments, for the Settings overview. */ + const ruleRows = (environmentIds: ReadonlyArray) => + pullRequestFeedRuleRows( + projects.filter((project) => environmentIds.includes(project.environmentId)), + (environmentId) => { + const environment = environments.find( + (candidate) => candidate.environmentId === environmentId, + ); + const config = environment?.serverConfig; + if (!environment || !config) return undefined; + return { + label: environment.label, + settings: config.settings, + connected: connected.has(environmentId), + capable: config.environment.capabilities.pullRequestFeed === true, + writeGranted: writeGranted.has(environmentId), + managedPolicy: config.managedPolicy, + }; + }, + ); + type RuleRow = PullRequestFeedRuleRow; + // A pick that changes no copy writes nothing, so it cannot pin inherited rules. + const setRowRule = (row: RuleRow, rule: PullRequestFeedRule) => { + const members = pullRequestFeedRuleTargets(row, rule); + if (members.length > 0) setProjectRule(members, rule); + }; + const resetRowRule = (row: RuleRow) => { + const members = pullRequestFeedRuleTargets(row, null); + if (members.length === 0) return; + runPlan(environments, (current) => + planProjectOverridesClear( + current, + members.map((project) => ({ environmentId: project.environmentId, projectId: project.id })), + ["pullRequestFeed"], + ), + ); + }; + const openRowMenu = async ( entry: EnvironmentPullRequestEntry, openLabel: string, @@ -198,7 +250,12 @@ export function usePullRequestFeed() { unhide(entry.url); } else { const picked = PULL_REQUEST_FEED_RULES.find((option) => action === `rule:${option.value}`); - if (picked) setProjectRule(members, picked.value); + // Like the Settings overview, a copy already on the rule keeps following its default. + const changed = members.filter( + (member) => + ruleFor({ environmentId: member.environmentId, projectId: member.id }) !== picked?.value, + ); + if (picked && changed.length > 0) setProjectRule(changed, picked.value); } }; @@ -217,5 +274,8 @@ export function usePullRequestFeed() { canUnhide, unhideBlockedBy, showRowMenu, + ruleRows, + setRowRule, + resetRowRule, }; } diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index 48022143d92d9..793262d64dcf2 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -28,6 +28,7 @@ import { toastManager } from "../ui/toast"; import { Switch } from "../ui/switch"; import { resolveDefaultModelSettingsPresentation } from "./ProjectDefaultsSettings.logic"; import type { ProjectSettingsCategory } from "./ProjectSettingsPanel"; +import { PullRequestFeedRulesSetting } from "./PullRequestFeedRulesSetting"; import { searchableSetting } from "./settingsSearch"; import { useSettingsScope } from "./SettingsScopeContext"; import { @@ -572,6 +573,9 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting } /> ) : null} + {scope.kind === "all" || scope.kind === "environment" ? ( + + ) : null} > )} diff --git a/apps/web/src/components/settings/PullRequestFeedRulesSetting.tsx b/apps/web/src/components/settings/PullRequestFeedRulesSetting.tsx new file mode 100644 index 0000000000000..9770c65d3bfad --- /dev/null +++ b/apps/web/src/components/settings/PullRequestFeedRulesSetting.tsx @@ -0,0 +1,72 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { PULL_REQUEST_FEED_RULES } from "@t3tools/client-runtime/pull-request-feed"; + +import { usePullRequestFeed } from "../pullRequest/usePullRequestFeed"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { searchableSetting } from "./settingsSearch"; +import { SettingResetButton, SettingsRow } from "./settingsLayout"; + +/** Every repository's rule in one place; each write covers all writable copies of it. */ +export function PullRequestFeedRulesSetting(props: { + readonly environmentIds: ReadonlyArray; +}) { + const feed = usePullRequestFeed(); + const rows = feed.ruleRows(props.environmentIds); + return ( + + {rows.length === 0 ? null : ( + + {rows.map((row) => ( + + + {row.name} + {row.covers} + {row.status ? {row.status} : null} + + + {row.canReset ? ( + feed.resetRowRule(row)} + /> + ) : null} + copy.access !== "writable")} + onValueChange={(value) => { + const rule = PULL_REQUEST_FEED_RULES.find((option) => option.value === value); + if (rule) feed.setRowRule(row, rule.value); + }} + > + + + {(value: string | null) => + PULL_REQUEST_FEED_RULES.find((option) => option.value === value)?.label ?? + (row.known ? "Differs" : "Unavailable") + } + + + + {PULL_REQUEST_FEED_RULES.map((option) => ( + + {option.label} + + ))} + + + + + ))} + + )} + + ); +} diff --git a/apps/web/src/components/settings/scopedSettings.ts b/apps/web/src/components/settings/scopedSettings.ts index bb90ff5d20394..365646b56d527 100644 --- a/apps/web/src/components/settings/scopedSettings.ts +++ b/apps/web/src/components/settings/scopedSettings.ts @@ -14,7 +14,6 @@ import { type T3ProjectFile, type ServerSettingsPatch, } from "@t3tools/contracts"; -import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { clearProjectSettingsOverrides, resolveProjectSettings, @@ -23,21 +22,21 @@ import { } from "@t3tools/shared/projectSettings"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; import * as Equal from "effect/Equal"; -import * as Cause from "effect/Cause"; import { Atom } from "effect/reactivity"; +import type { + ScopedServerWrite, + ScopedSettingsEnvironment, +} from "@t3tools/client-runtime/settings-writer"; + import type { ResolvedSettingsScope } from "./settingsScope"; -export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch; +export { + createScopedSettingsWriter, + persistScopedSettingsPatch, +} from "@t3tools/client-runtime/settings-writer"; -interface ScopedSettingsEnvironment { - readonly environmentId: EnvironmentId; - readonly label: string; - readonly connection: { readonly phase: EnvironmentConnectionPhase }; - readonly serverConfig: { - readonly settings: ServerSettings; - } | null; -} +export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch; const SERVER_KEYS = new Set(Object.keys(ServerSettings.fields)); const CLIENT_KEYS = new Set(Object.keys(ClientSettingsSchema.fields)); @@ -234,13 +233,6 @@ export function scopedSettingsSource( : "environment"; } -interface ScopedServerWrite { - readonly environmentId: EnvironmentId; - readonly label: string; - readonly patch: ServerSettingsPatch; - readonly previous: ServerSettings; -} - function projectOverrideWrites( members: readonly { readonly id: ProjectId; readonly environmentId: EnvironmentId }[], environments: readonly ScopedSettingsEnvironment[], @@ -486,36 +478,6 @@ export function planProjectOverridesClear( }; } -function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean { - if (value === null) return before != null && Equal.equals(saved, before); - if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) { - const field = (source: unknown, key: string) => - isPlainObject(source) ? source[key] : undefined; - return Object.entries(value).some(([key, next]) => - writeWasDropped(next, field(before, key), field(saved, key)), - ); - } - const unchanged = - typeof value === "string" && typeof before === "string" - ? value.trim() === before - : Equal.equals(value, before); - return !unchanged && Equal.equals(saved, before); -} - -/** Older servers silently drop unknown keys; report them so rows cannot stay mixed forever. */ -function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) { - if (saved === undefined) return []; - return Object.entries(write.patch).flatMap(([key, value]) => - writeWasDropped( - value, - write.previous[key as keyof ServerSettings], - saved[key as keyof ServerSettings], - ) - ? [key] - : [], - ); -} - type ScopedSettingsPlan = ReturnType; const unavailablePlan = ( @@ -556,173 +518,3 @@ export function planEnvironmentSettingsPatch( "Connect the environment to save this setting.", ); } - -type ScopedSettingsPersistServer = (input: { - environmentId: EnvironmentId; - input: { patch: ServerSettingsPatch }; -}) => Promise<{ - readonly _tag: "Success" | "Failure"; - readonly cause?: Cause.Cause; - readonly value?: ServerSettings; -}>; - -export async function persistScopedSettingsPatch( - plan: ScopedSettingsPlan, - persistServer: ScopedSettingsPersistServer, - persistClient: (patch: ClientSettingsPatch) => void, -) { - return persistScopedSettingsPlan( - plan, - async (write) => ({ - write, - result: await persistServer({ - environmentId: write.environmentId, - input: { patch: write.patch }, - }), - }), - persistClient, - ); -} - -const OWN_ECHO_LIMIT = 8; - -/** - * Project overrides are whole entries built from this client's copy of the settings, and that - * copy hears about a save only when the server pushes it back. So saves to one environment run - * one at a time, each planned as it starts from the newest settings this client holds: the - * previous save's response, unless an independently changed copy has arrived. - */ -export function createScopedSettingsWriter( - readSettings: (environmentId: EnvironmentId) => ServerSettings | null, -) { - const queues = new Map>(); - const responses = new Map< - EnvironmentId, - { - readonly settings: ServerSettings; - readonly copy: ServerSettings; - readonly saved: readonly ServerSettings[]; - } - >(); - return ( - environments: readonly ScopedSettingsEnvironment[], - plan: (environments: readonly ScopedSettingsEnvironment[]) => ScopedSettingsPlan, - persistServer: ScopedSettingsPersistServer, - persistClient: (patch: ClientSettingsPatch) => void, - ) => - persistScopedSettingsPlan( - plan(environments), - (planned) => { - const { environmentId } = planned; - const save = (queues.get(environmentId) ?? Promise.resolve()).then(async () => { - const copy = readSettings(environmentId); - const response = responses.get(environmentId); - // A copy equal to one of our earlier responses is a delayed echo, older than the latest. - const isOwnEcho = (settings: ServerSettings) => - response?.saved.some((saved) => Equal.equals(saved, settings)) === true; - const continues = - copy !== null && response !== undefined && (response.copy === copy || isOwnEcho(copy)); - const settings = continues ? response.settings : copy; - const replanned = - settings === null ? null : plan(withSettings(environments, environmentId, settings)); - const write = - replanned?.serverWrites.find((next) => next.environmentId === environmentId) ?? planned; - const result = await persistServer({ environmentId, input: { patch: write.patch } }); - const savedCopy = readSettings(environmentId); - if (result._tag === "Success" && result.value !== undefined && savedCopy !== null) { - // A changed copy may be a newer remote push or the delayed echo of our previous save. - if ( - savedCopy === copy || - Equal.equals(savedCopy, settings) || - Equal.equals(savedCopy, result.value) || - isOwnEcho(savedCopy) - ) { - responses.set(environmentId, { - settings: result.value, - copy: savedCopy, - saved: [...(continues ? response.saved : []), result.value].slice(-OWN_ECHO_LIMIT), - }); - } else { - responses.delete(environmentId); - } - } - return { write, result }; - }); - queues.set( - environmentId, - save.catch(() => undefined), - ); - return save; - }, - persistClient, - ); -} - -function withSettings( - environments: readonly ScopedSettingsEnvironment[], - environmentId: EnvironmentId, - settings: ServerSettings, -) { - return environments.map((environment) => - environment.environmentId === environmentId && environment.serverConfig - ? { ...environment, serverConfig: { ...environment.serverConfig, settings } } - : environment, - ); -} - -async function persistScopedSettingsPlan( - plan: ScopedSettingsPlan, - persistWrite: (write: ScopedServerWrite) => Promise<{ - readonly write: ScopedServerWrite; - readonly result: Awaited>; - }>, - persistClient: (patch: ClientSettingsPatch) => void, -) { - if (plan.hasClientWrite) persistClient(plan.clientPatch); - const results = await Promise.allSettled(plan.serverWrites.map(persistWrite)); - // A queued write is replanned before it is sent, so judge the write that was sent. - const writes = results.map((result, index) => - result.status === "fulfilled" ? result.value.write : plan.serverWrites[index]!, - ); - const saved = (index: number) => { - const result = results[index]; - return ( - result?.status === "fulfilled" && - result.value.result._tag === "Success" && - droppedSettingKeys(writes[index]!, result.value.result.value).length === 0 - ); - }; - const failedEnvironments = writes.flatMap((environment, index) => { - if (saved(index)) return []; - const result = results[index]; - if (result?.status === "fulfilled" && result.value.result._tag === "Success") { - return [ - { - ...environment, - message: "This environment does not support this setting. Update T3 Code on it.", - }, - ]; - } - const error: unknown = - result?.status === "rejected" - ? result.reason - : result?.status === "fulfilled" && result.value.result.cause - ? Cause.squash(result.value.result.cause) - : undefined; - return [ - { - ...environment, - message: - error instanceof Error - ? error.message - : "The save failed. Try reconnecting and saving again.", - }, - ]; - }); - const savedEnvironments = writes.filter((_, index) => saved(index)); - return { - failedEnvironments, - savedEnvironments, - savedEnvironmentCount: savedEnvironments.length, - }; -} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index af9fcc06971e3..f5f9a2d179daa 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1173,6 +1173,13 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "project-defaults", searchTerms: ["pull requests list feed authored waiting on me review requested hide exclude"], }, + { + id: "pull-request-feed-rules", + title: "Repository feed rules", + to: "/settings/source-control", + scope: "environment-defaults", + searchTerms: ["pull requests list feed per project repository override overview hide"], + }, { id: "source-control", title: "Source control", diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx index 20f65d45c7a5b..2ac7e16173c57 100644 --- a/apps/web/src/routes/_chat.settings.tsx +++ b/apps/web/src/routes/_chat.settings.tsx @@ -15,7 +15,8 @@ import { import { useEnvironments } from "../state/environments"; import { SettingsScopeNotice } from "../components/settings/SettingsScopeNotice"; import { SETTINGS_DEVICE_ONLY_PATHS } from "../components/settings/SettingsScopeSentence"; -import { SettingsPageContainer } from "../components/settings/settingsLayout"; +import { SettingsPageContainer, SettingsSection } from "../components/settings/settingsLayout"; +import { PullRequestFeedRulesSetting } from "../components/settings/PullRequestFeedRulesSetting"; import { retainSettingsScope, validateSettingsRouteSearch, @@ -100,6 +101,12 @@ function SettingsScopeBoundary({ pathname, children }: { pathname: string; child Reconnect {scope.label} to change its settings. + {/* The overview reads cached rules and says per row what needs a connection. */} + {pathname === "/settings/source-control" ? ( + + + + ) : null} ); } diff --git a/docs/user/source-control.md b/docs/user/source-control.md index c0f4159b43f3b..6068fc201581a 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -253,7 +253,9 @@ project selector there. On web and desktop you can also right-click a pull reque rule for its project. When the same repository is a project on several connected environments, the list shows a pull request if any of their rules allows it, and **Hidden** on any of them hides the repository. Picking one project in the list's project filter shows all its pull -requests. +requests. **Repository feed rules** in Settings → Source control lists every repository's rule in +one place, and a rule you pick there applies to every copy of that repository that you can change +from this device. To hide one pull request, right-click it on web and desktop, or touch and hold it on mobile, and choose **Hide from feed**. Hidden pull requests leave every list. Press **Show N hidden** in the diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 276c75a2aaa09..9773e93e3ee1c 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -467,6 +467,10 @@ "types": "./src/pullRequestFeed.ts", "default": "./src/pullRequestFeed.ts" }, + "./settings-writer": { + "types": "./src/settingsWriter.ts", + "default": "./src/settingsWriter.ts" + }, "./pull-request-project-filter": { "types": "./src/pullRequestProjectFilter.ts", "default": "./src/pullRequestProjectFilter.ts" diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts index d34f6e45ff1d7..14613ccce78db 100644 --- a/packages/client-runtime/src/pullRequestFeed.test.ts +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -13,7 +13,10 @@ import { pullRequestFeedGroup, pullRequestFeedRule, pullRequestFeedShows, + pullRequestFeedRuleRows, + pullRequestFeedRuleTargets, type PullRequestFeedGroup, + type PullRequestFeedRuleEnvironment, } from "./pullRequestFeed.ts"; const projectA = ProjectId.make("project-a"); @@ -212,3 +215,147 @@ describe("pull request feed rules", () => { expect(isPullRequestHidden(hiddenPullRequestUrls(settings), "https://h/A/1")).toBe(true); }); }); + +describe("pull request feed rule rows", () => { + const settings = ( + pullRequestFeed: PullRequestFeedRule, + overrides: Record = {}, + ) => ({ + ...DEFAULT_SERVER_SETTINGS, + pullRequestFeed, + projectSettingsOverrides: Object.fromEntries( + Object.entries(overrides).map(([id, rule]) => [id, { pullRequestFeed: rule }]), + ), + }); + const project = ( + environmentId: string, + id: string, + canonicalKey?: string, + isScratch = false, + ) => ({ + environmentId, + id: ProjectId.make(id), + title: id, + repositoryIdentity: canonicalKey === undefined ? null : { canonicalKey }, + isScratch, + }); + const rows = ( + projects: ReadonlyArray>, + environments: Record< + string, + Partial & { settings: ReturnType } + >, + ) => + pullRequestFeedRuleRows(projects, (environmentId) => { + const environment = environments[environmentId]; + return environment === undefined + ? undefined + : { + label: environmentId, + connected: true, + capable: true, + writeGranted: true, + ...environment, + }; + }); + + it("groups a repository's copies into one row and gives an unidentified project its own", () => { + const result = rows( + [ + project("laptop", "web", "github.com/x/Web"), + project("server", "web-copy", "github.com/x/web"), + project("laptop", "notes"), + project("offline", "lost", "github.com/x/web"), + project("laptop", "scratch", undefined, true), + ], + { laptop: { settings: settings("all") }, server: { settings: settings("all") } }, + ); + expect(result.map((row) => [row.name, row.covers])).toEqual([ + ["github.com/x/Web", "web, web-copy · laptop, server"], + ["notes", "notes · laptop"], + ]); + }); + + it("shows an inherited rule as the default and offers no reset", () => { + const [row] = rows([project("laptop", "web", "k"), project("server", "web", "k")], { + laptop: { settings: settings("authored") }, + server: { settings: settings("authored") }, + }); + expect(row).toMatchObject({ rule: "authored", status: "Default rule.", canReset: false }); + }); + + it("names each rule's environments when copies differ", () => { + const [row] = rows([project("laptop", "web", "k"), project("server", "web", "k")], { + laptop: { settings: settings("all") }, + server: { settings: settings("all", { web: "hidden" }) }, + }); + expect(row).toMatchObject({ + rule: null, + status: "Differs: All pull requests on laptop; Hidden on server.", + canReset: true, + }); + }); + + it("leaves an outdated server's fallback out of the comparison but keeps its note", () => { + const [row] = rows([project("laptop", "web", "k"), project("old", "web", "k")], { + laptop: { settings: settings("all", { web: "hidden" }) }, + old: { settings: settings("all"), capable: false }, + }); + expect(row).toMatchObject({ rule: "hidden", status: "Update old to change it." }); + // Offline, the outdated copy's fallback is still not a rule. + const [offline] = rows([project("laptop", "web", "k"), project("old", "web", "k")], { + laptop: { settings: settings("all", { web: "hidden" }) }, + old: { settings: settings("all"), capable: false, connected: false }, + }); + expect(offline).toMatchObject({ rule: "hidden", status: "Update old to change it." }); + // With no server that stores the rule, the row has no value to show. + const [unknown] = rows([project("old", "web", "k")], { + old: { settings: settings("all"), capable: false }, + }); + expect(unknown).toMatchObject({ rule: null, known: false, status: "Update old to change it." }); + }); + + it("writes a pick only to writable copies not already on it", () => { + const [row] = rows( + [project("laptop", "web", "k"), project("server", "web", "k"), project("mac", "web", "k")], + { + laptop: { settings: settings("all") }, + server: { settings: settings("all", { web: "authored" }) }, + mac: { settings: settings("hidden"), connected: false }, + }, + ); + // Picking the rule the laptop copy inherits must not pin it there. + expect(pullRequestFeedRuleTargets(row!, "all").map((copy) => copy.environmentId)).toEqual([ + "server", + ]); + expect(pullRequestFeedRuleTargets(row!, null).map((copy) => copy.environmentId)).toEqual([ + "server", + ]); + }); + + it("says which copies this client cannot change and resets only writable ones", () => { + const [row] = rows( + [project("laptop", "web", "k"), project("server", "web", "k"), project("corp", "web", "k")], + { + laptop: { settings: settings("all"), connected: false }, + server: { settings: settings("all", { web: "all" }), writeGranted: false }, + // The server refuses a project override of a locked setting. + corp: { + settings: settings("all", { web: "all" }), + managedPolicy: { organization: "Acme", lockedSettings: ["pullRequestFeed"] }, + }, + }, + ); + expect(row).toMatchObject({ + rule: "all", + status: + "Connect laptop to change it. This connection cannot change settings on server. Managed by Acme on corp.", + canReset: false, + }); + expect(row?.copies.map((copy) => copy.access)).toEqual([ + "disconnected", + "read-only", + "managed", + ]); + }); +}); diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts index c6cc05ab9d4c3..bbea555512486 100644 --- a/packages/client-runtime/src/pullRequestFeed.ts +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -1,8 +1,10 @@ -import type { - ProjectId, - PullRequestFeedRule, - PullRequestInvolvement, - ServerSettings, +import { + isManagedSettingPath, + type ManagedPolicySummary, + type ProjectId, + type PullRequestFeedRule, + type PullRequestInvolvement, + type ServerSettings, } from "@t3tools/contracts"; export type PullRequestFeedSettings = Pick< @@ -145,7 +147,10 @@ export function pullRequestRepositoryHidden( type RepositoryProject = { readonly id: ProjectId; readonly environmentId: string; - readonly repositoryIdentity?: { readonly canonicalKey?: string | undefined } | null | undefined; + readonly repositoryIdentity?: + | { readonly canonicalKey?: string | undefined; readonly displayName?: string | undefined } + | null + | undefined; }; /** @@ -230,3 +235,186 @@ export function filterPullRequestFeed< }); return { groups: changed ? next : groups, hiddenCount, ruledOutCount }; } + +/** Why this client cannot change a copy's rule, or `writable`. */ +export type PullRequestFeedRuleAccess = + | "writable" + | "disconnected" + | "outdated" + | "managed" + | "read-only"; + +/** What an environment tells the overview about its copies. */ +export interface PullRequestFeedRuleEnvironment { + readonly label: string; + readonly settings: PullRequestFeedSettings; + readonly connected: boolean; + /** The server stores the rule; older ones drop it. */ + readonly capable: boolean; + /** This connection holds the settings write grant there. */ + readonly writeGranted: boolean; + readonly managedPolicy?: + | Pick + | undefined; +} + +export interface PullRequestFeedRuleCopy { + readonly project: Project; + readonly environmentLabel: string; + /** Null when the server cannot store a rule: its settings hold only a decoded fallback. */ + readonly rule: PullRequestFeedRule | null; + /** False when the project inherits its environment's default rule, or the rule is unknown. */ + readonly overridden: boolean; + readonly access: PullRequestFeedRuleAccess; + /** The organization whose policy locks the rule, when `access` is `managed`. */ + readonly managedBy: string | null; +} + +export interface PullRequestFeedRuleRow { + readonly key: string; + readonly name: string; + /** The project titles and environments the row covers. */ + readonly covers: string; + readonly copies: ReadonlyArray>; + /** The copies' one rule, or null when they differ or no copy's rule is known. */ + readonly rule: PullRequestFeedRule | null; + /** False when every copy is on a server that cannot store the rule. */ + readonly known: boolean; + /** Inheritance, disagreement, and the copies this client cannot change, in short sentences. */ + readonly status: string; + readonly canReset: boolean; +} + +const ruleLabel = (rule: PullRequestFeedRule) => + PULL_REQUEST_FEED_RULES.find((option) => option.value === rule)?.label ?? rule; + +const ACCESS_NOTES: Record< + Exclude, + (on: string) => string +> = { + disconnected: (on) => `Connect ${on} to change it.`, + outdated: (on) => `Update ${on} to change it.`, + "read-only": (on) => `This connection cannot change settings on ${on}.`, +}; + +function pullRequestFeedRuleAccess(environment: PullRequestFeedRuleEnvironment): { + readonly access: PullRequestFeedRuleAccess; + readonly managedBy: string | null; +} { + // Reconnecting an outdated server does not let it store the rule, so it needs the update first. + if (!environment.capable) return { access: "outdated", managedBy: null }; + if (!environment.connected) return { access: "disconnected", managedBy: null }; + // The server refuses a project override of a locked setting too. + if (isManagedSettingPath(environment.managedPolicy, "pullRequestFeed")) { + return { access: "managed", managedBy: environment.managedPolicy?.organization ?? null }; + } + return { access: environment.writeGranted ? "writable" : "read-only", managedBy: null }; +} + +const unique = (values: ReadonlyArray) => [...new Set(values)]; + +/** + * One row per repository, keyed like `pullRequestRepositoryRules`, so a write covers every copy + * the feed reads. A project without a repository identity gets its own row. Environments without + * settings are left out: their rule is unknown. + */ +export function pullRequestFeedRuleRows< + Project extends RepositoryProject & { + readonly title: string; + readonly isScratch?: boolean | undefined; + }, +>( + projects: ReadonlyArray, + environmentOf: ( + environmentId: Project["environmentId"], + ) => PullRequestFeedRuleEnvironment | undefined, +): ReadonlyArray> { + const groups = new Map[] }>(); + for (const project of projects) { + // Scratch projects have no pull requests to show, as in the pull request project pickers. + if (project.isScratch) continue; + const environment = environmentOf(project.environmentId); + if (environment === undefined) continue; + const identity = project.repositoryIdentity; + const repositoryKey = identity?.canonicalKey?.toLowerCase(); + const key = repositoryKey ?? `project ${project.environmentId} ${project.id}`; + const copy: PullRequestFeedRuleCopy = { + project, + environmentLabel: environment.label, + rule: environment.capable ? pullRequestFeedRule(environment.settings, project.id) : null, + overridden: + environment.capable && + environment.settings.projectSettingsOverrides[project.id]?.pullRequestFeed !== undefined, + ...pullRequestFeedRuleAccess(environment), + }; + const group = groups.get(key); + if (group) group.copies.push(copy); + else + groups.set(key, { + name: identity?.displayName ?? identity?.canonicalKey ?? project.title, + copies: [copy], + }); + } + const rows = [...groups].map(([key, { name, copies }]) => { + const stored = copies.filter((copy) => copy.rule !== null); + const rules = [...new Set(stored.flatMap((copy) => (copy.rule === null ? [] : [copy.rule])))]; + const rule = rules.length === 1 ? rules[0]! : null; + const notes: string[] = []; + // With no known rule there is nothing to compare; the access notes say why. + if (stored.length > 0 && rule === null) { + const parts = rules.map((candidate) => { + const on = unique( + stored.filter((copy) => copy.rule === candidate).map((copy) => copy.environmentLabel), + ); + return `${ruleLabel(candidate)} on ${on.join(", ")}`; + }); + notes.push(`Differs: ${parts.join("; ")}.`); + } else if (stored.length > 0 && stored.every((copy) => !copy.overridden)) { + notes.push("Default rule."); + } + for (const access of ["disconnected", "outdated", "read-only"] as const) { + const on = unique( + copies.filter((copy) => copy.access === access).map((copy) => copy.environmentLabel), + ); + if (on.length > 0) notes.push(ACCESS_NOTES[access](on.join(", "))); + } + for (const organization of unique( + copies.flatMap((copy) => (copy.managedBy === null ? [] : [copy.managedBy])), + )) { + const on = unique( + copies + .filter((copy) => copy.managedBy === organization) + .map((copy) => copy.environmentLabel), + ); + notes.push(`Managed by ${organization} on ${on.join(", ")}.`); + } + return { + key, + name, + covers: `${unique(copies.map((copy) => copy.project.title)).join(", ")} · ${unique( + copies.map((copy) => copy.environmentLabel), + ).join(", ")}`, + copies, + rule, + known: stored.length > 0, + status: notes.join(" "), + canReset: copies.some((copy) => copy.overridden && copy.access === "writable"), + }; + }); + return rows.sort((left, right) => left.name.localeCompare(right.name)); +} + +/** + * The projects a pick writes: a rule goes to each writable copy not already on it, so a copy that + * inherits the rule keeps following the default; a reset (`null`) clears each writable override. + */ +export function pullRequestFeedRuleTargets( + row: Pick, "copies">, + rule: PullRequestFeedRule | null, +): ReadonlyArray { + return row.copies.flatMap((copy) => + copy.access === "writable" && (rule === null ? copy.overridden : copy.rule !== rule) + ? [copy.project] + : [], + ); +} diff --git a/packages/client-runtime/src/settingsWriter.test.ts b/packages/client-runtime/src/settingsWriter.test.ts new file mode 100644 index 0000000000000..3ceb2eb8eccbe --- /dev/null +++ b/packages/client-runtime/src/settingsWriter.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it, vi } from "@effect/vitest"; +import { + DEFAULT_SERVER_SETTINGS, + EnvironmentId, + ProjectId, + type ServerSettings, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; + +import { createScopedSettingsWriter, type ScopedSettingsPlan } from "./settingsWriter.ts"; + +const environmentId = EnvironmentId.make("server"); +const projectId = ProjectId.make("web"); + +describe("scoped settings writer", () => { + it("plans an empty save again from the save before it, and sends it only if it then changes something", async () => { + const copy: ServerSettings = { ...DEFAULT_SERVER_SETTINGS, projectSettingsOverrides: {} }; + let stored = copy; + const persistServer = vi.fn(async ({ input }: { input: { patch: ServerSettingsPatch } }) => { + stored = applyServerSettingsPatch(stored, input.patch); + return { _tag: "Success" as const, value: stored }; + }); + const environment = { + environmentId, + label: "Server", + connection: { phase: "connected" as const }, + serverConfig: { settings: copy }, + }; + // No config push arrives, so the client's copy stays as it was before the first save. + const write = createScopedSettingsWriter(() => copy); + const plan = + (patchFor: (settings: ServerSettings) => ServerSettingsPatch) => + (environments: ReadonlyArray): ScopedSettingsPlan => ({ + clientPatch: {}, + hasClientWrite: false, + unavailableReason: null, + serverWrites: environments.map((candidate) => ({ + environmentId, + label: candidate.label, + previous: candidate.serverConfig.settings, + patch: patchFor(candidate.serverConfig.settings), + })), + }); + const clearFeedRule = plan((settings) => + settings.projectSettingsOverrides[projectId]?.pullRequestFeed === undefined + ? {} + : { projectSettingsOverrides: { [projectId]: null } }, + ); + + await write([environment], clearFeedRule, persistServer, vi.fn()); + expect(persistServer).not.toHaveBeenCalled(); + + await Promise.all([ + write( + [environment], + plan(() => ({ projectSettingsOverrides: { [projectId]: { pullRequestFeed: "hidden" } } })), + persistServer, + vi.fn(), + ), + write([environment], clearFeedRule, persistServer, vi.fn()), + ]); + expect(persistServer).toHaveBeenCalledTimes(2); + expect(stored.projectSettingsOverrides[projectId]).toBeUndefined(); + }); +}); diff --git a/packages/client-runtime/src/settingsWriter.ts b/packages/client-runtime/src/settingsWriter.ts new file mode 100644 index 0000000000000..67f43dbd22c2c --- /dev/null +++ b/packages/client-runtime/src/settingsWriter.ts @@ -0,0 +1,243 @@ +import type { + ClientSettingsPatch, + EnvironmentId, + ServerSettings, + ServerSettingsPatch, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; + +import type { EnvironmentConnectionPhase } from "./connection/index.ts"; +import * as Equal from "effect/Equal"; + +/** One environment's server patch, with the settings it was planned from. */ +export interface ScopedServerWrite { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly patch: ServerSettingsPatch; + readonly previous: ServerSettings; +} + +export interface ScopedSettingsPlan { + readonly clientPatch: ClientSettingsPatch; + readonly hasClientWrite: boolean; + readonly serverWrites: readonly ScopedServerWrite[]; + readonly unavailableReason: string | null; +} + +export interface ScopedSettingsEnvironment { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly connection: { readonly phase: EnvironmentConnectionPhase }; + readonly serverConfig: { readonly settings: ServerSettings } | null; +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean { + if (value === null) return before != null && Equal.equals(saved, before); + if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) { + const field = (source: unknown, key: string) => + isPlainObject(source) ? source[key] : undefined; + return Object.entries(value).some(([key, next]) => + writeWasDropped(next, field(before, key), field(saved, key)), + ); + } + const unchanged = + typeof value === "string" && typeof before === "string" + ? value.trim() === before + : Equal.equals(value, before); + return !unchanged && Equal.equals(saved, before); +} + +/** Older servers silently drop unknown keys; report them so rows cannot stay mixed forever. */ +function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) { + if (saved === undefined) return []; + return Object.entries(write.patch).flatMap(([key, value]) => + writeWasDropped( + value, + write.previous[key as keyof ServerSettings], + saved[key as keyof ServerSettings], + ) + ? [key] + : [], + ); +} + +type ScopedSettingsPersistServer = (input: { + environmentId: EnvironmentId; + input: { patch: ServerSettingsPatch }; +}) => Promise<{ + readonly _tag: "Success" | "Failure"; + readonly cause?: Cause.Cause; + readonly value?: ServerSettings; +}>; + +export async function persistScopedSettingsPatch( + plan: ScopedSettingsPlan, + persistServer: ScopedSettingsPersistServer, + persistClient: (patch: ClientSettingsPatch) => void, +) { + return persistScopedSettingsPlan( + plan, + async (write) => ({ + write, + result: await persistServer({ + environmentId: write.environmentId, + input: { patch: write.patch }, + }), + }), + persistClient, + ); +} + +const OWN_ECHO_LIMIT = 8; + +/** + * Project overrides are whole entries built from this client's copy of the settings, and that + * copy hears about a save only when the server pushes it back. So saves to one environment run + * one at a time, each planned as it starts from the newest settings this client holds: the + * previous save's response, unless an independently changed copy has arrived. + */ +export function createScopedSettingsWriter< + Environment extends ScopedSettingsEnvironment = ScopedSettingsEnvironment, +>(readSettings: (environmentId: EnvironmentId) => ServerSettings | null) { + const queues = new Map>(); + const responses = new Map< + EnvironmentId, + { + readonly settings: ServerSettings; + readonly copy: ServerSettings; + readonly saved: readonly ServerSettings[]; + } + >(); + return ( + environments: readonly Environment[], + plan: (environments: readonly Environment[]) => ScopedSettingsPlan, + persistServer: ScopedSettingsPersistServer, + persistClient: (patch: ClientSettingsPatch) => void, + ) => + persistScopedSettingsPlan( + plan(environments), + (planned) => { + const { environmentId } = planned; + const save = (queues.get(environmentId) ?? Promise.resolve()).then(async () => { + const copy = readSettings(environmentId); + const response = responses.get(environmentId); + // A copy equal to one of our earlier responses is a delayed echo, older than the latest. + const isOwnEcho = (settings: ServerSettings) => + response?.saved.some((saved) => Equal.equals(saved, settings)) === true; + const continues = + copy !== null && response !== undefined && (response.copy === copy || isOwnEcho(copy)); + const settings = continues ? response.settings : copy; + const replanned = + settings === null ? null : plan(withSettings(environments, environmentId, settings)); + const write = + replanned?.serverWrites.find((next) => next.environmentId === environmentId) ?? planned; + // A save kept queued only in case an earlier one needed a follow-up; nothing to send. + if (Object.keys(write.patch).length === 0) { + return { + write, + result: { _tag: "Success" as const, value: settings ?? write.previous }, + }; + } + const result = await persistServer({ environmentId, input: { patch: write.patch } }); + const savedCopy = readSettings(environmentId); + if (result._tag === "Success" && result.value !== undefined && savedCopy !== null) { + // A changed copy may be a newer remote push or the delayed echo of our previous save. + if ( + savedCopy === copy || + Equal.equals(savedCopy, settings) || + Equal.equals(savedCopy, result.value) || + isOwnEcho(savedCopy) + ) { + responses.set(environmentId, { + settings: result.value, + copy: savedCopy, + saved: [...(continues ? response.saved : []), result.value].slice(-OWN_ECHO_LIMIT), + }); + } else { + responses.delete(environmentId); + } + } + return { write, result }; + }); + queues.set( + environmentId, + save.catch(() => undefined), + ); + return save; + }, + persistClient, + ); +} + +function withSettings( + environments: readonly Environment[], + environmentId: EnvironmentId, + settings: ServerSettings, +): readonly Environment[] { + return environments.map((environment) => + environment.environmentId === environmentId && environment.serverConfig + ? { ...environment, serverConfig: { ...environment.serverConfig, settings } } + : environment, + ); +} + +async function persistScopedSettingsPlan( + plan: ScopedSettingsPlan, + persistWrite: (write: ScopedServerWrite) => Promise<{ + readonly write: ScopedServerWrite; + readonly result: Awaited>; + }>, + persistClient: (patch: ClientSettingsPatch) => void, +) { + if (plan.hasClientWrite) persistClient(plan.clientPatch); + const results = await Promise.allSettled(plan.serverWrites.map(persistWrite)); + // A queued write is replanned before it is sent, so judge the write that was sent. + const writes = results.map((result, index) => + result.status === "fulfilled" ? result.value.write : plan.serverWrites[index]!, + ); + const saved = (index: number) => { + const result = results[index]; + return ( + result?.status === "fulfilled" && + result.value.result._tag === "Success" && + droppedSettingKeys(writes[index]!, result.value.result.value).length === 0 + ); + }; + const failedEnvironments = writes.flatMap((environment, index) => { + if (saved(index)) return []; + const result = results[index]; + if (result?.status === "fulfilled" && result.value.result._tag === "Success") { + return [ + { + ...environment, + message: "This environment does not support this setting. Update T3 Code on it.", + }, + ]; + } + const error: unknown = + result?.status === "rejected" + ? result.reason + : result?.status === "fulfilled" && result.value.result.cause + ? Cause.squash(result.value.result.cause) + : undefined; + return [ + { + ...environment, + message: + error instanceof Error + ? error.message + : "The save failed. Try reconnecting and saving again.", + }, + ]; + }); + const savedEnvironments = writes.filter((_, index) => saved(index)); + return { + failedEnvironments, + savedEnvironments, + savedEnvironmentCount: savedEnvironments.length, + }; +}
{row.name}
{row.covers}
{row.status}
Reconnect {scope.label} to change its settings.