dsh-mobile-plugin 0.5.50 → 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.
@@ -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 数,条数不齐时放命令结果原文),命令行那块根本不出现。
@@ -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.50",
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",