diff --git a/packages/doubao-work/cdp.mjs b/packages/doubao-work/cdp.mjs index 9e40860..d390ea2 100644 --- a/packages/doubao-work/cdp.mjs +++ b/packages/doubao-work/cdp.mjs @@ -51,18 +51,36 @@ export async function targets(port, fetchImpl = fetch) { } // copies lists the command lines of the processes running binary itself -// (not its helpers), or none where ps can't tell. On Windows it is none: -// there, Chromium keeps one copy per profile, not per app, so a copy the -// user opened doesn't keep this one from starting beside it. -export function copies(binary, platform = process.platform) { - if (platform === "win32") return [] +// (not its helpers), or none where they can't be read. On Windows they come +// from WMI (#1117): there Chromium keeps one copy per profile, so a copy +// the user opened doesn't keep this one from starting, but the plugin's +// own copy, still up on its profile, must be found rather than started +// again. +export function copies(binary, platform = process.platform, run = execFileSync) { + if (platform === "win32") { + const exe = path.win32.basename(binary).replace(/'/g, "''") + let out = "" + try { + out = run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process -Filter "Name='${exe}'" -ErrorAction SilentlyContinue | ForEach-Object { $_.CommandLine }`], { encoding: "utf8", timeout: 15000, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }) + } catch { + return [] + } + return String(out).split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.includes("--type=")) + } let out = "" try { - out = execFileSync("ps", ["-axww", "-o", "command="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }) + out = run("ps", ["-axww", "-o", "command="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }) } catch { return [] } - return out.split("\n").map((l) => l.trim()).filter((l) => l === binary || l.startsWith(binary + " ")) + return String(out).split("\n").map((l) => l.trim()).filter((l) => l === binary || l.startsWith(binary + " ")) +} + +// portIn is the --remote-debugging-port a command line names, else 0 +export function portIn(line) { + const m = /--remote-debugging-port=(\d+)/.exec(line) + const n = m ? Number(m[1]) : 0 + return n > 0 && n < 65536 ? n : 0 } // App starts and finds one Chromium-based desktop app run from its own @@ -76,9 +94,9 @@ export function copies(binary, platform = process.platform) { // that isn't on this profile keeps a single-instance app (as // Doubao is) from starting a second copy at all export class App { - constructor({ binary, dataDir, owns, args = [], spawn = nodeSpawn, fetchImpl = fetch, others }) { - Object.assign(this, { binary, dataDir, owns, args, spawn, fetchImpl }) - this.others = others ?? (() => copies(binary)) + constructor({ binary, dataDir, owns, args = [], spawn = nodeSpawn, fetchImpl = fetch, others, platform = process.platform }) { + Object.assign(this, { binary, dataDir, owns, args, spawn, fetchImpl, platform }) + this.others = others ?? (() => copies(binary, platform)) this.profile = path.join(dataDir, "profile") this.portFile = path.join(dataDir, "port") } @@ -100,35 +118,51 @@ export class App { return list && this.owns(list) ? port : 0 } + // waitOn waits until the pages on port are this app's, then saves port + async waitOn(port, until, signal) { + while (Date.now() < until) { + await sleep(400, signal) + const list = await targets(port, this.fetchImpl) + if (list && this.owns(list)) { + fs.writeFileSync(this.portFile, String(port)) + return port + } + } + throw Object.assign(Error(`${path.basename(this.binary)} did not open its debugging port in ${Math.round((until - this.startedAt) / 1000)}s`), { code: "app_start_timeout" }) + } + // start runs the app when it isn't running yet and waits until its pages // answer. It never stops or kills anything: a port someone else holds is - // left to them and the app is started on another. + // left to them and the app is started on another. A copy already up on + // this profile is waited for on its own port, never started again: a + // single-instance app hands a second launch to it and keeps the old port + // (#1117), and the port file is written only once a port is seen to be + // this app's. async start({ timeout = 45000, signal } = {}) { const up = await this.running() if (up) return up if (!fs.existsSync(this.binary)) throw Object.assign(Error(`${this.binary} is not installed`), { code: "app_missing" }) + this.startedAt = Date.now() + const until = this.startedAt + timeout + const mine = `--user-data-dir=${this.profile}` + const others = this.others() + const own = others.map(portIn).find((n, i) => n && others[i].includes(mine)) + if (own) return this.waitOn(own, until, signal) // A copy the user opened themselves takes the new one's launch and // the new one quits: there would be nothing to wait for. Its profile // can't be driven either (Chromium allows debugging only off the - // default profile), so the user has to quit it. - const mine = `--user-data-dir=${this.profile}` - if (this.others().some((c) => !c.includes(mine))) + // default profile), so the user has to quit it. Windows keeps a copy + // per profile, so there it is no hindrance. + if (this.platform !== "win32" && others.some((c) => !c.includes(mine))) throw Object.assign(Error(`${path.basename(this.binary)} is already running from another profile`), { code: "app_busy" }) fs.mkdirSync(this.profile, { recursive: true }) const port = await freePort() - fs.writeFileSync(this.portFile, String(port)) const child = this.spawn(this.binary, [`--remote-debugging-port=${port}`, `--user-data-dir=${this.profile}`, ...this.args], { detached: true, stdio: "ignore", }) child.unref?.() - const until = Date.now() + timeout - while (Date.now() < until) { - await sleep(400, signal) - const list = await targets(port, this.fetchImpl) - if (list && this.owns(list)) return port - } - throw Object.assign(Error(`${path.basename(this.binary)} did not open its debugging port in ${Math.round(timeout / 1000)}s`), { code: "app_start_timeout" }) + return this.waitOn(port, until, signal) } } diff --git a/packages/doubao-work/doubao-work.test.mjs b/packages/doubao-work/doubao-work.test.mjs index a9f7e3f..8df7331 100644 --- a/packages/doubao-work/doubao-work.test.mjs +++ b/packages/doubao-work/doubao-work.test.mjs @@ -2,7 +2,7 @@ import { test, expect } from "bun:test" import fs from "node:fs" import os from "node:os" import path from "node:path" -import { App, Page, copies } from "./cdp.mjs" +import { App, Page, copies, portIn } from "./cdp.mjs" import { Doubao, NEW_TASK, CLOUD, MENU, LIST, SEND, READ, STATE, MODELS, EFFORT, idFor, tableFrom, listOf, lookup, effortFor, rateIn, APPS, binary, choose, dataDir, installedAt, hintsWin, hintsMac, owns, isChat, usageOf, QUOTA, quotaOf, rateOf } from "./doubao.mjs" import { Streamer, sse, completion } from "./openai.mjs" import { flatten, parse, heldFrom } from "./prompt.mjs" @@ -457,6 +457,37 @@ test("App says at once that a copy the user opened keeps it from starting", asyn // its own copy, still starting, is waited for await expect(mk([`${bin} --user-data-dir=${path.join(dir, "profile")}`]).start({ timeout: 500 })).rejects.toMatchObject({ code: "app_start_timeout" }) expect(spawned.length).toBe(1) + expect(fs.existsSync(path.join(dir, "port"))).toBe(false) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +// #1117: on Windows a second launch handed itself to the copy already up +// on the plugin's profile, and start waited on a port nothing listened on +test("App waits for its own copy on that copy's port instead of starting another", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dw-")) + try { + const bin = path.join(dir, "app.exe") + fs.writeFileSync(bin, "") + fs.writeFileSync(path.join(dir, "port"), "1111") + const spawned = [] + const own = `"${bin}" --remote-debugging-port=4321 --user-data-dir=${path.join(dir, "profile")}` + let ready = false + setTimeout(() => (ready = true), 600) + const app = new App({ + binary: bin, dataDir: dir, owns, platform: "win32", + // a copy the user opened on their own profile doesn't count on Windows + others: () => [`"${bin}"`, own], + spawn: (...a) => { spawned.push(a); return { unref() {} } }, + fetchImpl: async (url) => { + if (!String(url).includes(":4321/") || !ready) throw Error("refused") + return Response.json([{ type: "page", url: "doubao://doubao-chat/chat" }]) + }, + }) + expect(await app.start({ timeout: 5000 })).toBe(4321) + expect(spawned.length).toBe(0) + expect(fs.readFileSync(path.join(dir, "port"), "utf8")).toBe("4321") } finally { fs.rmSync(dir, { recursive: true, force: true }) } @@ -464,6 +495,14 @@ test("App says at once that a copy the user opened keeps it from starting", asyn test("copies lists the binary's own processes only", () => { expect(copies("/no/such/binary-" + Date.now())).toEqual([]) + const wmi = ["C:\\D\\Doubao.exe --remote-debugging-port=5 --user-data-dir=C:\\p", "C:\\D\\Doubao.exe --type=renderer --user-data-dir=C:\\p", "", "\"C:\\D\\Doubao.exe\""].join("\r\n") + let asked + expect(copies("C:\\D\\Doubao.exe", "win32", (cmd, args) => { asked = [cmd, args.at(-1)]; return wmi })).toEqual(["C:\\D\\Doubao.exe --remote-debugging-port=5 --user-data-dir=C:\\p", "\"C:\\D\\Doubao.exe\""]) + expect(asked[0]).toBe("powershell.exe") + expect(asked[1]).toContain("Name='Doubao.exe'") + expect(copies("C:\\D\\Doubao.exe", "win32", () => { throw Error("no wmi") })).toEqual([]) + expect(portIn("x --remote-debugging-port=9222 y")).toBe(9222) + expect(portIn("x")).toBe(0) }) @@ -675,7 +714,7 @@ test("a list never read from the menu is read when the plugin lists models, once const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-")) const labels = ["自动", "豆包 2.1 Lite", "豆包 2.1 Pro", "DeepSeek V4.1 Flash", "Kimi K3.1 Pro", "Kimi K3.1 Pro 高速", "Kimi K3", "GLM 5.3", "GLM 5.3 Flash", "DeepSeek V4 Pro"] const page = fakePage([], { steps: { menu: { rows: labels.map((label) => ({ label })) } } }) - const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 }) + const d = new Doubao({ app: { start: async () => 1, running: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 }) const p = I.createPlugin({ doubao: d }) const listed = await p.provider.models({}, {}) expect(Object.values(listed).map((m) => m.name)).toEqual(labels) @@ -684,7 +723,7 @@ test("a list never read from the menu is read when the plugin lists models, once // a menu that fails is not asked again within the minute const bad = fakePage([], { steps: { menu: { error: "no model menu" } } }) const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-")) - const d2 = new Doubao({ app: { start: async () => 1, dataDir: dir2 }, openPage: async () => bad, poll: 1 }) + const d2 = new Doubao({ app: { start: async () => 1, running: async () => 1, dataDir: dir2 }, openPage: async () => bad, poll: 1 }) await d2.ensureList(); await d2.ensureList() expect(bad.calls.filter((c) => c === MENU).length).toBe(1) expect(Object.keys(d2.modelList())).toEqual(Object.keys(MODELS)) @@ -711,7 +750,7 @@ const SUMMARY = { status: 200, body: { data: { current_subscription: { display: test("the plugin tells the plan's allowance from quota/summary instead of 暂无额度数据", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-quota-")) const page = fakePage([], { steps: { quota: SUMMARY } }) - const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 }) + const d = new Doubao({ app: { start: async () => 1, running: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 }) const p = I.createPlugin({ doubao: d }) const u = await p.auth.usage(async () => ({})) expect(u).toEqual({ plan: "标准套餐", windows: [{ name: "额度", used: 0 }] }) @@ -727,7 +766,7 @@ test("the plugin tells the plan's allowance from quota/summary instead of 暂无 test("a quota that can't be read says why and keeps the sign-in", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-quota-")) - const mk = (quota, dataDir = dir) => I.createPlugin({ doubao: new Doubao({ app: { start: async () => 1, dataDir }, openPage: async () => fakePage([], { steps: { quota } }), poll: 1 }) }) + const mk = (quota, dataDir = dir) => I.createPlugin({ doubao: new Doubao({ app: { start: async () => 1, running: async () => 1, dataDir }, openPage: async () => fakePage([], { steps: { quota } }), poll: 1 }) }) for (const [quota, want] of [[{ status: 401, body: null }, "过期"], [{ status: 200, body: {} }, "没有额度数据"], [{ error: "Failed to fetch" }, "Failed to fetch"]]) { const u = await mk(quota).auth.usage(async () => ({})) expect(u.signIn).toBe("kept") @@ -804,7 +843,7 @@ test("a models.json 0.1.9 wrote from the 对话 menu (快速, 专家) is read ag const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-")) fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({ at: Date.now(), models: tableFrom([{ label: "快速" }, { label: "专家" }]) })) const page = fakePage([], { steps: { list: BRIEF } }) - const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 }) + const d = new Doubao({ app: { start: async () => 1, running: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 }) const p = I.createPlugin({ doubao: d }) const listed = await p.provider.models({}, {}) expect(Object.values(listed).map((m) => m.name)).toEqual(WORK) @@ -812,6 +851,41 @@ test("a models.json 0.1.9 wrote from the 对话 menu (快速, 专家) is read ag fs.rmSync(dir, { recursive: true, force: true }) }) +// #1117: listing models and reading usage brought Doubao up on Windows +// whenever magpie asked, with no request sent +test("models() and usage never start Doubao: they read from a window already open", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-closed-")) + fs.mkdirSync(path.join(dir, "profile")) + let started = 0 + const app = { start: async () => { started++; return 1 }, running: async () => 0, dataDir: dir } + const page = fakePage([], { steps: { list: BRIEF, quota: SUMMARY } }) + const d = new Doubao({ app, openPage: async () => page, poll: 1 }) + const p = I.createPlugin({ doubao: d }) + const listed = await p.provider.models({}, {}) + expect(Object.keys(listed).length).toBeGreaterThan(0) + const u = await p.auth.usage(async () => ({})) + expect(u.signIn).toBe("kept") + expect(u.error).toContain("没有打开") + expect(started).toBe(0) + // open, the same window is read for both + app.running = async () => 1 + d.readAt = 0 + expect(Object.values(await p.provider.models({}, {})).map((m) => m.name)).toEqual(WORK) + expect((await p.auth.usage(async () => ({}))).error).toBeUndefined() + expect(started).toBe(0) + fs.rmSync(dir, { recursive: true, force: true }) +}) + +test("a models.json from an older version keeps its models until the list is read again", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-")) + const table = tableFrom([{ label: "快速" }, { label: "自动" }, { label: "Kimi K3.1 Pro" }]) + fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({ v: 1, at: Date.now(), models: table })) + const d = new Doubao({ app: { start: async () => 1, running: async () => 0, dataDir: dir }, poll: 1 }) + expect(Object.keys(d.modelList())).toEqual(["auto", "kimi-k3.1-pro"]) + expect(d.tableAt).toBe(0) + expect(await d.known("kimi-k3.1-pro")).toBe(true) +}) + test("effortFor takes the client's reasoning effort to the nearest 推理强度 the model has", () => { const five = ["低", "中", "高", "极高", "最高"] expect(effortFor("low", five)).toBe("低") diff --git a/packages/doubao-work/doubao.mjs b/packages/doubao-work/doubao.mjs index c6864e6..3b212b3 100644 --- a/packages/doubao-work/doubao.mjs +++ b/packages/doubao-work/doubao.mjs @@ -605,6 +605,9 @@ export const usageOf = (raw) => { // CACHE is the models.json format: 2 since the list comes from brief_list. const CACHE = 2 +// CHAT_ONLY are the 对话 menu's models, which 0.1.9 could list +const CHAT_ONLY = ["快速", "专家"] + // rateIn finds the multiple the model menu shows for the model named label: // its row is the one with that name, or that name and a badge ("Kimi K3 // 0.65x") when no other model has the longer name. @@ -660,6 +663,15 @@ export class Doubao { this.tableAt = d.at return this.table } + // an older one keeps its models, less the 对话 menu's, until the + // next read (#1117: a model picked from it was dropped when an + // update made it unreadable); it counts as never read + const old = Object.fromEntries(Object.entries(d?.models ?? {}).filter(([, m]) => m?.label && !CHAT_ONLY.includes(m.label))) + if (Object.keys(old).length) { + this.table = old + this.tableAt = 0 + return this.table + } } catch {} this.table = { ...MODELS } this.tableAt = 0 @@ -690,8 +702,8 @@ export class Doubao { // another list. Nothing is sent, so no task runs. inTask says the page is // on a new work task already (ask), so its menu is read too, for the // multiple each model costs, which only the menu shows. - async discover({ signal, inTask = false } = {}) { - const page = await this.connect(signal) + async discover({ signal, inTask = false, launch = true } = {}) { + const page = await this.connect(signal, { launch }) const old = this.modelList() let rows = null try { rows = listOf(await page.eval(LIST)) } catch {} @@ -721,15 +733,16 @@ export class Doubao { // ensureList reads the menu once when it has never been read, for an // account that signed in before the plugin read menus (or whose sign-in // read failed): without it the list stays at the three built-in models - // until the first request. Only an app this plugin has started before - // (its data folder exists) is opened for it; a failed read is tried - // again after a minute. It queues behind a running ask. + // until the first request. It reads it only from a window already open: + // a model list is no reason to bring Doubao up (#1117), so a closed one + // is read on the next request. A failed read is tried again after a + // minute. It queues behind a running ask. async ensureList({ signal } = {}) { this.modelList() - if (this.tableAt || !this.app?.start || !this.cacheFile) return - if (!fs.existsSync(path.dirname(this.cacheFile)) || Date.now() - this.readAt < 60000) return + if (this.tableAt || !this.app?.running || !this.cacheFile) return + if (Date.now() - this.readAt < 60000) return this.readAt = Date.now() - const run = this.queue.then(() => this.tableAt || this.discover({ signal })) + const run = this.queue.then(() => this.tableAt || this.discover({ signal, launch: false })) this.queue = run.catch(() => {}) try { await run } catch {} } @@ -750,22 +763,28 @@ export class Doubao { return !!lookup(this.modelList(), model) } - // quota reads the plan's allowance through the app's page. Only an app - // this plugin has started before is opened for it (its data folder - // exists), so a usage read never launches Doubao for a user who has - // not signed in here. + // quota reads the plan's allowance through the app's page, from a + // window already open only: a usage read never brings Doubao up + // (#1117), it says the window is closed instead. async quota({ signal } = {}) { if (!(this.page && !this.page.closed)) { if (!this.app?.start) throw new DoubaoError("没有找到豆包。", "app_missing") if (this.app.dataDir && !fs.existsSync(this.app.dataDir)) throw new DoubaoError("还没有登录过豆包工作窗口。", "doubao_signin") } - const page = await this.connect(signal) + const page = await this.connect(signal, { launch: false }) return page.eval(QUOTA) } - async connect(signal) { + // connect gives the page of the app's chat window, starting the app + // when launch says so; without it a closed app is the app_closed error + async connect(signal, { launch = true } = {}) { if (this.page && !this.page.closed) return this.page - const port = await this.app.start({ signal }) + let port + if (launch) port = await this.app.start({ signal }) + else { + port = this.app?.running ? await this.app.running() : 0 + if (!port) throw new DoubaoError("豆包工作窗口没有打开:额度和模型列表在它打开时读取,下一次请求会打开它。", "app_closed") + } this.page = await this.openPage(port, (t) => isChat(t.url)) if (!this.page) throw new DoubaoError("豆包的对话窗口没有打开。请在豆包里打开一个对话窗口后再试。", "doubao_no_window") return this.page diff --git a/packages/doubao-work/package.json b/packages/doubao-work/package.json index a711301..35c39de 100644 --- a/packages/doubao-work/package.json +++ b/packages/doubao-work/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-doubao-work-auth", - "version": "0.1.10", + "version": "0.1.11", "type": "module", "main": "./opencode.mjs", "files": [