@in-the-loop-labs/pair-review 4.1.1 → 5.0.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.
Files changed (71) hide show
  1. package/README.md +81 -13
  2. package/package.json +6 -2
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/plugin-pair-loop/skills/loop/SKILL.md +17 -8
  7. package/public/css/ai-summary-modal.css +1 -1
  8. package/public/css/analysis-config.css +33 -49
  9. package/public/css/council-card.css +118 -0
  10. package/public/css/council-dropdown.css +164 -0
  11. package/public/css/pr.css +668 -393
  12. package/public/css/repo-settings.css +15 -305
  13. package/public/css/settings.css +1141 -0
  14. package/public/css/snippet-manager.css +233 -0
  15. package/public/index.html +40 -59
  16. package/public/js/components/AIPanel.js +82 -16
  17. package/public/js/components/ChatPanel.js +401 -5
  18. package/public/js/components/CouncilCard.js +202 -0
  19. package/public/js/components/CouncilDropdown.js +292 -0
  20. package/public/js/components/DiffOptionsDropdown.js +177 -4
  21. package/public/js/components/SnippetManager.js +463 -0
  22. package/public/js/index.js +7 -30
  23. package/public/js/local.js +20 -2
  24. package/public/js/modules/comment-manager.js +8 -1
  25. package/public/js/modules/comment-minimizer.js +249 -190
  26. package/public/js/modules/diff-renderer.js +16 -4
  27. package/public/js/modules/external-comment-manager.js +414 -48
  28. package/public/js/modules/file-comment-manager.js +28 -21
  29. package/public/js/modules/hunk-summary-renderer.js +155 -29
  30. package/public/js/modules/pierre-bridge.js +2513 -0
  31. package/public/js/modules/pierre-context.js +345 -0
  32. package/public/js/modules/suggestion-manager.js +176 -20
  33. package/public/js/modules/tour-renderer.js +400 -184
  34. package/public/js/pr.js +1614 -158
  35. package/public/js/repo-settings.js +60 -284
  36. package/public/js/settings.js +1086 -0
  37. package/public/js/theme-bootstrap.js +40 -0
  38. package/public/js/theme.js +247 -0
  39. package/public/js/utils/provider-model.js +3 -3
  40. package/public/js/utils/suggestion-ui.js +157 -8
  41. package/public/local.html +20 -31
  42. package/public/pr.html +14 -23
  43. package/public/repo-settings.html +24 -14
  44. package/public/settings.html +138 -0
  45. package/public/setup.html +8 -13
  46. package/src/chat/api-reference.js +9 -5
  47. package/src/chat/prompt-builder.js +8 -1
  48. package/src/config.js +15 -6
  49. package/src/database.js +307 -14
  50. package/src/external/github-adapter.js +39 -5
  51. package/src/headless/delegate.js +682 -0
  52. package/src/local-review.js +10 -10
  53. package/src/local-scope.js +9 -0
  54. package/src/main.js +276 -157
  55. package/src/mcp-stdio.js +24 -1
  56. package/src/review-config.js +93 -25
  57. package/src/routes/chat.js +2 -2
  58. package/src/routes/config.js +12 -10
  59. package/src/routes/external-comments.js +5 -1
  60. package/src/routes/local.js +2 -4
  61. package/src/routes/mcp.js +18 -13
  62. package/src/routes/reviews.js +223 -4
  63. package/src/routes/settings.js +252 -0
  64. package/src/routes/setup.js +80 -1
  65. package/src/routes/shared.js +31 -29
  66. package/src/routes/snippets.js +154 -0
  67. package/src/routes/stack-analysis.js +17 -14
  68. package/src/server.js +86 -18
  69. package/src/settings/global-settings-service.js +472 -0
  70. package/src/settings/registry.js +624 -0
  71. package/src/utils/db-identity.js +44 -0
@@ -0,0 +1,1086 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Global Settings Page JavaScript
4
+ *
5
+ * Renders the effective value + source of every global setting from
6
+ * GET /api/settings, lets the user edit dynamic/advanced settings with an
7
+ * immediate per-setting PUT, and reset in-app overrides with DELETE. Also
8
+ * lists configured/known repositories from GET /api/settings/repos.
9
+ *
10
+ * In-app edits persist to the app database (never to config files); the
11
+ * source badge makes "not explicitly set" (source = default) obvious.
12
+ */
13
+
14
+ /* global window, document, fetch, localStorage */
15
+
16
+ // Ordered group sections. Each entry: [groupKey, title, description].
17
+ const SETTINGS_GROUPS = [
18
+ ['general', 'General', 'Basic application preferences.'],
19
+ ['ai', 'AI Defaults', 'Default provider and model used for analysis and chat.'],
20
+ ['summaries', 'Summaries', 'Automatic PR summary generation.'],
21
+ ['tours', 'Tours', 'Automatic code tour generation.'],
22
+ ['chat', 'Chat', 'The AI chat assistant.'],
23
+ ['advanced', 'Advanced', 'These are captured at startup — changes take effect after you restart pair-review.'],
24
+ ['readonly', 'From config files & environment', 'Read-only here. Set these via config files, CLI flags, or environment variables.']
25
+ ];
26
+
27
+ // Keys whose string value should be picked from an ANALYSIS provider dropdown
28
+ // (from GET /api/providers) rather than a free-text input.
29
+ const PROVIDER_KEYS = new Set([
30
+ 'default_provider',
31
+ 'tours.provider',
32
+ 'summaries.provider'
33
+ ]);
34
+
35
+ // Keys whose string value should be picked from a CHAT provider dropdown. Chat
36
+ // providers are a separate namespace (GET /api/config → chat_providers) from
37
+ // analysis providers, so they must not be sourced from PROVIDER_KEYS.
38
+ const CHAT_PROVIDER_KEYS = new Set([
39
+ 'chat_provider'
40
+ ]);
41
+
42
+ // Model-valued string keys. Rendered as a free-text <input list> backed by a
43
+ // <datalist> of known models (union across analysis providers) — discoverable
44
+ // and typo-resistant, but still accepts a valid-but-unlisted model id (the
45
+ // effective provider can be "inherit" or vary per row, so a hard <select> would
46
+ // wrongly reject legitimate ids). Mirrors the PROVIDER_KEYS pattern so the three
47
+ // model rows stay consistent.
48
+ const MODEL_KEYS = new Set([
49
+ 'default_model',
50
+ 'summaries.model',
51
+ 'tours.model'
52
+ ]);
53
+
54
+ // Keys whose value is the "Default for Analysis" selection: EITHER the base
55
+ // Default Provider/Model pair (empty value) OR a saved council id. Rendered with
56
+ // the shared rich CouncilDropdown component (public/js/components/CouncilDropdown.js),
57
+ // mounted after render — not a native <select> — so the picker shows what you're
58
+ // selecting (council name + Standard/Advanced type), matching the repo settings
59
+ // page. Mirrors PROVIDER_KEYS/CHAT_PROVIDER_KEYS special-casing.
60
+ const COUNCIL_KEYS = new Set([
61
+ 'default_council_id'
62
+ ]);
63
+
64
+ // Map the API `source` enum to a display label + CSS modifier class.
65
+ const SOURCE_DISPLAY = {
66
+ app: { label: 'in-app', cls: 'app' },
67
+ env: { label: 'env', cls: 'env' },
68
+ 'project.local': { label: 'project config.local', cls: 'file' },
69
+ project: { label: 'project config', cls: 'file' },
70
+ 'config.local': { label: 'config.local.json', cls: 'file' },
71
+ config: { label: 'config.json', cls: 'file' },
72
+ managed: { label: 'managed', cls: 'managed' },
73
+ default: { label: 'default', cls: 'default' }
74
+ };
75
+
76
+ // Stable DOM id for the (static) Repositories section, and its nav title.
77
+ const REPOS_SECTION_ID = 'repos-section';
78
+ const REPOS_NAV_TITLE = 'Repositories';
79
+
80
+ // Stable DOM id for the (static) Chat Snippets section, and its nav title.
81
+ const SNIPPETS_SECTION_ID = 'snippets-section';
82
+ const SNIPPETS_NAV_TITLE = 'Chat Snippets';
83
+
84
+ class SettingsPage {
85
+ constructor() {
86
+ // Map of key -> descriptor from the API (kept in sync after PUT/DELETE).
87
+ this.settingsByKey = {};
88
+ // Array of analysis provider definitions from /api/providers.
89
+ this.providers = [];
90
+ // Array of chat provider definitions from /api/config (chat_providers).
91
+ this.chatProviders = [];
92
+ // Array of saved councils from /api/councils (for the default-council key).
93
+ this.councils = [];
94
+ // Mounted CouncilDropdown instances keyed by setting key, so a re-render can
95
+ // tear down the previous instance (its document outside-click listener)
96
+ // before mounting a fresh one.
97
+ this._councilDropdowns = {};
98
+ // CouncilCard composition-preview instances keyed by setting key (no
99
+ // listeners, so no teardown needed — re-created if the container changes).
100
+ this._councilCards = {};
101
+ // Per-key monotonic sequence for serializing in-flight mutations (PUT/DELETE)
102
+ // so a stale response can never overwrite a newer one. See updateSetting.
103
+ this._seq = {};
104
+ // Ordered section metadata from GET /api/settings (id/title/description/
105
+ // badge). Null until loaded; computeSections falls back to SETTINGS_GROUPS.
106
+ this.apiSections = null;
107
+ // Sections actually rendered (from computeSections); drives the side nav.
108
+ this.sections = [];
109
+ // Whether the Repositories section is visible (loaded successfully).
110
+ this.reposVisible = false;
111
+ // Whether the Chat Snippets section is visible (mounted successfully).
112
+ this.snippetsVisible = false;
113
+ // Mounted SnippetManager instance, if any.
114
+ this._snippetManager = null;
115
+ // Current active nav target id (scrollspy).
116
+ this.activeNavId = null;
117
+
118
+ this.init();
119
+ }
120
+
121
+ async init() {
122
+ this.initTheme();
123
+ this.setupEventDelegation();
124
+
125
+ // Providers are needed to render provider dropdowns; load first but do not
126
+ // block settings rendering fatally if it fails. Analysis providers and chat
127
+ // providers come from different endpoints and are independent — load both
128
+ // before settings so every dropdown can render against the right list.
129
+ await Promise.all([this.loadProviders(), this.loadChatProviders(), this.loadCouncils()]);
130
+ await this.loadSettings();
131
+ await this.loadRepos();
132
+ this.mountSnippets();
133
+
134
+ // Build the side navigation once the sections it points at are in the DOM.
135
+ this.buildNavigation();
136
+ }
137
+
138
+ // ─── Theme ────────────────────────────────────────────────────────────────
139
+
140
+ initTheme() {
141
+ // Shared helper owns preference storage, the light → dark → system toggle
142
+ // cycle, the button icon, and the live OS-change listener (js/theme.js).
143
+ window.PairReviewTheme.setup();
144
+ }
145
+
146
+ // ─── Data loading ─────────────────────────────────────────────────────────
147
+
148
+ async loadProviders() {
149
+ try {
150
+ const response = await fetch('/api/providers');
151
+ if (!response.ok) throw new Error('Failed to fetch providers');
152
+ const data = await response.json();
153
+ // Keep only providers that actually have models configured.
154
+ this.providers = (data.providers || []).filter(p => p.models && p.models.length > 0);
155
+ } catch (error) {
156
+ console.error('Error loading providers:', error);
157
+ this.providers = [];
158
+ }
159
+ }
160
+
161
+ async loadChatProviders() {
162
+ try {
163
+ const response = await fetch('/api/config');
164
+ if (!response.ok) throw new Error('Failed to fetch config');
165
+ const data = await response.json();
166
+ // chat_providers: [{ id, name, type, available }]. Kept as-is; the select
167
+ // renderer only needs id + name and preserves an unknown current value.
168
+ this.chatProviders = Array.isArray(data.chat_providers) ? data.chat_providers : [];
169
+ } catch (error) {
170
+ console.error('Error loading chat providers:', error);
171
+ this.chatProviders = [];
172
+ }
173
+ }
174
+
175
+ async loadCouncils() {
176
+ try {
177
+ const response = await fetch('/api/councils');
178
+ if (!response.ok) throw new Error('Failed to fetch councils');
179
+ const data = await response.json();
180
+ // councils: [{ id, name, type }]. The select renderer preserves an
181
+ // unknown current value so a stale/deleted council id still shows.
182
+ this.councils = Array.isArray(data.councils) ? data.councils : [];
183
+ } catch (error) {
184
+ console.error('Error loading councils:', error);
185
+ this.councils = [];
186
+ }
187
+ }
188
+
189
+ async loadSettings() {
190
+ const loadingEl = document.getElementById('settings-loading');
191
+ const errorEl = document.getElementById('settings-error');
192
+ try {
193
+ const response = await fetch('/api/settings');
194
+ if (!response.ok) throw new Error(`Failed to fetch settings (${response.status})`);
195
+ const data = await response.json();
196
+ const settings = data.settings || [];
197
+ // Section metadata (order/titles/descriptions/badges) is additive: older
198
+ // backends omit it, in which case computeSections falls back locally.
199
+ this.apiSections = Array.isArray(data.sections) ? data.sections : null;
200
+
201
+ this.settingsByKey = {};
202
+ for (const s of settings) {
203
+ this.settingsByKey[s.key] = s;
204
+ }
205
+
206
+ if (loadingEl) loadingEl.style.display = 'none';
207
+ this.renderSections(settings);
208
+ } catch (error) {
209
+ console.error('Error loading settings:', error);
210
+ if (loadingEl) loadingEl.style.display = 'none';
211
+ if (errorEl) {
212
+ errorEl.style.display = 'block';
213
+ errorEl.textContent = 'Failed to load settings. Please refresh the page.';
214
+ }
215
+ }
216
+ }
217
+
218
+ async loadRepos() {
219
+ const section = document.getElementById('repos-section');
220
+ const list = document.getElementById('repos-list');
221
+ if (!section || !list) return;
222
+
223
+ try {
224
+ const response = await fetch('/api/settings/repos');
225
+ if (!response.ok) throw new Error('Failed to fetch repos');
226
+ const data = await response.json();
227
+ this.renderRepos(data.repos || []);
228
+ section.style.display = '';
229
+ this.reposVisible = true;
230
+ } catch (error) {
231
+ console.error('Error loading repositories:', error);
232
+ // Leave the section hidden on error — it is supplementary.
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Mount the shared SnippetManager into the (static) Chat Snippets section.
238
+ * The component fetches its own data and renders its own empty/error states,
239
+ * so the section stays visible as long as the component is available. Hidden
240
+ * if the component script failed to load.
241
+ */
242
+ mountSnippets() {
243
+ const section = document.getElementById(SNIPPETS_SECTION_ID);
244
+ const mount = document.getElementById('snippets-manager');
245
+ if (!section || !mount) return;
246
+
247
+ if (typeof SnippetManager === 'undefined') {
248
+ section.style.display = 'none';
249
+ return;
250
+ }
251
+
252
+ try {
253
+ this._snippetManager = new SnippetManager(mount);
254
+ section.style.display = '';
255
+ this.snippetsVisible = true;
256
+ } catch (error) {
257
+ console.error('Error mounting snippet manager:', error);
258
+ section.style.display = 'none';
259
+ }
260
+ }
261
+
262
+ // ─── Rendering ────────────────────────────────────────────────────────────
263
+
264
+ /**
265
+ * Pure: compute the ordered list of sections that will actually render,
266
+ * skipping groups with no settings. Order/titles/descriptions/badges come
267
+ * from the API `sections` payload when present (the backend is authoritative
268
+ * and already omits empty sections); otherwise they fall back to the built-in
269
+ * SETTINGS_GROUPS derivation. This is the single source of truth shared by
270
+ * renderSections and the side navigation, so the nav can never drift from
271
+ * what's on the page.
272
+ *
273
+ * @param {Array} settings - setting descriptors from GET /api/settings
274
+ * @param {Array} [apiSections] - `sections` payload: {id,title,description,badge}
275
+ * @returns {Array<{groupKey, id, title, description, badge, settings}>}
276
+ */
277
+ computeSections(settings, apiSections) {
278
+ const byGroup = {};
279
+ for (const s of (settings || [])) {
280
+ (byGroup[s.group] = byGroup[s.group] || []).push(s);
281
+ }
282
+
283
+ // Metadata + order: prefer the server payload, fall back to SETTINGS_GROUPS.
284
+ // `hidden` is a build-time visibility default carried on the sections
285
+ // payload (registry SECTIONS `hidden: true`); such sections (and their nav
286
+ // entries) are omitted here.
287
+ const groupMeta = (Array.isArray(apiSections) && apiSections.length)
288
+ ? apiSections.map(s => ({
289
+ groupKey: s.id, title: s.title, description: s.description, badge: s.badge || null, hidden: Boolean(s.hidden)
290
+ }))
291
+ : SETTINGS_GROUPS.map(([groupKey, title, description]) => ({
292
+ groupKey, title, description, badge: null, hidden: false
293
+ }));
294
+
295
+ const sections = [];
296
+ for (const meta of groupMeta) {
297
+ if (meta.hidden) continue;
298
+ const groupSettings = byGroup[meta.groupKey];
299
+ if (!groupSettings || groupSettings.length === 0) continue;
300
+ sections.push({
301
+ groupKey: meta.groupKey,
302
+ id: `section-${meta.groupKey}`,
303
+ title: meta.title,
304
+ description: meta.description,
305
+ badge: meta.badge || null,
306
+ settings: groupSettings
307
+ });
308
+ }
309
+ return sections;
310
+ }
311
+
312
+ renderSections(settings) {
313
+ const container = document.getElementById('settings-sections');
314
+ if (!container) return;
315
+
316
+ this.sections = this.computeSections(settings, this.apiSections);
317
+
318
+ let html = '';
319
+ for (const section of this.sections) {
320
+ const rows = section.settings.map(s => this.settingRowHtml(s)).join('');
321
+ html += `
322
+ <section class="settings-section" id="${section.id}">
323
+ <div class="section-header">
324
+ <h2>${this.escapeHtml(section.title)}${this.badgePillHtml(section.badge)}</h2>
325
+ ${section.description ? `<p class="section-description">${this.escapeHtml(section.description)}</p>` : ''}
326
+ </div>
327
+ <div class="settings-rows">
328
+ ${rows}
329
+ </div>
330
+ </section>`;
331
+ }
332
+
333
+ container.innerHTML = html;
334
+ // Object read-onlys leave their <pre> empty in the HTML string; fill them
335
+ // now via textContent (no HTML escaping of the JSON).
336
+ this.populateObjectValues(container);
337
+ // Council keys render a mount point; instantiate the shared dropdown into it.
338
+ this.mountCouncilDropdowns(container);
339
+ }
340
+
341
+ /**
342
+ * Full HTML for one setting row (info column + control column).
343
+ */
344
+ settingRowHtml(setting) {
345
+ return `<div class="setting-row" data-key="${this.escapeHtml(setting.key)}">${this.rowInnerHtml(setting)}</div>`;
346
+ }
347
+
348
+ /**
349
+ * Inner HTML of a setting row — regenerated after each PUT/DELETE so the
350
+ * badge, control value, and reset visibility stay in sync with the server.
351
+ */
352
+ rowInnerHtml(setting) {
353
+ const src = SOURCE_DISPLAY[setting.source] || SOURCE_DISPLAY.default;
354
+ const isOverride = setting.source === 'app';
355
+ const isFinal = setting.final === true;
356
+ // A finalized key is locked by configuration: never a resettable override.
357
+ const showReset = isOverride && setting.editable && !isFinal;
358
+ const showRestart = setting.restartRequired && isOverride;
359
+
360
+ const badge = `<span class="source-badge source-badge--${src.cls}" data-role="badge" title="Source: ${this.escapeHtml(src.label)}">${this.escapeHtml(src.label)}</span>`;
361
+ const featureBadge = this.badgePillHtml(setting.badge);
362
+ const finalBadge = isFinal ? this.finalBadgeHtml() : '';
363
+ const restart = `<span class="restart-note" data-role="restart"${showRestart ? '' : ' hidden'}>
364
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="currentColor"><path d="M8 3a5 5 0 100 10A5 5 0 008 3zM1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zm6.5-3.25a.75.75 0 01.75.75v2.5l1.5 1a.75.75 0 11-.83 1.25l-1.84-1.23a.75.75 0 01-.33-.62V5.5A.75.75 0 018 4.75z"/></svg>
365
+ Takes effect after restart</span>`;
366
+
367
+ const control = setting.group === 'readonly' || !setting.editable
368
+ ? this.readonlyValueHtml(setting)
369
+ : this.controlHtml(setting);
370
+
371
+ const resetBtn = `<button type="button" class="reset-btn" data-role="reset"${showReset ? '' : ' hidden'}>Reset</button>`;
372
+
373
+ return `
374
+ <div class="setting-info">
375
+ <div class="setting-label-row">
376
+ <span class="setting-label">${this.escapeHtml(setting.label)}</span>
377
+ ${featureBadge}
378
+ ${badge}
379
+ ${finalBadge}
380
+ </div>
381
+ ${setting.description ? `<p class="setting-description">${this.escapeHtml(setting.description)}</p>` : ''}
382
+ ${restart}
383
+ </div>
384
+ <div class="setting-control">
385
+ ${control}
386
+ ${resetBtn}
387
+ </div>`;
388
+ }
389
+
390
+ /**
391
+ * A small feature-status pill ('new' / 'beta'). Unknown badge strings render
392
+ * their text verbatim but adopt the 'beta' styling. Returns '' for no badge.
393
+ */
394
+ badgePillHtml(badge) {
395
+ if (!badge) return '';
396
+ const known = badge === 'new' || badge === 'beta';
397
+ const cls = known ? `feature-badge--${badge}` : 'feature-badge--beta';
398
+ return `<span class="feature-badge ${cls}" data-role="feature-badge">${this.escapeHtml(String(badge))}</span>`;
399
+ }
400
+
401
+ /**
402
+ * The lock pill shown next to the source badge on a config-finalized setting.
403
+ */
404
+ finalBadgeHtml() {
405
+ return `<span class="final-badge" data-role="final-badge" title="Locked by configuration">
406
+ <svg width="11" height="11" viewBox="0 0 16 16" fill="currentColor"><path d="M4 5V4a4 4 0 118 0v1h.5A1.5 1.5 0 0114 6.5v6A1.5 1.5 0 0112.5 14h-9A1.5 1.5 0 012 12.5v-6A1.5 1.5 0 013.5 5H4zm1.5 0h5V4a2.5 2.5 0 00-5 0v1z"/></svg>
407
+ Final</span>`;
408
+ }
409
+
410
+ /**
411
+ * Editable control HTML for a setting, chosen by type.
412
+ */
413
+ controlHtml(setting) {
414
+ const type = setting.type;
415
+ // Config-finalized settings render their real control, but disabled.
416
+ const disabled = setting.final === true ? ' disabled' : '';
417
+
418
+ if (type === 'boolean') {
419
+ const checked = setting.value === true ? ' checked' : '';
420
+ return `<label class="toggle">
421
+ <input type="checkbox" data-role="control"${checked}${disabled}>
422
+ <span class="toggle-slider"></span>
423
+ </label>`;
424
+ }
425
+
426
+ if (type === 'integer') {
427
+ const val = setting.value == null ? '' : String(setting.value);
428
+ return `<input type="number" class="settings-input settings-input--number" data-role="control" min="0" step="1" value="${this.escapeHtml(val)}"${disabled}>`;
429
+ }
430
+
431
+ if (type === 'enum') {
432
+ const values = Array.isArray(setting.values) ? setting.values : [];
433
+ const options = values.map(v =>
434
+ `<option value="${this.escapeHtml(String(v))}"${String(v) === String(setting.value) ? ' selected' : ''}>${this.escapeHtml(String(v))}</option>`
435
+ ).join('');
436
+ return `<select class="settings-select" data-role="control"${disabled}>${options}</select>`;
437
+ }
438
+
439
+ // String types.
440
+ if (PROVIDER_KEYS.has(setting.key)) {
441
+ return this.providerSelectHtml(setting, this.providers);
442
+ }
443
+ if (CHAT_PROVIDER_KEYS.has(setting.key)) {
444
+ return this.providerSelectHtml(setting, this.chatProviders);
445
+ }
446
+ if (COUNCIL_KEYS.has(setting.key)) {
447
+ // "Default for Analysis": a mount point for the shared CouncilDropdown
448
+ // plus a preview container beneath it. Neither carries data-role="control"
449
+ // (so the generic change handler ignores them); mountCouncilDropdowns()
450
+ // instantiates the dropdown (which PUTs via its onSelect callback) and
451
+ // renders the composition preview / hint into the preview container.
452
+ return '<div class="council-control-wrap">' +
453
+ '<div class="custom-dropdown council-dropdown-control" data-role="council-mount"></div>' +
454
+ '<div class="council-preview" data-role="council-preview"></div>' +
455
+ '</div>';
456
+ }
457
+ if (MODEL_KEYS.has(setting.key)) {
458
+ return this.modelInputHtml(setting);
459
+ }
460
+
461
+ const val = setting.value == null ? '' : String(setting.value);
462
+ return `<input type="text" class="settings-input" data-role="control" value="${this.escapeHtml(val)}" placeholder="${this.escapeHtml(String(setting.default ?? ''))}"${disabled}>`;
463
+ }
464
+
465
+ /**
466
+ * A model input: a free-text field with a <datalist> of known model ids so
467
+ * the value is discoverable and typo-resistant while still accepting a
468
+ * valid-but-unlisted id (the effective provider may be "inherit" or differ
469
+ * per row, so a strict <select> would wrongly reject legitimate models). The
470
+ * datalist is the union of every analysis provider's models — simpler and more
471
+ * robust than reactively tracking the selected provider (the provider/model
472
+ * rows PUT independently with no live link).
473
+ */
474
+ modelInputHtml(setting) {
475
+ const disabled = setting.final === true ? ' disabled' : '';
476
+ const val = setting.value == null ? '' : String(setting.value);
477
+ // Stable, attribute-safe datalist id derived from the dot-path key.
478
+ const listId = `models-${String(setting.key).replace(/[^a-z0-9]/gi, '-')}`;
479
+
480
+ // Union of model ids across all analysis providers, de-duplicated + sorted.
481
+ const modelIds = new Set();
482
+ for (const p of (this.providers || [])) {
483
+ for (const m of (p.models || [])) {
484
+ const id = m && (m.id != null ? m.id : m);
485
+ if (id != null && id !== '') modelIds.add(String(id));
486
+ }
487
+ }
488
+ const options = [...modelIds]
489
+ .sort((a, b) => a.localeCompare(b))
490
+ .map((id) => `<option value="${this.escapeHtml(id)}"></option>`)
491
+ .join('');
492
+
493
+ return `<input type="text" class="settings-input" data-role="control" list="${this.escapeHtml(listId)}" value="${this.escapeHtml(val)}" placeholder="${this.escapeHtml(String(setting.default ?? ''))}"${disabled}>` +
494
+ `<datalist id="${this.escapeHtml(listId)}">${options}</datalist>`;
495
+ }
496
+
497
+ /**
498
+ * Instantiate the shared CouncilDropdown into every council mount point under
499
+ * `container`. Called after rows are inserted (renderSections / rerenderRow),
500
+ * mirroring populateObjectValues. Each dropdown's base option is "Default
501
+ * Provider / Model" (empty value): choosing it means analysis uses the
502
+ * provider/model rows; choosing a council makes that council the default. The
503
+ * onSelect callback PUTs immediately via updateSetting, just like every other
504
+ * control. A `final`-locked setting mounts a disabled dropdown.
505
+ */
506
+ mountCouncilDropdowns(container) {
507
+ if (!container) return;
508
+ const Dropdown = (typeof window !== 'undefined' && window.CouncilDropdown) || null;
509
+ if (!Dropdown) return;
510
+
511
+ for (const mount of container.querySelectorAll('[data-role="council-mount"]')) {
512
+ const row = mount.closest('.setting-row');
513
+ if (!row) continue;
514
+ const key = row.dataset.key;
515
+ const setting = this.settingsByKey[key];
516
+ if (!setting) continue;
517
+
518
+ // Tear down any prior instance for this key so its document-level
519
+ // outside-click listener doesn't leak across re-renders.
520
+ if (this._councilDropdowns[key]) {
521
+ this._councilDropdowns[key].destroy();
522
+ delete this._councilDropdowns[key];
523
+ }
524
+
525
+ this._councilDropdowns[key] = new Dropdown({
526
+ container: mount,
527
+ councils: this.councils,
528
+ selectedId: setting.value == null ? '' : String(setting.value),
529
+ includeNone: true,
530
+ noneLabel: 'Default Provider / Model',
531
+ disabled: setting.final === true,
532
+ onSelect: (value) => {
533
+ if (setting.final === true) return;
534
+ this.updateSetting(key, value);
535
+ }
536
+ });
537
+
538
+ // Composition preview beneath the dropdown, reflecting the current value.
539
+ this.renderCouncilPreview(row, setting);
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Resolve provider/model ids to display names from the loaded analysis
545
+ * providers (GET /api/providers, an array). Falls back to the raw ids when a
546
+ * provider or model is unknown — the CouncilCard component consumes this.
547
+ * @param {string} providerId
548
+ * @param {string} modelId
549
+ * @returns {{ providerName: string, modelName: string }}
550
+ */
551
+ resolveModelDisplay(providerId, modelId) {
552
+ const provider = (this.providers || []).find((p) => p.id === providerId);
553
+ if (!provider) {
554
+ return { providerName: providerId || 'Unknown', modelName: modelId || 'Unknown' };
555
+ }
556
+ const model = (provider.models || []).find((m) => (m && (m.id != null ? m.id : m)) === modelId);
557
+ return {
558
+ providerName: provider.name || provider.id || providerId,
559
+ modelName: model ? (model.name || model.id || modelId) : (modelId || 'Unknown')
560
+ };
561
+ }
562
+
563
+ /**
564
+ * Render the composition preview for a council row into its
565
+ * `[data-role="council-preview"]` container: the CouncilCard for a selected
566
+ * council, a short hint for the base "Default Provider / Model" option, or a
567
+ * "not found" note for a stale id.
568
+ * @param {HTMLElement} row - The setting row element.
569
+ * @param {Object} setting - The setting descriptor (value = council id or '').
570
+ */
571
+ renderCouncilPreview(row, setting) {
572
+ if (!row) return;
573
+ const el = row.querySelector('[data-role="council-preview"]');
574
+ if (!el) return;
575
+
576
+ const value = setting.value == null ? '' : String(setting.value);
577
+ if (value === '') {
578
+ // Base option chosen — analysis uses the provider/model rows below.
579
+ el.innerHTML = '';
580
+ const hint = document.createElement('p');
581
+ hint.className = 'council-preview-hint';
582
+ hint.textContent = 'Uses the Default Provider / Model rows below.';
583
+ el.appendChild(hint);
584
+ return;
585
+ }
586
+
587
+ const council = (this.councils || []).find((c) => c.id === value);
588
+ if (!council) {
589
+ el.innerHTML = '';
590
+ const note = document.createElement('p');
591
+ note.className = 'council-preview-hint';
592
+ note.textContent = 'Selected council was not found.';
593
+ el.appendChild(note);
594
+ return;
595
+ }
596
+
597
+ const Card = (typeof window !== 'undefined' && window.CouncilCard) || null;
598
+ if (!Card) { el.innerHTML = ''; return; }
599
+ if (!this._councilCards[setting.key] || this._councilCards[setting.key].container !== el) {
600
+ this._councilCards[setting.key] = new Card({
601
+ container: el,
602
+ resolveModelDisplay: (p, m) => this.resolveModelDisplay(p, m)
603
+ });
604
+ }
605
+ this._councilCards[setting.key].render(council);
606
+ }
607
+
608
+ /**
609
+ * A provider dropdown for provider-valued string settings. Includes a blank
610
+ * "inherit" option when the setting's default is empty. Ensures the current
611
+ * value is always selectable even if that provider is unavailable.
612
+ *
613
+ * @param {Object} setting - The setting descriptor.
614
+ * @param {Array} [providers] - Provider list to build options from. Defaults
615
+ * to the analysis providers; chat-provider keys pass this.chatProviders so
616
+ * they render from the chat namespace instead.
617
+ */
618
+ providerSelectHtml(setting, providers = this.providers) {
619
+ const current = setting.value == null ? '' : String(setting.value);
620
+ const allowEmpty = setting.default === '' || setting.default == null;
621
+ const disabled = setting.final === true ? ' disabled' : '';
622
+
623
+ let options = '';
624
+ if (allowEmpty) {
625
+ options += `<option value=""${current === '' ? ' selected' : ''}>Default (inherit)</option>`;
626
+ }
627
+
628
+ const known = new Set();
629
+ for (const p of (providers || [])) {
630
+ known.add(p.id);
631
+ options += `<option value="${this.escapeHtml(p.id)}"${p.id === current ? ' selected' : ''}>${this.escapeHtml(p.name || p.id)}</option>`;
632
+ }
633
+ // Preserve a configured-but-unavailable provider so it still shows.
634
+ if (current && !known.has(current)) {
635
+ options += `<option value="${this.escapeHtml(current)}" selected>${this.escapeHtml(current)} (unavailable)</option>`;
636
+ }
637
+
638
+ return `<select class="settings-select" data-role="control"${disabled}>${options}</select>`;
639
+ }
640
+
641
+ /**
642
+ * Read-only value display (no control) for the read-only group. Objects
643
+ * (providers / chat_providers / hooks / repos) render as an inline
644
+ * collapsible with their full contents; everything else is a plain code chip.
645
+ */
646
+ readonlyValueHtml(setting) {
647
+ if (setting.sensitive) {
648
+ const text = setting.configured ? 'Configured' : 'Not configured';
649
+ const extraClass = setting.configured ? ' readonly-value--set' : '';
650
+ return `<code class="readonly-value${extraClass}">${this.escapeHtml(text)}</code>`;
651
+ }
652
+
653
+ // Object-type read-onlys: the backend ships the full (secret-redacted)
654
+ // object as setting.value. Render it inline and collapsible.
655
+ if (setting.value && typeof setting.value === 'object') {
656
+ return this.readonlyObjectHtml(setting);
657
+ }
658
+
659
+ if (setting.value === null || setting.value === undefined || setting.value === '') {
660
+ return `<code class="readonly-value">${this.escapeHtml('Not set')}</code>`;
661
+ }
662
+
663
+ return `<code class="readonly-value readonly-value--set">${this.escapeHtml(String(setting.value))}</code>`;
664
+ }
665
+
666
+ /**
667
+ * Inline collapsible for an object-type read-only setting. The <pre> is left
668
+ * empty here and filled via textContent by populateObjectValues() after the
669
+ * row is in the DOM — sidestepping HTML-escaping of the JSON entirely.
670
+ */
671
+ readonlyObjectHtml(setting) {
672
+ const obj = setting.value && typeof setting.value === 'object' ? setting.value : {};
673
+ const n = Object.keys(obj).length;
674
+ if (n === 0) {
675
+ return `<code class="readonly-value">${this.escapeHtml('No entries')}</code>`;
676
+ }
677
+ const summary = `${n} ${n === 1 ? 'entry' : 'entries'}`;
678
+ return `<details class="readonly-object">
679
+ <summary class="readonly-object-summary">${this.escapeHtml(summary)}</summary>
680
+ <pre class="readonly-object-json" data-role="object-json"></pre>
681
+ </details>`;
682
+ }
683
+
684
+ /**
685
+ * Fill every object-json <pre> under `container` from its setting descriptor,
686
+ * via textContent (never innerHTML). Called after rows are inserted so the
687
+ * pretty-printed JSON needs no HTML escaping.
688
+ */
689
+ populateObjectValues(container) {
690
+ if (!container) return;
691
+ for (const pre of container.querySelectorAll('[data-role="object-json"]')) {
692
+ const row = pre.closest('.setting-row');
693
+ if (!row) continue;
694
+ const setting = this.settingsByKey[row.dataset.key];
695
+ if (!setting || !setting.value || typeof setting.value !== 'object') continue;
696
+ pre.textContent = JSON.stringify(setting.value, null, 2);
697
+ }
698
+ }
699
+
700
+ renderRepos(repos) {
701
+ const list = document.getElementById('repos-list');
702
+ if (!list) return;
703
+
704
+ if (!repos.length) {
705
+ list.innerHTML = '<div class="repos-empty">No repositories configured yet. Run <code>npx pair-review</code> from a local clone, or open a PR review, to register one.</div>';
706
+ return;
707
+ }
708
+
709
+ list.innerHTML = repos.map(repo => {
710
+ const name = repo.repository || '';
711
+ const configured = repo.hasDbSettings || repo.hasFileConfig;
712
+ const badge = configured
713
+ ? '<span class="repo-badge repo-badge--configured">Configured</span>'
714
+ : '<span class="repo-badge repo-badge--known">Known</span>';
715
+ const sources = [];
716
+ if (repo.hasDbSettings) sources.push('settings');
717
+ if (repo.hasFileConfig) sources.push('config file');
718
+ const sourceHint = sources.length
719
+ ? `<span class="repo-source-hint">${this.escapeHtml(sources.join(' · '))}</span>`
720
+ : '';
721
+ const pathHint = repo.localPath
722
+ ? `<code class="repo-path">${this.escapeHtml(repo.localPath)}</code>`
723
+ : '';
724
+
725
+ return `<a class="repo-row" href="/settings/${this.escapeHtml(name)}">
726
+ <div class="repo-row-main">
727
+ <span class="repo-row-name">${this.escapeHtml(name)}</span>
728
+ ${pathHint}
729
+ </div>
730
+ <div class="repo-row-badges">
731
+ ${sourceHint}
732
+ ${badge}
733
+ </div>
734
+ </a>`;
735
+ }).join('');
736
+ }
737
+
738
+ // ─── Section navigation (side nav + scrollspy) ─────────────────────────────
739
+
740
+ /**
741
+ * Pure: build the ordered nav items from the rendered sections plus, when
742
+ * visible, the Repositories section. Derives entirely from `sections` (the
743
+ * same data renderSections used) so it cannot drift from the page.
744
+ *
745
+ * @param {Array} sections - rendered dynamic sections
746
+ * @param {boolean} includeRepos - append the Repositories nav item
747
+ * @param {boolean} [includeSnippets] - append the Chat Snippets nav item
748
+ * @returns {Array<{id: string, title: string}>}
749
+ */
750
+ navItems(sections, includeRepos, includeSnippets) {
751
+ const items = (sections || []).map(s => {
752
+ // Only attach `badge` when the section actually has one, so callers that
753
+ // build sections without badges keep a clean {id, title} shape.
754
+ const item = { id: s.id, title: s.title };
755
+ if (s.badge) item.badge = s.badge;
756
+ return item;
757
+ });
758
+ // Chat Snippets precedes Repositories so Repositories stays the terminal
759
+ // section (both the static markup and the scrollspy depend on this order).
760
+ if (includeSnippets) {
761
+ items.push({ id: SNIPPETS_SECTION_ID, title: SNIPPETS_NAV_TITLE });
762
+ }
763
+ if (includeRepos) {
764
+ items.push({ id: REPOS_SECTION_ID, title: REPOS_NAV_TITLE });
765
+ }
766
+ return items;
767
+ }
768
+
769
+ /**
770
+ * Render the side-nav anchors into #settings-nav-list.
771
+ */
772
+ renderNav(items) {
773
+ const list = document.getElementById('settings-nav-list');
774
+ if (!list) return;
775
+
776
+ if (!items.length) {
777
+ list.innerHTML = '';
778
+ return;
779
+ }
780
+
781
+ list.innerHTML = items.map(item =>
782
+ `<a class="settings-nav-item" href="#${this.escapeHtml(item.id)}" data-target="${this.escapeHtml(item.id)}">${this.escapeHtml(item.title)}${this.badgePillHtml(item.badge)}</a>`
783
+ ).join('');
784
+ }
785
+
786
+ /**
787
+ * Wire up rendering, click-to-scroll, and scrollspy for the side nav. Called
788
+ * once after settings + repos have loaded so every target section exists.
789
+ */
790
+ buildNavigation() {
791
+ const items = this.navItems(this.sections, this.reposVisible, this.snippetsVisible);
792
+ this.navItemsList = items;
793
+ this.renderNav(items);
794
+ this.setupNavClickHandler();
795
+ this.setupScrollSpy(items);
796
+
797
+ // Start with the first section highlighted (page loads scrolled to top).
798
+ if (items.length) this.setActiveNav(items[0].id);
799
+ }
800
+
801
+ setupNavClickHandler() {
802
+ const list = document.getElementById('settings-nav-list');
803
+ if (!list) return;
804
+
805
+ list.addEventListener('click', (e) => {
806
+ const item = e.target.closest('.settings-nav-item');
807
+ if (!item) return;
808
+ e.preventDefault();
809
+ const target = document.getElementById(item.dataset.target);
810
+ if (!target) return;
811
+ target.scrollIntoView({ behavior: 'smooth', block: 'start' });
812
+ // Reflect the click immediately; the observer will keep it in sync after.
813
+ this.setActiveNav(item.dataset.target);
814
+ });
815
+ }
816
+
817
+ /**
818
+ * Highlight exactly one nav item. No-op if already active.
819
+ */
820
+ setActiveNav(id) {
821
+ if (this.activeNavId === id) return;
822
+ this.activeNavId = id;
823
+
824
+ const list = document.getElementById('settings-nav-list');
825
+ if (!list) return;
826
+ for (const anchor of list.querySelectorAll('.settings-nav-item')) {
827
+ const active = anchor.dataset.target === id;
828
+ anchor.classList.toggle('is-active', active);
829
+ if (active) {
830
+ anchor.setAttribute('aria-current', 'true');
831
+ } else {
832
+ anchor.removeAttribute('aria-current');
833
+ }
834
+ }
835
+ }
836
+
837
+ /**
838
+ * Scrollspy via IntersectionObserver. The rootMargin shrinks the detection
839
+ * band to a strip just below the sticky header, so the active section is the
840
+ * one whose heading sits near the top of the viewport. A bottom guard forces
841
+ * the last item active when the page can't scroll any further (the classic
842
+ * "last short section never reaches the top" case).
843
+ */
844
+ setupScrollSpy(items) {
845
+ if (typeof window === 'undefined' || typeof window.IntersectionObserver !== 'function') return;
846
+
847
+ this.navSections = items
848
+ .map(item => document.getElementById(item.id))
849
+ .filter(Boolean);
850
+ if (!this.navSections.length) return;
851
+
852
+ const visible = new Set();
853
+ this.scrollObserver = new window.IntersectionObserver((entries) => {
854
+ for (const entry of entries) {
855
+ if (entry.isIntersecting) visible.add(entry.target.id);
856
+ else visible.delete(entry.target.id);
857
+ }
858
+ // The bottom guard owns the active state at the very bottom of the page.
859
+ if (this.isAtPageBottom()) return;
860
+ // Active = first section (document order) currently in the detection band.
861
+ for (const section of this.navSections) {
862
+ if (visible.has(section.id)) {
863
+ this.setActiveNav(section.id);
864
+ break;
865
+ }
866
+ }
867
+ }, { rootMargin: '-72px 0px -55% 0px', threshold: 0 });
868
+
869
+ for (const section of this.navSections) this.scrollObserver.observe(section);
870
+
871
+ this._onScroll = () => {
872
+ if (this.isAtPageBottom() && this.navSections.length) {
873
+ this.setActiveNav(this.navSections[this.navSections.length - 1].id);
874
+ }
875
+ };
876
+ window.addEventListener('scroll', this._onScroll, { passive: true });
877
+ }
878
+
879
+ isAtPageBottom() {
880
+ if (typeof window === 'undefined' || typeof document === 'undefined') return false;
881
+ const doc = document.documentElement;
882
+ return (window.innerHeight + window.scrollY) >= (doc.scrollHeight - 2);
883
+ }
884
+
885
+ // ─── Event handling ───────────────────────────────────────────────────────
886
+
887
+ setupEventDelegation() {
888
+ const container = document.getElementById('settings-sections');
889
+ if (!container) return;
890
+
891
+ // Immediate PUT when a control changes. For text/number inputs 'change'
892
+ // fires on blur/Enter, which is the intended debounce.
893
+ container.addEventListener('change', (e) => {
894
+ const control = e.target.closest('[data-role="control"]');
895
+ if (!control) return;
896
+ const row = control.closest('.setting-row');
897
+ if (!row) return;
898
+ const key = row.dataset.key;
899
+ const setting = this.settingsByKey[key];
900
+ if (!setting) return;
901
+ // Finalized settings are locked by configuration — never PUT them (the
902
+ // control is disabled anyway; this guards programmatic change events).
903
+ if (setting.final === true) return;
904
+
905
+ const value = this.readControlValue(control, setting);
906
+ if (value === undefined) return; // no-op (e.g. empty integer)
907
+ this.updateSetting(key, value);
908
+ });
909
+
910
+ // Reset (DELETE the in-app override).
911
+ container.addEventListener('click', (e) => {
912
+ const resetBtn = e.target.closest('[data-role="reset"]');
913
+ if (!resetBtn) return;
914
+ const row = resetBtn.closest('.setting-row');
915
+ if (!row) return;
916
+ this.resetSetting(row.dataset.key);
917
+ });
918
+ }
919
+
920
+ /**
921
+ * Read a typed value out of a control element. Returns `undefined` to signal
922
+ * "do not send" (e.g. an integer field cleared to empty — use Reset instead).
923
+ */
924
+ readControlValue(control, setting) {
925
+ if (setting.type === 'boolean') {
926
+ return control.checked;
927
+ }
928
+ if (setting.type === 'integer') {
929
+ const raw = control.value.trim();
930
+ if (raw === '') return undefined;
931
+ const n = parseInt(raw, 10);
932
+ if (Number.isNaN(n)) return undefined;
933
+ return n;
934
+ }
935
+ // enum / string / provider select
936
+ return control.value;
937
+ }
938
+
939
+ async updateSetting(key, value) {
940
+ // Per-key sequence guard: a change event and a Reset (or two rapid changes)
941
+ // on the same key can be in flight at once. Both updateSetting and
942
+ // resetSetting bump the SAME counter, so whichever mutation was issued last
943
+ // owns the final state — an earlier response that lands afterwards is stale
944
+ // and must not overwrite it (or revert on its own error).
945
+ if (!this._seq) this._seq = {};
946
+ const seq = this._seq[key] = (this._seq[key] || 0) + 1;
947
+ try {
948
+ const response = await fetch(`/api/settings/${encodeURIComponent(key)}`, {
949
+ method: 'PUT',
950
+ headers: { 'Content-Type': 'application/json' },
951
+ body: JSON.stringify({ value })
952
+ });
953
+
954
+ if (!response.ok) {
955
+ const data = await response.json().catch(() => ({}));
956
+ throw new Error(data.error || `Failed to save (${response.status})`);
957
+ }
958
+
959
+ const data = await response.json();
960
+ if (this._seq[key] !== seq) return; // superseded by a newer mutation
961
+ const setting = data.setting;
962
+ this.settingsByKey[key] = setting;
963
+ this.rerenderRow(setting);
964
+ this.showToast('success', `${setting.label} saved`);
965
+ } catch (error) {
966
+ if (this._seq[key] !== seq) return; // superseded — leave newer state intact
967
+ console.error('Error saving setting:', error);
968
+ this.showToast('error', `Failed to save: ${error.message}`);
969
+ // Revert the control to the last known-good descriptor.
970
+ const known = this.settingsByKey[key];
971
+ if (known) this.rerenderRow(known);
972
+ }
973
+ }
974
+
975
+ async resetSetting(key) {
976
+ // Shares the sequence counter with updateSetting so the two serialize
977
+ // against each other (e.g. Reset clicked while a PUT is in flight).
978
+ if (!this._seq) this._seq = {};
979
+ const seq = this._seq[key] = (this._seq[key] || 0) + 1;
980
+ try {
981
+ const response = await fetch(`/api/settings/${encodeURIComponent(key)}`, {
982
+ method: 'DELETE'
983
+ });
984
+
985
+ if (!response.ok) {
986
+ const data = await response.json().catch(() => ({}));
987
+ throw new Error(data.error || `Failed to reset (${response.status})`);
988
+ }
989
+
990
+ const data = await response.json();
991
+ if (this._seq[key] !== seq) return; // superseded by a newer mutation
992
+ const setting = data.setting;
993
+ this.settingsByKey[key] = setting;
994
+ this.rerenderRow(setting);
995
+ this.showToast('success', `${setting.label} reset`);
996
+ } catch (error) {
997
+ if (this._seq[key] !== seq) return; // superseded — leave newer state intact
998
+ console.error('Error resetting setting:', error);
999
+ this.showToast('error', `Failed to reset: ${error.message}`);
1000
+ }
1001
+ }
1002
+
1003
+ /**
1004
+ * Replace one row's contents with freshly rendered HTML from its descriptor.
1005
+ */
1006
+ rerenderRow(setting) {
1007
+ const container = document.getElementById('settings-sections');
1008
+ if (!container) return;
1009
+ const row = container.querySelector(`.setting-row[data-key="${this.cssAttrEscape(setting.key)}"]`);
1010
+ if (!row) return;
1011
+ row.innerHTML = this.rowInnerHtml(setting);
1012
+ // Keep any object-json <pre> in this row populated (readonly objects never
1013
+ // rerender through here today, but this stays correct if that changes).
1014
+ this.populateObjectValues(row);
1015
+ // Re-mount a council dropdown if this row hosts one (e.g. after PUT/reset).
1016
+ this.mountCouncilDropdowns(row);
1017
+ }
1018
+
1019
+ // ─── Utilities ────────────────────────────────────────────────────────────
1020
+
1021
+ /**
1022
+ * Escape a value for safe use inside a quoted attribute selector.
1023
+ */
1024
+ cssAttrEscape(value) {
1025
+ if (window.CSS && typeof window.CSS.escape === 'function') {
1026
+ return window.CSS.escape(value);
1027
+ }
1028
+ // Fallback: escape backslashes and double quotes.
1029
+ return String(value).replace(/["\\]/g, '\\$&');
1030
+ }
1031
+
1032
+ escapeHtml(str) {
1033
+ if (str === null || str === undefined) return '';
1034
+ // Output is injected into double-quoted attribute contexts (data-key, title,
1035
+ // value, placeholder, href) as well as text nodes, so quotes MUST be escaped
1036
+ // too — a textContent→innerHTML pass only covers & < >.
1037
+ return String(str).replace(/[&<>"']/g, (c) => ({
1038
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
1039
+ }[c]));
1040
+ }
1041
+
1042
+ showToast(type, message) {
1043
+ const container = document.getElementById('toast-container');
1044
+ if (!container) return;
1045
+
1046
+ const toast = document.createElement('div');
1047
+ toast.className = `toast ${type}`;
1048
+ toast.innerHTML = `
1049
+ <div class="toast-icon">
1050
+ ${type === 'success'
1051
+ ? '<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"/></svg>'
1052
+ : '<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8zm9-3a1 1 0 11-2 0 1 1 0 012 0zM6.92 6.085c.081-.16.19-.299.34-.398.145-.097.371-.187.74-.187.302 0 .558.066.743.205a.677.677 0 01.26.514c0 .217-.062.376-.15.495-.083.112-.216.22-.436.345-.205.119-.36.234-.479.364a.788.788 0 00-.19.478v.413a.75.75 0 101.5 0v-.124c0-.05.024-.1.067-.14.052-.047.154-.113.333-.19.188-.083.37-.196.523-.35a1.724 1.724 0 00.437-1.18c0-.515-.177-.914-.504-1.199-.331-.289-.78-.447-1.3-.447-.531 0-.978.164-1.307.465-.323.295-.496.682-.558 1.093a.75.75 0 001.474.28.327.327 0 01.029-.073zM9 11a1 1 0 11-2 0 1 1 0 012 0z"/></svg>'
1053
+ }
1054
+ </div>
1055
+ <span class="toast-message"></span>
1056
+ <button class="toast-close" data-role="toast-close" aria-label="Dismiss">
1057
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
1058
+ <path d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"/>
1059
+ </svg>
1060
+ </button>
1061
+ `;
1062
+ // Assign message via textContent to avoid HTML injection.
1063
+ toast.querySelector('.toast-message').textContent = message;
1064
+ toast.querySelector('[data-role="toast-close"]').addEventListener('click', () => toast.remove());
1065
+
1066
+ container.appendChild(toast);
1067
+ requestAnimationFrame(() => toast.classList.add('show'));
1068
+
1069
+ setTimeout(() => {
1070
+ toast.classList.remove('show');
1071
+ setTimeout(() => toast.remove(), 300);
1072
+ }, 4000);
1073
+ }
1074
+ }
1075
+
1076
+ // Initialize when DOM is ready (browser only).
1077
+ if (typeof document !== 'undefined' && document.addEventListener) {
1078
+ document.addEventListener('DOMContentLoaded', () => {
1079
+ window.settingsPage = new SettingsPage();
1080
+ });
1081
+ }
1082
+
1083
+ // Export for unit tests (jsdom/vm sandbox), following the repo pattern.
1084
+ if (typeof module !== 'undefined' && module.exports) {
1085
+ module.exports = { SettingsPage, SETTINGS_GROUPS, PROVIDER_KEYS, CHAT_PROVIDER_KEYS, MODEL_KEYS, COUNCIL_KEYS, SOURCE_DISPLAY };
1086
+ }