From 7b52e3fc47c45e17fcbed6b42b2fa22acccdb140 Mon Sep 17 00:00:00 2001 From: Pursuit806 <35015883+jinyue806@users.noreply.github.com> Date: Tue, 10 Nov 2026 07:33:11 +0800 Subject: [PATCH] astudio: claim the daily reward without the desktop app (0.2.1) (#883) AStudio's daily reward is claimed without the desktop app: check-in completes the pending DAILY_REWARD_DIALOG popup (popupId + instanceKey only, once) and reports claimed/done only from today's GRANT ledger row. init-app and auth/bearer-token are no longer called from check-in. Version 0.2.1. Reviewed at 199d128f3 line by line (guards broken by hand, each turned a test red); e744ee9 is that code rebased onto main plus the version bump. index.mjs, index.test.mjs and README.md are byte-identical to 199d128f. Run at e744ee9 on mote: node --test 78/78; bun test 78/78 under TZ=UTC, America/Los_Angeles and Asia/Shanghai; bun scripts/check.mjs astudio ok. The author reports a real claim (+100) on two accounts at 2026-11-09 00:00:17 +08:00 with no desktop process; not repeated here (no AStudio account). Co-authored-by: jinyue806 --- packages/astudio/README.md | 12 +- packages/astudio/index.mjs | 224 +++++++++------------ packages/astudio/index.test.mjs | 345 ++++++++++++++++---------------- packages/astudio/package.json | 2 +- 4 files changed, 269 insertions(+), 314 deletions(-) diff --git a/packages/astudio/README.md b/packages/astudio/README.md index 848fe31..300ea26 100644 --- a/packages/astudio/README.md +++ b/packages/astudio/README.md @@ -11,7 +11,7 @@ AStudio 在 registry 里有两个入口,都保留([#614](https://github.com/ | 登录 | 浏览器登录(推荐,可多账号)、读取本机 AStudio 桌面端的登录态,或粘贴 `modelBearerToken` | 本机打开一个登录页:手机验证码、账号密码或微信扫码(含极验验证),不依赖桌面端 | | 适合 | 装了桌面端就复用登录态;没装也可以用浏览器登录(可多账号);两者都不方便时粘贴凭据 | 任何平台,没装桌面端也行 | | 模型端点 | `…/model-gateway/v1/responses`(OpenAI Responses,与桌面端一致) | `…/model-gateway/v1/chat/completions` | -| 每日积分 | 先读当日获得流水(与网页后台「获得明细」同源):有当日 GRANT 行即已发放,此时一个写请求都不发;流水为空才做一次会话活跃再读流水,流水不可用才退回余额差 + `client-popups/pending` 弹窗观测;不调用领取接口 | 调用 `client-popups` 领取每日奖励和新人礼包弹窗 | +| 每日积分 | 先读当日获得流水(与网页后台「获得明细」同源):有当日 GRANT 行即零写;没有才 `POST client-popups/complete` 领取 `DAILY_REWARD_DIALOG` 那一条,再以流水认定 | 调用 `client-popups` 领取每日奖励和新人礼包弹窗 | 两者用同一个 AStudio 账号时,读的是同一个 `points/balance`,模型调用也扣同一份积分:**每日登录积分是一个池子,装两个不会多一份。** 同一账号两边都登录只会重复显示同一笔余额。 @@ -54,11 +54,13 @@ same daily points balance. ## 每日签到(每日登录积分) -AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放(体验版 100 分/天,标准版 200,高级/畅享 400;活动期 31 天有效),客户端弹窗只做通知、没有领取接口。 +AStudio 有「每日登录积分」:账号面 `client-popups/pending` 里的 `DAILY_REWARD_DIALOG` 是**待领取的每日奖励**,桌面端点「知道了」时发 `POST client-popups/complete`,服务端随后记一笔「每日登录赠送」GRANT 流水(体验版 100 分/天,标准版 200,高级/畅享 400;活动期 31 天有效)。 -插件为此提供 magpie 的 `auth.checkin`,**先读当日获得流水**(`points/details?direction=CREDIT`,与网页后台「获得明细」同源,时间窗口按北京时间算):有 `GRANT` 且 reason 为「每日登录赠送」的入账即已发放——此时**一个写请求都不发**,连会话活跃也不做。流水为空才替账号做一次会话活跃(`POST tenant-app/v2/init-app`,带桌面端 `clientType` / `studioVersion` 身份头;缺 `clientType` 会被服务端以 `11001001` 拒绝),再读一次流水:新出现的 GRANT 行记为本次领取;流水接口不可用时退回余额差 + `client-popups/pending` 的 `DAILY_REWARD_DIALOG` 弹窗观测。余额涨了但流水还没入账也记领取(流水滞后);流水通畅、余额没涨、也没有当日弹窗则如实报「未观测到新发放」,**不谎称已签**。 +插件为此提供 magpie 的 `auth.checkin`,**先读当日获得流水**(`points/details?direction=CREDIT`,与网页后台「获得明细」同源,时间窗口按北京时间算):有 `GRANT` 且 reason 为「每日登录赠送」的入账即已发放——此时**零写**,连弹窗都不读。流水为空才去 pending 里精确筛选 `componentType === "DAILY_REWARD_DIALOG"`、`popupId` 为正整数、`instanceKey` 非空的条目,只对这一条 `POST client-popups/complete`(带桌面端 `clientType` / `studioVersion` 身份头;缺 `clientType` 会被服务端以 `11001001` 拒绝),再以流水认定结果:出现 GRANT 行记 `claimed`;流水尚未出现时短延迟复读一次,仍未出现就报 `failed`,**不拿余额差或弹窗文案当证据**。没有待领取弹窗则记 `inactive`。下载奖励、新人礼包、引导等非每日奖励弹窗一律不碰。 -签到**不调用** `client-popups/complete`:桌面端的「知道了」是桌面端的交互,插件只读弹窗、不替用户点掉。除 init-app 外,签到发出的都是只读请求。发放由服务端按账号会话判定,插件不能代替桌面端登录,也不保证某天一定有积分到账。签到需要账号带网页会话(浏览器登录与桌面端登录态方式默认有)。 +整个过程只用已保存的网页会话 Cookie,**不启动 AStudio 客户端、不启动浏览器、不发送模型对话**。签到需要账号带网页会话(浏览器登录与桌面端登录态方式默认有);会话过期会提示重新登录。 + +**实测记录(2026-11-09)**:两个 magpie 保存的账号(一个来自桌面端登录态、一个来自浏览器登录)当日 `points/details` 均为空、pending 各有 1 条 `DAILY_REWARD_DIALOG`;只发一次 `client-popups/complete` 后 2 秒内都出现 `GRANT 每日登录赠送 100`(余额 7900→8000、1100→1200),pending 清空。全程未启动 AStudio 客户端、浏览器或模型对话。仅验证了当天单次领取,跨日/重复领取等边界未宣称已验收。 ## 用量 @@ -68,7 +70,7 @@ AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃 - 模型调用:`POST https://astronstudio-api-volces-prod.xf-yun.com/model-gateway/v1/responses`(OpenAI Responses,`Authorization: Bearer`)——与 AStudio 桌面端写进 acode 内核的 `base_url` / `wire_api` 完全一致。 - 模型目录:`GET https://astronstudio-api-volces-prod.xf-yun.com/api/v1/model-manager/models`。 -- 账号面:`https://agent.xfyun.cn/xingchen-studio/`(`points/balance`、`membership/me`、`membership/plan-config`、`points/summary`、`client-popups/pending`,Cookie 会话鉴权 + `clientType` / `studioVersion` 身份头)。 +- 账号面:`https://agent.xfyun.cn/xingchen-studio/`(`points/balance`、`membership/me`、`membership/plan-config`、`points/summary`、`client-popups/pending`、`client-popups/complete`,Cookie 会话鉴权 + `clientType` / `studioVersion` 身份头)。 ## 风险提示 diff --git a/packages/astudio/index.mjs b/packages/astudio/index.mjs index 8dc684b..02434fd 100644 --- a/packages/astudio/index.mjs +++ b/packages/astudio/index.mjs @@ -21,13 +21,13 @@ // (magpie 的 oauth 方式,读不到时给出官网链接并轮询,等用户装好登录); // ③粘贴 modelBearerToken。目录与思考档位按账号实时拉取(目录读取不计费)。 // -// AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放,客户端弹窗 -// 只做通知、没有领取接口。auth.checkin 先读当日获得流水(points/details -// direction=CREDIT,与网页后台「获得明细」同源):已有「每日登录赠送」GRANT 行 -// 即 done,此时一个写请求都不发;流水为空才补一次会话活跃(POST -// tenant-app/v2/init-app,复刻桌面端启动),再读一次流水。流水读失败退回余额差 + -// 弹窗观测。流水通畅、余额没涨、也无当日弹窗则记 inactive——宿主把 done 渲染成 -// 「今日已签到」,没发生的不能断言。 +// AStudio 有「每日登录积分」:账号面 client-popups/pending 里的 DAILY_REWARD_DIALOG +// 是待领取的每日奖励(不是通知)。桌面端点「知道了」时发 POST +// client-popups/complete,服务端随后记一笔「每日登录赠送」GRANT 流水。 +// auth.checkin 先读当日获得流水(points/details direction=CREDIT,与网页后台 +// 「获得明细」同源):已有 GRANT 行就 done、一个写请求都不发;没有才 complete +// 那一条每日奖励弹窗,再以流水认定结果。流水没出现就不算 done——宿主把 done +// 渲染成「今日已签到」,没发生的不能断言。 import { spawnSync } from "node:child_process" import { readFileSync } from "node:fs" @@ -54,6 +54,8 @@ const WEB_SIGNIN_WAIT_MS = 10 * 60 * 1000 // 等待「用户去装桌面端并登录」的窗口与轮询间隔。 const DESKTOP_POLL_MS = 2000 const DESKTOP_WAIT_MS = 5 * 60 * 1000 +// complete 每日奖励弹窗后等入账的一次复读间隔(只复读一次,不重复 complete)。 +const CHECKIN_LEDGER_RETRY_MS = 1500 const REGISTRY_KEY = "HKCU\\Software\\AStudioStorage" const REGISTRY_PREFIXES = ["Production", "Canary", "Development"] @@ -414,7 +416,7 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir // 当日「每日登录赠送」入账流水。网页后台的获得明细(points/details // direction=CREDIT)是权威数据源:发放一旦发生就有 GRANT 行,不管由哪个 - // 端触发(桌面端 init-app、服务端午夜批量),都比「余额差+弹窗」可靠。 + // 端触发(桌面端 complete 弹窗、服务端批量),都是唯一可信的到账证据。 async function readDailyGrantLedger(session) { const now = nowMsImpl() const query = `pageNum=1&pageSize=50&direction=CREDIT&startTime=${encodeURIComponent(cstStamp(cstDayStart(now)))}&endTime=${encodeURIComponent(cstStamp(now))}` @@ -476,20 +478,32 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir return await studioJson("client-popups/pending", { session, fetchImpl, operation: "每日奖励弹窗" }) } - // 桌面端启动时的两个 POST 里,签到只复刻 init-app(租户初始化)。另一个 - // auth/bearer-token 会换发 modelBearerToken;2026-11-06 实测新旧 token 并存 - // (换发后旧 token 仍可用),但签到没有换发需求,多换一次只是白白轮换, - // 故仍不调用——浏览器登录自己需要 key 时才换。失败不塌方,但原因要收集 - // 起来交给上层,否则用户分不清「POST 失败」和「今天确实没发」。 - async function desktopLogin(session) { - const warnings = [] - try { - await studioJson("tenant-app/v2/init-app", { session, fetchImpl, method: "POST", operation: "租户初始化" }) - } catch (error) { - if (error?.signIn === "expired") throw error - warnings.push(`init-app ${error?.message ?? "失败"}`) - } - return { warnings } + // 只认桌面端 complete 契约能接受的每日奖励弹窗:componentType 精确匹配, + // popupId 为正整数,instanceKey 为非空字符串。其它弹窗(下载奖励、新人礼包、 + // 引导)一律不碰。 + function pickDailyRewardPopup(popups) { + if (!Array.isArray(popups)) return null + return ( + popups.find( + (item) => + item?.componentType === "DAILY_REWARD_DIALOG" && + Number.isSafeInteger(item.popupId) && + item.popupId > 0 && + typeof item.instanceKey === "string" && + item.instanceKey.trim().length > 0, + ) ?? null + ) + } + + // 桌面端「知道了」按钮对应的写请求:完成这一条每日奖励弹窗。 + async function completeDailyRewardPopup(session, popup) { + return await studioJson("client-popups/complete", { + session, + fetchImpl, + method: "POST", + operation: "每日奖励领取", + body: { popupId: popup.popupId, instanceKey: popup.instanceKey }, + }) } return { @@ -746,10 +760,9 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir windows, } }, - // 「每日登录积分」:服务端在当天账号会话首次活跃时发放,客户端没有领取 - // 接口(DAILY_REWARD_DIALOG 弹窗只做通知)。先读当日获得流水:已有当日 - // GRANT 行就 done、一个写请求都不发;流水为空才复刻桌面端启动的 init-app, - // 再读一次流水(流水读不到才退回余额差 + 弹窗观测)。 + // 「每日登录积分」:pending 里的 DAILY_REWARD_DIALOG 是待领取的每日奖励, + // 桌面端「知道了」按钮发 POST client-popups/complete。先读当日获得流水: + // 已有 GRANT 行就 done、零写;没有才 complete 这一条弹窗,再以流水认定。 async checkin(getAuth) { const auth = await getAuth() if (auth?.type !== "api" || !auth.key) return {} @@ -767,7 +780,6 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir if (config?.dailyLoginEnabled === false) { return { outcome: "inactive", message: "当前没有每日登录积分活动" } } - const warnings = [] // 星火 7 天内到期时给签到消息加一句提醒(按北京时间算日历天,不是 // 「剩不到 24 小时」)。余额是还没花掉的量,提示金额不能超过它。 const expiryNote = async (cap) => { @@ -783,132 +795,76 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir return `;注意 ${sparkExpiry.runsOut} 星火积分${daysLeft <= 0 ? "今天" : ` ${daysLeft} 天内`}到期` } - // 1) 流水优先:当日已有「每日登录赠送」GRANT 行 = 已发放。只读, - // 不写 init-app、不碰弹窗(11-06 实测服务端午夜批量先于签到)。 - let grant = null - let ledgerError = null - try { - grant = await readDailyGrantLedger(session) - } catch (error) { - if (error?.signIn === "expired") throw error - ledgerError = error + // 流水是唯一判据;读失败就没法证明结果,不猜。 + const readGrant = async () => { + try { + return { grant: await readDailyGrantLedger(session) } + } catch (error) { + if (error?.signIn === "expired") throw error + return { error } + } } - if (grant) { + const grantMessage = async (grant, via) => { const rawPoints = Number(grant.amount) const credit = Number.isFinite(rawPoints) && rawPoints > 0 ? rawPoints : 0 return { - outcome: "done", ...(credit > 0 ? { credit } : {}), - message: `每日登录积分 +${credit || 0} 已发放(流水实证,先于签到发生)${await expiryNote()}`, + message: `每日登录积分 +${credit || "?"}(${via},流水实证)${await expiryNote()}`, } } - // 2) 未发放:复刻桌面端启动的 init-app(签到唯一的写请求),再读一次 - // 流水。余额只用于「流水滞后」归因与旧判据兜底。 - let before = null - try { - before = await readBalance(session) - } catch (error) { - if (error?.signIn === "expired") throw error + // 1) 流水优先:当日已有「每日登录赠送」GRANT 行 = 已发放。只读,零写。 + const first = await readGrant() + if (first.error) { + return { outcome: "failed", message: first.error?.message ?? "当日获得流水读取失败" } } - // 旧判据(流水不可用)才需要基线弹窗:签到前就挂着的旧弹窗不能算今天。 - let hadDailyBefore = null - let baselineError = null - if (ledgerError) { - try { - const baseline = await readPopups(session) - hadDailyBefore = Array.isArray(baseline) && baseline.some((item) => item?.componentType === "DAILY_REWARD_DIALOG") - } catch (error) { - if (error?.signIn === "expired") throw error - baselineError = error - } + if (first.grant) { + return { outcome: "done", ...(await grantMessage(first.grant, "已发放")) } } - const login = await desktopLogin(session) - warnings.push(...login.warnings) - // 会话活跃 touch:与桌面端启动时同类只读请求。 - await studioJson("membership/me", { session, fetchImpl, operation: "会员信息" }).catch(() => null) - await studioJson("points/summary", { session, fetchImpl, operation: "积分汇总" }).catch(() => null) - await sleep(2500) - let after = null - try { - after = await readBalance(session) - } catch (error) { - if (error?.signIn === "expired") throw error - } - let grantAfter = null - try { - grantAfter = await readDailyGrantLedger(session) - } catch (error) { - if (error?.signIn === "expired") throw error - if (!ledgerError) ledgerError = error - } - if (grantAfter) { - const rawPoints = Number(grantAfter.amount) - const credit = Number.isFinite(rawPoints) && rawPoints > 0 ? rawPoints : 0 - return { - outcome: "claimed", - ...(credit > 0 ? { credit } : {}), - message: `每日登录积分 +${credit || "?"}(流水实证,本次签到触发)${await expiryNote(after?.sparkTotalBalance)}`, - } - } - const delta = - typeof before?.totalBalance === "number" && typeof after?.totalBalance === "number" - ? after.totalBalance - before.totalBalance - : null - const warnSuffix = warnings.length ? `(${warnings.join(" / ")})` : "" - if (!ledgerError) { - // 流水通畅但无 GRANT 行:余额涨了说明发放已到账、流水只是滞后; - // 余额没涨才是真的没发。不谎称已签。 - if (delta > 0) { - return { - outcome: "claimed", - credit: delta, - message: `每日登录积分 +${delta}(余额上涨,流水尚未入账)${await expiryNote(after?.sparkTotalBalance)}`, - } - } - return { outcome: "inactive", message: `未观测到新发放:当日获得流水无「每日登录赠送」记录${warnSuffix}` } - } - // ---- 流水读失败:退回旧判据(余额差+弹窗,只读)---- - if (typeof before?.totalBalance !== "number" || typeof after?.totalBalance !== "number") { - return { outcome: "failed", message: `积分余额读数不完整${warnSuffix}` } - } - let popups = null - let popupError = null + + // 2) 未发放:取 pending 里的每日奖励弹窗,只 complete 这一条。 + let popups try { popups = await readPopups(session) } catch (error) { if (error?.signIn === "expired") throw error - popupError = error + return { outcome: "failed", message: error?.message ?? "每日奖励弹窗读取失败" } } - if (delta > 0) { - return { - outcome: "claimed", - credit: delta, - message: `每日登录积分 +${delta}${await expiryNote(after?.sparkTotalBalance)}`, - } + const daily = pickDailyRewardPopup(popups) + if (!daily) { + // 没有待领取的每日奖励:不猜测、不写。 + return { outcome: "inactive", message: "当日没有待领取的每日登录积分" } } - // 基线读失败 ⇒ 不知道签到前是否已有弹窗,任何 done 结论都是猜的。 - if (hadDailyBefore === null) { - return { - outcome: "failed", - message: `签到前无法读取每日奖励弹窗,不能判定今日是否发放${baselineError?.message ? `:${baselineError.message}` : ""}${warnSuffix}`, - } + try { + await completeDailyRewardPopup(session, daily) + } catch (error) { + if (error?.signIn === "expired") throw error + return { outcome: "failed", message: `每日登录积分领取失败:${error?.message ?? "请求失败"}` } } - if (popupError) { - return { outcome: "failed", message: `${popupError?.message ?? "每日奖励弹窗读取失败"}${warnSuffix}` } + + // 3) 以流水认定;一次短延迟复读,不重复 complete。 + let after = await readGrant() + if (!after.error && !after.grant) { + await sleep(CHECKIN_LEDGER_RETRY_MS) + after = await readGrant() } - const daily = Array.isArray(popups) && popups.find((item) => item?.componentType === "DAILY_REWARD_DIALOG") - if (daily) { - const rawPoints = Number(daily.payload?.points) - const credit = Number.isFinite(rawPoints) && rawPoints >= 0 ? rawPoints : 0 - // payload 没有日期字段,签到前就挂着的那份无法断定是今天的。 - if (hadDailyBefore === true) { - return { outcome: "inactive", message: "余额无变化,且签到前已有未确认的每日奖励弹窗,无法判定今日是否发放" } - } - return { outcome: "done", ...(credit > 0 ? { credit } : {}), message: "每日登录积分已发放(服务端待通知弹窗)" } + if (after.error) { + return { outcome: "failed", message: `已提交领取,但当日获得流水读取失败:${after.error?.message ?? "未知错误"}` } + } + if (after.grant) { + return { outcome: "claimed", ...(await grantMessage(after.grant, "本次领取")) } + } + // complete 成功但流水没出现:不谎称已签,弹窗是否还在只用于说明原因。 + let stillPending = false + try { + stillPending = !!pickDailyRewardPopup(await readPopups(session)) + } catch (error) { + if (error?.signIn === "expired") throw error + } + return { + outcome: "failed", + message: `已提交领取,${stillPending ? "每日奖励弹窗仍在等待" : "弹窗已关闭"},但当日获得流水未出现`, } - // 余额没涨、也没有待通知弹窗:这套请求序列没触发发放,不谎称已签。 - return { outcome: "inactive", message: `未观测到新发放:余额无变化,也没有今日的每日奖励弹窗${warnSuffix}` } }, }, diff --git a/packages/astudio/index.test.mjs b/packages/astudio/index.test.mjs index 91a8d50..bc77bfe 100644 --- a/packages/astudio/index.test.mjs +++ b/packages/astudio/index.test.mjs @@ -544,9 +544,8 @@ test("usage spark window omits expiry when the ledger query fails", async () => assert.deepEqual(out.windows[1], { name: "星火积分", balance: 35000, aside: false }) }) -const checkinFetch = (balanceSequence, { popups = [], popupsSequence, identityAssert, popupFails = false, onComplete, onInitApp, ledger, ledgerSequence, ledgerFails = false, sparkLedger, sparkPages } = {}) => { +const checkinFetch = (balanceSequence, { popups = [], identityAssert, popupFails = false, onComplete, completeFails = false, ledger, ledgerSequence, ledgerFails = false, sparkLedger, sparkPages } = {}) => { let balanceCalls = 0 - let popupCalls = 0 let ledgerCalls = 0 return async (input, init) => { const url = String(input) @@ -583,20 +582,12 @@ const checkinFetch = (balanceSequence, { popups = [], popupsSequence, identityAs } if (url.includes("client-popups/pending")) { if (popupFails) return jsonRes({ flag: false, code: 11001001, desc: "客户端平台、版本或构建号无效", data: null }) - popupCalls += 1 - // popupsSequence 区分「基线读」与「签到后读」:前者看旧弹窗,后者看新发放。 - const data = popupsSequence - ? popupsSequence[Math.min(popupCalls - 1, popupsSequence.length - 1)] - : popups - return jsonRes({ flag: true, code: 0, data }) + return jsonRes({ flag: true, code: 0, data: popups }) } if (url.includes("client-popups/complete")) { + if (completeFails) return jsonRes({ flag: false, code: 11003002, desc: "每日奖励已领取" }, 409) if (onComplete) onComplete(JSON.parse(init.body)) - return jsonRes({ flag: true, code: 0, data: {} }) - } - if (url.includes("tenant-app/v2/init-app")) { - if (onInitApp) onInitApp() - return jsonRes({ flag: true, code: 0, data: {} }) + return jsonRes({ flag: true, code: 0, data: null }) } if (url.includes("membership/me") || url.includes("points/summary")) { return jsonRes({ flag: true, code: 0, data: {} }) @@ -618,68 +609,97 @@ const sparkGrantRow = (amount, expireTime) => ({ }) const dailyRewardPopup = [{ - popupId: 1, popupCode: "DAILY_LOGIN", popupType: "BANNER", componentType: "DAILY_REWARD_DIALOG", - priority: 100, instanceKey: "2026-11-04", payload: { points: "100" }, + popupId: 42, popupCode: "DAILY_LOGIN_REWARD_V1", popupType: "BANNER", componentType: "DAILY_REWARD_DIALOG", + priority: 100, instanceKey: "20261109", payload: { confirmText: "知道了", title: "今日登录积分已到账" }, }] +const otherRewardPopup = { + popupId: 7, popupCode: "CLIENT_DOWNLOAD_REWARD", popupType: "MODAL", componentType: "CLIENT_DOWNLOAD_REWARD_DIALOG", + priority: 300, instanceKey: "download", payload: {}, +} + const checkinAuth = { type: "api", key: "k", metadata: { session: { token: "T", ssoSessionId: "S", accountId: "A" } } } -test("check-in observes the balance delta around the session touch", async () => { - // 流水通畅但还没入账、余额涨了:发放已到账,记 claimed(不谎称 inactive)。 - const claimed = createPlugin({ fetchImpl: checkinFetch([7900, 8000], { ledger: [] }), sleepImpl: async () => {} }) - const out = await claimed.auth.checkin(async () => checkinAuth) - assert.equal(out.outcome, "claimed") - assert.equal(out.credit, 100) - assert.match(out.message, /余额上涨,流水尚未入账/) - - const unobserved = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { ledger: [] }), sleepImpl: async () => {} }) - const out2 = await unobserved.auth.checkin(async () => checkinAuth) - // 流水通畅但无当日 GRANT 行:没发放就是没发放,不谎称 done。 - assert.equal(out2.outcome, "inactive") - assert.match(out2.message, /未观测到新发放/) -}) - -test("check-in trusts the daily grant ledger as the authoritative signal", async () => { - // 11-06 实测:服务端午夜批量先于签到发放,纯余额差会误报 inactive; - // 流水里有当日 GRANT 行就是发了,谁触发的不影响结论。 - const plugin = createPlugin({ fetchImpl: checkinFetch([8000, 8000], { ledger: [dailyGrantRow()] }), sleepImpl: async () => {} }) - const out = await plugin.auth.checkin(async () => checkinAuth) - assert.equal(out.outcome, "done") - assert.equal(out.credit, 100) - assert.match(out.message, /流水实证,先于签到发生/) -}) - -test("check-in claims when the grant lands after the check-in started", async () => { - // 签到前读流水为空(还没发),init-app 之后才有 GRANT 行 ⇒ 本次触发。 +test("check-in completes the pending daily reward popup and claims from the ledger", async () => { + // 主路径:当日还没有 GRANT 行 ⇒ complete 这一条每日奖励弹窗 ⇒ 再读流水。 + const completed = [] const plugin = createPlugin({ - fetchImpl: checkinFetch([7900, 8000], { ledgerSequence: [[], [dailyGrantRow()]] }), + fetchImpl: checkinFetch([7900, 8000], { + popups: dailyRewardPopup, + ledgerSequence: [[], [dailyGrantRow()]], + onComplete: (body) => completed.push(body), + }), sleepImpl: async () => {}, }) const out = await plugin.auth.checkin(async () => checkinAuth) assert.equal(out.outcome, "claimed") assert.equal(out.credit, 100) - assert.match(out.message, /本次签到触发/) + assert.match(out.message, /本次领取/) + assert.deepEqual(completed, [{ popupId: 42, instanceKey: "20261109" }]) }) -test("check-in skips init-app when today's grant is already on the ledger", async () => { - // 流水已有当日 GRANT 行 ⇒ 只读,不再发 init-app(不给账号制造无谓写入)。 - let initCalls = 0 +test("check-in trusts the daily grant ledger and writes nothing when already granted", async () => { + // 当日已有 GRANT 行:done,一个弹窗不读、一个写请求不发。 let popupReads = 0 + let completeCalls = 0 const plugin = createPlugin({ fetchImpl: async (input, init) => { const url = String(input) - if (url.includes("client-popups")) popupReads += 1 - if (url.includes("points/details")) { - return jsonRes({ flag: true, code: 0, data: { items: [dailyGrantRow()] } }) - } - return checkinFetch([8000], { onInitApp: () => { initCalls += 1 } })(input, init) + if (url.includes("client-popups/pending")) popupReads += 1 + if (url.includes("client-popups/complete")) completeCalls += 1 + return checkinFetch([8000, 8000], { ledger: [dailyGrantRow()] })(input, init) }, sleepImpl: async () => {}, }) const out = await plugin.auth.checkin(async () => checkinAuth) assert.equal(out.outcome, "done") - assert.equal(initCalls, 0) + assert.equal(out.credit, 100) + assert.match(out.message, /已发放/) assert.equal(popupReads, 0) + assert.equal(completeCalls, 0) +}) + +test("check-in never reports done without a daily grant ledger row", async () => { + const completed = [] + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 7900], { popups: [], ledger: [], onComplete: (body) => completed.push(body) }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "inactive") + assert.notEqual(out.outcome, "done") + assert.equal(completed.length, 0) +}) + +test("check-in claims when the grant lands after the complete call", async () => { + // complete 之后才有 GRANT 行 ⇒ 本次领取。 + const completed = [] + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 8000], { + popups: dailyRewardPopup, + ledgerSequence: [[], [dailyGrantRow()]], + onComplete: (body) => completed.push(body), + }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "claimed") + assert.equal(completed.length, 1) +}) + +test("check-in completes only the daily reward popup among mixed popups", async () => { + const completed = [] + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 8000], { + popups: [otherRewardPopup, ...dailyRewardPopup], + ledgerSequence: [[], [dailyGrantRow()]], + onComplete: (body) => completed.push(body), + }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "claimed") + assert.deepEqual(completed, [{ popupId: 42, instanceKey: "20261109" }]) }) test("check-in message warns about spark points expiring within 7 days", async () => { @@ -714,11 +734,17 @@ test("check-in message stays quiet when spark expiry is far away", async () => { assert.doesNotMatch(out.message, /到期/) }) -test("check-in falls back to balance and popups when the ledger query fails", async () => { - // 流水读失败退回旧判据:余额差为正仍能 claimed。 - const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 8000], { ledgerFails: true }), sleepImpl: async () => {} }) +test("check-in fails without writes when the ledger query fails", async () => { + // 流水是唯一判据:读不到就不能猜,也不发 complete。 + const completed = [] + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 7900], { ledgerFails: true, popups: dailyRewardPopup, onComplete: (body) => completed.push(body) }), + sleepImpl: async () => {}, + }) const out = await plugin.auth.checkin(async () => checkinAuth) - assert.deepEqual(out, { outcome: "claimed", credit: 100, message: "每日登录积分 +100" }) + assert.equal(out.outcome, "failed") + assert.match(out.message, /获得明细|参数无效/) + assert.equal(completed.length, 0) }) test("check-in reports ineligible without a session and inactive without the campaign", async () => { @@ -743,157 +769,128 @@ test("check-in sends the desktop client identity on account requests", async () sleepImpl: async () => {}, }) await plugin.auth.checkin(async () => checkinAuth) - // 只数账号面 GET:POST(init-app)不参与这条断言。签到主路径(inactive 场景)= - // plan-config、签到前流水、签到前余额、touch(me+summary)、签到后余额、签到后流水。 + // 没有待领取弹窗的 inactive 路径只发只读 GET:plan-config、当日流水、pending。 const gets = seen.filter((item) => item.method !== "POST") - assert.equal(gets.length, 7) + assert.equal(gets.length, 3) + assert.ok(seen.every((item) => item.method !== "POST")) for (const { headers } of seen) { assert.equal(headers.clientType, process.platform === "darwin" ? "22" : "21") assert.equal(headers.studioVersion, STUDIO_VERSION) } }) -test("check-in reports done from popups when the ledger query fails", async () => { - // 弹窗 done 路径只属于退路:流水读失败 + 余额无变化 + 签到前无旧弹窗 + - // 签到后出现 DAILY_REWARD_DIALOG ⇒ 服务端发了但流水接口没读到。 +test("check-in reports inactive without completing when no daily popup is pending", async () => { + const completed = [] const plugin = createPlugin({ - fetchImpl: checkinFetch([7900, 7900], { popupsSequence: [[], dailyRewardPopup], ledgerFails: true }), - sleepImpl: async () => {}, - }) - const out = await plugin.auth.checkin(async () => checkinAuth) - assert.deepEqual(out, { outcome: "done", credit: 100, message: "每日登录积分已发放(服务端待通知弹窗)" }) -}) - -test("check-in omits credit when the daily reward popup has no usable points", async () => { - for (const payload of [{}, { points: "0" }, { points: "n/a" }]) { - const plugin = createPlugin({ - fetchImpl: checkinFetch([7900, 7900], { popupsSequence: [[], [{ ...dailyRewardPopup[0], payload }]], ledgerFails: true }), - sleepImpl: async () => {}, - }) - const out = await plugin.auth.checkin(async () => checkinAuth) - assert.deepEqual(out, { outcome: "done", message: "每日登录积分已发放(服务端待通知弹窗)" }) - } -}) - -test("check-in ignores other popup types", async () => { - const plugin = createPlugin({ - fetchImpl: checkinFetch([7900, 7900], { - popups: [{ ...dailyRewardPopup[0], componentType: "NEW_USER_DIALOG" }], - ledger: [], - }), + fetchImpl: checkinFetch([7900, 7900], { popups: [], ledger: [], onComplete: (body) => completed.push(body) }), sleepImpl: async () => {}, }) const out = await plugin.auth.checkin(async () => checkinAuth) assert.equal(out.outcome, "inactive") -}) - -test("check-in still falls back to popups when both ledger and popup query fail", async () => { - // 流水+弹窗都挂:退路里的退路,基线(第一次弹窗读)失败 ⇒ failed 不硬判。 - const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { popupFails: true, ledgerFails: true }), sleepImpl: async () => {} }) - const out = await plugin.auth.checkin(async () => checkinAuth) - assert.equal(out.outcome, "failed") - assert.match(out.message, /11001001|平台|版本/) -}) - -test("check-in never claims done when the baseline popup read fails", async () => { - // 退路里的场景:流水读失败 + 基线读失败 = 不知道签到前有没有旧弹窗, - // 签到后读到弹窗也不能判 done,更不能替用户把弹窗 complete 掉。 - let popupCalls = 0 - const completed = [] - const plugin = createPlugin({ - fetchImpl: async (input, init) => { - const url = String(input) - if (url.includes("membership/plan-config")) { - return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true } }) - } - if (url.includes("points/balance")) { - return jsonRes({ flag: true, code: 0, data: { totalBalance: 7900, activityBalance: 7900 } }) - } - if (url.includes("points/details")) { - return jsonRes({ flag: false, code: 11001001, desc: "参数无效" }) - } - if (url.includes("client-popups/pending")) { - popupCalls += 1 - if (popupCalls === 1) return jsonRes({ flag: false, code: 500, desc: "基线读失败" }) - return jsonRes({ flag: true, code: 0, data: dailyRewardPopup }) - } - if (url.includes("client-popups/complete")) { - completed.push(JSON.parse(init.body)) - return jsonRes({ flag: true, code: 0, data: {} }) - } - return jsonRes({ flag: true, code: 0, data: {} }) - }, - sleepImpl: async () => {}, - }) - const out = await plugin.auth.checkin(async () => checkinAuth) - assert.equal(out.outcome, "failed") - assert.match(out.message, /基线读失败/) + assert.match(out.message, /没有待领取/) assert.equal(completed.length, 0) }) -test("check-in leaves the daily popup alone on the ledger path", async () => { - // 流水能判定时不再碰弹窗:不读、更不替用户点「知道了」(那是桌面端的交互)。 - let popupReads = 0 - const completed = [] - const mock = checkinFetch([7900, 8000], { ledgerSequence: [[], [dailyGrantRow()]] }) - const plugin = createPlugin({ - fetchImpl: async (input, init) => { - const url = String(input) - if (url.includes("client-popups/pending")) popupReads += 1 - if (url.includes("client-popups/complete")) completed.push(JSON.parse(init.body)) - return mock(input, init) - }, - sleepImpl: async () => {}, - }) - const out = await plugin.auth.checkin(async () => checkinAuth) - assert.match(out.message, /本次签到触发/) - assert.equal(popupReads, 0) - assert.equal(completed.length, 0) +test("check-in only completes popups that match the daily reward contract", async () => { + // popupId 非正整数、instanceKey 为空:契约不成立,绝不 complete,也不判 done。 + for (const broken of [ + { ...dailyRewardPopup[0], popupId: 0 }, + { ...dailyRewardPopup[0], popupId: -1 }, + { ...dailyRewardPopup[0], instanceKey: " " }, + { ...dailyRewardPopup[0], instanceKey: undefined }, + ]) { + const completed = [] + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 7900], { popups: [broken], ledger: [], onComplete: (body) => completed.push(body) }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "inactive") + assert.equal(completed.length, 0) + } }) -test("check-in treats a pre-existing daily popup as unprovable on the fallback path", async () => { +test("check-in ignores other popup types and never completes them", async () => { const completed = [] const plugin = createPlugin({ fetchImpl: checkinFetch([7900, 7900], { - popupsSequence: [dailyRewardPopup, dailyRewardPopup], - ledgerFails: true, + popups: [otherRewardPopup, { ...dailyRewardPopup[0], componentType: "NEW_USER_DIALOG" }], + ledger: [], onComplete: (body) => completed.push(body), }), sleepImpl: async () => {}, }) const out = await plugin.auth.checkin(async () => checkinAuth) assert.equal(out.outcome, "inactive") - assert.match(out.message, /签到前已有/) - // 旧弹窗不属于今天,但也不替用户点掉:签到不再发 client-popups/complete。 assert.equal(completed.length, 0) }) -test("check-in surfaces init-app failures instead of hiding them", async () => { +test("check-in fails without writes when the popup query fails", async () => { + const completed = [] const plugin = createPlugin({ - fetchImpl: async (input) => { - const url = String(input) - if (url.includes("tenant-app/v2/init-app")) { - return jsonRes({ flag: false, code: 400, desc: "bad request" }, 400) - } - if (url.includes("membership/plan-config")) { - return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true } }) - } - if (url.includes("points/balance")) { - return jsonRes({ flag: true, code: 0, data: { totalBalance: 7900, activityBalance: 7900 } }) - } - if (url.includes("client-popups/pending")) return jsonRes({ flag: true, code: 0, data: [] }) - if (url.includes("points/details")) return jsonRes({ flag: true, code: 0, data: { total: 0, items: [] } }) - return jsonRes({ flag: true, code: 0, data: {} }) - }, + fetchImpl: checkinFetch([7900, 7900], { popupFails: true, ledger: [], onComplete: (body) => completed.push(body) }), sleepImpl: async () => {}, }) const out = await plugin.auth.checkin(async () => checkinAuth) - assert.equal(out.outcome, "inactive") - assert.match(out.message, /init-app/) - assert.match(out.message, /400/) + assert.equal(out.outcome, "failed") + assert.match(out.message, /11001001|平台|版本/) + assert.equal(completed.length, 0) }) -test("check-in never calls auth/bearer-token", async () => { +test("check-in does not report done when complete succeeds but no grant row appears", async () => { + // complete 成功 ≠ 到账:流水没有再复读一次,仍未出现就 failed。 + let sleeps = 0 + let ledgerReads = 0 + const completed = [] + const plugin = createPlugin({ + fetchImpl: async (input, init) => { + const url = String(input) + if (url.includes("points/details")) ledgerReads += 1 + return checkinFetch([7900, 7900], { + popups: dailyRewardPopup, + ledger: [], + onComplete: (body) => completed.push(body), + })(input, init) + }, + sleepImpl: async () => { sleeps += 1 }, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "failed") + assert.match(out.message, /流水未出现/) + assert.equal(completed.length, 1) + // complete 前 1 次 + complete 后立即 1 次 + 短延迟后 1 次;不无限重试。 + assert.equal(ledgerReads, 3) + assert.equal(sleeps, 1) +}) + +test("check-in reads the ledger once more after a short delay and claims", async () => { + const completed = [] + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 8000], { + popups: dailyRewardPopup, + ledgerSequence: [[], [], [dailyGrantRow()]], + onComplete: (body) => completed.push(body), + }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "claimed") + assert.equal(out.credit, 100) + assert.equal(completed.length, 1) +}) + +test("check-in surfaces complete failures and does not claim", async () => { + const plugin = createPlugin({ + fetchImpl: checkinFetch([7900, 7900], { popups: dailyRewardPopup, ledger: [], completeFails: true }), + sleepImpl: async () => {}, + }) + const out = await plugin.auth.checkin(async () => checkinAuth) + assert.equal(out.outcome, "failed") + assert.match(out.message, /每日奖励领取/) + assert.match(out.message, /已领取/) +}) + +test("check-in never calls init-app or auth/bearer-token", async () => { const paths = [] const plugin = createPlugin({ fetchImpl: async (input) => { @@ -912,7 +909,7 @@ test("check-in never calls auth/bearer-token", async () => { sleepImpl: async () => {}, }) await plugin.auth.checkin(async () => checkinAuth) - assert.ok(paths.some((p) => p.includes("tenant-app/v2/init-app"))) + assert.ok(!paths.some((p) => p.includes("tenant-app/v2/init-app"))) assert.ok(!paths.some((p) => p.includes("auth/bearer-token"))) }) diff --git a/packages/astudio/package.json b/packages/astudio/package.json index ee3b1b2..2f9fe08 100644 --- a/packages/astudio/package.json +++ b/packages/astudio/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-astudio-auth", - "version": "0.2.0", + "version": "0.2.1", "description": "AStudio (iFLYTEK Astron Studio) sign-in as an OpenCode/magpie provider: browser sign-in with one account-pool slot per account, or the desktop sign-in, over the Responses model gateway with live model catalog", "type": "module", "main": "./opencode.mjs",