@jayyuen66/dsh-zvec-grep 0.1.3 → 0.1.5

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 (6) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +42 -26
  3. package/README.zh-CN.md +44 -26
  4. package/client.js +221 -137
  5. package/host.js +1361 -1291
  6. package/package.json +48 -43
package/client.js CHANGED
@@ -82,6 +82,13 @@ const LOCAL_EMBEDDINGS = [
82
82
  }
83
83
  ];
84
84
  //#endregion
85
+ //#region node_modules/@jayyuen66/dsh-plugin-shared/dist/card-diff.js
86
+ function e$1(e, t) {
87
+ let n = [];
88
+ for (let r of Object.keys(e)) JSON.stringify(e[r] ?? null) !== JSON.stringify(t[r] ?? null) && n.push(r);
89
+ return n;
90
+ }
91
+ //#endregion
85
92
  //#region lib/card-draft.ts
86
93
  /** 草稿优先取值:touched 有该键(哪怕值是 undefined=待清空)即用草稿。 */
87
94
  function draftOf(touched, value, field) {
@@ -92,13 +99,21 @@ function numberText(raw, fallback) {
92
99
  return typeof raw === "number" && Number.isFinite(raw) ? String(raw) : fallback;
93
100
  }
94
101
  //#endregion
95
- //#region node_modules/@jayyuen66/dsh-plugin-shared/dist/record.js
96
- function e$1(e) {
97
- return typeof e == `object` && !!e && !Array.isArray(e);
98
- }
99
- //#endregion
100
102
  //#region lib/card-logic.ts
101
103
  /**
104
+ * 引导端点交回的守护进程就绪态该显示哪一行。
105
+ *
106
+ * `undefined` 是**必要**的一臂,不是兜底:旧版 host 的应答里没有 `serverReady` 这个字段,
107
+ * 而「应答里没写」与「写了未就绪」是两件事——把前者显示成后者,卡片就在用户眼前谎称了一次
108
+ * 「没有守护进程」。判据收在可单测的这一层,client 只负责渲染它选出来的那一行。
109
+ */
110
+ function daemonNoteKey(ready) {
111
+ let key;
112
+ if (ready === true) key = "daemonReadyNote";
113
+ else if (ready === false) key = "daemonOfflineNote";
114
+ return key;
115
+ }
116
+ /**
102
117
  * 把 settings scope 桥成 { getSnapshot, subscribe } store。
103
118
  * 缓存必须 per-scope(闭包内):模块全局会在多 scope 交错 getSnapshot 时互相
104
119
  * 冲 memo,导致 useSyncExternalStore 每次拿到新引用 → 无限重渲染。
@@ -230,32 +245,130 @@ function parseRebuildPoll(body, t) {
230
245
  output: outputText.length > 0 ? `${reason}\n${outputText}` : reason
231
246
  };
232
247
  }
233
- /**
234
- * 响应不健康的可行动描述;健康返回 null。
235
- * @param ok - res.ok
236
- * @param status - res.status(403 单列:CSRF token 过期时卡片要「重取 token 重试」)
237
- * @param contentType - res.headers.get('content-type') ?? ''
238
- * @param t - 文案取值(官方 locale 的 translator)
239
- */
240
- function httpProblem(ok, status, contentType, t) {
241
- if (status === 403) return t("httpForbidden");
242
- if (!ok) return t("httpFailed", { status });
243
- if (!contentType.toLowerCase().includes("application/json")) return t("httpNotJson", { contentType: contentType.length > 0 ? contentType : t("contentTypeMissing") });
244
- return null;
248
+ //#endregion
249
+ //#region node_modules/@jayyuen66/dsh-plugin-shared/dist/record.js
250
+ function e(e) {
251
+ return typeof e == `object` && !!e && !Array.isArray(e);
245
252
  }
246
- /** JSON 文本 → 对象;非对象/解析失败返回 null(调用方给可读错误)。 */
247
- function parseJsonRecord(text) {
248
- let parsed;
249
- try {
250
- parsed = JSON.parse(text);
251
- } catch {
252
- return null;
253
+ //#endregion
254
+ //#region src/rebuild-reader.ts
255
+ const REBUILD_NAMESPACE = "zvecGrepRebuild";
256
+ /** 网关给命名空间注册的**服务键**:`remote.<namespace>`。它在 `$mount` 完成之后才存在,
257
+ * 所以只能在挂载后按这个键去读,而不是提前 inject。 */
258
+ const REBUILD_SERVICE_KEY = `remote.${REBUILD_NAMESPACE}`;
259
+ /** 卡片所在 bundle 的包名(`$mount` 的 `package` 位与槽位键同源,见 client-entry.ts 的 BUNDLE_PKG)。 */
260
+ const PACKAGE_NAME = "@jayyuen66/dsh-zvec-grep";
261
+ /** 把宿主那三个方法挂到客户端远程面上的描述符(`id` 的形状照生成器:`<包>#<命名空间>/<方法>`)。
262
+ * 导出它只为一件事:`test/rebuild-remote.test.ts` 拿它与宿主侧 `remoteMethods()` 的标记对质
263
+ * —— 两侧分叉时卡片不会报错,只会"读不到",所以那条比较必须在门禁里。 */
264
+ const REBUILD_DESCRIPTORS = [
265
+ {
266
+ id: `${PACKAGE_NAME}#${REBUILD_NAMESPACE}/roots`,
267
+ service: REBUILD_NAMESPACE,
268
+ namespace: REBUILD_NAMESPACE,
269
+ method: "roots",
270
+ invocation: { kind: "direct" },
271
+ parameters: [],
272
+ result: { mode: "src-json" }
273
+ },
274
+ {
275
+ id: `${PACKAGE_NAME}#${REBUILD_NAMESPACE}/rebuild`,
276
+ service: REBUILD_NAMESPACE,
277
+ namespace: REBUILD_NAMESPACE,
278
+ method: "rebuild",
279
+ invocation: { kind: "direct" },
280
+ parameters: [{
281
+ name: "request",
282
+ wire: "request",
283
+ source: "json",
284
+ codec: {
285
+ mode: "strict",
286
+ typeSymbol: `${PACKAGE_NAME}#rebuild-request`,
287
+ create: () => ({ parse(value) {
288
+ if (!e(value) || typeof value["root"] !== "string") throw new TypeError("rebuild request requires a string root");
289
+ return { root: value["root"] };
290
+ } })
291
+ }
292
+ }],
293
+ result: { mode: "src-json" }
294
+ },
295
+ {
296
+ id: `${PACKAGE_NAME}#${REBUILD_NAMESPACE}/status`,
297
+ service: REBUILD_NAMESPACE,
298
+ namespace: REBUILD_NAMESPACE,
299
+ method: "status",
300
+ invocation: { kind: "direct" },
301
+ parameters: [{
302
+ name: "request",
303
+ wire: "request",
304
+ source: "json",
305
+ codec: {
306
+ mode: "strict",
307
+ typeSymbol: `${PACKAGE_NAME}#rebuild-status-request`,
308
+ create: () => ({ parse(value) {
309
+ if (!e(value) || typeof value["jobId"] !== "string") throw new TypeError("rebuild status request requires a string jobId");
310
+ return { jobId: value["jobId"] };
311
+ } })
312
+ }
313
+ }],
314
+ result: { mode: "src-json" }
253
315
  }
254
- return e$1(parsed) ? parsed : null;
316
+ ];
317
+ /** 这个值能当远程面用吗(只核我们要调的那一位;服务来自别的实现或版本时保守当作没有)。 */
318
+ const isRemoteMounter = (value) => e(value) && typeof value["$mount"] === "function";
319
+ /** 同上:命名空间服务(挂载之后才有,缺它说明网关没认这枚贡献)。 */
320
+ const isRebuildNamespace = (value) => e(value) && typeof value["roots"] === "function" && typeof value["rebuild"] === "function" && typeof value["status"] === "function";
321
+ /**
322
+ * 造出真正的读取器(挂载一次 + 每次读命名空间服务)。
323
+ * @param ctx - 客户端上下文
324
+ * @param remote - 已核过形状的远程面
325
+ * @returns 读取器
326
+ */
327
+ function buildRebuildReader(ctx, remote) {
328
+ let mounted;
329
+ const namespaceOf = async () => {
330
+ mounted ??= remote.$mount({
331
+ package: PACKAGE_NAME,
332
+ descriptors: REBUILD_DESCRIPTORS
333
+ });
334
+ await mounted;
335
+ const namespace = ctx.get?.(REBUILD_SERVICE_KEY, false);
336
+ if (!isRebuildNamespace(namespace)) throw new Error(`${REBUILD_SERVICE_KEY} 未提供:宿主网关没有挂上这枚命名空间`);
337
+ return namespace;
338
+ };
339
+ return {
340
+ async roots() {
341
+ const result = await (await namespaceOf()).roots();
342
+ if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
343
+ return result.value;
344
+ },
345
+ async rebuild(root) {
346
+ const result = await (await namespaceOf()).rebuild({ root });
347
+ if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
348
+ if (!result.value.ok) throw new Error(result.value.error);
349
+ return result.value;
350
+ },
351
+ async status(jobId) {
352
+ const result = await (await namespaceOf()).status({ jobId });
353
+ if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
354
+ if (!result.value.ok) throw new Error(result.value.error);
355
+ return { ...result.value };
356
+ }
357
+ };
255
358
  }
256
- /** 端点统一应答形状:`{ ok: true, … }` 才算成功。 */
257
- function isOkBody(body) {
258
- return body["ok"] === true;
359
+ /**
360
+ * 造一个「读宿主侧工作区重建」的读取器;**当前部署没有远程面时返回 `undefined`**
361
+ * (卡片照常渲染,只是点重建时给出错误 —— 与 host 侧可选读面同一条口径)。
362
+ *
363
+ * `$mount` 是**幂等**的(挂进本 fiber,随卡片卸载自动撤),所以这里缓存那枚 promise:
364
+ * 同一次会话里反复轮询只挂一次。
365
+ *
366
+ * @param ctx - 客户端上下文(只用 `get` 一位)
367
+ * @returns 读取器;没有远程面时 `undefined`
368
+ */
369
+ function createRebuildReader(ctx) {
370
+ const remote = ctx.get?.("remote");
371
+ return isRemoteMounter(remote) ? buildRebuildReader(ctx, remote) : void 0;
259
372
  }
260
373
  //#endregion
261
374
  //#region src/ui-messages.ts
@@ -287,6 +400,8 @@ const UI_MESSAGES = {
287
400
  windowHint: "超过该时长未再次 zg_search,配额整体过期;清空恢复默认 10",
288
401
  windowInvalid: "解锁时效必须是 {min}-{max} 的整数",
289
402
  rebuildLabel: "工作区重建(切换 embedding 并保存后执行)",
403
+ daemonReadyNote: "守护进程:就绪 —— 检索可走 server 模式,索引有增量刷新与后台刷新,embedding 模型池常驻。",
404
+ daemonOfflineNote: "守护进程:未就绪 —— 检索按直连模式逐次冷加载 embedding 模型(大工作区更慢),refresh=background 与索引增量刷新不可用;需要时在终端执行 `zg server on`。",
290
405
  rebuildHint: "以当前默认模型重建:{embedding};等价于 zg index --rebuild。{roots}",
291
406
  rootsNoteWith: "候选工作区来自本 daemon 已打开过的会话(服务端白名单)。",
292
407
  rootsNoteEmpty: "尚无可选工作区:先在该工作区里开一个会话(任一次工具调用即登记)。",
@@ -299,16 +414,11 @@ const UI_MESSAGES = {
299
414
  rebuildExitCode: "重建进程退出码 {exitCode}(zg 未安装/权限不足/沙箱拒绝都会走到这里)",
300
415
  rebuildMissingJobId: "启动重建失败:应答缺 jobId",
301
416
  rebuildRootNotAbsolute: "root 必须是绝对路径(以 / 开头)",
417
+ rebuildUnavailable: "宿主没有提供工作区重建读面(未装远程服务)",
302
418
  modelOption: "{reference}({dimension}维)",
303
419
  backendLlamaCpp: "llama-cpp(原生,需 node-llama-cpp)",
304
420
  backendTransformersJs: "transformers-js(纯 JS ONNX)",
305
- backendModel2Vec: "model2vec(纯 JS worker,最轻)",
306
- httpForbidden: "403:请求被拒绝(同源校验或 CSRF token 失效)",
307
- httpFailed: "请求失败(HTTP {status})",
308
- httpNotJson: "响应不是 JSON(content-type={contentType}):重建端点未注册或路径被前端兜住了",
309
- contentTypeMissing: "缺省",
310
- notJsonBody: "响应不是 JSON 对象:{url}",
311
- requestRejected: "请求未被接受"
421
+ backendModel2Vec: "model2vec(纯 JS worker,最轻)"
312
422
  },
313
423
  en: {
314
424
  cardTitle: "zvec-grep (zg)",
@@ -337,6 +447,8 @@ const UI_MESSAGES = {
337
447
  windowHint: "Without another zg_search inside this window the whole quota expires; clear to restore the default 10",
338
448
  windowInvalid: "the unlock window must be an integer between {min} and {max}",
339
449
  rebuildLabel: "Workspace rebuild (run after switching embedding and saving)",
450
+ daemonReadyNote: "Daemon: ready — searches can use server mode, with incremental and background index refreshing and a resident embedding model pool.",
451
+ daemonOfflineNote: "Daemon: not ready — searches run in direct mode and cold-load the embedding model every call (slower on large workspaces); refresh=background and incremental index refresh are unavailable. Run `zg server on` in a terminal when you want it.",
340
452
  rebuildHint: "Rebuild with the current default model: {embedding}; same as zg index --rebuild. {roots}",
341
453
  rootsNoteWith: "Candidates come from sessions this daemon already opened (server-side whitelist).",
342
454
  rootsNoteEmpty: "No workspace to pick yet: open a session in that workspace first (any tool call registers it).",
@@ -349,73 +461,61 @@ const UI_MESSAGES = {
349
461
  rebuildExitCode: "the rebuild process exited with code {exitCode} (missing zg, insufficient permissions and sandbox denials all land here)",
350
462
  rebuildMissingJobId: "failed to start the rebuild: the response has no jobId",
351
463
  rebuildRootNotAbsolute: "root must be an absolute path (starting with /)",
464
+ rebuildUnavailable: "the host does not expose the rebuild Remote API",
352
465
  modelOption: "{reference} ({dimension} dims)",
353
466
  backendLlamaCpp: "llama-cpp (native, requires node-llama-cpp)",
354
467
  backendTransformersJs: "transformers-js (pure JS ONNX)",
355
- backendModel2Vec: "model2vec (pure JS worker, lightest)",
356
- httpForbidden: "403: request rejected (same-origin check or expired CSRF token)",
357
- httpFailed: "request failed (HTTP {status})",
358
- httpNotJson: "response is not JSON (content-type={contentType}): the rebuild endpoint is not registered, or a front-end fallback caught the path",
359
- contentTypeMissing: "unset",
360
- notJsonBody: "response is not a JSON object: {url}",
361
- requestRejected: "the request was not accepted"
468
+ backendModel2Vec: "model2vec (pure JS worker, lightest)"
362
469
  }
363
470
  };
364
471
  //#endregion
365
472
  //#region node_modules/@jayyuen66/dsh-plugin-shared/dist/errors.js
366
- function e(e) {
473
+ function t(e) {
367
474
  let t = Object.getOwnPropertyDescriptor(e, `message`);
368
475
  return t !== void 0 && `value` in t && typeof t.value == `string` ? t.value : void 0;
369
476
  }
370
- function t(n, r) {
371
- if (r.has(n)) return `<circular cause>`;
372
- r.add(n);
477
+ function n(e, r) {
478
+ if (r.has(e)) return `<circular cause>`;
479
+ r.add(e);
373
480
  try {
374
- if (!(n instanceof Error)) {
375
- if (typeof n == `object` && n) {
376
- let t = e(n);
377
- if (t !== void 0) return t;
481
+ if (!(e instanceof Error)) {
482
+ if (typeof e == `object` && e) {
483
+ let n = t(e);
484
+ if (n !== void 0) return n;
378
485
  }
379
- return String(n);
486
+ return String(e);
380
487
  }
381
- let i = n.message === `` ? n.name : n.message, a = n instanceof AggregateError && n.errors.length > 0 ? ` [${n.errors.map((e) => t(e, r)).join(`; `)}]` : ``, o = n.cause === void 0 || n.cause === null ? `` : t(n.cause, r);
488
+ let i = e.message === `` ? e.name : e.message, a = e instanceof AggregateError && e.errors.length > 0 ? ` [${e.errors.map((e) => n(e, r)).join(`; `)}]` : ``, o = e.cause === void 0 || e.cause === null ? `` : n(e.cause, r);
382
489
  return `${i}${a}${o === `` || o === i ? `` : `: ${o}`}`;
383
490
  } catch {
384
491
  return `<unrenderable value>`;
385
492
  } finally {
386
- r.delete(n);
493
+ r.delete(e);
387
494
  }
388
495
  }
389
- function n(e) {
390
- return t(e, /* @__PURE__ */ new Set());
496
+ function r(e) {
497
+ return n(e, /* @__PURE__ */ new Set());
391
498
  }
392
499
  //#endregion
393
500
  //#region src/client-entry.ts
394
501
  const NS = "zvec-grep";
395
502
  /**
396
503
  * `plugins.bundle.config` 的 key = **bundle 的 npm 包名**(不是裸条目 id)。
397
- * 派发证据(installed dsh 0.1.7):
398
- * · dsh-client-ui-plugin-manager/lib/client.js:1821 `renderSlot("plugins.bundle.config",
504
+ * 派发证据(installed dsh 0.2.1-rc.2,按符号核对):
505
+ * · dsh-client-ui-plugin-manager 的 client.js 里 `renderSlot("plugins.bundle.config",
399
506
  * { view: "page" }, { entryKey: pkg.name })`——pkg.name 是 bundle 包名;
400
- * · 同文件 :2698 `configured: ledger.bundles.has(openPkg.name)`,:306/:320 的
401
- * `packageView()` 里 `name: bundle.name`(= bundle 包),所以没有第二条可匹配的 key;
507
+ * · 同文件里 `configured: ledger.bundles.has(openPkg.name)` 与 `packageView()` 的
508
+ * `name: bundle.name`(= bundle 包),所以没有第二条可匹配的 key;
402
509
  * · 同包 lib/types/client/slot-contract.d.ts「A bundle's own configuration,
403
510
  * **keyed by the bundle's package name**」,且 kind 为 `keyed` → `key` 必填;
404
- * · dsh-client-ui-renderer/lib/client.js:1154 逐字相等匹配 `entry.options.key === entryKey`,
405
- * 错一个字符就是「整张卡不渲染」(不是回落、不是报错);
406
- * · 官方占位者 dsh-experimental-client-ui-voice-input/lib/client.js:5659-5661 同样把
407
- * key 写成包名 `@deepseek-ai/dsh-experimental-voice-input-bundle`。
408
- * 行槽(本包未用)则是 `<pkg>#<rowId>`(plugin-manager/lib/client.js:27-28 `rowConfigKey`)。
511
+ * · dsh-client-ui-renderer 的 `entriesOfSlot(...).find((e) => e.options.key === opts?.entryKey)`
512
+ * 是逐字相等匹配,错一个字符就是「整张卡不渲染」(不是回落、不是报错)。
513
+ * 行槽(本包未用)则是 `<pkg>#<rowId>`(同包的 `rowConfigKey(bundle, rowId)`)。
409
514
  * 值 = 本包 package.json 的 name,且必须出现在 profile 的 `dsh.profile.bundles` 里;
410
515
  * test/build-client.test.ts 从 `~/.dsh/profiles/web/package.json` 解析校验,不在此处硬抄。
411
516
  * 设置命名空间**不跟着改**:`ctx.configForms.get(entryId)` 仍吃裸条目 id(见 apply)。
412
517
  */
413
518
  const BUNDLE_PKG = "@jayyuen66/dsh-zvec-grep";
414
- const REBUILD_ROOTS_URL = "/_dsh/zvec-grep/rebuild-roots";
415
- const REBUILD_URL = "/_dsh/zvec-grep/rebuild";
416
- const REBUILD_STATUS_URL = "/_dsh/zvec-grep/rebuild-status";
417
- /** 与 host.ts REBUILD_CSRF_HEADER 一致:动作端点要求回填这个头。 */
418
- const REBUILD_CSRF_HEADER = "x-zvec-grep-csrf";
419
519
  /** 重建轮询间隔(宿主后台进程,2s 足够跟上 zg 的进度输出)。 */
420
520
  const REBUILD_POLL_MS = 2e3;
421
521
  /** 解锁配额/时效的合法上限(与 host Config 的 schema 同范围,输入框与提示共用)。 */
@@ -502,12 +602,6 @@ function PluginCard(props) {
502
602
  const body = open ? (0, react.createElement)("div", { className: "zgc-card-body" }, children) : null;
503
603
  return (0, react.createElement)("li", { className: open ? "zgc-card zgc-card-open" : "zgc-card" }, header, body);
504
604
  }
505
- /** touched 层与快照的差异字段(值语义比较;undefined 与缺失等价)。 */
506
- function diffTouched(touched, value) {
507
- const out = [];
508
- for (const key of Object.keys(touched)) if (JSON.stringify(touched[key] ?? null) !== JSON.stringify(value[key] ?? null)) out.push(key);
509
- return out;
510
- }
511
605
  /** 保存条(全自研插件统一)。 */
512
606
  function SaveBar(props) {
513
607
  const { t } = props;
@@ -702,6 +796,21 @@ function buildRebuildRow(deps) {
702
796
  }, rebuild.phase === "running" ? t("rebuildRunning") : t("rebuildButton"));
703
797
  return (0, react.createElement)("div", { className: "zgc-row" }, rebuildLabel, rebuildHint, rootDatalist, rebuildInput, rebuildButton);
704
798
  }
799
+ /**
800
+ * 守护进程(`zg server`)就绪态一行,取自 rebuild-roots 引导端点。
801
+ *
802
+ * 为什么值得单独占一行:daemon 缺席时检索按直连模式逐次冷加载 embedding 模型,而
803
+ * `refresh=background`、索引增量刷新与常驻模型池都不存在——本包因此在命令构造期就拒
804
+ * background。把这一档摆在「工作区重建」旁边,用户才不至于从「检索怎么这么慢」倒推。
805
+ * `undefined` 那一档**不渲染**:旧版 host 的应答没有这个字段,说成「未就绪」是谎称。
806
+ */
807
+ function buildDaemonNote(deps) {
808
+ const { t } = deps;
809
+ const key = daemonNoteKey(deps.serverReady);
810
+ if (key === void 0) return null;
811
+ const note = (0, react.createElement)("div", { className: "zgc-hint" }, t(key));
812
+ return (0, react.createElement)("div", { className: "zgc-row" }, note);
813
+ }
705
814
  /** 重建状态节点:phase 非 idle 才出现;done 且无输出时给一句「已完成」。 */
706
815
  function buildRebuildStatusRow(deps) {
707
816
  const { rebuild, t } = deps;
@@ -748,6 +857,7 @@ function buildCardBody(deps) {
748
857
  onSave: deps.onSave,
749
858
  onDiscard: deps.onDiscard
750
859
  }),
860
+ buildDaemonNote(deps),
751
861
  buildRebuildRow(deps)
752
862
  ];
753
863
  const status = buildRebuildStatusRow(deps);
@@ -763,45 +873,22 @@ function pushFieldWrite(ops, key, draft, set) {
763
873
  else if (key === "grepBudgetPerSearch") ops.push(set("grepBudgetPerSearch", draft));
764
874
  else if (key === "unlockWindowMin") ops.push(set("unlockWindowMin", draft));
765
875
  }
766
- /** 服务端 `{ok:false,error}` 里的可行动文案(无 error 字段给通用兜底)。 */
767
- function serverErrorOf(body, t) {
768
- if (body === null) return null;
769
- const { error } = body;
770
- return typeof error === "string" && error.length > 0 ? error : t("requestRejected");
771
- }
772
- /**
773
- * 一次 JSON 往返:先按 content-type 决定能不能当 JSON 读(未注册的路径会被前端
774
- * SPA fallback 兜成 200 + text/html,直接 JSON.parse 只能给出
775
- * `SyntaxError: Unexpected token '<'`),再让服务端的 error 文案优先于 HTTP 层
776
- * 的笼统描述。
777
- */
778
- async function requestJson(url, t, init) {
779
- const res = await fetch(url, init);
780
- const contentType = res.headers.get("content-type") ?? "";
781
- const record = contentType.toLowerCase().includes("json") ? parseJsonRecord(await res.text()) : null;
782
- const problem = serverErrorOf(record, t) ?? httpProblem(res.ok, res.status, contentType, t);
783
- if (problem !== null) throw new Error(problem);
784
- if (record === null) throw new Error(t("notJsonBody", { url }));
785
- return record;
876
+ /** 读取器缺席时的可行动文案:宿主没装远程面(或网关没挂上这枚命名空间)。 */
877
+ function requireReader(reader, t) {
878
+ if (reader === void 0) throw new Error(t("rebuildUnavailable"));
879
+ return reader;
786
880
  }
787
881
  const NO_ACCESS = {
788
- csrf: "",
789
- roots: []
882
+ roots: [],
883
+ serverReady: void 0
790
884
  };
791
- /** 引导端点应答 → { csrf, roots }(字段缺失/类型不对一律当作没拿到)。 */
792
- function readAccess(body) {
793
- const { csrf, roots } = body;
794
- return {
795
- csrf: typeof csrf === "string" ? csrf : "",
796
- roots: Array.isArray(roots) ? roots.filter((item) => typeof item === "string") : []
797
- };
798
- }
799
885
  /**
800
- * 「工作区重建」状态机:取 token/白名单 → POST 启动 → 2s 轮询到终态。
886
+ * 「工作区重建」状态机:取白名单 → 起一条重建 → 2s 轮询到终态。
801
887
  * 从 ZgCard 拆出,保持组件体在一屏内可读。
802
888
  * @param t - 取文案(官方 locale 的 translator,随卡片一起下发)。
889
+ * @param reader - 宿主重建读面;`undefined` = 当前部署没有远程面(点重建时报错)。
803
890
  */
804
- function useRebuild(t) {
891
+ function useRebuild(t, reader) {
805
892
  const [root, setRoot] = (0, react.useState)("");
806
893
  const [access, setAccess] = (0, react.useState)(NO_ACCESS);
807
894
  const [rebuild, setRebuild] = (0, react.useState)({
@@ -818,13 +905,17 @@ function useRebuild(t) {
818
905
  (0, react.useEffect)(() => () => {
819
906
  stopPolling();
820
907
  }, []);
821
- /** 拉 CSRF token + 白名单。失败**不**改重建面板:面板 idle 时冒一个红字只是噪音,
908
+ /** 拉白名单 + 就绪态。失败**不**改重建面板:面板 idle 时冒一个红字只是噪音,
822
909
  * 用户真点「重建」时 start() 会把同一错误显示出来。 */
823
910
  const refreshAccess = (0, react.useCallback)(async () => {
824
- const next = readAccess(await requestJson(REBUILD_ROOTS_URL, t));
825
- setAccess(next);
826
- return next;
827
- }, [t]);
911
+ const next = await requireReader(reader, t).roots();
912
+ const view = {
913
+ roots: [...next.roots],
914
+ serverReady: next.serverReady
915
+ };
916
+ setAccess(view);
917
+ return view;
918
+ }, [reader, t]);
828
919
  (0, react.useEffect)(() => {
829
920
  (async () => {
830
921
  try {
@@ -836,7 +927,7 @@ function useRebuild(t) {
836
927
  }, [refreshAccess]);
837
928
  async function pollStatus(jobId) {
838
929
  try {
839
- const poll = parseRebuildPoll(await requestJson(`${REBUILD_STATUS_URL}?jobId=${encodeURIComponent(jobId)}`, t), t);
930
+ const poll = parseRebuildPoll(await requireReader(reader, t).status(jobId), t);
840
931
  if (poll.phase !== "running") stopPolling();
841
932
  setRebuild({
842
933
  phase: poll.phase,
@@ -846,18 +937,15 @@ function useRebuild(t) {
846
937
  stopPolling();
847
938
  setRebuild({
848
939
  phase: "error",
849
- output: n(error)
940
+ output: r(error)
850
941
  });
851
942
  }
852
943
  }
853
- /** 发起一次重建(带 token);成功后进入轮询。 */
854
- async function startOnce(token) {
855
- const body = await requestJson(`${REBUILD_URL}?root=${encodeURIComponent(root.trim())}`, t, {
856
- method: "POST",
857
- headers: { [REBUILD_CSRF_HEADER]: token }
858
- });
859
- const { jobId } = body;
860
- if (!isOkBody(body) || typeof jobId !== "string") throw new Error(t("rebuildMissingJobId"));
944
+ /** 发起一次重建;成功后进入轮询。 */
945
+ async function startOnce() {
946
+ const started = await requireReader(reader, t).rebuild(root.trim());
947
+ if (typeof started.jobId !== "string") throw new TypeError(t("rebuildMissingJobId"));
948
+ const { jobId } = started;
861
949
  pollRef.current = setInterval(() => {
862
950
  pollStatus(jobId);
863
951
  }, REBUILD_POLL_MS);
@@ -876,25 +964,19 @@ function useRebuild(t) {
876
964
  output: t("rebuildStarting")
877
965
  });
878
966
  try {
879
- let token = access.csrf;
880
- if (token === "") token = (await refreshAccess()).csrf;
881
- try {
882
- await startOnce(token);
883
- } catch (error) {
884
- if (access.csrf === "") throw error;
885
- await startOnce((await refreshAccess()).csrf);
886
- }
967
+ await startOnce();
887
968
  } catch (error) {
888
969
  stopPolling();
889
970
  setRebuild({
890
971
  phase: "error",
891
- output: n(error)
972
+ output: r(error)
892
973
  });
893
974
  }
894
975
  }
895
976
  return {
896
977
  root,
897
978
  roots: access.roots,
979
+ serverReady: access.serverReady,
898
980
  state: rebuild,
899
981
  setRoot,
900
982
  start
@@ -909,9 +991,9 @@ function ZgCard(props) {
909
991
  const [touched, setTouched] = (0, react.useState)({});
910
992
  const [busy, setBusy] = (0, react.useState)(false);
911
993
  const [saveError, setSaveError] = (0, react.useState)(null);
912
- const rebuildView = useRebuild(t);
994
+ const rebuildView = useRebuild(t, props.rebuildRemote);
913
995
  const fields = draftFields(touched, value);
914
- const dirty = diffTouched(touched, value).length > 0;
996
+ const dirty = e$1(touched, value).length > 0;
915
997
  const setField = (field, draft) => {
916
998
  setTouched((prev) => ({
917
999
  ...prev,
@@ -919,7 +1001,7 @@ function ZgCard(props) {
919
1001
  }));
920
1002
  };
921
1003
  const save = async () => {
922
- const keys = diffTouched(touched, value);
1004
+ const keys = e$1(touched, value);
923
1005
  if (keys.length === 0) return;
924
1006
  setBusy(true);
925
1007
  setSaveError(null);
@@ -937,7 +1019,7 @@ function ZgCard(props) {
937
1019
  }
938
1020
  } catch (error) {
939
1021
  setBusy(false);
940
- setSaveError(t("saveFailed", { reason: n(error) }));
1022
+ setSaveError(t("saveFailed", { reason: r(error) }));
941
1023
  return;
942
1024
  }
943
1025
  const savedKeys = new Set(keys);
@@ -954,6 +1036,7 @@ function ZgCard(props) {
954
1036
  fields,
955
1037
  writable,
956
1038
  roots: rebuildView.roots,
1039
+ serverReady: rebuildView.serverReady,
957
1040
  root: rebuildView.root,
958
1041
  rebuild: rebuildView.state,
959
1042
  dirty,
@@ -995,6 +1078,7 @@ function apply(ctx) {
995
1078
  const store = cardStore(scope);
996
1079
  ctx.effect(() => ctx.locale.register(NS, UI_MESSAGES), "zvec-grep-card: locale dictionaries");
997
1080
  const t = ctx.locale.bind(NS);
1081
+ const rebuildRemote = createRebuildReader(ctx);
998
1082
  const writeField = async (field, valueDraft) => {
999
1083
  try {
1000
1084
  return await scope.set(field, valueDraft);
@@ -1019,7 +1103,8 @@ function apply(ctx) {
1019
1103
  t,
1020
1104
  hooks: { card: store },
1021
1105
  set: writeField,
1022
- unset: unsetField
1106
+ unset: unsetField,
1107
+ rebuildRemote
1023
1108
  })
1024
1109
  }, ZgCard);
1025
1110
  });
@@ -1027,7 +1112,6 @@ function apply(ctx) {
1027
1112
  //#endregion
1028
1113
  exports.apply = apply;
1029
1114
  exports.cardStore = cardStore;
1030
- exports.diffTouched = diffTouched;
1031
1115
  exports.draftFields = draftFields;
1032
1116
  exports.inject = inject;
1033
1117
  exports.parseRebuildPoll = parseRebuildPoll;