dsh-mobile-plugin 0.5.121 → 0.5.122

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
@@ -72,7 +72,7 @@
72
72
  <img src="https://raw.githubusercontent.com/WNLUO/dsh-mobile-plugin/main/assets/remote-computer.jpg" alt="在另一台电脑上通过本机地址打开 DeepSeek Harness 的完整网页" width="720">
73
73
  </p>
74
74
 
75
- 窗口优先由插件随包分发的桌面显示壳打开,Mac 上按官方桌面端的样式排版;每次访问一小时,可自动续期。细节和撤销方式见 [docs/remote-computer.md](docs/remote-computer.md)。
75
+ 窗口优先由插件随包分发的桌面显示壳打开,Mac 上按官方桌面端的样式排版;每次访问一小时,可自动续期。用桌面壳打开时快捷键和桌面端一致,按你本机保存,只作用于这台远程窗口,用普通浏览器打开还是网页版那套。细节和撤销方式见 [docs/remote-computer.md](docs/remote-computer.md)。
76
76
 
77
77
  ## 安全与隐私
78
78
 
@@ -1,7 +1,11 @@
1
- /** 远程网页的只读租期提示、桌面壳的排版适配与主文档流式脚本注入。 */
1
+ /**
2
+ * 远程网页的只读租期提示、桌面壳的排版适配与主文档流式脚本注入。
3
+ * 2026-11-26:桌面壳会话安装官方快捷键桥,普通浏览器不碰键盘。
4
+ */
2
5
  'use strict';
3
6
 
4
7
  const { Transform } = require('node:stream');
8
+ const { shortcutBridgeScript } = require('./shortcut-bridge.cjs');
5
9
 
6
10
  const SCRIPT_TAG = Buffer.from('<script src="/__dsh_remote_notice.js" defer></script>');
7
11
  const TEXT = {
@@ -187,7 +191,7 @@ function shellScript(platform) {
187
191
  }
188
192
 
189
193
  function noticeScript({ shell = false, platform = '' } = {}) {
190
- return `${shell ? shellScript(platform) : ''}(${browserNotice.toString()})(${JSON.stringify(TEXT)});`;
194
+ return `${shell ? shellScript(platform) : ''}${shell ? shortcutBridgeScript(platform) : ''}(${browserNotice.toString()})(${JSON.stringify(TEXT)});`;
191
195
  }
192
196
 
193
197
  /** 仅保留开头少量字节定位 head;剩余文档直接透传,保留字节与背压。 */
@@ -1,7 +1,9 @@
1
1
  'use strict';
2
+ // 2026-11-26:远程电脑取启动令牌改走 launchTokenOf,跟新宿主删 browserAuth 后的兜底同源,别再硬读旧字段。
2
3
  // 电脑间远程网页的装配与生命周期;入口只在可信本机界面签发。
3
4
  // 落点代理转给宿主 web 服务时跟随宿主实际绑定地址(见 relay/tunnel-forwarder.cjs)。
4
5
  const os = require('node:os');
6
+ const { launchTokenOf } = require('../mobile/host-web.js');
5
7
  const { createRemoteStore } = require('./store.cjs');
6
8
  const { createRemoteHost } = require('./host.cjs');
7
9
  const transport = require('./transport.cjs');
@@ -18,7 +20,7 @@ function mountRemoteComputers({ ctx, state, credentials, registerRoute, lanPortI
18
20
  state, credentials, routesOf: control.routesOf,
19
21
  getUpstreamPort: async () => { await forwarder.start(); return forwarder.port(); },
20
22
  getWebPort: () => ctx.webServer.port,
21
- getLaunchToken: () => ctx.get('connection')?.browserAuth?.launchToken || '',
23
+ getLaunchToken: () => launchTokenOf(ctx) || '',
22
24
  getConnectionInfo: control.connectionInfo,
23
25
  onControl: control.onControl, onInvite, log,
24
26
  });
@@ -0,0 +1,158 @@
1
+ /**
2
+ * 远程桌面壳会话里的官方快捷键运行时桥接脚本。
3
+ *
4
+ * 桌面壳打开的是 A 电脑上的完整 DSH 网页。官方 @deepseek-ai/dsh-client-shortcuts
5
+ * 靠根元素的 data-platform 判断运行时:有值走 desktop、没值走 web。想在壳里用上官方
6
+ * desktop 快捷键,就得让根元素的 dataset.platform 有值;但这个值绝不能变成真实的
7
+ * HTML 属性,否则会命中官方桌面 CSS、让壳排版错乱,所以只在 dataset 对象上挂一个
8
+ * 自有属性,JS 读到精确平台值(决定键位和键帽),CSS 的 [data-platform] 一概不命中。
9
+ * desktop 运行时还要求 window.dshDesktop 提供 keyboard 和 shortcuts 两个桥,缺一个
10
+ * 就抛 "Desktop keyboard bridge unavailable"、让整页插件加载失败,因此这里把浏览器
11
+ * 键盘事件转成官方 DesktopShortcutInput,并用 localStorage 持久化一份合法快捷键文档。
12
+ * 只在 Mac/Windows 壳接管:Linux 桌面运行时仍由 DOM 处理可配置键,装原生桥会双投递。
13
+ *
14
+ * 日期:2026-11-26
15
+ */
16
+ 'use strict';
17
+
18
+ /**
19
+ * 浏览器端自执行函数,完全自包含,不引用任何 Node 作用域变量,可在 vm.runInContext 上执行。
20
+ * @param {string} nodePlatform Node 的 process.platform(darwin/win32/linux)。
21
+ */
22
+ function install(nodePlatform) {
23
+ 'use strict';
24
+
25
+ // 官方 detectEnvironment 读根元素 dataset.platform 决定运行时和平台。挂一个自有属性
26
+ // 让 JS 读到精确平台值(决定 default profile 和键帽),但不写真实属性,避免命中
27
+ // 官方桌面 CSS。重复执行时属性已在,整体跳过,保持幂等。
28
+ // Linux 桌面运行时仍由 DOM 处理可配置快捷键,再装原生桥会双投递,故只接管 Mac/Windows。
29
+ const root = document.documentElement;
30
+ if (Object.prototype.hasOwnProperty.call(root.dataset, 'platform')) return;
31
+ const platform = nodePlatform === 'darwin' ? 'darwin'
32
+ : nodePlatform === 'win32' ? 'win32' : '';
33
+ if (!platform) return;
34
+ try {
35
+ Object.defineProperty(root.dataset, 'platform', { value: platform, configurable: true });
36
+ } catch { return; } // 浏览器不让挂就整段跳过:退回网页版快捷键,绝不半安装触发原生桥缺失。
37
+ if (root.dataset.platform !== platform) return;
38
+
39
+ // 官方 shortcut document 的 profile 键是 desktop:<平台标识>。
40
+ const official = platform === 'darwin' ? 'macos' : 'windows';
41
+ const profileKey = 'desktop:' + official;
42
+ const storageKey = 'dshm:remote:shortcuts';
43
+
44
+ let sequence = 1;
45
+ let revision = 'remote-1';
46
+ let profile = {};
47
+
48
+ function buildDocument() {
49
+ const doc = { schemaVersion: 1, profiles: {} };
50
+ doc.profiles[profileKey] = profile;
51
+ return doc;
52
+ }
53
+
54
+ // 某些 webview 会禁用 localStorage,读写都要兜住,坏数据就当无覆盖。
55
+ function read() {
56
+ try {
57
+ const raw = window.localStorage.getItem(storageKey);
58
+ const saved = raw ? JSON.parse(raw) : null;
59
+ const value = saved && saved.profiles && saved.profiles[profileKey];
60
+ if (value && typeof value === 'object' && !Array.isArray(value)) profile = value;
61
+ } catch { /* 禁用或坏数据:从空覆盖开始。 */ }
62
+ }
63
+
64
+ function write() {
65
+ try {
66
+ window.localStorage.setItem(storageKey, JSON.stringify(buildDocument()));
67
+ } catch { /* 写不进去也不影响本次会话。 */ }
68
+ }
69
+
70
+ read();
71
+
72
+ const shortcutListeners = new Set();
73
+ const keyboardListeners = new Set();
74
+
75
+ function snapshot() {
76
+ return {
77
+ revision,
78
+ sequence,
79
+ document: buildDocument(),
80
+ status: 'ready',
81
+ error: null,
82
+ usingDefaults: Object.keys(profile).length === 0,
83
+ };
84
+ }
85
+
86
+ // 官方 ShortcutsService.syncDefinitions() 会 .then() 这个返回值,必须是 Promise。
87
+ const shortcuts = {
88
+ get() {
89
+ return Promise.resolve(snapshot());
90
+ },
91
+ edit(edit) {
92
+ if (edit && typeof edit === 'object') {
93
+ if (edit.type === 'set' && edit.id != null) profile[edit.id] = edit.binding;
94
+ else if (edit.type === 'reset' && edit.id != null) delete profile[edit.id];
95
+ else if (edit.type === 'reset-all') profile = {};
96
+ }
97
+ write();
98
+ sequence += 1;
99
+ revision = 'remote-' + sequence;
100
+ const next = snapshot();
101
+ for (const listener of shortcutListeners) listener(next);
102
+ return Promise.resolve({ status: 'saved', snapshot: next });
103
+ },
104
+ subscribe(listener) {
105
+ shortcutListeners.add(listener);
106
+ return () => shortcutListeners.delete(listener);
107
+ },
108
+ recording() {
109
+ return Promise.resolve();
110
+ },
111
+ };
112
+
113
+ // 官方 installNativeKeyboard 会拿 input.revision 与 get() 的 revision 比对,
114
+ // 所以派发时读最新值,edit 之后自然跟上。只监听 keydown:官方原生键盘桥只在
115
+ // 按下时投递一次,keyup 再投一次会让每个快捷键执行两遍。
116
+ function dispatch(event) {
117
+ const input = {
118
+ revision,
119
+ kind: 'keyboard',
120
+ frameName: '',
121
+ code: event.code,
122
+ control: !!event.ctrlKey,
123
+ alt: !!event.altKey,
124
+ shift: !!event.shiftKey,
125
+ meta: !!event.metaKey,
126
+ repeat: !!event.repeat,
127
+ };
128
+ for (const listener of keyboardListeners) listener(input);
129
+ }
130
+
131
+ // 不 preventDefault / stopPropagation:键盘事件还要照常到达输入框。
132
+ window.addEventListener('keydown', dispatch);
133
+
134
+ const keyboard = {
135
+ subscribe(listener) {
136
+ keyboardListeners.add(listener);
137
+ return () => keyboardListeners.delete(listener);
138
+ },
139
+ closeWindow() {
140
+ return Promise.resolve();
141
+ },
142
+ };
143
+
144
+ // fileActions / deviceInfo 只在被读取时提供,且都不能是「有对象但缺方法」:
145
+ // 官方 BrowserFileActions 用 desktop!==undefined 判断能否 save,缺方法会在点保存时抛错。
146
+ window.dshDesktop = {
147
+ keyboard,
148
+ shortcuts,
149
+ deviceInfo: () => Promise.resolve('DSH remote desktop'),
150
+ };
151
+ }
152
+
153
+ /** 生成可注入主文档的自执行脚本字符串。 */
154
+ function shortcutBridgeScript(platform) {
155
+ return `(${install.toString()})(${JSON.stringify(platform)});`;
156
+ }
157
+
158
+ module.exports = { shortcutBridgeScript };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.121",
3
+ "version": "0.5.122",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",
@@ -117,23 +117,23 @@
117
117
  "yaml": "2.9.1"
118
118
  },
119
119
  "dshMobileReleaseNotes": {
120
- "version": "0.5.121",
120
+ "version": "0.5.122",
121
121
  "kinds": [
122
122
  "feature",
123
123
  "fix"
124
124
  ],
125
125
  "notes": {
126
- "zh-Hans": "- 面板补齐土耳其语,错误提示也会按界面语言显示,看不懂的报错更少了。\n- 修复 Windows 上关闭控制台时可能误把后台连接进程一起关掉的问题,连接更稳。",
127
- "zh-Hant": "- 面板補齊土耳其語,錯誤提示也會按介面語言顯示,看不懂的報錯更少了。\n- 修正 Windows 上關閉主控台時可能誤把背景連線程序一起關掉的問題,連線更穩。",
128
- "en": "- The panel now supports Turkish, and error messages follow your interface language, so fewer errors are left untranslated.\n- Fixed an issue on Windows where closing the console could also shut down the background connection process, making connections more stable.",
129
- "ja": "- パネルにトルコ語を追加し、エラー表示も画面の言語に合わせて表示されるようになりました。意味が分からないエラーが減ります。\n- Windows でコンソールを閉じたときにバックグラウンド接続プロセスまで終了してしまう問題を修正し、接続がより安定しました。",
130
- "ko": "- 패널에 튀르키예어를 추가했고, 오류 메시지도 화면 언어에 맞춰 표시되어 이해할 수 없는 오류가 줄었습니다.\n- Windows에서 콘솔을 닫을 때 백그라운드 연결 프로세스까지 함께 종료되던 문제를 수정해 연결이 더 안정적입니다.",
131
- "de": "- Das Panel unterstützt jetzt Türkisch, und Fehlermeldungen folgen der Oberflächensprache, sodass weniger Meldungen unverständlich bleiben.\n- Behoben: Unter Windows konnte das Schließen der Konsole auch den Hintergrund-Verbindungsprozess beenden; Verbindungen sind jetzt stabiler.",
132
- "es": "- El panel ahora admite turco y los mensajes de error siguen el idioma de la interfaz, así que hay menos errores sin traducir.\n- Se corrigió un problema en Windows por el que cerrar la consola podía cerrar también el proceso de conexión en segundo plano; las conexiones son más estables.",
133
- "fr": "- Le panneau prend désormais en charge le turc et les messages d'erreur suivent la langue de l'interface : moins d'erreurs restent incompréhensibles.\n- Correction sous Windows : fermer la console pouvait aussi arrêter le processus de connexion en arrière-plan ; les connexions sont plus stables.",
134
- "pt": "- O painel agora suporta turco e as mensagens de erro seguem o idioma da interface, então há menos erros sem tradução.\n- Corrigido um problema no Windows em que fechar o console também encerrava o processo de conexão em segundo plano; as conexões ficam mais estáveis.",
135
- "ru": "- Панель теперь поддерживает турецкий язык, а сообщения об ошибках выводятся на языке интерфейса, поэтому непонятных ошибок стало меньше.\n- Исправлена проблема в Windows: закрытие консоли могло завершить и фоновый процесс подключения; соединения стали стабильнее.",
136
- "tr": "- Panel artık Türkçe'yi destekliyor ve hata mesajları arayüz dilinde gösteriliyor, böylece anlaşılmayan hata sayısı azalıyor.\n- Windows'da konsolu kapatmanın arka plandaki bağlantı sürecini de sonlandırabilmesi sorunu düzeltildi; bağlantılar artık daha kararlı."
126
+ "zh-Hans": "- 远程桌面窗口(Mac/Windows)现在支持 ⌘N、⌘B、⌘K 等桌面快捷键,改过的键位按本机保存,页面排版不变。\n- 修复新版宿主下远程电脑取不到启动令牌、被误判为「对方电脑暂时不可用」的问题,连接更稳。",
127
+ "zh-Hant": "- 遠端桌面視窗(Mac/Windows)現在支援 ⌘N、⌘B、⌘K 等桌面快捷鍵,改過的鍵位按本機儲存,頁面排版不變。\n- 修正新版宿主下遠端電腦取不到啟動令牌、被誤判為「對方電腦暫時不可用」的問題,連線更穩。",
128
+ "en": "- Remote desktop windows on Mac and Windows now support desktop shortcuts such as Cmd-N, Cmd-B and Cmd-K; your custom key bindings are saved on the local machine and the page layout is unchanged.\n- Fixed an issue where newer hosts could leave a remote computer without its launch token, causing a false \"computer temporarily unavailable\" message. Connections are now more reliable.",
129
+ "ja": "- Mac/Windows のリモートデスクトップ画面で、Cmd-N や Cmd-B、Cmd-K などのデスクトップショートカットが使えるようになりました。変更したキー設定はそのパソコンに保存され、画面のレイアウトは変わりません。\n- 新しいホスト環境でリモートパソコンが起動トークンを取得できず、「相手のパソコンが一時的に利用できません」と誤表示される問題を修正し、接続がより安定しました。",
130
+ "ko": "- Mac/Windows 원격 데스크톱 창에서 Cmd-N, Cmd-B, Cmd-K 같은 데스크톱 단축키를 이제 사용할 수 있습니다. 변경한 키 설정은 해당 컴퓨터에 저장되며 화면 배치는 그대로입니다.\n- 새로운 호스트 환경에서 원격 컴퓨터가 시작 토큰을 가져오지 못해 '상대 컴퓨터를 일시적으로 사용할 수 없습니다'라고 잘못 표시되던 문제를 수정했습니다. 연결이 더 안정적입니다.",
131
+ "de": "- Remote-Desktop-Fenster unter Mac und Windows unterstützen jetzt Desktop-Tastenkürzel wie Cmd-N, Cmd-B und Cmd-K. Eigene Tastenbelegungen werden auf dem jeweiligen Rechner gespeichert, das Seitenlayout bleibt unverändert.\n- Behoben: Unter neueren Hosts konnte ein Remoterechner seinen Start-Token nicht abrufen und wurde fälschlich als „vorübergehend nicht verfügbar“ gemeldet. Verbindungen sind jetzt stabiler.",
132
+ "es": "- Las ventanas de escritorio remoto en Mac y Windows ahora admiten atajos de escritorio como Cmd-N, Cmd-B y Cmd-K; tus combinaciones personalizadas se guardan en ese equipo y el diseño de la página no cambia.\n- Se corrigió un problema por el que, en hosts más recientes, un equipo remoto no obtenía su token de inicio y se mostraba erróneamente como «temporalmente no disponible». Las conexiones son más estables.",
133
+ "fr": "- Les fenêtres de bureau distant sous Mac et Windows prennent désormais en charge les raccourcis bureau comme Cmd-N, Cmd-B et Cmd-K ; vos raccourcis personnalisés sont enregistrés sur l'ordinateur local et la mise en page reste inchangée.\n- Correction : avec les hôtes récents, un ordinateur distant n'obtenait pas son jeton de lancement et était signalé à tort comme « temporairement indisponible ». Les connexions sont plus stables.",
134
+ "pt": "- As janelas de área de trabalho remota no Mac e no Windows agora aceitam atalhos de desktop como Cmd-N, Cmd-B e Cmd-K; suas teclas personalizadas ficam salvas naquele computador e o layout da página não muda.\n- Corrigido um problema em que, em hosts mais recentes, um computador remoto não conseguia obter o token de inicialização e era exibido incorretamente como «temporariamente indisponível». As conexões ficaram mais estáveis.",
135
+ "ru": "- Окна удалённого рабочего стола на Mac и Windows теперь поддерживают системные сочетания клавиш, например Cmd-N, Cmd-B и Cmd-K; ваши настройки клавиш сохраняются на этом компьютере, а вёрстка страницы не меняется.\n- Исправлена проблема, когда на новых хостах удалённый компьютер не получал токен запуска и ошибочно отображался как «временно недоступный». Соединения стали стабильнее.",
136
+ "tr": "- Mac ve Windows'taki uzak masaüstü pencereleri artık Cmd-N, Cmd-B, Cmd-K gibi masaüstü kısayollarını destekliyor; değiştirdiğiniz tuş atamaları o bilgisayarda saklanıyor, sayfa düzeni değişmiyor.\n- Yeni host sürümlerinde uzak bilgisayarın başlangıç jetonunu alamayıp yanlışlıkla 'karşı taraf geçici olarak kullanılamıyor' diye görünmesi sorunu düzeltildi; bağlantılar artık daha kararlı."
137
137
  }
138
138
  }
139
139
  }