From 8b8f91ba8f486754d2f701d038d9bd3c8ae6c91d Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 3 Oct 2026 23:48:54 +0800 Subject: [PATCH] =?UTF-8?q?usage:=20a=20WorkBuddy=20account's=20card=20say?= =?UTF-8?q?s=20how=20its=20daily=20check-in=20went,=20and=20turns=20it=20o?= =?UTF-8?q?n=20(#694,=20Dazzle-sys:=20=E7=AD=BE=E5=88=B0=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E6=94=BE=E5=88=B0=E7=94=A8=E9=87=8F=E5=8D=A1=E7=89=87=E4=B8=8A?= =?UTF-8?q?=EF=BC=8C=E5=8D=A1=E7=89=87=E6=98=BE=E7=A4=BA=E4=BB=8A=E6=97=A5?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E5=B7=B2=E7=BB=8F=E7=AD=BE=E5=88=B0=EF=BC=9B?= =?UTF-8?q?=E8=A6=81=E5=8E=BB=E8=AE=BE=E7=BD=AE=E9=87=8C=E7=9C=8B=E6=89=8D?= =?UTF-8?q?=E7=9F=A5=E9=81=93=E7=AD=BE=E6=B2=A1=E7=AD=BE=E6=98=AF=E4=B8=8D?= =?UTF-8?q?=E5=AF=B9=E7=9A=84)=20=E2=80=94=20the=20check-in=20ran=20and=20?= =?UTF-8?q?was=20kept=20(workbuddy-checkin.json)=20but=20only=20Settings'?= =?UTF-8?q?=20Daily=20check-in=20said=20anything=20of=20it.=20It=20runs=20?= =?UTF-8?q?in=20magpie=20for=20a=20moved=20account=20too=20(through=20the?= =?UTF-8?q?=20plugin's=20fetch,=20wbCheckinAccounts),=20so=20the=20card=20?= =?UTF-8?q?can=20say=20it=20for=20both.=20GET=20/api/usage/quotas=20now=20?= =?UTF-8?q?adds,=20uncached,=20to=20each=20WorkBuddy=20(China)=20account?= =?UTF-8?q?=20checked=20in=20each=20day=20(provider.WithCheckins,=20matche?= =?UTF-8?q?d=20by=20user=20name,=20an=20unnamed=20card=20only=20when=20the?= =?UTF-8?q?re=20is=20one=20account)=20checkins=20and=20its=20last=20record?= =?UTF-8?q?;=20each=20such=20account's=20meters=20end=20in=20a=20line=20wi?= =?UTF-8?q?th=20a=20dot:=20Checked=20in=20today=20+credit=20=C2=B7=20N-day?= =?UTF-8?q?=20streak=20(green),=20Not=20eligible=20for=20the=20daily=20che?= =?UTF-8?q?ck-in,=20No=20check-in=20event=20now,=20Check-in=20failed;=20ma?= =?UTF-8?q?gpie=20tries=20again=20later=20(red,=20the=20vendor's=20message?= =?UTF-8?q?=20in=20its=20tooltip),=20or=20Not=20checked=20in=20yet=20today?= =?UTF-8?q?=20(amber)=20/=20Auto=20check-in=20is=20off,=20with=20=C2=B7=20?= =?UTF-8?q?last=20checked=20in=20{day}.=20The=20card's=20first=20such=20li?= =?UTF-8?q?ne=20has=20Auto=20check-in,=20the=20same=20setting=20as=20Setti?= =?UTF-8?q?ngs'=20Daily=20check-in,=20which=20stays=20(POST=20/api/setting?= =?UTF-8?q?s/workbuddy-checkin,=20written=20as=20Codex's=20auto=20reset=20?= =?UTF-8?q?is),=20and=20Check=20in=20now=20while=20an=20account=20isn't=20?= =?UTF-8?q?in=20today=20(POST=20/api/usage/workbuddy-checkin,=20CheckInWor?= =?UTF-8?q?kBuddy,=20then=20the=20cards=20are=20read=20again).=20Another?= =?UTF-8?q?=20vendor's=20card=20has=20none=20of=20it;=20no=20native=20sele?= =?UTF-8?q?ct,=20no=20left=20stripe,=20the=20page=20doesn't=20move.=20zh?= =?UTF-8?q?=20strings=20added.=20usage-checkin.test.cjs=20(webkit,=20en/zh?= =?UTF-8?q?:=20three=20accounts'=20lines=20and=20states,=20none=20on=20Cod?= =?UTF-8?q?ex,=20the=20switch=20once=20and=20off,=20turned=20on=20with=20n?= =?UTF-8?q?o=20scroll=20and=20the=20line=20turning=20amber,=20Check=20in?= =?UTF-8?q?=20now=20posted=20and=20the=20cards=20re-read)=20fails=20on=20t?= =?UTF-8?q?he=20old=20code=20and=20passes;=20TestWorkBuddyCheckinOnTheCard?= =?UTF-8?q?=20covers=20the=20matching=20and=20that=20the=20cache=20isn't?= =?UTF-8?q?=20changed.=20credit-days,=20codex-auto-reset,=20quota-*,=20usa?= =?UTF-8?q?ge-arrange/fold/alert,=20settings-sections,=20tray-usages,=20ba?= =?UTF-8?q?lance-parts,=20click-scroll,=20add-sheet,=20removed-forget/hide?= =?UTF-8?q?=20and=20plugin-two-subs=20still=20pass.=20go=20vet,=20builds?= =?UTF-8?q?=20(darwin,=20GOOS=3Dlinux,=20GOOS=3Dwindows)=20and=20go=20test?= =?UTF-8?q?=20-tags=20nogui=20-count=3D1=20./...=20under=20a=20temp=20HOME?= =?UTF-8?q?=20pass.=20Not=20tried=20with=20a=20real=20WorkBuddy=20account.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gui/api.go | 16 +++ internal/gui/assets/app.css | 13 +++ internal/gui/assets/app.js | 92 +++++++++++++++- internal/gui/assets/i18n.js | 18 ++++ internal/gui/tests/usage-checkin.test.cjs | 114 ++++++++++++++++++++ internal/gui/usage.go | 16 ++- internal/provider/subscription_usage.go | 6 ++ internal/provider/workbuddy_checkin.go | 46 ++++++++ internal/provider/workbuddy_checkin_test.go | 37 +++++++ 9 files changed, 356 insertions(+), 2 deletions(-) create mode 100644 internal/gui/tests/usage-checkin.test.cjs diff --git a/internal/gui/api.go b/internal/gui/api.go index da8e77dc6..b0013b919 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -919,6 +919,22 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) + // whether WorkBuddy's daily check-in is pressed each day, the Usage + // card's toggle (#694), set on its own as Settings' is + mux.HandleFunc("POST /api/settings/workbuddy-checkin", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ On bool } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + s := settings.Load() + s.WorkBuddyCheckin = in.On + if err := settings.Save(s); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) // how large the window and the panel are drawn: Settings' choice and // Ctrl/Cmd +, − and 0 in either, set on its own so a key pressed while // the Settings page saves something else is never undone by it diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 603c6b297..583f5217f 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -597,6 +597,19 @@ body.window .field.solo { grid-column: auto; } .quota-resets .text { margin-left: auto; flex: none; font-size: 11px; padding: 2px 7px; } .subscription-card.several .quota-resets:not([hidden]) + .subscription-account { margin-top: 10px; padding-top: 9px; border-top: 1px solid var(--line); } .reset-ask .reset-idle { color: var(--amber); } +/* a WorkBuddy account's daily check-in on its Usage card (#694) */ +.wb-checkin { display: flex; align-items: center; gap: 8px; margin-top: 8px; font-size: 10.5px; color: var(--muted); font-variant-numeric: tabular-nums; } +.wb-checkin .ci-say { display: inline-flex; align-items: center; gap: 6px; min-width: 0; } +.wb-checkin .ci-say > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.wb-checkin .ci-dot { flex: none; width: 7px; height: 7px; border-radius: 50%; background: var(--faint); } +.wb-checkin .ci-dot.ok { background: var(--green); } +.wb-checkin .ci-dot.bad { background: var(--red); } +.wb-checkin .ci-dot.wait { background: var(--amber); } +.wb-checkin[data-state="ok"] .ci-say { color: var(--fg-2); } +.wb-checkin .text { flex: none; font-size: 11px; padding: 2px 7px; } +.wb-checkin .ci-auto { margin-left: auto; } +.subscription-card.several .wb-checkin { margin-bottom: 6px; } +.wb-checkin .ci-auto.on { background: color-mix(in srgb, var(--accent) 16%, transparent); color: var(--accent); } .quota-balance { display: flex; align-items: baseline; gap: 6px; font-size: 10.5px; color: var(--muted); } .quota-windows + .quota-balance { margin-top: 9px; } /* "Every model" at the end of the account's line, above its families */ diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 7562f5d92..fd5b86923 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -9265,6 +9265,9 @@ function renderQuotas() { // its tooltip; the curve and the rest only in full if (brief) meters.classList.add("brief"); card.append(meters); + // WorkBuddy's daily check-in, how this account's went, and the + // switch for it, on the card rather than only in Settings (#694) + if (sub.checkins) card.append(checkinRow(sub, sub === subs.find((x) => x.checkins), subs)); // what was left over time, against an even burn (#651) const curve = !brief && !sub.error && quotaCurve(sub); if (curve) card.append(curve); @@ -10310,6 +10313,93 @@ function autoResetButton(q, cls) { return b; } +// checkinRow is a WorkBuddy (China) account's daily check-in on its +// Usage card: today's (a Beijing day) done, with the credits and the +// streak, or why not, or the last day it was; the card's first such row +// also holds the switch, which is Settings' "Daily check-in", and a press +// for those not in yet today (#694, Dazzle-sys: 卡片显示今日是否已经签到). +function checkinRow(q, first, subs) { + const on = !!state.settings?.workbuddyCheckin; + const r = q.checkin; + const today = wbToday(); + const row = el("div", "wb-checkin"); + let kind = "", text; + const last = r && r.day !== today && (r.outcome === "claimed" || r.outcome === "done") ? t("last checked in {day}", { day: r.day }) : ""; + if (r && r.day === today) { + switch (r.outcome) { + case "claimed": + case "done": + kind = "ok"; + text = t("Checked in today") + (r.credit ? " +" + r.credit : "") + (r.streak ? " · " + t("{n}-day streak", { n: r.streak }) : ""); + break; + case "ineligible": + text = t("Not eligible for the daily check-in"); + break; + case "inactive": + text = t("No check-in event now"); + break; + default: + kind = "bad"; + text = t(on ? "Check-in failed; magpie tries again later" : "Check-in failed"); + } + } else { + kind = on ? "wait" : ""; + text = [t(on ? "Not checked in yet today" : "Auto check-in is off"), last].filter(Boolean).join(" · "); + } + row.dataset.state = kind || "none"; + const say = el("span", "ci-say"); + say.append(el("i", "ci-dot" + (kind ? " " + kind : "")), el("span", "", text)); + say.title = [t("WorkBuddy's daily check-in, as pressing 签到 in WorkBuddy does"), r?.outcome === "failed" ? r.msg : ""].filter(Boolean).join("\n"); + row.append(say); + if (!first) return row; + const auto = el("button", "text ci-auto" + (on ? " on" : ""), t("Auto check-in")); + auto.type = "button"; + auto.setAttribute("aria-pressed", String(on)); + auto.title = t(on ? "On: magpie checks each WorkBuddy (China) account in once a day, as Settings' Daily check-in does. Click to turn it off." + : "Check each WorkBuddy (China) account in once a day, as Settings' Daily check-in does"); + auto.onclick = async (e) => { + e.stopPropagation(); + auto.disabled = true; + try { + prefs = await writingPrefs(api("settings/workbuddy-checkin", { on: !on })); + state.settings = prefs; + status(t(on ? "Daily check-in turned off" : "Daily check-in turned on; magpie checks in within a few minutes"), "ok"); + renderQuotas(); + } catch (err) { + auto.disabled = false; + status(err.message, "err"); + } + }; + row.append(auto); + // pressed now: shown while an account isn't in today and could be + const due = subs.filter((x) => x.checkins && !(x.checkin?.day === today && x.checkin.outcome !== "failed")); + if (due.length) { + const now = el("button", "text ci-now", t("Check in now")); + now.type = "button"; + now.title = t("Press 签到 now for the accounts not checked in today"); + now.onclick = async (e) => { + e.stopPropagation(); + now.disabled = true; + now.classList.add("busy"); + try { + const rs = await api("usage/workbuddy-checkin", {}); + const bad = (rs || []).filter((x) => x.outcome === "failed").length; + status(bad ? t("Check-in failed for {n} account(s)", { n: bad }) : t("Checked in"), bad ? "err" : "ok"); + } catch (err) { + status(err.message, "err"); + } + loadQuotas(); + }; + row.append(now); + } + return row; +} + +// wbToday is today as WorkBuddy's check-in counts it, a Beijing day +function wbToday() { + return new Date(Date.now() + 8 * 3600e3).toISOString().slice(0, 10); +} + // askReset: spending a Codex account's reset can't be taken // back, so it asks first; then it says what came of it and reads the // usage again. @@ -14345,7 +14435,7 @@ async function renderUpdate(r, u) { // wbCheckinLine is how an account's last WorkBuddy check-in went: today's // (a Beijing day) with the credits and the streak, an earlier one by its day. function wbCheckinLine(r) { - const today = new Date(Date.now() + 8 * 3600e3).toISOString().slice(0, 10); + const today = wbToday(); if (r.day !== today) { return r.outcome === "claimed" || r.outcome === "done" ? t("{user} checked in {day}", { user: r.user, day: r.day }) : ""; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 4cee9d6d2..28992e165 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -318,6 +318,24 @@ const I18N = { "{user} is not eligible": "{user} 不符合签到条件", "{user}: no check-in event now": "{user}:当前没有签到活动", "{user} couldn't check in, tried again later": "{user} 签到失败,稍后重试", + "Checked in today": "今日已签到", + "last checked in {day}": "上次签到于 {day}", + "Not eligible for the daily check-in": "不符合签到条件", + "No check-in event now": "当前没有签到活动", + "Check-in failed; magpie tries again later": "签到失败,magpie 稍后重试", + "Check-in failed": "签到失败", + "Not checked in yet today": "今日尚未签到", + "Auto check-in is off": "自动签到已关闭", + "WorkBuddy's daily check-in, as pressing 签到 in WorkBuddy does": "WorkBuddy 的每日签到,和在 WorkBuddy 里点「签到」一样", + "Auto check-in": "自动签到", + "On: magpie checks each WorkBuddy (China) account in once a day, as Settings' Daily check-in does. Click to turn it off.": "已开启:magpie 每天替每个 WorkBuddy 国内版账号签到一次,与设置里的「每日自动签到」是同一个开关。点击关闭。", + "Check each WorkBuddy (China) account in once a day, as Settings' Daily check-in does": "每天替每个 WorkBuddy 国内版账号签到一次,与设置里的「每日自动签到」是同一个开关", + "Daily check-in turned off": "已关闭每日自动签到", + "Daily check-in turned on; magpie checks in within a few minutes": "已开启每日自动签到;magpie 几分钟内会签到", + "Check in now": "立即签到", + "Press 签到 now for the accounts not checked in today": "现在为今天还没签到的账号点「签到」", + "Check-in failed for {n} account(s)": "{n} 个账号签到失败", + "Checked in": "已签到", "Emails, phone numbers, ID and bank card numbers too": "邮箱、手机号、身份证号和银行卡号也一并脱敏", "Masked words": "脱敏词", "Your own words to keep from vendors, separated by commas": "不想让模型厂商看到的词,用逗号分隔", diff --git a/internal/gui/tests/usage-checkin.test.cjs b/internal/gui/tests/usage-checkin.test.cjs new file mode 100644 index 000000000..cf6e450e3 --- /dev/null +++ b/internal/gui/tests/usage-checkin.test.cjs @@ -0,0 +1,114 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #694 (Dazzle-sys): "put the check-in settings on the Usage card, and show +// on the card whether today's check-in is done; having to look in Settings +// to know whether it checked in is wrong". A WorkBuddy (China) account's +// card says how its daily check-in went — today's with the credits and the +// streak, not eligible, failed, or not yet with the last day it was — a +// dot beside it; the card's first such row has Auto check-in, the same +// switch as Settings' Daily check-in (POST /api/settings/workbuddy-checkin), +// and Check in now while an account isn't in today +// (POST /api/usage/workbuddy-checkin). Another vendor's card has none of it. +// Clicks never move the page. English and Chinese; the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const today = new Date(Date.now() + 8 * 3600e3).toISOString().slice(0, 10); +const quotas = () => [ + { provider: "workbuddy", name: "WorkBuddy", icon: "workbuddy-color", plan: "Pro", user: "李雷", windows: [{ name: "Credits", used: 8.9 }], + checkins: true, checkin: { user: "李雷", day: today, outcome: "claimed", credit: 50, streak: 3 } }, + { provider: "workbuddy", name: "WorkBuddy", icon: "workbuddy-color", plan: "Free", user: "韩梅梅", windows: [{ name: "Credits", used: 2 }], + checkins: true, checkin: { user: "韩梅梅", day: "2026-09-30", outcome: "claimed", credit: 20 } }, + { provider: "workbuddy", name: "WorkBuddy", icon: "workbuddy-color", plan: "Free", user: "Lucy", windows: [{ name: "Credits", used: 1 }], + checkins: true, checkin: { user: "Lucy", day: today, outcome: "ineligible" } }, + { provider: "codex", name: "Codex", icon: "openai", plan: "Plus", windows: [{ name: "5 hours", used: 20 }] }, +]; + +function serve(lang, asked) { + const settings = { theme: "light", lang, quotaLeft: false, currency: "usd", workbuddyCheckin: false }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/settings/workbuddy-checkin") { + asked.push(["set", route.request().postDataJSON()]); + settings.workbuddyCheckin = route.request().postDataJSON().on; + return json(settings); + } + if (url.pathname === "/api/usage/workbuddy-checkin") { + asked.push(["now"]); + return json([{ user: "韩梅梅", day: today, outcome: "claimed", credit: 20 }]); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/usage/quotas") return json(quotas()); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const words = { + en: { done: "Checked in today +50 · 3-day streak", off: "Auto check-in is off · last checked in 2026-09-30", wait: "Not checked in yet today · last checked in 2026-09-30", no: "Not eligible for the daily check-in", auto: "Auto check-in", now: "Check in now" }, + zh: { done: "今日已签到 +50 · 连续 3 天", off: "自动签到已关闭 · 上次签到于 2026-09-30", wait: "今日尚未签到 · 上次签到于 2026-09-30", no: "不符合签到条件", auto: "自动签到", now: "立即签到" }, +}; + +const scrolls = (page) => page.evaluate(() => [scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop)].join(",")); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + test(`${engine} ${lang}: the WorkBuddy card says how its check-in went`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 900, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], asked = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, asked)); + await page.goto("http://magpie.test/?view=usage"); + const card = page.locator(".subscription-card", { hasText: "WorkBuddy" }); + // every account in full, so each row is there to read + await card.locator(".wb-checkin").first().waitFor(); + const rows = card.locator(".wb-checkin"); + assert.equal(await rows.count(), 3, "one line an account"); + const says = (await rows.locator(".ci-say").allInnerTexts()).map((s) => s.trim()); + assert.deepEqual(says, [w.done, w.off, w.no]); + assert.deepEqual(await rows.evaluateAll((rs) => rs.map((r) => r.dataset.state)), ["ok", "none", "none"]); + assert.equal(await page.locator(".subscription-card", { hasText: "Codex" }).locator(".wb-checkin").count(), 0); + // the switch once, on the first row, off as Settings has it + const auto = card.locator(".ci-auto"); + assert.equal(await auto.count(), 1); + assert.equal((await auto.innerText()).trim(), w.auto); + assert.equal(await auto.getAttribute("aria-pressed"), "false"); + assert.equal(await card.locator(".ci-now").count(), 1, "韩梅梅 isn't in today"); + if (process.env.ARTIFACT_DIR) await card.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `usage-checkin-${engine}-${lang}.png`) }); + + // turned on from the card: saved as Settings' is, the page left where it was + const y = await scrolls(page); + await auto.click(); + await page.waitForFunction(() => document.querySelector(".ci-auto")?.getAttribute("aria-pressed") === "true"); + assert.deepEqual(asked, [["set", { on: true }]]); + assert.equal(await scrolls(page), y, "the toggle moved the page"); + assert.equal((await rows.nth(1).locator(".ci-say").innerText()).trim(), w.wait); + assert.equal(await rows.nth(1).getAttribute("data-state"), "wait"); + + // Check in now presses it, and the cards are read again + const before = asked.length; + const reread = page.waitForRequest((r) => new URL(r.url()).pathname === "/api/usage/quotas"); + await card.locator(".ci-now").click(); + await reread; + assert.deepEqual(asked.slice(before), [["now"]]); + assert.equal(await page.locator("select").count(), 0); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/usage.go b/internal/gui/usage.go index 8f9799e16..85915a92e 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -430,7 +430,21 @@ func usageRoutes(mux *http.ServeMux, w Windows) { } ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) defer cancel() - writeJSON(rw, provider.Quotas(ctx)) + // a WorkBuddy (China) account's card says how its daily check-in + // went (#694) + writeJSON(rw, provider.WithCheckins(provider.Quotas(ctx))) + }) + // WorkBuddy's daily check-in pressed now, from the Usage card, for + // each account not in yet today, as `magpie accounts checkin` does; the + // card is read again after + mux.HandleFunc("POST /api/usage/workbuddy-checkin", func(rw http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + rs := provider.CheckInWorkBuddy(ctx) + if rs == nil { + rs = []provider.WorkBuddyCheckin{} + } + writeJSON(rw, rs) }) // what was left of each window over time, for the quota cards' curves // (#651); ?days= back diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 8d6a76498..415a45454 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -96,6 +96,12 @@ type SubscriptionQuota struct { // Daily is a WorkBuddy account's credits used day by day, as magpie // counted them from its readings (credits_daily.go). Daily *DailyCredits `json:"daily,omitempty"` + // Checkins is set on a WorkBuddy (China) account that WorkBuddy's + // daily check-in is pressed for, and Checkin is how its last one went, + // nil before the first; never cached, added as the page asks + // (WithCheckins). + Checkins bool `json:"checkins,omitempty"` + Checkin *WorkBuddyCheckin `json:"checkin,omitempty"` } var subscriptionUsageCache struct { diff --git a/internal/provider/workbuddy_checkin.go b/internal/provider/workbuddy_checkin.go index 072c9ba8f..bfce7ab1c 100644 --- a/internal/provider/workbuddy_checkin.go +++ b/internal/provider/workbuddy_checkin.go @@ -37,6 +37,7 @@ import ( "net/http" "os" "path/filepath" + "slices" "sort" "strings" "sync" @@ -292,6 +293,51 @@ func WorkBuddyCheckins() []WorkBuddyCheckin { return out } +// WithCheckins is qs with each WorkBuddy (China) account's card told it +// is checked in each day and how its last check-in went, for the Usage +// page to say on the card (#694: having to look in Settings to know whether +// it checked in is wrong). It holds for a moved account too: magpie checks +// those in through the plugin's fetch. qs, which may be the usage cache, +// is left as it is; nothing is asked. +func WithCheckins(qs []SubscriptionQuota) []SubscriptionQuota { + return withCheckins(qs, wbCheckinAccounts(), readCheckins(wbCheckinPath())) +} + +func withCheckins(qs []SubscriptionQuota, accts []wbAccount, st map[string]WorkBuddyCheckin) []SubscriptionQuota { + var on []wbAccount + for _, a := range accts { + if a.On && a.creds.UID != "" { + on = append(on, a) + } + } + if len(on) == 0 { + return qs + } + out := slices.Clone(qs) + for i, q := range out { + if q.Provider != wbCN.id { + continue + } + var a *wbAccount + for j := range on { + // a card without an account's name is the only account's + if strings.EqualFold(on[j].User, q.User) || q.User == "" && len(on) == 1 { + a = &on[j] + break + } + } + if a == nil { + continue + } + out[i].Checkins = true + if r, ok := st[wbCheckinKey(*a)]; ok { + r.User = a.User + out[i].Checkin = &r + } + } + return out +} + // HasWorkBuddy says whether a WorkBuddy (China) account is signed in. func HasWorkBuddy() bool { return len(wbCheckinAccounts()) > 0 } diff --git a/internal/provider/workbuddy_checkin_test.go b/internal/provider/workbuddy_checkin_test.go index 729280ae4..7698c2d16 100644 --- a/internal/provider/workbuddy_checkin_test.go +++ b/internal/provider/workbuddy_checkin_test.go @@ -327,3 +327,40 @@ func TestWorkBuddyCheckinThroughPlugin(t *testing.T) { t.Fatalf("asked %v", paths) } } + +// The Usage page's WorkBuddy card says how each account's check-in went +// (#694): matched by its name, or the only account's on a card without +// one; another vendor's card, and an account not checked in, untouched, +// and the cards given (the usage cache) left as they were. +func TestWorkBuddyCheckinOnTheCard(t *testing.T) { + accts := []wbAccount{ + {Login: Login{User: "Ann", On: true}, site: wbCN, creds: wbCreds{UID: "u1"}}, + {Login: Login{User: "Bob", On: true}, site: wbCN, creds: wbCreds{UID: "u2"}}, + {Login: Login{User: "Off", On: false}, site: wbCN, creds: wbCreds{UID: "u3"}}, + } + st := map[string]WorkBuddyCheckin{ + "workbuddy|u1": {Day: "2026-10-03", Outcome: CheckinClaimed, Credit: 50, Streak: 3}, + "workbuddy|u3": {Day: "2026-10-03", Outcome: CheckinDone}, + } + qs := []SubscriptionQuota{{Provider: "workbuddy", User: "ann"}, {Provider: "workbuddy", User: "Bob"}, {Provider: "workbuddy", User: "Off"}, {Provider: "codex", User: "Ann"}} + got := withCheckins(qs, accts, st) + if !got[0].Checkins || got[0].Checkin == nil || got[0].Checkin.Credit != 50 || got[0].Checkin.User != "Ann" { + t.Fatalf("Ann: %+v", got[0]) + } + if !got[1].Checkins || got[1].Checkin != nil { + t.Fatalf("Bob, not checked in yet: %+v", got[1]) + } + if got[2].Checkins || got[2].Checkin != nil || got[3].Checkins || got[3].Checkin != nil { + t.Fatalf("an account off, or another vendor's: %+v %+v", got[2], got[3]) + } + if qs[0].Checkins || qs[0].Checkin != nil { + t.Fatal("the cards given were changed") + } + one := withCheckins([]SubscriptionQuota{{Provider: "workbuddy"}}, accts[:1], st) + if !one[0].Checkins || one[0].Checkin == nil { + t.Fatalf("one account, its card unnamed: %+v", one[0]) + } + if two := withCheckins([]SubscriptionQuota{{Provider: "workbuddy"}}, accts[:2], st); two[0].Checkins { + t.Fatalf("an unnamed card of two accounts: %+v", two[0]) + } +}