@marktrue/dsh-mobile-remote 3.2.4-rc.5 → 3.2.4-rc.6
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.
- package/CHANGELOG.md +77 -0
- package/docs/03-api.md +8 -2
- package/docs/04-security.md +1 -1
- package/docs/09-compatibility.md +1 -1
- package/lib/index.js +444 -53
- package/lib/sse-connections.js +172 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,82 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## v3.2.4-rc.6(build 59,issues #124 #126 #128 #129 #130 #131 #132 #135)— 对话页高度模型重做、加载态与 SSE 修复
|
|
4
|
+
|
|
5
|
+
> 插件 `3.2.4-rc.6` / App `3.2.4+59` / 载体 `3.2.4-rc.6-app`。RC 候选:插件发布到 npm `rc` dist-tag,`latest` 保持 `3.2.3-rc.1` 不动(只有 stable 可前进)。
|
|
6
|
+
|
|
7
|
+
### 中文
|
|
8
|
+
|
|
9
|
+
#### 新增与体验改进
|
|
10
|
+
|
|
11
|
+
- **首次打开会话三态加载(#129)**:聊天页首次加载明确区分 loading / empty / failed;失败可重试,实时流式内容到达后不再误判为空态。
|
|
12
|
+
- **上翻历史加载状态行(#130)**:上翻历史时在顶部以固定高度状态行展示 loading / 已加载 / 空 / 失败四态,失败可重试,不挤压聊天内容。
|
|
13
|
+
- **长用户消息查看全文(#132)**:超过 2000 字符的用户消息把「查看全文」入口移入气泡内;按需加载详情并显式区分已加载 / 失败,不再伪造成功。
|
|
14
|
+
- **子代理运行指示(#124)**:主会话列表聚合递归子代理运行状态,子代理未结束时主会话持续显示运行中;断链或切换宿主会清空旧宿主计数,避免假运行状态。
|
|
15
|
+
- **环境诊断中文化(#135)**:诊断页的指标、服务、端点与状态值按白名单中文化,不再出现重复或裸露英文 key;新增 SSE 指标 `mobileOldestAgeMs` / `mobileOldestIdleMs` / `mobileStalled` / `mobileEvicted` / `mobileRejected` 也有中文名。
|
|
16
|
+
|
|
17
|
+
#### 修复
|
|
18
|
+
|
|
19
|
+
- **对话页高度模型重做(ADR 0035,#126/#103/#114)**:短内容顶对齐,删除 `_liveBottomGap` 底部占位及其反馈环;折叠行固定 24dp,过程组 body 上限 `min(400dp, 50% 窗口)`,工具/思考/用户消息正文上限 320dp,图片单张 320dp、网格上限 `min(400dp, 50%)`;删除活动条与自动详情,思考状态落到段摘要/组抬头/provisional 行;gutter 恒定 38dp。修复分批隐藏行场景下内容被推离顶部、上下方大段空白和滚动越界等真机问题。
|
|
20
|
+
- **首屏补拉最新轮(#126)**:初始 50 条若截断最新一轮(缺 `turn/start`),自动补拉 30 条/页、最多 5 页,直到拿到最新轮起止或用户上翻;不按视口高度补拉,避免首屏跳动。
|
|
21
|
+
- **移除聊天页后台任务内联卡(#128)**:后台任务不再在聊天页占一张卡,也不再因卡片显隐触发视口跳变;取消入口统一到「会话工具 → 任务」页签,运行中可取消、停止中不可重复取消;任务面板重试会清除旧错误。
|
|
22
|
+
- **SSE 连接泄漏与 503(#131)**:App 端每次 SSE 使用独立 `http.Client`,在取消/超时/错误/503/正常结束路径显式关闭,503 使用 5s/10s 退避;宿主端满额时不再直接 503,按「stalled 优先 → 同 clientId → 同 clientIp → 最旧」驱逐 1 条满龄(≥60s)连接,无候选才返回 503 + `Retry-After: 5`;诊断新增连接年龄/空闲/stalled/驱逐/拒绝指标。
|
|
23
|
+
- **原生 SSE 版本与生命周期(#131)**:悬浮球原生 SSE 上报 `x-mobile-app-version` 与持久化 `x-mobile-client-id`,同一服务实例只启动一条 SSE 线程;连接建立、读取、异常与 onDestroy 均保证 `disconnect` 并清理 `sseConn`。
|
|
24
|
+
- **导航回归测试**:补「点第 N 轮刻度后高亮必须落在第 N 轮」用例,锁定既有阅读线对齐行为。
|
|
25
|
+
|
|
26
|
+
#### 验证
|
|
27
|
+
|
|
28
|
+
- Flutter analyze:0 error / 0 warning(26 info,与 develop 基线同类)
|
|
29
|
+
- Flutter test:**1640 通过 / 1 skip**
|
|
30
|
+
- Node 套件:1239 例,1218 通过 / 17 skip / **4 失败**——4 项均为本机 root 环境既有问题(`chmod 0500` 在 root 下失效 ×2、`host-canary-smoke` source identity、`ANDROID_HOME` 下 aapt 存在却执行失败);已与 rc.5 基线(`1e8658a`)同环境对照,失败集合逐条相同
|
|
31
|
+
- timeline-contract:181 PASS / 0 FAIL
|
|
32
|
+
- account-usage:15 通过 / 0 失败
|
|
33
|
+
- Kotlin `UsagePanelModelTest`:BUILD SUCCESSFUL(27 用例,`--rerun-tasks` 强制重跑)
|
|
34
|
+
- 受影响测试:Flutter 29 个改动测试文件 323 通过;Node `issue131-sse-connections` / `sse-connections` / `session-list-running-indicator` 56 通过
|
|
35
|
+
|
|
36
|
+
#### 重要说明与已知风险
|
|
37
|
+
|
|
38
|
+
- **未包含 3080 代理泄漏修复**:该修复在 `nas-dsh-migration` 镜像,不属于 rc.6。
|
|
39
|
+
- **build 59 小于本机测试 build 61**:已安装本地测试 build 61 的设备安装 rc.6 会被系统视为降级;如无法安装/被拒,需卸载后重装或等待 build ≥61 的版本。不通过手改 build 规避。
|
|
40
|
+
- **#136 日志级别尚未实现**:本版仅临时注释 Chat.geo / build itemCount / 跟随校正三类脱底排障日志以降低噪声,待 #136 实现后恢复为 debug 级别。
|
|
41
|
+
- **真机未复验**:高度模型与原生 SSE 修复需在 rc.6 真机确认;本版验证为 widget/单测 + 真实代码路径回放。
|
|
42
|
+
|
|
43
|
+
### English
|
|
44
|
+
|
|
45
|
+
#### Added & improved
|
|
46
|
+
|
|
47
|
+
- **First-open three-state loading (#129)**: the chat page now distinguishes loading, empty, and failed states on first open. Failures are retryable, and live-streamed content no longer gets misclassified as an empty state.
|
|
48
|
+
- **History-paging status row (#130)**: paging back through history now shows a fixed-height status row with loading / loaded / empty / failed states and a retry action, without squeezing the conversation.
|
|
49
|
+
- **View full text for long user messages (#132)**: messages over 2000 characters get a “view full text” entry inside the bubble; details load on demand and explicitly distinguish loaded vs failed instead of faking success.
|
|
50
|
+
- **Subagent running indicator (#124)**: the recent-session list aggregates recursive subagent activity, so a session keeps showing as running while any descendant subagent is still active. Disconnects or host switches clear stale counts from the previous host.
|
|
51
|
+
- **Localized environment diagnostics (#135)**: diagnostic metrics, services, endpoint checks, and status values now use human-readable Chinese labels instead of duplicated or bare English keys. The new SSE metrics (`mobileOldestAgeMs`, `mobileOldestIdleMs`, `mobileStalled`, `mobileEvicted`, `mobileRejected`) are covered too.
|
|
52
|
+
|
|
53
|
+
#### Fixed
|
|
54
|
+
|
|
55
|
+
- **Transcript height model rework (ADR 0035, #126/#103/#114)**: short content is now top-aligned and the `_liveBottomGap` bottom placeholder (and its feedback loop) is removed. Collapsed rows are fixed at 24dp; process-group bodies are capped at `min(400dp, 50% of the window)`; tool, reasoning, and user-message bodies are capped at 320dp; images are 320dp each with grids capped at `min(400dp, 50%)`. The activity bar and auto-expanded details are gone; reasoning state now lives in segment summaries, group headers, and provisional rows; gutter is a constant 38dp. This fixes content being pushed off the top, large blank areas above/below the batch-hidden process block, and scroll-range overshoot on real devices.
|
|
56
|
+
- **First-screen backfill of the latest turn (#126)**: if the initial 50 events cut off the latest turn (missing `turn/start`), the app now backfills 30 events per page for up to 5 pages, stopping at the latest turn start, at the end of history, or when the user scrolls up. It does not backfill by viewport height, avoiding first-screen jumps.
|
|
57
|
+
- **Removed the in-chat background-job card (#128)**: background jobs no longer occupy an inline card in the chat or trigger viewport jumps when the card appears/disappears. Cancellation is centralized in “Session tools → Jobs”; running jobs can be cancelled, stopping jobs cannot be cancelled twice, and retrying the jobs panel clears previous errors.
|
|
58
|
+
- **SSE connection leaks and 503 (#131)**: the app now opens a dedicated `http.Client` per SSE connection and explicitly closes it on cancel/timeout/error/503/normal end; 503 responses use 5s/10s backoff. On the host, a full pool no longer returns 503 immediately: it evicts one age-eligible (≥60s) connection ordered by “stalled first → same clientId → same clientIp → oldest”, and only returns 503 + `Retry-After: 5` when no candidate exists. Diagnostics now expose connection age/idle/stalled/evicted/rejected metrics.
|
|
59
|
+
- **Native SSE version and lifecycle (#131)**: the floating-bubble native SSE now sends `x-mobile-app-version` and a persistent `x-mobile-client-id`, starts at most one SSE thread per service instance, and guarantees `disconnect()` plus `sseConn` cleanup on setup, read, exception, and onDestroy paths.
|
|
60
|
+
- **Navigation regression coverage**: added a test asserting that tapping turn tick N highlights turn N, locking the existing reading-line alignment behavior.
|
|
61
|
+
|
|
62
|
+
#### Verification
|
|
63
|
+
|
|
64
|
+
- Flutter analyze: 0 errors / 0 warnings (26 infos, same class as the develop baseline)
|
|
65
|
+
- Flutter test: **1640 passed / 1 skipped**
|
|
66
|
+
- Node suite: 1239 tests, 1218 passed / 17 skipped / **4 failed** — all four are pre-existing local root-environment issues (two `chmod 0500` cases that root bypasses, `host-canary-smoke` source identity, and aapt present under `ANDROID_HOME` but failing to execute). Re-ran the same set against the rc.5 baseline (`1e8658a`) in the same environment: identical failure set, item by item.
|
|
67
|
+
- timeline-contract: 181 PASS / 0 FAIL
|
|
68
|
+
- account-usage: 15 passed / 0 failed
|
|
69
|
+
- Kotlin `UsagePanelModelTest`: BUILD SUCCESSFUL (27 cases, forced rerun with `--rerun-tasks`)
|
|
70
|
+
- Affected tests: 323 passed across the 29 changed Flutter test files; 56 passed in the Node `issue131-sse-connections` / `sse-connections` / `session-list-running-indicator` files
|
|
71
|
+
|
|
72
|
+
#### Important notes & known risks
|
|
73
|
+
|
|
74
|
+
- **The 3080 proxy-leak fix is not included**: that fix lives in the `nas-dsh-migration` image and is not part of rc.6.
|
|
75
|
+
- **Build 59 is lower than local test build 61**: devices with local test build 61 installed will treat rc.6 as a downgrade. If installation is rejected, uninstall/reinstall or wait for a build ≥61. Do not hand-edit the build number to work around this.
|
|
76
|
+
- **Log levels (#136) are not implemented yet**: this release only comments out three noisy transcript-debug log groups (Chat.geo / build itemCount / follow correction) until #136 lands; they should return as debug-level logs then.
|
|
77
|
+
- **Not re-verified on a real device**: the height model and native SSE fixes need on-device confirmation; this release was verified with widget/unit tests plus real code-path replay.
|
|
78
|
+
|
|
79
|
+
|
|
3
80
|
## v3.2.4-rc.5(build 58,真机 59aaa367)— 分批隐藏行导致的底部空白修复
|
|
4
81
|
|
|
5
82
|
> 插件 `3.2.4-rc.5` / App `3.2.4+58` / 载体 `3.2.4-rc.5-app`。RC 候选:插件发布到 npm `rc` dist-tag,`latest` 保持 `3.2.3-rc.1` 不动(只有 stable 可前进)。
|
package/docs/03-api.md
CHANGED
|
@@ -187,7 +187,8 @@
|
|
|
187
187
|
"lastActivity": 1750000123456,
|
|
188
188
|
"lastMessageAt": 1750000111000,
|
|
189
189
|
"origin": "subagent",
|
|
190
|
-
"parentSession": "session-parent"
|
|
190
|
+
"parentSession": "session-parent",
|
|
191
|
+
"subagentsRunning": true
|
|
191
192
|
}
|
|
192
193
|
]
|
|
193
194
|
}
|
|
@@ -207,6 +208,7 @@
|
|
|
207
208
|
- `lastMessageAt`(规划中,可选):最近一条用户/助手可见对话消息的时间(ms);无记录时为 `null`。打开会话不更新,工具活动与生命周期事件也不更新。字段缺失或为 `null` 时,客户端回退 `lastActivity`、再回退 `createdAt`,不提示降级;这项兼容回退不保证打开/内部事件后顺序始终不变。
|
|
208
209
|
- `origin`(规划中,可选):会话来源,子代理会话为 `"subagent"`;其余会话不返回。客户端据此隐藏子代理会话;字段缺失即不过滤。
|
|
209
210
|
- `parentSession`(规划中,可选):派生来源会话 id,为将来"折叠到父会话"预留。**不得**用它判定子代理会话——用户主动 fork 的会话只有该字段而没有 `origin`。
|
|
211
|
+
- `subagentsRunning`(int,**始终下发,0 也表示无**;issue #124/#133):该会话下**递归**运行中的子代理 descendant 数(不含根自身)。服务端用**空会话过滤前**的原始会话 header 建 `origin=subagent → parentSession` 父子映射,再对 `agents.list()` 中 `status=running` 的子代理一次反向计数到各层祖先,**不**逐会话调用 `/subagents` 或 `listDescendants`(88 会话也只读一次 agent 列表)。用户 fork(只有 `parentSession`、无 `origin`)不计入。客户端优先用 SSE 帧的 `subagentsRunning`,其次本字段,缺失时才按本地树递归聚合——三路取并集,不互相门控。
|
|
210
212
|
|
|
211
213
|
### 3.4 归档 / 活跃时间接口
|
|
212
214
|
|
|
@@ -280,6 +282,8 @@
|
|
|
280
282
|
|
|
281
283
|
**规范化正文(`text`)**:`assistant/message` 的详情响应额外附 `data.text`,由服务端用**与事件摘要同一个 `blocksToText`** 提取(只拼 `type == "text"` 的块,跳过 `reasoning` 与内部块),因此与摘要下发的 `text` 同源同规则。客户端必须直接采用该字段作为正文,**不得自行递归拼接 `message.content`**——那会把 `reasoning` 块并进正文,使思维链在折叠块之外重复出现(issue #1 需求变更记录)。`tool/result` 等其它类型的详情仍以原始事件载荷为准;原始 `message` 块原样保留。
|
|
282
284
|
|
|
285
|
+
**长用户消息与完整思考(issue #126 / ADR 0035)**:`user/message` 的详情响应额外附 `data.text`(同一 `blocksToText`,`imagePlaceholder:false`),客户端在摘要 2000 字截断时用它补齐长用户消息。`assistant/message` 的详情响应额外附 `data.reasoning`(完整思维链,与摘要同一 `reasoningText` 口径);摘要的 `reasoning` 在 20000 字处截断时,客户端在用户首次展开思考行时用它补齐。两者都受单事件详情 8 MiB 上限约束;客户端渲染前仍按 20000 字上限裁剪并明确提示。
|
|
286
|
+
|
|
283
287
|
### 3.6 GET /m/api/events(SSE)
|
|
284
288
|
`Content-Type: text/event-stream`。帧格式(`data:` 单行 JSON):
|
|
285
289
|
|
|
@@ -307,6 +311,8 @@
|
|
|
307
311
|
**控制帧**:连接建立后立即 `data: {"type":"hello","serverTime":...,"capabilities":{"eventTimeline":{...},"turnOutline":{...}}}`;每 25s `: ping` 注释行。bootstrap 同样返回这两项能力;`turnOutline` 与 bootstrap 同判据、同形状(见 §6.18),客户端应按能力协商而不是按版本号猜测。
|
|
308
312
|
**错误语义**:鉴权失败在连接建立阶段以 `401` HTTP 状态返回(EventSource 会触发 error 事件,客户端转登录态)。
|
|
309
313
|
|
|
314
|
+
**容量与满龄连接驱逐(启发式,issue #131)**:`connections.size >= maxConnections` 时不再直接 `503 too-many-connections`。宿主按「**stalled 优先** → 同 `clientId`(若请求头 `x-mobile-client-id` 带)→ 同来源 IP → 全局最旧」排序,只驱逐 **1 条年龄 ≥ `sseEvictMinAgeMs`(默认 60000ms)** 的满龄候选;没有达标候选才返回 `503`(body 带 `mobileOnline` / `maxConnections` / `oldestAgeMs` / `maxIdleMs` / `evictMinAgeMs`,并带 `Retry-After: 5`)。被驱逐的客户端按既有 SSE 重连逻辑自动回来并用 `/history` 补拉;年龄阈值用于保护多设备与重连风暴,绝不通过调大 `maxConnections` 掩盖泄漏。`GET /m/api/diagnostics` 的 `runtime.metrics` 增量输出 `mobileOldestAgeMs` / `mobileOldestIdleMs` / `mobileStalled` / `mobileEvicted` / `mobileRejected`,`checks.sseConnections` 输出「连接数 / 上限 · 最旧 · 最久未写 · 满龄候选 · stalled · 安全年龄 · 累计驱逐/拒绝」。**边界(Reviewer P3)**:`age >= sseEvictMinAgeMs` 只是可驱逐门槛,不是"活跃/陈旧"判据(活跃设备也可能连接很久);`stalled`(写失败/背压/50s 无成功写)只用于排序与日志。二者合起来仍是启发式,宿主不宣称已精确区分活跃/陈旧连接;能保证的只有「60s 内不驱逐、stalled 优先、每次最多 1 条、无候选才 503」。
|
|
315
|
+
|
|
310
316
|
### 3.6b SSE 帧类型汇总(v2.3+ 扩展)
|
|
311
317
|
|
|
312
318
|
除 3.6 的 `session/event` 外,SSE 还会推送:
|
|
@@ -314,7 +320,7 @@
|
|
|
314
320
|
| type | 说明 |
|
|
315
321
|
|---|---|
|
|
316
322
|
| `session/context` | `{ sessionId, contextWindow }`——模型上下文窗口(`request/context` 事件,PC 端圆环同源) |
|
|
317
|
-
| `agent/status` | `{ agentId, sessionId, status, child }`——`status` 只有 `running` / `idle` 两值(内核 `AgentStatus` 即为二元联合);`sessionId` 为去 `session:` 前缀的会话 id,`child` 标记子代理会话(v2.7.2 起携带后两字段)。**不存在 `waiting`**:等待用户审批/作答时 agent 仍为 `running`,该事实由 `mobile/frame`
|
|
323
|
+
| `agent/status` | `{ agentId, sessionId, status, child, rootSessionId?, subagentsRunning? }`——`status` 只有 `running` / `idle` 两值(内核 `AgentStatus` 即为二元联合);`sessionId` 为去 `session:` 前缀的会话 id,`child` 标记子代理会话(v2.7.2 起携带后两字段)。**不存在 `waiting`**:等待用户审批/作答时 agent 仍为 `running`,该事实由 `mobile/frame` 的挂起问询/审批承载。issue #124/#133 起附 `rootSessionId`(该 agent 所属主会话根;根 agent 即自身)与 `subagentsRunning`(该根下递归 running 子代理数,**0 也发**);子代理 root 解析失败时**省略**两字段、不猜。`agent/disposed` 没有 orchestration idle 帧时,插件补发一条合成 `status=idle` 的 `agent/status`(同字段),供客户端清除运行指示 |
|
|
318
324
|
| `notifications/changed` | 通知记录增删(如移动端删除后),客户端刷新列表与角标 |
|
|
319
325
|
| `mobile/notify` | `{ notification: { id, kind, sessionId, title, detail, time } }`——插件"真结束"判定后推送的通知(completed / failed / needs-answer),桌面宠物/App 与通知中心同源渲染(v2.7.2) |
|
|
320
326
|
| `mobile/frame` | 内核瞬态帧(问询/审批)。`frame` 字段为 `question/requested`(含 `rpcId`、`questions[]`)、`question/resolved`(`questionRpcId`)、`approval/requested`(`rpcId`、`approvalId`、`toolName`、`reason?`)、`approval/resolved`(`approvalId`)。**`approvalId` 标识一次实际审批请求**:同一 `callId` 的 pre-execute 与 sandbox escalation 是两个不同 `approvalId`,`callId` 仅作关联(issue #60 R16);`$events` 路径的 `rpcId` 使用稳定的 `eventId`。**App 断线重连时服务端补发挂起的待答帧**(`pendingFrames` 回放) |
|
package/docs/04-security.md
CHANGED
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
**这是新增攻击面,边界在代码中强制(`lib/index.js`「LAN 桥」段):**
|
|
62
62
|
1. **只转发移动 API 面**:`pathname.startsWith(/m/api)` 之外一律 404——桌面 `/api` RPC 网关、`/m/api/qr-config`(含口令)、`/m/qr.png`(仅本机语义)、一切其他 `/m/*` 面均不转发;Host 头重写为 `127.0.0.1:<webServer.port>` 使下游 hostAllowed 自然放行(真实鉴权仍由口令把关)。
|
|
63
63
|
2. **口令强制**:未配置 `authToken`、或口令短于 16 字符 → **拒绝启动桥**(仅警告不断言;schema 不设 min 以免破坏既有用户)并记日志。
|
|
64
|
-
3.
|
|
64
|
+
3. **资源防护**:LAN 桥 Node server 的 `lanServer.maxConnections=128`(**传输层并发 socket 上限**,与移动端 SSE 配额不是同一个值;SSE 走插件 `maxConnections`,默认 **16**,满额时按 issue #131 驱逐 1 条满龄候选(stalled 优先;启发式,不宣称精确判活)而不是盲目调大)、headersTimeout 15s、requestTimeout 180s、upstream SSE 60s/普通请求 180s 超时、在网连接随插件卸载销毁。
|
|
65
65
|
4. **暴露条件**:桥默认关闭;开启即等于「0.0.0.0 移动 API 可达」——前置条件:可信 WiFi + ≥16 字符强口令(同 §2.1)。`/m/api/diagnostics` 的 `runtime.lanBridge.listening` 可确认监听状态(绑定失败时 QR/地址自动回退,不会指向死端口)。
|
|
66
66
|
5. **与 §3 表格关系**:桥上的流量走「局域网(可信 WiFi)明文」档位,残余风险与缓解同 §3 末。
|
|
67
67
|
|
package/docs/09-compatibility.md
CHANGED
|
@@ -242,7 +242,7 @@ App 为 Flutter 原生 APK(`com.dsh.remote`),渲染后端为 **Impeller(
|
|
|
242
242
|
|---|---|---|
|
|
243
243
|
| 设计令牌(有意) | 品牌色 `#426EFE` / 深色 `#0E1116` 等(App `theme.dart`)、`com.dsh.remote`、QR 协议 `DSHREMOTE\|地址\|口令`、`EnableImpeller=true` | 产品设计/通信契约,勿随意改 |
|
|
244
244
|
| 内核耦合词(有意) | 系统消息过滤词 `Current runtime context` / `This snapshot supersedes` / `background job `(App `chat_screen.dart`) | 与内核/PC 端保持一致的隐藏规则;apiProxy 帧桥已于 v3.1.6 删除,见 §1.4 |
|
|
245
|
-
| 插件可配置项 | `path` / `authToken` / `cookieName` / `sessionTtlMs` / `rechargeUrl` / `maxConnections` / `pushUrls` / `pushCooldownMs` / `pushContent` / `rateLimit` / `trustedHosts` / `doneGraceMs`(v2.8.0)/ `lanBridge`(v3.0.0:`enabled` 可选;未配置时仅可信 Desktop 自动启用,显式 `false` 关闭,可配 `port`/`host`)/ `approvalMode`(v3.1.3:`both` 默认 \| `mobile` \| `desktop`)/ `turnOutlineTimeoutMs`(轮次大纲端点有界等待,默认 5000ms
|
|
245
|
+
| 插件可配置项 | `path` / `authToken` / `cookieName` / `sessionTtlMs` / `rechargeUrl` / `maxConnections` / `pushUrls` / `pushCooldownMs` / `pushContent` / `rateLimit` / `trustedHosts` / `doneGraceMs`(v2.8.0)/ `lanBridge`(v3.0.0:`enabled` 可选;未配置时仅可信 Desktop 自动启用,显式 `false` 关闭,可配 `port`/`host`)/ `approvalMode`(v3.1.3:`both` 默认 \| `mobile` \| `desktop`)/ `turnOutlineTimeoutMs`(轮次大纲端点有界等待,默认 5000ms,契约门禁可调短)/ `sseEvictMinAgeMs`(issue #131:SSE 连接满时允许驱逐的最旧连接最小年龄,默认/硬下限 60000ms,只可调高) | schema 默认值,改配置即可 |
|
|
246
246
|
| 插件内置常量 | 通知上限 100、catalog 缓存 15s、SSE 心跳 25s、SSE 超时 15s、登录限流默认 10 次/60s(`rateLimit` 可配)、状态文件 `~/.dsh/mobile-remote/` | 合理默认,无需配置 |
|
|
247
247
|
| App 内置常量 | HTTP 超时 15/20s(余额 25s)、连接/探测超时 8s、地址表上限 8、重试退避 1s→15s、看门狗 15s 检查 / 心跳 75s(3 周期)、日志保留 15 天/256KB、聊天初始窗口 50 条、历史分段 30 条、上下文圆环阈值 70%/90%、思维链折叠手动状态键 `dsh_mr_reasoning_overrides`(按会话持久化,每会话软上限 100 条) | 合理默认;修改点集中在各文件顶部常量 |
|
|
248
248
|
| 已消除的写死 | 充值链接(原 App 硬编码 `platform.deepseek.com/top_up`) | v2.4.2 起走 `catalog.rechargeUrl`(插件配置为准) |
|
package/lib/index.js
CHANGED
|
@@ -109,6 +109,16 @@ import {
|
|
|
109
109
|
stageRelease,
|
|
110
110
|
} from "./app-carrier-store.js";
|
|
111
111
|
import { describeAppCarrier, discoverAppCarrier } from "./app-carrier.js";
|
|
112
|
+
import {
|
|
113
|
+
createSseConnectionMeta,
|
|
114
|
+
decideConnectionAdmission,
|
|
115
|
+
formatDurationMs,
|
|
116
|
+
SSE_BACKPRESSURE_BYTES,
|
|
117
|
+
SSE_EVICT_MIN_AGE_MS,
|
|
118
|
+
SSE_HEARTBEAT_MS,
|
|
119
|
+
SSE_REJECT_LOG_WINDOW_MS,
|
|
120
|
+
sseConnectionStats,
|
|
121
|
+
} from "./sse-connections.js";
|
|
112
122
|
|
|
113
123
|
/** Cordis 插件名(cordis.patch.yml 中按此 id 引用)。 */
|
|
114
124
|
export const name = "mobile-remote";
|
|
@@ -215,6 +225,14 @@ export const Config = z.object({
|
|
|
215
225
|
pluginUpdateManifest: z.string().default("npm").description("固定使用宿主 npm registry;只有设置为 off 时停用自动更新。"),
|
|
216
226
|
/** SSE 连接数上限。 */
|
|
217
227
|
maxConnections: z.number().default(16),
|
|
228
|
+
/**
|
|
229
|
+
* issue #131:SSE 配额满时,允许驱逐的「满龄候选」最小年龄(毫秒,默认 60 秒)。
|
|
230
|
+
*
|
|
231
|
+
* 旧实现满额直接 503,旧 App/被杀进程留下的半开连接会把配额永久占满;现在按
|
|
232
|
+
* **stalled 优先 → 同 clientId → 同 clientIp → 最旧** 选 1 条满龄连接再接受新连接。
|
|
233
|
+
* 60s 是硬下限(多设备/重连风暴保护),只允许调高。age 只是门槛而非判活依据。
|
|
234
|
+
*/
|
|
235
|
+
sseEvictMinAgeMs: z.number().min(SSE_EVICT_MIN_AGE_MS).default(SSE_EVICT_MIN_AGE_MS),
|
|
218
236
|
/**
|
|
219
237
|
* 推送桥(Phase 2):agent 完成/需要回答/失败 → 手机系统通知。
|
|
220
238
|
* 每个条目一个通道;format:
|
|
@@ -1318,6 +1336,121 @@ export const latestMessageTimeOf = (events) => {
|
|
|
1318
1336
|
return latest;
|
|
1319
1337
|
};
|
|
1320
1338
|
|
|
1339
|
+
/**
|
|
1340
|
+
* issue #124/#133:agent → 会话 id 的唯一归一(与 apply 内 `agentSessionId` 同源)。
|
|
1341
|
+
*
|
|
1342
|
+
* 生产 `agents.list()` 原生对象是 `{ id: "session:<sid>" | 其他, session: { id } }`,
|
|
1343
|
+
* **没有**直接的 `agent.sessionId` 字段;任何聚合/SSE 替换都必须经此函数。
|
|
1344
|
+
*/
|
|
1345
|
+
export const agentSessionIdOf = (agent) =>
|
|
1346
|
+
agent?.session?.id ?? String(agent?.id ?? "").replace(/^session:/, "");
|
|
1347
|
+
|
|
1348
|
+
/**
|
|
1349
|
+
* issue #124/#133:从会话行/会话头构建「子代理 → 父会话」映射。
|
|
1350
|
+
*
|
|
1351
|
+
* 只认 `origin === "subagent"`:用户主动 fork 的会话只有 `parentSession` 而没有
|
|
1352
|
+
* `origin`,不得当子代理聚合(ADR 0013)。
|
|
1353
|
+
*/
|
|
1354
|
+
export const buildSubagentParentById = (rows) => {
|
|
1355
|
+
const parentById = new Map();
|
|
1356
|
+
for (const row of rows ?? []) {
|
|
1357
|
+
if (row?.origin !== "subagent") continue;
|
|
1358
|
+
const id = typeof row?.id === "string" ? row.id : "";
|
|
1359
|
+
const parent = typeof row?.parentSession === "string" ? row.parentSession : "";
|
|
1360
|
+
if (id === "" || parent === "") continue;
|
|
1361
|
+
parentById.set(id, parent);
|
|
1362
|
+
}
|
|
1363
|
+
return parentById;
|
|
1364
|
+
};
|
|
1365
|
+
|
|
1366
|
+
/** 从子代理会话沿 parentById 向上找主会话根;链断/成环 → null(不猜)。 */
|
|
1367
|
+
export const resolveSubagentRoot = (sessionId, parentById, knownSessionIds = null) => {
|
|
1368
|
+
if (typeof sessionId !== "string" || sessionId === "" || !parentById?.has?.(sessionId)) return null;
|
|
1369
|
+
const visited = new Set([sessionId]);
|
|
1370
|
+
let current = sessionId;
|
|
1371
|
+
while (parentById.has(current)) {
|
|
1372
|
+
const parent = parentById.get(current);
|
|
1373
|
+
if (typeof parent !== "string" || parent === "" || visited.has(parent)) return null;
|
|
1374
|
+
visited.add(parent);
|
|
1375
|
+
current = parent;
|
|
1376
|
+
}
|
|
1377
|
+
// 链断了(根会话不在本次已知会话集合里)同样视为解析失败,不猜。
|
|
1378
|
+
if (knownSessionIds && !knownSessionIds.has(current)) return null;
|
|
1379
|
+
return current;
|
|
1380
|
+
};
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* 递归统计**每个会话**下 running 的子代理 descendant 数(不含自身)。
|
|
1384
|
+
*
|
|
1385
|
+
* 例如 root → child → grandchild(running):root 计 1、child 计 1、grandchild 计 0。
|
|
1386
|
+
* 单一来源:`agents.list()` 的 status(AgentStatus 只有 running/idle;activity 不算)。
|
|
1387
|
+
* 只认 origin=subagent 链(parentById 已过滤 fork);链上未知会话/成环即停止,不猜。
|
|
1388
|
+
*/
|
|
1389
|
+
export const computeSubagentRunningCounts = (agentsList, parentById, knownSessionIds = null) => {
|
|
1390
|
+
const counts = new Map();
|
|
1391
|
+
for (const agent of agentsList ?? []) {
|
|
1392
|
+
if (agent?.status !== "running") continue;
|
|
1393
|
+
const sid = agentSessionIdOf(agent);
|
|
1394
|
+
if (sid === "" || !parentById?.has?.(sid)) continue; // 非子代理(含根自身)不计
|
|
1395
|
+
const visited = new Set([sid]);
|
|
1396
|
+
let current = sid;
|
|
1397
|
+
while (parentById.has(current)) {
|
|
1398
|
+
const parent = parentById.get(current);
|
|
1399
|
+
if (typeof parent !== "string" || parent === "" || visited.has(parent)) break;
|
|
1400
|
+
if (knownSessionIds && !knownSessionIds.has(parent)) break; // 根/链断:不猜
|
|
1401
|
+
visited.add(parent);
|
|
1402
|
+
counts.set(parent, (counts.get(parent) ?? 0) + 1);
|
|
1403
|
+
current = parent;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
return counts;
|
|
1407
|
+
};
|
|
1408
|
+
|
|
1409
|
+
/**
|
|
1410
|
+
* 构造一条 `agent/status` SSE 帧(issue #124/#133)。
|
|
1411
|
+
*
|
|
1412
|
+
* - `rootSessionId`:该 agent 所属主会话根(子代理沿 parentSession 上溯;根 agent 即自身);
|
|
1413
|
+
* - `subagentsRunning`:该根下递归 running 子代理数(**0 也发**);
|
|
1414
|
+
* - 子代理 root 解析失败时**省略**两字段(不猜),客户端回落本地树聚合。
|
|
1415
|
+
*/
|
|
1416
|
+
export const subagentStatusPayload = ({
|
|
1417
|
+
sessionId,
|
|
1418
|
+
agentId,
|
|
1419
|
+
status,
|
|
1420
|
+
agentsList,
|
|
1421
|
+
parentById,
|
|
1422
|
+
rootHint,
|
|
1423
|
+
knownSessionIds = null,
|
|
1424
|
+
}) => {
|
|
1425
|
+
const sid = typeof sessionId === "string" ? sessionId : "";
|
|
1426
|
+
const child = parentById?.has?.(sid) === true;
|
|
1427
|
+
const payload = {
|
|
1428
|
+
type: "agent/status",
|
|
1429
|
+
sessionId,
|
|
1430
|
+
agentId,
|
|
1431
|
+
status,
|
|
1432
|
+
child,
|
|
1433
|
+
};
|
|
1434
|
+
let root = null;
|
|
1435
|
+
if (child) root = resolveSubagentRoot(sid, parentById, knownSessionIds) ?? (typeof rootHint === "string" && rootHint !== "" ? rootHint : null);
|
|
1436
|
+
else if (sid !== "") root = typeof rootHint === "string" && rootHint !== "" ? rootHint : sid;
|
|
1437
|
+
if (root === null) return payload; // root 解析失败:不猜
|
|
1438
|
+
// 当前 frames 的 status 覆盖 agents.list() 的同会话项,保证计数含本次启停。
|
|
1439
|
+
const live = [];
|
|
1440
|
+
let found = false;
|
|
1441
|
+
for (const agent of agentsList ?? []) {
|
|
1442
|
+
if (agentSessionIdOf(agent) === sid) {
|
|
1443
|
+
live.push({ ...agent, status });
|
|
1444
|
+
found = true;
|
|
1445
|
+
} else {
|
|
1446
|
+
live.push(agent);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
if (!found && sid !== "") live.push({ session: { id: sid }, status });
|
|
1450
|
+
const counts = computeSubagentRunningCounts(live, parentById, knownSessionIds);
|
|
1451
|
+
return { ...payload, rootSessionId: root, subagentsRunning: counts.get(root) ?? 0 };
|
|
1452
|
+
};
|
|
1453
|
+
|
|
1321
1454
|
/**
|
|
1322
1455
|
* issue #109:默认列表要排除「零可见消息」会话,但 `lastMessageAt` 对休眠会话是
|
|
1323
1456
|
* 异步回填的。过滤前对未知会话做一次**有界**消息时间解析(与后台回填共用读取/缓存),
|
|
@@ -3462,9 +3595,31 @@ function detailTextCharsHint(event) {
|
|
|
3462
3595
|
*/
|
|
3463
3596
|
export function detailEventFor(event) {
|
|
3464
3597
|
const detailEvent = { ...event };
|
|
3465
|
-
if (event?.
|
|
3466
|
-
|
|
3467
|
-
|
|
3598
|
+
if (event?.data && typeof event.data === "object") {
|
|
3599
|
+
if (event.type === "assistant/message") {
|
|
3600
|
+
const content = event.data.message?.content;
|
|
3601
|
+
if (Array.isArray(content)) {
|
|
3602
|
+
detailEvent.data = {
|
|
3603
|
+
...event.data,
|
|
3604
|
+
text: blocksToText(content),
|
|
3605
|
+
// issue #126(可见内容对齐):摘要里的 reasoning 会被 20k 截断;详情
|
|
3606
|
+
// 返回同一 canonical 口径的完整思维链,客户端只在用户“查看全文/展开”
|
|
3607
|
+
// 时采用,不在摘要路径自行递归拼接 content。
|
|
3608
|
+
reasoning: reasoningText(content),
|
|
3609
|
+
};
|
|
3610
|
+
}
|
|
3611
|
+
} else if (event.type === "user/message") {
|
|
3612
|
+
// user/message 的 data 就是 message 本身(assistant/message 才包在 data.message)。
|
|
3613
|
+
const content = Array.isArray(event.data.content)
|
|
3614
|
+
? event.data.content
|
|
3615
|
+
: event.data.message?.content;
|
|
3616
|
+
if (Array.isArray(content)) {
|
|
3617
|
+
detailEvent.data = {
|
|
3618
|
+
...event.data,
|
|
3619
|
+
text: blocksToText(content, { imagePlaceholder: false }),
|
|
3620
|
+
};
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3468
3623
|
}
|
|
3469
3624
|
return detailEvent;
|
|
3470
3625
|
}
|
|
@@ -4875,6 +5030,8 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
4875
5030
|
}
|
|
4876
5031
|
return {
|
|
4877
5032
|
mobileOnline: connections.size, // SSE 在线手机连接数(0 = 手机离线)
|
|
5033
|
+
// issue #131:连接年龄/空闲/stalled 与满额驱逐/拒绝累计(排查 mobileOnline 占满)。
|
|
5034
|
+
...sseRuntimeMetrics(),
|
|
4878
5035
|
agents, // 运行中 agent(会话运行时)数
|
|
4879
5036
|
sessions, // 会话总数
|
|
4880
5037
|
workspaces, // 工作区数
|
|
@@ -4917,6 +5074,33 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
4917
5074
|
// ── 会话活跃时间(插件本地持久化);归档状态直接使用内核 workspaceRegistry(与 PC 端同一份) ──
|
|
4918
5075
|
const ACTIVITY_FILE = join(homedir(), ".dsh", "mobile-remote", "session-activity.json");
|
|
4919
5076
|
const activityMap = new Map(); // sessionId -> lastActivity(ms)
|
|
5077
|
+
// issue #124/#133:agent 所属主会话根缓存(agent/disposed 时仍能发合成 idle 帧)。
|
|
5078
|
+
const subagentRootCache = new Map(); // sessionId -> rootSessionId
|
|
5079
|
+
// issue #124/#133(复审 P2):/sessions 用**完整语料**(sessionQuery,含 dormant root)
|
|
5080
|
+
// 建 parentById/knownIds 后缓存,SSE root 解析复用它——不能只用 sessions.list() 活跃子集。
|
|
5081
|
+
let subagentCorpusParentById = null;
|
|
5082
|
+
let subagentCorpusKnownSessionIds = null;
|
|
5083
|
+
const subagentParentMapNow = () => {
|
|
5084
|
+
// 以最近一次 /sessions 的完整语料为底;再合并当前活跃会话头,补上新出现的子代理。
|
|
5085
|
+
const parentById = new Map(subagentCorpusParentById ?? []);
|
|
5086
|
+
const knownSessionIds = new Set(subagentCorpusKnownSessionIds ?? []);
|
|
5087
|
+
const sessionsSvc = ctx.get("sessions");
|
|
5088
|
+
let rows = [];
|
|
5089
|
+
try {
|
|
5090
|
+
rows = sessionsSvc?.list?.() ?? [];
|
|
5091
|
+
} catch {
|
|
5092
|
+
rows = [];
|
|
5093
|
+
}
|
|
5094
|
+
for (const session of rows) {
|
|
5095
|
+
const id = session?.id ?? session?.header?.id;
|
|
5096
|
+
if (typeof id !== "string" || id === "") continue;
|
|
5097
|
+
knownSessionIds.add(id);
|
|
5098
|
+
if (session?.header?.origin === "subagent" && typeof session?.header?.parentSession === "string" && session.header.parentSession !== "") {
|
|
5099
|
+
parentById.set(id, session.header.parentSession);
|
|
5100
|
+
}
|
|
5101
|
+
}
|
|
5102
|
+
return { parentById, knownSessionIds };
|
|
5103
|
+
};
|
|
4920
5104
|
// ── 最新消息时间(ADR 0013,会话列表排序依据):只记 user/message 与 assistant/message ──
|
|
4921
5105
|
// 与 activityMap 分开持久化:`lastActivity` 语义冻结给旧版 App,`lastMessageAt` 才是排序真源。
|
|
4922
5106
|
const MESSAGE_TIME_FILE = join(homedir(), ".dsh", "mobile-remote", "session-message-time.json");
|
|
@@ -6756,31 +6940,141 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
6756
6940
|
|
|
6757
6941
|
// ── SSE 事件桥 ──────────────────────────────────────────────
|
|
6758
6942
|
const connections = new Set();
|
|
6759
|
-
|
|
6943
|
+
/**
|
|
6944
|
+
* issue #131:每个在网 SSE 连接的元数据(id / 建立时刻 / 最后写帧 / 最后心跳 /
|
|
6945
|
+
* 写失败数 / 背压状态 / 来源 IP 与 App 版本,clientId 可选)。
|
|
6946
|
+
*
|
|
6947
|
+
* 旧实现只有 `connections.size`,配额满直接 503:旧 App/被杀进程留下的半开连接
|
|
6948
|
+
* 服务端侧 TCP 仍"活着"(`res.write` 不报错),配额会被永久占满,只能重启宿主。
|
|
6949
|
+
* 元数据用于「满额时驱逐最旧且超过安全年龄的连接」、诊断指标与可归因日志。
|
|
6950
|
+
*/
|
|
6951
|
+
const connectionMeta = new Map();
|
|
6952
|
+
const sseEvictMinAgeMs = (() => {
|
|
6953
|
+
const raw = Number(config.sseEvictMinAgeMs ?? SSE_EVICT_MIN_AGE_MS);
|
|
6954
|
+
// 60s 是硬下限(架构顾问 #131 契约):配置只能调高,不能把"新连接"变成候选。
|
|
6955
|
+
return Number.isFinite(raw) ? Math.max(SSE_EVICT_MIN_AGE_MS, raw) : SSE_EVICT_MIN_AGE_MS;
|
|
6956
|
+
})();
|
|
6957
|
+
let sseConnSeq = 0;
|
|
6958
|
+
let sseEvicted = 0;
|
|
6959
|
+
let sseRejected = 0;
|
|
6960
|
+
const sseRejectLog = { windowStart: Date.now(), count: 0 };
|
|
6961
|
+
const SSE_CLIENT_ID_HEADER = "x-mobile-client-id";
|
|
6962
|
+
/** 当前在网连接 + 元数据(策略/统计输入;res 只作不透明句柄)。 */
|
|
6963
|
+
const sseEntries = () => {
|
|
6964
|
+
const entries = [];
|
|
6965
|
+
for (const res of connections) {
|
|
6966
|
+
const meta = connectionMeta.get(res);
|
|
6967
|
+
if (meta) entries.push({ res, meta });
|
|
6968
|
+
}
|
|
6969
|
+
return entries;
|
|
6970
|
+
};
|
|
6971
|
+
const logSseClose = (meta, reason) => {
|
|
6972
|
+
const now = Date.now();
|
|
6973
|
+
ctx.logger.info(`mobile-remote: SSE close id=${meta.id} age=${formatDurationMs(now - meta.createdAt)} idle=${formatDurationMs(now - meta.lastWriteAt)} remote=${meta.clientIp || "-"} app=${meta.appVersion || "-"} reason=${reason}`);
|
|
6974
|
+
};
|
|
6975
|
+
/** close/error/驱逐/卸载共用的幂等清理:重复调用不会二次删除或重复打日志。 */
|
|
6976
|
+
const cleanupConnection = (res, reason) => {
|
|
6977
|
+
const meta = connectionMeta.get(res);
|
|
6760
6978
|
connections.delete(res);
|
|
6979
|
+
connectionMeta.delete(res);
|
|
6980
|
+
if (meta) logSseClose(meta, reason);
|
|
6981
|
+
return meta;
|
|
6982
|
+
};
|
|
6983
|
+
/** 断开连接:先摘除配额与元数据,再销毁 socket(静默用于驱逐,避免 close/evict 双日志)。 */
|
|
6984
|
+
const dropConn = (res, reason = "drop", { silent = false } = {}) => {
|
|
6985
|
+
const meta = silent ? connectionMeta.get(res) ?? null : null;
|
|
6986
|
+
if (silent) {
|
|
6987
|
+
connections.delete(res);
|
|
6988
|
+
connectionMeta.delete(res);
|
|
6989
|
+
} else {
|
|
6990
|
+
cleanupConnection(res, reason);
|
|
6991
|
+
}
|
|
6761
6992
|
try {
|
|
6762
6993
|
res.destroy();
|
|
6763
6994
|
} catch {
|
|
6764
6995
|
// 已销毁
|
|
6765
6996
|
}
|
|
6997
|
+
return meta;
|
|
6766
6998
|
};
|
|
6767
|
-
const
|
|
6768
|
-
const
|
|
6769
|
-
|
|
6770
|
-
|
|
6771
|
-
|
|
6772
|
-
|
|
6773
|
-
|
|
6774
|
-
|
|
6775
|
-
|
|
6776
|
-
|
|
6777
|
-
|
|
6778
|
-
|
|
6779
|
-
|
|
6780
|
-
|
|
6999
|
+
const readSseClientId = (req) => {
|
|
7000
|
+
const raw = req?.headers?.[SSE_CLIENT_ID_HEADER];
|
|
7001
|
+
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
7002
|
+
return typeof value === "string" ? value.trim().slice(0, 128) : "";
|
|
7003
|
+
};
|
|
7004
|
+
/**
|
|
7005
|
+
* 所有 SSE `res.write` 的统一入口(issue #131):成功即刷新 lastWriteAt;
|
|
7006
|
+
* 写失败立即断开;背压超阈值标记并断开(防慢客户端无限堆积内存)。
|
|
7007
|
+
*/
|
|
7008
|
+
const safeWrite = (res, chunk) => {
|
|
7009
|
+
const meta = connectionMeta.get(res);
|
|
7010
|
+
try {
|
|
7011
|
+
res.write(chunk);
|
|
7012
|
+
if (meta) meta.lastWriteAt = Date.now();
|
|
7013
|
+
if (typeof res.writableLength === "number" && res.writableLength > SSE_BACKPRESSURE_BYTES) {
|
|
7014
|
+
if (meta) meta.backpressure = true;
|
|
7015
|
+
dropConn(res, "backpressure");
|
|
7016
|
+
return false;
|
|
6781
7017
|
}
|
|
7018
|
+
return true;
|
|
7019
|
+
} catch {
|
|
7020
|
+
if (meta) meta.writeFailures += 1;
|
|
7021
|
+
dropConn(res, "write-error");
|
|
7022
|
+
return false;
|
|
6782
7023
|
}
|
|
6783
7024
|
};
|
|
7025
|
+
const noteHeartbeat = (res) => {
|
|
7026
|
+
const meta = connectionMeta.get(res);
|
|
7027
|
+
if (!meta) return;
|
|
7028
|
+
const now = Date.now();
|
|
7029
|
+
meta.lastWriteAt = now;
|
|
7030
|
+
meta.lastHeartbeatAt = now;
|
|
7031
|
+
};
|
|
7032
|
+
const evictForAdmission = (candidate) => {
|
|
7033
|
+
sseEvicted += 1;
|
|
7034
|
+
dropConn(candidate.res, "evict", { silent: true });
|
|
7035
|
+
ctx.logger.warn(`mobile-remote: SSE evict id=${candidate.meta.id} age=${formatDurationMs(candidate.ageMs)} idle=${formatDurationMs(candidate.idleMs)} remote=${candidate.meta.clientIp || "-"} app=${candidate.meta.appVersion || "-"} reason=${candidate.reason} stalled=${candidate.stalled === true}`);
|
|
7036
|
+
};
|
|
7037
|
+
/** 503 拒绝日志每 30s 汇总一次,避免 App 重试风暴刷屏。 */
|
|
7038
|
+
const noteSseRejection = (now, stats, reason) => {
|
|
7039
|
+
sseRejected += 1;
|
|
7040
|
+
sseRejectLog.count += 1;
|
|
7041
|
+
if (sseRejectLog.count > 1 && now - sseRejectLog.windowStart < SSE_REJECT_LOG_WINDOW_MS) return;
|
|
7042
|
+
ctx.logger.warn(`mobile-remote: SSE reject count=${sseRejectLog.count} window=${Math.round(SSE_REJECT_LOG_WINDOW_MS / 1000)}s oldestAge=${formatDurationMs(stats.oldestAgeMs)} oldestIdle=${formatDurationMs(stats.oldestIdleMs)} reason=${reason}`);
|
|
7043
|
+
sseRejectLog.windowStart = now;
|
|
7044
|
+
sseRejectLog.count = 0;
|
|
7045
|
+
};
|
|
7046
|
+
/** 诊断页一行字符串:App 对未知 checks key 按「ℹ key = value」直读,无需 App 改动。 */
|
|
7047
|
+
const sseConnectionSummary = () => {
|
|
7048
|
+
const stats = sseConnectionStats(sseEntries(), Date.now(), { minAgeMs: sseEvictMinAgeMs });
|
|
7049
|
+
const parts = [`${stats.total} / ${config.maxConnections}`];
|
|
7050
|
+
if (stats.total > 0) {
|
|
7051
|
+
parts.push(`最旧 ${formatDurationMs(stats.oldestAgeMs)}`);
|
|
7052
|
+
parts.push(`最久未写 ${formatDurationMs(stats.oldestIdleMs)}`);
|
|
7053
|
+
// 满龄候选 ≠ 陈旧连接:age 只是可驱逐门槛(Reviewer P3),不宣称"活跃/陈旧已区分"。
|
|
7054
|
+
parts.push(`满龄候选 ${stats.ageEligible}`);
|
|
7055
|
+
parts.push(`stalled ${stats.stalled}`);
|
|
7056
|
+
}
|
|
7057
|
+
parts.push(`安全年龄 ${formatDurationMs(sseEvictMinAgeMs)}`);
|
|
7058
|
+
parts.push(`累计驱逐 ${sseEvicted}`);
|
|
7059
|
+
parts.push(`累计拒绝 ${sseRejected}`);
|
|
7060
|
+
return parts.join(" · ");
|
|
7061
|
+
};
|
|
7062
|
+
/** runtime.metrics 增量(issue #131):旧版 App 忽略未知字段;App 诊断页按 key 直读。 */
|
|
7063
|
+
const sseRuntimeMetrics = () => {
|
|
7064
|
+
const stats = sseConnectionStats(sseEntries(), Date.now(), { minAgeMs: sseEvictMinAgeMs });
|
|
7065
|
+
return {
|
|
7066
|
+
mobileOldestAgeMs: stats.oldestAgeMs,
|
|
7067
|
+
mobileOldestIdleMs: stats.oldestIdleMs,
|
|
7068
|
+
mobileStalled: stats.stalled,
|
|
7069
|
+
mobileEvicted: sseEvicted,
|
|
7070
|
+
mobileRejected: sseRejected,
|
|
7071
|
+
};
|
|
7072
|
+
};
|
|
7073
|
+
const broadcast = (frame) => {
|
|
7074
|
+
const line = `data: ${JSON.stringify(frame)}\n\n`;
|
|
7075
|
+
// 复制迭代:safeWrite 可能在背压/写失败时移除连接。
|
|
7076
|
+
for (const res of [...connections]) safeWrite(res, line);
|
|
7077
|
+
};
|
|
6784
7078
|
// ── v2.7 任务(jobs)视图:与 PC 端 GUI 同源(apiproxy 模式)──
|
|
6785
7079
|
// 内核任务注册表(ctx.jobs)按会话(agent)隔离;任务视图随 session/jobs 帧下发。
|
|
6786
7080
|
const jobViews = (list) =>
|
|
@@ -6852,44 +7146,73 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
6852
7146
|
}
|
|
6853
7147
|
return budget;
|
|
6854
7148
|
};
|
|
6855
|
-
const connect = (res) => {
|
|
7149
|
+
const connect = (res, req) => {
|
|
7150
|
+
const now = Date.now();
|
|
7151
|
+
const incoming = {
|
|
7152
|
+
clientIp: typeof req?.socket?.remoteAddress === "string" ? req.socket.remoteAddress : "",
|
|
7153
|
+
clientId: readSseClientId(req),
|
|
7154
|
+
};
|
|
7155
|
+
const appVersion = readAppVersionHeader(req?.headers) ?? "";
|
|
6856
7156
|
if (connections.size >= config.maxConnections) {
|
|
6857
|
-
|
|
6858
|
-
|
|
6859
|
-
|
|
7157
|
+
// issue #131:不再"满额直接 503"。满池时按策略驱逐「最旧且超过安全年龄」的
|
|
7158
|
+
// 1 条陈旧连接再接受新连接;没有 60s 候选才 503。绝不调大 maxConnections 掩盖泄漏。
|
|
7159
|
+
const decision = decideConnectionAdmission({
|
|
7160
|
+
currentSize: connections.size,
|
|
7161
|
+
maxConnections: config.maxConnections,
|
|
7162
|
+
entries: sseEntries(),
|
|
7163
|
+
incoming,
|
|
7164
|
+
now,
|
|
7165
|
+
minAgeMs: sseEvictMinAgeMs,
|
|
7166
|
+
});
|
|
7167
|
+
if (decision.action !== "evict") {
|
|
7168
|
+
const stats = sseConnectionStats(sseEntries(), now, { minAgeMs: sseEvictMinAgeMs });
|
|
7169
|
+
noteSseRejection(now, stats, decision.reason ?? "no-eligible");
|
|
7170
|
+
res.writeHead(503, { "content-type": "application/json; charset=utf-8", "Retry-After": "5" });
|
|
7171
|
+
res.end(JSON.stringify({ error: "too-many-connections", mobileOnline: stats.total, maxConnections: config.maxConnections, oldestAgeMs: stats.oldestAgeMs, maxIdleMs: stats.oldestIdleMs, evictMinAgeMs: sseEvictMinAgeMs }));
|
|
7172
|
+
return;
|
|
7173
|
+
}
|
|
7174
|
+
evictForAdmission(decision.evict);
|
|
6860
7175
|
}
|
|
6861
7176
|
// review:先挂清理监听再写头/回放——握手瞬间客户端断开时不会留下滞留连接
|
|
6862
7177
|
//(此前 close/error 监听在写完后才挂,握手即断的死连接靠 25s 心跳兜底)
|
|
6863
|
-
|
|
7178
|
+
const meta = createSseConnectionMeta({ id: `c${++sseConnSeq}`, now, clientIp: incoming.clientIp, appVersion, clientId: incoming.clientId });
|
|
7179
|
+
connectionMeta.set(res, meta);
|
|
7180
|
+
res.on("close", () => cleanupConnection(res, "close"));
|
|
6864
7181
|
// 半开连接:客户端进程被杀/断网后 close 可能迟迟不来,error 事件立即清理僵尸
|
|
6865
|
-
res.on("error", () =>
|
|
6866
|
-
|
|
6867
|
-
|
|
6868
|
-
|
|
6869
|
-
|
|
6870
|
-
|
|
6871
|
-
|
|
6872
|
-
|
|
7182
|
+
res.on("error", () => cleanupConnection(res, "error"));
|
|
7183
|
+
try {
|
|
7184
|
+
res.writeHead(200, {
|
|
7185
|
+
"content-type": "text/event-stream",
|
|
7186
|
+
"cache-control": "no-cache",
|
|
7187
|
+
"connection": "keep-alive",
|
|
7188
|
+
});
|
|
7189
|
+
} catch {
|
|
7190
|
+
dropConn(res, "write-error"); // 握手写头失败(连接已不可用)
|
|
7191
|
+
return;
|
|
7192
|
+
}
|
|
7193
|
+
if (!safeWrite(res, ": connected\n\n")) return;
|
|
7194
|
+
if (!safeWrite(res, `data: ${JSON.stringify({ type: "hello", serverTime: now, capabilities: { eventTimeline: EVENT_TIMELINE_CAPABILITIES, turnOutline: turnOutlineCapabilityOf(ctx), fileRange: FILE_RANGE_CAPABILITIES, turnTail: turnTailCapabilityOf(ctx), toolCards: toolCardsCapabilityOf(), hold: { version: 1, onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? DEFAULT_PENDING_TIMEOUT_MS) || 0), offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0) } } })}\n\n`)) return;
|
|
6873
7195
|
connections.add(res);
|
|
7196
|
+
ctx.logger.info(`mobile-remote: SSE open id=${meta.id} age=0s idle=0s remote=${meta.clientIp || "-"} app=${meta.appVersion || "-"} reason=open`);
|
|
6874
7197
|
// 补发断线期间挂起的问询/审批(与 PC 端 GUI 连接时的 pending 回放一致;超 TTL 的僵尸帧先清掉)
|
|
6875
7198
|
for (const [key, f] of pendingFrames) {
|
|
6876
|
-
if (
|
|
7199
|
+
if (now - (f.at ?? 0) > PENDING_FRAMES_TTL) {
|
|
6877
7200
|
pendingFrames.delete(key);
|
|
6878
7201
|
continue;
|
|
6879
7202
|
}
|
|
6880
|
-
res
|
|
7203
|
+
if (!safeWrite(res, `data: ${JSON.stringify({ type: "mobile/frame", frame: f })}\n\n`)) return;
|
|
6881
7204
|
}
|
|
6882
7205
|
// v3.3(吸收上游 #64):同一有序流上,回放后追加完整待办快照边界。
|
|
6883
7206
|
// 客户端只据此撤销本宿主已不在 pending 中的业务通知(其它宿主/常驻通知不受影响)。
|
|
6884
|
-
res
|
|
7207
|
+
if (!safeWrite(res, `data: ${JSON.stringify({ type: "attention/snapshot", version: 1,
|
|
6885
7208
|
pending: [...pendingFrames.values()].flatMap((f) => {
|
|
6886
7209
|
const kind = f.type === "approval/requested" ? "approval" : f.type === "question/requested" ? "question" : null;
|
|
6887
7210
|
const identity = kind === "approval" ? f.approvalId || f.rpcId : f.rpcId;
|
|
6888
7211
|
return kind && identity && f.sessionId ? [{ kind, identity, sessionId: f.sessionId }] : [];
|
|
6889
|
-
}) })}\n\n`);
|
|
7212
|
+
}) })}\n\n`)) return;
|
|
6890
7213
|
// v2.7:连接回放各会话任务视图(与 PC 端 GUI 同源)
|
|
6891
7214
|
for (const f of sessionJobsFrames()) {
|
|
6892
|
-
res
|
|
7215
|
+
if (!safeWrite(res, `data: ${JSON.stringify(f)}\n\n`)) return;
|
|
6893
7216
|
}
|
|
6894
7217
|
};
|
|
6895
7218
|
const onSessionEvent = (session, event) => {
|
|
@@ -6989,15 +7312,37 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
6989
7312
|
// v2.7.2:帧补 sessionId(去 "session:" 前缀)与 child 标志,供悬浮球渲染/过滤
|
|
6990
7313
|
const agentSession = payload.agent?.session;
|
|
6991
7314
|
const sessionId = agentSessionId(payload.agent);
|
|
6992
|
-
|
|
6993
|
-
|
|
7315
|
+
// issue #124/#133:帧携带 rootSessionId + 递归 running 子代理数(0 也发),
|
|
7316
|
+
// 让 App 在根 idle 时仍能显示运行指示;子代理 root 解析失败则省略、不猜。
|
|
7317
|
+
const { parentById, knownSessionIds } = subagentParentMapNow();
|
|
7318
|
+
if (
|
|
7319
|
+
agentSession?.header?.origin === "subagent" &&
|
|
7320
|
+
typeof agentSession?.header?.parentSession === "string" &&
|
|
7321
|
+
agentSession.header.parentSession !== ""
|
|
7322
|
+
) {
|
|
7323
|
+
parentById.set(sessionId, agentSession.header.parentSession);
|
|
7324
|
+
}
|
|
7325
|
+
let agentsList = [];
|
|
7326
|
+
try {
|
|
7327
|
+
agentsList = ctx.get("agents")?.list?.() ?? [];
|
|
7328
|
+
} catch {
|
|
7329
|
+
agentsList = [];
|
|
7330
|
+
}
|
|
7331
|
+
const statusPayload = subagentStatusPayload({
|
|
6994
7332
|
sessionId,
|
|
6995
7333
|
agentId: payload.agent?.id ?? "", // review:payload.agent 可能缺失(防御)
|
|
6996
7334
|
status: payload.status,
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
|
|
7335
|
+
agentsList,
|
|
7336
|
+
parentById,
|
|
7337
|
+
rootHint: subagentRootCache.get(sessionId),
|
|
7338
|
+
knownSessionIds,
|
|
7000
7339
|
});
|
|
7340
|
+
if (typeof statusPayload.rootSessionId === "string") {
|
|
7341
|
+
subagentRootCache.set(sessionId, statusPayload.rootSessionId);
|
|
7342
|
+
} else {
|
|
7343
|
+
subagentRootCache.delete(sessionId);
|
|
7344
|
+
}
|
|
7345
|
+
broadcast(statusPayload);
|
|
7001
7346
|
// 恢复运行 = 宽限判定作废(防御:正常情况下 turn/start 已处理)
|
|
7002
7347
|
if (payload.status === "running" && sessionId) cancelDone(sessionId);
|
|
7003
7348
|
// v3.0.0(方案 A):agent 真正空闲(整个任务/目标结束)→ 释放持存的排队消息
|
|
@@ -7269,7 +7614,7 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
7269
7614
|
};
|
|
7270
7615
|
// ── Phase 0 收敛 helper(统一散落各处的重复写法) ──
|
|
7271
7616
|
/** 会话/agent id 归一(去 "session:" 前缀)。 */
|
|
7272
|
-
const agentSessionId = (agent) =>
|
|
7617
|
+
const agentSessionId = (agent) => agentSessionIdOf(agent);
|
|
7273
7618
|
/** 回环地址判定。 */
|
|
7274
7619
|
const isLoopback = (remote) => remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1";
|
|
7275
7620
|
/** 限流/本机判定的**有效来源 IP**(v3.1.5 S9):回环连接优先采信桥写入的内部头
|
|
@@ -8648,6 +8993,32 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
8648
8993
|
});
|
|
8649
8994
|
}
|
|
8650
8995
|
}
|
|
8996
|
+
// issue #124/#133:主会话行需要聚合**递归**子代理的运行状态(根 idle + 子 running
|
|
8997
|
+
// 时列表仍显示运行指示)。用**空会话过滤前**的原始行(含空子会话)建 parentById,
|
|
8998
|
+
// 一次 `agents.list()` 反向计数到根;不逐会话调用 /subagents 或 listDescendants。
|
|
8999
|
+
const subagentParentById = buildSubagentParentById(list);
|
|
9000
|
+
const knownSessionIds = new Set(list.map((row) => row.id));
|
|
9001
|
+
const subagentRunningCounts = (() => {
|
|
9002
|
+
const agentsSvc = ctx.get("agents");
|
|
9003
|
+
if (typeof agentsSvc?.list !== "function") return new Map();
|
|
9004
|
+
try {
|
|
9005
|
+
return computeSubagentRunningCounts(
|
|
9006
|
+
agentsSvc.list() ?? [],
|
|
9007
|
+
subagentParentById,
|
|
9008
|
+
knownSessionIds,
|
|
9009
|
+
);
|
|
9010
|
+
} catch {
|
|
9011
|
+
return new Map(); // 宿主 agents 读失败:退化为 0,不阻塞会话列表
|
|
9012
|
+
}
|
|
9013
|
+
})();
|
|
9014
|
+
for (const row of list) {
|
|
9015
|
+
// 契约:始终下发 int(0 表示无运行子代理),客户端据此优先于本地树 fallback。
|
|
9016
|
+
row.subagentsRunning = subagentRunningCounts.get(row.id) ?? 0;
|
|
9017
|
+
}
|
|
9018
|
+
// issue #124/#133(复审 P2):把同一份**完整语料**映射留给 SSE root 解析,
|
|
9019
|
+
// 保证 dormant root / 被空会话过滤的子代理也能正确上溯,而不是退化成活跃子集。
|
|
9020
|
+
subagentCorpusParentById = subagentParentById;
|
|
9021
|
+
subagentCorpusKnownSessionIds = knownSessionIds;
|
|
8651
9022
|
// issue #109:默认过滤要在 title/message 回填后做;判空用**事件可见性**,
|
|
8652
9023
|
// 不用 latestMessageTimeOf/time(可见消息可能没有 time,不能因此误删)。
|
|
8653
9024
|
if (!includeEmpty) {
|
|
@@ -9170,7 +9541,7 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
9170
9541
|
// review:HEAD 会悬挂 SSE 连接(Node 对 HEAD 丢弃 body 但连接保持打开)——
|
|
9171
9542
|
// 必须严格 GET-only,不能走 requireGet(其放行 HEAD)
|
|
9172
9543
|
if (method !== "GET") return error(res, 405, "method-not-allowed");
|
|
9173
|
-
connect(res);
|
|
9544
|
+
connect(res, req);
|
|
9174
9545
|
return;
|
|
9175
9546
|
}
|
|
9176
9547
|
|
|
@@ -10004,6 +10375,9 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
10004
10375
|
// remoteEvents=true 表示瀑布已放行内核 $events 转发 → 桌面 GUI 与手机双端同卡)
|
|
10005
10376
|
checks.approvalMode = approvalMode;
|
|
10006
10377
|
checks.remoteEvents = eventsCapable();
|
|
10378
|
+
// issue #131:SSE 连接年龄/空闲摘要——帮诊断页判断"是否有满龄/stalled 候选";
|
|
10379
|
+
// age 只是可驱逐门槛,不代表连接已死(活跃设备也可能连接很久),见 docs/03-api.md §3.6。
|
|
10380
|
+
checks.sseConnections = sseConnectionSummary();
|
|
10007
10381
|
// ── v3.1.6(issue #19):宿主能力三态报告(ADR 0017)────────────────────────
|
|
10008
10382
|
// 插件**不设宿主版本门禁**,其成立前提就是"能力状态必须如实报出"。只报 services 的
|
|
10009
10383
|
// 布尔存在性不够——本次四处不兼容全部是"服务在、调用不报错、语义已变"(能力语义漂移),
|
|
@@ -12334,6 +12708,29 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
12334
12708
|
for (const [key, f] of pendingFrames) {
|
|
12335
12709
|
if (f.sessionId === sid) pendingFrames.delete(key);
|
|
12336
12710
|
}
|
|
12711
|
+
// issue #124/#133:agent 被销毁时可能没有 idle 帧——补一条**合成 idle**,
|
|
12712
|
+
// 携带 rootSessionId + 重新计算的 subagentsRunning;root 未知则不猜。
|
|
12713
|
+
const knownRoot = subagentRootCache.get(sid);
|
|
12714
|
+
subagentRootCache.delete(sid);
|
|
12715
|
+
let agentsList = [];
|
|
12716
|
+
try {
|
|
12717
|
+
agentsList = ctx.get("agents")?.list?.() ?? [];
|
|
12718
|
+
} catch {
|
|
12719
|
+
agentsList = [];
|
|
12720
|
+
}
|
|
12721
|
+
const disposedParents = subagentParentMapNow();
|
|
12722
|
+
const statusPayload = subagentStatusPayload({
|
|
12723
|
+
sessionId: sid,
|
|
12724
|
+
agentId: agent?.id ?? "",
|
|
12725
|
+
status: "idle",
|
|
12726
|
+
agentsList,
|
|
12727
|
+
parentById: disposedParents.parentById,
|
|
12728
|
+
rootHint: knownRoot,
|
|
12729
|
+
knownSessionIds: disposedParents.knownSessionIds,
|
|
12730
|
+
});
|
|
12731
|
+
if (typeof statusPayload.rootSessionId === "string") {
|
|
12732
|
+
broadcast(statusPayload);
|
|
12733
|
+
}
|
|
12337
12734
|
});
|
|
12338
12735
|
// v2.7.2 review(M4):定期剪枝无界 Map(每 10 分钟)
|
|
12339
12736
|
const pruneTimer = setInterval(() => {
|
|
@@ -12406,17 +12803,10 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
12406
12803
|
}
|
|
12407
12804
|
const heartbeat = setInterval(() => {
|
|
12408
12805
|
for (const res of [...connections]) {
|
|
12409
|
-
|
|
12410
|
-
|
|
12411
|
-
// review:心跳也做背压检查——卡死但不报错的慢客户端靠 5B/25s 永远到不了踢线
|
|
12412
|
-
if (typeof res.writableLength === "number" && res.writableLength > 256 * 1024) {
|
|
12413
|
-
dropConn(res);
|
|
12414
|
-
}
|
|
12415
|
-
} catch {
|
|
12416
|
-
dropConn(res); // 心跳写失败 → 僵尸连接立即清理
|
|
12417
|
-
}
|
|
12806
|
+
if (!safeWrite(res, ": ping\n\n")) continue;
|
|
12807
|
+
noteHeartbeat(res);
|
|
12418
12808
|
}
|
|
12419
|
-
},
|
|
12809
|
+
}, SSE_HEARTBEAT_MS);
|
|
12420
12810
|
heartbeat.unref();
|
|
12421
12811
|
return () => {
|
|
12422
12812
|
// v3.1.6(issue #14 复核):先置卸载位并清空回填队列,再冲刷落盘。
|
|
@@ -12493,6 +12883,7 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
12493
12883
|
}
|
|
12494
12884
|
for (const res of connections) res.destroy();
|
|
12495
12885
|
connections.clear();
|
|
12886
|
+
connectionMeta.clear();
|
|
12496
12887
|
};
|
|
12497
12888
|
}, "mobile-remote: /m routes and event bridge");
|
|
12498
12889
|
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* issue #131:SSE 连接准入策略(纯函数,无 HTTP/无副作用,便于单测)。
|
|
3
|
+
*
|
|
4
|
+
* 真机症状:只有一台手机,`mobileOnline = 16 / 16`,新 `/m/api/events` 永久 503,
|
|
5
|
+
* 只能重启宿主。App 侧泄漏已修(9670849),宿主侧仍需兜底:
|
|
6
|
+
* - 满额时**不直接 503**,先驱逐「满龄且优先 stalled」的候选连接,再接受新连接;
|
|
7
|
+
* - 候选必须 `age >= minAgeMs`(默认 60s):只能保证"60s 内不驱逐",不保证不误踢;
|
|
8
|
+
* - 每次准入最多驱逐 1 条,绝不通过调大 maxConnections 掩盖泄漏。
|
|
9
|
+
*
|
|
10
|
+
* 排序(架构顾问 #131 契约 + Reviewer 预审 P3 收口):
|
|
11
|
+
* **stalled 优先** > 同 clientId(若双方都有)> 同 clientIp > 全局最旧。
|
|
12
|
+
*
|
|
13
|
+
* 重要语义边界:`age >= 60s` 只是**可驱逐门槛**,不是"活跃/陈旧"判据——真实活跃设备
|
|
14
|
+
* 也可能连接超过 60s;`stalled` 也只是排序/日志信号(半开连接的 `res.write` 可能仍成功,
|
|
15
|
+
* 不能用"写成功"证明还活着)。两者合起来仍是启发式,不能宣称"不会误踢活跃连接"。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** 满龄候选的最小年龄(毫秒):低于此年龄的连接一律不驱逐(硬门槛,不等于判活)。 */
|
|
19
|
+
export const SSE_EVICT_MIN_AGE_MS = 60_000;
|
|
20
|
+
/** 服务端 SSE 心跳间隔(毫秒):与既有 `: ping` 周期一致。 */
|
|
21
|
+
export const SSE_HEARTBEAT_MS = 25_000;
|
|
22
|
+
/** 无成功写的 stalled 判定(毫秒):约 2 个心跳周期。 */
|
|
23
|
+
export const SSE_STALL_IDLE_MS = 50_000;
|
|
24
|
+
/** SSE 背压阈值(字节):与 v2.7.2 review(M5) 一致。 */
|
|
25
|
+
export const SSE_BACKPRESSURE_BYTES = 256 * 1024;
|
|
26
|
+
/** 503 拒绝日志汇总窗口(毫秒):避免 App 重试风暴刷屏。 */
|
|
27
|
+
export const SSE_REJECT_LOG_WINDOW_MS = 30_000;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 创建一条 SSE 连接的元数据。
|
|
31
|
+
*
|
|
32
|
+
* `id` 仅用于日志/诊断关联,不含 token/cookie;`clientIp` / `appVersion` / `clientId`
|
|
33
|
+
* 都来自请求头或 socket,只用于准入排序与排障,不参与鉴权。
|
|
34
|
+
*/
|
|
35
|
+
export function createSseConnectionMeta({ id, now = Date.now(), clientIp = "", appVersion = "", clientId = "" }) {
|
|
36
|
+
return {
|
|
37
|
+
id,
|
|
38
|
+
createdAt: now,
|
|
39
|
+
lastWriteAt: now,
|
|
40
|
+
lastHeartbeatAt: now,
|
|
41
|
+
writeFailures: 0,
|
|
42
|
+
backpressure: false,
|
|
43
|
+
clientIp,
|
|
44
|
+
appVersion,
|
|
45
|
+
clientId,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 是否处于 stalled 状态(只用于排序/日志,不作为驱逐的唯一判据)。 */
|
|
50
|
+
export function isSseConnectionStalled(meta, now = Date.now()) {
|
|
51
|
+
if (!meta) return false;
|
|
52
|
+
if (meta.writeFailures > 0) return true;
|
|
53
|
+
if (meta.backpressure === true) return true;
|
|
54
|
+
return now - meta.lastWriteAt >= SSE_STALL_IDLE_MS;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 连接统计(诊断指标):最旧年龄 / 最久无成功写 / stalled 数 / 满龄候选数(非陈旧数)。
|
|
59
|
+
*
|
|
60
|
+
* @param {{res: unknown, meta: object}[]} entries
|
|
61
|
+
*/
|
|
62
|
+
export function sseConnectionStats(entries, now = Date.now(), { minAgeMs = SSE_EVICT_MIN_AGE_MS } = {}) {
|
|
63
|
+
let total = 0;
|
|
64
|
+
let oldestAgeMs = 0;
|
|
65
|
+
let oldestIdleMs = 0;
|
|
66
|
+
let stalled = 0;
|
|
67
|
+
// 仅表示"年龄达到可驱逐门槛"的候选数,不等于陈旧/活跃判定(Reviewer P3)。
|
|
68
|
+
let ageEligible = 0;
|
|
69
|
+
for (const entry of entries ?? []) {
|
|
70
|
+
const meta = entry?.meta;
|
|
71
|
+
if (!meta) continue;
|
|
72
|
+
total += 1;
|
|
73
|
+
const ageMs = Math.max(0, now - meta.createdAt);
|
|
74
|
+
const idleMs = Math.max(0, now - meta.lastWriteAt);
|
|
75
|
+
if (ageMs > oldestAgeMs) oldestAgeMs = ageMs;
|
|
76
|
+
if (idleMs > oldestIdleMs) oldestIdleMs = idleMs;
|
|
77
|
+
if (isSseConnectionStalled(meta, now)) stalled += 1;
|
|
78
|
+
if (ageMs >= minAgeMs) ageEligible += 1;
|
|
79
|
+
}
|
|
80
|
+
return { total, oldestAgeMs, oldestIdleMs, stalled, ageEligible };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 毫秒 → 紧凑可读(日志/诊断用)。 */
|
|
84
|
+
export function formatDurationMs(ms) {
|
|
85
|
+
if (!Number.isFinite(ms) || ms <= 0) return "0s";
|
|
86
|
+
if (ms < 1000) return `${Math.round(ms)}ms`;
|
|
87
|
+
if (ms < 60_000) return `${Math.round(ms / 1000)}s`;
|
|
88
|
+
if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m${Math.round((ms % 60_000) / 1000)}s`;
|
|
89
|
+
return `${Math.floor(ms / 3_600_000)}h${Math.floor((ms % 3_600_000) / 60_000)}m`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function identityTier(meta, incoming) {
|
|
93
|
+
const wantedClientId = typeof incoming?.clientId === "string" ? incoming.clientId : "";
|
|
94
|
+
if (wantedClientId !== "" && typeof meta.clientId === "string" && meta.clientId === wantedClientId) return 0;
|
|
95
|
+
const wantedIp = typeof incoming?.clientIp === "string" ? incoming.clientIp : "";
|
|
96
|
+
if (wantedIp !== "" && typeof meta.clientIp === "string" && meta.clientIp === wantedIp) return 1;
|
|
97
|
+
return 2;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const TIER_REASON = ["same-client-id", "same-client-ip", "oldest"];
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 准入决策(纯函数):未满直接 accept;满池才调用 planConnectionAdmission;
|
|
104
|
+
* 候选不存在则 reject;任何情况下最多返回 1 条 evict。
|
|
105
|
+
*
|
|
106
|
+
* @returns {{action: "accept"} |
|
|
107
|
+
* {action: "evict", evict: object} |
|
|
108
|
+
* {action: "reject", reason: string}}
|
|
109
|
+
*/
|
|
110
|
+
export function decideConnectionAdmission({ currentSize, maxConnections, entries, incoming = {}, now = Date.now(), minAgeMs = SSE_EVICT_MIN_AGE_MS }) {
|
|
111
|
+
if (currentSize < maxConnections) return { action: "accept" };
|
|
112
|
+
// 配额被调小到低于当前连接数:不通过连续驱逐掩盖配置问题(每次准入最多 1 条的原则)。
|
|
113
|
+
if (currentSize > maxConnections) return { action: "reject", reason: "over-capacity" };
|
|
114
|
+
const plan = planConnectionAdmission({ entries, incoming, now, minAgeMs });
|
|
115
|
+
if (!plan.evict) return { action: "reject", reason: "no-eligible" };
|
|
116
|
+
return { action: "evict", evict: plan.evict };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 满池时的准入计划:最多返回 1 条可驱逐连接;没有年龄达标的候选就拒绝。
|
|
121
|
+
*
|
|
122
|
+
* **只在 `connections.size >= maxConnections` 时调用**;未满池直接接受,不经过本函数。
|
|
123
|
+
*
|
|
124
|
+
* @param {object} args
|
|
125
|
+
* @param {{res: unknown, meta: object}[]} args.entries 当前在网连接
|
|
126
|
+
* @param {{clientIp?: string, clientId?: string}} [args.incoming] 新连接的来源信息
|
|
127
|
+
* @param {number} [args.now]
|
|
128
|
+
* @param {number} [args.minAgeMs] 安全年龄(默认 60s)
|
|
129
|
+
* @returns {{evict: null | {res: unknown, meta: object, ageMs: number, idleMs: number, stalled: boolean, reason: string, eligible: number}, eligible: number, stalled: number}}
|
|
130
|
+
*/
|
|
131
|
+
export function planConnectionAdmission({ entries, incoming = {}, now = Date.now(), minAgeMs = SSE_EVICT_MIN_AGE_MS }) {
|
|
132
|
+
const eligible = [];
|
|
133
|
+
for (const entry of entries ?? []) {
|
|
134
|
+
const meta = entry?.meta;
|
|
135
|
+
if (!meta) continue;
|
|
136
|
+
const ageMs = Math.max(0, now - meta.createdAt);
|
|
137
|
+
if (ageMs < minAgeMs) continue;
|
|
138
|
+
eligible.push({
|
|
139
|
+
res: entry.res,
|
|
140
|
+
meta,
|
|
141
|
+
ageMs,
|
|
142
|
+
idleMs: Math.max(0, now - meta.lastWriteAt),
|
|
143
|
+
stalled: isSseConnectionStalled(meta, now),
|
|
144
|
+
tier: identityTier(meta, incoming),
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
if (eligible.length === 0) {
|
|
148
|
+
return { evict: null, eligible: 0, stalled: 0 };
|
|
149
|
+
}
|
|
150
|
+
for (const candidate of eligible) candidate.reason = TIER_REASON[candidate.tier];
|
|
151
|
+
eligible.sort(
|
|
152
|
+
(a, b) =>
|
|
153
|
+
(a.stalled === b.stalled ? 0 : a.stalled ? -1 : 1) ||
|
|
154
|
+
a.tier - b.tier ||
|
|
155
|
+
a.meta.createdAt - b.meta.createdAt ||
|
|
156
|
+
String(a.meta.id ?? "").localeCompare(String(b.meta.id ?? "")),
|
|
157
|
+
);
|
|
158
|
+
const best = eligible[0];
|
|
159
|
+
return {
|
|
160
|
+
evict: {
|
|
161
|
+
res: best.res,
|
|
162
|
+
meta: best.meta,
|
|
163
|
+
ageMs: best.ageMs,
|
|
164
|
+
idleMs: best.idleMs,
|
|
165
|
+
stalled: best.stalled,
|
|
166
|
+
reason: best.reason,
|
|
167
|
+
eligible: eligible.length,
|
|
168
|
+
},
|
|
169
|
+
eligible: eligible.length,
|
|
170
|
+
stalled: eligible.filter((candidate) => candidate.stalled).length,
|
|
171
|
+
};
|
|
172
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktrue/dsh-mobile-remote",
|
|
3
|
-
"version": "3.2.4-rc.
|
|
3
|
+
"version": "3.2.4-rc.6",
|
|
4
4
|
"description": "DSH Mobile:把 DeepSeek Harness 变成随身控制台——手机远程发消息派活、看进度、收通知、审批决策、管理会话;配套 Flutter App(当前 Android 端,iOS 未开发)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"qrcode"
|
|
53
53
|
],
|
|
54
54
|
"optionalDependencies": {
|
|
55
|
-
"@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-rc.
|
|
55
|
+
"@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-rc.6-app"
|
|
56
56
|
},
|
|
57
57
|
"peerDependencies": {
|
|
58
58
|
"@deepseek-ai/dsh-credentials": ">=0.1.0-rc.6 <=0.2.2 || >=0.2.0-0 <0.2.0 || >=0.2.1-0 <0.2.1 || >=0.2.2-0 <0.2.2",
|