@omercnet/paseo-pr-radar 3.4.0-next.543.1 → 3.4.0-next.545.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,10 +43,15 @@ DevTools before capture. Both PNGs come from an isolated Paseo test daemon at 2
43
43
  A routing script may return `"labels": {"key": "value"}`, and PR Radar puts them on the agent it launches (next to its own `pr-radar.cwd`). The script reads PR text on stdin, so its labels are untrusted and are checked as a whole:
44
44
 
45
45
  - **Namespaced by default.** A label key is stored as `pr-radar.route.<key>` (`{"kind": "external-review"}` becomes `pr-radar.route.kind=external-review`). The namespaced key must still fit the 128 character key limit.
46
- - **Allowed label prefixes** (setting `routingLabelPrefixes`, empty by default; comma or space separated, for example `ade.kind` or `ade.`). A key that a prefix admits keeps its own name. Everything else stays namespaced. A prefix admits a key that equals it, a key that continues it with `.` or `/` (`ade.kind` admits `ade.kind` and `ade.kind.x`, not `ade.kinder`; `team` admits `team/x`, not `teamx`), and every key under a prefix that itself ends in `.` or `/` (`ade.` admits `ade.anything`). That can include keys other tools treat as control labels, so list the narrowest prefix you trust (`ade.kind` does not admit `ade.lead`) rather than a whole family (`ade.`) unless every key under it is safe for a script to set. A prefix never admits a reserved key, and a prefix that is a root of or extends `pr-radar` or `paseo` (`p`, `paseo-`, `pr-radar/`) or a malformed entry voids the whole setting, so every script label then stays namespaced.
46
+ - **Allowed label prefixes** (setting `routingLabelPrefixes`, empty by default; separated by commas, ASCII spaces, tabs or line breaks, for example `ade.kind` or `ade.`; any other character, such as a no-break space, a byte order mark or an ideographic space, stays inside its entry and makes it malformed, so it can never split one entry into two valid ones). **An empty list protects nothing**: with no prefix, every script label is namespaced and no label counts as a downgrade label. A key that a prefix admits keeps its own name. Everything else stays namespaced. A prefix admits a key that equals it, a key that continues it with `.` or `/` (`ade.kind` admits `ade.kind` and `ade.kind.x`, not `ade.kinder`; `team` admits `team/x`, not `teamx`), and every key under a prefix that itself ends in `.` or `/` (`ade.` admits `ade.anything`). That can include keys other tools treat as control labels, so list the narrowest prefix you trust (`ade.kind` does not admit `ade.lead`) rather than a whole family (`ade.`) unless every key under it is safe for a script to set. A prefix never admits a reserved key, and a prefix that is a root of or extends `pr-radar` or `paseo` (`p`, `paseo-`, `pr-radar/`) or a malformed entry voids the whole setting, so every script label then stays namespaced.
47
47
  - **Always reserved:** `pr-radar`, `pr-radar.*` (including `pr-radar.cwd`, which PR Radar sets itself, and `pr-radar.route.*`, which only PR Radar writes), `paseo` and `paseo.*`, compared without regard to case. A script cannot set them; naming one is an invalid label.
48
48
  - **Limits:** at most 16 script labels (PR Radar adds `pr-radar.cwd`, so an agent carries up to 17), keys of letters, digits and `. _ / -` that start with a letter or digit, trimmed non-empty string values of at most 128 characters. A set with more than 64 keys is refused outright. Control characters (Unicode `Cc`), invisible or direction-changing format characters (`Cf`: zero-width characters, bidi overrides and isolates such as U+202A to U+202E and U+2066 to U+2069, the byte order mark), other default-ignorable characters (fillers, variation selectors), line and paragraph separators and lone surrogates are refused in keys and values. Notices quote the rejected keys and list the first five with `and N more`; the Start New Agent window lists every rejected key. Two keys that become the same label (for example after trimming) are both refused.
49
49
  - **All or nothing, never silent.** If any label is invalid, no label is applied and the launch is blocked on both paths. The start-agent modal shows each rejected key with its reason and disables **Start New Agent**; auto-launch starts nothing and shows the same notice. A label set the script returns therefore either applies or stops the launch. This covers the labels only: if the script itself fails (error, timeout, oversized output, or a result with another invalid field), the modal shows the error and can still launch with your own choices, and auto-launch uses PR Radar defaults, so the script's labels are absent in that case.
50
+ - **Temporary fallback rules** (setting `routingLabelFallbacks`, empty by default; add them in the routing script section of the settings). A rule is `{ repository: "owner/name" | "*", until: <ISO-8601 time with a zone>, note?: string }`. While a rule that matches the repository has not expired, a launch with invalid script labels goes ahead without any script label (all or nothing still holds) and shows a warning that names each rejected key and the rule. A rule must end within 7 days: a later one is refused when added, and one already stored with a later end is ignored until its end is within 7 days of the current time, then applies for those last days (the settings show it as ignored until then). A rule whose date does not exist (such as 2026-11-31) is refused when added and never applies. A rule note cannot hold control or invisible characters; any stored rule that fails validation (including an unsafe or over-long note or malformed repository) is dropped on load (fail closed). Expired rules show as expired in the settings. Use a rule to keep working while you fix the script, then remove it. **Upgrading from a release that stored rules before settings version 3 drops them** (any document older than version 3 is stripped of `routingLabelFallbacks` on load, so a rule an intermediate release retired cannot come back after a skipped upgrade); add a rule again if you still need it. **A rule never drops a downgrade label.** A downgrade label is one an Allowed label prefix trusts to keep its own name (for example `ade.kind=external-review`). With an empty Allowed label prefixes list no label is trusted that way, so nothing counts as a downgrade label and a rule may skip every script label (they are all namespaced `pr-radar.route.*`, which means nothing to other tools). If any key the script returned, valid or not, is admitted by a prefix (compared without regard to case, with invisible and compatibility characters normalized away on both the prefix and the key, and reading the prefix setting entry by entry even when one entry voids it), or if any Allowed label prefix is malformed (a look-alike letter, say, which no key can be matched against), or if the script's labels are not a key and value object while a prefix is set, the rule does not apply and the launch stays blocked, on both paths, with a message naming the label. Namespaced `pr-radar.route.*` labels mean nothing to other tools, so the rule may still skip those.
51
+
52
+ **What the never-drop guarantee covers.** It covers fallback rules only. It does not cover a routing script that fails: when the script itself errors, times out or prints output PR Radar cannot read, the modal shows the error and still lets you launch, and auto-launch uses PR Radar defaults, both without any script labels, so a downgrade label can be missing. That behavior comes from the routing labels feature and is a separate follow-up. If you rely on a downgrade label, make the script exit cleanly on every input.
53
+
54
+ **Whose clock decides.** A rule's end time and the seven day cap are read from the clock of the device that starts the launch, not the host's. The host does not check them. A device with a wrong clock can keep an expired rule alive or end one early, so keep device clocks synced. The Start New Agent window follows the rule as it ends while open, and the launch checks again when you press Start.
50
55
 
51
56
  When PR Radar checks out or fetches a repository, it runs `git` with a hardened environment: `~/.gitconfig` and the system git config are ignored, repository hooks, filters, credential helpers and transport helpers are neutralized, and GitHub credentials come only from the `gh` CLI (never from git's environment). Network proxies must be provided through the environment (`HTTPS_PROXY`/`http_proxy`/`NO_PROXY` and friends), not through git config.
52
57
  - Linked workspaces and agents include those in background workspaces. Helpers, meaning background
package/client/launch.ts CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  type LabelPolicy,
4
4
  RoutedLabelsBlockedError,
5
5
  } from "../shared/routed-labels";
6
- import type { PrRadarSettings } from "../shared/settings";
6
+ import { type PrRadarSettings, PrRadarSettingsSchema } from "../shared/settings";
7
7
  import type { RoutingScriptResult } from "../shared/viewer-scope";
8
8
  import {
9
9
  type AgentLaunchOverrides,
@@ -14,6 +14,7 @@ import {
14
14
  type CwdTag,
15
15
  type LabelableWorkspace,
16
16
  labelWorkspaceCwd,
17
+ type RadarRow,
17
18
  restrictRoutedLaunch,
18
19
  routedProviderModel,
19
20
  vetRoutedProfile,
@@ -56,10 +57,42 @@ export interface PreparedCwd {
56
57
  warning?: string;
57
58
  }
58
59
 
60
+ export type SettingsReadResult =
61
+ | { status: "ready"; revision: string; values: unknown }
62
+ | { status: "invalid"; revision: string; error: string };
63
+
64
+ export type ReadPrRadarSettingsRpc = (input: Record<string, never>) => Promise<SettingsReadResult>;
65
+
66
+ /**
67
+ * Reads and validates the current PR Radar settings directly from the daemon. Throws on an invalid
68
+ * status, schema parse failure, or RPC error so launches fail closed instead of reusing a stale or
69
+ * default policy.
70
+ */
71
+ export async function readCurrentLabelPolicy(
72
+ readSettings: ReadPrRadarSettingsRpc,
73
+ ): Promise<PrRadarSettings> {
74
+ const result = await readSettings({});
75
+ if (result.status !== "ready") {
76
+ const reason = result.error.trim();
77
+ throw new Error(
78
+ reason ? `PR Radar settings are invalid: ${reason}` : "PR Radar settings are invalid.",
79
+ );
80
+ }
81
+ const parsed = PrRadarSettingsSchema.safeParse(result.values);
82
+ if (!parsed.success) {
83
+ const detail = parsed.error.issues.map((issue) => issue.message).join("; ");
84
+ throw new Error(
85
+ detail ? `PR Radar settings are invalid: ${detail}` : "PR Radar settings are invalid.",
86
+ );
87
+ }
88
+ return parsed.data;
89
+ }
90
+
59
91
  export interface LaunchDeps {
60
92
  paseo: LaunchPaseo;
61
93
  prepareCwd(input: PrepareCwdInput): Promise<PreparedCwd>;
62
- policy: LabelPolicy;
94
+ readPolicy(): Promise<LabelPolicy>;
95
+ now(): number;
63
96
  }
64
97
 
65
98
  export interface LaunchedAgent {
@@ -69,8 +102,9 @@ export interface LaunchedAgent {
69
102
 
70
103
  /**
71
104
  * Starts the agent for a Start New Agent request, from the modal or from auto-launch. The routing
72
- * script's labels are validated here, before any worktree is prepared, so a path that skips its own
73
- * check still cannot launch with a label set PR Radar rejected.
105
+ * script's labels are validated against the live settings policy before any worktree is prepared
106
+ * and again right before `agents.create`, so neither a caller that skips its own check nor a
107
+ * policy change during preparation can launch with a label set PR Radar rejects.
74
108
  */
75
109
  export async function launchNewAgent(
76
110
  deps: LaunchDeps,
@@ -80,12 +114,18 @@ export async function launchNewAgent(
80
114
  if (!row.number) {
81
115
  throw new Error("An issue or pull request number is required to start a new agent.");
82
116
  }
83
- const decision = decideRoutedLabels({
84
- labels: request.overrides.labels,
85
- policy: deps.policy,
86
- });
87
- if (decision.status === "blocked") {
88
- throw new RoutedLabelsBlockedError(decision.message, decision.rejected);
117
+ const decide = async () => {
118
+ const policy = await deps.readPolicy();
119
+ return decideRoutedLabels({
120
+ labels: request.overrides.labels,
121
+ repository: row.repository,
122
+ policy,
123
+ now: deps.now(),
124
+ });
125
+ };
126
+ const early = await decide();
127
+ if (early.status === "blocked") {
128
+ throw new RoutedLabelsBlockedError(early.message, early.rejected);
89
129
  }
90
130
 
91
131
  const prepared = await deps.prepareCwd({
@@ -113,15 +153,24 @@ export async function launchNewAgent(
113
153
  profiles.find((candidate) => candidate.name.toLowerCase() === "model router") ??
114
154
  profiles[0];
115
155
 
156
+ // Preparing the worktree can be slow (a clone, a fetch), and the saved policy or a fallback rule
157
+ // may change or end meanwhile: read the current settings and clock right before creating the
158
+ // agent, so a prefix added during preparation or an expired rule cannot be bypassed.
159
+ const decision = await decide();
160
+ if (decision.status === "blocked") {
161
+ throw new RoutedLabelsBlockedError(decision.message, decision.rejected);
162
+ }
163
+ const accepted = decision.status === "ok" ? decision.labels : {};
116
164
  const created = await targetWorkspace.agents.create({
117
165
  config: buildAgentConfig(profile, request.overrides),
118
166
  title: `PR Radar: ${row.repository}#${row.number}`,
119
167
  prompt: buildAgentPrompt(row),
120
- labels: buildAgentLabels(prepared.cwdTag, decision.labels),
168
+ labels: buildAgentLabels(prepared.cwdTag, accepted),
121
169
  });
122
170
 
123
171
  const baseMsg = `Started new agent in ${prepared.cwdTag} (${prepared.cwd}) for ${row.repository}#${row.number}.`;
124
- const warnings = [request.routingWarning, prepared.warning].filter(Boolean);
172
+ const fallbackWarning = decision.status === "fallback" ? decision.warning : undefined;
173
+ const warnings = [request.routingWarning, fallbackWarning, prepared.warning].filter(Boolean);
125
174
  return {
126
175
  agentId: created.id,
127
176
  message: warnings.length > 0 ? `${warnings.join(" ")} ${baseMsg}` : baseMsg,
@@ -143,6 +192,8 @@ export interface AutoRoutingInput {
143
192
  routed: RoutingScriptResult;
144
193
  // Agent profiles from Paseo; only read when the script names a profile.
145
194
  profiles: readonly LaunchProfile[];
195
+ row: Pick<RadarRow, "repository">;
196
+ now: number;
146
197
  }
147
198
 
148
199
  export type AutoRouting =
@@ -159,8 +210,13 @@ export type AutoRouting =
159
210
  * label set PR Radar rejects stops the launch here instead of reaching the agent.
160
211
  */
161
212
  export function applyAutoRouting(input: AutoRoutingInput): AutoRouting {
162
- const { settings, routed, profiles } = input;
163
- const decision = decideRoutedLabels({ labels: routed.labels, policy: settings });
213
+ const { settings, routed, profiles, row, now } = input;
214
+ const decision = decideRoutedLabels({
215
+ labels: routed.labels,
216
+ repository: row.repository,
217
+ policy: settings,
218
+ now,
219
+ });
164
220
  if (decision.status === "blocked") return { status: "blocked", message: decision.message };
165
221
 
166
222
  let overrides = defaultLaunchOverrides(settings);
@@ -1,3 +1,4 @@
1
+ import { settingsRpc } from "@getpaseo/plugin";
1
2
  import {
2
3
  openExternalUrl,
3
4
  type PluginSurfaceProps,
@@ -23,7 +24,12 @@ import {
23
24
  runRoutingScript,
24
25
  } from "../shared/viewer-scope";
25
26
  import { HighlightedText } from "./highlighted-text";
26
- import { applyAutoRouting, defaultLaunchOverrides, launchNewAgent } from "./launch";
27
+ import {
28
+ applyAutoRouting,
29
+ defaultLaunchOverrides,
30
+ launchNewAgent,
31
+ readCurrentLabelPolicy,
32
+ } from "./launch";
27
33
  import {
28
34
  type AgentLaunchOverrides,
29
35
  agentActionFor,
@@ -57,6 +63,7 @@ import { useRadar } from "./use-radar";
57
63
  import { revealFocusedChip } from "./web";
58
64
 
59
65
  const CLOCK_TICK_MS = 30_000;
66
+ const readPrRadarSettingsRpc = settingsRpc(prRadarSettings.id).read;
60
67
 
61
68
  type SavedView = "security" | "updated" | "stale" | "automation";
62
69
 
@@ -102,6 +109,7 @@ export function PrRadar({
102
109
  const acknowledgeUpdates = useRpc(acknowledgeViewerScope);
103
110
  const prepareCwd = useRpc(prepareWorkspaceCwd);
104
111
  const invokeRouter = useRpc(runRoutingScript);
112
+ const readSettings = useRpc(readPrRadarSettingsRpc);
105
113
  const settingsState = useSettings(prRadarSettings);
106
114
  const settings =
107
115
  settingsState.status === "ready" ? settingsState.values : DEFAULT_PR_RADAR_SETTINGS;
@@ -241,7 +249,15 @@ export function PrRadar({
241
249
 
242
250
  const startNewAgentMutation = useMutation({
243
251
  mutationFn: async (request: StartAgentLaunchRequest) => {
244
- const launched = await launchNewAgent({ paseo, prepareCwd, policy: settings }, request);
252
+ const launched = await launchNewAgent(
253
+ {
254
+ paseo,
255
+ prepareCwd,
256
+ readPolicy: () => readCurrentLabelPolicy(readSettings),
257
+ now: Date.now,
258
+ },
259
+ request,
260
+ );
245
261
  if (navigation) {
246
262
  navigation.openAgent({ agentId: launched.agentId, serverId: host.id });
247
263
  }
@@ -329,7 +345,7 @@ export function PrRadar({
329
345
  const profiles = routed.profile
330
346
  ? ((await paseo.config.get()).config.agentProfiles ?? [])
331
347
  : [];
332
- const applied = applyAutoRouting({ settings, routed, profiles });
348
+ const applied = applyAutoRouting({ settings, routed, profiles, row, now: Date.now() });
333
349
  if (applied.status === "blocked") {
334
350
  setActionNotice(applied.message);
335
351
  return;
@@ -0,0 +1,359 @@
1
+ import { fallbackRuleTarget } from "../shared/routed-labels";
2
+
3
+ /**
4
+ * A change to a settings document: a partial value, or a function of the newest document that
5
+ * returns one. A list edit (add or remove a rule) must be a function, because the list it builds
6
+ * on may have changed while an earlier save was still in flight.
7
+ */
8
+ export type SettingsPatch<Values> = Partial<Values> | ((latest: Values) => Partial<Values>);
9
+
10
+ export interface SettingsSaveOptions<Values> {
11
+ /**
12
+ * Field values the caller's UI input was built from (mount, last resync, or this client's own
13
+ * accepted write). For uncontrolled inputs, pass this so conflict detection checks against what
14
+ * the user actually saw rather than `deps.latest()` at enqueue time.
15
+ */
16
+ base?: Partial<Values>;
17
+ }
18
+
19
+ export type SettingsParse<Values> =
20
+ | { success: true; data: Values }
21
+ | { success: false; message: string };
22
+
23
+ export interface SettingsSaveQueueDeps<Values> {
24
+ /** The newest document and revision known to the client; read when a queued write starts. */
25
+ latest(): { values: Values; revision: string };
26
+ /** Remembers a document that was just saved, before the host sends the new state back. */
27
+ remember(values: Values): void;
28
+ parse(values: Values): SettingsParse<Values>;
29
+ /** Writes the whole document against `revision`; resolves false on a concurrent change. */
30
+ write(values: Values, revision: string): Promise<boolean>;
31
+ /** Called with null when a write succeeds and with a message when it fails or conflicts. */
32
+ report(message: string | null): void;
33
+ /** Called with the conflicting field keys whenever a plain patch is refused for a same-field conflict. */
34
+ onConflict?(keys: Array<keyof Values>): void;
35
+ /** Sleeps; replaceable so a test controls the clock. Defaults to setTimeout. */
36
+ wait?(ms: number): Promise<void>;
37
+ /** A monotonic time in milliseconds that bounds the wait; replaceable like `wait`. Defaults to performance.now. */
38
+ now?(): number;
39
+ }
40
+
41
+ const RETRY_POLL_MS = 20;
42
+ const RETRY_MAX_WAIT_MS = 1000;
43
+
44
+ export const SAME_FIELD_CONFLICT_MESSAGE =
45
+ "Settings were not saved: another client changed the same setting. Review the updated value and apply your edit again.";
46
+
47
+ // A clock that never steps back: a wall clock set backwards (a time sync, a manual change) would
48
+ // keep the wait polling past its deadline and hold up every later save. Falls back to the wall
49
+ // clock only where `performance` does not exist.
50
+ function monotonicNow(): number {
51
+ return typeof performance !== "undefined" && typeof performance.now === "function"
52
+ ? performance.now()
53
+ : Date.now();
54
+ }
55
+
56
+ // Structural equality for plain JSON-like setting values (strings, primitives, arrays, objects),
57
+ // treating missing keys and explicit `undefined` keys alike.
58
+ function sameValue(a: unknown, b: unknown): boolean {
59
+ if (Object.is(a, b)) return true;
60
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
61
+ if (Array.isArray(a) || Array.isArray(b)) {
62
+ return (
63
+ Array.isArray(a) &&
64
+ Array.isArray(b) &&
65
+ a.length === b.length &&
66
+ a.every((item, index) => sameValue(item, b[index]))
67
+ );
68
+ }
69
+ const aRecord = a as Record<string, unknown>;
70
+ const bRecord = b as Record<string, unknown>;
71
+ const aKeys = Object.keys(aRecord).filter((key) => aRecord[key] !== undefined);
72
+ const bKeys = Object.keys(bRecord).filter((key) => bRecord[key] !== undefined);
73
+ if (aKeys.length !== bKeys.length) return false;
74
+ return aKeys.every((key) => Object.hasOwn(bRecord, key) && sameValue(aRecord[key], bRecord[key]));
75
+ }
76
+
77
+ interface QueuedPatch<Values> {
78
+ patch: SettingsPatch<Values>;
79
+ // Base values of the fields a plain patch expects to replace, captured when the edit was queued.
80
+ baseFields?: Partial<Values>;
81
+ settle(saved: boolean): void;
82
+ }
83
+
84
+ /**
85
+ * Saves settings one write at a time. Patches queued while a write is in flight are applied in
86
+ * order to the newest document when their write starts, so two quick edits both survive and a
87
+ * function patch never sees a stale list. A write the host refuses is retried once when a newer
88
+ * document has arrived, with every patch applied again to that document. A function patch must
89
+ * therefore be pure and idempotent: a retry can run on a document that already holds its effect
90
+ * (the host may have saved the write and lost the reply).
91
+ *
92
+ * Plain-patch conflict guarantee: for every key touched by a plain patch, the queue compares the
93
+ * server's current value against the expected base value (`options.base[key]` when provided by the
94
+ * caller, otherwise `deps.latest().values[key]` when the patch was queued). On attempt 0, any
95
+ * mismatch refuses immediately without writing; on retry (attempt 1), a mismatch refuses unless
96
+ * the server already holds this batch's own parsed value (the lost-reply case). Refused writes do
97
+ * not call `deps.report(null)`, so an existing conflict message stays visible while the conflict
98
+ * stands. For uncontrolled inputs, callers must supply the input's mounted or last-synced value in
99
+ * `options.base` (for example via `initFieldState` / `syncFieldFromServer` / `finishFieldSave`)
100
+ * and advance it only on resync or this client's own accepted write; without an explicit base, the
101
+ * queue only sees `deps.latest()` at enqueue time. Each caller learns whether the write holding
102
+ * its own patch succeeded.
103
+ */
104
+ export function createSettingsSaveQueue<Values extends object>(
105
+ deps: SettingsSaveQueueDeps<Values>,
106
+ ): (patch: SettingsPatch<Values>, options?: SettingsSaveOptions<Values>) => Promise<boolean> {
107
+ let queue: QueuedPatch<Values>[] = [];
108
+ let chain: Promise<void> = Promise.resolve();
109
+
110
+ async function flush(): Promise<void> {
111
+ const batch = queue;
112
+ queue = [];
113
+ if (batch.length === 0) return;
114
+ let saved = false;
115
+ try {
116
+ saved = await writeBatch(batch);
117
+ } catch (error) {
118
+ deps.report(error instanceof Error ? error.message : "Could not save settings.");
119
+ }
120
+ for (const entry of batch) entry.settle(saved);
121
+ }
122
+
123
+ // After a write the host reports the new revision on a later render, so the next write in the
124
+ // queue may start against the revision the previous write already replaced and be refused as
125
+ // a concurrent change. Wait for a newer revision until a clock deadline (not a count of waits,
126
+ // so a throttled background tab ends after one late timer); the caller then rebuilds the batch
127
+ // on it. Resolves null when none arrives.
128
+ async function newerThan(revision: string): Promise<{ values: Values; revision: string } | null> {
129
+ const wait = deps.wait ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms)));
130
+ const now = deps.now ?? monotonicNow;
131
+ const deadline = now() + RETRY_MAX_WAIT_MS;
132
+ for (;;) {
133
+ const newest = deps.latest();
134
+ if (newest.revision !== revision) return newest;
135
+ if (now() >= deadline) return null;
136
+ await wait(RETRY_POLL_MS);
137
+ }
138
+ }
139
+
140
+ async function writeBatch(batch: QueuedPatch<Values>[]): Promise<boolean> {
141
+ const plainBase = new Map<keyof Values, unknown>();
142
+ for (const { baseFields } of batch) {
143
+ if (!baseFields) continue;
144
+ for (const key of Object.keys(baseFields) as Array<keyof Values>) {
145
+ if (!plainBase.has(key)) plainBase.set(key, baseFields[key]);
146
+ }
147
+ }
148
+ let base = deps.latest();
149
+ for (let attempt = 0; attempt < 2; attempt++) {
150
+ let next = base.values;
151
+ for (const { patch } of batch) {
152
+ next = { ...next, ...(typeof patch === "function" ? patch(next) : patch) };
153
+ }
154
+ const parsed = deps.parse(next);
155
+ if (!parsed.success) {
156
+ deps.report(parsed.message);
157
+ return false;
158
+ }
159
+ const conflicts: Array<keyof Values> = [];
160
+ for (const [key, expected] of plainBase) {
161
+ const current = base.values[key];
162
+ const isLostReplyMatch = attempt > 0 && sameValue(parsed.data[key], current);
163
+ if (!sameValue(expected, current) && !isLostReplyMatch) {
164
+ conflicts.push(key);
165
+ }
166
+ }
167
+ if (conflicts.length > 0) {
168
+ deps.onConflict?.(conflicts);
169
+ deps.report(SAME_FIELD_CONFLICT_MESSAGE);
170
+ return false;
171
+ }
172
+ const written = await deps.write(parsed.data, base.revision);
173
+ if (written !== false) {
174
+ deps.remember(parsed.data);
175
+ deps.report(null);
176
+ // Carry this client's own accepted plain-field writes forward as the expected base for any
177
+ // follow-up edits already queued while this write was in flight (for example rapid typing).
178
+ for (const [key, expected] of plainBase) {
179
+ for (const pending of queue) {
180
+ if (
181
+ pending.baseFields &&
182
+ Object.hasOwn(pending.baseFields, key) &&
183
+ sameValue(pending.baseFields[key], expected)
184
+ ) {
185
+ pending.baseFields[key] = parsed.data[key];
186
+ }
187
+ }
188
+ }
189
+ return true;
190
+ }
191
+ // Refused. The host says no more than "false" for a stale revision, a document it rejects
192
+ // and a lost connection alike, so retry only when a newer document has actually arrived
193
+ // (the stale-revision case); otherwise a retry would just repeat the refusal.
194
+ if (attempt === 0) {
195
+ const newest = await newerThan(base.revision);
196
+ if (!newest) break;
197
+ base = newest;
198
+ }
199
+ }
200
+ deps.report(
201
+ "Settings were not saved: they changed in the meantime or the host refused the write. Please retry.",
202
+ );
203
+ return false;
204
+ }
205
+
206
+ return (patch, options) =>
207
+ new Promise<boolean>((resolve) => {
208
+ let baseFields: Partial<Values> | undefined;
209
+ if (typeof patch !== "function") {
210
+ const current = deps.latest().values;
211
+ const explicitBase = options?.base;
212
+ const snapshot: Partial<Values> = {};
213
+ for (const key of Object.keys(patch) as Array<keyof Values>) {
214
+ snapshot[key] =
215
+ explicitBase && Object.hasOwn(explicitBase, key) ? explicitBase[key] : current[key];
216
+ }
217
+ baseFields = snapshot;
218
+ }
219
+ queue.push({ patch, baseFields, settle: resolve });
220
+ chain = chain.then(flush);
221
+ });
222
+ }
223
+
224
+ /**
225
+ * Tracks an uncontrolled text input's base value, local draft, server value, remount key and
226
+ * conflict state. `base` advances only on resync (external update with no local edit, or explicit
227
+ * user resync) or after this client's own accepted write, so an uncontrolled input never silently
228
+ * reverts an external update on a later keystroke.
229
+ */
230
+ export interface UncontrolledFieldState {
231
+ base: string;
232
+ draft: string;
233
+ server: string;
234
+ mountKey: number;
235
+ conflicted: boolean;
236
+ }
237
+
238
+ export function initFieldState(server: string): UncontrolledFieldState {
239
+ return { base: server, draft: server, server, mountKey: 0, conflicted: false };
240
+ }
241
+
242
+ // Called when the host delivers a new server value for the field. If this client holds no unsaved
243
+ // edit, no in-flight save and no standing conflict, resync and bump `mountKey` so the uncontrolled
244
+ // input displays the new value. Otherwise preserve the local edit, base and conflict state while
245
+ // recording the latest server value so the UI can show it.
246
+ export function syncFieldFromServer(
247
+ state: UncontrolledFieldState,
248
+ server: string,
249
+ inFlight: boolean,
250
+ ): UncontrolledFieldState {
251
+ if (server === state.server) return state;
252
+ const hasUnsaved = state.conflicted || inFlight || state.draft !== state.base;
253
+ if (!hasUnsaved) {
254
+ return {
255
+ base: server,
256
+ draft: server,
257
+ server,
258
+ mountKey: state.mountKey + 1,
259
+ conflicted: false,
260
+ };
261
+ }
262
+ return { ...state, server };
263
+ }
264
+
265
+ export function editFieldDraft(
266
+ state: UncontrolledFieldState,
267
+ next: string,
268
+ ): UncontrolledFieldState {
269
+ return { ...state, draft: next };
270
+ }
271
+
272
+ export function finishFieldSave(
273
+ state: UncontrolledFieldState,
274
+ written: string,
275
+ saved: boolean,
276
+ conflicted: boolean,
277
+ ): UncontrolledFieldState {
278
+ if (saved) {
279
+ return { ...state, base: written, conflicted: false };
280
+ }
281
+ if (conflicted) {
282
+ return { ...state, conflicted: true };
283
+ }
284
+ return state;
285
+ }
286
+
287
+ export function resyncFieldToServer(state: UncontrolledFieldState): UncontrolledFieldState {
288
+ return {
289
+ base: state.server,
290
+ draft: state.server,
291
+ server: state.server,
292
+ mountKey: state.mountKey + 1,
293
+ conflicted: false,
294
+ };
295
+ }
296
+
297
+ interface RuleIdentity {
298
+ repository: string;
299
+ until: string;
300
+ note?: string | undefined;
301
+ }
302
+
303
+ // Two rules with the same repository (any case) and end instant do the same thing, however they
304
+ // are written; the first one listed is the one that applies, so a second would only use a slot.
305
+ function sameTarget(a: RuleIdentity, b: RuleIdentity): boolean {
306
+ return fallbackRuleTarget(a) === fallbackRuleTarget(b);
307
+ }
308
+
309
+ function sameText(a: RuleIdentity, b: RuleIdentity): boolean {
310
+ return a.repository === b.repository && a.until === b.until && (a.note ?? "") === (b.note ?? "");
311
+ }
312
+
313
+ // The note is part of what the user sees, so removing a rule matches it too.
314
+ function sameRule(a: RuleIdentity, b: RuleIdentity): boolean {
315
+ return sameTarget(a, b) && (a.note ?? "") === (b.note ?? "");
316
+ }
317
+
318
+ // Appends a rule to the newest list. A rule that does the same as one already there (its note
319
+ // aside) is not added again: the rule already in the list stays as it is.
320
+ export function addFallbackRule<Rule extends RuleIdentity>(
321
+ rules: readonly Rule[],
322
+ rule: Rule,
323
+ ): Rule[] {
324
+ return rules.some((existing) => sameTarget(existing, rule)) ? [...rules] : [...rules, rule];
325
+ }
326
+
327
+ // An add-rule patch that also tells the caller whether the add changed anything. The question is
328
+ // answered by the list the patch last ran on inside the save queue, which holds every edit queued
329
+ // before it, so a rule whose removal is still pending is not "already there" and a rule whose
330
+ // add is still pending is. (A check against the rendered settings would see neither.)
331
+ //
332
+ // `wasDuplicate` is true only when the list holds an equivalent rule that is not this one as
333
+ // written (it differs in its note, which the add would drop). A rule that is already listed
334
+ // exactly as entered counts as saved: that is what a double press of Add, or a retry after a lost
335
+ // reply (the host saved this very add), finds.
336
+ export function fallbackRuleAdder<Rule extends RuleIdentity>(rule: Rule) {
337
+ let duplicate = false;
338
+ return {
339
+ patch(latest: { routingLabelFallbacks: readonly Rule[] }) {
340
+ const listed = latest.routingLabelFallbacks.find((existing) => sameTarget(existing, rule));
341
+ duplicate = listed !== undefined && !sameText(listed, rule);
342
+ return { routingLabelFallbacks: addFallbackRule(latest.routingLabelFallbacks, rule) };
343
+ },
344
+ wasDuplicate: () => duplicate,
345
+ };
346
+ }
347
+
348
+ // Removes a rule from the newest list by what it says, not by its position: the position the
349
+ // user pressed may belong to an older list. The row pressed (exactly as written) goes first; a
350
+ // rule that only reads the same (case, end written another way) is the fallback, so a list that
351
+ // already holds equivalent rows loses the one that was pressed.
352
+ export function removeFallbackRule<Rule extends RuleIdentity>(
353
+ rules: readonly Rule[],
354
+ rule: RuleIdentity,
355
+ ): Rule[] {
356
+ const exact = rules.findIndex((existing) => sameText(existing, rule));
357
+ const at = exact >= 0 ? exact : rules.findIndex((existing) => sameRule(existing, rule));
358
+ return at < 0 ? [...rules] : rules.filter((_, index) => index !== at);
359
+ }