dsh-mobile-plugin 0.5.118 → 0.5.120
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/README.md +2 -2
- package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +3 -2
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network-guide.md +1 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network.md +2 -4
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/port-conflict.md +42 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay-server.md +1 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay.md +11 -15
- package/lib/cloudflared/wiring.cjs +88 -10
- package/lib/impl.js +59 -22
- package/lib/mirror/pusher.cjs +150 -139
- package/lib/mobile/channel-proxy.js +204 -0
- package/lib/mobile/channels.js +100 -0
- package/lib/mobile/events.js +2 -1
- package/lib/mobile/host-bridge/endpoints.js +3 -0
- package/lib/mobile/host-bridge/event-synthesis.js +38 -10
- package/lib/mobile/permissions.js +5 -2
- package/lib/mobile/push-notify.js +39 -106
- package/lib/mobile/rpc.js +7 -4
- package/lib/mobile/session-cache.js +8 -0
- package/lib/mobile/sessions.js +26 -6
- package/lib/panel/index.html +25 -25
- package/lib/relay/address-slot.cjs +1 -1
- package/lib/relay/config-store.js +23 -4
- package/lib/relay/control.js +2 -2
- package/lib/relay/core.js +27 -156
- package/lib/relay/ingress-guard.cjs +111 -0
- package/lib/relay/lan-proxy.js +56 -2
- package/lib/relay/pairing-check.cjs +181 -0
- package/lib/relay/pairing-payload.cjs +7 -19
- package/lib/relay/protocol.js +1 -2
- package/lib/relay/relay-probe.js +1 -1
- package/lib/relay/status.js +8 -0
- package/lib/remote/host-control.cjs +1 -1
- package/lib/routes/control-plane.js +53 -18
- package/lib/routes/mobile-api.js +11 -21
- package/lib/sidecar-facade-worker.cjs +18 -11
- package/lib/zeronews/runner.cjs +11 -3
- package/lib/zeronews/wiring.cjs +12 -2
- package/package.json +14 -13
- package/lib/mobile/notification-prefs.js +0 -205
- package/lib/mobile/push-notify-route.js +0 -37
package/lib/mobile/channels.js
CHANGED
|
@@ -20,6 +20,9 @@ const { unwrap } = require('./envelope.js');
|
|
|
20
20
|
const { dropSessionModelsForDevice } = require('./session-cache.js');
|
|
21
21
|
const { unchangedListBody, revisionOf, stableRevision } = require('../shared/list-revision.js');
|
|
22
22
|
const { lookupModelMeta } = require('./model-meta.js');
|
|
23
|
+
// 「本机跑的渠道,手机打电脑的局域网地址能不能通」要这台机器的网卡清单;纯计算,住在代里。
|
|
24
|
+
const os = require('node:os');
|
|
25
|
+
const { lanInterfaces } = require('../relay/lan-network.cjs');
|
|
23
26
|
|
|
24
27
|
/** 自建渠道写在这个命名空间里;桌面端 `src/custom-channels.js` 的 PI_AI_NS 同值。 */
|
|
25
28
|
const PI_AI_NS = 'llm-pi-ai';
|
|
@@ -202,6 +205,36 @@ function customChannelOf(id, profile) {
|
|
|
202
205
|
};
|
|
203
206
|
}
|
|
204
207
|
|
|
208
|
+
/** 只在这台电脑上成立的主机名:手机拨这些地址一律打到自己身上,永远不通。 */
|
|
209
|
+
const LOCAL_ONLY_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '::1']);
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 一条渠道地址 → 手机该依次试的地址。
|
|
213
|
+
*
|
|
214
|
+
* 头一个是原样。原样是本机 / 通配主机时,再补「这台电脑的每个局域网 IPv4 + 同一个端口」:
|
|
215
|
+
* 同一 Wi-Fi 下手机打电脑的局域网地址是通的,本机跑的 Ollama、one-api 就不必绕经电脑转发。
|
|
216
|
+
* 只换主机,协议、端口、路径原样保留;地址本身解析不了就只回原样,让手机自己去报地址错。
|
|
217
|
+
*/
|
|
218
|
+
function reachCandidatesOf(baseUrl, interfaces) {
|
|
219
|
+
const candidates = [baseUrl];
|
|
220
|
+
let parsed;
|
|
221
|
+
try {
|
|
222
|
+
parsed = new URL(baseUrl);
|
|
223
|
+
} catch {
|
|
224
|
+
return candidates;
|
|
225
|
+
}
|
|
226
|
+
const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
227
|
+
if (!LOCAL_ONLY_HOSTS.has(host)) return candidates;
|
|
228
|
+
const defaultPort = parsed.protocol === 'https:' ? 443 : 80;
|
|
229
|
+
const port = Number(parsed.port) || defaultPort;
|
|
230
|
+
const suffix = port === defaultPort ? '' : `:${port}`;
|
|
231
|
+
const pathname = parsed.pathname === '/' ? '' : parsed.pathname;
|
|
232
|
+
for (const row of lanInterfaces(port, interfaces)) {
|
|
233
|
+
candidates.push(`${parsed.protocol}//${row.address}${suffix}${pathname}${parsed.search}`);
|
|
234
|
+
}
|
|
235
|
+
return candidates;
|
|
236
|
+
}
|
|
237
|
+
|
|
205
238
|
/**
|
|
206
239
|
* GET /api/mobile/v1/channels —— 这台宿主的渠道清单(自建 + 插件提供)。
|
|
207
240
|
*
|
|
@@ -605,16 +638,83 @@ async function handleChannelDelete(ctx, req, res) {
|
|
|
605
638
|
sendJson(res, 200, { ok: true });
|
|
606
639
|
}
|
|
607
640
|
|
|
641
|
+
/**
|
|
642
|
+
* 按 id 取一条自建渠道,连同它那把 Key。
|
|
643
|
+
*
|
|
644
|
+
* 两个调用方:导出给手机(一键导入),以及「经电脑转发」的模型请求(见 channel-proxy.js)。
|
|
645
|
+
* 两边要的是同一份东西——名字、协议、地址、Key——所以查找只写一遍:只认 `llm-pi-ai` 的
|
|
646
|
+
* `providers`,插件 / 宿主注册的提供方在这里一律找不到。
|
|
647
|
+
*
|
|
648
|
+
* Key 取不到不算失败:`apiKey` 留空、`keySet` 说明有没有,由调用方决定怎么办。
|
|
649
|
+
*/
|
|
650
|
+
async function customChannelWithKey(ctx, id) {
|
|
651
|
+
const settings = unwrap(await ctx.apiProxy.settings.describe({
|
|
652
|
+
rpcId: 'mobile',
|
|
653
|
+
method: 'settings.describe',
|
|
654
|
+
payload: {},
|
|
655
|
+
}));
|
|
656
|
+
if (settings.error) return { error: settings.error };
|
|
657
|
+
const namespaces = Array.isArray(settings.value && settings.value.namespaces) ? settings.value.namespaces : [];
|
|
658
|
+
const piAi = namespaces.find((entry) => entry && entry.ns === PI_AI_NS);
|
|
659
|
+
const providers = piAiProvidersOf(piAi && piAi.value);
|
|
660
|
+
const channel = Object.prototype.hasOwnProperty.call(providers, id) ? customChannelOf(id, providers[id]) : null;
|
|
661
|
+
if (!channel) return { error: { code: 'channel-not-found', message: '这台电脑上没有这条自建渠道' }, status: 404 };
|
|
662
|
+
let apiKey = '';
|
|
663
|
+
try {
|
|
664
|
+
const resolved = unwrap(await ctx.apiProxy.credentials.resolve({
|
|
665
|
+
rpcId: 'mobile',
|
|
666
|
+
method: 'credentials.resolve',
|
|
667
|
+
payload: { ref: credentialRefOf(id) },
|
|
668
|
+
}));
|
|
669
|
+
if (!resolved.error && resolved.value && typeof resolved.value.value === 'string') apiKey = resolved.value.value;
|
|
670
|
+
} catch { /* 宿主没注册 resolve:按「没带 Key」处理 */ }
|
|
671
|
+
return { channel, apiKey, keySet: apiKey !== '' };
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* POST /api/mobile/v1/channels/export(token){ id }
|
|
676
|
+
* → { ok, channel, keySet, candidates }
|
|
677
|
+
*
|
|
678
|
+
* 把电脑上这条自建渠道整条交给手机,给「本机 Agent 新增渠道」页的一键导入用:名字、协议、
|
|
679
|
+
* 地址、模型,以及**它的 Key**。手机本来就为手动添加的渠道在本地存着同一把 Key,这里只是
|
|
680
|
+
* 把「用户再敲一遍」换成「电脑交过来」,不是新开一类暴露。
|
|
681
|
+
*
|
|
682
|
+
* 只认自建那一类:插件 / 宿主注册的提供方没有可搬的地址,也没有一把属于这条路由的 Key。
|
|
683
|
+
* Key 只在用户点名这一条时取一次,取不到(宿主没注册 resolve、凭据是环境变量提供的)就
|
|
684
|
+
* 如实回 keySet:false,由手机让用户自己填,不把失败报成整条导入失败。
|
|
685
|
+
*
|
|
686
|
+
* `candidates` 是手机该依次试的地址(见 reachCandidatesOf):本机地址会多出局域网那几个,
|
|
687
|
+
* 手机探通哪个用哪个,全不通就说明这条渠道只有电脑够得着。
|
|
688
|
+
*/
|
|
689
|
+
async function handleChannelExport(ctx, req, res) {
|
|
690
|
+
const body = await readJsonBody(req, 8 * 1024);
|
|
691
|
+
const id = body && typeof body.id === 'string' ? body.id.trim() : '';
|
|
692
|
+
if (!CHANNEL_ID_PATTERN.test(id)) {
|
|
693
|
+
return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要渠道 id' } });
|
|
694
|
+
}
|
|
695
|
+
const found = await customChannelWithKey(ctx, id);
|
|
696
|
+
if (found.error) return sendJson(res, found.status || 400, { ok: false, error: found.error });
|
|
697
|
+
sendJson(res, 200, {
|
|
698
|
+
ok: true,
|
|
699
|
+
channel: { ...found.channel, ...(found.apiKey === '' ? {} : { apiKey: found.apiKey }) },
|
|
700
|
+
keySet: found.keySet,
|
|
701
|
+
candidates: reachCandidatesOf(found.channel.baseUrl, os.networkInterfaces()),
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
|
|
608
705
|
module.exports = {
|
|
609
706
|
handleChannels,
|
|
610
707
|
handleChannelDiscover,
|
|
611
708
|
handleChannelSave,
|
|
612
709
|
handleChannelDelete,
|
|
710
|
+
handleChannelExport,
|
|
711
|
+
customChannelWithKey,
|
|
613
712
|
credentialRefOf,
|
|
614
713
|
providerIdOf,
|
|
615
714
|
normalizeBaseUrl,
|
|
616
715
|
normalizeModels,
|
|
617
716
|
profileOf,
|
|
618
717
|
discoverCandidates,
|
|
718
|
+
reachCandidatesOf,
|
|
619
719
|
PI_AI_NS,
|
|
620
720
|
};
|
package/lib/mobile/events.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 清单事件同时识别 event.type 与 event.data.type,正文仍只走会话流。
|
|
1
2
|
// 转发设备事件,并按已鉴权实例登记可吊销的 SSE 连接。
|
|
2
3
|
/**
|
|
3
4
|
* 设备流响应声明心跳周期,供客户端检测首帧缺失。
|
|
@@ -112,7 +113,7 @@ function listRelevantPayload(rawPayload) {
|
|
|
112
113
|
if (type === 'session/event') {
|
|
113
114
|
const ev = rawPayload.event && typeof rawPayload.event === 'object' ? rawPayload.event : null;
|
|
114
115
|
const inner = ev && ev.data && typeof ev.data === 'object' ? ev.data.type : undefined;
|
|
115
|
-
if (LIST_EVENT_INNER.has(inner)) return lightPayload(rawPayload);
|
|
116
|
+
if (LIST_EVENT_INNER.has(ev && ev.type) || LIST_EVENT_INNER.has(inner)) return lightPayload(rawPayload);
|
|
116
117
|
return null;
|
|
117
118
|
}
|
|
118
119
|
return null;
|
|
@@ -158,6 +158,9 @@ const ENDPOINTS = {
|
|
|
158
158
|
});
|
|
159
159
|
}),
|
|
160
160
|
'credentials.describe': inv('credentials', 'describe', (p) => ({ refs: p.refs })),
|
|
161
|
+
// 取一次凭据的值:只给「把这条自建渠道交给手机」用(见 mobile/channels.js 的导出路由)。
|
|
162
|
+
// describe 回的是状态、resolve 回的才是值,两者在宿主那边是分开的两个方法。
|
|
163
|
+
'credentials.resolve': inv('credentials', 'resolve', (p) => ({ ref: p.ref })),
|
|
161
164
|
'credentials.set': inv('credentials', 'set', (p) => ({ ref: p.ref, value: p.value })),
|
|
162
165
|
'credentials.unset': inv('credentials', 'unset', (p) => ({ ref: p.ref })),
|
|
163
166
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 设备级工作区与会话控制流并发接收,并在取消或结束消费时一并回收。
|
|
1
2
|
// 单会话 follow 仅按明确 activate 请求恢复 Agent;历史和被动订阅保持不激活。
|
|
2
3
|
'use strict';
|
|
3
4
|
|
|
@@ -384,20 +385,47 @@ async function* projectionFrames(ctx, sessionId, signal) {
|
|
|
384
385
|
}
|
|
385
386
|
}
|
|
386
387
|
|
|
387
|
-
/**
|
|
388
|
+
/** 设备级:工作区基线与全局投影并发接收,长流互不等待结束。 */
|
|
388
389
|
async function* deviceFrames(ctx, signal) {
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
390
|
+
const controller = new AbortController();
|
|
391
|
+
const abort = () => controller.abort();
|
|
392
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
393
|
+
if (signal?.aborted) abort();
|
|
394
|
+
const sources = [];
|
|
395
|
+
try {
|
|
396
|
+
const childSignal = controller.signal;
|
|
397
|
+
const workspace = openStream(ctx, 'workspace', 'follow', {}, childSignal);
|
|
398
|
+
sources.push((async function* () {
|
|
399
|
+
const frames = await workspace;
|
|
400
|
+
for await (const frame of tolerate(frames, 'workspace/follow', ctx)) {
|
|
401
|
+
if (!frame) continue;
|
|
402
|
+
if (frame.type === 'baseline' && frame.value) {
|
|
403
|
+
yield { payload: { type: 'host/workspace', ...frame.value } };
|
|
404
|
+
} else if (frame.type === 'increment' || frame.type === 'change') {
|
|
405
|
+
yield { payload: { type: 'host/workspace', ...(frame.value && typeof frame.value === 'object' ? frame.value : { change: frame }) } };
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
})());
|
|
409
|
+
sources.push(projectionFrames(ctx, null, childSignal));
|
|
410
|
+
const read = index => sources[index].next().then(step => ({ index, step }), error => ({ index, error }));
|
|
411
|
+
const pending = new Map(sources.map((_, index) => [index, read(index)]));
|
|
412
|
+
while (pending.size > 0) {
|
|
413
|
+
const winner = await Promise.race(pending.values());
|
|
414
|
+
if (winner.error) {
|
|
415
|
+
warn(ctx, `设备事件流中断:${winner.error.message || String(winner.error)}`);
|
|
416
|
+
pending.delete(winner.index);
|
|
417
|
+
} else if (winner.step.done) {
|
|
418
|
+
pending.delete(winner.index);
|
|
419
|
+
} else {
|
|
420
|
+
pending.set(winner.index, read(winner.index));
|
|
421
|
+
yield winner.step.value;
|
|
397
422
|
}
|
|
398
423
|
}
|
|
424
|
+
} finally {
|
|
425
|
+
controller.abort();
|
|
426
|
+
signal?.removeEventListener('abort', abort);
|
|
427
|
+
for (const source of sources) void source.return().catch(() => {});
|
|
399
428
|
}
|
|
400
|
-
yield* projectionFrames(ctx, null, signal);
|
|
401
429
|
}
|
|
402
430
|
|
|
403
431
|
/** 旧 `events.mux`:设备级帧流,带 sessionId 时收窄成单会话视角。 */
|
|
@@ -153,8 +153,6 @@ const BASE = Object.freeze([
|
|
|
153
153
|
'/api/mobile/v1/connection-info',
|
|
154
154
|
'/api/mobile/v1/tunnel',
|
|
155
155
|
'/api/mobile/v1/p2p/rendezvous',
|
|
156
|
-
'/api/mobile/v1/push-token',
|
|
157
|
-
'/api/mobile/v1/notification-prefs',
|
|
158
156
|
'/api/mobile/v1/device-credential/revoke',
|
|
159
157
|
'/api/mobile/v1/device-credential/upgrade',
|
|
160
158
|
// 换身份过渡期:用旧号下的凭据换当前号的新凭据,属于「自愈」,任何已鉴权设备都能调。
|
|
@@ -219,6 +217,11 @@ const MAP = Object.freeze({
|
|
|
219
217
|
'/api/mobile/v1/channels/discover': V.CONFIG,
|
|
220
218
|
'/api/mobile/v1/channels/save': V.CONFIG,
|
|
221
219
|
'/api/mobile/v1/channels/delete': V.CONFIG,
|
|
220
|
+
// 导入一条:读出来的是渠道配置**与它那把 Key**。归「改模型 / 渠道配置」这一档,
|
|
221
|
+
// 与保存 / 删除同权 —— 能改这条渠道的设备本来就能给它换一把新的 Key。
|
|
222
|
+
'/api/mobile/v1/channels/export': V.CONFIG,
|
|
223
|
+
// 经电脑转发一次对话:动的是这条渠道的 Key 与它的额度,归同一档。
|
|
224
|
+
'/api/mobile/v1/channels/chat': V.CONFIG,
|
|
222
225
|
'/api/mobile/v1/plugins': V.VIEW,
|
|
223
226
|
'/api/mobile/v1/skills': V.VIEW,
|
|
224
227
|
'/api/mobile/v1/narration': { GET: V.VIEW, POST: V.FILES_WRITE },
|
|
@@ -1,37 +1,23 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* iOS 推送的宿主侧出口:完成 / 失败 /
|
|
5
|
-
*
|
|
4
|
+
* iOS 推送的宿主侧出口:完成 / 失败 / 待处理(审批、提问)发生时,直接请求总控,
|
|
5
|
+
* 由总控调 APNs 送到苹果。总控没配密钥时那头静默忽略,这里照发不误——
|
|
6
6
|
* 「推没推成」不是宿主的账,宿主只负责「该推的时候说一声」。
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* 走总控而不是中转:中转是「一人一台」(还有大量自建),苹果密钥只能配在总控那一台上。
|
|
9
|
+
* 请求带本机那枚总控设备令牌(与上报地址同一枚),所以不用再开别的鉴权面。总控连不上时
|
|
10
|
+
* 这次提醒就放弃——App 端自己的本地通知通道会在它回到前台 / 后台刷新时补上,推送只是增强。
|
|
11
11
|
*
|
|
12
|
-
* ##
|
|
12
|
+
* ## 声音与分类
|
|
13
13
|
*
|
|
14
|
-
* App
|
|
15
|
-
*
|
|
16
|
-
* 查一遍(见 `eventTypeOf`):`completed` → `done`、`failed` → `failed`;待处理按卡的种类拆成
|
|
17
|
-
* `approval` / `question` / `planReview`,映射不上的按 `approval`——宁可多问一次也别漏掉一张
|
|
18
|
-
* 要用户点头的卡。级别 `off` 的就不发。
|
|
19
|
-
*
|
|
20
|
-
* 这一帧的 `deviceId` 留空(推给该实例全部已登记设备),本仓库又没有「令牌 ↔ 偏好桶」的映射表,
|
|
21
|
-
* 所以口径是:**对文件里登记过的每台设备各查它那一份,全部为 off 才不发;还剩一台是
|
|
22
|
-
* ring / silent 就照发**,没有登记过任何桶时按默认档判。偏严的方向是「宁可按默认发」——
|
|
23
|
-
* 漏一条审批提醒让用户卡在那里,比多发一条打扰重得多。
|
|
24
|
-
*
|
|
25
|
-
* ## 已知限制(做不到,不是没做)
|
|
26
|
-
*
|
|
27
|
-
* 只有 `off` 这一档能在推送里兑现。`silent` 要求「上通知栏但不响」,而声音字段是苹果推送负载
|
|
28
|
-
* 的一部分、由中转仓库的 `apns.rs` 决定,本仓库发出去的帧里改不了它;所以 `silent` 在推送
|
|
29
|
-
* 这条路上仍然可能发声,它在 App 进程活着时的本地通知通道里才有效。
|
|
14
|
+
* 推送一律带声音:按事件分级、单会话静音这些开关 App 侧已经整体下线,声音与静音交给系统的
|
|
15
|
+
* 通知设置。通知栏能挂哪些按钮由 `category` 决定(审批 / 提问 / 待处理三类)。
|
|
30
16
|
*
|
|
31
17
|
* ## 去重与可作答
|
|
32
18
|
*
|
|
33
19
|
* 去重账按 `${sessionId}:${rpcId}`(卡)与 `${sessionId}:${turn}:${status}`(轮次)分槽,
|
|
34
|
-
*
|
|
20
|
+
* **只在真的送出去之后**才记:先记账后发的话,网络抖一下这一次就永久丢了(账上有它,下一次
|
|
35
21
|
* 同样的收尾被当成重复吃掉)。发不出去留一行 `console.warn`。
|
|
36
22
|
*
|
|
37
23
|
* 通知栏能不能就地作答只由 `isAnswerable` 判(与 iOS 原生建按钮的条件逐条对齐),判为真的
|
|
@@ -39,9 +25,9 @@
|
|
|
39
25
|
* 点按钮就是 400。
|
|
40
26
|
*/
|
|
41
27
|
|
|
42
|
-
const notificationPrefs = require('./notification-prefs.js');
|
|
43
|
-
|
|
44
28
|
const FRAME_TTL_MS = 10_000;
|
|
29
|
+
/** 一条推送请求的期限:总控回得慢也不该让宿主这一头一直挂着。 */
|
|
30
|
+
const REQUEST_TIMEOUT_MS = 10_000;
|
|
45
31
|
|
|
46
32
|
/** 卡帧(审批 / 提问)的去重窗口。同一张卡会经 noteAsk(占位 id)→ `approval/asked`(真 id)
|
|
47
33
|
* 各 pushCard 一次,两次共用同一个 rpcId —— 按(会话, rpcId)只放一帧,**但「占位 → 真 id」
|
|
@@ -51,14 +37,11 @@ const INTERACTION_TTL_MS = 30_000;
|
|
|
51
37
|
|
|
52
38
|
/**
|
|
53
39
|
* @param {object} deps
|
|
54
|
-
* @param {() =>
|
|
55
|
-
*
|
|
56
|
-
* @param {() => string} [deps.instanceId] 实例标识,帧里带上便于中转日志定位。
|
|
40
|
+
* @param {() => {baseUrl: string, token: string, instanceId: string}|null} deps.controlTarget
|
|
41
|
+
* 总控的入口与那枚设备令牌;没登记过(没有令牌 / 关了上报)就返回 null,这次不发。
|
|
57
42
|
*/
|
|
58
43
|
function createPushNotifier(deps) {
|
|
59
|
-
const
|
|
60
|
-
const tunnelConnected = typeof deps.tunnelConnected === 'function' ? deps.tunnelConnected : () => false;
|
|
61
|
-
const instanceId = typeof deps.instanceId === 'function' ? deps.instanceId : () => '';
|
|
44
|
+
const controlTarget = typeof deps.controlTarget === 'function' ? deps.controlTarget : () => null;
|
|
62
45
|
|
|
63
46
|
/** 已经发出去的帧:key → { at, approvalId? }。key 是 `${sessionId}:${rpcId}`(卡)或
|
|
64
47
|
* `${sessionId}:${turn}:${status}`(轮次)。同一次收尾会被事件流与列表折叠两条路各观察到
|
|
@@ -103,12 +86,12 @@ function createPushNotifier(deps) {
|
|
|
103
86
|
* 送出去的那一帧;发不出去的留一行日志,别静默(这类丢失最难查)。
|
|
104
87
|
*/
|
|
105
88
|
function sendFrame(key, payload, meta) {
|
|
106
|
-
return
|
|
89
|
+
return post(payload).then((ok) => {
|
|
107
90
|
if (!ok) {
|
|
108
|
-
console.warn('[dsh-mobile-plugin] push
|
|
91
|
+
console.warn('[dsh-mobile-plugin] push dropped', {
|
|
109
92
|
kind: meta && meta.kind,
|
|
110
93
|
sessionId: meta && meta.sessionId,
|
|
111
|
-
reason:
|
|
94
|
+
reason: 'send-failed',
|
|
112
95
|
});
|
|
113
96
|
return false;
|
|
114
97
|
}
|
|
@@ -142,40 +125,6 @@ function createPushNotifier(deps) {
|
|
|
142
125
|
return run;
|
|
143
126
|
}
|
|
144
127
|
|
|
145
|
-
/** 事件 kind → 分级表里的类型键(表里只有这五类)。 */
|
|
146
|
-
function eventTypeOf(kind) {
|
|
147
|
-
if (kind === 'completed') return 'done';
|
|
148
|
-
if (kind === 'failed') return 'failed';
|
|
149
|
-
if (kind === 'question') return 'question';
|
|
150
|
-
if (kind === 'plan-review') return 'planReview';
|
|
151
|
-
// 审批卡,以及任何映射不上来的待处理(缺 `pendingInteraction` 等):按审批算。
|
|
152
|
-
// 要用户点头的卡漏掉一条就会把对话卡死,打扰一条只是响一下。
|
|
153
|
-
return 'approval';
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* 这一个类型是不是「要推的每一台设备都关了」。
|
|
158
|
-
*
|
|
159
|
-
* 帧里 `deviceId` 为空 = 推给该实例全部已登记设备,而本仓库没有「APNs 令牌 ↔ 偏好桶」的
|
|
160
|
-
* 映射(令牌登记在中转,桶键是凭据 deviceId),所以只能按「文件里登记过的每一个桶」判定:
|
|
161
|
-
* 全部 off 才不发,还剩一台 ring / silent 就照发(见文件头口径)。没有任何桶时按默认档判。
|
|
162
|
-
* 读文件失败也按默认档判——读不出来不该让通知静默消失。
|
|
163
|
-
*/
|
|
164
|
-
function mutedEverywhere(type) {
|
|
165
|
-
const fallback = notificationPrefs.DEFAULT_EVENT_LEVELS[type] === 'off';
|
|
166
|
-
let store = null;
|
|
167
|
-
try {
|
|
168
|
-
store = notificationPrefs.loadStore();
|
|
169
|
-
} catch {
|
|
170
|
-
store = null;
|
|
171
|
-
}
|
|
172
|
-
const devices = store && store.ok ? store.devices : null;
|
|
173
|
-
if (!devices) return fallback;
|
|
174
|
-
const ids = Object.keys(devices).filter((id) => devices[id] && typeof devices[id] === 'object');
|
|
175
|
-
if (ids.length === 0) return fallback;
|
|
176
|
-
return ids.every((id) => notificationPrefs.normalizeEvents(devices[id].events)[type] === 'off');
|
|
177
|
-
}
|
|
178
|
-
|
|
179
128
|
/**
|
|
180
129
|
* 报告一轮收尾。`fact` 是 session-last-turn 的 `lastTurnOf` 形状
|
|
181
130
|
* ({ turn, endedAt, status, ... }),只有 completed / failed 两种值得推。
|
|
@@ -183,28 +132,18 @@ function createPushNotifier(deps) {
|
|
|
183
132
|
function notifyTurnEnded(sessionId, fact, title) {
|
|
184
133
|
if (!sessionId || !fact || typeof fact.turn !== 'number') return;
|
|
185
134
|
if (fact.status !== 'completed' && fact.status !== 'failed') return;
|
|
186
|
-
// 分级表在这一步判:关着就不发,也**不记去重账**——用户中途改回响铃时,下一次观察同一次
|
|
187
|
-
// 收尾还能发出去。
|
|
188
|
-
if (mutedEverywhere(eventTypeOf(fact.status))) return;
|
|
189
135
|
const fingerprint = `${sessionId}:${fact.turn}:${fact.status}`;
|
|
190
136
|
if (recentlySent(fingerprint, FRAME_TTL_MS)) return;
|
|
191
137
|
// 文案只用跨语言的事实,不写死某一门语言:这条推送由系统直接显示,App 没机会再本地化
|
|
192
138
|
// (没有通知服务扩展),而这个列表在电脑上、读它的手机可能被设成十门语言里的任一门。
|
|
193
139
|
// 所以标题是会话名(用户自己起的),正文只给「成没成」一个符号。
|
|
194
140
|
const body = fact.status === 'failed' ? '✗' : '✓';
|
|
195
|
-
//
|
|
196
|
-
//
|
|
141
|
+
// 推给这台实例登记过的全部手机:按设备记账在 App 自己手里(本机已读水位),
|
|
142
|
+
// 总控只存「实例 + 设备 → 令牌」一级。
|
|
197
143
|
void pushFrame(fingerprint, {
|
|
198
|
-
kind: 'push',
|
|
199
|
-
pushFrame: 'send',
|
|
200
|
-
deviceId: '',
|
|
201
|
-
// deviceId 留空 = 这台实例上全部已登记设备都推。completion 的按设备记账
|
|
202
|
-
// 在 App 自己手里(本机已读水位),中转只存「实例 → 令牌」一级。
|
|
203
144
|
title: title || String(sessionId).slice(0, 8),
|
|
204
145
|
body,
|
|
205
146
|
sessionId,
|
|
206
|
-
pushKind: fact.status === 'failed' ? 'failed' : 'completed',
|
|
207
|
-
instanceId: instanceId(),
|
|
208
147
|
}, { kind: fact.status === 'failed' ? 'failed' : 'completed', sessionId });
|
|
209
148
|
}
|
|
210
149
|
|
|
@@ -257,8 +196,6 @@ function createPushNotifier(deps) {
|
|
|
257
196
|
(q) => q && q.intent && typeof q.intent === 'object' && q.intent.kind === 'plan-review',
|
|
258
197
|
);
|
|
259
198
|
const kind = isApproval ? 'approval' : (planReview ? 'plan-review' : 'question');
|
|
260
|
-
// 同上:这一级关着就直接不发,去重账也不动。
|
|
261
|
-
if (mutedEverywhere(eventTypeOf(kind))) return;
|
|
262
199
|
|
|
263
200
|
const fingerprint = `${sessionId}:${rpcId}`;
|
|
264
201
|
const approvalId = kind === 'approval' && typeof card.approvalId === 'string' ? card.approvalId : '';
|
|
@@ -323,41 +260,37 @@ function createPushNotifier(deps) {
|
|
|
323
260
|
? 'dsh.approval'
|
|
324
261
|
: (answerable ? 'dsh.question' : 'dsh.pending');
|
|
325
262
|
return pushFrame(fingerprint, {
|
|
326
|
-
kind: 'push',
|
|
327
|
-
pushFrame: 'send',
|
|
328
|
-
deviceId: '',
|
|
329
263
|
title: hint.title || String(sessionId).slice(0, 8),
|
|
330
264
|
body: summary,
|
|
331
265
|
sessionId,
|
|
332
|
-
pushKind: kind,
|
|
333
266
|
category,
|
|
334
267
|
interaction,
|
|
335
|
-
instanceId: instanceId(),
|
|
336
268
|
}, { kind, sessionId, approvalId }, upgrade);
|
|
337
269
|
}
|
|
338
270
|
|
|
339
|
-
/**
|
|
340
|
-
function
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
271
|
+
/** 把一条通知交给总控。发不出去返回 false,调用方据此不记去重账。 */
|
|
272
|
+
function post(payload) {
|
|
273
|
+
const target = controlTarget();
|
|
274
|
+
if (!target || !target.baseUrl || !target.token || !target.instanceId) return Promise.resolve(false);
|
|
275
|
+
const controller = new AbortController();
|
|
276
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
277
|
+
timer.unref?.();
|
|
278
|
+
return fetch(`${target.baseUrl}/push/send`, {
|
|
279
|
+
method: 'POST',
|
|
280
|
+
headers: {
|
|
281
|
+
'content-type': 'application/json',
|
|
282
|
+
'x-dsh-instance': target.instanceId,
|
|
283
|
+
authorization: `Bearer ${target.token}`,
|
|
284
|
+
},
|
|
285
|
+
body: JSON.stringify(payload),
|
|
286
|
+
signal: controller.signal,
|
|
287
|
+
}).then(
|
|
288
|
+
(response) => response.ok,
|
|
356
289
|
() => false,
|
|
357
|
-
);
|
|
290
|
+
).finally(() => clearTimeout(timer));
|
|
358
291
|
}
|
|
359
292
|
|
|
360
|
-
return { notifyTurnEnded, notifyInteraction
|
|
293
|
+
return { notifyTurnEnded, notifyInteraction };
|
|
361
294
|
}
|
|
362
295
|
|
|
363
296
|
module.exports = { createPushNotifier };
|
package/lib/mobile/rpc.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 宿主列表仅在同一失效代次内合流,新变更后的读取不能复用旧 RPC。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -14,6 +15,7 @@
|
|
|
14
15
|
*/
|
|
15
16
|
|
|
16
17
|
const { MOBILE_PROMPT_RPC_PREFIX } = require('./history-derive.js');
|
|
18
|
+
const { sessionListResponseState } = require('./session-cache.js');
|
|
17
19
|
|
|
18
20
|
// 移动端提示词的 rpcId 约定与 user 消息回溯共用,前缀常量定义放在没有依赖的
|
|
19
21
|
// history-derive 里(history-derive 要用 clientMessageIdFromSource,而会话模块
|
|
@@ -40,8 +42,9 @@ function callSessions(ctx, method, payload, rpcId = 'mobile', signal, options) {
|
|
|
40
42
|
if (method !== 'list') return invoke();
|
|
41
43
|
if (options && options.fresh) return invoke();
|
|
42
44
|
|
|
45
|
+
const epoch = sessionListResponseState(ctx).droppedAt || 0;
|
|
43
46
|
const existing = sessionListInFlight.get(ctx);
|
|
44
|
-
if (existing) return existing;
|
|
47
|
+
if (existing && existing.epoch === epoch) return existing.promise;
|
|
45
48
|
|
|
46
49
|
let request;
|
|
47
50
|
try {
|
|
@@ -53,15 +56,15 @@ function callSessions(ctx, method, payload, rpcId = 'mobile', signal, options) {
|
|
|
53
56
|
}
|
|
54
57
|
const tracked = request.then(
|
|
55
58
|
value => {
|
|
56
|
-
if (sessionListInFlight.get(ctx) === tracked) sessionListInFlight.delete(ctx);
|
|
59
|
+
if (sessionListInFlight.get(ctx)?.promise === tracked) sessionListInFlight.delete(ctx);
|
|
57
60
|
return value;
|
|
58
61
|
},
|
|
59
62
|
error => {
|
|
60
|
-
if (sessionListInFlight.get(ctx) === tracked) sessionListInFlight.delete(ctx);
|
|
63
|
+
if (sessionListInFlight.get(ctx)?.promise === tracked) sessionListInFlight.delete(ctx);
|
|
61
64
|
throw error;
|
|
62
65
|
},
|
|
63
66
|
);
|
|
64
|
-
sessionListInFlight.set(ctx, tracked);
|
|
67
|
+
sessionListInFlight.set(ctx, { epoch, promise: tracked });
|
|
65
68
|
return tracked;
|
|
66
69
|
}
|
|
67
70
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 清单变更会断开旧构建的合流引用,后续读取不能继续搭旧快照。
|
|
1
2
|
// 会话缓存集中保存按 ctx 隔离的状态,持久化修订随服务身份换代。
|
|
2
3
|
'use strict';
|
|
3
4
|
|
|
@@ -437,6 +438,9 @@ function writeIdempotencyStateOf(ctx) {
|
|
|
437
438
|
* @param {string} [deviceKey] 只清这一台设备的缓存;缺省清掉该 ctx 下所有设备。
|
|
438
439
|
*/
|
|
439
440
|
function invalidateSessionList(ctx, deviceKey) {
|
|
441
|
+
// 宿主 list 在 ctx 内共享,任一设备写入后都要换掉其底层合流代次。
|
|
442
|
+
const shared = sessionListResponseState(ctx);
|
|
443
|
+
shared.droppedAt = (shared.droppedAt || 0) + 1;
|
|
440
444
|
const byDevice = sessionListResponseCache.get(ctx);
|
|
441
445
|
if (!byDevice) return;
|
|
442
446
|
const keys = deviceKey === undefined ? [...byDevice.keys()] : [deviceKey];
|
|
@@ -465,6 +469,8 @@ function invalidateSessionList(ctx, deviceKey) {
|
|
|
465
469
|
* @param {string} [deviceKey] 只丢这一台设备的缓存;缺省丢掉该 ctx 下所有设备。
|
|
466
470
|
*/
|
|
467
471
|
function dropSessionListCache(ctx, deviceKey) {
|
|
472
|
+
const shared = sessionListResponseState(ctx);
|
|
473
|
+
shared.droppedAt = (shared.droppedAt || 0) + 1;
|
|
468
474
|
const byDevice = sessionListResponseCache.get(ctx);
|
|
469
475
|
if (!byDevice) return;
|
|
470
476
|
const keys = deviceKey === undefined ? [...byDevice.keys()] : [deviceKey];
|
|
@@ -473,6 +479,8 @@ function dropSessionListCache(ctx, deviceKey) {
|
|
|
473
479
|
if (!state) continue;
|
|
474
480
|
state.value = null;
|
|
475
481
|
state.updatedAt = 0;
|
|
482
|
+
state.promise = null;
|
|
483
|
+
state.lastRevision = '';
|
|
476
484
|
state.droppedAt = (state.droppedAt || 0) + 1;
|
|
477
485
|
}
|
|
478
486
|
}
|
package/lib/mobile/sessions.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 失效前发起的列表构建不得回填缓存或登记条件刷新基准。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -23,9 +24,9 @@ const { listTitle, deriveMessages, lastMessageOf, promptErrorObject, MODEL_UNAVA
|
|
|
23
24
|
const { unwrap } = require('./envelope.js');
|
|
24
25
|
const { callSessions } = require('./rpc.js');
|
|
25
26
|
const {
|
|
26
|
-
canonicalDeviceKey, sessionListResponseState, invalidateSessionList, deletedSessionIdsOf,
|
|
27
|
+
canonicalDeviceKey, sessionListResponseState, invalidateSessionList, dropSessionListCache, deletedSessionIdsOf,
|
|
27
28
|
completionGenerationOf, bumpCompletionGeneration,
|
|
28
|
-
completionStateOf, sessionModelsStateOf, invalidateSessionModels, sendIdempotencyStateOf,
|
|
29
|
+
completionStateOf, sessionModelsStateOf, invalidateSessionModels, sendIdempotencyStateOf, sessionPreviewStateOf,
|
|
29
30
|
} = require('./session-cache.js');
|
|
30
31
|
const { resolveEventAttachments } = require('./attachments.js');
|
|
31
32
|
const { updateCompletionStates, confirmCompletionFromHistory } = require('./completion.js');
|
|
@@ -125,7 +126,11 @@ async function handleSessions(ctx, req, res) {
|
|
|
125
126
|
// 但「丢掉」挡不住**已经在飞**的那次构建:它手里是变更之前的数据,落地后会在缓存里
|
|
126
127
|
// 再活 10 秒。用缓存自带的朝代号兜住(见 session-cache.js 的 dropSessionListCache)。
|
|
127
128
|
const epoch = cache.droppedAt || 0;
|
|
128
|
-
const
|
|
129
|
+
const buildOptions = revEligible && rev ? {
|
|
130
|
+
awaitPreviews: false,
|
|
131
|
+
onPreviewsReady: () => dropSessionListCache(ctx, deviceKey),
|
|
132
|
+
} : {};
|
|
133
|
+
const promise = buildSessionsResponse(ctx, deviceKey, generation, wantFresh, archivedOnly, page, buildOptions);
|
|
129
134
|
cache.promise = promise;
|
|
130
135
|
try {
|
|
131
136
|
const response = await promise;
|
|
@@ -140,15 +145,15 @@ async function handleSessions(ctx, req, res) {
|
|
|
140
145
|
cache.value = response.body;
|
|
141
146
|
cache.updatedAt = Date.now();
|
|
142
147
|
}
|
|
148
|
+
if (!archivedOnly) rememberListBuild(cache, response.body, generation);
|
|
143
149
|
}
|
|
144
|
-
if (response.status === 200) rememberListBuild(cache, response.body, completionGenerationOf(ctx, deviceKey));
|
|
145
150
|
return respond(response.status, response.body);
|
|
146
151
|
} finally {
|
|
147
152
|
if (cache.promise === promise) cache.promise = null;
|
|
148
153
|
}
|
|
149
154
|
}
|
|
150
155
|
|
|
151
|
-
async function buildSessionsResponse(ctx, deviceKey = 'legacy', generation = completionGenerationOf(ctx, deviceKey), fresh = false, archivedOnly = false, page = null) {
|
|
156
|
+
async function buildSessionsResponse(ctx, deviceKey = 'legacy', generation = completionGenerationOf(ctx, deviceKey), fresh = false, archivedOnly = false, page = null, buildOptions = {}) {
|
|
152
157
|
const { value, error } = unwrap(await callSessions(ctx, 'list', {}, 'mobile', undefined, { fresh }));
|
|
153
158
|
if (error) return { status: 400, body: { ok: false, error } };
|
|
154
159
|
// 形状不对 = 没取到,不是「你一个会话都没有」。旧实现 `(value.items || [])` 把
|
|
@@ -245,7 +250,16 @@ async function buildSessionsResponse(ctx, deviceKey = 'legacy', generation = com
|
|
|
245
250
|
(b.summary.running ? 1 : 0) - (a.summary.running ? 1 : 0)
|
|
246
251
|
|| (b.summary.updatedAt || 0) - (a.summary.updatedAt || 0))
|
|
247
252
|
.slice(0, SESSIONS_PREVIEW_LIMIT);
|
|
248
|
-
|
|
253
|
+
const deferPreviews = buildOptions.awaitPreviews === false;
|
|
254
|
+
if (deferPreviews) {
|
|
255
|
+
for (const { summary: s, base } of previewCandidates) {
|
|
256
|
+
base.lastMessage = sessionPreviewStateOf(ctx).get(s.sessionId)?.lastMessage || null;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const previewsBefore = deferPreviews ? JSON.stringify(previewCandidates.map(({ base }) => base)) : '';
|
|
260
|
+
const previews = Promise.all(previewCandidates.map(async ({ summary: s, base: listed }) => {
|
|
261
|
+
// 先发清单时只在副本里补预览,不能修改已经返回且算过 revision 的那份行。
|
|
262
|
+
const base = deferPreviews ? { ...listed } : listed;
|
|
249
263
|
try {
|
|
250
264
|
const preview = await sessionPreviewFor(ctx, s);
|
|
251
265
|
const events = preview.events;
|
|
@@ -270,7 +284,13 @@ async function buildSessionsResponse(ctx, deviceKey = 'legacy', generation = com
|
|
|
270
284
|
} catch {
|
|
271
285
|
// 预览失败不影响标题与行数据。
|
|
272
286
|
}
|
|
287
|
+
return base;
|
|
273
288
|
}));
|
|
289
|
+
if (deferPreviews) {
|
|
290
|
+
void previews.then((completed) => {
|
|
291
|
+
if (previewsBefore !== JSON.stringify(completed)) buildOptions.onPreviewsReady?.();
|
|
292
|
+
}).catch(() => {});
|
|
293
|
+
} else await previews;
|
|
274
294
|
const allItems = rows.map((r) => r.base);
|
|
275
295
|
const items = page ? allItems.slice(page.offset, page.offset + page.limit) : allItems;
|
|
276
296
|
const generatedAt = Date.now();
|