@dsh-mobile/mobile-remote 3.5.0-beta.1 → 3.5.0-beta.3

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/lib/config.js CHANGED
@@ -27,6 +27,8 @@ export const DEFAULT_ENUMERATION_BUDGET_MS = 12_000;
27
27
 
28
28
  export const DEFAULT_WARM_UP_TITLE_BUDGET_MS = 10_000;
29
29
 
30
+ export const DEFAULT_RELAY_URLS = Object.freeze(["wss://dsh.claud.ing", "wss://hk-relay.dsh.claud.ing"]);
31
+
30
32
 
31
33
  export const Config = z.object({
32
34
 
@@ -174,7 +176,11 @@ export const Config = z.object({
174
176
  .object({
175
177
  enabled: z.boolean().default(true),
176
178
 
177
- urls: z.array(z.string()).default(["wss://dsh.claud.ing"]),
179
+
180
+
181
+
182
+
183
+ urls: z.array(z.string()).default([...DEFAULT_RELAY_URLS]),
178
184
 
179
185
  name: z.string().default(""),
180
186
  })
@@ -0,0 +1,49 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ import { createHash } from "node:crypto";
10
+ import { createReadStream } from "node:fs";
11
+
12
+ export const HASH_MAX_BYTES = 512 * 1024 * 1024;
13
+ export const DIGEST_HEADER = "x-dsh-sha256";
14
+ const CACHE_MAX = 64;
15
+ const cache = new Map();
16
+
17
+
18
+ export async function fileSha256(fd, { path, size, mtimeMs }) {
19
+ if (!Number.isFinite(size) || size < 0 || size > HASH_MAX_BYTES) return null;
20
+ const key = `${path}\0${size}\0${mtimeMs}`;
21
+ const hit = cache.get(key);
22
+ if (hit) {
23
+ cache.delete(key);
24
+ cache.set(key, hit);
25
+ return hit;
26
+ }
27
+ const hash = createHash("sha256");
28
+ try {
29
+ if (size > 0) {
30
+ await new Promise((resolve, reject) => {
31
+ const s = createReadStream(null, { fd, start: 0, end: size - 1, autoClose: false });
32
+ s.on("data", (chunk) => hash.update(chunk));
33
+ s.on("end", resolve);
34
+ s.on("error", reject);
35
+ });
36
+ }
37
+ } catch {
38
+ return null;
39
+ }
40
+ const hex = hash.digest("hex");
41
+ cache.set(key, hex);
42
+ while (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value);
43
+ return hex;
44
+ }
45
+
46
+
47
+ export function clearDigestCache() {
48
+ cache.clear();
49
+ }
@@ -23,6 +23,8 @@
23
23
 
24
24
 
25
25
 
26
+
27
+
26
28
 
27
29
 
28
30
 
@@ -75,6 +77,61 @@ const receiptView = (r) => ({
75
77
  targetSessionId: str(r?.targetSessionId) ?? null,
76
78
  });
77
79
 
80
+ const hostZone = () => {
81
+ try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; } catch { return "UTC"; }
82
+ };
83
+ const TIME_RE = /^\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?$/;
84
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
85
+ const zoneOf = (v) => (typeof v === "string" && v.length > 0 && v.length <= 64 ? v : hostZone());
86
+ const secondsOf = (v) => (Number.isInteger(v) && v >= 1 && v <= 366 * 86400 ? v : undefined);
87
+
88
+
89
+ export function scheduleTimingOf(t) {
90
+ if (!t || typeof t !== "object" || Array.isArray(t)) return { error: "timing must be an object" };
91
+ switch (t.kind) {
92
+ case "after": {
93
+ const n = secondsOf(t.afterSeconds);
94
+ return n ? { timing: { kind: "after", after_seconds: n } } : { error: "afterSeconds must be a whole number of seconds" };
95
+ }
96
+ case "every": {
97
+ const n = secondsOf(t.everySeconds);
98
+ return n ? { timing: { kind: "every", every_seconds: n } } : { error: "everySeconds must be a whole number of seconds" };
99
+ }
100
+ case "at":
101
+ if (!DATE_RE.test(t.date ?? "") || !TIME_RE.test(t.time ?? "")) return { error: "at needs date (YYYY-MM-DD) and time (HH:mm)" };
102
+ return { timing: { kind: "at", at: { date: t.date, time: t.time.length === 5 ? `${t.time}:00` : t.time, time_zone: zoneOf(t.timeZone) } } };
103
+ case "daily":
104
+ if (!TIME_RE.test(t.time ?? "")) return { error: "daily needs time (HH:mm)" };
105
+ return { timing: { kind: "daily", daily: { time: t.time.length === 5 ? `${t.time}:00` : t.time, time_zone: zoneOf(t.timeZone) } } };
106
+ case "weekly": {
107
+ const days = Array.isArray(t.weekdays) ? [...new Set(t.weekdays)] : [];
108
+ if (!TIME_RE.test(t.time ?? "")) return { error: "weekly needs time (HH:mm)" };
109
+ if (days.length === 0 || days.some((d) => !Number.isInteger(d) || d < 1 || d > 7)) return { error: "weekdays must be 1 (Mon) to 7 (Sun)" };
110
+ return { timing: { kind: "weekly", weekly: { time: t.time.length === 5 ? `${t.time}:00` : t.time, time_zone: zoneOf(t.timeZone), weekdays: days.sort((a, b) => a - b) } } };
111
+ }
112
+ case "cron":
113
+ if (typeof t.expression !== "string" || !t.expression.trim() || t.expression.length > 200) return { error: "cron needs an expression" };
114
+ return { timing: { kind: "cron", cron: { expression: t.expression.trim(), time_zone: zoneOf(t.timeZone) } } };
115
+ default:
116
+ return { error: "timing.kind is not one the phone can set" };
117
+ }
118
+ }
119
+
120
+
121
+ export function scheduleTargetOf(t) {
122
+ if (!t || typeof t !== "object" || Array.isArray(t)) return { error: "target must be an object" };
123
+ if (t.kind === "session") {
124
+ if (typeof t.sessionId !== "string" || !ID_RE.test(t.sessionId)) return { error: "target.sessionId is not valid" };
125
+ return { target: { kind: "session", sessionId: t.sessionId } };
126
+ }
127
+ if (t.kind === "new_once" || t.kind === "new") {
128
+ const create = {};
129
+ if (typeof t.cwd === "string" && t.cwd && t.cwd.length <= 1024) create.cwd = t.cwd;
130
+ return { target: { kind: t.kind, ...(Object.keys(create).length ? { create } : {}) } };
131
+ }
132
+ return { error: "target.kind is not one the phone can set" };
133
+ }
134
+
78
135
 
79
136
  export function schedulePatchOf(body) {
80
137
  if (!body || typeof body !== "object" || Array.isArray(body)) return { error: "body must be an object" };
@@ -93,6 +150,16 @@ export function schedulePatchOf(body) {
93
150
  if (typeof body.active !== "boolean") return { error: "active must be true or false" };
94
151
  patch.active = body.active;
95
152
  }
153
+ if (body.timing !== undefined) {
154
+ const r = scheduleTimingOf(body.timing);
155
+ if (r.error) return { error: r.error };
156
+ patch.timing = r.timing;
157
+ }
158
+ if (body.target !== undefined) {
159
+ const r = scheduleTargetOf(body.target);
160
+ if (r.error) return { error: r.error };
161
+ patch.target = r.target;
162
+ }
96
163
  if (Object.keys(patch).length === 0) return { error: "nothing to change" };
97
164
  const expected = body.expectedUpdatedAt;
98
165
  if (expected !== undefined && expected !== null && typeof expected !== "string") return { error: "expectedUpdatedAt must be a string or null" };
@@ -0,0 +1,149 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+ import { sendError, sendJson } from "./http-util.js";
21
+
22
+
23
+ export const SESSION_SEARCH_FEATURE = "session-search";
24
+
25
+ export const MAX_QUERY = 200;
26
+ export const MAX_LIMIT = 30;
27
+ export const SNIPPET_MAX = 160;
28
+ export const SCAN_SESSIONS = 80;
29
+ export const SCAN_CONCURRENCY = 4;
30
+ export const SCAN_BUDGET_MS = 4000;
31
+ const INDEX_TIMEOUT_MS = 5000;
32
+
33
+ const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
34
+
35
+
36
+
37
+
38
+
39
+
40
+ export function snippetAround(text, query, max = SNIPPET_MAX) {
41
+ const t = oneLine(text);
42
+ if (!t) return "";
43
+ if (t.length <= max) return t;
44
+ const lower = t.toLowerCase();
45
+ const q = oneLine(query).toLowerCase();
46
+ let at = q ? lower.indexOf(q) : -1;
47
+ if (at < 0 && q) {
48
+ const first = q.split(" ").find(Boolean);
49
+ if (first) at = lower.indexOf(first);
50
+ }
51
+ if (at < 0) return `${t.slice(0, max - 1)}…`;
52
+ const lead = Math.floor((max - Math.min(q.length, max)) / 3);
53
+ let start = Math.max(0, at - lead);
54
+ let end = Math.min(t.length, start + max);
55
+ start = Math.max(0, end - max);
56
+ return `${start > 0 ? "…" : ""}${t.slice(start, end)}${end < t.length ? "…" : ""}`;
57
+ }
58
+
59
+ const isDisabled = (err) => err?.code === "SESSION_QUERY_SEARCH_DISABLED" || /SEARCH_DISABLED/.test(String(err?.message ?? ""));
60
+
61
+ export function createSessionSearchRoutes({ service, logger, now = () => Date.now() }) {
62
+ const get = (fn) => {
63
+ try { return fn(); } catch { return undefined; }
64
+ };
65
+
66
+ async function viaIndex(svc, query, limit) {
67
+ const page = await svc.searchSessions({ query, limit }, { signal: AbortSignal.timeout(INDEX_TIMEOUT_MS) });
68
+ const hits = [];
69
+ for (const hit of Array.isArray(page?.items) ? page.items : []) {
70
+ const id = hit?.header?.id;
71
+ if (typeof id !== "string" || !id) continue;
72
+ hits.push({
73
+ id,
74
+ snippet: snippetAround(hit.bestMatch?.snippet ?? "", query),
75
+ at: Number.isFinite(hit.bestMatch?.time) ? hit.bestMatch.time : null,
76
+ });
77
+ }
78
+ return { mode: "index", partial: Boolean(page?.nextCursor), hits };
79
+ }
80
+
81
+ async function viaScan(svc, query, limit) {
82
+ const started = now();
83
+ const records = await svc.listSessions(AbortSignal.timeout(SCAN_BUDGET_MS));
84
+ const ids = (Array.isArray(records) ? records : [])
85
+ .map((r) => r?.header?.id)
86
+ .filter((id) => typeof id === "string" && id);
87
+ const queue = ids.slice(0, SCAN_SESSIONS);
88
+ let partial = ids.length > queue.length;
89
+ const found = new Map();
90
+ const worker = async () => {
91
+ while (queue.length > 0 && found.size < limit) {
92
+ if (now() - started > SCAN_BUDGET_MS) { partial = true; return; }
93
+ const id = queue.shift();
94
+ try {
95
+ const docs = await svc.filterEvents(id, [{ kind: "text", text: query }]);
96
+ if (Array.isArray(docs) && docs.length > 0) {
97
+ const last = docs[docs.length - 1];
98
+ found.set(id, { id, snippet: snippetAround(last?.text ?? "", query), at: Number.isFinite(last?.time) ? last.time : null });
99
+ }
100
+ } catch (err) {
101
+ logger?.debug?.(`mobile-remote: session search scan ${id}: ${err?.message ?? err}`);
102
+ }
103
+ }
104
+ if (queue.length > 0) partial = true;
105
+ };
106
+ await Promise.all(Array.from({ length: SCAN_CONCURRENCY }, worker));
107
+ const hits = ids.filter((id) => found.has(id)).map((id) => found.get(id)).slice(0, limit);
108
+ return { mode: "scan", partial, hits };
109
+ }
110
+
111
+ return async function handleSessionSearch(req, res, rest, method, url) {
112
+ if (rest !== "/session-search") return false;
113
+ if (method !== "GET" && method !== "HEAD") { sendError(res, 405, "method-not-allowed"); return true; }
114
+ const query = oneLine(url?.searchParams?.get("q") ?? "");
115
+ if (!query || query.length > MAX_QUERY) { sendError(res, 400, "bad-request", `q must be 1..${MAX_QUERY} characters`); return true; }
116
+ const limitRaw = Number.parseInt(url?.searchParams?.get("limit") ?? "", 10);
117
+ const limit = Number.isFinite(limitRaw) ? Math.min(MAX_LIMIT, Math.max(1, limitRaw)) : 20;
118
+ const svc = get(service);
119
+ const canIndex = typeof svc?.searchSessions === "function";
120
+ const canScan = typeof svc?.listSessions === "function" && typeof svc?.filterEvents === "function";
121
+ if (!canIndex && !canScan) {
122
+ sendError(res, 503, "session-search-unavailable", "this computer's DSH does not offer session search");
123
+ return true;
124
+ }
125
+ let result = null;
126
+ if (canIndex) {
127
+ try {
128
+ result = await viaIndex(svc, query, limit);
129
+ } catch (err) {
130
+ if (!isDisabled(err)) logger?.debug?.(`mobile-remote: session search index: ${err?.message ?? err}`);
131
+ }
132
+ }
133
+ if (!result && canScan) {
134
+ try {
135
+ result = await viaScan(svc, query, limit);
136
+ } catch (err) {
137
+ logger?.warn?.(`mobile-remote: session search failed: ${err?.message ?? err}`);
138
+ sendError(res, 503, "session-search-unavailable", "session search failed on this computer");
139
+ return true;
140
+ }
141
+ }
142
+ if (!result) {
143
+ sendError(res, 503, "session-search-unavailable", "full-text search is switched off in this computer's DSH");
144
+ return true;
145
+ }
146
+ sendJson(res, 200, { ok: true, query, ...result });
147
+ return true;
148
+ };
149
+ }
package/lib/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
 
9
9
 
10
- import { protocolInfo } from "./protocol.js"; import { createPhoneActions } from "./phone-actions.js"; import { attachLiveActivity } from "./live-activity.js";
10
+ import { protocolInfo } from "./protocol.js"; import { createPhoneActions } from "./phone-actions.js"; import { attachLiveActivity } from "./live-activity.js"; import { PHONE_PUSH_KINDS, attachPushAnswers, createPhonePush, phoneActionText, replyTarget, workerEndpoint } from "./phone-push.js";
11
11
  import { networkInterfaces, hostname } from "node:os";
12
12
  import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
13
13
  import { ftruncateSync, mkdirSync, readFileSync, renameSync, writeFileSync, writeSync } from "node:fs";
@@ -1342,8 +1342,9 @@ export function apply(ctx, configInput) {
1342
1342
 
1343
1343
 
1344
1344
 
1345
- const pushSend = async (kind, sessionId, title, detail) => {
1346
- if (config.pushUrls.length === 0) return false;
1345
+ const pushSend = async (kind, sessionId, title, detail, ask) => {
1346
+ const toPhone = PHONE_PUSH_KINDS[kind] !== undefined && phonePush.active && !appInForeground();
1347
+ if (config.pushUrls.length === 0 && !toPhone) return false;
1347
1348
  const key = `${sessionId}:${kind}`;
1348
1349
  const now = Date.now();
1349
1350
  const last = pushCooldowns.get(key) ?? 0;
@@ -1388,7 +1389,7 @@ export function apply(ctx, configInput) {
1388
1389
  const safeHeadline = headline.trim() === "" ? kindLabel : headline;
1389
1390
  const redactedTitle = safeHeadline;
1390
1391
  const redactedDetail = body.trim() === "" ? redactPathText(detail) : body;
1391
- let delivered = 0;
1392
+ let delivered = toPhone ? await phonePush.notify({ kind: PHONE_PUSH_KINDS[kind], title: redactedTitle, body: redactedDetail, sid: sessionId, ask }).catch(() => 0) : 0;
1392
1393
  for (const target of config.pushUrls) {
1393
1394
 
1394
1395
  const outcome = await pushTracked(target, kind, kindLabel, redactedTitle, redactedDetail, sessionId);
@@ -1408,7 +1409,7 @@ export function apply(ctx, configInput) {
1408
1409
 
1409
1410
  const lastNeedsAnswerAt = new Map();
1410
1411
  const NEEDS_ANSWER_DEDUP_MS = 10_000;
1411
- const notifyNeedsAnswer = (sessionId, detail) => {
1412
+ const notifyNeedsAnswer = (sessionId, detail, ask) => {
1412
1413
  const now = Date.now();
1413
1414
  const last = lastNeedsAnswerAt.get(sessionId) ?? 0;
1414
1415
  if (now - last < NEEDS_ANSWER_DEDUP_MS) return false;
@@ -1420,7 +1421,7 @@ export function apply(ctx, configInput) {
1420
1421
  });
1421
1422
  const sessions = ctx.get("sessions");
1422
1423
  const sess = sessions?.get(sessionId);
1423
- void pushSend("needs-answer", sessionId, notifyTitle(sessionId, sess), detail).catch((err) => {
1424
+ void pushSend("needs-answer", sessionId, notifyTitle(sessionId, sess), detail, ask).catch((err) => {
1424
1425
 
1425
1426
  ctx.logger.warn(`mobile-remote: pushSend 失败(${sessionId}):${err?.message ?? err}`);
1426
1427
  });
@@ -1712,7 +1713,7 @@ export function apply(ctx, configInput) {
1712
1713
  }
1713
1714
  }
1714
1715
  };
1715
- const phoneActions = createPhoneActions({ ctx, broadcast, phoneConnected: () => connections.size > 0, pcName: config.relay?.name }); const liveActivity = attachLiveActivity({ ctx, config, agentSessionId: (a) => agentSessionId(a), sessionTitleOf: (s) => sessionTitleOf(s), pending: () => [...pendingApprovals.values(), ...pendingQuestions.values()] });
1716
+ const phonePush = createPhonePush({ dir: STATE_DIR, endpoint: workerEndpoint(config), pcName: () => config.relay?.name || hostname(), reply: () => { try { return replyTarget(relay); } catch { return null; } }, logger: ctx.logger }); const phoneActions = createPhoneActions({ ctx, broadcast, phoneConnected: () => connections.size > 0, pcName: config.relay?.name, canPush: () => phonePush.active && !appInForeground(), onRequest: (f) => void phonePush.notify({ kind: "phone-action", ...phoneActionText(f), sid: f.sessionId, ask: { type: "phone-action", id: f.id } }).catch(() => 0) }); const liveActivity = attachLiveActivity({ ctx, config, agentSessionId: (a) => agentSessionId(a), sessionTitleOf: (s) => sessionTitleOf(s), pending: () => [...pendingApprovals.values(), ...pendingQuestions.values()] });
1716
1717
  const toolbox = createToolbox({ ctx, broadcast, pcName: config.relay?.name });
1717
1718
 
1718
1719
 
@@ -1863,7 +1864,7 @@ export function apply(ctx, configInput) {
1863
1864
  res.write(`data: ${JSON.stringify({ type: "mobile/frame", frame: f })}\n\n`);
1864
1865
  }
1865
1866
 
1866
- for (const f of sessionJobsFrames()) {
1867
+ for (const f of [...sessionJobsFrames(), ...phoneActions.pendingFrames()]) {
1867
1868
  res.write(`data: ${JSON.stringify(f)}\n\n`);
1868
1869
  }
1869
1870
  };
@@ -2546,7 +2547,7 @@ export function apply(ctx, configInput) {
2546
2547
  get pendingQuestions() { return pendingQuestions; },
2547
2548
  get persistHeld() { return persistHeld; },
2548
2549
  get persistReceipts() { return persistReceipts; },
2549
- get phoneActions() { return phoneActions; }, get liveActivity() { return liveActivity; },
2550
+ get phoneActions() { return phoneActions; }, get liveActivity() { return liveActivity; }, get phonePush() { return phonePush; },
2550
2551
  get pluginVersion() { return pluginVersion; },
2551
2552
  get toolbox() { return toolbox; },
2552
2553
  get presenceState() { return presenceState; },
@@ -2828,8 +2829,8 @@ export function apply(ctx, configInput) {
2828
2829
  timer.unref?.();
2829
2830
  entry.timer = timer;
2830
2831
  };
2831
- const notifyAsk = (sessionId, req) =>
2832
- notifyNeedsAnswer(sessionId, `审批请求:${typeof req?.toolName === "string" && req.toolName ? req.toolName : "工具"} 需要授权`);
2832
+ const notifyAsk = (sessionId, req, id) =>
2833
+ notifyNeedsAnswer(sessionId, `审批请求:${typeof req?.toolName === "string" && req.toolName ? req.toolName : "工具"} 需要授权`, id ? { type: "approval", id } : undefined);
2833
2834
  const notifyQuestion = (sessionId) => notifyNeedsAnswer(sessionId, "agent 正在等待你的回答");
2834
2835
 
2835
2836
 
@@ -2862,7 +2863,7 @@ export function apply(ctx, configInput) {
2862
2863
 
2863
2864
  putAskReplay("a", entry, requested);
2864
2865
  broadcast({ type: "mobile/frame", frame: requested });
2865
- notifyAskDeferred(sessionId, () => pendingApprovals.has(phoneKey), () => notifyAsk(sessionId, req));
2866
+ notifyAskDeferred(sessionId, () => pendingApprovals.has(phoneKey), () => notifyAsk(sessionId, req, phoneKey));
2866
2867
  return { held, entry };
2867
2868
  };
2868
2869
  const holdQuestion = (req, sessionId) => {
@@ -2950,7 +2951,7 @@ export function apply(ctx, configInput) {
2950
2951
  broadcast({ type: "mobile/frame", frame: requested });
2951
2952
 
2952
2953
 
2953
- notifyAskDeferred(sessionId, () => pendingApprovals.has(phoneKey), () => notifyAsk(sessionId, request));
2954
+ notifyAskDeferred(sessionId, () => pendingApprovals.has(phoneKey), () => notifyAsk(sessionId, request, phoneKey));
2954
2955
  return;
2955
2956
  }
2956
2957
  if (frame.event === "user-questions/request") {
@@ -3247,7 +3248,7 @@ export function apply(ctx, configInput) {
3247
3248
  const demand = relayRemote
3248
3249
  ? createRelayDemand({ connector, devices, log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`) })
3249
3250
  : { active: false, start() { return false; }, stop() {}, sync() { return false; }, dispose() {} };
3250
- relay = { identity, devices, connector, demand, p2p, remote: relayRemote, urls: relayRemote ? relayUrls : [], name: config.relay?.name || hostname() };
3251
+ relay = { identity, devices, connector, demand, p2p, remote: relayRemote, urls: relayRemote ? relayUrls : [], name: config.relay?.name || hostname() }; attachPushAnswers({ connector, phonePush, room: () => identity.roomId, approve: (id, outcome) => { const e = pendingApprovals.get(id); if (e) finishApproval(e, outcome); return Boolean(e); }, cancelPhoneAction: (id) => phoneActions.cancelFromPush(id), logger: ctx.logger });
3251
3252
  } catch (err) {
3252
3253
  ctx.logger.warn?.(`mobile-remote: 中继初始化失败,已关闭:${err?.message ?? err}`);
3253
3254
  }
@@ -14,6 +14,8 @@
14
14
 
15
15
 
16
16
 
17
+
18
+
17
19
  import { randomUUID } from "node:crypto";
18
20
  import { hostname } from "node:os";
19
21
  import { ACTIONS, TOOL_NAMES, TOOL_SPECS, validatePhoneAction } from "./phone-action-args.js";
@@ -49,7 +51,7 @@ const sessionIdOf = (agent) => agent?.session?.id ?? String(agent?.id ?? "").rep
49
51
 
50
52
 
51
53
 
52
- export const createPhoneActions = ({ ctx, broadcast, phoneConnected, pcName, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, graceMs = GRACE_MS }) => {
54
+ export const createPhoneActions = ({ ctx, broadcast, phoneConnected, pcName, canPush = () => false, onRequest = () => {}, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, graceMs = GRACE_MS }) => {
53
55
  const pending = new Map();
54
56
  const settled = new Map();
55
57
  const turns = new Map();
@@ -77,7 +79,8 @@ export const createPhoneActions = ({ ctx, broadcast, phoneConnected, pcName, now
77
79
  };
78
80
 
79
81
  const request = (action, args, exec) => {
80
- if (!phoneConnected()) throw new Error("phone not connected: the DSH Mobile app is not connected to this computer right now, so this action cannot be done. Tell the user.");
82
+ const pushed = !phoneConnected() && canPush();
83
+ if (!phoneConnected() && !pushed) throw new Error("phone not connected: the DSH Mobile app is not connected to this computer right now, so this action cannot be done. Tell the user.");
81
84
  if (pending.size >= MAX_PENDING) throw new Error("too many phone actions are waiting for the user");
82
85
  const id = randomUUID();
83
86
  const sessionId = sessionIdOf(exec?.agent);
@@ -96,13 +99,18 @@ export const createPhoneActions = ({ ctx, broadcast, phoneConnected, pcName, now
96
99
  entry.offAbort = () => signal.removeEventListener("abort", onAbort);
97
100
  }
98
101
  }
99
- pending.set(id, entry);
100
- broadcast({
102
+ const frame = {
101
103
  type: "phone-action-request", id, pcName: name, action, args,
102
104
  expiresAt: at + ASK_MS,
103
105
  ...(sessionId ? { sessionId } : {}),
104
106
  ...(turnId ? { turnId } : {}),
105
- });
107
+ };
108
+ entry.frame = frame;
109
+ pending.set(id, entry);
110
+ broadcast(frame);
111
+ if (pushed) {
112
+ try { onRequest(frame); } catch { }
113
+ }
106
114
  });
107
115
  };
108
116
 
@@ -223,5 +231,9 @@ export const createPhoneActions = ({ ctx, broadcast, phoneConnected, pcName, now
223
231
 
224
232
  features: () => (supported ? [FEATURE] : []),
225
233
  pendingCount: () => pending.size,
234
+
235
+ pendingFrames: () => [...pending.values()].map((e) => e.frame).filter((f) => f && f.expiresAt > now()),
236
+
237
+ cancelFromPush: (id) => settle(id, { status: "cancelled", detail: "cancelled on the phone's lock screen" }, { byPhone: true }),
226
238
  };
227
239
  };