@240xu/dsh-websearch 2.8.8 → 2.8.9

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/lib/client.js CHANGED
@@ -23,16 +23,29 @@ window.__ModuleLoader__.load({
23
23
  { id: "deepseek", keyEnv: "DEEPSEEK_API_KEY", label: "DeepSeek" },
24
24
  { id: "anthropic", keyEnv: "ANTHROPIC_API_KEY", label: "Anthropic" },
25
25
  { id: "openai", keyEnv: "OPENAI_API_KEY", label: "OpenAI" },
26
+ // these two are metered, opt-in backends. They are
27
+ // deliberately NOT in KEYLESS: listing them under "keyless, ready to
28
+ // use" would imply zero cost / zero limits, while the hosted keyless
29
+ // tier is rate limited and its exact ceiling is not published. They
30
+ // still accept an optional key (OPTIONAL_KEYS) to raise limits.
31
+ { id: "firecrawl", keyEnv: "FIRECRAWL_API_KEY", optionalKey: true, metered: true, label: "Firecrawl (免 Key · 有额度 · 默认关)" },
32
+ { id: "tinyfish", keyEnv: "TINYFISH_API_KEY", optionalKey: true, metered: true, label: "TinyFish (免 Key · 30/分·50/日 · 默认关)" },
26
33
  ];
27
34
  const GLOBAL_FIELDS = ["numResults", "concurrency", "backendTimeoutMs"];
28
35
  /** Enum-valued settings (validated client-side, saved as strings). */
29
36
  const SELECT_FIELDS = {
37
+ intervention: ["official", "balanced", "thorough"],
30
38
  recency: ["any", "day", "week", "month", "year"],
31
39
  dedupStrategy: ["url", "url+title"],
32
40
  };
33
41
  /** Boolean settings staged as "true"/"false" strings by the selects. */
34
42
  const BOOLEAN_FIELDS = ["rerank", "safeSearch", "resultTelemetry"];
35
- const KEYLESS = BACKENDS.filter((b) => !b.keyEnv || b.optionalKey);
43
+ // split metered, opt-in backends out of the
44
+ // "keyless / ready to use" group. They work without a key but are rate
45
+ // limited and default OFF, so a separate section with an explicit hint
46
+ // prevents the misleading impression of a free unlimited backend.
47
+ const METERED = BACKENDS.filter((b) => b.metered);
48
+ const KEYLESS = BACKENDS.filter((b) => (!b.keyEnv || b.optionalKey) && !b.metered);
36
49
  const KEYED = BACKENDS.filter((b) => b.keyEnv && !b.optionalKey);
37
50
  const OPTIONAL_KEYS = BACKENDS.filter((b) => b.keyEnv && b.optionalKey);
38
51
 
@@ -51,12 +64,18 @@ window.__ModuleLoader__.load({
51
64
  nav: "搜索",
52
65
  groupFree: "免密钥(开箱即用)",
53
66
  groupKeyed: "需要 API Key",
67
+ // metered/opt-in section copy (zh).
68
+ groupMetered: "计量型(免 Key 但有额度,默认关)",
69
+ meteredHint: "官方 hosted keyless tier 按 IP/日限额并可能返回 429;启用前请确认额度。填可选 Key 可提升限额。",
54
70
  statusEnabled: "已启用后端",
55
71
  statusKeys: "已配置密钥",
72
+ // status bar labels for the metered section.
73
+ statusMetered: "计量型",
74
+ statusOffByDefault: "默认关",
56
75
  keyMissing: "缺密钥",
57
76
  unsavedHint: "有未保存的修改", savedOk: "已保存 ✓",
58
77
  title: "统一搜索 (Unified Search)",
59
- description: "聚合网络搜索:11 个后端并发 fan-out、URL 去重合并。开关后端、填 API Key、调参数,保存即生效。",
78
+ description: "聚合网络搜索:多后端并发 fan-out、URL 去重合并(含 2 个默认关的计量型后端)。开关后端、填 API Key、调参数,保存即生效。",
60
79
  save: "保存",
61
80
  discard: "放弃修改",
62
81
  dirty: "有未保存修改",
@@ -67,12 +86,17 @@ window.__ModuleLoader__.load({
67
86
  overridden: "已自定义",
68
87
  keyLabel: "{id} API Key",
69
88
  getKey: "获取 Key ↗",
70
- keyHint: "填入后保存到凭证库(对应环境变量引用);留空表示不修改",
89
+ // the switch is immediate, the key needs Save.
90
+ keySaveModeHint: "开关即时生效;密钥填写后需点「保存」写入凭证库",
71
91
  keySet: "已配置",
72
92
  keyUnset: "未配置",
73
93
  togglesTitle: "启用后端",
74
94
  globalsTitle: "全局参数",
75
- keysTitle: "API 密钥(保存后写入凭证库,立即生效)",
95
+ numResultsLabel: "结果条数",
96
+ concurrencyLabel: "并发数",
97
+ timeoutLabel: "后端超时 (ms)",
98
+ saveFailed: "保存失败",
99
+ conflictHint: "其他端已修改,请先刷新",
76
100
  shapingTitle: "结果策略",
77
101
  recencyLabel: "时间范围",
78
102
  langLabel: "搜索语言",
@@ -90,22 +114,37 @@ window.__ModuleLoader__.load({
90
114
  dedupTitle: "链接 + 标题(合并转载)",
91
115
  langPlaceholder: "如 en、zh-CN,留空为默认",
92
116
  envProvided: "环境变量提供", readOnly: "只读,无需填写", conflict: "设置已在其他端被修改,请重试", keyFailed: "该 Key 保存失败",
117
+ keyReadFailed: "密钥状态读取失败,请稍后重试",
93
118
  telemetryLabel: "结果健康遥测",
94
- fallbackHint: "全部后端已关闭:搜索将回退到默认免 Key 后端",
119
+ fallbackHint: "全部后端已关闭:搜索将回退到默认免 Key 后端(计量型仍保持关闭)",
95
120
  invalidFields: "以下字段未通过校验:",
96
121
  readOnlyScope: "当前配置只读(可能由宿主锁定)",
97
- optionalTitle: "私有实例可选 Key",
122
+ interventionLabel: "搜索介入程度",
123
+ interventionOfficial: "官方(原样查询,不加结果头/遥测)",
124
+ interventionBalanced: "平衡(确定性去噪 + 去重/遥测,默认)",
125
+ interventionThorough: "彻底(相关性重排 + 深度覆盖)",
126
+ interventionHint: "official 把查询与结果呈现完全交给官方工具;balanced 只剥明确的口语前缀;thorough 会重排并扩大后端请求,延迟与额度消耗更高。内部多查询仍是独立开关。",
127
+ unavailable: "设置暂不可用:宿主没有返回配置快照(服务未就绪或路由未挂载)。",
128
+ retry: "重试",
129
+ toggleFailed: "开关未生效",
130
+ optionalTitle: "可选 Key(私有实例 / 提升计量型额度)",
98
131
  };
99
132
  const en = {
100
133
  nav: "Web Search",
101
134
  groupFree: "Keyless (ready to use)",
102
135
  groupKeyed: "Requires API key",
136
+ // metered/opt-in section copy (en).
137
+ groupMetered: "Metered (keyless but rate limited, off by default)",
138
+ meteredHint: "The hosted keyless tier is limited per IP/day and may return 429; check quotas before enabling. An optional API key raises the limits.",
103
139
  statusEnabled: "Backends enabled",
104
140
  statusKeys: "Keys configured",
141
+ // status bar labels for the metered section.
142
+ statusMetered: "Metered",
143
+ statusOffByDefault: "off by default",
105
144
  keyMissing: "key missing",
106
145
  unsavedHint: "You have unsaved changes", savedOk: "Saved ✓",
107
146
  title: "Unified Search",
108
- description: "Aggregated web search: 11 backends fan out concurrently, URL-deduped. Toggle backends, set API keys, tune globals — saves apply immediately.",
147
+ description: "Aggregated web search: multiple backends fan out concurrently, URL-deduped (incl. 2 metered backends that are off by default). Toggle backends, set API keys, tune globals — saves apply immediately.",
109
148
  save: "Save",
110
149
  discard: "Discard",
111
150
  dirty: "Unsaved changes",
@@ -116,12 +155,17 @@ window.__ModuleLoader__.load({
116
155
  overridden: "customized",
117
156
  keyLabel: "{id} API Key",
118
157
  getKey: "Get key ↗",
119
- keyHint: "Stored into the credential store on save; leave blank to keep current",
158
+ // the switch is immediate, the key needs Save.
159
+ keySaveModeHint: "The switch applies immediately; the key is written to the credential store when you press Save",
120
160
  keySet: "configured",
121
161
  keyUnset: "not set",
122
162
  togglesTitle: "Enabled backends",
123
163
  globalsTitle: "Global parameters",
124
- keysTitle: "API keys (saved to the credential store, effective immediately)",
164
+ numResultsLabel: "Results",
165
+ concurrencyLabel: "Concurrency",
166
+ timeoutLabel: "Backend timeout (ms)",
167
+ saveFailed: "Save failed",
168
+ conflictHint: "Changed elsewhere — refresh first",
125
169
  shapingTitle: "Result shaping",
126
170
  recencyLabel: "Recency",
127
171
  langLabel: "Language",
@@ -142,15 +186,24 @@ window.__ModuleLoader__.load({
142
186
  readOnly: "read-only, nothing to fill",
143
187
  conflict: "Changed elsewhere - please retry",
144
188
  keyFailed: "failed to save this key",
189
+ keyReadFailed: "could not read key status, please retry later",
145
190
  telemetryLabel: "Result health telemetry",
146
- fallbackHint: "All backends off: search falls back to the default keyless four.",
191
+ fallbackHint: "All backends off: search falls back to the default keyless four (metered backends stay off).",
147
192
  invalidFields: "Fields failed validation:",
148
193
  readOnlyScope: "Configuration is read-only (locked by host?)",
149
- optionalTitle: "Private instance optional keys",
194
+ interventionLabel: "Search intervention",
195
+ interventionOfficial: "Official (raw query, no header/telemetry)",
196
+ interventionBalanced: "Balanced (deterministic cleanup + dedupe/telemetry, default)",
197
+ interventionThorough: "Thorough (relevance rerank + deep coverage)",
198
+ interventionHint: "official leaves query construction and presentation to the host tool; balanced strips only explicit conversational prefixes; thorough reranks and widens backend requests, costing more latency and quota. Internal multi-query stays a separate opt-in.",
199
+ unavailable: "Settings are unavailable: the host returned no configuration snapshot (service not ready or route not mounted).",
200
+ retry: "Retry",
201
+ toggleFailed: "Toggle failed",
202
+ optionalTitle: "Optional keys (private instance / higher metered limits)",
150
203
  };
151
204
 
152
205
  //#region styles
153
- const css = ".wsc-card{display:flex;flex-direction:column;gap:14px}.wsc-sectionTitle{font-size:13px;font-weight:600;opacity:.75;margin:4px 0 0}.wsc-toggles{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:6px}.wsc-toggle{display:flex;align-items:center;gap:8px;padding:7px 10px;border-radius:10px;border:1px solid var(--dsw-alias-border-subtle);cursor:pointer;font-size:13px;color:var(--dsw-alias-label-primary);background:0 0}.wsc-toggle input{accent-color:var(--dsw-alias-accent-primary)}.wsc-input,.wsc-keyInput{box-sizing:border-box;width:100%;padding:8px 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-subtle);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:13px;font-family:inherit}.wsc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px}.wsc-fieldHead{display:flex;justify-content:space-between;align-items:center;margin-bottom:3px}.wsc-label{font-size:12px;opacity:.8}.wsc-badge{font-size:11px;padding:1px 8px;border-radius:999px;border:1px solid var(--dsw-alias-border-subtle)}.wsc-badgeOn{color:var(--dsw-alias-accent-primary);border-color:var(--dsw-alias-accent-primary)}.wsc-hint{font-size:11px;opacity:.55;margin:3px 0 0}.wsc-actions{display:flex;gap:8px;align-items:center}.wsc-btn{cursor:pointer;border:none;border-radius:10px;padding:8px 16px;font-size:13px;font-family:inherit;background:var(--dsw-alias-accent-primary);color:#fff}.wsc-btnGhost{background:0 0;color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-subtle)}.wsc-btn:disabled{opacity:.5;cursor:default}.wsc-status{font-size:12px;opacity:.7}";
206
+ const css = ".wsc-card{display:flex;flex-direction:column;gap:14px}.wsc-sectionTitle{font-size:13px;font-weight:600;opacity:.75;margin:4px 0 0}.wsc-toggles{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:6px}.wsc-toggle{display:flex;align-items:center;gap:8px;padding:7px 10px;border-radius:10px;border:1px solid var(--dsw-alias-border-l2);cursor:pointer;font-size:13px;color:var(--dsw-alias-label-primary);background:0 0}.wsc-toggle input{accent-color:var(--dsw-alias-brand-primary)}.wsc-input,.wsc-keyInput{box-sizing:border-box;width:100%;padding:8px 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:13px;font-family:inherit}.wsc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px}.wsc-fieldHead{display:flex;justify-content:space-between;align-items:center;margin-bottom:3px}.wsc-label{font-size:12px;opacity:.8}.wsc-badge{font-size:11px;padding:1px 8px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2)}.wsc-badgeOn{color:var(--dsw-alias-state-success-primary);border-color:var(--dsw-alias-state-success-primary)}.wsc-hint{font-size:11px;opacity:.55;margin:3px 0 0}.wsc-actions{display:flex;gap:8px;align-items:center}.wsc-btn{cursor:pointer;border:none;border-radius:10px;padding:8px 16px;font-size:13px;font-family:inherit;background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground)}.wsc-btn:hover:not(:disabled){background:var(--dsw-alias-button-primary-hover)}.wsc-btnGhost{background:0 0;color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-l2)}.wsc-btn:disabled{opacity:.5;cursor:default}.wsc-status{font-size:12px;opacity:.7}";
154
207
  if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=\"dsh-websearch/card\"]") === null) {
155
208
  const tag = document.createElement("style");
156
209
  tag.dataset.plugin = "@240xu/dsh-websearch";
@@ -188,17 +241,54 @@ window.__ModuleLoader__.load({
188
241
  user: undefined,
189
242
  revision: undefined,
190
243
  mode: "routes",
244
+ unavailable: false,
245
+ reason: undefined,
191
246
  });
247
+ // Serialise writes: a queued write must read the revision only
248
+ // when its turn comes, otherwise two concurrent toggles both
249
+ // send revision=0 and the second is rejected as a conflict.
250
+ this.writeQueue = Promise.resolve();
251
+ // A load starts before a write but can land after it; applying
252
+ // that snapshot would roll the UI back and restore a stale
253
+ // revision (the next write is then rejected as a conflict).
254
+ this.loadSeq = 0;
192
255
  }
193
256
 
194
257
  getSnapshot() { return this.store.getSnapshot(); }
195
258
  subscribe(listener) { return this.store.subscribe(listener); }
196
259
 
197
260
  accept(payload) {
198
- if (payload === null || typeof payload !== "object" || payload.ok !== true || payload.writable === false) {
199
- // Keep the card rendered (status ready) but read-only, so the section
200
- // explains itself instead of showing an endless loading ellipsis.
201
- this.store.set({ status: "ready", writable: false, value: {}, base: undefined, user: undefined, revision: undefined, mode: "routes" });
261
+ if (payload === null || typeof payload !== "object" || payload.ok !== true) {
262
+ // Keep the card rendered (status ready) but explain the actual state:
263
+ // a 404/503 is "settings unavailable", not "you configured nothing".
264
+ this.store.set({
265
+ status: "ready",
266
+ writable: false,
267
+ value: {},
268
+ base: undefined,
269
+ user: undefined,
270
+ revision: undefined,
271
+ mode: "routes",
272
+ unavailable: true,
273
+ reason: payload !== null && typeof payload === "object" && typeof payload.reason === "string"
274
+ ? payload.reason
275
+ : "settings-unavailable",
276
+ });
277
+ return;
278
+ }
279
+ if (payload.writable === false) {
280
+ // The host answered with a real snapshot but marked it read-only.
281
+ this.store.set({
282
+ status: "ready",
283
+ writable: false,
284
+ value: payload.value ?? {},
285
+ base: payload.base,
286
+ user: payload.user,
287
+ revision: payload.revision,
288
+ mode: "routes",
289
+ unavailable: false,
290
+ reason: payload.reason,
291
+ });
202
292
  return;
203
293
  }
204
294
  this.store.set({
@@ -209,20 +299,31 @@ window.__ModuleLoader__.load({
209
299
  user: payload.user,
210
300
  revision: payload.revision,
211
301
  mode: "routes",
302
+ unavailable: false,
303
+ reason: undefined,
212
304
  });
213
305
  }
214
306
 
215
307
  async load() {
308
+ const seq = ++this.loadSeq;
216
309
  try {
217
- const response = await fetch("/api/unified-search/settings", { credentials: "same-origin", headers: { accept: "application/json" } });
218
- const payload = await response.json().catch(() => undefined);
219
- this.accept(response.status === 404 ? undefined : payload);
310
+ const response = await fetch("/api/unified-search/settings", { credentials: "same-origin", headers: { accept: "application/json" } });
311
+ const payload = await response.json().catch(() => undefined);
312
+ if (seq !== this.loadSeq) return;
313
+ this.accept(response.status === 404 ? undefined : payload);
220
314
  } catch (_noRoutes) {
221
- this.accept(undefined);
315
+ if (seq === this.loadSeq) this.accept(undefined);
222
316
  }
223
317
  }
224
318
 
225
- async write(ops) {
319
+ write(ops) {
320
+ const run = () => this.writeNow(ops);
321
+ const result = this.writeQueue.then(run, run);
322
+ this.writeQueue = result.then(() => undefined, () => undefined);
323
+ return result;
324
+ }
325
+
326
+ async writeNow(ops) {
226
327
  const expectedRevision = this.store.getSnapshot().revision;
227
328
  const response = await fetch("/api/unified-search/settings", {
228
329
  method: "POST",
@@ -236,6 +337,7 @@ window.__ModuleLoader__.load({
236
337
  if (!response.ok || payload === undefined || payload.ok !== true) {
237
338
  throw new Error(payload !== undefined && payload.error !== undefined ? String(payload.error) : "settings request failed (" + response.status + ")");
238
339
  }
340
+ this.loadSeq += 1;
239
341
  this.accept(payload);
240
342
  }
241
343
 
@@ -247,6 +349,13 @@ window.__ModuleLoader__.load({
247
349
  * Card state machine: reads the bound settings scope snapshot, stages edits,
248
350
  * writes section fields through scope.set/unset and secrets via credentials.
249
351
  */
352
+ // Host errors can carry internal paths and reference names. Only a
353
+ // stable, shape-checked error code is safe to display in the card.
354
+ function safeFailureReason(err) {
355
+ const code = err && typeof err === "object" && typeof err.code === "string" ? err.code : "";
356
+ return /^[a-z][a-z0-9/_-]{0,60}$/i.test(code) ? code : "write rejected";
357
+ }
358
+
250
359
  class UnifiedSearchCardController {
251
360
  constructor(scope, connection, remote) {
252
361
  this.scope = scope;
@@ -258,11 +367,22 @@ window.__ModuleLoader__.load({
258
367
  this.saving = false;
259
368
  this.failed = false;
260
369
  this.conflict = false;
370
+ // A toggle write is independent of Save; its failure must not be
371
+ // cleared only by a later Save, nor persist after a retry succeeds.
372
+ this.toggleFailed = false;
373
+ this.toggleConflict = false;
261
374
  this.failedKeys = new Map(); // envRef -> failure reason
375
+ // Credential READ failures, distinct from SAVE failures above.
376
+ // Only a fixed code is stored; raw host errors are never kept.
377
+ this.readErrors = new Map();
262
378
  this.failedFields = new Set();
263
379
  this.savedAt = 0;
380
+ // Per-ref read sequence: a describe() started before a successful
381
+ // write must not repaint that key as "not configured".
382
+ this.credSeq = new Map();
383
+ this.disposed = false;
264
384
  this.store = createStore(this.projection());
265
- this.scope.subscribe(() => this.republish());
385
+ this.unsubscribe = this.scope.subscribe(() => this.republish());
266
386
  }
267
387
 
268
388
  sectionValue(field) {
@@ -276,11 +396,19 @@ window.__ModuleLoader__.load({
276
396
  return { text: staged.clear ? "" : staged.text, overridden: !staged.clear };
277
397
  }
278
398
 
399
+ /**
400
+ * Project the controller state into the snapshot the card renders from.
401
+ * Everything the render layer needs is derived here, so the store never
402
+ * exposes the raw staging maps.
403
+ */
279
404
  projection() {
280
405
  const snap = this.scope.getSnapshot();
281
406
  return {
282
407
  ready: snap.status === "ready",
283
408
  writable: snap.writable,
409
+ unavailable: snap.unavailable === true,
410
+ reason: snap.reason,
411
+ revision: snap.revision,
284
412
  value: snap.value ?? {},
285
413
  keyState: Object.fromEntries(this.keyState),
286
414
  stagedKeys: Object.fromEntries([...this.stagedKeys].map(([k, v]) => [k, v.text])),
@@ -292,59 +420,142 @@ window.__ModuleLoader__.load({
292
420
  },
293
421
  conflict: this.conflict,
294
422
  failedKeys: [...this.failedKeys].map(([ref, reason]) => ({ ref, reason })),
423
+ readErrors: [...this.readErrors].map(([ref, reason]) => ({ ref, reason })),
295
424
  failedFields: [...this.failedFields],
296
425
  saving: this.saving,
297
426
  failed: this.failed,
427
+ toggleFailed: this.toggleFailed,
428
+ toggleConflict: this.toggleConflict,
298
429
  version: (this.staged.size + ":" + [...this.staged.keys()].join(",")),
299
430
  };
300
431
  }
301
432
 
302
- republish() { this.store.set(this.projection()); }
433
+ /** Push the current projection to the store and notify subscribers. */
434
+ republish() {
435
+ if (this.disposed) return;
436
+ this.store.set(this.projection());
437
+ }
438
+
439
+ /** Detach from the host scope; late responses must not publish. */
440
+ dispose() {
441
+ this.disposed = true;
442
+ if (typeof this.unsubscribe === "function") this.unsubscribe();
443
+ }
444
+
445
+ /** Re-read the settings snapshot (used by the unavailable-state retry). */
446
+ reload() {
447
+ return typeof this.scope.load === "function" ? this.scope.load() : undefined;
448
+ }
303
449
 
450
+ /** Stage a field edit (clears the saved marker so the card shows "unsaved"). */
304
451
  edit(field, text) { this.savedAt = 0; this.staged.set(field, { text }); this.republish(); }
452
+ /** Drop a staged field edit; the stored value is untouched. */
305
453
  reset(field) { this.staged.delete(field); this.republish(); }
306
- editKey(envRef, text) { this.savedAt = 0; this.stagedKeys.set(envRef, { text }); this.republish(); }
454
+ /** Stage a credential draft; a blank draft is never staged so Save can drain. */
455
+ editKey(envRef, text) {
456
+ this.savedAt = 0;
457
+ // A blank draft is not a pending change; staging it would keep
458
+ // the Save button enabled with nothing to write.
459
+ if (String(text).trim() === "") this.stagedKeys.delete(envRef);
460
+ else this.stagedKeys.set(envRef, { text });
461
+ this.republish();
462
+ }
307
463
 
308
464
  /** Toggles write immediately (no staging); globals/keys stage + save. */
309
465
  async setToggle(id, checked) {
466
+ // A retry supersedes the previous toggle error. Keep the message
467
+ // while the new write is in flight so the card does not flicker.
468
+ this.toggleFailed = false;
469
+ this.toggleConflict = false;
310
470
  try {
311
471
  await this.scope.set("enable" + id.charAt(0).toUpperCase() + id.slice(1), checked);
312
472
  } catch (err) {
313
- this.failed = true;
314
- this.conflict = String(err).includes("SETTINGS_CONFLICT");
473
+ this.toggleFailed = true;
474
+ this.toggleConflict = String(err).includes("SETTINGS_CONFLICT");
475
+ this.failed = false;
476
+ this.conflict = false;
477
+ // The host may have committed the write even when the
478
+ // response failed. Resync instead of leaving the stale
479
+ // pre-write value on screen. Report only the conflict
480
+ // classification, never the raw error text.
481
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
482
+ console.warn("websearch: toggle write failed", { conflict: this.conflict });
483
+ }
484
+ if (typeof this.scope.load === "function") {
485
+ try { await this.scope.load(); } catch { /* keep current snapshot */ }
486
+ }
315
487
  }
316
-
317
488
  this.republish();
318
489
  }
319
490
 
320
491
  async readCredential(ref) {
492
+ const seq = (this.credSeq.get(ref) ?? 0) + 1;
493
+ this.credSeq.set(ref, seq);
494
+ let readFailed = false;
495
+ let reason;
321
496
  try {
322
497
  let view;
323
- if (this.remote !== undefined && this.remote.credentials !== undefined && typeof this.remote.credentials.describe === "function") {
324
- // 0.2.x remote face: Record<ref, {configured, writable, source}> behind {ok, value}.
325
- const res = await this.remote.credentials.describe([ref]);
326
- const record = res !== null && typeof res === "object" && res.value !== undefined ? res.value : res;
327
- const byRef = record !== null && typeof record === "object" && record.credentials !== undefined ? record.credentials : record;
328
- view = byRef !== null && typeof byRef === "object" ? byRef[ref] : undefined;
498
+ // Guard the namespace access: an undeclared remote service throws on
499
+ // access, and a swallowed error would leave the configured badge dark.
500
+ let api;
501
+ try { api = this.remote === undefined ? undefined : this.remote.credentials; } catch { api = undefined; }
502
+ if (api !== undefined && typeof api.describe === "function") {
503
+ // 0.2.x remote face: RemoteResult<Record<ref, CredentialInfo>>.
504
+ const res = await api.describe([ref]);
505
+ // Judge the RemoteResult envelope before unwrapping: `ok:false` is a
506
+ // read failure, not an unconfigured credential. Do not fall
507
+ // through to the legacy connection branch, which could surface
508
+ // a stale value. failedKeys is reserved for save failures.
509
+ if (res !== null && typeof res === "object" && res.ok === false) {
510
+ readFailed = true;
511
+ reason = "credential/read-failed";
512
+ } else {
513
+ const record = res !== null && typeof res === "object" && res.value !== undefined ? res.value : res;
514
+ const byRef = record !== null && typeof record === "object" && record.credentials !== undefined ? record.credentials : record;
515
+ view = byRef !== null && typeof byRef === "object" ? byRef[ref] : undefined;
516
+ }
329
517
  }
330
- if (view === undefined && this.connection !== undefined && this.connection.api !== undefined && this.connection.api.credentials !== undefined) {
518
+ if (!readFailed && view === undefined && this.connection !== undefined && this.connection.api !== undefined && this.connection.api.credentials !== undefined) {
331
519
  // Older line: the connection controller's credentials API.
332
520
  const res = await this.connection.api.credentials.describe({ refs: [ref] });
333
521
  if (res?.result?.ok) view = res.result.value.credentials[ref];
334
522
  }
335
- if (view === undefined) return;
336
- this.keyState.set(ref, { configured: view.configured === true, writable: view.writable !== false });
337
- } catch { /* ignore */ }
338
- this.republish();
523
+ if (!readFailed && view !== undefined && seq === this.credSeq.get(ref)) {
524
+ this.keyState.set(ref, { configured: view.configured === true, writable: view.writable !== false });
525
+ this.readErrors.delete(ref);
526
+ }
527
+ } catch {
528
+ reason = "credential/read-failed";
529
+ } finally {
530
+ // Only a fixed code is stored; host error text may contain
531
+ // internal paths or credential reference names.
532
+ if (reason !== undefined && seq === this.credSeq.get(ref)) {
533
+ this.readErrors.set(ref, safeFailureReason({ code: reason }));
534
+ }
535
+ this.republish();
536
+ }
339
537
  }
340
538
 
341
539
  async writeCredential(ref, value) {
342
- if (this.remote !== undefined && this.remote.credentials !== undefined && typeof this.remote.credentials.set === "function") {
343
- await this.remote.credentials.set(ref, value);
540
+ // The namespace access may throw on hosts that do not register
541
+ // `remote.credentials`; guard it so the older connection API can
542
+ // still serve as fallback. `set()` resolves with a RemoteResult
543
+ // envelope instead of throwing on rejection, so `ok === false`
544
+ // must be treated as a failure.
545
+ let api;
546
+ try { api = this.remote === undefined ? undefined : this.remote.credentials; } catch { api = undefined; }
547
+ if (api !== undefined && typeof api.set === "function") {
548
+ const res = await api.set(ref, value);
549
+ const rejected = res !== null && typeof res === "object" && res.ok === false;
550
+ if (rejected) throw new Error(res.error?.message ?? "credential write rejected");
551
+ this.credSeq.set(ref, (this.credSeq.get(ref) ?? 0) + 1);
344
552
  return;
345
553
  }
346
554
  if (this.connection !== undefined && this.connection.api !== undefined && this.connection.api.credentials !== undefined && typeof this.connection.api.credentials.set === "function") {
347
- await this.connection.api.credentials.set({ ref, value });
555
+ const res = await this.connection.api.credentials.set({ ref, value });
556
+ const rejected = res !== null && typeof res === "object" && (res.ok === false || res.result?.ok === false);
557
+ if (rejected) throw new Error(res.error?.message ?? res.result?.error?.message ?? "credential write rejected");
558
+ this.credSeq.set(ref, (this.credSeq.get(ref) ?? 0) + 1);
348
559
  return;
349
560
  }
350
561
  throw new Error("credentials service unavailable");
@@ -354,14 +565,33 @@ window.__ModuleLoader__.load({
354
565
  for (const b of BACKENDS) if (b.keyEnv) this.readCredential(b.keyEnv);
355
566
  }
356
567
 
568
+ /**
569
+ * Commit every staged field and credential draft.
570
+ *
571
+ * Entries are snapshotted before each await so an edit that arrives while a
572
+ * write is in flight keeps its own unsaved state instead of being deleted
573
+ * as if it had been saved. A second call while one is running is a no-op.
574
+ */
357
575
  async save() {
358
576
  if (this.saving) return;
359
577
  this.saving = true; this.failed = false;
360
578
  this.conflict = false; this.failedFields.clear(); this.republish();
361
579
  const doneFields = [];
362
580
  const doneKeys = [];
581
+ // Snapshot the staged entry object for each field/key we save.
582
+ // edit()/editKey() replace the entry with a NEW object, so comparing
583
+ // by identity tells us whether the user typed again while the
584
+ // awaits were in flight. Those newer edits must not be discarded
585
+ // or reported as saved.
586
+ const savedFieldRefs = new Map();
587
+ const savedKeyRefs = new Map();
363
588
  try {
364
589
  for (const [field, staged] of this.staged) {
590
+ // Snapshot the entry BEFORE any await. edit() replaces the staged
591
+ // entry with a new object, so identity comparison later detects an edit
592
+ // that arrived while the awaits were in flight. Recording after the
593
+ // await would capture the NEW edit and delete it as if saved.
594
+ savedFieldRefs.set(field, staged);
365
595
  // Empty draft clears the override so the schema default applies again.
366
596
  if (staged.clear || staged.text === "") { await this.scope.unset(field); doneFields.push(field); continue; }
367
597
  if (SELECT_FIELDS[field]) {
@@ -395,6 +625,8 @@ window.__ModuleLoader__.load({
395
625
  }
396
626
  }
397
627
  for (const [ref, staged] of this.stagedKeys) {
628
+ // Snapshot before any await, same reason as the field loop.
629
+ savedKeyRefs.set(ref, staged);
398
630
  const value = staged.text.trim();
399
631
  if (value !== "") {
400
632
  try {
@@ -405,22 +637,42 @@ window.__ModuleLoader__.load({
405
637
  } catch (keyErr) {
406
638
  // env-shadowed reference (fail-loud doctrine): isolate so other keys still land.
407
639
  this.failed = true;
408
- this.failedKeys.set(ref, String(keyErr && keyErr.message ? keyErr.message : keyErr).slice(0, 140));
640
+ this.failedKeys.set(ref, safeFailureReason(keyErr));
409
641
  void keyErr;
410
642
  }
643
+ } else {
644
+ // Consume a blank draft so the Save button drains.
645
+ doneKeys.push(ref);
411
646
  }
412
647
  }
413
- for (const f of doneFields) this.staged.delete(f);
414
- for (const k of doneKeys) this.stagedKeys.delete(k);
415
- if (!this.failed && (doneFields.length > 0 || doneKeys.length > 0)) this.savedAt = Date.now();
648
+ for (const f of doneFields) {
649
+ if (this.staged.get(f) === savedFieldRefs.get(f)) this.staged.delete(f);
650
+ }
651
+ for (const k of doneKeys) {
652
+ if (this.stagedKeys.get(k) === savedKeyRefs.get(k)) this.stagedKeys.delete(k);
653
+ }
654
+ // Only claim "saved" when nothing is left pending. An edit
655
+ // that arrived during the awaits keeps its own unsaved state.
656
+ if (!this.failed && (doneFields.length > 0 || doneKeys.length > 0)
657
+ && this.staged.size === 0 && this.stagedKeys.size === 0) this.savedAt = Date.now();
416
658
  } catch (err) {
417
659
  this.failed = true;
418
660
  this.conflict = String(err).includes("SETTINGS_CONFLICT");
661
+ // Without a reload the stale expectedRevision makes every
662
+ // subsequent Save fail the same way. Staged edits survive, so
663
+ // the user can inspect and retry after the refresh.
664
+ if (this.conflict) {
665
+ try { await this.reload(); } catch { /* keep the conflict notice */ }
666
+ }
419
667
  }
420
668
  this.saving = false;
421
669
  this.republish();
422
670
  }
423
671
 
672
+ /**
673
+ * Props handed to the settings section: the store as an observable hook
674
+ * plus the actions the card calls.
675
+ */
424
676
  inject() {
425
677
  // Slot contract: hooks.{name} must be an observable store; the renderer
426
678
  // converts it into props.use{Name} (observableHook). Actions go top-level.
@@ -431,12 +683,13 @@ window.__ModuleLoader__.load({
431
683
  reset: (f) => this.reset(f),
432
684
  editKey: (r, t) => this.editKey(r, t),
433
685
  save: () => this.save(),
434
- discard: () => { this.staged.clear(); this.stagedKeys.clear(); this.failed = false; this.conflict = false; this.failedKeys.clear(); this.republish(); },
686
+ retry: () => this.reload(),
687
+ discard: () => { this.staged.clear(); this.stagedKeys.clear(); this.failed = false; this.conflict = false; this.failedFields.clear(); this.failedKeys.clear(); this.republish(); },
435
688
  };
436
689
  }
437
690
  }
438
691
 
439
- /** Toggle row for one backend. */
692
+ /** Toggle row for one backend (keyless / metered backends). */
440
693
  function ToggleRow(props) {
441
694
  const b = props.backend;
442
695
  // The Host serves schema-resolved values, so defaults arrive materialized;
@@ -457,6 +710,55 @@ window.__ModuleLoader__.load({
457
710
  ] });
458
711
  }
459
712
 
713
+ /**
714
+ * Combined card for a key-gated backend: switch, status badge, get-key
715
+ * link, input, hint and per-key error in one place so the credential is
716
+ * matched to its toggle without scrolling.
717
+ *
718
+ * The switch writes immediately (setToggle), the key is staged until
719
+ * Save (editKey) — `keySaveModeHint` states this so the two behaviours
720
+ * are not mistaken for one atomic action.
721
+ */
722
+ function KeyedBackendCard(props) {
723
+ const b = props.backend;
724
+ const state = props.state;
725
+ const checked = props.value === true;
726
+ const configured = !!state.keyState[b.keyEnv]?.configured;
727
+ const readOnly = configured && state.keyState[b.keyEnv]?.writable === false;
728
+ // failedKeys is an array of { ref, reason }, NOT an array of strings.
729
+ const failure = (state.failedKeys ?? []).find((f) => f && f.ref === b.keyEnv);
730
+ const readFailure = (state.readErrors ?? []).find((f) => f && f.ref === b.keyEnv);
731
+ const needsKey = !configured;
732
+ const dotColor = needsKey ? (checked ? "#e6a700" : "#888") : "#2ea043";
733
+ return react_jsx_runtime.jsxs("div", { className: "wsc-keyCard", style: { display: "flex", flexDirection: "column", gap: 6, padding: "9px 10px", borderRadius: 10, border: "1px solid var(--dsw-alias-border-l2)" }, children: [
734
+ react_jsx_runtime.jsxs("label", { className: "wsc-toggle", style: { display: "flex", alignItems: "center", gap: 8, cursor: "pointer", padding: 0, border: "none", borderRadius: 0 }, children: [
735
+ react_jsx_runtime.jsx("input", { type: "checkbox", checked, onChange: (e) => props.onToggle(e.target.checked) }),
736
+ react_jsx_runtime.jsx("span", { style: { width: 8, height: 8, borderRadius: "50%", background: dotColor, display: "inline-block" } }),
737
+ react_jsx_runtime.jsx("span", { children: b.label }),
738
+ needsKey && checked && react_jsx_runtime.jsx("span", { style: { fontSize: 10, opacity: .65 }, children: props.t("keyMissing") }),
739
+ ] }),
740
+ react_jsx_runtime.jsxs("div", { style: { display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }, children: [
741
+ react_jsx_runtime.jsx("span", { className: "wsc-badge" + (configured ? " wsc-badgeOn" : ""), children: configured ? props.t("keySet") : props.t("keyUnset") }),
742
+ readOnly && react_jsx_runtime.jsx("span", { className: "wsc-badge", style: { opacity: .75 }, children: props.t("envProvided") }),
743
+ KEY_URLS[b.id] && react_jsx_runtime.jsx("a", {
744
+ href: KEY_URLS[b.id], target: "_blank", rel: "noreferrer",
745
+ style: { fontSize: 11, color: "var(--dsw-alias-link)", textDecoration: "none" },
746
+ children: props.t("getKey"),
747
+ }),
748
+ ] }),
749
+ react_jsx_runtime.jsx("input", {
750
+ className: "wsc-keyInput", type: "password", autoComplete: "off",
751
+ disabled: readOnly,
752
+ placeholder: readOnly ? props.t("readOnly") : b.keyEnv,
753
+ value: state.stagedKeys[b.keyEnv] ?? "",
754
+ onChange: (e) => props.onEditKey(b.keyEnv, e.target.value),
755
+ }),
756
+ react_jsx_runtime.jsx("p", { className: "wsc-hint", children: props.t("keySaveModeHint") }),
757
+ failure && react_jsx_runtime.jsx("p", { className: "wsc-hint", style: { color: "#e5534b" }, children: props.t("keyFailed") + (failure.reason ? ": " + failure.reason : "") }),
758
+ readFailure && react_jsx_runtime.jsx("p", { className: "wsc-hint", style: { color: "#e6a700" }, children: props.t("keyReadFailed") }),
759
+ ] });
760
+ }
761
+
460
762
  /** Labeled <select> for enum / boolean settings. */
461
763
  function SelectField(props) {
462
764
  return react_jsx_runtime.jsxs("div", { children: [
@@ -473,169 +775,238 @@ window.__ModuleLoader__.load({
473
775
  }
474
776
 
475
777
  /** The card root. */
476
- function UnifiedSearchSection(props) {
477
- const state = props.useUnifiedSearchCard((snapshot) => snapshot);
478
- const card = { edit: props.edit, setToggle: props.setToggle, reset: props.reset, editKey: props.editKey, save: props.save, discard: props.discard };
479
- // Occupants of settings.plugin.item render inside the tab's <ul>; use <li>.
480
- if (!state.ready) {
481
- return react_jsx_runtime.jsx("div", { className: "wsc-card", style: { fontSize: 12, opacity: .6 }, children: "…" });
482
- }
483
-
484
- const toggleField = (id) => "enable" + id.charAt(0).toUpperCase() + id.slice(1);
485
-
486
- // Status summary: enabled backends + configured keys at a glance.
487
- const enabledCount = BACKENDS.filter((b) => state.value[toggleField(b.id)] === true).length;
488
- const keyedBackends = BACKENDS.filter((b) => b.keyEnv && !b.optionalKey);
489
- const keysReady = keyedBackends.filter((b) => state.keyState[b.keyEnv]?.configured).length;
490
-
491
- const recencyOptions = [
492
- { value: "any", label: props.t("recencyAny") },
493
- { value: "day", label: props.t("recencyDay") },
494
- { value: "week", label: props.t("recencyWeek") },
495
- { value: "month", label: props.t("recencyMonth") },
496
- { value: "year", label: props.t("recencyYear") },
497
- ];
498
- const dedupOptions = [
499
- { value: "url", label: props.t("dedupUrl") },
500
- { value: "url+title", label: props.t("dedupTitle") },
501
- ];
502
- const boolOptions = [
503
- { value: "true", label: props.t("on") },
504
- { value: "false", label: props.t("off") },
505
- ];
506
- const selVal = (f, dflt) => state.stagedText(f) ?? String(state.value[f] ?? dflt);
507
-
508
- return react_jsx_runtime.jsxs("div", { className: "wsc-card", children: [
509
- react_jsx_runtime.jsx("div", { style: { display: "flex", gap: 14, alignItems: "center", padding: "10px 12px", marginBottom: 10, borderRadius: 8, background: "rgba(127,127,127,.08)", fontSize: 13 }, children: [
510
- react_jsx_runtime.jsxs("span", { children: [props.t("statusEnabled"), ": ", react_jsx_runtime.jsx("b", { children: enabledCount + "/" + BACKENDS.length })] }),
511
- react_jsx_runtime.jsxs("span", { children: [props.t("statusKeys"), ": ", react_jsx_runtime.jsx("b", { children: keysReady + "/" + keyedBackends.length })] }),
778
+ /**
779
+ * Status strip above the settings form: enabled / keyed counts plus the
780
+ * three advisories (all-off fallback, read-only scope, metered default-off).
781
+ * @param {object} props { state, enabledCount, keysReady, t }
782
+ */
783
+ function StatusSummary(props) {
784
+ const { state, enabledCount, keysReady, t } = props;
785
+ return react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
786
+ react_jsx_runtime.jsx("div", { style: { display: "flex", gap: 14, alignItems: "center", padding: "10px 12px", marginBottom: 10, borderRadius: 8, background: "var(--dsw-alias-bg-module-platform)" }, children: [
787
+ react_jsx_runtime.jsxs("span", { children: [t("statusEnabled"), ": ", react_jsx_runtime.jsx("b", { children: enabledCount + "/" + BACKENDS.length })] }),
788
+ react_jsx_runtime.jsxs("span", { children: [t("statusKeys"), ": ", react_jsx_runtime.jsx("b", { children: keysReady + "/" + KEYED.length })] }),
789
+ METERED.length > 0 && react_jsx_runtime.jsxs("span", { style: { opacity: .65 }, children: [
790
+ t("statusMetered"), ": ", METERED.length, " ", t("statusOffByDefault"),
791
+ ] }),
512
792
  ] }),
513
- react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .65 }, children: props.t("description") }),
514
- (enabledCount === 0) && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, color: "#e6a700" }, children: props.t("fallbackHint") }),
515
- (state.writable === false) && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, color: "#e6a700" }, children: props.t("readOnlyScope") }),
516
- react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: props.t("groupFree") }),
793
+ react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .65 }, children: t("description") }),
794
+ (enabledCount === 0) && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, color: "#e6a700" }, children: t("fallbackHint") }),
795
+ (state.writable === false) && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, color: "#e6a700" }, children: t("readOnlyScope") }),
796
+ ] });
797
+ }
798
+
799
+ /**
800
+ * The three backend groups: keyless toggles, keyed cards, and the metered
801
+ * opt-in section. The metered group keeps its own header and hint so it is
802
+ * never silently mixed into "keyless".
803
+ * @param {object} props { state, card, toggleField, t }
804
+ */
805
+ function BackendToggles(props) {
806
+ const { state, card, toggleField, t } = props;
807
+ return react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
808
+ react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: t("groupFree") }),
517
809
  react_jsx_runtime.jsx("div", { className: "wsc-toggles", children: KEYLESS.map((b) =>
518
810
  react_jsx_runtime.jsx(ToggleRow, {
519
811
  backend: b,
520
812
  value: state.value[toggleField(b.id)],
521
813
  keyConfigured: true,
522
- t: props.t,
814
+ t,
523
815
  onChange: (checked) => card.setToggle(b.id, checked),
524
816
  }, b.id)
525
817
  ) }),
526
- react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: props.t("groupKeyed") }),
527
- react_jsx_runtime.jsx("div", { className: "wsc-toggles", children: KEYED.map((b) =>
528
- react_jsx_runtime.jsx(ToggleRow, {
818
+ react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: t("groupKeyed") }),
819
+ // The switch and the credential input are one card per backend.
820
+ react_jsx_runtime.jsx("div", { className: "wsc-grid", children: KEYED.map((b) =>
821
+ react_jsx_runtime.jsx(KeyedBackendCard, {
529
822
  backend: b,
823
+ state,
530
824
  value: state.value[toggleField(b.id)],
531
- keyConfigured: !!state.keyState[b.keyEnv]?.configured,
532
- t: props.t,
533
- onChange: (checked) => card.setToggle(b.id, checked),
825
+ t,
826
+ onToggle: (checked) => card.setToggle(b.id, checked),
827
+ onEditKey: (ref, text) => card.editKey(ref, text),
534
828
  }, b.id)
535
829
  ) }),
536
- react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: props.t("globalsTitle") }),
830
+ METERED.length > 0 && react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
831
+ react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: t("groupMetered") }),
832
+ react_jsx_runtime.jsx("p", { style: { margin: "0 0 6px", fontSize: 11, opacity: .6 }, children: t("meteredHint") }),
833
+ react_jsx_runtime.jsx("div", { className: "wsc-toggles", children: METERED.map((b) =>
834
+ react_jsx_runtime.jsx(ToggleRow, {
835
+ backend: b,
836
+ value: state.value[toggleField(b.id)],
837
+ keyConfigured: true,
838
+ t,
839
+ onChange: (checked) => card.setToggle(b.id, checked),
840
+ }, b.id)
841
+ ) }),
842
+ ] }),
843
+ ] });
844
+ }
845
+
846
+ /**
847
+ * Global limits and result-shaping fields (rendered as inputs and selects).
848
+ * @param {object} props { state, card, t }
849
+ */
850
+ function SettingsFields(props) {
851
+ const { state, card, t } = props;
852
+ const selVal = (f, dflt) => state.stagedText(f) ?? String(state.value[f] ?? dflt);
853
+ const recencyOptions = [
854
+ { value: "any", label: t("recencyAny") },
855
+ { value: "day", label: t("recencyDay") },
856
+ { value: "week", label: t("recencyWeek") },
857
+ { value: "month", label: t("recencyMonth") },
858
+ { value: "year", label: t("recencyYear") },
859
+ ];
860
+ const dedupOptions = [
861
+ { value: "url", label: t("dedupUrl") },
862
+ { value: "url+title", label: t("dedupTitle") },
863
+ ];
864
+ const boolOptions = [
865
+ { value: "true", label: t("on") },
866
+ { value: "false", label: t("off") },
867
+ ];
868
+ const interventionOptions = [
869
+ { value: "official", label: t("interventionOfficial") },
870
+ { value: "balanced", label: t("interventionBalanced") },
871
+ { value: "thorough", label: t("interventionThorough") },
872
+ ];
873
+ return react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
874
+ react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: t("interventionLabel") }),
875
+ react_jsx_runtime.jsx("div", { className: "wsc-grid", children: react_jsx_runtime.jsx(SelectField, {
876
+ label: t("interventionLabel"),
877
+ value: selVal("intervention", "balanced"),
878
+ options: interventionOptions,
879
+ onChange: (v) => card.edit("intervention", v),
880
+ }) }),
881
+ react_jsx_runtime.jsx("p", { className: "wsc-hint", children: t("interventionHint") }),
882
+ react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: t("globalsTitle") }),
537
883
  react_jsx_runtime.jsxs("div", { className: "wsc-grid", children: [
538
884
  react_jsx_runtime.jsxs("div", { children: [
539
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: "numResults" }) }),
540
- react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("numResults") ?? String(state.value.numResults ?? ""), onChange: e => card.edit("numResults", e.target.value), inputMode: "numeric" }),
885
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("numResultsLabel") }) }),
886
+ react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("numResults") ?? String(state.value.numResults ?? ""), onChange: (e) => card.edit("numResults", e.target.value), inputMode: "numeric" }),
541
887
  ] }),
542
888
  react_jsx_runtime.jsxs("div", { children: [
543
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: "concurrency" }) }),
544
- react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("concurrency") ?? String(state.value.concurrency ?? ""), onChange: e => card.edit("concurrency", e.target.value), inputMode: "numeric" }),
889
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("concurrencyLabel") }) }),
890
+ react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("concurrency") ?? String(state.value.concurrency ?? ""), onChange: (e) => card.edit("concurrency", e.target.value), inputMode: "numeric" }),
545
891
  ] }),
546
892
  react_jsx_runtime.jsxs("div", { children: [
547
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: "backendTimeoutMs" }) }),
548
- react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("backendTimeoutMs") ?? String(state.value.backendTimeoutMs ?? ""), onChange: e => card.edit("backendTimeoutMs", e.target.value), inputMode: "numeric" }),
893
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("timeoutLabel") }) }),
894
+ react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("backendTimeoutMs") ?? String(state.value.backendTimeoutMs ?? ""), onChange: (e) => card.edit("backendTimeoutMs", e.target.value), inputMode: "numeric" }),
549
895
  ] }),
550
896
  ] }),
551
- react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: props.t("shapingTitle") }),
897
+ react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: t("shapingTitle") }),
552
898
  react_jsx_runtime.jsxs("div", { className: "wsc-grid", children: [
553
- react_jsx_runtime.jsx(SelectField, {
554
- label: props.t("recencyLabel"),
555
- value: selVal("recency", "any"),
556
- options: recencyOptions,
557
- onChange: (v) => card.edit("recency", v),
558
- }),
899
+ // A language tag is free text ("en", "zh-CN", …), not an enum: keeping
900
+ // it as a select with no options threw on render.
559
901
  react_jsx_runtime.jsxs("div", { children: [
560
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: props.t("langLabel") }) }),
902
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("langLabel") }) }),
561
903
  react_jsx_runtime.jsx("input", {
562
904
  className: "wsc-input",
563
- placeholder: props.t("langPlaceholder"),
905
+ placeholder: t("langPlaceholder"),
564
906
  value: state.stagedText("language") ?? String(state.value.language ?? ""),
565
- onChange: e => card.edit("language", e.target.value),
907
+ onChange: (e) => card.edit("language", e.target.value),
566
908
  }),
567
909
  ] }),
568
- react_jsx_runtime.jsx(SelectField, {
569
- label: props.t("dedupLabel"),
570
- value: selVal("dedupStrategy", "url"),
571
- options: dedupOptions,
572
- onChange: (v) => card.edit("dedupStrategy", v),
573
- }),
574
- react_jsx_runtime.jsx(SelectField, {
575
- label: props.t("rerankLabel"),
576
- value: selVal("rerank", "false"),
577
- options: boolOptions,
578
- onChange: (v) => card.edit("rerank", v),
579
- }),
580
- react_jsx_runtime.jsx(SelectField, {
581
- label: props.t("safeSearchLabel"),
582
- value: selVal("safeSearch", "true"),
583
- options: boolOptions,
584
- onChange: (v) => card.edit("safeSearch", v),
585
- }),
586
- react_jsx_runtime.jsx(SelectField, {
587
- label: props.t("telemetryLabel"),
588
- value: selVal("resultTelemetry", "true"),
589
- options: boolOptions,
590
- onChange: (v) => card.edit("resultTelemetry", v),
591
- }),
910
+ react_jsx_runtime.jsx(SelectField, { label: t("recencyLabel"), value: selVal("recency", "any"), options: recencyOptions, onChange: (v) => card.edit("recency", v) }),
911
+ react_jsx_runtime.jsx(SelectField, { label: t("dedupLabel"), value: selVal("dedupStrategy", "url"), options: dedupOptions, onChange: (v) => card.edit("dedupStrategy", v) }),
912
+ react_jsx_runtime.jsx(SelectField, { label: t("rerankLabel"), value: selVal("rerank", "false"), options: boolOptions, onChange: (v) => card.edit("rerank", v) }),
913
+ react_jsx_runtime.jsx(SelectField, { label: t("safeSearchLabel"), value: selVal("safeSearch", "true"), options: boolOptions, onChange: (v) => card.edit("safeSearch", v) }),
914
+ react_jsx_runtime.jsx(SelectField, { label: t("telemetryLabel"), value: selVal("resultTelemetry", "true"), options: boolOptions, onChange: (v) => card.edit("resultTelemetry", v) }),
592
915
  ] }),
593
- react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: props.t("keysTitle") }),
594
- react_jsx_runtime.jsx("div", { className: "wsc-grid", children: BACKENDS.filter((b) => b.keyEnv && !b.optionalKey).map((b) =>
595
- react_jsx_runtime.jsxs("div", { children: [
916
+ ] });
917
+ }
918
+
919
+ /**
920
+ * The optional-key grid (private instances / metered limits) and the save bar.
921
+ * @param {object} props { state, card, t }
922
+ */
923
+ function OptionalKeysAndActions(props) {
924
+ const { state, card, t } = props;
925
+ return react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
926
+ react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: t("optionalTitle") }),
927
+ react_jsx_runtime.jsx("div", { className: "wsc-grid", children: OPTIONAL_KEYS.map((b) => {
928
+ // failedKeys is [{ref, reason}], not a string array: the old
929
+ // `.includes(b.keyEnv)` never matched, so failures stayed silent.
930
+ const failure = (state.failedKeys ?? []).find((f) => f && f.ref === b.keyEnv);
931
+ const readFailure = (state.readErrors ?? []).find((f) => f && f.ref === b.keyEnv);
932
+ return react_jsx_runtime.jsxs("div", { children: [
596
933
  react_jsx_runtime.jsxs("div", { className: "wsc-fieldHead", children: [
597
- react_jsx_runtime.jsx("span", { className: "wsc-label", children: props.t("keyLabel", { id: b.id }) }),
598
- react_jsx_runtime.jsxs("span", { className: "wsc-badges", style: { display: "flex", gap: 6, alignItems: "center" }, children: [
599
- KEY_URLS[b.id] && react_jsx_runtime.jsx("a", {
600
- href: KEY_URLS[b.id], target: "_blank", rel: "noreferrer",
601
- style: { fontSize: 11, color: "var(--dsw-alias-accent-primary)", textDecoration: "none" },
602
- children: props.t("getKey"),
603
- }),
604
- react_jsx_runtime.jsx("span", { className: "wsc-badge" + (state.keyState[b.keyEnv]?.configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.configured ? props.t("keySet") : props.t("keyUnset") }),
605
- state.keyState[b.keyEnv]?.configured && state.keyState[b.keyEnv]?.writable === false && react_jsx_runtime.jsx("span", { className: "wsc-badge", style: { opacity: .75 }, children: props.t("envProvided") }),
606
- ] }),
934
+ react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("keyLabel", { id: b.label }) }),
935
+ react_jsx_runtime.jsx("span", { className: "wsc-badge" + (state.keyState[b.keyEnv]?.configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.configured ? t("keySet") : t("keyUnset") }),
607
936
  ] }),
608
937
  react_jsx_runtime.jsx("input", {
609
938
  className: "wsc-keyInput", type: "password", autoComplete: "off",
610
939
  disabled: state.keyState[b.keyEnv]?.configured && state.keyState[b.keyEnv]?.writable === false,
611
- placeholder: (state.keyState[b.keyEnv]?.configured && state.keyState[b.keyEnv]?.writable === false) ? props.t("readOnly") : b.keyEnv,
612
- value: state.stagedKeys[b.keyEnv] ?? "",
613
- onChange: (e) => card.editKey(b.keyEnv, e.target.value),
614
- }),
615
- react_jsx_runtime.jsx("p", { className: "wsc-hint", children: props.t("keyHint") }),
616
- state.failedKeys.includes(b.keyEnv) && react_jsx_runtime.jsx("p", { className: "wsc-hint", style: { color: "#e5534b" }, children: props.t("keyFailed") }),
617
- ] }, b.id)
618
- ) }),
619
- react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: props.t("optionalTitle") }),
620
- react_jsx_runtime.jsx("div", { className: "wsc-grid", children: OPTIONAL_KEYS.map((b) =>
621
- react_jsx_runtime.jsxs("div", { children: [
622
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: props.t("keyLabel", { id: b.id }) }) }),
623
- react_jsx_runtime.jsx("input", {
624
- className: "wsc-keyInput", type: "password", autoComplete: "off",
625
940
  placeholder: b.keyEnv,
626
941
  value: state.stagedKeys[b.keyEnv] ?? "",
627
942
  onChange: (e) => card.editKey(b.keyEnv, e.target.value),
628
943
  }),
629
- ] }, b.id),
630
- ) }),
631
- state.stagedCount > 0 && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .6 }, children: props.t("unsavedHint") }),
944
+ react_jsx_runtime.jsx("p", { className: "wsc-hint", children: t("keySaveModeHint") }),
945
+ failure && react_jsx_runtime.jsx("p", { className: "wsc-hint", style: { color: "#e5534b" }, children: t("keyFailed") + (failure.reason ? ": " + failure.reason : "") }),
946
+ readFailure && react_jsx_runtime.jsx("p", { className: "wsc-hint", style: { color: "#e6a700" }, children: t("keyReadFailed") }),
947
+ ] }, b.id);
948
+ }) }),
949
+ state.stagedCount > 0 && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .65 }, children: t("unsavedHint") }),
632
950
  react_jsx_runtime.jsxs("div", { className: "wsc-actions", children: [
633
- react_jsx_runtime.jsx("button", { className: "wsc-btn", disabled: state.saving || state.stagedCount === 0 || state.writable === false, onClick: () => card.save(), children: state.saving ? props.t("saving") : props.t("save") }),
634
- (state.stagedCount > 0) && react_jsx_runtime.jsx("button", { className: "wsc-btn wsc-btnGhost", onClick: () => card.discard(), children: props.t("discard") }),
635
- state.failed && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e5534b" }, children: props.t("failed") }),
636
- (state.failedFields.length > 0) && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e5534b", fontSize: 11 }, children: props.t("invalidFields") + ": " + state.failedFields.join(", ") }),
637
- state.conflict && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e6a700" }, children: props.t("conflict") }),
638
- !state.failed && !state.saving && state.savedAt > 0 && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#2ea043" }, children: props.t("savedOk") }),
951
+ react_jsx_runtime.jsx("button", { className: "wsc-btn", disabled: state.saving || state.stagedCount === 0 || state.writable === false, onClick: () => card.save(), children: state.saving ? t("saving") : t("save") }),
952
+ (state.stagedCount > 0) && react_jsx_runtime.jsx("button", { className: "wsc-btn wsc-btnGhost", disabled: state.saving, onClick: () => card.discard(), children: t("discard") }),
953
+ state.failed && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e5534b" }, children: state.conflict ? t("conflict") : t("saveFailed") }),
954
+ state.toggleFailed && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e5534b" }, children: t("toggleFailed") + (state.toggleConflict ? " — " + t("conflict") : "") }),
955
+ (state.failedFields.length > 0) && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e6a700" }, children: t("invalidFields") + " " + state.failedFields.join(", ") }),
956
+ state.conflict && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e6a700" }, children: t("conflictHint") }),
957
+ !state.failed && !state.saving && state.savedAt > 0 && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#2ea043" }, children: t("savedOk") }),
958
+ ] }),
959
+ ] });
960
+ }
961
+
962
+ function UnifiedSearchSection(props) {
963
+ const state = props.useUnifiedSearchCard((snapshot) => snapshot);
964
+ const card = { edit: props.edit, setToggle: props.setToggle, reset: props.reset, editKey: props.editKey, save: props.save, discard: props.discard };
965
+ // Occupants of settings.plugin.item render inside the tab's <ul>; use <li>.
966
+ if (!state.ready) {
967
+ return react_jsx_runtime.jsx("div", { className: "wsc-card", style: { fontSize: 12, opacity: .6 }, children: "…" });
968
+ }
969
+ // No snapshot at all (404/503): showing "0/13 enabled" plus live
970
+ // controls would be a fabricated state. Explain it and offer a retry.
971
+ if (state.unavailable) {
972
+ return react_jsx_runtime.jsxs("div", { className: "wsc-card", children: [
973
+ react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .75 }, children: props.t("unavailable") }),
974
+ react_jsx_runtime.jsx("div", { className: "wsc-actions", children: react_jsx_runtime.jsx("button", { className: "wsc-btn", onClick: () => props.retry(), children: props.t("retry") }) }),
975
+ ] });
976
+ }
977
+
978
+ const toggleField = (id) => "enable" + id.charAt(0).toUpperCase() + id.slice(1);
979
+
980
+ // Status summary: enabled backends + configured keys at a glance.
981
+ const enabledCount = BACKENDS.filter((b) => state.value[toggleField(b.id)] === true).length;
982
+ const keysReady = KEYED.filter((b) => state.keyState[b.keyEnv]?.configured).length;
983
+
984
+ const recencyOptions = [
985
+ { value: "any", label: props.t("recencyAny") },
986
+ { value: "day", label: props.t("recencyDay") },
987
+ { value: "week", label: props.t("recencyWeek") },
988
+ { value: "month", label: props.t("recencyMonth") },
989
+ { value: "year", label: props.t("recencyYear") },
990
+ ];
991
+ const dedupOptions = [
992
+ { value: "url", label: props.t("dedupUrl") },
993
+ { value: "url+title", label: props.t("dedupTitle") },
994
+ ];
995
+ const boolOptions = [
996
+ { value: "true", label: props.t("on") },
997
+ { value: "false", label: props.t("off") },
998
+ ];
999
+ const selVal = (f, dflt) => state.stagedText(f) ?? String(state.value[f] ?? dflt);
1000
+
1001
+ return react_jsx_runtime.jsxs("div", { className: "wsc-card", children: [
1002
+ react_jsx_runtime.jsx(StatusSummary, { state, enabledCount, keysReady, t: props.t }),
1003
+ // A read-only snapshot (scope locked by the host) must not render
1004
+ // live toggles: fieldset disabled disables every descendant input,
1005
+ // select and button without relying on each call site.
1006
+ react_jsx_runtime.jsxs("fieldset", { disabled: state.writable === false, style: { border: 0, margin: 0, padding: 0, minWidth: 0 }, children: [
1007
+ react_jsx_runtime.jsx(BackendToggles, { state, card, toggleField, t: props.t }),
1008
+ react_jsx_runtime.jsx(SettingsFields, { state, card, t: props.t }),
1009
+ react_jsx_runtime.jsx(OptionalKeysAndActions, { state, card, t: props.t }),
639
1010
  ] }),
640
1011
  ] });
641
1012
  }
@@ -646,7 +1017,12 @@ window.__ModuleLoader__.load({
646
1017
  * the 0.2.x line; the card binds whichever data source the build offers
647
1018
  * (see selectBridge) and registers the section unconditionally.
648
1019
  */
649
- const inject = ["slots", "locale", "connection", "remote"];
1020
+ // DSH 0.2.x registers each remote namespace as its own service key
1021
+ // (`remote.<namespace>`). Undeclared access throws instead of returning
1022
+ // undefined, so the namespace must be declared in inject for key saves
1023
+ // and credential reads. The official settings models plugin declares
1024
+ // the same key.
1025
+ const inject = ["slots", "locale", "connection", "remote", "remote.credentials"];
650
1026
  /**
651
1027
  * Resolve the settings data source for this build, in order:
652
1028
  * 1. the legacy `settingsScope` service (DSH <= 0.1.6 line, or a shim);
@@ -672,6 +1048,9 @@ window.__ModuleLoader__.load({
672
1048
  ctx.get("connection"),
673
1049
  ctx.get("remote"),
674
1050
  );
1051
+ // The store subscription and late fetch responses outlive the section
1052
+ // unless the controller is detached with the plugin.
1053
+ ctx.effect(() => () => controller.dispose(), "websearch: card controller");
675
1054
  // Credential invalidations: 0.2.x forwards `credentials/reference-updated`;
676
1055
  // older lines forwarded `credentials/updated`. Subscribe to whichever
677
1056
  // event face this build exposes; a missing face must not abort apply().
@@ -705,22 +1084,25 @@ window.__ModuleLoader__.load({
705
1084
  try {
706
1085
  if (window.__dshDevkit && typeof window.__dshDevkit.toast === "function") {
707
1086
  window.__dshDevkit.toast(hint, { kind: "info" });
708
- return;
1087
+ } else {
1088
+ console.info("[dsh-websearch] " + hint);
709
1089
  }
710
- } catch (e) { /* fall through */ }
711
- console.info("[dsh-websearch] " + hint);
1090
+ } catch (e) { /* best-effort notification */ }
1091
+ try {
1092
+ window.dispatchEvent(new CustomEvent("dsh-websearch:open-settings:ack"));
1093
+ } catch (e) { /* CustomEvent unavailable */ }
712
1094
  };
713
1095
  // Probe contract (devkit 0.1.1): ready flag + ack event, so the
714
1096
  // palette can tell "listener present" from "gracefully absent".
715
1097
  try {
716
1098
  window.__dshWebsearchSettingsReady = true;
717
- window.addEventListener("dsh-websearch:open-settings", (ev) => {
718
- onOpenSettings(ev);
719
- try {
720
- window.dispatchEvent(new CustomEvent("dsh-websearch:open-settings:ack"));
721
- } catch (e) { /* CustomEvent unavailable */ }
722
- });
723
- ctx.effect(() => () => window.removeEventListener("dsh-websearch:open-settings", onOpenSettings), "websearch: open-settings listener");
1099
+ // Remove the exact function that was added: an anonymous listener
1100
+ // cannot be removed, so every reload used to stack another one.
1101
+ window.addEventListener("dsh-websearch:open-settings", onOpenSettings);
1102
+ ctx.effect(() => () => {
1103
+ window.removeEventListener("dsh-websearch:open-settings", onOpenSettings);
1104
+ window.__dshWebsearchSettingsReady = false;
1105
+ }, "websearch: open-settings listener");
724
1106
  } catch (e) { /* non-window env */ }
725
1107
  }
726
1108