dsh-mobile-plugin 0.5.48 → 0.5.50

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.
@@ -113,7 +113,12 @@ function monitorItem(summary, state, fact) {
113
113
  * `{ error }` —— 两种都由调用方照 `/sessions` 的口径回,别在这里编一个空清单:空清单会被
114
114
  * 原生当成「所有会话都没了」,基线一清,下一轮就为所有正在跑的会话重新报一次完成。
115
115
  */
116
- async function buildMonitorState(ctx, deviceKey, extraItems = null) {
116
+ /**
117
+ * @param {string|null} scopeSessionId 只回这一条会话(对话页对账用);null = 整份视图(后台提醒用)。
118
+ *
119
+ * **收窄只发生在出 item 那一步**:完成态台账仍按整份清单推进 —— 见下面那句注释。
120
+ */
121
+ async function buildMonitorState(ctx, deviceKey, extraItems = null, scopeSessionId = null) {
117
122
  const { value, error } = unwrap(await callSessions(ctx, 'list', {}, 'mobile'));
118
123
  if (error) return { error };
119
124
  const rawSummaries = Array.isArray(value) ? value : (value && Array.isArray(value.items) ? value.items : null);
@@ -203,7 +208,15 @@ async function buildMonitorState(ctx, deviceKey, extraItems = null) {
203
208
  // 按 id 排序后再算指纹:宿主是按 updatedAt 排的,聊一句话顺序就换,指纹会跟着每轮都变,
204
209
  // 条件刷新等于白做。监控视图不关心顺序。
205
210
  items.sort((a, b) => (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0));
206
- return { items, revision: stableRevision(items) };
211
+ /**
212
+ * 收窄到一条会话(`?sessionId=`,对话页对账用)。
213
+ *
214
+ * **只影响回什么,不影响台账**:上面那些按整份清单跑的(完成态、未定结局的补确认、指纹)
215
+ * 一个字不动 —— `updateCompletionStates` 的「不在列表里就丢」是拿完整清单定的,收窄放在
216
+ * 它之后,免得一次单条请求把别条会话的状态清掉。
217
+ */
218
+ const scoped = scopeSessionId ? items.filter((item) => item.sessionId === scopeSessionId) : items;
219
+ return { items: scoped, revision: stableRevision(scoped) };
207
220
  }
208
221
 
209
222
  /** 一次挂起的上限。手机侧每次挂 20 秒,再长没有意义:断线重连比占着一条连接便宜。 */
@@ -241,10 +254,10 @@ function waitForChange(timeoutMs, res) {
241
254
  }
242
255
 
243
256
  /** 算一次监控视图,把「宿主出错 / 形状异常」也收成一个可下发的响应。 */
244
- async function buildMonitorView(ctx, deviceKey, extraItems = null) {
257
+ async function buildMonitorView(ctx, deviceKey, extraItems = null, scopeSessionId = null) {
245
258
  let built;
246
259
  try {
247
- built = await buildMonitorState(ctx, deviceKey, extraItems);
260
+ built = await buildMonitorState(ctx, deviceKey, extraItems, scopeSessionId);
248
261
  } catch (error) {
249
262
  return {
250
263
  status: 500,
@@ -272,16 +285,22 @@ async function buildMonitorView(ctx, deviceKey, extraItems = null) {
272
285
  *
273
286
  * 只挂一次:醒来之后不管变没变都如实回(变没变由 revision 说了算),由手机自己决定
274
287
  * 要不要再挂。这样这里没有循环、没有重试,断线也不会在宿主侧留下一个转不停的请求。
288
+ *
289
+ * `sessionId` 是可选的收窄:对话页「这张卡还在不在」的对账只关心自己那一条,带上它就只回
290
+ * 这一条(台账照旧按整份清单推进,见 buildMonitorState)。
275
291
  */
276
292
  async function handleMonitor(ctx, req, res, extraItems = null) {
277
293
  const deviceKey = canonicalDeviceKey(req);
278
294
  const url = new URL(req.url, 'http://x');
279
295
  const rev = (url.searchParams.get('rev') || '').trim();
280
296
  const waitSeconds = Number(url.searchParams.get('wait') || 0) || 0;
297
+ // 只回这一条会话(见 buildMonitorState 的同名参数):对话页对账只要自己那一格,
298
+ // 不必为了一格卡把整台电脑的会话状态搬一遍。
299
+ const scopeSessionId = (url.searchParams.get('sessionId') || '').trim() || null;
281
300
  // 没有 rev 就不挂:那不是「确认一下有没有变」,而是「给我一份完整状态」,立刻回。
282
301
  const waitMs = rev ? Math.max(0, Math.min(WAIT_MAX_MS, Math.round(waitSeconds * 1000))) : 0;
283
302
 
284
- const first = await buildMonitorView(ctx, deviceKey, extraItems);
303
+ const first = await buildMonitorView(ctx, deviceKey, extraItems, scopeSessionId);
285
304
  if (first.status !== 200) {
286
305
  return sendJson(res, first.status, first.body);
287
306
  }
@@ -298,7 +317,7 @@ async function handleMonitor(ctx, req, res, extraItems = null) {
298
317
  await waitForChange(waitMs, res);
299
318
  // 手机在这段时间里断了(切网 / 进程被杀):别为一个没人收的响应再算一遍。
300
319
  if (res.destroyed || res.writableEnded) return;
301
- const again = await buildMonitorView(ctx, deviceKey, extraItems);
320
+ const again = await buildMonitorView(ctx, deviceKey, extraItems, scopeSessionId);
302
321
  const body = again.status === 200 ? (unchangedListBody(again.body, rev) || again.body) : again.body;
303
322
  // 头已经出去了,不能再走 sendJson(它会再写一次头):这里只补正文。
304
323
  try { res.end(JSON.stringify(body)); } catch { /* 连接已断开 */ }
@@ -0,0 +1,183 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 移动端「这台电脑上还连着哪些手机」:只读清单 + 单台吊销,外加凭据时效投影。
5
+ *
6
+ * 真源是宿主的每设备凭据库(`dsh-mobile-credentials` 的 `listDevices` / `revokeDevice`)。
7
+ * 这里只做两件事:把一行设备压成手机要画的东西,以及按设备标识吊销一台。控制面那条
8
+ * `/api/relay/devices` 只认本机,手机打不到;移动端此前也只能看到自己这一台,所以要
9
+ * 单开这两条。清单里的 `hash` / `hostToken` / `deviceKey` 一律不回,跟控制面同一口径。
10
+ *
11
+ * 吊销按 `deviceId` 整台做(该名下所有活记录一起收),不是只收出示的那一枚 —— 同一台
12
+ * 手机重配、升级会留下好几条活凭据,只吊一条等于旧的那枚还能用。被吊销的设备下一次请求
13
+ * 由守卫回 `device-revoked`(「请重新扫码」),这条不用在这里再拼文案。
14
+ *
15
+ * 时效投影(第 54 条):凭据库记录里只有 `createdAt` / `expiresAt`,续期是「剩余不足一半
16
+ * 就把 `expiresAt` 后推一个 TTL」,所以「最近一次续期」= `expiresAt - TTL`(早于签发时刻
17
+ * 就是从未续期,不回这一格)。这几格只从记录算,不改凭据库本身。
18
+ */
19
+
20
+ const { sendJson, readJsonBody } = require('../shared/http-util.js');
21
+
22
+ const DEVICE_ID_MAX = 128; // 与凭据库签发时同一个截断长度
23
+ const FALLBACK_TTL_MS = 365 * 24 * 3600 * 1000; // 凭据库默认有效期(`DEFAULT_TTL_MS` 的兜底)
24
+ const RENEW_EPSILON_MS = 60 * 1000; // 续期时刻与签发时刻差不到一分钟,按「从未续期」处理
25
+
26
+ /** 凭据库的默认 TTL;拿不到就用本文件的兜底,保证时效投影总能算出一个结果。 */
27
+ function ttlOf(store) {
28
+ const ttl = store && Number(store.DEFAULT_TTL_MS);
29
+ return Number.isFinite(ttl) && ttl > 0 ? ttl : FALLBACK_TTL_MS;
30
+ }
31
+
32
+ /**
33
+ * 一条凭据(或一台设备聚合后)的时效投影。
34
+ *
35
+ * @param {{ createdAt?: number, boundAt?: number, expiresAt?: number }} record
36
+ * @param {object} store 凭据库(用来读默认 TTL)
37
+ * @returns {{ authorizedAt: number|null, renewedAt: number|null, expiresAt: number|null } | null}
38
+ */
39
+ function credentialTiming(record, store) {
40
+ if (!record || typeof record !== 'object') return null;
41
+ const authorizedAt = Number(record.createdAt ?? record.boundAt) || 0;
42
+ const expiresAt = Number(record.expiresAt) || 0;
43
+ if (!authorizedAt && !expiresAt) return null;
44
+ let renewedAt = 0;
45
+ if (expiresAt) {
46
+ const renewed = expiresAt - ttlOf(store);
47
+ if (authorizedAt && renewed > authorizedAt + RENEW_EPSILON_MS) renewedAt = renewed;
48
+ }
49
+ return {
50
+ authorizedAt: authorizedAt || null,
51
+ renewedAt: renewedAt || null,
52
+ expiresAt: expiresAt || null,
53
+ };
54
+ }
55
+
56
+ /**
57
+ * 本机这枚凭据的时效投影(`GET /api/mobile/v1/status` 的 `credential` 那一格用它)。
58
+ *
59
+ * 传请求对象:从它出示的那枚凭据查记录。查不到记录(升级前的无状态 HMAC 通行证)就回
60
+ * null —— 那种凭据本来就没有记录,也就没有签发 / 到期时刻可报。
61
+ */
62
+ function credentialTimingFor(store, instanceId, req) {
63
+ if (!store || typeof store.lookup !== 'function' || !req) return null;
64
+ const headers = req.headers || {};
65
+ const header = headers['x-dsh-device-credential'];
66
+ const presented = typeof header === 'string' && header.trim()
67
+ ? header.trim()
68
+ : ((/^Bearer\s+([^\s]+)$/.exec(String(headers.authorization || '')) || [])[1] || null);
69
+ if (!presented) return null;
70
+ const record = store.lookup(presented, String(instanceId || ''));
71
+ return record ? credentialTiming(record, store) : null;
72
+ }
73
+
74
+ /** 设备标识清洗:只留短串,畸形的一律拒绝,别拿垃圾去碰凭据库。 */
75
+ function normalizeDeviceId(value) {
76
+ if (typeof value !== 'string') return null;
77
+ const deviceId = value.trim();
78
+ if (!deviceId || deviceId.length > DEVICE_ID_MAX) return null;
79
+ return deviceId;
80
+ }
81
+
82
+ /** 一台设备的一行(`listDevices` 的活动行 → 手机要的形状)。 */
83
+ function toPairedDevice(row, store, latest) {
84
+ return {
85
+ deviceId: String(row.deviceId || ''),
86
+ name: typeof row.name === 'string' ? row.name : '',
87
+ model: typeof row.model === 'string' ? row.model : '',
88
+ platform: typeof row.platform === 'string' ? row.platform : '',
89
+ osVersion: typeof row.osVersion === 'string' ? row.osVersion : '',
90
+ appVersion: typeof row.appVersion === 'string' ? row.appVersion : '',
91
+ boundAt: Number(row.boundAt) || 0,
92
+ lastSeenAt: Number(row.lastSeenAt) || 0,
93
+ bindings: Number(row.bindings) || 0,
94
+ legacy: row.legacy === true,
95
+ encrypted: row.encrypted === true,
96
+ // 时效取**这一台最新签发的那条**:聚合行只给「最早的绑定时刻 + 最晚的到期时刻」,
97
+ // 拿它俩相减会把「重配过一次」说成「续期过」。续期只发生在单条记录上。
98
+ credential: credentialTiming(latest || { createdAt: row.boundAt, expiresAt: row.expiresAt }, store),
99
+ };
100
+ }
101
+
102
+ /**
103
+ * 每台设备最新签发的那条活记录(按 `deviceId`)。
104
+ *
105
+ * `listActive` 一条记录一行,这里按签发时刻取最大 —— 时效要算在它上面,见 `toPairedDevice`。
106
+ * 老凭据库没有 `listActive` 就回空表,调用方退回聚合行那两格。
107
+ */
108
+ function latestRecords(store, instanceId) {
109
+ const out = new Map();
110
+ if (typeof store.listActive !== 'function') return out;
111
+ for (const record of store.listActive(instanceId) || []) {
112
+ const key = String(record.deviceId || '');
113
+ if (!key) continue;
114
+ const previous = out.get(key);
115
+ if (!previous || (Number(record.createdAt) || 0) > (Number(previous.createdAt) || 0)) out.set(key, record);
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /**
121
+ * `GET /api/mobile/v1/paired-devices` —— 这台电脑上仍有效的设备清单(只读)。
122
+ *
123
+ * `serverNow` 给手机算「几分钟前」用(手机与宿主的时钟可能差得多,但都是同一台机器的基准)。
124
+ */
125
+ async function handlePairedDevices(_req, res, deps) {
126
+ const instanceId = String((deps && deps.instanceId) || '');
127
+ const store = deps && deps.store;
128
+ if (!store || typeof store.listDevices !== 'function') {
129
+ return sendJson(res, 503, { ok: false, error: { code: 'unavailable', message: '凭据库不可用' } });
130
+ }
131
+ try {
132
+ const now = Date.now();
133
+ const latest = latestRecords(store, instanceId);
134
+ const devices = (store.listDevices(instanceId) || [])
135
+ .map((row) => toPairedDevice(row, store, latest.get(String(row.deviceId || ''))));
136
+ return sendJson(res, 200, { ok: true, serverNow: now, devices });
137
+ } catch (error) {
138
+ return sendJson(res, 500, { ok: false, error: { code: 'internal', message: String(error && error.message ? error.message : error) } });
139
+ }
140
+ }
141
+
142
+ /**
143
+ * `POST /api/mobile/v1/paired-devices/revoke` —— body `{ deviceId }`,吊销一台设备。
144
+ *
145
+ * 尽力而为地主动收掉这台设备已开着的流(`dropDeviceStreams`,装配层可选注入):token 换了
146
+ * 只保证「下一次请求」被拒,一条已经开着的 SSE 不会自己停。
147
+ */
148
+ async function handlePairedDevicesRevoke(req, res, deps) {
149
+ const instanceId = String((deps && deps.instanceId) || '');
150
+ const store = deps && deps.store;
151
+ if (!store || typeof store.revokeDevice !== 'function') {
152
+ return sendJson(res, 503, { ok: false, error: { code: 'unavailable', message: '凭据库不可用' } });
153
+ }
154
+ // 协议 v2 的 body 由守卫解好后放在 req.body;明文老会话的 body 还挂在流上,现读。
155
+ const body = req.body && typeof req.body === 'object'
156
+ ? req.body
157
+ : ((await readJsonBody(req, 16 * 1024)) || {});
158
+ const deviceId = normalizeDeviceId(body.deviceId);
159
+ if (!deviceId) {
160
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要 { deviceId }' } });
161
+ }
162
+ let revoked = 0;
163
+ try {
164
+ revoked = store.revokeDevice(instanceId, deviceId);
165
+ } catch (error) {
166
+ return sendJson(res, 500, { ok: false, error: { code: 'internal', message: String(error && error.message ? error.message : error) } });
167
+ }
168
+ let closed = 0;
169
+ try {
170
+ closed = typeof deps.dropDeviceStreams === 'function' ? deps.dropDeviceStreams(deviceId) : 0;
171
+ } catch { /* 尽力:断流失败不影响吊销已经落地 */ }
172
+ return sendJson(res, 200, { ok: true, revoked, closed });
173
+ }
174
+
175
+ module.exports = {
176
+ handlePairedDevices,
177
+ handlePairedDevicesRevoke,
178
+ credentialTiming,
179
+ credentialTimingFor,
180
+ normalizeDeviceId,
181
+ toPairedDevice,
182
+ latestRecords,
183
+ };
@@ -125,7 +125,6 @@ const BASE = Object.freeze([
125
125
  '/api/mobile/v1/tunnel',
126
126
  '/api/mobile/v1/p2p/rendezvous',
127
127
  '/api/mobile/v1/push-token',
128
- '/api/mobile/v1/perf-trace',
129
128
  '/api/mobile/v1/notification-prefs',
130
129
  '/api/mobile/v1/device-credential/revoke',
131
130
  '/api/mobile/v1/device-credential/upgrade',
@@ -155,6 +154,8 @@ const MAP = Object.freeze({
155
154
  '/api/mobile/v1/session/archive': V.VIEW,
156
155
  '/api/mobile/v1/session/head': V.VIEW,
157
156
  '/api/mobile/v1/session/models': V.VIEW,
157
+ // 侧边提问入口:当前插件如实回 `side-question-unsupported`,不产生副作用,归 view。
158
+ '/api/mobile/v1/session/side-question': V.VIEW,
158
159
  '/api/mobile/v1/session/stats': V.VIEW,
159
160
  '/api/mobile/v1/session/search': V.VIEW,
160
161
  '/api/mobile/v1/session/stream': V.VIEW,
@@ -174,6 +175,8 @@ const MAP = Object.freeze({
174
175
  '/api/mobile/v1/file-references': V.VIEW,
175
176
  '/api/mobile/v1/session-references': V.VIEW,
176
177
  '/api/mobile/v1/deepseek-account': V.VIEW,
178
+ // 「这台电脑上还连着哪些手机」:只读清单,归 view。
179
+ '/api/mobile/v1/paired-devices': V.VIEW,
177
180
  '/api/mobile/v1/model-meta': V.VIEW,
178
181
  '/api/mobile/v1/model-meta/apply': V.CONFIG,
179
182
  '/api/mobile/v1/llm/providers': V.VIEW,
@@ -295,6 +298,11 @@ const MAP = Object.freeze({
295
298
  '/api/mobile/v1/file/delete': V.FILES_WRITE,
296
299
  '/api/mobile/v1/file/rename': V.FILES_WRITE,
297
300
  '/api/mobile/v1/directory/create': V.FILES_WRITE,
301
+ // 把这一轮回答落成文件:带正文写盘,落点与 file/create 同一份允许区,归 files.write。
302
+ '/api/mobile/v1/session/write-body': V.FILES_WRITE,
303
+ // 操作记录回传:本质是往宿主磁盘写文件(`mobile-traces/`),与文件写入同档;以前误挂在
304
+ // BASE 上,等于任何已鉴权设备都能不限量写盘。
305
+ '/api/mobile/v1/perf-trace': V.FILES_WRITE,
298
306
  // 项目写入队列的暂停 / 恢复:只切插件自己的队列开关,**一个文件都不写**,所以 POST 也算
299
307
  // view(给 files.write 会把只读设备挡在一件它本来就做不了的事之外,没有收益)。
300
308
  '/api/mobile/v1/project/writes': { GET: V.VIEW, POST: V.VIEW },
@@ -327,6 +335,8 @@ const MAP = Object.freeze({
327
335
  '/api/mobile/v1/sync/inbox': V.TRANSFER,
328
336
 
329
337
  // ── manage:设备凭据本体 + 中继配置 + 网页登录令牌 ─────────────
338
+ // 吊销一台已配对手机:动的是凭据本体,与设备凭据同档(manage)。
339
+ '/api/mobile/v1/paired-devices/revoke': V.MANAGE,
330
340
  '/api/mobile/v1/relay/config/save': V.MANAGE,
331
341
  '/api/mobile/v1/relay/enabled': V.MANAGE,
332
342
  '/api/mobile/v1/relay/pairing-code': V.MANAGE,
@@ -1,10 +1,11 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * 交付声明补格:把 `deliverables/presented` 里每一份的 size / mtime 一起带上。
4
+ * 交付声明补格:把 `deliverables/presented` 里每一份的 size / mtime / duration 一起带上。
5
5
  *
6
- * 轮尾那张「交付文件卡」的第二行要写「1.2 MB · 今天 14:32」。电脑这边本来就知道文件在哪,
7
- * 所以在**投影交付声明时顺手量一下**,手机端一条额外请求都不用发。
6
+ * 轮尾那张「交付文件卡」的第二行要写「1.2 MB · 3:05 · 今天 14:32」。电脑这边本来就知道
7
+ * 文件在哪,所以在**投影交付声明时顺手量一下**,手机端一条额外请求都不用发。时长只对
8
+ * ISO BMFF 那一族音视频量(mp4 / mov / m4a),见下面「音视频时长」那一节。
8
9
  *
9
10
  * 三条硬约束,改的时候别破:
10
11
  *
@@ -28,7 +29,10 @@
28
29
  const {
29
30
  inspectPaths,
30
31
  ARTIFACT_STAT_CONCURRENCY,
32
+ mapLimit,
31
33
  } = require('./session-artifacts.js');
34
+ const fs = require('node:fs/promises');
35
+ const path = require('node:path');
32
36
  const {
33
37
  presentedFileStatsOf,
34
38
  rememberPresentedFileStats,
@@ -75,6 +79,149 @@ function statWithinBudget(ctx, sessionId, paths, budgetMs) {
75
79
  });
76
80
  }
77
81
 
82
+ // ── 音视频时长 ───────────────────────────────────────────────────────────────
83
+ //
84
+ // 卡片第二行要写「1.2 MB · 3:05 · 今天 14:32」。时长只能从文件头读:解 ISO BMFF 的
85
+ // `mvhd`(mp4 / mov / m4a 都是这一族)。**不引任何依赖**,也不整份读文件 —— 只读顶层盒子
86
+ // 头跳到 `moov`,再读它开头那几 KB 找 `mvhd`,与 size/mtime 同口径:量不到就不写那一截,
87
+ // 不报错、不拖慢消息。
88
+ //
89
+ // webm / mp3 不在这里做:它们各有另一套容器格式(EBML / MPEG 帧头),为两格字再写两个
90
+ // 解析器不划算 —— 那两档就当没量到(见 `turn-tail-cards` 的 `deliverableMeta`)。
91
+
92
+ /** 能按 ISO BMFF 读时长的扩展名(小写、不含点)。 */
93
+ const DURATION_EXTENSIONS = new Set(['mp4', 'm4v', 'mov', 'm4a']);
94
+
95
+ /** `moov` 开头读多少字节找 `mvhd`:它一定是第一个子盒子,4KB 足够。 */
96
+ const MOOV_HEAD_BYTES = 4096;
97
+
98
+ /** 一条 24 小时以上的「时长」只可能是解析错(错位的字节被读成了大整数)。 */
99
+ const DURATION_MAX_MS = 24 * 60 * 60 * 1000;
100
+
101
+ /** 文件路径 → 小写扩展名(没有就是空串)。 */
102
+ function extensionOf(target) {
103
+ const ext = path.extname(String(target || ''));
104
+ return ext.startsWith('.') ? ext.slice(1).toLowerCase() : '';
105
+ }
106
+
107
+ /** 从 `position` 读 `length` 字节;读不满就回短的那一截(文件尾)。 */
108
+ async function readAt(handle, position, length) {
109
+ const buffer = Buffer.alloc(length);
110
+ const { bytesRead } = await handle.read(buffer, 0, length, position);
111
+ return bytesRead === length ? buffer : buffer.subarray(0, bytesRead);
112
+ }
113
+
114
+ /**
115
+ * 一个 ISO BMFF 盒子的头:`{ size, header, type }`,认不出回 `null`。
116
+ *
117
+ * `size === 1` 是 64 位长度(头 16 字节),`size === 0` 表示「到文件尾」。
118
+ */
119
+ function boxOf(buffer, offset) {
120
+ if (offset + 8 > buffer.length) return null;
121
+ let size = buffer.readUInt32BE(offset);
122
+ const type = buffer.toString('latin1', offset + 4, offset + 8);
123
+ let header = 8;
124
+ if (size === 1) {
125
+ if (offset + 16 > buffer.length) return null;
126
+ size = buffer.readUInt32BE(offset + 8) * 2 ** 32 + buffer.readUInt32BE(offset + 12);
127
+ header = 16;
128
+ } else if (size === 0) {
129
+ size = buffer.length - offset;
130
+ }
131
+ if (!(size >= header)) return null;
132
+ return { size, header, type };
133
+ }
134
+
135
+ /** `mvhd` 正文 → 毫秒;版本、时间刻度、时长三样读不出合理值就回 0。 */
136
+ function durationOfMvhd(payload) {
137
+ if (payload.length < 20) return 0;
138
+ const version = payload[0];
139
+ let timescale;
140
+ let duration;
141
+ if (version === 1) {
142
+ if (payload.length < 32) return 0;
143
+ timescale = payload.readUInt32BE(20);
144
+ duration = Number(payload.readBigUInt64BE(24));
145
+ } else {
146
+ timescale = payload.readUInt32BE(12);
147
+ duration = payload.readUInt32BE(16);
148
+ }
149
+ if (!(timescale > 0) || !(duration > 0)) return 0;
150
+ const ms = Math.round((duration * 1000) / timescale);
151
+ return Number.isFinite(ms) && ms > 0 && ms <= DURATION_MAX_MS ? ms : 0;
152
+ }
153
+
154
+ /** `moov` 正文开头里找 `mvhd`;没有就回 0。 */
155
+ function durationOfMoov(payload) {
156
+ let offset = 0;
157
+ for (let guard = 0; guard < 16 && offset + 8 <= payload.length; guard += 1) {
158
+ const box = boxOf(payload, offset);
159
+ if (box === null) return 0;
160
+ if (box.type === 'mvhd') return durationOfMvhd(payload.subarray(offset + box.header));
161
+ offset += Math.max(box.size, box.header);
162
+ }
163
+ return 0;
164
+ }
165
+
166
+ /**
167
+ * 一份文件的时长(毫秒);量不到就回 0。
168
+ *
169
+ * 只走到 `moov` 为止:`mdat` 那种几十 MB 的盒子按头里的大小直接跳过,不进内存。
170
+ */
171
+ async function mediaDurationMsOf(target) {
172
+ const handle = await fs.open(target, 'r');
173
+ try {
174
+ const info = await handle.stat();
175
+ const fileSize = Number(info.size) || 0;
176
+ let offset = 0;
177
+ for (let guard = 0; guard < 64 && offset + 8 <= fileSize; guard += 1) {
178
+ const head = await readAt(handle, offset, Math.min(16, fileSize - offset));
179
+ const box = boxOf(head, 0);
180
+ if (box === null) return 0;
181
+ if (box.type === 'moov') {
182
+ const length = Math.min(box.size, MOOV_HEAD_BYTES);
183
+ const payload = await readAt(handle, offset + box.header, length - box.header);
184
+ return durationOfMoov(payload);
185
+ }
186
+ offset += box.size;
187
+ }
188
+ return 0;
189
+ } finally {
190
+ await handle.close();
191
+ }
192
+ }
193
+
194
+ /**
195
+ * 给 stat 过的那几行补上 `duration`(只补音视频扩展名、只补 stat 成功的那几条)。
196
+ *
197
+ * 并发压在 2:这是一次读盘,一页里通常只有一两份音视频,串行也没问题,但别让它去和
198
+ * stat 那 8 路抢 IO。任何一条读失败都只是那一份没有时长。
199
+ */
200
+ async function withDurations(rows) {
201
+ if (!Array.isArray(rows) || rows.length === 0) return rows;
202
+ const wanted = rows.filter((row) => (
203
+ row && row.status === 'ok' && typeof row.target === 'string' && DURATION_EXTENSIONS.has(extensionOf(row.target))
204
+ ));
205
+ if (wanted.length === 0) return rows;
206
+ const measured = await mapLimit(wanted, 2, async (row) => {
207
+ try {
208
+ return await mediaDurationMsOf(row.target);
209
+ } catch {
210
+ return 0;
211
+ }
212
+ });
213
+ const byTarget = new Map();
214
+ for (let index = 0; index < wanted.length; index += 1) {
215
+ const ms = measured[index];
216
+ if (ms > 0) byTarget.set(wanted[index].target, ms);
217
+ }
218
+ if (byTarget.size === 0) return rows;
219
+ return rows.map((row) => {
220
+ const ms = row && typeof row.target === 'string' ? byTarget.get(row.target) : undefined;
221
+ return ms === undefined ? row : { ...row, duration: ms };
222
+ });
223
+ }
224
+
78
225
  /** 把 `rows` 里的 size/mtime 盖回文件对象;没量到的保持原样。 */
79
226
  function applyStats(files, rows) {
80
227
  const byPath = new Map();
@@ -85,7 +232,12 @@ function applyStats(files, rows) {
85
232
  return files.map((file) => {
86
233
  const row = byPath.get(file.path);
87
234
  if (!row) return file;
88
- return { ...file, size: row.size, mtime: row.mtime };
235
+ return {
236
+ ...file,
237
+ size: row.size,
238
+ mtime: row.mtime,
239
+ ...(typeof row.duration === 'number' && row.duration > 0 ? { duration: row.duration } : {}),
240
+ };
89
241
  });
90
242
  }
91
243
 
@@ -110,7 +262,7 @@ function presentedPathsIn(messages) {
110
262
  }
111
263
 
112
264
  /**
113
- * 给 `deriveMessages` 的输出补上交付文件的 size / mtime。
265
+ * 给 `deriveMessages` 的输出补上交付文件的 size / mtime / duration。
114
266
  *
115
267
  * 返回**新的**消息数组(只有带 `presentedFiles` 的那几条是新的对象),没补到任何一条时原样
116
268
  * 返回入参 —— 调用方可以按引用判断「有没有变化」。`messages` 本身是 `derived-cache` 交回来
@@ -146,7 +298,8 @@ function statsRowsFor(ctx, sessionId, messages, options = {}) {
146
298
  forgetPresentedFileStats(ctx, messages);
147
299
  return [];
148
300
  }
149
- return rows;
301
+ // 时长那几格是读文件头,不占 stat 的预算,但同样「量不到就不写」。
302
+ return withDurations(rows);
150
303
  }).catch(() => {
151
304
  forgetPresentedFileStats(ctx, messages);
152
305
  return [];
@@ -194,7 +347,7 @@ function createPresentedStats(ctx, sessionId, options = {}) {
194
347
  };
195
348
 
196
349
  /**
197
- * 给一帧 `deliverables/presented` 补 size / mtime。
350
+ * 给一帧 `deliverables/presented` 补 size / mtime / duration。
198
351
  *
199
352
  * 回**新的**事件对象(`data.files` 换掉),任何失败 / 超时都原样回入参。
200
353
  */
@@ -214,11 +367,15 @@ function createPresentedStats(ctx, sessionId, options = {}) {
214
367
  if (!pending) {
215
368
  const paths = [...new Set(files.map((file) => file.path))];
216
369
  pending = statWithinBudget(ctx, sessionId, paths, budgetMs)
217
- .then((rows) => {
370
+ .then(async (rows) => {
218
371
  // 超时 / 整批失败:这一帧发未补的版本,且不记账 —— 下一帧同样的 key 允许再试。
219
- if (rows === null) done.delete(key);
220
- else done.set(key, rows);
221
- return rows;
372
+ if (rows === null) {
373
+ done.delete(key);
374
+ return null;
375
+ }
376
+ const enriched = await withDurations(rows);
377
+ done.set(key, enriched);
378
+ return enriched;
222
379
  })
223
380
  .catch(() => {
224
381
  done.delete(key);
@@ -532,7 +532,9 @@ function createRelayControlHandlers(deps) {
532
532
  ? credentials.revokeAllByInstance(state.instanceId)
533
533
  : 0;
534
534
  state.lanSecret = randomBytes(32).toString('hex');
535
- state.pairingCode = core.genPairingCode();
535
+ // 换码的同时换票据(`core.rotatePairing` 一次换码换票):只换码的话,截图里旧二维码
536
+ // 的票据还能再配一台新设备进来。
537
+ core.rotatePairing(state);
536
538
  core.saveState(state);
537
539
  console.warn(`[dsh-mobile-plugin] [relay-control] 已吊销全部授权:中转 ${revoked}、本机 ${localRevoked}`);
538
540
  await syncSidecar().catch(() => undefined);
@@ -606,7 +608,9 @@ function createRelayControlHandlers(deps) {
606
608
  * **必须由宿主代测**:手机在蜂窝网络下直连那些域名可能被运营商挡、也可能被 CORS 挡住
607
609
  * (读到的是浏览器拦截而不是真实耗时)。宿主是出站无 CORS 的本机进程。
608
610
  *
609
- * 只认 http(s)、最多 8 条:这条不接受「任意地址探测」那种用法。
611
+ * **只测本机配置里登记过的中转地址**:这条由宿主代测,若放行任意 http(s) 就等于给一台
612
+ * 已配对手机一台内网扫描器(打任意 host:port 的 `/healthz`)。按 host 与配置里的
613
+ * `relayUrls` 比对,正常的「测中转候选」只测自己存着的那几条,不受影响。
610
614
  */
611
615
  async function handleRelayProbe(_ctx, req, res) {
612
616
  let body = {};
@@ -615,11 +619,17 @@ function createRelayControlHandlers(deps) {
615
619
  } catch {
616
620
  body = {};
617
621
  }
622
+ const allowedHosts = new Set(
623
+ core.relayAddressesOf(state).relayUrls
624
+ .map((url) => { try { return new URL(url).host; } catch { return ''; } })
625
+ .filter(Boolean),
626
+ );
618
627
  const list = Array.isArray(body.urls) ? body.urls : [];
619
628
  const targets = list
620
629
  .filter((url) => typeof url === 'string' && /^https?:\/\//i.test(url.trim()))
621
- .slice(0, PROBE_MAX_URLS)
622
- .map((url) => url.trim().replace(/\/+$/, ''));
630
+ .map((url) => url.trim().replace(/\/+$/, ''))
631
+ .filter((url) => { try { return allowedHosts.has(new URL(url).host); } catch { return false; } })
632
+ .slice(0, PROBE_MAX_URLS);
623
633
  const runner = typeof probeUrls === 'function' ? probeUrls : (urls) => Promise.all(urls.map(probeOne));
624
634
  const results = await runner(targets);
625
635
  sendJson(res, 200, { ok: true, results });
@@ -320,6 +320,11 @@ async function handleScheduleCatalog(ctx, _req, res) {
320
320
  * 走 `catalog()` 再按 sessionId 筛,而不是宿主的 `list({sessionId})`:后者只回还在跑的,
321
321
  * 且行上没有 sessionId / status(见文件头)。`state` 因此由行上的 status 推出来,
322
322
  * 已结束的任务才能如实显示成「已结束」。
323
+ *
324
+ * `?brief=1` 是页头那只闹钟用的轻量档:只要「几条活动任务 + 最近要跑的那条 id」,
325
+ * 不把每条任务的正文本、规则、交付记录整份搬回去。**筛选与判定完全同一套**(同一个
326
+ * `normalizeScheduleEntries` + 同一个 active 判据),只是出参少了两样 —— 两处各写一份
327
+ * 判定迟早会给出两个数(角标说 2、任务页说 3)。
323
328
  */
324
329
  async function handleScheduleList(ctx, req, res) {
325
330
  const url = new URL(req.url, 'http://x');
@@ -340,11 +345,21 @@ async function handleScheduleList(ctx, req, res) {
340
345
 
341
346
  // 先按目录整体收敛(保住 status → state 的推导),再筛这条会话的。
342
347
  const all = normalizeScheduleEntries(value, undefined, undefined);
343
- sendJson(res, 200, {
344
- ok: true,
345
- records: all.filter((entry) => entry.sessionId === sessionId),
346
- serverNow: Date.now(),
347
- });
348
+ const records = all.filter((entry) => entry.sessionId === sessionId);
349
+ if (queryValue(url, 'brief') === '1') {
350
+ const active = records
351
+ .filter((entry) => entry.state === 'active')
352
+ // 与 App 侧同一条排序口径:下次运行最近的在前,没有 scheduledAt 的垫底。
353
+ .sort((a, b) => (Date.parse(a.scheduledAt ?? '') || Infinity) - (Date.parse(b.scheduledAt ?? '') || Infinity));
354
+ return sendJson(res, 200, {
355
+ ok: true,
356
+ brief: true,
357
+ count: active.length,
358
+ ...(active[0]?.id === undefined ? {} : { firstTaskId: active[0].id }),
359
+ serverNow: Date.now(),
360
+ });
361
+ }
362
+ sendJson(res, 200, { ok: true, records, serverNow: Date.now() });
348
363
  }
349
364
 
350
365
  /** 把查询串里的 limit 收成 1–100 的整数;非法返回 0。 */