dsh-builtin-browser 0.4.15 → 0.5.1

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.en.md +17 -9
  3. package/README.md +48 -10
  4. package/client.js +410 -6
  5. package/desktop-bridge/install-and-start.cmd +36 -0
  6. package/desktop-bridge/install.mjs +166 -3
  7. package/desktop-bridge/plugin-browser-bridge.js +133 -11
  8. package/docs/development.md +19 -0
  9. package/docs/limitations.md +7 -3
  10. package/docs/user-guide.md +46 -18
  11. package/lib/browser/runtime.d.ts +21 -2
  12. package/lib/browser/runtime.js +30 -0
  13. package/lib/browser/types.d.ts +54 -0
  14. package/lib/browser-electron/bridge-status.d.ts +41 -0
  15. package/lib/browser-electron/bridge-status.js +164 -0
  16. package/lib/browser-electron/desktop-bridge-host.d.ts +15 -2
  17. package/lib/browser-electron/desktop-bridge-host.js +75 -44
  18. package/lib/browser-electron/entry.js +130 -11
  19. package/lib/browser-electron/file-write.d.ts +2 -0
  20. package/lib/browser-electron/file-write.js +39 -0
  21. package/lib/browser-electron/history-store.d.ts +8 -19
  22. package/lib/browser-electron/history-store.js +37 -58
  23. package/lib/browser-electron/host-main.js +15 -22
  24. package/lib/browser-electron/preview-route.d.ts +89 -0
  25. package/lib/browser-electron/preview-route.js +172 -0
  26. package/lib/browser-electron/provider.d.ts +62 -3
  27. package/lib/browser-electron/provider.js +246 -12
  28. package/lib/browser-electron/remote-host.js +5 -1
  29. package/lib/browser-electron/rpc-input.d.ts +4 -0
  30. package/lib/browser-electron/rpc-input.js +11 -0
  31. package/lib/browser-electron/runtime-diagnostics.d.ts +12 -0
  32. package/lib/browser-electron/runtime-diagnostics.js +29 -0
  33. package/lib/browser-electron/settings-store.d.ts +15 -2
  34. package/lib/browser-electron/settings-store.js +25 -5
  35. package/lib/browser-electron/system-browser.d.ts +18 -0
  36. package/lib/browser-electron/system-browser.js +116 -33
  37. package/lib/tool-browser/index.js +10 -1
  38. package/package.json +8 -3
  39. package/scripts/install-electron.mjs +66 -0
  40. package/scripts/verify-preview-route.mjs +150 -0
  41. package/src/browser/runtime.ts +36 -0
  42. package/src/browser/types.ts +55 -0
  43. package/src/browser-electron/bridge-status.ts +180 -0
  44. package/src/browser-electron/desktop-bridge-host.ts +75 -41
  45. package/src/browser-electron/entry.ts +119 -11
  46. package/src/browser-electron/file-write.ts +31 -0
  47. package/src/browser-electron/history-store.ts +36 -57
  48. package/src/browser-electron/host-main.ts +16 -18
  49. package/src/browser-electron/preview-route.ts +222 -0
  50. package/src/browser-electron/provider.ts +286 -16
  51. package/src/browser-electron/remote-host.ts +5 -1
  52. package/src/browser-electron/rpc-input.ts +13 -0
  53. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  54. package/src/browser-electron/settings-store.ts +37 -5
  55. package/src/browser-electron/system-browser.ts +108 -29
  56. package/src/tool-browser/index.ts +13 -1
package/client.js CHANGED
@@ -29,8 +29,21 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
29
29
 
30
30
  const zh = {
31
31
  nav: "浏览器",
32
+ "watch.open": "观看浏览器",
33
+ "watch.title": "实时画面",
34
+ "watch.readOnly": "只读,不转发点击与输入",
35
+ "watch.stop": "停止",
36
+ "watch.live": "直播",
37
+ "watch.paused": "已暂停",
38
+ "watch.stopped": "已停止",
39
+ "watch.connecting": "连接中",
40
+ "watch.disconnected": "连接中断",
41
+ "watch.disabled": "主机未开启远程观看",
42
+ "watch.noPage": "该任务尚未打开浏览器",
43
+ "watch.bridgeStale": "桌面端升级后 bridge 已失效,请重跑安装:",
44
+ "watch.bridgeMissing": "桌面 bridge 未安装,侧栏载体不可用。安装命令:",
32
45
  title: "浏览器(Browser Use)",
33
- lead: "这些开关控制共享浏览器如何工作;改动立即生效,不需要重启 DSH。",
46
+ lead: "多数设置立即生效。保留 cookies 与无头模式仅适用于本机 Chrome / Edge,修改后需重新选择载体或重启 DSH。",
34
47
  loading: "读取设置…",
35
48
  failed: "读取设置失败:",
36
49
  retry: "重试",
@@ -41,7 +54,7 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
41
54
  "history.hint": "记录访问过的页面;关闭浏览器后仍可查询并重新打开,关闭此开关后不再记录新访问。",
42
55
  "cookies.title": "登录状态",
43
56
  "cookies.persist": "保留 cookies",
44
- "cookies.hint": "关闭后每次启动浏览器都是未登录状态。",
57
+ "cookies.hint": "仅控制本机 Chrome / Edge 的独立 profile:关闭后下次启动使用临时 profile;需重新选择载体或重启 DSH。内置 Electron 与桌面侧栏的登录态由各自载体保存。",
45
58
  "ui.title": "展示",
46
59
  "ui.autoExpandOnce": "侧栏自动展开(每轮一次)",
47
60
  "ui.autoExpandOnce.hint": "Agent 首次操作时自动展开;你手动收起后,本轮不再打扰。",
@@ -77,8 +90,21 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
77
90
 
78
91
  const en = {
79
92
  nav: "Browser",
93
+ "watch.open": "Watch browser",
94
+ "watch.title": "Live view",
95
+ "watch.readOnly": "Read-only; clicks and typing are not forwarded",
96
+ "watch.stop": "Stop",
97
+ "watch.live": "Live",
98
+ "watch.paused": "Paused",
99
+ "watch.stopped": "Stopped",
100
+ "watch.connecting": "Connecting",
101
+ "watch.disconnected": "Disconnected",
102
+ "watch.disabled": "Remote viewing is off on the host",
103
+ "watch.noPage": "This task has not opened a browser",
104
+ "watch.bridgeStale": "A desktop update invalidated the bridge; re-run:",
105
+ "watch.bridgeMissing": "The desktop bridge is not installed, so the sidebar carrier cannot work:",
80
106
  title: "Browser (Browser Use)",
81
- lead: "These switches decide how the shared browser behaves; changes apply immediately, no DSH restart.",
107
+ lead: "Most settings apply immediately. Cookie persistence and headless mode apply only to installed Chrome / Edge; reselect the carrier or restart DSH after changing them.",
82
108
  loading: "Loading settings…",
83
109
  failed: "Could not load settings:",
84
110
  retry: "Retry",
@@ -89,7 +115,7 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
89
115
  "history.hint": "Records visited pages so they can be found and reopened after the browser is closed; off means no new visits are recorded.",
90
116
  "cookies.title": "Login state",
91
117
  "cookies.persist": "Keep cookies",
92
- "cookies.hint": "Off makes every browser start a signed-out session.",
118
+ "cookies.hint": "Controls only the separate Chrome / Edge profile: off uses a temporary profile on the next launch. Reselect the carrier or restart DSH. Bundled Electron and the desktop sidebar retain login state through their own carrier.",
93
119
  "ui.title": "Presentation",
94
120
  "ui.autoExpandOnce": "Auto-expand the side panel (once per task)",
95
121
  "ui.autoExpandOnce.hint": "Expands when the agent first operates; after you collapse it, this task stays quiet.",
@@ -228,6 +254,47 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
228
254
  background: var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,.18));
229
255
  }
230
256
  .dsh-bb-dd-opt[aria-selected="true"] { font-weight: 600; }
257
+
258
+ /* Live-view panel. Fixed layer rather than a slot: the host has no stable slot for an extra
259
+ surface over the conversation, and a layer works in every layout including a phone. */
260
+ .dsh-bw-watch { position: fixed; right: 16px; bottom: 16px; z-index: 2147483000; font-family: inherit; }
261
+ .dsh-bw-watch-open {
262
+ display: inline-flex; align-items: center; gap: 7px; cursor: pointer;
263
+ border: 1px solid var(--dsw-alias-border, rgba(128,128,128,.45)); border-radius: 999px;
264
+ padding: 7px 13px; font-size: 12px; color: inherit;
265
+ background: var(--dsw-alias-interactive-bg, rgba(128,128,128,.12));
266
+ }
267
+ .dsh-bw-watch-open:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,.2)); }
268
+ .dsh-bw-watch-dot { width: 7px; height: 7px; border-radius: 50%; background: #d9534f; }
269
+ .dsh-bw-watch-panel {
270
+ position: absolute; right: 0; bottom: 40px; width: min(560px, calc(100vw - 32px));
271
+ border: 1px solid var(--dsw-alias-border, rgba(128,128,128,.35)); border-radius: 10px;
272
+ background: var(--dsw-alias-bg-elevated, #1b1b1f); color: inherit; overflow: hidden;
273
+ box-shadow: 0 10px 30px rgba(0,0,0,.35);
274
+ }
275
+ .dsh-bw-watch-head { display: flex; align-items: center; gap: 8px; padding: 8px 10px; font-size: 12px; }
276
+ .dsh-bw-watch-title { font-weight: 600; }
277
+ .dsh-bw-watch-state { opacity: .7; margin-left: auto; }
278
+ .dsh-bw-watch-close {
279
+ border: 0; background: transparent; color: inherit; cursor: pointer;
280
+ font-size: 16px; line-height: 1; padding: 0 2px; opacity: .7;
281
+ }
282
+ .dsh-bw-watch-stage { background: #000; min-height: 120px; display: flex; align-items: center; justify-content: center; }
283
+ .dsh-bw-watch-img { display: block; max-width: 100%; height: auto; }
284
+ .dsh-bw-watch-note { margin: 0; padding: 24px 14px; font-size: 12px; opacity: .75; text-align: center; }
285
+ .dsh-bw-watch-foot {
286
+ display: flex; align-items: center; gap: 8px; padding: 7px 10px;
287
+ font-size: 11px; border-top: 1px solid var(--dsw-alias-border, rgba(128,128,128,.25));
288
+ }
289
+ .dsh-bw-watch-readonly { opacity: .6; }
290
+ .dsh-bw-watch-bridge { padding: 8px 10px; font-size: 11px; border-bottom: 1px solid var(--dsw-alias-border, rgba(128,128,128,.25)); background: rgba(217,83,79,.12); }
291
+ .dsh-bw-watch-bridge-line { line-height: 1.5; }
292
+ .dsh-bw-watch-bridge-cmd { display: block; margin-top: 5px; padding: 5px 7px; font-size: 11px; white-space: pre-wrap; word-break: break-all; background: rgba(0,0,0,.28); border-radius: 5px; }
293
+ .dsh-bw-watch-stop {
294
+ margin-left: auto; cursor: pointer; font-size: 11px; padding: 4px 10px;
295
+ border: 1px solid var(--dsw-alias-border, rgba(128,128,128,.45)); border-radius: 6px;
296
+ background: transparent; color: inherit;
297
+ }
231
298
  `
232
299
 
233
300
  /** Install the stylesheet once, however many times the panel is mounted. */
@@ -617,6 +684,13 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
617
684
  return null
618
685
  }
619
686
 
687
+ /** rc.5 marks both SessionView and its nested SidebarPanel, including floating panes. */
688
+ function panelRootsFor(sessionId) {
689
+ const roots = Array.from(document.querySelectorAll("[data-sidebar-right-session]"))
690
+ // Only shells without DOM ownership markers may use the legacy React adapter.
691
+ return roots.length === 0 ? undefined : roots.filter(root => root.getAttribute("data-sidebar-right-session") === sessionId)
692
+ }
693
+
620
694
  /**
621
695
  * Every live `<webview>` guest inside this conversation's panel subtree.
622
696
  *
@@ -631,6 +705,17 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
631
705
  * "is there one that is NOT mine", never a count.
632
706
  */
633
707
  function guestsInPanel(sessionId) {
708
+ const roots = panelRootsFor(sessionId)
709
+ if (roots !== undefined) {
710
+ // The nested markers can enumerate a guest twice. Its closest owner must still
711
+ // name this session, so an embedded foreign session never enters the result.
712
+ return Array.from(new Set(roots.flatMap(root => Array.from(root.querySelectorAll("webview"))))).filter(view => {
713
+ try {
714
+ return roots.includes(view.closest("[data-sidebar-right-session]"))
715
+ && typeof view.getWebContentsId === "function" && view.getWebContentsId() > 0
716
+ } catch { return false }
717
+ })
718
+ }
634
719
  const strip = tabStripFor(sessionId)
635
720
  if (strip === null) return []
636
721
  // Start at the strip itself: it is by construction this conversation's own, so the foreign test
@@ -653,8 +738,8 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
653
738
 
654
739
  /** Read this conversation's current guest, preferring the one actually drawn. */
655
740
  function guestStateFor(sessionId) {
656
- const strip = tabStripFor(sessionId)
657
- if (strip === null) return { panel: false, guestId: null, url: "" }
741
+ const roots = panelRootsFor(sessionId)
742
+ if (roots === undefined ? tabStripFor(sessionId) === null : roots.length === 0) return { panel: false, guestId: null, url: "" }
658
743
  const guests = guestsInPanel(sessionId)
659
744
  if (guests.length === 0) return { panel: true, guestId: null, url: "" }
660
745
  // A sidebar keeps every tab mounted (`keepMounted`), so a background tab's guest is
@@ -670,6 +755,33 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
670
755
  catch (error) { return { panel: true, guestId: null, url: "" } }
671
756
  }
672
757
 
758
+ /** Resolve a shell tab by its stable id, never by the page's displayed title. */
759
+ function tabIdOfElement(element, allowed, roots) {
760
+ if (roots !== undefined) {
761
+ const owner = element.closest("[data-sidebar-right-session]")
762
+ if (!roots.includes(owner)) return null
763
+ let id = null
764
+ for (let node = element; node && node !== owner; node = node.parentElement) {
765
+ for (const value of [node.getAttribute("data-sidebar-right-tab"), node.getAttribute("data-dockkit-tab")]) {
766
+ if (value === null) continue
767
+ if (id !== null && id !== value) return null
768
+ id = value
769
+ }
770
+ }
771
+ return allowed.has(id) ? id : null
772
+ }
773
+ const key = Object.keys(element).find(name => name.startsWith("__reactFiber$") || name.startsWith("__reactInternalInstance$"))
774
+ let fiber = key === undefined ? null : element[key]
775
+ for (let depth = 0; fiber && depth < 60; depth += 1, fiber = fiber.return) {
776
+ const props = fiber.memoizedProps
777
+ if (!props || typeof props !== "object") continue
778
+ for (const id of [props.tabId, props.tab && props.tab.id]) {
779
+ if (typeof id === "string" && allowed.has(id)) return id
780
+ }
781
+ }
782
+ return null
783
+ }
784
+
673
785
  /**
674
786
  * Publish the service every host-side panel request goes through.
675
787
  *
@@ -761,6 +873,44 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
761
873
  panelGuest(sessionId) {
762
874
  return guestStateFor(typeof sessionId === "string" ? sessionId : "")
763
875
  },
876
+ /** All guest ids verified inside this conversation, including shell-created popup tabs. */
877
+ panelGuests(sessionId) {
878
+ if (typeof sessionId !== "string" || !/^session-/.test(sessionId)) return []
879
+ return guestsInPanel(sessionId).map(view => view.getWebContentsId())
880
+ },
881
+ /** Close exactly the tab hosting this guest. An unknown shell shape must fail closed. */
882
+ closePanelGuest(sessionId, guestId) {
883
+ const refuse = reason => ({ ok: false, reason, closed: 0 })
884
+ if (typeof sessionId !== "string" || !/^session-/.test(sessionId)) return refuse("a conversation id is required")
885
+ const view = guestsInPanel(sessionId).find(candidate => candidate.getWebContentsId() === guestId)
886
+ if (view === undefined) return refuse("the guest does not belong to this conversation panel")
887
+ const roots = panelRootsFor(sessionId)
888
+ const containers = roots === undefined ? [tabStripFor(sessionId)].filter(Boolean) : roots
889
+ if (containers.length === 0 || sidebarRight === null || typeof sidebarRight.tabsIn !== "function") {
890
+ return refuse("the shell cannot identify its tabs; refresh or upgrade the browser plugin client")
891
+ }
892
+ let tabs
893
+ try { tabs = sidebarRight.tabsIn(sessionId) } catch { return refuse("the conversation tabs are unavailable") }
894
+ const allowed = new Set(tabs.map(tab => tab.id))
895
+ const id = tabIdOfElement(view, allowed, roots)
896
+ if (id === null) return refuse("the shell does not expose this guest's tab identity; refresh or upgrade the desktop")
897
+ // rc.5's scoped controller runs registered cleanup and removes the shell tab as one action.
898
+ if (typeof sidebarRight.closeIn === "function") {
899
+ try {
900
+ sidebarRight.closeIn(sessionId, id)
901
+ if (sidebarRight.tabsIn(sessionId).some(tab => tab.id === id)) return refuse("the shell did not remove the requested conversation tab")
902
+ return { ok: true, closed: 1 }
903
+ } catch (error) { return refuse("the shell could not close the conversation tab: " + String(error?.message ?? error)) }
904
+ }
905
+ const headers = Array.from(new Set(containers.flatMap(container => Array.from(container.querySelectorAll("[role=tab]")))))
906
+ .filter(tab => tabIdOfElement(tab, allowed, roots) === id)
907
+ if (headers.length !== 1) return refuse("the shell does not expose one matching tab control; refresh or upgrade the desktop")
908
+ const buttons = Array.from(headers[0].querySelectorAll("button"))
909
+ .filter(button => /关闭|close/i.test((button.getAttribute("aria-label") || "") + " " + (button.getAttribute("title") || "")))
910
+ if (buttons.length !== 1) return refuse("the shell does not expose one matching close control; refresh or upgrade the desktop")
911
+ buttons[0].click()
912
+ return { ok: true, closed: 1 }
913
+ },
764
914
  }
765
915
  ctx.effect(() => {
766
916
  globalThis.__dshBuiltinBrowser = api
@@ -770,11 +920,265 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
770
920
  }, "dsh-builtin-browser: conversation panel service")
771
921
  }
772
922
 
923
+ /**
924
+ * The live-view panel: one frame at a time, for an operator who is not sitting at this machine.
925
+ *
926
+ * A plain floating layer rather than a slot registration, deliberately. The host's layout has no
927
+ * stable slot for "an extra surface over the conversation", and inventing one would tie this
928
+ * panel to a layout that changes; a fixed layer works in every layout including a phone. It is
929
+ * also entirely inert until the host turns `remoteView.enabled` on, which the sessions probe
930
+ * reports.
931
+ *
932
+ * Pulls one frame per request and waits for it to paint before asking for the next, so a slow
933
+ * link shows fewer frames instead of queueing them. Nothing here retries in a tight loop: a
934
+ * refusal or a 503 moves the panel to a paused state, and it resumes on the next user action.
935
+ * @param ctx - the plugin context, for the disposal hook.
936
+ */
937
+ function installWatchPanel(ctx) {
938
+ if (typeof document === "undefined") return
939
+ const SESSIONS = "/dsh-builtin-browser/browser-view/sessions"
940
+ const FRAME = "/dsh-builtin-browser/browser-view/frame"
941
+ const MIN_INTERVAL_MS = 500
942
+
943
+ // Built element by element and referenced directly, never through innerHTML + querySelector.
944
+ // Two reasons: the host's test sandbox provides a minimal `createElement`, and re-parsing markup
945
+ // to find elements this code just made is work without a purpose.
946
+ const make = (tag, className, text) => {
947
+ const node = document.createElement(tag)
948
+ if (className !== undefined) node.className = className
949
+ if (text !== undefined) node.textContent = text
950
+ return node
951
+ }
952
+
953
+ const layer = make("div", "dsh-bw-watch")
954
+ layer.setAttribute("data-dsh-bw-watch", "")
955
+
956
+ const openButton = make("button", "dsh-bw-watch-open")
957
+ openButton.setAttribute("type", "button")
958
+ const dot = make("span", "dsh-bw-watch-dot")
959
+ const openLabel = make("span", "dsh-bw-watch-label")
960
+ openButton.appendChild(dot)
961
+ openButton.appendChild(openLabel)
962
+
963
+ const panel = make("section", "dsh-bw-watch-panel")
964
+ panel.hidden = true
965
+
966
+ const head = make("header", "dsh-bw-watch-head")
967
+ const title = make("span", "dsh-bw-watch-title")
968
+ const state = make("span", "dsh-bw-watch-state")
969
+ const closeButton = make("button", "dsh-bw-watch-close", "×")
970
+ closeButton.setAttribute("type", "button")
971
+ head.appendChild(title)
972
+ head.appendChild(state)
973
+ head.appendChild(closeButton)
974
+
975
+ const stage = make("div", "dsh-bw-watch-stage")
976
+ const img = make("img", "dsh-bw-watch-img")
977
+ img.hidden = true
978
+ const note = make("p", "dsh-bw-watch-note")
979
+ stage.appendChild(img)
980
+ stage.appendChild(note)
981
+
982
+ const foot = make("footer", "dsh-bw-watch-foot")
983
+ const readonlyLabel = make("span", "dsh-bw-watch-readonly")
984
+ const stopButton = make("button", "dsh-bw-watch-stop")
985
+ stopButton.setAttribute("type", "button")
986
+ foot.appendChild(readonlyLabel)
987
+ foot.appendChild(stopButton)
988
+
989
+ panel.appendChild(head)
990
+ panel.appendChild(stage)
991
+ panel.appendChild(foot)
992
+ layer.appendChild(openButton)
993
+ layer.appendChild(panel)
994
+ document.body.appendChild(layer)
995
+
996
+ /** Localized text, falling back to the key so a missing entry is visible rather than blank. */
997
+ const say = key => {
998
+ try { return translate(key) } catch { return key }
999
+ }
1000
+ openLabel.textContent = say("watch.open")
1001
+ title.textContent = say("watch.title")
1002
+ readonlyLabel.textContent = say("watch.readOnly")
1003
+ stopButton.textContent = say("watch.stop")
1004
+ openButton.title = say("watch.open")
1005
+
1006
+ /** One running view: a session, its frames, and whether it should keep pulling. */
1007
+ const view = { session: undefined, timer: undefined, running: false, lastAt: 0, objectUrl: undefined }
1008
+
1009
+ const setState = text => { state.textContent = text }
1010
+ const showNote = text => {
1011
+ note.textContent = text
1012
+ note.hidden = false
1013
+ img.hidden = true
1014
+ }
1015
+ /** Release the previous frame. A viewer that keeps every frame is a memory leak in a phone browser. */
1016
+ const dropFrame = () => {
1017
+ if (view.objectUrl !== undefined) {
1018
+ URL.revokeObjectURL(view.objectUrl)
1019
+ view.objectUrl = undefined
1020
+ }
1021
+ }
1022
+ const stop = () => {
1023
+ view.running = false
1024
+ if (view.timer !== undefined) { clearTimeout(view.timer); view.timer = undefined }
1025
+ dropFrame()
1026
+ img.removeAttribute("src")
1027
+ img.hidden = true
1028
+ setState(say("watch.stopped"))
1029
+ showNote(say("watch.stopped"))
1030
+ panel.hidden = true
1031
+ }
1032
+
1033
+ /** Ask which sessions exist; returns whether watching is enabled at all. */
1034
+ const probe = async () => {
1035
+ try {
1036
+ const response = await fetch(SESSIONS, { headers: { accept: "application/json" } })
1037
+ if (!response.ok) return { enabled: false, sessions: [] }
1038
+ const data = await response.json()
1039
+ return { enabled: data?.enabled === true, sessions: Array.isArray(data?.sessions) ? data.sessions : [] }
1040
+ } catch {
1041
+ return { enabled: false, sessions: [] }
1042
+ }
1043
+ }
1044
+
1045
+ /**
1046
+ * Pull frames until stopped. One request in flight at a time, and the next one is scheduled only
1047
+ * after the current image has painted — that is what makes a slow link degrade into fewer
1048
+ * frames rather than a growing queue.
1049
+ */
1050
+ const pump = async () => {
1051
+ if (!view.running) return
1052
+ if (document.visibilityState === "hidden") {
1053
+ // The design's rule: a hidden panel stops pulling immediately. Resuming is the user's
1054
+ // action, not a timer's.
1055
+ setState(say("watch.paused"))
1056
+ showNote(say("watch.paused"))
1057
+ view.timer = setTimeout(pump, MIN_INTERVAL_MS * 4)
1058
+ return
1059
+ }
1060
+ const waited = Date.now() - view.lastAt
1061
+ if (waited < MIN_INTERVAL_MS) {
1062
+ view.timer = setTimeout(pump, MIN_INTERVAL_MS - waited)
1063
+ return
1064
+ }
1065
+ view.lastAt = Date.now()
1066
+ let nextDelay = MIN_INTERVAL_MS
1067
+ try {
1068
+ const url = `${FRAME}?session=${encodeURIComponent(String(view.session))}`
1069
+ const response = await fetch(url, { headers: { accept: "image/jpeg" } })
1070
+ if (!view.running) return
1071
+ if (!response.ok) {
1072
+ const body = await response.json().catch(() => undefined)
1073
+ setState(say("watch.paused"))
1074
+ showNote(body?.error === "remote-view-disabled"
1075
+ ? say("watch.disabled")
1076
+ : body?.error === "no-such-session"
1077
+ ? say("watch.noPage")
1078
+ : say("watch.paused"))
1079
+ // Slower polling while paused: a paused view must not turn into a hot loop.
1080
+ nextDelay = MIN_INTERVAL_MS * 4
1081
+ } else {
1082
+ const blob = await response.blob()
1083
+ if (!view.running) return
1084
+ const painted = new Promise(resolve => {
1085
+ img.onload = () => resolve()
1086
+ img.onerror = () => resolve()
1087
+ })
1088
+ dropFrame()
1089
+ view.objectUrl = URL.createObjectURL(blob)
1090
+ img.src = view.objectUrl
1091
+ img.hidden = false
1092
+ note.hidden = true
1093
+ await painted
1094
+ if (!view.running) return
1095
+ setState(say("watch.live"))
1096
+ }
1097
+ } catch {
1098
+ if (!view.running) return
1099
+ setState(say("watch.disconnected"))
1100
+ showNote(say("watch.disconnected"))
1101
+ nextDelay = MIN_INTERVAL_MS * 4
1102
+ }
1103
+ if (view.running) view.timer = setTimeout(pump, nextDelay)
1104
+ }
1105
+
1106
+ const start = async session => {
1107
+ view.session = session
1108
+ view.running = true
1109
+ view.lastAt = 0
1110
+ panel.hidden = false
1111
+ setState(say("watch.connecting"))
1112
+ showNote(say("watch.connecting"))
1113
+ await pump()
1114
+ }
1115
+
1116
+ openButton.addEventListener("click", () => {
1117
+ void (async () => {
1118
+ const found = await probe()
1119
+ if (!found.enabled) { showNote(say("watch.disabled")); panel.hidden = false; return }
1120
+ if (found.sessions.length === 0) { showNote(say("watch.noPage")); panel.hidden = false; return }
1121
+ await start(found.sessions[0])
1122
+ })()
1123
+ })
1124
+ closeButton.addEventListener("click", stop)
1125
+ stopButton.addEventListener("click", stop)
1126
+ // A panel hidden by a closed button must not keep pulling frames.
1127
+ document.addEventListener("visibilitychange", () => {
1128
+ if (document.visibilityState === "hidden" && view.running) {
1129
+ if (view.timer !== undefined) { clearTimeout(view.timer); view.timer = undefined }
1130
+ view.timer = setTimeout(pump, MIN_INTERVAL_MS)
1131
+ }
1132
+ })
1133
+
1134
+ ctx.effect(() => () => {
1135
+ stop()
1136
+ layer.remove()
1137
+ }, "dsh-builtin-browser: live view panel")
1138
+
1139
+ /**
1140
+ * Report the desktop bridge's install state next to the entry button.
1141
+ *
1142
+ * A missing bridge used to be a log line and nothing else, so a user on `channel: sidebar` saw
1143
+ * "another window opened again" with no way to connect that to the actual cause (issue #36).
1144
+ * The reading comes from the install tree, so it is true even before anything has been watched.
1145
+ *
1146
+ * The repair command is shown, never run: a page that could decide to close the desktop shell
1147
+ * would be a worse problem than the one this line solves.
1148
+ */
1149
+ const showBridgeStatus = async () => {
1150
+ let status
1151
+ try {
1152
+ const response = await fetch("/dsh-builtin-browser/bridge-status", { headers: { accept: "application/json" } })
1153
+ if (!response.ok) return
1154
+ const data = await response.json()
1155
+ status = data?.bridge
1156
+ } catch {
1157
+ return
1158
+ }
1159
+ if (status === undefined) return
1160
+ // Only the two states a user can act on: an installed bridge needs no notice, and a host
1161
+ // without a desktop install has nothing to repair here.
1162
+ if (status.state === "installed" || status.present !== true) return
1163
+ const notice = make("div", "dsh-bw-watch-bridge")
1164
+ const line = make("div", "dsh-bw-watch-bridge-line",
1165
+ status.state === "stale" ? say("watch.bridgeStale") : say("watch.bridgeMissing"))
1166
+ notice.appendChild(line)
1167
+ if (typeof status.command === "string" && status.command !== "") {
1168
+ const code = make("code", "dsh-bw-watch-bridge-cmd", status.command)
1169
+ notice.appendChild(code)
1170
+ }
1171
+ panel.insertBefore(notice, panel.firstChild)
1172
+ }
1173
+ void showBridgeStatus()
1174
+ }
1175
+
773
1176
  function apply(ctx) {
774
1177
  // Before anything renders: the rows need a hover state, and inline styles cannot express
775
1178
  // one. Idempotent, so a re-apply does not stack copies.
776
1179
  installStyles()
777
1180
  installPanelService(ctx)
1181
+ installWatchPanel(ctx)
778
1182
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), "dsh-builtin-browser: dictionaries")
779
1183
  const t = ctx.locale.bind(NS)
780
1184
  translate = t
@@ -0,0 +1,36 @@
1
+ @echo off
2
+ REM Install (or repair) the desktop bridge and restart DSH Desktop, in one step.
3
+ REM
4
+ REM Reported as issue #36: installing by hand meant closing DSH first, because the archive cannot be
5
+ REM moved while the shell holds it, and every "wait for the exit" arrangement lost its waiter. This
6
+ REM runs the installer with --restart, which closes the shell itself, installs, and starts it again.
7
+ REM
8
+ REM No arguments needed: the installer probes for the install directory. Pass one to override it.
9
+ REM install-and-start.cmd "C:\path\to\DSH Desktop"
10
+ REM install-and-start.cmd "C:\path\to\DSH Desktop" --yes
11
+ REM
12
+ REM --yes skips the confirmation prompt; without it the installer asks before closing DSH.
13
+
14
+ setlocal
15
+ set "HERE=%~dp0"
16
+
17
+ where node >nul 2>nul
18
+ if errorlevel 1 (
19
+ echo node was not found on PATH. Install Node.js 22 or later, then run this again.
20
+ exit /b 1
21
+ )
22
+
23
+ if "%~1"=="" (
24
+ node "%HERE%install.mjs" --restart
25
+ ) else if "%~2"=="" (
26
+ node "%HERE%install.mjs" "%~1" --restart
27
+ ) else (
28
+ node "%HERE%install.mjs" "%~1" %2 --restart
29
+ )
30
+
31
+ set "CODE=%ERRORLEVEL%"
32
+ if not "%CODE%"=="0" (
33
+ echo.
34
+ echo The installer exited with code %CODE%. Nothing was changed if the message above says so.
35
+ )
36
+ endlocal & exit /b %CODE%