Skip to content

Commit d4d2b35

Browse files
committed
Exercise the real OpenCLI Browser Bridge on Windows and Linux
1 parent 20af24e commit d4d2b35

3 files changed

Lines changed: 246 additions & 0 deletions

File tree

‎.github/workflows/contracts.yml‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,3 +235,44 @@ jobs:
235235
platform-evidence
236236
target/surefire-reports
237237
if-no-files-found: error
238+
239+
240+
browser-bridge:
241+
name: Real Browser Bridge (${{ matrix.os }})
242+
if: github.ref_name == 'feature/REQ-20261118-wandl-opencli-contracts-20'
243+
strategy:
244+
fail-fast: false
245+
matrix:
246+
os: [ubuntu-latest, windows-latest]
247+
runs-on: ${{ matrix.os }}
248+
timeout-minutes: 15
249+
defaults:
250+
run:
251+
shell: bash
252+
steps:
253+
- uses: actions/checkout@v7
254+
- uses: actions/setup-java@v5
255+
with:
256+
distribution: temurin
257+
java-version: '17'
258+
cache: maven
259+
- uses: actions/setup-python@v7
260+
with:
261+
python-version: '3.13'
262+
- uses: actions/setup-node@v4
263+
with:
264+
node-version: '24.18.0'
265+
- name: Install the published OpenCLI in the runner's temporary directory
266+
run: npm install --prefix "$RUNNER_TEMP/opencli-browser-cli" --ignore-scripts --no-audit --no-fund @jackwener/opencli@1.8.8
267+
- name: Exercise the real Chrome extension against the loopback daemon
268+
run: |
269+
python scripts/run_browser_bridge_contracts.py \
270+
--cli-entry "$RUNNER_TEMP/opencli-browser-cli/node_modules/@jackwener/opencli/dist/src/main.js" \
271+
--evidence browser-bridge-evidence -- mvn
272+
- name: Upload real Bridge evidence
273+
if: always()
274+
uses: actions/upload-artifact@v7
275+
with:
276+
name: browser-bridge-${{ matrix.os }}-${{ github.sha }}
277+
path: browser-bridge-evidence
278+
if-no-files-found: error

‎openspec/changes/harden-opencli-process-lifecycle/tasks.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,3 +142,7 @@ Java 8 `1310c54`、Java 17 `1946d9f`、Java 21 `89da70e` 为修改前基线。
142142
| 21 | `e4022f1c7a3cf9789e347270143ec5f013f58f99` | [Ubuntu、Intel 与 Apple Silicon macOS、Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44410064678) |
143143

144144
清理结果区分直属进程与未知后代。若直属进程退出、读取线程排空,可报告 `ROOT_EXIT_CONFIRMED`,同时将 `descendantsExitConfirmed` 保持为 false。无法确认读取线程排空时返回 `UNCONFIRMED`。真实 Browser Bridge 的共享 daemon 与 Chrome 存活证据来自 macOS 回环联调,Windows/Linux 平台工件使用真实 JVM 子进程夹具。3.2 继续记录跨平台真实 Bridge 验收和未追踪后代的能力边界。
145+
146+
### Windows 与 Linux 的真实 Browser Bridge 验收
147+
148+
在独立 runner 使用锁定版本的 OpenCLI、扩展归档及 Chrome for Testing。真实 Node daemon 和临时 Chrome profile 只访问回环页面。沿用 `OpenCliBrowserBridgeIT` 验证类型结果、查询、绑定标签页及有界采集。验证完成后检查同一个 daemon 和 Chrome 进程仍在运行,上传本次 Surefire XML。缺报告、跳过或任一进程异常退出均判失败。
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
"""Run the Java Browser Bridge contract against an isolated real browser."""
2+
import argparse
3+
from hashlib import sha256
4+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
5+
import json
6+
import os
7+
from pathlib import Path
8+
import shutil
9+
import subprocess
10+
import sys
11+
import tempfile
12+
import threading
13+
import time
14+
from urllib.error import URLError
15+
from urllib.request import Request, urlopen
16+
from zipfile import ZipFile
17+
18+
import contract_report
19+
20+
21+
OPENCLI_VERSION = '1.8.8'
22+
EXTENSION_VERSION = '1.0.24'
23+
EXTENSION_SHA = 'bad9163f32a66224404e302f52f35391672341d2bd0bf30c8bbaae3c6e6e246c'
24+
CHROME_VERSION = '158.0.8127.18'
25+
DAEMON_STATUS = 'http://127.0.0.1:19825/status'
26+
SUITE = 'io.github.easy4j.opencli.contract.OpenCliBrowserBridgeIT'
27+
PAGE = b"""<!doctype html><title>Bridge fixture</title><main><button id="go">Continue</button></main>
28+
<script>
29+
const capture = setInterval(() => fetch('/api/items'), 250);
30+
setTimeout(() => clearInterval(capture), 120000);
31+
</script>"""
32+
33+
34+
class FixtureHandler(BaseHTTPRequestHandler):
35+
def do_GET(self):
36+
if self.path == '/api/items':
37+
body, content_type = b'{"items":[{"id":17}]}', 'application/json'
38+
else:
39+
body, content_type = PAGE, 'text/html; charset=utf-8'
40+
self.send_response(200)
41+
self.send_header('Content-Type', content_type)
42+
self.send_header('Content-Length', str(len(body)))
43+
self.end_headers()
44+
self.wfile.write(body)
45+
46+
def log_message(self, *_):
47+
pass
48+
49+
50+
def download_zip(url, directory, expected_sha=None):
51+
archive = directory.with_suffix('.zip')
52+
with urlopen(url, timeout=60) as response, archive.open('wb') as output:
53+
shutil.copyfileobj(response, output)
54+
if expected_sha and sha256(archive.read_bytes()).hexdigest() != expected_sha:
55+
raise RuntimeError(f'Artifact digest mismatch for {url}')
56+
with ZipFile(archive) as zipped:
57+
zipped.extractall(directory)
58+
if os.name != 'nt':
59+
for entry in zipped.infolist():
60+
if entry.external_attr >> 16 & 0o111:
61+
(directory / entry.filename).chmod(0o755)
62+
63+
64+
def chrome_executable(root):
65+
platform = {'linux': 'linux64', 'win32': 'win64'}[sys.platform]
66+
download_zip(
67+
f'https://storage.googleapis.com/chrome-for-testing-public/{CHROME_VERSION}/{platform}/chrome-{platform}.zip',
68+
root / 'chrome',
69+
)
70+
return root / 'chrome' / f'chrome-{platform}' / ('chrome.exe' if os.name == 'nt' else 'chrome')
71+
72+
73+
def daemon_status():
74+
with urlopen(Request(DAEMON_STATUS, headers={'X-OpenCLI': '1'}), timeout=1) as response:
75+
return json.load(response)
76+
77+
78+
def wait_for_bridge(daemon, browser):
79+
deadline = time.monotonic() + 30
80+
while time.monotonic() < deadline:
81+
if daemon.poll() is not None or browser.poll() is not None:
82+
raise RuntimeError('The isolated daemon or Chrome exited before the extension connected')
83+
try:
84+
status = daemon_status()
85+
except URLError:
86+
time.sleep(0.25)
87+
continue
88+
if status.get('pid') != daemon.pid:
89+
raise RuntimeError('The Bridge endpoint belongs to a different daemon')
90+
if status.get('extensionConnected'):
91+
if (status.get('daemonVersion'), status.get('extensionVersion')) != (OPENCLI_VERSION, EXTENSION_VERSION):
92+
raise RuntimeError('The connected Bridge versions differ from the pinned versions')
93+
return status
94+
time.sleep(0.25)
95+
raise RuntimeError('The extension did not connect to the isolated daemon')
96+
97+
98+
def stop(process):
99+
if process is None or process.poll() is not None:
100+
return
101+
process.terminate()
102+
try:
103+
process.wait(timeout=8)
104+
except subprocess.TimeoutExpired:
105+
process.kill()
106+
process.wait()
107+
108+
109+
def execute(args, root, evidence):
110+
extension = root / 'extension'
111+
download_zip(f'https://github.com/jackwener/OpenCLI/releases/download/v{OPENCLI_VERSION}/'
112+
f'opencli-extension-v{EXTENSION_VERSION}.zip', extension, EXTENSION_SHA)
113+
chrome = args.chrome or chrome_executable(root)
114+
node = shutil.which('node')
115+
if not node:
116+
raise RuntimeError('Node executable is unavailable')
117+
home = root / 'home'
118+
home.mkdir()
119+
env = dict(os.environ, HOME=str(home), USERPROFILE=str(home),
120+
OPENCLI_CONFIG_DIR=str(root / 'config'), OPENCLI_CACHE_DIR=str(root / 'cache'),
121+
OPENCLI_INSTALLED_NODE=node, OPENCLI_INSTALLED_ENTRY=str(args.cli_entry))
122+
for name in ('OPENCLI_DAEMON_PORT', 'OPENCLI_CDP_ENDPOINT', 'OPENCLI_CDP_TARGET'):
123+
env.pop(name, None)
124+
125+
# Use the upstream loopback port without changing the published binaries.
126+
try:
127+
daemon_status()
128+
except URLError:
129+
pass
130+
else:
131+
raise RuntimeError('An existing OpenCLI daemon already uses the fixture port')
132+
133+
reports = Path('target/surefire-reports')
134+
xml = reports / f'TEST-{SUITE}.xml'
135+
xml.unlink(missing_ok=True)
136+
java = subprocess.run(['java', '-version'], check=True, capture_output=True, text=True)
137+
maven = subprocess.run([*args.maven, '-version'], check=True, capture_output=True, text=True)
138+
daemon = browser = None
139+
with ThreadingHTTPServer(('127.0.0.1', 0), FixtureHandler) as server:
140+
threading.Thread(target=server.serve_forever, daemon=True).start()
141+
url = f'http://127.0.0.1:{server.server_port}/fixture.html'
142+
env['OPENCLI_BRIDGE_FIXTURE_URL'] = url
143+
try:
144+
with (evidence / 'daemon.log').open('w') as log:
145+
daemon = subprocess.Popen([node, str(args.cli_entry.with_name('daemon.js'))],
146+
cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT)
147+
chrome_args = [
148+
'--headless=new', '--no-first-run', '--no-default-browser-check',
149+
'--disable-background-networking', '--disable-component-update',
150+
'--disable-sync', '--remote-debugging-port=0', '--no-proxy-server',
151+
'--host-resolver-rules=MAP localhost 127.0.0.1, MAP * ~NOTFOUND',
152+
'--user-data-dir=' + str(root / 'profile'),
153+
'--disable-extensions-except=' + str(extension), '--load-extension=' + str(extension),
154+
]
155+
if sys.platform == 'darwin':
156+
chrome_args.append('--use-mock-keychain')
157+
with (evidence / 'chrome.log').open('w') as log:
158+
browser = subprocess.Popen([str(chrome), *chrome_args, url.replace('/fixture', '/bound-fixture')],
159+
cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT)
160+
wait_for_bridge(daemon, browser)
161+
with (evidence / 'maven.log').open('w') as log:
162+
result = subprocess.run([*args.maven, '-B', '--no-transfer-progress', '-Dtest=OpenCliBrowserBridgeIT', 'test'],
163+
env=env, stdout=log, stderr=subprocess.STDOUT, timeout=180)
164+
status = wait_for_bridge(daemon, browser)
165+
(evidence / 'bridge.json').write_text(json.dumps({
166+
'daemonPid': daemon.pid, 'chromePid': browser.pid, 'chromeVersion': CHROME_VERSION,
167+
'opencliVersion': status['daemonVersion'], 'extensionVersion': status['extensionVersion'],
168+
}) + '\n', encoding='utf-8')
169+
finally:
170+
stop(browser)
171+
stop(daemon)
172+
server.shutdown()
173+
174+
if xml.exists():
175+
shutil.copyfile(xml, evidence / xml.name)
176+
report = contract_report.build_report(
177+
evidence, head=subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),
178+
branch=os.environ.get('GITHUB_REF_NAME') or subprocess.check_output(
179+
['git', 'branch', '--show-current'], text=True).strip(),
180+
java_version=(java.stdout + java.stderr).strip(), maven_version=(maven.stdout + maven.stderr).strip(),
181+
exit_code=result.returncode, required_suites={'real-execution': [SUITE]},
182+
)
183+
(evidence / 'report.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
184+
print(json.dumps(report['layers']['real-execution']))
185+
return 0 if report['status'] == 'PASS' else 1
186+
187+
188+
def main():
189+
parser = argparse.ArgumentParser(description=__doc__)
190+
parser.add_argument('--cli-entry', required=True, type=lambda path: Path(path).resolve())
191+
parser.add_argument('--chrome', type=lambda path: Path(path).resolve())
192+
parser.add_argument('--evidence', required=True, type=lambda path: Path(path).resolve())
193+
parser.add_argument('maven', nargs='+')
194+
args = parser.parse_args()
195+
args.evidence.mkdir(parents=True, exist_ok=False)
196+
with tempfile.TemporaryDirectory(prefix='opencli-bridge-', ignore_cleanup_errors=True) as root:
197+
return execute(args, Path(root), args.evidence)
198+
199+
200+
if __name__ == '__main__':
201+
sys.exit(main())

0 commit comments

Comments
 (0)