dsh-mobile-plugin 0.5.41 → 0.5.45

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.
@@ -0,0 +1,244 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 交付声明补格:把 `deliverables/presented` 里每一份的 size / mtime 一起带上。
5
+ *
6
+ * 轮尾那张「交付文件卡」的第二行要写「1.2 MB · 今天 14:32」。电脑这边本来就知道文件在哪,
7
+ * 所以在**投影交付声明时顺手量一下**,手机端一条额外请求都不用发。
8
+ *
9
+ * 三条硬约束,改的时候别破:
10
+ *
11
+ * 1. **放行面复用 `createSessionFileScope`**(经 `session-artifacts.js` 的 `inspectPaths`):
12
+ * 能 stat 的路径 = 本来就能下载的那一批(本会话工作区 ∪ 本会话声明过)。这里一次也**不**
13
+ * 直接 `fs.stat` 任意路径 —— 那等于把移动 API 的读口子开到整台机器上。
14
+ * 2. **不许拖慢 `/session/messages`**:只在出现交付声明的路径上做、并发封在
15
+ * `ARTIFACT_STAT_CONCURRENCY`(8),整批还有总预算,超时就当没补。开屏与轮询是主路径,
16
+ * 网络盘上一条 stat 卡住也不能把整页消息一起钉住。
17
+ * 3. **失败一律静默降级**:denied / missing / stat 抛错 / 超时 → 该条就只有 path
18
+ * (+description),不抛错、不改 HTTP 状态码、不影响这一页的其它内容。
19
+ *
20
+ * 缓存都不落盘(与 `session-artifacts.js` 同一个口径,见 A1-139 的坑),分两层:
21
+ * - 投影那一路:`deriveMessages` 的结果本来就在 `derived-cache` 里按事件指纹缓存,同一份
22
+ * 结果第二次出来是**同一个数组引用**,所以这里按那个引用记账(表住在 `session-cache.js`,
23
+ * 模块级可变状态只许在那儿)—— 同指纹的第二次调用一次 stat 都不发。补齐后的数组是新的,
24
+ * 缓存里那份保持只读不变。
25
+ * - 实时流那一路:按 `callId` 记一条在飞 / 已完成的 promise,同一帧重发不重复 stat。
26
+ */
27
+
28
+ const {
29
+ inspectPaths,
30
+ ARTIFACT_STAT_CONCURRENCY,
31
+ } = require('./session-artifacts.js');
32
+ const {
33
+ presentedFileStatsOf,
34
+ rememberPresentedFileStats,
35
+ forgetPresentedFileStats,
36
+ } = require('./session-cache.js');
37
+
38
+ /**
39
+ * 投影那一路的整批预算。
40
+ *
41
+ * 一页里的交付文件通常在个位数到十几个,局域网盘上批量 stat 是个位数毫秒;1500ms 是给
42
+ * 「网络盘 / 文件被别的进程占着」留的余量,到点就放弃补齐照常返回 —— 那两格字值不了更长。
43
+ */
44
+ const PRESENTED_STAT_BUDGET_MS = 1500;
45
+
46
+ /**
47
+ * 实时流那一帧的预算。
48
+ *
49
+ * **远小于投影那一路**,因为它卡的是帧顺序而不是一页响应:`deliverables/presented` 要排在
50
+ * 收尾正文之后发出去,后面的帧才跟着走。弱网 + 长任务下,晚两格字比晚一整帧糟得多 ——
51
+ * 超时就发未补的版本,绝不 await 到底。
52
+ */
53
+ const PRESENTED_FRAME_STAT_BUDGET_MS = 400;
54
+
55
+ /**
56
+ * 跑一批 stat,但最多等 `budgetMs`。
57
+ *
58
+ * 超时回 `null`(调用方据此发未补的版本)。已经开始的那批不取消:它自己会跑完,结果丢掉就是。
59
+ * `inspectPaths` 内部逐条兜住,所以这里不该有异常冒出来 —— 真冒出来也按「没补」处理。
60
+ *
61
+ * @returns {Promise<Array|null>}
62
+ */
63
+ function statWithinBudget(ctx, sessionId, paths, budgetMs) {
64
+ if (paths.length === 0) return Promise.resolve([]);
65
+ if (!(budgetMs > 0)) return Promise.resolve(null);
66
+ let timer = null;
67
+ const guard = new Promise((resolve) => {
68
+ timer = setTimeout(() => resolve(null), budgetMs);
69
+ // 定时器不该拖住进程退出(与 stream.js 的 keepAlive 同一条理由)。
70
+ if (timer && typeof timer.unref === 'function') timer.unref();
71
+ });
72
+ const work = inspectPaths(ctx, sessionId, paths).catch(() => null);
73
+ return Promise.race([work, guard]).finally(() => {
74
+ if (timer) clearTimeout(timer);
75
+ });
76
+ }
77
+
78
+ /** 把 `rows` 里的 size/mtime 盖回文件对象;没量到的保持原样。 */
79
+ function applyStats(files, rows) {
80
+ const byPath = new Map();
81
+ for (const row of rows) {
82
+ if (row && row.status === 'ok') byPath.set(row.path, row);
83
+ }
84
+ if (byPath.size === 0) return files;
85
+ return files.map((file) => {
86
+ const row = byPath.get(file.path);
87
+ if (!row) return file;
88
+ return { ...file, size: row.size, mtime: row.mtime };
89
+ });
90
+ }
91
+
92
+ /**
93
+ * 一批消息上的交付声明要不要补格:收集去重后的路径。
94
+ *
95
+ * @param {unknown[]} messages `deriveMessages` 的输出
96
+ */
97
+ function presentedPathsIn(messages) {
98
+ const paths = [];
99
+ const seen = new Set();
100
+ for (const item of messages) {
101
+ if (!item || !Array.isArray(item.presentedFiles)) continue;
102
+ for (const file of item.presentedFiles) {
103
+ if (!file || typeof file.path !== 'string' || file.path === '') continue;
104
+ if (seen.has(file.path)) continue;
105
+ seen.add(file.path);
106
+ paths.push(file.path);
107
+ }
108
+ }
109
+ return paths;
110
+ }
111
+
112
+ /**
113
+ * 给 `deriveMessages` 的输出补上交付文件的 size / mtime。
114
+ *
115
+ * 返回**新的**消息数组(只有带 `presentedFiles` 的那几条是新的对象),没补到任何一条时原样
116
+ * 返回入参 —— 调用方可以按引用判断「有没有变化」。`messages` 本身是 `derived-cache` 交回来
117
+ * 的那份,**不许就地改**(见 `shared/derived-cache.js`)。
118
+ *
119
+ * @param {object} ctx 插件上下文
120
+ * @param {string} sessionId 会话 id
121
+ * @param {unknown[]} messages `deriveMessages` 出来的消息
122
+ * @param {{budgetMs?: number}} [options]
123
+ * @returns {Promise<unknown[]>}
124
+ */
125
+ function withPresentedFileStats(ctx, sessionId, messages, options = {}) {
126
+ if (!sessionId || !Array.isArray(messages) || messages.length === 0) return Promise.resolve(messages);
127
+ return statsRowsFor(ctx, sessionId, messages, options)
128
+ .then((rows) => applyRows(messages, rows));
129
+ }
130
+
131
+ /**
132
+ * 这一批消息要量哪些路径,量到的那些行按「消息数组」记账。
133
+ *
134
+ * 记的键是 `messages` 引用本身:`deriveMessages` 的缓存对同一份事件交回同一个数组,所以
135
+ * 同一指纹的第二次调用在这里直接命中,一次 stat 都不再发。
136
+ */
137
+ function statsRowsFor(ctx, sessionId, messages, options = {}) {
138
+ const paths = presentedPathsIn(messages);
139
+ if (paths.length === 0) return Promise.resolve([]);
140
+ const cached = presentedFileStatsOf(ctx, messages);
141
+ if (cached) return cached;
142
+ const budgetMs = Number.isFinite(options.budgetMs) ? options.budgetMs : PRESENTED_STAT_BUDGET_MS;
143
+ const pending = statWithinBudget(ctx, sessionId, paths, budgetMs).then((rows) => {
144
+ // 超时:**不记账**。这一发只是没等到,下一发同指纹还能再试一次。
145
+ if (rows === null) {
146
+ forgetPresentedFileStats(ctx, messages);
147
+ return [];
148
+ }
149
+ return rows;
150
+ }).catch(() => {
151
+ forgetPresentedFileStats(ctx, messages);
152
+ return [];
153
+ });
154
+ rememberPresentedFileStats(ctx, messages, pending);
155
+ return pending;
156
+ }
157
+
158
+ /** 把量到的那些行盖回消息里的 `presentedFiles`;一条都没盖上时原样返回入参。 */
159
+ function applyRows(messages, rows) {
160
+ if (!Array.isArray(rows) || rows.length === 0) return messages;
161
+ let changed = false;
162
+ const next = messages.map((item) => {
163
+ if (!item || !Array.isArray(item.presentedFiles) || item.presentedFiles.length === 0) return item;
164
+ const files = applyStats(item.presentedFiles, rows);
165
+ if (files === item.presentedFiles) return item;
166
+ changed = true;
167
+ return { ...item, presentedFiles: files };
168
+ });
169
+ return changed ? next : messages;
170
+ }
171
+
172
+ /**
173
+ * 实时流那一帧的补格器(**一条流一份**)。
174
+ *
175
+ * `deliverables/presented` 在流里就是原样转发的一帧,事件本身不带 size/mtime。这里按
176
+ * `callId` 记账:同一帧重复到达(回放 + 实时交界、或者宿主重发)不再 stat 一遍;超过这一帧的
177
+ * 小预算就发未补的版本,帧顺序优先。
178
+ *
179
+ * @param {object} ctx 插件上下文
180
+ * @param {string} sessionId 会话 id
181
+ * @param {{budgetMs?: number}} [options]
182
+ */
183
+ function createPresentedStats(ctx, sessionId, options = {}) {
184
+ const budgetMs = Number.isFinite(options.budgetMs) ? options.budgetMs : PRESENTED_FRAME_STAT_BUDGET_MS;
185
+ /** 帧身份 → 量到的那些行(这一条流自己的小账,不进上面那张按引用的表)。 */
186
+ const done = new Map();
187
+ /** 帧身份 → 在飞的那一趟(同一帧并发到达时合并,别各 stat 一遍)。 */
188
+ const inFlight = new Map();
189
+
190
+ /** 帧身份:有 `callId` 就用它,没有就按路径清单认(一轮里也就一两帧)。 */
191
+ const keyOf = (data, files) => {
192
+ if (typeof data.callId === 'string' && data.callId !== '') return `c:${data.callId}`;
193
+ return `p:${files.map((file) => file.path).join('\u0000')}`;
194
+ };
195
+
196
+ /**
197
+ * 给一帧 `deliverables/presented` 补 size / mtime。
198
+ *
199
+ * 回**新的**事件对象(`data.files` 换掉),任何失败 / 超时都原样回入参。
200
+ */
201
+ async function enrich(event) {
202
+ if (!event || event.type !== 'deliverables/presented') return event;
203
+ const data = event.data;
204
+ if (!data || typeof data !== 'object' || !Array.isArray(data.files) || data.files.length === 0) return event;
205
+ const files = data.files.filter((file) => file && typeof file.path === 'string' && file.path !== '');
206
+ if (files.length === 0) return event;
207
+ const key = keyOf(data, files);
208
+ const settled = done.get(key);
209
+ if (settled !== undefined) {
210
+ if (!settled) return event;
211
+ return { ...event, data: { ...data, files: applyStats(data.files, settled) } };
212
+ }
213
+ let pending = inFlight.get(key);
214
+ if (!pending) {
215
+ const paths = [...new Set(files.map((file) => file.path))];
216
+ pending = statWithinBudget(ctx, sessionId, paths, budgetMs)
217
+ .then((rows) => {
218
+ // 超时 / 整批失败:这一帧发未补的版本,且不记账 —— 下一帧同样的 key 允许再试。
219
+ if (rows === null) done.delete(key);
220
+ else done.set(key, rows);
221
+ return rows;
222
+ })
223
+ .catch(() => {
224
+ done.delete(key);
225
+ return null;
226
+ })
227
+ .finally(() => { inFlight.delete(key); });
228
+ inFlight.set(key, pending);
229
+ }
230
+ const rows = await pending;
231
+ if (rows === null) return event;
232
+ return { ...event, data: { ...data, files: applyStats(data.files, rows) } };
233
+ }
234
+
235
+ return { enrich };
236
+ }
237
+
238
+ module.exports = {
239
+ withPresentedFileStats,
240
+ createPresentedStats,
241
+ PRESENTED_STAT_BUDGET_MS,
242
+ PRESENTED_FRAME_STAT_BUDGET_MS,
243
+ ARTIFACT_STAT_CONCURRENCY,
244
+ };
@@ -36,7 +36,7 @@ const { sendJson } = require('../shared/http-util');
36
36
  const { unwrap } = require('./envelope.js');
37
37
  const { callSessions } = require('./rpc.js');
38
38
  const { liveStepsOf, liveStepsTurnOf } = require('./live-steps.js');
39
- const { buildToolResultMap, parseBlocks, blocksToText } = require('./history-derive.js');
39
+ const { buildToolResultMap, parseBlocks, userVisibleText } = require('./history-derive.js');
40
40
  const { reasoningText, reasoningStepSummary, toolStepSummary, toolStepState } = require('./step-index.js');
41
41
 
42
42
  /**
@@ -240,7 +240,10 @@ function turnMetaOf(events, turn) {
240
240
  if (event.type === 'turn/start' && typeof event.time === 'number') startedAt = event.time;
241
241
  if (event.type === 'user/message') {
242
242
  const content = event.data && Array.isArray(event.data.content) ? event.data.content : [];
243
- const text = blocksToText(parseBlocks(content, toolResults)).trim();
243
+ // 轮标题取的是「用户说了什么」:用 `userVisibleText` 而不是裸 `blocksToText` —— 照片说明
244
+ // 那几行是发给模型看的元数据(哨兵见 `app/src/services/viewmodels/photo-caption.ts`),
245
+ // 混进标题就是时间线上一行「[照片 …]」,而用户其实什么都没写。
246
+ const text = userVisibleText(parseBlocks(content, toolResults)).trim();
244
247
  if (text !== '' && title === '') title = text.length > 120 ? `${text.slice(0, 119)}…` : text;
245
248
  }
246
249
  if (event.type === 'turn/end') {