// Claude Usage Tray — shows the Claude 5-hour session limit as a number in the Windows taskbar. // // Reads the Claude Code login from %USERPROFILE%\.claude\.credentials.json (or %CLAUDE_CONFIG_DIR%) // or from ~/.claude/.credentials.json in a running WSL distro, asks https://api.anthropic.com/api/oauth/usage how much of the 5-hour and 7-day windows is used, // and draws the 5-hour percentage into a notification-area icon. Tokens are only ever sent to Anthropic // and never logged. When the login is about to expire, the program renews it the way Claude Code does, // under Claude Code's own locks, and saves it back (see "renewing the login" below). // // Build: csc /target:winexe /r:System.Web.Extensions.dll ClaudeUsageTray.cs (see install.ps1) using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Globalization; using System.IO; using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Web.Script.Serialization; using System.Windows.Forms; using Microsoft.Win32; [assembly: AssemblyTitle("Claude Usage Tray")] [assembly: AssemblyProduct("Claude Usage Tray")] [assembly: AssemblyVersion("1.0.0.0")] namespace ClaudeUsageTray { sealed class Usage { public double FiveHour = -1; // percent, -1 = unknown public DateTime? FiveHourReset; // local time public double SevenDay = -1; public DateTime? SevenDayReset; public string Error; public bool RateLimited; public int RetryAfterSeconds; // from the Retry-After header of a 429, 0 if none public DateTime Fetched; public string Source; // where the login came from, e.g. "WSL Ubuntu (alice)" public DateTimeOffset? RenewableUntil; } sealed class CodexUsage { public double FiveHour = -1; // percent as of AsOf, -1 = unknown public DateTime? FiveHourReset; // local time public double Weekly = -1; public DateTime? WeeklyReset; public DateTime AsOf; // when Codex last ran here and got these numbers public string Source; // "WSL archlinux (alice)" or "Windows" public string Error; // a window whose reset time has passed is back at 0 %, even if Codex has not run since public double FiveHourNow { get { return Now(FiveHour, FiveHourReset); } } public double WeeklyNow { get { return Now(Weekly, WeeklyReset); } } static double Now(double pct, DateTime? reset) { return pct >= 0 && reset.HasValue && DateTime.Now >= reset.Value ? 0 : pct; } } static class Program { [STAThread] static int Main(string[] args) { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; if (Array.IndexOf(args, "--renew-now") >= 0) return TrayContext.RenewNow(); bool created; using (var mutex = new Mutex(true, "Local\\ClaudeUsageTray", out created)) { if (!created) return 0; SetProcessDPIAware(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TrayContext()); return 0; } } [DllImport("user32.dll")] static extern bool SetProcessDPIAware(); } sealed class TrayContext : ApplicationContext { const string AppName = "ClaudeUsageTray"; const string UsageUrl = "https://api.anthropic.com/api/oauth/usage"; const string UsagePage = "https://claude.ai/settings/usage"; const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; const int PollMinutes = 3; const int BackoffMinutes = 10; // after a 429: 10, 20, 40, then 60 min const int MaxBackoffMinutes = 60; const int MinGapSeconds = 60; // clicks, wake-up etc. never ask more often than this // Two icons, created in this order: Windows knows them as UID 1 and 2 (see PromoteIconOnce). readonly NotifyIcon tray = new NotifyIcon(); // Claude, 5-hour limit readonly NotifyIcon codexTray = new NotifyIcon(); // Codex, 5-hour limit readonly ContextMenuStrip menu = new ContextMenuStrip(); readonly ToolStripMenuItem fiveHourItem = new ToolStripMenuItem(); readonly ToolStripMenuItem sevenDayItem = new ToolStripMenuItem(); readonly ToolStripMenuItem codexFiveHourItem = new ToolStripMenuItem(); readonly ToolStripMenuItem codexWeeklyItem = new ToolStripMenuItem(); readonly ToolStripMenuItem codexStatusItem = new ToolStripMenuItem(); readonly System.Windows.Forms.Timer codexTimer = new System.Windows.Forms.Timer(); readonly ToolStripMenuItem statusItem = new ToolStripMenuItem(); readonly ToolStripMenuItem loginItem = new ToolStripMenuItem(); readonly ToolStripMenuItem autostartItem = new ToolStripMenuItem("Start with Windows"); readonly System.Windows.Forms.Timer pollTimer = new System.Windows.Forms.Timer(); readonly System.Windows.Forms.Timer tickTimer = new System.Windows.Forms.Timer(); readonly Control invoker = new Control(); static string dataDir; Usage last; // last successful result Usage latest; // last attempt, successful or not bool fetching; int rateLimitStreak; DateTime notBefore = DateTime.MinValue; // no request before this time Icon currentIcon; Icon currentCodexIcon; CodexUsage codex; // last read of the Codex session logs bool readingCodex; public TrayContext() { InitDataDir(); IntPtr forceHandle = invoker.Handle; // CreateControl() alone does not always create the window Log("started, pid " + Process.GetCurrentProcess().Id); foreach (var item in new[] { fiveHourItem, sevenDayItem, statusItem, loginItem, codexFiveHourItem, codexWeeklyItem, codexStatusItem }) item.Enabled = false; loginItem.Visible = false; menu.Items.Add(fiveHourItem); menu.Items.Add(sevenDayItem); menu.Items.Add(statusItem); menu.Items.Add(loginItem); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add(codexFiveHourItem); menu.Items.Add(codexWeeklyItem); menu.Items.Add(codexStatusItem); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("Refresh now", null, delegate { Refresh(); }); menu.Items.Add("Open usage page on claude.ai", null, delegate { OpenUsagePage(); }); autostartItem.Click += delegate { SetAutostart(!autostartItem.Checked); }; menu.Items.Add(autostartItem); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("Exit", null, delegate { ExitThread(); }); menu.Opening += delegate { autostartItem.Checked = IsAutostart(); UpdateTexts(); }; foreach (NotifyIcon icon in new[] { tray, codexTray }) { icon.ContextMenuStrip = menu; icon.MouseUp += OnTrayMouseUp; icon.DoubleClick += delegate { OpenUsagePage(); }; } SetIcon(tray, ref currentIcon, Render(-1, false, false)); SetIcon(codexTray, ref currentCodexIcon, Render(-1, false, true)); tray.Text = "Claude 5h: loading…"; codexTray.Text = "Codex 5h: loading…"; tray.Visible = true; codexTray.Visible = true; pollTimer.Interval = PollMinutes * 60 * 1000; pollTimer.Tick += delegate { Refresh(); }; pollTimer.Start(); tickTimer.Interval = 30 * 1000; tickTimer.Tick += delegate { OnTick(); }; tickTimer.Start(); // local files only, so it can be read far more often than the Claude API is asked codexTimer.Interval = 60 * 1000; codexTimer.Tick += delegate { RefreshCodex(); }; codexTimer.Start(); SystemEvents.PowerModeChanged += OnPowerModeChanged; PromoteIconOnce(1, "promoted"); PromoteIconOnce(2, "promoted-2"); Refresh(); RefreshCodex(); } // ---- fetching ---------------------------------------------------------------------- void Refresh() { if (fetching) { Log("refresh skipped: still fetching"); return; } if (DateTime.Now < notBefore) { Log("refresh skipped: not before " + notBefore.ToString("HH:mm:ss")); return; } fetching = true; Log("refresh"); ThreadPool.QueueUserWorkItem(delegate { Usage u = Fetch(dataDir); Log("fetched: " + (u.Error ?? "ok")); try { invoker.BeginInvoke((MethodInvoker)delegate { OnFetched(u); }); } catch (Exception ex) { Log("handing result to UI failed: " + ex.Message); fetching = false; } }); } void OnFetched(Usage u) { fetching = false; latest = u; if (u.Error == null) last = u; int wait; if (u.RateLimited) { rateLimitStreak++; wait = Math.Min(MaxBackoffMinutes, BackoffMinutes << Math.Min(rateLimitStreak - 1, 3)) * 60; if (u.RetryAfterSeconds > wait) wait = u.RetryAfterSeconds; notBefore = DateTime.Now.AddSeconds(wait - 5); // slack so the timer tick itself is not refused u.Error = "Rate limited, next try at " + DateTime.Now.AddSeconds(wait).ToString("HH:mm"); } else { rateLimitStreak = 0; wait = PollMinutes * 60; notBefore = DateTime.Now.AddSeconds(MinGapSeconds); } pollTimer.Interval = wait * 1000; // restarts the timer WriteStatus(u); Redraw(); } static Usage Fetch(string dataDir) { var u = new Usage { Fetched = DateTime.Now }; try { Login l = GetLogin(); u.Source = l.Source; u.RenewableUntil = l.RefreshExpires; Log("login from " + l.Source + ", valid until " + l.Expires.ToLocalTime().ToString("HH:mm") + "; asking the API"); string token = l.Token; var req = (HttpWebRequest)WebRequest.Create(UsageUrl); req.Method = "GET"; req.Timeout = 20000; req.ReadWriteTimeout = 20000; // the default lets a stalled body block for 5 minutes req.Accept = "application/json"; req.UserAgent = "claude-usage-tray/1.0"; req.Headers["Authorization"] = "Bearer " + token; req.Headers["anthropic-beta"] = "oauth-2025-04-20"; string body; // hard limit for the whole request; only one runs at a time, so a hang would stop all updates using (new System.Threading.Timer(delegate { req.Abort(); }, null, 30000, Timeout.Infinite)) using (var resp = (HttpWebResponse)req.GetResponse()) using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)) body = sr.ReadToEnd(); try { File.WriteAllText(Path.Combine(dataDir, "last-response.json"), body); } catch (IOException) { } Parse(body, u); } catch (WebException ex) { var r = ex.Response as HttpWebResponse; using (r) // an undisposed error response keeps its connection busy { int code = r != null ? (int)r.StatusCode : 0; if (code == 401) { u.Error = "Login rejected, renewing it"; login = null; renewAfter401 = true; } else if (code == 429) { u.Error = "Rate limited"; u.RateLimited = true; int seconds; if (int.TryParse(r.Headers["Retry-After"], NumberStyles.Integer, CultureInfo.InvariantCulture, out seconds)) u.RetryAfterSeconds = seconds; } else if (code != 0) u.Error = "HTTP " + code + " from api.anthropic.com"; else if (ex.Status == WebExceptionStatus.RequestCanceled || ex.Status == WebExceptionStatus.Timeout) u.Error = "No answer from api.anthropic.com"; else u.Error = ex.Message; } } catch (Exception ex) { u.Error = ex.Message; } return u; } sealed class Login { public string Token; public DateTimeOffset Expires; public string Source; public string Path; // the .credentials.json it came from public string RefreshToken; public DateTimeOffset? RefreshExpires; // renewing stops working then; /login is needed } static Login login; // kept between polls so a login inside WSL does not need WSL running all the time static bool renewAfter401; static DateTime lastForcedRenewal = DateTime.MinValue; // Renew this long before expiry, like Claude Code does. static readonly TimeSpan RenewAhead = TimeSpan.FromMinutes(5); static Login GetLogin() { bool force = renewAfter401 && DateTime.Now - lastForcedRenewal > TimeSpan.FromHours(1); renewAfter401 = false; if (login != null && !force && login.Expires > DateTimeOffset.UtcNow + RenewAhead) return login; Login found = FindLogin(); if (force || found.Expires <= DateTimeOffset.UtcNow + RenewAhead) { if (force) lastForcedRenewal = DateTime.Now; try { found = Renew(found, force); } catch (Exception ex) { Log("renewing the login failed: " + ex.Message); if (found.Expires <= DateTimeOffset.UtcNow) throw; // still usable for a few minutes otherwise } } login = found; return login; } // Claude Code keeps its login in ~/.claude/.credentials.json - on Windows and in every WSL distro // where it is installed. Take the freshest one, expired or not (an expired one gets renewed). static Login FindLogin() { Login best = null; foreach (string path in CredentialCandidates()) { Login l = TryLoad(path); if (l != null && (best == null || l.Expires > best.Expires)) best = l; } if (best == null) throw new Exception("No Claude Code login found - run 'claude' and log in"); return best; } static IEnumerable CredentialCandidates() { string dir = Environment.GetEnvironmentVariable("CLAUDE_CONFIG_DIR"); if (!string.IsNullOrEmpty(dir)) yield return Path.Combine(dir, ".credentials.json"); yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude", ".credentials.json"); foreach (string distro in RunningWslDistros()) { string root = @"\\wsl.localhost\" + distro; string[] homes; try { homes = Directory.GetDirectories(root + @"\home"); } catch (Exception) { continue; } foreach (string home in homes) yield return Path.Combine(home, ".claude", ".credentials.json"); } } static List cachedDistros; static DateTime distrosAt; static readonly object distroLock = new object(); // Only running distros: touching \\wsl.localhost would otherwise boot WSL every few minutes. // Cached briefly, since the Codex reader asks every minute. static List RunningWslDistros() { lock (distroLock) { if (cachedDistros == null || DateTime.Now - distrosAt > TimeSpan.FromMinutes(2)) { cachedDistros = QueryRunningWslDistros(); distrosAt = DateTime.Now; } return cachedDistros; } } static List QueryRunningWslDistros() { var result = new List(); try { var psi = new ProcessStartInfo("wsl.exe", "--list --running --quiet") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, StandardOutputEncoding = Encoding.Unicode, }; using (var p = Process.Start(psi)) { var read = p.StandardOutput.ReadToEndAsync(); if (!p.WaitForExit(10000)) { try { p.Kill(); } catch (Exception) { } return result; } string output = read.Result; if (p.ExitCode != 0) return result; foreach (string line in output.Split('\r', '\n')) { string name = line.Trim('\0', ' ', '\t'); if (name.Length > 0 && !name.StartsWith("docker-desktop", StringComparison.OrdinalIgnoreCase)) result.Add(name); } } } catch (Exception) { } // no WSL installed return result; } static Login TryLoad(string path) { try { if (!File.Exists(path)) return null; return FromJson(ReadCredentials(path), path); } catch (Exception) { return null; } } static Dictionary ReadCredentials(string path) { string json; using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) using (var sr = new StreamReader(fs, Encoding.UTF8)) json = sr.ReadToEnd(); var root = new JavaScriptSerializer().DeserializeObject(json) as Dictionary; if (root == null) throw new Exception("Claude Code's credentials file is not readable"); return root; } static Dictionary OAuthOf(Dictionary root) { object o; return root.TryGetValue("claudeAiOauth", out o) ? o as Dictionary : null; } static Login FromJson(Dictionary root, string path) { var oauth = OAuthOf(root); if (oauth == null) return null; object token, exp, refresh; if (!oauth.TryGetValue("accessToken", out token) || !(token is string) || ((string)token).Length == 0) return null; var l = new Login { Token = (string)token, Expires = DateTimeOffset.MaxValue, Source = Describe(path), Path = path }; if (oauth.TryGetValue("expiresAt", out exp) && exp != null) l.Expires = DateTimeOffset.FromUnixTimeMilliseconds(Convert.ToInt64(exp, CultureInfo.InvariantCulture)); if (oauth.TryGetValue("refreshToken", out refresh)) l.RefreshToken = refresh as string; if (oauth.TryGetValue("refreshTokenExpiresAt", out exp) && exp != null) l.RefreshExpires = DateTimeOffset.FromUnixTimeMilliseconds(Convert.ToInt64(exp, CultureInfo.InvariantCulture)); return l; } // "Windows" or "WSL Ubuntu (alice)", for the menu static string Describe(string path) { if (!path.StartsWith(@"\\wsl.localhost\", StringComparison.OrdinalIgnoreCase)) return "Windows"; string[] parts = path.Split('\\'); // "", "", wsl.localhost, distro, home, user, .claude, file return parts.Length > 5 ? "WSL " + parts[3] + " (" + parts[5] + ")" : "WSL"; } // ---- Codex ------------------------------------------------------------------------------ // // Codex writes one log per session, /sessions/YYYY/MM/DD/rollout-*.jsonl. Every answer adds a // token_count event with the rate limits OpenAI sent along: "primary" is the 5-hour window, "secondary" // the weekly one. The newest such event is the current state - no login or request needed, but it only // changes when Codex runs on this machine. void RefreshCodex() { if (readingCodex) return; readingCodex = true; ThreadPool.QueueUserWorkItem(delegate { CodexUsage c; try { c = ReadCodex(); } catch (Exception ex) { c = new CodexUsage { Error = ex.Message }; } try { invoker.BeginInvoke((MethodInvoker)delegate { OnCodexRead(c); }); } catch (Exception ex) { Log("handing Codex result to UI failed: " + ex.Message); readingCodex = false; } }); } void OnCodexRead(CodexUsage c) { readingCodex = false; if (codex == null || c.AsOf != codex.AsOf || c.Error != codex.Error) Log("codex: " + (c.Error ?? ("5h=" + Pct(c.FiveHour) + " 7d=" + Pct(c.Weekly) + " as of " + c.AsOf.ToString("yyyy-MM-dd HH:mm") + " from " + c.Source))); codex = c; Redraw(); } static CodexUsage ReadCodex() { CodexUsage best = null; foreach (string home in CodexHomes()) { CodexUsage c = ReadCodexHome(home); if (c != null && (best == null || c.AsOf > best.AsOf)) best = c; } return best ?? new CodexUsage { Error = "no usage found - Codex has not run here yet" }; } static IEnumerable CodexHomes() { string env = Environment.GetEnvironmentVariable("CODEX_HOME"); if (!string.IsNullOrEmpty(env)) yield return env; yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".codex"); foreach (string distro in RunningWslDistros()) { string[] homes; try { homes = Directory.GetDirectories(@"\\wsl.localhost\" + distro + @"\home"); } catch (Exception) { continue; } foreach (string home in homes) yield return Path.Combine(home, ".codex"); } } static CodexUsage ReadCodexHome(string home) { string sessions = Path.Combine(home, "sessions"); if (!Directory.Exists(sessions)) return null; var files = new List(); foreach (string day in NewestDayDirs(sessions, 3)) try { files.AddRange(new DirectoryInfo(day).GetFiles("rollout-*.jsonl")); } catch (Exception) { } files.Sort((a, b) => b.LastWriteTimeUtc.CompareTo(a.LastWriteTimeUtc)); CodexUsage best = null; for (int i = 0; i < files.Count && i < 5; i++) { CodexUsage c = ReadRateLimits(files[i].FullName); if (c != null && (best == null || c.AsOf > best.AsOf)) best = c; } if (best != null) best.Source = Describe(home); return best; } // the session folders are named 2026/11/20 - zero-padded, so name order is date order static IEnumerable NewestDayDirs(string sessions, int count) { int n = 0; foreach (string year in DirsNewestFirst(sessions)) foreach (string month in DirsNewestFirst(year)) foreach (string day in DirsNewestFirst(month)) { if (n++ >= count) yield break; yield return day; } } static string[] DirsNewestFirst(string dir) { string[] dirs; try { dirs = Directory.GetDirectories(dir); } catch (Exception) { return new string[0]; } Array.Sort(dirs, StringComparer.Ordinal); Array.Reverse(dirs); return dirs; } // Session logs can be large; the newest rate limits are near the end. static CodexUsage ReadRateLimits(string path) { string text; try { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { fs.Seek(Math.Max(0, fs.Length - 256 * 1024), SeekOrigin.Begin); using (var sr = new StreamReader(fs, Encoding.UTF8)) text = sr.ReadToEnd(); } } catch (Exception) { return null; } string[] lines = text.Split('\n'); var json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; for (int i = lines.Length - 1; i >= 0; i--) { if (lines[i].IndexOf("\"rate_limits\"", StringComparison.Ordinal) < 0) continue; Dictionary entry; try { entry = json.DeserializeObject(lines[i]) as Dictionary; } catch (Exception) { continue; } // the first line of the tail may be cut off object payload, rl, id, ts; if (entry == null || !entry.TryGetValue("payload", out payload) || !(payload is Dictionary)) continue; if (!((Dictionary)payload).TryGetValue("rate_limits", out rl)) continue; var limits = rl as Dictionary; if (limits == null) continue; if (limits.TryGetValue("limit_id", out id) && id is string && (string)id != "codex") continue; var c = new CodexUsage(); ReadCodexWindow(limits, "primary", out c.FiveHour, out c.FiveHourReset); ReadCodexWindow(limits, "secondary", out c.Weekly, out c.WeeklyReset); if (c.FiveHour < 0 && c.Weekly < 0) continue; DateTime t; c.AsOf = entry.TryGetValue("timestamp", out ts) && ts is string && DateTime.TryParse((string)ts, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out t) ? t.ToLocalTime() : File.GetLastWriteTime(path); return c; } return null; } static void ReadCodexWindow(Dictionary limits, string key, out double pct, out DateTime? reset) { pct = -1; reset = null; object o, v; var w = limits.TryGetValue(key, out o) ? o as Dictionary : null; if (w == null) return; if (w.TryGetValue("used_percent", out v) && v != null) pct = Convert.ToDouble(v, CultureInfo.InvariantCulture); if (w.TryGetValue("resets_at", out v) && v != null) reset = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(v, CultureInfo.InvariantCulture)).LocalDateTime; } // ---- renewing the login -------------------------------------------------------------- // // Claude Code only renews its login while it runs; unused for ~8 hours, the login expires. So this // program renews it the way Claude Code does (Claude Code 2.1.x, read from its source): // 1. take its two refresh locks: ~/.claude/.oauth_refresh.lock and ~/.claude.lock // (proper-lockfile: a directory; abandoned when its mtime is older than 60 s), // 2. re-read the file inside the lock - if a Claude Code session renewed it meanwhile, use that, // 3. POST the refresh token to the token endpoint with Claude Code's client id and the login's scopes, // 4. under its write lock ~/.claude/.storage-write.lock, replace the file atomically, mode 600, // changing only the token fields of claudeAiOauth. // Claude Code sessions that are running pick up the renewed file themselves (they re-read it before // they renew and after a 401). const string TokenUrl = "https://platform.claude.com/v1/oauth/token"; const string ClaudeCodeClientId = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"; static readonly string[] DefaultScopes = { "user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload" }; static readonly HashSet deadRefreshTokens = new HashSet(); static Login Renew(Login stale, bool force) { if (string.IsNullOrEmpty(stale.RefreshToken)) throw new Exception("Login cannot be renewed - run /login in Claude Code"); if (deadRefreshTokens.Contains(stale.RefreshToken)) throw new Exception("Login was revoked - run /login in Claude Code"); string dir = Path.GetDirectoryName(stale.Path); string refreshLock = Path.Combine(dir, ".oauth_refresh.lock"); string legacyLock = dir.TrimEnd('\\') + ".lock"; string writeLock = Path.Combine(dir, ".storage-write.lock"); if (!TakeLock(refreshLock, 90)) throw new Exception("Claude Code is renewing the login right now"); try { if (!TakeLock(legacyLock, 90)) throw new Exception("Claude Code is renewing the login right now"); try { Login current = FromJson(ReadCredentials(stale.Path), stale.Path); if (current == null) throw new Exception("Claude Code login disappeared"); if (current.Token != stale.Token) { Log("login was renewed by Claude Code meanwhile"); return current; } if (!force && current.Expires > DateTimeOffset.UtcNow + RenewAhead) return current; Dictionary answer = RequestRenewal(current, OAuthOf(ReadCredentials(stale.Path))); // retries like Claude Code's write lock (10 retries, 100 ms - 1 s apart) bool locked = false; for (int i = 0; i < 11 && !(locked = TakeLock(writeLock, 30)); i++) Thread.Sleep(100 * (i + 1)); if (!locked) throw new Exception("Renewed, but Claude Code's credentials file stayed locked - not saved"); try { Dictionary root = ReadCredentials(stale.Path); // fresh copy, other fields untouched ApplyRenewal(OAuthOf(root), answer); WriteCredentials(stale.Path, new JavaScriptSerializer().Serialize(root)); } finally { ReleaseLock(writeLock); } Login renewed = FromJson(ReadCredentials(stale.Path), stale.Path); if (renewed == null || renewed.Token != (string)answer["access_token"]) throw new Exception("Renewed login did not end up in the credentials file"); Log("renewed the login in " + renewed.Source + ", valid until " + renewed.Expires.ToLocalTime().ToString("HH:mm")); return renewed; } finally { ReleaseLock(legacyLock); } } finally { ReleaseLock(refreshLock); } } static Dictionary RequestRenewal(Login l, Dictionary oauth) { object scopes, clientId; string scope = oauth.TryGetValue("scopes", out scopes) && scopes is object[] && ((object[])scopes).Length > 0 ? string.Join(" ", (object[])scopes) : string.Join(" ", DefaultScopes); string client = oauth.TryGetValue("clientId", out clientId) && clientId is string ? (string)clientId : ClaudeCodeClientId; string payload = new JavaScriptSerializer().Serialize(new Dictionary { { "grant_type", "refresh_token" }, { "refresh_token", l.RefreshToken }, { "client_id", client }, { "scope", scope }, }); var req = (HttpWebRequest)WebRequest.Create(TokenUrl); req.Method = "POST"; req.ContentType = "application/json"; req.Accept = "application/json"; req.UserAgent = "claude-usage-tray/1.0"; req.Timeout = 15000; req.ReadWriteTimeout = 15000; byte[] data = Encoding.UTF8.GetBytes(payload); try { using (new System.Threading.Timer(delegate { req.Abort(); }, null, 25000, Timeout.Infinite)) { using (Stream s = req.GetRequestStream()) s.Write(data, 0, data.Length); using (var resp = (HttpWebResponse)req.GetResponse()) using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)) { var answer = new JavaScriptSerializer().DeserializeObject(sr.ReadToEnd()) as Dictionary; object token, expiresIn; if (answer == null || !answer.TryGetValue("access_token", out token) || !(token is string) || !answer.TryGetValue("expires_in", out expiresIn) || expiresIn == null) throw new Exception("Unexpected answer when renewing the login"); return answer; } } } catch (WebException ex) { var r = ex.Response as HttpWebResponse; using (r) { if (r == null) throw new Exception("No answer when renewing the login"); string body = ""; try { using (var sr = new StreamReader(r.GetResponseStream())) body = sr.ReadToEnd(); } catch (Exception) { } if (body.Contains("invalid_grant")) { deadRefreshTokens.Add(l.RefreshToken); // never retry it, Claude Code would not either throw new Exception("Login was revoked - run /login in Claude Code"); } throw new Exception("Renewing the login failed: HTTP " + (int)r.StatusCode); } } } static void ApplyRenewal(Dictionary oauth, Dictionary answer) { long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); object v; oauth["accessToken"] = answer["access_token"]; if (answer.TryGetValue("refresh_token", out v) && v is string && ((string)v).Length > 0) oauth["refreshToken"] = v; oauth["expiresAt"] = now + (long)(Convert.ToDouble(answer["expires_in"], CultureInfo.InvariantCulture) * 1000); if (answer.TryGetValue("refresh_token_expires_in", out v) && v != null) oauth["refreshTokenExpiresAt"] = now + (long)(Convert.ToDouble(v, CultureInfo.InvariantCulture) * 1000); if (answer.TryGetValue("scope", out v) && v is string && ((string)v).Trim().Length > 0) oauth["scopes"] = ((string)v).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); } // Atomic replace, readable by the owner only - as Claude Code writes it. static void WriteCredentials(string path, string json) { byte[] bytes = new UTF8Encoding(false).GetBytes(json); string[] parts = path.Split('\\'); // "", "", wsl.localhost, distro, home, user, .claude, .credentials.json if (path.StartsWith(@"\\wsl.localhost\", StringComparison.OrdinalIgnoreCase) && parts.Length == 8) { // inside WSL a file created from Windows would not get mode 600, so let WSL write it string linuxDir = "/" + string.Join("/", parts, 4, 3); var psi = new ProcessStartInfo("wsl.exe", "-d " + parts[3] + " -u " + parts[5] + " --cd \"" + linuxDir + "\" --exec sh -c " + "\"umask 077 && cat > .credentials.json.tray-tmp && mv -f .credentials.json.tray-tmp .credentials.json\"") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, }; using (var p = Process.Start(psi)) { p.StandardInput.BaseStream.Write(bytes, 0, bytes.Length); p.StandardInput.Close(); if (!p.WaitForExit(15000)) { try { p.Kill(); } catch (Exception) { } throw new Exception("Saving the renewed login timed out"); } if (p.ExitCode != 0) throw new Exception("Saving the renewed login failed (exit " + p.ExitCode + ")"); } } else { string tmp = path + ".tray-tmp"; File.WriteAllBytes(tmp, bytes); File.Replace(tmp, path, null); } } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CreateDirectoryW(string path, IntPtr securityAttributes); // proper-lockfile compatible: the lock is a directory, created atomically; its holder touches it every // few seconds, so an old one was abandoned. staleSeconds is a little above Claude Code's own limit. static bool TakeLock(string path, int staleSeconds) { if (CreateDirectoryW(path, IntPtr.Zero)) return true; int error = Marshal.GetLastWin32Error(); if (error != 183) throw new IOException("Cannot create lock " + path + " (error " + error + ")"); // 183 = exists if (DateTime.UtcNow - Directory.GetLastWriteTimeUtc(path) < TimeSpan.FromSeconds(staleSeconds)) return false; Log("removing abandoned lock " + path); try { Directory.Delete(path); } catch (Exception) { } return CreateDirectoryW(path, IntPtr.Zero); } static void ReleaseLock(string path) { try { Directory.Delete(path); } catch (Exception ex) { Log("releasing lock " + path + " failed: " + ex.Message); } } // --renew-now: renew once regardless of expiry, for testing. Result in log.txt and the exit code. public static int RenewNow() { InitDataDir(); Log("--renew-now"); try { Login l = Renew(FindLogin(), true); Log("--renew-now done, login from " + l.Source + " valid until " + l.Expires.ToLocalTime().ToString("HH:mm")); return 0; } catch (Exception ex) { Log("--renew-now failed: " + ex.Message); return 1; } } static void Parse(string json, Usage u) { var root = new JavaScriptSerializer().DeserializeObject(json) as Dictionary; if (root == null || !root.ContainsKey("five_hour")) throw new Exception("Unexpected answer from usage API"); ReadWindow(root, "five_hour", out u.FiveHour, out u.FiveHourReset); ReadWindow(root, "seven_day", out u.SevenDay, out u.SevenDayReset); } static void ReadWindow(Dictionary root, string key, out double pct, out DateTime? reset) { pct = -1; reset = null; object o; if (!root.TryGetValue(key, out o)) return; var w = o as Dictionary; if (w == null) { pct = 0; return; } // null window = nothing used yet object v; pct = w.TryGetValue("utilization", out v) && v != null ? Convert.ToDouble(v, CultureInfo.InvariantCulture) : 0; DateTime d; if (w.TryGetValue("resets_at", out v) && v is string && DateTime.TryParse((string)v, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out d)) reset = d.ToLocalTime(); } static string logPath; static readonly object logLock = new object(); static void InitDataDir() { dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppName); Directory.CreateDirectory(dataDir); logPath = Path.Combine(dataDir, "log.txt"); } // Step log for troubleshooting, never contains the token. Starts over at 100 KB. static void Log(string message) { lock (logLock) { try { if (File.Exists(logPath) && new FileInfo(logPath).Length > 100 * 1024) File.Delete(logPath); File.AppendAllText(logPath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + message + Environment.NewLine); } catch (Exception) { } } } void WriteStatus(Usage u) { string line = u.Fetched.ToString("yyyy-MM-dd HH:mm:ss") + " " + (u.Error ?? ("5h=" + Pct(u.FiveHour) + " reset " + When(u.FiveHourReset) + " 7d=" + Pct(u.SevenDay) + " reset " + When(u.SevenDayReset) + " login=" + u.Source)); try { File.WriteAllText(Path.Combine(dataDir, "status.txt"), line + Environment.NewLine); } catch (Exception ex) { Log("writing status.txt failed: " + ex.Message); } Log("status: " + line.Substring(21)); } // ---- display ----------------------------------------------------------------------- void OnTick() { // the 5-hour window rolled over: the shown number is stale, fetch the new one if (last != null && last.FiveHourReset.HasValue && DateTime.Now > last.FiveHourReset.Value.AddSeconds(30) && latest != null && latest.Fetched < last.FiveHourReset.Value.AddSeconds(30)) Refresh(); UpdateTexts(); } void Redraw() { bool stale = latest != null && latest.Error != null; SetIcon(tray, ref currentIcon, Render(last != null ? last.FiveHour : -1, stale, false)); bool codexKnown = codex != null && codex.Error == null; SetIcon(codexTray, ref currentCodexIcon, Render(codexKnown ? codex.FiveHourNow : -1, !codexKnown, true)); UpdateTexts(); } void UpdateTexts() { string tip; if (last != null) { fiveHourItem.Text = "Claude 5-hour: " + Pct(last.FiveHour) + ResetText(last.FiveHourReset, false); sevenDayItem.Text = "Claude weekly: " + Pct(last.SevenDay) + ResetText(last.SevenDayReset, true); tip = "Claude 5h: " + Pct(last.FiveHour) + ShortReset(last.FiveHourReset, false) + "\nweekly: " + Pct(last.SevenDay); } else { fiveHourItem.Text = "Claude 5-hour: unknown"; sevenDayItem.Text = "Claude weekly: unknown"; tip = "Claude 5h"; } if (latest == null) statusItem.Text = "Loading…"; else if (latest.Error != null) { statusItem.Text = "⚠ " + latest.Error; tip += "\n⚠ " + latest.Error; } else statusItem.Text = "Updated " + latest.Fetched.ToString("HH:mm") + " - login: " + latest.Source; DateTimeOffset? until = last != null ? last.RenewableUntil : null; loginItem.Visible = until.HasValue; if (until.HasValue) { string date = until.Value.ToLocalTime().ToString("ddd d MMM", CultureInfo.CurrentCulture); loginItem.Text = until.Value - DateTimeOffset.UtcNow < TimeSpan.FromDays(3) ? "⚠ Login ends " + date + " - run /login in Claude Code before" : "Login renews itself until " + date; } tray.Text = Tooltip(tip); string codexTip; codexWeeklyItem.Visible = codexStatusItem.Visible = codex != null && codex.Error == null; if (codex == null) { codexFiveHourItem.Text = "Codex: loading…"; codexTip = "Codex 5h"; } else if (codex.Error != null) { codexFiveHourItem.Text = "Codex: " + codex.Error; codexTip = "Codex: " + codex.Error; } else { codexFiveHourItem.Text = "Codex 5-hour: " + Pct(codex.FiveHourNow) + CodexReset(codex.FiveHourReset, false, false); codexWeeklyItem.Text = "Codex weekly: " + Pct(codex.WeeklyNow) + CodexReset(codex.WeeklyReset, true, false); string asOf = codex.AsOf.ToString(codex.AsOf.Date == DateTime.Today ? "HH:mm" : "ddd HH:mm", CultureInfo.CurrentCulture); codexStatusItem.Text = "As of the last Codex run, " + asOf + " - " + codex.Source; codexTip = "Codex 5h: " + Pct(codex.FiveHourNow) + CodexReset(codex.FiveHourReset, false, true) + "\nas of last Codex run " + asOf; } codexTray.Text = Tooltip(codexTip); } // like ResetText/ShortReset, but a Codex window can lie in the past when Codex has not run since static string CodexReset(DateTime? t, bool withDay, bool shortForm) { if (t.HasValue && DateTime.Now >= t.Value) return (shortForm ? ", " : " - ") + "reset at " + t.Value.ToString(withDay ? "ddd HH:mm" : "HH:mm", CultureInfo.CurrentCulture); return shortForm ? ShortReset(t, withDay) : ResetText(t, withDay); } static string Tooltip(string text) { return text.Length > 63 ? text.Substring(0, 62) + "…" : text; } static string Pct(double p) { return p < 0 ? "?" : Math.Round(p).ToString(CultureInfo.InvariantCulture) + "%"; } static string When(DateTime? t) { return t.HasValue ? t.Value.ToString("yyyy-MM-dd HH:mm") : "-"; } static string Left(DateTime t) { TimeSpan d = t - DateTime.Now; if (d.TotalMinutes < 1) return "<1m"; if (d.TotalHours < 24) return (d.Hours > 0 ? d.Hours + "h " : "") + d.Minutes + "m"; return d.Days + "d " + d.Hours + "h"; } static string ResetText(DateTime? t, bool withDay) { if (!t.HasValue) return ""; string at = t.Value.ToString(withDay ? "ddd HH:mm" : "HH:mm", CultureInfo.CurrentCulture); return " - resets " + at + " (in " + Left(t.Value) + ")"; } static string ShortReset(DateTime? t, bool withDay) { return t.HasValue ? ", resets " + t.Value.ToString(withDay ? "ddd HH:mm" : "HH:mm", CultureInfo.CurrentCulture) + " (" + Left(t.Value) + ")" : ""; } static void SetIcon(NotifyIcon target, ref Icon current, Icon icon) { Icon old = current; current = icon; target.Icon = icon; if (old != null) old.Dispose(); } static Color Accent(double pct) { if (pct < 0) return Color.FromArgb(160, 160, 160); if (pct >= 90) return Color.FromArgb(255, 95, 95); if (pct >= 70) return Color.FromArgb(255, 190, 60); return Color.FromArgb(90, 210, 110); } // Dark rounded square, the percentage as a number and a bar. Claude: warm tint, bar at the bottom; // Codex: cool tint, bar at the top - so the two can be told apart at a glance. static Icon Render(double pct, bool stale, bool codexStyle) { bool barOnTop = codexStyle; int s = SystemInformation.SmallIconSize.Width; using (var bmp = new Bitmap(s, s)) using (var g = Graphics.FromImage(bmp)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; g.Clear(Color.Transparent); Color accent = stale ? Color.FromArgb(160, 160, 160) : Accent(pct); using (var path = Rounded(new RectangleF(0, 0, s, s), s / 5f)) { Color background = codexStyle ? Color.FromArgb(235, 22, 28, 42) : Color.FromArgb(235, 38, 28, 24); using (var bg = new SolidBrush(background)) g.FillPath(bg, path); if (pct > 0) { float barH = Math.Max(2, s / 8f); float barW = (float)(s * Math.Min(pct, 100) / 100.0); g.SetClip(path); using (var bar = new SolidBrush(accent)) g.FillRectangle(bar, 0, barOnTop ? 0 : s - barH, barW, barH); g.ResetClip(); } } string text = pct < 0 ? "?" : Math.Min(Math.Round(pct), 999).ToString(CultureInfo.InvariantCulture); float barSpace = Math.Max(2, s / 8f); var area = new RectangleF(0, barOnTop ? barSpace : 0, s, s - barSpace); float size = s * (text.Length >= 3 ? 0.5f : 0.72f); using (var fmt = (StringFormat)StringFormat.GenericTypographic.Clone()) { fmt.Alignment = StringAlignment.Center; fmt.LineAlignment = StringAlignment.Center; fmt.FormatFlags |= StringFormatFlags.NoWrap; Font font = null; try { // shrink until the number fits the icon width while (true) { font = new Font("Segoe UI", size, FontStyle.Bold, GraphicsUnit.Pixel); if (g.MeasureString(text, font, 1000, fmt).Width <= s || size <= 6) break; font.Dispose(); size -= 0.5f; } using (var brush = new SolidBrush(stale ? Color.FromArgb(170, 170, 170) : accent)) g.DrawString(text, font, brush, area, fmt); } finally { if (font != null) font.Dispose(); } } IntPtr h = bmp.GetHicon(); try { return (Icon)Icon.FromHandle(h).Clone(); } finally { DestroyIcon(h); } } } static GraphicsPath Rounded(RectangleF r, float radius) { float d = radius * 2; var p = new GraphicsPath(); p.AddArc(r.X, r.Y, d, d, 180, 90); p.AddArc(r.Right - d, r.Y, d, d, 270, 90); p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90); p.AddArc(r.X, r.Bottom - d, d, d, 90, 90); p.CloseFigure(); return p; } [DllImport("user32.dll")] static extern bool DestroyIcon(IntPtr handle); // ---- interaction ------------------------------------------------------------------- void OnTrayMouseUp(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; Refresh(); // NotifyIcon only opens its menu on right click; this is the usual way to open it on left click MethodInfo show = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic); if (show != null) show.Invoke(sender, null); } void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e) { if (e.Mode != PowerModes.Resume) return; // give the network a moment after waking up invoker.BeginInvoke((MethodInvoker)delegate { var once = new System.Windows.Forms.Timer { Interval = 15000 }; once.Tick += delegate { once.Dispose(); Refresh(); }; once.Start(); }); } static void OpenUsagePage() { try { Process.Start(UsagePage); } catch (Exception) { } } static string ExePath() { return Application.ExecutablePath; } static bool IsAutostart() { using (var k = Registry.CurrentUser.OpenSubKey(RunKey)) return k != null && k.GetValue(AppName) != null; } static void SetAutostart(bool on) { using (var k = Registry.CurrentUser.CreateSubKey(RunKey)) { if (on) k.SetValue(AppName, "\"" + ExePath() + "\""); else k.DeleteValue(AppName, false); } } // Windows 11 hides new tray icons in the overflow flyout. On the first start of each icon, mark it // as "show in taskbar" (the same switch as Settings > Taskbar > Other system tray icons). // Only once per icon, so a later choice by the user to hide it is respected. void PromoteIconOnce(int uid, string flagName) { string flag = Path.Combine(dataDir, flagName); if (File.Exists(flag)) return; var t = new System.Windows.Forms.Timer { Interval = 5000 }; int tries = 0; t.Tick += delegate { tries++; if (TryPromote(uid) || tries >= 12) { t.Dispose(); try { File.WriteAllText(flag, DateTime.Now.ToString("s")); } catch (IOException) { } } }; t.Start(); } // Windows keeps one entry per icon: our exe path plus the icon's UID. static bool TryPromote(int uid) { try { using (var root = Registry.CurrentUser.OpenSubKey(@"Control Panel\NotifyIconSettings")) { if (root == null) return true; // not Windows 11, nothing to do foreach (string name in root.GetSubKeyNames()) using (var k = Registry.CurrentUser.OpenSubKey(@"Control Panel\NotifyIconSettings\" + name, true)) { string exe = k == null ? null : k.GetValue("ExecutablePath") as string; object id = k == null ? null : k.GetValue("UID"); if (exe != null && string.Equals(exe, ExePath(), StringComparison.OrdinalIgnoreCase) && id is int && (int)id == uid) { k.SetValue("IsPromoted", 1, RegistryValueKind.DWord); return true; } } } } catch (Exception) { } return false; } protected override void ExitThreadCore() { SystemEvents.PowerModeChanged -= OnPowerModeChanged; pollTimer.Stop(); tickTimer.Stop(); codexTimer.Stop(); tray.Visible = false; codexTray.Visible = false; tray.Dispose(); codexTray.Dispose(); if (currentIcon != null) currentIcon.Dispose(); if (currentCodexIcon != null) currentCodexIcon.Dispose(); invoker.Dispose(); base.ExitThreadCore(); } } }