usage: switched-off providers' accounts can be checked in, and Check in all (wxkwxk666 on X)

wxkwxk666 asked for two things on the Usage page. First, a provider
switched off should still show its accounts, at the bottom and folded,
so they can still be checked in each day. Second, one button should check
in every account at once.

- provider.OffCheckins (off_checkins.go) lists every account a
  checkiner reaches whose provider is switched off (Off, not Hidden).
  Each is a card with no windows. Nothing is read or asked for it. Its
  check-in result is matched by its own key, not by its name, since two
  sign-ins can share a name (plugins#254).
  GET /api/usage/checkins/off serves the list.
- The Usage page (plugins/usage) adds a "Switched off · n" line after
  the cards and the hidden line. It is folded until clicked. Each
  account shows today's check-in, and a Check in button when it isn't
  checked in yet. The button uses checkinnow.js's ciNowSend, which
  POSTs /api/usage/checkin-account.
- Check in all, at the head of the allowances, presses every account
  not checked in today, from the cards and from the switched-off line.
  It sends one checkin-account request per account, three at a time,
  shows "Checking in i/n…", then gives the counts (checkinPressSaid).
  When no account is due, it says so and sends nothing.
- Nothing switches a provider back on. The new strings are in zh,
  zh-TW, ja and de. Plugin files only: app.js is unchanged.
- docs/subsystems/provider-plugins.md says all of this.

Run, on mote:
- TestOffCheckinsListsSwitchedOffAccounts, in the fakeco plugin
  sandbox:
  - nothing is listed before the switch-off;
  - after it, two cards with distinct keys;
  - a press on one checks in exactly that account;
  - the provider stays off;
  - only the pressed card carries a result;
  - nothing is listed once the provider is switched on.
- go test ./internal/provider ./internal/gui, at this commit on
  origin/main 0fda3a1c1: gui ok; provider ok but for
  TestHostBuildsNoList, red on main already (#6479)
- gofmt
- go vet for darwin, linux (-tags nogui, ./...) and windows
- usage-checkin-all.test.cjs, in Chromium and WebKit, at 900 and
  420px, in en, zh, zh-TW, ja and de (20 of 20). It covers:
  - the line is folded, at the end, with its count;
  - opening it doesn't scroll;
  - a row's own press asks for that account only;
  - Check in all shows 0/2 while held, presses only the two due
    accounts, and POSTs nothing else (no provider switched on);
  - a second press asks nothing and says every account is in.
- 187 GUI files (the Usage page, panel, tray, settings and their
  neighbours), at the rebased head on mote: 3080 cases, 104 red in 16
  files. Those 16 run again on mote at origin/main 5a2d0ff47 and at
  this commit, under the same load: the same 12 files are red on both
  (checkin-now-account #6029, codex-auto-reset #4790, key-balance-card
  #6414, menu-scroll #5982, mobile-web #3952, old-webkit #6030,
  quota-refresh-order #6180, tray-cell-click #5215, usage-cards-hide
  #6294, usage-fold #4790, usage-hidden-way-back #6295,
  usage-range-times #6499, filed now). account-eye, i18n-keys,
  last-page and quota-warm pass on both in that rerun.
- That wide run found account-alias and account-eye red on an earlier
  draft: a fixture answering {} for the new endpoint made the page
  spread a non-array. The page now takes only an array.

Broken by hand:
- Without checkinAll's not-due skip, all 20 GUI cases go red.
- Without OffCheckins' check-in result (q.Checkin), the Go test goes
  red at off_checkins_test.go:56.
- Matching results by name (WithCheckins), as an earlier draft did,
  also went red.

Not tried: checking in a real switched-off vendor account through the
real app. The press is the existing CheckInAccount path, the same one
Settings' per-account Check in now already uses.
This commit is contained in:
yetone
2026-11-13 16:56:19 +08:00
parent 0fda3a1c12
commit 5d54a990d4
9 changed files with 431 additions and 0 deletions
+2
View File
@@ -62,6 +62,8 @@ The hook returns `{outcome, credit?, streak?, message?, until?}`. `outcome` is o
The switch is off by default. For a provider whose vendor magpie checked in through the plugin's fetch before (WorkBuddy, Trae CN, MiniMax Code, Qoder), it follows that vendor's existing switch until set on its own, and magpie's own check-in leaves that provider's accounts to the plugin (`pluginChecksIn`), so an account is never checked in twice.
A provider switched off (`Off`, not `Hidden`) has no Usage card and the loop leaves it alone (`leftAlone`), but its accounts can still be checked in by hand (wxkwxk666 on X). `GET /api/usage/checkins/off` lists them (`provider.OffCheckins` in [`off_checkins.go`](../../internal/provider/off_checkins.go)): one card per account a checkiner reaches, with no windows, nothing read or asked, its check-in marked by its own key rather than its name. The Usage page shows them in a *Switched off · n* line after the cards and the hidden line, folded until clicked (`renderQuotaOff` in `plugins/usage/page.js`), each account with what came of today's check-in and, when it isn't in, its own *Check in* (`ciNowSend` from `checkinnow.js`, `POST /api/usage/checkin-account`). *Check in all*, at the allowances' head (`checkinAll`), presses every account of the cards and of that line not checked in today (`checkinDue`, its per-account switch ignored as a press does), one `checkin-account` each, three at a time, saying how far it has got and then the counts (`checkinPressSaid`); with none due it says so and asks nothing. Neither switches a provider back on. See `TestOffCheckinsListsSwitchedOffAccounts`, `usage-checkin-all.test.cjs`.
Trae CN plugins without `auth.checkin` use [`trae_checkin.go`](../../internal/provider/trae_checkin.go) through the plugin's fetch: `/status`, then `/claim` while the check-in is on and today's isn't in. A claim answered 9074 (当前参与用户太多,请稍后再试) is saved as `own-app`, settled for the Beijing day like any answer other than `failed`: no retry ever got past it (#808), so neither the loop nor Check in now claims again that day, and the card, Settings, TUI and CLI say Trae CN refused the check-in (9074) and to check in in the Trae CN app, not that Trae pays only its own app, which Buddy Switch disproves (#1920). Since plugin 0.2.14 the account this machine's Trae CN desktop client is signed in as sends the client's own device id (the `iCubeAuthInfo://icube-dc:<id>` key of its `storage.json`, read only) with its check-in; every other account keeps its own device, and none is made up or rotated (#1705). 9074 on `/status`, and every other code, keep their previous handling. `own-app` is not a plugin hook outcome.
WorkBuddy's check-in ([`workbuddy_checkin.go`](../../internal/provider/workbuddy_checkin.go), built-in or through the plugin's fetch) tells a 401 apart. WorkBuddy's gateway answers a token it refuses with a bare HTML 401, which the card said only as "Unauthorized" and retried every 30 minutes. On a 401 from `/v2/billing/meter/checkin-activity-status` or `/daily-checkin`, the account's credits (`/billing/meter/get-user-resource-summary`) are read with the same headers: when they read, the sign-in is good and the check-in alone refuses magpie (WorkBuddy's own app sends its check-in, and only that, with an `X-Device-Token` from its security SDK), so it is saved as `own-app` for the day; when they don't, it is `failed` with "sign in to it again".
+6
View File
@@ -1427,6 +1427,12 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske
.us-hid .us-showall { align-self: flex-start; margin: 4px 0 0 2px; font-size: 11.5px; }
.us-hid .us-showall[hidden] { display: none; }
#quotaHid .row.stat .who { flex: 1 1 auto; min-width: 0; }
/* the switched-off providers' check-ins (wxkwxk666 on X) */
#quotaOff .row.stat .who { flex: 1 1 auto; min-width: 0; }
#quotaOff .wb-checkin { margin-top: 3px; }
#quotaOff .ci-acct { flex: none; margin-right: -4px; }
.quota-head .us-ciall { font-variant-numeric: tabular-nums; }
.quota-head .us-ciall:disabled { color: var(--muted); }
.row.stat.hid > :not(.us-unhide) { opacity: .55; }
.usage-note { padding: 10px 4px 2px; font-size: 11px; color: var(--faint); user-select: text; -webkit-user-select: text; }
.usage-clear { margin: 0; padding: 2px 0 6px; }
@@ -34,6 +34,7 @@ magpie.plugin("usage", (ctx) => {
<span class="label" data-t>Allowances</span>
<span class="grow"></span>
<button class="sess-pick quota-trend" id="quotaTrend" type="button" hidden></button>
<button class="text us-ciall" type="button" id="usageCheckinAll" hidden></button>
<button class="text us-toset" type="button" id="usageToSet"><span data-t>Settings</span> ›</button>
<button class="text rt-mask" id="usageMask" aria-pressed="false" data-tt="Mask the accounts on every page — email addresses and account names — for a screenshot to share"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.9 4.2A10.4 10.4 0 0 1 12 4c6.5 0 10 8 10 8a17.6 17.6 0 0 1-2.2 3.2M6.6 6.6C3.9 8.4 2 12 2 12s3.5 8 10 8a9.7 9.7 0 0 0 5.4-1.6M9.9 9.9a3 3 0 0 0 4.2 4.2M2 2l20 20"/></svg><span data-t>Hide accounts</span></button>
<div class="segs" id="quotaView" hidden></div>
@@ -41,6 +42,7 @@ magpie.plugin("usage", (ctx) => {
</div>
<section class="subscription-usage" id="subscriptionUsage"></section>
<div class="us-hid" id="quotaHid" hidden><button class="text us-hidline" type="button" aria-expanded="false"></button><div class="list" hidden></div></div>
<div class="us-hid us-off" id="quotaOff" hidden><button class="text us-hidline" type="button" aria-expanded="false"></button><div class="list" hidden></div></div>
<p class="usage-note" id="usageScope" data-t>Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.</p>
<section class="stats" id="stats"></section>
<section class="chart" id="chart"></section>
+24
View File
@@ -16,6 +16,12 @@ magpie.strings({
"{size} ({n} images)": "{size}({n} 张)",
"Show in Overview": "在概览中显示",
"Show {n} Hidden": "显示已隐藏的 {n} 个",
"Switched off · {n}": "已禁用 · {n}",
"Providers you switched off: magpie doesn't check them in by itself. Checking in here leaves them off.": "你禁用的供应商:magpie 不会自动给它们签到。在这里签到不会重新启用它们。",
"Check in all": "全部签到",
"Check in every account not checked in today, those of switched-off providers too; no provider is switched on": "给今天还没签到的每个账号签到,已禁用供应商的也包括在内;不会启用任何供应商",
"Checking in {i}/{n}…": "正在签到 {i}/{n}…",
"Every account is checked in today": "所有账号今天都已签到",
"Hide from Overview": "从概览中隐藏",
"Hide this account from Overview": "从概览中隐藏这个账号",
"Hide its balance from Overview": "从概览中隐藏它的余额",
@@ -285,6 +291,12 @@ magpie.strings({
"{size} ({n} images)": "{size}({n} 張)",
"Show in Overview": "在概覽中顯示",
"Show {n} Hidden": "顯示已隱藏的 {n} 個",
"Switched off · {n}": "已停用 · {n}",
"Providers you switched off: magpie doesn't check them in by itself. Checking in here leaves them off.": "你停用的供應商:magpie 不會自動為它們簽到。在這裡簽到不會重新啟用它們。",
"Check in all": "全部簽到",
"Check in every account not checked in today, those of switched-off providers too; no provider is switched on": "為今天還沒簽到的每個帳號簽到,已停用供應商的也包括在內;不會啟用任何供應商",
"Checking in {i}/{n}…": "正在簽到 {i}/{n}…",
"Every account is checked in today": "所有帳號今天都已簽到",
"Hide from Overview": "從概覽中隱藏",
"Hide this account from Overview": "從概覽中隱藏這個帳號",
"Hide its balance from Overview": "從概覽中隱藏它的餘額",
@@ -554,6 +566,12 @@ magpie.strings({
"{size} ({n} images)": "{size}({n} 枚)",
"Show in Overview": "概要に表示",
"Show {n} Hidden": "非表示の {n} 件を表示",
"Switched off · {n}": "オフ · {n}",
"Providers you switched off: magpie doesn't check them in by itself. Checking in here leaves them off.": "オフにしたプロバイダ:magpie は自動でチェックインしません。ここでチェックインしてもオフのままです。",
"Check in all": "すべてチェックイン",
"Check in every account not checked in today, those of switched-off providers too; no provider is switched on": "今日まだチェックインしていないすべてのアカウントをチェックインします。オフにしたプロバイダのものも含みます。プロバイダはオンになりません",
"Checking in {i}/{n}…": "チェックイン中 {i}/{n}…",
"Every account is checked in today": "すべてのアカウントは今日チェックイン済みです",
"Hide from Overview": "概要から隠す",
"Hide this account from Overview": "このアカウントを概要から隠す",
"Hide its balance from Overview": "残高を概要から隠す",
@@ -823,6 +841,12 @@ magpie.strings({
"{size} ({n} images)": "{size} ({n} Bilder)",
"Show in Overview": "In der Übersicht einblenden",
"Show {n} Hidden": "{n} ausgeblendete anzeigen",
"Switched off · {n}": "Ausgeschaltet · {n}",
"Providers you switched off: magpie doesn't check them in by itself. Checking in here leaves them off.": "Anbieter, die du ausgeschaltet hast: magpie checkt sie nicht selbst ein. Ein Check-in hier lässt sie ausgeschaltet.",
"Check in all": "Alle einchecken",
"Check in every account not checked in today, those of switched-off providers too; no provider is switched on": "Jedes heute noch nicht eingecheckte Konto einchecken, auch die ausgeschalteter Anbieter; kein Anbieter wird eingeschaltet",
"Checking in {i}/{n}…": "Einchecken {i}/{n}…",
"Every account is checked in today": "Alle Konten sind heute eingecheckt",
"Hide from Overview": "In der Übersicht ausblenden",
"Hide this account from Overview": "Dieses Konto in der Übersicht ausblenden",
"Hide its balance from Overview": "Sein Guthaben in der Übersicht ausblenden",
+103
View File
@@ -1328,6 +1328,7 @@ function hiddenQuotas() {
// renderQuotaHid: the line under the cards saying how many are hidden,
// opening them, each with Unhide, and Show all
function renderQuotaHid() {
renderQuotaOff();
const hb = $("#quotaHid");
const cards = hiddenQuotas(), rowList = hiddenRowList();
const hidden = [...cards, ...rowList];
@@ -1375,6 +1376,108 @@ function renderQuotaHid() {
hl.append(r);
}
}
// The switched-off providers' accounts a daily check-in reaches, in a
// folded line at the cards' end (wxkwxk666 on X: 禁用的供应商也要能签到):
// the page leaves their cards out and the daily check-in leaves them
// alone, so each is checked in here by hand, which switches nothing on.
// Asked again whenever the cards come in.
let offCards = [], offFor = null, offOpen = false, ciAllAt = "";
function loadOffCards() {
return api("usage/checkins/off").then((qs) => { offCards = Array.isArray(qs) ? qs : []; renderQuotaOff(); }, () => {});
}
// offSay: an off account's check-in, never saying the daily check-in
// will ask again, which it doesn't for a switched-off provider
function offSay(q) {
if (!checkinDue({ ...q, checkinOff: false })) return checkinRow(q, false, offCards);
const r = q.checkin, bad = r?.day === wbToday() && r.outcome === "failed";
const row = el("div", "wb-checkin"), say = el("span", "ci-say");
say.append(el("i", "ci-dot" + (bad ? " bad" : "")), el("span", "", t(bad ? "Check-in failed" : "Not checked in yet today") + (bad && r.msg ? " · " + r.msg : "")));
row.append(say);
return row;
}
function renderQuotaOff() {
if (quotas && quotas !== offFor) { offFor = quotas; loadOffCards(); }
const hb = $("#quotaOff");
hb.hidden = !offCards.length;
if (offCards.length) $("#quotaHead").hidden = false;
renderCheckinAll();
if (!offCards.length) return;
const line = hb.querySelector(".us-hidline"), hl = hb.querySelector(".list");
line.replaceChildren(el("span", "", t("Switched off · {n}", { n: offCards.length })), svg(CHEV, 11, 1.6));
line.title = t("Providers you switched off: magpie doesn't check them in by itself. Checking in here leaves them off.");
line.setAttribute("aria-expanded", String(offOpen));
line.onclick = () => { offOpen = !offOpen; renderQuotaOff(); };
hl.hidden = !offOpen;
hl.replaceChildren();
if (!offOpen) return;
for (const q of offCards) {
const r = el("div", "row stat acts us-offrow");
r.dataset.key = q.checkinKey;
r.append(icon(q.icon));
const who = el("div", "who");
who.append(el("div", "name", quotaName(q)), el("div", "sub", q.alias || q.user || ""), offSay(q));
r.append(who);
if (checkinDue({ ...q, checkinOff: false })) {
const b = el("button", "text ci-acct", t("Check in"));
b.type = "button";
b.onclick = async (e) => {
e.stopPropagation();
try { window.ciNowSend || await import(new URL("checkinnow.js", document.baseURI).href); } catch (err) { return statusErr(err); }
ciNowSend({ key: q.checkinKey, user: q.user }, q.checkinBy || "", (o) => {
b.disabled = !!o.busy;
b.classList.toggle("busy", !!o.busy);
if (!o.busy) loadOffCards();
});
};
r.append(b);
}
hl.append(r);
}
}
// renderCheckinAll: Check in all at the allowances' head, for every
// account any check-in reaches, a switched-off provider's too; it shows
// how far a press has got
function renderCheckinAll() {
const b = $("#usageCheckinAll");
b.hidden = ![...(quotas || []), ...offCards].some((q) => q.checkins && !q.from);
b.textContent = ciAllAt || t("Check in all");
b.disabled = !!ciAllAt;
b.classList.toggle("busy", !!ciAllAt);
b.title = t("Check in every account not checked in today, those of switched-off providers too; no provider is switched on");
b.onclick = (e) => { e.stopPropagation(); checkinAll(); };
}
// checkinAll checks in, three at a time, each account not checked in
// today, once each, leaving every switch as it is; what came of it is
// said once all have answered
async function checkinAll() {
if (ciAllAt) return;
const seen = new Set(), due = [];
for (const q of [...(quotas || []), ...offCards]) {
const k = (q.checkinBy || "") + "\0" + q.checkinKey;
if (q.from || !q.checkinKey || seen.has(k) || !checkinDue({ ...q, checkinOff: false })) continue;
seen.add(k);
due.push(q);
}
if (!due.length) return status(t("Every account is checked in today"), "ok");
const rs = [];
let n = 0;
const step = () => { ciAllAt = t("Checking in {i}/{n}…", { i: rs.length, n: due.length }); renderCheckinAll(); };
step();
const next = async () => {
while (n < due.length) {
const q = due[n++];
try { rs.push(await api("usage/checkin-account", { by: q.checkinBy || "", key: q.checkinKey })); } catch { rs.push({ outcome: "failed" }); }
step();
}
};
await Promise.all([next(), next(), next()]);
ciAllAt = "";
const said = checkinPressSaid(rs);
status(said.text, said.bad ? "err" : "ok");
renderCheckinAll();
loadQuotas();
loadOffCards();
}
// hideQuotaRows hides a card's rows from the Overview, or has them back:
// drawn at once, put back if the save fails
async function hideQuotaRows(keys, hide) {
@@ -0,0 +1,161 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// wxkwxk666 on X: a provider switched off still has accounts to check in
// each day, and checking every account in meant a press per vendor. The
// Usage page lists the switched-off providers' accounts a check-in reaches
// in a line at the cards' end, folded until clicked (GET
// /api/usage/checkins/off), each with its own Check in; and Check in all,
// at the allowances' head, presses every account not checked in today
// (POST /api/usage/checkin-account each), a switched-off provider's too,
// saying how far it has got and then what came of it. Nothing switches a
// provider on. Every language, wide and narrow, both engines; the API is
// faked.
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);
function serve(lang, w) {
const settings = { theme: "light", lang, quotaLeft: false, currency: "usd", workbuddyCheckin: true, traeCheckin: false };
const done = new Set(["fakeco|b"]);
const ci = (key, by, user) => done.has(key)
? { user, by, day: today, outcome: "claimed", credit: 10 }
: { user, by, day: "2026-10-01", outcome: "claimed", credit: 10 };
const quotas = () => [
{ provider: "workbuddy", name: "WorkBuddy", icon: "workbuddy-color", plan: "Pro", user: "lilei", windows: [{ name: "Credits", used: 8 }],
checkins: true, checkinKey: "wb|lilei", checkin: { user: "lilei", day: today, outcome: "claimed", credit: 50 } },
{ provider: "trae-cn", name: "Trae CN", plan: "Free", user: "hu", windows: [{ name: "Credits", used: 3 }],
checkins: true, checkinBy: "trae", checkinKey: "trae|hu", checkin: ci("trae|hu", "trae", "hu") },
{ provider: "codex", name: "Codex", icon: "openai", plan: "Plus", windows: [{ name: "5 hours", used: 20 }] },
];
const off = () => [
{ provider: "fakeco", name: "FakeCo", icon: "", user: "alice", windows: [], checkins: true, checkinBy: "plugin:fakeco", checkinKey: "fakeco|a", checkin: ci("fakeco|a", "plugin:fakeco", "alice") },
{ provider: "fakeco", name: "FakeCo", icon: "", user: "bob", windows: [], checkins: true, checkinBy: "plugin:fakeco", checkinKey: "fakeco|b", checkin: ci("fakeco|b", "plugin:fakeco", "bob") },
{ provider: "fakeco", name: "FakeCo", icon: "", user: "carol", windows: [], checkins: true, checkinBy: "plugin:fakeco", checkinKey: "fakeco|c", checkin: ci("fakeco|c", "plugin:fakeco", "carol") },
];
w.posts = [];
w.hold = null; // a promise the presses wait on, to see the progress
return async (route) => {
const req = route.request();
const url = new URL(req.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 = {};" });
// what a press could change: a check-in, a setting, a provider (not the window's own pings)
if (req.method() === "POST" && /^\/api\/(usage|settings|provider)/.test(url.pathname)) w.posts.push([url.pathname, req.postDataJSON()]);
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/usage/checkin-account") {
const { by, key } = req.postDataJSON();
if (w.hold) await w.hold;
done.add(key);
return json({ user: key, by, day: today, outcome: "claimed", asked: true, credit: 10 });
}
if (url.pathname === "/api/usage/checkins/off") return json(off());
if (url.pathname === "/api/usage/quotas") return json(quotas());
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
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: { line: "Switched off · 3", all: "Check in all", busy: "Checking in 0/2…", ok: "Claimed: 2 (+20 credits)", none: "Every account is checked in today", wait: "Not checked in yet today", in: "Check in" },
zh: { line: "已禁用 · 3", all: "全部签到", busy: "正在签到 0/2…", ok: "已领取:2(+20 积分)", none: "所有账号今天都已签到", wait: "今日尚未签到", in: "签到" },
"zh-TW": { line: "已停用 · 3", all: "全部簽到", busy: "正在簽到 0/2…", ok: null, none: "所有帳號今天都已簽到", wait: "今日尚未簽到", in: "簽到" },
ja: { line: "オフ · 3", all: "すべてチェックイン", busy: "チェックイン中 0/2…", ok: null, none: "すべてのアカウントは今日チェックイン済みです", wait: "今日はまだチェックインしていません", in: "チェックイン" },
de: { line: "Ausgeschaltet · 3", all: "Alle einchecken", busy: "Einchecken 0/2…", ok: null, none: "Alle Konten sind heute eingecheckt", wait: "Heute noch nicht eingecheckt", in: "Einchecken" },
};
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 Object.keys(words)) {
for (const width of [900, 420]) {
const w = words[lang];
test(`${engine} ${lang} ${width}: switched-off providers' check-ins, and Check in all`, 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, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], fake = {};
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, fake));
await page.goto("http://magpie.test/?view=usage");
// the switched-off line: after the cards and the hidden line, folded
const off = page.locator("#quotaOff");
await off.waitFor();
const line = off.locator(".us-hidline");
assert.equal((await line.innerText()).trim(), w.line);
assert.equal(await line.getAttribute("aria-expanded"), "false");
assert.equal(await off.locator(".list").isHidden(), true, "folded until clicked");
assert.equal(await page.evaluate(() => {
const a = document.querySelector("#subscriptionUsage"), b = document.querySelector("#quotaHid"), c = document.querySelector("#quotaOff");
return !!(a.compareDocumentPosition(c) & Node.DOCUMENT_POSITION_FOLLOWING) && !!(b.compareDocumentPosition(c) & Node.DOCUMENT_POSITION_FOLLOWING);
}), true, "the line is at the cards' end");
// nothing of FakeCo among the cards themselves
assert.equal(await page.locator("#subscriptionUsage", { hasText: "FakeCo" }).count(), 0);
// opened: each account, the one not in today with its own Check in
const y = await scrolls(page);
await line.click();
const rows = off.locator(".us-offrow");
await rows.first().waitFor();
assert.equal(await rows.count(), 3);
assert.equal(await scrolls(page), y, "opening moved the page");
assert.equal((await rows.nth(0).locator(".ci-say").innerText()).trim(), w.wait);
assert.equal(await rows.nth(0).locator(".ci-acct").count(), 1);
assert.equal((await rows.nth(0).locator(".ci-acct").innerText()).trim(), w.in);
assert.equal(await rows.nth(1).locator(".ci-acct").count(), 0, "bob is in today");
for (const r of await rows.all()) {
const box = await r.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= width + 1, `a row runs off the window: ${JSON.stringify(box)}`);
}
// carol's own Check in: that account alone, and read again
const reread = page.waitForRequest((r) => new URL(r.url()).pathname === "/api/usage/checkins/off");
await rows.nth(2).locator(".ci-acct").click();
await reread;
await page.waitForFunction(() => !document.querySelector('#quotaOff .us-offrow[data-key="fakeco|c"] .ci-acct'));
assert.deepEqual(fake.posts, [["/api/usage/checkin-account", { by: "plugin:fakeco", key: "fakeco|c" }]]);
fake.posts.length = 0;
// Check in all: only the accounts not in today, shown as it goes
const all = page.locator("#usageCheckinAll");
assert.equal((await all.innerText()).trim(), w.all);
let let_go;
fake.hold = new Promise((r) => { let_go = r; });
await all.click();
await page.waitForFunction((s) => document.querySelector("#usageCheckinAll")?.textContent === s, w.busy);
assert.equal(await all.isDisabled(), true);
let_go();
fake.hold = null;
await page.waitForFunction((s) => document.querySelector("#usageCheckinAll")?.textContent === s, w.all);
const pressed = fake.posts.filter(([p]) => p === "/api/usage/checkin-account").map(([, b]) => b.key).sort();
assert.deepEqual(pressed, ["fakeco|a", "trae|hu"]);
assert.deepEqual(fake.posts.filter(([p]) => p !== "/api/usage/checkin-account"), [], "nothing else was asked, no provider switched on");
if (w.ok) assert.equal((await page.locator("#status").innerText()).trim(), w.ok);
// read again: alice is in now, and no Check in is left
await page.waitForFunction(() => document.querySelectorAll("#quotaOff .ci-acct").length === 0);
assert.equal(await scrolls(page), y, "Check in all moved the page");
// pressed again with every account in: nothing asked, said so
const before = fake.posts.length;
await all.click();
await page.waitForFunction((s) => document.querySelector("#status")?.textContent === s, w.none);
assert.equal(fake.posts.length, before);
if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `usage-checkin-all-${engine}-${lang}-${width}.png`) });
assert.equal(await page.locator("select").count(), 0);
assert.deepEqual(errors, []);
});
}
}
}
+10
View File
@@ -389,6 +389,16 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
}
writeJSON(rw, rs[0])
})
// the accounts a check-in reaches whose provider is switched off, for
// the Usage page's folded Switched off group (wxkwxk666 on X): asks
// nothing, switches nothing on
mux.HandleFunc("GET /api/usage/checkins/off", func(rw http.ResponseWriter, r *http.Request) {
qs := provider.OffCheckins()
if qs == nil {
qs = []provider.SubscriptionQuota{}
}
writeJSON(rw, qs)
})
// what was left of each window over time, for the quota cards' curves
// (#651); ?days= back
mux.HandleFunc("GET /api/usage/quotas/history", func(rw http.ResponseWriter, r *http.Request) {
+57
View File
@@ -0,0 +1,57 @@
package provider
// OffCheckins are the accounts a daily check-in reaches whose provider
// the user switched off (wxkwxk666 on X: 禁用的供应商也要能签到). The Usage
// page leaves a switched-off provider's cards out (visibleQuotas), and the
// daily loop leaves it alone (leftAlone), so these are shown in a folded
// group of their own, each to be checked in by hand (CheckInAccount),
// which switches nothing back on.
//
// Each is a card with no windows: the provider, its name and icon, the
// account, and its check-in, found by its own key. No allowance is
// read and nothing is asked; a provider whose account was removed from
// magpie (Hidden) is not listed.
func OffCheckins() []SubscriptionQuota {
off := map[string]Provider{}
for _, p := range All() {
if p.Off && !p.Hidden {
off[p.ID] = p
}
}
if len(off) == 0 {
return nil
}
var qs []SubscriptionQuota
seen := map[string]bool{}
skip := checkinOff()
for _, c := range checkiners() {
var st map[string]WorkBuddyCheckin
for _, a := range c.accounts() {
p, ok := off[a.provider]
if !ok || !a.On || a.key == "" || seen[c.by+"\x00"+a.key] {
continue
}
seen[c.by+"\x00"+a.key] = true
name, icon := p.Name, p.Icon
if pp, ok := PluginOf(a.provider); ok {
name, icon = pluginCard(pp)
}
if name == "" {
name = a.provider
}
// marked by its own key, not by its name as WithCheckins does
// a card: two sign-ins can share a name (plugins#254)
q := SubscriptionQuota{Provider: a.provider, Name: name, Icon: icon, User: a.User, Windows: []QuotaWindow{},
Checkins: true, CheckinBy: c.by, CheckinKey: a.key, CheckinOff: skip[a.key]}
if st == nil {
st = shownCheckins(c.path)
}
if r, ok := st[a.key]; ok {
r.User, r.By = a.User, c.by
q.Checkin = &r
}
qs = append(qs, q)
}
}
return InProviderOrder(qs)
}
+66
View File
@@ -0,0 +1,66 @@
package provider
import (
"context"
"testing"
"time"
)
// A switched-off provider's accounts are still listed for their check-in
// (wxkwxk666 on X), each with its key; a press checks one in and leaves
// the provider off.
func TestOffCheckinsListsSwitchedOffAccounts(t *testing.T) {
keys := []string{"ck-claim", "ck-done"}
presses := pluginCheckinSandbox(t, keys...)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
if qs := OffCheckins(); len(qs) != 0 {
t.Fatalf("with nothing switched off: %+v", qs)
}
id := PluginID("fakeco")
if err := SetOff(id, true); err != nil {
t.Fatal(err)
}
qs := OffCheckins()
if len(qs) != len(keys) {
t.Fatalf("switched off: %d cards, want %d: %+v", len(qs), len(keys), qs)
}
if qs[0].CheckinKey == qs[1].CheckinKey {
t.Fatalf("two accounts, one key: %+v", qs)
}
for _, q := range qs {
if q.Provider != id || q.Name != "FakeCo" || q.User == "" || !q.Checkins || q.CheckinBy != "plugin:fakeco" || q.CheckinKey == "" || q.Windows == nil {
t.Fatalf("a card: %+v", q)
}
}
done := qs[len(qs)-1]
rs := CheckInAccount(ctx, done.CheckinBy, done.CheckinKey)
if len(rs) != 1 || rs[0].Outcome != CheckinDone && rs[0].Outcome != CheckinClaimed {
t.Fatalf("the press: %+v", rs)
}
if p := pressed(t, presses); len(p) != 1 {
t.Fatalf("pressed %q", p)
}
p, err := Find(id)
if err != nil {
t.Fatal(err)
}
if !p.Off {
t.Fatal("the press switched the provider back on")
}
// what came of it is on its card
for _, q := range OffCheckins() {
if (q.CheckinKey == done.CheckinKey) != (q.Checkin != nil) {
t.Fatalf("after the press of %s: %+v", done.CheckinKey, q)
}
}
if err := SetOff(id, false); err != nil {
t.Fatal(err)
}
if qs := OffCheckins(); len(qs) != 0 {
t.Fatalf("switched on again: %+v", qs)
}
}