From 775165a0603cd5ae073b4042770c1d7a84f518ea Mon Sep 17 00:00:00 2001 From: starsstreaming <2946843254lw@gmail.com> Date: Wed, 18 Nov 2026 11:06:37 +0800 Subject: [PATCH] fix: restore DSH, WorkBuddy, and Doubao host compatibility --- docs/deepseek-harness.md | 2 + docs/host-adapter-cursor-doubao.md | 2 + integrations/deepseek-harness/cli.js | 207 ++-------------- integrations/deepseek-harness/package.json | 1 + .../deepseek-harness/profile-patch.mjs | 165 +++++++++++++ .../deepseek-harness/test/pack.test.mjs | 25 +- packages/adapter-desktop-cdp/src/cdp.ts | 5 +- packages/adapter-doubao/src/spec.ts | 3 + packages/adapter-doubao/test/contract.test.js | 23 +- .../adapter-dsh/test/launcher-scripts.test.js | 20 +- packages/adapter-workbuddy/src/launch.ts | 218 +---------------- .../src/process-discovery.ts | 225 ++++++++++++++++++ .../adapter-workbuddy/test/discovery.test.js | 8 + .../src/dsh-installation.mjs | 8 +- .../src/host-executables.mjs | 66 +++++ packages/beauticode-desktop/src/index.mjs | 63 +---- packages/beauticode-desktop/test/all.test.mjs | 5 + .../test/dsh-installation.test.mjs | 16 +- packages/core/test/media-server.test.js | 8 +- scripts/build-windows-installer.ps1 | 2 + scripts/install-dsh-plugin.ps1 | 20 +- scripts/pack-dsh-plugin.mjs | 1 + 22 files changed, 615 insertions(+), 478 deletions(-) create mode 100644 integrations/deepseek-harness/profile-patch.mjs create mode 100644 packages/adapter-workbuddy/src/process-discovery.ts create mode 100644 packages/beauticode-desktop/src/host-executables.mjs diff --git a/docs/deepseek-harness.md b/docs/deepseek-harness.md index 4e912c9..7232335 100644 --- a/docs/deepseek-harness.md +++ b/docs/deepseek-harness.md @@ -2,6 +2,8 @@ beautiCode 通过 DeepSeek Harness 的 Cordis 插件接口接入(`beauticode-dsh`),不修改 DSH 源码,也不依赖 Chromium 调试端口。插件通过 DSH 的结构化页面注入同时支持 Web 和官方 Desktop;后者的页面地址是 `dsh-app://app/`,Host 默认端口是 `19387`。DSH 由你自己启动;beautiCode 只挂插件、不替代、不重启你的 DSH。Codex Desktop 仍由托盘按原路径拉起,与本节无关。 +Web 安装器按 profile 的 dsh.profile.bundles 判断插件是否已经注册为包层。已注册时保留包层并备份、移除重复的补丁条目;未注册时由当前 profile 的补丁挂载。已有 DSH 主目录改用目录联接点时,安装器解析该目录的真实位置,继续检查插件子目录及链接归属。 + ## 已实现能力 - 图片背景、MP4 视频背景与清除。首页(`data-phase="hero"`)壁纸保持原亮度;进入会话(`active` / `settling`)后才压暗。 diff --git a/docs/host-adapter-cursor-doubao.md b/docs/host-adapter-cursor-doubao.md index 0eebd05..de6ba1c 100644 --- a/docs/host-adapter-cursor-doubao.md +++ b/docs/host-adapter-cursor-doubao.md @@ -35,6 +35,8 @@ runtime\node.exe scripts\desktop-cdp-setup.mjs --host doubao install | Cursor | 3.18.9 | 9341 | `vscode-file://vscode-app/d:/cursor/resources/app/out/vs/code/electron-sandbox/workbench/workbench.html` | `[data-action-id="marketplace"][data-sidebar-primary-action]`,标签 `Customize` | | 豆包 | 2.29.12 | 9342 | `doubao://doubao-chat/chat` | `[data-testid="skill-page-item-more"]`,标签 `更多` | +豆包 2.31.4 的当前 Windows 安装程序默认写入 %LOCALAPPDATA%\Doubao\Application\Doubao.exe,主窗口启动阶段也会报告 doubao://doubao-chat/chat/。两种精确主路由都可匹配,其他窗口或路径会被忽略。 + 锚点或标签不一致时注入会失败关闭,不会用模糊文本匹配插入其他页面。客户端升级后应先重新测量这些契约。 Cursor 的入口是 `background`,直接位于 `Customize` 后;所有面板文案为英文。豆包的入口是 `自定义背景`,直接位于 `更多` 后;面板文案为中文。 diff --git a/integrations/deepseek-harness/cli.js b/integrations/deepseek-harness/cli.js index 432fd8e..8d97697 100644 --- a/integrations/deepseek-harness/cli.js +++ b/integrations/deepseek-harness/cli.js @@ -11,6 +11,7 @@ import crypto from "node:crypto"; import os from "node:os"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { backupPatch, fileUriInsert, hasBridge, packageInsert, removePatch, writePatch } from "./profile-patch.mjs"; function findPackageRoot(startDir) { let dir = startDir; @@ -30,7 +31,6 @@ function findPackageRoot(startDir) { const here = findPackageRoot(path.dirname(fileURLToPath(import.meta.url))); const pluginName = "beauticode-dsh"; -const bridgeId = "beauticode-bridge"; function argValue(argv, name) { const idx = argv.indexOf(name); @@ -134,51 +134,6 @@ function legacyDefaultPluginHome() { return path.join(defaultDataRoot(), "plugin"); } -function toFileUri(filePath) { - const full = path.resolve(filePath).replaceAll("\\", "/"); - if (/^[A-Za-z]:/.test(full)) return `file:///${full}`; - return pathToFileURL(full).href; -} - -function fileUriInsert(uri) { - return [ - "# beauticode-bridge (installer)", - "- insert:", - " - id: beauticode-bridge", - ` name: '${uri}'`, - " inject: [webServer]", - "", - ].join("\n"); -} - -function packageInsert() { - return [ - "# beauticode-bridge (installer)", - "- insert:", - " - id: beauticode-bridge", - ` name: '${pluginName}'`, - " inject: [webServer]", - "", - ].join("\n"); -} - -function hasBridge(text) { - return new RegExp(`^[ \\t]*-[ \\t]*id:[ \\t]*${bridgeId}[ \\t]*(?:#.*)?\\r?$`, "m").test(text); -} - -function bridgeCount(text) { - return (String(text).match(new RegExp(`^[ \\t]*-[ \\t]*id:[ \\t]*${bridgeId}[ \\t]*(?:#.*)?\\r?$`, "gm")) || []).length; -} - -async function backupPatch(filePath) { - const base = `${filePath}.beauticode-backup-${Date.now()}`; - let backup = base; - let suffix = 0; - while (fs.existsSync(backup)) backup = `${base}-${++suffix}`; - await fsp.copyFile(filePath, backup, fs.constants.COPYFILE_EXCL); - return backup; -} - async function backupDirectory(target) { const base = `${target}.beauticode-backup-${Date.now()}`; let backup = base; @@ -188,129 +143,6 @@ async function backupDirectory(target) { return backup; } -async function backupDuplicatePatch(filePath) { - return backupPatch(filePath); -} - -function stripBridge(text) { - const lines = text.split(/\r?\n/); - const removed = new Array(lines.length).fill(false); - const indentOf = (line) => line.match(/^[ \t]*/)?.[0].length ?? 0; - - for (let i = 0; i < lines.length; i += 1) { - const insert = lines[i].match(/^([ \t]*)-\s*insert:\s*(?:#.*)?$/); - if (!insert) continue; - const insertIndent = insert[1].length; - let blockEnd = i + 1; - while (blockEnd < lines.length) { - const line = lines[blockEnd]; - if (line.trim() && indentOf(line) <= insertIndent) break; - blockEnd += 1; - } - - let foundBridge = false; - for (let j = i + 1; j < blockEnd; ) { - const bridge = lines[j].match( - /^([ \t]*)-\s*id:\s*beauticode-bridge\s*(?:#.*)?$/, - ); - if (!bridge || bridge[1].length <= insertIndent) { - j += 1; - continue; - } - foundBridge = true; - const itemIndent = bridge[1].length; - let itemEnd = j + 1; - while (itemEnd < blockEnd) { - const line = lines[itemEnd]; - if (line.trim() && indentOf(line) <= itemIndent) break; - itemEnd += 1; - } - for (let k = j; k < itemEnd; k += 1) removed[k] = true; - j = itemEnd; - } - - if (!foundBridge) continue; - const marker = `${insert[1]}# beauticode-bridge (installer)`; - if (i > 0 && lines[i - 1].trimEnd() === marker) removed[i - 1] = true; - const hasSibling = lines - .slice(i + 1, blockEnd) - .some( - (line, offset) => - !removed[i + 1 + offset] && - line.trim() !== "" && - !line.trimStart().startsWith("#"), - ); - if (!hasSibling) { - for (let k = i; k < blockEnd; k += 1) removed[k] = true; - } - i = blockEnd - 1; - } - - return lines.filter((_, index) => !removed[index]).join("\n"); -} - -function overlayPayload(text) { - return text - .split(/\r?\n/) - .map((line) => line.trim()) - .filter((line) => line && !line.startsWith("#")) - .join("\n"); -} - -function isEmptyOverlay(text) { - const payload = overlayPayload(text); - return payload === "" || payload === "[]"; -} - -// DSH seeds overlays as `# comment\n[]`. `[]` is already a complete YAML -// document, so appending `- insert:` makes js-yaml throw. -function keptOverlay(text) { - const withoutFlowEmpty = text - .split(/\r?\n/) - .filter((line) => line.trim() !== "[]") - .join("\n"); - if (isEmptyOverlay(withoutFlowEmpty)) return ""; - return withoutFlowEmpty.trim(); -} - -function withTrailingNewline(text) { - return text.endsWith("\n") ? text : `${text}\n`; -} - -async function writePatch(filePath, body) { - await fsp.mkdir(path.dirname(filePath), { recursive: true }); - const insert = withTrailingNewline(body); - if (!fs.existsSync(filePath)) { - await fsp.writeFile(filePath, insert, "utf8"); - return; - } - const raw = await fsp.readFile(filePath, "utf8"); - if (hasBridge(raw) && bridgeCount(raw) > 1) { - await backupDuplicatePatch(filePath); - } - const remainder = hasBridge(raw) ? stripBridge(raw) : raw; - const kept = keptOverlay(remainder); - const next = kept ? `${kept}\n\n${insert}` : insert; - await fsp.writeFile(filePath, withTrailingNewline(next), "utf8"); -} - -async function removePatch(filePath) { - if (!fs.existsSync(filePath)) return false; - const raw = await fsp.readFile(filePath, "utf8"); - if (!hasBridge(raw)) return false; - const kept = keptOverlay(stripBridge(raw)); - if (!kept) { - await fsp.writeFile( - filePath, - "# Your patch layer for this dsh profile.\n[]\n", - "utf8", - ); - return true; - } - await fsp.writeFile(filePath, withTrailingNewline(kept), "utf8"); - return true; -} - function shouldCopy(source) { const relative = path.relative(here, source); if (relative.startsWith("test") || relative.includes(`${path.sep}test${path.sep}`)) { @@ -404,8 +236,7 @@ async function sameLinkTarget(link, dest) { try { const stat = await fsp.lstat(link); if (stat.isSymbolicLink()) { - const target = await fsp.readlink(link); - return path.resolve(path.dirname(link), target) === path.resolve(dest); + return path.relative(await fsp.realpath(link), await fsp.realpath(dest)) === ""; } if (stat.isDirectory()) { return path.resolve(link) === path.resolve(dest); @@ -488,9 +319,12 @@ async function ensureWebPackageDep(webPackage, pluginHome) { ); delete json.dependencies["@beauticode/dsh-plugin"]; const current = json.dependencies[pluginName]; - if (current === spec && !hadLegacy) return; + const bundles = json.dsh?.profile?.bundles; + const loadsPluginBundle = Array.isArray(bundles) && bundles.includes(pluginName); + if (current === spec && !hadLegacy) return loadsPluginBundle; json.dependencies[pluginName] = spec; await fsp.writeFile(webPackage, `${JSON.stringify(json, null, 2)}\n`, "utf8"); + return loadsPluginBundle; } async function removeWebPackageDep(webPackage) { @@ -504,6 +338,14 @@ async function removeWebPackageDep(webPackage) { changed = true; } } + const bundles = json.dsh?.profile?.bundles; + if (Array.isArray(bundles)) { + const remaining = bundles.filter((name) => name !== pluginName && name !== "@beauticode/dsh-plugin"); + if (remaining.length !== bundles.length) { + json.dsh.profile.bundles = remaining; + changed = true; + } + } if (!changed) return false; await fsp.writeFile(webPackage, `${JSON.stringify(json, null, 2)}\n`, "utf8"); return true; @@ -526,15 +368,13 @@ async function install(opts) { if (fs.existsSync(webPackage)) { await linkPluginIntoProfile(webProfile, dest); - await ensureWebPackageDep(webPackage, dest); + const loadsPluginBundle = await ensureWebPackageDep(webPackage, dest); const pluginPatch = path.join(dest, "cordis.patch.yml"); const pluginShipsBridge = fs.existsSync(pluginPatch) && hasBridge(await fsp.readFile(pluginPatch, "utf8")); - if (pluginShipsBridge) { - // DSH loads the package patch as well as the profile patch. Keep the - // package's canonical loader and remove only beautiCode's managed - // profile block, preserving unrelated profile configuration. Back up - // the user's profile before this repair, even when it had one entry. + if (loadsPluginBundle && pluginShipsBridge) { + // DSH composes only the bundles listed by this profile. Keep its + // existing bundle mount and back up any redundant overlay entry. if (fs.existsSync(webPatch)) { const profilePatch = await fsp.readFile(webPatch, "utf8"); if (hasBridge(profilePatch)) { @@ -543,7 +383,7 @@ async function install(opts) { } } } else { - await writePatch(webPatch, packageInsert()); + await writePatch(webPatch, packageInsert(pluginName)); } if (fs.existsSync(homePatch)) { const homeRaw = await fsp.readFile(homePatch, "utf8"); @@ -558,7 +398,7 @@ async function install(opts) { } await fsp.mkdir(dshHome, { recursive: true }); - await writePatch(homePatch, fileUriInsert(toFileUri(indexFile))); + await writePatch(homePatch, fileUriInsert(pathToFileURL(indexFile).href)); const migrated = await removeLegacyManagedPlugin(opts.legacyPluginHome, dest); console.log(`DSH web profile 还不存在,已写入 ${homePatch}`); console.log(copied ? `插件已安装到 ${dest}` : `已复用已安装的插件 ${dest}`); @@ -625,7 +465,12 @@ export async function runCli(argv = process.argv.slice(2)) { console.log(version); return { version }; } - const dshHome = argValue(argv, "--dsh-home") || defaultDshHome(); + const selectedHome = argValue(argv, "--dsh-home") || defaultDshHome(); + // A relocated DSH home defines the installation boundary. Guard its child paths separately. + const dshHome = await fsp.realpath(selectedHome).catch(error => { + if (error.code === "ENOENT") return selectedHome; + throw error; + }); const requestedPluginHome = argValue(argv, "--plugin-home"); const pluginHome = requestedPluginHome || defaultPluginHome(dshHome); const opts = { diff --git a/integrations/deepseek-harness/package.json b/integrations/deepseek-harness/package.json index e6b5e65..93ed5a3 100644 --- a/integrations/deepseek-harness/package.json +++ b/integrations/deepseek-harness/package.json @@ -29,6 +29,7 @@ "host-apply.mjs", "ui-host.mjs", "cli.js", + "profile-patch.mjs", "bin/beauticode-dsh", "cordis.patch.yml", "vendor", diff --git a/integrations/deepseek-harness/profile-patch.mjs b/integrations/deepseek-harness/profile-patch.mjs new file mode 100644 index 0000000..5397d85 --- /dev/null +++ b/integrations/deepseek-harness/profile-patch.mjs @@ -0,0 +1,165 @@ +import fs from "node:fs"; +import fsp from "node:fs/promises"; +import path from "node:path"; + +const bridgeId = "beauticode-bridge"; + +function fileUriInsert(uri) { + return [ + "# beauticode-bridge (installer)", + "- insert:", + " - id: beauticode-bridge", + ` name: '${uri}'`, + " inject: [webServer]", + "", + ].join("\n"); +} + +function packageInsert(pluginName) { + return [ + "# beauticode-bridge (installer)", + "- insert:", + " - id: beauticode-bridge", + ` name: '${pluginName}'`, + " inject: [webServer]", + "", + ].join("\n"); +} + +function hasBridge(text) { + return new RegExp(`^[ \\t]*-[ \\t]*id:[ \\t]*${bridgeId}[ \\t]*(?:#.*)?\\r?$`, "m").test(text); +} + +function bridgeCount(text) { + return (String(text).match(new RegExp(`^[ \\t]*-[ \\t]*id:[ \\t]*${bridgeId}[ \\t]*(?:#.*)?\\r?$`, "gm")) || []).length; +} + +async function backupPatch(filePath) { + const base = `${filePath}.beauticode-backup-${Date.now()}`; + let backup = base; + let suffix = 0; + while (fs.existsSync(backup)) backup = `${base}-${++suffix}`; + await fsp.copyFile(filePath, backup, fs.constants.COPYFILE_EXCL); + return backup; +} + +function stripBridge(text) { + const lines = text.split(/\r?\n/); + const removed = new Array(lines.length).fill(false); + const indentOf = (line) => line.match(/^[ \t]*/)?.[0].length ?? 0; + + for (let i = 0; i < lines.length; i += 1) { + const insert = lines[i].match(/^([ \t]*)-\s*insert:\s*(?:#.*)?$/); + if (!insert) continue; + const insertIndent = insert[1].length; + let blockEnd = i + 1; + while (blockEnd < lines.length) { + const line = lines[blockEnd]; + if (line.trim() && indentOf(line) <= insertIndent) break; + blockEnd += 1; + } + + let foundBridge = false; + for (let j = i + 1; j < blockEnd; ) { + const bridge = lines[j].match( + /^([ \t]*)-\s*id:\s*beauticode-bridge\s*(?:#.*)?$/, + ); + if (!bridge || bridge[1].length <= insertIndent) { + j += 1; + continue; + } + foundBridge = true; + const itemIndent = bridge[1].length; + let itemEnd = j + 1; + while (itemEnd < blockEnd) { + const line = lines[itemEnd]; + if (line.trim() && indentOf(line) <= itemIndent) break; + itemEnd += 1; + } + for (let k = j; k < itemEnd; k += 1) removed[k] = true; + j = itemEnd; + } + + if (!foundBridge) continue; + const marker = `${insert[1]}# beauticode-bridge (installer)`; + if (i > 0 && lines[i - 1].trimEnd() === marker) removed[i - 1] = true; + const hasSibling = lines + .slice(i + 1, blockEnd) + .some( + (line, offset) => + !removed[i + 1 + offset] && + line.trim() !== "" && + !line.trimStart().startsWith("#"), + ); + if (!hasSibling) { + for (let k = i; k < blockEnd; k += 1) removed[k] = true; + } + i = blockEnd - 1; + } + + return lines.filter((_, index) => !removed[index]).join("\n"); +} + +function overlayPayload(text) { + return text + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith("#")) + .join("\n"); +} + +function isEmptyOverlay(text) { + const payload = overlayPayload(text); + return payload === "" || payload === "[]"; +} + +// DSH seeds overlays as `# comment\n[]`. `[]` is already a complete YAML +// document, so appending `- insert:` makes js-yaml throw. +function keptOverlay(text) { + const withoutFlowEmpty = text + .split(/\r?\n/) + .filter((line) => line.trim() !== "[]") + .join("\n"); + if (isEmptyOverlay(withoutFlowEmpty)) return ""; + return withoutFlowEmpty.trim(); +} + +function withTrailingNewline(text) { + return text.endsWith("\n") ? text : `${text}\n`; +} + +async function writePatch(filePath, body) { + await fsp.mkdir(path.dirname(filePath), { recursive: true }); + const insert = withTrailingNewline(body); + if (!fs.existsSync(filePath)) { + await fsp.writeFile(filePath, insert, "utf8"); + return; + } + const raw = await fsp.readFile(filePath, "utf8"); + if (hasBridge(raw) && bridgeCount(raw) > 1) { + await backupPatch(filePath); + } + const remainder = hasBridge(raw) ? stripBridge(raw) : raw; + const kept = keptOverlay(remainder); + const next = kept ? `${kept}\n\n${insert}` : insert; + await fsp.writeFile(filePath, withTrailingNewline(next), "utf8"); +} + +async function removePatch(filePath) { + if (!fs.existsSync(filePath)) return false; + const raw = await fsp.readFile(filePath, "utf8"); + if (!hasBridge(raw)) return false; + const kept = keptOverlay(stripBridge(raw)); + if (!kept) { + await fsp.writeFile( + filePath, + "# Your patch layer for this dsh profile.\n[]\n", + "utf8", + ); + return true; + } + await fsp.writeFile(filePath, withTrailingNewline(kept), "utf8"); + return true; +} + +export { backupPatch, fileUriInsert, hasBridge, packageInsert, removePatch, writePatch }; diff --git a/integrations/deepseek-harness/test/pack.test.mjs b/integrations/deepseek-harness/test/pack.test.mjs index 5cda5bd..67a2d67 100644 --- a/integrations/deepseek-harness/test/pack.test.mjs +++ b/integrations/deepseek-harness/test/pack.test.mjs @@ -87,9 +87,8 @@ test("installer backs up and deduplicates its own duplicate loader entries", asy ].join("\n"), "utf8"); await runCli(["--dsh-home", dshHome, "--plugin-home", pluginHome]); const patch = await fs.readFile(path.join(web, "cordis.patch.yml"), "utf8"); - // The plugin package carries the canonical loader. The profile must not - // retain a second managed loader, but unrelated profile entries survive. - assert.equal((patch.match(/id:\s*beauticode-bridge/g) || []).length, 0); + // This profile has no beautiCode bundle, so one usable overlay survives. + assert.equal((patch.match(/id:\s*beauticode-bridge/g) || []).length, 1); assert.match(patch, /id:\s*unrelated-plugin/); const pluginPatch = await fs.readFile(path.join(pluginHome, "cordis.patch.yml"), "utf8"); assert.equal((pluginPatch.match(/id:\s*beauticode-bridge/g) || []).length, 1); @@ -100,6 +99,26 @@ test("installer backs up and deduplicates its own duplicate loader entries", asy } }); +test("installer follows the selected DSH home junction and reuses its existing plugin link", async t => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "bc-dsh-relocated-home-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const home = path.join(root, "dsh"); + const alias = path.join(root, ".dsh"); + const plugin = path.join(home, "plugins", "beauticode-dsh"); + const profile = path.join(home, "profiles", "web"); + const link = path.join(profile, "node_modules", "beauticode-dsh"); + const type = process.platform === "win32" ? "junction" : "dir"; + await fs.mkdir(path.dirname(link), { recursive: true }); + await fs.symlink(home, alias, type); + await fs.writeFile(path.join(profile, "package.json"), JSON.stringify({ dependencies: {} })); + await runCli(["--dsh-home", home]); + await fs.unlink(link); + await fs.symlink(path.join(alias, "plugins", "beauticode-dsh"), link, type); + const result = await runCli(["--dsh-home", alias]); + assert.equal(await fs.realpath(result.dest), await fs.realpath(plugin)); + assert.equal(await fs.realpath(link), await fs.realpath(plugin)); +}); + test("installer refuses to overwrite or remove an unrelated plugin-home directory", async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "bc-dsh-plugin-home-guard-")); try { diff --git a/packages/adapter-desktop-cdp/src/cdp.ts b/packages/adapter-desktop-cdp/src/cdp.ts index b5d3798..4c545b4 100644 --- a/packages/adapter-desktop-cdp/src/cdp.ts +++ b/packages/adapter-desktop-cdp/src/cdp.ts @@ -83,7 +83,10 @@ export function isDesktopTarget( ): boolean { if (target.type !== "page") return false; const identity = spec.targetIdentity; - if (!identity) return target.url === spec.targetUrl; + if (!identity) { + const route = spec.targetUrl.replace(/\/$/, ""); + return target.url === route || target.url === route + "/"; + } let parsed: URL; try { parsed = new URL(target.url); diff --git a/packages/adapter-doubao/src/spec.ts b/packages/adapter-doubao/src/spec.ts index 2be83c6..b4a9d82 100644 --- a/packages/adapter-doubao/src/spec.ts +++ b/packages/adapter-doubao/src/spec.ts @@ -16,6 +16,9 @@ export function doubaoExecutableCandidates(options: CandidateOptions = {}): stri const exists = options.exists || fs.existsSync; const realpath = options.realpath || fs.realpathSync.native; const values = [ + env.LOCALAPPDATA + ? path.join(env.LOCALAPPDATA, "Doubao", "Application", "Doubao.exe") + : "", env.LOCALAPPDATA ? path.join(env.LOCALAPPDATA, "Doubao", "Doubao.exe") : "", diff --git a/packages/adapter-doubao/test/contract.test.js b/packages/adapter-doubao/test/contract.test.js index bccf6ec..422cb11 100644 --- a/packages/adapter-doubao/test/contract.test.js +++ b/packages/adapter-doubao/test/contract.test.js @@ -6,7 +6,7 @@ import { DOUBAO_HOST_DESCRIPTOR, buildDoubaoBackgroundInjection, } from '../dist/index.js'; -import { DesktopStartupRepairController, selectDesktopMainProcesses } from '@beauticode/adapter-desktop-cdp'; +import { DesktopStartupRepairController, pickDesktopTarget, selectDesktopMainProcesses } from '@beauticode/adapter-desktop-cdp'; const customPath = 'D:\\Custom Apps\\豆包\\Doubao.exe'; const candidateOptions = { @@ -54,6 +54,13 @@ test('Doubao canonicalizes recorded paths and deduplicates Windows case aliases' assert.ok(!values.includes(customPath)); }); +test('Doubao recognizes the current per-user Application install layout', () => { + const candidate = 'C:\\Users\\test\\AppData\\Local\\Doubao\\Application\\Doubao.exe'; + const executableCandidates = doubaoModule.doubaoExecutableCandidates({ ...candidateOptions, readRecord: () => null }); + const rows = [{ pid: 17, name: 'Doubao.exe', exe: candidate, cmd: candidate, created: 1000 }]; + assert.deepEqual(selectDesktopMainProcesses({ ...DOUBAO_CDP_SPEC, executableCandidates }, rows, 'win32').map(row => row.pid), [17]); +}); + test('Doubao uses the measured chat target and direct More successor', () => { assert.equal(DOUBAO_HOST_DESCRIPTOR.kind, 'doubao'); assert.equal(DOUBAO_HOST_DESCRIPTOR.capabilities.video, true); @@ -81,6 +88,20 @@ test('Doubao uses the measured chat target and direct More successor', () => { assert.match(source, /MutationObserver/); }); +test('Doubao recognizes both chat route spellings and ignores non-chat targets', () => { + const overlay = { id: 'overlay', type: 'page', url: 'doubao://doubao-chat/search/' }; + const frame = { id: 'frame', type: 'iframe', url: 'doubao://doubao-chat/chat/' }; + const foreign = { id: 'foreign', type: 'page', url: 'doubao://doubao-work/chat/' }; + const nested = { id: 'nested', type: 'page', url: 'doubao://doubao-chat/chat/settings' }; + const query = { id: 'query', type: 'page', url: 'doubao://doubao-chat/chat/?other=yes' }; + const primary = { id: 'main', type: 'page', url: 'doubao://doubao-chat/chat/' }; + const targets = [overlay, frame, foreign, nested, query]; + assert.equal(pickDesktopTarget(DOUBAO_CDP_SPEC, targets), null); + assert.equal(pickDesktopTarget(DOUBAO_CDP_SPEC, [...targets, primary]), primary); + const earlier = { ...primary, url: 'doubao://doubao-chat/chat' }; + assert.equal(pickDesktopTarget(DOUBAO_CDP_SPEC, [earlier]), earlier); +}); + test('a new Doubao PID and creation time remain repairable after a verified session', async () => { let now = 1_000; let repairs = 0; diff --git a/packages/adapter-dsh/test/launcher-scripts.test.js b/packages/adapter-dsh/test/launcher-scripts.test.js index c5408a3..20d6c32 100644 --- a/packages/adapter-dsh/test/launcher-scripts.test.js +++ b/packages/adapter-dsh/test/launcher-scripts.test.js @@ -176,6 +176,7 @@ test("picker and tray never spawn a DSH process", () => { assert.doesNotMatch(source, /install-dsh-runtime/, `${name} must not install DSH`); } assert.match(installer, /agent\.mjs/); + assert.match(installer, /readability\.js/); assert.match(installer, /control-client\.mjs/); assert.match(installer, /host-apply\.mjs/); assert.match(installer, /integration-note\.zh\.txt/); @@ -267,7 +268,7 @@ test("install-dsh-plugin wires a missing DSH home and can uninstall", requiresWi ); assert.equal(migrate.status, 0, migrate.stderr || migrate.stdout); const webPatch = fs.readFileSync(path.join(web, "cordis.patch.yml"), "utf8"); - assert.doesNotMatch(webPatch, /id:\s*beauticode-bridge/); + assert.match(webPatch, /id:\s*beauticode-bridge/); assert.doesNotMatch(webPatch, /@beauticode\/dsh-plugin/); assert.match(fs.readFileSync(path.join(pluginRoot, "cordis.patch.yml"), "utf8"), /id:\s*beauticode-bridge/); assert.equal(fs.existsSync(path.join(home, "cordis.patch.yml")), false); @@ -466,8 +467,21 @@ test("install-dsh-plugin deduplicates a loader already shipped by the plugin", r assert.equal(result.status, 0, result.stderr || result.stdout); const webPatch = fs.readFileSync(path.join(web, "cordis.patch.yml"), "utf8"); assert.match(webPatch, /id: user-loader/); - assert.doesNotMatch(webPatch, /id: beauticode-bridge/); - const backups = fs.readdirSync(web).filter((name) => name.startsWith("cordis.patch.yml.beauticode-backup-")); + assert.match(webPatch, /id: beauticode-bridge/); + const manifest = path.join(web, "package.json"); + const configured = JSON.parse(fs.readFileSync(manifest, "utf8")); + configured.dsh = { profile: { bundles: ["@deepseek-ai/dsh-base", "beauticode-dsh"] } }; + fs.writeFileSync(manifest, JSON.stringify(configured)); + const backupPrefix = "cordis.patch.yml.beauticode-backup-"; + const priorBackups = fs.readdirSync(web).filter((name) => name.startsWith(backupPrefix)); + const repair = spawnSync( + powerShellExecutable, + ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, "-PluginRoot", pluginRoot, "-DshHome", home], + { encoding: "utf8", windowsHide: true }, + ); + assert.equal(repair.status, 0, repair.stderr || repair.stdout); + assert.doesNotMatch(fs.readFileSync(path.join(web, "cordis.patch.yml"), "utf8"), /id: beauticode-bridge/); + const backups = fs.readdirSync(web).filter((name) => name.startsWith(backupPrefix) && !priorBackups.includes(name)); assert.equal(backups.length, 1); assert.match(fs.readFileSync(path.join(web, backups[0]), "utf8"), /id: beauticode-bridge/); assert.match(fs.readFileSync(path.join(pluginRoot, "cordis.patch.yml"), "utf8"), /id: beauticode-bridge/); diff --git a/packages/adapter-workbuddy/src/launch.ts b/packages/adapter-workbuddy/src/launch.ts index 3d78727..8b7c30d 100644 --- a/packages/adapter-workbuddy/src/launch.ts +++ b/packages/adapter-workbuddy/src/launch.ts @@ -4,32 +4,23 @@ import net from "node:net"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; -import { listLinuxProcesses, selectLinuxMainProcesses } from "@beauticode/core"; import { DEFAULT_WORKBUDDY_CDP_PORT, DEFAULT_WORKBUDDY_CDP_PORTS, WORKBUDDY_CDP_ENV_KEY, discoverWorkBuddyCdp, - parseRemoteDebuggingFlags, probeCdpPort, probeWorkBuddyCdp, type DiscoveredWorkBuddyCdp, } from "./discovery.js"; +import { listWorkBuddyProcesses, type WorkBuddyProcess } from "./process-discovery.js"; +export { isWorkBuddyMainProcess, listWorkBuddyProcesses, parsePsElapsedSeconds, type WorkBuddyProcess } from "./process-discovery.js"; + const execFileAsync = promisify(execFile); export const DEFAULT_WORKBUDDY_REPAIR_WINDOW_MS = 10_000; -export interface WorkBuddyProcess { - pid: number; - name: string; - executablePath: string; - commandLine: string; - port: number | null; - /** Main-process creation time. Null means it is unsafe to auto-restart. */ - createdAtMs: number | null; -} - export type WorkBuddyStartupProcessDecision = | "repair-now" | "wait-for-cdp" @@ -71,47 +62,6 @@ export interface EnsuredWorkBuddyCdp extends DiscoveredWorkBuddyCdp { restarted: boolean; } -function executableFromCommandLine(commandLine: string): string { - const quoted = commandLine.match(/^\s*["']([^"']+)["']/); - return quoted?.[1] ?? commandLine.trim().split(/\s+/)[0] ?? ""; -} - -export function isWorkBuddyMainProcess( - commandLine: string, - name: string, - exePath = "", - platform: NodeJS.Platform = process.platform, -): boolean { - if (/\s--type=/.test(commandLine)) return false; - const executable = exePath || executableFromCommandLine(commandLine); - if (!executable) return false; - if (platform === "win32") { - return ( - name.toLowerCase() === "workbuddy.exe" && - path.win32.basename(executable).toLowerCase() === "workbuddy.exe" - ); - } - if (platform === "darwin") { - return /\/WorkBuddy\.app\/Contents\/MacOS\/(?:Electron|WorkBuddy)$/i.test( - executable, - ); - } - return path.basename(executable).toLowerCase() === "workbuddy"; -} - -export function parsePsElapsedSeconds(value: string): number | null { - const match = /^(?:(\d+)-)?(?:(\d{1,2}):)?(\d{1,2}):(\d{2})$/.exec( - value.trim(), - ); - if (!match) return null; - const days = Number(match[1] ?? 0); - const hours = Number(match[2] ?? 0); - const minutes = Number(match[3]); - const seconds = Number(match[4]); - if (hours > 23 || minutes > 59 || seconds > 59) return null; - return days * 86_400 + hours * 3_600 + minutes * 60 + seconds; -} - export function workBuddyInstallCandidates( env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, @@ -196,168 +146,6 @@ export async function pickAvailableLoopbackPort( }); } -async function scanWindowsWorkBuddyProcesses(): Promise { - const script = [ - "$ErrorActionPreference='SilentlyContinue';", - "Get-CimInstance Win32_Process | ForEach-Object {", - "$cmd=$_.CommandLine;", - "if(-not $cmd){return};", - "if($cmd -match '\\s--type='){return};", - "if($_.Name -ine 'WorkBuddy.exe'){return};", - "$created=0;", - "try{$created=([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()}catch{};", - "$o=@{pid=$_.ProcessId;name=$_.Name;exe=$_.ExecutablePath;cmd=$cmd;created=$created};", - "($o | ConvertTo-Json -Compress -Depth 3)", - "}", - ].join(" "); - try { - const { stdout } = await execFileAsync( - "powershell.exe", - [ - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Bypass", - "-Command", - script, - ], - { windowsHide: true, timeout: 12_000, maxBuffer: 4 * 1024 * 1024 }, - ); - const found: WorkBuddyProcess[] = []; - for (const line of String(stdout ?? "").split(/\r?\n/)) { - const trimmed = line.trim(); - if (!trimmed.startsWith("{")) continue; - let row: { - pid?: unknown; - name?: unknown; - exe?: unknown; - cmd?: unknown; - created?: unknown; - }; - try { - row = JSON.parse(trimmed) as typeof row; - } catch { - continue; - } - const commandLine = typeof row.cmd === "string" ? row.cmd : ""; - const name = typeof row.name === "string" ? row.name : "unknown"; - const executablePath = typeof row.exe === "string" ? row.exe : ""; - if (!isWorkBuddyMainProcess(commandLine, name, executablePath, "win32")) { - continue; - } - const flags = parseRemoteDebuggingFlags(commandLine); - found.push({ - pid: Number(row.pid) || 0, - name, - executablePath, - commandLine, - port: flags.safe ? flags.port : null, - createdAtMs: - Number.isFinite(Number(row.created)) && Number(row.created) > 0 - ? Number(row.created) - : null, - }); - } - return found; - } catch { - return []; - } -} - -async function scanUnixWorkBuddyProcesses(): Promise { - try { - const elapsedField = process.platform === "darwin" ? "etime=" : "etimes="; - const { stdout } = await execFileAsync("ps", [ - "-axo", - `pid=,${elapsedField},command=`, - ], { - timeout: 5_000, - maxBuffer: 4 * 1024 * 1024, - }); - const found: WorkBuddyProcess[] = []; - for (const line of String(stdout ?? "").split(/\n/)) { - const match = /^\s*(\d+)\s+(\S+)\s+(\S.*)$/.exec(line); - if (!match) continue; - const commandLine = match[3] ?? ""; - const executablePath = executableFromCommandLine(commandLine); - const processName = path.basename(executablePath); - if ( - !isWorkBuddyMainProcess( - commandLine, - processName, - executablePath, - process.platform, - ) - ) { - continue; - } - const flags = parseRemoteDebuggingFlags(commandLine); - const elapsedSeconds = - process.platform === "darwin" - ? parsePsElapsedSeconds(match[2] ?? "") - : Number(match[2]); - found.push({ - pid: Number(match[1]) || 0, - name: "WorkBuddy", - executablePath, - commandLine, - port: flags.safe ? flags.port : null, - createdAtMs: elapsedSeconds != null && Number.isFinite(elapsedSeconds) - ? Date.now() - elapsedSeconds * 1_000 - : null, - }); - } - return found; - } catch { - return []; - } -} - -/** - * Linux reads /proc so ELECTRON_RUN_AS_NODE workers (`workbuddy `, - * same binary, no --type) are excluded by parent image instead of counting - * as extra main processes. - */ -function scanLinuxWorkBuddyProcesses(): WorkBuddyProcess[] { - const rows = listLinuxProcesses((row) => path.posix.basename(row.executablePath).toLowerCase() === "workbuddy"); - return selectLinuxMainProcesses(rows, (row) => - isWorkBuddyMainProcess(row.commandLine, row.name, row.executablePath, "linux"), - ).map((row) => { - const flags = parseRemoteDebuggingFlags(row.commandLine); - // WorkBuddy enables CDP from its environment, not argv. A same-user - // /proc//environ read tells a CDP launch apart from a blind one, so a - // just-started CDP process is never mistaken for a repair candidate. - const envPort = linuxProcessEnvPort(row.pid); - return { - pid: row.pid, - name: "WorkBuddy", - executablePath: row.executablePath, - commandLine: row.commandLine, - port: flags.safe && flags.port != null ? flags.port : envPort, - createdAtMs: row.createdAtMs, - }; - }); -} - -function linuxProcessEnvPort(pid: number): number | null { - try { - const prefix = `${WORKBUDDY_CDP_ENV_KEY}=`; - const entry = fs.readFileSync(`/proc/${pid}/environ`, "utf8") - .split("\0") - .find((value) => value.startsWith(prefix)); - const port = Number(entry?.slice(prefix.length)); - return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null; - } catch { - return null; - } -} - -export async function listWorkBuddyProcesses(): Promise { - if (process.platform === "win32") return scanWindowsWorkBuddyProcesses(); - if (process.platform === "linux") return scanLinuxWorkBuddyProcesses(); - return scanUnixWorkBuddyProcesses(); -} - export async function stopWorkBuddyProcesses( procs: readonly WorkBuddyProcess[], ): Promise { diff --git a/packages/adapter-workbuddy/src/process-discovery.ts b/packages/adapter-workbuddy/src/process-discovery.ts new file mode 100644 index 0000000..1f47b2a --- /dev/null +++ b/packages/adapter-workbuddy/src/process-discovery.ts @@ -0,0 +1,225 @@ +import { execFile } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { promisify } from "node:util"; +import { listLinuxProcesses, selectLinuxMainProcesses } from "@beauticode/core"; +import { parseRemoteDebuggingFlags, WORKBUDDY_CDP_ENV_KEY } from "./discovery.js"; + +const execFileAsync = promisify(execFile); + +export interface WorkBuddyProcess { + pid: number; + name: string; + executablePath: string; + commandLine: string; + port: number | null; + /** Main-process creation time. Null means it is unsafe to auto-restart. */ + createdAtMs: number | null; +} + +function executableFromCommandLine(commandLine: string): string { + const quoted = commandLine.match(/^\s*["']([^"']+)["']/); + return quoted?.[1] ?? commandLine.trim().split(/\s+/)[0] ?? ""; +} + +export function isWorkBuddyMainProcess( + commandLine: string, + name: string, + exePath = "", + platform: NodeJS.Platform = process.platform, +): boolean { + if (/\s--type=/.test(commandLine)) return false; + const executable = exePath || executableFromCommandLine(commandLine); + if (!executable) return false; + if (platform === "win32") { + // WorkBuddy starts its stdio service and prewarm worker with the same + // executable as the desktop process, without Electron's --type flag. + const args = commandLine.match(/"[^"]*"|[^\s"]+/g)?.slice(1) ?? []; + if (args.some(arg => /^--(?:stdio|prewarm-id)(?:=|$)/.test(arg))) return false; + return ( + name.toLowerCase() === "workbuddy.exe" && + path.win32.basename(executable).toLowerCase() === "workbuddy.exe" + ); + } + if (platform === "darwin") { + return /\/WorkBuddy\.app\/Contents\/MacOS\/(?:Electron|WorkBuddy)$/i.test( + executable, + ); + } + return path.basename(executable).toLowerCase() === "workbuddy"; +} + +export function parsePsElapsedSeconds(value: string): number | null { + const match = /^(?:(\d+)-)?(?:(\d{1,2}):)?(\d{1,2}):(\d{2})$/.exec( + value.trim(), + ); + if (!match) return null; + const days = Number(match[1] ?? 0); + const hours = Number(match[2] ?? 0); + const minutes = Number(match[3]); + const seconds = Number(match[4]); + if (hours > 23 || minutes > 59 || seconds > 59) return null; + return days * 86_400 + hours * 3_600 + minutes * 60 + seconds; +} + +async function scanWindowsWorkBuddyProcesses(): Promise { + const script = [ + "$ErrorActionPreference='SilentlyContinue';", + "Get-CimInstance Win32_Process | ForEach-Object {", + "$cmd=$_.CommandLine;", + "if(-not $cmd){return};", + "if($cmd -match '\\s--type='){return};", + "if($_.Name -ine 'WorkBuddy.exe'){return};", + "$created=0;", + "try{$created=([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()}catch{};", + "$o=@{pid=$_.ProcessId;name=$_.Name;exe=$_.ExecutablePath;cmd=$cmd;created=$created};", + "($o | ConvertTo-Json -Compress -Depth 3)", + "}", + ].join(" "); + try { + const { stdout } = await execFileAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-Command", + script, + ], + { windowsHide: true, timeout: 12_000, maxBuffer: 4 * 1024 * 1024 }, + ); + const found: WorkBuddyProcess[] = []; + for (const line of String(stdout ?? "").split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed.startsWith("{")) continue; + let row: { + pid?: unknown; + name?: unknown; + exe?: unknown; + cmd?: unknown; + created?: unknown; + }; + try { + row = JSON.parse(trimmed) as typeof row; + } catch { + continue; + } + const commandLine = typeof row.cmd === "string" ? row.cmd : ""; + const name = typeof row.name === "string" ? row.name : "unknown"; + const executablePath = typeof row.exe === "string" ? row.exe : ""; + if (!isWorkBuddyMainProcess(commandLine, name, executablePath, "win32")) { + continue; + } + const flags = parseRemoteDebuggingFlags(commandLine); + found.push({ + pid: Number(row.pid) || 0, + name, + executablePath, + commandLine, + port: flags.safe ? flags.port : null, + createdAtMs: + Number.isFinite(Number(row.created)) && Number(row.created) > 0 + ? Number(row.created) + : null, + }); + } + return found; + } catch { + return []; + } +} + +async function scanUnixWorkBuddyProcesses(): Promise { + try { + const elapsedField = process.platform === "darwin" ? "etime=" : "etimes="; + const { stdout } = await execFileAsync("ps", [ + "-axo", + `pid=,${elapsedField},command=`, + ], { + timeout: 5_000, + maxBuffer: 4 * 1024 * 1024, + }); + const found: WorkBuddyProcess[] = []; + for (const line of String(stdout ?? "").split(/\n/)) { + const match = /^\s*(\d+)\s+(\S+)\s+(\S.*)$/.exec(line); + if (!match) continue; + const commandLine = match[3] ?? ""; + const executablePath = executableFromCommandLine(commandLine); + const processName = path.basename(executablePath); + if ( + !isWorkBuddyMainProcess( + commandLine, + processName, + executablePath, + process.platform, + ) + ) { + continue; + } + const flags = parseRemoteDebuggingFlags(commandLine); + const elapsedSeconds = + process.platform === "darwin" + ? parsePsElapsedSeconds(match[2] ?? "") + : Number(match[2]); + found.push({ + pid: Number(match[1]) || 0, + name: "WorkBuddy", + executablePath, + commandLine, + port: flags.safe ? flags.port : null, + createdAtMs: elapsedSeconds != null && Number.isFinite(elapsedSeconds) + ? Date.now() - elapsedSeconds * 1_000 + : null, + }); + } + return found; + } catch { + return []; + } +} + +/** + * Linux reads /proc so ELECTRON_RUN_AS_NODE workers (`workbuddy `, + * same binary, no --type) are excluded by parent image instead of counting + * as extra main processes. + */ +function scanLinuxWorkBuddyProcesses(): WorkBuddyProcess[] { + const rows = listLinuxProcesses((row) => path.posix.basename(row.executablePath).toLowerCase() === "workbuddy"); + return selectLinuxMainProcesses(rows, (row) => + isWorkBuddyMainProcess(row.commandLine, row.name, row.executablePath, "linux"), + ).map((row) => { + const flags = parseRemoteDebuggingFlags(row.commandLine); + // WorkBuddy enables CDP from its environment, not argv. A same-user + // /proc//environ read tells a CDP launch apart from a blind one, so a + // just-started CDP process is never mistaken for a repair candidate. + const envPort = linuxProcessEnvPort(row.pid); + return { + pid: row.pid, + name: "WorkBuddy", + executablePath: row.executablePath, + commandLine: row.commandLine, + port: flags.safe && flags.port != null ? flags.port : envPort, + createdAtMs: row.createdAtMs, + }; + }); +} + +function linuxProcessEnvPort(pid: number): number | null { + try { + const prefix = `${WORKBUDDY_CDP_ENV_KEY}=`; + const entry = fs.readFileSync(`/proc/${pid}/environ`, "utf8") + .split("\0") + .find((value) => value.startsWith(prefix)); + const port = Number(entry?.slice(prefix.length)); + return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null; + } catch { + return null; + } +} + +export async function listWorkBuddyProcesses(): Promise { + if (process.platform === "win32") return scanWindowsWorkBuddyProcesses(); + if (process.platform === "linux") return scanLinuxWorkBuddyProcesses(); + return scanUnixWorkBuddyProcesses(); +} diff --git a/packages/adapter-workbuddy/test/discovery.test.js b/packages/adapter-workbuddy/test/discovery.test.js index b32d91b..01d1704 100644 --- a/packages/adapter-workbuddy/test/discovery.test.js +++ b/packages/adapter-workbuddy/test/discovery.test.js @@ -104,6 +104,14 @@ test("WorkBuddy process matching rejects command lines that only mention its nam ); }); +test("Windows WorkBuddy counts its desktop process without stdio and prewarm helpers", () => { + const executable = "E:\\WorkBuddy\\WorkBuddy.exe"; + const isMain = args => isWorkBuddyMainProcess(`"${executable}" ${args}`, "WorkBuddy.exe", executable, "win32"); + assert.equal(isMain("--disable-warning --stdio"), false); + assert.equal(isMain("--optimize-for-size --prewarm --prewarm-id=a"), false); + assert.equal(isMain('"E:\\Projects\\test --stdio flag" --user-data-dir=profile'), true); +}); + test("macOS ps elapsed time is parsed without Linux etimes", () => { assert.equal(parsePsElapsedSeconds("00:09"), 9); assert.equal(parsePsElapsedSeconds("00:00:09"), 9); diff --git a/packages/beauticode-desktop/src/dsh-installation.mjs b/packages/beauticode-desktop/src/dsh-installation.mjs index cab32f8..a242530 100644 --- a/packages/beauticode-desktop/src/dsh-installation.mjs +++ b/packages/beauticode-desktop/src/dsh-installation.mjs @@ -11,14 +11,16 @@ export function inspectDshInstallation({ home, env, exists = fs.existsSync, read try { profilePatch = readFile(path.join(profile, 'cordis.patch.yml'), 'utf8'); } catch (error) { if (error.code !== 'ENOENT') continue; } const patches = [profilePatch]; - // The installer removes a duplicate profile bridge when the linked package - // ships its own patch. Require the actual dependency and matching link target. + // A dependency exposes its files to the loader. The profile's bundle list + // determines whether the dependency's patch is part of the composition. if (!/\bbeauticode-bridge\b/.test(profilePatch)) { try { const manifest = JSON.parse(readFile(path.join(profile, 'package.json'), 'utf8')); const dependency = manifest.dependencies?.['beauticode-dsh']; + const bundles = manifest.dsh?.profile?.bundles; const plugin = path.join(profile, 'node_modules', 'beauticode-dsh'); - if (typeof dependency === 'string' && dependency.startsWith('link:') && dependency.length > 5) { + if (Array.isArray(bundles) && bundles.includes('beauticode-dsh') && + typeof dependency === 'string' && dependency.startsWith('link:') && dependency.length > 5) { const target = path.resolve(profile, dependency.slice(5)); if (fs.realpathSync.native(plugin) === fs.realpathSync.native(target)) { patches.push(readFile(path.join(plugin, 'cordis.patch.yml'), 'utf8')); diff --git a/packages/beauticode-desktop/src/host-executables.mjs b/packages/beauticode-desktop/src/host-executables.mjs new file mode 100644 index 0000000..b510722 --- /dev/null +++ b/packages/beauticode-desktop/src/host-executables.mjs @@ -0,0 +1,66 @@ +import path from "node:path"; + +function xdgDir(env, key, home, fallback) { + const value = env[key]; + return value && path.isAbsolute(value) ? value : path.join(home, ...fallback); +} + +function windowsExecutableCandidates(host, env, home) { + const local = env.LOCALAPPDATA || path.join(home, "AppData", "Local"); + const programFiles = env.ProgramFiles || "C:\\Program Files"; + const programFilesX86 = env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"; + if (host === "codex") return [ + path.join(local, "Programs", "ChatGPT", "ChatGPT.exe"), + path.join(local, "Programs", "chatgpt", "ChatGPT.exe"), + path.join(local, "Programs", "Codex", "Codex.exe"), + path.join(local, "Programs", "codex", "Codex.exe"), + path.join(local, "OpenAI", "Codex", "Codex.exe"), + path.join(local, "OpenAI", "ChatGPT", "ChatGPT.exe"), + path.join(local, "Codex", "app", "Codex.exe"), + path.join(programFiles, "Codex", "Codex.exe"), + path.join(programFiles, "ChatGPT", "ChatGPT.exe"), + path.join(programFilesX86, "ChatGPT", "ChatGPT.exe"), + ]; + if (host === "workbuddy") return [ + path.join(local, "Programs", "WorkBuddy", "WorkBuddy.exe"), + path.join(local, "WorkBuddy", "WorkBuddy.exe"), + path.join(programFiles, "WorkBuddy", "WorkBuddy.exe"), + path.join(programFilesX86, "WorkBuddy", "WorkBuddy.exe"), + ]; + if (host === "cursor") return [ + path.join(local, "Programs", "cursor", "Cursor.exe"), + path.join(programFiles, "Cursor", "Cursor.exe"), + path.join(programFilesX86, "Cursor", "Cursor.exe"), + ]; + if (host === "doubao") return [ + // Pre-install detection runs before the desktop adapter is loaded. + path.join(local, "Doubao", "Application", "Doubao.exe"), + path.join(local, "Doubao", "Doubao.exe"), + path.join(local, "Programs", "Doubao", "Doubao.exe"), + path.join(programFiles, "Doubao", "Doubao.exe"), + "D:\\Doubao\\app\\Doubao.exe", + ]; + return []; +} + +/** Mirrors the adapters' Linux executable candidates (deb/rpm/opt and per-user installs). */ +function linuxExecutableCandidates(host, env, home) { + const data = xdgDir(env, "XDG_DATA_HOME", home, [".local", "share"]); + if (host === "codex") return [ + "/usr/lib/chatgpt/ChatGPT", "/opt/ChatGPT/ChatGPT", "/opt/chatgpt/ChatGPT", + "/usr/lib/codex/Codex", "/opt/Codex/Codex", + path.join(data, "chatgpt", "ChatGPT"), path.join(home, ".local", "opt", "ChatGPT", "ChatGPT"), + ]; + if (host === "workbuddy") return [ + "/opt/WorkBuddy/workbuddy", "/opt/workbuddy/workbuddy", "/usr/lib/workbuddy/workbuddy", + path.join(data, "WorkBuddy", "workbuddy"), + ]; + if (host === "cursor") return [ + ...(env.BEAUTICODE_CURSOR_EXECUTABLE ? [env.BEAUTICODE_CURSOR_EXECUTABLE] : []), + "/usr/share/cursor/cursor", "/opt/Cursor/cursor", "/opt/cursor/cursor", + path.join(data, "cursor", "cursor"), path.join(home, "Applications", "cursor", "cursor"), + ]; + return []; +} + +export { linuxExecutableCandidates, windowsExecutableCandidates, xdgDir }; diff --git a/packages/beauticode-desktop/src/index.mjs b/packages/beauticode-desktop/src/index.mjs index d47ee2f..a5b1069 100644 --- a/packages/beauticode-desktop/src/index.mjs +++ b/packages/beauticode-desktop/src/index.mjs @@ -1,6 +1,7 @@ import os from "node:os"; import path from "node:path"; import { inspectDshInstallation } from "./dsh-installation.mjs"; +import { linuxExecutableCandidates, windowsExecutableCandidates, xdgDir } from "./host-executables.mjs"; import { fileURLToPath } from "node:url"; import fs from "node:fs"; import { spawnSync } from "node:child_process"; @@ -16,11 +17,6 @@ const here = path.dirname(fileURLToPath(import.meta.url)); const SUPPORTED_PLATFORMS = Object.freeze(["win32", "linux"]); const LINUX_UNSUPPORTED_HOSTS = Object.freeze(["doubao"]); -function xdgDir(env, key, home, fallback) { - const value = env[key]; - return value && path.isAbsolute(value) ? value : path.join(home, ...fallback); -} - function canonicalStartupMarker(host, env, home) { const appData = env.APPDATA || path.join(home, "AppData", "Roaming"); return path.join(appData, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", `beauticode-${host}-runner.vbs`); @@ -41,6 +37,7 @@ export const HOST_RUNTIME = Object.freeze({ required: Object.freeze([ "dsh/index.mjs", "dsh/cli.js", + "dsh/profile-patch.mjs", "dsh/vendor/core/index.js", "dsh/vendor/core/skin-catalog.js", "dsh/vendor/adapter-dsh/index.js", @@ -213,62 +210,6 @@ export function statusText(status) { return JSON.stringify(status, null, 2); } -function windowsExecutableCandidates(host, env, home) { - const local = env.LOCALAPPDATA || path.join(home, "AppData", "Local"); - const programFiles = env.ProgramFiles || "C:\\Program Files"; - const programFilesX86 = env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"; - if (host === "codex") return [ - path.join(local, "Programs", "ChatGPT", "ChatGPT.exe"), - path.join(local, "Programs", "chatgpt", "ChatGPT.exe"), - path.join(local, "Programs", "Codex", "Codex.exe"), - path.join(local, "Programs", "codex", "Codex.exe"), - path.join(local, "OpenAI", "Codex", "Codex.exe"), - path.join(local, "OpenAI", "ChatGPT", "ChatGPT.exe"), - path.join(local, "Codex", "app", "Codex.exe"), - path.join(programFiles, "Codex", "Codex.exe"), - path.join(programFiles, "ChatGPT", "ChatGPT.exe"), - path.join(programFilesX86, "ChatGPT", "ChatGPT.exe"), - ]; - if (host === "workbuddy") return [ - path.join(local, "Programs", "WorkBuddy", "WorkBuddy.exe"), - path.join(local, "WorkBuddy", "WorkBuddy.exe"), - path.join(programFiles, "WorkBuddy", "WorkBuddy.exe"), - path.join(programFilesX86, "WorkBuddy", "WorkBuddy.exe"), - ]; - if (host === "cursor") return [ - path.join(local, "Programs", "cursor", "Cursor.exe"), - path.join(programFiles, "Cursor", "Cursor.exe"), - path.join(programFilesX86, "Cursor", "Cursor.exe"), - ]; - if (host === "doubao") return [ - path.join(local, "Doubao", "Doubao.exe"), - path.join(local, "Programs", "Doubao", "Doubao.exe"), - path.join(programFiles, "Doubao", "Doubao.exe"), - "D:\\Doubao\\app\\Doubao.exe", - ]; - return []; -} - -/** Mirrors the adapters' Linux executable candidates (deb/rpm/opt and per-user installs). */ -function linuxExecutableCandidates(host, env, home) { - const data = xdgDir(env, "XDG_DATA_HOME", home, [".local", "share"]); - if (host === "codex") return [ - "/usr/lib/chatgpt/ChatGPT", "/opt/ChatGPT/ChatGPT", "/opt/chatgpt/ChatGPT", - "/usr/lib/codex/Codex", "/opt/Codex/Codex", - path.join(data, "chatgpt", "ChatGPT"), path.join(home, ".local", "opt", "ChatGPT", "ChatGPT"), - ]; - if (host === "workbuddy") return [ - "/opt/WorkBuddy/workbuddy", "/opt/workbuddy/workbuddy", "/usr/lib/workbuddy/workbuddy", - path.join(data, "WorkBuddy", "workbuddy"), - ]; - if (host === "cursor") return [ - ...(env.BEAUTICODE_CURSOR_EXECUTABLE ? [env.BEAUTICODE_CURSOR_EXECUTABLE] : []), - "/usr/share/cursor/cursor", "/opt/Cursor/cursor", "/opt/cursor/cursor", - path.join(data, "cursor", "cursor"), path.join(home, "Applications", "cursor", "cursor"), - ]; - return []; -} - function commandOnPath(command, options) { const pathValue = options.env.PATH || options.env.Path || ""; if (options.platform === "linux") { diff --git a/packages/beauticode-desktop/test/all.test.mjs b/packages/beauticode-desktop/test/all.test.mjs index 0850e5a..b4749c7 100644 --- a/packages/beauticode-desktop/test/all.test.mjs +++ b/packages/beauticode-desktop/test/all.test.mjs @@ -40,6 +40,11 @@ function fakeOptions(hostFiles, spawnSync) { }; } +test("aggregate install discovers Doubao in its Application directory", () => { + const options = fakeOptions(["C:/Users/test/AppData/Local/Doubao/Application/Doubao.exe"], () => ({ status: 0 })); + assert.equal(detectHostAvailability("doubao", options).available, true); +}); + test("all install skips missing hosts and updates detected hosts without launching them", () => { const invocations = []; const options = fakeOptions([ diff --git a/packages/beauticode-desktop/test/dsh-installation.test.mjs b/packages/beauticode-desktop/test/dsh-installation.test.mjs index 2cf79ee..71ba451 100644 --- a/packages/beauticode-desktop/test/dsh-installation.test.mjs +++ b/packages/beauticode-desktop/test/dsh-installation.test.mjs @@ -44,6 +44,10 @@ test('DSH status follows the profile dependency to the bundled bridge patch', t const manifest = path.join(profile, 'package.json'); fs.writeFileSync(manifest, JSON.stringify({ dependencies: { 'beauticode-dsh': `link:${plugin.replaceAll('\\', '/')}` } })); const opts = { home: root, env: { DSH_HOME: root }, platform: 'linux', runtimeRoot: root }; + assert.equal(getHostStatus('dsh', opts).installed, false); + const configured = JSON.parse(fs.readFileSync(manifest, 'utf8')); + configured.dsh = { profile: { bundles: ['@deepseek-ai/dsh-base', 'beauticode-dsh'] } }; + fs.writeFileSync(manifest, JSON.stringify(configured)); assert.equal(getHostStatus('dsh', opts).installed, true); assert.equal(getAllStatus(opts).hosts.find(h => h.host === 'dsh').readiness, 'plugin-wired'); fs.writeFileSync(path.join(profile, 'cordis.patch.yml'), '- remove:\n - id: beauticode-bridge\n'); @@ -68,5 +72,15 @@ test('a staged DSH CLI install into an existing temporary profile is recognized' await runCli(['--dsh-home', home, '--plugin-home', path.join(root, 'installed-plugin')]); const status = getHostStatus('dsh', { home: root, env: { DSH_HOME: home }, platform: process.platform, runtimeRoot: root }); assert.equal(status.installed, true); - assert.equal(fs.existsSync(path.join(profile, 'cordis.patch.yml')), false); + const patch = path.join(profile, 'cordis.patch.yml'); + assert.match(fs.readFileSync(patch, 'utf8'), /id: beauticode-bridge/); + const manifest = path.join(profile, 'package.json'); + const configured = JSON.parse(fs.readFileSync(manifest, 'utf8')); + configured.dsh = { profile: { bundles: ['@deepseek-ai/dsh-base', 'beauticode-dsh'] } }; + fs.writeFileSync(manifest, JSON.stringify(configured)); + await runCli(['--dsh-home', home, '--plugin-home', path.join(root, 'installed-plugin')]); + assert.doesNotMatch(fs.readFileSync(patch, 'utf8'), /id: beauticode-bridge/); + await runCli(['--remove', '--dsh-home', home, '--plugin-home', path.join(root, 'installed-plugin')]); + const after = JSON.parse(fs.readFileSync(manifest, 'utf8')); + assert.deepEqual(after.dsh.profile.bundles, ['@deepseek-ai/dsh-base']); }); diff --git a/packages/core/test/media-server.test.js b/packages/core/test/media-server.test.js index a4c9483..e1fbdec 100644 --- a/packages/core/test/media-server.test.js +++ b/packages/core/test/media-server.test.js @@ -138,23 +138,27 @@ test("loopback media server: token, range, origin, identity drift", async () => test("fast staging rejects local media drift without requiring a full-file hash", async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "bc-media-fast-")); + const media = new MediaServerController(); try { const videoPath = path.join(root, "background.mp4"); await fs.writeFile(videoPath, mp4Fixture("FAST")); - const media = new MediaServerController(); const staged = await media.stage(videoPath, { validation: "fast" }); assert.ok(staged); assert.equal(staged.validation, "fast"); await media.commit(staged); await fs.writeFile(videoPath, mp4Fixture("DRFT")); + // Fast staging checks file metadata. Windows can assign the same time to + // two immediate writes of equal size, so make the drift explicit. + const changedAt = new Date(staged.mtimeMs + 2000); + await fs.utimes(videoPath, changedAt, changedAt); const changed = await fetch(staged.url, { headers: { [MEDIA_TOKEN_HEADER_CANON]: staged.token }, }); assert.equal(changed.status, 404); - await media.close(); } finally { + await media.close(); await fs.rm(root, { recursive: true, force: true }); } }); diff --git a/scripts/build-windows-installer.ps1 b/scripts/build-windows-installer.ps1 index fe5ff4a..0b03ecd 100644 --- a/scripts/build-windows-installer.ps1 +++ b/scripts/build-windows-installer.ps1 @@ -247,6 +247,7 @@ foreach ($relativeFile in @( "integrations\deepseek-harness\browser-injection.mjs", "integrations\deepseek-harness\transport.js", "integrations\deepseek-harness\client.js", + "integrations\deepseek-harness\readability.js", "integrations\deepseek-harness\console.js", "integrations\deepseek-harness\atmosphere.js", "integrations\deepseek-harness\presets.mjs", @@ -258,6 +259,7 @@ foreach ($relativeFile in @( "integrations\deepseek-harness\gallery-host.mjs", "integrations\deepseek-harness\skin-center.json", "integrations\deepseek-harness\cli.js", + "integrations\deepseek-harness\profile-patch.mjs", "integrations\deepseek-harness\bin\beauticode-dsh", "integrations\deepseek-harness\cordis.patch.yml", "integrations\deepseek-harness\package.json", diff --git a/scripts/install-dsh-plugin.ps1 b/scripts/install-dsh-plugin.ps1 index 5b367e1..acc1391 100644 --- a/scripts/install-dsh-plugin.ps1 +++ b/scripts/install-dsh-plugin.ps1 @@ -391,6 +391,14 @@ function Remove-WebPackageDeps { $changed = $true } } + $bundles = $json.dsh.profile.bundles + if ($bundles -is [array]) { + $remaining = @($bundles | Where-Object { $_ -cne $pluginName -and $_ -cne $legacyPluginName }) + if ($remaining.Count -ne $bundles.Count) { + $json.dsh.profile.bundles = $remaining + $changed = $true + } + } if (-not $changed) { return $false } $text = $json | ConvertTo-Json -Depth 8 Write-RecoverableText $webPackage ($text.TrimEnd() + "`n") @@ -427,17 +435,15 @@ $webExists = Test-Path -LiteralPath $webPackage -PathType Leaf if ($webExists) { Ensure-PluginJunction Ensure-WebPackageDep - # DSH also loads a package's own cordis.patch.yml. Keep one loader entry: - # when the plugin ships the bridge, retain that patch and remove only our - # managed profile block (with a backup); otherwise install the profile entry. + # A dependency's patch is only composed when the profile lists it as a bundle. + $profileManifest = [IO.File]::ReadAllText($webPackage) | ConvertFrom-Json + $loadsPluginBundle = @($profileManifest.dsh.profile.bundles) -ccontains $pluginName $pluginShipsBridge = $false if (Test-Path -LiteralPath $pluginPatch -PathType Leaf) { $pluginShipsBridge = Test-PatchHasBridge ([IO.File]::ReadAllText($pluginPatch)) } - if ($pluginShipsBridge) { - if (Test-PatchHasBridge ([IO.File]::ReadAllText($webPatch))) { - [void](Remove-BridgeFromPatch $webPatch) - } + if ($loadsPluginBundle -and $pluginShipsBridge) { + [void](Remove-BridgeFromPatch $webPatch) } else { Write-BridgePatch $webPatch (Get-PackageInsert) } diff --git a/scripts/pack-dsh-plugin.mjs b/scripts/pack-dsh-plugin.mjs index 71aa9e5..1a39558 100644 --- a/scripts/pack-dsh-plugin.mjs +++ b/scripts/pack-dsh-plugin.mjs @@ -31,6 +31,7 @@ const PLUGIN_FILES = [ "gallery-host.mjs", "skin-center.json", "cli.js", + "profile-patch.mjs", "bin/beauticode-dsh", "cordis.patch.yml", "package.json",