* Plan multiple Claude and Codex accounts with manual or automatic switching Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep several Claude and Codex accounts and start new sessions as the active one Each added account gets its own home holding only its login, with history, settings and skills linked back to ~/.claude or ~/.codex so --continue works across a switch. Accounts are added through the CLI's own login, and cx, cy, plain claude/codex and omarchy-agent all start as the active account unless CLAUDE_CONFIG_DIR or CODEX_HOME is already set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Report limits for every Claude and Codex account in the usage records Each registered account is probed with its own sign-in and cached on its own, and a parked account whose sign-in lapsed keeps its last-known numbers marked stale. The record's top-level limits keep describing the active account. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Switch accounts automatically near a limit, or notify with a one-click switch After each usage update, an active account at or over its provider's threshold (95% by default) moves new sessions to the account with the most headroom in auto mode, or offers that switch as a notification in manual mode. It never flaps back to an account that just reset, and says once when every account is over. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Show every subscription account's limits in the agents panel With several Claude or Codex accounts, the limits become one card per account with the active one badged. Pick a card with its number and press Enter (or click Use) to move new sessions to it, press a to add an account, and m to toggle automatic switching. Limits refresh every minute while an active account is above 80%. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Add Setup > Agent Accounts to list, switch and add Claude and Codex accounts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Document switching between several Claude and Codex subscriptions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Count a rested parked account as available, and pin Main to its own home A parked Claude account whose windows all reset now reads as 0% instead of unknown, so switching can pick it. Main's Codex limits come from ~/.codex even when CODEX_HOME is set, and duplicate logins are checked against who each home is signed in as now. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Key limits caches by subscription and report when an account truly frees up An added account's limits cache follows its account id, so a new account reusing a removed one's label never inherits its allowance. The all-accounts notice now names when an account's blocking windows have all reset, not the earliest reset of any window. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep account ids clear of routing keywords and refresh the panel after removal Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Share Codex plugins and hooks across accounts, and key Claude caches by current sign-in Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop the key hint from the Add account button Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Sign new agent accounts in through a private browser window The main browser is almost certainly signed in to the account you already have, and the login would silently reuse it. Both CLIs open their login page through $BROWSER, so it now points at omarchy-launch-browser --private. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Let agent account commands default to your default agent's provider With Claude or Codex as the default agent, the provider can be left out: omarchy agent account use work, and primary names the primary account. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop the primary alias, which shadowed an account named Primary Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Replace the auto switch button with a small Notify / Autoswitch toggle Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Add accounts from a small + beside the switch toggle Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Fix the punctuation of the switch toggle's README line Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop the border around the add account + Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Rename Claude and Codex accounts without moving their homes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Lay out agent accounts on accent rails instead of boxed cards The active account gets an accent rail and the others a quiet one, each window is a single compact line, and the switch toggle, add, and Use are text. Clicking an account's name renames it in place. A window without a reset time no longer leaves an empty line, and last-known numbers are only red when the sign-in needs attention. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Read Codex limits without waiting on account/read Codex 0.158's app-server can leave account/read unanswered, and asking it first lost the limits whenever it did, leaving the agents panel showing "Codex limits unavailable". The limits name the plan themselves, so they're asked first and account/read is only a short fallback when they don't. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Switch agent providers from their marks in the panel header The row of provider buttons gives way to a small mark per provider in the hero's corner, the selected one at full strength, with the add account + beside them in place of the + by the switch toggle and the full-width Add account button. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the agents panel's scrollbar off its contents The panel's content narrows to leave the scrollbar its own strip whenever it scrolls, and the add account + leads the provider marks instead of sitting at the very edge. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Add Claude, Codex, or Grok subscriptions from one Add Account menu The first account for a provider installs its CLI if needed and signs in to the CLI's own home through the normal browser; only additional accounts get a home of their own and a private window. Grok signs in its first account. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Reveal Autoswitch beside Use instead of a Notify / Autoswitch row The panel's + now opens the Add Account menu for any provider. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Split agent accounts with plain separators instead of rails ACTIVE already marks the account new sessions use. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Only call Claude limits stale once they're old, and poll near a limit less Anthropic rate-limits its usage endpoint, and polling two accounts every minute near a limit got every re-check refused, so both accounts read "Last known" with numbers a minute old. A refused check of numbers under 15 minutes old now counts as current, older ones say how old they are, and near-limit polling is every three minutes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Show every agent's limits on one page under an Agents hero The panel stops switching between one provider at a time and lists every agent and account with its limits, dropping the tokens-by-day and by-model charts. The hero carries the agents robot and rotates through what the token counts add up to: tokens this week and today, the most used model, the busiest day, and today's prompts and sessions. Middle-clicking the bar icon refreshes, since there's no provider left to advance to. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Report Codex's free rate-limit resets in its usage record Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Give the agents panel more room, and show Codex's free resets Limit lines are a notch larger with more space between them, each account's limits sit a clear step below its name, and sections breathe. Codex has one limit on Pro, so its section now also says how many free full resets are waiting and when the next one lapses. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Mark Claude's Fable limit on the Weekly meter instead of its own row A model-scoped allowance on the same clock as a base window is drawn as a tick on that window's meter and named in the row's tooltip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Let omarchy-default-agent set the default without launching it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Let the agents panel drive adding an account without a terminal --check says whether adding one now would be each provider's first sign-in or an additional account, and --events reports progress as tagged lines alongside the CLI's own output, notifies with the result, and cleans up the login and its scratch home when cancelled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Add subscriptions and pick the default agent right in the agents panel The + is a proper accent button, and it swaps the list for a picker of Claude, Codex, and Grok that signs in without a terminal: name a further account, then follow the sign-in with its status, Grok's confirmation code, a field for Claude's pasted code, and a link to reopen the page. A dropdown at the bottom sets the default agent without launching it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Draw the Fable tick in its meter's own color Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Revert "Let omarchy-default-agent set the default without launching it" This reverts commit da96261f7d26bb76774cbdc1cb9e0abde92bb841. * Make the first agent signed in the default when none is picked Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the agents panel in the bar, with setup, starters, and adding in it A machine with no agent opens the panel on setting one up. Once set up, the list ends with starter prompts for a new theme, plugin, or app, and a quiet Add a subscription. The panel no longer sets the default agent, and the hero drops its add button. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Offer the starter prompts as tiles, and adding as a row beneath them Theme, Plugin, and App each get a tile with its glyph, and Add a subscription a matching row with the + in a tinted square. The panel is allowed to grow tall enough to show it all without scrolling. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Put the tinted add button in the agents panel's hero corner Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Show when a limit resets in small type under its meter The percentage keeps the right edge to itself, so the meter runs longer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Revert "Show when a limit resets in small type under its meter" This reverts commit 108d9de59da1af12cddbf232b0b5333ad8994c64. * Put each account's plan beside its name, and its email in a tooltip Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Stack each limit's percentage over its time left, so the meter runs longer Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Show only each limit's time left, with the exact percentage on hover The meter already says how full a window is. Dropping the percentage beside it leaves one calm figure per row, and the row's tooltip carries the number. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Sign an existing account in again with omarchy-agent-account-add --reauth It signs in where the account already lives: the CLI's own home (:primary) through the normal browser, an added one through a private window. The usage records now say which account is the primary. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Offer Sign-in required in the agents panel instead of how old the numbers are A lapsed sign-in shows as a link that signs that account in again right in the panel. The "as of" and "last known" notes are gone; trouble that isn't about signing in still shows as text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the separator dot out of the Sign-in required link Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop the Setup > Agent Accounts menu and the stale plan The agents panel now lists, switches, and adds accounts, so the menu's duplicate of it goes, and the plan written before the design settled no longer describes it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Install the compiler and Qt pieces for building Omarchy-style apps base-devel plus qt6-base, qt6-declarative, qt6-multimedia, and qt6-wayland, which is what Hype, Monologue, and Omacut build with through qmake6 and make. Qt was only there as a dependency of those apps, and the compiler not at all. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Add an omarchy-app agent skill for building apps the Omarchy way It teaches how Hype, Monologue, and Omacut are built: C++ and Qt Quick in one flat project, qmake6 and make into a single binary, a theme that follows Omarchy's accent live, portal dialogs, keyboard-first conventions, Qt Test offscreen, and a PKGBUILD that puts the app in the launcher, with starter files that build and pass their tests as written. The agents panel's App starter uses it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Link the omarchy-app skill on existing installs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Let Cancel stop a waiting login, and list a lone account's limits Bash holds a trap until the foreground command finishes, so a login waiting on the browser outlived Cancel. It now runs behind an interruptible wait. With one account the usage record keeps its limits at the top level, which omarchy agent account list now reads for the primary. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Re-read identity even when signed out, and count Grok as set up A home whose login is gone no longer keeps the identity the registry saved, so it reads as signed out and can be added again. The agents panel leaves its setup screen once any agent is signed in, not only once one has usage to show, since Grok has no usage collector. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Save each account's current identity before collecting usage A home signed in to someone else since it was added kept the old email in the registry, which the usage records name accounts by. The usage update now refreshes the registry from each home first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Offer Claude's paste field from the start, and keep providers with accounts Claude's login prompts for a pasted code without a newline, so the panel's line reader never saw it; the field is simply there for Claude sign-ins. A provider with accounts stays listed even when the active one's limits are unavailable, so its other accounts can still be switched to. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Never autoswitch to a signed-out account, and report Codex's missing sign-in An account nobody is signed in to is left out of switching, however much room its cached numbers show. Codex answers a home without a login with an error, which now reads as Waiting for auth, so the panel offers Sign-in required for Codex accounts too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Link shared files before they exist, and only call every account over when it is A shared file the primary home didn't have yet was left unlinked, so an added account made its own copy and the two diverged for good; it's linked up front now, and written in the primary home by whichever account writes it first. The all-accounts-over notice waits until every account's limits are actually known. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Make the agent starter tiles compact and call the section Make something cool Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Hold the agents hero line until its next fade Every usage record that landed rebuilt the summary phrases, and the hero indexed that live list, so opening the panel could swap the line several times between fades. It now keeps what it shows until the timed swap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Start the default agent from the agents panel hero A console button beside the add button runs the same launcher as the right click: the default agent, or the picker when none is set. It hides while adding a subscription, where the add button becomes the way back. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Put the add button before the agent launcher in the hero corner Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Bring keyboard navigation back to the agents panel The one-page redesign dropped left and right with the per-agent pages, leaving the arrows only to scroll. They now walk everything that does something, row by row: the hero's add and launch buttons, each switchable account, and the starter tiles. Enter acts on the cursor, the cursor scrolls into view, and hovering moves the same cursor so only one thing is lit. Number keys still jump to an account. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Let adding an account take over the agents hero While adding, the hero's line reads "Add an account" in place of the rotating summary, and the X in its corner is the only way back, so the add view drops its own title and Back link. Each agent to add is just its mark and name; one that can't be added is dimmed and says why on hover. The arrows walk that list too, and Enter picks one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Show the agents to add as large marks, three across Each agent is a large mark over its name with no box around it, in one row the arrows move along. The chosen one turns accent and grows a touch. The reason an agent can't be added is shortened to fit inside the panel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Move between Autoswitch and Use on an account with the arrows An account that isn't active is now two stops, Autoswitch then Use, so left and right move between them and Enter acts on the one that's lit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Land on Use when moving up or down onto an account Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Hide Use on an autoswitching account until you're on its line With Autoswitch on, the line shows only Autoswitch. Use appears when the line is hovered anywhere or the keyboard is on it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Start adding an account with the first agent focused Opening the add screen puts the keyboard cursor on the first agent, so Enter picks it straight away. A focused agent lights up even before the check says whether it can be added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop the Sign in link under the account name field Enter in the field already starts the sign-in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Key the primary Claude account's limits cache by its subscription The primary home always used claude-limits.json, so signing it in to another subscription could carry the old one's numbers over when the first probe failed, and autoswitch would act on them. Once the home says who it's signed in as, its cache is keyed by that like every other account's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Leave Qt Multimedia out of the base packages again Quattro dropped it once the shell no longer needed it, and the app skill already has an app that plays audio or video add it and list it in its own depends. The compiler and the rest of Qt stay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Render the agents panel's dynamic text as plain text Sign-in status, help text, and provider names come from outside the shell, so none of them should be read as markup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep an account's plan and trouble clear of its Use and Autoswitch links The details beside an account's name grew to their full width, so a long plan or warning could run under the links on the right. They now shorten with an ellipsis instead, and Sign-in required keeps its whole width. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Let primary name the first account, as the manual says `omarchy agent account rename primary Hey` was documented but failed, since the primary account's id is main and lookups took exact ids only. primary now reaches the account marked primary, whatever it's been renamed to, and no new account can take primary as its id. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Install everything an Omarchy app needs by default The app skill builds with Qt Multimedia, SVG icons, and ffmpeg as well as the compiler and the rest of Qt, so qt6-multimedia, qt6-svg, and ffmpeg join the base packages and the migration. The shell still plays no video through Qt Multimedia, which is what its test now checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Dim agent limits kept from an earlier check, with their age on hover When a Claude probe fails, the last numbers carry on and looked just like fresh ones. Those meters now dim, and their tooltip says how old they are. The record carries limitsStale and limitsFetchedAt for this. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Give the app skill templates for every file its build needs The templates named src/backend.{h,cpp} and a test file without showing them, so each app had to invent its own. They're now templated, with a starter icon, a note that LICENSE and the icon must exist for package(), and qt6-wayland in the PKGBUILD's depends. Scaffolded from the templates alone, the app builds and its tests pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Start the agents panel cursor over when the agent list comes or goes Right after the shell starts, the panel can briefly look like a first setup and focus the first agent to add. When the records land the rows change under the cursor, which then lit an account nobody had picked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop dead hover and limit checks from the agents panel The tiles and hero buttons fell back on their own hover when there were no keyboard rows, but the hero always has one, so hover only ever moves the cursor. Stale meters only exist when there are limits, so neither the panel nor the record needs to check for some. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop the a hotkey for adding an agent subscription The + in the hero is the way in, by mouse or by arrowing to it. The plugin README also catches up with the panel: the launcher, dimmed stale limits, the new add screen, and the arrows walking a cursor rather than scrolling. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * List a command family that sits under a flags-only command `omarchy agent account` reached omarchy-agent, which takes only flags, and failed on the word instead of listing the account commands. When the command matched so far takes only flags and the next word names visible commands, the router now lists them. `omarchy update aur` likewise lists the update aur commands rather than running a full update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Refuse to remove an agent account a running session uses Removing an account deleted its home at once, pulling the login out from under any session started in it, though running sessions are never meant to be touched. It now says to quit that session first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Prefer an account checked just now when switching near a limit Autoswitch weighed numbers kept from an earlier check like fresh ones. A parked account's sign-in lapses within hours, so a stale one stays a candidate, but an account checked just now wins over it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Leave a user's own omarchy-app skill in place when linking ours Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Reach Sign-in required with the keyboard in the agents panel Both the link on a lapsed account and the one on a single-account agent are now stops in the cursor's walk, and Enter signs in again. A picked link scrolls into view. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Bring the manual's agent accounts paragraph up to date Near-limit checks run every three minutes, not every minute, and Autoswitch now appears on hovering an account's line and takes Use's place while it's on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the agents panel cursor on things you can act on The active account was a stop with nothing to do, so the cursor seemed to vanish there. It now only stops on it to sign in again. The hero's buttons also show the cursor plainly, with an accent border and a deeper tint instead of a shade's difference. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Never leave an added agent account's login outside the registry Registering moved the login into its home before carrying settings over and saving the registry, so a failure in either stranded a home holding a sign-in that the account commands couldn't see. Settings are now carried while the login is still pending, and a failed save moves the home back there for the add command to clean up. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Put room before freshness when picking an account to switch to Preferring accounts checked just now outright could pick a fresh one at 94% over a stale one at 10%. An account within 15 points of the threshold now counts as near its limit however fresh, so accounts with room come first and freshness only decides among them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Check agent limits more often relative to the switch threshold Faster checks started at a fixed 80%, so a threshold set lower could be crossed and wait out the 15-minute interval. They now start 15 points below the threshold, which is still 80% at the default 95%. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
776 lines
28 KiB
QML
776 lines
28 KiB
QML
import QtQuick
|
|
import Quickshell
|
|
import Quickshell.Io
|
|
|
|
// The display side of agent usage. All extraction lives behind
|
|
// omarchy-agent-usage-update, which writes one JSON record per agent into
|
|
// the usage directory; this file only discovers those records, watches them
|
|
// for changes, and optionally merges snapshots synced from other machines.
|
|
Item {
|
|
id: root
|
|
visible: false
|
|
|
|
property var settings: ({})
|
|
|
|
readonly property string home: Quickshell.env("HOME") || ""
|
|
readonly property string usageDir: (Quickshell.env("XDG_STATE_HOME") || home + "/.local/state") + "/omarchy/agents/usage"
|
|
|
|
// ------------------------------------------------------------- discovery
|
|
|
|
property var agentIds: []
|
|
property var agents: []
|
|
property int dataRevision: 0
|
|
|
|
Process {
|
|
id: listProcess
|
|
running: false
|
|
command: ["find", root.usageDir, "-maxdepth", "1", "-name", "*.json", "-printf", "%f\n"]
|
|
|
|
stdout: StdioCollector {
|
|
waitForEnd: true
|
|
onStreamFinished: root.applyAgentListing(text)
|
|
}
|
|
}
|
|
|
|
function rescanAgents() {
|
|
if (!listProcess.running) listProcess.running = true
|
|
}
|
|
|
|
function applyAgentListing(output) {
|
|
var ids = []
|
|
var lines = String(output || "").split("\n")
|
|
for (var i = 0; i < lines.length; i++) {
|
|
var name = lines[i].trim()
|
|
if (name.slice(-5) === ".json") ids.push(name.slice(0, -5))
|
|
}
|
|
ids.sort()
|
|
// Same list, same objects: reassigning the model would tear down every
|
|
// FileView just to build identical ones.
|
|
if (JSON.stringify(ids) !== JSON.stringify(agentIds)) agentIds = ids
|
|
}
|
|
|
|
Instantiator {
|
|
id: agentInstantiator
|
|
model: root.agentIds
|
|
|
|
delegate: Agent {
|
|
required property var modelData
|
|
agentId: modelData
|
|
path: root.usageDir + "/" + modelData + ".json"
|
|
onRecordChanged: root.recordsChanged()
|
|
}
|
|
|
|
onObjectAdded: (index, object) => root.rebuildAgents()
|
|
onObjectRemoved: (index, object) => root.rebuildAgents()
|
|
}
|
|
|
|
function rebuildAgents() {
|
|
var result = []
|
|
for (var i = 0; i < agentInstantiator.count; i++) {
|
|
var agent = agentInstantiator.objectAt(i)
|
|
if (agent) result.push(agent)
|
|
}
|
|
agents = result
|
|
recordsChanged()
|
|
}
|
|
|
|
function recordsChanged() {
|
|
dataRevision++
|
|
scheduleLimitsRetry()
|
|
scheduleSync()
|
|
}
|
|
|
|
// A collector that could not reach its limits endpoint at all — typically
|
|
// the seconds after login before the network is up — writes retryAdvised
|
|
// into its record. Honor it with one sooner try instead of waiting out the
|
|
// full refresh interval; a run that reaches the endpoint clears the flag.
|
|
// Only the advising agents rerun, so an outage at one provider does not
|
|
// put every other collector on a 30-second treadmill.
|
|
property var retryAgentIds: []
|
|
|
|
Timer {
|
|
id: limitsRetry
|
|
interval: 30000
|
|
repeat: false
|
|
onTriggered: root.runUpdate("limits", root.retryAgentIds)
|
|
}
|
|
|
|
function scheduleLimitsRetry() {
|
|
var advising = []
|
|
for (var i = 0; i < agents.length; i++) {
|
|
var record = agents[i] ? agents[i].record : null
|
|
if (record && record.retryAdvised === true && providerEnabled(String(record.id || "")))
|
|
advising.push(String(record.id))
|
|
}
|
|
retryAgentIds = advising
|
|
if (advising.length > 0) limitsRetry.restart()
|
|
else limitsRetry.stop()
|
|
}
|
|
|
|
Component.onCompleted: {
|
|
rescanAgents()
|
|
if (syncConfigured()) scheduleSync()
|
|
}
|
|
|
|
// -------------------------------------------------------------- refresh
|
|
|
|
property int refreshIntervalSec: Math.max(30, Number(setting("refreshIntervalSec", 900)))
|
|
property string pendingUpdateKind: ""
|
|
|
|
// A fifteen-minute interval can't catch an account crossing its switch
|
|
// threshold, so while any provider with several accounts has its active one
|
|
// within 15 points of that threshold (80% at the default 95%), the limits
|
|
// are checked every three minutes. Those runs
|
|
// reuse the transcript scans; only the limits probes are new, and any more
|
|
// often than this Anthropic starts refusing them.
|
|
readonly property bool nearLimit: {
|
|
var rev = dataRevision
|
|
for (var i = 0; i < agents.length; i++) {
|
|
var record = agents[i] ? agents[i].record : null
|
|
if (!record || !Array.isArray(record.accounts) || record.accounts.length < 2) continue
|
|
var limits = Array.isArray(record.limits) ? record.limits : []
|
|
var threshold = Number(record.accountSwitch && record.accountSwitch.threshold || 95)
|
|
var from = Math.min(0.8, (threshold - 15) / 100)
|
|
for (var j = 0; j < limits.length; j++)
|
|
if (Number(limits[j] && limits[j].percent) >= from) return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
Timer {
|
|
interval: root.nearLimit ? Math.min(180, root.refreshIntervalSec) * 1000 : root.refreshIntervalSec * 1000
|
|
running: true
|
|
repeat: true
|
|
triggeredOnStart: true
|
|
onTriggered: root.runUpdate(root.nearLimit ? "limits" : "normal")
|
|
}
|
|
|
|
Process {
|
|
id: updateProcess
|
|
running: false
|
|
onExited: {
|
|
root.rescanAgents()
|
|
if (root.pendingUpdateKind !== "") {
|
|
var kind = root.pendingUpdateKind
|
|
root.pendingUpdateKind = ""
|
|
root.runUpdate(kind)
|
|
}
|
|
}
|
|
|
|
stderr: StdioCollector {
|
|
waitForEnd: true
|
|
onStreamFinished: if (text.trim() !== "") console.warn("agents", text.trim())
|
|
}
|
|
}
|
|
|
|
function updateCommand(kind, agentIds) {
|
|
var command = ["omarchy-agent-usage-update"]
|
|
if (kind === "force") command.push("--force")
|
|
if (kind === "limits") command.push("--limits-only")
|
|
var providers = settings && settings.providers ? settings.providers : {}
|
|
for (var id in providers) {
|
|
if (providers[id] && providers[id].enabled === false) command.push("--except", id)
|
|
}
|
|
if (agentIds) {
|
|
for (var i = 0; i < agentIds.length; i++) command.push(agentIds[i])
|
|
}
|
|
return command
|
|
}
|
|
|
|
function runUpdate(kind, agentIds) {
|
|
if (updateProcess.running) {
|
|
// Collapse queued requests to one full rerun; a forced refresh outranks
|
|
// the cheaper kinds it might have been queued behind.
|
|
if (kind === "force" || root.pendingUpdateKind === "") root.pendingUpdateKind = kind
|
|
return
|
|
}
|
|
updateProcess.command = updateCommand(kind, agentIds)
|
|
updateProcess.running = true
|
|
}
|
|
|
|
function refresh() { refreshAll(true) }
|
|
function refreshAll(force) { runUpdate(force === true ? "force" : "normal") }
|
|
|
|
// Opening the panel wants the numbers that go stale on the wire, not
|
|
// another walk over every transcript on disk — the collectors reuse their
|
|
// recent scans in this mode.
|
|
function refreshLimits() { runUpdate("limits") }
|
|
|
|
// ------------------------------------------------------------- providers
|
|
|
|
// An agent earns a place in the bar and the panel by being switched on in
|
|
// settings and having actually produced numbers — locally or on a synced
|
|
// device. With nothing to show, the whole module collapses out of the bar
|
|
// rather than sitting there dimmed.
|
|
property var enabledProviders: {
|
|
var rev = dataRevision
|
|
var syncRev = syncRevision
|
|
var result = []
|
|
var localIds = {}
|
|
for (var i = 0; i < agents.length; i++) {
|
|
var record = agents[i] ? agents[i].record : null
|
|
if (!record || !record.id) continue
|
|
var id = String(record.id)
|
|
localIds[id] = true
|
|
if (!providerEnabled(id)) continue
|
|
var display = displayProvider(record)
|
|
if (providerHasData(display)) result.push(display)
|
|
}
|
|
// An agent that only ever ran on another machine has no local record, but
|
|
// its synced numbers still deserve a tab. Rate limits stay blank — they
|
|
// are per-account and never travel.
|
|
var syncedProviders = syncConfigured() && aggregateData && aggregateData.providers ? aggregateData.providers : {}
|
|
for (var syncedId in syncedProviders) {
|
|
if (localIds[syncedId] || !providerEnabled(syncedId)) continue
|
|
var stats = syncedProviders[syncedId] || {}
|
|
var syncedDisplay = displayProvider({ id: syncedId, name: stats.providerName || syncedId })
|
|
if (providerHasData(syncedDisplay)) result.push(syncedDisplay)
|
|
}
|
|
return result
|
|
}
|
|
|
|
function providerEnabled(id) {
|
|
if (!settings || !settings.providers || !settings.providers[id]) return true
|
|
return settings.providers[id].enabled !== false
|
|
}
|
|
|
|
// All-time keeps a quiet day from hiding an agent; today's counts admit a
|
|
// machine whose only source is history.jsonl, which knows nothing older.
|
|
function providerHasData(p) {
|
|
return numberValue(p.totalPrompts) > 0 || numberValue(p.totalSessions) > 0
|
|
|| numberValue(p.activeDays) > 0 || numberValue(p.todayPrompts) > 0
|
|
|| numberValue(p.todaySessions) > 0 || (p.limits && p.limits.length > 0)
|
|
|| (p.accounts && p.accounts.length > 0) || !!p.balance
|
|
}
|
|
|
|
// A prepaid agent's credit ledger. Like rate limits, the balance is
|
|
// per-account and never merged across devices.
|
|
function balanceValue(raw) {
|
|
if (!raw || typeof raw !== "object") return null
|
|
var remaining = Number(raw.remaining)
|
|
var funded = Number(raw.funded)
|
|
if (!isFinite(remaining) || remaining < 0) return null
|
|
return {
|
|
remaining: remaining,
|
|
funded: isFinite(funded) && funded > 0 ? funded : 0,
|
|
spent: Math.max(0, Number(raw.spent) || 0),
|
|
currency: String(raw.currency || "USD"),
|
|
estimated: raw.estimated === true
|
|
}
|
|
}
|
|
|
|
function displayProvider(record) {
|
|
var stats = syncedStatsFor(String(record.id))
|
|
var synced = !!stats
|
|
var deviceCount = synced ? Number(stats.deviceCount || aggregateData.deviceCount || 0) : 0
|
|
|
|
return {
|
|
providerId: String(record.id),
|
|
providerName: String(record.name || record.id),
|
|
ready: record.ready === true || synced,
|
|
usageStatusText: String(record.usageStatusText || ""),
|
|
authHelpText: String(record.authHelpText || ""),
|
|
|
|
// Rate limits and balances stay per-account and are never merged
|
|
// across devices.
|
|
limits: Array.isArray(record.limits) ? record.limits : [],
|
|
limitsStale: record.limitsStale === true,
|
|
limitsFetchedAt: numberValue(record.limitsFetchedAt),
|
|
tierLabel: String(record.tierLabel || ""),
|
|
// Every subscription account's own limits, once there's more than one.
|
|
accounts: Array.isArray(record.accounts) ? record.accounts : [],
|
|
accountSwitch: record.accountSwitch || ({ mode: "manual", threshold: 95 }),
|
|
// Codex's free full resets of its rate limits, when it has any.
|
|
resetCredits: record.resetCredits || null,
|
|
balance: balanceValue(record.balance),
|
|
|
|
todayPrompts: synced ? numberValue(stats.todayPrompts) : numberValue(record.todayPrompts),
|
|
todaySessions: synced ? numberValue(stats.todaySessions) : numberValue(record.todaySessions),
|
|
todayTotalTokens: synced ? numberValue(stats.todayTotalTokens) : numberValue(record.todayTotalTokens),
|
|
todayTokensByModel: synced ? (stats.todayTokensByModel || ({})) : (record.todayTokensByModel || ({})),
|
|
recentDays: synced ? (stats.recentDays || []) : (record.recentDays || []),
|
|
totalPrompts: synced ? numberValue(stats.totalPrompts) : numberValue(record.totalPrompts),
|
|
totalSessions: synced ? numberValue(stats.totalSessions) : numberValue(record.totalSessions),
|
|
activeDays: synced ? numberValue(stats.activeDays) : numberValue(record.activeDays),
|
|
modelUsage: synced ? (stats.modelUsage || ({})) : (record.modelUsage || ({})),
|
|
hasLocalStats: synced ? (stats.hasLocalStats !== false) : (record.hasLocalStats !== false),
|
|
hasPromptStats: synced ? (stats.hasPromptStats !== false) : (record.hasPromptStats !== false),
|
|
|
|
syncEnabled: synced,
|
|
syncDeviceCount: deviceCount,
|
|
syncUpdatedAt: aggregateData && aggregateData.updatedAt ? aggregateData.updatedAt : ""
|
|
}
|
|
}
|
|
|
|
function setting(name, fallback) {
|
|
var value = settings ? settings[name] : undefined
|
|
return value === undefined || value === null ? fallback : value
|
|
}
|
|
|
|
// ------------------------------------------------------------------ sync
|
|
|
|
property var syncModeSetting: setting("syncMode", setting("syncEnabled", false))
|
|
property bool syncEnabled: parseSyncEnabled(syncModeSetting)
|
|
property string syncDir: String(setting("syncDir", ""))
|
|
property string syncFileName: String(setting("syncFileName", ""))
|
|
property string syncDeviceId: String(setting("syncDeviceId", ""))
|
|
property string detectedHostname: ""
|
|
readonly property string syncEffectiveDir: expandPath(syncDir)
|
|
readonly property string syncEffectiveFileName: safeSnapshotFileName(syncFileName, syncDeviceId)
|
|
readonly property string syncEffectiveDeviceId: safeDeviceId(syncDeviceId || syncEffectiveFileName.replace(/\.json$/i, ""))
|
|
readonly property string syncSnapshotPath: syncConfigured() ? syncEffectiveDir + "/" + syncEffectiveFileName : home + "/.cache/omarchy/agents-disabled.json"
|
|
property var aggregateData: ({})
|
|
property int syncRevision: 0
|
|
property bool syncRunning: false
|
|
property bool syncRequestedWhileRunning: false
|
|
property string syncStatusText: ""
|
|
property double aggregateUpdatedAtMs: aggregateData && aggregateData.updatedAtMs ? Number(aggregateData.updatedAtMs) : 0
|
|
|
|
onSyncEnabledChanged: syncSettingsChanged()
|
|
onSyncDirChanged: syncSettingsChanged()
|
|
onSyncFileNameChanged: if (syncConfigured()) scheduleSync()
|
|
onSyncDeviceIdChanged: if (syncConfigured()) scheduleSync()
|
|
|
|
Timer {
|
|
id: syncDebounce
|
|
interval: 1000
|
|
repeat: false
|
|
onTriggered: root.runSync()
|
|
}
|
|
|
|
Process {
|
|
id: syncMkdirProcess
|
|
running: false
|
|
onRunningChanged: root.updateSyncRunning()
|
|
onExited: function(exitCode) {
|
|
if (exitCode !== 0) {
|
|
if (root.syncConfigured()) root.syncStatusText = "Usage sync mkdir failed"
|
|
root.finishSyncRun()
|
|
return
|
|
}
|
|
root.writeSyncSnapshot()
|
|
}
|
|
}
|
|
|
|
Process {
|
|
id: syncScanProcess
|
|
running: false
|
|
onRunningChanged: root.updateSyncRunning()
|
|
onExited: function(exitCode) {
|
|
if (exitCode !== 0 && root.syncConfigured()) root.syncStatusText = "Usage sync scan failed"
|
|
root.finishSyncRun()
|
|
}
|
|
|
|
stdout: StdioCollector {
|
|
waitForEnd: true
|
|
onStreamFinished: root.parseSyncScanOutput(text)
|
|
}
|
|
|
|
stderr: StdioCollector {
|
|
waitForEnd: true
|
|
onStreamFinished: if (text.trim() !== "") console.warn("agents/sync", text.trim())
|
|
}
|
|
}
|
|
|
|
FileView {
|
|
id: syncSnapshotFile
|
|
path: root.syncSnapshotPath
|
|
watchChanges: false
|
|
atomicWrites: true
|
|
printErrors: false
|
|
}
|
|
|
|
FileView {
|
|
id: hostnameFile
|
|
path: "/etc/hostname"
|
|
watchChanges: false
|
|
printErrors: false
|
|
onLoaded: root.detectedHostname = String(text() || "").trim()
|
|
}
|
|
|
|
function parseSyncEnabled(value) {
|
|
if (value === true) return true
|
|
var text = String(value || "").trim().toLowerCase()
|
|
return text === "on" || text === "enabled" || text === "true" || text === "yes" || text === "1"
|
|
}
|
|
|
|
function syncConfigured() {
|
|
return root.syncEnabled === true && String(root.syncDir || "").trim() !== ""
|
|
}
|
|
|
|
function syncSettingsChanged() {
|
|
if (syncConfigured()) {
|
|
scheduleSync()
|
|
} else {
|
|
syncDebounce.stop()
|
|
syncRequestedWhileRunning = false
|
|
aggregateData = ({})
|
|
syncStatusText = ""
|
|
syncRevision++
|
|
}
|
|
}
|
|
|
|
function updateSyncRunning() {
|
|
root.syncRunning = syncMkdirProcess.running || syncScanProcess.running
|
|
}
|
|
|
|
function scheduleSync() {
|
|
if (!syncConfigured()) return
|
|
syncDebounce.restart()
|
|
}
|
|
|
|
function runSync() {
|
|
if (!syncConfigured()) return
|
|
if (root.syncRunning) {
|
|
syncRequestedWhileRunning = true
|
|
return
|
|
}
|
|
|
|
syncRequestedWhileRunning = false
|
|
syncStatusText = ""
|
|
syncMkdirProcess.command = ["mkdir", "-p", root.syncEffectiveDir]
|
|
syncMkdirProcess.running = true
|
|
}
|
|
|
|
function writeSyncSnapshot() {
|
|
if (!syncConfigured()) {
|
|
finishSyncRun()
|
|
return
|
|
}
|
|
syncSnapshotFile.setText(JSON.stringify(localSnapshot(), null, 2) + "\n")
|
|
Qt.callLater(root.startSyncScan)
|
|
}
|
|
|
|
function startSyncScan() {
|
|
if (!syncConfigured()) {
|
|
finishSyncRun()
|
|
return
|
|
}
|
|
var script = "dir=$0; [[ -d \"$dir\" ]] || exit 0; shopt -s nullglob; for f in \"$dir\"/*.json; do [[ -f \"$f\" ]] || continue; printf '===%s===\\n' \"$f\"; cat \"$f\"; printf '\\n=== EOM ===\\n'; done"
|
|
syncScanProcess.command = ["bash", "-c", script, root.syncEffectiveDir]
|
|
syncScanProcess.running = true
|
|
}
|
|
|
|
function finishSyncRun() {
|
|
if (syncRequestedWhileRunning && syncConfigured()) {
|
|
syncRequestedWhileRunning = false
|
|
scheduleSync()
|
|
}
|
|
}
|
|
|
|
function expandPath(path) {
|
|
var value = String(path || "").trim()
|
|
if (value === "") return ""
|
|
if (value === "~") return home
|
|
if (value.indexOf("~/") === 0) return home + value.substring(1)
|
|
if (value.indexOf("$HOME/") === 0) return home + value.substring(5)
|
|
if (value.charAt(0) !== "/") return home + "/" + value
|
|
return value
|
|
}
|
|
|
|
function safeDeviceId(raw) {
|
|
var value = String(raw || "").trim()
|
|
if (value === "") value = Quickshell.env("HOSTNAME") || root.detectedHostname || Quickshell.env("HOST") || Quickshell.env("USER") || "device"
|
|
value = value.replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^[._-]+|[._-]+$/g, "")
|
|
if (value === "") value = "device"
|
|
return value.length > 80 ? value.substring(0, 80) : value
|
|
}
|
|
|
|
function safeSnapshotFileName(rawFileName, rawDeviceId) {
|
|
var value = String(rawFileName || "").trim()
|
|
if (value === "") value = safeDeviceId(rawDeviceId) + ".json"
|
|
value = value.split("/").pop().replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^[._-]+|[._-]+$/g, "")
|
|
if (value === "") value = safeDeviceId(rawDeviceId) + ".json"
|
|
if (!/\.json$/i.test(value)) value += ".json"
|
|
return value.length > 100 ? value.substring(0, 95) + ".json" : value
|
|
}
|
|
|
|
function parseSyncScanOutput(output) {
|
|
var lines = String(output || "").split("\n")
|
|
var snapshots = []
|
|
var currentPath = ""
|
|
var currentJson = []
|
|
|
|
function flush() {
|
|
if (currentPath === "") return
|
|
var raw = currentJson.join("\n").trim()
|
|
try {
|
|
var parsed = JSON.parse(raw)
|
|
if (parsed && parsed.providers) snapshots.push(parsed)
|
|
} catch (e) {
|
|
console.warn("agents/sync", "Ignoring bad snapshot", currentPath, e)
|
|
}
|
|
currentPath = ""
|
|
currentJson = []
|
|
}
|
|
|
|
for (var i = 0; i < lines.length; i++) {
|
|
var line = lines[i]
|
|
var start = line.match(/^===(.+)===$/)
|
|
if (start && line !== "=== EOM ===") {
|
|
flush()
|
|
currentPath = start[1]
|
|
currentJson = []
|
|
continue
|
|
}
|
|
if (line === "=== EOM ===") {
|
|
flush()
|
|
continue
|
|
}
|
|
if (currentPath !== "") currentJson.push(line)
|
|
}
|
|
flush()
|
|
|
|
aggregateData = aggregateSnapshots(snapshots)
|
|
syncStatusText = ""
|
|
syncRevision++
|
|
}
|
|
|
|
function cloneValue(value, fallback) {
|
|
if (value === undefined || value === null) return fallback
|
|
try {
|
|
return JSON.parse(JSON.stringify(value))
|
|
} catch (e) {
|
|
return fallback
|
|
}
|
|
}
|
|
|
|
function numberValue(value) {
|
|
var n = Number(value || 0)
|
|
return isFinite(n) ? Math.round(n) : 0
|
|
}
|
|
|
|
function dateString(date) {
|
|
var y = date.getFullYear()
|
|
var m = String(date.getMonth() + 1).padStart(2, "0")
|
|
var d = String(date.getDate()).padStart(2, "0")
|
|
return y + "-" + m + "-" + d
|
|
}
|
|
|
|
function recentDateStrings() {
|
|
var result = []
|
|
for (var offset = 6; offset >= 0; offset--) {
|
|
var date = new Date()
|
|
date.setDate(date.getDate() - offset)
|
|
result.push(dateString(date))
|
|
}
|
|
return result
|
|
}
|
|
|
|
function emptyTokenBucket() {
|
|
return { inputTokens: 0, outputTokens: 0, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 }
|
|
}
|
|
|
|
// Device-scoped stats add up across machines; account-scoped stats
|
|
// (Fireworks' billing API) are replicas of the same upstream truth on
|
|
// every synced device, so the widest value wins — summing them would
|
|
// double every token per machine.
|
|
function combineNumber(additive, current, value) {
|
|
return additive ? numberValue(current) + numberValue(value) : Math.max(numberValue(current), numberValue(value))
|
|
}
|
|
|
|
function combineObjectNumbers(additive, target, source) {
|
|
if (!source) return
|
|
for (var key in source) target[key] = combineNumber(additive, target[key], source[key])
|
|
}
|
|
|
|
function aggregateSnapshots(snapshots) {
|
|
var dates = recentDateStrings()
|
|
var devices = {}
|
|
var providers = {}
|
|
|
|
function providerAcc(id) {
|
|
if (providers[id]) return providers[id]
|
|
var recentByDay = {}
|
|
for (var d = 0; d < dates.length; d++) recentByDay[dates[d]] = 0
|
|
providers[id] = {
|
|
providerId: id,
|
|
providerName: "",
|
|
ready: false,
|
|
hasLocalStats: false,
|
|
hasPromptStats: false,
|
|
todayPrompts: 0,
|
|
todaySessions: 0,
|
|
todayTotalTokens: 0,
|
|
todayTokensByModel: ({}),
|
|
recentByDay: recentByDay,
|
|
totalPrompts: 0,
|
|
totalSessions: 0,
|
|
activeDays: 0,
|
|
activeDates: ({}),
|
|
modelUsage: ({}),
|
|
devices: ({})
|
|
}
|
|
return providers[id]
|
|
}
|
|
|
|
for (var i = 0; i < snapshots.length; i++) {
|
|
var snapshot = snapshots[i]
|
|
var device = safeDeviceId(snapshot.deviceId || "device")
|
|
devices[device] = true
|
|
var snapshotProviders = snapshot.providers || {}
|
|
for (var providerId in snapshotProviders) {
|
|
var stats = snapshotProviders[providerId] || {}
|
|
var acc = providerAcc(String(providerId))
|
|
acc.devices[device] = true
|
|
if (stats.providerName && acc.providerName === "") acc.providerName = String(stats.providerName)
|
|
acc.ready = acc.ready || stats.ready === true
|
|
acc.hasLocalStats = acc.hasLocalStats || stats.hasLocalStats !== false
|
|
// Snapshots from before the field existed only came from agents that
|
|
// count prompts, so a missing value reads as true.
|
|
acc.hasPromptStats = acc.hasPromptStats || stats.hasPromptStats !== false
|
|
var additive = String(stats.scope || "device") !== "account"
|
|
acc.todayPrompts = combineNumber(additive, acc.todayPrompts, stats.todayPrompts)
|
|
acc.todaySessions = combineNumber(additive, acc.todaySessions, stats.todaySessions)
|
|
acc.todayTotalTokens = combineNumber(additive, acc.todayTotalTokens, stats.todayTotalTokens)
|
|
acc.totalPrompts = combineNumber(additive, acc.totalPrompts, stats.totalPrompts)
|
|
acc.totalSessions = combineNumber(additive, acc.totalSessions, stats.totalSessions)
|
|
// Active days overlap between machines, so union the dates rather than
|
|
// summing counts. Snapshots written before activeDates existed only
|
|
// carry a count; the widest one stands in for them.
|
|
var activeDates = Array.isArray(stats.activeDates) ? stats.activeDates : []
|
|
for (var ad = 0; ad < activeDates.length; ad++) acc.activeDates[String(activeDates[ad])] = true
|
|
acc.activeDays = Math.max(acc.activeDays, numberValue(stats.activeDays))
|
|
combineObjectNumbers(additive, acc.todayTokensByModel, stats.todayTokensByModel || {})
|
|
|
|
var recent = Array.isArray(stats.recentDays) ? stats.recentDays : []
|
|
for (var r = 0; r < recent.length; r++) {
|
|
var day = recent[r] || {}
|
|
var date = String(day.date || "")
|
|
if (acc.recentByDay[date] !== undefined)
|
|
acc.recentByDay[date] = combineNumber(additive, acc.recentByDay[date], day.messageCount)
|
|
}
|
|
|
|
var usage = stats.modelUsage || {}
|
|
for (var modelId in usage) {
|
|
var bucket = acc.modelUsage[modelId]
|
|
if (!bucket) bucket = acc.modelUsage[modelId] = emptyTokenBucket()
|
|
combineObjectNumbers(additive, bucket, usage[modelId] || {})
|
|
}
|
|
}
|
|
}
|
|
|
|
var outProviders = {}
|
|
for (var id in providers) {
|
|
var acc = providers[id]
|
|
var recentDays = []
|
|
for (var di = 0; di < dates.length; di++) recentDays.push({ date: dates[di], messageCount: acc.recentByDay[dates[di]] || 0 })
|
|
var providerDevices = Object.keys(acc.devices).sort()
|
|
outProviders[id] = {
|
|
providerId: acc.providerId,
|
|
providerName: acc.providerName,
|
|
ready: acc.ready || providerDevices.length > 0,
|
|
hasLocalStats: acc.hasLocalStats,
|
|
hasPromptStats: acc.hasPromptStats,
|
|
todayPrompts: acc.todayPrompts,
|
|
todaySessions: acc.todaySessions,
|
|
todayTotalTokens: acc.todayTotalTokens,
|
|
todayTokensByModel: acc.todayTokensByModel,
|
|
recentDays: recentDays,
|
|
totalPrompts: acc.totalPrompts,
|
|
totalSessions: acc.totalSessions,
|
|
activeDays: Math.max(acc.activeDays, Object.keys(acc.activeDates).length),
|
|
modelUsage: acc.modelUsage,
|
|
deviceCount: providerDevices.length,
|
|
devices: providerDevices
|
|
}
|
|
}
|
|
|
|
return {
|
|
schemaVersion: 1,
|
|
updatedAt: new Date().toISOString(),
|
|
updatedAtMs: Date.now(),
|
|
deviceCount: Object.keys(devices).length,
|
|
devices: Object.keys(devices).sort(),
|
|
providers: outProviders
|
|
}
|
|
}
|
|
|
|
// Snapshots keep the field names older Omarchy versions wrote, so a fleet
|
|
// of machines on mixed versions still merges cleanly in both directions.
|
|
function providerSnapshot(record) {
|
|
return {
|
|
providerId: String(record.id),
|
|
providerName: String(record.name || record.id),
|
|
ready: record.ready === true,
|
|
hasLocalStats: record.hasLocalStats !== false,
|
|
hasPromptStats: record.hasPromptStats !== false,
|
|
scope: String(record.scope || "device"),
|
|
todayPrompts: numberValue(record.todayPrompts),
|
|
todaySessions: numberValue(record.todaySessions),
|
|
todayTotalTokens: numberValue(record.todayTotalTokens),
|
|
todayTokensByModel: cloneValue(record.todayTokensByModel, ({})),
|
|
recentDays: cloneValue(record.recentDays, []),
|
|
totalPrompts: numberValue(record.totalPrompts),
|
|
totalSessions: numberValue(record.totalSessions),
|
|
activeDays: numberValue(record.activeDays),
|
|
activeDates: cloneValue(record.activeDates, []),
|
|
modelUsage: cloneValue(record.modelUsage, ({}))
|
|
}
|
|
}
|
|
|
|
function localSnapshot() {
|
|
var providerMap = {}
|
|
for (var i = 0; i < agents.length; i++) {
|
|
var record = agents[i] ? agents[i].record : null
|
|
if (!record || !record.id) continue
|
|
if (!providerEnabled(String(record.id))) continue
|
|
providerMap[String(record.id)] = providerSnapshot(record)
|
|
}
|
|
return {
|
|
schemaVersion: 1,
|
|
deviceId: syncEffectiveDeviceId,
|
|
updatedAt: new Date().toISOString(),
|
|
providers: providerMap
|
|
}
|
|
}
|
|
|
|
function syncedStatsFor(providerId) {
|
|
var rev = syncRevision
|
|
if (!syncConfigured() || !aggregateData || !aggregateData.providers) return null
|
|
return aggregateData.providers[providerId] || null
|
|
}
|
|
|
|
// ---------------------------------------------------------------- format
|
|
|
|
function formatTokenCount(n) {
|
|
if (n === undefined || n === null) return "0"
|
|
if (n >= 1e9) return (n / 1e9).toFixed(1) + "B"
|
|
if (n >= 1e6) return (n / 1e6).toFixed(1) + "M"
|
|
if (n >= 1e3) return (n / 1e3).toFixed(1) + "K"
|
|
return String(n)
|
|
}
|
|
|
|
function modelWordCase(word) {
|
|
if (word === "gpt") return "GPT"
|
|
if (word === "deepseek") return "DeepSeek"
|
|
return word.charAt(0).toUpperCase() + word.slice(1)
|
|
}
|
|
|
|
// Model ids arrive hyphenated with the version split across segments
|
|
// (`claude-opus-4-8`, `gpt-5.6-sol`). Rejoin the numeric run into one
|
|
// version and title-case the words around it.
|
|
function friendlyModelName(id) {
|
|
if (!id) return "Unknown"
|
|
var name = String(id).replace(/^claude-/, "").replace(/-\d{8}$/, "")
|
|
var parts = name.split("-")
|
|
var words = []
|
|
var version = []
|
|
for (var i = 0; i < parts.length; i++) {
|
|
var part = parts[i]
|
|
if (part === "") continue
|
|
if (/^\d/.test(part)) {
|
|
version.push(part)
|
|
continue
|
|
}
|
|
if (version.length > 0) {
|
|
words.push(version.join("."))
|
|
version = []
|
|
}
|
|
words.push(modelWordCase(part))
|
|
}
|
|
if (version.length > 0) words.push(version.join("."))
|
|
return words.length > 0 ? words.join(" ") : "Unknown"
|
|
}
|
|
}
|