dsh-builtin-browser 0.4.13 → 0.4.15
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/CHANGELOG.md +74 -0
- package/docs/limitations.md +14 -0
- package/lib/browser-electron/entry.js +3 -1
- package/lib/browser-electron/settings-store.d.ts +24 -0
- package/lib/browser-electron/settings-store.js +34 -2
- package/lib/browser-electron/system-browser.d.ts +12 -1
- package/lib/browser-electron/system-browser.js +151 -5
- package/package.json +1 -1
- package/src/browser-electron/entry.ts +4 -1
- package/src/browser-electron/settings-store.ts +58 -2
- package/src/browser-electron/system-browser.ts +145 -3
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,80 @@
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
# 第五十二轮(2026-10-19,两个启动缺陷:hand-off 只认一次、启动参数白送一个空标签)
|
|
8
|
+
|
|
9
|
+
报告者在 Windows 11 + Chrome 156 上报了两个,并自己定位了位置。他先报在 0.4.7 上,**升到 0.4.14 复测后两个都仍在** —— 我核实确认。
|
|
10
|
+
|
|
11
|
+
## 一、exit 0 的认领只做一次(0.4.14 上是"读早了")
|
|
12
|
+
|
|
13
|
+
`start()` 在 child 退出后判 `clean = exitCode === 0 && signal === null`,然后调**一次** `adoptRunningBrowser('after a hand-off')`。0.4.14 已经把"exit 0 当作移交而不是失败"做对了,但**只认一次**。
|
|
14
|
+
|
|
15
|
+
报告者测出了为什么必然失败:Windows 上启动器 stub **300 ms 就退出**,而 `DevToolsActivePort` **441 ms 才落地** —— stub 退出那一刻文件还不存在,认领返回 undefined,于是仍然抛 `exited immediately after launch (exit code 0)`,而浏览器其实已经在启动。
|
|
16
|
+
|
|
17
|
+
改法按他的建议做成**有界重试**:`HANDOFF_ADOPT_MS = 8_000`、间隔复用既有的 `PORT_PROBE_MS`(250 ms),`this.disposed` 或超时即停。8 秒是他实测可用的上界,相对那约 150 ms 的间隙是宽裕的;真正失败的启动仍会在同一预算内报错,不会被拖成"慢失败"。
|
|
18
|
+
|
|
19
|
+
**重试只在 `clean` 分支内**。非 0 退出码或信号仍然立即判死并给出"它没有把请求交给谁"的措辞 —— 把它们也重试会把一句明确的"检查它能不能跑"变成 8 秒停顿后同一句话。
|
|
20
|
+
|
|
21
|
+
## 二、启动参数 `about:blank` 白送一个空标签
|
|
22
|
+
|
|
23
|
+
参数列表原来以 `'about:blank'` 结尾。插件自己的页面是首次使用时由 `Target.createTarget` 建的(`buildSession`),**开头那个标签从来不复用也不关闭** —— 标签栏是"空页 + 目标页"两行,而 `dsh_browser_list_tabs` 只报 1 个,因为那个空标签不在插件的模型里。这正是报告者描述的形态。
|
|
24
|
+
|
|
25
|
+
改为 **`--no-startup-window`**:不建窗口、不起初始 page,浏览器仍然存活并可连 CDP。报告者实测(用正确引号重测后):`DevToolsActivePort` 599 ms 落地、`/json/version` 200、`/json/list` 只有两个 extension target 没有 page、然后 `Target.createTarget` 能正常建出窗口与页面。
|
|
26
|
+
|
|
27
|
+
**兼容性没丢**:若某个浏览器仍开了一个空白页,`normalizeBlankPages` 会关掉多余的、`buildSession` 会领养留下来的那个 —— 这条路径本来就在,现在只是不再主动制造它。
|
|
28
|
+
|
|
29
|
+
## 三、验证:先证明断言能区分修复前后
|
|
30
|
+
|
|
31
|
+
3 条新断言,把源码回退到修复前跑同一组:**3 条全失败**(其中启动参数那条等了 30 秒超时),修复后 3 条全过。全量 **295 → 298**(297 通过 + 1 条平台门控跳过),`tsc` 干净。
|
|
32
|
+
|
|
33
|
+
**未验证部分**:我没有在 Windows 上跑真实的 Chrome 156 复现那 150 ms 的间隙。两个改动都按报告者的实测参数落地(8 秒 / 250 ms、`--no-startup-window`),但真实时序仍需在他的机器上复测。
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
# 第五十一轮(2026-10-19,无显示环境无法启动浏览器:自动 headless)
|
|
38
|
+
|
|
39
|
+
报告者把一个 systemd 服务上的部署失败追到了底:Debian 13、`dsh web` 以服务常驻、**进程里没有 `DISPLAY` / `WAYLAND_DISPLAY`**,于是每次 `dsh_browser_*` 都报 `exited immediately after launch (exit code 1)`,`DevToolsActivePort` 从不出现,整组工具不可用。底层原因是 Chromium 打印 `qt.qpa.xcb: could not connect to display` 后立即退出,而我们的启动参数从来不含 `--headless`。
|
|
40
|
+
|
|
41
|
+
他给了本地补丁(改在 `node_modules` 里)、端到端验证(重启服务后成功打开页面并产出 780×437 的 PNG),并明确要求**上游做成设置驱动**,因为 `node_modules` 的改动会被插件更新覆盖。
|
|
42
|
+
|
|
43
|
+
## 一、核实
|
|
44
|
+
|
|
45
|
+
`start()` 的参数确实只有 `--remote-debugging-port=0`、`--user-data-dir`、`--no-first-run`、`--no-default-browser-check`、`--disable-features`、两个 bubble 开关 —— **没有 `--headless`,也没有 `--no-sandbox`**。而 `--headless` 缺席时,无显示的 Chromium 必然退出。这不是配置问题:桌面端有显示所以能开窗,服务端没有所以必然失败,而服务端恰好是"用截图把结果回传"的主流用法。
|
|
46
|
+
|
|
47
|
+
## 二、改法:设置项 + 环境变量,而不是只在源码里加参数
|
|
48
|
+
|
|
49
|
+
新增 **`browser.headless`**,取值 `auto`(默认) / `headless` / `windowed`:
|
|
50
|
+
|
|
51
|
+
| 值 | 行为 |
|
|
52
|
+
| --- | --- |
|
|
53
|
+
| `auto` | 有显示 → 窗口;**无显示 → headless** |
|
|
54
|
+
| `headless` | 强制 headless |
|
|
55
|
+
| `windowed` | 强制窗口;显示不可用时**明确失败**,不悄悄退化 |
|
|
56
|
+
|
|
57
|
+
**为什么是三个字符串而不是布尔三元组**:JSON 文档里混用 string 与 boolean 会产生歧义(手写 `true` 与 `"true"` 是两回事)。但手写 `true` / `false` 仍然接受,分别映射到 `headless` / `windowed` —— 那是任何人第一次写这个设置时会写的形态,因为类型差异拒绝它属于咬文嚼字。任何不认识的值都会被**报告**并回落到 `auto`,理由与 `browser.channel` 相同:被丢弃的值和生效的值看起来必须不一样。
|
|
58
|
+
|
|
59
|
+
**环境变量优先于设置**:`DSH_BROWSER_HEADLESS=1` / `=0` 覆盖设置项。报告者第 4.3 条提的就是这个 —— 运维改一个运行中的部署不该需要编辑文件。测试里专门断言了**覆盖在模式判断之前生效**,否则存下来的设置会压过运维的应急开关。
|
|
60
|
+
|
|
61
|
+
## 三、headless 时补的三个开关与一条安全约束
|
|
62
|
+
|
|
63
|
+
`--headless=new`(不是旧 `--headless`):新模式的行为更接近有窗口的浏览器,而本插件所有命令都是对着有窗口的浏览器写并实测的 —— 包括 CDP 输入,Chromium 会静默丢弃"它认为没有显示表面"的视图的输入。
|
|
64
|
+
|
|
65
|
+
`--disable-gpu`、`--disable-dev-shm-usage`:无 GPU、`/dev/shm` 远小于桌面的环境里,这两个是让 headless 可用的前提。
|
|
66
|
+
|
|
67
|
+
**`--no-sandbox` 只在必要时加**,按报告者第 4.4 条:只有"以 root 运行"或"在容器内"(`/.dockerenv` 或 `container` 环境变量)才加,并且**在 stderr 明确写出这次降级**。默认仍走沙箱;降低进程隔离这件事必须让人能看见并反对。
|
|
68
|
+
|
|
69
|
+
## 四、验证:先证明断言能区分修复前后
|
|
70
|
+
|
|
71
|
+
5 条新断言,把源码回退到修复前跑同一组:**4 条失败**(其中"启动参数"那条等了 30 秒超时 —— 那正是没有 `--headless` 时浏览器起不来的表现),修复后 5 条全过。唯一在旧代码上也通过的是"windowed 不加 headless",它本来就该一直成立。
|
|
72
|
+
|
|
73
|
+
`--no-sandbox` 那条是静态断言(检查它挂在 `headless && needsNoSandbox()` 条件下、且会打印),因为本机是 Windows、`needsNoSandbox()` 恒为 false,无法在这里触发真实的 root/容器分支。
|
|
74
|
+
|
|
75
|
+
**未验证部分**:本次没有在真实的 systemd / 无显示环境里跑过。报告者已经用等价补丁做过端到端验证(页面打开 + PNG 产出),而我实现的路径与他的补丁在同一处、同样的开关;但仍需在真实无显示环境复测,这一点如实记下。
|
|
76
|
+
|
|
77
|
+
**测试**:290 → 295(新增 5 条:`tests/headless-launch.test.mjs`)。`tsc` 干净。
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
7
81
|
# 第五十轮(2026-10-17,对齐 DSH 0.2.1 的插件契约 + 工具描述瘦身)
|
|
8
82
|
|
|
9
83
|
## 一、版本范围改到 DSH 真正读取的位置
|
package/docs/limitations.md
CHANGED
|
@@ -32,6 +32,20 @@
|
|
|
32
32
|
|
|
33
33
|
## 载体行为
|
|
34
34
|
|
|
35
|
+
- **无显示环境会自动改用 headless**,不需要额外配置。Chromium 在没有 `DISPLAY` 与 `WAYLAND_DISPLAY` 时会以 `could not connect to display` 立即退出,而 systemd 服务、容器、只有 SSH 的服务器正好都是这个状态——那偏偏是服务端浏览器最有用的部署形态。`browser.headless` 的默认值 `auto` 就是"有显示开窗口,没显示走 headless",桌面端与侧栏用户不受影响。
|
|
36
|
+
|
|
37
|
+
想显式控制时:
|
|
38
|
+
|
|
39
|
+
| 设置 | 行为 |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `"auto"`(默认) | 有显示 → 窗口;无显示 → headless |
|
|
42
|
+
| `"headless"` | 强制 headless(服务器 / 截图专用 / CI) |
|
|
43
|
+
| `"windowed"` | 强制窗口;显示不可用时**直接报错**,而不是悄悄退化 |
|
|
44
|
+
|
|
45
|
+
手写 `true` / `false` 也接受,分别等价于 `headless` / `windowed`。运行中的部署可以用环境变量覆盖设置,不必改文件:`DSH_BROWSER_HEADLESS=1` 强制 headless,`=0` 强制窗口(环境变量优先于设置项)。
|
|
46
|
+
|
|
47
|
+
headless 启动会自动带上 `--disable-gpu` 与 `--disable-dev-shm-usage`;`--no-sandbox` **只在必要时**加(以 root 运行,或在容器内),并且会在 stderr 明确写出——降低进程隔离这件事必须让人能看见并反对。
|
|
48
|
+
|
|
35
49
|
- **侧栏载体有前置条件**,不是装上 bridge 就成立。官方侧栏浏览器面板只在**外壳同时满足**两个条件时才是 `<webview>`:
|
|
36
50
|
1. `preload` 暴露 `dshDesktop.browser`(而不只是 `protocolVersion`);
|
|
37
51
|
2. 外壳窗口开启 `webviewTag`。
|
|
@@ -294,7 +294,9 @@ export function apply(ctx, config) {
|
|
|
294
294
|
sweepAbandonedEphemeralProfiles(profileRoot, detected.kind);
|
|
295
295
|
claimEphemeralProfile(profileDir);
|
|
296
296
|
}
|
|
297
|
-
|
|
297
|
+
// The headless mode rides along so a display-less host (systemd, container, SSH-only server)
|
|
298
|
+
// still gets a working browser instead of "exited immediately after launch" — issue #32.
|
|
299
|
+
adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir, undefined, settings.get().browser.headless), `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`);
|
|
298
300
|
}
|
|
299
301
|
}
|
|
300
302
|
// An explicit choice was already adopted above; discovering the sidebar here would
|
|
@@ -11,6 +11,15 @@
|
|
|
11
11
|
import type { BrowserChannel } from './system-browser.js';
|
|
12
12
|
/** Vision/operation strategy the provider prefers when the model can see. */
|
|
13
13
|
export type VisionStrategy = 'auto' | 'nonVisual';
|
|
14
|
+
/**
|
|
15
|
+
* Whether a launched browser gets a window.
|
|
16
|
+
*
|
|
17
|
+
* Split from {@link VisionStrategy} because these answer different questions: that one is how the
|
|
18
|
+
* agent examines a page, this one is whether the browser has anywhere to draw.
|
|
19
|
+
*/
|
|
20
|
+
export type HeadlessMode = 'auto' | 'headless' | 'windowed';
|
|
21
|
+
/** Every value {@link HeadlessMode} accepts, for validation and the settings UI. */
|
|
22
|
+
export declare const HEADLESS_MODES: readonly ["auto", "headless", "windowed"];
|
|
14
23
|
/** The full settings document, with every field resolved. */
|
|
15
24
|
export interface BrowserSettings {
|
|
16
25
|
/** Persistent browsing history (visited pages). */
|
|
@@ -39,6 +48,21 @@ export interface BrowserSettings {
|
|
|
39
48
|
/** Which browser binary carries the agent's pages. */
|
|
40
49
|
readonly browser: {
|
|
41
50
|
readonly channel: BrowserChannel;
|
|
51
|
+
/**
|
|
52
|
+
* Whether the browser gets a window.
|
|
53
|
+
*
|
|
54
|
+
* `auto` (the default) launches headless when the process has no display — no `DISPLAY` and no
|
|
55
|
+
* `WAYLAND_DISPLAY` — and with a window otherwise. That combination is what makes the plugin
|
|
56
|
+
* work under systemd, in a container, or on an SSH-only server while leaving desktop users
|
|
57
|
+
* with the visible window they expect. `true` forces headless (CI, screenshot-only servers);
|
|
58
|
+
* `false` forces a window, so a misconfigured display fails loudly instead of silently
|
|
59
|
+
* degrading into a browser nobody can see.
|
|
60
|
+
*
|
|
61
|
+
* Reported as issue #32: as a systemd service there is no display, Chromium exits with
|
|
62
|
+
* "could not connect to display", and every `dsh_browser_*` call failed with "exited
|
|
63
|
+
* immediately after launch".
|
|
64
|
+
*/
|
|
65
|
+
readonly headless: HeadlessMode;
|
|
42
66
|
};
|
|
43
67
|
/** Whether the agent may read cookies / export login state. */
|
|
44
68
|
readonly credentials: {
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
12
12
|
import { homedir } from 'node:os';
|
|
13
13
|
import { dirname, join } from 'node:path';
|
|
14
|
+
/** Every value {@link HeadlessMode} accepts, for validation and the settings UI. */
|
|
15
|
+
export const HEADLESS_MODES = ['auto', 'headless', 'windowed'];
|
|
14
16
|
/** Defaults for every switch: the documented out-of-the-box behaviour. */
|
|
15
17
|
export const DEFAULT_SETTINGS = {
|
|
16
18
|
history: { enabled: true, maxEntries: 5_000, maxAgeDays: 90 },
|
|
@@ -20,7 +22,7 @@ export const DEFAULT_SETTINGS = {
|
|
|
20
22
|
// Bundled by default: it needs nothing installed, and on the desktop the carrier
|
|
21
23
|
// is the sidebar anyway. Choosing a system browser is an explicit opt-in because
|
|
22
24
|
// it starts a real Chrome/Edge with its own profile.
|
|
23
|
-
browser: { channel: 'bundled' },
|
|
25
|
+
browser: { channel: 'bundled', headless: 'auto' },
|
|
24
26
|
credentials: { allowRead: true },
|
|
25
27
|
actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
|
|
26
28
|
};
|
|
@@ -75,6 +77,33 @@ const SETTINGS_WHEN_UNREADABLE = {
|
|
|
75
77
|
* message that lists a value the code rejects (or omits one it takes) is worse than no message.
|
|
76
78
|
*/
|
|
77
79
|
export const BROWSER_CHANNELS = ['chrome', 'edge', 'auto', 'bundled', 'sidebar'];
|
|
80
|
+
/**
|
|
81
|
+
* Coerce the headless mode, keeping `auto` when the value is not one of the known choices.
|
|
82
|
+
*
|
|
83
|
+
* Booleans are accepted as a convenience because "headless: true" is what anyone writing this by
|
|
84
|
+
* hand would try first, and rejecting it over a type difference would be pedantry: `true` maps to
|
|
85
|
+
* `headless`, `false` to `windowed`. Anything else is reported rather than silently defaulted,
|
|
86
|
+
* for the same reason as {@link resolveChannel}: a discarded value and an honoured one must not
|
|
87
|
+
* look alike.
|
|
88
|
+
* @param value - the raw value from the settings document.
|
|
89
|
+
* @param warn - where to report a discarded value.
|
|
90
|
+
* @returns a valid mode.
|
|
91
|
+
*/
|
|
92
|
+
function resolveHeadless(value, warn) {
|
|
93
|
+
if (value === undefined)
|
|
94
|
+
return DEFAULT_SETTINGS.browser.headless;
|
|
95
|
+
if (value === true)
|
|
96
|
+
return 'headless';
|
|
97
|
+
if (value === false)
|
|
98
|
+
return 'windowed';
|
|
99
|
+
if (typeof value === 'string' && HEADLESS_MODES.includes(value)) {
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
warn?.(`dsh-builtin-browser: browser.headless ${JSON.stringify(value)} is not a known mode, so the `
|
|
103
|
+
+ `default "${DEFAULT_SETTINGS.browser.headless}" was used instead. Expected one of: `
|
|
104
|
+
+ `${HEADLESS_MODES.join(', ')} (or a boolean).`);
|
|
105
|
+
return DEFAULT_SETTINGS.browser.headless;
|
|
106
|
+
}
|
|
78
107
|
/**
|
|
79
108
|
* Coerce the browser channel, keeping the default when it is not one of the
|
|
80
109
|
* known choices. A hand-edited typo must not silently select a different browser.
|
|
@@ -164,7 +193,10 @@ export function resolveSettings(raw, warn) {
|
|
|
164
193
|
virtualCursor: bool(ui?.virtualCursor, DEFAULT_SETTINGS.ui.virtualCursor),
|
|
165
194
|
},
|
|
166
195
|
vision: { strategy: vision?.strategy === 'nonVisual' ? 'nonVisual' : DEFAULT_SETTINGS.vision.strategy },
|
|
167
|
-
browser: {
|
|
196
|
+
browser: {
|
|
197
|
+
channel: resolveChannel(browser?.channel, warn),
|
|
198
|
+
headless: resolveHeadless(browser?.headless, warn),
|
|
199
|
+
},
|
|
168
200
|
credentials: {
|
|
169
201
|
// `gate` returns false for anything present-and-not-a-boolean, so an unreadable section
|
|
170
202
|
// is refused here for free: the section itself is the "present but wrong" value.
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
* only the carrier differs.
|
|
25
25
|
* @module dsh-browser/browser-electron/system-browser
|
|
26
26
|
*/
|
|
27
|
+
import type { HeadlessMode } from './settings-store.js';
|
|
27
28
|
/**
|
|
28
29
|
* Starts a browser process and returns a handle to it.
|
|
29
30
|
*
|
|
@@ -79,6 +80,11 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
|
|
|
79
80
|
private readonly extraArgs;
|
|
80
81
|
private readonly ephemeralDir?;
|
|
81
82
|
private readonly launcher;
|
|
83
|
+
/**
|
|
84
|
+
* Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
|
|
85
|
+
* and why a display-less host needs headless at all (issue #32).
|
|
86
|
+
*/
|
|
87
|
+
private readonly headlessMode;
|
|
82
88
|
/**
|
|
83
89
|
* viewId -> the session that view rides, and the client that issued it.
|
|
84
90
|
*
|
|
@@ -145,7 +151,12 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
|
|
|
145
151
|
* removing every sessions.clear() left the recovery tests green. A launcher lets a test
|
|
146
152
|
* provide something that actually speaks CDP, so the state those tests describe exists.
|
|
147
153
|
*/
|
|
148
|
-
constructor(browser: DetectedBrowser, profileDir: string, extraArgs?: readonly string[], ephemeralDir?: string | undefined, launcher?: BrowserLauncher
|
|
154
|
+
constructor(browser: DetectedBrowser, profileDir: string, extraArgs?: readonly string[], ephemeralDir?: string | undefined, launcher?: BrowserLauncher,
|
|
155
|
+
/**
|
|
156
|
+
* Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
|
|
157
|
+
* and why a display-less host needs headless at all (issue #32).
|
|
158
|
+
*/
|
|
159
|
+
headlessMode?: HeadlessMode);
|
|
149
160
|
/** Which product this host would drive (for diagnostics). */
|
|
150
161
|
get kind(): DetectedBrowser['kind'];
|
|
151
162
|
/** Whether the browser has actually been started yet (diagnostics and tests). */
|
|
@@ -61,6 +61,20 @@ const CLOSE_GRACE_MS = 6_000;
|
|
|
61
61
|
* interval, so a worst-case iteration costs 500 ms and the budget still affords ~60 attempts.
|
|
62
62
|
*/
|
|
63
63
|
const PORT_PROBE_MS = 250;
|
|
64
|
+
/**
|
|
65
|
+
* How long to keep trying to adopt a browser after a launcher reported a clean exit.
|
|
66
|
+
*
|
|
67
|
+
* Exit code 0 means the launcher handed the request to an instance already holding this profile —
|
|
68
|
+
* but on Windows that stub exits BEFORE the real browser writes `DevToolsActivePort`. Measured on
|
|
69
|
+
* Chrome 156: stub gone at 300 ms, port file present at 441 ms (issue #33). A single attempt read
|
|
70
|
+
* too early and reported a launch failure for a browser that was starting normally, so this is a
|
|
71
|
+
* retry rather than one shot.
|
|
72
|
+
*
|
|
73
|
+
* 8 s is the reporter's measured-working bound and is generous against that ~150 ms gap: an honest
|
|
74
|
+
* hand-off resolves in well under a second, and a launch that genuinely failed still reaches the
|
|
75
|
+
* error within the same budget the CDP loop already allows.
|
|
76
|
+
*/
|
|
77
|
+
const HANDOFF_ADOPT_MS = 8_000;
|
|
64
78
|
/** The real launcher: spawn a detached-free child with pipes closed. */
|
|
65
79
|
const defaultLauncher = (path, args) => spawn(path, [...args], { stdio: ['ignore', 'ignore', 'ignore'], windowsHide: false });
|
|
66
80
|
import { spawn } from 'node:child_process';
|
|
@@ -168,6 +182,86 @@ const INSTALL_LOCATIONS = {
|
|
|
168
182
|
function isBrowserProduct(product) {
|
|
169
183
|
return typeof product === 'string' && /chrome|chromium|edg/i.test(product);
|
|
170
184
|
}
|
|
185
|
+
/**
|
|
186
|
+
* Whether this process has somewhere to draw a window.
|
|
187
|
+
*
|
|
188
|
+
* The same test Chromium makes: with neither `DISPLAY` nor `WAYLAND_DISPLAY` set it cannot open a
|
|
189
|
+
* window and exits with "could not connect to display". Declared here rather than in
|
|
190
|
+
* settings-store because that module imports from this one, and a value import back would be a
|
|
191
|
+
* cycle; the equivalent export there delegates to this.
|
|
192
|
+
* @param env - the environment to inspect; defaults to the current process.
|
|
193
|
+
* @returns true when a display is advertised.
|
|
194
|
+
*/
|
|
195
|
+
function hasDisplay(env = process.env) {
|
|
196
|
+
// Windows and macOS use neither variable, and always have a window server.
|
|
197
|
+
if (process.platform === 'win32' || process.platform === 'darwin')
|
|
198
|
+
return true;
|
|
199
|
+
return (env.DISPLAY ?? '') !== '' || (env.WAYLAND_DISPLAY ?? '') !== '';
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Whether Chromium's own sandbox cannot start here.
|
|
203
|
+
*
|
|
204
|
+
* Two cases, both of which make the browser exit at once rather than degrade: running as root
|
|
205
|
+
* (the sandbox refuses), and running inside a container that lacks the namespaces it needs. The
|
|
206
|
+
* check is deliberately conservative — when it is unsure it answers false, so the default is the
|
|
207
|
+
* sandboxed launch and the weaker mode only happens where it is required.
|
|
208
|
+
* @param env - the environment to inspect; defaults to the current process.
|
|
209
|
+
* @returns true when `--no-sandbox` is required for the browser to start at all.
|
|
210
|
+
*/
|
|
211
|
+
function needsNoSandbox(env = process.env) {
|
|
212
|
+
if (process.platform === 'win32')
|
|
213
|
+
return false;
|
|
214
|
+
try {
|
|
215
|
+
if (typeof process.getuid === 'function' && process.getuid() === 0)
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// No getuid: not a POSIX process; the container checks below still apply.
|
|
220
|
+
}
|
|
221
|
+
if ((env.container ?? '') !== '')
|
|
222
|
+
return true;
|
|
223
|
+
try {
|
|
224
|
+
if (existsSync('/.dockerenv'))
|
|
225
|
+
return true;
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
// An unreadable root is not evidence of a container.
|
|
229
|
+
}
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Resolve `auto` into a concrete decision, and say why.
|
|
234
|
+
*
|
|
235
|
+
* Chromium refuses to start without a display: with neither `DISPLAY` nor `WAYLAND_DISPLAY` set it
|
|
236
|
+
* exits at once with "could not connect to display", and the caller sees only "exited immediately
|
|
237
|
+
* after launch (exit code 1)". That is the ordinary state of a systemd service, a container, and an
|
|
238
|
+
* SSH-only server — the deployment where a server-side browser is most useful, and the one reported
|
|
239
|
+
* as issue #32: every `dsh_browser_*` call failed, with nothing in the message pointing at the
|
|
240
|
+
* display.
|
|
241
|
+
*
|
|
242
|
+
* `auto` therefore launches headless exactly when there is no display, which leaves desktop and
|
|
243
|
+
* sidebar users with the visible window they expect. An environment override wins over the setting
|
|
244
|
+
* so an operator can fix a running deployment without editing settings: `DSH_BROWSER_HEADLESS=1`
|
|
245
|
+
* forces headless, `=0` forces a window.
|
|
246
|
+
* @param mode - the configured mode.
|
|
247
|
+
* @param env - the environment to inspect; defaults to the current process.
|
|
248
|
+
* @returns whether to launch headless, and a one-line reason for the log.
|
|
249
|
+
*/
|
|
250
|
+
function resolveLaunchMode(mode, env = process.env) {
|
|
251
|
+
const override = env.DSH_BROWSER_HEADLESS;
|
|
252
|
+
if (override === '1' || override === 'true')
|
|
253
|
+
return { headless: true, why: 'DSH_BROWSER_HEADLESS' };
|
|
254
|
+
if (override === '0' || override === 'false')
|
|
255
|
+
return { headless: false, why: 'DSH_BROWSER_HEADLESS' };
|
|
256
|
+
if (mode === 'headless')
|
|
257
|
+
return { headless: true, why: 'browser.headless = headless' };
|
|
258
|
+
if (mode === 'windowed')
|
|
259
|
+
return { headless: false, why: 'browser.headless = windowed' };
|
|
260
|
+
const display = hasDisplay(env);
|
|
261
|
+
return display
|
|
262
|
+
? { headless: false, why: 'a display is available' }
|
|
263
|
+
: { headless: true, why: 'no DISPLAY or WAYLAND_DISPLAY' };
|
|
264
|
+
}
|
|
171
265
|
/**
|
|
172
266
|
* Whether a target URL is one of the blanks a browser opens by itself.
|
|
173
267
|
*
|
|
@@ -388,6 +482,7 @@ export class SystemBrowserViewHost {
|
|
|
388
482
|
extraArgs;
|
|
389
483
|
ephemeralDir;
|
|
390
484
|
launcher;
|
|
485
|
+
headlessMode;
|
|
391
486
|
/**
|
|
392
487
|
* viewId -> the session that view rides, and the client that issued it.
|
|
393
488
|
*
|
|
@@ -454,12 +549,18 @@ export class SystemBrowserViewHost {
|
|
|
454
549
|
* removing every sessions.clear() left the recovery tests green. A launcher lets a test
|
|
455
550
|
* provide something that actually speaks CDP, so the state those tests describe exists.
|
|
456
551
|
*/
|
|
457
|
-
constructor(browser, profileDir, extraArgs = [], ephemeralDir, launcher = defaultLauncher
|
|
552
|
+
constructor(browser, profileDir, extraArgs = [], ephemeralDir, launcher = defaultLauncher,
|
|
553
|
+
/**
|
|
554
|
+
* Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
|
|
555
|
+
* and why a display-less host needs headless at all (issue #32).
|
|
556
|
+
*/
|
|
557
|
+
headlessMode = 'auto') {
|
|
458
558
|
this.browser = browser;
|
|
459
559
|
this.profileDir = profileDir;
|
|
460
560
|
this.extraArgs = extraArgs;
|
|
461
561
|
this.ephemeralDir = ephemeralDir;
|
|
462
562
|
this.launcher = launcher;
|
|
563
|
+
this.headlessMode = headlessMode;
|
|
463
564
|
}
|
|
464
565
|
/** Which product this host would drive (for diagnostics). */
|
|
465
566
|
get kind() {
|
|
@@ -639,6 +740,7 @@ export class SystemBrowserViewHost {
|
|
|
639
740
|
const adopted = await this.adoptRunningBrowser('before launch');
|
|
640
741
|
if (adopted !== undefined)
|
|
641
742
|
return adopted;
|
|
743
|
+
const launch = resolveLaunchMode(this.headlessMode);
|
|
642
744
|
const args = [
|
|
643
745
|
'--remote-debugging-port=0',
|
|
644
746
|
`--user-data-dir=${this.profileDir}`,
|
|
@@ -649,9 +751,40 @@ export class SystemBrowserViewHost {
|
|
|
649
751
|
'--disable-features=Translate,MediaRouter',
|
|
650
752
|
'--disable-session-crashed-bubble',
|
|
651
753
|
'--hide-crash-restore-bubble',
|
|
754
|
+
// Headless only where there is nothing to draw on. `--headless=new` rather than the legacy
|
|
755
|
+
// flag: the new mode behaves like a windowed browser, which matters because every command
|
|
756
|
+
// here was written and measured against one — including CDP input, which Chromium silently
|
|
757
|
+
// drops for a view it believes has no display surface. `--disable-gpu` and
|
|
758
|
+
// `--disable-dev-shm-usage` are what make that mode usable on a server: no GPU, and a
|
|
759
|
+
// /dev/shm far smaller than a desktop. See resolveLaunchMode for why this is conditional.
|
|
760
|
+
...launch.headless ? ['--headless=new', '--disable-gpu', '--disable-dev-shm-usage'] : [],
|
|
652
761
|
...this.extraArgs,
|
|
653
|
-
|
|
762
|
+
// NOT `about:blank`. Every page this plugin drives is created by `Target.createTarget` when a
|
|
763
|
+
// session first needs one (`buildSession`, which adopts a blank if the browser opened one and
|
|
764
|
+
// creates one otherwise), so a startup page is a tab nobody asked for and nobody closes: the
|
|
765
|
+
// tab strip showed `about:blank` next to the real page while `dsh_browser_list_tabs` reported
|
|
766
|
+
// only the real one. Reported as issue #33, banner and all.
|
|
767
|
+
//
|
|
768
|
+
// `--no-startup-window` keeps the browser alive with no window and no initial page; measured
|
|
769
|
+
// by the reporter on Chrome 156 as writing DevToolsActivePort in 599 ms, answering
|
|
770
|
+
// `/json/version`, listing two extension targets and no page, and then creating windows
|
|
771
|
+
// normally through `Target.createTarget`. A browser that does start a blank despite this is
|
|
772
|
+
// still handled: `normalizeBlankPages` closes the surplus and `buildSession` adopts the rest.
|
|
773
|
+
'--no-startup-window',
|
|
654
774
|
];
|
|
775
|
+
// Chromium's own sandbox cannot start in some of these environments — running as root, or
|
|
776
|
+
// inside a container without the namespaces it needs — and it exits rather than degrading.
|
|
777
|
+
// Only then is the sandbox dropped, and never silently: a setting that weakens process
|
|
778
|
+
// isolation must be visible in the log, because whoever reads it has to be able to disagree.
|
|
779
|
+
if (launch.headless && needsNoSandbox()) {
|
|
780
|
+
args.splice(args.length - 2, 0, '--no-sandbox');
|
|
781
|
+
process.stderr.write('[dsh-browser] launching with --no-sandbox: '
|
|
782
|
+
+ 'this process runs as root or in a container, where the Chromium sandbox cannot start\n');
|
|
783
|
+
}
|
|
784
|
+
if (launch.headless) {
|
|
785
|
+
process.stderr.write(`[dsh-browser] launching headless (${launch.why}); `
|
|
786
|
+
+ 'the browser has no window but every tool works the same\n');
|
|
787
|
+
}
|
|
655
788
|
// A browser from a previous attempt may still be running with this same
|
|
656
789
|
// --user-data-dir. On Windows the new one would merely hand off to it and exit, and that
|
|
657
790
|
// exit would then be treated as the launch failing.
|
|
@@ -890,10 +1023,23 @@ export class SystemBrowserViewHost {
|
|
|
890
1023
|
// Exit code 0 IS the hand-off: the request went to an instance already holding this profile,
|
|
891
1024
|
// so that instance is our browser and it is running right now. Adopting it turns the
|
|
892
1025
|
// reported "kill the leftovers by hand, on every restart" into a call that just works.
|
|
1026
|
+
//
|
|
1027
|
+
// Adopted with a bounded RETRY, because on Windows the launcher stub exits before the browser
|
|
1028
|
+
// has written its port file: measured 300 ms to exit against 441 ms for DevToolsActivePort.
|
|
1029
|
+
// One attempt therefore read too early and reported "exited immediately after launch" for a
|
|
1030
|
+
// browser that was starting normally — reported as issue #33, where the reporter's own
|
|
1031
|
+
// retry loop fixed it. 8 s at 250 ms is their measured-working bound and is generous against
|
|
1032
|
+
// the ~150 ms gap, without turning a genuinely failed launch into a slow failure.
|
|
893
1033
|
if (clean) {
|
|
894
|
-
const
|
|
895
|
-
|
|
896
|
-
|
|
1034
|
+
const deadline = Date.now() + HANDOFF_ADOPT_MS;
|
|
1035
|
+
for (;;) {
|
|
1036
|
+
const recovered = await this.adoptRunningBrowser('after a hand-off');
|
|
1037
|
+
if (recovered !== undefined)
|
|
1038
|
+
return recovered;
|
|
1039
|
+
if (this.disposed || Date.now() >= deadline)
|
|
1040
|
+
break;
|
|
1041
|
+
await new Promise(resolve => setTimeout(resolve, PORT_PROBE_MS));
|
|
1042
|
+
}
|
|
897
1043
|
}
|
|
898
1044
|
throw new Error(clean
|
|
899
1045
|
? `dsh-builtin-browser: ${target} exited immediately after launch (exit code 0). `
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-builtin-browser",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.15",
|
|
4
4
|
"description": "Shared real browser plugin for DeepSeek Harness: install-and-use — a visible native browser the human can take over, driven by the agent over CDP. DOM-level interaction (React/Vue safe), per-task session isolation, cookie persistence (dsh_browser_auth), CAPTCHA detection, batch form fill (dsh_browser_fill), authenticated download, history/replay, action restriction",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -327,7 +327,10 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
327
327
|
sweepAbandonedEphemeralProfiles(profileRoot, detected.kind)
|
|
328
328
|
claimEphemeralProfile(profileDir)
|
|
329
329
|
}
|
|
330
|
-
|
|
330
|
+
// The headless mode rides along so a display-less host (systemd, container, SSH-only server)
|
|
331
|
+
// still gets a working browser instead of "exited immediately after launch" — issue #32.
|
|
332
|
+
adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir,
|
|
333
|
+
undefined, settings.get().browser.headless),
|
|
331
334
|
`will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`)
|
|
332
335
|
}
|
|
333
336
|
}
|
|
@@ -17,6 +17,17 @@ import type { BrowserChannel } from './system-browser.js'
|
|
|
17
17
|
/** Vision/operation strategy the provider prefers when the model can see. */
|
|
18
18
|
export type VisionStrategy = 'auto' | 'nonVisual'
|
|
19
19
|
|
|
20
|
+
/**
|
|
21
|
+
* Whether a launched browser gets a window.
|
|
22
|
+
*
|
|
23
|
+
* Split from {@link VisionStrategy} because these answer different questions: that one is how the
|
|
24
|
+
* agent examines a page, this one is whether the browser has anywhere to draw.
|
|
25
|
+
*/
|
|
26
|
+
export type HeadlessMode = 'auto' | 'headless' | 'windowed'
|
|
27
|
+
|
|
28
|
+
/** Every value {@link HeadlessMode} accepts, for validation and the settings UI. */
|
|
29
|
+
export const HEADLESS_MODES = ['auto', 'headless', 'windowed'] as const
|
|
30
|
+
|
|
20
31
|
/** The full settings document, with every field resolved. */
|
|
21
32
|
export interface BrowserSettings {
|
|
22
33
|
/** Persistent browsing history (visited pages). */
|
|
@@ -45,6 +56,21 @@ export interface BrowserSettings {
|
|
|
45
56
|
/** Which browser binary carries the agent's pages. */
|
|
46
57
|
readonly browser: {
|
|
47
58
|
readonly channel: BrowserChannel
|
|
59
|
+
/**
|
|
60
|
+
* Whether the browser gets a window.
|
|
61
|
+
*
|
|
62
|
+
* `auto` (the default) launches headless when the process has no display — no `DISPLAY` and no
|
|
63
|
+
* `WAYLAND_DISPLAY` — and with a window otherwise. That combination is what makes the plugin
|
|
64
|
+
* work under systemd, in a container, or on an SSH-only server while leaving desktop users
|
|
65
|
+
* with the visible window they expect. `true` forces headless (CI, screenshot-only servers);
|
|
66
|
+
* `false` forces a window, so a misconfigured display fails loudly instead of silently
|
|
67
|
+
* degrading into a browser nobody can see.
|
|
68
|
+
*
|
|
69
|
+
* Reported as issue #32: as a systemd service there is no display, Chromium exits with
|
|
70
|
+
* "could not connect to display", and every `dsh_browser_*` call failed with "exited
|
|
71
|
+
* immediately after launch".
|
|
72
|
+
*/
|
|
73
|
+
readonly headless: HeadlessMode
|
|
48
74
|
}
|
|
49
75
|
/** Whether the agent may read cookies / export login state. */
|
|
50
76
|
readonly credentials: {
|
|
@@ -77,7 +103,7 @@ export const DEFAULT_SETTINGS: BrowserSettings = {
|
|
|
77
103
|
// Bundled by default: it needs nothing installed, and on the desktop the carrier
|
|
78
104
|
// is the sidebar anyway. Choosing a system browser is an explicit opt-in because
|
|
79
105
|
// it starts a real Chrome/Edge with its own profile.
|
|
80
|
-
browser: { channel: 'bundled' },
|
|
106
|
+
browser: { channel: 'bundled', headless: 'auto' },
|
|
81
107
|
credentials: { allowRead: true },
|
|
82
108
|
actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
|
|
83
109
|
}
|
|
@@ -137,6 +163,33 @@ const SETTINGS_WHEN_UNREADABLE: BrowserSettings = {
|
|
|
137
163
|
*/
|
|
138
164
|
export const BROWSER_CHANNELS = ['chrome', 'edge', 'auto', 'bundled', 'sidebar'] as const
|
|
139
165
|
|
|
166
|
+
/**
|
|
167
|
+
* Coerce the headless mode, keeping `auto` when the value is not one of the known choices.
|
|
168
|
+
*
|
|
169
|
+
* Booleans are accepted as a convenience because "headless: true" is what anyone writing this by
|
|
170
|
+
* hand would try first, and rejecting it over a type difference would be pedantry: `true` maps to
|
|
171
|
+
* `headless`, `false` to `windowed`. Anything else is reported rather than silently defaulted,
|
|
172
|
+
* for the same reason as {@link resolveChannel}: a discarded value and an honoured one must not
|
|
173
|
+
* look alike.
|
|
174
|
+
* @param value - the raw value from the settings document.
|
|
175
|
+
* @param warn - where to report a discarded value.
|
|
176
|
+
* @returns a valid mode.
|
|
177
|
+
*/
|
|
178
|
+
function resolveHeadless(value: unknown, warn?: (message: string) => void): HeadlessMode {
|
|
179
|
+
if (value === undefined) return DEFAULT_SETTINGS.browser.headless
|
|
180
|
+
if (value === true) return 'headless'
|
|
181
|
+
if (value === false) return 'windowed'
|
|
182
|
+
if (typeof value === 'string' && (HEADLESS_MODES as readonly string[]).includes(value)) {
|
|
183
|
+
return value as HeadlessMode
|
|
184
|
+
}
|
|
185
|
+
warn?.(
|
|
186
|
+
`dsh-builtin-browser: browser.headless ${JSON.stringify(value)} is not a known mode, so the `
|
|
187
|
+
+ `default "${DEFAULT_SETTINGS.browser.headless}" was used instead. Expected one of: `
|
|
188
|
+
+ `${HEADLESS_MODES.join(', ')} (or a boolean).`,
|
|
189
|
+
)
|
|
190
|
+
return DEFAULT_SETTINGS.browser.headless
|
|
191
|
+
}
|
|
192
|
+
|
|
140
193
|
/**
|
|
141
194
|
* Coerce the browser channel, keeping the default when it is not one of the
|
|
142
195
|
* known choices. A hand-edited typo must not silently select a different browser.
|
|
@@ -227,7 +280,10 @@ export function resolveSettings(raw: unknown, warn?: (message: string) => void):
|
|
|
227
280
|
virtualCursor: bool(ui?.virtualCursor, DEFAULT_SETTINGS.ui.virtualCursor),
|
|
228
281
|
},
|
|
229
282
|
vision: { strategy: vision?.strategy === 'nonVisual' ? 'nonVisual' : DEFAULT_SETTINGS.vision.strategy },
|
|
230
|
-
browser: {
|
|
283
|
+
browser: {
|
|
284
|
+
channel: resolveChannel(browser?.channel, warn),
|
|
285
|
+
headless: resolveHeadless(browser?.headless, warn),
|
|
286
|
+
},
|
|
231
287
|
credentials: {
|
|
232
288
|
// `gate` returns false for anything present-and-not-a-boolean, so an unreadable section
|
|
233
289
|
// is refused here for free: the section itself is the "present but wrong" value.
|
|
@@ -28,6 +28,9 @@
|
|
|
28
28
|
import { readFileSync, rmSync, statSync } from 'node:fs'
|
|
29
29
|
import { existsSync } from 'node:fs'
|
|
30
30
|
import { join } from 'node:path'
|
|
31
|
+
// Type-only: settings-store imports BrowserChannel from here, so a value import would be a cycle.
|
|
32
|
+
// `hasDisplay` lives here instead of there for the same reason — it is a runtime function.
|
|
33
|
+
import type { HeadlessMode } from './settings-store.js'
|
|
31
34
|
|
|
32
35
|
/**
|
|
33
36
|
* How long a killed browser is given to actually exit before the launch proceeds.
|
|
@@ -65,6 +68,21 @@ const CLOSE_GRACE_MS = 6_000
|
|
|
65
68
|
*/
|
|
66
69
|
const PORT_PROBE_MS = 250
|
|
67
70
|
|
|
71
|
+
/**
|
|
72
|
+
* How long to keep trying to adopt a browser after a launcher reported a clean exit.
|
|
73
|
+
*
|
|
74
|
+
* Exit code 0 means the launcher handed the request to an instance already holding this profile —
|
|
75
|
+
* but on Windows that stub exits BEFORE the real browser writes `DevToolsActivePort`. Measured on
|
|
76
|
+
* Chrome 156: stub gone at 300 ms, port file present at 441 ms (issue #33). A single attempt read
|
|
77
|
+
* too early and reported a launch failure for a browser that was starting normally, so this is a
|
|
78
|
+
* retry rather than one shot.
|
|
79
|
+
*
|
|
80
|
+
* 8 s is the reporter's measured-working bound and is generous against that ~150 ms gap: an honest
|
|
81
|
+
* hand-off resolves in well under a second, and a launch that genuinely failed still reaches the
|
|
82
|
+
* error within the same budget the CDP loop already allows.
|
|
83
|
+
*/
|
|
84
|
+
const HANDOFF_ADOPT_MS = 8_000
|
|
85
|
+
|
|
68
86
|
/**
|
|
69
87
|
* Starts a browser process and returns a handle to it.
|
|
70
88
|
*
|
|
@@ -201,6 +219,81 @@ function isBrowserProduct(product: unknown): boolean {
|
|
|
201
219
|
return typeof product === 'string' && /chrome|chromium|edg/i.test(product)
|
|
202
220
|
}
|
|
203
221
|
|
|
222
|
+
/**
|
|
223
|
+
* Whether this process has somewhere to draw a window.
|
|
224
|
+
*
|
|
225
|
+
* The same test Chromium makes: with neither `DISPLAY` nor `WAYLAND_DISPLAY` set it cannot open a
|
|
226
|
+
* window and exits with "could not connect to display". Declared here rather than in
|
|
227
|
+
* settings-store because that module imports from this one, and a value import back would be a
|
|
228
|
+
* cycle; the equivalent export there delegates to this.
|
|
229
|
+
* @param env - the environment to inspect; defaults to the current process.
|
|
230
|
+
* @returns true when a display is advertised.
|
|
231
|
+
*/
|
|
232
|
+
function hasDisplay(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
233
|
+
// Windows and macOS use neither variable, and always have a window server.
|
|
234
|
+
if (process.platform === 'win32' || process.platform === 'darwin') return true
|
|
235
|
+
return (env.DISPLAY ?? '') !== '' || (env.WAYLAND_DISPLAY ?? '') !== ''
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Whether Chromium's own sandbox cannot start here.
|
|
240
|
+
*
|
|
241
|
+
* Two cases, both of which make the browser exit at once rather than degrade: running as root
|
|
242
|
+
* (the sandbox refuses), and running inside a container that lacks the namespaces it needs. The
|
|
243
|
+
* check is deliberately conservative — when it is unsure it answers false, so the default is the
|
|
244
|
+
* sandboxed launch and the weaker mode only happens where it is required.
|
|
245
|
+
* @param env - the environment to inspect; defaults to the current process.
|
|
246
|
+
* @returns true when `--no-sandbox` is required for the browser to start at all.
|
|
247
|
+
*/
|
|
248
|
+
function needsNoSandbox(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
249
|
+
if (process.platform === 'win32') return false
|
|
250
|
+
try {
|
|
251
|
+
if (typeof process.getuid === 'function' && process.getuid() === 0) return true
|
|
252
|
+
} catch {
|
|
253
|
+
// No getuid: not a POSIX process; the container checks below still apply.
|
|
254
|
+
}
|
|
255
|
+
if ((env.container ?? '') !== '') return true
|
|
256
|
+
try {
|
|
257
|
+
if (existsSync('/.dockerenv')) return true
|
|
258
|
+
} catch {
|
|
259
|
+
// An unreadable root is not evidence of a container.
|
|
260
|
+
}
|
|
261
|
+
return false
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Resolve `auto` into a concrete decision, and say why.
|
|
266
|
+
*
|
|
267
|
+
* Chromium refuses to start without a display: with neither `DISPLAY` nor `WAYLAND_DISPLAY` set it
|
|
268
|
+
* exits at once with "could not connect to display", and the caller sees only "exited immediately
|
|
269
|
+
* after launch (exit code 1)". That is the ordinary state of a systemd service, a container, and an
|
|
270
|
+
* SSH-only server — the deployment where a server-side browser is most useful, and the one reported
|
|
271
|
+
* as issue #32: every `dsh_browser_*` call failed, with nothing in the message pointing at the
|
|
272
|
+
* display.
|
|
273
|
+
*
|
|
274
|
+
* `auto` therefore launches headless exactly when there is no display, which leaves desktop and
|
|
275
|
+
* sidebar users with the visible window they expect. An environment override wins over the setting
|
|
276
|
+
* so an operator can fix a running deployment without editing settings: `DSH_BROWSER_HEADLESS=1`
|
|
277
|
+
* forces headless, `=0` forces a window.
|
|
278
|
+
* @param mode - the configured mode.
|
|
279
|
+
* @param env - the environment to inspect; defaults to the current process.
|
|
280
|
+
* @returns whether to launch headless, and a one-line reason for the log.
|
|
281
|
+
*/
|
|
282
|
+
function resolveLaunchMode(
|
|
283
|
+
mode: HeadlessMode,
|
|
284
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
285
|
+
): { readonly headless: boolean; readonly why: string } {
|
|
286
|
+
const override = env.DSH_BROWSER_HEADLESS
|
|
287
|
+
if (override === '1' || override === 'true') return { headless: true, why: 'DSH_BROWSER_HEADLESS' }
|
|
288
|
+
if (override === '0' || override === 'false') return { headless: false, why: 'DSH_BROWSER_HEADLESS' }
|
|
289
|
+
if (mode === 'headless') return { headless: true, why: 'browser.headless = headless' }
|
|
290
|
+
if (mode === 'windowed') return { headless: false, why: 'browser.headless = windowed' }
|
|
291
|
+
const display = hasDisplay(env)
|
|
292
|
+
return display
|
|
293
|
+
? { headless: false, why: 'a display is available' }
|
|
294
|
+
: { headless: true, why: 'no DISPLAY or WAYLAND_DISPLAY' }
|
|
295
|
+
}
|
|
296
|
+
|
|
204
297
|
/**
|
|
205
298
|
* Whether a target URL is one of the blanks a browser opens by itself.
|
|
206
299
|
*
|
|
@@ -494,6 +587,11 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
|
|
|
494
587
|
private readonly extraArgs: readonly string[] = [],
|
|
495
588
|
private readonly ephemeralDir?: string,
|
|
496
589
|
private readonly launcher: BrowserLauncher = defaultLauncher,
|
|
590
|
+
/**
|
|
591
|
+
* Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
|
|
592
|
+
* and why a display-less host needs headless at all (issue #32).
|
|
593
|
+
*/
|
|
594
|
+
private readonly headlessMode: HeadlessMode = 'auto',
|
|
497
595
|
) {}
|
|
498
596
|
|
|
499
597
|
/** Which product this host would drive (for diagnostics). */
|
|
@@ -667,6 +765,7 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
|
|
|
667
765
|
// after launch (exit code 0)" that required killing seven processes by hand.
|
|
668
766
|
const adopted = await this.adoptRunningBrowser('before launch')
|
|
669
767
|
if (adopted !== undefined) return adopted
|
|
768
|
+
const launch = resolveLaunchMode(this.headlessMode)
|
|
670
769
|
const args = [
|
|
671
770
|
'--remote-debugging-port=0',
|
|
672
771
|
`--user-data-dir=${this.profileDir}`,
|
|
@@ -677,9 +776,40 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
|
|
|
677
776
|
'--disable-features=Translate,MediaRouter',
|
|
678
777
|
'--disable-session-crashed-bubble',
|
|
679
778
|
'--hide-crash-restore-bubble',
|
|
779
|
+
// Headless only where there is nothing to draw on. `--headless=new` rather than the legacy
|
|
780
|
+
// flag: the new mode behaves like a windowed browser, which matters because every command
|
|
781
|
+
// here was written and measured against one — including CDP input, which Chromium silently
|
|
782
|
+
// drops for a view it believes has no display surface. `--disable-gpu` and
|
|
783
|
+
// `--disable-dev-shm-usage` are what make that mode usable on a server: no GPU, and a
|
|
784
|
+
// /dev/shm far smaller than a desktop. See resolveLaunchMode for why this is conditional.
|
|
785
|
+
...launch.headless ? ['--headless=new', '--disable-gpu', '--disable-dev-shm-usage'] : [],
|
|
680
786
|
...this.extraArgs,
|
|
681
|
-
|
|
787
|
+
// NOT `about:blank`. Every page this plugin drives is created by `Target.createTarget` when a
|
|
788
|
+
// session first needs one (`buildSession`, which adopts a blank if the browser opened one and
|
|
789
|
+
// creates one otherwise), so a startup page is a tab nobody asked for and nobody closes: the
|
|
790
|
+
// tab strip showed `about:blank` next to the real page while `dsh_browser_list_tabs` reported
|
|
791
|
+
// only the real one. Reported as issue #33, banner and all.
|
|
792
|
+
//
|
|
793
|
+
// `--no-startup-window` keeps the browser alive with no window and no initial page; measured
|
|
794
|
+
// by the reporter on Chrome 156 as writing DevToolsActivePort in 599 ms, answering
|
|
795
|
+
// `/json/version`, listing two extension targets and no page, and then creating windows
|
|
796
|
+
// normally through `Target.createTarget`. A browser that does start a blank despite this is
|
|
797
|
+
// still handled: `normalizeBlankPages` closes the surplus and `buildSession` adopts the rest.
|
|
798
|
+
'--no-startup-window',
|
|
682
799
|
]
|
|
800
|
+
// Chromium's own sandbox cannot start in some of these environments — running as root, or
|
|
801
|
+
// inside a container without the namespaces it needs — and it exits rather than degrading.
|
|
802
|
+
// Only then is the sandbox dropped, and never silently: a setting that weakens process
|
|
803
|
+
// isolation must be visible in the log, because whoever reads it has to be able to disagree.
|
|
804
|
+
if (launch.headless && needsNoSandbox()) {
|
|
805
|
+
args.splice(args.length - 2, 0, '--no-sandbox')
|
|
806
|
+
process.stderr.write('[dsh-browser] launching with --no-sandbox: '
|
|
807
|
+
+ 'this process runs as root or in a container, where the Chromium sandbox cannot start\n')
|
|
808
|
+
}
|
|
809
|
+
if (launch.headless) {
|
|
810
|
+
process.stderr.write(`[dsh-browser] launching headless (${launch.why}); `
|
|
811
|
+
+ 'the browser has no window but every tool works the same\n')
|
|
812
|
+
}
|
|
683
813
|
// A browser from a previous attempt may still be running with this same
|
|
684
814
|
// --user-data-dir. On Windows the new one would merely hand off to it and exit, and that
|
|
685
815
|
// exit would then be treated as the launch failing.
|
|
@@ -880,9 +1010,21 @@ export class SystemBrowserViewHost implements ElectronBrowserViewHost {
|
|
|
880
1010
|
// Exit code 0 IS the hand-off: the request went to an instance already holding this profile,
|
|
881
1011
|
// so that instance is our browser and it is running right now. Adopting it turns the
|
|
882
1012
|
// reported "kill the leftovers by hand, on every restart" into a call that just works.
|
|
1013
|
+
//
|
|
1014
|
+
// Adopted with a bounded RETRY, because on Windows the launcher stub exits before the browser
|
|
1015
|
+
// has written its port file: measured 300 ms to exit against 441 ms for DevToolsActivePort.
|
|
1016
|
+
// One attempt therefore read too early and reported "exited immediately after launch" for a
|
|
1017
|
+
// browser that was starting normally — reported as issue #33, where the reporter's own
|
|
1018
|
+
// retry loop fixed it. 8 s at 250 ms is their measured-working bound and is generous against
|
|
1019
|
+
// the ~150 ms gap, without turning a genuinely failed launch into a slow failure.
|
|
883
1020
|
if (clean) {
|
|
884
|
-
const
|
|
885
|
-
|
|
1021
|
+
const deadline = Date.now() + HANDOFF_ADOPT_MS
|
|
1022
|
+
for (;;) {
|
|
1023
|
+
const recovered = await this.adoptRunningBrowser('after a hand-off')
|
|
1024
|
+
if (recovered !== undefined) return recovered
|
|
1025
|
+
if (this.disposed || Date.now() >= deadline) break
|
|
1026
|
+
await new Promise(resolve => setTimeout(resolve, PORT_PROBE_MS))
|
|
1027
|
+
}
|
|
886
1028
|
}
|
|
887
1029
|
throw new Error(
|
|
888
1030
|
clean
|