源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Creator App Tests / PR Spam Gate (push) Skipped
Frontend Tests / PR Spam Gate (push) Skipped
NPM Format (website & console) / PR Spam Gate (push) Skipped
Pre-commit Checks / PR Spam Gate (push) Skipped
QwenPaw Creator Plugin Release / check-version (push) Canceled after 0s
QwenPaw Creator Plugin Release / upload-oss (push) Canceled after 0s
Tests / PR Spam Gate (push) Skipped
CodeQL / CodeQL (python) (push) Canceled after 0s
CodeQL / CodeQL (typescript) (push) Canceled after 0s
Creator App Tests / Creator Backend Tests (push) Canceled after 0s
Creator App Tests / Creator UI Build & Tests (push) Canceled after 0s
E2E Smoke Tests / Playwright UI Smoke (push) Canceled after 0s
Frontend Tests / Detect console changes (push) Canceled after 0s
NPM Format (website & console) / website format check (push) Canceled after 0s
NPM Format (website & console) / console format check (push) Canceled after 0s
Pre-commit Checks / Pre-commit (push) Canceled after 0s
QwenPaw Data Plugin Release / check-version (push) Canceled after 0s
Tests / Detect code changes (push) Canceled after 0s
Frontend Tests / Vitest Unit Tests (push) Canceled after 0s
Frontend Tests / Frontend Summary (push) Canceled after 0s
QwenPaw Data Plugin Release / upload-oss (push) Canceled after 0s
Tests / Maintainer Approval (push) Canceled after 0s
Tests / Unit Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - fallback (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p2 (push) Canceled after 0s
Tests / Coverage Report (push) Canceled after 0s
Tests / Test Summary (push) Canceled after 0s

This commit is contained in:
agent-radar committed 2026-09-01 20:01:50 +08:00
commit 1a3a4ccde1
4652 files changed
+1891610

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""Chrome browser integration plugin."""
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""Chrome plugin HTTP API package."""
+173
View File
@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*-
"""HTTP-only Chrome extension installation and status routes."""
# pylint: disable=relative-beyond-top-level
from __future__ import annotations
import asyncio
import json
import secrets
import threading
from pathlib import Path
from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, ConfigDict
from qwenpaw.browser.control_link.chrome.bridge import (
NMBridgeError,
get_nm_bridge,
)
from ..extension_setup import (
CHROME_EXTENSIONS_URL,
atomic_write_json_0600,
extension_install_status,
BridgeEndpointUnavailable,
InstallModeError,
open_extension_folder,
require_bridge_endpoint,
setup_extension_files,
)
from ..transport.state import get_nm_bridge_route_state
api_router = APIRouter(tags=["chrome"])
router = api_router
DEFAULT_CONFIG_PATH = Path.home() / ".qwenpaw" / "nm-bridge.json"
_state = get_nm_bridge_route_state()
_SETUP_LOCK = threading.Lock()
class ExtensionSetupRequest(BaseModel):
"""Request for installing or repairing the local Chrome extension."""
model_config = ConfigDict(extra="forbid")
install_mode: str = "unpacked"
reset: bool = False
def _read_existing_token(config_path: Path) -> str | None:
"""Return the installed core bridge token, if one is available."""
if not config_path.exists():
return None
try:
config = json.loads(config_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
token = str(config.get("token") or "").strip()
return token or None
def _write_private_bridge_config(
config_path: Path,
*,
token: str,
ws_url: str,
) -> None:
"""Atomically update the configuration shared with the core WS handler."""
atomic_write_json_0600(config_path, {"ws_url": ws_url, "token": token})
def configure_nm_bridge(
*,
token: str | None = None,
config_path: Path = DEFAULT_CONFIG_PATH,
) -> str:
"""Write the Native Messaging host's single backend configuration."""
ws_url = require_bridge_endpoint()
path = Path(config_path)
if token is not None and not token.strip():
raise ValueError("Native Messaging bridge token must not be empty")
token = token or _read_existing_token(path) or secrets.token_urlsafe(32)
path.parent.mkdir(parents=True, exist_ok=True)
_write_private_bridge_config(path, token=token, ws_url=ws_url)
_state.token = token
_state.ws_url = ws_url
_state.config_path = path
return token
async def get_extension_status() -> dict[str, Any]:
"""Return install state plus the core endpoint the host will contact."""
status = extension_install_status()
bridge_endpoint = require_bridge_endpoint()
configured_endpoint = status.pop("ws_url", None)
return {
**status,
"bridge_endpoint": bridge_endpoint,
"configured_endpoint": configured_endpoint,
"bridge_endpoint_stale": configured_endpoint != bridge_endpoint,
}
def _setup_extension_files_serially(
*,
install_mode: str,
reset: bool,
) -> dict[str, str | bool]:
"""Run one local setup operation at a time within this backend process."""
with _SETUP_LOCK:
return setup_extension_files(
install_mode=install_mode,
reset=reset,
)
@api_router.get("/install-status")
async def extension_status() -> dict[str, Any]:
"""Return Chrome extension installation status."""
return await get_extension_status()
@api_router.post("/setup")
async def extension_setup(
request: ExtensionSetupRequest,
) -> dict[str, Any]:
"""Install or repair the extension and its Native Messaging host."""
try:
result = await asyncio.to_thread(
_setup_extension_files_serially,
install_mode=request.install_mode,
reset=request.reset,
)
except InstallModeError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
except BridgeEndpointUnavailable as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return {**result, **await get_extension_status()}
@api_router.post("/open-chrome-extensions")
async def open_chrome_extensions() -> dict[str, str | bool | None]:
"""Ask the connected extension to open Chrome's extensions manager."""
bridge = get_nm_bridge()
if not bridge.is_connected():
return {
"opened": False,
"url": CHROME_EXTENSIONS_URL,
"error": "Chrome extension is not connected.",
}
try:
result = await bridge.request(
"extension.open_extensions_manager",
timeout=5.0,
)
except NMBridgeError:
return {
"opened": False,
"url": CHROME_EXTENSIONS_URL,
"error": "Chrome extension could not open the extensions page.",
}
if not isinstance(result, dict) or result.get("opened") is not True:
return {
"opened": False,
"url": CHROME_EXTENSIONS_URL,
"error": "Chrome extension could not open the extensions page.",
}
return {"opened": True, "url": CHROME_EXTENSIONS_URL, "error": None}
@api_router.post("/open-extension-folder")
async def open_local_extension_folder() -> dict[str, str | bool | None]:
"""Open the unpacked extension directory."""
return open_extension_folder()
@@ -0,0 +1,46 @@
{
"manifest_version": 3,
"name": "QwenPaw",
"version": "0.1.1",
"description": "Connect QwenPaw to this Chrome browser.",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtfrrReREyZU2GsWs55nzHlNhI9fQWTmyytFrGxLYSl9buVhPNIRqIggeJrVY1y3e4+UI8QAvItuPO7XdcT3zHW5XKVT+ZtnLjWmAFFKUBA3MlsAu5rBtNJeiJc15XpAJokuJHq+vb7bPi6sW6wmieexAa3I6pxn4C0bZEegrQ9g3sunqDM/ihd5mi3Im3G9IYnmsKioMsOP6tj08d4znDCavjazgpI9ImoX/D3JBxR5pEBYC7Ia+nv8ipY/H/ZqDWZ+X3qn5fsQoClYTZGUUFbQ8ckif1svMnHe6LoNuNyAy4hVSOTV3k707N5+9inLgK01o3E7XgkULpwiEW+ny+QIDAQAB",
"permissions": [
"nativeMessaging",
"debugger",
"tabs",
"activeTab",
"alarms",
"storage",
"tabGroups",
"webNavigation"
],
"host_permissions": [
"<all_urls>"
],
"externally_connectable": {
"matches": [
"http://localhost:*/*",
"http://127.0.0.1:*/*",
"http://[::1]:*/*"
]
},
"background": {
"service_worker": "service_worker.js"
},
"icons": {
"16": "icons/logo-16.png",
"32": "icons/logo-32.png",
"48": "icons/logo-48.png",
"128": "icons/logo-128.png"
},
"action": {
"default_title": "QwenPaw",
"default_popup": "popup/popup.html",
"default_icon": {
"16": "icons/logo-16.png",
"32": "icons/logo-32.png",
"48": "icons/logo-48.png",
"128": "icons/logo-128.png"
}
}
}
@@ -0,0 +1,97 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>QwenPaw</title>
<style>
body {
box-sizing: border-box;
width: 280px;
margin: 0;
padding: 14px;
color: #172033;
background: #ffffff;
font: 13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
h1 {
margin: 0;
font-size: 15px;
font-weight: 650;
letter-spacing: 0;
}
.header {
display: flex;
align-items: center;
gap: 10px;
margin: 0 0 12px;
}
.logo {
width: 32px;
height: 32px;
border-radius: 8px;
}
.subtitle {
margin: 2px 0 0;
color: #64748b;
font-size: 12px;
}
dl {
display: grid;
grid-template-columns: 92px 1fr;
gap: 8px 10px;
margin: 0;
}
dt {
color: #64748b;
}
dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.status {
display: inline-flex;
align-items: center;
gap: 6px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 999px;
background: #dc2626;
}
.dot[data-connected="true"] {
background: #059669;
}
</style>
</head>
<body>
<div class="header">
<img class="logo" src="../icons/logo-48.png" alt="">
<div>
<h1>QwenPaw</h1>
<p class="subtitle">Connects this browser to QwenPaw.</p>
</div>
</div>
<dl>
<dt>Status</dt>
<dd class="status"><span id="dot" class="dot"></span><span id="status">Checking</span></dd>
<dt>QwenPaw tabs</dt>
<dd id="tabs">0</dd>
<dt>Version</dt>
<dd id="version">-</dd>
</dl>
<script src="popup.js"></script>
</body>
</html>
@@ -0,0 +1,25 @@
const SOURCE = "qwenpaw-chrome-popup";
function setText(id, text) {
const el = document.getElementById(id);
if (el) {
el.textContent = text;
}
}
chrome.runtime.sendMessage(
{ source: SOURCE, method: "status.get" },
(response) => {
const status = response && response.connected ? "Connected" : "Not connected";
const dot = document.getElementById("dot");
if (dot) {
dot.dataset.connected = response && response.connected ? "true" : "false";
}
setText("status", status);
setText(
"tabs",
String(response && Number.isFinite(response.managedTabsCount) ? response.managedTabsCount : 0),
);
setText("version", response && response.version ? response.version : "-");
},
);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
# -*- coding: utf-8 -*-
"""Fallback build fingerprint for source-tree Native Messaging execution."""
BUILD_FINGERPRINT: dict[str, str | None] = {
"commit": "unknown",
"builtAt": None,
}
@@ -0,0 +1,140 @@
# -*- coding: utf-8 -*-
"""Hello handshake helpers for chrome backend connections."""
from __future__ import annotations
import asyncio
import json
from typing import Any
try:
from .protocol_mirror import PROTOCOL_VERSION, contract_snapshot
except ImportError:
from protocol_mirror import PROTOCOL_VERSION, contract_snapshot
try:
from .build_fingerprint import BUILD_FINGERPRINT
except ImportError:
try:
from build_fingerprint import BUILD_FINGERPRINT
except ImportError:
BUILD_FINGERPRINT = {"commit": "unknown", "builtAt": None}
class HandshakeError(RuntimeError):
"""Raised when a backend hello handshake fails."""
class HandshakePermanentError(HandshakeError):
"""Raised when the core rejects hello and retrying cannot help."""
def __init__(
self,
message: str,
*,
code: str = "",
expected_min: int | None = None,
expected: int | None = None,
actual: int | None = None,
advice: str = "",
raw_message: dict[str, Any] | None = None,
) -> None:
super().__init__(message)
self.code = code
self.expected_min = expected_min
self.expected = expected
self.actual = actual
self.advice = advice
self.raw_message = raw_message or {}
class HandshakeTransientError(HandshakeError):
"""Raised when retrying the hello handshake may succeed."""
def _protocol_value(message: dict[str, Any], key: str) -> int | None:
value = message.get(key)
return value if isinstance(value, int) else None
def _rejection_advice(
code: str,
expected_min: int | None,
expected: int | None,
actual: int | None,
) -> str:
if code == "BROWSER_PROTOCOL_VERSION_MISMATCH":
if (
actual is not None
and expected_min is not None
and actual < expected_min
):
return "Please upgrade the extension to a compatible version."
if actual is not None and expected is not None and actual > expected:
return "Please upgrade QwenPaw core to a compatible version."
return (
"Please upgrade the extension or QwenPaw core to compatible "
"versions."
)
return "QwenPaw core permanently rejected the Native Messaging hello."
async def send_hello(
ws: Any,
entry_id: str,
protocol_version: int = PROTOCOL_VERSION,
) -> None:
"""Send bridge hello metadata to a backend websocket."""
# Contract and build metadata let the core compare this installed host
# without changing the existing protocol-version handshake fields.
await ws.send(
json.dumps(
{
"type": "hello",
"entryId": entry_id,
"protocolVersion": protocol_version,
"contract": contract_snapshot(),
"build": dict(BUILD_FINGERPRINT),
},
separators=(",", ":"),
),
)
async def wait_hello_ack(ws: Any, timeout: float = 5.0) -> dict:
"""Wait for and validate hello_ack."""
try:
raw = await asyncio.wait_for(ws.recv(), timeout=timeout)
except asyncio.TimeoutError as exc:
raise HandshakeTransientError("Hello ack timeout") from exc
message = json.loads(
raw.decode("utf-8") if isinstance(raw, bytes) else raw,
)
if message.get("type") != "hello_ack" or message.get("status") != "ok":
code = str(message.get("code") or "")
expected_min = _protocol_value(
message,
"expected_min_protocol_version",
)
expected = _protocol_value(message, "expected_protocol_version")
actual = _protocol_value(message, "actual_protocol_version")
raise HandshakePermanentError(
f"Hello rejected: {message}",
code=code,
expected_min=expected_min,
expected=expected,
actual=actual,
advice=_rejection_advice(code, expected_min, expected, actual),
raw_message=message,
)
return message
__all__ = [
"HandshakeError",
"HandshakePermanentError",
"HandshakeTransientError",
"send_hello",
"wait_hello_ack",
]
@@ -0,0 +1,493 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Single-backend Native Messaging dumb pipe for QwenPaw."""
from __future__ import annotations
import asyncio
import inspect
import json
import os
import re
import struct
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Awaitable, BinaryIO, Callable
try:
from .handshake import (
HandshakePermanentError,
send_hello,
wait_hello_ack,
)
except ImportError:
from handshake import HandshakePermanentError, send_hello, wait_hello_ack
try:
from .protocol_mirror import (
NM_CLOSE_FRAME_PROTOCOL,
NM_CLOSE_INBOUND_TOO_LARGE,
NM_CLOSE_INTERNAL_ERROR,
NM_CLOSE_STDIN_EOF,
NM_MAX_INBOUND_BYTES,
NM_MAX_OUTBOUND_BYTES,
close_code_catalog,
)
except ImportError:
from protocol_mirror import (
NM_CLOSE_FRAME_PROTOCOL,
NM_CLOSE_INBOUND_TOO_LARGE,
NM_CLOSE_INTERNAL_ERROR,
NM_CLOSE_STDIN_EOF,
NM_MAX_INBOUND_BYTES,
NM_MAX_OUTBOUND_BYTES,
close_code_catalog,
)
DEFAULT_CONFIG_PATH = Path.home() / ".qwenpaw" / "nm-bridge.json"
DEFAULT_CONNECT_RETRY_SECONDS = 120.0
INITIAL_CONNECT_RETRY_DELAY_SECONDS = 0.5
MAX_CONNECT_RETRY_DELAY_SECONDS = 5.0
LOG_PATH = Path.home() / ".qwenpaw" / "logs" / "nm-host.log"
LOG_MAX_BYTES = 8 * 1024 * 1024
_DRAIN_CHUNK_BYTES = 64 * 1024
_ID_RE = re.compile(rb'"id"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+)')
# Chrome Native Messaging limits are imported from protocol_mirror. They are
# protocol facts, not tunables: Chrome kills this process above its hard wall.
class InvalidTokenError(ValueError):
"""Raised when Native Messaging configuration has no bearer token."""
class NativeMessageTooLargeError(ValueError):
"""Raised when a core message exceeds Chrome's host-to-extension limit."""
class InboundFrameTooLargeError(ValueError):
"""Raised after an oversized inbound frame has been drained."""
def __init__(self, size: int, head: bytes) -> None:
super().__init__("Native Messaging frame exceeds maximum size")
self.size = size
self.head = head
def _dumps(message: dict[str, Any]) -> str:
return json.dumps(message, separators=(",", ":"))
def log_diagnostic(text: str) -> None:
"""Persist a flushed diagnostic line without changing bridge behavior."""
try:
LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
if LOG_PATH.exists() and LOG_PATH.stat().st_size > LOG_MAX_BYTES:
previous = LOG_PATH.with_suffix(".log.1")
if previous.exists():
previous.unlink()
LOG_PATH.replace(previous)
timestamp = datetime.now(timezone.utc).isoformat()
with LOG_PATH.open("a", encoding="utf-8") as output:
output.write(f"{timestamp} {text}\n")
output.flush()
except OSError:
# Chrome controls stderr's destination; an unavailable local log must
# not turn a recoverable bridge error into a different failure.
return
def _drain(reader: BinaryIO, size: int, keep_first: int = 4096) -> bytes:
"""Discard a frame in bounded reads while preserving a diagnostic head."""
remaining = size
head_parts: list[bytes] = []
kept = 0
while remaining > 0:
chunk = reader.read(min(_DRAIN_CHUNK_BYTES, remaining))
if not chunk:
break
remaining -= len(chunk)
if kept < keep_first:
fragment = chunk[: keep_first - kept]
head_parts.append(fragment)
kept += len(fragment)
return b"".join(head_parts)
def _close_reason(text: str) -> str:
"""Fit a WebSocket close reason into its 123-byte UTF-8 limit."""
encoded = text.encode("utf-8")[:123]
while encoded:
try:
return encoded.decode("utf-8")
except UnicodeDecodeError:
encoded = encoded[:-1]
return ""
def read_nm_frame(reader: BinaryIO) -> bytes | None:
"""Read one length-prefixed Native Messaging frame as raw bytes."""
raw_length = reader.read(4)
if not raw_length:
return None
if len(raw_length) != 4:
raise EOFError("Incomplete Native Messaging length prefix")
size = struct.unpack("<I", raw_length)[0]
if size > NM_MAX_INBOUND_BYTES:
raise InboundFrameTooLargeError(size, _drain(reader, size))
payload = reader.read(size)
if len(payload) != size:
raise EOFError("Incomplete Native Messaging payload")
return payload
def write_nm_frame(writer: BinaryIO, payload: bytes) -> None:
"""Write one length-prefixed frame; enforce Chrome's outbound wall."""
if len(payload) > NM_MAX_OUTBOUND_BYTES:
raise NativeMessageTooLargeError(
f"core message is {len(payload)} bytes, above Chrome's "
f"{NM_MAX_OUTBOUND_BYTES}-byte host-to-extension limit",
)
writer.write(struct.pack("<I", len(payload)) + payload)
writer.flush()
def _set_binary_stdio() -> None:
"""Prevent Windows text-mode newline conversion from corrupting frames."""
if sys.platform != "win32":
return
import msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
def run_probe(
stdin: BinaryIO | None = None,
stdout: BinaryIO | None = None,
) -> int:
"""Echo one frame without loading config or third-party runtime."""
payload = read_nm_frame(stdin or sys.stdin.buffer)
if payload is not None:
write_nm_frame(stdout or sys.stdout.buffer, payload)
return 0
def _load_websockets() -> Any:
"""Import the runtime dependency through one testable boundary."""
import websockets
return websockets
def validate_runtime() -> None:
"""Reject a missing or API-incompatible WebSocket runtime."""
websockets = _load_websockets()
connect = getattr(websockets, "connect", None)
if not callable(connect):
raise RuntimeError("websockets.connect is unavailable")
try:
parameters = inspect.signature(connect).parameters
except (TypeError, ValueError) as exc:
raise RuntimeError(
"websockets.connect has an unreadable signature",
) from exc
if "additional_headers" not in parameters:
version = str(getattr(websockets, "__version__", "unknown"))
raise RuntimeError(
f"incompatible websockets {version}: connect() must support "
"additional_headers",
)
def run_runtime_check() -> int:
"""Check third-party runtime APIs without reading bridge state."""
try:
validate_runtime()
except Exception as exc:
diagnostic = (
"Native Messaging host runtime check failed: "
f"{type(exc).__name__}: {exc}"
)
print(diagnostic, file=sys.stderr)
return 1
return 0
def load_config(path: Path = DEFAULT_CONFIG_PATH) -> dict[str, str]:
"""Load the one configured core backend and its bearer token."""
data = json.loads(Path(path).read_text(encoding="utf-8"))
ws_url = str(data.get("ws_url") or "").strip()
token = str(data.get("token") or "").strip()
if not ws_url:
raise ValueError("Native Messaging bridge ws_url is required")
if not token:
raise InvalidTokenError("Native Messaging bridge token is required")
return {"ws_url": ws_url, "token": token}
async def connect_websocket(
url: str,
token: str,
connector: Callable[..., Any] | None = None,
) -> Any:
"""Connect the pipe to its only backend."""
token = token.strip()
if not token:
raise InvalidTokenError("Native Messaging bridge token is required")
headers = {"Authorization": f"Bearer {token}"}
if connector:
return await connector(
url,
additional_headers=headers,
max_size=NM_MAX_OUTBOUND_BYTES,
)
websockets = _load_websockets()
# Fast exit relies on websockets' default ping/pong keepalive (20-second
# interval and timeout) to end iteration on a half-open peer; never disable
# ping_interval here or the zombie Native Messaging host bug returns.
# Frames destined for the extension cannot exceed Chrome's hard outbound
# wall, so accepting more would only defer the inevitable host failure.
return await websockets.connect(
url,
additional_headers=headers,
max_size=NM_MAX_OUTBOUND_BYTES,
)
async def connect_websocket_with_retry(
url: str,
token: str,
connector: Callable[..., Any] | None = None,
on_connected: Callable[[Any], Awaitable[None]] | None = None,
*,
retry_seconds: float = DEFAULT_CONNECT_RETRY_SECONDS,
sleep: Callable[[float], Any] = asyncio.sleep,
monotonic: Callable[[], float] = time.monotonic,
) -> Any:
"""Connect and initialize the bridge through a short core restart."""
if retry_seconds <= 0:
ws = await connect_websocket(url, token, connector)
if on_connected is not None:
await on_connected(ws)
return ws
deadline = monotonic() + retry_seconds
delay = INITIAL_CONNECT_RETRY_DELAY_SECONDS
while True:
ws = None
try:
ws = await connect_websocket(url, token, connector)
if on_connected is not None:
await on_connected(ws)
return ws
except HandshakePermanentError:
if ws is not None:
await ws.close()
raise
except Exception:
if ws is not None:
await ws.close()
remaining = deadline - monotonic()
if remaining <= 0:
raise
wait_seconds = min(delay, remaining)
result = sleep(wait_seconds)
if asyncio.iscoroutine(result):
await result
delay = min(delay * 2, MAX_CONNECT_RETRY_DELAY_SECONDS)
async def pump_stdin_to_ws(stdin: BinaryIO, ws: Any) -> None:
"""Pump extension messages straight to the configured core backend."""
while True:
try:
payload = await asyncio.to_thread(read_nm_frame, stdin)
except InboundFrameTooLargeError as exc:
match = _ID_RE.search(exc.head)
try:
message_id = json.loads(match.group(1)) if match else None
except (TypeError, json.JSONDecodeError):
message_id = None
log_diagnostic(
"Rejected oversized inbound Native Messaging frame "
f"size={exc.size}",
)
await ws.send(
_dumps(
{
"jsonrpc": "2.0",
"id": message_id,
"error": {
"code": -32002,
"message": (
"Native Messaging frame exceeds maximum "
f"size ({exc.size} bytes)"
),
},
},
),
)
continue
if payload is None:
return
await ws.send(payload.decode("utf-8"))
async def pump_ws_to_stdout(ws: Any, stdout: BinaryIO) -> None:
"""Pump core backend messages straight back to the extension."""
async for raw_message in ws:
payload = (
raw_message
if isinstance(raw_message, bytes)
else raw_message.encode("utf-8")
)
try:
await asyncio.to_thread(write_nm_frame, stdout, payload)
except NativeMessageTooLargeError as exc:
# Unreachable in production: websocket max_size equals the
# Chrome wall and pass-through never changes byte counts.
diagnostic = f"Rejecting oversized core message: {exc}"
print(diagnostic, file=sys.stderr)
log_diagnostic(diagnostic)
message_id = None
try:
message_id = json.loads(payload).get("id")
except Exception:
pass
await ws.send(
_dumps(
{
"jsonrpc": "2.0",
"id": message_id,
"error": {"code": -32001, "message": str(exc)},
},
),
)
continue
async def _run_single_backend_bridge(
stdin: BinaryIO,
stdout: BinaryIO,
ws: Any,
) -> None:
"""Run the two direct pump loops until either side disconnects."""
tasks = {
asyncio.create_task(pump_stdin_to_ws(stdin, ws)),
asyncio.create_task(pump_ws_to_stdout(ws, stdout)),
}
close_code = NM_CLOSE_STDIN_EOF
close_reason = close_code_catalog()[close_code]
try:
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_COMPLETED,
)
for task in pending:
task.cancel()
await asyncio.gather(*pending, return_exceptions=True)
for task in done:
task.result()
except EOFError as exc:
if "length prefix" in str(exc).lower():
close_code = NM_CLOSE_FRAME_PROTOCOL
else:
close_code = NM_CLOSE_INTERNAL_ERROR
close_reason = str(exc)
raise
except InboundFrameTooLargeError as exc:
close_code = NM_CLOSE_INBOUND_TOO_LARGE
close_reason = str(exc)
raise
except Exception as exc:
close_code = NM_CLOSE_INTERNAL_ERROR
close_reason = str(exc)
raise
finally:
log_diagnostic(
"Native Messaging bridge closed "
f"code={close_code} reason={close_reason}",
)
await ws.close(code=close_code, reason=_close_reason(close_reason))
async def run_bridge(
config_path: Path = DEFAULT_CONFIG_PATH,
stdin: BinaryIO | None = None,
stdout: BinaryIO | None = None,
*,
connector: Callable[..., Any] | None = None,
retry_seconds: float = DEFAULT_CONNECT_RETRY_SECONDS,
sleep: Callable[[float], Any] = asyncio.sleep,
monotonic: Callable[[], float] = time.monotonic,
terminate: Callable[[int], None] | None = None,
) -> None:
"""Connect, handshake, then run the direct Native Messaging pipe."""
config = load_config(config_path)
async def send_and_wait_for_hello(ws: Any) -> None:
await send_hello(ws, "")
await wait_hello_ack(ws)
ws = await connect_websocket_with_retry(
config["ws_url"],
config["token"],
connector,
send_and_wait_for_hello,
retry_seconds=retry_seconds,
sleep=sleep,
monotonic=monotonic,
)
try:
await _run_single_backend_bridge(
stdin or sys.stdin.buffer,
stdout or sys.stdout.buffer,
ws,
)
except Exception as exc:
if terminate is None:
raise
diagnostic = f"Native Messaging bridge pump failed: {exc}"
print(diagnostic, file=sys.stderr)
log_diagnostic(diagnostic)
exit_code = 1
else:
exit_code = 0
if terminate is not None:
sys.stdout.buffer.flush()
sys.stderr.flush()
terminate(exit_code)
def main() -> int:
"""Run the Native Messaging host."""
_set_binary_stdio()
if sys.argv[1:] == ["--probe"]:
return run_probe()
if sys.argv[1:] == ["--check-runtime"]:
return run_runtime_check()
try:
validate_runtime()
asyncio.run(run_bridge(terminate=os._exit))
except HandshakePermanentError as exc:
diagnostic = exc.advice or str(exc)
print(diagnostic, file=sys.stderr)
log_diagnostic(diagnostic)
return 1
except Exception as exc:
diagnostic = (
"Native Messaging host startup failed: "
f"{type(exc).__name__}: {exc}"
)
print(diagnostic, file=sys.stderr)
log_diagnostic(diagnostic)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
"""Plugin-local mirror of the core Chrome wire protocol; never import core."""
PROTOCOL_VERSION = 2
MIN_COMPATIBLE_PROTOCOL_VERSION = 2
# Chrome Native Messaging hard limits. Protocol facts, not tunables.
NM_MAX_INBOUND_BYTES = 64 * 1024 * 1024
NM_MAX_OUTBOUND_BYTES = 1024 * 1024
# Application-reserved WebSocket close codes for the Native Messaging bridge.
NM_CLOSE_STDIN_EOF = 4000
NM_CLOSE_FRAME_PROTOCOL = 4001
NM_CLOSE_INBOUND_TOO_LARGE = 4002
NM_CLOSE_INTERNAL_ERROR = 4003
EXTENSION_COMMANDS = frozenset(
{
"cdp.send",
"command.execute",
"command.status",
"tabs.list",
"tab.attach",
"tab.detach",
"tab.ensure",
"tab.activate",
"tab.close",
"tab.create",
"tab.metadata.commit",
"banner.show",
"banner.hide",
"file.upload",
"download.read",
"dialog.set",
"extension.open_extensions_manager",
"status.get",
"bridge.connect",
"extension.reload",
},
)
EVENT_TYPES = frozenset({"load", "dialog"})
def contract_snapshot() -> dict[str, object]:
"""Values this plugin build claims to implement, for core comparison."""
return {
"protocolVersion": PROTOCOL_VERSION,
"minCompatibleProtocolVersion": MIN_COMPATIBLE_PROTOCOL_VERSION,
"nmMaxInboundBytes": NM_MAX_INBOUND_BYTES,
"nmMaxOutboundBytes": NM_MAX_OUTBOUND_BYTES,
}
def close_code_catalog() -> dict[int, str]:
"""Close-code meanings shared with the core browser bridge."""
return {
NM_CLOSE_STDIN_EOF: "stdin_eof",
NM_CLOSE_FRAME_PROTOCOL: "frame_protocol_error",
NM_CLOSE_INBOUND_TOO_LARGE: "inbound_frame_too_large",
NM_CLOSE_INTERNAL_ERROR: "host_internal_error",
}
+936
View File
@@ -0,0 +1,936 @@
# -*- coding: utf-8 -*-
"""Chrome extension setup command."""
from __future__ import annotations
import json
import os
import secrets
import shutil
import stat
import struct
import subprocess
import sys
import webbrowser
from ipaddress import ip_address
from pathlib import Path
from qwenpaw.config.utils import read_last_api
from qwenpaw.utils.io_utils import write_json_atomic
try:
# Cross-track contract (lands with unified browser, PR #6276).
from qwenpaw.browser.control_link.chrome.protocol import (
NM_HOST_BASENAME,
NM_HOST_WIN_SUFFIX,
)
except ImportError: # pre-rebase fallback; values locked 2026-07-27.
# After rebasing onto a main that contains PR #6276 this branch is
# dead code: delete the whole except block in the rebase commit.
NM_HOST_BASENAME = "qwenpaw-nm-host"
NM_HOST_WIN_SUFFIX = ".bat"
NATIVE_HOST_NAME = "com.qwenpaw.browser"
NATIVE_HOST_REGISTRY_KEY = (
"Software\\Google\\Chrome\\NativeMessagingHosts\\com.qwenpaw.browser"
)
# EXTENSION_ID is Chrome's deterministic derivation of the manifest "key":
# base64-decode the public key (SubjectPublicKeyInfo DER), sha256 it, take the
# first 32 hex chars, map 0-f to a-p. Pinning "key" keeps the unpacked-mode id
# stable so it matches the Native Messaging allowed_origins. Regenerate via:
# openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -out key.pem
# openssl rsa -in key.pem -pubout -outform DER | openssl base64 -A
# Keep key.pem secret and never commit it; only the public "key" ships.
EXTENSION_ID = "nflcgkfjgoiipklkpenmbiificbakoch"
# NOTE: The Chrome Web Store assigns the real id at listing time; this
# placeholder is unused while CWS installation remains unavailable.
CWS_EXTENSION_ID = EXTENSION_ID
CWS_URL = (
"https://chromewebstore.google.com/detail/"
f"qwenpaw-chrome/{CWS_EXTENSION_ID}"
)
CWS_COMING_SOON_MESSAGE = (
"cws install mode is coming soon and not supported in this "
"Developer Preview"
)
DEFAULT_WS_URL = "ws://127.0.0.1:8088/api/ws/chrome"
CHROME_EXTENSIONS_URL = "chrome://extensions"
LOCAL_BRIDGE_CONFIG_JS = "bridge_config.js"
LOCAL_INITIAL_RECONNECT_BACKOFF_SECONDS = 5
LOCAL_MAX_RECONNECT_BACKOFF_SECONDS = 60
INSTALL_MODE_STATE_FILENAME = "chrome-extension-install.json"
WINDOWS_MAINTENANCE_BACKUP_SUFFIX = ".qwenpaw-maintenance"
WINDOWS_MAINTENANCE_STUB_MARKER = "QWENPAW_INSTALL_MAINTENANCE"
NATIVE_HOST_REPAIR_INSTRUCTION = (
"Re-run Setup from the Chrome plugin detail page, then reload the Chrome "
"extension."
)
def native_manifest_path(
home: Path,
*,
platform: str | None = None,
) -> Path:
platform = platform or sys.platform
if platform == "darwin":
return (
home
/ "Library"
/ "Application Support"
/ "Google"
/ "Chrome"
/ "NativeMessagingHosts"
/ f"{NATIVE_HOST_NAME}.json"
)
if platform == "win32":
return home / ".qwenpaw" / f"{NATIVE_HOST_NAME}.json"
return (
home
/ ".config"
/ "google-chrome"
/ "NativeMessagingHosts"
/ f"{NATIVE_HOST_NAME}.json"
)
def _plugin_root() -> Path:
return Path(__file__).resolve().parent
def _repo_root() -> Path:
"""Return the source checkout root when this module runs from a repo."""
return _plugin_root().parents[2]
def _packaged_build_fingerprint() -> dict[str, str | None]:
"""Read build data materialized into packaged Native Messaging assets."""
try:
from .assets.scripts.build_fingerprint import BUILD_FINGERPRINT
except ImportError:
return {"commit": "unknown", "builtAt": None}
commit = str(BUILD_FINGERPRINT.get("commit") or "unknown")
built_at = BUILD_FINGERPRINT.get("builtAt")
return {
"commit": commit,
"builtAt": str(built_at) if built_at is not None else None,
}
def _build_fingerprint() -> dict[str, str | None]:
"""Return the checkout build identity, degrading outside a git worktree."""
try:
commit = subprocess.run(
["git", "rev-parse", "HEAD"],
cwd=_repo_root(),
capture_output=True,
check=True,
text=True,
).stdout.strip()
built_at = subprocess.run(
["git", "show", "-s", "--format=%cI", "HEAD"],
cwd=_repo_root(),
capture_output=True,
check=True,
text=True,
).stdout.strip()
if commit and built_at:
return {"commit": commit, "builtAt": built_at}
except (OSError, subprocess.CalledProcessError):
pass
return _packaged_build_fingerprint()
def _first_existing_path(candidates: list[Path], label: str) -> Path:
for candidate in candidates:
if candidate.exists():
return candidate
joined = ", ".join(str(path) for path in candidates)
raise FileNotFoundError(f"{label} not found. Checked: {joined}")
def _extension_source_dir() -> Path:
plugin_root = _plugin_root()
return _first_existing_path(
[
plugin_root / "assets" / "extensions" / "chrome",
],
"Chrome extension assets",
)
def _native_host_source_path() -> Path:
plugin_root = _plugin_root()
return _first_existing_path(
[
plugin_root / "assets" / "scripts" / "nm_host.py",
],
"Native Messaging host script",
)
def _native_host_support_paths() -> list[Path]:
source_dir = _native_host_source_path().parent
return [
source_dir / name
for name in (
"build_fingerprint.py",
"handshake.py",
"protocol_mirror.py",
)
if (source_dir / name).exists()
]
def _qwenpaw_home(home: Path) -> Path:
return home / ".qwenpaw"
def _resolve_host_interpreter() -> str:
"""Return the Python runtime that can execute the Native Messaging host."""
bundled_runtime = os.environ.get("QWENPAW_DESKTOP_PY_RUNTIME", "")
if bundled_runtime and Path(bundled_runtime).is_file():
return bundled_runtime
if not getattr(sys, "frozen", False) and not os.environ.get(
"QWENPAW_DESKTOP_APP",
):
return sys.executable
raise RuntimeError(
"QWENPAW_DESKTOP_PY_RUNTIME is missing or invalid; reinstall the "
"QwenPaw desktop app.",
)
def _windows_batch_path_literal(value: str) -> str:
"""Return a cmd.exe-safe literal path for a generated batch file."""
normalized = value
if value.upper().startswith("\\\\?\\UNC\\"):
normalized = "\\\\" + value[len("\\\\?\\UNC\\") :]
elif value.startswith("\\\\?\\"):
normalized = value[len("\\\\?\\") :]
return normalized.replace("%", "%%")
def native_host_launcher_path(
qwenpaw_home: Path,
*,
platform: str | None = None,
) -> Path:
"""Return the Native Messaging launcher path for a platform."""
name = NM_HOST_BASENAME
if (platform or sys.platform) == "win32":
name += NM_HOST_WIN_SUFFIX
return qwenpaw_home / "bin" / name
def recover_windows_native_host_launcher(
*,
home: Path | None = None,
platform: str | None = None,
) -> bool:
"""Recover a launcher left gated by an interrupted Windows installer."""
platform = platform or sys.platform
if platform != "win32":
return False
qwenpaw_home = _qwenpaw_home(home or Path.home())
launcher = native_host_launcher_path(qwenpaw_home, platform=platform)
backup = launcher.with_name(
launcher.name + WINDOWS_MAINTENANCE_BACKUP_SUFFIX,
)
if not backup.is_file():
return False
is_gate = False
if launcher.is_file():
try:
is_gate = (
WINDOWS_MAINTENANCE_STUB_MARKER.encode("ascii")
in launcher.read_bytes()
)
except OSError:
return False
if launcher.exists() and not is_gate:
backup.unlink()
return False
launcher.unlink(missing_ok=True)
backup.replace(launcher)
return True
class _NoopNativeHostRegistry:
def set_value(self, key_path: str, value: str) -> None:
del key_path, value
def get_value(self, key_path: str) -> str | None:
del key_path
def delete_value(self, key_path: str) -> None:
del key_path
class _WindowsNativeHostRegistry:
def set_value(self, key_path: str, value: str) -> None:
import winreg
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_path) as key:
winreg.SetValueEx(key, None, 0, winreg.REG_SZ, value)
def get_value(self, key_path: str) -> str | None:
import winreg
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path) as key:
value, _ = winreg.QueryValueEx(key, None)
except FileNotFoundError:
return None
return str(value)
def delete_value(self, key_path: str) -> None:
import winreg
try:
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path)
except FileNotFoundError:
pass
def _native_host_registry(platform: str, registry: object | None) -> object:
if platform != "win32":
return _NoopNativeHostRegistry()
return registry if registry is not None else _WindowsNativeHostRegistry()
def resolve_default_ws_url() -> str:
"""Resolve the bridge WebSocket URL for the currently running API."""
return require_bridge_endpoint()
class BridgeEndpointUnavailable(RuntimeError):
"""Raised when the local API bind cannot safely host the bridge token."""
class InstallModeError(ValueError):
"""Raised when the requested extension install mode cannot be used."""
def require_bridge_endpoint() -> str:
"""Derive a loopback-only bridge endpoint from the running server bind."""
try:
api_info = read_last_api()
except Exception:
api_info = None
if not api_info:
return DEFAULT_WS_URL
host, port = api_info
host = "127.0.0.1" if host in {"", "0.0.0.0"} else str(host)
raw_host = (
host[1:-1] if host.startswith("[") and host.endswith("]") else host
)
if raw_host != "localhost":
try:
is_loopback = ip_address(raw_host).is_loopback
except ValueError:
is_loopback = False
if not is_loopback:
raise BridgeEndpointUnavailable(
"Chrome Native Messaging requires QwenPaw to bind to a "
"loopback address (127.0.0.1, ::1, or localhost).",
)
if ":" in host and not host.startswith("["):
host = f"[{host}]"
return f"ws://{host}:{port}/api/ws/chrome"
def _copy_extension(qwenpaw_home: Path) -> Path:
source = _extension_source_dir()
target = qwenpaw_home / "chrome-extension" / "qwenpaw-chrome"
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(source, target, dirs_exist_ok=True)
return target
def _write_local_extension_config(
extension_dir: Path,
build: dict[str, str | None] | None = None,
) -> Path:
config_path = extension_dir / LOCAL_BRIDGE_CONFIG_JS
config = {
"initialReconnectBackoffSeconds": (
LOCAL_INITIAL_RECONNECT_BACKOFF_SECONDS
),
"maxReconnectBackoffSeconds": LOCAL_MAX_RECONNECT_BACKOFF_SECONDS,
"localPort": int(
resolve_default_ws_url().rsplit(":", 1)[1].split("/")[0],
),
"build": build or _build_fingerprint(),
}
config_path.write_text(
"globalThis.QWENPAW_BRIDGE_CONFIG = "
f"{json.dumps(config, separators=(',', ':'))};\n",
encoding="utf-8",
)
return config_path
def atomic_write_json_0600(path: Path, data: dict[str, object]) -> Path:
"""Atomically persist bridge secrets with owner-only permissions."""
write_json_atomic(path, data, new_file_mode=0o600)
return path
def _write_nm_config(qwenpaw_home: Path, token: str, ws_url: str) -> Path:
config_path = qwenpaw_home / "nm-bridge.json"
return atomic_write_json_0600(
config_path,
{"ws_url": ws_url, "token": token},
)
def _install_mode_state_path(qwenpaw_home: Path) -> Path:
return qwenpaw_home / INSTALL_MODE_STATE_FILENAME
def _write_install_mode_state(
qwenpaw_home: Path,
install_mode: str,
native_host_probe: dict[str, object] | None = None,
) -> Path:
state_path = _install_mode_state_path(qwenpaw_home)
state: dict[str, object] = {"install_mode": install_mode}
if native_host_probe is not None:
state["native_host_probe"] = native_host_probe
return atomic_write_json_0600(state_path, state)
def _read_install_mode_state_data(
qwenpaw_home: Path,
) -> dict[str, object] | None:
try:
state = json.loads(
_install_mode_state_path(qwenpaw_home).read_text(
encoding="utf-8",
),
)
except (OSError, json.JSONDecodeError):
return None
return state if isinstance(state, dict) else None
def _read_install_mode_state(qwenpaw_home: Path) -> str | None:
state = _read_install_mode_state_data(qwenpaw_home)
install_mode = state.get("install_mode") if state is not None else None
return install_mode if install_mode in {"unpacked", "cws"} else None
def _check_native_host_runtime(
launcher: Path,
*,
timeout: float = 5.0,
) -> dict[str, str | bool] | None:
"""Return a probe failure when the host runtime is unusable."""
try:
runtime_check = subprocess.run(
[str(launcher), "--check-runtime"],
capture_output=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
return {"ok": False, "stage": "timeout", "detail": str(exc)}
except OSError as exc:
return {"ok": False, "stage": "launch", "detail": str(exc)}
if runtime_check.returncode != 0:
detail = runtime_check.stderr.decode("utf-8", "replace").strip()
return {
"ok": False,
"stage": "runtime",
"detail": detail or f"exit code {runtime_check.returncode}",
}
return None
def _probe_native_host(
launcher: Path,
*,
timeout: float = 5.0,
) -> dict[str, str | bool]:
"""Validate the host runtime, then verify an unmodified NM frame."""
runtime_failure = _check_native_host_runtime(launcher, timeout=timeout)
if runtime_failure is not None:
return runtime_failure
payload = {"probe": "qwenpaw"}
raw_payload = json.dumps(payload, separators=(",", ":")).encode("utf-8")
frame = struct.pack("<I", len(raw_payload)) + raw_payload
try:
completed = subprocess.run(
[str(launcher), "--probe"],
input=frame,
capture_output=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
return {"ok": False, "stage": "timeout", "detail": str(exc)}
except OSError as exc:
return {"ok": False, "stage": "launch", "detail": str(exc)}
if completed.returncode != 0:
detail = completed.stderr.decode("utf-8", "replace").strip()
return {
"ok": False,
"stage": "launch",
"detail": detail or f"exit code {completed.returncode}",
}
if completed.stdout != frame:
return {
"ok": False,
"stage": "framing",
"detail": "Native Messaging probe frame did not round-trip",
}
return {"ok": True, "stage": "", "detail": ""}
def _native_host_repair_instruction(probe: dict[str, object]) -> str:
"""Return a bounded, actionable repair message for a failed probe."""
stage = str(probe.get("stage") or "unknown")
prefix = f"Native host self-check failed during {stage}."
if stage == "runtime":
detail = " ".join(str(probe.get("detail") or "").split())[:500]
if detail:
prefix = f"{prefix} {detail}"
return f"{prefix} {NATIVE_HOST_REPAIR_INSTRUCTION}"
def _read_existing_nm_token(qwenpaw_home: Path) -> str | None:
config_path = qwenpaw_home / "nm-bridge.json"
if not config_path.exists():
return None
try:
raw = json.loads(config_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
token = str(raw.get("token") or "").strip()
return token or None
def _write_host(
qwenpaw_home: Path,
*,
platform: str | None = None,
build: dict[str, str | None] | None = None,
) -> Path:
platform = platform or sys.platform
bin_dir = qwenpaw_home / "bin"
bin_dir.mkdir(parents=True, exist_ok=True)
host_impl = bin_dir / "qwenpaw-nm-host.py"
shutil.copy2(_native_host_source_path(), host_impl)
if platform != "win32":
host_impl.chmod(0o755)
for support_path in _native_host_support_paths():
shutil.copy2(support_path, bin_dir / support_path.name)
(bin_dir / "build_fingerprint.py").write_text(
"# -*- coding: utf-8 -*-\n"
'"""Build fingerprint materialized at installation time."""\n\n'
f"BUILD_FINGERPRINT = {repr(build or _build_fingerprint())}\n",
encoding="utf-8",
)
host = native_host_launcher_path(qwenpaw_home, platform=platform)
interpreter = _resolve_host_interpreter()
if platform == "win32":
interpreter = _windows_batch_path_literal(interpreter)
host_impl_literal = _windows_batch_path_literal(str(host_impl))
# cmd.exe reads batch files through the current OEM code page. This
# ASCII-only line switches decoding to UTF-8 before paths are read.
host.write_text(
"@echo off\n"
"chcp 65001 >nul\n"
f'"{interpreter}" "{host_impl_literal}" %*\n',
encoding="utf-8",
)
else:
host.write_text(
"#!/usr/bin/env sh\n" f'exec "{interpreter}" "{host_impl}" "$@"\n',
encoding="utf-8",
)
host.chmod(
host.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH,
)
return host
def _write_native_manifest(
host_path: Path,
extension_id: str = EXTENSION_ID,
*,
home: Path,
platform: str | None = None,
) -> Path:
manifest_path = native_manifest_path(home, platform=platform)
manifest_path.parent.mkdir(parents=True, exist_ok=True)
manifest = {
"name": NATIVE_HOST_NAME,
"description": "QwenPaw Native Messaging host",
"path": str(host_path),
"type": "stdio",
"allowed_origins": [f"chrome-extension://{extension_id}/"],
}
return atomic_write_json_0600(manifest_path, manifest)
def _uninstall(
qwenpaw_home: Path,
*,
home: Path,
platform: str | None = None,
registry: object | None = None,
) -> None:
platform = platform or sys.platform
native_host_registry = _native_host_registry(platform, registry)
manifest_path = native_manifest_path(home, platform=platform)
if manifest_path.exists():
manifest_path.unlink()
native_host_registry.delete_value(NATIVE_HOST_REGISTRY_KEY)
config_path = qwenpaw_home / "nm-bridge.json"
if config_path.exists():
config_path.unlink()
install_mode_state_path = _install_mode_state_path(qwenpaw_home)
if install_mode_state_path.exists():
install_mode_state_path.unlink()
host = native_host_launcher_path(qwenpaw_home, platform=platform)
host_impl = qwenpaw_home / "bin" / "qwenpaw-nm-host.py"
host_paths = [host, host_impl]
if platform == "win32":
host_paths.append(
host.with_name(
host.name + WINDOWS_MAINTENANCE_BACKUP_SUFFIX,
),
)
for path in host_paths:
if path.exists():
path.unlink()
shutil.rmtree(qwenpaw_home / "chrome-extension", ignore_errors=True)
def setup_extension_files(
*,
install_mode: str = "unpacked",
reset: bool = False,
home: Path | None = None,
platform: str | None = None,
registry: object | None = None,
) -> dict[str, str | bool]:
"""Install extension files and Native Messaging registration."""
if install_mode == "cws":
raise InstallModeError(CWS_COMING_SOON_MESSAGE)
if install_mode != "unpacked":
raise InstallModeError("install_mode must be 'unpacked'")
home = home or Path.home()
platform = platform or sys.platform
native_host_registry = _native_host_registry(platform, registry)
ws_url = require_bridge_endpoint()
qwenpaw_home = _qwenpaw_home(home)
if reset:
_uninstall(
qwenpaw_home,
home=home,
platform=platform,
registry=native_host_registry,
)
token = None if reset else _read_existing_nm_token(qwenpaw_home)
token = token or secrets.token_urlsafe(32)
build = _build_fingerprint()
extension_dir = None
if install_mode == "unpacked":
extension_dir = _copy_extension(qwenpaw_home)
_write_local_extension_config(extension_dir, build)
config_path = _write_nm_config(qwenpaw_home, token, ws_url)
host_path = _write_host(qwenpaw_home, platform=platform, build=build)
manifest_path = _write_native_manifest(
host_path,
home=home,
platform=platform,
)
native_host_registry.set_value(
NATIVE_HOST_REGISTRY_KEY,
str(manifest_path),
)
native_host_probe = _probe_native_host(host_path)
_write_install_mode_state(qwenpaw_home, install_mode, native_host_probe)
result: dict[str, str | bool] = {
"installed": bool(native_host_probe["ok"]),
"install_mode": install_mode,
"extension_id": EXTENSION_ID,
"extension_dir": (
str(extension_dir) if extension_dir is not None else ""
),
"native_manifest_path": str(manifest_path),
"native_host_path": str(host_path),
"config_path": str(config_path),
"manifest_configured": True,
"native_host_repair_required": not native_host_probe["ok"],
"native_host_repair_instruction": (
_native_host_repair_instruction(native_host_probe)
if not native_host_probe["ok"]
else ""
),
"ws_url": ws_url,
"chrome_extensions_url": CHROME_EXTENSIONS_URL,
}
return result
def extension_install_status(
*,
home: Path | None = None,
platform: str | None = None,
registry: object | None = None,
) -> dict[str, str | bool | None]:
"""Return install paths and whether the local registration exists."""
home = home or Path.home()
platform = platform or sys.platform
native_host_registry = _native_host_registry(platform, registry)
qwenpaw_home = _qwenpaw_home(home)
extension_dir = qwenpaw_home / "chrome-extension" / "qwenpaw-chrome"
manifest_path = native_manifest_path(home, platform=platform)
host_path = native_host_launcher_path(qwenpaw_home, platform=platform)
config_path = qwenpaw_home / "nm-bridge.json"
manifest_configured = False
repair_required = False
ws_url = None
if config_path.exists():
try:
config = json.loads(config_path.read_text(encoding="utf-8"))
ws_url = config.get("ws_url")
manifest_configured = bool(ws_url and config.get("token"))
except (OSError, json.JSONDecodeError):
ws_url = None
if platform == "win32":
registered_manifest = native_host_registry.get_value(
NATIVE_HOST_REGISTRY_KEY,
)
try:
registry_manifest_readable = (
bool(registered_manifest)
and Path(
str(registered_manifest),
).is_file()
)
if registry_manifest_readable:
Path(str(registered_manifest)).read_bytes()
except OSError:
registry_manifest_readable = False
native_host_configured = (
registry_manifest_readable and host_path.exists()
)
else:
native_host_configured = (
manifest_path.exists()
and host_path.exists()
and config_path.exists()
and manifest_configured
)
unpacked_installed = (extension_dir / "manifest.json").exists() and (
native_host_configured
)
install_state = _read_install_mode_state_data(qwenpaw_home)
install_mode = _read_install_mode_state(qwenpaw_home)
cws_installed = native_host_configured and (
install_mode == "cws"
or (install_mode is None and not unpacked_installed)
)
if install_mode == "unpacked":
cws_installed = False
installed = unpacked_installed or cws_installed
probe = (
install_state.get("native_host_probe")
if install_state is not None
else None
)
if isinstance(probe, dict) and probe.get("ok") is False:
repair_required = True
repair_instruction = _native_host_repair_instruction(probe)
else:
repair_instruction = ""
return {
"installed": installed,
"install_mode": (
"cws"
if cws_installed
else "unpacked"
if unpacked_installed
else None
),
"extension_id": EXTENSION_ID,
"extension_dir": str(extension_dir),
"native_manifest_path": str(manifest_path),
"native_host_path": str(host_path),
"config_path": str(config_path),
"manifest_configured": manifest_configured,
"native_host_repair_required": repair_required,
"native_host_repair_instruction": repair_instruction,
"legacy_config_path": "",
# This is the endpoint actually persisted for the Native Messaging
# host. Do not replace a missing value with the current server bind:
# callers use the distinction to detect an incomplete or stale setup.
"ws_url": ws_url,
"chrome_extensions_url": CHROME_EXTENSIONS_URL,
}
def open_extension_folder(
extension_dir: Path | None = None,
*,
platform: str | None = None,
home: Path | None = None,
) -> dict[str, str | bool | None]:
"""Open the local unpacked extension folder with a native file manager."""
home = home or Path.home()
platform = platform or sys.platform
target = extension_dir or (
_qwenpaw_home(home) / "chrome-extension" / "qwenpaw-chrome"
)
target = target.expanduser()
if not target.exists():
return {
"opened": False,
"path": str(target),
"error": "Extension folder does not exist yet.",
}
if platform == "darwin":
commands = [["open", str(target)]]
elif platform == "win32":
commands = [["explorer", str(target)]]
else:
commands = [["xdg-open", str(target)]]
for command in commands:
try:
subprocess.Popen( # pylint: disable=consider-using-with
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return {"opened": True, "path": str(target), "error": None}
except OSError as exc:
last_error = str(exc)
return {"opened": False, "path": str(target), "error": last_error}
def _find_windows_chrome_executable() -> Path | None:
"""Return a registered or standard-install Google Chrome executable."""
candidates: list[Path] = []
try:
import winreg
except ImportError:
winreg = None
if winreg is not None:
app_paths_key = (
r"Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"
)
for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
try:
with winreg.OpenKey(hive, app_paths_key) as key:
value, _ = winreg.QueryValueEx(key, "")
except OSError:
continue
candidate = str(value).strip().strip('"')
if candidate:
candidates.append(Path(candidate))
for env_name in ("LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"):
root = os.environ.get(env_name)
if root:
candidates.append(
Path(root)
/ "Google"
/ "Chrome"
/ "Application"
/ "chrome.exe",
)
seen: set[str] = set()
for candidate in candidates:
key = os.path.normcase(str(candidate))
if key in seen:
continue
seen.add(key)
if candidate.is_file():
return candidate
return None
def open_chrome_extensions_page(
*,
platform: str | None = None,
) -> dict[str, str | bool]:
"""Open Chrome's extension manager through a fixed local action."""
platform = platform or sys.platform
commands: list[list[str]] = []
if platform == "darwin":
commands.append(["open", "-a", "Google Chrome", CHROME_EXTENSIONS_URL])
elif platform == "win32":
chrome_executable = _find_windows_chrome_executable()
if chrome_executable is None:
return {
"opened": False,
"url": CHROME_EXTENSIONS_URL,
"error": "Google Chrome executable was not found.",
}
try:
subprocess.Popen( # pylint: disable=consider-using-with
[str(chrome_executable), CHROME_EXTENSIONS_URL],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except OSError as exc:
return {
"opened": False,
"url": CHROME_EXTENSIONS_URL,
"error": f"Could not start Google Chrome: {exc}",
}
return {"opened": True, "url": CHROME_EXTENSIONS_URL}
else:
commands.extend(
[
[browser, CHROME_EXTENSIONS_URL]
for browser in (
"google-chrome",
"google-chrome-stable",
"chromium",
"chromium-browser",
)
],
)
for command in commands:
try:
subprocess.Popen( # pylint: disable=consider-using-with
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return {"opened": True, "url": CHROME_EXTENSIONS_URL}
except OSError:
continue
try:
opened = webbrowser.open(CHROME_EXTENSIONS_URL)
except Exception as exc: # pragma: no cover - defensive OS fallback
return {
"opened": False,
"url": CHROME_EXTENSIONS_URL,
"error": str(exc),
}
return {"opened": bool(opened), "url": CHROME_EXTENSIONS_URL}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,17 @@
{
"name": "qwenpaw-chrome-plugin",
"private": true,
"version": "0.1.0",
"scripts": {
"build": "vite build",
"format": "tsc --noEmit && prettier --write --cache .",
"format:check": "tsc --noEmit && prettier --check ."
},
"devDependencies": {
"@types/react": "^18.3.3",
"@vitejs/plugin-react": "^4.3.1",
"prettier": "3.0.0",
"typescript": "^5.5.4",
"vite": "^5.4.2"
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,258 @@
export type ChromeLocale = "zh" | "en";
const messages = {
en: {
routeLabel: "Chrome",
pageTitle: "Chrome",
pageSubtitle: "Connect QwenPaw to this Chrome browser.",
loading: "Checking Chrome connection...",
refreshStatus: "Refresh Status",
installedRefresh: "I've installed it, refresh status",
versionUnknown: "unknown",
installTitle: "Install Chrome Extension",
installDescription:
"Load the local extension, then return here to confirm the connection.",
readyTitle: "Chrome Connected",
readyDescription: "Version {version}. Connected {connectedSince}.",
awaitingTitle: "Extension installed, waiting for Chrome",
awaitingDescription:
"The extension is installed. Keep Chrome running; the bridge will connect automatically.",
repairTitle: "Browser Connector needs repair",
repairDescription:
"The Native Messaging host failed its runtime check. Repair it before Chrome can connect.",
openChrome: "Open extensions page",
installMethodsTitle: "Install method",
localMethodTitle: "Local install",
recommendedBadge: "Recommended",
localMethodDescription:
"Use the extension files included with QwenPaw for this local browser.",
copyChromeExtensionsPage: "Copy chrome://extensions",
chromeWebStoreTitle: "Chrome Web Store",
chromeWebStoreDescription:
"The store listing is not available yet. Use local install for now.",
comingSoon: "Coming soon",
localStepsTitle: "Local install steps",
localStepsOnce: "Only once",
openExtensionsStepTitle: "Copy extensions page address",
openExtensionsPrefix: "Click",
openExtensionsAction: "chrome://extensions",
openExtensionsSuffix:
"then paste it into Chrome's address bar and press Enter.",
developerModeStepTitle: "Enable Developer mode",
developerModePrefix: "Turn on",
developerModeAction: "Developer mode",
developerModeSuffix: "in the upper-right corner.",
loadUnpackedStepTitle: "Click load button",
loadUnpackedPrefix: "Click",
loadUnpackedAction: "Load unpacked",
loadUnpackedSuffix: "in Chrome.",
pastePathStepTitle: "Paste path and open",
pastePathGuide:
"Follow the Quick paste path tips on the right to copy the path, paste it, and open the folder.",
qwenpawExtensionPath: "Copy QwenPaw extension path",
shortcutTipsTitle: "Quick paste path tips",
shortcutTipsScope: "Use when selecting folder",
currentSystem: "Current system",
shortcutCopyPathPrefix: "Click",
shortcutCopyPathSuffix:
"button to copy the QwenPaw extension path to your clipboard.",
shortcutMacStep1:
"Press Cmd + Shift + G, paste the path, then press Enter.",
shortcutMacStep2: "After the folder is selected, click Open.",
shortcutWindowsStep1:
"Click the address bar, paste the path, then press Enter.",
shortcutWindowsStep2: "After the folder is selected, click Select Folder.",
shortcutLinuxStep1: "Press Ctrl + L, paste the path, then press Enter.",
shortcutLinuxStep2: "After the folder is selected, click Open.",
stepOpen: "Open chrome://extensions and enable Developer mode.",
stepLoad: "Choose Load unpacked and select the QwenPaw extension folder.",
stepVerify: "Return here and refresh the status.",
directoryLabel: "QwenPaw built-in extension folder",
directoryHint: "Path is available from copy or advanced information.",
openExtensionFolder: "Open Folder",
copyPath: "Copy Path",
advancedInfo: "Advanced information",
extensionDir: "Extension folder",
nativeManifest: "Local connection config",
nativeHost: "Local connection helper",
config: "Local settings file",
bridgeEndpoint: "Connection endpoint",
checksTitle: "Connection checks",
checkExtensionBridge: "Extension bridge",
checkNmHost: "Native Messaging host",
checkExtensionAssets: "Extension assets",
checkBridgeLifecycle: "Bridge lifecycle",
checkContractDrift: "Extension compatibility",
checkUnknown: "Unknown check: {name}",
checkReady: "Ready",
checkFailed: "Needs attention",
checksPending: "Connection checks are not available yet. Refresh to retry.",
repairReinstallNmHost: "Reinstall the Native Messaging host.",
repairReloadUnpackedExtension:
"Reload the unpacked extension in chrome://extensions.",
repairWaitOrRestartChrome: "Wait a moment or restart Chrome.",
repairReloadExtension: "Reload the extension.",
repairReloadOrUpdateExtension: "Reload or update the extension.",
version: "Extension version",
connected: "Connected",
justNow: "just now",
minutesAgo: "{count} minutes ago",
hoursAgo: "{count} hours ago",
installSuccess: "Extension files ready",
installFailed: "Extension setup failed",
repairBrowserConnector: "Repair Browser Connector",
repairSuccess:
"Browser Connector repaired. Waiting for Chrome to reconnect.",
copied: "Copied",
copyFailed: "Could not copy to the clipboard. Copy the address manually.",
chromeExtensionsCopied:
"Copied. Paste it into Chrome's address bar and press Enter.",
chromeExtensionsCopiedFallback:
"Chrome could not open the extensions page automatically. The address was copied; paste it into Chrome's address bar and press Enter.",
chrome_disconnected:
"Reload the extension or reopen the target browser tab.",
browser_backend_unavailable:
"Refresh the status after the backend is available.",
chrome_action_runtime_missing:
"Restart QwenPaw or reload the Chrome plugin.",
isolated_backend_unavailable:
"Install or restart the isolated browser runtime.",
},
zh: {
routeLabel: "Chrome浏览器",
pageTitle: "Chrome",
pageSubtitle: "将 QwenPaw 连接到此 Chrome 浏览器。",
loading: "正在检查 Chrome 连接...",
refreshStatus: "刷新状态",
installedRefresh: "我已安装,刷新状态",
versionUnknown: "未知",
installTitle: "安装 Chrome 扩展",
installDescription: "加载本地扩展后,回到这里确认连接状态。",
readyTitle: "Chrome 已连接",
readyDescription: "版本 {version}。连接于 {connectedSince}。",
awaitingTitle: "扩展已安装,等待 Chrome 连接",
awaitingDescription: "扩展已安装。保持 Chrome 运行,桥接将自动建立连接。",
repairTitle: "浏览器连接器需要修复",
repairDescription:
"Native Messaging Host 运行时检查失败。请先修复连接器,再连接 Chrome。",
openChrome: "打开扩展页",
installMethodsTitle: "安装方式",
localMethodTitle: "本地安装",
recommendedBadge: "推荐",
localMethodDescription: "使用 QwenPaw 自带扩展文件连接当前本地浏览器。",
copyChromeExtensionsPage: "复制 chrome://extensions",
chromeWebStoreTitle: "Chrome Web Store",
chromeWebStoreDescription: "官方商店版本尚未发布。当前请使用本地安装。",
comingSoon: "Coming soon",
localStepsTitle: "本地安装步骤",
localStepsOnce: "只需要完成一次",
openExtensionsStepTitle: "复制扩展页地址",
openExtensionsPrefix: "点击",
openExtensionsAction: "chrome://extensions",
openExtensionsSuffix: ",在 Chrome 地址栏粘贴并按 Enter。",
developerModeStepTitle: "开启开发者模式",
developerModePrefix: "在页面右上角打开",
developerModeAction: "开发者模式",
developerModeSuffix: "开关。",
loadUnpackedStepTitle: "点击加载按钮",
loadUnpackedPrefix: "点击 Chrome 页面里的",
loadUnpackedAction: "加载未打包的扩展程序",
loadUnpackedSuffix: "。",
pastePathStepTitle: "粘贴路径并打开",
pastePathGuide:
"请按右侧“快捷粘贴路径 Tips”的步骤完成复制、粘贴并打开目录。",
qwenpawExtensionPath: "复制 QwenPaw 扩展路径",
shortcutTipsTitle: "快捷粘贴路径 Tips",
shortcutTipsScope: "选择目录时使用",
currentSystem: "当前系统",
shortcutCopyPathPrefix: "点击",
shortcutCopyPathSuffix: "按钮复制 QwenPaw 扩展路径到剪贴板。",
shortcutMacStep1: "按 Cmd + Shift + G,粘贴路径并回车。",
shortcutMacStep2: "确认定位到目录后,点击“打开”。",
shortcutWindowsStep1: "点击地址栏,粘贴路径并回车。",
shortcutWindowsStep2: "确认定位到目录后,点击“选择文件夹”。",
shortcutLinuxStep1: "按 Ctrl + L,粘贴路径并回车。",
shortcutLinuxStep2: "确认定位到目录后,点击“打开”。",
stepOpen: "打开 chrome://extensions,并启用开发者模式。",
stepLoad: "选择“加载未打包的扩展程序”,并选择 QwenPaw 扩展目录。",
stepVerify: "回到此页面并刷新状态。",
directoryLabel: "QwenPaw 自带扩展目录",
directoryHint: "完整路径可通过复制或高级信息查看。",
openExtensionFolder: "打开目录",
copyPath: "复制路径",
advancedInfo: "高级信息",
extensionDir: "扩展目录",
nativeManifest: "本机连接配置",
nativeHost: "本机连接助手",
config: "本地设置文件",
bridgeEndpoint: "连接端点",
checksTitle: "连接检查",
checkExtensionBridge: "扩展桥接",
checkNmHost: "Native Messaging 宿主",
checkExtensionAssets: "扩展资产",
checkBridgeLifecycle: "桥接生命周期",
checkContractDrift: "扩展兼容性",
checkUnknown: "未知检查:{name}",
checkReady: "就绪",
checkFailed: "需要处理",
checksPending: "连接检查结果暂不可用,请刷新重试。",
repairReinstallNmHost: "重新安装 Native Messaging 宿主。",
repairReloadUnpackedExtension:
"在 chrome://extensions 重新加载未打包的扩展。",
repairWaitOrRestartChrome: "稍候片刻或重启 Chrome。",
repairReloadExtension: "重新加载扩展。",
repairReloadOrUpdateExtension: "重新加载或更新扩展。",
version: "扩展版本",
connected: "连接时间",
justNow: "刚刚",
minutesAgo: "{count} 分钟前",
hoursAgo: "{count} 小时前",
installSuccess: "扩展文件已准备好",
installFailed: "扩展设置失败",
repairBrowserConnector: "修复浏览器连接器",
repairSuccess: "浏览器连接器已修复,正在等待 Chrome 重新连接。",
copied: "已复制",
copyFailed: "无法复制到剪贴板,请手动复制该地址。",
chromeExtensionsCopied: "已复制,请在 Chrome 地址栏粘贴并按 Enter。",
chromeExtensionsCopiedFallback:
"Chrome 未能自动打开扩展页。地址已复制,请在 Chrome 地址栏粘贴并按 Enter。",
chrome_disconnected: "重载扩展,或重新打开目标浏览器标签页。",
browser_backend_unavailable: "后端可用后刷新状态。",
chrome_action_runtime_missing: "重启 QwenPaw,或重新加载 Chrome 插件。",
isolated_backend_unavailable: "安装或重启隔离浏览器运行时。",
},
} as const;
export type MessageKey = keyof typeof messages.en;
export function readConsoleLanguage(): string | null {
try {
return window.localStorage?.getItem("language") ?? null;
} catch {
return null;
}
}
export function resolveChromeLocale(
language: string | null | undefined = readConsoleLanguage(),
): ChromeLocale {
const base = String(language || "")
.trim()
.split("-")[0]
.toLowerCase();
return base === "zh" ? "zh" : "en";
}
export function t(
locale: ChromeLocale,
key: MessageKey,
params?: Record<string, string | number>,
): string {
let text: string = messages[locale][key] ?? messages.en[key];
if (params) {
for (const [name, value] of Object.entries(params)) {
text = text.split(`{${name}}`).join(String(value));
}
}
return text;
}
+37
View File
@@ -0,0 +1,37 @@
// Ambient declarations for the QwenPaw console host API.
//
// The QwenPaw console injects a shared `window.QwenPaw` object at
// runtime; we externalize `react`/`react-dom` (see `vite.config.ts`)
// and pull `React`/`antd` off `host` instead of bundling them. Without
// these declarations every access reduces to `any` and the compiler
// cannot tell us when the host contract drifts.
import type * as ReactNS from "react";
declare global {
interface QwenPawHost {
React: typeof ReactNS;
antd: any;
getApiUrl: (path: string) => string;
getApiToken: () => string;
}
interface QwenPawRoute {
path: string;
component: unknown;
label?: string;
icon?: ReactNS.ReactNode;
priority?: number;
}
interface QwenPawGlobal {
host: QwenPawHost;
registerRoutes?: (pluginId: string, routes: QwenPawRoute[]) => void;
}
interface Window {
QwenPaw: QwenPawGlobal;
}
}
export {};
@@ -0,0 +1,21 @@
{
"//": [
"`types: []` disables automatic @types/* registration. Without it,",
"@types/react's `export as namespace React` would expose `React` as",
"a global value and clash with the `const React = host.React` line",
"in `src/index.tsx` ('Cannot redeclare block-scoped variable React').",
"Window globals are declared explicitly in `src/qwenpaw-host.d.ts`",
"instead. The unknown `//` key is ignored by tsc."
],
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"types": []
},
"include": ["src"]
}
@@ -0,0 +1,19 @@
import react from "@vitejs/plugin-react";
import { resolve } from "path";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react({ jsxRuntime: "classic" })],
build: {
lib: {
entry: resolve(__dirname, "src/index.tsx"),
formats: ["es"],
fileName: () => "index.js",
},
outDir: resolve(__dirname, "../dist"),
emptyOutDir: true,
rollupOptions: {
external: ["react", "react-dom"],
},
},
});
+17
View File
@@ -0,0 +1,17 @@
{
"id": "chrome",
"name": "Chrome",
"version": "0.1.0",
"type": "general",
"description": "Connect QwenPaw to this Chrome browser.",
"description_i18n": {
"zh-CN": "将 QwenPaw 连接到当前 Chrome 浏览器。",
"en-US": "Connect QwenPaw to this Chrome browser."
},
"author": "QwenPaw",
"icon": "Chrome",
"qwenpaw_version": {"min": "2.0.0"},
"capabilities": [{"id": "chrome", "name": "Chrome", "description": "Use QwenPaw with this Chrome browser."}],
"entry": {"backend": "plugin.py", "frontend": "dist/index.js"},
"dependencies": []
}
+66
View File
@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
"""Chrome plugin entry point."""
from __future__ import annotations
import logging
from qwenpaw.plugins.api import PluginApi
# Kept for the milestone-A bridge wiring contract. A semantic dispatcher is
# deliberately not registered until the later control milestone.
# no-name-in-module: astroid confuses this namespace-relative "api" package
# with other plugins' top-level "api" packages during whole-repo lint runs.
# pylint: disable=unused-import,no-name-in-module
from .api.routes import (
api_router,
configure_nm_bridge,
get_extension_status,
)
from .extension_setup import recover_windows_native_host_launcher
logger = logging.getLogger(__name__)
class ChromePlugin:
"""Register Chrome plugin capabilities."""
def startup(self) -> None:
"""Recover the launcher and write the Native Messaging config."""
try:
if recover_windows_native_host_launcher():
logger.info("Recovered the Native Messaging launcher")
except OSError:
logger.warning(
"Could not recover the Native Messaging launcher",
exc_info=True,
)
configure_nm_bridge()
async def shutdown(self) -> None:
"""Keep the installed Native Messaging configuration on unload."""
def register(self, api: PluginApi) -> None:
"""Register plugin integrations."""
api.register_http_router(
api_router,
prefix="/chrome",
tags=["chrome"],
)
api.register_shutdown_hook(
hook_name="chrome_clear_connection_manager",
callback=self.shutdown,
priority=120,
)
api.register_startup_hook(
hook_name="chrome_register_manifest",
callback=self.startup,
priority=110,
)
logger.info("Chrome plugin registered: %s", api.plugin_id)
async def get_runtime_status(self) -> dict:
"""Return Chrome runtime status for plugin detail pages."""
return await get_extension_status()
plugin = ChromePlugin()
@@ -0,0 +1,4 @@
# -*- coding: utf-8 -*-
"""Plugin transport configuration types only; runtime bridge lives in core."""
__all__: list[str] = []
+27
View File
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
"""Native Messaging bridge route state."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
@dataclass
class NMBridgeRouteState:
"""State shared by Chrome route module instances."""
token: str | None = None
ws_url: str = ""
config_path: Path | None = None
_state = NMBridgeRouteState()
def get_nm_bridge_route_state() -> NMBridgeRouteState:
"""Return the process-wide Chrome route state."""
return _state
__all__ = ["NMBridgeRouteState", "get_nm_bridge_route_state"]