698ed4adb(a busy port names its holder) was committed from a tree made before919780414and88d2962e0landed (09:38, eight minutes before it), and took both out with no word in its body: quotatable.js, the Usage Cards / Table switch and its test, and sessions' 16-byte head and prefix hashes (digest.go) were gone from main from v0.1.3823. This puts both back as they were, on top of 698ed4adb's own change, which is kept. Run at this tree, on mote (cherry-pick of both onto origin/maindb0c1b039, no conflicts): - gofmt -l internal/sessions: clean. - go vet ./internal/sessions ./internal/gui; GOOS=windows and GOOS=linux -tags nogui go vet ./internal/sessions: ok. - go test -count=1 ./internal/sessions: ok 83.6s. - go test -run 'Budget|Lazy|I18n' ./internal/gui: ok (the core script budget holds with both changes). - GUI, chromium and webkit: usage-quota-table, gateway-port-holder, i18n-keys, i18n-en-no-cjk, old-webkit: 44 of 46. The two reds are old-webkit's "compat.js is the first" (headerpresets.js, #6030) and "the styles hold up in Safari 15.0" (#5919), red the same on an origin/maindb0c1b039copy. Not run: the full Go and GUI suites.
This commit is contained in:
@@ -361,6 +361,23 @@ card's "Show … accounts" button keeps its room but is hidden and inert, so
|
||||
the strip stays where it was. A menu bar cell asking for one of the
|
||||
accounts unfolds them (`focusQuotaCard`). See `usage-all-fold.test.cjs`.
|
||||
|
||||
The Usage page's allowances are cards, or a table when the reader picks
|
||||
Table in the Allowances head (`#quotaView`; zysicyj on X: a dozen-plus
|
||||
accounts were hard to scan as cards). The pick is kept in localStorage
|
||||
`magpie.quotaView` on this computer and nothing is written until it is
|
||||
made, so the default stays cards. The table (`quotaTable` in
|
||||
`quotatable.js`, which app.js imports once it is picked) has a row per
|
||||
account in the cards' order, so what the cards hide or merge is hidden or
|
||||
merged here too, with the subscription, the account, the four windows most
|
||||
accounts have (each as its used or left share, a bar and when it resets,
|
||||
from the same `quotaFill` and `quotaText` as the cards, so Used/Left turns
|
||||
both) and the rest of an account's windows in a last column; a failed read
|
||||
and a balance say so across the windows. A head sorts by it (most used first
|
||||
for a window, A first for a name), again the other way, a third time back
|
||||
to the cards' order; accounts with nothing in that column stay last. It
|
||||
scrolls in its own box at a narrow width, the subscription held at the left.
|
||||
See `usage-quota-table.test.cjs`.
|
||||
|
||||
### The Sessions page's folders
|
||||
|
||||
The Sessions page lists an agent's project folders as one list, newest
|
||||
|
||||
@@ -998,14 +998,41 @@ body.panel .row.pref.flash { border-radius: 10px; }
|
||||
/* packed into columns (packUsage): each card as tall as itself, placed on
|
||||
rows a pixel high, the gap between cards in its place on them (#860) */
|
||||
.subscription-usage.packed { grid-auto-rows: 1px; row-gap: 0; }
|
||||
/* the allowances as a table: a row an account (quotatable.js); wider than the
|
||||
page, it scrolls in its own box with the subscription held at the left */
|
||||
.subscription-usage.tabled { display: block; }
|
||||
.qt-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: 10px; background: var(--card); }
|
||||
.qt { width: 100%; min-width: 560px; border-collapse: separate; border-spacing: 0; font-size: 12px; }
|
||||
.qt th, .qt td { padding: 8px 10px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--line); }
|
||||
.qt tbody tr:last-child td { border-bottom: 0; }
|
||||
.qt th { padding-block: 4px; font-size: 10.5px; font-weight: 500; color: var(--muted); white-space: nowrap; }
|
||||
.qt .qt-sub { position: sticky; left: 0; z-index: 1; min-width: 118px; background: var(--card); }
|
||||
.qt .qt-w { min-width: 84px; width: 15%; }
|
||||
.qt-sort { display: inline-flex; align-items: center; gap: 3px; padding: 2px 0; font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
|
||||
.qt-sort.on { color: var(--fg); }
|
||||
.qt-arrow { display: inline-block; min-width: 1ch; }
|
||||
@media (hover: hover) and (pointer: fine) { .qt-sort:hover { color: var(--fg); } }
|
||||
.qt-id { display: flex; align-items: center; gap: 6px; }
|
||||
.qt-id .ic { width: 15px; height: 15px; flex: none; }
|
||||
.qt-id b { font-weight: 600; white-space: nowrap; }
|
||||
.qt .plan { display: block; margin: 2px 0 0 21px; font-size: 10.5px; color: var(--muted); text-transform: capitalize; white-space: nowrap; }
|
||||
.qt .qt-acct { min-width: 120px; max-width: 220px; color: var(--fg-2); }
|
||||
.qt .subscription-account { margin: 0; font-size: 12px; }
|
||||
.qt .qt-acct .quota-of, .qt .qt-acct .quota-seat { color: var(--muted); }
|
||||
.qt-win { display: grid; gap: 4px; }
|
||||
.qt-win + .qt-win { margin-top: 8px; }
|
||||
.qt-fig { font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.qt-name { font-weight: 400; color: var(--muted); }
|
||||
.qt-reset { font-size: 10px; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.qt .qt-msg { color: var(--muted); }
|
||||
.subscription-card { padding: 10px 12px 11px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); min-width: 0; }
|
||||
/* a card's captions (resets, the period, a curve's dates) read at 4.5:1 or
|
||||
better on the card, below its figures (Jiabubu on Discord): light's
|
||||
--muted is 3.7:1 on white, so a card takes the controls' quiet text;
|
||||
dark's --muted is 4.6:1 already */
|
||||
.subscription-card, .pq-card, .quota-all { --muted: var(--ctl-fg); }
|
||||
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) :is(.subscription-card, .pq-card) { --muted: inherit; } }
|
||||
:root[data-theme="dark"] :is(.subscription-card, .pq-card) { --muted: inherit; }
|
||||
.subscription-card, .pq-card, .quota-all, .qt-wrap { --muted: var(--ctl-fg); }
|
||||
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) :is(.subscription-card, .pq-card, .qt-wrap) { --muted: inherit; } }
|
||||
:root[data-theme="dark"] :is(.subscription-card, .pq-card, .qt-wrap) { --muted: inherit; }
|
||||
.subscription-head { display: flex; align-items: center; gap: 7px; margin-bottom: 9px; }
|
||||
.subscription-head:last-child { margin-bottom: 0; }
|
||||
.subscription-head .ic { width: 17px; height: 17px; }
|
||||
|
||||
@@ -14604,6 +14604,10 @@ function quotaAllJS() {
|
||||
return (quotaAllJS.p ||= import("./quotaall.js").then(() => renderQuotas(), () => {}));
|
||||
}
|
||||
const quotaAllOf = (...a) => window.quotaAll ? quotaAll(...a) : void quotaAllJS();
|
||||
// quotatable.js: the allowances as a table, loaded once chosen. Cards or
|
||||
// table is the reader's own pick on this computer, cards until then.
|
||||
let quotaView = kept("quotaView", "cards");
|
||||
const quotaTableJS = () => (quotaTableJS.p ||= import("./quotatable.js").then(() => renderQuotas(), () => {}));
|
||||
// tiersText: a family's windows, one a line, for its tooltip.
|
||||
function tiersText(w) {
|
||||
return (w.tiers || []).map((x) => t(x.name) + " " + quotaText(x)
|
||||
@@ -15983,6 +15987,16 @@ function renderQuotas(lazy) {
|
||||
}
|
||||
slide(pick, "quotaMode");
|
||||
}
|
||||
const views = $("#quotaView");
|
||||
views.hidden = !quotas?.length;
|
||||
if (!views.hidden) {
|
||||
views.replaceChildren(...[["cards", "Cards"], ["table", "Table"]].map(([v, name]) => {
|
||||
const b = el("button", "opt" + (v === quotaView ? " on" : ""), t(name));
|
||||
b.onclick = () => { if (v !== quotaView) { quotaView = v; keep("quotaView", v); renderQuotas(); } };
|
||||
return b;
|
||||
}));
|
||||
slide(views, "quotaView");
|
||||
}
|
||||
renderQuotaTrend();
|
||||
renderQuotaHid();
|
||||
if (!quotas) {
|
||||
@@ -16000,6 +16014,19 @@ function renderQuotas(lazy) {
|
||||
// less the ones hidden from it (overviewCards, the Usage page's)
|
||||
const shown = overviewCards(quotas);
|
||||
subscriptions.hidden = !shown.length;
|
||||
// the table: a row an account, in the cards' order
|
||||
const rows = quotaView === "table" && shown.length && (window.quotaTable ? quotaTable(byUsageOrder(keyCards(shown))) : void quotaTableJS());
|
||||
subscriptions.classList.toggle("tabled", !!rows);
|
||||
if (rows) {
|
||||
usagePack.disconnect();
|
||||
usagePacked = null;
|
||||
subscriptions.classList.remove("packed");
|
||||
subscriptions.style.gridTemplateColumns = "";
|
||||
subscriptions.append(rows);
|
||||
restoreFlash();
|
||||
restoreRefresh();
|
||||
return;
|
||||
}
|
||||
// an agent with several accounts is one card, a section per account
|
||||
const groups = [];
|
||||
keepIcons(...was);
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
// works. {name} slots are filled by t(str, vars).
|
||||
const I18N = {
|
||||
zh: {
|
||||
"Cards": "卡片",
|
||||
"Table": "表格",
|
||||
"Quick check": "快速检测",
|
||||
"Test all": "全部测试",
|
||||
"One real call each, at the provider's price": "每项真实调用一次,按服务商的价格计费",
|
||||
@@ -5124,6 +5126,8 @@ const I18N = {
|
||||
"This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。",
|
||||
},
|
||||
"zh-TW": {
|
||||
"Cards": "卡片",
|
||||
"Table": "表格",
|
||||
"Quick check": "快速檢測",
|
||||
"Test all": "全部測試",
|
||||
"One real call each, at the provider's price": "每項真實呼叫一次,按服務商的價格計費",
|
||||
@@ -10229,6 +10233,8 @@ const I18N = {
|
||||
"This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。",
|
||||
},
|
||||
ja: {
|
||||
"Cards": "カード",
|
||||
"Table": "表",
|
||||
"Quick check": "クイックチェック",
|
||||
"Test all": "すべてテスト",
|
||||
"One real call each, at the provider's price": "それぞれ実際に 1 回呼び出し、プロバイダの料金がかかります",
|
||||
@@ -15336,6 +15342,8 @@ const I18N = {
|
||||
"This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。",
|
||||
},
|
||||
de: {
|
||||
"Cards": "Karten",
|
||||
"Table": "Tabelle",
|
||||
"Quick check": "Schnelltest",
|
||||
"Test all": "Alle testen",
|
||||
"One real call each, at the provider's price": "Je ein echter Aufruf, zum Preis des Anbieters",
|
||||
|
||||
@@ -36,6 +36,7 @@ magpie.plugin("usage", (ctx) => {
|
||||
<button class="sess-pick quota-trend" id="quotaTrend" type="button" 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>
|
||||
<div class="segs" id="quotaMode" hidden></div>
|
||||
</div>
|
||||
<section class="subscription-usage" id="subscriptionUsage"></section>
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// The Usage page's allowances as a table (zysicyj on X: a dozen-plus
|
||||
// accounts are hard to scan as cards): a row an account, the subscription
|
||||
// and the account first, then its windows' used (or left) share with the
|
||||
// time they start again, the same readings the cards draw. app.js imports
|
||||
// this once the table is chosen (quotaTableJS), so it weighs nothing on the
|
||||
// core.
|
||||
//
|
||||
// The columns are the windows most accounts have ("5 hours", "7 days");
|
||||
// the rest of an account's go in the last column. A click on a head sorts
|
||||
// by it, again the other way, a third time back to the cards' order.
|
||||
const TABLE_WINDOWS = 4;
|
||||
let sorted = null; // { key, down }
|
||||
|
||||
// the figure a window sorts and bars by: the share as the page shows it
|
||||
// (used, or left), -1 when it has none
|
||||
const share = (w) => (!w || w.unlimited || quotaNoShare(w) ? -1 : quotaFill(w));
|
||||
const spanOf = (name) => {
|
||||
const m = /^(\d+)\s*(hour|day|week)s?$/i.exec(name || "");
|
||||
return m ? m[1] * { hour: 1, day: 24, week: 168 }[m[2].toLowerCase()] : Infinity;
|
||||
};
|
||||
|
||||
// a window's cell: its share and bar, and when it starts again
|
||||
function windowCell(w, long) {
|
||||
const box = el("div", "qt-win");
|
||||
if (!w) return box;
|
||||
const top = el("div", "qt-fig");
|
||||
const text = quotaText(w);
|
||||
const bar = share(w) >= 0;
|
||||
top.append(el("span", "qt-n", bar ? quotaFill(w) + "%" : text));
|
||||
if (long) top.prepend(el("span", "qt-name", t(w.name)), " ");
|
||||
box.append(top);
|
||||
if (bar) {
|
||||
const track = el("div", "quota-track"), fill = el("i");
|
||||
fill.style.width = quotaFill(w) + "%";
|
||||
track.append(fill);
|
||||
box.append(track);
|
||||
}
|
||||
const at = w.resetsAt ? new Date(w.resetsAt) : null;
|
||||
if (at) box.append(el("div", "qt-reset", at > Date.now() ? resetClock(at) : t("Reset time passed")));
|
||||
box.title = tipLines(t(w.name) + " · " + text, at && resetText(at, at.toLocaleString(intlLang())), w.tiers && tiersText(w));
|
||||
return box;
|
||||
}
|
||||
|
||||
function quotaTable(subs) {
|
||||
const rows = subs.map((sub, order) => ({ sub, order, ws: sub.error ? [] : familyWindows(sub.windows) || [] }));
|
||||
// the windows most rows have, by their span
|
||||
const count = new Map();
|
||||
for (const r of rows) for (const w of new Set(r.ws.filter((x) => !x.members).map((x) => x.name))) count.set(w, (count.get(w) || 0) + 1);
|
||||
const names = [...count.keys()].map((n, i) => [n, i]).sort(([a, i], [b, j]) => count.get(b) - count.get(a) || i - j).slice(0, TABLE_WINDOWS)
|
||||
.sort(([a, i], [b, j]) => spanOf(a) - spanOf(b) || i - j).map(([n]) => n);
|
||||
const extra = (r) => r.ws.filter((w) => !names.includes(w.name));
|
||||
const bare = (r) => r.sub.balance && !r.ws.length && !r.sub.error; // a balance and no window
|
||||
const more = rows.some((r) => extra(r).length || (r.sub.balance && r.ws.length)) || (!names.length && rows.some(bare));
|
||||
const value = (r, key) => key === "sub" ? quotaName(r.sub).toLowerCase()
|
||||
: key === "acct" ? (r.sub.alias || r.sub.user || "").toLowerCase() || null
|
||||
: Math.max(-1, ...r.ws.filter((w) => w.name === key).map(share));
|
||||
if (sorted && sorted.key !== "sub" && sorted.key !== "acct" && !names.includes(sorted.key)) sorted = null;
|
||||
const list = sorted ? [...rows].sort((a, b) => {
|
||||
const x = value(a, sorted.key), y = value(b, sorted.key);
|
||||
// a row with nothing here stays below the rest either way
|
||||
const none = (v) => v === null || v < 0;
|
||||
if (none(x) !== none(y)) return none(x) ? 1 : -1;
|
||||
return (x < y ? -1 : x > y ? 1 : 0) * (sorted.down ? -1 : 1) || a.order - b.order;
|
||||
}) : rows;
|
||||
|
||||
const wrap = el("div", "qt-wrap");
|
||||
const table = el("table", "qt");
|
||||
const head = el("tr");
|
||||
const th = (key, label, cls = "") => {
|
||||
const c = el("th", cls);
|
||||
const on = sorted?.key === key;
|
||||
c.scope = "col";
|
||||
c.setAttribute("aria-sort", on ? (sorted.down ? "descending" : "ascending") : "none");
|
||||
const b = el("button", "qt-sort" + (on ? " on" : ""), label);
|
||||
b.type = "button";
|
||||
const arrow = el("span", "qt-arrow", on ? (sorted.down ? "↓" : "↑") : "");
|
||||
arrow.setAttribute("aria-hidden", "true");
|
||||
b.append(arrow);
|
||||
b.onclick = () => {
|
||||
// windows start at the most used, names at A
|
||||
const first = key !== "sub" && key !== "acct";
|
||||
sorted = !on ? { key, down: first } : sorted.down === first ? { key, down: !first } : null;
|
||||
renderQuotas();
|
||||
};
|
||||
c.append(b);
|
||||
return c;
|
||||
};
|
||||
head.append(th("sub", t("Subscription"), "qt-sub"), th("acct", t("Account"), "qt-acct"));
|
||||
for (const n of names) head.append(th(n, t(n), "qt-w"));
|
||||
if (more) head.append(el("th", "qt-w", t("Other")));
|
||||
table.append(el("thead", "", head));
|
||||
|
||||
const body = el("tbody");
|
||||
for (const { sub, ws } of list) {
|
||||
const tr = el("tr");
|
||||
tr.dataset.card = trayCardID(sub);
|
||||
tr.dataset.provider = sub.provider;
|
||||
const s = el("td", "qt-sub");
|
||||
const who = el("div", "qt-id");
|
||||
who.append(icon(sub.icon), el("b", "", quotaName(sub)));
|
||||
s.append(who);
|
||||
if (sub.plan || sub.until) s.append(planSpan(sub));
|
||||
const a = el("td", "qt-acct");
|
||||
const name = el("div", "subscription-account");
|
||||
name.append(...quotaWho(sub));
|
||||
a.append(name);
|
||||
tr.append(s, a);
|
||||
const cols = names.length + (more ? 1 : 0);
|
||||
if (sub.error) {
|
||||
const e = el("td", "qt-msg", quotaError(sub.error, sub));
|
||||
e.colSpan = cols;
|
||||
e.title = sub.error;
|
||||
tr.append(e);
|
||||
} else {
|
||||
if (bare({ sub, ws })) {
|
||||
const b = el("td", "qt-msg", t("{n} left", { n: sub.balance }));
|
||||
b.colSpan = cols;
|
||||
tr.append(b);
|
||||
} else for (const n of names) {
|
||||
const w = ws.find((x) => x.name === n);
|
||||
const c = el("td", "qt-w");
|
||||
if (w) c.append(windowCell(w));
|
||||
tr.append(c);
|
||||
}
|
||||
if (more && !bare({ sub, ws })) {
|
||||
const o = el("td", "qt-w qt-other");
|
||||
for (const w of extra({ ws })) o.append(windowCell(w, true));
|
||||
if (sub.balance) o.append(el("div", "qt-fig", t("{n} left", { n: sub.balance })));
|
||||
tr.append(o);
|
||||
}
|
||||
}
|
||||
body.append(tr);
|
||||
}
|
||||
table.append(body);
|
||||
wrap.append(table);
|
||||
return wrap;
|
||||
}
|
||||
window.quotaTable = quotaTable;
|
||||
@@ -150,7 +150,7 @@ test("compat.js is the first of the page's own scripts", async () => {
|
||||
// the pointer comes over the sidebar, whatsnew.js when release notes
|
||||
// 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,
|
||||
// Use is pressed, quotaall.js when a provider has two accounts, quotatable.js when the Usage page's table is picked,
|
||||
// quitask.js when a Quit asks first, proxies.js when Settings draws its saved proxies, checkinnow.js when Settings' Check
|
||||
// in now for one account is pressed, autobackup.js when Settings draws
|
||||
// Sync, scrollends.js on the window's first scroll, profilerename.js
|
||||
@@ -178,7 +178,7 @@ test("compat.js is the first of the page's own scripts", async () => {
|
||||
// pipecheck.js when Settings draws Models;
|
||||
// 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", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
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", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
});
|
||||
|
||||
test("the styles hold up in Safari 15.0", async () => {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// The Usage page's allowances as a table beside the cards (zysicyj on X: "a
|
||||
// dozen-plus accounts, the waterfall is hard to scan, could it be a
|
||||
// table"). Cards stay the default and the table is the reader's own pick,
|
||||
// remembered on this computer: a row an account, its subscription and
|
||||
// account first, then its windows' share and when they start again; a click
|
||||
// on a head sorts by it, again the other way, a third time back to the
|
||||
// cards' order. A narrow window scrolls the table in its own box, never the
|
||||
// page. Both engines, every language, wide and narrow; no backend, 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 H = 3600e3;
|
||||
const at = (h) => new Date(Date.now() + h * H).toISOString();
|
||||
const w = (name, used, h) => ({ name, used, resetsAt: at(h) });
|
||||
// as a user with a dozen-plus accounts has them: several of one agent,
|
||||
// plans with other windows, a balance, a failed read
|
||||
const quotas = [
|
||||
...[["a", 20, 40], ["b", 90, 10], ["c", 55, 75], ["d", 5, 99]].map(([u, five, week]) => (
|
||||
{ provider: "codex", name: "Codex", kind: "subscription", icon: "codex-color", plan: "Plus", user: u + "@example.com", windows: [w("5 hours", five, 2), w("7 days", week, 90)] })),
|
||||
...[["e", 33, 12], ["f", 71, 61], ["g", 9, 3]].map(([u, five, week]) => (
|
||||
{ provider: "claude", name: "Claude Code", kind: "subscription", icon: "claude-color", plan: "Max 5x", user: u + "@example.com", windows: [w("5 hours", five, 3), w("7 days", week, 80), w("7 days Opus", 14, 80)] })),
|
||||
{ provider: "antigravity", name: "Antigravity", icon: "antigravity-color", plan: "Google AI Pro", user: "h@example.com", windows: [
|
||||
{ name: "Gemini 3 Flash", family: "Gemini", used: 100, resetsAt: at(13) }, { name: "Claude Sonnet 4.6", family: "Claude", used: 0, resetsAt: at(5) }] },
|
||||
{ provider: "kimi", name: "Kimi", icon: "kimi", user: "i@example.com", windows: [w("Weekly", 42, 70)] },
|
||||
{ provider: "zai", name: "Z.ai", icon: "zai", user: "j@example.com", windows: [w("5 hours", 64, 1), w("Weekly", 12, 70)] },
|
||||
{ provider: "deepseek", name: "DeepSeek", icon: "deepseek", windows: [], balance: "¥17.41" },
|
||||
{ provider: "minimax", name: "MiniMax", icon: "minimax", user: "k@example.com", windows: [], error: "unauthorized" },
|
||||
{ provider: "codex", name: "Codex", kind: "subscription", icon: "codex-color", plan: "Pro", user: "l@example.com", windows: [w("5 hours", 0, 5), w("7 days", 0, 160)] },
|
||||
{ provider: "claude", name: "Claude Code", kind: "subscription", icon: "claude-color", plan: "Pro", user: "m@example.com", windows: [w("5 hours", 12, 4), w("7 days", 25, 100)] },
|
||||
{ provider: "kimi", name: "Kimi", icon: "kimi", user: "n@example.com", windows: [w("Weekly", 77, 70)] },
|
||||
];
|
||||
|
||||
function serve(lang, left) {
|
||||
const settings = { theme: "light", lang, tray: "panel", quotaLeft: left, currency: "usd" };
|
||||
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/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 CARDS = { en: "Cards", zh: "卡片", "zh-TW": "卡片", ja: "カード", de: "Karten" };
|
||||
const TABLE = { en: "Table", zh: "表格", "zh-TW": "表格", ja: "表", de: "Tabelle" };
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}px: the allowances as cards or a table`, 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: 800 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, false));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
await page.waitForSelector("#subscriptionUsage .subscription-card");
|
||||
|
||||
// cards until the reader picks the table
|
||||
assert.equal(await page.locator(".qt").count(), 0);
|
||||
assert.equal(await page.locator("#quotaView .opt.on").innerText(), CARDS[lang]);
|
||||
assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaView")), null, "nothing is saved until the reader picks");
|
||||
|
||||
await page.locator("#quotaView .opt", { hasText: TABLE[lang] }).click();
|
||||
await page.waitForSelector("#subscriptionUsage .qt tbody tr");
|
||||
assert.equal(await page.locator("#subscriptionUsage .subscription-card").count(), 0);
|
||||
// a row an account (a card's several accounts are rows too)
|
||||
const accounts = quotas.length;
|
||||
assert.equal(await page.locator(".qt tbody tr").count(), accounts);
|
||||
const heads = await page.$$eval(".qt thead th", (ths) => ths.map((x) => x.textContent.trim()));
|
||||
assert.equal(heads.length, 2 + 4 + 1, `${heads}`);
|
||||
// the cards' figures, the same readings
|
||||
const row = await page.$eval('.qt tbody tr:nth-child(1)', (tr) => tr.innerText.replace(/\s+/g, " "));
|
||||
assert.match(row, /Codex/);
|
||||
assert.match(row, /a@example\.com/);
|
||||
assert.match(row, /20%/);
|
||||
assert.match(row, /40%/);
|
||||
// when each starts again
|
||||
assert.ok((await page.$$eval(".qt .qt-reset", (x) => x.length)) >= accounts, "resets are shown");
|
||||
// a failed read and a balance say so across the windows
|
||||
assert.equal(await page.locator('.qt tbody tr:has-text("¥17.41")').count(), 1);
|
||||
assert.equal(await page.locator(".qt tbody tr .qt-msg").count(), 2);
|
||||
|
||||
// the pick is remembered
|
||||
assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaView")), '"table"');
|
||||
await page.reload();
|
||||
await page.waitForSelector("#subscriptionUsage .qt tbody tr");
|
||||
assert.equal(await page.locator("#quotaView .opt.on").innerText(), TABLE[lang]);
|
||||
|
||||
// sorted by a window: the most used first, again the least, then the cards' order
|
||||
const first = () => page.$eval(".qt tbody tr:nth-child(1)", (tr) => tr.innerText.replace(/\s+/g, " "));
|
||||
const fiveHours = page.locator(".qt thead th.qt-w .qt-sort").first();
|
||||
await fiveHours.click();
|
||||
assert.match(await first(), /b@example\.com/);
|
||||
assert.equal(await page.locator('.qt thead th[aria-sort="descending"]').count(), 1);
|
||||
await page.locator(".qt thead th.qt-w .qt-sort").first().click();
|
||||
assert.match(await first(), /l@example\.com/, "ascending: unused first");
|
||||
assert.equal(await page.locator('.qt thead th[aria-sort="ascending"]').count(), 1);
|
||||
await page.locator(".qt thead th.qt-w .qt-sort").first().click();
|
||||
assert.match(await first(), /a@example\.com/, "back to the cards' order");
|
||||
assert.equal(await page.locator('.qt thead th[aria-sort]:not([aria-sort="none"])').count(), 0);
|
||||
// by account, A first
|
||||
await page.locator(".qt thead th.qt-acct .qt-sort").click();
|
||||
assert.match(await first(), /a@example\.com/);
|
||||
|
||||
// the page itself never scrolls sideways; the table scrolls in its box
|
||||
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||||
assert.ok(over <= 0, `the page scrolls sideways by ${over}px`);
|
||||
const box = await page.$eval(".qt-wrap", (b) => ({ w: b.clientWidth, s: b.scrollWidth, page: document.documentElement.clientWidth, right: b.getBoundingClientRect().right }));
|
||||
assert.ok(box.right <= box.page + 1, "the table's box stays inside the page");
|
||||
if (width === 420) assert.ok(box.s > box.w, "a narrow table scrolls in its box");
|
||||
|
||||
// back to the cards
|
||||
await page.locator("#quotaView .opt", { hasText: CARDS[lang] }).click();
|
||||
await page.waitForSelector("#subscriptionUsage .subscription-card");
|
||||
assert.equal(await page.locator(".qt").count(), 0);
|
||||
assert.equal(await page.evaluate(() => document.querySelector("#subscriptionUsage").classList.contains("tabled")), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
test(`${engine}: Left reads in the table too`, 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: 1100, height: 800 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
await page.addInitScript(() => localStorage.setItem("magpie.quotaView", '"table"'));
|
||||
await page.route("**/*", serve("en", true));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
await page.waitForSelector("#subscriptionUsage .qt tbody tr");
|
||||
const row = await page.$eval(".qt tbody tr:nth-child(1)", (tr) => tr.innerText.replace(/\s+/g, " "));
|
||||
assert.match(row, /80%/);
|
||||
assert.match(row, /60%/);
|
||||
});
|
||||
}
|
||||
@@ -596,7 +596,7 @@ type callDiskState struct {
|
||||
}
|
||||
|
||||
func diskCallState(s *callFile) callDiskState {
|
||||
d := callDiskState{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize,
|
||||
d := callDiskState{ContentHash: s.ContentHash.String(), Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head.String(), HeadSize: s.HeadSize,
|
||||
Path: s.Path, Agent: s.Agent, Parser: callParseVersions[s.Agent], At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested,
|
||||
LastUser: s.LastUser, LastAsst: s.LastAsst}
|
||||
if s.Dsh != nil {
|
||||
@@ -611,8 +611,8 @@ func diskCallState(s *callFile) callDiskState {
|
||||
return d
|
||||
}
|
||||
func (s callDiskState) restore() *callFile {
|
||||
st := &callFile{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off,
|
||||
Head: s.Head, HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End,
|
||||
st := &callFile{ContentHash: parseDigest(s.ContentHash), Size: s.Size, Mod: s.Mod, Off: s.Off,
|
||||
Head: parseDigest(s.Head), HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End,
|
||||
AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, LastUser: s.LastUser, LastAsst: s.LastAsst}
|
||||
if len(s.Dsh) > 0 {
|
||||
var c dshCarry
|
||||
|
||||
@@ -35,7 +35,7 @@ func writeCallRevisions(st *callFile) {
|
||||
_ = os.Remove(path)
|
||||
return
|
||||
}
|
||||
r := callRevisions{Off: st.Off, ContentHash: st.ContentHash, CompactMs: st.CompactMs, Window: st.Claude.window()}
|
||||
r := callRevisions{Off: st.Off, ContentHash: st.ContentHash.String(), CompactMs: st.CompactMs, Window: st.Claude.window()}
|
||||
var data bytes.Buffer
|
||||
if gob.NewEncoder(&data).Encode(r) != nil {
|
||||
return
|
||||
@@ -57,7 +57,7 @@ func writeCallRevisions(st *callFile) {
|
||||
// withCallRevisions is old with the window kept for it, when old is a
|
||||
// Claude file's read without one and the window kept is of that same read.
|
||||
func withCallRevisions(old *callFile) *callFile {
|
||||
if old == nil || old.Claude != nil || (old.Agent != "claude" && old.Agent != "claude-desktop") || old.ContentHash == "" {
|
||||
if old == nil || old.Claude != nil || (old.Agent != "claude" && old.Agent != "claude-desktop") || old.ContentHash == (digest{}) {
|
||||
return old
|
||||
}
|
||||
data, err := os.ReadFile(callRevisionsPath(old.Path))
|
||||
@@ -65,7 +65,7 @@ func withCallRevisions(old *callFile) *callFile {
|
||||
return old
|
||||
}
|
||||
var r callRevisions
|
||||
if gob.NewDecoder(bytes.NewReader(data)).Decode(&r) != nil || r.Off != old.Off || r.ContentHash != old.ContentHash {
|
||||
if gob.NewDecoder(bytes.NewReader(data)).Decode(&r) != nil || r.Off != old.Off || parseDigest(r.ContentHash) != old.ContentHash {
|
||||
return old
|
||||
}
|
||||
c := *old
|
||||
|
||||
+12
-12
@@ -70,7 +70,7 @@ type Call struct {
|
||||
// what it takes to read on from off.
|
||||
type callFile struct {
|
||||
Claude *claudeUsageState
|
||||
ContentHash string
|
||||
ContentHash digest
|
||||
dirty map[int]bool
|
||||
// readSize is the size of the file being read (prepareCalls), for
|
||||
// growCalls
|
||||
@@ -80,7 +80,7 @@ type callFile struct {
|
||||
Size int64
|
||||
Mod int64 // unix nanoseconds
|
||||
Off int64 // after the last whole line read
|
||||
Head string // hash of the prefix, to tell one replaced from one grown
|
||||
Head digest // of the prefix, to tell one replaced from one grown
|
||||
HeadSize int
|
||||
Path string
|
||||
Calls []Call
|
||||
@@ -392,7 +392,7 @@ func prepareCalls(f file, old *callFile, owned bool) *callFile {
|
||||
|
||||
head := headOf(f.path)
|
||||
var st *callFile
|
||||
if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != "" && prefixHash(f.path, old.Off) == old.ContentHash {
|
||||
if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != (digest{}) && prefixHash(f.path, old.Off) == old.ContentHash {
|
||||
if owned {
|
||||
st = old.cloneState()
|
||||
} else {
|
||||
@@ -411,7 +411,7 @@ func prepareCalls(f file, old *callFile, owned bool) *callFile {
|
||||
}
|
||||
}
|
||||
st.dirty = map[int]bool{}
|
||||
st.Head, st.HeadSize, st.Path = hashHead(head), len(head), f.path
|
||||
st.Head, st.HeadSize, st.Path = headDigest(head), len(head), f.path
|
||||
st.readSize = f.size
|
||||
return st
|
||||
}
|
||||
@@ -1292,18 +1292,18 @@ func (st *callFile) codexCompact(i int) {
|
||||
}
|
||||
|
||||
func hashHead(head string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(head))) }
|
||||
func sameHead(head, hash string, size int) bool {
|
||||
return size >= 0 && len(head) >= size && hashHead(head[:size]) == hash
|
||||
func sameHead(head string, hash digest, size int) bool {
|
||||
return size >= 0 && len(head) >= size && headDigest(head[:size]) == hash
|
||||
}
|
||||
|
||||
// prefixHash checks distributed windows of the indexed prefix. Small files
|
||||
// are checked in full. The version tag invalidates earlier full-file hashes.
|
||||
// are checked in full.
|
||||
// Rewrites outside the sampled windows can go undetected; appends cost at most
|
||||
// 64 KiB of reads per fingerprint regardless of the session's length.
|
||||
func prefixHash(path string, n int64) string {
|
||||
func prefixHash(path string, n int64) digest {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
return digest{}
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
@@ -1314,7 +1314,7 @@ func prefixHash(path string, n int64) string {
|
||||
defer hashBufs.Put(buf)
|
||||
if n <= window*samples {
|
||||
if _, err = io.ReadFull(f, buf[:n]); err != nil {
|
||||
return ""
|
||||
return digest{}
|
||||
}
|
||||
h.Write(buf[:n])
|
||||
} else {
|
||||
@@ -1322,12 +1322,12 @@ func prefixHash(path string, n int64) string {
|
||||
off := (n - window) * i / (samples - 1)
|
||||
// A full window may come back with io.EOF at the file's end.
|
||||
if k, _ := f.ReadAt(buf[:window], off); int64(k) < window {
|
||||
return ""
|
||||
return digest{}
|
||||
}
|
||||
h.Write(buf[:window])
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("sample-v1:%x", h.Sum(nil))
|
||||
return digest(h.Sum(nil)[:16])
|
||||
}
|
||||
|
||||
var hashBufs = sync.Pool{New: func() any { return new([64 << 10]byte) }}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// digest is a file's head or sampled prefix as kept to know it again
|
||||
// (headDigest, prefixHash): the first 16 bytes of its SHA-256, in the
|
||||
// state itself. As hex strings, 64 and 74 bytes of their own, they were
|
||||
// 144 bytes a file beside its state; 18k files' states held 2.6 MB of
|
||||
// them (#2278). The zero digest is none: the file couldn't be read.
|
||||
type digest [16]byte
|
||||
|
||||
// MarshalText is d in hex, "" for none.
|
||||
func (d digest) MarshalText() ([]byte, error) {
|
||||
if d == (digest{}) {
|
||||
return nil, nil
|
||||
}
|
||||
return []byte(hex.EncodeToString(d[:])), nil
|
||||
}
|
||||
|
||||
// UnmarshalText reads a digest as written, or as a magpie before it wrote
|
||||
// the whole hash: the 64 hex of hashHead's, or prefixHash's "sample-v1:"
|
||||
// before them, whose first 32 are this digest. A cache from before reads
|
||||
// as the same files, so nothing is read again for it. Anything else is
|
||||
// none, which matches no file.
|
||||
func (d *digest) UnmarshalText(b []byte) error {
|
||||
*d = parseDigest(string(b))
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseDigest is the digest s spells (UnmarshalText), none when it spells
|
||||
// none.
|
||||
func parseDigest(s string) digest {
|
||||
var d digest
|
||||
s = strings.TrimPrefix(s, "sample-v1:")
|
||||
if (len(s) != 32 && len(s) != 64) || s == "" {
|
||||
return d
|
||||
}
|
||||
if _, err := hex.Decode(d[:], []byte(s[:32])); err != nil {
|
||||
return digest{}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// String is d as MarshalText writes it, for the shards' gob, whose
|
||||
// field stays a string so a shard written before reads the same.
|
||||
func (d digest) String() string {
|
||||
b, _ := d.MarshalText()
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// headDigest is the digest of a file's first bytes, head.
|
||||
func headDigest(head string) digest {
|
||||
sum := sha256.Sum256([]byte(head))
|
||||
return digest(sum[:16])
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A cache a magpie before digest wrote holds the whole hashes in hex. Read
|
||||
// now, its files must be the same files, or every one is read again on the
|
||||
// first start after the update.
|
||||
func TestDigestReadsTheHashesWrittenBefore(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "rollout.jsonl")
|
||||
head := strings.Repeat(`{"type":"session_meta"}`+"\n", 3)
|
||||
if err := os.WriteFile(path, []byte(head+strings.Repeat("x", 200<<10)), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
size := int64(len(head) + 200<<10)
|
||||
oldHead := fmt.Sprintf("%x", sha256.Sum256([]byte(head)))
|
||||
oldHash := oldPrefixHash(path, size)
|
||||
if !strings.HasPrefix(oldHash, "sample-v1:") || len(oldHead) != 64 {
|
||||
t.Fatalf("old forms %q %q", oldHead, oldHash)
|
||||
}
|
||||
|
||||
var st state
|
||||
old := fmt.Sprintf(`{"head":%q,"head_size":%d,"content_hash":%q,"size":%d}`, oldHead, len(head), oldHash, size)
|
||||
if err := json.Unmarshal([]byte(old), &st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !sameHead(head, st.Head, int(st.HeadSize)) || st.ContentHash != prefixHash(path, size) || st.ContentHash == (digest{}) {
|
||||
t.Fatalf("an old state reads as another file: %x %x", st.Head, st.ContentHash)
|
||||
}
|
||||
// A shard keeps its hashes as strings: one written before restores the same.
|
||||
c := callDiskState{Head: oldHead, ContentHash: oldHash}.restore()
|
||||
if c.Head != st.Head || c.ContentHash != st.ContentHash {
|
||||
t.Fatalf("an old shard reads as another file: %x %x", c.Head, c.ContentHash)
|
||||
}
|
||||
if back := diskCallState(c).restore(); back.Head != c.Head || back.ContentHash != c.ContentHash {
|
||||
t.Fatal("a shard written now reads back as another file")
|
||||
}
|
||||
|
||||
b, err := json.Marshal(&st)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var again state
|
||||
if err := json.Unmarshal(b, &again); err != nil || again.Head != st.Head || again.ContentHash != st.ContentHash {
|
||||
t.Fatalf("written now, read again: %s", b)
|
||||
}
|
||||
if strings.Contains(string(b), oldHead) || !strings.Contains(string(b), oldHead[:32]) {
|
||||
t.Fatalf("not written as the digest: %s", b)
|
||||
}
|
||||
|
||||
// None stays none, and isn't written.
|
||||
b, _ = json.Marshal(&state{})
|
||||
if strings.Contains(string(b), "head") || strings.Contains(string(b), "content_hash") {
|
||||
t.Fatalf("no hash written as one: %s", b)
|
||||
}
|
||||
for _, s := range []string{"", "sample-v1:", "zz" + oldHead[2:], oldHead[:40]} {
|
||||
if parseDigest(s) != (digest{}) {
|
||||
t.Fatalf("%q read as a digest", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,7 @@ func TestSampledPrefixFingerprint(t *testing.T) {
|
||||
}
|
||||
os.WriteFile(path, data, 0600)
|
||||
}
|
||||
if prefixHash(path, n+1) != "" {
|
||||
if prefixHash(path, n+1) != (digest{}) {
|
||||
t.Fatal("short read accepted")
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ func BenchmarkPrefixFingerprint(b *testing.B) {
|
||||
for _, impl := range []struct {
|
||||
name string
|
||||
f func(string, int64) string
|
||||
}{{"sampled", prefixHash}, {"without_sampling", fullPrefixHash}} {
|
||||
}{{"sampled", func(p string, n int64) string { return prefixHash(p, n).String() }}, {"without_sampling", fullPrefixHash}} {
|
||||
b.Run(impl.name, func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
|
||||
@@ -10,8 +10,9 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// oldPrefixHash is prefixHash as it was, through io.CopyN: a stored hash
|
||||
// must still match after the change, or every cache is read again.
|
||||
// oldPrefixHash is prefixHash as it was, through io.CopyN and written in
|
||||
// full: a stored hash must still match after the change, or every cache
|
||||
// is read again.
|
||||
func oldPrefixHash(path string, n int64) string {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
@@ -45,13 +46,13 @@ func TestPrefixHashUnchangedAndUnbuffered(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, n := range []int64{0, 1, 4095, 4096, 65535, 65536, 65537, 1 << 20, 3 << 20} {
|
||||
if got, want := prefixHash(path, n), oldPrefixHash(path, n); got != want || got == "" {
|
||||
if got, want := prefixHash(path, n), parseDigest(oldPrefixHash(path, n)); got != want || got == (digest{}) {
|
||||
t.Fatalf("n=%d: %q, was %q", n, got, want)
|
||||
}
|
||||
}
|
||||
// Past the file's end is unknown, as it was.
|
||||
for _, n := range []int64{3<<20 + 1, 4 << 20} {
|
||||
if got := prefixHash(path, n); got != "" {
|
||||
if got := prefixHash(path, n); got != (digest{}) {
|
||||
t.Fatalf("n=%d past the end: %q", n, got)
|
||||
}
|
||||
if old := oldPrefixHash(path, n); old != "" {
|
||||
|
||||
@@ -218,14 +218,14 @@ type state struct {
|
||||
Codex *codexUsageState `json:"-"`
|
||||
codexPath string // the rollout read, for its fork's parent
|
||||
Claude *claudeUsageState `json:"claude,omitempty"`
|
||||
Head string `json:"head,omitempty"`
|
||||
Head digest `json:"head,omitzero"`
|
||||
// int32 beside CdRead: the head is headLen bytes at most, and the 8 bytes
|
||||
// it saves take a state from the 448-byte size class to 416 (#2278)
|
||||
HeadSize int32 `json:"head_size,omitempty"`
|
||||
// Claude Code: parsed by a magpie that reads /cd's relocated lines
|
||||
// (ccRelocated), so Cwd is the folder the session was last moved to
|
||||
CdRead bool `json:"cd_read,omitempty"`
|
||||
ContentHash string `json:"content_hash,omitempty"`
|
||||
ContentHash digest `json:"content_hash,omitzero"`
|
||||
Size int64 `json:"size"`
|
||||
Mod int64 `json:"mod"` // unix nanoseconds
|
||||
Off int64 `json:"off"` // after the last whole line read
|
||||
@@ -2346,13 +2346,13 @@ func parseRead(f file, old *state, calls *callsRide) *state {
|
||||
|
||||
headBytes := headOf(f.path)
|
||||
var s *state
|
||||
if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(headBytes, old.Head, int(old.HeadSize)) && old.ContentHash != "" && prefixHash(f.path, old.Size) == old.ContentHash {
|
||||
if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(headBytes, old.Head, int(old.HeadSize)) && old.ContentHash != (digest{}) && prefixHash(f.path, old.Size) == old.ContentHash {
|
||||
s = old.clone()
|
||||
} else {
|
||||
s = &state{}
|
||||
}
|
||||
s.Size, s.Mod = f.size, f.mod.UnixNano()
|
||||
s.Head, s.HeadSize = hashHead(headBytes), int32(len(headBytes))
|
||||
s.Head, s.HeadSize = headDigest(headBytes), int32(len(headBytes))
|
||||
s.CdRead = parser.claude
|
||||
s.ContentHash = prefixHash(f.path, f.size)
|
||||
var head func([]byte) bool
|
||||
|
||||
@@ -17,9 +17,9 @@ type tail struct {
|
||||
Off int64 `json:"off"`
|
||||
Skip int64 `json:"skip,omitempty"`
|
||||
Size int64 `json:"size"`
|
||||
Head string `json:"head"`
|
||||
Head digest `json:"head"`
|
||||
HeadSize int `json:"head_size"`
|
||||
Hash string `json:"hash"`
|
||||
Hash digest `json:"hash"`
|
||||
}
|
||||
|
||||
// markTail is the tail of a file read up to off, its first size bytes the
|
||||
@@ -30,10 +30,10 @@ func markTail(path string, off, skip, size int64) *tail {
|
||||
head = head[:size]
|
||||
}
|
||||
h := prefixHash(path, size)
|
||||
if h == "" && size > 0 {
|
||||
if h == (digest{}) && size > 0 {
|
||||
return nil
|
||||
}
|
||||
return &tail{Off: off, Skip: skip, Size: size, Head: hashHead(head), HeadSize: len(head), Hash: h}
|
||||
return &tail{Off: off, Skip: skip, Size: size, Head: headDigest(head), HeadSize: len(head), Hash: h}
|
||||
}
|
||||
|
||||
// holds says whether the file at path is still the one t was read from,
|
||||
|
||||
Reference in New Issue
Block a user