doubao-work 0.1.2: say at once that an open Doubao must be quit

The owner's sign-in spun with no end. Doubao runs one copy at a time: with
the user's own Doubao open, the plugin's copy (its own profile, debugging
port) quits within a second of starting, so the port never opens.
waitSignedIn took every error but app_missing as "not signed in yet" and
started it again for five minutes, saying nothing.

- App.start looks for a running copy of the binary on another profile
  before it starts one, and fails with app_busy. The user's copy can't be
  driven instead: Chromium allows debugging only off the default profile.
- waitSignedIn ends on any app_* error (busy, missing, start timeout) and
  on abort; only a window still loading is waited for.
- Sign-in and requests say: quit Doubao (⌘Q) and try again. A request
  gets 503.

Run: bun test packages/doubao-work on mote (+ check.mjs), Linux (WSL) and
Windows: 28 pass, 0 fail. With waitSignedIn's old catch put back, the new
waitSignedIn test is red (60s timeout instead of app_busy). Live on this
Mac, with a Doubao running from another profile: waitSignedIn threw
app_busy in 92ms, nothing spawned, no profile made. That a second copy
quits was tried first: Doubao with a fresh profile and port exited in ~1s,
port never up.
Not tried: the owner's Mac (10.0.0.175) itself.
This commit is contained in:
yetone
2026-11-09 06:53:05 +08:00
parent e918aa6c4b
commit f379bf907c
6 changed files with 82 additions and 9 deletions
+7 -2
View File
@@ -7,8 +7,8 @@ an OpenAI chat completion:
1. It starts Doubao from a profile of its own (`~/Library/Application
Support/magpie-doubao-work/profile`), with Chrome DevTools on a local
port. Your everyday Doubao is not touched; you sign in once in this
second window.
port. Your everyday Doubao's profile is not touched; you sign in once
in this second window.
2. Each request opens a new 工作任务, switches it from 本地电脑 to 云电脑
(so Doubao's agent never reads or runs anything on your computer), picks
the model, and writes the whole request (system prompt, tools, every
@@ -25,6 +25,11 @@ Models: 自动 (`auto`), 豆包 2.1 Lite (`doubao-2.1-lite`) and 豆包 2.1 Pro
- **Unofficial.** It uses Doubao the way its own window does, but ByteDance
may not like it. Use an account you can afford to lose.
- **Doubao runs one copy at a time.** If you opened Doubao yourself,
quit it (⌘Q) first: the plugin's copy can't start beside it, and yours
can't be driven (Chromium allows debugging only off the default
profile). While the plugin's copy runs, opening Doubao brings up its
window, which you can use as well.
- **One request at a time.** There is one window.
- **Every request is a new task** in your Doubao history.
- **A request the client stops** stops being read, but Doubao finishes
+25 -2
View File
@@ -8,7 +8,7 @@
// debugging port is one this driver picked and saved beside the profile,
// so a later request finds the same running app instead of starting
// another.
import { spawn as nodeSpawn } from "node:child_process"
import { execFileSync, spawn as nodeSpawn } from "node:child_process"
import fs from "node:fs"
import net from "node:net"
import path from "node:path"
@@ -50,6 +50,18 @@ 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 (Windows).
export function copies(binary) {
let out = ""
try {
out = execFileSync("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 + " "))
}
// App starts and finds one Chromium-based desktop app run from its own
// profile.
// binary the executable
@@ -57,9 +69,13 @@ export async function targets(port, fetchImpl = fetch) {
// owns (targets) => true when the pages on a port are this app's,
// so a port another program took since is never driven
// args more command-line switches
// others () => the command lines of the app's running copies; one
// 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 }) {
constructor({ binary, dataDir, owns, args = [], spawn = nodeSpawn, fetchImpl = fetch, others }) {
Object.assign(this, { binary, dataDir, owns, args, spawn, fetchImpl })
this.others = others ?? (() => copies(binary))
this.profile = path.join(dataDir, "profile")
this.portFile = path.join(dataDir, "port")
}
@@ -88,6 +104,13 @@ export class App {
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" })
// 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)))
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))
+41 -1
View File
@@ -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 } from "./cdp.mjs"
import { App, Page, copies } from "./cdp.mjs"
import { Doubao, NEW_TASK, CLOUD, READ, STATE, binary, owns, usageOf } from "./doubao.mjs"
import { Streamer, sse, completion } from "./openai.mjs"
import { flatten, parse, heldFrom } from "./prompt.mjs"
@@ -256,6 +256,7 @@ test("App reuses its own running app and never drives a port someone else took",
dataDir: dir,
owns,
spawn: (...a) => { spawned.push(a); return { unref() {} } },
others: () => [],
fetchImpl: async (url) => Response.json(String(url).includes(":4567/") ? pages : [{ type: "page", url: "doubao://doubao-chat/chat" }]),
})
expect(await mk([{ type: "page", url: "doubao://doubao-chat/chat" }]).start()).toBe(4567)
@@ -269,6 +270,37 @@ test("App reuses its own running app and never drives a port someone else took",
}
})
test("App says at once that a copy the user opened keeps it from starting", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dw-"))
try {
const bin = path.join(dir, "app")
fs.writeFileSync(bin, "")
const spawned = []
const mk = (others) =>
new App({ binary: bin, dataDir: dir, owns, others: () => others, spawn: (...a) => { spawned.push(a); return { unref() {} } }, fetchImpl: async () => { throw Error("refused") } })
await expect(mk([bin]).start({ timeout: 60000 })).rejects.toMatchObject({ code: "app_busy" })
await expect(mk([`${bin} --type=gpu --user-data-dir=/elsewhere`]).start({ timeout: 60000 })).rejects.toMatchObject({ code: "app_busy" })
expect(spawned.length).toBe(0)
// 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)
} finally {
fs.rmSync(dir, { recursive: true, force: true })
}
})
test("copies lists the binary's own processes only", () => {
expect(copies("/no/such/binary-" + Date.now())).toEqual([])
})
test("waitSignedIn says the app not starting at once, and waits for a window still loading", async () => {
const busy = new Doubao({ app: { start: async () => { throw Object.assign(Error("busy"), { code: "app_busy" }) } }, poll: 1 })
await expect(busy.waitSignedIn({ timeout: 60000 })).rejects.toMatchObject({ code: "app_busy" })
let n = 0
const loading = new Doubao({ app: fakeApp, openPage: async () => (++n < 2 ? null : fakePage([])), poll: 1 })
expect(await loading.waitSignedIn({ timeout: 60000 })).toMatchObject({ signedIn: true })
})
test("App says when the app is not installed", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dw-"))
try {
@@ -348,6 +380,10 @@ test("the plugin passes a sign-out on for re-sign-in and other failures as HTTP
await expect(out.fetch(req({ model: "auto", messages: [] }))).rejects.toMatchObject({ signIn: "expired" })
const missing = await fail(Object.assign(Error("not installed"), { code: "app_missing" })).auth.loader(async () => ({}))
expect((await missing.fetch(req({ model: "auto", stream: true, messages: [] }))).status).toBe(503)
const busy = await fail(Object.assign(Error("busy"), { code: "app_busy" })).auth.loader(async () => ({}))
const rb = await busy.fetch(req({ model: "auto", messages: [] }))
expect(rb.status).toBe(503)
expect((await rb.json()).error.message).toContain("退出豆包")
const paid = await fail(Object.assign(Error("upgrade"), { code: "doubao_upgrade", status: 403 })).auth.loader(async () => ({}))
const r = await paid.fetch(req({ model: "auto", messages: [] }))
expect(r.status).toBe(403)
@@ -361,6 +397,10 @@ test("sign-in waits for the Doubao window's account", async () => {
expect(r).toMatchObject({ type: "success", accountId: "豆包工作 · yetone" })
const late = I.createPlugin({ appBinary: mac, doubao: { waitSignedIn: async () => null } })
expect(await (await late.auth.methods[0].authorize()).callback()).toMatchObject({ type: "failed", error: expect.stringContaining("五分钟") })
const busy = I.createPlugin({ appBinary: mac, doubao: { waitSignedIn: async () => { throw Object.assign(Error("busy"), { code: "app_busy" }) } } })
const b = await (await busy.auth.methods[0].authorize()).callback()
expect(b.type).toBe("failed")
expect(b.error).toContain("退出豆包")
const linux = I.createPlugin({ appBinary: () => "", doubao: { waitSignedIn: async () => ({ signedIn: true, name: "x" }) } })
expect(await (await linux.auth.methods[0].authorize()).callback()).toMatchObject({ type: "failed", error: expect.stringContaining("macOS") })
})
+3 -1
View File
@@ -178,7 +178,9 @@ export class Doubao {
const until = Date.now() + timeout
for (;;) {
let s
try { s = await this.state(signal) } catch (e) { if (e?.code === "app_missing") throw e; s = null }
// the app not starting is said at once; a window still loading is
// waited for
try { s = await this.state(signal) } catch (e) { if (String(e?.code ?? "").startsWith("app_") || signal?.aborted) throw e; s = null }
if (s?.signedIn && s.name) return s
if (Date.now() > until) return null
await sleep(1500, signal)
+5 -2
View File
@@ -12,6 +12,8 @@ import { flatten } from "./prompt.mjs"
const ID = "doubao-work"
const BASE = "https://doubao-work.invalid/v1"
const BUSY = "豆包正在运行。豆包同时只能开一个,插件要用自己的豆包窗口:请先退出豆包(⌘Q)再试。"
const json = (status, message, type) =>
new Response(JSON.stringify({ error: { message, type } }), { status, headers: { "Content-Type": "application/json" } })
@@ -36,8 +38,8 @@ export function createPlugin({ doubao = new Doubao(), newId, appBinary = binary
const failed = (e) => {
if (e?.signIn) throw e
if (e?.name === "AbortError" || e?.name === "TimeoutError") throw e
const status = e?.code === "app_missing" || e?.code === "app_start_timeout" ? 503 : e?.status ?? 502
return json(status, String(e?.message ?? e), e?.code ?? "doubao_error")
const status = String(e?.code ?? "").startsWith("app_") ? 503 : e?.status ?? 502
return json(status, e?.code === "app_busy" ? BUSY : String(e?.message ?? e), e?.code ?? "doubao_error")
}
return {
config: async (cfg) => {
@@ -62,6 +64,7 @@ export function createPlugin({ doubao = new Doubao(), newId, appBinary = binary
s = await doubao.waitSignedIn()
} catch (e) {
if (e?.code === "app_missing") return { type: "failed", error: "没有找到豆包桌面版,请先安装:https://www.doubao.com/download/desktop" }
if (e?.code === "app_busy") return { type: "failed", error: BUSY }
return { type: "failed", error: "打开豆包失败:" + String(e?.message ?? e) }
}
if (!s) return { type: "failed", error: "五分钟内没有在豆包窗口里登录,请再试一次。" }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-doubao-work-auth",
"version": "0.1.1",
"version": "0.1.2",
"type": "module",
"main": "./opencode.mjs",
"files": [