AIUsageTracker
AGENTS.md44 starsChanged 7 months agoMITView on GitHub
This document provides essential information for agentic coding assistants working on this .NET 8.0 WPF application.
- Reads credentials
- Commits and pushes
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,337 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
57 rules. About 0 are common, 31 are distinctive, and 26 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈31
Distinctive · estimate
This author's own choices. Worth a look.
26
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Distinctive: line 8
I MUST NEVER: create git tags or releases without your explicit instruction
- Distinctive: line 10
I MUST NEVER: create beta or stable releases on my own
- Distinctive: line 11
You must explicitly tell me: when to create a release
- Distinctive: line 12
I will wait for your command: before any release-related action
- Distinctive: line 18
DO NOT: wait for fresh data before showing providers - display cached data immediately
- Very specific: line 24
Provider classes own the semantics of usage data: Every ProviderUsage and ProviderUsageDetail emitted by a provider must contain fully …
- Very specific: line 27
The database is lean: Do not duplicate provider metadata (like IsQuotaBased or PlanType) into the database.
- Very specific: line 31
Never push directly to
main: All changes, including release preparations, MUST be done on a feature branch (e.g., feature/branch-name) … - Very specific: line 32
ALWAYS target
develop: All Pull Requests MUST target the develop branch. - Distinctive: line 33
Never force push to
mainwithout explicit user permission: If you need to force push to main, ALWAYS ask for confirmation first. - Distinctive: line 34
Atomic Commits: Keep commits focused and logically grouped.
- Distinctive: line 35
CI/CD Compliance: Ensure that any UI changes or tests are compatible with the headless CI environment.
- Distinctive: line 36
No Icons in PRs: When creating pull requests, do not use emojis or icons in the title or body.
- Distinctive: line 37
PR Management: ALWAYS modify existing PRs instead of closing and creating new ones.
- Distinctive: line 79
Always run builds and tests with a sensible timeout to avoid hanging indefinitely on deadlocks, endless loops, or stalled restores.
- Distinctive: line 80
Treat timeout expiry as a failure that must be reported and investigated, not as a command to rerun indefinitely.
- Distinctive: line 85
If a command times out, isolate the specific hanging test or build step before retrying.
- Very specific: line 89
Use the outln CLI tool for fast log triage on large outputs.
- Very specific: line 107
Prefer scripts/run-local-tests-safe.ps1 for local test execution.
- Very specific: line 109
Avoid raw dotnet test for suspected hangs, because it may re-enter restore/build paths and ignore the intended timeout budget.
- Distinctive: line 111
If a test command exceeds the timeout budget, kill the full process tree and report the overrun explicitly.
- Distinctive: line 162
Keep deterministic screenshot fixture data stable (including fixed clock values) to avoid non-functional image drift.
- Very specific: line 163
If only screenshot baseline fails, download the slim-ui-screenshots artifact from the failing run and sync only the drifted files.
- Distinctive: line 164
Do not add new screenshot files to baseline verification unless workflow and verification script are updated together.
- Distinctive: line 170
Run the pre-commit validation script:
- Very specific: line 174
Default behavior checks formatting on staged files only.
- Distinctive: line 225
Run the pre-push validation script:
- Very specific: line 270
Use file-scoped namespace declarations: namespace AIUsageTracker.Core.Models.
- Distinctive: line 271
Place using statements at the top, before namespace declaration
- Very specific: line 282
Boolean properties: Prefer affirmative phrasing (e.g., IsAvailable, StayOpen)
- Distinctive: line 285
Nullable reference types are enabled globally: - always handle potential nulls
- Very specific: line 286
Use nullable annotations: public string?
- Very specific: line 287
Prefer non-nullable where possible: public bool ShowAll { get.
- Very specific: line 288
Use default value initializers for properties: public double WindowWidth { get.
- Very specific: line 297
String interpolation: Use $"Value: {value}" over concatenation
- Very specific: line 302
Log exceptions: Use _logger.LogError(ex, "message") for unexpected errors
- Distinctive: line 303
Swallow specific exceptions: Only when appropriate with logging
- Very specific: line 304
Never throw in async void: Use Task or async Task instead
- Very specific: line 307
Always await async calls (avoid .Result or .Wait())
- Very specific: line 308
Use ConfigureAwait(false) in library code (non-UI)
- Very specific: line 310
Use SemaphoreSlim for async locking
- Very specific: line 315
All dependencies declared as readonly fields
- Very specific: line 317
Use ILogger<T> for logging (never use Console.WriteLine)
- Very specific: line 321
Use [Fact] for normal tests, [Theory] with [InlineData] for parameterized tests
- Very specific: line 323
Use descriptive test names: GetAllUsageAsync_LoadsConfigAndFetchesUsageFromMocks
- Distinctive: line 324
Test both success and failure paths
- Distinctive: line 325
Avoid implementation details - test behavior
- Distinctive: line 330
MVVM preferred: Keep code-behind minimal, use bindings
- Very specific: line 332
Colors: Use hex codes for dark theme (e.g., #1E1E1E background)
- Distinctive: line 373
Database: Read-only access to Monitor's SQLite database
- Very specific: line 402
Read port from %LOCALAPPDATA%\AIUsageTracker\monitor.json
- Distinctive: line 403
Use that port for all API calls
- Distinctive: line 416
When tooltips are visible, the aggressive z-order reassertion is temporarily disabled to prevent tooltips from being pushed behind the main …
- Distinctive: line 455
Equality: All supported providers are treated equally in terms of system integration and display logic.
- Distinctive: line 483
No external API calls on startup: - Only refresh system providers (antigravity)
- Distinctive: line 530
NEVER use silent failures: Every exception, error, or unexpected condition MUST be logged.
- Distinctive: line 532
Rule: All catch blocks must either:
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AI Usage Tracker - Monitor Guidelines
This document provides essential information for agentic coding assistants working on this .NET 8.0 WPF application.
Critical Rules
NEVER Create Releases Without Explicit Permission
- I MUST NEVER create git tags or releases without your explicit instruction
- I MUST NEVER initiate CI/CD release workflows without your permission
- I MUST NEVER create beta or stable releases on my own
- You must explicitly tell me when to create a release
- I will wait for your command before any release-related action
Provider Visibility Requirement
- ALL configured providers MUST be visible in the UI at all times
- NEVER filter out providers just because they have
IsAvailable=false - Providers with missing API keys should show as "Not Available" or "Configure Provider"
- DO NOT wait for fresh data before showing providers - display cached data immediately
- DO NOT show only a subset of providers (e.g., only antigravity) on startup
- The UI must show provider cards immediately, even if data is stale or unavailable
Provider Classes Are the Single Source of Truth
- Provider classes own the semantics of usage data. Every
ProviderUsageandProviderUsageDetailemitted by a provider must contain fully resolved, unambiguous values. Downstream layers (UI, database, projection services) display and persist — they never interpret, flip, or re-derive meaning. - No downstream interpretation. The UI must not check
IsQuotaBasedto decide what a percentage means. If a provider saysUsedPercent = 55, that's 55% consumed. Period. - Provider definitions are immutable for a given provider ID. If the semantics of a provider change (e.g. quota-based becomes pay-as-you-go), introduce a new provider class with a new ID. Do not change the definition retroactively — the database stores
RequestsPercentagewithoutIsQuotaBased, so flipping the definition would silently reinterpret all historical data. - The database is lean. Do not duplicate provider metadata (like
IsQuotaBasedorPlanType) into the database. The provider definition is the authority. The database stores raw values; the provider definition gives them meaning on read.
Development Workflow
- Never push directly to
main: All changes, including release preparations, MUST be done on a feature branch (e.g.,feature/branch-name) and integrated via a Pull Request. - ALWAYS target
develop: All Pull Requests MUST target thedevelopbranch.mainis only updated via merges fromdevelop. - Never force push to
mainwithout explicit user permission: If you need to force push to main, ALWAYS ask for confirmation first. - Atomic Commits: Keep commits focused and logically grouped.
- CI/CD Compliance: Ensure that any UI changes or tests are compatible with the headless CI environment.
- No Icons in PRs: When creating pull requests, do not use emojis or icons in the title or body.
- PR Management: ALWAYS modify existing PRs instead of closing and creating new ones. Keep work in the same PR to maintain conversation context and avoid PR number inflation.
Project Structure
- AIUsageTracker.Core: Domain models, interfaces, and business logic (PCL)
- AIUsageTracker.Infrastructure: External providers, data access, configuration
- AIUsageTracker.UI.Slim: Lightweight WPF desktop application with compact UI
- AIUsageTracker.Monitor: Background service that collects provider usage data via HTTP API
- AIUsageTracker.CLI: Console interface (cross-platform)
- AIUsageTracker.Web: ASP.NET Core Razor Pages web application for viewing data
- AIUsageTracker.Tests: xUnit unit tests with Moq mocking
Build & Test Commands
Building
# Build entire solution
dotnet build AIUsageTracker.sln --configuration Debug
# Build specific project
dotnet build AIUsageTracker.UI.Slim/AIUsageTracker.UI.Slim.csproj
# Restore dependencies
dotnet restoreTesting
# Run all unit tests
dotnet test AIUsageTracker.Tests/AIUsageTracker.Tests.csproj --configuration Debug
# Run all tests (no rebuild)
dotnet test --no-build --verbosity normal
# Run a single test
dotnet test --filter "FullyQualifiedName~GetAllUsageAsync_LoadsConfigAndFetchesUsageFromMocks"
# Run tests by class
dotnet test --filter "FullyQualifiedName~ProviderManagerTests"Test Timeouts
- Always run builds and tests with a sensible timeout to avoid hanging indefinitely on deadlocks, endless loops, or stalled restores.
- Treat timeout expiry as a failure that must be reported and investigated, not as a command to rerun indefinitely.
- Preferred limits:
- Targeted test runs: 15-30 seconds
- Project builds: 30-45 seconds
- Full test suites: 180-300 seconds
- If a command times out, isolate the specific hanging test or build step before retrying.
outln Helper
Use the outln CLI tool for fast log triage on large outputs.
outln <pattern> <path>- Produces compact one-line summaries per matching file.
- Helpful for quickly narrowing analyzer output, test logs, and warning-heavy build logs.
Local Test Environment Stabilization
Important local finding (2026-03-06): on this machine, plain dotnet build / dotnet test can fail or behave erratically during SDK workload resolver / project-reference evaluation even after repairing and reinstalling the .NET 8 SDK. This is a local tooling/workflow issue, not necessarily an application-code issue.
Required environment variables for stable local build/test runs:
$env:MSBuildEnableWorkloadResolver = "false"
$env:MSBUILDDISABLENODEREUSE = "1"
$env:DOTNET_CLI_DO_NOT_USE_MSBUILD_SERVER = "1"Local workflow requirements:
- Prefer
scripts/run-local-tests-safe.ps1for local test execution. - For very narrow or suspect test slices, prefer running
dotnet vstestagainst the already-built test assembly instead of rawdotnet test. - Avoid raw
dotnet testfor suspected hangs, because it may re-enter restore/build paths and ignore the intended timeout budget. - Build once under the stabilized environment, then run tiny test slices with hard wall-clock caps.
- If a test command exceeds the timeout budget, kill the full process tree and report the overrun explicitly.
- Quick stable one-liner entrypoint:
./scripts/run-local-tests-stable.ps1 -Suites web -Configuration Debug -MaxParallel 8 -TotalTimeoutMinutes 10 - What it does:
- sets environment flags used for deterministic local runs:
$env:MSBuildEnableWorkloadResolver="false"$env:MSBUILDDISABLENODEREUSE="1"$env:DOTNET_CLI_DO_NOT_USE_MSBUILD_SERVER="1"$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"
- runs
scripts/run-local-tests-safe.ps1with the configured suite list, parallelism, and timeout
- sets environment flags used for deterministic local runs:
Running the Monitor
# Run the Monitor service
dotnet run --project AIUsageTracker.Monitor
# Monitor runs on port 5000 by default (auto-discovers available port 5000-5010)
# Port is saved to %LOCALAPPDATA%\AIUsageTracker\monitor.jsonRunning the Web UI
# Run the Web application (requires Monitor to be running)
dotnet run --project AIUsageTracker.Web
# Web UI runs on port 5100
# Access at http://localhost:5100Running the Slim UI
# Run the Slim WPF application
dotnet run --project AIUsageTracker.UI.Slim
# Automatically discovers Monitor port from monitor.json file
# Falls back to ports 5000-5010 if discovery failsAutomated Screenshots
To generate updated screenshots for documentation (headless and in Privacy Mode):
# Run from the UI bin directory or project root
AIUsageTracker.exe --test --screenshot[!NOTE] The
--testflag enables explicit UI initialization required for headless rendering. This logic is gated to avoid performance overhead for normal users.
Screenshot Baseline Policy (Slim UI)
- CI screenshot baseline checks run on
windows-2025; treat CI-rendered artifacts as the final baseline authority. - Keep deterministic screenshot fixture data stable (including fixed clock values) to avoid non-functional image drift.
- If only screenshot baseline fails, download the
slim-ui-screenshotsartifact from the failing run and sync only the drifted files. - Do not add new screenshot files to baseline verification unless workflow and verification script are updated together.
Pre-Commit Validation (CRITICAL)
ALWAYS run validation before committing and pushing changes. This prevents CI failures and broken builds.
Run the pre-commit validation script:
./scripts/pre-commit-check.shDefault behavior checks formatting on staged files only. Use --all for full-solution formatting validation.
To enable automatic pre-commit enforcement for this repo, configure local hooks once:
./scripts/setup-git-hooks.ps1./scripts/setup-git-hooks.shFor local Windows troubleshooting or hang investigation, use:
./scripts/run-local-tests-safe.ps1This script performs:
- Format Validation - Enforces
dotnet format whitespace --verify-no-changes - Build Validation - Ensures solution compiles without errors
- Test Execution - Runs core and monitor test suites
Manual validation (if script unavailable):
# Format check (required, full solution)
./scripts/pre-commit-check.sh --all
# Build
dotnet build AIUsageTracker.sln --configuration Release
# Core tests
dotnet test AIUsageTracker.Tests/AIUsageTracker.Tests.csproj --configuration Release --no-build
# Monitor tests
dotnet test AIUsageTracker.Monitor.Tests/AIUsageTracker.Monitor.Tests.csproj --configuration Release --no-buildDo NOT commit if:
- ❌ Build fails
- ❌ Any tests fail
- ❌ Format check fails
Why this matters:
- CI/CD pipelines will reject broken builds
- Other developers will be blocked by failing tests
- Fixes require additional commits and PR updates
- Wastes CI minutes on known-failing builds
Pre-Push Validation (RECOMMENDED)
Run local CI/CD checks before pushing to catch failures early.
Run the pre-push validation script:
./scripts/pre-push-validation.ps1This script mimics GitHub Actions workflows locally:
- Build Validation - Ensures solution compiles
- Format Validation (changed files) - Verifies whitespace/style formatting on files changed versus
origin/develop - Unit Tests - Runs all tests
- Theme Validation - Checks theme contract parity
- Build Error Check - Verifies no compile errors
Optional flags:
# Skip tests (faster)
./scripts/pre-push-validation.ps1 -SkipTests
# Skip theme validation
./scripts/pre-push-validation.ps1 -SkipThemeValidation
# Skip formatting validation step
./scripts/pre-push-validation.ps1 -SkipFormat
# Enforce analyzer verification as blocking
./scripts/pre-push-validation.ps1 -StrictAnalyzersBenefits:
- Catches CI/CD failures before pushing
- Saves CI minutes
- Faster feedback loop
- Prevents broken PRs
Publishing
# Publish Windows UI
.\scripts\publish-app.ps1 -Runtime win-x64
# Publish Linux CLI
.\scripts\publish-app.ps1 -Runtime linux-x64Code Style Guidelines
Imports & Namespaces
- Use file-scoped namespace declarations:
namespace AIUsageTracker.Core.Models; - Place using statements at the top, before namespace declaration
- Group by: System → Third-party → Project references (separated by blank lines)
- Explicitly type
using Microsoft.Extensions.Logging;when needed to avoid ambiguity
Naming Conventions
- Classes: PascalCase (e.g.,
ProviderManager,AppPreferences) - Methods: PascalCase (e.g.,
GetUsageAsync,LoadConfigAsync) - Properties: PascalCase (e.g.,
ProviderId,IsAvailable) - Private fields: _camelCase with underscore prefix (e.g.,
_httpClient,_logger) - Interfaces: I prefix (e.g.,
IProviderService,IConfigLoader) - Async methods: End with
Asyncsuffix - Boolean properties: Prefer affirmative phrasing (e.g.,
IsAvailable,StayOpen)
Type & Nullable Guidelines
- Nullable reference types are enabled globally - always handle potential nulls
- Use nullable annotations:
public string? ApiKey { get; set; } - Prefer non-nullable where possible:
public bool ShowAll { get; set; } = false; - Use default value initializers for properties:
public double WindowWidth { get; set; } = 420; - Implicit usings enabled - don't add redundant using statements
Formatting
- Indentation: 4 spaces (no tabs)
- Braces: Allman style (opening brace on new line)
- Line length: Aim for ~120 characters, max 150
- Blank lines: One between methods, two between logical sections
- Object initializers: Preferred for new objects:
new ProviderUsage { ProviderId = "openai" } - String interpolation: Use
$"Value: {value}"over concatenation
Error Handling
- ArgumentException: For missing/invalid parameters with descriptive message
- Return error state in objects: For provider errors, return
ProviderUsagewithIsAvailable = false - Log exceptions: Use
_logger.LogError(ex, "message")for unexpected errors - Swallow specific exceptions: Only when appropriate with logging
- Never throw in async void: Use
Taskorasync Taskinstead
Async/Await Patterns
- Always
awaitasync calls (avoid.Resultor.Wait()) - Use
ConfigureAwait(false)in library code (non-UI) - Pass
CancellationTokenwhen available for long-running operations - Use
SemaphoreSlimfor async locking - Return
IEnumerablefor lazy evaluation,IListfor materialized collections
Dependency Injection
- Constructor injection only (no property injection)
- All dependencies declared as
readonlyfields - Register services in
App.xaml.cswithMicrosoft.Extensions.DependencyInjection - Use
ILogger<T>for logging (never useConsole.WriteLine)
Testing Guidelines
- Arrange-Act-Assert pattern for all tests
- Use
[Fact]for normal tests,[Theory]with[InlineData]for parameterized tests - Mock interfaces with Moq:
var mock = new Mock<ILogger<ProviderManager>>(); - Use descriptive test names:
GetAllUsageAsync_LoadsConfigAndFetchesUsageFromMocks - Test both success and failure paths
- Avoid implementation details - test behavior
- Fixture Synchronization Required: Provider test/screenshot fixtures must be based on real provider responses (sanitized only), not invented values. Keep
docs/test_fixture_sync.mdand fixture data in sync in the same PR.
WPF-Specific Guidelines
- XAML: 4-space indentation, self-closing tags when no content
- MVVM preferred: Keep code-behind minimal, use bindings
- Styles: Define in Window.Resources, use
x:Keyfor named styles - Colors: Use hex codes for dark theme (e.g.,
#1E1E1Ebackground) - Resource inclusion: Images as
<Resource>, SVG files as<Content>withPreserveNewest - Settings auth lookup: Slim UI must not spawn GitHub CLI (
gh) to resolve username; use local auth cache/files or provider API data.
Agent Architecture
The Agent is a background HTTP service that collects and stores provider usage data:
Key Components:
- UsageDatabase.cs: SQLite database with four tables (providers, provider_history, raw_snapshots, reset_events)
- ProviderRefreshService.cs: Scheduled refresh logic, filters providers without API keys
- ConfigService.cs: Configuration and preferences management
Port Management:
- Default port: 5000
- Auto-discovery: Tries ports 5000-5010, then random
- Port saved to:
%LOCALAPPDATA%\AIUsageTracker\monitor.json
Database Schema:
providers - Static provider configuration
provider_history - Time-series usage data (kept indefinitely)
raw_snapshots - Raw JSON data (14-day TTL, auto-cleanup)
reset_events - Quota/limit reset tracking (kept indefinitely)Web UI Architecture
The Web UI is an ASP.NET Core Razor Pages application that reads from the Monitor's database:
Features:
- Dashboard: Stats cards, provider usage with progress bars, 60s auto-refresh
- Providers: Table view of all providers with status
- Provider Details: Individual history + reset events
- History: Complete usage history across all providers
- Performance: Output caching, chart downsampling, deferred reset-events loading
Technology Stack:
- Framework: ASP.NET Core 8.0
- Pattern: Razor Pages (server-rendered)
- Styling: CSS variables for theming
- Database: Read-only access to Monitor's SQLite database
HTMX Integration:
- Auto-refresh via
hx-trigger="every 60s" - Partial page updates without full reload
- CDN loaded from unpkg.com
Web Performance Notes:
- Dashboard and Charts use short-lived output cache policies with query variance
- Hot DB reads use short-lived in-memory caches and structured timing/row-count logs
- Charts downsample server-side by time range and fetch reset events after initial render
Theme System: Seven built-in themes using CSS variables:
- Dark (default):
#1e1e1ebackground - Light: Clean white background
- High Contrast: Pure black/white for accessibility
- Solarized Dark: Blue-green palette
- Solarized Light: Sepia-toned
- Dracula: Purple/pink highlights
- Nord: Frosty blue-gray tones
Theme toggle in navbar with localStorage persistence.
Slim UI Port Discovery
The Slim UI reads the Monitor port directly from the configuration file:
Process:
- Read port from
%LOCALAPPDATA%\AIUsageTracker\monitor.json - Use that port for all API calls
Implementation:
MonitorService.RefreshPortAsync()- Reads port from monitor.jsonMonitorLauncher.GetAgentPortAsync()- Returns port from the file- NO port scanning - the file is the authoritative source
Slim UI Window Behavior
Always-On-Top Handling:
The Slim UI supports always-on-top mode via Topmost property and Win32 SetWindowPos API. When enabled, the window aggressively reasserts its z-order to prevent other applications from stealing focus.
Tooltip Coordination: When tooltips are visible, the aggressive z-order reassertion is temporarily disabled to prevent tooltips from being pushed behind the main window:
_isTooltipOpenflag tracks tooltip visibility stateReassertTopmostWithoutFocus()skips reassertion when_isTooltipOpenis trueEnsureAlwaysOnTop()also checks_isTooltipOpenbefore reasserting- Tooltips set their own
Topmost = truewhen opened
Implementation:
// Tooltip tracking in MainWindow.xaml.cs
toolTip.Opened += (s, e) => _isTooltipOpen = true;
toolTip.Closed += (s, e) => _isTooltipOpen = false;
// Guard in topmost reassertion methods
if (_isSettingsDialogOpen || _isTooltipOpen || !Topmost) return;Settings Dialog Coordination:
Similar to tooltips, the Settings dialog sets _isSettingsDialogOpen = true when shown to prevent the main window from fighting for z-order while a modal dialog is active.
Content Security Policy
CSP is configured in Program.cs with different policies for Development vs Production:
Development:
script-src 'self' 'unsafe-inline' 'unsafe-eval' https://unpkg.com;- Allows HTMX eval and Browser Link/Hot Reload
Production:
script-src 'self' https://unpkg.com;- Strict policy - requires self-hosted HTMX
Provider Philosophy
- No Essential Providers: There are no hardcoded "essential" providers that the application depends on.
- Key-Driven Activation: A provider is considered active and essential only if the user has provided a valid API key (either via configuration or environment variables).
- Listing: The UI pre-populates a list of supported providers to allow users to easily add keys, but their underlying presence is merely structural until configured.
- Equality: All supported providers are treated equally in terms of system integration and display logic.
Startup Refresh Behavior (CRITICAL)
When the Monitor starts, it MUST serve existing data from the database immediately and MUST NOT hammer 3rd party APIs.
Why: Users should see their providers immediately from cached data, but the Monitor should not overwhelm external APIs with startup requests. API calls should only happen on the scheduled refresh interval.
Implementation in ProviderRefreshService.cs:
// On startup with existing cached data:
// CORRECT: Serve from database, only refresh system providers (no external API)
_ = Task.Run(async () =>
{
await TriggerRefreshAsync(
forceAll: true,
includeProviderIds: new[] { "antigravity" });
});
// WRONG: Hammer all 3rd party APIs on startup
_ = Task.Run(async () =>
{
await TriggerRefreshAsync(forceAll: true); // DON'T DO THIS
});Key Principles:
- Serve from database immediately - The UI gets cached data right away
- No external API calls on startup - Only refresh system providers (antigravity)
- Scheduled refresh updates data - Normal 60s interval refreshes all providers
- Database is the source of truth - Between refreshes, serve what's stored
Consequence of wrong implementation: Hammering APIs on startup causes rate limiting and poor user experience.
Data Preservation (CRITICAL)
NEVER delete customer data automatically. Do NOT implement cleanup logic that removes provider history.
Why: Customer data must be preserved. If placeholder data is being created, fix the SOURCE (don't write it) rather than cleaning it up later.
Implementation in UsageDatabase.cs:
// CORRECT: Filter placeholder data BEFORE storing
public async Task StoreHistoryAsync(IEnumerable<ProviderUsage> usages)
{
var validUsages = usages.Where(u =>
!(u.RequestsAvailable == 0 && u.RequestsUsed == 0 &&
u.RequestsPercentage == 0 && !u.IsAvailable &&
(u.Description?.Contains("API Key") == true ||
u.Description?.Contains("configured") == true))
).ToList();
// Only store validUsages...
}
// WRONG: Store everything then clean up later
public async Task StoreHistoryAsync(IEnumerable<ProviderUsage> usages)
{
// Store all usages including placeholders...
}
// Later...
await CleanupEmptyHistoryAsync(); // DON'T DO THIS - deletes customer dataKey Principles:
- Prevent placeholder data at the source - Filter in StoreHistoryAsync, not after
- NEVER delete provider history - Once stored, data must be preserved
- Raw snapshots can have TTL - CleanupOldSnapshotsAsync with 14-day retention is OK
- Customer data is sacred - Storage layer must protect it
Consequence of wrong implementation: Customer provider history is deleted, causing providers to disappear from the UI until next refresh.
Error Handling and Logging (CRITICAL)
NEVER use silent failures. Every exception, error, or unexpected condition MUST be logged.
Rule: All catch blocks must either:
- Re-throw the exception (if caller should handle it)
- Log the error with context
BAD:
catch
{
// Silent failure - user has no idea what went wrong
}GOOD:
catch (Exception ex)
{
_logger.LogDebug("GitHub CLI discovery failed: {Message}", ex.Message);
}Why this matters: Silent failures make debugging impossible. When users report "nothing works," we need logs to understand what failed.
Provider Implementation Pattern
public class ExampleProvider : IProviderService
{
public string ProviderId => "example";
private readonly HttpClient _httpClient;
private readonly ILogger<ExampleProvider> _logger;
public ExampleProvider(HttpClient httpClient, ILogger<ExampleProvider> logger)
{
_httpClient = httpClient;
_logger = logger;
}
public async Task<IEnumerable<ProviderUsage>> GetUsageAsync(ProviderConfig config)
{
if (string.IsNullOrEmpty(config.ApiKey))
{
return new[] { new ProviderUsage
{
ProviderId = ProviderId,
ProviderName = "Example",
IsAvailable = false,
Description = "API Key missing"
}};
}
try
{
// Fetch usage...
return new[] { /* usage data */ };
}
catch (Exception ex)
{
_logger.LogError(ex, "Provider check failed");
return new[] { new ProviderUsage
{
ProviderId = ProviderId,
ProviderName = "Example",
IsAvailable = false,
Description = "Connection Failed"
}};
}
}
### Progress Bar Calculation for Payment Types
The application uses different progress bar calculations depending on the payment type to provide intuitive visual feedback. Additionally, users can toggle between showing "used" or "remaining" percentages.
#### Quota-Based Providers (e.g., Synthetic, Z.AI, GitHub Copilot)
**Calculation:** Show **remaining percentage** (full bar = lots of credits remaining)
```csharp
var utilization = (total - used) / total * 100.0;Visual Behavior:
- 0 used / 135 total = 100% full bar (all credits available used / 135 total = **50)
- 67% bar** (half credits remaining)
- 135 used / 135 total = 0% empty bar (no credits remaining)
Color Logic:
- Green: UsagePercentage > ColorThresholdYellow (lots remaining)
- Yellow: ColorThresholdRed < UsagePercentage <= ColorThresholdYellow (moderate remaining)
- Red: UsagePercentage < ColorThresholdRed (dangerously low remaining)
Rationale: Users expect to see a full green bar when they have all their quota available. The bar depletes and turns red as they use credits, similar to a fuel gauge.
Credits-Based Providers (e.g., OpenCode)
Calculation: Show used percentage (full bar = high usage/spending)
var utilization = used / total * 100.0;Visual Behavior:
- 0 used / 100 total = 0% empty bar (no spending yet)
- 50 used / 100 total = 50% bar (moderate spending)
- 100 used / 100 total = 100% full bar (budget exhausted)
Color Logic:
- Green: UsagePercentage < ColorThresholdYellow (low spending)
- Yellow: ColorThresholdYellow <= UsagePercentage < ColorThresholdRed (moderate spending)
- Red: UsagePercentage >= ColorThresholdRed (high spending/budget exhausted)
Rationale: For pay-as-you-go providers, users want to see spending accumulate. The bar fills up and turns red as they spend money, acting as a spending warning indicator.
User Toggle: Show Used vs Remaining
Users can toggle between viewing "used" or "remaining" percentages via the settings or UI toggle button. This affects only the display text, not the progress bar color.
Toggle Behavior:
- Toggle OFF (default): Shows "remaining" percentage (e.g., "75% remaining")
- Toggle ON: Shows "used" percentage (e.g., "25% used")
What the toggle changes:
- Display text: "X% remaining" ↔ "X% used"
- Status messages in the UI
What the toggle does NOT change:
- Progress bar color: Always based on used percentage regardless of toggle state
- The underlying data calculations
Implementation:
bool showUsed = ShowUsedToggle?.IsChecked ?? false;
// Display text changes based on toggle
var displayText = showUsed
? $"{usedPercent:F0}% used"
: $"{(100.0 - usedPercent):F0}% remaining";
// Color is ALWAYS based on used percentage
var barColor = GetProgressBarColor(usedPercent);Why colors stay consistent:
- Even when showing "remaining" in text, the bar color reflects actual usage
- This prevents confusion: green always means "healthy usage", red always means "high usage"
- Users can quickly assess their usage status regardless of which percentage they prefer to see
Implementation
Backend (Provider):
// For quota-based providers, show remaining percentage (full bar = lots remaining)
// For other providers, show used percentage (full bar = high usage)
var utilization = paymentType == PaymentType.Quota
? (total > 0 ? ((total - used) / total) * 100.0 : 100) // Remaining % for quota
: (total > 0 ? (used / total) * 100.0 : 0); // Used % for othersFrontend (UI Color Logic):
// Color is ALWAYS based on used percentage, regardless of toggle state
double pctRemaining = isQuotaType ? usage.RequestsPercentage : Math.Max(0, 100 - usage.RequestsPercentage);
double pctUsed = isQuotaType ? Math.Max(0, 100 - usage.RequestsPercentage) : usage.RequestsPercentage;
// Toggle controls what user sees, NOT the color
bool showUsed = ShowUsedToggle?.IsChecked ?? false;
var displayText = showUsed ? $"{pctUsed:F0}% used" : $"{pctRemaining:F0}% remaining";
// Progress bar always uses pctUsed for color calculation
var barColor = GetProgressBarColor(pctUsed);Color Thresholds:
- Red: >= 90% used
- Yellow: >= 50% used
- Green: < 50% used
JSON Handling
- Use
System.Text.Json(not Newtonsoft) - Configure with
JsonSerializerOptionsif needed - Prefer
await HttpClient.GetFromJsonAsync<T>()for GET requests - Use
JsonSerializer.Serialize()andJsonContent.Create()for POST
Database & Storage
- SQLite via
Microsoft.Data.Sqlite - Encrypted storage using
System.Security.Cryptography.ProtectedData - Configuration stored in
auth.jsonin app data directory - Automatic backup created on updates
Logging
- Use
Microsoft.Extensions.Loggingwith structured logging - Log levels:
LogDebug,LogInformation,LogWarning,LogError - Include context in messages:
LogDebug($"Fetching usage for provider: {config.ProviderId}")
Versioning
- Version numbers in
.csprojfiles:<Version>X.Y.Z</Version> - Update UI version for releases, other projects follow semantic versioning
- CI/CD triggered on tag push:
v* - Release Notes: Keep them concise. Do not repeat information already present in the change log. Focus on the high-level summary of changes.
- Changelog: Maintain a
CHANGELOG.mdfile with concise documentation of changes for each version. Include the date of the release. Also keep an## Unreleasedsection at the top for tracking upcoming changes.
Release Process
IMPORTANT: All release-related changes MUST be made via pull request. Never trigger the release workflow directly on main. Always:
- Create a feature branch (e.g.,
feature/v2.2.0-release) - Update version files on that branch
- Create a pull request to main
- After PR is merged, either:
- create and push the release tag manually with maintainer credentials, or
- trigger the
Create Releaseworkflow withskip_file_updates=trueonly if you want the workflow summary/help text; GitHub Actions itself must not be relied on to create the tag in this repository because repository rules blockGITHUB_TOKENtag creation
Next Release Checklist
- Prepare version/changelog updates on a feature branch and merge them to the target release branch.
- If the release-prep PR is already merged, run
Create Releasewithskip_file_updates=true; otherwise leave itfalseso the workflow can still push the version-file commit. - Create and push the release tag manually with maintainer credentials.
- Verify the
Publish & Distributeworkflow starts from the tag push and completes successfully. - After assets are published, update the appcast files if required by the channel/release type.
When preparing a new release (e.g., v2.2.0), ensure the following files are updated with the new version number:
1. Project Files (.csproj)
Update the <Version> tag in all project files:
AIUsageTracker.Core/AIUsageTracker.Core.csprojAIUsageTracker.Infrastructure/AIUsageTracker.Infrastructure.csprojAIUsageTracker.UI.Slim/AIUsageTracker.UI.Slim.csprojAIUsageTracker.CLI/AIUsageTracker.CLI.csproj
2. Changelog
- Update
CHANGELOG.md: Move the## Unreleasedsection to a new version header with the current date (e.g.,## [2.2.0] - 2026-02-22). - Ensure a new empty
## Unreleasedsection is created at the top if needed for future tracking.
3. Documentation
README.md: Update the version badge at the top:scripts/publish-app.ps1: Update the example usage comment:# Usage: .\scripts\publish-app.ps1 -Runtime win-x64 -Version 2.2.0
4. Installer Setup
scripts/setup.iss: Update theMyAppVersiondefinition:#define MyAppVersion "2.2.0"
5. Git Tagging
Once all files are committed and pushed to the target release branch, create a git tag manually to trigger the CI/CD release workflow:
git tag v2.2.0
git push origin v2.2.0Important: the repository currently blocks tag creation by GitHub Actions. The Create Release workflow can prepare or verify release state, but the final tag push must be done with maintainer credentials.
6. Appcast Files (Updater)
After the release workflow completes and assets are published, update the appcast files in appcast/ to point to the new release assets:
Appcast files to update:
appcast/appcast.xml- Default (x64)appcast/appcast_x64.xml- x64 architectureappcast/appcast_arm64.xml- ARM64 architectureappcast/appcast_x86.xml- x86 architecture
Important: Match the exact asset filenames from the release:
# Check release assets
gh release view v2.2.0 --json assets --jq '.assets[].name'URL pattern: https://github.com/rygel/AIConsumptionTracker/releases/download/v2.2.0/AIUsageTracker_Setup_v2.2.0_win-x64.exe
Note: Release assets use -win-x64, -win-arm64, -win-x86 suffixes (NOT -x64, -arm64, -x86).
Update appcast entries:
<item>
<title>Version 2.2.0</title>
<sparkle:releaseNotesLink>https://github.com/rygel/AIConsumptionTracker/releases/tag/v2.2.0</sparkle:releaseNotesLink>
<pubDate>Sun, 22 Feb 2026 15:30:00 +0000</pubDate>
<enclosure url="https://github.com/rygel/AIConsumptionTracker/releases/download/v2.2.0/AIUsageTracker_Setup_v2.2.0_win-x64.exe"
sparkle:version="2.2.0"
sparkle:os="windows"
length="0"
type="application/octet-stream" />
</item>Commit and push the appcast updates after the release assets are available.
Testing Guidelines
UI Startup Tests (CRITICAL)
Always add automated tests for UI startup sequences to prevent deadlocks and theme issues.
Example tests in AIUsageTracker.Tests/UI/AppStartupTests.cs:
[Fact]
public async Task LoadPreferencesAsync_DoesNotBlockThread()
{
// Ensures async loading doesn't block the UI thread
var startTime = DateTime.UtcNow;
var loadTask = UiPreferencesStore.LoadAsync();
var completed = await Task.WhenAny(loadTask, Task.Delay(TimeSpan.FromSeconds(5)));
Assert.Same(loadTask, completed);
Assert.True(DateTime.UtcNow - startTime < TimeSpan.FromSeconds(5),
"Loading preferences took too long - possible blocking call");
}
[Fact]
public async Task PreferencesStore_SaveLoad_NoDeadlock()
{
// Tests for deadlock in rapid save/load cycles
for (int i = 0; i < 10; i++)
{
await UiPreferencesStore.SaveAsync(preferences);
var loaded = await UiPreferencesStore.LoadAsync();
Assert.NotNull(loaded);
}
}What these tests catch:
- Synchronous
.GetAwaiter().GetResult()blocking calls - Deadlocks in preference save/load
- Theme revert issues
- Race conditions during startup
Run tests before committing:
dotnet test AIUsageTracker.Tests/AIUsageTracker.Tests.csproj --filter "FullyQualifiedName~AppStartupTests"Testing Principles
- Test async behavior - Ensure async methods don't block
- Test defaults - Verify fallback values when files don't exist
- Test persistence - Round-trip save/load cycles
- Test edge cases - Null resources, corrupted files, rapid operations
- Test themes - Verify theme persistence across restarts
CI/CD
- GitHub Actions for testing on push/PR to main.
- Release workflow creates installers for multiple platforms.
- Winget submission for Windows packages.
Run Testsincludes a web endpoint perf smoke guardrail for/and/chartsin CI.
UI Polling Algorithm
The Slim UI uses a dynamic polling strategy to ensure providers appear quickly while minimizing resource usage:
Startup Phase
- Rapid Polling: Poll every 5 seconds until data is available
- Max Attempts: 15 attempts (75 seconds max)
- On No Data: Trigger background refresh and continue polling
- Display: Show cached data immediately, update when fresh data arrives
Normal Operation
- Standard Interval: Poll every 1 minute
- Concurrent Prevention: Skip poll if previous still in progress
- Data Preservation: Never overwrite existing data with empty results
Error Handling
- Connection Error: Switch to rapid polling (5s)
- Monitor Unavailable: Show error but preserve cached data
- Refresh Failure: Keep last successful snapshot
Key Principles
- Always show something (cached data or loading state)
- Never block waiting for data
- Prefer stale data over empty UI
- Aggressive polling only during startup or errors
This algorithm ensures providers appear within 30 seconds while maintaining responsiveness.
Async/Await Best Practices
See WPF Async/Await Best Practices for critical patterns to avoid UI blocking and deadlocks.
Key rules:
- Never use
.GetAwaiter().GetResult()or.Resulton the UI thread - Never create sync wrappers for async methods
- Always add timeouts to HTTP calls (> 30s is too long for UI)
- Use fire-and-forget (
_ =) for non-critical background work - Add exception handling to all
async voidevent handlers - Use
ConfigureAwait(false)in library code (Core/Infrastructure projects)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

