dsh-builtin-browser 0.5.1 → 0.5.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/README.en.md +68 -67
  3. package/README.md +63 -91
  4. package/client.js +235 -11
  5. package/desktop-bridge/desktop-identity.json +9 -0
  6. package/desktop-bridge/install.mjs +220 -1
  7. package/docs/README.md +1 -1
  8. package/docs/architecture.md +1 -1
  9. package/docs/limitations.md +19 -1
  10. package/docs/tool-reference.md +2 -1
  11. package/lib/browser/runtime.d.ts +4 -2
  12. package/lib/browser/runtime.js +4 -0
  13. package/lib/browser/types.d.ts +37 -0
  14. package/lib/browser-electron/bridge-status.d.ts +5 -3
  15. package/lib/browser-electron/bridge-status.js +25 -8
  16. package/lib/browser-electron/desktop-bridge-host.d.ts +5 -3
  17. package/lib/browser-electron/desktop-bridge-host.js +47 -13
  18. package/lib/browser-electron/desktop-identity.d.ts +58 -0
  19. package/lib/browser-electron/desktop-identity.js +236 -0
  20. package/lib/browser-electron/electron-provision.d.ts +59 -0
  21. package/lib/browser-electron/electron-provision.js +164 -0
  22. package/lib/browser-electron/entry.js +61 -2
  23. package/lib/browser-electron/host-main.js +68 -14
  24. package/lib/browser-electron/provider.d.ts +51 -3
  25. package/lib/browser-electron/provider.js +77 -4
  26. package/lib/browser-electron/remote-host.d.ts +3 -3
  27. package/lib/browser-electron/remote-host.js +25 -11
  28. package/lib/browser-electron/settings-store.d.ts +19 -0
  29. package/lib/browser-electron/settings-store.js +5 -1
  30. package/lib/tool-browser/index.js +49 -0
  31. package/package.json +2 -3
  32. package/src/browser/runtime.ts +8 -0
  33. package/src/browser/types.ts +36 -0
  34. package/src/browser-electron/bridge-status.ts +28 -9
  35. package/src/browser-electron/desktop-bridge-host.ts +49 -13
  36. package/src/browser-electron/desktop-identity.ts +260 -0
  37. package/src/browser-electron/electron-provision.ts +195 -0
  38. package/src/browser-electron/entry.ts +49 -2
  39. package/src/browser-electron/host-main.ts +62 -12
  40. package/src/browser-electron/provider.ts +118 -6
  41. package/src/browser-electron/remote-host.ts +26 -12
  42. package/src/browser-electron/settings-store.ts +24 -1
  43. package/src/tool-browser/index.ts +49 -0
  44. package/src/types/electron-shim.d.ts +8 -0
package/client.js CHANGED
@@ -62,6 +62,8 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
62
62
  "ui.closeWithSession.hint": "关闭会释放浏览器进程;浏览历史与登录状态会保留。",
63
63
  "ui.virtualCursor": "显示可视化鼠标",
64
64
  "ui.virtualCursor.hint": "让 Agent 正在操作的位置可见(出现即代表它在接管该标签页)。",
65
+ "ui.quiet": "安静模式",
66
+ "ui.quiet.hint": "Agent 操作时不激活应用、不抢键盘焦点;导航与截图不还原最小化的窗口。真实点击/输入仍需要窗口可见,可能把最小化的窗口恢复,但不会成为前台窗口,也不会盖住你正在用的窗口。",
65
67
  "vision.title": "视觉策略",
66
68
  "vision.strategy": "默认策略",
67
69
  "vision.auto": "Auto(坐标与语义都允许;适合能读图的模型)",
@@ -123,6 +125,8 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
123
125
  "ui.closeWithSession.hint": "Closing releases the browser process; history and login state survive.",
124
126
  "ui.virtualCursor": "Show the synthetic cursor",
125
127
  "ui.virtualCursor.hint": "Makes the agent's operating position visible (its presence means the agent has taken over that tab).",
128
+ "ui.quiet": "Quiet mode",
129
+ "ui.quiet.hint": "The agent does not activate the app or steal keyboard focus; navigation and screenshots leave a minimized window minimized. Real clicks and typing still need a visible window, so they may restore it — but never raise it above your work or make it the front window.",
126
130
  "vision.title": "Vision strategy",
127
131
  "vision.strategy": "Default strategy",
128
132
  "vision.auto": "Auto (coordinates and semantics both allowed; for models that read images)",
@@ -269,7 +273,11 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
269
273
  .dsh-bw-watch-panel {
270
274
  position: absolute; right: 0; bottom: 40px; width: min(560px, calc(100vw - 32px));
271
275
  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;
276
+ /* --dsw-alias-bg-elevated does not exist in the theme this ships against (measured on rc.5: 0
277
+ * occurrences, while --dsw-alias-bg-layer-2 has 5). With a token that is never defined, the
278
+ * fallback is what everyone sees — a dark card in a light theme. bg-layer-2 is the token the
279
+ * host's own elevated rows use. */
280
+ background: var(--dsw-alias-bg-layer-2, #1b1b1f); color: inherit; overflow: hidden;
273
281
  box-shadow: 0 10px 30px rgba(0,0,0,.35);
274
282
  }
275
283
  .dsh-bw-watch-head { display: flex; align-items: center; gap: 8px; padding: 8px 10px; font-size: 12px; }
@@ -536,6 +544,14 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
536
544
  busy,
537
545
  onChange: value => patch({ ui: { virtualCursor: value } }),
538
546
  }),
547
+ h(Toggle, {
548
+ key: "quiet",
549
+ labelKey: "ui.quiet",
550
+ hintKey: "ui.quiet.hint",
551
+ checked: settings.ui.quiet,
552
+ busy,
553
+ onChange: value => patch({ ui: { quiet: value } }),
554
+ }),
539
555
  ]),
540
556
 
541
557
  section("vision.title", [
@@ -792,6 +808,8 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
792
808
  */
793
809
  function installPanelService(ctx) {
794
810
  let sidebarRight = null
811
+ /** The shell's own navigation service: `openSession` is how it is asked to DISPLAY a conversation. */
812
+ let uiWorkspace = null
795
813
  // `inject` is how a client plugin waits for a service to appear. A host that does not offer it
796
814
  // — an older composition, or a harness that mounted this bundle for its settings panel alone —
797
815
  // must still get the panel, so the wait is skipped and the published API names the missing
@@ -804,7 +822,140 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
804
822
  if (sidebarRight === scope.sidebarRight) sidebarRight = null
805
823
  }, "dsh-builtin-browser: conversation panel binding")
806
824
  })
825
+ // A separate inject, deliberately: waiting for both services in one call would take the
826
+ // panel down on a host that has the sidebar but not the workspace service (an older
827
+ // composition), and the panel is the part that must keep working.
828
+ ctx.inject(["uiWorkspace"], (scope) => {
829
+ uiWorkspace = scope.uiWorkspace
830
+ scope.effect(() => () => {
831
+ if (uiWorkspace === scope.uiWorkspace) uiWorkspace = null
832
+ }, "dsh-builtin-browser: workspace binding")
833
+ })
834
+ }
835
+ /**
836
+ * Ask the shell to DISPLAY the conversation a page was requested for.
837
+ *
838
+ * The shell renders the sidebar of the conversation it shows and no other, so a request from a
839
+ * background conversation can place a tab but never grow a webview. The old answer was "show
840
+ * that conversation and the page appears" — true, and a dependency on the human's timing.
841
+ * `openSession` is the shell's own navigation for exactly this: the same call its own session
842
+ * list makes, aimed at a session id, with no input event and no DOM touched.
843
+ *
844
+ * Only called when this conversation's panel DOM is absent, so it never fires for the
845
+ * conversation the human is already reading, and never as a side effect of a read.
846
+ *
847
+ * @param sessionId - the conversation the page belongs to.
848
+ * @param state - the panel read taken just before; `panel: true` means nothing to claim.
849
+ * @returns whether the shell was asked to switch.
850
+ */
851
+ /**
852
+ * The conversation the shell is displaying, as the shell itself reports it.
853
+ *
854
+ * `undefined`/`null` means "the shell would not say" — an older shell, or one whose surface was
855
+ * never minted. Both callers treat that as "not this conversation", which is the fail-safe
856
+ * direction: no navigation, no expand, nothing that could move a view it cannot identify.
857
+ * @returns the on-screen session id, or null.
858
+ */
859
+ function onScreenSession() {
860
+ try {
861
+ const screen = sidebarRight === null || typeof sidebarRight.screen !== "function" ? undefined : sidebarRight.screen()
862
+ return screen !== undefined && screen !== null && typeof screen.sessionId === "string" ? screen.sessionId : null
863
+ } catch (error) {
864
+ return null
865
+ }
866
+ }
867
+
868
+ function claimConversation(sessionId, state) {
869
+ if (state.panel === true) return false
870
+ if (uiWorkspace === null || typeof uiWorkspace.openSession !== "function") return false
871
+ // Already displayed? Then the shell needs no navigation: the panel simply has not been opened
872
+ // yet, and `revealPlacedPanel` opens it. Re-opening the conversation a human is reading would
873
+ // be a no-op at best and a view reset at worst.
874
+ if (onScreenSession() === sessionId) return false
875
+ try {
876
+ uiWorkspace.openSession(sessionId)
877
+ return true
878
+ } catch (error) {
879
+ return false
880
+ }
807
881
  }
882
+
883
+ /**
884
+ * Make a page that has been PLACED actually appear: expand the column, focus its tab.
885
+ *
886
+ * A placed tab is not a shown page. The shell renders the body of the ACTIVE tab, and only
887
+ * while the column is expanded. A collapsed column keeps the strip — so the read side still
888
+ * reports `panel: true` — while no `<webview>` is ever created, and every guest read comes
889
+ * back empty. That is the state that used to sit here for 20 s and then get reported as an
890
+ * unusable panel: measured on the running shell as `panel: true`, `guestId: null` in the
891
+ * renderer and `sidebar: []` from the bridge, with no carrier-side step that could have
892
+ * fixed it, because nobody had ever asked the column to open.
893
+ *
894
+ * Both calls are layout commands on a conversation's own surface store — no input event, no
895
+ * key dispatch, no element click. Two guards keep them from touching a conversation the
896
+ * human is not reading:
897
+ * - only when `screen()` names THIS conversation. `screen()` is the shell's own answer to
898
+ * "which conversation is displayed", and `toggleExpanded` acts on exactly that one, so
899
+ * without this check an expand could fold the column a human is reading. A conversation
900
+ * that is displayed but was never opened (a fresh window has no right sidebar at all until
901
+ * something asks for it) passes this check — that case is why the DOM alone is not enough;
902
+ * - `focus` is scoped by the shell itself (a tab outside the mounted surface is ignored),
903
+ * so passing it a tab id from another conversation's list cannot move that view.
904
+ *
905
+ * @param sessionId - the conversation whose page was just placed.
906
+ * @param state - what the panel read before the placement; a live guest means nothing to do.
907
+ * @returns what was asked for, so a caller can tell "expanded" from "already visible", and
908
+ * `displayed` so it can tell "the shell is showing this conversation" from "it is not".
909
+ */
910
+ function revealPlacedPanel(sessionId, state) {
911
+ if (state.guestId !== null || sidebarRight === null) return {}
912
+ const done = {}
913
+ // Which conversation is the shell DISPLAYING? `screen()` answers it, and it is the question
914
+ // that decides whether an expand call is safe: `toggleExpanded()` acts on the on-screen
915
+ // session, so calling it for any other conversation would fold the column a human is reading.
916
+ //
917
+ // It also separates two states that the DOM alone cannot:
918
+ // - this conversation is displayed but its column has never been opened (a fresh window
919
+ // starts with no right sidebar at all) — expand, and the panel mounts;
920
+ // - another conversation is displayed — nothing here may touch the column; the claim step
921
+ // is what moves the shell, and the caller retries one render later.
922
+ let onScreen = null
923
+ try {
924
+ onScreen = onScreenSession()
925
+ } catch (error) {
926
+ onScreen = null
927
+ }
928
+ if (onScreen !== sessionId) {
929
+ done.displayed = false
930
+ return done
931
+ }
932
+ done.displayed = true
933
+ try {
934
+ if (typeof sidebarRight.isExpanded === "function" && typeof sidebarRight.toggleExpanded === "function") {
935
+ // `isExpanded()` is false both for "folded" and for "never opened". Both want the same
936
+ // thing here, and `screen()` above has already established that the column being toggled
937
+ // is THIS conversation's, so expanding cannot touch anybody else's.
938
+ if (sidebarRight.isExpanded() === false) {
939
+ sidebarRight.toggleExpanded()
940
+ done.expanded = true
941
+ }
942
+ }
943
+ } catch (error) {
944
+ done.expandError = String(error?.message ?? error)
945
+ }
946
+ try {
947
+ const tabs = typeof sidebarRight.tabsIn === "function" ? sidebarRight.tabsIn(sessionId) : []
948
+ const page = Array.isArray(tabs) ? tabs.find(entry => entry !== null && typeof entry === "object" && entry.kind === "browser") : undefined
949
+ if (page !== undefined && typeof sidebarRight.focus === "function") {
950
+ sidebarRight.focus(page.id)
951
+ done.focused = String(page.id)
952
+ }
953
+ } catch (error) {
954
+ done.focusError = String(error?.message ?? error)
955
+ }
956
+ return done
957
+ }
958
+
808
959
  const api = {
809
960
  /** @returns what happened: an existing guest, a newly opened tab, or a named refusal. */
810
961
  openPanel(sessionId, url) {
@@ -819,6 +970,13 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
819
970
  if (state.guestId !== null) {
820
971
  return { ok: true, created: false, panel: true, guestId: state.guestId, url: state.url }
821
972
  }
973
+ // No panel DOM for this conversation means the shell is not DISPLAYING it, and no tab placed
974
+ // here can ever grow a webview: the shell renders one sidebar, for the conversation it shows.
975
+ // Asking the human to click over was the old answer, and it made a working carrier depend on
976
+ // their timing. Ask the shell instead — `openSession` is its own navigation, one call on its
977
+ // own workspace service, no input events — and report `switched` so the caller can retry one
978
+ // render later instead of reporting a dead carrier.
979
+ const switched = claimConversation(wanted, state)
822
980
  // A mounted panel is NOT required to place a tab.
823
981
  //
824
982
  // `openTabIn` acts on the conversation's own surface store, and the sidebar-right service
@@ -859,6 +1017,7 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
859
1017
  reason: "this conversation's sidebar is not mounted, so a panel cannot be opened in it",
860
1018
  panel: state.panel,
861
1019
  guestId: null,
1020
+ ...switched ? { switched: true } : {},
862
1021
  found: {
863
1022
  wanted: wanted,
864
1023
  strips: strips.length,
@@ -867,7 +1026,19 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
867
1026
  },
868
1027
  }
869
1028
  }
870
- return { ok: true, created: placed > before, panel: state.panel, guestId: null, tabs: placed }
1029
+ // Placing is not showing: ask the shell to expand the column and focus that tab, so the
1030
+ // body (and with it the `<webview>`) actually gets created. Without this the caller polls
1031
+ // a panel that can never answer, which is exactly what "produced no page" used to mean.
1032
+ const revealed = revealPlacedPanel(wanted, state)
1033
+ return {
1034
+ ok: true,
1035
+ created: placed > before,
1036
+ panel: state.panel,
1037
+ guestId: null,
1038
+ tabs: placed,
1039
+ ...switched ? { switched: true } : {},
1040
+ ...revealed,
1041
+ }
871
1042
  },
872
1043
  /** Read-only: this conversation's current guest, if it has one. */
873
1044
  panelGuest(sessionId) {
@@ -991,17 +1162,46 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
991
1162
  panel.appendChild(foot)
992
1163
  layer.appendChild(openButton)
993
1164
  layer.appendChild(panel)
994
- document.body.appendChild(layer)
1165
+ // Deliberately NOT appended here. The entry is mounted only when the host reports that watching
1166
+ // is on — reported as issue #40: with the feature off, the button still sat on every page and
1167
+ // the bridge-status request fired at startup, so a setting nobody turned on produced a permanent
1168
+ // control and a permanent diagnostic call.
995
1169
 
996
1170
  /** Localized text, falling back to the key so a missing entry is visible rather than blank. */
997
1171
  const say = key => {
998
1172
  try { return translate(key) } catch { return key }
999
1173
  }
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")
1174
+
1175
+ /**
1176
+ * Apply the current locale to every static label.
1177
+ *
1178
+ * Called at mount and again once the dictionaries are bound. The panel used to set these exactly
1179
+ * once, inside `apply()`, *before* `locale.register` had run — so the shipped build showed
1180
+ * `watch.title` as its title and the key was never replaced (issue #40).
1181
+ */
1182
+ const relabel = () => {
1183
+ openLabel.textContent = say("watch.open")
1184
+ title.textContent = say("watch.title")
1185
+ readonlyLabel.textContent = say("watch.readOnly")
1186
+ stopButton.textContent = say("watch.stop")
1187
+ openButton.title = say("watch.open")
1188
+ }
1189
+ relabel()
1190
+
1191
+ let mounted = false
1192
+ /** Put the entry on the page. Idempotent, so a second enable cannot stack copies. */
1193
+ const mount = () => {
1194
+ if (mounted) return
1195
+ mounted = true
1196
+ document.body.appendChild(layer)
1197
+ relabel()
1198
+ }
1199
+ /** Take it off again — the host turned the feature off after it had been on. */
1200
+ const unmount = () => {
1201
+ if (!mounted) return
1202
+ mounted = false
1203
+ layer.remove()
1204
+ }
1005
1205
 
1006
1206
  /** One running view: a session, its frames, and whether it should keep pulling. */
1007
1207
  const view = { session: undefined, timer: undefined, running: false, lastAt: 0, objectUrl: undefined }
@@ -1133,7 +1333,7 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
1133
1333
 
1134
1334
  ctx.effect(() => () => {
1135
1335
  stop()
1136
- layer.remove()
1336
+ unmount()
1137
1337
  }, "dsh-builtin-browser: live view panel")
1138
1338
 
1139
1339
  /**
@@ -1170,7 +1370,27 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
1170
1370
  }
1171
1371
  panel.insertBefore(notice, panel.firstChild)
1172
1372
  }
1173
- void showBridgeStatus()
1373
+
1374
+ /**
1375
+ * Mount the entry only if the host says viewing is enabled, and only then ask about the bridge.
1376
+ *
1377
+ * Both halves are the point of the ordering: the probe answers "is this feature on", and the
1378
+ * bridge-status request is a diagnostic for a feature that is on. Issuing it for a feature that
1379
+ * is off is what the review called a default entry manufacturing a call (issue #40).
1380
+ *
1381
+ * A host that does not serve the sessions endpoint answers `enabled: false`, so the fallback is
1382
+ * "no entry" rather than "an entry that cannot work".
1383
+ */
1384
+ const mountIfEnabled = async () => {
1385
+ const found = await probe()
1386
+ if (!found.enabled) {
1387
+ unmount()
1388
+ return
1389
+ }
1390
+ mount()
1391
+ await showBridgeStatus()
1392
+ }
1393
+ void mountIfEnabled()
1174
1394
  }
1175
1395
 
1176
1396
  function apply(ctx) {
@@ -1178,10 +1398,14 @@ window.__ModuleLoader__.load({ id: "dsh-builtin-browser", factory: (require) =>
1178
1398
  // one. Idempotent, so a re-apply does not stack copies.
1179
1399
  installStyles()
1180
1400
  installPanelService(ctx)
1181
- installWatchPanel(ctx)
1401
+ // Dictionaries and the bound `t` come BEFORE anything that sets text from them. The watch panel
1402
+ // used to be installed first, so its static labels were written while `translate` still returned
1403
+ // the key and were never rewritten — the panel shipped with `watch.title` as its title
1404
+ // (issue #40).
1182
1405
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), "dsh-builtin-browser: dictionaries")
1183
1406
  const t = ctx.locale.bind(NS)
1184
1407
  translate = t
1408
+ installWatchPanel(ctx)
1185
1409
  ctx.slots.inject("settings.section", () => ctx.slots.register({
1186
1410
  name: "settings.section",
1187
1411
  id: "dsh-builtin-browser",
@@ -0,0 +1,9 @@
1
+ {
2
+ "_comment": "What proves a directory is DSH Desktop, in one place: the installer (desktop-bridge/install.mjs) and the plugin's status reader (src/browser-electron/bridge-status.ts) both read this file, and a test asserts neither hard-codes a second copy. A generic Electron layout — resources/app/lib/main.js or resources/app.asar — is NOT proof: any Electron app has that shape.",
3
+ "packageNames": [
4
+ "@deepseek-ai/dsh-desktop",
5
+ "dsh-desktop"
6
+ ],
7
+ "mainEntry": "lib/main.js",
8
+ "_layoutNote": "resources/app.asar wins over resources/app whenever it exists, so identity is read from the archive in that case and never from the sibling extraction, which the updater leaves behind and which may be a different build."
9
+ }
@@ -66,7 +66,7 @@
66
66
  * and nothing started from outside survives the exit far enough to install afterwards (issue #36).
67
67
  * --restart asks for confirmation on a console; add --yes for an unattended run.
68
68
  */
69
- import { copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
69
+ import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
70
70
  import { execFileSync, spawn } from 'node:child_process'
71
71
  import { dirname, join } from 'node:path'
72
72
 
@@ -435,6 +435,215 @@ function installCliCompatibility() {
435
435
  console.log(` cli runtime resolution: ${patchHostCli()}`)
436
436
  }
437
437
 
438
+ // ---------------------------------------------------------------------------
439
+ // Identity — before anything is stopped, deleted, extracted, renamed or written.
440
+ //
441
+ // Reported as issue #40. The check used to be "resources/app/lib/main.js or resources/app.asar
442
+ // exists", which is the shape of EVERY Electron app. Measured: a throwaway app whose package.json
443
+ // said `unrelated-meeting-app` was accepted, had its entry file rewritten and the bridge copied in;
444
+ // and a second sample lost its `resources/app` directory to the packed-layout rebuild before the
445
+ // archive was found to be invalid.
446
+ //
447
+ // The rule now lives in `desktop-identity.json`, shared with the plugin's status reader, and the
448
+ // order is the point: identity first, then the archive is VALIDATED, and only then may this script
449
+ // close the app or delete a tree.
450
+ // ---------------------------------------------------------------------------
451
+
452
+ /**
453
+ * The identity rule (accepted package names and the main entry), from the JSON next to this file.
454
+ * @returns the rule, or undefined after printing why it cannot be trusted.
455
+ */
456
+ function readIdentityRule() {
457
+ try {
458
+ const raw = JSON.parse(readFileSync(new URL('./desktop-identity.json', import.meta.url), 'utf8'))
459
+ const names = raw.packageNames
460
+ const mainEntry = raw.mainEntry
461
+ if (!Array.isArray(names) || names.length === 0 || names.some(name => typeof name !== 'string')
462
+ || typeof mainEntry !== 'string' || mainEntry === '') {
463
+ console.error('desktop-identity.json is malformed: expected packageNames[] and mainEntry')
464
+ return undefined
465
+ }
466
+ return { packageNames: names, mainEntry }
467
+ } catch (error) {
468
+ console.error(`desktop-identity.json could not be read: ${String(error)}`)
469
+ return undefined
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Read one file out of an asar archive without extracting anything.
475
+ *
476
+ * Identity has to come from the archive when one exists: Electron loads it in preference to the
477
+ * sibling directory, and a desktop update leaves that older extraction behind, so verifying the
478
+ * directory would verify bytes nobody runs.
479
+ * @param archive - the archive path.
480
+ * @param entryPath - slash-separated path inside the archive.
481
+ * @returns the bytes, or undefined when the entry is missing or unreadable.
482
+ */
483
+ function readAsarEntry(archive, entryPath) {
484
+ let fd
485
+ try {
486
+ const parsed = readAsarHeader(archive)
487
+ fd = parsed.fd
488
+ let node
489
+ let files = parsed.header.files
490
+ for (const part of entryPath.split('/')) {
491
+ if (files === undefined) return undefined
492
+ node = files[part]
493
+ if (node === undefined) return undefined
494
+ files = node.files
495
+ }
496
+ if (node.files !== undefined || node.unpacked === true) return undefined
497
+ const size = Number(node.size)
498
+ const offset = Number(node.offset)
499
+ if (!Number.isFinite(size) || !Number.isFinite(offset) || size < 0) return undefined
500
+ const buffer = Buffer.alloc(size)
501
+ const read = readSync(fd, buffer, 0, size, parsed.contentBase + offset)
502
+ return read === size ? buffer : undefined
503
+ } catch {
504
+ return undefined
505
+ } finally {
506
+ if (fd !== undefined) {
507
+ try { closeSync(fd) } catch { /* already closed */ }
508
+ }
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Validate the archive the shell will actually load: it must parse, carry a DSH Desktop manifest and
514
+ * the declared main entry, and every `unpacked` entry must exist beside it with the size the header
515
+ * claims. Read-only.
516
+ * @param archive - the archive path.
517
+ * @returns `{ ok: true }`, or `{ ok: false, reason }`.
518
+ */
519
+ function validateArchive(archive) {
520
+ let parsed
521
+ try {
522
+ parsed = readAsarHeader(archive)
523
+ } catch (error) {
524
+ return { ok: false, reason: `the archive header cannot be read: ${String(error)}` }
525
+ }
526
+ const { fd, header, contentBase } = parsed
527
+ try {
528
+ const fileSize = statSync(archive).size
529
+ const problems = []
530
+ const walk = (node, prefix) => {
531
+ for (const [name, entry] of Object.entries(node.files ?? {})) {
532
+ const relativePath = prefix === '' ? name : `${prefix}/${name}`
533
+ if (entry.files !== undefined) {
534
+ walk(entry, relativePath)
535
+ continue
536
+ }
537
+ const size = Number(entry.size)
538
+ if (!Number.isFinite(size) || size < 0) {
539
+ problems.push(`${relativePath}: implausible size ${String(entry.size)}`)
540
+ continue
541
+ }
542
+ if (entry.unpacked === true) {
543
+ const source = join(`${archive}.unpacked`, ...relativePath.split('/'))
544
+ if (!existsSync(source)) {
545
+ problems.push(`${relativePath}: listed as unpacked but ${source} is missing`)
546
+ continue
547
+ }
548
+ if (statSync(source).size !== size) problems.push(`${relativePath}: unpacked size does not match the header`)
549
+ continue
550
+ }
551
+ const offset = Number(entry.offset)
552
+ if (!Number.isFinite(offset) || contentBase + offset + size > fileSize) {
553
+ problems.push(`${relativePath}: content lies outside the archive`)
554
+ }
555
+ }
556
+ }
557
+ walk(header, '')
558
+ if (problems.length > 0) {
559
+ return { ok: false, reason: `the archive is not usable: ${problems.slice(0, 5).join('; ')}` }
560
+ }
561
+ const rule = readIdentityRule()
562
+ if (rule === undefined) return { ok: false, reason: 'the identity rule is unavailable' }
563
+ let node
564
+ let files = header.files
565
+ for (const part of rule.mainEntry.split('/')) {
566
+ if (files === undefined) { node = undefined; break }
567
+ node = files[part]
568
+ files = node?.files
569
+ }
570
+ if (node === undefined) return { ok: false, reason: `the archive has no ${rule.mainEntry}` }
571
+ return { ok: true }
572
+ } catch (error) {
573
+ return { ok: false, reason: `the archive cannot be validated: ${String(error)}` }
574
+ } finally {
575
+ try { closeSync(fd) } catch { /* already closed */ }
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Whether a directory is a DSH Desktop install, by the shared identity rule.
581
+ *
582
+ * Every uncertainty refuses: this answer gates stopping the app, deleting a tree and writing files.
583
+ * @param root - the install directory to verify.
584
+ * @returns `{ ok: true, layout, packageName, version }`, or `{ ok: false, reason }`.
585
+ */
586
+ function verifyDesktopIdentity(root) {
587
+ const rule = readIdentityRule()
588
+ if (rule === undefined) return { ok: false, reason: 'the identity rule is unavailable' }
589
+ const resources = join(root, 'resources')
590
+ const archive = join(resources, 'app.asar')
591
+ const appDir = join(resources, 'app')
592
+ const archivePresent = existsSync(archive)
593
+ const layout = archivePresent ? 'packed' : 'unpacked'
594
+
595
+ let manifestText
596
+ if (archivePresent) {
597
+ const bytes = readAsarEntry(archive, 'package.json')
598
+ if (bytes === undefined) {
599
+ return { ok: false, reason: `${archive} exists but its package.json cannot be read` }
600
+ }
601
+ manifestText = bytes.toString('utf8')
602
+ } else {
603
+ const manifestPath = join(appDir, 'package.json')
604
+ if (!existsSync(manifestPath)) {
605
+ return { ok: false, reason: `neither ${manifestPath} nor ${archive} exists` }
606
+ }
607
+ manifestText = readFileSync(manifestPath, 'utf8')
608
+ }
609
+
610
+ let manifest
611
+ try {
612
+ manifest = JSON.parse(manifestText)
613
+ } catch {
614
+ return { ok: false, reason: 'the package manifest is not valid JSON' }
615
+ }
616
+ const name = typeof manifest.name === 'string' ? manifest.name : ''
617
+ if (!rule.packageNames.includes(name)) {
618
+ return {
619
+ ok: false,
620
+ reason: `the app calls itself ${name === '' ? '(no name)' : JSON.stringify(name)}, which is not one of `
621
+ + `${rule.packageNames.join(' / ')} — a generic Electron layout is not proof of identity`,
622
+ }
623
+ }
624
+ const mainPresent = archivePresent
625
+ ? readAsarEntry(archive, rule.mainEntry) !== undefined
626
+ : existsSync(join(appDir, ...rule.mainEntry.split('/')))
627
+ if (!mainPresent) {
628
+ return { ok: false, reason: `${rule.mainEntry} is not present under ${archivePresent ? archive : appDir}` }
629
+ }
630
+ return {
631
+ ok: true,
632
+ layout,
633
+ packageName: name,
634
+ version: typeof manifest.version === 'string' ? manifest.version : undefined,
635
+ }
636
+ }
637
+
638
+ const identity = verifyDesktopIdentity(installRoot)
639
+ if (!identity.ok) {
640
+ console.error(`refusing to touch ${installRoot}`)
641
+ console.error(` ${identity.reason}`)
642
+ console.error('Pass the installation directory of DSH Desktop as the first argument.')
643
+ console.error('Nothing was stopped, deleted, extracted or written.')
644
+ process.exit(1)
645
+ }
646
+
438
647
  // `--restart` closes the shell BEFORE anything else, because the archive cannot be moved while the
439
648
  // shell holds it (EBUSY), and because there is no safe way to wait across the exit from outside —
440
649
  // both arrangements measured in issue #36 died at that moment. Doing it here keeps the whole
@@ -569,6 +778,16 @@ if (revert) {
569
778
  }
570
779
 
571
780
  if (packedLayout) {
781
+ // Validate BEFORE the tree is deleted. Reported as issue #40: with an invalid archive and an
782
+ // existing extraction, this script removed `resources/app` and only then discovered the archive
783
+ // was unusable — leaving the app directory gone for no gain. The check is read-only and cheap
784
+ // (header walk plus a stat per unpacked entry), so it belongs on this side of the deletion.
785
+ const checked = validateArchive(asarPath)
786
+ if (!checked.ok) {
787
+ console.error(`refusing to rebuild from an archive that cannot be verified: ${checked.reason}`)
788
+ console.error('Nothing was deleted; the archive and the existing directory are untouched.')
789
+ process.exit(1)
790
+ }
572
791
  const stale = existsSync(appDir)
573
792
  const started = Date.now()
574
793
  console.log(stale
package/docs/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  | --- | --- |
7
7
  | 了解插件为什么存在、与无头方案的区别 | [为什么做共享真实浏览器](why-browser.md) |
8
8
  | 安装、配置、日常使用与常见问题 | [用户指南](user-guide.md) |
9
- | 全部 34 个工具的参数、输出与示例 | [工具参考](tool-reference.md) |
9
+ | 全部 35 个工具的参数、输出与示例 | [工具参考](tool-reference.md) |
10
10
  | 了解 seam / provider / 工具三层与自托管实现 | [架构说明](architecture.md) |
11
11
  | 知道哪些事**做不到**、以及为什么 | [已知限制](limitations.md) |
12
12
  | 构建、测试、复验宿主兼容性 | [开发](development.md) |
@@ -37,7 +37,7 @@ agent (dsh_browser_* 工具)
37
37
 
38
38
  ### 工具层(`src/tool-browser/`)
39
39
 
40
- 34 个 `dsh_browser_*` 工具,按**调用方任务**(`exec.agent.id`)维护独立浏览器会话:
40
+ 35 个 `dsh_browser_*` 工具,按**调用方任务**(`exec.agent.id`)维护独立浏览器会话:
41
41
 
42
42
  - 会话缓存 `sessionsByTask`:同一任务复用同一会话,并发首开去重;
43
43
  - `dsh_browser_reset_session` 关闭本任务会话并遗忘映射(即使 close 抛错也清除,下次调用重建);
@@ -6,7 +6,7 @@
6
6
 
7
7
  - JPEG 在**自托管**与**本机 Chrome / Edge** 上可用;**桌面端侧栏**走外壳的 `webContents.debugger`,其 Electron 的 CDP JPEG 编码会挂起,因此该载体下请求 JPEG 会返回 PNG。
8
8
  - 降采样(`maxWidth`/`maxHeight`)**三种载体都支持**(经 CDP `clip.scale`,或自托管走原生 `capturePage`)。
9
- - 自托管截图优先走 Electron 原生 `capturePage`(CDP `captureScreenshot` 在多视图下会挂起);截图前自动把目标标签置顶。
9
+ - 自托管截图优先走 Electron 原生 `capturePage`(CDP `captureScreenshot` 在多视图下会挂起);截图前自动把目标标签置顶 —— 除非开启**安静模式**,那时不碰窗口(见下)。
10
10
  - `fullPage` 在部分主机的**软件合成**下不稳定 —— 请求 `fullPage` 时**原生 `capturePage` 路径被整体跳过**(它没有捕获滚动区以外内容的能力),因此**三种载体都走 CDP 的 `captureBeyondViewport`**。也就是说 `fullPage` 的不稳定性与载体无关,任何载体都可能碰到;只有视口截图才优先走原生路径。
11
11
 
12
12
  ## 验证与登录
@@ -63,6 +63,24 @@
63
63
  - 新视图创建前会先有界加载 `about:blank`(3 秒上限,保证视图一存在就有可响应的渲染进程),宿主侧命令另有 20s 有界超时。
64
64
  - 子进程 stderr 与退出码/信号落到 `$DSH_HOME/logs/dsh-builtin-browser-host.log`;写之前若该文件已超过 2 MiB,则**丢弃旧内容、只写入一行带时间戳的轮转记录**(形如 `<ISO 时间戳> log rotated: previous content exceeded 2097152 bytes and was discarded`)—— 旧内容就此消失不留副本,但那一行证明"曾发生过轮转",纯 `dsh web` 自托管可据此自助排查崩溃循环。
65
65
 
66
+ ## 安静模式(`ui.quiet`)
67
+
68
+ 默认关闭。默认契约是"人机共享同一个窗口":每次操作把窗口带到前面,用户能直接看见 agent 在做什么。开启后,自托管的 Electron 载体改成"能操作,但不接管屏幕":
69
+
70
+ | 操作 | 默认 | 安静模式 |
71
+ | --- | --- | --- |
72
+ | 截图 | 显示 / 还原 / 聚焦窗口,再 `capturePage` | 不碰窗口;窗口不可见时直接走 CDP `Page.captureScreenshot` |
73
+ | 输入(点击 / 输入 / 按键) | `show()` + `moveTop()` + 聚焦 | 最小化则 `restore()`,不可见则 `showInactive()`;不激活应用、不抢键盘焦点、不 `moveTop()` |
74
+ | 标签切换 / 导航 | 同输入,把窗口置前 | 只换窗口内可见的标签,最小化的窗口保持最小化 |
75
+
76
+ 它不是"不显示窗口"。合成输入(CDP `Input.*`)仍需要视图有**显示表面**,Chromium 对没有表面的视图会静默丢弃输入 —— 所以点击/输入可能把最小化的窗口恢复成可见,但不会成为 key window,也不会盖在用户正在用的窗口上。截图和导航没有这个约束,因此是安静模式下完全不动窗口的操作。
77
+
78
+ 边界:
79
+
80
+ - **只作用于自托管 Electron 载体**(插件的 `host-main` 子进程)。桌面端侧栏由外壳承载,`ui.quiet` 不改变外壳的展示策略;安装版 Chrome / Edge 载体各自管理自己的窗口。
81
+ - 用户主动操作(点工具栏、切标签)不受影响 —— 它们本来就发生在那个窗口里。
82
+ - 窗口完全不可见时,安静模式仍会让它出现在屏幕上(只是不聚焦)。要"连出现都不要",请在截图之外使用非视觉能力(snapshot / a11y / content),它们本来就不需要显示表面。
83
+
66
84
  ## 不提供的东西
67
85
 
68
86
  - **无痕模式(`privateMode`)未实现**:它需要 Electron 的 session 分区能力,属于宿主层,本插件不承诺。