@duke-dsh-plugins/dsh-remote-control 1.1.4 → 1.1.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/README.md CHANGED
@@ -75,7 +75,7 @@ scripts/verify-pairing.mjs /remote-pairing 命令逻辑自检(mock ctx;devD
75
75
 
76
76
  ```bash
77
77
  # DSH 插件市场(推荐):在「设置 → 插件市场」添加索引 URL 后搜「DSH Pocket」安装
78
- # https://unpkg.com/@duke-dsh-plugins/dsh-remote-control-market@latest/index.json
78
+ # https://unpkg.com/@duke-dsh-plugins/dsh-remote-control@latest/market/index.json
79
79
  #
80
80
  # 或直接用插件管理器:会解析 peerDependencies 并做兼容性 gate
81
81
  plugin_manager install @duke-dsh-plugins/dsh-remote-control
@@ -24,8 +24,9 @@
24
24
  // 生成缩略图,按 §5.10 的 assistant.image / image.fetch 通道发给手机。
25
25
  import { randomUUID, createHash } from "node:crypto";
26
26
  import { readFileSync } from "node:fs";
27
- import { readFile } from "node:fs/promises";
28
- import { hostname } from "node:os";
27
+ import { mkdir, readFile } from "node:fs/promises";
28
+ import { homedir, hostname } from "node:os";
29
+ import { join } from "node:path";
29
30
  import { createRequire } from "node:module";
30
31
  import { msg, sanitizeEnvelope } from "./protocol.mjs";
31
32
  import { ASSISTANT_THROTTLE_PER_SEC } from "./config.mjs";
@@ -51,6 +52,23 @@ import {
51
52
  */
52
53
  const DELIVERED_MAX_BYTES = 20 * 1024 * 1024;
53
54
 
55
+ /**
56
+ * 单会话待发流式文本的字符上限(正文 + 思考合计)。
57
+ *
58
+ * 流式缓冲按「保序队列」实现:同一 125ms 窗口内的块都受这个上限约束,
59
+ * 超了从**最旧**的内容开始丢(保留顺序,不丢新内容),
60
+ * 避免长时间运行 / 异常事件流把内存吃满。
61
+ */
62
+ const STREAM_BUFFER_MAX_CHARS = 65_536;
63
+
64
+ /**
65
+ * 单会话待发流式**块**数的上限。
66
+ *
67
+ * 块只在「类型切换」时新增,125ms 窗口内正常也就几条;但异常事件流
68
+ * (重连回放 / 高频交替)不该让块数无界增长——超了从最旧的块开始丢。
69
+ */
70
+ const STREAM_BUFFER_MAX_BLOCKS = 256;
71
+
54
72
  /**
55
73
  * 单会话待执行消息的条数上限(契约 §5.2 session.queue)。
56
74
  *
@@ -492,33 +510,6 @@ export function mapToolResultEvent(sessionId, event) {
492
510
  };
493
511
  }
494
512
 
495
- /**
496
- * 契约 §5.2 `system.message` 事件映射(宿主 session/event 的
497
- * system/message 与 developer/message;两者共用一个 topic,用 kind 区分)。
498
- * message 可能是 {content:[blocks]},也可能是字符串——两种都兜住。
499
- * @returns {{sessionId:string,kind:"system"|"developer",text:string,ts:number}|null}
500
- */
501
- export function mapSystemMessageEvent(sessionId, event, kind) {
502
- if (!event || typeof event !== "object") return null;
503
- if (event.type !== "system/message" && event.type !== "developer/message") return null;
504
- const data = event.data;
505
- if (!data || typeof data !== "object") return null;
506
- const message = data.message !== undefined ? data.message : data;
507
- let text = "";
508
- if (typeof message === "string") {
509
- text = message;
510
- } else if (message && typeof message === "object") {
511
- text = contentText(message.content);
512
- }
513
- if (text.trim() === "") return null;
514
- return {
515
- sessionId: String(sessionId ?? ""),
516
- kind: kind === "developer" ? "developer" : "system",
517
- text,
518
- ts: eventTime(event),
519
- };
520
- }
521
-
522
513
  /**
523
514
  * 契约 §5.7 StepRecord 提取:session.history 的 page.records → steps[]。
524
515
  *
@@ -810,6 +801,34 @@ export function hostErrorOf(e, fallbackCode) {
810
801
  return { code, message: errText(e) };
811
802
  }
812
803
 
804
+ /**
805
+ * 契约 §5.1 session.create:**默认工作目录**。
806
+ *
807
+ * 手机端不传 cwd(或传空串)时,不再让宿主回退到 DSH 后端的 process.cwd(),
808
+ * 而是解析为 Host 用户主目录下的 `.dsh/remote`(用 node:path.join 拼,
809
+ * Windows / POSIX 都对)。
810
+ * @param {string} [home] 用户主目录(默认 os.homedir())
811
+ * @returns {string} 绝对路径
812
+ */
813
+ export function defaultSessionCwd(home = homedir()) {
814
+ return join(home, ".dsh", "remote");
815
+ }
816
+
817
+ /**
818
+ * 契约 §5.1 session.create:解析手机端传来的 cwd。
819
+ *
820
+ * 缺省 / undefined / 空串 / trim 后空串 → 默认目录(`~/.dsh/remote`);
821
+ * 其余按既有行为 trim 后返回;显式 cwd 不自动创建目录。
822
+ * @param {unknown} raw payload.cwd
823
+ * @param {string} [home] 用户主目录(默认 os.homedir())
824
+ * @returns {{cwd:string, isDefault:boolean}}
825
+ */
826
+ export function resolveSessionCwd(raw, home = homedir()) {
827
+ const explicit = typeof raw === "string" ? raw : "";
828
+ if (explicit.trim() !== "") return { cwd: explicit.trim(), isDefault: false };
829
+ return { cwd: defaultSessionCwd(home), isDefault: true };
830
+ }
831
+
813
832
  /** result / error 信封(契约 §5)。 */
814
833
  function resultOf(m, value) {
815
834
  return msg("result", { id: m.id, ok: true, value });
@@ -829,9 +848,16 @@ export class HostBridge {
829
848
  #cfg;
830
849
  #log;
831
850
  #pluginVersion;
851
+ // v1.1.4:session.create 的默认工作目录基准(用户主目录)+ 建目录实现
852
+ // —— 二者都可注入,生产用 homedir() / fs.mkdir,测试用临时目录(不写真实 home)。
853
+ #homeDir;
854
+ #mkdir;
832
855
  #disposed = false; // dispose() 后禁止一切出站与拦截
833
- #deltaBuf = new Map(); // sessionId -> { text, timer }(正文增量)
834
- #reasoningBuf = new Map(); // sessionId -> { text, timer }(思考增量,v1.0.7 与正文分流)
856
+ // v1.1.x:每个 session 一个**统一保序**的流式缓冲(正文 + 思考共用一条队列)
857
+ // sessionId -> { blocks: [{kind:"text"|"reasoning", text}], timer }
858
+ // 同一 125ms 窗口内只合并**相邻同类**块;不同类各占一块 → 冲刷时严格按
859
+ // 原始 chunk 顺序发 assistant.delta / assistant.reasoningDelta(跨类型也保序)。
860
+ #streamBuf = new Map();
835
861
  #modelSelections = new Map(); // sessionId -> {provider, model, reasoningEffort?}(v1.0.8 内存态)
836
862
  #pending = new Map(); // askId -> { resolve, kind, sessionId, timer, abortHandler, signal }
837
863
  #titles = new Map(); // sessionId -> title(turn.end 推送文案用)
@@ -863,6 +889,8 @@ export class HostBridge {
863
889
  * push: { notify:(req:object)=>Promise<{ok:boolean,reason?:string}>, configured:boolean, unavailableReason?:()=>string },
864
890
  * config: any,
865
891
  * log: (level:"info"|"warn"|"error", message:string, extra?:object)=>void,
892
+ * homeDir?: string, // v1.1.4:默认 cwd 的基准目录(默认 os.homedir())
893
+ * mkdir?: (p:string)=>Promise<unknown>, // v1.1.4:建默认目录(默认 fs.mkdir recursive)
866
894
  * }} deps
867
895
  */
868
896
  constructor(deps) {
@@ -871,6 +899,12 @@ export class HostBridge {
871
899
  this.#push = deps.push;
872
900
  this.#cfg = deps.config;
873
901
  this.#log = deps.log;
902
+ this.#homeDir =
903
+ typeof deps.homeDir === "string" && deps.homeDir !== "" ? deps.homeDir : homedir();
904
+ this.#mkdir =
905
+ typeof deps.mkdir === "function"
906
+ ? deps.mkdir
907
+ : (p) => mkdir(p, { recursive: true });
874
908
  this.#pluginVersion = pluginVersion();
875
909
  this.#hostName = hostname();
876
910
  this.#dshVersion = dshVersion();
@@ -899,6 +933,8 @@ export class HostBridge {
899
933
  this.#queues.delete(key);
900
934
  this.#deliveredEntries.delete(key);
901
935
  this.#runningSessions.delete(key);
936
+ // 待发的流式增量也没意义了(定时器一并清掉,别在会话没了之后还出站)
937
+ this.#dropStream(key);
902
938
  this.#sendEvent("session.removed", { sessionId: key });
903
939
  });
904
940
  this.#on("api-session/status", (sessionId, running) => {
@@ -917,20 +953,27 @@ export class HostBridge {
917
953
 
918
954
  // agent/assistant-stream:文本增量与**思考增量分流**,按 sessionId 合并节流(≤8 条/秒)
919
955
  // v1.0.7:chunk.type==='reasoning-delta' → assistant.reasoningDelta(§5.2)
956
+ // v1.1.x:两者进**同一条保序队列**——原先两个独立缓冲 + 固定「先正文后思考」
957
+ // 的冲刷顺序会把 reasoning→text 的 wire 顺序倒过来(手机端按到达顺序渲染,
958
+ // 与冷启动历史「思考在前」不一致,用户看到正文跑到思考前面)。
920
959
  this.#on("agent/assistant-stream", (payload) => {
921
960
  try {
922
961
  const frame = payload?.frame;
923
- if (!frame || frame.type !== "chunk") return;
924
- const chunk = frame.chunk;
925
- if (!chunk || typeof chunk.text !== "string" || chunk.text === "") return;
926
- if (chunk.type !== "text-delta" && chunk.type !== "reasoning-delta") return;
962
+ if (!frame) return;
927
963
  const sessionId = payload?.agent?.session?.id;
928
964
  if (!sessionId) return;
929
- if (chunk.type === "reasoning-delta") {
930
- this.#queueReasoning(String(sessionId), chunk.text);
965
+ // 一条 assistant 流结束时立即冲刷,后续 tool.call/result、图片等持久事件
966
+ // 不得越过尚未上屏的正文/思考。
967
+ if (frame.type === "end") {
968
+ this.#flushStream(String(sessionId));
931
969
  return;
932
970
  }
933
- this.#queueDelta(String(sessionId), chunk.text);
971
+ if (frame.type !== "chunk") return;
972
+ const chunk = frame.chunk;
973
+ if (!chunk || typeof chunk.text !== "string" || chunk.text === "") return;
974
+ if (chunk.type !== "text-delta" && chunk.type !== "reasoning-delta") return;
975
+ // 正文与思考进**同一条保序队列**(v1.1.x):跨类型的先后关系必须保住
976
+ this.#queueStream(String(sessionId), chunk.type === "reasoning-delta" ? "reasoning" : "text", chunk.text);
934
977
  } catch (e) {
935
978
  this.#log("warn", "assistant-stream bridge error", { error: errText(e) });
936
979
  }
@@ -942,8 +985,8 @@ export class HostBridge {
942
985
  const sessionId = payload?.agent?.session?.id;
943
986
  if (!sessionId) return;
944
987
  if (payload.status === "idle") {
945
- this.#flushDelta(String(sessionId));
946
- this.#flushReasoning(String(sessionId));
988
+ // 先统一冲刷全部待发块(正文 + 思考,**保持原始顺序**),再发 turn.end
989
+ this.#flushStream(String(sessionId));
947
990
  this.#sendEvent("turn.end", { sessionId: String(sessionId), status: "idle" });
948
991
  this.#maybeNotifyTurnEnd(String(sessionId));
949
992
  }
@@ -958,8 +1001,8 @@ export class HostBridge {
958
1001
  if (!sessionId) return;
959
1002
  const err = payload.error;
960
1003
  const message = err && typeof err.message === "string" ? err.message : String(err);
961
- this.#flushDelta(String(sessionId));
962
- this.#flushReasoning(String(sessionId));
1004
+ // 与 idle 同口径:先统一冲刷(保序),再发 turn.end
1005
+ this.#flushStream(String(sessionId));
963
1006
  this.#sendEvent("turn.end", { sessionId: String(sessionId), status: "error", error: message });
964
1007
  this.#maybeNotifyTurnEnd(String(sessionId), message);
965
1008
  } catch (e) {
@@ -967,28 +1010,32 @@ export class HostBridge {
967
1010
  }
968
1011
  });
969
1012
 
970
- // --- v1.0.6(§5.7):会话事件总闸 → tool.call / tool.result / system.message ---
1013
+ // --- v1.0.6(§5.7)→ v1.1.4:会话事件总闸 → tool.call / tool.result ---
971
1014
  // 宿主每写入一条会话日志事件就触发(覆盖所有会话,含 subagent)。
972
1015
  // 按 session.id 寻址即可,**不过滤**子代理;不认识的事件类型直接忽略,
973
1016
  // 绝不因为形状不认识而抛错(#on 包装器已兜底)。
1017
+ // v1.1.4:**不再桥接 system/message / developer/message**——宿主里它们是
1018
+ // 系统提示词节点与工具注册表变更(提示词组装记录,不是对话内容),
1019
+ // DSH 桌面端的聊天视图从不展示;手机端曾把它们当「系统消息」显示,
1020
+ // 造成时间线里出现大段多余的系统提示文本(用户反馈)。
974
1021
  this.#on("session/event", (session, event) => {
975
1022
  const sessionId = String(session?.id ?? "");
976
1023
  if (sessionId === "") return;
977
1024
  const type = event?.type;
978
1025
  if (type === "tool/call") {
979
1026
  const mapped = mapToolCallEvent(sessionId, event);
980
- if (mapped !== null) this.#sendEvent("tool.call", mapped);
1027
+ if (mapped !== null) {
1028
+ this.#flushStream(sessionId);
1029
+ this.#sendEvent("tool.call", mapped);
1030
+ }
981
1031
  return;
982
1032
  }
983
1033
  if (type === "tool/result") {
984
1034
  const mapped = mapToolResultEvent(sessionId, event);
985
- if (mapped !== null) this.#sendEvent("tool.result", mapped);
986
- return;
987
- }
988
- if (type === "system/message" || type === "developer/message") {
989
- const kind = type === "developer/message" ? "developer" : "system";
990
- const mapped = mapSystemMessageEvent(sessionId, event, kind);
991
- if (mapped !== null) this.#sendEvent("system.message", mapped);
1035
+ if (mapped !== null) {
1036
+ this.#flushStream(sessionId);
1037
+ this.#sendEvent("tool.result", mapped);
1038
+ }
992
1039
  return;
993
1040
  }
994
1041
  if (type === "model/selection") {
@@ -1000,13 +1047,16 @@ export class HostBridge {
1000
1047
  return;
1001
1048
  }
1002
1049
  if (type === "assistant/message") {
1003
- // v1.0.9(§5.10):助手消息里的图片 → 广播 assistant.image(带内联缩略图)
1050
+ // v1.0.9(§5.10):助手消息里的图片 → 广播 assistant.image(带内联缩略图)。
1051
+ // 即便本条没有图片,也先把之前的流式文本/思考冲出去,保持时间线顺序。
1052
+ this.#flushStream(sessionId);
1004
1053
  this.#emitAssistantImages(sessionId, event);
1005
1054
  return;
1006
1055
  }
1007
1056
  if (type === "deliverables/presented") {
1008
1057
  // present 工具投递的文件:宿主记的是**路径**,不是图片附件块 →
1009
1058
  // 不桥接的话手机端永远看不到这些图(用户反馈:桌面有、手机没有)。
1059
+ this.#flushStream(sessionId);
1010
1060
  void this.#emitDeliveredImages(sessionId, event);
1011
1061
  return;
1012
1062
  }
@@ -1189,6 +1239,36 @@ export class HostBridge {
1189
1239
  return this.#service("workspaceRegistry");
1190
1240
  }
1191
1241
 
1242
+ /**
1243
+ * v1.1.4:按 cwd 反查它是否属于某个**已注册工作区**的目录。
1244
+ * 命中返回该工作区的 id(供 `session.create` 传 `workspaceId` 归组),
1245
+ * 否则返回 null(调用方退回传 cwd,与 PC 在普通目录新建一样 = 未分组)。
1246
+ *
1247
+ * 用宿主 `workspaceRegistry.resolveByPath`:按 canonical path 匹配,
1248
+ * **不创建**工作区、不改写注册表;目录不存在会 reject。
1249
+ * 任何异常(服务缺失 / 方法不存在 / 路径解析失败)都兜底回 null——
1250
+ * 归组是增强,绝不能因此让 session.create 失败。
1251
+ * @param {string} cwd
1252
+ * @returns {Promise<string|null>}
1253
+ */
1254
+ async #resolveWorkspaceByCwd(cwd) {
1255
+ try {
1256
+ const reg = this.#workspaceRegistry();
1257
+ if (!reg || typeof reg.resolveByPath !== "function") return null;
1258
+ const ws = await reg.resolveByPath(cwd);
1259
+ const id = typeof ws?.id === "string" && ws.id !== "" ? ws.id : null;
1260
+ if (id !== null) {
1261
+ this.#log("info", "session.create cwd matches a workspace; attaching to it", {
1262
+ workspaceId: id,
1263
+ });
1264
+ }
1265
+ return id;
1266
+ } catch (e) {
1267
+ this.#log("warn", "resolveByPath failed; session stays ungrouped", { error: errText(e) });
1268
+ return null;
1269
+ }
1270
+ }
1271
+
1192
1272
  /** 事件监听包装:emit 监听必须永不抛出。 */
1193
1273
  #on(name, handler) {
1194
1274
  const wrapped = (...args) => {
@@ -1211,14 +1291,10 @@ export class HostBridge {
1211
1291
  /** 释放全部资源(定时器/待答项/监听)。 */
1212
1292
  dispose() {
1213
1293
  this.#disposed = true;
1214
- for (const b of this.#deltaBuf.values()) {
1294
+ for (const b of this.#streamBuf.values()) {
1215
1295
  if (b.timer !== null) clearTimeout(b.timer);
1216
1296
  }
1217
- this.#deltaBuf.clear();
1218
- for (const b of this.#reasoningBuf.values()) {
1219
- if (b.timer !== null) clearTimeout(b.timer);
1220
- }
1221
- this.#reasoningBuf.clear();
1297
+ this.#streamBuf.clear();
1222
1298
  for (const entry of this.#pending.values()) {
1223
1299
  if (entry.timer !== null) clearTimeout(entry.timer);
1224
1300
  if (entry.signal && entry.abortHandler) {
@@ -1605,58 +1681,101 @@ export class HostBridge {
1605
1681
  }
1606
1682
  }
1607
1683
 
1608
- // ---- assistant.delta 节流 -------------------------------------------------
1684
+ // ---- assistant 流式增量:统一保序缓冲(正文 + 思考,v1.1.x)---------------
1609
1685
 
1610
- #queueDelta(sessionId, text) {
1611
- let b = this.#deltaBuf.get(sessionId);
1686
+ /**
1687
+ * 入队一个流式增量块。
1688
+ *
1689
+ * 规则:
1690
+ * - 正文(text)与思考(reasoning)进**同一条队列**,块按到达顺序排;
1691
+ * - 同一窗口内**只合并相邻同类**块(尾块同类就并进去);
1692
+ * - 不同类**不跨块合并**——否则 reasoning 与 text 会糊成一条,
1693
+ * 冲刷时无法还原原始先后顺序。
1694
+ *
1695
+ * @param {string} sessionId
1696
+ * @param {"text"|"reasoning"} kind
1697
+ * @param {string} text
1698
+ */
1699
+ #queueStream(sessionId, kind, text) {
1700
+ if (this.#disposed) return; // dispose() 后不再产生任何出站
1701
+ let b = this.#streamBuf.get(sessionId);
1612
1702
  if (b === undefined) {
1613
- b = { text: "", timer: null };
1614
- this.#deltaBuf.set(sessionId, b);
1703
+ b = { blocks: [], timer: null };
1704
+ this.#streamBuf.set(sessionId, b);
1615
1705
  }
1616
- b.text += text;
1617
- if (b.text.length > 65_536) b.text = b.text.slice(-65_536); // 内存上限
1706
+ const last = b.blocks[b.blocks.length - 1];
1707
+ if (last !== undefined && last.kind === kind) {
1708
+ last.text += text;
1709
+ } else {
1710
+ b.blocks.push({ kind, text });
1711
+ }
1712
+ this.#trimStreamBuffer(b);
1618
1713
  if (b.timer === null) {
1619
- b.timer = setTimeout(() => this.#flushDelta(sessionId), Math.ceil(1000 / ASSISTANT_THROTTLE_PER_SEC));
1714
+ b.timer = setTimeout(() => this.#flushStream(sessionId), Math.ceil(1000 / ASSISTANT_THROTTLE_PER_SEC));
1620
1715
  }
1621
1716
  }
1622
1717
 
1623
- #flushDelta(sessionId) {
1624
- const b = this.#deltaBuf.get(sessionId);
1718
+ /**
1719
+ * 内存上限:单会话待发文本(正文 + 思考合计)不超过 STREAM_BUFFER_MAX_CHARS。
1720
+ *
1721
+ * 超了从**最旧**的内容开始丢(保序:只丢头,不动类型顺序,也不丢新内容)。
1722
+ * 块数另有 STREAM_BUFFER_MAX_BLOCKS 上限(类型频繁切换时的兜底)。
1723
+ * @param {{blocks:{kind:string,text:string}[]}} b
1724
+ */
1725
+ #trimStreamBuffer(b) {
1726
+ let total = 0;
1727
+ for (const blk of b.blocks) total += blk.text.length;
1728
+ let excess = total - STREAM_BUFFER_MAX_CHARS;
1729
+ while (excess > 0 && b.blocks.length > 0) {
1730
+ const first = b.blocks[0];
1731
+ if (first.text.length <= excess) {
1732
+ excess -= first.text.length;
1733
+ b.blocks.shift();
1734
+ } else {
1735
+ first.text = first.text.slice(excess);
1736
+ excess = 0;
1737
+ }
1738
+ }
1739
+ while (b.blocks.length > STREAM_BUFFER_MAX_BLOCKS) b.blocks.shift();
1740
+ }
1741
+
1742
+ /**
1743
+ * 冲刷一个会话的全部待发块:**严格按原始 chunk 顺序**逐块发
1744
+ * (assistant.delta / assistant.reasoningDelta),跨类型也保序。
1745
+ * @param {string} sessionId
1746
+ */
1747
+ #flushStream(sessionId) {
1748
+ const b = this.#streamBuf.get(sessionId);
1625
1749
  if (b === undefined) return;
1626
1750
  if (b.timer !== null) {
1627
1751
  clearTimeout(b.timer);
1628
1752
  b.timer = null;
1629
1753
  }
1630
- const text = b.text;
1631
- b.text = "";
1632
- if (text !== "") this.#sendEvent("assistant.delta", { sessionId, text });
1633
- }
1634
-
1635
- // ---- assistant.reasoningDelta 节流(v1.0.7,与正文同口径 ≤8 条/秒)--------
1636
-
1637
- #queueReasoning(sessionId, text) {
1638
- let b = this.#reasoningBuf.get(sessionId);
1639
- if (b === undefined) {
1640
- b = { text: "", timer: null };
1641
- this.#reasoningBuf.set(sessionId, b);
1642
- }
1643
- b.text += text;
1644
- if (b.text.length > 65_536) b.text = b.text.slice(-65_536); // 内存上限
1645
- if (b.timer === null) {
1646
- b.timer = setTimeout(() => this.#flushReasoning(sessionId), Math.ceil(1000 / ASSISTANT_THROTTLE_PER_SEC));
1754
+ const blocks = b.blocks;
1755
+ b.blocks = [];
1756
+ // 空了就别占着 map(会话很多时避免无界增长)
1757
+ if (this.#streamBuf.get(sessionId) === b) this.#streamBuf.delete(sessionId);
1758
+ if (this.#disposed) return; // dispose() 后不再产生任何出站
1759
+ for (const blk of blocks) {
1760
+ if (blk.text === "") continue;
1761
+ if (blk.kind === "reasoning") {
1762
+ this.#sendEvent("assistant.reasoningDelta", { sessionId, text: blk.text });
1763
+ } else {
1764
+ this.#sendEvent("assistant.delta", { sessionId, text: blk.text });
1765
+ }
1647
1766
  }
1648
1767
  }
1649
1768
 
1650
- #flushReasoning(sessionId) {
1651
- const b = this.#reasoningBuf.get(sessionId);
1769
+ /** 丢弃某会话的待发块(会话没了)——清定时器 + 清队列。 */
1770
+ #dropStream(sessionId) {
1771
+ const b = this.#streamBuf.get(sessionId);
1652
1772
  if (b === undefined) return;
1653
1773
  if (b.timer !== null) {
1654
1774
  clearTimeout(b.timer);
1655
1775
  b.timer = null;
1656
1776
  }
1657
- const text = b.text;
1658
- b.text = "";
1659
- if (text !== "") this.#sendEvent("assistant.reasoningDelta", { sessionId, text });
1777
+ b.blocks = [];
1778
+ this.#streamBuf.delete(sessionId);
1660
1779
  }
1661
1780
 
1662
1781
  // ---- 业务请求分发(§5.1)---------------------------------------------------
@@ -1689,7 +1808,7 @@ export class HostBridge {
1689
1808
  case "session.selectModel":
1690
1809
  return await this.#rSessionSelectModel(m);
1691
1810
  case "session.model":
1692
- return this.#rSessionModel(m);
1811
+ return await this.#rSessionModel(m);
1693
1812
  case "session.queue":
1694
1813
  return this.#rSessionQueue(m);
1695
1814
  case "session.archive":
@@ -2072,7 +2191,44 @@ export class HostBridge {
2072
2191
  try {
2073
2192
  const sc = this.#sc();
2074
2193
  const req = {};
2075
- if (typeof p.cwd === "string" && p.cwd !== "") req.cwd = p.cwd;
2194
+ // v1.1.4:cwd 缺省 / undefined / 空串 / trim 后空串时,**不再**交给宿主
2195
+ // 回退到 DSH 后端的 process.cwd()——解析为 Host 用户主目录下的
2196
+ // `~/.dsh/remote`,并**先确保目录存在**(失败直接回错,不静默回退)。
2197
+ // 显式非空 cwd 保持原行为(不自动建目录)。
2198
+ const { cwd, isDefault } = resolveSessionCwd(p.cwd, this.#homeDir);
2199
+ if (isDefault) {
2200
+ if (p.cwd !== undefined && p.cwd !== null && typeof p.cwd !== "string") {
2201
+ this.#log("warn", "session.create got a non-string cwd; using the default directory", {
2202
+ type: typeof p.cwd,
2203
+ });
2204
+ }
2205
+ try {
2206
+ await this.#mkdir(cwd);
2207
+ } catch (e) {
2208
+ this.#log("error", "failed to create the default session directory", {
2209
+ error: errText(e),
2210
+ });
2211
+ this.#reply(
2212
+ m,
2213
+ errorOf(m, "session-create-failed", "cannot create session directory: " + errText(e)),
2214
+ );
2215
+ return;
2216
+ }
2217
+ }
2218
+ // v1.1.4:cwd 若命中某个**已注册工作区**的目录,改传 `workspaceId`
2219
+ // 让会话自动归到该工作区下面(与 PC 端「在工作区里新建」一致——
2220
+ // PC 走 createInWorkspace → createNamed({workspaceId}))。
2221
+ // 旧实现只传 cwd,宿主不会 attach 到任何工作区 → PC 上显示「未分组」。
2222
+ // 未命中(普通目录)保持传 cwd,与 PC 在任意目录新建一样 = 未分组。
2223
+ // resolveByPath 不创建工作区、不改写注册表;路径不存在会 reject → 兜底回 cwd。
2224
+ // 默认目录(~/.dsh/remote)同样走这条反查:已注册 → 传 workspaceId,
2225
+ // 未注册 → 传该 cwd(**不自动注册工作区**)。
2226
+ const ws = await this.#resolveWorkspaceByCwd(cwd);
2227
+ if (ws !== null) {
2228
+ req.workspaceId = ws;
2229
+ } else {
2230
+ req.cwd = cwd;
2231
+ }
2076
2232
  if (agentPreset !== "") req.agentPreset = agentPreset;
2077
2233
  let value;
2078
2234
  try {
@@ -2267,18 +2423,48 @@ export class HostBridge {
2267
2423
  }
2268
2424
  }
2269
2425
 
2270
- /** 契约 §5.1/§5.8(v1.0.8)session.model:查询会话当前模型/思考强度。
2271
- * 数据源是 model/selection 会话事件维护的**内存态**——插件重启后无记录 → null
2272
- * (**不得臆造**;客户端回退展示目录默认)。 */
2273
- #rSessionModel(m) {
2426
+ /** 契约 §5.1/§5.8 session.model:查询会话当前模型/思考强度(v1.0.8 引入,
2427
+ * v1.1.4 数据源升级)。
2428
+ *
2429
+ * 权威数据源 = 宿主 **modelSelection 持久投影**(`sessionController.projections`
2430
+ * 的 `values.modelSelection`,视图形状 `{lastUsed, next}`,`next = pending ?? lastUsed`)。
2431
+ * 这与 DSH 桌面端 composer 显示的是**同一份**(dsh-client-ui-model-selection 的
2432
+ * syncInputs:`selection = projected.next ?? catalog.default`):
2433
+ * - `pending`:用户在会话里显式切换过、还没被请求消费的模型;
2434
+ * - `lastUsed`:上一个 `request/header` 实际使用的模型(旧实现完全漏掉它——
2435
+ * 从没显式切换过的会话在旧实现里永远回 null,手机端就总显示目录默认,
2436
+ * 与 PC 对不上,用户实测反馈);
2437
+ * - 两者都空(从未跑过也没选过的空白会话)→ null,客户端回退目录默认
2438
+ * (= PC 的 catalog.default 回退,天然一致)。
2439
+ *
2440
+ * 投影不可用(旧宿主没注册)/读取失败 → 退回 `model/selection` 直播事件维护的
2441
+ * 内存态(v1.0.8 行为);再没有 → null。**不得臆造**。 */
2442
+ async #rSessionModel(m) {
2274
2443
  const p = m.payload ?? {};
2275
2444
  const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
2276
2445
  if (sessionId === "") {
2277
2446
  this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
2278
2447
  return;
2279
2448
  }
2280
- const model = this.#modelSelections.get(sessionId) ?? null;
2281
- this.#reply(m, resultOf(m, { model }));
2449
+ try {
2450
+ const sc = this.#sc();
2451
+ if (typeof sc.projections === "function") {
2452
+ const projections = await sc.projections({ sessionId }, this.#signal(10_000));
2453
+ const view = projections?.values?.modelSelection;
2454
+ if (view !== undefined && view !== null) {
2455
+ const model = mapModelSelection(view.next ?? view.lastUsed ?? null);
2456
+ this.#reply(m, resultOf(m, { model }));
2457
+ return;
2458
+ }
2459
+ }
2460
+ } catch (e) {
2461
+ // 投影缺失/读取失败 → 退回直播事件内存态(不报错,静默降级)
2462
+ this.#log("warn", "modelSelection projection unavailable; falling back to live tracking", {
2463
+ sessionId,
2464
+ error: errText(e),
2465
+ });
2466
+ }
2467
+ this.#reply(m, resultOf(m, { model: this.#modelSelections.get(sessionId) ?? null }));
2282
2468
  }
2283
2469
 
2284
2470
  /** 模式目录(宿主 Agent preset 目录)。服务缺失/抛错 → 空目录。 */
package/market/index.json CHANGED
@@ -69,9 +69,29 @@
69
69
  "sortKeys": {}
70
70
  },
71
71
  "versions": [
72
+ {
73
+ "version": "1.1.6",
74
+ "publishTimestamp": 1793202911,
75
+ "source": {
76
+ "type": "npm"
77
+ },
78
+ "engines": {
79
+ "dsh": "^0.1.5-rc.3 || ^0.2.0-rc.1 || ^0.2.1-rc.0"
80
+ }
81
+ },
82
+ {
83
+ "version": "1.1.5",
84
+ "publishTimestamp": 1793149134,
85
+ "source": {
86
+ "type": "npm"
87
+ },
88
+ "engines": {
89
+ "dsh": "^0.1.5-rc.3 || ^0.2.0-rc.1 || ^0.2.1-rc.0"
90
+ }
91
+ },
72
92
  {
73
93
  "version": "1.1.4",
74
- "publishTimestamp": 1793036288,
94
+ "publishTimestamp": 1793036707,
75
95
  "source": {
76
96
  "type": "npm"
77
97
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duke-dsh-plugins/dsh-remote-control",
3
- "version": "1.1.4",
3
+ "version": "1.1.6",
4
4
  "description": "Remote-control bridge for DeepSeek Harness: pairs a HarmonyOS phone app with the desktop Host over an end-to-end-encrypted public relay (WebSocket). Lets the phone list/create/switch sessions, send prompts, watch streamed replies, cancel turns, and answer approval and ask-user-question requests from anywhere; pushes Huawei Push Kit notifications (gracefully disabled when AGC is unconfigured) for approvals, questions, and turn completion. The pairing QR lives in the DSH settings panel (\"DSH Pocket\"). Fail-open by design: any relay timeout or fault hands the request back to the desktop answerer.",
5
5
  "type": "module",
6
6
  "main": "index.js",