Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(desktop): add CodeBuddy as a local ACP agent (#761)

yulei6669aad6f918ae3
diff --git a/README.ja.md b/README.ja.md
index 4dc92ab0..376f2639 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -89,7 +89,7 @@ EdgeEver は、オープンソースのノートと知識ベースの作業領
| **整理と検索** | • 無制限階層のノートブックとフォルダツリー<br>• タグシステム、ドラッグ&ドロップ並べ替え、一括結合・移動<br>• ミリ秒単位のインクリメンタル全文検索とフィルタ | • **独立した知識ベースサイト公開**:ノートブック全体をツリーナビゲーション付きの静的 Web サイトとしてワンクリック公開(パスワード保護対応)<br>• マルチアカウント・複数ワークスペースの物理分離 |
| **収集とメディア** | • デスクトップ・モバイルでの各種添付ファイル(PDF、Office、音声・動画など)保存<br>• ブラウザ拡張によるテキスト・画像の選択クリップ<br>• スマホの共有メニューから画像や Web 記事を即時保存 | • **高度な構造化クリッピング**:小紅書、X (Twitter)、知乎、Reddit、GitHub、YouTube、Bilibili など 20 以上の主要サービスに対応<br>• **微信チャット履歴の取り込み**:タイムライン、発言者、引用、スタンプ、メディアを完全保持<br>• **クライアント側自動圧縮**:画像アップロード時に 50%〜90% 自動軽量化;最大 1 GiB の分割ストリーミングアップロード対応 |
| **データと可視化** | • ネイティブ表編集と Markdown テーブル描画<br>• Mermaid 記法によるフローチャート・シーケンス図・構成図の直接描画 | • **AI 多次元テーブル**:プロンプトからタグや日付などの列型を備えた業務テーブルを自動生成<br>• **一般公開集計フォーム**:ログイン不要の Web フォームを発行し、回答をリアルタイムでテーブルへ集約<br>• **AI インフォグラフィック生成**:タイムライン、比較図、マトリクス、マインドマップを自動生成 |
-| **AI とエコシステム** | • サイドバーの伴走型 AI アシスタント(要約、校正、翻訳、推敲)<br>• BYOK(独自 API キー):OpenAI、Anthropic、Gemini 互換プロトコル対応 | • **ネイティブ Agent プロトコル連携**:外部 Agent が読み書きできる MCP、ローカル Agent を直接呼び出す ACP を標準搭載<br>• **AI RSS 購読日報**:フィードを自動収集し、AI がノイズを排除して構造化日報を作成<br>• 自由な拡張を可能にするプラグイン開発 API |
+| **AI とエコシステム** | • サイドバーの伴走型 AI アシスタント(要約、校正、翻訳、推敲)<br>• BYOK(独自 API キー):OpenAI、Anthropic、Gemini 互換プロトコル対応 | • **ネイティブ Agent プロトコル連携**:外部 Agent が読み書きできる MCP、Codex、Claude Code、CodeBuddy などのローカル Agent を直接呼び出す ACP を標準搭載<br>• **AI RSS 購読日報**:フィードを自動収集し、AI がノイズを排除して構造化日報を作成<br>• 自由な拡張を可能にするプラグイン開発 API |
| **マルチ端末同期と基盤** | • PC・スマホ・タブレット間で低遅延・シームレスに同期、接続端末数無制限<br>• Web、macOS、Windows、Linux、iOS、Android の全プラットフォーム公式対応<br>• オフラインファーストと自動同期キュー:オフラインでも軽快に執筆、再接続時に自動増分同期<br>• 標準 SQLite、可逆 ZIP アーカイブ・Markdown の入出力に対応 | • **生涯サーバー代ゼロ**:Cloudflare の無料枠で 100% 稼働(短文約 15 万件+画像約 5 万枚)<br>• **自由な Docker セルフホスト**:自宅サーバー・VPS・NAS にワンクリック配置、数百万件規模の高速同期に対応<br>• サーバー側ブルートフォース保護とセキュリティ隔離 |
## 導入
diff --git a/README.md b/README.md
index b1830ecb..ec93ce06 100644
--- a/README.md
+++ b/README.md
@@ -89,7 +89,7 @@ An all-in-one workspace connecting inspiration capture, deep creation, and knowl
| **Organization & Search** | • Infinite-depth notebooks & folder tree navigation<br>• Tagging system, drag-and-drop sorting, batch note merging/moving<br>• Millisecond-level full-text search with historical filtering | • **Standalone Knowledge Base Publishing**: One-click publish entire notebooks as static documentation sites with tree navigation & password protection<br>• Multi-user spaces & physical tenant data isolation |
| **Capture & Media** | • Universal attachment uploads (PDF, Office, audio/video, archives)<br>• Browser extension precision clipping for web text & images<br>• Mobile system share sheet to save photos & articles | • **Deep Multi-Platform Structured Clipping**: Deeply adapted for Xiaohongshu, X (Twitter), Zhihu, Reddit, GitHub, YouTube, Bilibili, and 20+ sources<br>• **WeChat Chat History Archiving**: One-click full transcript import on macOS with timestamps, quotes, emojis, and media<br>• **Client-Side Image Compression**: Automatic 50%–90% silent size reduction; chunked streaming safely supports up to 1 GiB files |
| **Data & Visuals** | • Native table editing & Markdown table rendering<br>• Native Mermaid diagrams (flowcharts, sequence diagrams, architecture) | • **AI Multi-Dimensional Tables**: Prompt-to-database with automatic field typing (tags, dates, selects)<br>• **Public Online Collection Forms**: One-click shareable forms without login, syncing responses into tables in real time<br>• **AI Diagram & Infographic Generation**: In-place creation of timelines, comparison charts, quadrant matrices & mind maps |
-| **AI & Ecosystem** | • Companion sidebar AI assistant for summaries, proofreading & translations<br>• BYOK (Bring Your Own Key): compatible with OpenAI, Claude, Gemini & custom endpoints | • **Native Agent Protocols (MCP & ACP)**: Built-in MCP for external agent read/write; ACP in desktop app to drive local coding agents directly<br>• **AI RSS Daily Digest**: Automated feed aggregation, AI noise filtering, and structured digest generation<br>• Extensible Plugin Development API |
+| **AI & Ecosystem** | • Companion sidebar AI assistant for summaries, proofreading & translations<br>• BYOK (Bring Your Own Key): compatible with OpenAI, Claude, Gemini & custom endpoints | • **Native Agent Protocols (MCP & ACP)**: Built-in MCP for external agent read/write; ACP in desktop app to drive local agents such as Codex, Claude Code and CodeBuddy directly<br>• **AI RSS Daily Digest**: Automated feed aggregation, AI noise filtering, and structured digest generation<br>• Extensible Plugin Development API |
| **Multi-Device Sync & Foundation** | • Seamless, low-latency sync across desktop, mobile, and web with zero device limits<br>• Official client support across Web, macOS, Windows, Linux, iOS, and Android<br>• Offline-first with auto-sync queue: write smoothly offline, automatically resume and sync when reconnected<br>• Standard SQLite database, lossless ZIP backup & Markdown export/import | • **Zero Server Cost for Life**: 100% runnable on Cloudflare Free tier (~150k short notes & ~50k images)<br>• **Flexible Docker Self-Hosting**: One-click deployment for VPS, NAS, or home server with millions of notes & instant sync<br>• Server-side brute-force protection and tenant security |
## Deployment
diff --git a/README.pl-PL.md b/README.pl-PL.md
index ea480466..1c795a05 100644
--- a/README.pl-PL.md
+++ b/README.pl-PL.md
@@ -89,7 +89,7 @@ Wszechstronny obszar roboczy łączący zbieranie inspiracji, głębokie tworzen
| **Organizacja i wyszukiwanie** | • Nieograniczone zagnieżdżanie notatników i drzewo folderów<br>• System tagów, sortowanie przeciąganiem, łączenie i przenoszenie notatek<br>• Błyskawiczne wyszukiwanie pełnotekstowe z filtrami | • **Samodzielna publikacja bazy wiedzy**: Publikuj całe notatniki jako statyczne strony dokumentacji z nawigacją i ochroną hasłem<br>• Wiele odizolowanych przestrzeni użytkowników |
| **Zapisywanie i załączniki** | • Obsługa załączników dowolnego formatu (PDF, Office, wideo, archiwa)<br>• Precyzyjne wycinanie tekstu i obrazów ze stron w rozszerzeniu przeglądarki<br>• Udostępnianie systemowe w telefonie do zapisu zdjęć i artykułów | • **Ustrukturyzowane zapisywanie z wielu platform**: Dostosowane do Xiaohongshu, X (Twittera), Zhihu, Reddita, GitHuba, YouTube i 20+ serwisów<br>• **Archiwizacja rozmów WeChat**: Import całych rozmów na macOS ze znacznikami czasu, cytatami, emotikonami i załącznikami<br>• **Cicha kompresja obrazów**: Zmniejszenie rozmiaru o 50–90%; strumieniowe przesyłanie plików do 1 GiB |
| **Dane i wizualizacje** | • Natywna edycja tabel i renderowanie tabel Markdown<br>• Natywne diagramy Mermaid (schematy blokowe, sekwencje, architektura) | • **Wielowymiarowe tabele AI**: Tworzenie tabel biznesowych z promptu (z tagami, datami i polami wyboru)<br>• **Publiczne formularze zbierania danych**: Udostępnianie formularzy bez logowania i zapis odpowiedzi w czasie rzeczywistym<br>• **Generowanie infografik i map myśli przez AI**: Osi czasu, porównania, macierze i mapy myśli |
-| **AI i ekosystem** | • Asystent AI w panelu bocznym do streszczeń, korekty, tłumaczeń i redakcji<br>• Własne klucze API (BYOK): zgodność z OpenAI, Claude, Gemini i serwerami proxy | • **Protokoły MCP i ACP**: Wbudowany MCP do odczytu/zapisu przez agentów zewnętrznych; ACP w aplikacji desktopowej do współpracy z lokalnymi agentami<br>• **Inteligentne podsumowania RSS AI**: Agregacja źródeł, filtrowanie szumu i generowanie zwięzłych podsumowań<br>• API tworzenia wtyczek do rozbudowy funkcji |
+| **AI i ekosystem** | • Asystent AI w panelu bocznym do streszczeń, korekty, tłumaczeń i redakcji<br>• Własne klucze API (BYOK): zgodność z OpenAI, Claude, Gemini i serwerami proxy | • **Protokoły MCP i ACP**: Wbudowany MCP do odczytu/zapisu przez agentów zewnętrznych; ACP w aplikacji desktopowej do współpracy z lokalnymi agentami, takimi jak Codex, Claude Code i CodeBuddy<br>• **Inteligentne podsumowania RSS AI**: Agregacja źródeł, filtrowanie szumu i generowanie zwięzłych podsumowań<br>• API tworzenia wtyczek do rozbudowy funkcji |
| **Synchronizacja i fundament** | • Natychmiastowa synchronizacja bez opóźnień na komputerach, telefonach i w sieci bez limitu urządzeń<br>• Oficjalne aplikacje na Web, macOS, Windows, Linux, iOS i Android<br>• Architektura offline-first i kolejka synchronizacji: płynne pisanie bez sieci, automatyczna synchronizacja po połączeniu<br>• Standardowa baza SQLite, bezstratny eksport/import archiwów ZIP i Markdown | • **Zero kosztów serwera na zawsze**: 100% działania w darmowym planie Cloudflare (~150 tys. notatek i ~50 tys. obrazów)<br>• **Elastyczny hosting Docker**: Wdrożenie na VPS, NAS lub domowym serwerze dla milionów notatek z natychmiastową synchronizacją<br>• Ochrona serwera przed atakami brute-force i bezpieczna izolacja |
## Wdrożenie
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 51c58a89..7515d11d 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -89,7 +89,7 @@ EdgeEver 是一款现代化的开源笔记与个人知识库工作区。它保
| **组织与检索** | • 无限层级笔记本与目录树导航<br>• 标签体系(Tags)与笔记拖拽排序、批量合并/移动<br>• 毫秒级即时全文搜索与历史记录过滤 | • **独立知识库网站发布**:一键将整个笔记本公开发布为带目录树导航的独立静态站点(支持密码保护)<br>• 多账号与工作区多空间数据物理隔离 |
| **剪藏与附件** | • 桌面与移动端全格式附件上传(PDF、Office、音视频等)<br>• 浏览器划选网页文字与图片精准抓取<br>• 手机系统分享一键转存全网图片与微信文章 | • **全渠道结构化剪藏**:深度适配小红书、X (Twitter)、知乎、Reddit、GitHub 等 20+ 平台<br>• **微信聊天记录一键归档**:整段对话转笔记,保留时间轴、引用、表情与附件<br>• **端侧静默压缩**:图片上传前压缩 50%–90%;分片流式上传安全支持最大 1 GiB 附件 |
| **数据与可视化** | • 原生表格编辑与 Markdown 表格渲染<br>• 原生 Mermaid 流程图、时序图与架构图渲染 | • **AI 多维表格**:自然语言一句话生成业务数据库(含标签、日期等字段)<br>• **在线公开收集表单**:多维表格一键生成免登录外链表单,填报数据实时入库<br>• **AI 智能信息图与导图**:一键生成时间线、对比图、象限矩阵及思维导图 |
-| **AI 与生态** | • 侧边伴随式 AI 助手,选区/全文一键总结、翻译与润色<br>• BYOK(自带模型):兼容 OpenAI、Anthropic、Gemini 等主流协议 | • **原生 Agent 协议互联**:内置 MCP(外部 Agent 读写笔记)与 ACP(桌面端直接唤起本机 Agent 协作创作)<br>• **AI RSS 智能订阅日报**:定时聚合资讯源,AI 自动过滤噪音并生成精炼日报<br>• 开放插件开发 API 自由扩展 |
+| **AI 与生态** | • 侧边伴随式 AI 助手,选区/全文一键总结、翻译与润色<br>• BYOK(自带模型):兼容 OpenAI、Anthropic、Gemini 等主流协议 | • **原生 Agent 协议互联**:内置 MCP(外部 Agent 读写笔记)与 ACP(桌面端直接唤起 Codex、Claude Code、CodeBuddy 等本机 Agent 协作创作)<br>• **AI RSS 智能订阅日报**:定时聚合资讯源,AI 自动过滤噪音并生成精炼日报<br>• 开放插件开发 API 自由扩展 |
| **多端同步与底座** | • 电脑、手机全端秒级无感同步,无设备数量限制<br>• 官方覆盖 Web / macOS / Windows / Linux / iOS / Android 全平台<br>• 离线优先与同步队列:断网流畅写作,联网自动恢复并增量同步<br>• 标准 SQLite 存储,无损 ZIP 档案与 Markdown 导出导入 | • **终身零服务器成本**:100% 运行于 Cloudflare 免费配额(容量约 15 万条短笔记与 5 万张图片)<br>• **灵活 Docker 自托管**:私有 VPS/NAS 一键部署,轻松承载百万级笔记与瞬时同步<br>• 服务端防暴力破解限流保护与安全数据隔离 |
## 部署
diff --git a/README.zh-TW.md b/README.zh-TW.md
index 1e9371b5..99b99dac 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -89,7 +89,7 @@ EdgeEver 是一款現代化的開源筆記與個人知識庫工作區。它延
| **組織與檢索** | • 無限層級筆記本與目錄樹導覽<br>• 標籤體系(Tags)與筆記拖放排序、批次合併/移動<br>• 毫秒級即時全文搜尋與歷史記錄篩選 | • **獨立知識庫網站發布**:一鍵將整個筆記本公開發布為帶目錄樹導覽的獨立靜態網站(支援密碼保護)<br>• 多帳號與工作區多空間資料實體隔離 |
| **擷取與附件** | • 桌面與行動端全格式附件上傳(PDF、Office、影音等)<br>• 瀏覽器選取網頁文字與圖片精準擷取<br>• 手機系統分享一鍵轉存全網圖片與微信文章 | • **全渠道結構化擷取**:深度適配小紅書、X (Twitter)、知乎、Reddit、GitHub 等 20+ 平台<br>• **微信聊天記錄一鍵歸檔**:整段對話轉筆記,保留時間軸、引用、表情與附件<br>• **端側靜默壓縮**:圖片上傳前壓縮 50%–90%;分塊串流上傳安全支援最大 1 GiB 附件 |
| **資料與視覺化** | • 原生表格編輯與 Markdown 表格繪製<br>• 原生 Mermaid 流程圖、循序圖與架構圖繪製 | • **AI 多維表格**:自然語言一句話產生業務資料庫(含標籤、日期等欄位)<br>• **線上公開收集表單**:多維表格一鍵產生免登入外鏈表單,填報資料即時入庫<br>• **AI 智慧資訊圖與導圖**:一鍵產生時間線、對比圖、象限矩陣及心智圖 |
-| **AI 與生態** | • 側邊伴隨式 AI 助手,選取範圍/全文一鍵摘要、翻譯與修飾潤色<br>• BYOK(自備金鑰):相容 OpenAI、Anthropic、Gemini 等主流協定 | • **原生 Agent 協定互聯**:內建 MCP(外部 Agent 讀寫筆記)與 ACP(桌面端直接喚起本機 Agent 協同創作)<br>• **AI RSS 智慧訂閱日報**:定時聚合資訊來源,AI 自動過濾雜訊並產生精煉日報<br>• 開放外掛開發文件自由擴充 |
+| **AI 與生態** | • 側邊伴隨式 AI 助手,選取範圍/全文一鍵摘要、翻譯與修飾潤色<br>• BYOK(自備金鑰):相容 OpenAI、Anthropic、Gemini 等主流協定 | • **原生 Agent 協定互聯**:內建 MCP(外部 Agent 讀寫筆記)與 ACP(桌面端直接喚起 Codex、Claude Code、CodeBuddy 等本機 Agent 協同創作)<br>• **AI RSS 智慧訂閱日報**:定時聚合資訊來源,AI 自動過濾雜訊並產生精煉日報<br>• 開放外掛開發文件自由擴充 |
| **多端同步與底座** | • 電腦、手機全端秒級無感同步,無裝置數量限制<br>• 官方涵蓋 Web / macOS / Windows / Linux / iOS / Android 全平台<br>• 離線優先與同步佇列:斷網流暢寫作,連網自動復原並增量同步<br>• 標準 SQLite 儲存,無損 ZIP 封存與 Markdown 匯出匯入 | • **終身零伺服器成本**:100% 執行於 Cloudflare 免費配額(容量約 15 萬條短筆記與 5 萬張圖片)<br>• **彈性 Docker 自託管**:私有 VPS/NAS 一鍵部署,輕鬆承載百萬級筆記與瞬時同步<br>• 伺服端防暴力破解限流保護與安全資料隔離 |
## 部署
diff --git a/apps/desktop/src/main/acp-host.mjs b/apps/desktop/src/main/acp-host.mjs
index 9a24153b..9bbb2b58 100644
--- a/apps/desktop/src/main/acp-host.mjs
+++ b/apps/desktop/src/main/acp-host.mjs
@@ -1,6 +1,6 @@
import { spawn as nodeSpawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
-import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
+import { accessSync, constants as fsConstants, existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
import { mkdtemp, rm } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import path from "node:path";
@@ -13,6 +13,7 @@ import { createAcpAdapterManager } from "./acp-adapter-manager.mjs";
import { startAcpMcpBridge } from "./acp-mcp-bridge.mjs";
import { withAntigravityMacProxy } from "./antigravity-proxy.mjs";
import { authenticateWorkBuddy, prepareWorkBuddyAuth } from "./workbuddy-auth.mjs";
+import { codeBuddyLoginUrl, resolveCodeBuddyCli } from "./codebuddy-cli.mjs";
const ADAPTERS = {
codex: { id: "codex", label: "Codex" },
@@ -25,6 +26,7 @@ const ADAPTERS = {
piAgent: { id: "piAgent", label: "pi agent" },
workbuddyCn: { id: "workbuddyCn", label: "WorkBuddy 中国版" },
workbuddyIntl: { id: "workbuddyIntl", label: "WorkBuddy International" },
+ codebuddy: { id: "codebuddy", label: "CodeBuddy" },
};
const AUTH_REQUIRED_CODE = -32000;
const MAX_ATTACHMENTS = 8;
@@ -130,6 +132,8 @@ const resolutionDeps = (deps = {}) => ({
realpath: deps.realpathSync ?? realpathSync,
stat: deps.statSync ?? statSync,
exists: deps.existsSync ?? existsSync,
+ readFile: deps.readFileSync ?? ((file) => readFileSync(file, "utf8")),
+ readdir: deps.readdirSync ?? ((dir) => readdirSync(dir)),
pathEnv: deps.pathEnv ?? process.env.PATH ?? "",
delimiter: deps.delimiter ?? path.delimiter,
sep: deps.sep ?? path.sep,
@@ -146,6 +150,13 @@ export function resolveAcpCommand(input, deps = {}) {
if (id === "hermesAgent") return resolveAgentCli("hermes", ["acp"], resolved);
if (id === "grokBuild") return resolveGrok(input?.path, resolved);
if (id === "deepseekHarness") return resolveLocalAcpCli("dsh", ["--profile", "acp"], resolved);
+ if (id === "codebuddy") {
+ return resolveCodeBuddyCli({
+ ...resolved,
+ executableMode: fsConstants.X_OK,
+ toolPath: desktopToolPath({ platform: resolved.platform, home: resolved.home, pathEnv: resolved.pathEnv, env: resolved.env, exists: resolved.exists, readFile: resolved.readFile, readdir: resolved.readdir }),
+ });
+ }
if (id === "piAgent") {
if (!localExecutable("pi", resolved)) return { ok: false, state: "not_installed" };
const adapter = resolveLocalAcpCli("pi-acp", [], resolved);
@@ -343,6 +354,8 @@ export function classifyAcpFailure(error) {
}
const adapterShell = (id) => ({ ...ADAPTERS[id] });
+const accountCheckFor = (id) => (id === "codebuddy" ? "codebuddy" : id === "workbuddyCn" || id === "workbuddyIntl");
+const CODEBUDDY_REOPEN_INTERVAL_MS = 3_000;
const adapterFromResolution = (id, resolution) => {
const adapter = adapterShell(id);
@@ -555,14 +568,61 @@ const desktopToolDirectories = (platform, home, env) => {
].filter(Boolean);
};
-const nvmDefaultBin = (home, exists, readFile) => {
- let version = "";
- try {
- version = String(readFile(path.posix.join(home, ".nvm", "alias", "default")) ?? "").trim();
- } catch {
- return null;
+const NVM_VERSION = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
+const NVM_ALIAS_NAME = /^(?!.*\.\.)[A-Za-z0-9._*-]+(?:\/[A-Za-z0-9._*-]+)?$/;
+
+const compareNodeVersions = (a, b) => {
+ const [, ...x] = /^v(\d+)\.(\d+)\.(\d+)/.exec(a) ?? [];
+ const [, ...y] = /^v(\d+)\.(\d+)\.(\d+)/.exec(b) ?? [];
+ for (let index = 0; index < 3; index += 1) {
+ const diff = Number(x[index] ?? -1) - Number(y[index] ?? -1);
+ if (diff) return diff;
}
- if (!/^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.]+)?$/.test(version)) return null;
+ return 0;
+};
+
+// Resolves nvm's default alias like `nvm use default` does for the common
+// forms: an exact or partial version (v22.14.0, 22, v22.14), node/stable,
+// lts/* and named aliases stored under ~/.nvm/alias, followed a few levels deep.
+export function nvmDefaultVersion(home, { readFile, readdir }) {
+ const nvmDir = path.posix.join(home, ".nvm");
+ let installed;
+ const installedVersions = () => {
+ if (installed) return installed;
+ try {
+ installed = readdir(path.posix.join(nvmDir, "versions", "node"))
+ .filter((name) => /^v\d+\.\d+\.\d+$/.test(name))
+ .sort(compareNodeVersions);
+ } catch {
+ installed = [];
+ }
+ return installed;
+ };
+ const resolve = (value, depth) => {
+ const name = String(value ?? "").trim();
+ if (!name || depth > 5 || name === "system" || name.startsWith("iojs")) return null;
+ if (/^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.]+)?$/.test(name)) return name;
+ const version = NVM_VERSION.exec(name);
+ if (version) {
+ const parts = version.slice(1).filter((part) => part !== undefined);
+ return installedVersions().filter((candidate) => (
+ candidate.slice(1).split(".").slice(0, parts.length).join(".") === parts.join(".")
+ )).at(-1) ?? null;
+ }
+ if (name === "node" || name === "stable") return installedVersions().at(-1) ?? null;
+ if (!NVM_ALIAS_NAME.test(name)) return null;
+ try {
+ return resolve(readFile(path.posix.join(nvmDir, "alias", ...name.split("/"))), depth + 1);
+ } catch {
+ return null;
+ }
+ };
+ return resolve("default", 0);
+}
+
+const nvmDefaultBin = (home, exists, readFile, readdir) => {
+ const version = nvmDefaultVersion(home, { readFile, readdir });
+ if (!version) return null;
const bin = path.posix.join(home, ".nvm", "versions", "node", version, "bin");
try {
return exists(bin) ? bin : null;
@@ -578,6 +638,7 @@ export function desktopToolPath({
env = {},
exists = existsSync,
readFile = (file) => readFileSync(file, "utf8"),
+ readdir = (dir) => readdirSync(dir),
} = {}) {
const delimiter = platform === "win32" ? ";" : ":";
const current = String(pathEnv).split(delimiter).filter(Boolean);
@@ -594,7 +655,7 @@ export function desktopToolPath({
seen.add(key);
};
for (const dir of desktopToolDirectories(platform, home, env)) add(dir);
- if (platform !== "win32") add(nvmDefaultBin(home, exists, readFile));
+ if (platform !== "win32") add(nvmDefaultBin(home, exists, readFile, readdir));
return [...extras, ...current].join(delimiter);
}
@@ -616,6 +677,7 @@ export function createAcpSpawnPlan(input, cwd, deps = {}) {
env,
exists: deps.exists ?? existsSync,
readFile: deps.readFile ?? ((file) => readFileSync(file, "utf8")),
+ readdir: deps.readdir ?? ((dir) => readdirSync(dir)),
});
return {
command,
@@ -739,9 +801,11 @@ export function automaticAcpPermissionResponse(params) {
return { outcome: option ? { outcome: "selected", optionId: option.optionId } : { outcome: "cancelled" } };
}
-const createEdgeEverAcpClient = (requestId, emit, allowPermissions, onAuthStatus) => ({
+const createEdgeEverAcpClient = (requestId, emit, allowPermissions, onAuthStatus, onAuthUrl) => ({
extNotification(method, params) {
if (method === "_auth/status_update") onAuthStatus?.(params?.authStatus);
+ // Only an active CodeBuddy sign-in passes a handler; other sessions ignore it.
+ if (method === "_codebuddy.ai/authUrl") onAuthUrl?.(params?.authUrl);
},
requestPermission(params) {
// Probe, install, and sign-in sessions do not originate from a user prompt.
@@ -867,7 +931,9 @@ export function createAcpHostRuntime(options = {}) {
return adapt(resolveAcpCommand(input, commandDeps));
};
- const connect = async (command, requestId, emit, signal, authMethodId, mcpServers = [], allowPermissions = false, workBuddyAuth = null, verifyWorkBuddy = false) => {
+ // accountCheck: true verifies WorkBuddy's stored token; "codebuddy" treats a
+ // missing account or token as signed out. onAuthUrl receives CodeBuddy login links.
+ const connect = async (command, requestId, emit, signal, authMethodId, mcpServers = [], allowPermissions = false, workBuddyAuth = null, accountCheck = false, onAuthUrl = null) => {
const sink = emit && typeof emit === "object" && typeof emit.emit === "function"
? emit
: { emit: typeof emit === "function" ? emit : () => {} };
@@ -929,7 +995,7 @@ export function createAcpHostRuntime(options = {}) {
});
child.stderr?.on("end", () => { recordStderr(stderrBuffer); stderrBuffer = ""; });
const stream = acpNdJsonStream(child);
- const connection = new ClientSideConnection(() => createEdgeEverAcpClient(liveRequestId, notifyConnection, allowPermissions, onAuthStatus), stream);
+ const connection = new ClientSideConnection(() => createEdgeEverAcpClient(liveRequestId, notifyConnection, allowPermissions, onAuthStatus, authMethodId ? onAuthUrl : null), stream);
void connection.closed?.catch(() => {});
const initialized = await connection.initialize(acpInitializeParams(version));
authMethods = publicAuthMethods(initialized);
@@ -940,7 +1006,14 @@ export function createAcpHostRuntime(options = {}) {
if (result?.userInfo && !(typeof token === "string" && token)) throw new Error("workbuddy_credentials_unavailable");
return typeof token === "string" && token ? createHash("sha256").update(token).digest("hex") : null;
};
- if (verifyWorkBuddy) await readCredential();
+ const hasCodeBuddyAccount = async () => {
+ const result = await connection.extMethod("_codebuddy.ai/getUserInfo", {});
+ const token = result?.userInfo?.accessToken ?? result?.userInfo?.token;
+ return Boolean(result?.userInfo) && typeof token === "string" && token.length > 0;
+ };
+ if (accountCheck === "codebuddy") {
+ if (!authMethodId && !(await hasCodeBuddyAccount())) throw RequestError.authRequired();
+ } else if (accountCheck) await readCredential();
if (authMethodId) {
if (!authMethods.some((method) => method.id === authMethodId)) throw new Error("invalid_auth_method");
authenticationPending = true;
@@ -950,6 +1023,8 @@ export function createAcpHostRuntime(options = {}) {
}
if (workBuddyAuth) await authenticateWorkBuddy(workBuddyAuth, authMethodId, signal, { readCredential });
else await connection.authenticate({ methodId: authMethodId });
+ // A resolved authenticate call is not proof of a usable sign-in.
+ if (accountCheck === "codebuddy" && !(await hasCodeBuddyAccount())) throw new Error("authentication_failed");
authenticationPending = false;
}
if (authStatusKind === "none") throw RequestError.authRequired();
@@ -991,6 +1066,62 @@ export function createAcpHostRuntime(options = {}) {
}
};
+ // One CodeBuddy sign-in at a time. The CLI opens the login page itself; the
+ // validated link stays in the main process for an explicit "reopen" request.
+ let codeBuddyLogin = null;
+ const authenticateCodeBuddy = async (input, resolved) => {
+ const id = "codebuddy";
+ codeBuddyLogin?.cancel.abort();
+ const attempt = { cancel: new AbortController(), url: null, reopenedAt: 0 };
+ codeBuddyLogin = attempt;
+ const onAuthUrl = (raw) => {
+ if (codeBuddyLogin !== attempt || attempt.cancel.signal.aborted) return;
+ const url = codeBuddyLoginUrl(raw);
+ // Never log the link: its query can carry a temporary login credential.
+ if (!url) {
+ try { options.onDiagnostic?.({ requestId: `auth-${id}`, message: "codebuddy_login_url_rejected" }); } catch { /* diagnostics are optional */ }
+ return;
+ }
+ attempt.url = url;
+ };
+ let connected;
+ try {
+ connected = await withHandshakeTimeout((signal) => connect(
+ resolved.command, `auth-${id}`, () => {}, AbortSignal.any([signal, attempt.cancel.signal]),
+ input.methodId, [], false, null, "codebuddy", onAuthUrl,
+ ), authenticationTimeoutMs);
+ await connected.stop();
+ await cleanupWorkspace(connected.cwd);
+ connected = null;
+ if (attempt.cancel.signal.aborted) throw Object.assign(new Error("authentication_cancelled"), { cancelled: true });
+ // Login is useful only if a fresh chat process restores the account.
+ connected = await withHandshakeTimeout((signal) => connect(
+ resolved.command, `auth-check-${id}`, () => {}, AbortSignal.any([signal, attempt.cancel.signal]),
+ undefined, [], false, null, "codebuddy",
+ ));
+ const adapter = { ...adapterShell(id), state: "available", promptCapabilities: connected.promptCapabilities, authMethods: connected.authMethods };
+ latestStatus.set(id, adapter);
+ return adapter;
+ } catch (error) {
+ const authMethods = error?.authMethods ?? latestStatus.get(id)?.authMethods ?? [];
+ const detail = attempt.cancel.signal.aborted ? "authentication_cancelled"
+ : error?.code === "TIMEOUT" && error?.authenticationPending ? "authentication_timeout"
+ : error?.message === "authentication_failed" || isAuthRequiredError(error) ? "authentication_failed"
+ : null;
+ const adapter = detail
+ ? { ...adapterShell(id), state: "needs_login", detail, authMethods }
+ : { ...adapterShell(id), ...failureFields(classifyAcpFailure(error)), ...(authMethods.length ? { authMethods } : {}) };
+ latestStatus.set(id, adapter);
+ return adapter;
+ } finally {
+ if (codeBuddyLogin === attempt) codeBuddyLogin = null;
+ if (connected) {
+ await connected.stop();
+ await cleanupWorkspace(connected.cwd);
+ }
+ }
+ };
+
const withHandshakeTimeout = async (operation, timeoutMs = handshakeTimeoutMs) => {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -1059,7 +1190,7 @@ export function createAcpHostRuntime(options = {}) {
const sink = { emit: (event) => { if (requestRef.open) requestRef.notify(event); } };
const connected = await withHandshakeTimeout((signal) => connect(
spec.command, () => requestRef.id, sink, signal, undefined,
- mcpBridge ? [mcpServerFor(mcpBridge)] : [], true, null, spec.verifyWorkBuddy,
+ mcpBridge ? [mcpServerFor(mcpBridge)] : [], true, null, spec.accountCheck,
));
spec.rememberPromptStatus({
state: "available",
@@ -1109,7 +1240,7 @@ export function createAcpHostRuntime(options = {}) {
},
clearAdapterStatus(id) { latestStatus.delete(id); },
listAdapters(configuredPaths = {}) {
- return ["codex", "claudeCode", "antigravity", "openClaw", "hermesAgent", "grokBuild", "deepseekHarness", "piAgent", "workbuddyCn", "workbuddyIntl"].map((id) => {
+ return ["codex", "claudeCode", "antigravity", "openClaw", "hermesAgent", "grokBuild", "deepseekHarness", "piAgent", "workbuddyCn", "workbuddyIntl", "codebuddy"].map((id) => {
if (installingIds.has(id)) return { ...adapterShell(id), state: "installing", ...(manager?.get(id) ? { managed: true, version: manager.get(id).version } : {}), ...(updateFailures.has(id) ? { updateError: updateFailures.get(id) } : {}) };
const customPath = configuredPaths[id];
const resolved = resolveCommand({ id, path: customPath }, { prepareProxy: false });
@@ -1195,7 +1326,7 @@ export function createAcpHostRuntime(options = {}) {
if (!resolved.ok) return adapterFromResolution(id, resolved);
let connected;
try {
- connected = await withHandshakeTimeout((signal) => connect(resolved.command, `probe-${id}`, () => {}, signal, undefined, [], false, null, id === "workbuddyCn" || id === "workbuddyIntl"));
+ connected = await withHandshakeTimeout((signal) => connect(resolved.command, `probe-${id}`, () => {}, signal, undefined, [], false, null, accountCheckFor(id)));
} catch (error) {
const failure = { ...adapterShell(id), ...failureFields(classifyAcpFailure(error)), ...(error.authMethods?.length ? { authMethods: error.authMethods } : {}), ...(resolved.version ? { version: resolved.version, managed: true } : {}) };
latestStatus.set(id, failure);
@@ -1220,6 +1351,7 @@ export function createAcpHostRuntime(options = {}) {
if (typeof input.methodId !== "string" || !input.methodId || input.methodId.length > 120) throw new Error("invalid_auth_method");
const resolved = resolveCommand(input);
if (!resolved.ok) return adapterFromResolution(id, resolved);
+ if (id === "codebuddy") return authenticateCodeBuddy(input, resolved);
let connected;
try {
connected = await withHandshakeTimeout(async (signal) => {
@@ -1296,7 +1428,7 @@ export function createAcpHostRuntime(options = {}) {
command: resolved.command,
wantsNotes,
access,
- verifyWorkBuddy: input.adapterId === "workbuddyCn" || input.adapterId === "workbuddyIntl",
+ accountCheck: accountCheckFor(input.adapterId),
rememberPromptStatus,
}));
return { ready: true };
@@ -1359,7 +1491,7 @@ export function createAcpHostRuntime(options = {}) {
// Dropping the other process makes the next normal turn replay the transcript.
if (key) await retireSiblingSessions(key, sessionKey);
- const verifyWorkBuddy = input.adapterId === "workbuddyCn" || input.adapterId === "workbuddyIntl";
+ const accountCheck = accountCheckFor(input.adapterId);
const claim = (session) => {
session.requestRef.id = requestId;
session.requestRef.open = true;
@@ -1369,7 +1501,7 @@ export function createAcpHostRuntime(options = {}) {
};
if (!warm && key) {
const pending = preparing.get(key) ?? startWarmSession(key, {
- command: resolved.command, wantsNotes, access, verifyWorkBuddy, rememberPromptStatus,
+ command: resolved.command, wantsNotes, access, accountCheck, rememberPromptStatus,
});
try {
warm = await pending;
@@ -1401,7 +1533,7 @@ export function createAcpHostRuntime(options = {}) {
try {
connected = await withHandshakeTimeout((signal) => connect(
resolved.command, () => spawnedRequest.id, sink, signal, undefined,
- mcpBridge ? [mcpServerFor(mcpBridge)] : [], true, null, verifyWorkBuddy,
+ mcpBridge ? [mcpServerFor(mcpBridge)] : [], true, null, accountCheck,
));
rememberPromptStatus({
state: "available",
@@ -1503,6 +1635,24 @@ export function createAcpHostRuntime(options = {}) {
return { requestId, rejectedAttachments: content.rejectedAttachments };
},
+ // Ends an in-progress CodeBuddy sign-in; the process and workspace are cleaned up.
+ cancelAuthentication(id) {
+ if (id !== "codebuddy" || !codeBuddyLogin) return { cancelled: false };
+ codeBuddyLogin.cancel.abort();
+ return { cancelled: true };
+ },
+
+ // Reopens the validated login page of the current CodeBuddy sign-in only.
+ reopenLoginPage(id) {
+ const attempt = id === "codebuddy" ? codeBuddyLogin : null;
+ if (!attempt?.url || attempt.cancel.signal.aborted || !options.openExternal) return { opened: false };
+ const now = Date.now();
+ if (now - attempt.reopenedAt < CODEBUDDY_REOPEN_INTERVAL_MS) return { opened: false };
+ attempt.reopenedAt = now;
+ void Promise.resolve(options.openExternal(attempt.url)).catch(() => {});
+ return { opened: true };
+ },
+
async cancel(requestId) {
const session = active.get(requestId);
if (!session) return { ok: true };
@@ -1580,6 +1730,14 @@ export function registerAcpIpc(ipcMain, runtime = createAcpHostRuntime(), {
if (!allowInstall(event.sender, event)) throw new Error("adapter_auth_forbidden");
return runtime.authenticateAdapter(await withRecordedPath(input));
});
+ ipcMain.handle("desktop:acp-cancel-auth", (event, id) => {
+ if (!allowInstall(event.sender, event)) throw new Error("adapter_auth_forbidden");
+ return runtime.cancelAuthentication(id);
+ });
+ ipcMain.handle("desktop:acp-reopen-login", (event, id) => {
+ if (!allowInstall(event.sender, event)) throw new Error("adapter_auth_forbidden");
+ return runtime.reopenLoginPage(id);
+ });
ipcMain.handle("desktop:acp-prepare", async (event, input) => {
if (!allowPrompt(event.sender, event)) throw new Error("acp_prepare_forbidden");
return runtime.prepare(await withRecordedPath(input));
diff --git a/apps/desktop/src/main/acp-host.test.mjs b/apps/desktop/src/main/acp-host.test.mjs
index c5391d58..2979f0a3 100644
--- a/apps/desktop/src/main/acp-host.test.mjs
+++ b/apps/desktop/src/main/acp-host.test.mjs
@@ -86,9 +86,9 @@ const collector = () => {
};
};
-const fakeAgentSource = ({ reportPath, secretPath, allowImage, allowEmbedded, hold, requireAuth, advertiseAuth, promptRefusal, hangAuth, hangSession, failSessionBeforeLogin, workBuddyAccountApi, workBuddyLoginFailure, workBuddyUnreadable, workBuddyUnreadableAfterLogin, authMethodId = "browser", authStatusKind, advertiseAuthStatus = false, authStatusDelay = 20, stderrText, promptAuthStatusKind }) => `#!/usr/bin/env bun
+const fakeAgentSource = ({ reportPath, secretPath, allowImage, allowEmbedded, hold, requireAuth, advertiseAuth, promptRefusal, hangAuth, hangSession, failSessionBeforeLogin, workBuddyAccountApi, workBuddyLoginFailure, workBuddyUnreadable, workBuddyUnreadableAfterLogin, authMethodId = "browser", authStatusKind, advertiseAuthStatus = false, authStatusDelay = 20, stderrText, promptAuthStatusKind, codeBuddy }) => `#!/usr/bin/env bun
import * as acp from ${JSON.stringify(sdkHref)};
-import { writeFileSync, readFileSync, appendFileSync } from "node:fs";
+import { writeFileSync, readFileSync, appendFileSync, existsSync } from "node:fs";
const reportPath = ${JSON.stringify(reportPath)};
const secretPath = ${JSON.stringify(secretPath)};
@@ -105,6 +105,10 @@ if (${workBuddyAccountApi ? "true" : "false"}) {
try { Object.assign(report, JSON.parse(readFileSync(reportPath, "utf8"))); authenticated = report.accountLogin === true && ${workBuddyLoginFailure ? "false" : "true"}; } catch {}
}
if (${workBuddyUnreadable ? "true" : "false"}) authenticated = true;
+// CodeBuddy keeps its login in its own config directory; a file stands in for it.
+const codeBuddy = ${JSON.stringify(codeBuddy ?? null)};
+if (codeBuddy?.persist && existsSync(reportPath + ".login")) authenticated = true;
+const codeBuddyRestored = authenticated;
const restoredAccount = authenticated;
const save = () => writeFileSync(reportPath, JSON.stringify(report));
// Like WorkBuddy, serve the account API only when started with --serve, which
@@ -183,14 +187,19 @@ acp.agent({ name: "edgeever-fake-agent" })
authMethods: requireAuth || advertiseAuth ? [{ id: ${JSON.stringify(authMethodId)}, name: "Browser" }] : [],
};
})
- .onRequest("_codebuddy.ai/getUserInfo", (params) => params, () => ({ userInfo: authenticated ? { ${workBuddyUnreadable ? 'userId: "saved-user"' : 'accessToken: "new-token"'} , ...(${workBuddyUnreadableAfterLogin ? "true" : "false"} && restoredAccount ? { accessToken: undefined, userId: "saved-user" } : {}) } : undefined }))
- .onRequest("authenticate", (ctx) => {
+ .onRequest("_codebuddy.ai/getUserInfo", (params) => params, async () => {
+ if (codeBuddy?.slowRestore && codeBuddyRestored) await new Promise((resolve) => setTimeout(resolve, 3000));
+ return { userInfo: authenticated ? { ${workBuddyUnreadable || codeBuddy?.tokenless ? 'userId: "saved-user"' : 'accessToken: "new-token"'} , ...(${workBuddyUnreadableAfterLogin ? "true" : "false"} && restoredAccount ? { accessToken: undefined, userId: "saved-user" } : {}) } : undefined };
+ })
+ .onRequest("authenticate", async (ctx) => {
report.authMethod = ctx.params.methodId;
+ for (const authUrl of codeBuddy?.authUrls ?? []) await ctx.client.notify("_codebuddy.ai/authUrl", { authUrl, provider: "fixture" });
if (${hangAuth ? "true" : "false"}) {
save();
return new Promise(() => {});
}
authenticated = true;
+ if (codeBuddy?.persist && !codeBuddy?.forgetAfterLogin) writeFileSync(reportPath + ".login", "1");
if (${advertiseAuthStatus ? "true" : "false"}) void ctx.client.notify("_auth/status_update", { authStatus: { kind: "api_key", label: "Fixture" } });
save();
return {};
@@ -1203,6 +1212,136 @@ describe("ACP stdio session", () => {
} finally { await rm(directory, { recursive: true, force: true }); }
}, 10_000);
+ const codeBuddyRuntime = (scriptPath, extra = {}) => {
+ const opened = [];
+ const diagnostics = [];
+ const runtime = createAcpHostRuntime({
+ openExternal: (url) => { opened.push(url); },
+ onDiagnostic: (event) => diagnostics.push(event),
+ adapterManager: { get: (id) => id === "codebuddy" ? { command: { command: process.execPath, args: [scriptPath], unsetEnv: ["CODEBUDDY_INTERNET_ENVIRONMENT", "CODEBUDDY_INTERNET_ENVIROMENT"] } } : null },
+ ...extra,
+ });
+ return { runtime, opened, diagnostics };
+ };
+ const loginLink = "https://copilot.tencent.com/login?state=private-login-state";
+ const waitFor = async (check, timeoutMs = 5_000) => {
+ const started = Date.now();
+ while (!(await check())) {
+ if (Date.now() - started > timeoutMs) throw new Error("timed out waiting");
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ };
+
+ sessionTest("CodeBuddy reports success only after a fresh process restores the account", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-codebuddy-login-"));
+ const reportPath = path.join(directory, "report.json");
+ try {
+ const scriptPath = await writeFakeAgent(directory, { reportPath, advertiseAuth: true, authMethodId: "internal", codeBuddy: { persist: true, authUrls: [loginLink] } });
+ const { runtime, opened, diagnostics } = codeBuddyRuntime(scriptPath);
+ // The CLI starts a session without an account; EdgeEver must still call it signed out.
+ expect(await runtime.probeAdapter({ id: "codebuddy" })).toMatchObject({ state: "needs_login", authMethods: [{ id: "internal", name: "Browser" }] });
+ expect(await runtime.authenticateAdapter({ id: "codebuddy", methodId: "internal" })).toMatchObject({ state: "available" });
+ // A second, fresh process must restore the account before success is reported.
+ const sessions = (await readFile(`${reportPath}.sessions`, "utf8")).trim().split("\n");
+ expect(sessions).toHaveLength(2);
+ expect(new Set(sessions).size).toBe(2);
+ expect(sessions[1]).toBe((await readFile(`${reportPath}.pid`, "utf8")).trim());
+ expect(await runtime.probeAdapter({ id: "codebuddy" })).toMatchObject({ state: "available" });
+ // The CLI opens the browser itself; EdgeEver opens nothing on its own.
+ expect(opened).toEqual([]);
+ expect(runtime.reopenLoginPage("codebuddy")).toEqual({ opened: false });
+ expect(JSON.stringify(diagnostics)).not.toContain("private-login-state");
+ } finally { await rm(directory, { recursive: true, force: true }); }
+ }, 15_000);
+
+ for (const [name, codeBuddy] of [
+ ["an account without a token", { persist: true, tokenless: true }],
+ ["a login the next process cannot restore", { persist: true, forgetAfterLogin: true }],
+ ]) sessionTest(`CodeBuddy treats ${name} as signed out`, async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-codebuddy-signed-out-"));
+ const reportPath = path.join(directory, "report.json");
+ try {
+ const scriptPath = await writeFakeAgent(directory, { reportPath, advertiseAuth: true, authMethodId: "internal", codeBuddy });
+ const { runtime } = codeBuddyRuntime(scriptPath);
+ expect(await runtime.authenticateAdapter({ id: "codebuddy", methodId: "internal" })).toMatchObject({
+ state: "needs_login", detail: "authentication_failed", authMethods: [{ id: "internal", name: "Browser" }],
+ });
+ expect(await runtime.probeAdapter({ id: "codebuddy" })).toMatchObject({ state: "needs_login" });
+ const events = [];
+ await runtime.prompt({ adapterId: "codebuddy", prompt: "hello", noteAccess: false }, (event) => events.push(event));
+ expect(events).toMatchObject([{ type: "error", message: "needs_login" }]);
+ } finally { await rm(directory, { recursive: true, force: true }); }
+ }, 15_000);
+
+ sessionTest("CodeBuddy sign-in keeps only verified links, throttles reopening and can be cancelled", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-codebuddy-cancel-"));
+ const reportPath = path.join(directory, "report.json");
+ try {
+ const scriptPath = await writeFakeAgent(directory, {
+ reportPath, advertiseAuth: true, hangAuth: true, authMethodId: "external",
+ codeBuddy: { authUrls: [loginLink, "https://evil.example/login?state=leak", "http://www.codebuddy.ai/login", "https://www.codebuddy.ai/login?state=private-login-state", "https://www.codebuddy.ai/login?state=private-login-state"] },
+ });
+ const { runtime, opened, diagnostics } = codeBuddyRuntime(scriptPath);
+ expect(runtime.cancelAuthentication("codebuddy")).toEqual({ cancelled: false });
+ const pending = runtime.authenticateAdapter({ id: "codebuddy", methodId: "external" });
+ await waitFor(() => diagnostics.filter((event) => event.message === "codebuddy_login_url_rejected").length === 2);
+ await waitFor(() => runtime.reopenLoginPage("codebuddy").opened);
+ // Repeated notifications and clicks inside the interval do not open more pages.
+ expect(runtime.reopenLoginPage("codebuddy")).toEqual({ opened: false });
+ expect(opened).toEqual(["https://www.codebuddy.ai/login?state=private-login-state"]);
+ expect(runtime.reopenLoginPage("claudeCode")).toEqual({ opened: false });
+ expect(runtime.cancelAuthentication("claudeCode")).toEqual({ cancelled: false });
+ const pid = Number(await readFile(`${reportPath}.pid`, "utf8"));
+ expect(runtime.cancelAuthentication("codebuddy")).toEqual({ cancelled: true });
+ expect(await pending).toMatchObject({ state: "needs_login", detail: "authentication_cancelled", authMethods: [{ id: "external", name: "Browser" }] });
+ await waitFor(() => { try { process.kill(pid, 0); return false; } catch { return true; } });
+ expect(runtime.cancelAuthentication("codebuddy")).toEqual({ cancelled: false });
+ expect(runtime.reopenLoginPage("codebuddy")).toEqual({ opened: false });
+ const logged = JSON.stringify(diagnostics);
+ expect(logged).not.toContain("private-login-state");
+ expect(logged).not.toContain("evil.example");
+ expect((await readReport(reportPath)).newSession).toBeNull();
+ } finally { await rm(directory, { recursive: true, force: true }); }
+ }, 15_000);
+
+ sessionTest("CodeBuddy cancel during the post-login check is reported as cancelled", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-codebuddy-cancel-check-"));
+ const reportPath = path.join(directory, "report.json");
+ try {
+ const scriptPath = await writeFakeAgent(directory, { reportPath, advertiseAuth: true, authMethodId: "internal", codeBuddy: { persist: true, slowRestore: true } });
+ const { runtime } = codeBuddyRuntime(scriptPath);
+ const pending = runtime.authenticateAdapter({ id: "codebuddy", methodId: "internal" });
+ // The login process has saved the account; the fresh check process is still restoring it.
+ await waitFor(async () => (await readFile(`${reportPath}.sessions`, "utf8").catch(() => "")).trim().split("\n").filter(Boolean).length === 1
+ && (await readFile(`${reportPath}.pid`, "utf8").catch(() => "")) !== (await readFile(`${reportPath}.sessions`, "utf8")).trim());
+ expect(runtime.cancelAuthentication("codebuddy")).toEqual({ cancelled: true });
+ expect(await pending).toMatchObject({ state: "needs_login", detail: "authentication_cancelled" });
+ } finally { await rm(directory, { recursive: true, force: true }); }
+ }, 15_000);
+
+ sessionTest("CodeBuddy sign-in that never finishes ends as a timeout", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-codebuddy-timeout-"));
+ const reportPath = path.join(directory, "report.json");
+ try {
+ const scriptPath = await writeFakeAgent(directory, { reportPath, advertiseAuth: true, hangAuth: true, authMethodId: "internal", codeBuddy: { authUrls: [loginLink] } });
+ const { runtime } = codeBuddyRuntime(scriptPath, { authenticationTimeoutMs: 1_500 });
+ expect(await runtime.authenticateAdapter({ id: "codebuddy", methodId: "internal" })).toMatchObject({ state: "needs_login", detail: "authentication_timeout" });
+ expect(runtime.reopenLoginPage("codebuddy")).toEqual({ opened: false });
+ } finally { await rm(directory, { recursive: true, force: true }); }
+ }, 10_000);
+
+ sessionTest("other agents ignore CodeBuddy login links", async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-codebuddy-other-"));
+ const reportPath = path.join(directory, "report.json");
+ try {
+ const scriptPath = await writeFakeAgent(directory, { reportPath, requireAuth: true, codeBuddy: { authUrls: [loginLink] } });
+ const opened = [];
+ const runtime = createAcpHostRuntime({ openExternal: (url) => { opened.push(url); } });
+ expect(await runtime.authenticateAdapter({ id: "antigravity", path: scriptPath, methodId: "browser" })).toMatchObject({ state: "available" });
+ expect(opened).toEqual([]);
+ } finally { await rm(directory, { recursive: true, force: true }); }
+ }, 10_000);
+
for (const adapterId of ["workbuddyIntl", "workbuddyCn"]) for (const loginFailure of [false, true]) sessionTest(`${adapterId} account login ${loginFailure ? "returns failure without hanging" : "verifies ACP session without the broken authenticate RPC"}`, async () => {
const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-workbuddy-auth-"));
const reportPath = path.join(directory, "report.json");
@@ -1746,8 +1885,14 @@ test("desktop preload and main process expose the ACP host", async () => {
expect(preload).toContain('promptAcp: (input) => ipcRenderer.invoke("desktop:acp-prompt", input)');
expect(preload).toContain('cancelAcp: (requestId) => ipcRenderer.invoke("desktop:acp-cancel", requestId)');
expect(preload).toContain('ipcRenderer.on("desktop:acp-event"');
+ expect(preload).toContain('cancelAcpAuthentication: (id) => ipcRenderer.invoke("desktop:acp-cancel-auth", id)');
+ expect(preload).toContain('reopenAcpLoginPage: (id) => ipcRenderer.invoke("desktop:acp-reopen-login", id)');
+ expect(main).toContain("openExternal: (url) => shell.openExternal(url)");
const handlers = new Map();
registerAcpIpc({ handle: (channel, handler) => handlers.set(channel, handler) });
- expect([...handlers.keys()]).toEqual(["desktop:acp-list", "desktop:acp-choose-path", "desktop:acp-probe", "desktop:acp-install", "desktop:acp-authenticate", "desktop:acp-prepare", "desktop:acp-prompt", "desktop:acp-cancel"]);
+ expect([...handlers.keys()]).toEqual(["desktop:acp-list", "desktop:acp-choose-path", "desktop:acp-probe", "desktop:acp-install", "desktop:acp-authenticate", "desktop:acp-cancel-auth", "desktop:acp-reopen-login", "desktop:acp-prepare", "desktop:acp-prompt", "desktop:acp-cancel"]);
await expect(handlers.get("desktop:acp-prompt")({ sender: {} }, { prompt: "test" })).rejects.toThrow("acp_prompt_forbidden");
+ // Sign-in controls follow the same sender check as starting a sign-in.
+ expect(() => handlers.get("desktop:acp-cancel-auth")({ sender: {} }, "codebuddy")).toThrow("adapter_auth_forbidden");
+ expect(() => handlers.get("desktop:acp-reopen-login")({ sender: {} }, "codebuddy")).toThrow("adapter_auth_forbidden");
});
diff --git a/apps/desktop/src/main/codebuddy-cli.mjs b/apps/desktop/src/main/codebuddy-cli.mjs
new file mode 100644
index 00000000..37a1f9f7
--- /dev/null
+++ b/apps/desktop/src/main/codebuddy-cli.mjs
@@ -0,0 +1,136 @@
+// Standalone CodeBuddy CLI (`@tencent-ai/codebuddy-code`) support for the local
+// agent list. Only the user's own npm installation is used; WorkBuddy's bundled
+// CLI, `--serve`, credential bridging and gateway login stay with WorkBuddy.
+import { spawnSync } from "node:child_process";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+export const CODEBUDDY_PACKAGE = "@tencent-ai/codebuddy-code";
+// The CLI picks its region from the login method; an inherited override can
+// route requests to the wrong endpoint, so EdgeEver never forwards one.
+export const CODEBUDDY_UNSET_ENV = ["CODEBUDDY_INTERNET_ENVIRONMENT", "CODEBUDDY_INTERNET_ENVIROMENT"];
+// Hosts observed for the verified login methods: `internal` (WeChat) opens
+// copilot.tencent.com and `external` (Google / GitHub) opens www.codebuddy.ai.
+// Other hosts, including enterprise domains, are not opened by EdgeEver.
+export const CODEBUDDY_LOGIN_HOSTS = ["copilot.tencent.com", "codebuddy.ai"];
+
+export function codeBuddyLoginUrl(value) {
+ if (typeof value !== "string" || value.length > 4096) return null;
+ let url;
+ try { url = new URL(value); } catch { return null; }
+ if (url.protocol !== "https:" || url.username || url.password || url.port) return null;
+ const host = url.hostname.toLowerCase().replace(/\.$/, "");
+ return CODEBUDDY_LOGIN_HOSTS.some((root) => host === root || host.endsWith(`.${root}`)) ? url.href : null;
+}
+
+const isExecutableFile = (candidate, deps) => {
+ try {
+ if (!deps.stat(candidate).isFile()) return false;
+ deps.access(candidate, deps.executableMode);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+// Every executable `name` on the search path, in order, so an invalid early
+// candidate (for example a version-manager shim) does not hide a later install.
+const findAll = (names, dirs, deps) => dirs.filter(Boolean).flatMap((dir) => (
+ names.map((name) => deps.pathImpl.join(dir, name)).filter((candidate) => isExecutableFile(candidate, deps))
+));
+
+const findIn = (names, dirs, deps) => findAll(names, dirs, deps)[0] ?? null;
+
+const isOfficialPackage = (root, deps) => {
+ try {
+ return JSON.parse(deps.readFile(deps.pathImpl.join(root, "package.json")))?.name === CODEBUDDY_PACKAGE;
+ } catch {
+ return false;
+ }
+};
+
+// The entry inside the official npm package, never WorkBuddy's bundled copy.
+const officialEntry = (entry, deps) => {
+ if (!entry || /app\.asar/i.test(entry)) return null;
+ try { if (!deps.exists(entry)) return null; } catch { return null; }
+ const root = deps.pathImpl.dirname(deps.pathImpl.dirname(entry));
+ return isOfficialPackage(root, deps) ? { entry, root } : null;
+};
+
+const realEntry = (file, deps) => {
+ try { return officialEntry(deps.realpath(file), deps); } catch { return null; }
+};
+
+// asdf, mise and Volta put shims (scripts or links to the manager) on PATH
+// instead of links to the npm entry. Ask the manager which real executable the
+// shim runs, as a terminal would, and fall back to the next candidate otherwise.
+const SHIM_LOOKUP_TTL_MS = 30_000;
+const shimLookups = new Map();
+
+const shimManager = (candidate, deps) => {
+ const { pathImpl, home, env = {} } = deps;
+ if (!home) return null;
+ const dir = pathImpl.dirname(candidate);
+ const asdfShims = pathImpl.join(env.ASDF_DATA_DIR || pathImpl.join(home, ".asdf"), "shims");
+ const miseShims = pathImpl.join(env.MISE_DATA_DIR || pathImpl.join(home, ".local", "share", "mise"), "shims");
+ const voltaBin = pathImpl.join(env.VOLTA_HOME || pathImpl.join(home, ".volta"), "bin");
+ if (dir === asdfShims) return { name: "asdf", extraDirs: [pathImpl.join(home, ".asdf", "bin")] };
+ if (dir === miseShims) return { name: "mise", extraDirs: [pathImpl.join(home, ".local", "bin")] };
+ if (dir === voltaBin) return { name: "volta", extraDirs: [voltaBin] };
+ return null;
+};
+
+const defaultRunManager = (command, args, options) => {
+ const key = `${command}\0${args.join("\0")}`;
+ const cached = shimLookups.get(key);
+ if (cached && Date.now() - cached.at < SHIM_LOOKUP_TTL_MS) return cached.output;
+ let output = null;
+ try {
+ const result = spawnSync(command, args, { ...options, encoding: "utf8", timeout: 5_000, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
+ if (result.status === 0) output = String(result.stdout ?? "").trim().split(/\r?\n/).pop() || null;
+ } catch { /* An unusable manager means this shim is skipped. */ }
+ shimLookups.set(key, { at: Date.now(), output });
+ return output;
+};
+
+const resolveShim = (candidate, dirs, deps) => {
+ const manager = shimManager(candidate, deps);
+ if (!manager) return null;
+ const binary = findIn([manager.name], [...manager.extraDirs, ...dirs], deps);
+ if (!binary) return null;
+ const run = deps.runManager ?? defaultRunManager;
+ const target = run(binary, ["which", "codebuddy"], {
+ // A neutral directory resolves the user's global version, like the CLI's workspace.
+ cwd: deps.tmpdir ?? tmpdir(),
+ env: { ...deps.env, PATH: dirs.join(":") },
+ });
+ return target && deps.pathImpl.isAbsolute(target) ? realEntry(target, deps) : null;
+};
+
+// Resolves `node <package>/bin/codebuddy --acp`. Running the JS entry with an
+// explicit Node avoids `#!/usr/bin/env node` lookups on POSIX and `.cmd` shims
+// (which would need a shell) on Windows. The CLI ships native modules, so it
+// needs a real Node rather than Electron's embedded runtime.
+export function resolveCodeBuddyCli(deps) {
+ const windows = deps.platform === "win32";
+ const pathImpl = windows ? path.win32 : path.posix;
+ const search = { ...deps, pathImpl };
+ const dirs = String(deps.toolPath ?? "").split(windows ? ";" : ":").filter(Boolean);
+ const nodeName = windows ? "node.exe" : "node";
+ for (const shim of findAll([windows ? "codebuddy.cmd" : "codebuddy"], dirs, search)) {
+ const shimDir = pathImpl.dirname(shim);
+ // npm writes codebuddy.cmd next to node_modules in the global prefix.
+ const found = windows
+ ? officialEntry(pathImpl.join(shimDir, "node_modules", "@tencent-ai", "codebuddy-code", "bin", "codebuddy"), search)
+ : realEntry(shim, search) ?? resolveShim(shim, dirs, search);
+ if (!found) continue;
+ // Prefer the Node that installed the CLI: the npm prefix (nvm, asdf, mise,
+ // Homebrew, ~/.local) or the shim's directory, then the tool path.
+ // <prefix>/lib/node_modules/@tencent-ai/codebuddy-code -> <prefix>/bin
+ const prefixBin = windows ? null : pathImpl.join(pathImpl.resolve(found.root, "..", "..", "..", ".."), "bin");
+ const node = findIn([nodeName], [prefixBin, shimDir, ...dirs], search);
+ if (!node) return { ok: false, state: "failed", detail: "node_missing" };
+ return { ok: true, command: { command: node, args: [found.entry, "--acp"], env: {}, unsetEnv: CODEBUDDY_UNSET_ENV } };
+ }
+ return { ok: false, state: "not_installed" };
+}
diff --git a/apps/desktop/src/main/codebuddy-cli.test.mjs b/apps/desktop/src/main/codebuddy-cli.test.mjs
new file mode 100644
index 00000000..d59293ce
--- /dev/null
+++ b/apps/desktop/src/main/codebuddy-cli.test.mjs
@@ -0,0 +1,302 @@
+import { describe, expect, test } from "bun:test";
+import { existsSync, realpathSync } from "node:fs";
+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { CODEBUDDY_UNSET_ENV, codeBuddyLoginUrl, resolveCodeBuddyCli } from "./codebuddy-cli.mjs";
+import { createAcpSpawnPlan, nvmDefaultVersion, resolveAcpCommand } from "./acp-host.mjs";
+
+const officialPackage = JSON.stringify({ name: "@tencent-ai/codebuddy-code" });
+
+// In-memory files: path -> contents. Every listed file counts as executable.
+const memoryDeps = (platform, files, links = {}) => ({
+ platform,
+ executableMode: 1,
+ stat: (file) => {
+ if (!Object.hasOwn(files, file)) throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ return { isFile: () => true };
+ },
+ access: (file) => {
+ if (!Object.hasOwn(files, file)) throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ },
+ exists: (file) => Object.hasOwn(files, file),
+ realpath: (file) => links[file] ?? file,
+ readFile: (file) => {
+ if (!Object.hasOwn(files, file)) throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ return files[file];
+ },
+});
+
+describe("CodeBuddy CLI resolution", () => {
+ const posixPrefix = "/Users/me/.nvm/versions/node/v22.11.0";
+ const posixRoot = `${posixPrefix}/lib/node_modules/@tencent-ai/codebuddy-code`;
+ const posixFiles = {
+ [`${posixPrefix}/bin/codebuddy`]: "",
+ [`${posixPrefix}/bin/node`]: "",
+ [`${posixRoot}/bin/codebuddy`]: "",
+ [`${posixRoot}/package.json`]: officialPackage,
+ "/usr/bin/node": "",
+ };
+ const posixLinks = { [`${posixPrefix}/bin/codebuddy`]: `${posixRoot}/bin/codebuddy` };
+
+ test("runs the npm entry with the Node that installed it, without a shell", () => {
+ const result = resolveCodeBuddyCli({ ...memoryDeps("darwin", posixFiles, posixLinks), toolPath: `/usr/bin:${posixPrefix}/bin` });
+ expect(result).toEqual({
+ ok: true,
+ command: { command: `${posixPrefix}/bin/node`, args: [`${posixRoot}/bin/codebuddy`, "--acp"], env: {}, unsetEnv: CODEBUDDY_UNSET_ENV },
+ });
+ });
+
+ test("falls back to Node on the tool path and reports a missing Node", () => {
+ const { [`${posixPrefix}/bin/node`]: _, ...withoutNvmNode } = posixFiles;
+ expect(resolveCodeBuddyCli({ ...memoryDeps("linux", withoutNvmNode, posixLinks), toolPath: `${posixPrefix}/bin:/usr/bin` }).command?.command).toBe("/usr/bin/node");
+ const { "/usr/bin/node": __, ...noNode } = withoutNvmNode;
+ expect(resolveCodeBuddyCli({ ...memoryDeps("linux", noNode, posixLinks), toolPath: `${posixPrefix}/bin:/usr/bin` })).toEqual({ ok: false, state: "failed", detail: "node_missing" });
+ });
+
+ test("reports not installed for a missing CLI, another package or WorkBuddy's bundled copy", () => {
+ expect(resolveCodeBuddyCli({ ...memoryDeps("darwin", posixFiles, posixLinks), toolPath: "/usr/bin" })).toEqual({ ok: false, state: "not_installed" });
+ const otherPackage = { ...posixFiles, [`${posixRoot}/package.json`]: JSON.stringify({ name: "codebuddy" }) };
+ expect(resolveCodeBuddyCli({ ...memoryDeps("darwin", otherPackage, posixLinks), toolPath: `${posixPrefix}/bin` })).toEqual({ ok: false, state: "not_installed" });
+ const bundledRoot = "/Applications/WorkBuddy.app/Contents/Resources/app.asar.unpacked/cli";
+ const bundled = {
+ "/usr/local/bin/codebuddy": "", "/usr/local/bin/node": "",
+ [`${bundledRoot}/bin/codebuddy`]: "", [`${bundledRoot}/package.json`]: officialPackage,
+ };
+ expect(resolveCodeBuddyCli({ ...memoryDeps("darwin", bundled, { "/usr/local/bin/codebuddy": `${bundledRoot}/bin/codebuddy` }), toolPath: "/usr/local/bin" })).toEqual({ ok: false, state: "not_installed" });
+ });
+
+ describe("version-manager shims", () => {
+ const home = "/Users/me";
+ const brewRoot = "/opt/homebrew/lib/node_modules/@tencent-ai/codebuddy-code";
+ const brew = {
+ "/opt/homebrew/bin/codebuddy": "", "/opt/homebrew/bin/node": "",
+ [`${brewRoot}/bin/codebuddy`]: "", [`${brewRoot}/package.json`]: officialPackage,
+ };
+ const brewLinks = { "/opt/homebrew/bin/codebuddy": `${brewRoot}/bin/codebuddy` };
+ const install = (prefix) => ({
+ [`${prefix}/bin/codebuddy`]: "", [`${prefix}/bin/node`]: "",
+ [`${prefix}/lib/node_modules/@tencent-ai/codebuddy-code/bin/codebuddy`]: "",
+ [`${prefix}/lib/node_modules/@tencent-ai/codebuddy-code/package.json`]: officialPackage,
+ });
+ const installLinks = (prefix) => ({ [`${prefix}/bin/codebuddy`]: `${prefix}/lib/node_modules/@tencent-ai/codebuddy-code/bin/codebuddy` });
+ const run = (answers, calls = []) => (command, args, options) => {
+ calls.push({ command, args, cwd: options.cwd });
+ return answers[command] ?? null;
+ };
+
+ test("asks asdf for the real executable and uses that install's Node", () => {
+ const asdfInstall = `${home}/.asdf/installs/nodejs/22.14.0`;
+ const files = { [`${home}/.asdf/shims/codebuddy`]: "", [`${home}/.asdf/bin/asdf`]: "", ...install(asdfInstall), ...brew };
+ const calls = [];
+ const result = resolveCodeBuddyCli({
+ ...memoryDeps("darwin", files, { ...installLinks(asdfInstall), ...brewLinks }), home, env: {}, tmpdir: "/tmp",
+ toolPath: `${home}/.asdf/shims:/opt/homebrew/bin`,
+ runManager: run({ [`${home}/.asdf/bin/asdf`]: `${asdfInstall}/bin/codebuddy` }, calls),
+ });
+ expect(result.command).toMatchObject({ command: `${asdfInstall}/bin/node`, args: [`${asdfInstall}/lib/node_modules/@tencent-ai/codebuddy-code/bin/codebuddy`, "--acp"] });
+ expect(calls).toEqual([{ command: `${home}/.asdf/bin/asdf`, args: ["which", "codebuddy"], cwd: "/tmp" }]);
+ });
+
+ test("an unresolvable shim does not hide a later valid install", () => {
+ const files = { [`${home}/.asdf/shims/codebuddy`]: "", [`${home}/.asdf/bin/asdf`]: "", ...brew };
+ const result = resolveCodeBuddyCli({
+ ...memoryDeps("darwin", files, brewLinks), home, env: {}, tmpdir: "/tmp",
+ toolPath: `${home}/.asdf/shims:/opt/homebrew/bin`, runManager: run({}),
+ });
+ expect(result.command).toMatchObject({ command: "/opt/homebrew/bin/node", args: [`${brewRoot}/bin/codebuddy`, "--acp"] });
+ });
+
+ test("resolves mise shims that link to the mise binary", () => {
+ const miseInstall = `${home}/.local/share/mise/installs/node/22.14.0`;
+ const files = { [`${home}/.local/share/mise/shims/codebuddy`]: "", [`${home}/.local/bin/mise`]: "", ...install(miseInstall) };
+ const result = resolveCodeBuddyCli({
+ ...memoryDeps("linux", files, { [`${home}/.local/share/mise/shims/codebuddy`]: `${home}/.local/bin/mise`, ...installLinks(miseInstall) }),
+ home, env: {}, tmpdir: "/tmp", toolPath: `${home}/.local/share/mise/shims`,
+ runManager: run({ [`${home}/.local/bin/mise`]: `${miseInstall}/bin/codebuddy` }),
+ });
+ expect(result.command).toMatchObject({ command: `${miseInstall}/bin/node`, args: [`${miseInstall}/lib/node_modules/@tencent-ai/codebuddy-code/bin/codebuddy`, "--acp"] });
+ });
+
+ test("resolves Volta packages and runs them with Volta's Node", () => {
+ const pkg = `${home}/.volta/tools/image/packages/@tencent-ai/codebuddy-code`;
+ const files = {
+ [`${home}/.volta/bin/codebuddy`]: "", [`${home}/.volta/bin/volta`]: "", [`${home}/.volta/bin/node`]: "",
+ [`${pkg}/bin/codebuddy`]: "", [`${pkg}/lib/node_modules/@tencent-ai/codebuddy-code/bin/codebuddy`]: "",
+ [`${pkg}/lib/node_modules/@tencent-ai/codebuddy-code/package.json`]: officialPackage,
+ };
+ const result = resolveCodeBuddyCli({
+ ...memoryDeps("darwin", files, {
+ [`${home}/.volta/bin/codebuddy`]: `${home}/.volta/bin/volta-shim`,
+ [`${pkg}/bin/codebuddy`]: `${pkg}/lib/node_modules/@tencent-ai/codebuddy-code/bin/codebuddy`,
+ }),
+ home, env: {}, tmpdir: "/tmp", toolPath: `${home}/.volta/bin`,
+ runManager: run({ [`${home}/.volta/bin/volta`]: `${pkg}/bin/codebuddy` }),
+ });
+ expect(result.command).toMatchObject({ command: `${home}/.volta/bin/node`, args: [`${pkg}/lib/node_modules/@tencent-ai/codebuddy-code/bin/codebuddy`, "--acp"] });
+ });
+
+ test("another package earlier on the path does not hide the official CLI", () => {
+ const files = { "/usr/local/bin/codebuddy": "", "/usr/local/lib/node_modules/codebuddy/bin/codebuddy": "", "/usr/local/lib/node_modules/codebuddy/package.json": JSON.stringify({ name: "codebuddy" }), ...brew };
+ const result = resolveCodeBuddyCli({
+ ...memoryDeps("darwin", files, { "/usr/local/bin/codebuddy": "/usr/local/lib/node_modules/codebuddy/bin/codebuddy", ...brewLinks }),
+ home, env: {}, toolPath: "/usr/local/bin:/opt/homebrew/bin", runManager: run({}),
+ });
+ expect(result.command?.args[0]).toBe(`${brewRoot}/bin/codebuddy`);
+ });
+ });
+
+ test("uses npm's codebuddy.cmd location on Windows without running the shim", () => {
+ const prefix = "C:\\Users\\me\\AppData\\Roaming\\npm";
+ const root = `${prefix}\\node_modules\\@tencent-ai\\codebuddy-code`;
+ const files = {
+ [`${prefix}\\codebuddy.cmd`]: "",
+ [`${root}\\bin\\codebuddy`]: "",
+ [`${root}\\package.json`]: officialPackage,
+ "C:\\Program Files\\nodejs\\node.exe": "",
+ };
+ const result = resolveCodeBuddyCli({ ...memoryDeps("win32", files), toolPath: `${prefix};C:\\Program Files\\nodejs` });
+ expect(result).toEqual({
+ ok: true,
+ command: { command: "C:\\Program Files\\nodejs\\node.exe", args: [`${root}\\bin\\codebuddy`, "--acp"], env: {}, unsetEnv: CODEBUDDY_UNSET_ENV },
+ });
+ // An nvm-windows install keeps node.exe beside the shim and wins.
+ const nvm = { ...files, [`${prefix}\\node.exe`]: "" };
+ expect(resolveCodeBuddyCli({ ...memoryDeps("win32", nvm), toolPath: `${prefix};C:\\Program Files\\nodejs` }).command.command).toBe(`${prefix}\\node.exe`);
+ expect(resolveCodeBuddyCli({ ...memoryDeps("win32", { [`${prefix}\\codebuddy.cmd`]: "" }), toolPath: prefix })).toEqual({ ok: false, state: "not_installed" });
+ expect(resolveCodeBuddyCli({ ...memoryDeps("win32", { ...files, "C:\\Program Files\\nodejs\\node.exe": undefined }), toolPath: prefix }).detail).toBe("node_missing");
+ });
+
+ test("resolves a real npm-style install and clears inherited region overrides", async () => {
+ const directory = realpathSync(await mkdtemp(path.join(tmpdir(), "edgeever-codebuddy-cli-")));
+ try {
+ const root = path.join(directory, "lib", "node_modules", "@tencent-ai", "codebuddy-code");
+ await mkdir(path.join(root, "bin"), { recursive: true });
+ await mkdir(path.join(directory, "bin"), { recursive: true });
+ await writeFile(path.join(root, "package.json"), officialPackage);
+ await writeFile(path.join(root, "bin", "codebuddy"), "#!/usr/bin/env node\n", { mode: 0o755 });
+ await symlink(path.join(root, "bin", "codebuddy"), path.join(directory, "bin", "codebuddy"));
+ await writeFile(path.join(directory, "bin", "node"), "#!/bin/sh\n", { mode: 0o755 });
+ const resolved = resolveAcpCommand({ id: "codebuddy" }, {
+ platform: "darwin", home: directory, pathEnv: path.join(directory, "bin"),
+ // Keep machine-wide installs (e.g. Homebrew) out of the lookup.
+ existsSync: (candidate) => candidate.startsWith(directory) && existsSync(candidate),
+ });
+ expect(resolved.ok).toBe(true);
+ expect(resolved.command.command).toBe(path.join(directory, "bin", "node"));
+ expect(resolved.command.args).toEqual([realpathSync(path.join(root, "bin", "codebuddy")), "--acp"]);
+ const previous = { a: process.env.CODEBUDDY_INTERNET_ENVIRONMENT, b: process.env.CODEBUDDY_INTERNET_ENVIROMENT };
+ process.env.CODEBUDDY_INTERNET_ENVIRONMENT = "internal";
+ process.env.CODEBUDDY_INTERNET_ENVIROMENT = "internal";
+ try {
+ const env = createAcpSpawnPlan(resolved.command, directory).options.env;
+ expect(env.CODEBUDDY_INTERNET_ENVIRONMENT).toBeUndefined();
+ expect(env.CODEBUDDY_INTERNET_ENVIROMENT).toBeUndefined();
+ } finally {
+ if (previous.a === undefined) delete process.env.CODEBUDDY_INTERNET_ENVIRONMENT; else process.env.CODEBUDDY_INTERNET_ENVIRONMENT = previous.a;
+ if (previous.b === undefined) delete process.env.CODEBUDDY_INTERNET_ENVIROMENT; else process.env.CODEBUDDY_INTERNET_ENVIROMENT = previous.b;
+ }
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("CodeBuddy login links", () => {
+ test("accepts only https links on verified hosts", () => {
+ for (const url of [
+ "https://copilot.tencent.com/login?state=x",
+ "https://www.codebuddy.ai/login?state=x",
+ "https://codebuddy.ai/login",
+ "https://WWW.CODEBUDDY.AI/login",
+ ]) expect(codeBuddyLoginUrl(url)).toBe(new URL(url).href);
+ });
+
+ test("rejects other schemes, hosts, credentials and ports", () => {
+ for (const url of [
+ "http://www.codebuddy.ai/login",
+ "javascript:alert(1)",
+ "file:///etc/passwd",
+ "https://www.tencent.com/login",
+ "https://evil.copilot.tencent.com.example/login",
+ "https://notcodebuddy.ai/login",
+ "https://codebuddy.ai.evil.example/login",
+ "https://codebuddy.cn/login",
+ "https://user:[email protected]/login",
+ "https://[email protected]/login",
+ "https://www.codebuddy.ai:8443/login",
+ "not a url",
+ "",
+ undefined,
+ `https://www.codebuddy.ai/${"a".repeat(5000)}`,
+ ]) expect(codeBuddyLoginUrl(url)).toBeNull();
+ });
+});
+
+describe("nvm default alias", () => {
+ const home = "/Users/me";
+ const nvm = (aliases, versions = ["v20.18.0", "v22.9.0", "v22.14.0", "v23.1.0"]) => ({
+ readFile: (file) => {
+ const name = file.slice(`${home}/.nvm/alias/`.length);
+ if (!file.startsWith(`${home}/.nvm/alias/`) || !Object.hasOwn(aliases, name)) throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ return `${aliases[name]}\n`;
+ },
+ readdir: (dir) => {
+ if (dir !== `${home}/.nvm/versions/node`) throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ return [...versions, ".DS_Store"];
+ },
+ });
+
+ test("resolves exact, partial and newest-version aliases to an installed version", () => {
+ expect(nvmDefaultVersion(home, nvm({ default: "v22.9.0" }))).toBe("v22.9.0");
+ expect(nvmDefaultVersion(home, nvm({ default: "22" }))).toBe("v22.14.0");
+ expect(nvmDefaultVersion(home, nvm({ default: "v22" }))).toBe("v22.14.0");
+ expect(nvmDefaultVersion(home, nvm({ default: "22.9" }))).toBe("v22.9.0");
+ expect(nvmDefaultVersion(home, nvm({ default: "node" }))).toBe("v23.1.0");
+ expect(nvmDefaultVersion(home, nvm({ default: "stable" }))).toBe("v23.1.0");
+ expect(nvmDefaultVersion(home, nvm({ default: "21" }))).toBeNull();
+ });
+
+ test("follows lts and named aliases", () => {
+ expect(nvmDefaultVersion(home, nvm({ default: "lts/*", "lts/*": "lts/jod", "lts/jod": "v22.14.0" }))).toBe("v22.14.0");
+ expect(nvmDefaultVersion(home, nvm({ default: "lts/jod", "lts/jod": "v22.9.0" }))).toBe("v22.9.0");
+ expect(nvmDefaultVersion(home, nvm({ default: "work", work: "20" }))).toBe("v20.18.0");
+ });
+
+ test("ignores system, missing, looping and unsafe aliases", () => {
+ expect(nvmDefaultVersion(home, nvm({ default: "system" }))).toBeNull();
+ expect(nvmDefaultVersion(home, nvm({}))).toBeNull();
+ expect(nvmDefaultVersion(home, nvm({ default: "lts/*" }))).toBeNull();
+ expect(nvmDefaultVersion(home, nvm({ default: "a", a: "b", b: "a" }))).toBeNull();
+ expect(nvmDefaultVersion(home, nvm({ default: "../../etc/passwd" }))).toBeNull();
+ expect(nvmDefaultVersion(home, nvm({ default: "22" }, []))).toBeNull();
+ });
+
+ test("finds CodeBuddy under nvm's lts default with a minimal desktop PATH", async () => {
+ const directory = realpathSync(await mkdtemp(path.join(tmpdir(), "edgeever-codebuddy-nvm-")));
+ try {
+ const prefix = path.join(directory, ".nvm", "versions", "node", "v22.14.0");
+ const root = path.join(prefix, "lib", "node_modules", "@tencent-ai", "codebuddy-code");
+ await mkdir(path.join(root, "bin"), { recursive: true });
+ await mkdir(path.join(prefix, "bin"), { recursive: true });
+ await mkdir(path.join(directory, ".nvm", "versions", "node", "v20.18.0", "bin"), { recursive: true });
+ await mkdir(path.join(directory, ".nvm", "alias", "lts"), { recursive: true });
+ await writeFile(path.join(directory, ".nvm", "alias", "default"), "lts/*\n");
+ await writeFile(path.join(directory, ".nvm", "alias", "lts", "*"), "lts/jod\n");
+ await writeFile(path.join(directory, ".nvm", "alias", "lts", "jod"), "v22.14.0\n");
+ await writeFile(path.join(root, "package.json"), officialPackage);
+ await writeFile(path.join(root, "bin", "codebuddy"), "#!/usr/bin/env node\n", { mode: 0o755 });
+ await symlink(path.join(root, "bin", "codebuddy"), path.join(prefix, "bin", "codebuddy"));
+ await writeFile(path.join(prefix, "bin", "node"), "#!/bin/sh\n", { mode: 0o755 });
+ const resolved = resolveAcpCommand({ id: "codebuddy" }, {
+ platform: "darwin", home: directory, pathEnv: "/usr/bin:/bin",
+ existsSync: (candidate) => candidate.startsWith(directory) && existsSync(candidate),
+ });
+ expect(resolved.ok).toBe(true);
+ expect(resolved.command.command).toBe(path.join(prefix, "bin", "node"));
+ expect(resolved.command.args).toEqual([path.join(root, "bin", "codebuddy"), "--acp"]);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index c6e85ca2..468b9216 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -2120,6 +2120,8 @@ const startApplication = async () => {
onUpdateDiagnostic: (details) => { void writeDiagnostic("acp.adapter-update-failed", details); },
onDiagnostic: (details) => { void writeDiagnostic("acp.adapter-stderr", details); },
onProcessDiagnostic: ({ event, ...details }) => { void writeDiagnostic(`acp.adapter-${event}`, details); },
+ // Used only to reopen a validated CodeBuddy login page on explicit request.
+ openExternal: (url) => shell.openExternal(url),
mcpScriptPath: app.isPackaged
? join(process.resourcesPath, "mcp-bridge", "edgeever-mcp-stdio.mjs")
: join(projectRoot, "scripts", "edgeever-mcp-stdio.mjs"),
diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjs
index 4c9a5ef2..aa02fe43 100644
--- a/apps/desktop/src/preload/index.cjs
+++ b/apps/desktop/src/preload/index.cjs
@@ -83,6 +83,8 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({
probeAcpAdapter: (input) => ipcRenderer.invoke("desktop:acp-probe", input),
installAcpAdapter: (id) => ipcRenderer.invoke("desktop:acp-install", id),
authenticateAcpAdapter: (input) => ipcRenderer.invoke("desktop:acp-authenticate", input),
+ cancelAcpAuthentication: (id) => ipcRenderer.invoke("desktop:acp-cancel-auth", id),
+ reopenAcpLoginPage: (id) => ipcRenderer.invoke("desktop:acp-reopen-login", id),
prepareAcp: (input) => ipcRenderer.invoke("desktop:acp-prepare", input),
promptAcp: (input) => ipcRenderer.invoke("desktop:acp-prompt", input),
cancelAcp: (requestId) => ipcRenderer.invoke("desktop:acp-cancel", requestId),
diff --git a/apps/web/src/assets/agent-logos/codebuddy.svg b/apps/web/src/assets/agent-logos/codebuddy.svg
new file mode 100644
index 00000000..513e5ce3
--- /dev/null
+++ b/apps/web/src/assets/agent-logos/codebuddy.svg
@@ -0,0 +1,5 @@
+<svg width="873" height="612" viewBox="0 0 873 612" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M611.24 0C631.42 0.472994 652.67 0.151247 672.917 0.149414L783.53 0.125977L783.58 114.446C783.58 131.188 782.828 155.62 783.732 171.959C793.764 172.165 866.262 170.817 869.239 173.294C869.728 173.699 870.138 174.379 870.486 174.905L872.008 175.384C873.402 179.664 872.344 228.902 872.338 236.71C872.313 263.731 873.157 518.745 871.959 521.349C871.837 521.605 871.58 521.905 871.415 522.119L869.141 522.375C841.374 521.684 811.566 522.247 783.646 522.271C784.001 538.325 783.695 555.229 783.72 571.344C783.738 583.932 784.056 598.74 783.451 611.182C613.783 610.846 273.598 611.469 87.6807 611.041C87.3452 610.736 87.0093 610.436 86.6738 610.137L86.2393 607.375C86.831 602.028 86.4052 585.668 86.3984 579.416L86.2812 521.838C82.9453 522.522 63.9127 522.272 59.0283 522.266L0.391602 522.259L0.398438 278.798L0.427734 209.334C0.430803 201.523 0.934097 181.445 0 174.62C0.578928 172.779 0.0735528 173.48 1.33105 172.293C17.2444 171.377 36.4875 172.458 52.7188 172.065C59.0087 171.913 81.4327 171.805 86.0195 172.717L85.9805 56.9336L85.9072 21.3467C85.895 15.7024 85.6474 5.58945 86.2832 0.297852L89.3057 0.0224609C145.847 1.00635 204.767 0.149918 261.493 0.137695L261.571 58.8008C261.576 63.634 261.865 82.5764 261.06 86.293C288.984 85.6006 319.108 86.1736 347.17 86.1797L509.068 86.1846L576.67 86.1357C582.985 86.1314 604.124 85.7374 608.728 86.8135C607.982 81.7879 608.33 64.0733 608.33 58.0186L608.428 1.34473C609.424 -0.0534957 608.978 0.391111 611.24 0ZM697.12 173.048C694.553 171.797 619.805 172.389 610.134 172.389L279.41 172.397L201.266 172.392C193.899 172.39 184.497 172.27 176.995 172.399C175.636 172.423 175.324 173.65 174.702 174.81L172.704 175.383C172.033 177.999 172.341 204.836 172.348 208.9L172.398 294.312L172.37 445.969L172.349 494.032C172.347 501.781 172.011 513.954 172.658 521.324C174.533 523.401 174.111 521.52 174.854 522.534C175.611 523.561 175.655 525.034 177.928 525.016C181.545 524.988 185.335 524.97 189.044 524.966H347.752L604.785 524.96L669.054 525.009C673.406 525.009 693.575 525.296 696.857 524.643C697.499 523.408 697.493 523.505 697.542 522.118C696.815 500.607 697.389 475.931 697.389 454.243V327.045L697.383 228.248C697.383 211.843 696.729 190.781 697.64 174.935L697.12 173.048Z" fill="#00BC90"/>
+<path d="M347.56 260.864L349.808 261.441C351.42 265.483 350.329 418.222 350.229 435.792C344.53 436.85 263.503 436.929 260.894 435.722L261.464 433.765C261.114 420.392 261.416 405.532 261.413 392.005L261.412 313.381C261.422 299.699 262.22 276.275 261.106 263.652C261.428 261.859 261.059 262.619 262.19 261.257C268.232 260.664 277.082 261.319 283.456 261.111C303.554 260.454 327.973 262.241 347.56 260.864Z" fill="#00BC90"/>
+<path d="M608.752 260.881L610.641 261.353C612.854 266.169 610.268 347.019 611.302 358.962C611.693 363.539 611.436 434.199 610.892 435.767C610.293 435.847 609.248 436.027 608.685 436.028C584.88 436.436 548.549 435.89 523.533 435.943C522.702 435.945 522.567 435.098 522.127 434.149C522.787 429.284 522.445 415.565 522.445 410.114L522.415 362.246L522.457 298.316C522.463 288.598 522.94 272.837 522.097 263.668L522.586 261.78C525.887 259.891 595.756 261.699 608.752 260.881Z" fill="#00BC90"/>
+</svg>
diff --git a/apps/web/src/assets/agent-logos/sources.json b/apps/web/src/assets/agent-logos/sources.json
index 26aa65a4..f4a4dd4c 100644
--- a/apps/web/src/assets/agent-logos/sources.json
+++ b/apps/web/src/assets/agent-logos/sources.json
@@ -36,5 +36,10 @@
"workbuddy": {
"source": "https://download.codebuddy.ai/web/workbuddy/913b2390aae396c66b937bd9143ae5259306d7d7/assets/logo.svg",
"website": "https://www.workbuddy.ai/"
+ },
+ "codebuddy": {
+ "source": "https://unpkg.com/@tencent-ai/[email protected]/dist/web-ui/logo.svg",
+ "package": "@tencent-ai/[email protected] (dist/web-ui/logo.svg)",
+ "website": "https://www.codebuddy.ai/"
}
}
diff --git a/apps/web/src/components/ai-sidebar/AgentLogo.tsx b/apps/web/src/components/ai-sidebar/AgentLogo.tsx
index 69f6d4fb..92830c57 100644
--- a/apps/web/src/components/ai-sidebar/AgentLogo.tsx
+++ b/apps/web/src/components/ai-sidebar/AgentLogo.tsx
@@ -9,6 +9,7 @@ import grokBuild from "@/assets/agent-logos/grok.svg?url";
import deepseekHarness from "@/assets/agent-logos/deepseek-color.svg?url";
import piAgent from "@/assets/agent-logos/pi.svg?url";
import workbuddy from "@/assets/agent-logos/workbuddy.svg?url";
+import codebuddy from "@/assets/agent-logos/codebuddy.svg?url";
const logos: Record<DesktopAcpAdapterId, { src: string; monochrome?: boolean }> = {
codex: { src: codex, monochrome: true },
@@ -21,6 +22,7 @@ const logos: Record<DesktopAcpAdapterId, { src: string; monochrome?: boolean }>
piAgent: { src: piAgent, monochrome: true },
workbuddyCn: { src: workbuddy },
workbuddyIntl: { src: workbuddy },
+ codebuddy: { src: codebuddy },
};
export function AgentLogo({ id, className }: { id: DesktopAcpAdapterId; className?: string }) {
diff --git a/apps/web/src/components/ai-sidebar/AiSidebar.tsx b/apps/web/src/components/ai-sidebar/AiSidebar.tsx
index 36fe10c3..1a966f3c 100644
--- a/apps/web/src/components/ai-sidebar/AiSidebar.tsx
+++ b/apps/web/src/components/ai-sidebar/AiSidebar.tsx
@@ -903,6 +903,7 @@ function AiSidebarSession({
setError(noteAccessErrorKey ? t(noteAccessErrorKey)
: event.message === "workbuddy_credentials_unavailable" ? t("aiAssistant.agentSource.workbuddyCredentialsUnavailable")
: event.message === "identity_status_unavailable" ? t("aiAssistant.agentSource.identityStatusUnavailable")
+ : event.message === "node_missing" && localAdapterId === "codebuddy" ? t("aiAssistant.agentSource.codebuddyNodeMissingHint")
: event.message === "needs_login" && localAdapterId === "claudeCode" ? t("aiAssistant.agentSource.claudeCodeLoginHint")
: event.message === "needs_login" ? t(localAdapterId === "workbuddyCn" || localAdapterId === "workbuddyIntl"
? "aiAssistant.sidebar.workbuddyLoginRequired" : "aiAssistant.sidebar.localLoginRequired")
diff --git a/apps/web/src/components/settings/DesktopAcpAgentCard.tsx b/apps/web/src/components/settings/DesktopAcpAgentCard.tsx
index 34e3892e..d8440edb 100644
--- a/apps/web/src/components/settings/DesktopAcpAgentCard.tsx
+++ b/apps/web/src/components/settings/DesktopAcpAgentCard.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useId, useState } from "react";
+import { useEffect, useId, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Bot, ChevronDown, Info } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -17,6 +17,9 @@ import {
listDesktopAcpAdapters,
installDesktopAcpAdapter,
authenticateDesktopAcpAdapter,
+ cancelDesktopAcpAuthentication,
+ codeBuddyAuthMethodLabelKey,
+ reopenDesktopAcpLoginPage,
probeDesktopAcpAdapter,
type AiSidebarSource,
type DesktopAcpAdapter,
@@ -33,7 +36,7 @@ import {
SETTINGS_ITEM_TITLE_CLASSNAME,
} from "./settings-ui";
-const adapterIds: DesktopAcpAdapterId[] = ["codex", "claudeCode", "antigravity", "openClaw", "hermesAgent", "grokBuild", "deepseekHarness", "piAgent", "workbuddyCn", "workbuddyIntl"];
+const adapterIds: DesktopAcpAdapterId[] = ["codex", "claudeCode", "antigravity", "openClaw", "hermesAgent", "grokBuild", "deepseekHarness", "piAgent", "workbuddyCn", "workbuddyIntl", "codebuddy"];
const readSource = (): AiSidebarSource => (
localStorage.getItem(AI_SIDEBAR_SOURCE_KEY) === "local" ? "local" : "builtin"
@@ -48,6 +51,8 @@ const statusKey = (adapter: DesktopAcpAdapter | undefined, probing: boolean) =>
if (probing) return "aiAssistant.agentSource.probing";
if (!adapter || adapter.detail === "not_probed") return "aiAssistant.agentSource.notProbed";
if (adapter.detail === "workbuddy_credentials_unavailable") return "aiAssistant.agentSource.workbuddyCredentialsUnavailable";
+ if (adapter.detail === "authentication_cancelled") return "aiAssistant.agentSource.authenticationCancelled";
+ if (adapter.detail === "node_missing") return "aiAssistant.agentSource.codebuddyNodeMissing";
if (adapter.detail === "authentication_timeout") return "aiAssistant.agentSource.authenticationTimedOut";
if (adapter.detail === "identity_status_unavailable") return "aiAssistant.agentSource.identityStatusNotReported";
if (adapter.id === "claudeCode" && adapter.state === "needs_login") return "aiAssistant.agentSource.claudeCodeCredentialsRequired";
@@ -62,6 +67,8 @@ const statusKey = (adapter: DesktopAcpAdapter | undefined, probing: boolean) =>
if (adapter.id === "piAgent" && adapter.state === "not_installed") return adapter.detail === "adapter_missing" ? "aiAssistant.agentSource.piAgentAdapterMissing" : "aiAssistant.agentSource.piAgentNotFound";
if ((adapter.id === "workbuddyCn" || adapter.id === "workbuddyIntl") && adapter.state === "not_installed") return "aiAssistant.agentSource.workbuddyNotFound";
if ((adapter.id === "workbuddyCn" || adapter.id === "workbuddyIntl") && adapter.state === "needs_login") return "aiAssistant.agentSource.workbuddyLoginRequired";
+ if (adapter.id === "codebuddy" && adapter.state === "not_installed") return "aiAssistant.agentSource.codebuddyNotFound";
+ if (adapter.id === "codebuddy" && adapter.state === "needs_login") return "aiAssistant.agentSource.codebuddyLoginRequired";
return `aiAssistant.agentSource.states.${adapter.state}`;
};
@@ -83,6 +90,8 @@ const getStatusTone = ({
return "neutral";
};
+const cliMethodName = (name: string) => name.replace(/^Login with\s+/i, "").replace(/Google\/Github/gi, "Google / GitHub");
+
const desktopBridgeAvailable = () => (
typeof window !== "undefined" && typeof window.edgeeverDesktop?.listAcpAdapters === "function"
);
@@ -100,6 +109,12 @@ const DesktopAcpAgentCardBody = ({ bridge }: { bridge: boolean }) => {
const [installing, setInstalling] = useState(false);
const [installError, setInstallError] = useState(false);
const [authenticating, setAuthenticating] = useState<string | null>(null);
+ const codeBuddyLoginActive = useRef(false);
+
+ // Leaving the settings page ends a CodeBuddy sign-in that no one can finish here.
+ useEffect(() => () => {
+ if (codeBuddyLoginActive.current) void cancelDesktopAcpAuthentication("codebuddy").catch(() => {});
+ }, []);
useEffect(() => {
const stored = readSource();
@@ -147,6 +162,8 @@ const DesktopAcpAgentCardBody = ({ bridge }: { bridge: boolean }) => {
const shown = displayedDesktopAcpAdapter({ id: adapterId, path: adapterPath, listed, probed });
const updateHintKey = shown?.updateError ? desktopAcpUpdateErrorHintKey(shown.updateError) : null;
const isWorkBuddy = adapterId === "workbuddyCn" || adapterId === "workbuddyIntl";
+ const isCodeBuddy = adapterId === "codebuddy";
+ const codeBuddySigningIn = isCodeBuddy && Boolean(authenticating);
const status = t(statusKey(shown, probing));
const tone = getStatusTone({
probing,
@@ -159,12 +176,14 @@ const DesktopAcpAgentCardBody = ({ bridge }: { bridge: boolean }) => {
)) ?? [];
const canRetryLogin = desktopAcpLoginRetryAvailable(shown);
// Host failure details are sanitized before crossing the desktop bridge.
- const failureReason = shown?.state === "failed"
+ const failureReason = shown?.state === "failed" && shown.detail !== "node_missing"
? shown.detail?.trim().slice(0, 160) || t("aiAssistant.agentSource.connectionFailureUnknown")
: null;
const hasDetails = Boolean(
failureReason ||
canRetryLogin ||
+ codeBuddySigningIn ||
+ shown?.detail === "node_missing" ||
shown?.state === "not_installed" ||
shown?.state === "needs_login" ||
(shown?.state === "available" && (isWorkBuddy || authMethods.length > 0)) ||
@@ -178,15 +197,28 @@ const DesktopAcpAgentCardBody = ({ bridge }: { bridge: boolean }) => {
<div className="flex flex-wrap gap-2 pt-0.5">
{authMethods.map((method) => (
<Button key={method.id} type="button" variant="outline" size="sm" className="h-8 bg-card text-xs font-normal" disabled={probing || installing || Boolean(authenticating)} onClick={() => void authenticate(method.id)}>
- {authenticating === method.id ? t("aiAssistant.agentSource.authenticating") : isWorkBuddy
- ? t("aiAssistant.agentSource.workbuddyAuthenticateWith", { method: method.name.replace(/^Login with\s+/i, "").replace(/Google\/Github/gi, "Google / GitHub") })
+ {authenticating === method.id ? t("aiAssistant.agentSource.authenticating") : isCodeBuddy
+ ? codeBuddyMethodLabel(method)
+ : isWorkBuddy
+ ? t("aiAssistant.agentSource.workbuddyAuthenticateWith", { method: cliMethodName(method.name) })
: t("aiAssistant.agentSource.authenticateWith", { method: method.name })}
</Button>
))}
</div>
);
+ function codeBuddyMethodLabel(method: { id: string; name: string }) {
+ const key = codeBuddyAuthMethodLabelKey(method.id);
+ // Other methods keep the CLI's own name, without its "Login with" prefix.
+ return key ? t(key) : t("aiAssistant.agentSource.workbuddyAuthenticateWith", { method: cliMethodName(method.name) });
+ }
+
+ const cancelCodeBuddyLogin = () => {
+ void cancelDesktopAcpAuthentication("codebuddy").catch(() => {});
+ };
+
const selectAdapter = (id: DesktopAcpAdapterId) => {
+ if (codeBuddySigningIn && id !== "codebuddy") cancelCodeBuddyLogin();
setAdapterId(id);
setProbed(null);
setInstallError(false);
@@ -215,6 +247,7 @@ const DesktopAcpAgentCardBody = ({ bridge }: { bridge: boolean }) => {
const authenticate = async (methodId: string) => {
setAuthenticating(methodId);
setInstallError(false);
+ if (adapterId === "codebuddy") codeBuddyLoginActive.current = true;
try {
const result = await authenticateDesktopAcpAdapter({
id: adapterId,
@@ -225,6 +258,7 @@ const DesktopAcpAgentCardBody = ({ bridge }: { bridge: boolean }) => {
} catch {
setProbed({ id: adapterId, label: t(`aiAssistant.agentSource.${adapterId}`), state: "failed" });
} finally {
+ if (adapterId === "codebuddy") codeBuddyLoginActive.current = false;
setAuthenticating(null);
}
};
@@ -420,9 +454,28 @@ const DesktopAcpAgentCardBody = ({ bridge }: { bridge: boolean }) => {
) : null}
{shown?.state === "not_installed" ? (
<p>
- {t(adapterId === "claudeCode" ? "aiAssistant.agentSource.claudeCodeMissingHint" : adapterId === "openClaw" ? "aiAssistant.agentSource.openClawMissingHint" : adapterId === "hermesAgent" ? "aiAssistant.agentSource.hermesAgentMissingHint" : adapterId === "grokBuild" ? "aiAssistant.agentSource.grokBuildMissingHint" : adapterId === "deepseekHarness" ? "aiAssistant.agentSource.deepseekHarnessMissingHint" : adapterId === "piAgent" ? shown.detail === "adapter_missing" ? "aiAssistant.agentSource.piAgentAdapterMissingHint" : "aiAssistant.agentSource.piAgentMissingHint" : adapterId === "workbuddyCn" || adapterId === "workbuddyIntl" ? "aiAssistant.agentSource.workbuddyMissingHint" : "aiAssistant.agentSource.installHint")}
+ {t(adapterId === "claudeCode" ? "aiAssistant.agentSource.claudeCodeMissingHint" : adapterId === "openClaw" ? "aiAssistant.agentSource.openClawMissingHint" : adapterId === "hermesAgent" ? "aiAssistant.agentSource.hermesAgentMissingHint" : adapterId === "grokBuild" ? "aiAssistant.agentSource.grokBuildMissingHint" : adapterId === "deepseekHarness" ? "aiAssistant.agentSource.deepseekHarnessMissingHint" : adapterId === "piAgent" ? shown.detail === "adapter_missing" ? "aiAssistant.agentSource.piAgentAdapterMissingHint" : "aiAssistant.agentSource.piAgentMissingHint" : adapterId === "workbuddyCn" || adapterId === "workbuddyIntl" ? "aiAssistant.agentSource.workbuddyMissingHint" : adapterId === "codebuddy" ? "aiAssistant.agentSource.codebuddyMissingHint" : "aiAssistant.agentSource.installHint")}
</p>
) : null}
+ {shown?.detail === "node_missing" ? (
+ <p>{t("aiAssistant.agentSource.codebuddyNodeMissingHint")}</p>
+ ) : null}
+ {shown?.state === "needs_login" && isCodeBuddy && !codeBuddySigningIn ? (
+ <p>{t("aiAssistant.agentSource.codebuddyLoginHint")}</p>
+ ) : null}
+ {codeBuddySigningIn ? (
+ <div className="space-y-2">
+ <p role="status">{t("aiAssistant.agentSource.codebuddyLoginInProgress")}</p>
+ <div className="flex flex-wrap gap-2">
+ <Button type="button" variant="outline" size="sm" className="h-8 bg-card text-xs font-normal" onClick={() => void reopenDesktopAcpLoginPage("codebuddy").catch(() => {})}>
+ {t("aiAssistant.agentSource.codebuddyReopenLogin")}
+ </Button>
+ <Button type="button" variant="ghost" size="sm" className="h-8 text-xs font-normal" onClick={cancelCodeBuddyLogin}>
+ {t("aiAssistant.agentSource.cancelLogin")}
+ </Button>
+ </div>
+ </div>
+ ) : null}
{shown?.detail === "identity_status_unavailable" ? (
<p>{t("aiAssistant.agentSource.identityStatusUnavailable")}</p>
) : null}
diff --git a/apps/web/src/lib/desktop-acp.test.mjs b/apps/web/src/lib/desktop-acp.test.mjs
index 4e6e266c..d2fdfd19 100644
--- a/apps/web/src/lib/desktop-acp.test.mjs
+++ b/apps/web/src/lib/desktop-acp.test.mjs
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test";
-import { desktopAcpUpdateErrorHintKey, desktopAcpLoginRetryAvailable, desktopAcpNoteAccessErrorKey, aiSidebarAdapterFromStorage, aiSidebarSourceFromStorage, displayedDesktopAcpAdapter } from "./desktop-acp.ts";
+import { codeBuddyAuthMethodLabelKey, desktopAcpUpdateErrorHintKey, desktopAcpLoginRetryAvailable, desktopAcpNoteAccessErrorKey, aiSidebarAdapterFromStorage, aiSidebarSourceFromStorage, displayedDesktopAcpAdapter } from "./desktop-acp.ts";
test("a checked custom Antigravity executable takes priority over the managed connector status", () => {
const managed = { id: "antigravity", label: "Antigravity", state: "failed", version: "1.2.1", managed: true };
@@ -25,6 +25,14 @@ test("the sidebar follows a stored local agent only when the desktop bridge exis
expect(aiSidebarAdapterFromStorage("missing", "")).toBeNull();
});
+test("CodeBuddy is a selectable local agent with region hints only for verified sign-in methods", () => {
+ expect(aiSidebarAdapterFromStorage("codebuddy", "/tmp/ignored")).toEqual({ id: "codebuddy" });
+ expect(codeBuddyAuthMethodLabelKey("internal")).toBe("aiAssistant.agentSource.codebuddyMethodInternal");
+ for (const methodId of ["external", "iOA", "selfhosted", "unknown"]) expect(codeBuddyAuthMethodLabelKey(methodId)).toBeNull();
+ // CodeBuddy signs in from the needs_login state; WorkBuddy's failed-state retry does not apply.
+ expect(desktopAcpLoginRetryAvailable({ id: "codebuddy", state: "failed", authMethods: [{ id: "internal" }] })).toBe(false);
+});
+
test("a prompt-time login failure takes priority over an earlier successful session probe", () => {
const current = { id: "grokBuild", label: "Grok Build", state: "needs_login", authMethods: [{ id: "browser", name: "Browser" }] };
const earlierProbe = { id: "grokBuild", label: "Grok Build", state: "available" };
diff --git a/apps/web/src/lib/desktop-acp.ts b/apps/web/src/lib/desktop-acp.ts
index 29208add..5b28b425 100644
--- a/apps/web/src/lib/desktop-acp.ts
+++ b/apps/web/src/lib/desktop-acp.ts
@@ -1,4 +1,4 @@
-export type DesktopAcpAdapterId = "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl";
+export type DesktopAcpAdapterId = "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl" | "codebuddy";
export type DesktopAcpAdapterState = "not_installed" | "not_probed" | "installing" | "needs_login" | "available" | "failed";
export type DesktopAcpPromptCapabilities = {
@@ -119,7 +119,7 @@ export const startsNewLocalAgentThread = (
) => next.source === "local" && (previous.source !== "local" || previous.adapterId !== next.adapterId);
const AI_SIDEBAR_ADAPTER_IDS = new Set<string>([
- "codex", "claudeCode", "antigravity", "openClaw", "hermesAgent", "grokBuild", "deepseekHarness", "piAgent", "workbuddyCn", "workbuddyIntl",
+ "codex", "claudeCode", "antigravity", "openClaw", "hermesAgent", "grokBuild", "deepseekHarness", "piAgent", "workbuddyCn", "workbuddyIntl", "codebuddy",
]);
export const aiSidebarSourceFromStorage = (value: string | null, desktopAvailable: boolean): AiSidebarSource => (
@@ -205,6 +205,24 @@ export const authenticateDesktopAcpAdapter = async (input: { id: DesktopAcpAdapt
return desktop.authenticateAcpAdapter(input);
};
+export const cancelDesktopAcpAuthentication = async (id: "codebuddy") => {
+ const desktop = bridge();
+ if (!desktop?.cancelAcpAuthentication) return { cancelled: false };
+ return desktop.cancelAcpAuthentication(id);
+};
+
+export const reopenDesktopAcpLoginPage = async (id: "codebuddy") => {
+ const desktop = bridge();
+ if (!desktop?.reopenAcpLoginPage) return { opened: false };
+ return desktop.reopenAcpLoginPage(id);
+};
+
+// Region hints only for login methods verified end to end (#758); other
+// methods keep the name the CLI reports.
+export const codeBuddyAuthMethodLabelKey = (methodId: string) => (
+ methodId === "internal" ? "aiAssistant.agentSource.codebuddyMethodInternal" : null
+);
+
export const prepareDesktopAcp = async (input: Omit<DesktopAcpPromptInput, "prompt" | "contextText" | "historyText" | "attachments">) => {
const desktop = bridge();
if (!desktop?.prepareAcp || !input.sessionKey) return { ready: false as const };
diff --git a/apps/web/src/lib/infographic-local-agent.test.mjs b/apps/web/src/lib/infographic-local-agent.test.mjs
index 1897fa9b..290e55e4 100644
--- a/apps/web/src/lib/infographic-local-agent.test.mjs
+++ b/apps/web/src/lib/infographic-local-agent.test.mjs
@@ -93,6 +93,7 @@ test("local infographic text follows one ACP request and can be cancelled", asyn
test("infographic requests use the same note access errors without blaming the agent login", () => {
expect(infographicLocalAgentErrorKey("note_access_network", "workbuddyIntl")).toBe("aiAssistant.sidebar.noteAccessNetwork");
+ expect(infographicLocalAgentErrorKey("node_missing", "codebuddy")).toBe("aiAssistant.agentSource.codebuddyNodeMissingHint");
expect(infographicLocalAgentErrorKey("note_access_login_required", "workbuddyIntl")).toBe("aiAssistant.sidebar.noteAccessLoginRequired");
expect(infographicLocalAgentErrorKey("note_access_changed", "codex")).toBe("aiAssistant.sidebar.noteAccessChanged");
});
diff --git a/apps/web/src/lib/infographic-local-agent.ts b/apps/web/src/lib/infographic-local-agent.ts
index 2c2aa258..b3ff0467 100644
--- a/apps/web/src/lib/infographic-local-agent.ts
+++ b/apps/web/src/lib/infographic-local-agent.ts
@@ -110,6 +110,7 @@ export const infographicLocalAgentErrorKey = (message: string, adapterId: string
? "aiAssistant.sidebar.workbuddyLoginRequired"
: "aiAssistant.sidebar.localLoginRequired";
}
+ if (message === "node_missing" && adapterId === "codebuddy") return "aiAssistant.agentSource.codebuddyNodeMissingHint";
if (message === "agent_refused") return "aiAssistant.sidebar.agentRefused";
const noteAccessErrorKey = desktopAcpNoteAccessErrorKey(message);
if (noteAccessErrorKey) return noteAccessErrorKey;
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 6453c638..e6d0b2cd 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -161,7 +161,7 @@ interface EdgeEverDesktopBridge {
finishWeChatImport?(importId: string, success: boolean): Promise<void>;
retryWeChatImport?(importId: string): Promise<boolean>;
listAcpAdapters?(): Promise<Array<{
- id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl";
+ id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl" | "codebuddy";
label: string;
state: "not_installed" | "not_probed" | "installing" | "needs_login" | "available" | "failed";
detail?: string;
@@ -172,8 +172,8 @@ interface EdgeEverDesktopBridge {
authMethods?: Array<{ id: string; name: string }>;
}>>;
chooseAcpAdapterPath?(): Promise<string | null>;
- probeAcpAdapter?(input: { id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl"; path?: string }): Promise<{
- id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl";
+ probeAcpAdapter?(input: { id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl" | "codebuddy"; path?: string }): Promise<{
+ id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl" | "codebuddy";
label: string;
state: "not_installed" | "needs_login" | "available" | "failed";
detail?: string;
@@ -190,21 +190,23 @@ interface EdgeEverDesktopBridge {
promptCapabilities?: { image?: boolean; embeddedContext?: boolean };
authMethods?: Array<{ id: string; name: string }>;
} }>;
- authenticateAcpAdapter?(input: { id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl"; path?: string; methodId: string }): Promise<{
- id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl";
+ authenticateAcpAdapter?(input: { id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl" | "codebuddy"; path?: string; methodId: string }): Promise<{
+ id: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl" | "codebuddy";
label: string;
state: "not_installed" | "needs_login" | "available" | "failed";
detail?: string;
authMethods?: Array<{ id: string; name: string }>;
}>;
+ cancelAcpAuthentication?(id: "codebuddy"): Promise<{ cancelled: boolean }>;
+ reopenAcpLoginPage?(id: "codebuddy"): Promise<{ opened: boolean }>;
prepareAcp?(input: {
- adapterId: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl";
+ adapterId: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl" | "codebuddy";
path?: string;
sessionKey?: string;
noteAccess?: boolean;
}): Promise<{ ready: boolean }>;
promptAcp?(input: {
- adapterId: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl";
+ adapterId: "codex" | "claudeCode" | "antigravity" | "openClaw" | "hermesAgent" | "grokBuild" | "deepseekHarness" | "piAgent" | "workbuddyCn" | "workbuddyIntl" | "codebuddy";
path?: string;
prompt: string;
contextText?: string;
diff --git a/docs/changes/2026-11-02-desktop-codebuddy-agent.md b/docs/changes/2026-11-02-desktop-codebuddy-agent.md
new file mode 100644
index 00000000..b2c9f38b
--- /dev/null
+++ b/docs/changes/2026-11-02-desktop-codebuddy-agent.md
@@ -0,0 +1,65 @@
+# Add CodeBuddy as a desktop local agent
+
+[简体中文](2026-11-02-desktop-codebuddy-agent.zh-CN.md)
+
+Related Issue: #758
+
+## Problem and outcome
+
+WorkBuddy and CodeBuddy share accounts and quota, but the desktop WorkBuddy integration depends on private details of the CLI bundled inside the WorkBuddy app (the lite-wb bundle, `--serve`, the credential encryption module), so WorkBuddy updates often break the connection (for example #584 and #600). Add a separate **CodeBuddy** option that runs the standard stdio ACP of the official CLI the user installs (`@tencent-ai/codebuddy-code`). WorkBuddy users can switch to it.
+
+## Allowed changes and acceptance
+
+1. Add a single CodeBuddy option with no China / international split; the CLI picks the region from the sign-in method. Clear inherited `CODEBUDDY_INTERNET_ENVIRONMENT` and `CODEBUDDY_INTERNET_ENVIROMENT` at launch so the endpoint cannot disagree with the sign-in.
+2. Use only the standalone official CLI: never WorkBuddy's bundled CLI (paths inside `app.asar` are rejected and the package name is checked), and no `--serve`, credential bridge or gateway sign-in. Launch `node <package>/bin/codebuddy --acp`. On POSIX, check every `codebuddy` on the PATH and the desktop tool directories in order:
+ - Symbolic links are followed to the official entry.
+ - asdf, mise and Volta shims are resolved through the manager's own `which` (cached per shim for 30 seconds).
+ - An invalid candidate moves on to the next one, so it never hides a later valid install.
+ - nvm's default alias may be a full or partial version (such as `22`), `node` / `stable`, `lts/*` or a named alias. On Windows, find npm's `codebuddy.cmd` and use the entry in the `node_modules` beside it, without running the `.cmd` or using `shell: true`. Prefer the Node in the npm prefix that installed the CLI, then the shim directory, and report `node_missing` when none is found.
+3. Sign in through the standard ACP `authenticate`, reusing the existing 5-minute sign-in timeout. The CLI opens the browser itself, so EdgeEver does not open it again. `_codebuddy.ai/authUrl` is handled only during a CodeBuddy sign-in the user started; a validated link stays in the main process for a manual "Reopen sign-in page" (repeat clicks within 3 seconds are ignored). The allowlist holds only the verified `copilot.tencent.com` (WeChat) and `codebuddy.ai` (Google / GitHub) and their subdomains, and rejects non-https links, user info and non-default ports. Enterprise domains are not included. A rejected link records only a fixed diagnostic code, never the URL or its query.
+4. A `_codebuddy.ai/getUserInfo` response without `userInfo` or a token counts as signed out. Tokens never cross IPC or appear in logs. After `authenticate` returns, a fresh CLI process must restore the sign-in before success is reported.
+5. Cancel works through the UI, IPC and the process lifecycle: it ends the CLI process and removes its temporary workspace. Switching to another agent or leaving the settings page also cancels a sign-in in progress. Results distinguish cancelled, timed out and failed. Closing the browser page is not a cancel.
+6. Front end: agent list, AI sidebar, official logo (source recorded in `sources.json`) and strings in five languages. Only the verified WeChat method is labelled as China; other methods keep the CLI's name. When the CLI is missing, the hint shows `npm i -g @tencent-ai/codebuddy-code`.
+
+## Boundaries, risks and recovery
+
+- The change is concentrated in the new `codebuddy-cli.mjs` and the CodeBuddy branch of `acp-host.mjs` (sign-in flow and IPC for cancel and reopen). The shared `connect` gained an account-check parameter and an `authUrl` callback. WorkBuddy's existing check is unchanged, but this is a shared path, so other agents need regression testing.
+- EdgeEver's own accounts, storage and migrations are untouched. Revert the commit to roll back; the user's CodeBuddy sign-in lives in the CLI's own configuration directory and is unaffected.
+- iOA and enterprise-domain sign-ins are not on the allowlist: the CLI still opens the browser itself, but EdgeEver's "Reopen sign-in page" is unavailable for them.
+
+## Implementation and acceptance
+
+- Unit tests: command resolution and not installed (POSIX, Windows `.cmd`, nvm Node, other packages, WorkBuddy's bundled copy, missing Node; asdf, mise and Volta shims; invalid candidates not hiding later installs; nvm `22`, `lts/*`, `node` and named aliases, plus a real-filesystem regression finding the CLI through `lts/*` with a minimal PATH), clearing region variables, the link allowlist, handling `authUrl` only during sign-in, duplicate notifications and reopen throttling, timeout and cancel (including process exit), missing credentials, the fresh-process check after sign-in, and IPC permissions.
+- Real macOS (CodeBuddy CLI 2.164.0 via Homebrew), using a minimal Finder-like PATH:
+ - Resolution found `/opt/homebrew/bin/node` and the official entry.
+ - With `CODEBUDDY_INTERNET_ENVIRONMENT=selfhosted` set, the connection check still reported available, and a real chat replied "OK".
+ - With an isolated empty configuration, the check reported sign-in required and listed the CLI's four methods.
+ - The WeChat sign-in produced a `copilot.tencent.com` link, and reopen throttling worked.
+ - Cancel ended the sign-in as cancelled in about one second, with no leftover process.
+ - Leaving the sign-in unfinished ended it as a timeout.
+ - Diagnostics contained no sign-in link parameters.
+
+ WeChat sign-in, keeping the sign-in after a restart, and independence from WorkBuddy accounts were verified earlier with the same CLI (see #758).
+- macOS desktop UI (development Electron with the official v2.16.1 sidecar and an isolated app profile):
+ - With the signed-in CLI, the check reported a usable session. The logo and sign-in labels were correct ("微信登录(国内)"; other methods keep the CLI's names).
+ - With an empty CLI configuration, the card showed "Sign in to CodeBuddy".
+ - Clicking the WeChat sign-in showed the in-progress hint, "Reopen sign-in page" and "Cancel sign-in".
+ - Cancelling showed "Sign-in cancelled" and left no process.
+ - Switching to Codex during sign-in ended the CLI process.
+- `bun run typecheck`, `bun run typecheck:mobile`, `bun run build:web` and `bun run lint` passed. The only failure in the full non-E2E suite, `tests/deployment-entrypoints.test.ts`, also fails on unchanged `main` and is unrelated.
+- Unsigned test installers (built by a temporary workflow on the fork):
+ - Linux arm64 (Ubuntu 24.04, AppImage run after extraction). Setup:
+ - Node 22 and CodeBuddy CLI 2.179.2 were installed under `~/.local`.
+ - The desktop session PATH did not include `~/.local/bin`.
+ - The system Node was v18.19.1, below the CLI's requirement.
+
+ Results:
+ - Launched from the app menu, the app still found the CLI and the Node 22 beside it.
+ - The check reported sign-in required.
+ - The WeChat sign-in opened the login page in the browser, and cancel worked.
+ - After a QR sign-in, the sign-in survived an app restart.
+ - A real chat replied "OK".
+ - Logs contained no sign-in link or token.
+ - macOS arm64 (DMG, locally ad-hoc signed): opened from Launchpad, the check reported a usable session and a real chat replied "OK".
+ - Windows x64 (NSIS installer, CLI installed with npm): manual testing of the connection check, sign-in and chat passed.
+- Not verified: iOA and enterprise-domain sign-in; a full Google / GitHub sign-in; token expiry and refresh; real-device regression for other agents (unit tests only); real nvm, asdf, mise and Volta installs (unit tests only).
diff --git a/docs/changes/2026-11-02-desktop-codebuddy-agent.zh-CN.md b/docs/changes/2026-11-02-desktop-codebuddy-agent.zh-CN.md
new file mode 100644
index 00000000..375af2b8
--- /dev/null
+++ b/docs/changes/2026-11-02-desktop-codebuddy-agent.zh-CN.md
@@ -0,0 +1,36 @@
+# 桌面端本机 Agent 新增 CodeBuddy
+
+[English](2026-11-02-desktop-codebuddy-agent.md)
+
+关联 Issue:#758
+
+## 问题与目标
+
+WorkBuddy 与 CodeBuddy 共用账号和额度,但桌面端接入 WorkBuddy 依赖其应用内置 CLI 的私有实现(lite-wb 精简包、`--serve`、凭据加密模块等),WorkBuddy 升级后容易连接失败(如 #584、#600)。新增独立的 **CodeBuddy** 选项,直接调用用户自行安装的官方 CLI(`@tencent-ai/codebuddy-code`)的标准 stdio ACP,WorkBuddy 用户可改用该选项。
+
+## 允许变更与验收
+
+1. 只新增一个 CodeBuddy 选项,不区分国内版与国际版;区域由 CLI 按用户选择的登录方式决定。启动时清除继承的 `CODEBUDDY_INTERNET_ENVIRONMENT` 与 `CODEBUDDY_INTERNET_ENVIROMENT`,避免端点与登录状态不一致。
+2. 只使用独立安装的官方 CLI:不使用 WorkBuddy 内置 CLI(排除 `app.asar` 路径并校验包名),不使用 `--serve`、凭据桥接或网关登录。以 `node <包>/bin/codebuddy --acp` 启动:POSIX 依次检查 PATH 与桌面工具目录中的每个 `codebuddy`:符号链接解析到官方入口;asdf、mise、Volta 的 shim 交给对应管理器的 `which` 解析真实入口(按 shim 缓存 30 秒);某个候选无效时继续检查后续候选,不会遮蔽后面的有效安装。nvm 的默认别名支持完整或部分版本号(如 `22`)、`node`/`stable`、`lts/*` 及自定义别名;Windows 通过 npm 的 `codebuddy.cmd` 定位同目录 `node_modules` 中的入口,不执行 `.cmd`、不使用 `shell: true`。优先使用安装该 CLI 的 npm 前缀中的 Node,其次是 shim 所在目录,找不到时报告 `node_missing`。
+3. 登录走 ACP 标准 `authenticate`,复用现有 5 分钟登录超时。CLI 会自行打开浏览器,EdgeEver 不再自动打开;仅在用户发起的 CodeBuddy 登录期间接收 `_codebuddy.ai/authUrl`,校验后只保存在主进程,供用户手动“重新打开登录页”(3 秒内重复点击不生效)。白名单仅含已验证的 `copilot.tencent.com`(微信)与 `codebuddy.ai`(Google / GitHub)及其子域;拒绝非 https、带用户信息或非默认端口的链接,不包含企业域名。被拒绝的链接只记录固定诊断码,不记录完整 URL 或查询参数。
+4. `_codebuddy.ai/getUserInfo` 缺少 `userInfo` 或 token 一律视为未登录;token 不跨 IPC、不写日志。`authenticate` 返回后还需新启动一个 CLI 进程恢复登录,才报告登录成功。
+5. 取消贯通界面、IPC 与进程生命周期:取消会结束 CLI 进程并清理临时工作区;切换到其他 Agent 或离开设置页也会取消进行中的登录。结果区分已取消、超时与失败;关闭浏览器页面不视为取消。
+6. 前端:Agent 列表、AI 侧边栏、官方 Logo(来源记录于 `sources.json`)和五种语言文案。登录方式只为已验证的微信登录标注“国内”,其他方式沿用 CLI 返回的名称。未安装时提示 `npm i -g @tencent-ai/codebuddy-code`。
+
+## 边界、风险与恢复
+
+- 改动集中在新的 `codebuddy-cli.mjs` 与 `acp-host.mjs` 中 CodeBuddy 分支(登录流程、取消与重新打开登录页的 IPC)。共享的 `connect` 增加了账号校验参数与 `authUrl` 回调,WorkBuddy 的原有校验逻辑保持不变,但属于共享路径的改动,需对其他 Agent 回归。
+- 不涉及 EdgeEver 自身账号、数据存储或迁移;回滚撤回本次提交即可,用户的 CodeBuddy 登录保存在 CLI 自己的配置目录中,不受影响。
+- iOA、企业域名登录不在白名单内:CLI 仍会自行打开浏览器,但 EdgeEver 的“重新打开登录页”不可用。
+
+## 实现与验收结论
+
+- 单元测试:命令解析与未安装(POSIX、Windows `.cmd`、nvm Node、非官方包、WorkBuddy 内置副本、缺少 Node;asdf、mise、Volta shim;无效候选不遮蔽后续安装;nvm 的 `22`、`lts/*`、`node` 与自定义别名,以及最小 PATH 下经 `lts/*` 找到 CLI 的真实文件系统回归)、清除区域变量、链接白名单、仅登录上下文处理 `authUrl`、重复通知与重新打开节流、超时与取消(含进程退出)、缺少凭据、登录后新进程校验、IPC 权限。
+- macOS 真机(CodeBuddy CLI 2.164.0,Homebrew 安装):在仿 Finder 启动的最小 PATH 下解析到 `/opt/homebrew/bin/node` 与官方入口;设置 `CODEBUDDY_INTERNET_ENVIRONMENT=selfhosted` 后检查连接仍为可用,真实对话回复 “OK”;隔离的空配置目录中检查为需要登录、列出 CLI 的 4 种登录方式;微信登录收到 `copilot.tencent.com` 链接,重新打开节流生效,取消后约 1 秒结束为“已取消”且无残留进程;不完成登录时按超时结束;诊断中不含登录链接参数。此前已用同一 CLI 验证微信登录、重启后保持登录及与 WorkBuddy 账号互不影响(见 #758)。
+- macOS 桌面端界面(开发版 Electron + 官方 v2.16.1 sidecar,隔离的应用配置):已登录 CLI 检查为“会话可用”,Logo 与登录按钮文案正确(“微信登录(国内)”,其他方式沿用 CLI 名称);空 CLI 配置下显示“请登录 CodeBuddy”;点击微信登录后显示进行中提示、“重新打开登录页”与“取消登录”;取消后显示“已取消登录”且无残留进程;登录进行中切换到 Codex 会结束 CLI 进程。
+- `bun run typecheck`、`bun run typecheck:mobile`、`bun run build:web`、`bun run lint` 通过;完整非 E2E 测试中唯一失败的 `tests/deployment-entrypoints.test.ts` 在未改动的 `main` 上同样失败,与本次无关。
+- 未签名测试安装包(fork 上的临时工作流编译):
+ - Linux arm64(Ubuntu 24.04,AppImage 解压运行):Node 22 与 CodeBuddy CLI 2.179.2 装在 `~/.local`,桌面会话 PATH 不含 `~/.local/bin`,系统 Node 为不满足 CLI 要求的 v18.19.1。从应用菜单启动后仍找到 CLI 与同目录 Node 22;检查连接显示需要登录;微信登录时浏览器自动打开登录页;取消正常;扫码登录后重启应用仍保持登录;真实对话回复 “OK”;日志中无登录链接或 token。
+ - macOS arm64(DMG,本机临时签名):从启动台打开,检查连接为会话可用,真实对话回复 “OK”。
+ - Windows x64(NSIS 安装包,npm 安装的 CLI):人工测试检查连接、登录与对话正常。
+- 未验证:iOA 与企业域名登录;Google / GitHub 完整登录流程;token 过期与刷新;其他 Agent 的真机回归(仅单元测试);nvm、asdf、mise、Volta 安装的真机场景(仅单元测试)。
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 1a6affbf..8c69bc0f 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -1909,6 +1909,7 @@ export const enUS = {
workbuddy: "WorkBuddy",
workbuddyCn: "WorkBuddy China",
workbuddyIntl: "WorkBuddy International",
+ codebuddy: "CodeBuddy",
grokBuild: "Grok Build",
deepseekHarness: "DeepSeek Harness",
piAgent: "pi agent",
@@ -1960,6 +1961,17 @@ export const enUS = {
updating: "Updating…",
authenticating: "Signing in…",
authenticationTimedOut: "Sign-in did not complete. Please try again.",
+ codebuddyNotFound: "CodeBuddy CLI not found",
+ codebuddyMissingHint: "Run npm i -g @tencent-ai/codebuddy-code in a terminal to install the official CodeBuddy CLI, then check the connection again. CodeBuddy and WorkBuddy share the same account and quota.",
+ codebuddyNodeMissing: "Node.js not found",
+ codebuddyNodeMissingHint: "CodeBuddy CLI needs Node.js. Make sure the Node.js used to install the CLI is still available, then check the connection again.",
+ codebuddyLoginRequired: "Sign in to CodeBuddy",
+ codebuddyLoginHint: "Choose a sign-in method. CodeBuddy opens the sign-in page in your browser; come back here when you finish.",
+ codebuddyMethodInternal: "Sign in with WeChat (China)",
+ codebuddyLoginInProgress: "Finish signing in in your browser within 5 minutes. Closing the browser page does not cancel sign-in.",
+ codebuddyReopenLogin: "Reopen sign-in page",
+ cancelLogin: "Cancel sign-in",
+ authenticationCancelled: "Sign-in cancelled",
authenticationFailed: "Sign-in failed or was cancelled. Try again.",
authenticateWith: "Sign in with {{method}}",
authAvailableHint: "This agent offers ACP sign-in. If sending a message requires login, complete it here.",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index bb81fb52..332634e4 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -1898,6 +1898,7 @@ export const ja = {
workbuddy: "WorkBuddy",
workbuddyCn: "WorkBuddy 中国版",
workbuddyIntl: "WorkBuddy 国際版",
+ codebuddy: "CodeBuddy",
grokBuild: "Grok Build",
deepseekHarness: "DeepSeek Harness",
piAgent: "pi agent",
@@ -1949,6 +1950,17 @@ export const ja = {
updating: "更新中…",
authenticating: "ログイン中…",
authenticationTimedOut: "ログインが完了しませんでした。再試行してください。",
+ codebuddyNotFound: "CodeBuddy CLI が見つかりません",
+ codebuddyMissingHint: "ターミナルで npm i -g @tencent-ai/codebuddy-code を実行して公式 CodeBuddy CLI をインストールし、接続を再確認してください。CodeBuddy と WorkBuddy はアカウントと利用枠を共有します。",
+ codebuddyNodeMissing: "Node.js が見つかりません",
+ codebuddyNodeMissingHint: "CodeBuddy CLI の実行には Node.js が必要です。CLI のインストールに使った Node.js が利用できることを確認し、接続を再確認してください。",
+ codebuddyLoginRequired: "CodeBuddy にログインしてください",
+ codebuddyLoginHint: "ログイン方法を選ぶと、CodeBuddy がブラウザでログインページを開きます。完了したらここに戻ってください。",
+ codebuddyMethodInternal: "WeChat でログイン(中国)",
+ codebuddyLoginInProgress: "5 分以内にブラウザでログインを完了してください。ブラウザのページを閉じてもログインはキャンセルされません。",
+ codebuddyReopenLogin: "ログインページを再度開く",
+ cancelLogin: "ログインをキャンセル",
+ authenticationCancelled: "ログインをキャンセルしました",
authenticationFailed: "ログインに失敗したか、キャンセルされました。再試行してください。",
authenticateWith: "{{method}} でログイン",
authAvailableHint: "この Agent は ACP ログインに対応しています。メッセージ送信時にログインを求められた場合は、ここで認証してください。",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 4286f2bb..8fdebf9c 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -1898,6 +1898,7 @@ export const pl = {
workbuddy: "WorkBuddy",
workbuddyCn: "WorkBuddy (Chiny)",
workbuddyIntl: "WorkBuddy (międzynarodowy)",
+ codebuddy: "CodeBuddy",
grokBuild: "Grok Build",
deepseekHarness: "DeepSeek Harness",
piAgent: "pi agent",
@@ -1949,6 +1950,17 @@ export const pl = {
updating: "Aktualizowanie…",
authenticating: "Logowanie…",
authenticationTimedOut: "Logowanie nie zostało ukończone. Spróbuj ponownie.",
+ codebuddyNotFound: "Nie znaleziono CodeBuddy CLI",
+ codebuddyMissingHint: "Uruchom w terminalu npm i -g @tencent-ai/codebuddy-code, aby zainstalować oficjalny CodeBuddy CLI, a potem ponownie sprawdź połączenie. CodeBuddy i WorkBuddy korzystają z tego samego konta i limitu.",
+ codebuddyNodeMissing: "Nie znaleziono Node.js",
+ codebuddyNodeMissingHint: "CodeBuddy CLI wymaga Node.js. Upewnij się, że Node.js użyty do instalacji CLI jest nadal dostępny, a potem ponownie sprawdź połączenie.",
+ codebuddyLoginRequired: "Zaloguj się do CodeBuddy",
+ codebuddyLoginHint: "Wybierz metodę logowania. CodeBuddy otworzy stronę logowania w przeglądarce; po zakończeniu wróć tutaj.",
+ codebuddyMethodInternal: "Zaloguj przez WeChat (Chiny)",
+ codebuddyLoginInProgress: "Dokończ logowanie w przeglądarce w ciągu 5 minut. Zamknięcie strony w przeglądarce nie anuluje logowania.",
+ codebuddyReopenLogin: "Otwórz ponownie stronę logowania",
+ cancelLogin: "Anuluj logowanie",
+ authenticationCancelled: "Logowanie anulowane",
authenticationFailed: "Logowanie nie powiodło się lub zostało anulowane. Spróbuj ponownie.",
authenticateWith: "Zaloguj się przez {{method}}",
authAvailableHint: "Ten agent oferuje logowanie ACP. Jeśli wysłanie wiadomości wymaga zalogowania, dokończ je tutaj.",
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index 6921cc0a..36ab3921 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -1909,6 +1909,7 @@ export const ru = {
workbuddy: "WorkBuddy",
workbuddyCn: "WorkBuddy Китай",
workbuddyIntl: "WorkBuddy международный",
+ codebuddy: "CodeBuddy",
grokBuild: "Grok Build",
deepseekHarness: "DeepSeek Harness",
piAgent: "pi agent",
@@ -1960,6 +1961,17 @@ export const ru = {
updating: "Обновление…",
authenticating: "Вход…",
authenticationTimedOut: "Вход не завершился. Повторите попытку.",
+ codebuddyNotFound: "CodeBuddy CLI не найден",
+ codebuddyMissingHint: "Выполните в терминале npm i -g @tencent-ai/codebuddy-code, чтобы установить официальный CodeBuddy CLI, затем снова проверьте подключение. CodeBuddy и WorkBuddy используют общий аккаунт и лимит.",
+ codebuddyNodeMissing: "Node.js не найден",
+ codebuddyNodeMissingHint: "Для CodeBuddy CLI нужен Node.js. Убедитесь, что Node.js, с помощью которого установлен CLI, по-прежнему доступен, затем снова проверьте подключение.",
+ codebuddyLoginRequired: "Войдите в CodeBuddy",
+ codebuddyLoginHint: "Выберите способ входа. CodeBuddy откроет страницу входа в браузере; после входа вернитесь сюда.",
+ codebuddyMethodInternal: "Войти через WeChat (Китай)",
+ codebuddyLoginInProgress: "Завершите вход в браузере в течение 5 минут. Закрытие страницы в браузере не отменяет вход.",
+ codebuddyReopenLogin: "Открыть страницу входа снова",
+ cancelLogin: "Отменить вход",
+ authenticationCancelled: "Вход отменён",
authenticationFailed: "Вход не удался или был отменён. Повторите.",
authenticateWith: "Войти через {{method}}",
authAvailableHint: "У этого агента есть вход ACP. Если для сообщения нужен вход, выполните его здесь.",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 19cb70c0..d35dcabf 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -1909,6 +1909,7 @@ export const zhCN = {
workbuddy: "WorkBuddy",
workbuddyCn: "WorkBuddy 国内版",
workbuddyIntl: "WorkBuddy 国际版",
+ codebuddy: "CodeBuddy",
grokBuild: "Grok Build",
deepseekHarness: "DeepSeek Harness",
piAgent: "pi agent",
@@ -1960,6 +1961,17 @@ export const zhCN = {
updating: "正在更新…",
authenticating: "正在登录…",
authenticationTimedOut: "登录未完成,请重试",
+ codebuddyNotFound: "未找到 CodeBuddy CLI",
+ codebuddyMissingHint: "在终端运行 npm i -g @tencent-ai/codebuddy-code 安装官方 CodeBuddy CLI,然后重新检查连接。CodeBuddy 与 WorkBuddy 共用账号和额度。",
+ codebuddyNodeMissing: "未找到 Node.js",
+ codebuddyNodeMissingHint: "CodeBuddy CLI 需要 Node.js 运行。请确认安装 CLI 时使用的 Node.js 仍然可用,然后重新检查连接。",
+ codebuddyLoginRequired: "请登录 CodeBuddy",
+ codebuddyLoginHint: "选择登录方式后,CodeBuddy 会在浏览器中打开登录页,完成后回到这里。",
+ codebuddyMethodInternal: "微信登录(国内)",
+ codebuddyLoginInProgress: "请在浏览器中完成登录,5 分钟内有效。关闭浏览器页面不会取消登录。",
+ codebuddyReopenLogin: "重新打开登录页",
+ cancelLogin: "取消登录",
+ authenticationCancelled: "已取消登录",
authenticationFailed: "登录失败或已取消,请重试",
authenticateWith: "使用 {{method}} 登录",
authAvailableHint: "此 Agent 提供 ACP 登录方式。若发消息时提示需要登录,可在这里完成认证。",