settings: Check in now for one account, its switch left as it is (xiaowu_95660)

xiaowu_95660 (Discord #general) asked for a way to check in one account
right now where its daily check-in switch is, without turning the switch.

- provider: a checkiner can be held to one account (`only`), and
  CheckInAccount(ctx, by, key) runs the same claim path once for it, for
  WorkBuddy, Trae, MiniMax, Qoder and every plugin with a check-in.
  CheckinOff is not read or written.
- gui: POST /api/usage/checkin-account {By, Key}. Settings' daily check-in
  group (built-ins and plugins) gets a "Check in now" row under its
  accounts. One account checks in at once; several open the app menu to
  pick one. The line says done, already checked in, not eligible,
  inactive, captcha, own-app or the failure. Only quotas reload, so
  Settings isn't redrawn under the button.
- The row and press live in the lazy checkinnow.js (core budget unchanged,
  three check-in comments cut). Once loaded it draws at once, so a redraw
  by the switch doesn't shorten the page for a moment.
- Strings in zh, zh-TW, ja, de. provider-plugins.md says how it works.

Run at befdfa72b (on origin/main d89f03aa9; 4ffd5b96d, the Cursor min line, landed after), on mote:
- gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  internal/provider and internal/gui ok.
- go test ./internal/provider ok. go test ./internal/gui: only
  TestMainWindowCorners/macOS_26_SDK red, the same at base de7953e3b
  (#3949, macOS 27 box).
- GUI, chromium and webkit, every language, narrow widths: checkin-now-
  account (new), checkin-account, plugin-checkin, checkin-reason,
  checkin-reason-once, checkin-early-done, usage-checkin,
  qoder-checkin-recheck, settings-groups, settings-lines-wrap,
  click-scroll, old-webkit, i18n-keys: 252 of 252 ok.
- Earlier at the pre-rebase head: warm-now webkit 440 en/ja/de click
  timeouts (#4322) and segs-press-redraw (#4566) red, both the same at the
  base.

Broken by hand: without the `only` branch in reaches(),
TestCheckinOneAccountNow goes red (every account is claimed). Loading
checkinnow.js after every redraw made checkin-account's "the switch moved
the page" red on webkit 420 zh/zh-TW/ja; fixed as above.

Not tried: the whole GUI suite (another session's full suite was running
on mote); a press against a real account (no real claim was made).
This commit is contained in:
yetone
2026-11-02 05:22:12 +08:00
parent 9f1734645a
commit e87140242b
10 changed files with 523 additions and 30 deletions
File diff suppressed because one or more lines are too long
+18 -15
View File
@@ -17867,13 +17867,9 @@ function creditsSwitch(q, cls, on, title, body, label, said) {
return b;
}
// checkinRow is a WorkBuddy (China), Trae CN or MiniMax Code 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 vendor's first such
// row also holds the switch, which is Settings' "Daily check-in", and a
// press for its accounts not in yet today (#694, Dazzle-sys:
// 卡片显示今日是否已经签到; Hu9956: TRAE cn 也有每天签到送100积分;
// #811, MiniMax Code's).
// checkinRow: an account's daily check-in on its Usage card, today's
// (Beijing) or why not; the vendor's first row holds its switch and press
// (#694, #811)
const CHECKINS = {
"": {
pref: "workbuddyCheckin", api: "workbuddy-checkin",
@@ -19781,8 +19777,8 @@ function renderSettings() {
$(`#${id}CheckinSegs`).replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s[on] ? "on" : "off", (v) => savePrefs({ ...keep, [on]: v === "on" })));
sub.textContent = [say, ...ciLines(s[on + "s"])].filter(Boolean).join(" · ");
sub.title = as;
list.querySelectorAll(".ci-acct").forEach((x) => x.remove());
list.append(...checkinAccountRows(s, id === "wb" ? "" : id));
list.querySelectorAll(".ci-acct, .ci-now-row").forEach((x) => x.remove());
list.append(...checkinAccountRows(s, id === "wb" ? "" : id), ...checkinNowRow(s, id === "wb" ? "" : id));
}
setWarmTab(warmTab);
// and the plugins that check in themselves, a row each, their tab shown
@@ -22544,8 +22540,7 @@ async function renderUpdate(r, u) {
if (kept && !pageShown) kept.remove();
}
// renderPluginCheckins draws a Daily check-in row for each plugin's
// provider that checks in itself (auth.checkin), under the Plugins tab.
// a Daily check-in row per plugin that checks in itself (auth.checkin)
function renderPluginCheckins(s) {
const ps = s.checkinPlugins || [];
$("#warmTab-plugins").hidden = !ps.length;
@@ -22568,13 +22563,21 @@ function renderPluginCheckins(s) {
}
}));
row.append(who, segBox);
return [row, ...checkinAccountRows(s, "plugin:" + p.id)];
return [row, ...checkinAccountRows(s, "plugin:" + p.id), ...checkinNowRow(s, "plugin:" + p.id)];
}).flat());
}
// checkinAccountRows are an Off/On row for each account vendor by checks
// in (#1902, magicLaLa: 根据每个账号设置是否开启自动签到), under its Daily
// check-in; none for a vendor of one account, whose switch is its own.
// one account's Check in now (xiaowu_95660), drawn by checkinnow.js
function checkinNowRow(s, by) {
if (!(s.checkinAccounts || []).some((a) => (a.by || "") === by)) return [];
const row = el("div", "row pref warm-now ci-now-row");
if (window.ciNowFill) ciNowFill(row, s, by);
else { row.hidden = true; import("./checkinnow.js").then(() => ciNowFill(row, s, by), () => {}); }
return [row];
}
// checkinAccountRows: an Off/On row per account under vendor by's Daily
// check-in when it has two or more (#1902, magicLaLa)
function checkinAccountRows(s, by) {
const accts = (s.checkinAccounts || []).filter((a) => (a.by || "") === by);
if (accts.length < 2) return [];
+89
View File
@@ -0,0 +1,89 @@
// Settings' Check in now for one account (xiaowu_95660: 手动签到一次):
// its row, the press and what it came to. app.js imports this when
// Settings draws a vendor's check-in (checkinNowRow), so it weighs nothing
// on the core.
// what each vendor's last press said, kept over Settings' redraws
const checkinNowSaid = {};
// ciNowFill draws Check in now into row, for vendor by's accounts: one
// account checked in once now, picked from the app menu when there are
// several, its switch and the account's left as they are; what came of it
// is said in the row.
window.ciNowFill = function (row, s, by) {
const accts = (s.checkinAccounts || []).filter((a) => (a.by || "") === by);
row.dataset.by = by;
const sub = el("div", "sub");
const who = el("div", "who");
who.append(el("div", "name", t("Check in now")), sub);
const box = el("div");
row.append(who, box);
const draw = () => {
const said = checkinNowSaid[by];
sub.textContent = said ? said.text : t("Checks one account in once now; the daily check-in's switches stay as they are");
sub.classList.toggle("err", !!said?.bad);
const b = el("button", "text ci-now-go", t(accts.length > 1 ? "Check in…" : "Check in"));
b.type = "button";
b.disabled = !!said?.busy;
b.classList.toggle("busy", !!said?.busy);
if (accts.length > 1) b.setAttribute("aria-haspopup", "menu");
b.onclick = (e) => {
e.stopPropagation();
if (accts.length === 1) return send(accts[0]);
if (b.classList.contains("open")) return closeProtoMenu();
openProtoMenu(b, accts.map((a) => ({ v: a.key, name: a.user || a.key, note: "", literalName: true })), null,
(k) => send(accts.find((a) => a.key === k)), "Check in which account", "sess-menu", "right");
};
box.replaceChildren(b);
};
const send = (a) => ciNowSend(a, by, (o) => { checkinNowSaid[by] = o; if (row.isConnected) draw(); });
draw();
row.hidden = false;
};
// ciNowSend checks account a of vendor by in once now and says, through
// say, how it went; no switch is changed.
window.ciNowSend = async function (a, by, say) {
if (!a) return;
const name = a.user || a.key;
say({ busy: true, text: t("Checking in {who}…", { who: name }) });
try {
const r = await api("usage/checkin-account", { by, key: a.key });
const said = checkinNowLine(r, name);
say(said);
status(said.text, said.bad ? "err" : "ok");
} catch (err) {
const text = t("Couldn't check in {who}: {why}", { who: name, why: t(err.message) });
say({ bad: true, text });
status(text, "err");
}
// the Usage cards' lines read again; Settings isn't drawn again under
// the button just pressed, which a redraw moved at 420px
loadQuotas();
};
// checkinNowLine is what one account's press came to: checked in now,
// already in today, not eligible or no event, its own app's, or failed,
// with the vendor's reason.
function checkinNowLine(r, who) {
const why = r?.msg ? " · " + r.msg : "";
switch (r?.outcome) {
case "claimed":
case "done":
if (r.again) return { text: t("{user}: {name} says already checked in; magpie asks again later", { user: who, name: checkinVendorName(r) }) };
if (r.outcome === "claimed" && r.asked) return { text: t("Checked in {who}", { who }) + (r.credit ? " +" + r.credit : "") + (r.streak ? " · " + t("{n}-day streak", { n: r.streak }) : "") };
return { text: t("{who} was already checked in today", { who }) };
case "ineligible":
return { text: t("{user} is not eligible", { user: who }) + why };
case "inactive":
return { text: t("{user}: no check-in event now", { user: who }) + why };
case "captcha":
return { text: t("{user} is asked for a captcha; check in in the app", { user: who }) };
case "own-app":
return { text: r.by === "trae"
? t("{user}: Trae CN refused this check-in (9074: too many taking part); check in in the Trae CN app", { user: who })
: t("{user}: {name} only gives check-in credits to its own app; check in in the {name} app", { user: who, name: checkinVendorName(r) }) };
default:
return { bad: true, text: t("Couldn't check in {who}: {why}", { who, why: r?.msg || t("Check-in failed") }) };
}
}
+36
View File
@@ -1270,6 +1270,15 @@ const I18N = {
"Daily check-in turned off": "已关闭每日自动签到",
"Daily check-in turned on; magpie checks in within a few minutes": "已开启每日自动签到;magpie 几分钟内会签到",
"Check in now": "立即签到",
"Checks one account in once now; the daily check-in's switches stay as they are": "现在给一个账号签到一次;每日签到的开关保持不变",
"Check in…": "签到…",
"Check in": "签到",
"Check in which account": "给哪个账号签到",
"Checking in {who}…": "正在给 {who} 签到…",
"Couldn't check in {who}: {why}": "{who} 签到失败:{why}",
"Checked in {who}": "{who} 已签到",
"{who} was already checked in today": "{who} 今天已经签过到了",
"No daily check-in reaches this account": "这个账号没有可用的每日签到",
"Press 签到 now for the accounts not checked in today": "现在为今天还没签到的账号点「签到」",
"Trae CN's daily check-in, as pressing 签到 in Trae does": "Trae CN 的每日签到,和在 Trae 里点「签到」一样",
"On: magpie checks each Trae CN account in once a day, as Settings' Daily check-in does. Click to turn it off.": "已开启:每天为每个 Trae CN 账号签到一次,与设置中的「每日自动签到」为同一开关。点击关闭。",
@@ -5640,6 +5649,15 @@ const I18N = {
"Daily check-in turned off": "已關閉每日自動簽到",
"Daily check-in turned on; magpie checks in within a few minutes": "已開啟每日自動簽到;magpie 幾分鐘內會簽到",
"Check in now": "立即簽到",
"Checks one account in once now; the daily check-in's switches stay as they are": "現在給一個帳號簽到一次;每日簽到的開關保持不變",
"Check in…": "簽到…",
"Check in": "簽到",
"Check in which account": "給哪個帳號簽到",
"Checking in {who}…": "正在給 {who} 簽到…",
"Couldn't check in {who}: {why}": "{who} 簽到失敗:{why}",
"Checked in {who}": "{who} 已簽到",
"{who} was already checked in today": "{who} 今天已經簽過到了",
"No daily check-in reaches this account": "這個帳號沒有可用的每日簽到",
"Press 签到 now for the accounts not checked in today": "現在為今天還沒簽到的帳號點「簽到」",
"Trae CN's daily check-in, as pressing 签到 in Trae does": "Trae CN 的每日簽到,和在 Trae 裡點「簽到」一樣",
"On: magpie checks each Trae CN account in once a day, as Settings' Daily check-in does. Click to turn it off.": "已開啟:每天為每個 Trae CN 帳號簽到一次,與設定中的「每日自動簽到」為同一開關。點選關閉。",
@@ -9979,6 +9997,15 @@ const I18N = {
"Daily check-in turned off": "毎日のチェックインをオフにしました",
"Daily check-in turned on; magpie checks in within a few minutes": "毎日のチェックインをオンにしました。magpie が数分以内にチェックインします",
"Check in now": "今すぐチェックイン",
"Checks one account in once now; the daily check-in's switches stay as they are": "1 つのアカウントを今すぐ 1 回チェックインします。毎日のチェックインのスイッチはそのままです",
"Check in…": "チェックイン…",
"Check in": "チェックイン",
"Check in which account": "チェックインするアカウント",
"Checking in {who}…": "{who} をチェックイン中…",
"Couldn't check in {who}: {why}": "{who} をチェックインできませんでした: {why}",
"Checked in {who}": "{who} をチェックインしました",
"{who} was already checked in today": "{who} は今日すでにチェックイン済みです",
"No daily check-in reaches this account": "このアカウントに使える毎日のチェックインはありません",
"Press 签到 now for the accounts not checked in today": "今日まだチェックインしていないアカウントで今すぐ「签到」を押します",
"Trae CN's daily check-in, as pressing 签到 in Trae does": "Trae CN の毎日のチェックイン(Trae で「签到」を押すのと同じ)",
"On: magpie checks each Trae CN account in once a day, as Settings' Daily check-in does. Click to turn it off.": "オン:magpie が各 Trae CN アカウントを 1 日 1 回チェックインします。設定の「毎日のチェックイン」と同じです。クリックでオフにします。",
@@ -14349,6 +14376,15 @@ const I18N = {
"Daily check-in turned off": "Täglicher Check-in ausgeschaltet",
"Daily check-in turned on; magpie checks in within a few minutes": "Täglicher Check-in eingeschaltet; magpie checkt in wenigen Minuten ein",
"Check in now": "Jetzt einchecken",
"Checks one account in once now; the daily check-in's switches stay as they are": "Checkt ein Konto jetzt einmal ein; die Schalter des täglichen Check-ins bleiben, wie sie sind",
"Check in…": "Einchecken…",
"Check in": "Einchecken",
"Check in which account": "Welches Konto einchecken",
"Checking in {who}…": "{who} wird eingecheckt…",
"Couldn't check in {who}: {why}": "{who} konnte nicht eingecheckt werden: {why}",
"Checked in {who}": "{who} eingecheckt",
"{who} was already checked in today": "{who} war heute schon eingecheckt",
"No daily check-in reaches this account": "Kein täglicher Check-in erreicht dieses Konto",
"Press 签到 now for the accounts not checked in today": "Jetzt 签到 für die heute noch nicht eingecheckten Konten drücken",
"Trae CN's daily check-in, as pressing 签到 in Trae does": "Täglicher Check-in von Trae CN, wie ein Klick auf 签到 in Trae",
"On: magpie checks each Trae CN account in once a day, as Settings' Daily check-in does. Click to turn it off.": "An: magpie checkt jedes Trae-CN-Konto einmal täglich ein, wie „Täglicher Check-in“ in den Einstellungen. Zum Ausschalten klicken.",
File diff suppressed because one or more lines are too long
@@ -0,0 +1,220 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// xiaowu_95660 on Discord: a manual "check in once now" beside the daily
// check-in switch. The last row of each check-in tab in Settings › Usage,
// Check in now, checks one account in at a press (POST
// /api/usage/checkin-account {by, key}); with several the press opens the
// app's menu of them (no <select>), an account left out of the daily
// check-in among them. What came of it stays on the row's line: checked in,
// already in today, not eligible, or failed with the vendor's reason in
// red. No switch is written. Chromium and WebKit, 1100 and 420 wide, en,
// zh, zh-TW, ja, de; 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 WHY = "500 Internal Server Error: the check-in service is unavailable right now, try again later";
// answers is the reply to each press by account key, in order
function serve(lang, asked, answers) {
const settings = { theme: "light", lang, quotaLeft: false, currency: "usd", workbuddy: true, workbuddyCheckin: true, trae: true, traeCheckin: false,
checkinAccounts: [
{ key: "workbuddy|u1", by: "", user: "Ann", on: true },
{ key: "workbuddy|u2", by: "", user: "Bob", on: false },
{ key: "trae-cn|u9", by: "trae", user: "Cat", on: true },
] };
return async (route) => {
const url = new URL(route.request().url());
const json = (data, status = 200) => route.fulfill({ status, 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.startsWith("/api/settings/")) {
asked.push(["write", url.pathname]);
return json(settings);
}
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/usage/checkin-account") {
const b = route.request().postDataJSON();
asked.push([b.by, b.key]);
const a = answers[b.key].shift();
return a.error ? json(a, 400) : json(a);
}
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json([]);
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 W = {
en: { name: "Check in now", go: "Check in", pick: "Check in…", head: "Check in which account", claimed: "Checked in Bob +50 · 3-day streak", already: "Bob was already checked in today", ineligible: "Ann is not eligible · new users only", failed: "Couldn't check in Ann: " + WHY, trae: "Checked in Cat +100" },
zh: { name: "立即签到", go: "签到", pick: "签到…", head: "给哪个账号签到", claimed: "Bob 已签到 +50 · 连续 3 天", already: "Bob 今天已经签过到了", ineligible: "Ann 不符合签到条件 · new users only", failed: "Ann 签到失败:" + WHY, trae: "Cat 已签到 +100" },
"zh-TW": { name: "立即簽到", go: "簽到", pick: "簽到…", head: "給哪個帳號簽到", claimed: "Bob 已簽到 +50 · 連續 3 天", already: "Bob 今天已經簽過到了", ineligible: "Ann 不符合簽到條件 · new users only", failed: "Ann 簽到失敗:" + WHY, trae: "Cat 已簽到 +100" },
ja: { name: "今すぐチェックイン", go: "チェックイン", pick: "チェックイン…", head: "チェックインするアカウント", claimed: "Bob をチェックインしました +50 · 3 日連続", already: "Bob は今日すでにチェックイン済みです", ineligible: "Ann は対象外です · new users only", failed: "Ann をチェックインできませんでした: " + WHY, trae: "Cat をチェックインしました +100" },
de: { name: "Jetzt einchecken", go: "Einchecken", pick: "Einchecken…", head: "Welches Konto einchecken", claimed: "Bob eingecheckt +50 · 3 Tage in Folge", already: "Bob war heute schon eingecheckt", ineligible: "Ann ist nicht berechtigt · new users only", failed: "Ann konnte nicht eingecheckt werden: " + WHY, trae: "Cat eingecheckt +100" },
};
const at = (loc) => loc.evaluate((b) => Math.round(b.getBoundingClientRect().top));
const sideways = (page) => page.evaluate(() => {
const out = [];
const de = document.documentElement, v = document.querySelector("#view-settings");
if (de.scrollWidth > de.clientWidth) out.push("page");
if (v.scrollWidth > v.clientWidth) out.push("view");
for (const r of document.querySelectorAll(".row.ci-now-row")) {
if (!r.offsetParent) continue;
const rr = r.getBoundingClientRect();
for (const e of r.querySelectorAll(".name, .sub, button")) {
const b = e.getBoundingClientRect();
if (b.right > rr.right + 0.5 || b.left < rr.left - 0.5) out.push(r.dataset.by + " " + e.className);
}
}
return out;
});
// still: until no box has scrolled for ten frames (a wheel's scroll in
// WebKit eases in after a fixed wait)
const still = (page) => page.evaluate(() => new Promise((done) => {
let last = "", same = 0;
const at = () => [scrollY, ...[...document.querySelectorAll("*")].map((e) => e.scrollTop)].join(",");
const f = () => { const now = at(); same = now === last ? same + 1 : 0; last = now; if (same >= 10) done(); else requestAnimationFrame(f); };
requestAnimationFrame(f);
}));
// wheelTo scrolls the page, as a reader would, until loc is in the
// window's upper half, so the menu it opens has room under it
async function wheelTo(page, loc, x) {
await page.mouse.move(x, 300);
for (let i = 0; i < 20; i++) {
await still(page);
const r = await loc.boundingBox();
if (r && r.y < 450) return;
await page.mouse.wheel(0, 200);
}
await still(page);
}
const launch = (engine) => engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" });
const subOf = (by) => `.ci-now-row[data-by="${by}"] .sub`;
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(W)) {
const w = W[lang];
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}px: Check in now checks one account in and says what came of it`, async (t) => {
const browser = await launch(engine);
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 = [], asked = [];
page.on("pageerror", (e) => errors.push(e.message));
const answers = {
"workbuddy|u2": [
{ user: "Bob", day: today, outcome: "claimed", credit: 50, streak: 3, asked: true },
{ user: "Bob", day: today, outcome: "claimed", credit: 50, streak: 3 },
],
"workbuddy|u1": [
{ user: "Ann", day: today, outcome: "ineligible", msg: "new users only", asked: true },
{ user: "Ann", day: today, outcome: "failed", msg: WHY, asked: true },
],
"trae-cn|u9": [{ user: "Cat", by: "trae", day: today, outcome: "claimed", credit: 100, asked: true }],
};
await page.route("**/*", serve(lang, asked, answers));
await page.goto("http://magpie.test/?view=settings&tab=usage");
const tab = page.locator("#warmTab-wb");
await tab.waitFor();
await tab.click();
const row = page.locator('#wbList .ci-now-row[data-by=""]');
await row.locator("button").waitFor();
assert.equal((await row.locator(".name").innerText()).trim(), w.name);
assert.equal(await page.evaluate(() => document.querySelector("#wbList").lastElementChild.classList.contains("ci-now-row")), true, "last in the tab, under each account's own row");
const go = row.locator("button");
assert.equal((await go.innerText()).trim(), w.pick);
assert.equal(await go.getAttribute("aria-haspopup"), "menu");
assert.deepEqual(await sideways(page), []);
await wheelTo(page, go, width / 2);
const y = await at(go);
// claimed now, for the account left out of the daily check-in
await go.click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.equal((await menu.locator(".pm-head").innerText()).trim(), w.head);
assert.deepEqual((await menu.locator(".pm-name").allInnerTexts()).map((s) => s.trim()), ["Ann", "Bob"]);
assert.deepEqual(asked, [], "the menu opening sent nothing");
await menu.locator(".pm-item").nth(1).click();
await page.waitForFunction(([s, want]) => document.querySelector(s)?.textContent === want, [subOf(""), w.claimed]);
assert.deepEqual(asked, [["", "workbuddy|u2"]], "that account alone, by its key");
assert.equal(await page.locator(subOf("") + ".err").count(), 0);
if (process.env.ARTIFACT_DIR) await page.locator("#wbList").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `checkin-now-${engine}-${lang}-${width}-claimed.png`) });
// already in today
await go.click();
await menu.locator(".pm-item").nth(1).click();
await page.waitForFunction(([s, want]) => document.querySelector(s)?.textContent === want, [subOf(""), w.already]);
// not eligible, with the vendor's reason
await go.click();
await menu.locator(".pm-item").nth(0).click();
await page.waitForFunction(([s, want]) => document.querySelector(s)?.textContent === want, [subOf(""), w.ineligible]);
assert.equal(await page.locator(subOf("") + ".err").count(), 0);
// failed: the reason, in red, on the line and in the status
await go.click();
await menu.locator(".pm-item").nth(0).click();
await page.waitForFunction((s) => document.querySelector(s + ".err"), subOf(""));
assert.equal((await page.locator(subOf("")).innerText()).trim(), w.failed);
assert.ok((await page.locator("#status").textContent()).includes("check-in service is unavailable"));
assert.equal(await go.isDisabled(), false, "pressable again");
if (process.env.ARTIFACT_DIR) await page.locator("#wbList").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `checkin-now-${engine}-${lang}-${width}-failed.png`) });
const settled = () => page.evaluate(() => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(ok))));
await settled();
assert.ok(Math.abs(await at(go) - y) <= 1, `a click moved the page: the button went from ${y} to ${await at(go)}`);
assert.deepEqual(await sideways(page), []);
// Trae CN: one account, checked in at a press, its switch off and left off
await page.locator("#warmTab-trae").click();
const trow = page.locator('#traeList .ci-now-row[data-by="trae"]');
await trow.locator("button").waitFor();
await wheelTo(page, trow.locator("button"), width / 2);
assert.equal((await trow.locator("button").innerText()).trim(), w.go);
assert.equal(await trow.locator("button").getAttribute("aria-haspopup"), null);
await trow.locator("button").click();
await page.waitForFunction(([s, want]) => document.querySelector(s)?.textContent === want, [subOf("trae"), w.trae]);
if (process.env.ARTIFACT_DIR) await page.locator("#traeList").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `checkin-now-${engine}-${lang}-${width}-trae.png`) });
assert.deepEqual(asked.filter((a) => a[0] === "write"), [], "a press wrote a switch");
assert.equal(asked.length, 5);
assert.deepEqual(await sideways(page), []);
assert.equal(await page.locator("select").count(), 0);
assert.deepEqual(errors, []);
});
}
}
test(`${engine}: no account, no Check in now`, async (t) => {
const browser = await launch(engine);
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 900, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const route = serve("en", [], {});
await page.route("**/*", async (r) => {
if (new URL(r.request().url()).pathname === "/api/settings") return r.fulfill({ json: { theme: "light", lang: "en", workbuddy: true, workbuddyCheckin: true, checkinAccounts: [] } });
return route(r);
});
await page.goto("http://magpie.test/?view=settings&tab=usage");
await page.locator("#warmTab-wb").waitFor();
await page.locator("#warmTab-wb").click();
await page.locator("#wbCheckinSegs .opt").first().waitFor();
assert.equal(await page.locator(".ci-now-row").count(), 0);
assert.deepEqual(errors, []);
});
}
+3 -2
View File
@@ -151,8 +151,9 @@ test("compat.js is the first of the page's own scripts", async () => {
// open, claudemode.js when a Claude provider's editor opens, ctxtext.js
// when a context window part is opened, resetask.js when a Codex reset's
// Use is pressed, quotaall.js when a provider has two accounts,
// quitask.js when a Quit asks first; the checks above still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
// quitask.js when a Quit asks first, checkinnow.js when Settings' Check
// in now for one account is pressed; the checks above still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
});
test("the styles hold up in Safari 15.0", async () => {
+18
View File
@@ -354,6 +354,24 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
}
writeJSON(rw, rs)
})
// and one account's, from Settings' Check in now (xiaowu_95660), by
// its vendor and key as /api/settings lists them: asked once now,
// whatever its switch says, which it leaves as it is
mux.HandleFunc("POST /api/usage/checkin-account", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ By, Key string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Key == "" {
fail(rw, errors.New("no account"))
return
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
rs := provider.CheckInAccount(ctx, in.By, in.Key)
if len(rs) == 0 {
fail(rw, errors.New("No daily check-in reaches this account"))
return
}
writeJSON(rw, rs[0])
})
// 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) {
+65 -11
View File
@@ -42,6 +42,10 @@ type checkiner struct {
label string // the vendor in the log
recheck bool // its campaigns can change before the Beijing day ends
accounts func() []checkinAcct
// only, of a press for one account (CheckInAccount), is its key: the
// others are neither asked nor said, and it is asked even while left
// out of the daily check-in, whose switch it leaves as it is
only string
}
// checkinRunner is a check-in the daily loop runs.
@@ -79,7 +83,7 @@ func (c checkiner) checkinNow(ctx context.Context, soon bool) []WorkBuddyCheckin
// or a press (#1902)
off := checkinOff()
for _, a := range c.accounts() {
if !a.On || a.key == "" || asked[a.key] || off[a.key] {
if !a.On || a.key == "" || asked[a.key] || !c.reaches(a.key, off) {
continue
}
// nor, by the loop, one whose provider is switched off or removed
@@ -155,7 +159,7 @@ func (c checkiner) unread(now time.Time, err error) []WorkBuddyCheckin {
listed := map[string]bool{}
off := checkinOff()
for _, a := range c.accounts() {
if !a.On || a.key == "" || listed[a.key] || off[a.key] {
if !a.On || a.key == "" || listed[a.key] || !c.reaches(a.key, off) {
continue
}
listed[a.key] = true
@@ -164,6 +168,15 @@ func (c checkiner) unread(now time.Time, err error) []WorkBuddyCheckin {
return out
}
// reaches says whether a run of c asks the account at key: one the user
// left out (off) only by a press for it alone (only).
func (c checkiner) reaches(key string, off map[string]bool) bool {
if c.only != "" {
return key == c.only
}
return !off[key]
}
// checkinOff are the accounts left out of their vendor's daily check-in
// (settings.CheckinOff), by their entry in its file.
func checkinOff() map[string]bool {
@@ -190,15 +203,7 @@ type CheckinAccount struct {
// reaches, WorkBuddy's, Trae CN's, MiniMax Code's, Qoder's and the
// plugins' that check in themselves, each once; asks nothing.
func CheckinAccounts() []CheckinAccount {
cs := []checkiner{
newWBCheckiner().checkiner(),
newTraeCheckiner(traeCheckinAccounts),
newMiniMaxCheckiner(miniMaxCheckinAccounts),
newQoderCheckiner(qoderCheckinAccounts, time.Now),
}
for _, p := range pluginCheckinProviders() {
cs = append(cs, p.checkiner(time.Now))
}
cs := checkiners()
off := checkinOff()
var out []CheckinAccount
seen := map[string]bool{}
@@ -216,3 +221,52 @@ func CheckinAccounts() []CheckinAccount {
}
return out
}
// checkiners are every vendor's check-in: WorkBuddy's, Trae CN's, MiniMax
// Code's, Qoder's and each plugin's that checks in itself, with its name
// (a plugin's provider's, for WorkBuddyCheckin.Vendor; "" for a built-in).
func checkiners() []checkiner {
cs, _ := namedCheckiners()
return cs
}
func namedCheckiners() ([]checkiner, []string) {
cs := []checkiner{
newWBCheckiner().checkiner(),
newTraeCheckiner(traeCheckinAccounts),
newMiniMaxCheckiner(miniMaxCheckinAccounts),
newQoderCheckiner(qoderCheckinAccounts, time.Now),
}
names := make([]string, len(cs))
for _, p := range pluginCheckinProviders() {
cs = append(cs, p.checkiner(time.Now))
names = append(names, p.Name)
}
return cs, names
}
// CheckInAccount checks one account in for today now, as a press of Check
// in now does for its vendor's (CheckinAccount's By and Key): asked again
// unless claimed today, even while left out of the daily check-in, and
// no switch changed (xiaowu_95660: 手动签到一次). It says how the account
// stands, or nothing for an account no check-in reaches.
func CheckInAccount(ctx context.Context, by, key string) []WorkBuddyCheckin {
if key == "" {
return nil
}
cs, names := namedCheckiners()
for i, c := range cs {
if c.by != by {
continue
}
c.only = key
rs := c.checkinNow(ctx, true)
for j := range rs {
if names[i] != "" {
rs[j].Vendor = names[i]
}
}
return rs
}
return nil
}
+72
View File
@@ -0,0 +1,72 @@
package provider
import (
"context"
"slices"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// Check in now for one account (xiaowu_95660: 手动签到一次) asks that
// account alone, once, even one left out of the daily check-in, and
// changes no switch: the other account is neither asked nor said, a
// second press the same day is answered from the claim, and the left-out
// account stays left out.
func TestCheckinOneAccountNow(t *testing.T) {
signIn(t)
f := &fakeWBCheckin{active: true}
srv := f.serve(t)
now := time.Date(2026, 11, 2, 3, 0, 0, 0, time.UTC)
w := wbCheckinFixture(t, srv, &now)
one := w.accounts()[0]
two := one
two.User, two.creds.UID = "second", "u2"
w.accounts = func() []wbAccount { return []wbAccount{one, two} }
ctx := context.Background()
leaveOut(t, "workbuddy|u2")
c := w.checkiner()
c.only = "workbuddy|u2"
rs := c.checkinNow(ctx, true)
if len(rs) != 1 || rs[0].User != "second" || rs[0].Outcome != CheckinClaimed || !rs[0].Asked {
t.Fatalf("pressed for the left-out account: %+v", rs)
}
s0, cl0 := f.counts()
if cl0 != 1 {
t.Fatalf("claims %d, want 1 (the other account asked too?)", cl0)
}
if off := settings.Load().CheckinOff; !slices.Equal(off, []string{"workbuddy|u2"}) {
t.Fatalf("the press changed the switch: %v", off)
}
// pressed again the same day: the claim stands, the vendor not asked
rs = c.checkinNow(ctx, true)
if len(rs) != 1 || rs[0].Asked || !rs[0].Checked() {
t.Fatalf("second press: %+v", rs)
}
if s, cl := f.counts(); s != s0 || cl != cl0 {
t.Fatalf("second press asked: status %d, claims %d", s, cl)
}
// the daily loop still leaves it out and checks the other in
f.mu.Lock()
f.checked = false
f.mu.Unlock()
rs = w.checkinNow(ctx, false)
if len(rs) != 1 || rs[0].User != "旅行者" || !rs[0].Asked {
t.Fatalf("the loop after the press: %+v", rs)
}
}
// A press for an account no check-in reaches answers nothing.
func TestCheckinAccountNowUnknown(t *testing.T) {
signIn(t)
if rs := CheckInAccount(context.Background(), "", "workbuddy|nobody"); len(rs) != 0 {
t.Fatalf("unknown account: %+v", rs)
}
if rs := CheckInAccount(context.Background(), "", ""); len(rs) != 0 {
t.Fatalf("no key: %+v", rs)
}
}