From 4ac4766217e54dbc00e2cc73d4d6dbf20083a134 Mon Sep 17 00:00:00 2001 From: moxuanchen Date: Sun, 25 Oct 2026 14:04:10 +0800 Subject: [PATCH] trae 0.2.22: every client profile is read, a claim's code 0 is read back (#333) moxuanchen's change for #361 (a second Trae CN account can't check in). - Every Trae CN client profile is read (Trae CN, TRAE SOLO CN, trae-cn): the one signed in as the account gives its device. A profile signed in as someone else, or one that doesn't parse, no longer hides the rest. - A claim's code 0 is read back from the status. Not in after the claim is `ineligible` for the day (no repeat claims); a failed read-back is ineligible too. - 9074's message says Trae did not take the check-in for this account's device, and no longer sends people to Trae CN's app. - Credit: the claim's credits, else its extra_credits, else the read-back's credits; never summed (matches 0.2.21). - Version 0.2.22, README updated. Run at the reviewed head 4006fef51 (rebased on ba9801c), sandbox HOME: - packages/trae: bun test, 213 pass, 0 fail. bun scripts/check.mjs: trae ok. - Broken by hand, each red: first profile decides (2 red), no read-back (2 red), failed read-back reported as failed (1 red), credits summed (2 red), TRAE SOLO CN folder dropped (1 red). Restored after. Not tried: a real second Trae CN account, and TRAE SOLO CN's real storage.json (its folder and keys are inferred, as the README says). A status that lags a claim that did land would read ineligible once that day; the README names it. --- packages/trae/README.md | 78 ++++++++++++---- packages/trae/index.mjs | 129 +++++++++++++++++++------- packages/trae/native-checkin.test.mjs | 111 +++++++++++++++++++--- packages/trae/ownclient.test.mjs | 78 ++++++++++++++-- packages/trae/package.json | 2 +- 5 files changed, 323 insertions(+), 75 deletions(-) diff --git a/packages/trae/README.md b/packages/trae/README.md index b8bc523..f5f87df 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -354,12 +354,15 @@ an empty answer. Trae CN gives credits for a daily check-in (每日签到); Trae Global has no such page, so this is CN only. magpie can press it once a day for each account (Settings, or the switch on the usage card), -through `auth.checkin`: `claimed` when Trae grants the credits, `done` -when the status says today's is in already, `inactive` when the page is +through `auth.checkin`: `claimed` when the status says today's is in after +the claim, `done` when it said so before it, `inactive` when the page is disabled, `ineligible` when the claim answers 9095 (this device has -checked in today) or 9074 (to be done in Trae CN's own app; not asked -again that day), and `failed` for a turned-away sign-in or any other -answer, which is tried again later that day. +checked in today) or 9074 (Trae did not take it for this account's +device) or answers code 0 while the read-back still says the day is out, +and `failed` for a turned-away sign-in or any answer that got nowhere, +which is tried again later that day. An `ineligible` is the day's answer: +magpie asks that account no more until tomorrow, and only reads its +status. It asks Trae CN's own pages through this plugin's fetch, which sends them as the account, as Trae CN's IDE (3.3.104) sends them: its Cloud-IDE-JWT (renewed first when near its @@ -390,10 +393,27 @@ answered it 9074 even with the client's headers. plugin's, on its own device, got 9074 (yetone/magpie#808, #1920); that this header is what changes it hasn't been tried on a real account yet. Every other account keeps its own device, and a file that can't be - read or made out, or holds no single device, changes nothing. Files: - macOS `~/Library/Application Support/Trae CN/…`, Windows - `%APPDATA%\Trae CN\…` (or `trae-cn`), Linux `~/.config/trae-cn/…` - (or `Trae CN`; not seen on a real Linux install). + read or made out, or holds no single device, changes nothing. +- **Every profile is read (0.2.21):** a machine can hold more than one + Trae CN client profile — the IDE's and TRAE SOLO CN's each write their + own `storage.json`, and each names the account that profile is signed in + as, with that account's device. So every profile is read and the one + signed in as the account answers with its device, which is how two + accounts can each check in on a real client's device. Before, only the + first profile was read and it decided for all of them: a second + account's own profile was never seen, and one profile signed in as + someone else (or one file that didn't parse) hid every profile after it. + A profile that isn't signed in as the account, or that names no single + device, is passed over rather than ending the search. Files: macOS + `~/Library/Application Support/Trae CN/…` and `…/TRAE SOLO CN/…`, Windows + `%APPDATA%\Trae CN\…`, `…\TRAE SOLO CN\…` (or `trae-cn`), Linux + `~/.config/trae-cn/…`, `…/Trae CN/…`, `…/TRAE SOLO CN/…`. The IDE's + folder has been seen in a real install (macOS and Windows); TRAE SOLO + CN's name and its `iCubeAuthInfo://` keys are read as the same client + of the same realm writes them, which hasn't been checked against real + files — harmless if they differ, since a folder that isn't there, or a + key that isn't named, is simply not read. A client started with its own + `--user-data-dir` is not found: there is no list of those to read. - **Every other account's device (0.2.16):** its own device id, in the client's shape. Trae CN answered a claim on the plugin's 19-digit id 9074, while the same account and token on a 16-digit id were taken @@ -404,15 +424,37 @@ answered it 9074 even with the client's headers. keep the 19-digit device it signed in with. - **What comes back:** Trae's answer as it is. A 401 or code 1001 marks the account for a new sign-in. Code 9095 means this device has checked - in today, and that holds for the day. No device id is ever changed or - rotated to get round a 9095 or a 9074, and no account is given another - account's device or its own client's device unless the client is signed - in as that account. The credit a claim granted is its `credits`, or - its `extra_credits` when it names only that; Trae CN's claim usually - names neither (`{"code":0,"message":"success"}`), and then the status - answer's `credits` is the credit. The two are never added: the status - carries `extra_credits` beside `credits` (100 and 100 on a real - account) while the day gives 100. + in today, and that holds for the day. Code 9074 means Trae did not take + the claim for this account's device: its own words say the pool is busy, + which two measurements do not bear out — the same account, token and + headers were taken on a 16-digit id where a 19-digit one got 9074 + (plugins#194), and on 2026-10-23 the same account and headers were taken + on a device id Trae had never seen while this account's own id answered + 9074. The message says so, and does not send people to Trae CN's app, + which is not where the problem is. Signing the account in to a Trae CN + client on this machine is the one thing seen to change a 9074, but it + hasn't been tried on a real account, so it isn't named in the message; + nor is it named when the claim already rode a client's device, where it + would only tell the user to do what they did. No device id is ever + changed or rotated to get round a 9095 or a 9074, and no account is + given another account's device or its own client's device unless a + client is signed in as that account. +- **A claim's code 0 is not the answer (0.2.22):** Trae answers a + claim code 0 for one that registered nothing, so the status is read back + after every claim and only a day that is in is reported as `claimed`. + Since 0.2.22 one that isn't is an `ineligible` — the day's answer, not a + `failed` to be tried again: a `failed` is retried with backoff for the + rest of the day and each retry is another claim, which for an account + Trae keeps answering code 0 would turn one claim a day into many, and a + status that lags a claim that did land would read as not in once and + claim again. Nothing is claimed again that day; the status alone is + read, so a lag that catches up is still reported as `done`. The credit a + claim granted is its `credits`, or its `extra_credits` when it names + only that; Trae CN's claim usually names neither + (`{"code":0,"message":"success"}`), and then the read-back's `credits` + is the credit. The two are never added: the status carries + `extra_credits` beside `credits` (100 and 100 on a real account) while + the day gives 100. Only `api.trae.cn`'s `/trae/api/` pages are sent this way; any other URL that isn't a chat request is still refused (400). Needs 0.1.4 or later. diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index 5bd869f..808607b 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -826,9 +826,16 @@ const ownClient = { paths: () => clientStoragePaths(process.platform, homedir(), process.env), } +// CLIENT_PROFILES are the folder names a Trae CN client profile is kept +// under: the IDE's own, and TRAE SOLO CN's, which is a client of the same +// realm and signs in its own account. A profile started with its own +// --user-data-dir is found only if it is one of these; there is no list of +// them to read, and nothing is guessed from a folder's contents. +const CLIENT_PROFILES = ["Trae CN", "TRAE SOLO CN", "trae-cn"] + function clientStoragePaths(platform, home, env) { const file = (root, name) => join(root, name, "User", "globalStorage", "storage.json") - if (platform === "darwin") return [file(join(home, "Library", "Application Support"), "Trae CN")] + if (platform === "darwin") return CLIENT_PROFILES.filter((n) => n !== "trae-cn").map((n) => file(join(home, "Library", "Application Support"), n)) if (platform === "win32") { // the two roots are often the same folder: APPDATA and the home's own // AppData\Roaming. They are compared as one system spells them, so a @@ -840,19 +847,28 @@ function clientStoragePaths(platform, home, env) { if (roots.some((was) => spell(was) === spell(r))) continue roots.push(r) } - return roots.flatMap((r) => ["Trae CN", "trae-cn"].map((n) => file(r, n))) + return roots.flatMap((r) => CLIENT_PROFILES.map((n) => file(r, n))) } - if (platform === "linux") return ["trae-cn", "Trae CN"].map((n) => file(env.XDG_CONFIG_HOME || join(home, ".config"), n)) + if (platform === "linux") return CLIENT_PROFILES.map((n) => file(env.XDG_CONFIG_HOME || join(home, ".config"), n)) return [] } -// clientDevice is the device id of this machine's Trae CN client when the -// client is signed in as uid, else undefined. It only reads: nothing of -// the client's is written, kept or sent but that id, and the client's own -// token is read past, never used. A file it can't read or make out, or one -// with no single device, names no device, and the account keeps its own. -// Never an id made up or changed: an account the client isn't signed in -// as never gets the client's id. +// clientDevice is the device id of a Trae CN client profile on this machine +// that is signed in as uid, else undefined. It only reads: nothing of the +// client's is written, kept or sent but that id, and the client's own token +// is read past, never used. Never an id made up or changed: an account no +// profile is signed in as never gets a client's id. +// +// A machine can hold more than one profile — Trae CN and TRAE SOLO CN each +// write one, and a client started with its own --user-data-dir writes +// another — and each profile's storage.json names the account it is signed +// in as, with that account's device. So every profile is read and the one +// signed in as uid answers with its device, which is what lets two accounts +// each check in on a real client's device. A profile that isn't signed in +// as uid, that can't be read or made out, or that names no single device +// is passed over rather than ending the search: before, the first profile +// read decided for all of them, so a second account's own profile was never +// seen (and one unreadable file hid every profile after it). async function clientDevice(uid) { if (!uid) return undefined for (const p of ownClient.paths()) { @@ -862,14 +878,19 @@ async function clientDevice(uid) { } catch { continue // not installed here } + let doc try { - const doc = JSON.parse(text) - const ids = Object.keys(doc ?? {}).filter((k) => k.startsWith(DC_KEY)).map((k) => k.slice(DC_KEY.length)) - if (ids.length !== 1 || !/^\d{8,20}$/.test(ids[0])) return undefined - const who = clientAuth(doc[AUTH_KEY])?.userId - return who != null && String(who) === String(uid) ? ids[0] : undefined + doc = JSON.parse(text) } catch { - return undefined + continue // not a file we can make out: the next profile may be + } + try { + const ids = Object.keys(doc ?? {}).filter((k) => k.startsWith(DC_KEY)).map((k) => k.slice(DC_KEY.length)) + if (ids.length !== 1 || !/^\d{8,20}$/.test(ids[0])) continue + const who = clientAuth(doc[AUTH_KEY])?.userId + if (who != null && String(who) === String(uid)) return ids[0] + } catch { + continue // a sign-in that doesn't decode: the next profile may be } } return undefined @@ -2874,34 +2895,78 @@ const makePlugin = (site) => async ({ client }) => { return new Response(text, { status: res.status, headers }) } - // checkin asks Trae CN's own pages as magpie's check-in host does, with - // the same account, device and renewal as any own page. Trae Global has - // no such page. + // checkinStatus reads the check-in's status page: its body, or an outcome + // to give back as it is (a turned-away sign-in, Trae's own error, a reply + // that isn't one). checkin reads it before the claim, and again after it. + const checkinStatus = async (getAuth, a0) => { + const res = await ownRequest(getAuth, a0, site.hosts.auth + site.checkin.status.path, "POST", "{}") + const text = await res.text() + let body + try { body = JSON.parse(text) } catch {} + if (!body || typeof body !== "object" || Array.isArray(body)) return { outcome: { outcome: "failed", message: `check-in status: unreadable reply ${text.trim().slice(0, 120) || "(empty)"}` } } + const e = errorOf(body) + if (res.status === 401 || lapsedCode(e.code, site)) return { outcome: { outcome: "failed", message: e.message || `${a0.name || a0.uid}: Trae's sign-in has expired` } } + if (res.status !== 200 || (e.code && String(e.code) !== "0")) return { outcome: { outcome: "failed", message: e.message || statusLine(res.status) } } + return { body } + } + const checkin = async (getAuth) => { if (!site.checkin) return { outcome: "inactive", message: `${site.realm} has no daily check-in` } const a0 = fromAuth(await getAuth(), site) if (!a0) return { outcome: "failed", message: "not signed in" } - const base = site.hosts.auth + site.checkin.status.path - const status = await ownRequest(getAuth, a0, base, "POST", "{}") - const statusText = await status.text() - let body - try { body = JSON.parse(statusText) } catch {} - if (!body || typeof body !== "object" || Array.isArray(body)) return { outcome: "failed", message: `check-in status: unreadable reply ${statusText.trim().slice(0, 120) || "(empty)"}` } - const e = errorOf(body) - if (status.status === 401 || lapsedCode(e.code, site)) return { outcome: "failed", message: e.message || `${a0.name || a0.uid}: Trae's sign-in has expired` } - if (status.status !== 200 || (e.code && String(e.code) !== "0")) return { outcome: "failed", message: e.message || statusLine(status.status) } - if (body?.checked_in) return { outcome: "done", ...(Number(body.credits) > 0 ? { credit: Number(body.credits) } : {}) } - if (!body?.enable) return { outcome: "inactive" } + const first = await checkinStatus(getAuth, a0) + if (first.outcome) return first.outcome + const body = first.body + if (body.checked_in) return { outcome: "done", ...(Number(body.credits) > 0 ? { credit: Number(body.credits) } : {}) } + if (!body.enable) return { outcome: "inactive" } const claim = await ownRequest(getAuth, a0, site.hosts.auth + site.checkin.claim.path, "POST", "{}") const claimText = await claim.text() let answer try { answer = JSON.parse(claimText) } catch {} const ce = errorOf(answer) if (claim.status === 401 || lapsedCode(ce.code, site)) return { outcome: "failed", message: ce.message || `${a0.name || a0.uid}: Trae's sign-in has expired` } + // 9095: this device is in for today, whoever took it — the day's answer if (String(ce.code) === "9095") return { outcome: "ineligible", message: ce.message || "this device has checked in today" } - if (String(ce.code) === "9074") return { outcome: "ineligible", message: `${ce.message} — check in in the Trae CN app` } + // 9074: Trae did not take this claim for this account's device. Its own + // words say the pool is busy, which measurements do not bear out: the + // same account, token and headers were taken on a 16-digit id where a + // 19-digit one got 9074 (plugins#194), and on 2026-10-23 the same + // account and headers were taken on a device id Trae had never seen + // while this account's own id answered 9074. So the message says what + // Trae said and that the device is what it refused, rather than + // sending people to check in in Trae CN's app, which is not where the + // problem is. No device id is made up or rotated to get round this: + // the account keeps its own until a client of its own is here to sign + // it in. Nothing is said of signing one in: it is the one thing seen + // to change a 9074, but it hasn't been tried on a real account, and + // on a claim that already rode a client's device it is what the user + // did — the advice would only send them back to do it again. + if (String(ce.code) === "9074") return { outcome: "ineligible", message: `${ce.message} (9074) — Trae CN did not take this check-in for this account's device` } if (claim.status !== 200 || (ce.code && String(ce.code) !== "0")) return { outcome: "failed", message: ce.message || statusLine(claim.status) } if (!answer || typeof answer !== "object" || Array.isArray(answer)) return { outcome: "failed", message: `check-in claim: unreadable reply ${claimText.trim().slice(0, 120) || "(empty)"}` } + // a claim's own code 0 is not proof the day is in: Trae answers it for + // a claim that registered nothing, which cli2api works around by asking + // the status again (internal/providers/trae/checkin.go). So success is + // what the status page says after the claim, and one that didn't land + // is never reported as claimed. + // + // Nor is it a `failed`. magpie retries a failed check-in with backoff + // for the rest of the day, up to every 30 minutes, and each retry is + // another claim: a claim answered code 0 while the status still says + // the day is out is the very case that would multiply, since code 0 + // for a claim that registered nothing is this plugin's own premise — + // an account that claimed once a day would claim many times. A status + // that lags a claim that did land reads as not in once, which is a + // false failure and a second claim. So once a claim has been sent, + // what the read-back says is the day's answer and nothing is claimed + // again: `ineligible`, as a 9095 is. A read-back that itself comes to + // nothing — the network, an answer that isn't one — is the same: the + // claim was made, and whether the day is in is not known, so it is + // read again on the next press rather than claimed again. + const noMore = (o) => (o.outcome === "failed" ? { outcome: "ineligible", message: `${o.message} — nothing is claimed again today` } : o) + const back = await checkinStatus(getAuth, a0) + if (back.outcome) return noMore(back.outcome) + if (!back.body.checked_in) return { outcome: "ineligible", message: `${site.realm}: the claim answered success, but the day's check-in is not in — nothing is claimed again today` } // The credit is the day's credits, never credits plus extra_credits. // Trae CN's real claim answers {"code":0,"message":"success"}, with no // credit at all (plugins#194), so the status's credits stand in. Its @@ -2912,7 +2977,7 @@ const makePlugin = (site) => async ({ client }) => { // taken first; one naming extra_credits alone is that (#260). Either // may be absent, and Number(undefined) is NaN, which reads as none. const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0) - const credit = n(answer.credits) || n(answer.extra_credits) || n(body.credits) + const credit = n(answer.credits) || n(answer.extra_credits) || n(back.body.credits) return { outcome: "claimed", ...(credit > 0 ? { credit } : {}) } } diff --git a/packages/trae/native-checkin.test.mjs b/packages/trae/native-checkin.test.mjs index 30247bb..cbe70b3 100644 --- a/packages/trae/native-checkin.test.mjs +++ b/packages/trae/native-checkin.test.mjs @@ -13,23 +13,30 @@ async function checkin(plugin = TraeCNAuthPlugin, auth = signedIn(), client = {} return hooks.auth.checkin(async () => auth) } +// claimable is a day that is not in until the claim lands: the status +// answers checked_in false, then true once the claim has been made — as +// Trae's does, and as the plugin's read-back after a claim reads it. +// claimRoute answers the claim itself; day is what the status says. +function claimable(day = {}, claimRoute = () => json({ code: 0 })) { + let claimed = false + f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: claimed, ...day })) + f.route("POST " + CLAIM, () => { claimed = true; return claimRoute() }) +} + test("a claim answering extra_credits alone is claimed with that credit", async () => { f = fakeTrae() - f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: false, credits: 0 })) - f.route("POST " + CLAIM, () => json({ code: 0, extra_credits: 20 })) // credits absent: Number(undefined) is NaN, and NaN + 20 read as no credit + claimable({ credits: 0 }, () => json({ code: 0, extra_credits: 20 })) expect(await checkin()).toEqual({ outcome: "claimed", credit: 20 }) }) test("a claim answering neither credit says so, and the status's is the fallback", async () => { f = fakeTrae() - f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: false, credits: 30 })) - f.route("POST " + CLAIM, () => json({ code: 0 })) + claimable({ credits: 30 }) expect(await checkin()).toEqual({ outcome: "claimed", credit: 30 }) f.close() f = fakeTrae() - f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: false })) - f.route("POST " + CLAIM, () => json({ code: 0 })) + claimable() expect(await checkin()).toEqual({ outcome: "claimed" }) }) @@ -39,15 +46,13 @@ test("a claim answering neither credit says so, and the status's is the fallback // so the status's stands in, and its extra_credits is not added on top. test("a claim with no credit of its own is the status's credits, not credits plus extra_credits", async () => { f = fakeTrae() - f.route("POST " + STATUS, () => json({ checked_in: false, code: 0, credits: 100, did_checked_in: false, enable: true, extra_credits: 100 })) - f.route("POST " + CLAIM, () => json({ code: 0, message: "success" })) + claimable({ credits: 100, did_checked_in: false, extra_credits: 100 }, () => json({ code: 0, message: "success" })) expect(await checkin()).toEqual({ outcome: "claimed", credit: 100 }) }) test("a claim naming both credits and extra_credits is its credits, once", async () => { f = fakeTrae() - f.route("POST " + STATUS, () => json({ checked_in: false, code: 0, credits: 100, enable: true, extra_credits: 100 })) - f.route("POST " + CLAIM, () => json({ code: 0, credits: 100, extra_credits: 100 })) + claimable({ credits: 100, extra_credits: 100 }, () => json({ code: 0, credits: 100, extra_credits: 100 })) expect(await checkin()).toEqual({ outcome: "claimed", credit: 100 }) }) @@ -59,10 +64,11 @@ test("an already-checked day with extra_credits is its credits", async () => { test("a claimable day is claimed through Trae's own pages", async () => { f = fakeTrae() - f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: false })) - f.route("POST " + CLAIM, () => json({ code: 0, credits: 100 })) + claimable({}, () => json({ code: 0, credits: 100 })) expect(await checkin()).toEqual({ outcome: "claimed", credit: 100 }) - expect(f.seen.map((r) => r.path)).toEqual([STATUS, CLAIM]) + // the status before the claim, the claim, and the status that reads the + // day back: a claim's code 0 is not the answer by itself + expect(f.seen.map((r) => r.path)).toEqual([STATUS, CLAIM, STATUS]) for (const r of f.seen) { expect(r.json).toEqual({ req_source: 1 }) expect(r.headers.get("authorization")).toBe("Cloud-IDE-JWT jwt-1") @@ -90,19 +96,94 @@ test("the device's already-checked answer is ineligible", async () => { expect(await checkin()).toEqual({ outcome: "ineligible", message: "this device has checked in today" }) }) -test("Trae's 9074 on the claim is the day's answer, on the account's own device", async () => { +// 9074 is not "the pool is busy": the same account, token and headers were +// taken on a 16-digit id where a 19-digit one got 9074 (plugins#194), and +// on 2026-10-23 the same account and headers were taken on a device id Trae +// had never seen while this account's own id answered 9074. The account is +// told what Trae said and that the device is what it refused — not sent to +// check in in Trae CN's app, which is not where the problem is. Signing the +// account in to a client here is the one thing seen to change it, but it +// hasn't been tried on a real account, so the message doesn't promise it; +// and on a claim that already rode a client's device there is nothing to +// advise, so it says nothing. +test("Trae's 9074 on the claim says the device is what Trae refused, and promises no fix", async () => { f = fakeTrae() f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: false })) f.route("POST " + CLAIM, () => json({ code: 9074, message: "当前参与用户太多" })) const out = await checkin() expect(out.outcome).toBe("ineligible") expect(out.message).toContain("当前参与用户太多") - expect(out.message).toContain("check in in the Trae CN app") + expect(out.message).toContain("9074") + expect(out.message).toContain("device") + expect(out.message).not.toContain("Trae CN client") + expect(out.message).not.toContain("check in in the Trae CN app") // the check-in rides ugDevice like every other ug page: the 19-digit // sign-in device becomes the account's own 16-digit shape (#194) expect(f.seen.map((r) => r.headers.get("x-device-id"))).toEqual(["2866487253502651", "2866487253502651"]) }) +// a claim's code 0 is not the answer: Trae answers it for a claim that +// registered nothing, so the status is read back after it +test("a claim answered success that didn't land is the day's answer, not a retry", async () => { + f = fakeTrae() + f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: false })) + f.route("POST " + CLAIM, () => json({ code: 0, credits: 100 })) + const out = await checkin() + expect(out).toMatchObject({ outcome: "ineligible" }) + expect(out.message).toContain("not in") + // the status before the claim, the claim, and the read-back that found + // the day still out + expect(f.seen.map((r) => r.path)).toEqual([STATUS, CLAIM, STATUS]) +}) + +// ineligible, not failed: magpie retries a failed check-in with backoff for +// the rest of the day and each retry is another claim, so a claim answered +// code 0 while the status still says the day is out — this plugin's own +// premise for an account Trae keeps refusing — would claim many times a day, +// and a status that lags a claim that did land would read as not in once and +// claim again. An ineligible is the day's answer in magpie's eyes: it asks +// that account no more until tomorrow, and only reads its status, so a lag +// that catches up within the day still reads as done. +test("a claim that didn't land is ineligible, which magpie reads rather than asks again", async () => { + f = fakeTrae() + f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: false })) + f.route("POST " + CLAIM, () => json({ code: 0, credits: 100 })) + const out = await checkin() + expect(out).toMatchObject({ outcome: "ineligible" }) + // the status before the claim, the claim, and the read-back that found the + // day still out — no second claim on the day + expect(f.seen.map((r) => r.path)).toEqual([STATUS, CLAIM, STATUS]) + // magpie's next pass reads the status alone, which is what a day already + // answered with an ineligible asks of the plugin: the claim is not sent + f.seen.length = 0 + f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: true, credits: 100 })) + const later = await checkin() + expect(later).toEqual({ outcome: "done", credit: 100 }) + expect(f.seen.map((r) => r.path)).toEqual([STATUS]) +}) + +// a read-back that can't be read after a claim is the day's answer too: the +// claim was made and whether the day is in isn't known, so it is read again +// rather than claimed again +test("a read-back that can't be read is not claimed again that day", async () => { + f = fakeTrae() + let n = 0 + f.route("POST " + STATUS, () => (n++ === 0 ? json({ code: 0, enable: true, checked_in: false }) : new Response("gateway"))) + f.route("POST " + CLAIM, () => json({ code: 0 })) + const out = await checkin() + expect(out).toMatchObject({ outcome: "ineligible" }) + expect(out.message).toContain("unreadable") + expect(out.message).toContain("nothing is claimed again today") +}) + +test("a claim that lands is claimed on the status's word, its credit the read-back's", async () => { + f = fakeTrae() + let claimed = false + f.route("POST " + STATUS, () => json({ code: 0, enable: true, checked_in: claimed, credits: claimed ? 120 : 0 })) + f.route("POST " + CLAIM, () => { claimed = true; return json({ code: 0 }) }) + expect(await checkin()).toEqual({ outcome: "claimed", credit: 120 }) +}) + test("an unreadable status reply is failed", async () => { f = fakeTrae() f.route("POST " + STATUS, () => new Response("gateway")) diff --git a/packages/trae/ownclient.test.mjs b/packages/trae/ownclient.test.mjs index 02b45f3..c533dc6 100644 --- a/packages/trae/ownclient.test.mjs +++ b/packages/trae/ownclient.test.mjs @@ -18,6 +18,15 @@ beforeEach(() => { file = join(dir, "storage.json") _internal.ownClient.paths = () => [join(dir, "missing.json"), file] }) + +// clientFile writes a client's storage.json at p: its sign-in as userId, +// and the device ids dcs (the key iCubeAuthInfo://icube-dc:) +function clientFile(p, userId, { encoded = true, dcs = [DC] } = {}) { + const auth = JSON.stringify({ token: "client-jwt", refreshToken: "client-refresh", userId, host: "https://api.trae.cn" }) + const doc = { "telemetry.machineId": "m".repeat(64), [`iCubeAuthInfo://icube.cloudide`]: encoded ? encode(auth) : auth } + for (const d of dcs) doc[`iCubeAuthInfo://icube-dc:${d}`] = "device-key-pair" + writeFileSync(p, JSON.stringify(doc)) +} afterEach(() => { f?.close() f = undefined @@ -40,11 +49,8 @@ function encode(text, header = "746305100000") { } const xor = (a, b) => Buffer.from(a.map((x, i) => x ^ b[i])) -function client(userId, { encoded = true, dcs = [DC] } = {}) { - const auth = JSON.stringify({ token: "client-jwt", refreshToken: "client-refresh", userId, host: "https://api.trae.cn" }) - const doc = { "telemetry.machineId": "m".repeat(64), [`iCubeAuthInfo://icube.cloudide`]: encoded ? encode(auth) : auth } - for (const d of dcs) doc[`iCubeAuthInfo://icube-dc:${d}`] = "device-key-pair" - writeFileSync(file, JSON.stringify(doc)) +function client(userId, opts) { + clientFile(file, userId, opts) } async function checkIn(auth = signedIn()) { @@ -122,6 +128,40 @@ test("a client file that can't be made out names no device", async () => { plugins(await checkIn()) }) +// A machine can hold more than one Trae CN client profile (Trae CN and +// TRAE SOLO CN both write one, and so does a client started with its own +// --user-data-dir). Each profile's storage.json names the account that +// profile is signed in as, and that account's device — so two accounts can +// each have a real client's device, which is what a check-in needs. The +// plugin read only the first profile, and gave up on all of them the moment +// one named an account it wasn't looking for. +test("each account finds its own profile's client device, not the first profile's", async () => { + const other = join(dir, "other.json") + _internal.ownClient.paths = () => [file, other] + clientFile(file, "u-1", { dcs: [DC] }) + clientFile(other, "u-2", { dcs: ["7654321098765432"] }) + // u-2's device is in the second profile: reading only the first said no + expect((await checkIn(signedIn({ uid: "u-2" }))).get("x-device-id")).toBe("7654321098765432") + // and u-1's is still in the first + expect((await checkIn(signedIn({ uid: "u-1" }))).get("x-device-id")).toBe(DC) +}) + +test("a profile signed in as someone else doesn't hide a later profile's device", async () => { + const other = join(dir, "other.json") + _internal.ownClient.paths = () => [file, other] + clientFile(file, "someone-else", { dcs: [DC] }) + clientFile(other, "u-2", { dcs: ["7654321098765432"] }) + expect((await checkIn(signedIn({ uid: "u-2" }))).get("x-device-id")).toBe("7654321098765432") +}) + +test("a profile that can't be read doesn't hide a later profile's device", async () => { + const other = join(dir, "other.json") + _internal.ownClient.paths = () => [file, other] + writeFileSync(file, "{not json") + clientFile(other, "u-2", { dcs: ["7654321098765432"] }) + expect((await checkIn(signedIn({ uid: "u-2" }))).get("x-device-id")).toBe("7654321098765432") +}) + test("no client on this machine: the account's own device, as before", async () => { plugins(await checkIn()) }) @@ -145,33 +185,53 @@ test("where each OS keeps the client's storage.json", () => { // the paths are joined with this system's separator: the composition is // what is checked, so they are read as one system spells them const same = (ps) => ps.map((x) => x.replaceAll(sep, "/")) - expect(same(p("darwin", "/Users/a", {}))).toEqual(["/Users/a/Library/Application Support/Trae CN/User/globalStorage/storage.json"]) + // a profile is the IDE's, TRAE SOLO CN's, or the trae-cn folder some + // installs use: each is a client of the same realm with its own sign-in + expect(same(p("darwin", "/Users/a", {}))).toEqual([ + "/Users/a/Library/Application Support/Trae CN/User/globalStorage/storage.json", + "/Users/a/Library/Application Support/TRAE SOLO CN/User/globalStorage/storage.json", + ]) expect(same(p("win32", "/h", { APPDATA: "/h/Roam" }))).toEqual([ "/h/Roam/Trae CN/User/globalStorage/storage.json", + "/h/Roam/TRAE SOLO CN/User/globalStorage/storage.json", "/h/Roam/trae-cn/User/globalStorage/storage.json", "/h/AppData/Roaming/Trae CN/User/globalStorage/storage.json", + "/h/AppData/Roaming/TRAE SOLO CN/User/globalStorage/storage.json", "/h/AppData/Roaming/trae-cn/User/globalStorage/storage.json", ]) - expect(same(p("linux", "/home/a", {}))[0]).toBe("/home/a/.config/trae-cn/User/globalStorage/storage.json") - expect(same(p("linux", "/home/a", { XDG_CONFIG_HOME: "/x" }))[0]).toBe("/x/trae-cn/User/globalStorage/storage.json") + // linux lists the same three profiles under .config, in the same order + expect(same(p("linux", "/home/a", {}))).toEqual([ + "/home/a/.config/Trae CN/User/globalStorage/storage.json", + "/home/a/.config/TRAE SOLO CN/User/globalStorage/storage.json", + "/home/a/.config/trae-cn/User/globalStorage/storage.json", + ]) + expect(same(p("linux", "/home/a", { XDG_CONFIG_HOME: "/x" }))).toEqual([ + "/x/Trae CN/User/globalStorage/storage.json", + "/x/TRAE SOLO CN/User/globalStorage/storage.json", + "/x/trae-cn/User/globalStorage/storage.json", + ]) // a root named twice is asked once: APPDATA the same as the home's own expect(same(p("win32", "/h", { APPDATA: "/h/AppData/Roaming" }))).toEqual([ "/h/AppData/Roaming/Trae CN/User/globalStorage/storage.json", + "/h/AppData/Roaming/TRAE SOLO CN/User/globalStorage/storage.json", "/h/AppData/Roaming/trae-cn/User/globalStorage/storage.json", ]) // the same folder spelled with another case, separator or a trailing one // is still that folder (the fix: string equality read it twice) - expect(same(p("win32", "/h", { APPDATA: "\\H\\APPDATA\\roaming\\" })).length).toBe(2) + expect(same(p("win32", "/h", { APPDATA: "\\H\\APPDATA\\roaming\\" })).length).toBe(3) // and a different APPDATA is a root of its own, beside the home's expect(same(p("win32", "/h", { APPDATA: "/other/Roam" }))).toEqual([ "/other/Roam/Trae CN/User/globalStorage/storage.json", + "/other/Roam/TRAE SOLO CN/User/globalStorage/storage.json", "/other/Roam/trae-cn/User/globalStorage/storage.json", "/h/AppData/Roaming/Trae CN/User/globalStorage/storage.json", + "/h/AppData/Roaming/TRAE SOLO CN/User/globalStorage/storage.json", "/h/AppData/Roaming/trae-cn/User/globalStorage/storage.json", ]) // no APPDATA at all: the home's own alone expect(same(p("win32", "/h", {}))).toEqual([ "/h/AppData/Roaming/Trae CN/User/globalStorage/storage.json", + "/h/AppData/Roaming/TRAE SOLO CN/User/globalStorage/storage.json", "/h/AppData/Roaming/trae-cn/User/globalStorage/storage.json", ]) }) diff --git a/packages/trae/package.json b/packages/trae/package.json index 7213b55..c414640 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.21", + "version": "0.2.22", "description": "OpenCode provider plugins for Trae: Trae CN (trae.cn) and Trae Global (trae.ai), free tier included, with Trae's own browser sign-in", "type": "module", "main": "./index.mjs",