dsh-mobile-plugin 0.5.83 → 0.5.85

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 (41) hide show
  1. package/lib/client.js +218 -6
  2. package/lib/http/routing.js +7 -0
  3. package/lib/impl.js +7 -1
  4. package/lib/mobile/channels.js +41 -18
  5. package/lib/mobile/feedback.js +142 -69
  6. package/lib/mobile/forge-contract.js +186 -0
  7. package/lib/mobile/forge-worktree.js +117 -0
  8. package/lib/mobile/forge.js +197 -0
  9. package/lib/mobile/host-bridge/endpoints.js +77 -8
  10. package/lib/mobile/host-bridge/event-synthesis.js +6 -7
  11. package/lib/mobile/host-bridge/shims.js +50 -29
  12. package/lib/mobile/host-settings.js +32 -0
  13. package/lib/mobile/model-caps.js +10 -6
  14. package/lib/mobile/pairing.js +10 -2
  15. package/lib/mobile/permissions.js +32 -0
  16. package/lib/mobile/plugin-market.js +94 -50
  17. package/lib/mobile/plugin-update.js +5 -0
  18. package/lib/mobile/relay-control.js +87 -0
  19. package/lib/mobile/schedule-edit.js +30 -55
  20. package/lib/mobile/schedule.js +98 -24
  21. package/lib/mobile/session-new.js +11 -1
  22. package/lib/mobile/subagents.js +63 -25
  23. package/lib/mobile/worktree-isolation.js +12 -4
  24. package/lib/mobile/worktree-lifecycle.js +2 -0
  25. package/lib/p2p/wiring.cjs +32 -14
  26. package/lib/panel/index.html +22 -21
  27. package/lib/relay/control.js +25 -8
  28. package/lib/relay/core.js +21 -18
  29. package/lib/relay/pairing-payload.cjs +7 -0
  30. package/lib/relay/status.js +2 -1
  31. package/lib/relay/tunnel-forwarder.cjs +5 -3
  32. package/lib/relay/tunnel.js +7 -2
  33. package/lib/remote/host-control.cjs +1 -1
  34. package/lib/routes/control-plane.js +4 -3
  35. package/lib/routes/mobile-api.js +59 -1
  36. package/lib/sidecar-facade-worker.cjs +9 -2
  37. package/lib/sidecar-facade.cjs +50 -22
  38. package/lib/sidecar-lifecycle.cjs +4 -3
  39. package/lib/tailcat/ingress.cjs +5 -3
  40. package/lib/tailcat/wiring.cjs +54 -30
  41. package/package.json +1 -1
@@ -172,6 +172,7 @@ const MAP = Object.freeze({
172
172
  '/api/mobile/v1/schedule/catalog': V.VIEW,
173
173
  '/api/mobile/v1/schedule/list': V.VIEW,
174
174
  '/api/mobile/v1/schedule/history': V.VIEW,
175
+ '/api/mobile/v1/schedule/view': V.VIEW,
175
176
  '/api/mobile/v1/inbox/status': V.VIEW,
176
177
  '/api/mobile/v1/inbox/clear': V.FILES_WRITE,
177
178
  '/api/mobile/v1/inbox/auto': V.CONFIG,
@@ -220,6 +221,7 @@ const MAP = Object.freeze({
220
221
  '/api/mobile/v1/plugin/market/detail': V.VIEW,
221
222
  '/api/mobile/v1/plugin/market/inspect': V.VIEW,
222
223
  '/api/mobile/v1/plugin/market/progress': V.VIEW,
224
+ '/api/mobile/v1/plugin/market/versions': V.VIEW,
223
225
  '/api/mobile/v1/plugin/update/status': V.VIEW,
224
226
  '/api/mobile/v1/plugin/update/check': V.VIEW,
225
227
  '/api/mobile/v1/plugin/self': V.VIEW,
@@ -245,6 +247,27 @@ const MAP = Object.freeze({
245
247
  '/api/mobile/v1/git/pr/comments': { GET: V.FILES_READ, POST: V.FILES_WRITE },
246
248
  '/api/mobile/v1/git/pr/ready': V.FILES_WRITE,
247
249
  '/api/mobile/v1/git/pr/merge': V.FILES_WRITE,
250
+ // Forge 评审:读链归 files.read;写评审 / 检查重跑 / 请求评审 / 更新分支 / 合并都动远端仓库,归 files.write。
251
+ '/api/mobile/v1/git/forge/capabilities': V.VIEW,
252
+ '/api/mobile/v1/git/forge/state': V.FILES_READ,
253
+ '/api/mobile/v1/git/forge/diff': V.FILES_READ,
254
+ '/api/mobile/v1/git/forge/checks': V.FILES_READ,
255
+ '/api/mobile/v1/git/forge/commits': V.FILES_READ,
256
+ '/api/mobile/v1/git/forge/review': V.FILES_READ,
257
+ '/api/mobile/v1/git/forge/reviewers': V.FILES_READ,
258
+ '/api/mobile/v1/git/forge/viewed': { GET: V.FILES_READ, POST: V.FILES_WRITE },
259
+ '/api/mobile/v1/git/forge/track': V.FILES_WRITE,
260
+ '/api/mobile/v1/git/forge/dismiss': V.FILES_WRITE,
261
+ '/api/mobile/v1/git/forge/review-write': V.FILES_WRITE,
262
+ '/api/mobile/v1/git/forge/submit-review': V.FILES_WRITE,
263
+ '/api/mobile/v1/git/forge/rerun-checks': V.FILES_WRITE,
264
+ '/api/mobile/v1/git/forge/request-reviews': V.FILES_WRITE,
265
+ '/api/mobile/v1/git/forge/update-branch': V.FILES_WRITE,
266
+ '/api/mobile/v1/git/forge/ready': V.FILES_WRITE,
267
+ '/api/mobile/v1/git/forge/merge': V.FILES_WRITE,
268
+ // 官方工作树:状态/清理读;请求与恢复动会话工作目录,归 dispatch(宿主再按 Session sandbox 复核)。
269
+ '/api/mobile/v1/git/worktree/state': V.FILES_READ,
270
+ '/api/mobile/v1/git/worktree/cleanup': V.FILES_READ,
248
271
  '/api/mobile/v1/session/file': V.FILES_READ,
249
272
  '/api/mobile/v1/session/attachment': V.FILES_READ,
250
273
  '/api/mobile/v1/session/local-image': V.FILES_READ,
@@ -278,6 +301,13 @@ const MAP = Object.freeze({
278
301
  '/api/mobile/v1/schedule/run': V.DISPATCH,
279
302
  '/api/mobile/v1/jobs/cancel': V.DISPATCH,
280
303
  '/api/mobile/v1/jobs/start': V.DISPATCH, // 恒 501,仍登记以保分类完整
304
+ // 官方工作树的请求 / 取消 / 停止 / 重试 / 恢复 / 在项目目录继续:动会话工作目录与生命周期。
305
+ '/api/mobile/v1/git/worktree/request': V.DISPATCH,
306
+ '/api/mobile/v1/git/worktree/cancel': V.DISPATCH,
307
+ '/api/mobile/v1/git/worktree/stop': V.DISPATCH,
308
+ '/api/mobile/v1/git/worktree/retry': V.DISPATCH,
309
+ '/api/mobile/v1/git/worktree/restore': V.DISPATCH,
310
+ '/api/mobile/v1/git/worktree/continue': V.DISPATCH,
281
311
 
282
312
  // ── approve:答审批 / 答提问 ───────────────────────────────────
283
313
  '/api/mobile/v1/approval/respond': V.APPROVE,
@@ -346,6 +376,8 @@ const MAP = Object.freeze({
346
376
  '/api/mobile/v1/relay/pairing-code': V.MANAGE,
347
377
  '/api/mobile/v1/relay/revoke-all': V.MANAGE,
348
378
  '/api/mobile/v1/relay/reconnect': V.MANAGE,
379
+ // 触发宿主向总控再报一次地址:不改配置,但会改总控侧那台设备的登记,与重连同档。
380
+ '/api/mobile/v1/relay/control-sync': V.MANAGE,
349
381
  '/api/mobile/v1/relay/restart-sidecar': V.MANAGE,
350
382
  '/api/mobile/v1/host-web': V.MANAGE,
351
383
 
@@ -1,3 +1,4 @@
1
+ // 对齐 Plugin Manager v2:安全更新、版本列表与失败恢复状态经移动端透传。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -22,11 +23,12 @@
22
23
  * 接口(都挂 `/api/mobile/v1/plugin/market`,走 token 守卫):
23
24
  * GET `/plugin/market` → { bundles }
24
25
  * GET `/plugin/market/registries` → { registry, fallbackRegistries, resolved }:安装时能选的 npm 源
26
+ * GET `/plugin/market/versions?name=&registry=` → 宿主版本列表与兼容性结果
25
27
  * POST `/plugin/market/inspect` { spec } → 读一下这个包是什么
26
28
  * GET `/plugin/market/detail?name=&language=` → { status, markdown, origin }:插件说明文档
27
29
  * POST `/plugin/market/remove` { name, requestId? } → 卸载(立即返回,结果看 progress)
28
30
  * POST `/plugin/market/install` { spec, registry?, requestId?, approvedBuilds? } → 开始装(立即返回)
29
- * POST `/plugin/market/update` { name, requestId? } → 卸载后重装成最新 / 官方给的目标版本
31
+ * POST `/plugin/market/update` { name, version, registry?, spec?, requestId? } → 宿主安全更新
30
32
  * POST `/plugin/market/cancel` { requestId } → 停一次正在跑的安装
31
33
  * GET `/plugin/market/progress?requestId=` → 那一次装完没有
32
34
  * POST `/plugin/market/enabled` { name, enabled } → 启用 / 停用(依赖留着)
@@ -61,7 +63,7 @@ const TASKS_MAX = 20;
61
63
  const BODY_MAX_BYTES = 8 * 1024;
62
64
 
63
65
  /** 安装结果里对手机有意义的几格(宿主的 `application` / `stage` / `error` 原样透出)。 */
64
- const APPLICATIONS = new Set(['cancelled', 'failed', 'applied', 'restart-required', 'overridden']);
66
+ const APPLICATIONS = new Set(['cancelled', 'failed', 'applied', 'restart-required', 'overridden', 'unknown']);
65
67
  const RESTART_REASONS = new Set(['no-hmr', 'package-moved', 'host-module', 'unmanaged-plugin', 'module-comparison']);
66
68
 
67
69
  /** 一次安装的进度账(只活在本进程里;宿主重启后手机按 unknown 处理,重新读列表)。 */
@@ -112,27 +114,40 @@ function errorDetailOf(error) {
112
114
  }
113
115
 
114
116
  function operationView(value) {
115
- if (!value || typeof value !== 'object') return null;
117
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
116
118
  const error = value.error && typeof value.error === 'object'
117
- ? {
118
- code: textOrNull(value.error.code, 64) || 'operation-error',
119
- message: errorDetailOf(value.error),
120
- }
121
- : null;
119
+ ? { code: textOrNull(value.error.code, 64) || 'operation-error', message: errorDetailOf(value.error),
120
+ ...(Array.isArray(value.error.incompatible) ? { incompatible: value.error.incompatible.slice(0, 20).map(incompatibleView).filter(Boolean) } : {}),
121
+ } : null;
122
122
  return {
123
123
  changed: value.changed === true,
124
- application: APPLICATIONS.has(value.application) ? value.application : 'failed',
124
+ application: APPLICATIONS.has(value.application) ? value.application : 'unknown',
125
125
  restartReason: RESTART_REASONS.has(value.restartReason) ? value.restartReason : null,
126
126
  stage: textOrNull(value.stage, 16),
127
127
  target: textOrNull(value.target, NAME_MAX_CHARS),
128
128
  version: textOrNull(value.version, 64),
129
129
  pendingBuilds: Array.isArray(value.pendingBuilds)
130
- ? value.pendingBuilds.filter((name) => typeof name === 'string').slice(0, 20)
131
- : [],
130
+ ? value.pendingBuilds.filter((name) => typeof name === 'string').slice(0, 20) : [],
131
+ ...(typeof value.enabled === 'boolean' ? { enabled: value.enabled } : {}),
132
+ ...(Array.isArray(value.warnings) ? { warnings: value.warnings.filter((item) => typeof item === 'string').slice(0, 20) } : {}),
133
+ ...(value.failedAt === 'registry' || value.failedAt === 'spec-host' ? { failedAt: value.failedAt } : {}),
132
134
  error,
133
135
  };
134
136
  }
135
137
 
138
+ function incompatibleView(value) {
139
+ if (!value || typeof value !== 'object') return null;
140
+ const name = textOrNull(value.name, NAME_MAX_CHARS);
141
+ const version = textOrNull(value.version, 64);
142
+ const runtimeVersion = textOrNull(value.runtimeVersion, 64);
143
+ if (!name || !version || !runtimeVersion) return null;
144
+ const requirements = {};
145
+ for (const [key, requirement] of Object.entries(value.requirements || {}).slice(0, 30)) {
146
+ if (typeof requirement === 'string') requirements[key] = requirement.slice(0, 300);
147
+ }
148
+ return { name, version, runtimeVersion, requirements };
149
+ }
150
+
136
151
  /** 显示名:宿主给的 meta 是「一句话或多语言表」,两种都原样转给 App 由它按语言挑。 */
137
152
  function displayField(value) {
138
153
  if (typeof value === 'string') return value;
@@ -171,6 +186,8 @@ function normalizeBundle(row) {
171
186
  official: row.official === true,
172
187
  optional: row.optional === true,
173
188
  removable: row.removable === true,
189
+ update: row.update === 'registry' || row.update === 'git' ? row.update : row.updatable === true ? 'registry' : null,
190
+ safeUpdate: name !== SELF_NAME && (row.update === 'registry' || row.update === 'git' || row.updatable === true),
174
191
  availability: textOrNull(row.availability, 16),
175
192
  installTarget: installTarget && installTarget.spec ? installTarget : null,
176
193
  /** 承载 App 连接的自己:停用一律拒绝、卸载没有入口,只留更新(见文件头)。 */
@@ -251,11 +268,6 @@ function normalizeRegistry(value) {
251
268
  return { value: text };
252
269
  }
253
270
 
254
- /**
255
- * 升级这一步的目标:官方按需插件由宿主给出**确切**的 installTarget(版本钉死在运行中的
256
- * DSH 上);第三方插件回到注册表最新的同名包。`file:` / `link:` / git 地址这类来源没有
257
- * 「最新版」可言,如实拒绝,让用户回电脑上换来源。
258
- */
259
271
  /**
260
272
  * 从一条依赖声明里取回 npm 包名:`name@^1.2.3` / `@scope/name@~2` / 别名都收,纯版本范围
261
273
  * (`^1.2.0` / `latest` / `*`)回落到包自己的名字。
@@ -268,20 +280,18 @@ function registryNameOf(source, fallback) {
268
280
  return at > 0 ? value.slice(0, at) : value;
269
281
  }
270
282
 
271
- function updateTargetOf(bundle) {
283
+ function updateTargetOf(bundle, version, options = {}) {
272
284
  if (!bundle) return { problem: '这台宿主上没有这个插件' };
273
- // 自己那条更新路不在这里:`/plugin/update/*` 有装前备份、装后自检与回滚,而通用那条
274
- // 是先卸载再装 —— 一旦装坏,手机连发一句话的机会都没有。
275
285
  if (bundle.name === SELF_NAME) return { problem: '这个插件要在「版本与更新」那一块更新(那条会自检、失败会自己退回)' };
276
- if (bundle.installTarget && bundle.installTarget.spec) return { spec: bundle.installTarget.spec };
277
- const source = bundle.source || '';
278
- if (!source) return { problem: '这个插件的来源不是一个可以从 npm 升级的名字;要换版本请在电脑上重装' };
279
- if (/^(?:file|link|workspace|git|github|gitlab|bitbucket|https?):/i.test(source) || /^\.{0,2}\//.test(source)) {
280
- return { problem: '这个插件是从本地目录或压缩包/仓库装的,没有「最新版」可升;要换版本请在电脑上重装' };
286
+ if (bundle.update === 'git') {
287
+ const spec = normalizeSpec(options.spec);
288
+ if (!spec.value) return { problem: 'Git 插件更新必须提供固定提交 spec' };
289
+ return { spec: spec.value, registry: null };
281
290
  }
282
- // 依赖声明里的 npm spec:宿主的 `source` 可能是「name@^1.2.3」这种整条 spec,也可能只是
283
- // 版本范围 / 标签(`^1.2.0`、`latest`)—— 后者按包本身的 name 走。
284
- return { spec: registryNameOf(source, bundle.name) };
291
+ if (bundle.update !== 'registry' && bundle.updatable !== true) return { problem: '这个插件没有宿主提供的安全更新能力' };
292
+ const targetVersion = textOrNull(version, 64);
293
+ if (!targetVersion) return { problem: '更新必须指定目标版本' };
294
+ return { version: targetVersion, registry: normalizeRegistry(options.registry).value };
285
295
  }
286
296
 
287
297
  /**
@@ -390,39 +400,72 @@ async function handlePluginMarketInstall(ctx, req, res) {
390
400
  sendJson(res, 202, { ok: true, requestId });
391
401
  }
392
402
 
393
- /**
394
- * POST /api/mobile/v1/plugin/market/update { name, requestId? }
395
- * 升级 = **卸载再装**(DSH 自己的规矩:第三方插件没有原地换代,官方按需插件则由宿主
396
- * 给出确切目标版本)。失败时插件会停在「已卸载」,界面必须把这一点写在确认框里。
397
- */
403
+ /** GET /plugin/market/versions?name=&registry=:只问宿主,不自行查询注册表。 */
404
+ async function handlePluginMarketVersions(ctx, req, res) {
405
+ const params = new URL(req.url || '/', 'http://x').searchParams;
406
+ const name = normalizeName(params.get('name'));
407
+ if (!name.value) return badRequest(res, name.problem);
408
+ const registry = normalizeRegistry(params.get('registry'));
409
+ if (registry.problem) return badRequest(res, registry.problem);
410
+ const result = await call(ctx, 'listVersions', { name: name.value, ...(registry.value ? { options: { registry: registry.value } } : {}) });
411
+ if (result.error) return sendJson(res, statusOf(result.error), { ok: false, error: result.error });
412
+ const value = result.value && typeof result.value === 'object' ? result.value : {};
413
+ const attempts = (Array.isArray(value.attempts) ? value.attempts : []).slice(0, 20).map((item) => ({
414
+ registry: textOrNull(item?.registry, REGISTRY_MAX_CHARS),
415
+ ...(textOrNull(item?.problem, 32) ? { problem: textOrNull(item.problem, 32) } : {}),
416
+ ...(typeof item?.reason === 'string' ? { reason: item.reason.slice(0, 4000) } : {}),
417
+ }));
418
+ if (value.status !== 'listed') return sendJson(res, 200, { ok: true, name: name.value, status: 'refused',
419
+ problem: textOrNull(value.problem, 32) || 'unknown', reason: typeof value.reason === 'string' ? value.reason : '', attempts });
420
+ const versions = (Array.isArray(value.versions) ? value.versions : []).slice(0, 100).filter((item) => textOrNull(item?.version, 64)).map((item) => ({
421
+ version: textOrNull(item.version, 64), tags: Array.isArray(item.tags) ? item.tags.filter((tag) => typeof tag === 'string').slice(0, 20) : [],
422
+ prerelease: item.prerelease === true, bundle: item.bundle === true,
423
+ ...(textOrNull(item.publishedAt, 64) ? { publishedAt: textOrNull(item.publishedAt, 64) } : {}),
424
+ ...(typeof item.deprecated === 'string' ? { deprecated: item.deprecated.slice(0, 4000) } : {}),
425
+ ...(incompatibleView(item.incompatible) ? { incompatible: incompatibleView(item.incompatible) } : {}),
426
+ }));
427
+ sendJson(res, 200, { ok: true, name: name.value, status: 'listed', installed: textOrNull(value.installed, 64),
428
+ registry: textOrNull(value.registry, REGISTRY_MAX_CHARS), attempts, versions,
429
+ omitted: Number.isSafeInteger(value.omitted) && value.omitted >= 0 ? value.omitted : 0 });
430
+ }
431
+
432
+ /** POST /plugin/market/update {name,version,registry?,spec?,requestId?}:替换和恢复均由宿主负责。 */
398
433
  async function handlePluginMarketUpdate(ctx, req, res) {
399
434
  const body = await readJsonBody(req, BODY_MAX_BYTES);
400
435
  const name = normalizeName(body && body.name);
401
436
  if (!name.value) return badRequest(res, name.problem);
437
+ const version = textOrNull(body && body.version, 64);
438
+ if (!version) return badRequest(res, '更新必须指定目标版本');
439
+ const registry = normalizeRegistry(body && body.registry);
440
+ if (registry.problem) return badRequest(res, registry.problem);
402
441
  const listed = await call(ctx, 'listBundles', {});
403
442
  if (listed.error) return sendJson(res, statusOf(listed.error), { ok: false, error: listed.error });
404
443
  const bundle = Array.isArray(listed.value) ? listed.value.map(normalizeBundle).find((item) => item && item.name === name.value) : null;
405
- const target = updateTargetOf(bundle);
444
+ const target = updateTargetOf(bundle, version, body || {});
406
445
  if (target.problem) return sendJson(res, 400, { ok: false, error: { code: 'no-update-target', message: target.problem } });
446
+ if (bundle.update !== 'git' && body.spec !== undefined) return badRequest(res, '注册表插件更新不接受 spec');
407
447
  const requestId = readRequestId(body && body.requestId, () => localRequestId('update'));
408
- beginTask(requestId, 'update', target.spec);
448
+ if (tasks.has(requestId)) return sendJson(res, 202, { ok: true, requestId, name: name.value, version });
449
+ const task = beginTask(requestId, 'update', name.value);
450
+ task.phase = 'checking';
451
+ let dispose;
452
+ if (typeof ctx?.on === 'function') dispose = ctx.on('plugin-manager/update-state', (progress) => {
453
+ if (progress?.requestId === requestId && ['checking', 'removing', 'installing', 'restoring'].includes(progress.step)) task.phase = progress.step;
454
+ }, { global: true });
409
455
  void (async () => {
410
- const removed = await call(ctx, 'removeBundle', { name: name.value });
411
- if (removed.error) {
412
- finishTask(requestId, { ok: false, error: removed.error, stage: 'remove' });
413
- return;
414
- }
415
- const removedView = operationView(removed.value);
416
- if (removedView && (removedView.application === 'failed' || removedView.application === 'cancelled')) {
417
- finishTask(requestId, { ok: true, operation: removedView, stage: 'remove' });
418
- return;
419
- }
420
- const installed = await call(ctx, 'installBundle', { spec: target.spec, options: { requestId, enabled: true } });
421
- finishTask(requestId, installed.error
422
- ? { ok: false, error: installed.error, stage: 'install' }
423
- : { ok: true, operation: operationView(installed.value), spec: target.spec, stage: 'install' });
456
+ try {
457
+ const options = { requestId, ...(registry.value ? { registry: registry.value } : {}), ...(target.spec ? { spec: target.spec } : {}) };
458
+ const updated = await call(ctx, 'updateBundle', { name: name.value, version, options });
459
+ if (updated.error) return finishTask(requestId, { ok: false, error: updated.error, stage: task.phase, unknown: updated.error.code !== UNAVAILABLE.code });
460
+ const value = updated.value && typeof updated.value === 'object' ? updated.value : {};
461
+ const operation = operationView(value.result);
462
+ const restore = operationView(value.restore);
463
+ finishTask(requestId, { ok: true, operation: operation || { application: 'unknown' }, stage: textOrNull(value.step, 16),
464
+ update: { from: textOrNull(value.from, 64), to: textOrNull(value.to, 64), step: textOrNull(value.step, 16), ...(restore ? { restore } : {}) } });
465
+ } catch (error) { finishTask(requestId, { ok: false, unknown: true, error: normalizeCallError(error) }); }
466
+ finally { if (typeof dispose === 'function') dispose(); }
424
467
  })();
425
- sendJson(res, 202, { ok: true, requestId, spec: target.spec });
468
+ sendJson(res, 202, { ok: true, requestId, name: name.value, version });
426
469
  }
427
470
 
428
471
  /**
@@ -435,7 +478,7 @@ async function handlePluginMarketProgress(_ctx, req, res) {
435
478
  if (!requestId) return badRequest(res, '需要 requestId');
436
479
  const task = tasks.get(requestId);
437
480
  if (!task) return sendJson(res, 200, { ok: true, state: 'unknown' });
438
- if (task.state === 'running') return sendJson(res, 200, { ok: true, state: 'running', kind: task.kind });
481
+ if (task.state === 'running') return sendJson(res, 200, { ok: true, state: 'running', kind: task.kind, ...(task.phase ? { phase: task.phase } : {}) });
439
482
  sendJson(res, 200, { ok: true, state: 'done', kind: task.kind, result: task.result });
440
483
  }
441
484
 
@@ -558,6 +601,7 @@ async function handlePluginMarketRemove(ctx, req, res) {
558
601
  module.exports = {
559
602
  handlePluginMarket,
560
603
  handlePluginMarketRegistries,
604
+ handlePluginMarketVersions,
561
605
  handlePluginMarketDetail,
562
606
  handlePluginMarketRemove,
563
607
  handlePluginMarketInspect,
@@ -1,3 +1,4 @@
1
+ // 自更新保留专用通道,并向 App 交付重启、回滚与实际恢复版本状态。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -62,6 +63,10 @@ function lastApplyOf(value) {
62
63
  installedVersion: typeof value.installedVersion === 'string' ? value.installedVersion : null,
63
64
  swapped: value.swapped === true,
64
65
  retryable: value.retryable === true,
66
+ restartRequired: value.restartRequired === true,
67
+ refreshRequired: value.refreshRequired === true,
68
+ rolledBack: value.rolledBack === true,
69
+ runningAfterRollback: typeof value.runningAfterRollback === 'string' ? value.runningAfterRollback : null,
65
70
  failure,
66
71
  };
67
72
  }
@@ -1,5 +1,6 @@
1
1
  // 手机和面板共用固定端口配置,端口变更仍由监听生命周期处理。
2
2
  // 既有中转配置复用有界健康判据与出网诊断,保留本实例吊销回执收尾。
3
+ // 2026-11-21:「立即同步」只上报不等查询 —— 查询归手机,宿主没有比自己更新的上游可查。
3
4
  'use strict';
4
5
 
5
6
  /**
@@ -47,6 +48,12 @@ const PROBE_TIMEOUT_MS = 6000;
47
48
  /** 一次最多测几条:手机只会问它自己存着的那几条,8 条已经很宽。 */
48
49
  const PROBE_MAX_URLS = 8;
49
50
 
51
+ /** 「立即同步」等总控回执的窗口:一次握手 + 一发 ack,6 秒够;超时就把当下的结论如实回。 */
52
+ const CONTROL_SYNC_WAIT_MS = 6000;
53
+
54
+ /** 等回执时复核快照的间隔。 */
55
+ const CONTROL_SYNC_POLL_MS = 120;
56
+
50
57
  /** 离线故障台账只搬最近几条,且**不搬堆栈**:那是宿主内部路径,手机上没用。 */
51
58
  const FAULT_TAIL = 5;
52
59
 
@@ -205,6 +212,10 @@ function createRelayControlHandlers(deps) {
205
212
  activeGuard = () => null,
206
213
  probeUrls = null,
207
214
  verifyRelay = null,
215
+ /** 总控上报:快照取值器 / 催一发上报 / 此刻会报上去的明文清单(见 lib/relay/control.js)。 */
216
+ getControl = null,
217
+ syncControl = null,
218
+ controlAddresses = null,
208
219
  } = deps || {};
209
220
 
210
221
  /**
@@ -296,6 +307,33 @@ function createRelayControlHandlers(deps) {
296
307
  };
297
308
  }
298
309
 
310
+ /**
311
+ * 地址分栏校验:什么地址能进哪个栏。返回一句中文错误,空串表示没问题。
312
+ *
313
+ * - 优先的局域网地址必须在这台电脑当前检测到的局域网 / 公网候选里(空串 = 清掉,合法)。
314
+ * 候选拿不到时(端口没监听 / 局域网关)不硬拦,交给排序层按「不在清单里」自然忽略。
315
+ * - 直连地址不能填成某条中转:两者是不同通道,串栏正是「局域网栏出现中转地址」的根源。
316
+ */
317
+ function addressSlotProblem(patch) {
318
+ if (patch.preferredLanAddress) {
319
+ const view = addressView();
320
+ const candidates = [...(view.lan || []), ...(view.public || [])]
321
+ .map((item) => String((item && item.address) || '').trim()).filter(Boolean);
322
+ if (candidates.length && !candidates.includes(patch.preferredLanAddress)) {
323
+ return '优先的局域网地址不在这台电脑当前检测到的地址里';
324
+ }
325
+ }
326
+ if (patch.manualLanUrl) {
327
+ const want = core.normalizeRelayUrl(patch.manualLanUrl);
328
+ const relays = [state.relayUrl, state.publicRelayAddress, ...(Array.isArray(state.relayUrls) ? state.relayUrls : [])]
329
+ .map((url) => (typeof url === 'string' ? core.normalizeRelayUrl(url) : '')).filter(Boolean);
330
+ if (want && relays.includes(want)) {
331
+ return '直连地址不能填成中转地址:这两条是不同通道,请把中转填到中转那一栏';
332
+ }
333
+ }
334
+ return '';
335
+ }
336
+
299
337
  /** 故障台账摘要:只给最近几条的 kind / 时间 / 一句话,**不带堆栈**。 */
300
338
  function faultsView() {
301
339
  const guard = typeof activeGuard === 'function' ? activeGuard() : null;
@@ -375,6 +413,13 @@ function createRelayControlHandlers(deps) {
375
413
  if (!parsed.ok) {
376
414
  return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: parsed.message } });
377
415
  }
416
+ // 「什么地址能进哪个栏」在宿主这一侧也核一遍:面板前端会核,但 APP 也可以直接推上来,
417
+ // 只靠前端等于没核。两类错误都当场拒:优先的局域网地址不在当前检测到的候选里;直连地址
418
+ // 填成了某条中转(两条是不同通道,串栏正是这个 bug 的根源)。
419
+ const slotProblem = addressSlotProblem(parsed.patch);
420
+ if (slotProblem) {
421
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: slotProblem } });
422
+ }
378
423
  const stage = body.stage === undefined ? null : body.stage;
379
424
  if (stage !== null && !STAGES.includes(stage)) {
380
425
  return sendJson(res, 400, {
@@ -564,6 +609,46 @@ function createRelayControlHandlers(deps) {
564
609
  afterResponse(() => syncSidecar().catch(() => undefined));
565
610
  }
566
611
 
612
+ /**
613
+ * `POST /api/mobile/v1/relay/control-sync` —— 立刻向总控报一次地址,并等它的回执。
614
+ *
615
+ * 手机网络页那颗「立即同步」的**上报那一半**;查询那一半在手机自己身上(连总控 `/ws/app`
616
+ * 拉一份密文、用本机 HK 解开)。这里不做查询是有意为之:总控对这台设备只存它自己发上去的
617
+ * 那份密文,没有比它更新的东西可查 —— 要分辨的只是「总控那份旧不旧」,那只能由手机比。
618
+ *
619
+ * 回执带三样:`control`(连没连上、总控认没认这发)、`addresses`(这台**此刻会报上去的**
620
+ * 明文清单,给手机与总控那份逐条比)、`at`(采样时刻)。那份地址不高出既有能力面:
621
+ * 手机本来就能用同一把 HK 从总控解开它。
622
+ *
623
+ * 只等有界的一小段(`CONTROL_SYNC_WAIT_MS`):没开上报 / 连不上就当场给结论,不要让人
624
+ * 对着一个转圈等六秒。`sync()` 内部按地址签名判变化,连着点不会多发 —— 没有变化时它
625
+ * 什么都不发,这里如实回「已是最新」。
626
+ */
627
+ async function handleControlSync(_ctx, _req, res) {
628
+ if (typeof syncControl !== 'function' || typeof getControl !== 'function') return unavailable(res);
629
+ // 没开远端或用户关了自动上报:连都不会连,催也催不动,等也等不出回执,当场给结论。
630
+ const reporting = Boolean(state && state.enabled && state.controlReportEnabled !== false);
631
+ if (reporting) {
632
+ try { syncControl(); } catch { /* 拨号失败会在下面的快照里如实反映 */ }
633
+ }
634
+ let snapshot = getControl() || {};
635
+ const deadline = Date.now() + CONTROL_SYNC_WAIT_MS;
636
+ while (reporting && !snapshot.published && Date.now() < deadline) {
637
+ await new Promise((resolve) => setTimeout(resolve, CONTROL_SYNC_POLL_MS));
638
+ snapshot = getControl() || {};
639
+ }
640
+ sendJson(res, 200, {
641
+ ok: true,
642
+ control: {
643
+ url: typeof snapshot.url === 'string' ? snapshot.url : '',
644
+ connected: snapshot.connected === true,
645
+ published: snapshot.published === true,
646
+ },
647
+ addresses: typeof controlAddresses === 'function' ? controlAddresses() : [],
648
+ at: Date.now(),
649
+ });
650
+ }
651
+
567
652
  /**
568
653
  * `POST /api/mobile/v1/relay/restart-sidecar` —— 重启后台服务(worker + facade)。
569
654
  *
@@ -715,6 +800,7 @@ function createRelayControlHandlers(deps) {
715
800
  handleRelayRegenerate,
716
801
  handleRelayRevokeAll,
717
802
  handleRelayReconnect,
803
+ handleControlSync,
718
804
  handleRelayRestartSidecar,
719
805
  handleRelayCheckPort,
720
806
  handleRelayProbe,
@@ -729,6 +815,7 @@ module.exports = {
729
815
  AFTER_RESPONSE_MS,
730
816
  CONFIG_BODY_MAX,
731
817
  PROBE_MAX_URLS,
818
+ CONTROL_SYNC_WAIT_MS,
732
819
  FAULT_TAIL,
733
820
  NAME_MAX_CHARS,
734
821
  STAGES,
@@ -1,3 +1,4 @@
1
+ // Schedule v2 写入沿用宿主 timing/target/CAS,读回统一完整目录字段与冲突结果。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -184,43 +185,13 @@ function normalizeTarget(value) {
184
185
  return null;
185
186
  }
186
187
 
187
- /** 宿主的 `status` → 手机认的 `state`(与 schedule.js 同一套:paused / ended 都算 inactive)。 */
188
- function stateOf(status) {
189
- return status === 'inactive' || status === 'paused' || status === 'ended' ? 'inactive' : 'active';
190
- }
191
-
192
188
  /**
193
189
  * 把宿主回的一条任务压成手机能画的形状。
194
190
  *
195
- * 正常走 `schedule.js` 的 `normalizeScheduleEntry`(字段收敛只有一份),再把编辑要用的
196
- * `updatedAt` 补上;极少数没有确定会话的 `new` 目标任务会被那一份判成 null(它要求
197
- * sessionId 非空),这里退化成最小形状,别让新建 / 编辑的返回凭空变成 500。
191
+ * 所有读取与写入结果共用 schedule.js 的归一化;无固定会话的任务也保留完整目标和规则。
198
192
  */
199
193
  function mobileEntry(raw, fallbackSessionId) {
200
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
201
- const base = normalizeScheduleEntry(raw, fallbackSessionId, undefined);
202
- if (base) {
203
- const updatedAt = optionalText(raw.updatedAt, SCHEDULE_TIME_MAX);
204
- if (updatedAt !== undefined) base.updatedAt = updatedAt;
205
- return base;
206
- }
207
-
208
- const id = requiredText(raw.id, SCHEDULE_ID_MAX);
209
- const title = requiredText(raw.title, SCHEDULE_TITLE_MAX);
210
- if (!id || !title || typeof raw.kind !== 'string' || !SCHEDULE_KINDS.has(raw.kind)) return null;
211
- const entry = {
212
- id,
213
- sessionId: requiredText(fallbackSessionId, SCHEDULE_ID_MAX),
214
- kind: raw.kind,
215
- title,
216
- prompt: promptText(raw.prompt),
217
- state: stateOf(raw.status),
218
- };
219
- const scheduledAt = optionalText(raw.scheduledAt, SCHEDULE_TIME_MAX);
220
- if (scheduledAt !== undefined) entry.scheduledAt = scheduledAt;
221
- const updatedAt = optionalText(raw.updatedAt, SCHEDULE_TIME_MAX);
222
- if (updatedAt !== undefined) entry.updatedAt = updatedAt;
223
- return entry;
194
+ return normalizeScheduleEntry(raw, fallbackSessionId, undefined);
224
195
  }
225
196
 
226
197
  /** 控制类响应额外带上宿主的原始 status:App 要区分「暂停」与「已结束」时用得着。 */
@@ -233,9 +204,7 @@ function withStatus(entry, raw) {
233
204
  function expectedFrom(body) {
234
205
  if (!body || body.expectedUpdatedAt === undefined) return undefined;
235
206
  if (body.expectedUpdatedAt === null) return null;
236
- if (typeof body.expectedUpdatedAt !== 'string') return undefined;
237
- const text = body.expectedUpdatedAt.trim();
238
- return text ? text : undefined;
207
+ return typeof body.expectedUpdatedAt === 'string' && body.expectedUpdatedAt.trim() ? body.expectedUpdatedAt.trim() : false;
239
208
  }
240
209
 
241
210
  /** 宿主服务:同进程直查,拿不到就是老宿主(或极简 profile 没装)。 */
@@ -270,21 +239,22 @@ function sendFailure(res, error) {
270
239
  const code = error && typeof error.code === 'string' && error.code.trim()
271
240
  ? error.code.trim()
272
241
  : 'schedule_failed';
273
- sendJson(res, 502, { ok: false, error: { code, message: errorText(error) } });
242
+ sendJson(res, 502, { ok: false, error: { code, message: errorText(error),
243
+ ...(error?.details && typeof error.details === 'object' ? { details: error.details } : {}),
244
+ } });
274
245
  }
275
246
 
276
247
  /** 宿主结果里带 `code` 的三种可解释结局。 */
277
- function sendResultCode(res, code) {
278
- if (code === 'schedule_not_found') {
279
- return sendJson(res, 404, { ok: false, error: { code: 'schedule_not_found', message: '没有这条定时任务' } });
280
- }
281
- if (code === 'schedule_conflict') {
282
- return sendJson(res, 409, { ok: false, error: { code: 'schedule_conflict', message: '这条任务刚被改过,刷新后再试' } });
283
- }
284
- if (code === 'schedule_execution_pending') {
285
- return sendJson(res, 409, { ok: false, error: { code: 'schedule_execution_pending', message: '这条任务正在执行中' } });
286
- }
287
- return sendFailure(res, { code: 'schedule_failed', message: `宿主回了未知结果码:${code}` });
248
+ function sendResultCode(res, result) {
249
+ const source = typeof result === 'string' ? { code: result } : result;
250
+ const code = source.code;
251
+ const messages = { schedule_not_found: '没有这条定时任务', schedule_conflict: '这条任务刚被改过,刷新后再试', schedule_execution_pending: '这条任务正在执行中' };
252
+ const message = typeof source.message === 'string' && source.message ? source.message : messages[code];
253
+ if (message) return sendJson(res, code === 'schedule_not_found' ? 404 : 409, {
254
+ ok: false, ...(typeof source.id === 'string' ? { id: source.id } : {}), code,
255
+ error: { code, message, ...(source.details && typeof source.details === 'object' ? { details: source.details } : {}) },
256
+ });
257
+ return sendFailure(res, { code, message: `宿主回了未知结果码:${code}` });
288
258
  }
289
259
 
290
260
  /**
@@ -294,10 +264,11 @@ function sendResultCode(res, code) {
294
264
  function sendHostError(res, error) {
295
265
  const code = error && typeof error.code === 'string' ? error.code.trim() : '';
296
266
  if (code === 'schedule/input-invalid' || code === 'invalid_rule') {
297
- return badRequest(res, 'invalid_rule', errorText(error));
267
+ const inputCode = typeof error?.details?.code === 'string' ? error.details.code : 'invalid_rule';
268
+ return sendJson(res, 400, { ok: false, error: { code: inputCode, message: errorText(error),
269
+ ...(error?.details && typeof error.details === 'object' ? { details: error.details } : {}) } });
298
270
  }
299
- if (code === 'schedule_not_found') return sendResultCode(res, 'schedule_not_found');
300
- if (code === 'schedule_conflict') return sendResultCode(res, 'schedule_conflict');
271
+ if (['schedule_not_found', 'schedule_conflict', 'schedule_execution_pending'].includes(code)) return sendResultCode(res, error);
301
272
  return sendFailure(res, error);
302
273
  }
303
274
 
@@ -356,7 +327,7 @@ async function handleScheduleCreate(ctx, req, res) {
356
327
  return sendHostError(res, error);
357
328
  }
358
329
  if (!result || typeof result !== 'object') return sendFailure(res, new Error('宿主没有返回任务'));
359
- if (typeof result.code === 'string') return sendResultCode(res, result.code);
330
+ if (typeof result.code === 'string') return sendResultCode(res, result);
360
331
 
361
332
  const record = withStatus(mobileEntry(result, sessionId), result);
362
333
  if (!record) return sendFailure(res, new Error('宿主返回的任务形状不对'));
@@ -409,7 +380,7 @@ async function applyEdit(res, service, id, patch, expected, fallbackSessionId) {
409
380
  return sendHostError(res, error);
410
381
  }
411
382
  if (!result || typeof result !== 'object') return sendFailure(res, new Error('宿主没有返回任务'));
412
- if (typeof result.code === 'string') return sendResultCode(res, result.code);
383
+ if (typeof result.code === 'string') return sendResultCode(res, result);
413
384
 
414
385
  const record = withStatus(mobileEntry(result, fallbackSessionId), result);
415
386
  if (!record) return sendFailure(res, new Error('宿主返回的任务形状不对'));
@@ -431,7 +402,9 @@ async function handleScheduleEdit(ctx, req, res) {
431
402
  const service = scheduleService(ctx);
432
403
  if (!hasEdit(service)) return sendUnavailable(res);
433
404
 
434
- return applyEdit(res, service, id, patch, expectedFrom(body), '');
405
+ const expected = expectedFrom(body);
406
+ if (expected === false) return badRequest(res, 'invalid_patch', 'expectedUpdatedAt 必须是修订时刻或 null');
407
+ return applyEdit(res, service, id, patch, expected, '');
435
408
  }
436
409
 
437
410
  /** 暂停 / 恢复共用:patch 固定 active。 */
@@ -443,7 +416,9 @@ async function setActive(ctx, req, res, active) {
443
416
  const service = scheduleService(ctx);
444
417
  if (!hasEdit(service)) return sendUnavailable(res);
445
418
 
446
- return applyEdit(res, service, id, { active }, expectedFrom(body), '');
419
+ const expected = expectedFrom(body);
420
+ if (expected === false) return badRequest(res, 'invalid_patch', 'expectedUpdatedAt 必须是修订时刻或 null');
421
+ return applyEdit(res, service, id, { active }, expected, '');
447
422
  }
448
423
 
449
424
  /** POST /api/mobile/v1/schedule/pause —— body { id, expectedUpdatedAt? } */
@@ -480,7 +455,7 @@ async function handleScheduleRun(ctx, req, res) {
480
455
  if (result.code === 'schedule_execution_pending') {
481
456
  return sendJson(res, 200, { ok: true, id, ran: false, code: 'schedule_execution_pending' });
482
457
  }
483
- if (typeof result.code === 'string') return sendResultCode(res, result.code);
458
+ if (typeof result.code === 'string') return sendResultCode(res, result);
484
459
 
485
460
  const record = withStatus(mobileEntry(result, ''), result);
486
461
  if (!record) return sendFailure(res, new Error('宿主返回的任务形状不对'));