-
Notifications
You must be signed in to change notification settings - Fork 149
feat: 添加 Native Messaging 桥接,支持 CLI 和 AI Agent 控制扩展 #1143
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
4bf30c0
feat: add native messaging bridge for CLI communication
LeiShi1313 cf2b110
fix(native-messaging): narrow stored instance id
LeiShi1313 914f29d
feat: move nativeMessaging to optional_permissions, bump to 0.0.6
LeiShi1313 09fdfae
feat: add nativeBridge message types to ProtocolMap
LeiShi1313 57f6706
feat(native-messaging): rewrite as permission-aware bridge manager
LeiShi1313 3b2b714
feat: add native-bridge tab route, hide save button for non-config tabs
LeiShi1313 49a0270
feat: add i18n keys for native bridge settings tab
LeiShi1313 62382ab
feat: add NativeBridgeWindow settings tab UI
LeiShi1313 33f9568
fix(native-messaging): remove premature connected state in connect()
LeiShi1313 145b2a3
fix(native-messaging): add retry budget and poll for test connection …
LeiShi1313 1fcb807
fix(native-messaging): mark connected after hello handshake send
LeiShi1313 8b3aabe
feat(native-bridge): show ptd install command when bridge not connected
LeiShi1313 9bdef03
fix(native-bridge): use correct browser flag in setup command
LeiShi1313 0a0061f
fix(native-bridge): wait for hello handshake before returning enable …
LeiShi1313 0b94183
fix(options): redirect /settings to /set-base by default
LeiShi1313 1409306
fix(options): move native bridge tab before backup & restore
LeiShi1313 ca230b7
feat(native-bridge): link to ptd-cli repo in info section
LeiShi1313 80304d5
feat: add getSiteList and getDownloaderList message handlers
LeiShi1313 2161d96
fix(native-bridge): update ptd-cli link to pt-plugins org repo
LeiShi1313 7b0749d
fix(native-bridge): address PR review feedback
LeiShi1313 797c73d
fix(native-bridge): add address back to downloader list, add privacy …
LeiShi1313 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| import { sendMessage } from "@/messages.ts"; | ||
| import { setupOffscreenDocument } from "./offscreen.ts"; | ||
|
|
||
| const NATIVE_HOST_NAME = "com.ptd.native"; | ||
| const INSTANCE_ID_KEY = "ptd_native_instance_id"; | ||
| const RECONNECT_BASE_MS = 1000; | ||
| const RECONNECT_MAX_MS = 30000; | ||
|
|
||
| /** Errors that indicate the native host is not installed — no point retrying. */ | ||
| const FATAL_ERRORS = [ | ||
| "Specified native messaging host not found.", | ||
| "Access to the specified native messaging host is forbidden.", | ||
| "Native messaging host has exited.", | ||
| ]; | ||
|
|
||
| /** Methods the bridge will proxy to sendMessage(). Everything else is rejected. */ | ||
| const ALLOWED_METHODS = new Set([ | ||
| // Storage and logging (read-only) | ||
| "getExtStorage", | ||
| "getLogger", | ||
| // Site config | ||
| "getSiteUserConfig", | ||
| "getSiteFavicon", | ||
| "clearSiteFaviconCache", | ||
| // Search | ||
| "getSiteSearchResult", | ||
| "getMediaServerSearchResult", | ||
| // Download and downloader | ||
| "getDownloaderConfig", | ||
| "getDownloaderVersion", | ||
| "getDownloaderStatus", | ||
| "getTorrentDownloadLink", | ||
| "getTorrentInfoForVerification", | ||
| "downloadTorrent", | ||
| "getDownloadHistory", | ||
| "getDownloadHistoryById", | ||
| "deleteDownloadHistoryById", | ||
| "clearDownloadHistory", | ||
| // User info | ||
| "getSiteUserInfoResult", | ||
| "cancelUserInfoQueue", | ||
| "getSiteUserInfo", | ||
| "removeSiteUserInfo", | ||
| // Keep-upload | ||
| "getKeepUploadTasks", | ||
| "getKeepUploadTaskById", | ||
| "createKeepUploadTask", | ||
| "updateKeepUploadTask", | ||
| "deleteKeepUploadTask", | ||
| "clearKeepUploadTasks", | ||
| ]); | ||
|
|
||
| let reconnectAttempt = 0; | ||
|
|
||
| async function getOrCreateInstanceId(): Promise<string> { | ||
| const stored = await chrome.storage.local.get(INSTANCE_ID_KEY); | ||
| if (stored[INSTANCE_ID_KEY]) { | ||
| return stored[INSTANCE_ID_KEY]; | ||
| } | ||
| const id = crypto.randomUUID(); | ||
| await chrome.storage.local.set({ [INSTANCE_ID_KEY]: id }); | ||
| return id; | ||
| } | ||
|
|
||
| function connect() { | ||
| let port: chrome.runtime.Port; | ||
| try { | ||
| port = chrome.runtime.connectNative(NATIVE_HOST_NAME); | ||
| } catch { | ||
| // Native host not installed — silently skip | ||
| console.debug("[PTD] Native messaging host not available, CLI bridge disabled."); | ||
| return; | ||
| } | ||
|
|
||
| let disconnected = false; | ||
| reconnectAttempt = 0; | ||
|
|
||
| // Send hello handshake | ||
| getOrCreateInstanceId().then((instanceId) => { | ||
| if (disconnected) return; | ||
| const hello = { | ||
| type: "hello", | ||
| instanceId, | ||
| browser: __BROWSER__, | ||
| extensionId: chrome.runtime.id, | ||
| version: __EXT_VERSION__, | ||
| capabilities: ["bridge-v1"], | ||
| }; | ||
| port.postMessage(hello); | ||
| }); | ||
|
|
||
| port.onMessage.addListener(async (msg: any) => { | ||
| if (msg?.type !== "request" || !msg.id || !msg.method) { | ||
| return; | ||
| } | ||
|
|
||
| const { id, method, params } = msg; | ||
|
|
||
| if (!ALLOWED_METHODS.has(method)) { | ||
| port.postMessage({ | ||
| type: "response", | ||
| id, | ||
| error: { code: "METHOD_NOT_ALLOWED", message: `Method '${method}' is not allowed` }, | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| await setupOffscreenDocument(); | ||
| const result = await sendMessage(method as any, params); | ||
| port.postMessage({ type: "response", id, result }); | ||
| } catch (e: any) { | ||
| port.postMessage({ | ||
| type: "response", | ||
| id, | ||
| error: { code: "EXTENSION_ERROR", message: e?.message ?? String(e) }, | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| port.onDisconnect.addListener(() => { | ||
| disconnected = true; | ||
| const err = chrome.runtime.lastError; | ||
| if (err) { | ||
| console.debug("[PTD] Native messaging disconnected:", err.message); | ||
| } | ||
|
|
||
| const errMsg = err?.message ?? ""; | ||
|
|
||
| // Don't retry if the host is not installed or access is denied — | ||
| // retrying just floods the console with errors. The user needs to | ||
| // install the native host and restart the browser. | ||
| if (FATAL_ERRORS.some((e) => errMsg.includes(e))) { | ||
| console.debug( | ||
| "[PTD] Native host not available, CLI bridge disabled. Install the host and restart the browser to enable.", | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| // Reconnect with bounded exponential backoff for transient errors | ||
| // (e.g. host process crashed, browser restarted the service worker) | ||
| reconnectAttempt++; | ||
| const delay = Math.min(RECONNECT_BASE_MS * 2 ** reconnectAttempt, RECONNECT_MAX_MS); | ||
| setTimeout(connect, delay); | ||
| }); | ||
| } | ||
|
|
||
| connect(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CLI 能够使用的 sendMessage methods 有必要进一步细分吗?比如按 site, search, download, userInfo, keepUpload 这种大类?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这现阶段应该问题不大,还没有那么多方法到让人困惑的地步