dsh-mobile-plugin 0.5.122 → 0.5.124

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,6 +1,6 @@
1
1
  ---
2
2
  name: dsh-mobile-kb
3
- description: DSH 手机版(电脑上装的「移动端插件」,手机 App 靠它连回这台电脑)的网络搭建与排查知识库。用户要给「移动端插件 / DSH 手机版 / 手机 App 连电脑」搭建、部署、开通一条能连回电脑的网络线路(比如「我想给移动端插件搭建一个网络线路」「给当前 DSH 装的这个移动端插件弄条能连的网络」),或用「帮我部署一个网络」「不知道该用什么网络」「你帮我看看我能怎么连」「隧道是不是关的」「怎么开内置隧道」这类说法时用它;遇到连不上电脑、配对失败、设备离线/失联、中转与局域网不通、自建公网入口(IPv4 公网/端口映射、IPv6、frp、DDNS、Nginx 反代、域名)等问题也用它。「配对没成功」「扫二维码没反应」「显示离线」「连不上」「中转连不上」「局域网不通」「IPv6 直连连不上」「家里光猫/路由器 IPv6 没开」「IPv6 防火墙」「有公网 IPv4 / 端口映射 / 路由器映射」「frp / frps / frpc / 自建 TCP 隧道」「dsh-relay / 自建中转服务器 / 部署中转 / 中转体检口」「ddns / 域名绑定 / 动态解析」「nginx 反代 / NAS 部署」「外网拨不进来」「ZeroNews / 节点小宝 / iepose / 国内线路 / 免注册接入 / AuthToken / 网页服务 / 组网设备端」「海外 IPv6 / 运营商不给 IPv6 / 网关锁死」「路由器后台密码/超级管理」「apiProxy 未注入 / 电脑插件没加载 / 加载会话或工作区失败 / 电脑服务处理失败」「归档或改名成功却弹加载失败 / 动作成功却报请求超时(GET /sessions)」「HTTP 522 / 注册超时」「stage: auth / parse / cleartext / credential / save / reset」「配对码不对 / 电脑拒绝新设备 / 二维码没有可用的连接地址 / 怎么拿到配对信息 / 怎么开始配对」「这台电脑暂时没连上 / 连接未完成 / 电脑没连上中转」「加载会话或工作区请求超时 / 请求超时」「响应无法校验」「Cloudflare 兜底隧道 / trycloudflare / cloudflared」「回环端口被占 / 局域网能连但隧道 403 / 手机从外面进不来 / 专属回环入口 / 端口被占弹窗」「怎么回这条反馈」时也用。先按这里分好类,再读对应参考,别从头猜。
3
+ description: DSH 手机版(电脑上装的「移动端插件」,手机 App 靠它连回这台电脑)的网络搭建与排查知识库。用户要给「移动端插件 / DSH 手机版 / 手机 App 连电脑」搭建、部署、开通一条能连回电脑的网络线路(比如「我想给移动端插件搭建一个网络线路」「给当前 DSH 装的这个移动端插件弄条能连的网络」),或用「帮我部署一个网络」「不知道该用什么网络」「你帮我看看我能怎么连」「隧道是不是关的」「怎么开内置隧道」这类说法时用它;遇到连不上电脑、配对失败、设备离线/失联、中转与局域网不通、自建公网入口(IPv4 公网/端口映射、IPv6、frp、DDNS、Nginx 反代、域名)等问题也用它。「配对没成功」「扫二维码没反应」「显示离线」「连不上」「中转连不上」「局域网不通」「IPv6 直连连不上」「家里光猫/路由器 IPv6 没开」「IPv6 防火墙」「有公网 IPv4 / 端口映射 / 路由器映射」「frp / frps / frpc / 自建 TCP 隧道」「dsh-relay / 自建中转服务器 / 部署中转 / 中转体检口」「ddns / 域名绑定 / 动态解析」「nginx 反代 / NAS 部署」「外网拨不进来」「ZeroNews / 节点小宝 / iepose / 国内线路 / 免注册接入 / AuthToken / 网页服务 / 组网设备端」「海外 IPv6 / 运营商不给 IPv6 / 网关锁死」「路由器后台密码/超级管理」「忘了光猫后台密码 / 光猫后台进不去 / 找回光猫管理密码 / 光猫凭据自查 / 光猫 Telnet 提权」「apiProxy 未注入 / 电脑插件没加载 / 加载会话或工作区失败 / 电脑服务处理失败」「归档或改名成功却弹加载失败 / 动作成功却报请求超时(GET /sessions)」「HTTP 522 / 注册超时」「stage: auth / parse / cleartext / credential / save / reset」「配对码不对 / 电脑拒绝新设备 / 二维码没有可用的连接地址 / 怎么拿到配对信息 / 怎么开始配对」「这台电脑暂时没连上 / 连接未完成 / 电脑没连上中转」「加载会话或工作区请求超时 / 请求超时」「响应无法校验」「Cloudflare 兜底隧道 / trycloudflare / cloudflared」「回环端口被占 / 局域网能连但隧道 403 / 手机从外面进不来 / 专属回环入口 / 端口被占弹窗」「怎么回这条反馈」时也用。先按这里分好类,再读对应参考,别从头猜。
4
4
  ---
5
5
 
6
6
  # DSH 手机版常见问题(dsh-mobile-kb)
@@ -38,6 +38,7 @@ description: DSH 手机版(电脑上装的「移动端插件」,手机 App
38
38
  - 自己架中转服务器 / dsh-relay / 部署中转 / 中转体检口 → `references/relay-server.md`(架一台中转程序)
39
39
  - 局域网 / 直连 / 只走公网 / 弱网切换等选路 → `references/network.md`
40
40
  - IPv6 直连连不上 / 光猫或路由器 IPv6 没开 / IPv6 防火墙 / 公网 IPv6 进不来 → `references/ipv6.md`
41
+ - 进不去光猫后台 / 忘了光猫后台密码 / 找回光猫管理凭据 / 要进光猫改防火墙或做映射但没密码 → `references/ont-gateway.md`(先确认自有设备,按型号 / 运营商上网查为主,仓库工具只作一次尝试;改完的验收另见 IPv4 / IPv6 两篇)
41
42
  - 公网 IPv4 / 端口映射 / 路由器映射 / 有公网 IP 连不上 → `references/ipv4.md`
42
43
  - frp / frps / frpc / 自己架公网服务器做 TCP 直连 → `references/frp.md`
43
44
  - ZeroNews / 国内线路 / 面板代装客户端 / 粘 AuthToken / 连接失败且地址为 https 域名 → `references/zeronews.md`(国内一条免注册线路,插件代装代起)
@@ -18,6 +18,22 @@
18
18
 
19
19
  **关键一点别搞错**:手机侧的加密靠 frps 在公网口终结 TLS(https 那档),不是 frp 隧道内部那条 `transport.tls`——后者只保护 frpc↔frps 那一段。想要手机侧加密就必须让手机连的是 https 地址。
20
20
 
21
+ ## 没公网服务器:用正规运营商
22
+
23
+ 用户没有公网服务器、也不想养一台时,可以买正规运营商的 frp 服务,不用自己搭 frps。挑的时候按三条过:主体是公司、能在工信部查到 ICP 备案(最好还有增值电信业务经营许可证和公安备案)、要实名认证、有免费档能先试。个人工作室、查不到备案的小站不推。
24
+
25
+ 国内这几家资质和价格都对得上,而且跑标准 frp,面板「导入 frpc 配置」能直接用:
26
+
27
+ - 樱花 FRP(natfrp.com):河南驰锋信息科技有限公司,ICP、公安备案、增值电信许可证齐。免费 2 条隧道、10Mbps、5GB/月,签到加流量;白银 VIP 20 元/月,36Mbps、10 条隧道、163GB;额外流量 0.5 元/GB。服务端明确兼容上游 frpc 0.18.0 以上,可直接复制配置文件连。
28
+ - OpenFrp(openfrp.net):北京樱云创梦网络科技有限公司与至远光辉信息技术(天津)有限公司共同运营,ICP 加增值电信许可证齐。免费 2 条隧道、约 12Mbps、1GB,签到加流量;流量单买约 0.5 元/GB,开会员更便宜。支持配置文件启动原版 frpc。
29
+ - 乐青 LoCyanFrp(locyanfrp.cn):杭州樱芸网络科技有限公司,ICP、公安备案加软件著作权齐。公益项目,全免费、不限流量不限速率;V3 已兼容 0.6X 版 frpc 的 TOML 配置。注意它国内节点的 http 请求要求域名备案,IP 加端口会被挡;选国内还是海外节点先按节点规则问清楚。
30
+
31
+ 有域名证书仍走 https 那档,只有 IP 就走裸 TCP,加密的取舍照上面「选哪一档」来,别以为用了运营商就自动加密。导入配置后起不来,先查 frpc 版本和运营商要求对不对得上,别把「填了地址」当成隧道在转发。
32
+
33
+ 资质也正规但跑的不是 frp、咱们 frpc 接不上的,别推:ngrok(免费档还有拦截页)、花生壳(自研协议)、NATAPP(ngrok 二次开发)、神卓互联和 nat123(自有协议)。ChmlFrp 主体是个人工作室、小鸡 FRP 域名已过期且查不到备案,都不算资质过关。
34
+
35
+ 价格和免费额度会变,报之前让对方去官网当前定价页核一眼,别拿这里的数字当报价。
36
+
21
37
  ## 电脑这侧怎么起隧道
22
38
 
23
39
  - 配好 frps(公网服务器)和 frpc(跑 DSH 的电脑),token 两端一致。frpc 的本地端口填插件实际监听的端口,默认 `18787`,改过就以状态里报的实绑端口为准。
@@ -45,6 +61,6 @@
45
61
 
46
62
  ## 什么时候停
47
63
 
48
- - 没公网服务器、又不想养一台:如实说 frp 这条路不适合,可走 IPv6 直连或中转,不写「已修复」。
64
+ - 没公网服务器、又不想养一台:指去上面「没公网服务器:用正规运营商」那节,或走 IPv6 直连、中转;不写「已修复」。
49
65
  - 隧道起了但实测不通、查不出原因:把卡在哪一步(frpc 状态 / 体检口 / 鉴权 / 流式)说清,标「待定位」,别假装查完。
50
66
  - 公网那段要明文的取舍让用户自己拍板,别替他决定降不降级。
@@ -0,0 +1,43 @@
1
+ # 进不去光猫后台、忘了后台密码(自有设备的排查)
2
+
3
+ IPv6 直连要进光猫关防火墙、端口映射要进光猫做映射,都卡在同一件事:用户手上没有能登录后台的管理员密码。运营商定制光猫的密码常被 TR-069 定期轮换,贴纸上的普通账号进不去。这一篇讲怎么在**用户自己的设备**上把这个问题查下去。
4
+
5
+ 主线是**按设备型号、运营商、固件主动上网查当下做法**:光猫型号和固件太多,运营商定制固件还会变,任何现成工具都只覆盖一部分老设备。那个光猫凭据自查工具(`WNLUO/ung220z-tool`)可以试一招,成功最好,不成也不代表没救 —— 换关键词继续查,别拿它失败当结论。拿到密码、改完开关之后怎么验收,回到 `references/ipv6.md` 或 `references/ipv4.md`。
6
+
7
+ ## 先认清自己站哪边
8
+
9
+ - 跑在用户电脑上、有本机 shell、能联网查资料 —— 执行者:自己查型号和指纹、自己上网找做法、自己跑工具试、自己回读确认。
10
+ - 回反馈、够不着用户局域网 —— 指导者:问清型号、运营商和贴纸信息,自己先联网查到做法再说给用户做;请他回报结果,不谎称自己登过后台、跑过工具。
11
+
12
+ ## 开查前先问一句(话要短)
13
+
14
+ 「这台光猫是你自己的吗?什么型号、哪家运营商?」自有设备才往下走;贴纸信息接着问。别上来一大段。
15
+
16
+ ## 先确认能碰
17
+
18
+ 只针对用户**自有设备**:找回自己忘记的密码、迁移自己的宽带配置。用户说不清设备归属、或是别人的光猫、公司/房东的网关 —— 停,不提供提取方法,转「什么时候停」。这是前提,不是走过场的免责声明。
19
+
20
+ ## 按顺序查,别跳
21
+
22
+ 1. **先看贴纸。** 光猫背面 S/N 标签常有「用户名 user / 密码 xxxxxxxx」,先用它试普通后台。运营商定制机常把 Web 普通账号和超级管理员分开,贴纸那组只能进普通页;能进普通页也有用 —— 从页面读固件信息、型号版本。
23
+ 2. **攒齐上网查的素材**:设备完整型号、运营商、固件版本、Web 后台地址和页面标题。能登录普通页就从页面里读;登不上就问用户拍贴纸和后台页。有工具在电脑上时,跑一下家族识别拿指纹:`python3 -m ontkit probe -H <光猫IP>`,它会打印 `Server` 头和页面标题;也可看有没有 `telnet.gch` 接口,返回 404 就不是九联/吉比特那套 `.gch` 固件。
24
+ 3. **主动上网查,这是主线。** 按「型号 + 运营商 + 超级管理 / Telnet / 固件版本」这类词搜,找当前有效的进后台做法:厂商文档、近期的实操贴、运营商定制机的专门教程都看。搜到做法先对一遍型号和固件版本,再用上面攒的指纹核对是不是同一台 / 同一类;老旧教程对新固件多半失效,别照搬。查到的命令先判断风险,不因为「网上这么写」就直接执行,更不要照抄到回复里让用户盲试。换着关键词多查几轮,一次搜不到不算查过。
25
+ 4. **工具只作一次尝试。** 仓库那套对部分老机型有用:UNG220Z 是作者真机验证,其余是公开案例或未验证。按家族试对应入口 —— 九联 / 吉比特 `.gch` 走主脚本,中兴系走 `webFac` 工厂模式,烽火走 `telnetenable.cgi`,华为 ssmp 只做登录并尝试开 Telnet。记下工具打印的指纹行和退出码;不成只说明这一招不适用,回到第 3 步换词继续查,别停在这里。
26
+ 5. **拿到密码后回到原问题。** 进后台关 IPv6 防火墙 / 做端口映射,改完回读确认(见 `references/ipv6.md` 第 4 步)。后台密码只在这次用,用完不留存、不写进任何记录、不在回复里复述。
27
+
28
+ ## 几个坑
29
+
30
+ - 工具不是通用解:新固件接口路径会变,运营商也可能关掉工厂模式;它失败只说明这一招对这台不管用,不是这台设备没救。它覆盖的也只是老设备常见家族,别把某个型号的案例当成通用做法。
31
+ - 上网查别只搜一次:换完整型号、运营商名、固件指纹、「超级管理 / 开 Telnet / 默认超密」几组词轮着来;注意资料发布时间,老教程对新固件常常已经失效。查到的命令先核对型号和风险,别照单全收。
32
+ - Web 登录和 Telnet 是**两套账号库**:Web 密码进不去 Telnet 是常事,工具会依次尝试贴纸账号、超级管理账号、从 Web 页读到的 Telnet 项;用户若知道两者口令不同就提前说。
33
+ - 口令里含 `%` 一类字符时,拼进 URL 会被当成转义、服务器返回 400;工具已处理,手工拼 URL 时别忘了编码。
34
+ - 连续登录失败(通常 3 次)会让设备进入延时校验:**立即停止重试**,静默等 10~30 分钟再说。别一遍遍试把设备锁死。
35
+ - 国内家宽(移动定制的九联、吉比特、中兴为主)和海外差异大:海外运营商租借网关(Comcast、BT、DT 等)常把管理员权限锁死,用户手里只有普通账号,找回密码也改不了防火墙 —— 直接转「什么时候停」。国内也有类似的锁死网关,别把某一台设备的入口当成通用账号密码或通用入口。
36
+ - 光猫重启、TR-069 远程下发之后密码可能又轮换,之前拿到的会失效。
37
+
38
+ ## 什么时候停
39
+
40
+ - 不是用户自有设备、或归属说不清:停,不提供提取方法。
41
+ - 运营商锁死网关、没有管理员权限:如实说这台改不动,转中转或两条内置隧道(直连隧道、点对点隧道);不写「已修复」。
42
+ - 多次失败进了延时校验:停,等 10~30 分钟再试;还不行就请用户提供指纹行和退出码,标「待定位」。
43
+ - 按型号和运营商上网查过多轮、工具也试过仍拿不到:把卡在哪一步、查到什么、指纹和退出码说清,标「待定位」继续找;只说一句「工具不支持」就交回,不算查过。
package/lib/impl.js CHANGED
@@ -1,3 +1,4 @@
1
+ // 2026-11-26:零讯旧隧道落点端口失效时接线层清掉地址,通知 Cloudflare 兜底重新判定顶上。
1
2
  // 2026-11-25:三条线路的本地端口接上回环入口判据;自检结论记入 ingress-guard,状态带出绕开与兜底原因。
2
3
  // 热重载跨代:隧道助手/点对点的父地址取值器改为挂载时缓存,回滚或半装载后不再现读失效 ctx.webServer。
3
4
  // 本次改动:网页版预览的宿主绑定地址随 ctx.webServer.host 传入,老宿主缺省时维持环回行为。
@@ -471,7 +472,7 @@ function apply(ctx) {
471
472
  mount('镜像推送', () => ctx.effect(() => mirror.start(), `${name}: mobile mirror sync`))
472
473
 
473
474
  // ZeroNews 线路:二进制获取、浏览器登录、建隧道与写回都在 wiring/runner/provision,装配层只挂一下。
474
- const zeroNews = mountZeroNews({ mount, settings, getState: () => state, control, warn, ctx, name, portOf: () => tunnelPortFor('zeronews') })
475
+ const zeroNews = mountZeroNews({ mount, settings, getState: () => state, control, warn, ctx, name, portOf: () => tunnelPortFor('zeronews'), onRouteStale: () => cloudflare?.reconcile?.() })
475
476
  // ZeroNews 状态 / 连接 / 断开给面板(见 lib/zeronews/wiring.cjs)。
476
477
 
477
478
  ctx.effect(() => {
@@ -28,6 +28,8 @@ const LOCAL_PORTS = Object.fromEntries(
28
28
  /** /detect/version 是轻量探针,超时短;/bind 要等它去云端换短链,实测 5~16 秒。 */
29
29
  const PROBE_TIMEOUT_MS = 3000;
30
30
  const BIND_TIMEOUT_MS = 30_000;
31
+ /** status 每 3 秒被轮询,判绑定时顺带问 /bind 只用探测级短超时:等不到就按没绑定算,不把用户卡在「已绑定」上。 */
32
+ const BIND_STATUS_TIMEOUT_MS = PROBE_TIMEOUT_MS;
31
33
 
32
34
  function endpointsFor(platform) {
33
35
  const key = String(platform || process.platform);
@@ -85,7 +87,7 @@ async function probePort(port, options = {}) {
85
87
  * @returns {Promise<{ supported: boolean, installed: boolean, bound: boolean, peerid: string,
86
88
  * tun: string, host: string, port: number, service: {installed:boolean}, error: string }>}
87
89
  * `supported=false` 是这一版没接的平台(Windows 只接 x64,Linux 接 x64/arm64);
88
- * `installed=false` 表示本机找不到设备端;`bound=false` 表示装了但还没登录绑定。
90
+ * `installed=false` 表示本机找不到设备端;`bound` 由 /bind 是否仍给链接判定(给链接=没绑)。
89
91
  */
90
92
  async function readStatus(options = {}) {
91
93
  const platform = String(options.platform || process.platform);
@@ -102,10 +104,14 @@ async function readStatus(options = {}) {
102
104
  for (const { host, port } of endpoints) {
103
105
  const result = await probePort(port, { ...options, host });
104
106
  if (result.ok) {
107
+ const bind = await readBindUrl({ ...options, host, port, timeoutMs: BIND_STATUS_TIMEOUT_MS });
108
+ // 是否绑定只看 /bind:仍给链接=没绑;设备端答话却不给链接=已绑;超时或连不上按没绑算,
109
+ // 让面板继续给绑定链接,别把用户卡死在误判的「已绑定」上。
110
+ const bound = bind.ok === false && bind.answered === true;
105
111
  return {
106
112
  supported: true,
107
113
  installed: true,
108
- bound: result.peerid !== '',
114
+ bound,
109
115
  peerid: result.peerid,
110
116
  tun: result.tun,
111
117
  host,
@@ -124,21 +130,23 @@ async function readStatus(options = {}) {
124
130
 
125
131
  /**
126
132
  * 取设备端的绑定链接。设备端回 302 指向它的云端绑定页,把那一段 Location 原样交给面板。
127
- * 已经绑过的设备不会再给链接(它回 404 或直接给已绑页面),这里按 `ok:false` 如实说明。
133
+ * 已经绑过的设备不会再给链接(它回 404 或直接给已绑页面),这里按 `ok:false` 如实说明;
134
+ * 返回的 `answered` 区分「设备端答话但不给链接」(已绑)与「超时/连不上」(无从判断)。
128
135
  * 只给了端口没给主机时,按平台的候选主机逐个问(Windows 要先问它的虚拟回环)。
129
136
  */
130
137
  async function readBindUrl(options = {}) {
131
138
  const doFetch = typeof options.fetchImpl === 'function'
132
139
  ? options.fetchImpl
133
140
  : (typeof globalThis.fetch === 'function' ? globalThis.fetch : null);
134
- if (!doFetch) return { ok: false, url: '', error: '当前环境没有可用的 fetch' };
141
+ if (!doFetch) return { ok: false, url: '', answered: false, error: '当前环境没有可用的 fetch' };
135
142
  const platform = String(options.platform || process.platform);
136
143
  const port = Number(options.port) > 0 ? Number(options.port) : 0;
137
144
  const hosts = typeof options.host === 'string' && options.host ? [options.host] : hostsFor(platform);
138
145
  const endpoints = port ? hosts.map((host) => ({ host, port })) : endpointsFor(platform);
139
- if (!endpoints.length) return { ok: false, url: '', error: '这一版没接这个平台' };
146
+ if (!endpoints.length) return { ok: false, url: '', answered: false, error: '这一版没接这个平台' };
140
147
  const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : BIND_TIMEOUT_MS;
141
148
  let lastError = '';
149
+ let answered = false;
142
150
  for (const { host, port: candidatePort } of endpoints) {
143
151
  const controller = typeof AbortController === 'function' ? new AbortController() : null;
144
152
  const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
@@ -149,10 +157,11 @@ async function readBindUrl(options = {}) {
149
157
  headers: { accept: 'text/html' },
150
158
  ...(controller ? { signal: controller.signal } : {}),
151
159
  });
160
+ answered = true;
152
161
  const location = response && response.headers && typeof response.headers.get === 'function'
153
162
  ? response.headers.get('location') : '';
154
163
  if (typeof location === 'string' && /^https?:\/\//i.test(location.trim())) {
155
- return { ok: true, url: location.trim(), error: '' };
164
+ return { ok: true, url: location.trim(), answered: true, error: '' };
156
165
  }
157
166
  lastError = '设备端没有给出绑定链接(可能已经绑定过)';
158
167
  } catch (error) {
@@ -165,7 +174,7 @@ async function readBindUrl(options = {}) {
165
174
  if (timer) clearTimeout(timer);
166
175
  }
167
176
  }
168
- return { ok: false, url: '', error: lastError };
177
+ return { ok: false, url: '', answered, error: lastError };
169
178
  }
170
179
 
171
180
  /**
@@ -0,0 +1,355 @@
1
+ // 2026-11-26:设备画像核心模块,采集宿主会话/工作区信号、归纳用途、开关与变化检测(插件侧每实例一份)。
2
+ 'use strict';
3
+
4
+ /**
5
+ * 设备画像的源头在电脑插件:一台电脑一份画像,手机只读同步过去的副本。
6
+ *
7
+ * 这个模块只做四件事:把宿主已有的会话/工作区清单折成少量信号(不碰模型),把信号交给
8
+ * 电脑上那把 Key 归纳成一句话,管两个开关,以及在信号真变了时才更新画像。所有磁盘读写
9
+ * 都吞掉失败——画像只是锦上添花的上下文,不该让路由或事件因为它挂掉。
10
+ */
11
+
12
+ const fs = require('node:fs');
13
+ const os = require('node:os');
14
+ const path = require('node:path');
15
+
16
+ const { dshHome } = require('../shared/paths.js');
17
+ const { stableRevision } = require('../shared/list-revision.js');
18
+ const { unwrap } = require('./envelope.js');
19
+ const { callSessions } = require('./rpc.js');
20
+ const { listTitle } = require('./history-derive.js');
21
+ const { customChannelWithKey, PI_AI_NS } = require('./channels.js');
22
+ const { chatCompletionUrlOf } = require('./channel-proxy.js');
23
+ const { deviceProfileRefreshStateOf } = require('./session-cache.js');
24
+
25
+ /** 画像与开关都落在 dshHome 下,固定文件名;与移动端其它插件状态互不干扰。 */
26
+ const PROFILE_FILE = 'mobile-device-profile.json';
27
+ const SWITCHES_FILE = 'mobile-learning-switches.json';
28
+
29
+ /** 工作区与最近会话各留几条:够模型认出这台电脑在干什么,不把整份清单塞进提示词。 */
30
+ const MAX_TITLES = 8;
31
+ /** 事件帧来得很密:最短间隔内只算一次,在途的那一次多方共用。 */
32
+ const REFRESH_MIN_INTERVAL_MS = 60 * 1000;
33
+ /** 归纳请求的上限;归纳卡住不该一直占着请求。 */
34
+ const UPSTREAM_TIMEOUT_MS = 30 * 1000;
35
+ /** 一句话用途的长度兜底。 */
36
+ const NOTE_MAX_CHARS = 400;
37
+
38
+ /** system 提示只许一到两句中文,不解释、不列表——这段文案直接决定画像有没有噪声。 */
39
+ const SYSTEM_PROMPT = '只输出一到两句中文,概括这台电脑的主要用途。不要解释,不要列表,不要引号。';
40
+
41
+ function profileFile() {
42
+ return path.join(dshHome(), PROFILE_FILE);
43
+ }
44
+
45
+ function switchesFile() {
46
+ return path.join(dshHome(), SWITCHES_FILE);
47
+ }
48
+
49
+ function emptyProfile() {
50
+ return { workspaces: [], recentTitles: [], updatedAt: 0, revision: '' };
51
+ }
52
+
53
+ function defaultSwitches() {
54
+ return { passiveEnabled: true, modelEnabled: false };
55
+ }
56
+
57
+ /** 去掉 revision 之后的本体算指纹;键序排一遍,落盘再读回来不会因插入顺序不同而误判成变化。 */
58
+ function makeRevision(profile) {
59
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) return '';
60
+ const body = { ...profile };
61
+ delete body.revision;
62
+ const canonical = {};
63
+ for (const key of Object.keys(body).sort()) canonical[key] = body[key];
64
+ return stableRevision(canonical);
65
+ }
66
+
67
+ /**
68
+ * 读画像:文件不在、读不动、坏了都当没有(null),不把异常交给调用方。
69
+ * 数组字段逐项筛一遍,坏条目不该让整份画像在后面拼接时炸掉。
70
+ */
71
+ function load() {
72
+ try {
73
+ const raw = JSON.parse(fs.readFileSync(profileFile(), 'utf8'));
74
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
75
+ if (!Array.isArray(raw.workspaces) || !Array.isArray(raw.recentTitles)) return null;
76
+ return {
77
+ ...(typeof raw.name === 'string' ? { name: raw.name } : {}),
78
+ ...(typeof raw.platform === 'string' ? { platform: raw.platform } : {}),
79
+ workspaces: raw.workspaces.filter((title) => typeof title === 'string'),
80
+ recentTitles: raw.recentTitles.filter((title) => typeof title === 'string'),
81
+ ...(typeof raw.note === 'string' ? { note: raw.note } : {}),
82
+ updatedAt: Number.isFinite(raw.updatedAt) ? raw.updatedAt : 0,
83
+ revision: typeof raw.revision === 'string' ? raw.revision : '',
84
+ };
85
+ } catch {
86
+ return null;
87
+ }
88
+ }
89
+
90
+ /** 原子写:同目录临时文件 + rename,写一半断电也不会留下半份 JSON。写不进去就吞掉。 */
91
+ async function save(profile) {
92
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) return;
93
+ try {
94
+ const file = profileFile();
95
+ fs.mkdirSync(path.dirname(file), { recursive: true });
96
+ const tmp = `${file}.${process.pid}.tmp`;
97
+ fs.writeFileSync(tmp, `${JSON.stringify(profile)}\n`, { mode: 0o600 });
98
+ fs.renameSync(tmp, file);
99
+ } catch {
100
+ /* 画像写不进去不影响这次请求 */
101
+ }
102
+ }
103
+
104
+ /**
105
+ * 采集宿主信号,一步一 try:哪扇门不可用就少那一项,其余照常返回。
106
+ * 只用宿主已有的 sessions.list / workspace.list,不查模型、不发额度请求。
107
+ */
108
+ async function collect(ctx) {
109
+ const out = {};
110
+
111
+ try {
112
+ const name = typeof os.hostname === 'function' ? os.hostname() : '';
113
+ if (typeof name === 'string' && name.trim()) out.name = name.trim();
114
+ } catch { /* 设备名拿不到就少这一项 */ }
115
+
116
+ try {
117
+ if (typeof process.platform === 'string' && process.platform) out.platform = process.platform;
118
+ } catch { /* 系统标识拿不到就少这一项 */ }
119
+
120
+ try {
121
+ const { value, error } = unwrap(await ctx.apiProxy.workspace.list({
122
+ rpcId: 'mobile', method: 'workspace.list', payload: {},
123
+ }));
124
+ if (!error) {
125
+ const items = Array.isArray(value) ? value : (value && Array.isArray(value.items) ? value.items : []);
126
+ out.workspaces = items
127
+ .map((item) => (item && typeof item.title === 'string' ? item.title.trim() : ''))
128
+ .filter(Boolean)
129
+ .slice(0, MAX_TITLES);
130
+ }
131
+ } catch { /* 工作区清单失败只少这一项 */ }
132
+
133
+ try {
134
+ const { value, error } = unwrap(await callSessions(ctx, 'list', {}));
135
+ if (!error) {
136
+ const items = Array.isArray(value) ? value : (value && Array.isArray(value.items) ? value.items : []);
137
+ out.recentTitles = items
138
+ .map((item) => listTitle(item))
139
+ .filter((title) => typeof title === 'string' && title.trim())
140
+ .slice(0, MAX_TITLES)
141
+ .map((title) => title.trim());
142
+ }
143
+ } catch { /* 会话清单失败只少这一项 */ }
144
+
145
+ return out;
146
+ }
147
+
148
+ /**
149
+ * 读开关。被动采集默认开、花额度的归纳默认关;读坏一律回默认值,不抛。
150
+ */
151
+ function getSwitches() {
152
+ const defaults = defaultSwitches();
153
+ try {
154
+ const raw = JSON.parse(fs.readFileSync(switchesFile(), 'utf8'));
155
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return defaults;
156
+ return {
157
+ passiveEnabled: typeof raw.passiveEnabled === 'boolean' ? raw.passiveEnabled : defaults.passiveEnabled,
158
+ modelEnabled: typeof raw.modelEnabled === 'boolean' ? raw.modelEnabled : defaults.modelEnabled,
159
+ };
160
+ } catch {
161
+ return defaults;
162
+ }
163
+ }
164
+
165
+ /** 写开关:只认两个布尔,其余键不落盘;读坏或写不动都不抛给调用方。 */
166
+ function setSwitches(next) {
167
+ const current = getSwitches();
168
+ const merged = {
169
+ passiveEnabled: next && typeof next.passiveEnabled === 'boolean' ? next.passiveEnabled : current.passiveEnabled,
170
+ modelEnabled: next && typeof next.modelEnabled === 'boolean' ? next.modelEnabled : current.modelEnabled,
171
+ };
172
+ try {
173
+ const file = switchesFile();
174
+ fs.mkdirSync(path.dirname(file), { recursive: true });
175
+ const tmp = `${file}.${process.pid}.tmp`;
176
+ fs.writeFileSync(tmp, `${JSON.stringify(merged, null, 2)}\n`, { mode: 0o600 });
177
+ fs.renameSync(tmp, file);
178
+ } catch {
179
+ /* 开关写不进去不抛;下一次读仍是磁盘上的真值 */
180
+ }
181
+ return merged;
182
+ }
183
+
184
+ /**
185
+ * 电脑上第一条可用的自建渠道。只认 llm-pi-ai 的 providers —— customChannelWithKey 也只认
186
+ * 这一处,挑别的 id 只会换来 channel-not-found。这里有地址就算可用,模型由调用方指定或
187
+ * 取这条渠道的第一个。
188
+ */
189
+ async function firstCustomChannelId(ctx) {
190
+ const described = unwrap(await ctx.apiProxy.settings.describe({
191
+ rpcId: 'mobile', method: 'settings.describe', payload: {},
192
+ }));
193
+ if (described.error) return '';
194
+ const namespaces = Array.isArray(described.value && described.value.namespaces) ? described.value.namespaces : [];
195
+ const piAi = namespaces.find((entry) => entry && entry.ns === PI_AI_NS);
196
+ const value = piAi && piAi.value;
197
+ const providers = value && typeof value === 'object' && value.providers
198
+ && typeof value.providers === 'object' && !Array.isArray(value.providers) ? value.providers : {};
199
+ for (const id of Object.keys(providers)) {
200
+ const row = providers[id];
201
+ if (row && typeof row === 'object' && typeof row.baseURL === 'string' && row.baseURL.trim()) return id;
202
+ }
203
+ return '';
204
+ }
205
+
206
+ function titlesLine(values, fallback) {
207
+ const source = Array.isArray(values) ? values : fallback;
208
+ return source.filter((title) => typeof title === 'string' && title.trim()).slice(0, MAX_TITLES).join('、') || '无';
209
+ }
210
+
211
+ /**
212
+ * 归纳一句话用途。额度闸在最前面:关着时连宿主都不问,更不发请求。
213
+ * 渠道与 Key 都取自电脑自己那一份(customChannelWithKey),Key 只放进这一发请求头,
214
+ * 不回包、不落盘。任何失败都只用契约里的三个错误码。
215
+ */
216
+ async function summarize(ctx, options = {}) {
217
+ if (getSwitches().modelEnabled !== true) return { ok: false, errorCode: 'learning-disabled' };
218
+
219
+ let found = null;
220
+ try {
221
+ const requested = typeof options.channelId === 'string' ? options.channelId.trim() : '';
222
+ const id = requested || await firstCustomChannelId(ctx);
223
+ if (!id) return { ok: false, errorCode: 'no-channel' };
224
+ found = await customChannelWithKey(ctx, id);
225
+ } catch {
226
+ return { ok: false, errorCode: 'no-channel' };
227
+ }
228
+ if (!found || found.error || !found.channel || !chatCompletionUrlOf(found.channel.baseUrl)) {
229
+ return { ok: false, errorCode: 'no-channel' };
230
+ }
231
+
232
+ const supplied = typeof options.model === 'string' ? options.model : '';
233
+ const first = Array.isArray(found.channel.models) && found.channel.models[0]
234
+ ? found.channel.models[0].id : '';
235
+ const model = (typeof supplied === 'string' && supplied.trim()) || (typeof first === 'string' ? first.trim() : '');
236
+ if (!model) return { ok: false, errorCode: 'summary-failed' };
237
+
238
+ const profile = load() || emptyProfile();
239
+ let signals = {};
240
+ try {
241
+ signals = await collect(ctx);
242
+ } catch {
243
+ signals = {};
244
+ }
245
+ const userContent = [
246
+ '以下是这台电脑的已知信号,请据此归纳它的一到两句用途。',
247
+ `设备名:${signals.name || profile.name || '未知'}`,
248
+ `系统:${signals.platform || profile.platform || '未知'}`,
249
+ `工作区:${titlesLine(signals.workspaces || profile.workspaces, [])}`,
250
+ `最近会话:${titlesLine(signals.recentTitles || profile.recentTitles, [])}`,
251
+ ...(profile.note ? [`上一版用途:${profile.note}`] : []),
252
+ ].join('\n');
253
+
254
+ const controller = new AbortController();
255
+ const timer = setTimeout(() => controller.abort(), UPSTREAM_TIMEOUT_MS);
256
+ try {
257
+ const response = await fetch(chatCompletionUrlOf(found.channel.baseUrl), {
258
+ method: 'POST',
259
+ signal: controller.signal,
260
+ headers: {
261
+ 'content-type': 'application/json',
262
+ ...(found.apiKey ? { authorization: `Bearer ${found.apiKey}` } : {}),
263
+ },
264
+ body: JSON.stringify({
265
+ model,
266
+ stream: false,
267
+ messages: [
268
+ { role: 'system', content: SYSTEM_PROMPT },
269
+ { role: 'user', content: userContent },
270
+ ],
271
+ max_tokens: 120,
272
+ }),
273
+ });
274
+ if (!response || !response.ok) return { ok: false, errorCode: 'summary-failed' };
275
+ const data = await response.json();
276
+ const choices = data && Array.isArray(data.choices) ? data.choices : [];
277
+ const message = choices[0] && choices[0].message;
278
+ let content = message ? message.content : '';
279
+ if (Array.isArray(content)) {
280
+ content = content.map((part) => (part && typeof part.text === 'string' ? part.text : '')).join('');
281
+ }
282
+ if (typeof content !== 'string') return { ok: false, errorCode: 'summary-failed' };
283
+ const note = content.trim().replace(/\s+/g, ' ').slice(0, NOTE_MAX_CHARS);
284
+ if (!note) return { ok: false, errorCode: 'summary-failed' };
285
+ return { ok: true, note };
286
+ } catch {
287
+ return { ok: false, errorCode: 'summary-failed' };
288
+ } finally {
289
+ clearTimeout(timer);
290
+ }
291
+ }
292
+
293
+ /**
294
+ * 变化检测:每 60 秒最多问一次宿主,在途的那一次多方合并。
295
+ * 用「保留旧 updatedAt 的候选」算指纹再比,空转时指纹不变就不写盘、不回 true;
296
+ * 真变了才改 updatedAt 并重算指纹,配合 makeRevision 的口径(指纹只盖本体)。
297
+ */
298
+ const fallbackRefreshState = { lastAt: 0, inFlight: null };
299
+
300
+ function refreshStateOf(ctx) {
301
+ if (!ctx || (typeof ctx !== 'object' && typeof ctx !== 'function')) return fallbackRefreshState;
302
+ return deviceProfileRefreshStateOf(ctx);
303
+ }
304
+
305
+ async function refreshIfChanged(ctx) {
306
+ const state = refreshStateOf(ctx);
307
+ if (state.inFlight) return state.inFlight;
308
+
309
+ const now = Date.now();
310
+ if (now - state.lastAt < REFRESH_MIN_INTERVAL_MS) return false;
311
+ state.lastAt = now;
312
+
313
+ const task = (async () => {
314
+ const existing = load();
315
+ const base = existing || emptyProfile();
316
+ let signals = {};
317
+ try {
318
+ signals = await collect(ctx);
319
+ } catch {
320
+ signals = {};
321
+ }
322
+ const candidate = {
323
+ ...base,
324
+ ...signals,
325
+ workspaces: Array.isArray(signals.workspaces) ? signals.workspaces : base.workspaces,
326
+ recentTitles: Array.isArray(signals.recentTitles) ? signals.recentTitles : base.recentTitles,
327
+ updatedAt: base.updatedAt,
328
+ };
329
+ const seen = makeRevision(candidate);
330
+ if (seen && seen === base.revision) return false;
331
+
332
+ const next = { ...candidate, updatedAt: Date.now() };
333
+ next.revision = makeRevision(next);
334
+ await save(next);
335
+ return true;
336
+ })();
337
+
338
+ state.inFlight = task;
339
+ try {
340
+ return await task;
341
+ } finally {
342
+ if (state.inFlight === task) state.inFlight = null;
343
+ }
344
+ }
345
+
346
+ module.exports = {
347
+ load,
348
+ save,
349
+ collect,
350
+ makeRevision,
351
+ summarize,
352
+ getSwitches,
353
+ setSwitches,
354
+ refreshIfChanged,
355
+ };
@@ -1,3 +1,4 @@
1
+ // 2026-11-26:会话/工作区变化帧顺带刷新本机画像,revision 真变才推 device/profile-changed。
1
2
  // 清单事件同时识别 event.type 与 event.data.type,正文仍只走会话流。
2
3
  // 转发设备事件,并按已鉴权实例登记可吊销的 SSE 连接。
3
4
  /**
@@ -15,6 +16,8 @@
15
16
  'use strict';
16
17
 
17
18
  const streamRegistry = require('./stream-registry.js');
19
+ // 画像采集调度(refreshIfChanged 自带节流与 in-flight 合并;导出签名见契约 A 块)。
20
+ const deviceProfile = require('./device-profile.js');
18
21
  const { createFrameSealer } = require('./stream.js');
19
22
  const { listSignal: sharedListSignal } = require('../shared/list-signal.js');
20
23
  const { sessionSignal: sharedSessionSignal } = require('../shared/session-signal.js');
@@ -104,6 +107,18 @@ function lightPayload(payload) {
104
107
  // irrelevant to the sidebar and are the bulk of the flood whenever any session
105
108
  // is generating; they belong to the per-session /session/stream instead.
106
109
  const LIST_EVENT_INNER = new Set(['turn/start', 'turn/end', 'session/title', 'session/disposed']);
110
+
111
+ /**
112
+ * 只有会话 / 工作区**清单**变化才动画像(recentTitles / workspaces):
113
+ * 清单变更走 session/summary,工作区变更走 host/workspace。
114
+ * session/event 的 turn/title/disposed 是单会话的正文水位信号,清单 revision 本来就会跟着变,
115
+ * 不在这里重复触发 —— 否则正文那种高频帧会把这条只推 revision 的信号一起带热。
116
+ */
117
+ function isProfileRelevantPayload(payload) {
118
+ if (!payload || typeof payload !== 'object') return false;
119
+ return payload.type === 'host/workspace' || payload.type === 'session/summary';
120
+ }
121
+
107
122
  function listRelevantPayload(rawPayload) {
108
123
  if (!rawPayload || typeof rawPayload !== 'object') return null;
109
124
  const type = rawPayload.type;
@@ -291,6 +306,17 @@ async function handleDeviceStream(ctx, req, res) {
291
306
  // 才收尾。
292
307
  if (sent.needDrain && !(await waitForDrain(res, ac.signal))) { clientGone = true; break; }
293
308
  framesSent += 1;
309
+ // 画像信号:refreshIfChanged 自带最小间隔与 in-flight 合并,返回 true 才是 revision 真变。
310
+ // 只推 type / revision / at 三个字段,不推画像内容;现有去重窗口与心跳都不改。
311
+ if (isProfileRelevantPayload(payload)) {
312
+ let changed = false;
313
+ try { changed = await deviceProfile.refreshIfChanged(ctx); } catch { /* 采集失败不掐断 SSE */ }
314
+ if (changed && !ac.signal.aborted) {
315
+ let revision = '';
316
+ try { revision = (deviceProfile.load() || {}).revision || ''; } catch { /* 读不到回空 revision */ }
317
+ if (!writeFrame({ type: 'device/profile-changed', revision, at: Date.now() })) ac.abort();
318
+ }
319
+ }
294
320
  }
295
321
  if (!clientGone) loopEnded = true;
296
322
  } catch (error) {
@@ -1,4 +1,5 @@
1
1
  // 用途:插件反馈统一提交、读取与轮询等回复口;工具和本机面板按线程查看官方回复、继续跟进。
2
+ // 自检 / 探针文案不进真人反馈队列:submit 只收真实问题的现象描述。
2
3
  'use strict';
3
4
 
4
5
  /**
@@ -41,6 +42,17 @@ const ATTACHMENT_NAME = 'diagnosis.txt';
41
42
  const CONTENT_MAX = 4000;
42
43
  /** 带一份小文本附件,30 秒足够。 */
43
44
  const SUBMIT_TIMEOUT_MS = 30_000;
45
+ /** 带这些自报标记的正文是连通性自检,不是用户或 AI 观察到的现象。 */
46
+ const SELF_TEST_MARKERS = [
47
+ /勿人工处理/i,
48
+ /自动化测试用/i,
49
+ /连接诊断探针/i,
50
+ /probe from desktop/i,
51
+ ];
52
+ function isSelfTestContent(content) {
53
+ return SELF_TEST_MARKERS.some((pattern) => pattern.test(content));
54
+ }
55
+
44
56
  /** 明确指定设备、但包名读不到时的兜底;没有设备时这一格留空。 */
45
57
  const DEFAULT_PACKAGE_ID = 'com.dsh.mobile';
46
58
 
@@ -227,6 +239,9 @@ async function submitFeedback(deps, content, threadKey, deviceId, options = {})
227
239
  content = typeof content === 'string' ? content.trim() : '';
228
240
  if (!content) throw Object.assign(new Error('submit 需要 content'), { status: 400 });
229
241
  if (content.length > CONTENT_MAX) throw Object.assign(new Error(`content 超长(上限 ${CONTENT_MAX} 字)`), { status: 400 });
242
+ if (isSelfTestContent(content)) {
243
+ throw Object.assign(new Error('自检 / 探针内容不要提交到真人反馈队列;用 channels 查看反馈通道'), { status: 400 });
244
+ }
230
245
  const id = typeof deps && typeof deps.instanceId === 'function' ? deps.instanceId() : '';
231
246
  const devices = deps && deps.credentials && typeof deps.credentials.listDevices === 'function'
232
247
  ? deps.credentials.listDevices(id)
@@ -276,6 +291,7 @@ function registerFeedbackTool(ctx, deps) {
276
291
  ctx.tools.register(defineTool({
277
292
  name: 'dsh_feedback',
278
293
  description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
294
+ + 'Do not use `submit` for connectivity tests or automated probes: those are not real problems and must not enter the human feedback queue; use `channels` to inspect the route instead. '
279
295
  + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. After `submit`, call `watch` with the returned threadKey: it checks the existing feedback endpoint every two seconds for the first official reply, for at most two minutes, then stops with a hint to use `read`. It is polling, not a live stream. Use `read` with the thread key only when you need to review the conversation history, and `submit` with the same threadKey to follow up. The local feedback dialog can show these threads; they are not written into the in-app feedback list. '
280
296
  + '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
281
297
  + 'Use `channels` to list both routes.',