+ """;
+
+ [Fact]
+ public void AChangedGameStatsStripNeverBreaksTheClasses()
+ {
+ // XP tracking and the leaderboard don't need the strip. Without it, or with a silver value that isn't a
+ // number, the classes still parse and silver is simply unknown.
+ foreach (var strip in new[] { "", Strip("lots"), Strip("-5"), Strip("") })
+ {
+ var snapshot = PlayerProfileHtmlParser.Parse(Page(strip));
+
+ Assert.Null(snapshot.Silver);
+ Assert.Equal("Warrior", snapshot.ActiveClassName);
+ Assert.Equal(5, snapshot.Classes["Warrior"].CurrentXp);
+ }
+
+ var read = PlayerProfileHtmlParser.Parse(Page(Strip("13,025,343")));
+
+ Assert.Equal(13_025_343, read.Silver);
+ Assert.Equal(95_050, read.Gold);
+ Assert.Equal("Arena", read.Location);
+ }
+}
diff --git a/src/FourFoldAccountManager.Core/Tracking/PlayerProfileHtmlParser.cs b/src/FourFoldAccountManager.Core/Tracking/PlayerProfileHtmlParser.cs
index 3a68acf..f3b7f13 100644
--- a/src/FourFoldAccountManager.Core/Tracking/PlayerProfileHtmlParser.cs
+++ b/src/FourFoldAccountManager.Core/Tracking/PlayerProfileHtmlParser.cs
@@ -73,9 +73,24 @@ public static PlayerProgressSnapshot Parse(string html)
});
}
- return new PlayerProgressSnapshot(username, activeClassName, classes, invalid);
+ return new PlayerProgressSnapshot(username, activeClassName, classes, invalid)
+ {
+ Silver = ReadGameNumber(document, "Silver"),
+ Gold = ReadGameNumber(document, "Gold"),
+ Location = ReadGameStat(document, "Location") is { Length: > 0 } location ? location : null
+ };
}
+ // The strip of facts above the classes:
Silver1,234
.
+ // Nothing that tracks XP needs it, so a missing or changed strip gives null and never throws.
+ private static string? ReadGameStat(IDocument document, string label) =>
+ document.QuerySelectorAll(".social-game-stats .social-game-stat")
+ .FirstOrDefault(stat => stat.QuerySelector("span")?.TextContent.Trim() == label)
+ ?.QuerySelector("strong")?.TextContent.Trim();
+
+ private static long? ReadGameNumber(IDocument document, string label) =>
+ TryParseNonnegativeLong(ReadGameStat(document, label), out var value) ? value : null;
+
private static ProfileStats ReadStats(IElement card) => new(
ParseDisplayedStat(ReadMeta(card, "HP"), useMaximum: true),
ParseDisplayedStat(ReadMeta(card, "SP"), useMaximum: true),
diff --git a/src/FourFoldAccountManager.Core/Tracking/PlayerProgressSnapshot.cs b/src/FourFoldAccountManager.Core/Tracking/PlayerProgressSnapshot.cs
index 387e646..180fcc8 100644
--- a/src/FourFoldAccountManager.Core/Tracking/PlayerProgressSnapshot.cs
+++ b/src/FourFoldAccountManager.Core/Tracking/PlayerProgressSnapshot.cs
@@ -4,4 +4,10 @@ public sealed record PlayerProgressSnapshot(
string Username,
string? ActiveClassName,
IReadOnlyDictionary Classes,
- IReadOnlyList InvalidClasses);
+ IReadOnlyList InvalidClasses)
+{
+ // From the profile's game-stats strip. Null when the page doesn't give them; nothing that tracks XP needs them.
+ public long? Silver { get; init; }
+ public long? Gold { get; init; }
+ public string? Location { get; init; }
+}
From 08b0c68e12eac60dedac37bee17e7db6f3be2be7 Mon Sep 17 00:00:00 2001
From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com>
Date: Sun, 4 Oct 2026 19:36:33 -0500
Subject: [PATCH 2/9] feat: give plugins silver, gold, location, player id and
equipment as API version 2
---
.../Plugins/PluginManifestReaderTests.cs | 2 +-
.../Plugins/PluginManifestReader.cs | 3 +-
.../Plugins/PluginApiTests.cs | 2 +
.../Plugins/PluginHostDataTests.cs | 11 ++++
.../MainWindow.CommunityPlugins.cs | 50 ++++++++++++++++++-
.../Plugins/Web/PluginApi.cs | 2 +
.../Plugins/Web/PluginHostData.cs | 16 +++++-
.../Plugins/Web/PluginSdk.cs | 1 +
8 files changed, 83 insertions(+), 4 deletions(-)
diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs
index 2d728c6..ec57ddc 100644
--- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs
+++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs
@@ -99,7 +99,7 @@ public void AValidManifestLoadsWithItsSitesAndCards()
[InlineData("\"id\": \"nul.tools\"")]
[InlineData("\"id\": \"com1.tools\"")]
[InlineData("\"id\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"")]
- [InlineData("\"apiVersion\": 2")]
+ [InlineData("\"apiVersion\": 3")]
[InlineData("\"apiVersion\": \"1\"")]
[InlineData("\"panel\": \"missing.html\"")]
[InlineData("\"panel\": \"plugin.json\"")]
diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs
index 95a278b..000f073 100644
--- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs
+++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs
@@ -8,7 +8,8 @@ namespace FourFoldAccountManager.Core.Plugins;
public static partial class PluginManifestReader
{
- public const int SupportedApiVersion = 1;
+ // 2 added fourfold.profile, and equipment on stats.get.
+ public const int SupportedApiVersion = 2;
// author.plugin-name: lowercase letters, digits and dashes in dot-separated parts, with at least one dot.
public const string IdPattern = @"[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+";
diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs
index 068e2c0..84c26f4 100644
--- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs
+++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs
@@ -285,6 +285,8 @@ private sealed class FakeHost : IPluginHostData
public PluginStatsInfo? GetStats(Guid accountId) => null;
+ public PluginProfileInfo? GetProfile(Guid accountId) => null;
+
public PluginTimerInfo GetTimer() => new("stopped", 0, []);
public bool IsPanelShowing(string pluginId) => PanelShowing;
diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs
index 467d231..37d88b7 100644
--- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs
+++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs
@@ -14,4 +14,15 @@ public void ABlankRankingNameNeverExposesTheProfileName()
Assert.Equal("HERO", MainWindow.PublicInGameName("Hero", "HERO"));
Assert.Equal("Hero", MainWindow.PublicInGameName("Hero", null));
}
+
+ [Fact]
+ public void ABlankRankingNameNeverExposesThePlayerId()
+ {
+ // The id leads to a public page that shows the profile's name, and with no ranking name that name is the login.
+ Assert.Null(MainWindow.PublicPlayerId(null, 277));
+ Assert.Null(MainWindow.PublicPlayerId("", 277));
+ Assert.Null(MainWindow.PublicPlayerId(" ", 277));
+ Assert.Equal(277, MainWindow.PublicPlayerId("Hero", 277));
+ Assert.Null(MainWindow.PublicPlayerId("Hero", null));
+ }
}
diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs
index 5cb60e0..beaef7f 100644
--- a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs
+++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs
@@ -202,6 +202,25 @@ private void NotifyPluginsOfDataChanges()
internal static string? PublicInGameName(string? rankingUsername, string? profileUsername) =>
string.IsNullOrWhiteSpace(rankingUsername) ? null : profileUsername ?? rankingUsername;
+ // The player id plugins may see, under the same rule as the name: with no ranking name saved the profile was
+ // looked up by the saved login, and the id leads straight to a public page that shows it.
+ internal static int? PublicPlayerId(string? rankingUsername, int? playerId) =>
+ string.IsNullOrWhiteSpace(rankingUsername) ? null : playerId;
+
+ // Text the game's site wrote (a location, an item's name), made safe to hand to a plugin: trimmed, at most 64
+ // characters, and dropped if it could rearrange or hide the text a plugin draws around it.
+ internal static string? PublicGameText(string? text)
+ {
+ text = text?.Trim();
+ if (string.IsNullOrEmpty(text) || PluginText.HasUnsafeCharacter(text))
+ {
+ return null;
+ }
+
+ // Never cut between the two halves of a character outside the basic plane.
+ return text.Length <= 64 ? text : text[..(char.IsHighSurrogate(text[63]) ? 63 : 64)];
+ }
+
IReadOnlyList IPluginHostData.GetAccounts() =>
_accounts.Select(account => new PluginAccountInfo(
account.Id,
@@ -244,10 +263,39 @@ IReadOnlyList IPluginHostData.GetAccounts() =>
var snapshot = _xpTracker.GetLatestSnapshot(accountId);
return snapshot?.ActiveClassName is { } className && snapshot.Classes.TryGetValue(className, out var active)
? new PluginStatsInfo(className, active.Level, active.Hp, active.Sp, active.Attack, active.Magic,
- active.Skill, active.Speed, active.Luck, active.Defense, active.Resistance)
+ active.Skill, active.Speed, active.Luck, active.Defense, active.Resistance,
+ new PluginEquipmentInfo(
+ PublicGameText(active.Equipment.GetValueOrDefault("Armor")),
+ PublicGameText(active.Equipment.GetValueOrDefault("Helmet")),
+ PublicGameText(active.Equipment.GetValueOrDefault("Hair")),
+ PublicGameText(active.Equipment.GetValueOrDefault("Weapon"))))
: null;
}
+ PluginProfileInfo? IPluginHostData.GetProfile(Guid accountId)
+ {
+ var account = _accounts.FirstOrDefault(candidate => candidate.Id == accountId);
+ if (account is null)
+ {
+ return null;
+ }
+
+ var state = _xpTracker.GetStates().FirstOrDefault(candidate => candidate.AccountId == accountId);
+ var snapshot = _xpTracker.GetLatestSnapshot(accountId);
+ var playerId = _xpTracker.GetActiveLeaderboardProfiles()
+ .Where(profile => profile.AccountId == accountId)
+ .Select(profile => (int?)profile.PlayerId)
+ .FirstOrDefault();
+ return new PluginProfileInfo(
+ PublicPlayerId(account.RankingUsername, playerId),
+ snapshot?.Silver,
+ snapshot?.Gold,
+ PublicGameText(snapshot?.Location),
+ state?.LastUpdated,
+ // No data yet reads as stale, for an open account as for a closed one. The same rule as GetXp.
+ state is null || state.IsStale || state.LastUpdated is null);
+ }
+
PluginTimerInfo IPluginHostData.GetTimer()
{
var snapshot = _timer.Snapshot();
diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs
index 1779d7f..c3b4e77 100644
--- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs
+++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs
@@ -111,6 +111,8 @@ internal sealed class PluginApi(
? host.GetStats(accountId)
: throw UnknownAccount();
}
+ case "profile.get":
+ return host.GetProfile(AccountId(parameters)) ?? throw UnknownAccount();
case "timer.get":
return host.GetTimer();
case "storage.get":
diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs
index 4f651f0..550fcb3 100644
--- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs
+++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs
@@ -28,7 +28,18 @@ public sealed record PluginStatsInfo(
long? Speed,
long? Luck,
long? Defense,
- long? Resistance);
+ long? Resistance,
+ PluginEquipmentInfo Equipment);
+
+public sealed record PluginEquipmentInfo(string? Armor, string? Helmet, string? Hair, string? Weapon);
+
+public sealed record PluginProfileInfo(
+ int? PlayerId,
+ long? Silver,
+ long? Gold,
+ string? Location,
+ DateTimeOffset? UpdatedAt,
+ bool IsStale);
public sealed record PluginLapInfo(int Number, long LapMs, long TotalMs);
@@ -45,6 +56,9 @@ public interface IPluginHostData
// Null before the account's first profile read.
PluginStatsInfo? GetStats(Guid accountId);
+ // Null when the account id isn't one of the user's accounts.
+ PluginProfileInfo? GetProfile(Guid accountId);
+
PluginTimerInfo GetTimer();
// True while this plugin's panel is the one showing in the strip.
diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs
index 5e79093..2e06c33 100644
--- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs
+++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs
@@ -90,6 +90,7 @@ internal static class PluginSdk
onUpdated: callback => on('xp.updated', callback)
}),
stats: Object.freeze({ get: accountId => call('stats.get', { accountId }) }),
+ profile: Object.freeze({ get: accountId => call('profile.get', { accountId }) }),
timer: Object.freeze({
get: () => call('timer.get'),
onChanged: callback => on('timer.changed', callback)
From 9dbafed0e20430db688121398ac81a25f03ad06e Mon Sep 17 00:00:00 2001
From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com>
Date: Sun, 4 Oct 2026 19:37:23 -0500
Subject: [PATCH 3/9] feat: add the Silver tracker's rate and goal maths, with
a check
---
samples/silver-tracker/.check/rate.check.mjs | 61 ++++++++++++++++++
samples/silver-tracker/rate.mjs | 67 ++++++++++++++++++++
2 files changed, 128 insertions(+)
create mode 100644 samples/silver-tracker/.check/rate.check.mjs
create mode 100644 samples/silver-tracker/rate.mjs
diff --git a/samples/silver-tracker/.check/rate.check.mjs b/samples/silver-tracker/.check/rate.check.mjs
new file mode 100644
index 0000000..97b4d03
--- /dev/null
+++ b/samples/silver-tracker/.check/rate.check.mjs
@@ -0,0 +1,61 @@
+// Checks rate.mjs outside FourFold. Run: node samples/silver-tracker/.check/rate.check.mjs
+import assert from 'node:assert/strict';
+import { applyRead, createSession, parseGoal, rateAt, toGoal } from '../rate.mjs';
+
+const at = minutes => new Date(Date.UTC(2026, 9, 4, 12, 0) + minutes * 60000).toISOString();
+const read = (silver, minutes, isStale = false) => ({ silver, updatedAt: at(minutes), isStale });
+const feed = (...reads) => {
+ const session = createSession();
+ for (const next of reads) applyRead(session, next);
+ return session;
+};
+const rate = session => rateAt(session, session.lastAt);
+const net = session => session.lastBalance - session.startBalance;
+
+// One read alone gives no rate. Two reads a minute apart: 600 silver in 60 seconds is 36,000 an hour.
+assert.equal(rate(feed(read(1000, 0))), null);
+let session = feed(read(1000, 0), read(1600, 1));
+assert.equal(session.earned, 600);
+assert.equal(Math.round(rate(session)), 36000);
+
+// Spending adds nothing to earned and never makes the rate negative. Net does go negative.
+session = feed(read(5000, 0), read(2000, 1), read(2500, 2));
+assert.equal(session.earned, 500);
+assert.equal(net(session), -2500);
+assert.equal(Math.round(rate(session)), 15000);
+
+// A failed read, then a good one half an hour later with far more silver: no interval spans the gap, so the rate
+// doesn't spike. Net is still the true change.
+session = feed(read(1000, 0), read(1100, 1), read(1100, 1, true), read(9000, 30), read(9100, 31));
+assert.equal(session.intervals.length, 2);
+assert.equal(session.earned, 200);
+assert.equal(net(session), 8100);
+assert.equal(Math.round(rate(session)), 6000);
+
+// The same read twice, or one stamped earlier than the last, changes nothing.
+session = feed(read(1000, 0), read(1600, 1), read(1600, 1), read(99999, 0));
+assert.equal(session.earned, 600);
+assert.equal(session.intervals.length, 1);
+
+// A read with no silver or no time counts as missed, like a stale one.
+session = feed(read(1000, 0), { silver: null, updatedAt: null, isStale: false }, read(5000, 1), read(5100, 2));
+assert.equal(session.earned, 100);
+
+// Only the last hour counts. An interval that ended before it is dropped; one that straddles it counts in part.
+session = feed(read(0, 0), read(60000, 1), read(60000, 90), read(60000, 91));
+assert.equal(rate(session), 0);
+assert.equal(session.earned, 60000);
+assert.equal(Math.round(rate(feed(read(0, 0), read(1200, 120)))), 600);
+
+// A goal is a whole number above zero, with commas or spaces as separators. Anything else is no goal.
+assert.equal(parseGoal('1,000,000'), 1000000);
+assert.equal(parseGoal(' 250 000 '), 250000);
+for (const bad of ['', '0', '-5', '1.5', '1e9', 'abc', '9'.repeat(16)]) assert.equal(parseGoal(bad), null);
+
+// Time to a goal needs a rate above zero. A reached goal has nothing left.
+assert.deepEqual(toGoal(1000, 400, 300), { remaining: 600, progress: 0.4, hours: 2 });
+assert.equal(toGoal(1000, 400, null).hours, null);
+assert.equal(toGoal(1000, 400, 0).hours, null);
+assert.deepEqual(toGoal(1000, 2500, 300), { remaining: 0, progress: 1, hours: null });
+
+console.log('rate.mjs: all checks passed');
diff --git a/samples/silver-tracker/rate.mjs b/samples/silver-tracker/rate.mjs
new file mode 100644
index 0000000..e49f753
--- /dev/null
+++ b/samples/silver-tracker/rate.mjs
@@ -0,0 +1,67 @@
+// Session, rate and goal maths for the Silver tracker. Nothing here touches the page or window.fourfold, so
+// .check/rate.check.mjs can run it with Node.
+
+const HOUR_MS = 3600000;
+
+// One account's session: what has been seen since tracking started. Times are milliseconds since the epoch.
+export function createSession() {
+ return { startBalance: null, lastBalance: null, lastAt: null, intervals: [], earned: 0, missed: false };
+}
+
+// Takes one answer from fourfold.profile.get.
+export function applyRead(session, read) {
+ const at = typeof read.updatedAt === 'string' ? Date.parse(read.updatedAt) : NaN;
+ if (read.isStale || !Number.isFinite(read.silver) || Number.isNaN(at)) {
+ session.missed = true;
+ return;
+ }
+ // The same read again: xp.onUpdated also fires for changes that aren't a new read.
+ if (session.lastAt !== null && at <= session.lastAt) return;
+ if (session.lastAt === null || session.missed) {
+ // Nothing trustworthy to measure from. FourFold's XP tracker starts over after a missed read too.
+ session.startBalance ??= read.silver;
+ session.missed = false;
+ } else {
+ // Silver earned only: a drop is spending, and adds nothing.
+ const gain = Math.max(0, read.silver - session.lastBalance);
+ session.intervals.push({ from: session.lastAt, to: at, gain });
+ session.earned += gain;
+ }
+ session.lastBalance = read.silver;
+ session.lastAt = at;
+ session.intervals = session.intervals.filter(interval => interval.to > at - HOUR_MS);
+}
+
+// Silver per hour over the hour ending at `now`, or null when nothing in that hour was measured. The same sum as
+// FourFold's XpRateWindow: each interval counts for the part of it inside the hour.
+export function rateAt(session, now) {
+ const start = now - HOUR_MS;
+ let gain = 0;
+ let covered = 0;
+ for (const interval of session.intervals) {
+ const overlap = Math.min(interval.to, now) - Math.max(interval.from, start);
+ if (overlap <= 0) continue;
+ gain += interval.gain * overlap / (interval.to - interval.from);
+ covered += overlap;
+ }
+ return covered > 0 ? gain / covered * HOUR_MS : null;
+}
+
+// A goal as the user typed it: digits, with commas or spaces as thousands separators. Null when it isn't a whole
+// number above zero. A dot is refused, not read as a separator: "1.5" must not become 15.
+export function parseGoal(text) {
+ const digits = String(text).replace(/[\s,]/g, '');
+ if (!/^\d{1,15}$/.test(digits)) return null;
+ const goal = Number(digits);
+ return goal > 0 ? goal : null;
+}
+
+// What is left to a goal and how long it takes at this rate. hours is null without a rate above zero.
+export function toGoal(goal, balance, rate) {
+ const remaining = Math.max(0, goal - balance);
+ return {
+ remaining,
+ progress: Math.min(1, Math.max(0, balance / goal)),
+ hours: remaining > 0 && rate > 0 ? remaining / rate : null
+ };
+}
From 71ce7c01a8e2e2d844e69d951d1912d94b97038f Mon Sep 17 00:00:00 2001
From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com>
Date: Sun, 4 Oct 2026 19:38:05 -0500
Subject: [PATCH 4/9] feat: add the Silver tracker plugin
---
samples/silver-tracker/app.js | 196 +++++++++++++++++++++++++++++
samples/silver-tracker/index.html | 15 +++
samples/silver-tracker/plugin.json | 11 ++
samples/silver-tracker/style.css | 14 +++
4 files changed, 236 insertions(+)
create mode 100644 samples/silver-tracker/app.js
create mode 100644 samples/silver-tracker/index.html
create mode 100644 samples/silver-tracker/plugin.json
create mode 100644 samples/silver-tracker/style.css
diff --git a/samples/silver-tracker/app.js b/samples/silver-tracker/app.js
new file mode 100644
index 0000000..fe87ca1
--- /dev/null
+++ b/samples/silver-tracker/app.js
@@ -0,0 +1,196 @@
+// Silver tracker: silver earned per hour, session totals and a silver goal for each open account, in the panel and
+// on a card. The maths is in rate.mjs.
+import { applyRead, createSession, parseGoal, rateAt, toGoal } from './rate.mjs';
+
+const container = document.getElementById('accounts');
+const empty = document.getElementById('empty');
+const sessions = new Map(); // account id -> session; open accounts only
+const blocks = new Map(); // account id -> that account's elements in the panel
+let goals = {};
+
+const whole = value => Math.round(value).toLocaleString('en-US');
+const signed = value => (value > 0 ? '+' : '') + whole(value);
+// A card's text can be at most 40 characters, and FourFold refuses a longer line, so clip it.
+const fit = text => (text.length > 40 ? `${text.slice(0, 39)}…` : text);
+const goalFor = id => (Number.isSafeInteger(goals[id]) && goals[id] > 0 ? goals[id] : null);
+
+function duration(hours) {
+ if (hours >= 10000) return '9,999h+';
+ const minutes = Math.max(1, Math.round(hours * 60));
+ return minutes < 60 ? `${minutes}m` : `${whole(Math.floor(minutes / 60))}h ${minutes % 60}m`;
+}
+
+function goalText(left) {
+ if (left.remaining === 0) return 'Reached';
+ const toGo = `${whole(left.remaining)} to go`;
+ return left.hours === null ? toGo : `${toGo} · ${duration(left.hours)}`;
+}
+
+// Everything one account's block and card show.
+function describe(account, session, read) {
+ const tracked = session.lastAt !== null;
+ const balance = tracked ? session.lastBalance : null;
+ const rate = tracked ? rateAt(session, session.lastAt) : null;
+ const goal = goalFor(account.id);
+ return {
+ id: account.id,
+ label: account.label,
+ balance,
+ rate,
+ earned: session.earned,
+ net: tracked ? balance - session.startBalance : null,
+ goal,
+ left: goal !== null && tracked ? toGoal(goal, balance, rate) : null,
+ status: !tracked ? 'No data yet'
+ : read.isStale ? 'Stale; the last read failed'
+ : rate === null ? 'Collecting baseline' : 'Tracking'
+ };
+}
+
+async function setCard(view) {
+ if (view.balance === null) {
+ await fourfold.cards.clear('silver', view.id);
+ return;
+ }
+ const rows = [
+ { label: 'Silver/hr', value: fit(view.rate === null ? 'No rate yet' : whole(view.rate)) },
+ { label: 'Session', value: fit(`+${whole(view.earned)} (net ${signed(view.net)})`) }
+ ];
+ if (view.left) rows.push({ label: 'Goal', value: fit(goalText(view.left)), progress: view.left.progress });
+ await fourfold.cards.set('silver', view.id, {
+ summary: fit(view.rate === null ? 'No rate yet' : `${whole(view.rate)}/hr`),
+ rows
+ });
+}
+
+function element(tag, className, parent) {
+ const created = document.createElement(tag);
+ if (className) created.className = className;
+ parent.append(created);
+ return created;
+}
+
+// One account's block, built once. Its handlers look the account up by id, so they never hold stale data.
+function createBlock(id) {
+ const root = document.createElement('div');
+ root.className = 'account';
+ const parts = { root, title: element('h2', '', root), rate: element('p', 'rate', root) };
+ parts.session = element('p', '', root);
+ parts.balance = element('p', '', root);
+ const label = element('label', '', root);
+ label.textContent = 'Goal';
+ parts.input = element('input', '', label);
+ parts.input.type = 'text';
+ parts.input.inputMode = 'numeric';
+ parts.input.placeholder = 'Target silver';
+ parts.bar = element('div', 'bar', root);
+ parts.fill = element('div', '', parts.bar);
+ parts.goal = element('p', '', root);
+ parts.status = element('p', 'status', root);
+ const reset = element('button', '', root);
+ reset.type = 'button';
+ reset.textContent = 'Reset';
+
+ parts.input.addEventListener('change', async () => {
+ const goal = parseGoal(parts.input.value);
+ if (goal === null) delete goals[id];
+ else goals[id] = goal;
+ await saveGoals();
+ await render();
+ });
+ // Leaving the box redraws it at once, so a goal that wasn't accepted doesn't stay on show.
+ parts.input.addEventListener('blur', render);
+ // Ending the session is enough: the next refresh starts a new one from the latest read.
+ reset.addEventListener('click', () => {
+ sessions.delete(id);
+ render();
+ });
+ return parts;
+}
+
+function updateBlock(parts, view) {
+ parts.title.textContent = view.label;
+ parts.title.title = view.label;
+ parts.rate.textContent = view.rate === null ? 'No rate yet' : `${whole(view.rate)} silver/hr`;
+ const tracked = view.balance !== null;
+ parts.session.hidden = !tracked;
+ parts.balance.hidden = !tracked;
+ if (tracked) {
+ parts.session.textContent = `Session: +${whole(view.earned)} earned, ${signed(view.net)} net`;
+ parts.balance.textContent = `Balance: ${whole(view.balance)}`;
+ }
+ // Never rewrite the box under the user's cursor.
+ if (document.activeElement !== parts.input) parts.input.value = view.goal === null ? '' : whole(view.goal);
+ parts.bar.hidden = !view.left;
+ parts.goal.hidden = !view.left;
+ if (view.left) {
+ parts.fill.style.width = `${Math.round(view.left.progress * 100)}%`;
+ parts.goal.textContent = goalText(view.left);
+ }
+ parts.status.textContent = view.status;
+}
+
+function paint(views) {
+ for (const [id, parts] of blocks) {
+ if (views.every(view => view.id !== id)) {
+ parts.root.remove();
+ blocks.delete(id);
+ }
+ }
+ views.forEach((view, index) => {
+ let parts = blocks.get(view.id);
+ if (!parts) blocks.set(view.id, (parts = createBlock(view.id)));
+ // Moving a block drops its focus, so only move one that is out of place.
+ if (container.children[index] !== parts.root) container.insertBefore(parts.root, container.children[index] ?? null);
+ updateBlock(parts, view);
+ });
+ empty.hidden = views.length > 0;
+}
+
+async function refresh() {
+ const open = (await fourfold.accounts.list()).filter(account => account.isOpen);
+ // A closed account's session is over, and its card goes with it.
+ for (const id of [...sessions.keys()]) {
+ if (open.every(account => account.id !== id)) {
+ sessions.delete(id);
+ await fourfold.cards.clear('silver', id).catch(() => {});
+ }
+ }
+
+ const views = [];
+ for (const account of open) {
+ let session = sessions.get(account.id);
+ if (!session) sessions.set(account.id, (session = createSession()));
+ const read = await fourfold.profile.get(account.id);
+ applyRead(session, read);
+ const view = describe(account, session, read);
+ // A refused card must not stop the panel from updating.
+ await setCard(view).catch(error => console.warn(error.code ?? error.message));
+ views.push(view);
+ }
+ paint(views);
+}
+
+// Events arrive in bursts (xp.onUpdated fires once per account), so refreshes run one after another, never
+// overlapping.
+let queue = Promise.resolve();
+const render = () => (queue = queue.then(refresh).catch(error => console.warn(error.code ?? error.message)));
+
+async function saveGoals() {
+ // Goals for accounts that no longer exist go, so the store doesn't grow for ever.
+ const known = new Set((await fourfold.accounts.list()).map(account => account.id));
+ for (const id of Object.keys(goals)) {
+ if (!known.has(id)) delete goals[id];
+ }
+ await fourfold.storage.set('goals', goals);
+}
+
+async function start() {
+ const saved = await fourfold.storage.get('goals');
+ goals = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};
+ fourfold.accounts.onChanged(render);
+ fourfold.xp.onUpdated(render);
+ await render();
+}
+
+start().catch(error => { container.textContent = `Silver tracker failed: ${error.message}`; });
diff --git a/samples/silver-tracker/index.html b/samples/silver-tracker/index.html
new file mode 100644
index 0000000..13d4fe2
--- /dev/null
+++ b/samples/silver-tracker/index.html
@@ -0,0 +1,15 @@
+
+
+
+
+ Silver tracker
+
+
+
+
Silver tracker
+
Silver earned per hour for each open account.
+
Open an account to track its silver.
+
+
+
+
diff --git a/samples/silver-tracker/plugin.json b/samples/silver-tracker/plugin.json
new file mode 100644
index 0000000..9736cc5
--- /dev/null
+++ b/samples/silver-tracker/plugin.json
@@ -0,0 +1,11 @@
+{
+ "id": "fourfold.silver-tracker",
+ "name": "Silver tracker",
+ "shortLabel": "Silver",
+ "version": "1.0.0",
+ "author": "FourFold",
+ "description": "Silver per hour, session totals and a silver goal for each open account.",
+ "apiVersion": 2,
+ "panel": "index.html",
+ "cards": [{ "id": "silver", "name": "Silver", "scope": "account" }]
+}
diff --git a/samples/silver-tracker/style.css b/samples/silver-tracker/style.css
new file mode 100644
index 0000000..256d87b
--- /dev/null
+++ b/samples/silver-tracker/style.css
@@ -0,0 +1,14 @@
+body { margin: 0; padding: 14px; background: var(--ff-surface); color: var(--ff-text); font: 13px "Segoe UI", sans-serif; }
+h1 { margin: 0 0 4px; font-size: 16px; font-weight: 600; }
+.muted { color: var(--ff-text-muted); margin: 0 0 12px; }
+.account { background: var(--ff-surface-raised); border: 1px solid var(--ff-border); border-radius: 6px; padding: 10px; margin-bottom: 8px; }
+.account h2 { margin: 0 0 6px; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.account p { margin: 3px 0 0; font-size: 11px; }
+.account .rate { margin: 0; font-size: 17px; font-weight: 700; color: var(--ff-accent); font-variant-numeric: tabular-nums; }
+.account label { display: block; color: var(--ff-text-muted); font-size: 11px; margin-top: 9px; }
+.account input { display: block; box-sizing: border-box; width: 100%; margin-top: 3px; background: var(--ff-background); color: var(--ff-text); border: 1px solid var(--ff-border); border-radius: 4px; padding: 3px 6px; font: inherit; }
+.account .status { color: var(--ff-text-muted); font-size: 10px; margin-top: 9px; }
+.account button { margin-top: 8px; background: var(--ff-surface); color: var(--ff-text); border: 1px solid var(--ff-border); border-radius: 4px; padding: 3px 10px; font: inherit; cursor: pointer; }
+.account button:hover { border-color: var(--ff-accent); }
+.bar { height: 4px; border-radius: 2px; background: var(--ff-border); margin-top: 8px; }
+.bar > div { height: 100%; border-radius: 2px; background: var(--ff-accent); }
From fed19db308e8816f5c720f03181e8e851c185027 Mon Sep 17 00:00:00 2001
From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com>
Date: Sun, 4 Oct 2026 19:38:45 -0500
Subject: [PATCH 5/9] docs: document fourfold.profile, equipment and API
version 2
---
PLUGIN_AUTHORS.md | 30 +++++++++++++++++++++++++-----
1 file changed, 25 insertions(+), 5 deletions(-)
diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md
index 01df8c6..30833e3 100644
--- a/PLUGIN_AUTHORS.md
+++ b/PLUGIN_AUTHORS.md
@@ -8,7 +8,7 @@ A plugin is a folder with a `plugin.json` file and ordinary web files: HTML, Jav
The page runs in its own sandboxed browser. It talks to FourFold only through `window.fourfold`, a small API that gives it:
-- read-only data from FourFold: the accounts, their XP and stats, and the timer (never logins);
+- read-only data from FourFold: the accounts, their XP, stats, equipment, silver, gold and location, and the timer (never logins);
- web requests to the sites the plugin declares;
- a small private store;
- overlay cards, drawn by FourFold.
@@ -29,7 +29,7 @@ Users get plugins from the plugin hub: they open the plugin list (the wrench in
When you build on a copy of a sample, change its `id` and `author` in `plugin.json` first.
-The other sample, `samples/sandbox-check`, contacts example.com each time it runs. See [Check your own plugin](#check-your-own-plugin).
+`samples/silver-tracker` is a fuller example: it reads `fourfold.profile`, keeps its maths in a module, and has a check that runs with Node. The third sample, `samples/sandbox-check`, contacts example.com each time it runs. See [Check your own plugin](#check-your-own-plugin).
Every folder directly inside `dev-plugins` is one plugin.
@@ -70,7 +70,7 @@ A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load,
| `version` | yes | `MAJOR.MINOR.PATCH`, digits only, such as `1.0.0`. |
| `author` | yes | 1 to 40 characters. |
| `description` | no | At most 200 characters. |
-| `apiVersion` | yes | A whole number. FourFold supports `1`. A higher number is rejected with "Update FourFold to use this plugin." |
+| `apiVersion` | yes | A whole number: the lowest API version the plugin needs. FourFold supports `1` and `2`. Declare `2` if the plugin calls `fourfold.profile` or reads `equipment`, so that an older FourFold tells the user to update instead of running a plugin that can't work. A higher number is rejected with "Update FourFold to use this plugin." |
| `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. |
| `icon` | no | Path to a `.png` file inside the plugin folder, at most 256 by 256 pixels and 64 KB. Forward slashes only. Without one, the strip shows a default icon. |
| `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no trailing dot, and no name that only works on the local network. `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names are refused, and so is a single-label name such as `router`. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. An international host name is fine: FourFold converts it to its `xn--` form, and that form is what it shows users. After the conversion the host can contain only letters, digits, dots and dashes, so a name with an underscore or any other punctuation is refused. |
@@ -151,7 +151,27 @@ const stats = await fourfold.stats.get(account.id);
if (stats) console.log(stats.className, stats.level, stats.hp, stats.attack);
```
-`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. An unknown account id is rejected with `invalid-argument`.
+`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the item's name, or `null` when the slot is empty or unknown. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`.
+
+### Profile
+
+```js
+const profile = await fourfold.profile.get(account.id);
+if (!profile.isStale && profile.silver !== null) console.log(account.label, 'has', profile.silver, 'silver');
+```
+
+`fourfold.profile.get(accountId)` returns facts from the account's public profile page. It needs `"apiVersion": 2`.
+
+| Field | Type | Meaning |
+|---|---|---|
+| `silver` | number or null | The account's silver. |
+| `gold` | number or null | The account's gold. |
+| `location` | string or null | Where the character is, as the profile page words it. At most 64 characters. |
+| `playerId` | number or null | The account's public player id. Like `inGameName`, it is `null` unless the user has filled in that account's **Ranking username**. |
+| `updatedAt` | string or null | Time of the last successful read, as an ISO 8601 date. |
+| `isStale` | boolean | `true` when there is no data yet, when the last read failed, and for a closed account. |
+
+The data comes from the same read as XP: about once a minute, for open accounts only. There is no profile event: read `profile.get` again when `xp.onUpdated` fires. That event also fires for changes that aren't a new read, and `updatedAt` only changes with a new one, so compare it to tell them apart. After a failed read the fields keep their last values and `isStale` is `true`. For a closed account the number and text fields are `null`. An unknown account id is rejected with `invalid-argument`.
### Timer
@@ -387,7 +407,7 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve
- Read or control the game, or see its pages, cookies or sessions.
- See logins: usernames, emails and passwords are never exposed. Plugins can't see other plugins or any file outside their own folder either.
-- Get real-time data. XP data arrives about once a minute, and the timer sends no tick events.
+- Get real-time data. XP and profile data arrive about once a minute, and the timer sends no tick events.
- Use shortcut keys, sounds or desktop notifications.
- Draw custom cards. Cards are FourFold's data cards.
- Add a settings page behind the cog. Keep settings in your own panel.
From a5a8873a6cf794c4280782e6455a55425380a42a Mon Sep 17 00:00:00 2001
From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com>
Date: Sun, 4 Oct 2026 19:38:45 -0500
Subject: [PATCH 6/9] ci: skip the release when a merge changes only the sample
plugins
---
.github/workflows/tag-on-merge.yml | 1 +
1 file changed, 1 insertion(+)
diff --git a/.github/workflows/tag-on-merge.yml b/.github/workflows/tag-on-merge.yml
index ada2a42..a306015 100644
--- a/.github/workflows/tag-on-merge.yml
+++ b/.github/workflows/tag-on-merge.yml
@@ -8,6 +8,7 @@ on:
paths-ignore:
- '**.md'
- 'docs/**'
+ - 'samples/**'
- '.github/**'
permissions:
From 04fc78a3fe5063dfc69ce6ceb200b98d0e914996 Mon Sep 17 00:00:00 2001
From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com>
Date: Sun, 4 Oct 2026 19:55:22 -0500
Subject: [PATCH 7/9] fix: keep a login's player id and name from plugins just
after a ranking name is saved
The tracker still holds what it read for the saved login until its next read. The id and the profile's name are now given to plugins only when the last profile read was made under the ranking name. The name rule had the same gap before this branch.
---
.../Plugins/PluginHostDataTests.cs | 18 ++++++++++++------
.../MainWindow.CommunityPlugins.cs | 15 +++++++++++----
2 files changed, 23 insertions(+), 10 deletions(-)
diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs
index 37d88b7..301da25 100644
--- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs
+++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs
@@ -13,16 +13,22 @@ public void ABlankRankingNameNeverExposesTheProfileName()
Assert.Null(MainWindow.PublicInGameName(" ", "MyLogin"));
Assert.Equal("HERO", MainWindow.PublicInGameName("Hero", "HERO"));
Assert.Equal("Hero", MainWindow.PublicInGameName("Hero", null));
+ // Just after a ranking name is saved, the last profile read is still the login's.
+ Assert.Equal("Hero", MainWindow.PublicInGameName("Hero", "MyLogin"));
}
[Fact]
- public void ABlankRankingNameNeverExposesThePlayerId()
+ public void ThePlayerIdIsOnlyGivenForAProfileReadUnderTheRankingName()
{
// The id leads to a public page that shows the profile's name, and with no ranking name that name is the login.
- Assert.Null(MainWindow.PublicPlayerId(null, 277));
- Assert.Null(MainWindow.PublicPlayerId("", 277));
- Assert.Null(MainWindow.PublicPlayerId(" ", 277));
- Assert.Equal(277, MainWindow.PublicPlayerId("Hero", 277));
- Assert.Null(MainWindow.PublicPlayerId("Hero", null));
+ Assert.Null(MainWindow.PublicPlayerId(null, "MyLogin", 277));
+ Assert.Null(MainWindow.PublicPlayerId("", "MyLogin", 277));
+ Assert.Null(MainWindow.PublicPlayerId(" ", "MyLogin", 277));
+ // Just after a ranking name is saved, the tracker still holds the id it resolved for the login.
+ Assert.Null(MainWindow.PublicPlayerId("Hero", "MyLogin", 277));
+ Assert.Null(MainWindow.PublicPlayerId("Hero", null, 277));
+ Assert.Equal(277, MainWindow.PublicPlayerId("Hero", "HERO", 277));
+ Assert.Equal(277, MainWindow.PublicPlayerId(" Hero ", "Hero", 277));
+ Assert.Null(MainWindow.PublicPlayerId("Hero", "Hero", null));
}
}
diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs
index beaef7f..279f832 100644
--- a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs
+++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs
@@ -200,12 +200,19 @@ private void NotifyPluginsOfDataChanges()
// The name plugins may see. With no ranking name saved, the profile is looked up by the saved login, so the
// name read from it is the login and stays private.
internal static string? PublicInGameName(string? rankingUsername, string? profileUsername) =>
- string.IsNullOrWhiteSpace(rankingUsername) ? null : profileUsername ?? rankingUsername;
+ string.IsNullOrWhiteSpace(rankingUsername) ? null
+ : IsRankingProfile(rankingUsername, profileUsername) ? profileUsername : rankingUsername;
// The player id plugins may see, under the same rule as the name: with no ranking name saved the profile was
// looked up by the saved login, and the id leads straight to a public page that shows it.
- internal static int? PublicPlayerId(string? rankingUsername, int? playerId) =>
- string.IsNullOrWhiteSpace(rankingUsername) ? null : playerId;
+ internal static int? PublicPlayerId(string? rankingUsername, string? profileUsername, int? playerId) =>
+ IsRankingProfile(rankingUsername, profileUsername) ? playerId : null;
+
+ // Whether the last profile read was made under the ranking name. Just after a ranking name is saved, the tracker
+ // still holds what it read for the saved login, and that belongs to the login until the next read.
+ private static bool IsRankingProfile(string? rankingUsername, string? profileUsername) =>
+ !string.IsNullOrWhiteSpace(rankingUsername) && profileUsername is not null &&
+ string.Equals(profileUsername.Trim(), rankingUsername.Trim(), StringComparison.OrdinalIgnoreCase);
// Text the game's site wrote (a location, an item's name), made safe to hand to a plugin: trimmed, at most 64
// characters, and dropped if it could rearrange or hide the text a plugin draws around it.
@@ -287,7 +294,7 @@ IReadOnlyList IPluginHostData.GetAccounts() =>
.Select(profile => (int?)profile.PlayerId)
.FirstOrDefault();
return new PluginProfileInfo(
- PublicPlayerId(account.RankingUsername, playerId),
+ PublicPlayerId(account.RankingUsername, snapshot?.Username, playerId),
snapshot?.Silver,
snapshot?.Gold,
PublicGameText(snapshot?.Location),
From d04f90b056b39ecdd5e77b7947e548908a9c9325 Mon Sep 17 00:00:00 2001
From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com>
Date: Sun, 4 Oct 2026 19:55:22 -0500
Subject: [PATCH 8/9] fix: show a Silver tracker account as stale whenever its
silver can't be read
The status followed the read's stale flag only, so a read that succeeded without a silver value left old numbers under "Tracking".
---
samples/silver-tracker/.check/rate.check.mjs | 13 ++++++++++++-
samples/silver-tracker/app.js | 13 +++++--------
samples/silver-tracker/rate.mjs | 7 +++++++
3 files changed, 24 insertions(+), 9 deletions(-)
diff --git a/samples/silver-tracker/.check/rate.check.mjs b/samples/silver-tracker/.check/rate.check.mjs
index 97b4d03..f0f789d 100644
--- a/samples/silver-tracker/.check/rate.check.mjs
+++ b/samples/silver-tracker/.check/rate.check.mjs
@@ -1,6 +1,6 @@
// Checks rate.mjs outside FourFold. Run: node samples/silver-tracker/.check/rate.check.mjs
import assert from 'node:assert/strict';
-import { applyRead, createSession, parseGoal, rateAt, toGoal } from '../rate.mjs';
+import { applyRead, createSession, parseGoal, rateAt, statusOf, toGoal } from '../rate.mjs';
const at = minutes => new Date(Date.UTC(2026, 9, 4, 12, 0) + minutes * 60000).toISOString();
const read = (silver, minutes, isStale = false) => ({ silver, updatedAt: at(minutes), isStale });
@@ -41,6 +41,17 @@ assert.equal(session.intervals.length, 1);
session = feed(read(1000, 0), { silver: null, updatedAt: null, isStale: false }, read(5000, 1), read(5100, 2));
assert.equal(session.earned, 100);
+// The status never calls old numbers live. If the page stops giving silver while the read itself still succeeds,
+// the account shows as stale until silver is back.
+assert.equal(statusOf(createSession()), 'No data yet');
+assert.equal(statusOf(feed(read(1000, 0))), 'Collecting baseline');
+assert.equal(statusOf(feed(read(1000, 0), read(1600, 1))), 'Tracking');
+session = feed(read(1000, 0), read(1600, 1), { silver: null, updatedAt: at(2), isStale: false });
+assert.equal(statusOf(session), 'Stale; the last read failed');
+applyRead(session, read(1700, 3));
+assert.equal(statusOf(session), 'Tracking');
+assert.equal(statusOf(feed(read(1000, 0), read(1000, 0, true))), 'Stale; the last read failed');
+
// Only the last hour counts. An interval that ended before it is dropped; one that straddles it counts in part.
session = feed(read(0, 0), read(60000, 1), read(60000, 90), read(60000, 91));
assert.equal(rate(session), 0);
diff --git a/samples/silver-tracker/app.js b/samples/silver-tracker/app.js
index fe87ca1..64e9df0 100644
--- a/samples/silver-tracker/app.js
+++ b/samples/silver-tracker/app.js
@@ -1,6 +1,6 @@
// Silver tracker: silver earned per hour, session totals and a silver goal for each open account, in the panel and
// on a card. The maths is in rate.mjs.
-import { applyRead, createSession, parseGoal, rateAt, toGoal } from './rate.mjs';
+import { applyRead, createSession, parseGoal, rateAt, statusOf, toGoal } from './rate.mjs';
const container = document.getElementById('accounts');
const empty = document.getElementById('empty');
@@ -27,7 +27,7 @@ function goalText(left) {
}
// Everything one account's block and card show.
-function describe(account, session, read) {
+function describe(account, session) {
const tracked = session.lastAt !== null;
const balance = tracked ? session.lastBalance : null;
const rate = tracked ? rateAt(session, session.lastAt) : null;
@@ -41,9 +41,7 @@ function describe(account, session, read) {
net: tracked ? balance - session.startBalance : null,
goal,
left: goal !== null && tracked ? toGoal(goal, balance, rate) : null,
- status: !tracked ? 'No data yet'
- : read.isStale ? 'Stale; the last read failed'
- : rate === null ? 'Collecting baseline' : 'Tracking'
+ status: statusOf(session)
};
}
@@ -161,9 +159,8 @@ async function refresh() {
for (const account of open) {
let session = sessions.get(account.id);
if (!session) sessions.set(account.id, (session = createSession()));
- const read = await fourfold.profile.get(account.id);
- applyRead(session, read);
- const view = describe(account, session, read);
+ applyRead(session, await fourfold.profile.get(account.id));
+ const view = describe(account, session);
// A refused card must not stop the panel from updating.
await setCard(view).catch(error => console.warn(error.code ?? error.message));
views.push(view);
diff --git a/samples/silver-tracker/rate.mjs b/samples/silver-tracker/rate.mjs
index e49f753..e874c01 100644
--- a/samples/silver-tracker/rate.mjs
+++ b/samples/silver-tracker/rate.mjs
@@ -47,6 +47,13 @@ export function rateAt(session, now) {
return covered > 0 ? gain / covered * HOUR_MS : null;
}
+// The account's status line. A missed read shows as stale whatever the reason, so old numbers never pass as live.
+export function statusOf(session) {
+ if (session.lastAt === null) return 'No data yet';
+ if (session.missed) return 'Stale; the last read failed';
+ return rateAt(session, session.lastAt) === null ? 'Collecting baseline' : 'Tracking';
+}
+
// A goal as the user typed it: digits, with commas or spaces as thousands separators. Null when it isn't a whole
// number above zero. A dot is refused, not read as a separator: "1.5" must not become 15.
export function parseGoal(text) {
From 32d41bd402f8c376ab48a943fafbe877c12aa50b Mon Sep 17 00:00:00 2001
From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com>
Date: Sun, 4 Oct 2026 19:55:23 -0500
Subject: [PATCH 9/9] docs: correct the guide on empty equipment slots, the
player id and failed reads
---
PLUGIN_AUTHORS.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md
index 30833e3..d256284 100644
--- a/PLUGIN_AUTHORS.md
+++ b/PLUGIN_AUTHORS.md
@@ -151,7 +151,7 @@ const stats = await fourfold.stats.get(account.id);
if (stats) console.log(stats.className, stats.level, stats.hp, stats.attack);
```
-`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the item's name, or `null` when the slot is empty or unknown. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`.
+`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the slot as the profile page words it, at most 64 characters, or `null` when unknown. An empty slot comes through as the page's own word for it (`Empty`, say), not as `null`. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`.
### Profile
@@ -167,11 +167,11 @@ if (!profile.isStale && profile.silver !== null) console.log(account.label, 'has
| `silver` | number or null | The account's silver. |
| `gold` | number or null | The account's gold. |
| `location` | string or null | Where the character is, as the profile page words it. At most 64 characters. |
-| `playerId` | number or null | The account's public player id. Like `inGameName`, it is `null` unless the user has filled in that account's **Ranking username**. |
+| `playerId` | number or null | The account's public player id. Like `inGameName`, it is `null` unless the user has filled in that account's **Ranking username**. It is also `null` until the profile has been read under that name. |
| `updatedAt` | string or null | Time of the last successful read, as an ISO 8601 date. |
| `isStale` | boolean | `true` when there is no data yet, when the last read failed, and for a closed account. |
-The data comes from the same read as XP: about once a minute, for open accounts only. There is no profile event: read `profile.get` again when `xp.onUpdated` fires. That event also fires for changes that aren't a new read, and `updatedAt` only changes with a new one, so compare it to tell them apart. After a failed read the fields keep their last values and `isStale` is `true`. For a closed account the number and text fields are `null`. An unknown account id is rejected with `invalid-argument`.
+The data comes from the same read as XP: about once a minute, for open accounts only. There is no profile event: read `profile.get` again when `xp.onUpdated` fires. That event also fires for changes that aren't a new read, and `updatedAt` only changes with a new one, so compare it to tell them apart. After a failed read `silver`, `gold`, `location` and `updatedAt` keep their last values and `isStale` is `true`. For a closed account the number and text fields are `null`. An unknown account id is rejected with `invalid-argument`.
### Timer