dsh-mobile-plugin 0.5.49 → 0.5.51

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.
@@ -239,6 +239,19 @@ function reset() {
239
239
  SESSIONS.clear();
240
240
  }
241
241
 
242
+ /**
243
+ * 只从盘上那份对象文件头量宽高,**不问宿主、不搬字节**(批量那一档用)。
244
+ *
245
+ * 量不出来(对象文件不在 / 不是位图)回 null,调用方退回问宿主那条路。这条比 `refFor`
246
+ * 便宜的地方在于:它连「和盘上字节对得上的引用」都不拼 —— 宿主那条校验只在真要取字节
247
+ * 或要宿主自己量的时候才用得上。
248
+ */
249
+ function localDims(attachmentId) {
250
+ const probed = probeObject(attachmentId);
251
+ if (!probed) return null;
252
+ return { width: probed.width, height: probed.height };
253
+ }
254
+
242
255
  module.exports = {
243
256
  MAX_IDS_PER_SESSION,
244
257
  MAX_SESSIONS,
@@ -247,6 +260,7 @@ module.exports = {
247
260
  remember,
248
261
  lookup,
249
262
  refFor,
263
+ localDims,
250
264
  openObject,
251
265
  streamIfRemembered,
252
266
  reset,
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * 会话历史的纯派生逻辑:从 host history 事件折叠出 v1 移动端的消息/结构化项。
4
+ * 会话历史的纯派生逻辑:消息、结构项和真实轮次起止一起交给移动端恢复。
5
5
  *
6
6
  * 本模块只做「事件 → 展示结构」的纯计算,不碰 ctx、不发 RPC,因此可以单独测;
7
7
  * 原先这些函数与路由 handler 混在 lib/mobile/sessions.js 里(该文件 1964 行),
@@ -16,6 +16,7 @@ const { rememberToolResults, toolResultsFor, toolResultsVersionFor } = require('
16
16
  const crypto = require('node:crypto');
17
17
  const { derivedCache } = require('../shared/derived-cache.js');
18
18
  const { foldTurnFacts, turnFactsSnapshot } = require('./turn-facts.js');
19
+ const { turnLifecyclesOf } = require('./turn-lifecycle.js');
19
20
 
20
21
  /** 每一轮出过的图(工具结果里的图片块),轮号 → 图。`lookback` 也扫:它才装得下更早那一页。 */
21
22
  function collectTurnImages(entries, lookbackEntries) {
@@ -598,6 +599,7 @@ function deriveMessages(events, sessionId, lookbackEvents) {
598
599
 
599
600
  // 模型归因、成功产出与净改动和直播同源;原始参数与 diff 只在本机折叠。
600
601
  const factsByTurn = foldTurnFacts((lookbackEvents || []).concat(events));
602
+ const lifecycles = turnLifecyclesOf(events, lookbackEvents || []);
601
603
  const producedItems = [];
602
604
 
603
605
  // 单步计时预扫描:为每条 assistant 消息派生「本轮」的 ttft / decode / 输出 token
@@ -1138,9 +1140,11 @@ function deriveMessages(events, sessionId, lookbackEvents) {
1138
1140
  for (const item of out) {
1139
1141
  const turn = typeof item.turn === 'number' ? item.turn : turnOfSeq(item.seq, turnIndex.bySeq, turnIndex.starts);
1140
1142
  const facts = factsByTurn.get(turn);
1141
- if (!facts) continue;
1143
+ const lifecycle = lifecycles.get(turn);
1144
+ if (!facts && !lifecycle) continue;
1142
1145
  if (turn !== null && turn !== undefined) item.turn = turn;
1143
- Object.assign(item, turnFactsSnapshot(facts));
1146
+ if (facts) Object.assign(item, turnFactsSnapshot(facts));
1147
+ if (lifecycle) item.turnLifecycle = lifecycle;
1144
1148
  }
1145
1149
  // 手动 `/compact` 在桌面上是**一件事**:`CompactionCommandCard` 只画一个 `CompactionItem`
1146
1150
  // (标题取命令名,摘要位放条数与 token 数,条数不齐时放命令结果原文),命令行那块根本不出现。
@@ -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 { /* 连接已断开 */ }
@@ -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。 */
@@ -278,6 +278,13 @@ async function handleFork(ctx, req, res) {
278
278
  */
279
279
  async function handleSessionAttachment(ctx, req, res) {
280
280
  const body = await readJsonBody(req);
281
+ // 批量宽高走同一条路由(`attachmentIds`):一次一屏,不再逐张发(见 handleAttachmentDimsBatch)。
282
+ if (body && Array.isArray(body.attachmentIds)) {
283
+ if (typeof body.sessionId !== 'string' || !body.sessionId) {
284
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要 { sessionId, attachmentIds }' } });
285
+ }
286
+ return handleAttachmentDimsBatch(ctx, body, res);
287
+ }
281
288
  if (!body || typeof body.sessionId !== 'string' || !body.sessionId
282
289
  || typeof body.attachmentId !== 'string' || !body.attachmentId) {
283
290
  return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要 { sessionId, attachmentId }' } });
@@ -325,4 +332,52 @@ async function handleSessionAttachment(ctx, req, res) {
325
332
  });
326
333
  }
327
334
 
328
- module.exports = { singleTextOf, executeCommand, promptOnce, handleSend, handleCommands, handleSessionRead, handleSessionAttachment, handleStop, handleRename, handleFork };
335
+ /**
336
+ * 一次问一批附件图的宽高:`{ sessionId, attachmentIds: [...] }` → `{ ok, dims: { <id>: {width, height} } }`。
337
+ *
338
+ * 为什么要有这一档:老会话里缺宽高的图一屏能有十几张,逐张各发一次请求,走中转时每一发
339
+ * 都是两秒起步;而这一档**先看盘上那份对象文件的文件头**,绝大多数图连宿主都不用问,
340
+ * 整屏一次往返就齐了。
341
+ *
342
+ * 三条口径:
343
+ * - **先盘上、后宿主**:`attachmentStore.localDims` 直接读文件头;量不出来的(对象不在 /
344
+ * 没登记过的老 id)才退回问宿主,仍是一张一次,但那是少数;
345
+ * - **量不出来的就是没有**:不进结果表,App 那边按兜底盒画 —— 与单张那档的 404 同一个语义,
346
+ * 只是批量里不能用一次失败毁掉整批;
347
+ * - **条数封顶**:`DIMS_BATCH_MAX` 与 App 侧「一屏最多补几张」同一量级,多出来的等下一批。
348
+ */
349
+ const DIMS_BATCH_MAX = 64;
350
+
351
+ async function handleAttachmentDimsBatch(ctx, body, res) {
352
+ const ids = Array.isArray(body.attachmentIds)
353
+ ? [...new Set(body.attachmentIds.filter((id) => typeof id === 'string' && id))]
354
+ : [];
355
+ if (ids.length === 0) {
356
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要 { sessionId, attachmentIds }' } });
357
+ }
358
+ const dims = {};
359
+ const misses = [];
360
+ for (const attachmentId of ids.slice(0, DIMS_BATCH_MAX)) {
361
+ const local = attachmentStore.localDims(attachmentId);
362
+ if (local) dims[attachmentId] = local;
363
+ else misses.push(attachmentId);
364
+ }
365
+ // 盘上量不出来的:照单张那条老路问一次宿主(拼不出引用 / 宿主读不到就跳过这张)。
366
+ for (const attachmentId of misses) {
367
+ const ref = attachmentStore.refFor(body.sessionId, attachmentId);
368
+ if (!ref) continue;
369
+ try {
370
+ const { value, error } = unwrap(await callSessions(ctx, 'attachment', { sessionId: body.sessionId, attachment: ref }));
371
+ if (error) continue;
372
+ const data = value && typeof value.data === 'string' ? value.data : '';
373
+ if (!data) continue;
374
+ const size = imageSizeOf(Buffer.from(data, 'base64'));
375
+ if (size && size.width > 0 && size.height > 0) dims[attachmentId] = { width: size.width, height: size.height };
376
+ } catch {
377
+ // 这一张量不到就当没有:整批照旧回,别让一张坏图拖垮一屏。
378
+ }
379
+ }
380
+ sendJson(res, 200, { ok: true, dims });
381
+ }
382
+
383
+ module.exports = { singleTextOf, executeCommand, promptOnce, handleSend, handleCommands, handleSessionRead, handleSessionAttachment, handleAttachmentDimsBatch, DIMS_BATCH_MAX, handleStop, handleRename, handleFork };
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * 消息快照:镜像推送与 /messages 分页共用的折叠路径;裁剪前的上下文仍算未交付历史。
4
+ * 消息快照:镜像与分页共用折叠路径,新增轮次起止即使没有新正文也随增量送达。
5
5
  *
6
6
  * buildMessagesSnapshot(不解析 query)与 handleMessages(解析 beforeSeq/afterSeq/limit)
7
7
  * 共用消息折叠逻辑。普通会话走 sessions.history;子代理必须携带 durable parent address,
@@ -167,7 +167,9 @@ async function handleMessages(ctx, req, res) {
167
167
  : (afterSeq === null
168
168
  ? enriched
169
169
  : enriched.filter((item) => item.kind === 'compaction' || item.kind === 'command'
170
- || (Number.isSafeInteger(item.seq) && item.seq > afterSeq)));
170
+ || (Number.isSafeInteger(item.seq) && item.seq > afterSeq)
171
+ // 收尾事件本身不产消息,仍须把原消息上的新起止事实交给增量补拉。
172
+ || (item.turnLifecycle && item.turnLifecycle.seq > afterSeq)));
171
173
  // 工具结果不产生消息行,但会把**缓存里已有的**工具卡从 running 补成最终态。补丁取自
172
174
  // 整个窗口(调用方游标可能已越过结果 seq);已随消息块下发的只回状态(见 toolResultPatchesFor)。
173
175
  // 增量那一发(带 afterSeq)一律只回状态:调用方手上已有一份会话,整窗重发等于每 15 秒
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ /** 会话日志里的真实轮次边界,随消息快照恢复开跑和收尾,不能用模型信息推断完成。 */
4
+ function turnLifecyclesOf(events, lookback = []) {
5
+ const turns = new Map();
6
+ for (const entry of [...lookback, ...events]) {
7
+ const event = entry.event || entry;
8
+ if (!event || !event.data || !Number.isSafeInteger(event.data.turn) || !Number.isSafeInteger(event.seq)) continue;
9
+ const turn = event.data.turn;
10
+ const previous = turns.get(turn);
11
+ if (previous && previous.seq >= event.seq) continue;
12
+ if (event.type === 'turn/start') {
13
+ if (previous && previous.state !== 'running') continue;
14
+ turns.set(turn, { turn, seq: event.seq, startSeq: event.seq, state: 'running', ...(typeof event.time === 'number' ? { startedAt: event.time } : {}) });
15
+ } else if (event.type === 'turn/end') {
16
+ const state = event.data.reason && event.data.reason.kind;
17
+ if (!['completed', 'aborted', 'error', 'max-tokens'].includes(state)) continue;
18
+ turns.set(turn, { ...previous, turn, seq: event.seq, state, ...(typeof event.time === 'number' ? { endedAt: event.time } : {}) });
19
+ }
20
+ }
21
+ return turns;
22
+ }
23
+
24
+ module.exports = { turnLifecyclesOf };
@@ -107,7 +107,8 @@ function createConnectionCheck(deps = {}) {
107
107
  // 防火墙查不到就让它是「查不到」:探测自己负责把 reason 说清楚,这里不兜底成 null 之外的值。
108
108
  let firewall;
109
109
  try {
110
- firewall = await probe({ force: options.force === true, platform });
110
+ // 把当前监听端口带过去:Windows 那边规则若收窄到别的端口,不能算放行。
111
+ firewall = await probe({ force: options.force === true, platform, port });
111
112
  } catch {
112
113
  firewall = null;
113
114
  }
@@ -5,12 +5,18 @@
5
5
  *
6
6
  * 只读、不提权、不改规则。查不到的实话是 `null`,「不知道」不许写成「正常」。
7
7
  *
8
- * ## 为什么只查「放不放行这个程序」,不查端口
8
+ * ## 主要查「放不放行这个程序」,但不忽略端口
9
9
  *
10
- * macOS 与 Windows 的入站规则都是按**程序**(可执行文件路径)挂的,不是按端口挂的:
11
- * 用户装完之后第一次被系统问到「是否允许接受传入连接」,点一次「拒绝」就永久挡着,
12
- * 面板上什么都看不出来。所以查的对象是 `process.execPath` —— 宿主进程自己的那个
13
- * 可执行文件,不是写死的 `node`(DSH 自带的运行时、nvm 切的版本,路径都不一样)。
10
+ * macOS 与 Windows 的入站规则大多按**程序**(可执行文件路径)挂:用户装完之后第一次被
11
+ * 系统问到「是否允许接受传入连接」,点一次「拒绝」就永久挡着,面板上什么都看不出来。
12
+ * 所以查的对象是 `process.execPath` —— 宿主进程自己的那个可执行文件,不是写死的 `node`
13
+ * (DSH 自带的运行时、nvm 切的版本,路径都不一样)。
14
+ *
15
+ * 但 Windows 的规则也能同时把端口收窄(例如只放行 18787)。端口一漂(首选端口被占、内核
16
+ * 另分一个),老规则还在、程序路径也对得上,可它压根不覆盖新端口——只看程序就会把「实际
17
+ * 被默认规则挡着」报成「放行」。所以程序规则的端口也带回来,跟当前监听端口比一下:收窄到
18
+ * 别的端口的那条不算放行(见 `coversPort`)。macOS 的 `--getappblocked` 天生按程序判,
19
+ * 不涉及端口。
14
20
  *
15
21
  * ## 三个平台能查到什么,差很远
16
22
  *
@@ -99,6 +105,8 @@ function parseWindowsReport(text) {
99
105
  action: String(item && item.action ? item.action : ''),
100
106
  enabled: item ? item.enabled !== false : false,
101
107
  profile: String(item && item.profile ? item.profile : ''),
108
+ // 规则可能只放行某几个端口(`Any` / `18787` / `1000-2000` / `80,443`)。空串当「不限」。
109
+ localPort: String(item && item.localPort ? item.localPort : ''),
102
110
  })),
103
111
  activeProfiles: asArray(profileObject.activeProfiles).map((item) => String(item)),
104
112
  // 这两个计数只用来区分「一条放行规则都没有」和「规则压根没读出来」,见 `decideWindowsAllows`。
@@ -129,23 +137,53 @@ function windowsRuleApplies(profileField, activeProfiles) {
129
137
  return scopes.some((scope) => activeProfiles.some((active) => String(active).trim().toLowerCase() === scope));
130
138
  }
131
139
 
140
+ /**
141
+ * 规则放行的端口覆不覆盖当前真正在听的那个端口。
142
+ *
143
+ * 规则可能把端口收窄成 `18787` 这种固定值。端口漂走之后(首选端口被占、内核另分一个),
144
+ * 老规则还在、程序路径也对得上,但它压根不覆盖新端口——只看程序路径会把「实际被挡」
145
+ * 报成「放行」。所以带端口比一下:`Any` / 空串算不限;当前端口不知道(0)时不收窄,
146
+ * 宁可漏报也不凭空说人家被挡。
147
+ */
148
+ function coversPort(localPort, port) {
149
+ const field = String(localPort || '').trim();
150
+ if (field === '' || /^any$/i.test(field)) return true;
151
+ if (!Number.isInteger(port) || port <= 0) return true;
152
+ const tokens = field.split(/[,\s]+/).filter(Boolean);
153
+ return tokens.some((token) => {
154
+ const range = /^(\d+)-(\d+)$/.exec(token);
155
+ if (range) {
156
+ const lo = Number(range[1]);
157
+ const hi = Number(range[2]);
158
+ return port >= Math.min(lo, hi) && port <= Math.max(lo, hi);
159
+ }
160
+ return Number(token) === port;
161
+ });
162
+ }
163
+
132
164
  /**
133
165
  * Windows 上的「放行」是个模型判断,不是一条规则。
134
166
  *
135
- * 顺序:显式 Block 优先 → 有生效中的 Allow → 防火墙开着却没有规则 = 默认拒绝(这是
136
- * 第一次弹框点了取消之后的样子)→ 防火墙关着 = 不挡。
167
+ * 顺序:显式 Block 优先 → 有生效中、且端口也覆盖当前监听端口的 Allow → 防火墙开着却没有
168
+ * 规则 = 默认拒绝(这是第一次弹框点了取消之后的样子)→ 防火墙关着 = 不挡。
137
169
  *
138
170
  * 只有「确实一条这个程序的规则都没有」才走默认拒绝。查到了过滤器却一条规则都没关联上,
139
171
  * 是查询出了问题,回 `null`(查不到)—— 报「挡住了」会把人引去关防火墙、加重复规则,
140
172
  * 真正的原因反而被盖住。
173
+ *
174
+ * `report.port` 是宿主当前监听的那个端口:规则收窄到别的端口时不算放行;缺省(0)时不按
175
+ * 端口收窄,跟旧行为一致。
141
176
  */
142
177
  function decideWindowsAllows(report) {
143
178
  if (!report || !Array.isArray(report.apps)) return null;
144
179
  const enabled = report.profiles.some((item) => item.enabled === true);
145
180
  if (!enabled) return true;
146
181
  if (countOf(report.filters) > 0 && countOf(report.rules) === 0) return null;
182
+ const port = Number.isInteger(report.port) ? report.port : 0;
147
183
  const hits = report.apps.filter((item) => item.program && sameWindowsPath(item.program, report.appPath));
148
- const live = hits.filter((item) => item.enabled !== false && windowsRuleApplies(item.profile, report.activeProfiles));
184
+ const live = hits.filter((item) => item.enabled !== false
185
+ && windowsRuleApplies(item.profile, report.activeProfiles)
186
+ && coversPort(item.localPort, port));
149
187
  if (live.some((item) => /block/i.test(item.action))) return false;
150
188
  if (live.some((item) => /allow/i.test(item.action))) return true;
151
189
  return false;
@@ -186,7 +224,10 @@ const WINDOWS_SCRIPT = [
186
224
  ' $rules = $rules + 1;',
187
225
  // 出站规则跟「手机连进来」无关;混进来会把「没有入站放行」看成「有规则」。
188
226
  ' if ("$($r.Direction)" -ne "Inbound") { continue; }',
189
- ' $apps += @{ program = "$($f.Program)"; action = "$($r.Action)"; enabled = ("$($r.Enabled)" -eq "True"); profile = "$($r.Profile)" }',
227
+ // 规则若把端口收窄了(只放行 18787 这种),要把那个端口带回来;否则光看程序路径会
228
+ // 把「端口漂走后的旧规则」当成还放行,真实阻塞被盖住。
229
+ ' $pf = $r | Get-NetFirewallPortFilter -PolicyStore ActiveStore;',
230
+ ' $apps += @{ program = "$($f.Program)"; action = "$($r.Action)"; enabled = ("$($r.Enabled)" -eq "True"); profile = "$($r.Profile)"; localPort = "$($pf.LocalPort)" }',
190
231
  ' }',
191
232
  '}',
192
233
  '@{ profiles = $profiles; apps = $apps; filters = $filters.Count; rules = $rules; activeProfiles = $active } | ConvertTo-Json -Depth 6 -Compress',
@@ -216,13 +257,14 @@ function defaultExec(command, args, options) {
216
257
  /**
217
258
  * 查一次防火墙。`exec` 与 `platform` 可注入,守卫才不用真去 fork 进程。
218
259
  *
219
- * @param {{platform?: string, execPath?: string, exec?: Function}} [options]
260
+ * @param {{platform?: string, execPath?: string, port?: number, exec?: Function}} [options]
220
261
  * @returns {Promise<{supported: boolean, enabled: boolean|null, allowsApp: boolean|null,
221
262
  * appPath: string, reason: string|null}>}
222
263
  */
223
264
  async function probeFirewall(options = {}) {
224
265
  const platform = options.platform || process.platform;
225
266
  const execPath = options.execPath || process.execPath || '';
267
+ const port = Number.isInteger(options.port) ? options.port : 0;
226
268
  const exec = options.exec || defaultExec;
227
269
  const timeoutMs = PROBE_TIMEOUT_MS[platform] || 3000;
228
270
 
@@ -258,7 +300,7 @@ async function probeFirewall(options = {}) {
258
300
  return unknownFirewall(execPath, 'parse-failed');
259
301
  }
260
302
  if (report.profiles.length === 0) return unknownFirewall(execPath, 'parse-failed');
261
- const allowsApp = decideWindowsAllows({ ...report, appPath: execPath });
303
+ const allowsApp = decideWindowsAllows({ ...report, appPath: execPath, port });
262
304
  if (allowsApp === null) return unknownFirewall(execPath, 'parse-failed');
263
305
  return {
264
306
  supported: true,
@@ -297,15 +339,16 @@ let pending = null;
297
339
  /**
298
340
  * 带缓存的取法。`force` 只由「重新自检」那颗按钮用。
299
341
  *
300
- * @param {{force?: boolean, platform?: string, execPath?: string, exec?: Function}} [options]
342
+ * @param {{force?: boolean, platform?: string, execPath?: string, port?: number, exec?: Function}} [options]
301
343
  */
302
344
  async function readFirewall(options = {}) {
303
345
  const now = Date.now();
304
- if (!options.force && cache && now - cache.at < CACHE_TTL_MS && cache.key === (options.platform || process.platform)) {
346
+ // 端口也算进 key:端口漂移后(同一次会话里换了监听端口)别把上一个端口的结果复用下来。
347
+ const key = `${options.platform || process.platform}|${Number.isInteger(options.port) ? options.port : ''}`;
348
+ if (!options.force && cache && now - cache.at < CACHE_TTL_MS && cache.key === key) {
305
349
  return cache.value;
306
350
  }
307
351
  if (pending) return pending;
308
- const key = options.platform || process.platform;
309
352
  pending = probeFirewall(options)
310
353
  .catch(() => unknownFirewall(options.execPath || process.execPath || '', 'parse-failed'))
311
354
  .then((value) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.49",
3
+ "version": "0.5.51",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",