Compare commits

...
5 changed files with 239 additions and 48 deletions
+2
View File
@@ -9,6 +9,8 @@ public class AppSettings
public string CookieStore { get; set; } = ""; public string CookieStore { get; set; } = "";
public string BurnHistory { get; set; } = ""; public string BurnHistory { get; set; } = "";
public string OrgId { get; set; } = ""; public string OrgId { get; set; } = "";
public string Email { get; set; } = "";
public string UsageJson { get; set; } = "";
public int RefreshInterval { get; set; } = 120; public int RefreshInterval { get; set; } = 120;
public bool ShowInTaskbar { get; set; } = true; public bool ShowInTaskbar { get; set; } = true;
public bool BetaChannel { get; set; } = false; public bool BetaChannel { get; set; } = false;
+43 -5
View File
@@ -2,6 +2,7 @@ using Microsoft.Web.WebView2.Core;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
@@ -9,6 +10,8 @@ namespace ClaudeCheckerWindows;
public partial class LoginWindow : Window public partial class LoginWindow : Window
{ {
private bool _closing;
public LoginWindow() public LoginWindow()
{ {
InitializeComponent(); InitializeComponent();
@@ -27,7 +30,7 @@ public partial class LoginWindow : Window
Browser.CoreWebView2.NavigationCompleted += async (_, e) => Browser.CoreWebView2.NavigationCompleted += async (_, e) =>
{ {
if (!e.IsSuccess) return; if (!e.IsSuccess || _closing) return;
var uri = Browser.CoreWebView2.Source; var uri = Browser.CoreWebView2.Source;
if (!uri.Contains("claude.ai")) return; if (!uri.Contains("claude.ai")) return;
@@ -44,23 +47,58 @@ public partial class LoginWindow : Window
: "Complete sign-in, then click Done."; : "Complete sign-in, then click Done.";
}); });
// Auto-close only on explicit post-login redirects, not on initial load // Auto-close as soon as we detect sign-in on any claude.ai page
if (signedIn && (uri.Contains("/chats") || uri.Contains("/new"))) if (signedIn && !uri.Contains("/login") && !uri.Contains("/signin"))
{
await SaveAndClose(cookies); await SaveAndClose(cookies);
}
}; };
} }
private async void Done_Click(object sender, RoutedEventArgs e) private async void Done_Click(object sender, RoutedEventArgs e)
{ {
if (_closing) return;
var cookies = await Browser.CoreWebView2.CookieManager.GetCookiesAsync("https://claude.ai"); var cookies = await Browser.CoreWebView2.CookieManager.GetCookiesAsync("https://claude.ai");
await SaveAndClose(cookies); await SaveAndClose(cookies);
} }
private async Task SaveAndClose(IReadOnlyList<CoreWebView2Cookie> cookies) private async Task SaveAndClose(IReadOnlyList<CoreWebView2Cookie> cookies)
{ {
if (_closing) return;
_closing = true;
UsageViewModel.SaveCookies(cookies); UsageViewModel.SaveCookies(cookies);
// Fetch bootstrap + usage from within WebView2 (already authenticated, no header issues)
try
{
const string script = @"(async()=>{try{
const b=await(await fetch('/api/bootstrap',{headers:{accept:'application/json'}})).json();
const id=b?.memberships?.[0]?.organization?.uuid||b?.organizations?.[0]?.uuid||null;
const e=b?.account?.email_address||null;
if(!id)return{email:e,orgId:null,usage:null};
const u=await(await fetch('/api/organizations/'+id+'/usage',{headers:{accept:'application/json'}})).json();
return{email:e,orgId:id,usage:u};
}catch(ex){return{error:String(ex)};}})()";
var json = await Browser.CoreWebView2.ExecuteScriptAsync(script);
if (json != "null" && !string.IsNullOrEmpty(json))
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.TryGetProperty("email", out var em) && em.ValueKind == JsonValueKind.String)
AppSettings.Default.Email = em.GetString() ?? "";
if (root.TryGetProperty("orgId", out var oi) && oi.ValueKind == JsonValueKind.String)
AppSettings.Default.OrgId = oi.GetString() ?? "";
if (root.TryGetProperty("usage", out var us) && us.ValueKind == JsonValueKind.Object)
AppSettings.Default.UsageJson = us.GetRawText();
AppSettings.Default.Save();
}
}
catch { }
await Dispatcher.InvokeAsync(() => DialogResult = true); await Dispatcher.InvokeAsync(() => DialogResult = true);
} }
} }
+5 -6
View File
@@ -1,7 +1,6 @@
## What's new in beta.19 ## What's new in beta.21
- Fixed dark mode: button hover no longer white, ComboBox fully themed - Fixed: clicking Sign In now auto-closes as soon as you are detected as signed in (no need to click Done)
- Fixed logo and version badge in Settings panel - Fixed: login now fetches and caches your data directly via the browser session (no more authentication failures)
- Fixed signed-in email showing blank (TextBrush instead of hardcoded white) - Fixed: periodic refresh falls back to browser-session API calls when HttpClient is rejected
- Fixed session limits not loading: org ID now fetched dynamically from API - Fixed: cached usage from login is shown immediately while refreshing
- Added anthropic-client-platform header for correct API responses
+130 -37
View File
@@ -89,12 +89,35 @@ public class UsageViewModel : INotifyPropertyChanged
return; return;
} }
using var http = BuildClient(cookies); // Try HttpClient first (fast path)
var (limits, overage, prepaid, email, orgId, ok) = await TryHttpRefreshAsync(cookies);
// Bootstrap gives us email + org ID. If it fails, cookies are invalid. // If HttpClient failed, fall back to WebView2 (uses existing browser session)
var (email, orgId) = await FetchBootstrapAsync(http); if (!ok)
if (string.IsNullOrEmpty(orgId)) (limits, email, orgId) = await TryWebView2RefreshAsync();
// Still no org ID? Use cached values from last successful login
if (string.IsNullOrEmpty(orgId) && !string.IsNullOrEmpty(AppSettings.Default.OrgId))
orgId = AppSettings.Default.OrgId;
if (string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(AppSettings.Default.Email))
email = AppSettings.Default.Email;
// If we have cached usage from login and still got nothing live, use that
if (limits.Count == 0 && !string.IsNullOrEmpty(AppSettings.Default.UsageJson))
{ {
try
{
var cached = System.Text.Json.JsonSerializer.Deserialize<UsageResponse>(
AppSettings.Default.UsageJson, JsonOpts);
limits = BuildLimits(cached);
}
catch { }
}
bool isAuth = !string.IsNullOrEmpty(email) || !string.IsNullOrEmpty(orgId) || limits.Count > 0;
if (!isAuth && cookies.Count > 0)
{
// Cookies exist but nothing worked — session likely expired
await Application.Current.Dispatcher.InvokeAsync(() => await Application.Current.Dispatcher.InvokeAsync(() =>
{ {
IsSignedIn = false; IsSignedIn = false;
@@ -104,19 +127,6 @@ public class UsageViewModel : INotifyPropertyChanged
return; return;
} }
// Cache org ID for resilience
AppSettings.Default.OrgId = orgId;
AppSettings.Default.Save();
var usageTask = FetchAsync<UsageResponse>(http, $"https://claude.ai/api/organizations/{orgId}/usage");
var overageTask = FetchAsync<OverageSpendLimit>(http, $"https://claude.ai/api/organizations/{orgId}/overage_spend_limit");
var prepaidTask = FetchAsync<PrepaidCredits>(http, $"https://claude.ai/api/organizations/{orgId}/prepaid/credits");
await Task.WhenAll(usageTask, overageTask, prepaidTask);
var usage = usageTask.Result;
var limits = BuildLimits(usage);
foreach (var limit in limits) foreach (var limit in limits)
{ {
var key = limit.Window.ToString(); var key = limit.Window.ToString();
@@ -131,9 +141,9 @@ public class UsageViewModel : INotifyPropertyChanged
await Application.Current.Dispatcher.InvokeAsync(() => await Application.Current.Dispatcher.InvokeAsync(() =>
{ {
Limits = limits; Limits = limits;
Overage = overageTask.Result; Overage = overage;
Prepaid = prepaidTask.Result; Prepaid = prepaid;
UserEmail = email ?? UserEmail; if (!string.IsNullOrEmpty(email)) UserEmail = email;
IsSignedIn = true; IsSignedIn = true;
ErrorMessage = null; ErrorMessage = null;
LastUpdated = DateTime.Now; LastUpdated = DateTime.Now;
@@ -150,10 +160,95 @@ public class UsageViewModel : INotifyPropertyChanged
} }
} }
private async Task<(List<AgentLimit>, OverageSpendLimit?, PrepaidCredits?, string?, string?, bool)>
TryHttpRefreshAsync(List<(string Name, string Value, string Domain, string Path)> cookies)
{
try
{
using var http = BuildClient(cookies);
var bootstrapResp = await http.GetAsync("https://claude.ai/api/bootstrap");
if (!bootstrapResp.IsSuccessStatusCode)
return ([], null, null, null, null, false);
var (email, orgId) = ParseBootstrap(await bootstrapResp.Content.ReadAsStringAsync());
if (string.IsNullOrEmpty(orgId))
orgId = await FetchOrgIdFromListAsync(http);
if (string.IsNullOrEmpty(orgId) && !string.IsNullOrEmpty(AppSettings.Default.OrgId))
orgId = AppSettings.Default.OrgId;
if (string.IsNullOrEmpty(orgId))
return ([], null, null, email, orgId, true);
AppSettings.Default.OrgId = orgId;
AppSettings.Default.Save();
var ut = FetchAsync<UsageResponse>(http, $"https://claude.ai/api/organizations/{orgId}/usage");
var ot = FetchAsync<OverageSpendLimit>(http, $"https://claude.ai/api/organizations/{orgId}/overage_spend_limit");
var pt = FetchAsync<PrepaidCredits>(http, $"https://claude.ai/api/organizations/{orgId}/prepaid/credits");
await Task.WhenAll(ut, ot, pt);
return (BuildLimits(ut.Result), ot.Result, pt.Result, email, orgId, true);
}
catch { return ([], null, null, null, null, false); }
}
private static async Task<(List<AgentLimit>, string?, string?)> TryWebView2RefreshAsync()
{
try
{
const string script = @"(async()=>{try{
const b=await(await fetch('/api/bootstrap',{headers:{accept:'application/json'}})).json();
const id=b?.memberships?.[0]?.organization?.uuid||b?.organizations?.[0]?.uuid||null;
const em=b?.account?.email_address||null;
if(!id)return{email:em,orgId:null,usage:null};
const u=await(await fetch('/api/organizations/'+id+'/usage',{headers:{accept:'application/json'}})).json();
return{email:em,orgId:id,usage:u};
}catch(ex){return null;}})()";
var resultJson = await Application.Current.Dispatcher.InvokeAsync(async () =>
{
var host = new WebViewFetchWindow();
host.Show();
try { return await host.FetchAsync("https://claude.ai", script); }
finally { host.Close(); }
}).Task;
if (resultJson == null || resultJson == "null") return ([], null, null);
using var doc = System.Text.Json.JsonDocument.Parse(resultJson);
var root = doc.RootElement;
string? email = root.TryGetProperty("email", out var em) && em.ValueKind == System.Text.Json.JsonValueKind.String
? em.GetString() : null;
string? orgId = root.TryGetProperty("orgId", out var oi) && oi.ValueKind == System.Text.Json.JsonValueKind.String
? oi.GetString() : null;
List<AgentLimit> limits = [];
if (root.TryGetProperty("usage", out var us) && us.ValueKind == System.Text.Json.JsonValueKind.Object)
{
var usage = System.Text.Json.JsonSerializer.Deserialize<UsageResponse>(
us.GetRawText(), new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true });
limits = BuildLimits(usage);
// Cache for next time
AppSettings.Default.UsageJson = us.GetRawText();
if (!string.IsNullOrEmpty(orgId)) AppSettings.Default.OrgId = orgId;
if (!string.IsNullOrEmpty(email)) AppSettings.Default.Email = email;
AppSettings.Default.Save();
}
return (limits, email, orgId);
}
catch { return ([], null, null); }
}
public async Task SignOutAsync() public async Task SignOutAsync()
{ {
AppSettings.Default.CookieStore = ""; AppSettings.Default.CookieStore = "";
AppSettings.Default.OrgId = ""; AppSettings.Default.OrgId = "";
AppSettings.Default.Email = "";
AppSettings.Default.UsageJson = "";
AppSettings.Default.Save(); AppSettings.Default.Save();
await Application.Current.Dispatcher.InvokeAsync(() => await Application.Current.Dispatcher.InvokeAsync(() =>
@@ -193,7 +288,9 @@ public class UsageViewModel : INotifyPropertyChanged
var handler = new HttpClientHandler { UseCookies = false }; var handler = new HttpClientHandler { UseCookies = false };
var http = new HttpClient(handler); var http = new HttpClient(handler);
http.DefaultRequestHeaders.Add("accept", "application/json"); http.DefaultRequestHeaders.Add("accept", "application/json");
http.DefaultRequestHeaders.Add("anthropic-client-platform", "web"); http.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36");
var cookieHeader = string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}")); var cookieHeader = string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}"));
http.DefaultRequestHeaders.Add("Cookie", cookieHeader); http.DefaultRequestHeaders.Add("Cookie", cookieHeader);
return http; return http;
@@ -211,17 +308,13 @@ public class UsageViewModel : INotifyPropertyChanged
catch { return null; } catch { return null; }
} }
// Returns (email, orgId). orgId null means auth failed. // Parse email and org ID out of bootstrap JSON (multiple fallback paths for org ID)
private static async Task<(string? Email, string? OrgId)> FetchBootstrapAsync(HttpClient http) private static (string? Email, string? OrgId) ParseBootstrap(string json)
{ {
try try
{ {
var resp = await http.GetAsync("https://claude.ai/api/bootstrap");
if (!resp.IsSuccessStatusCode) return (null, null);
var json = await resp.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(json); using var doc = JsonDocument.Parse(json);
var root = doc.RootElement; var root = doc.RootElement;
string? email = null; string? email = null;
string? orgId = null; string? orgId = null;
@@ -230,7 +323,7 @@ public class UsageViewModel : INotifyPropertyChanged
acct.TryGetProperty("email_address", out var em)) acct.TryGetProperty("email_address", out var em))
email = em.GetString(); email = em.GetString();
// Try memberships[0].organization.uuid // Path 1: memberships[0].organization.uuid
if (root.TryGetProperty("memberships", out var mems) && mems.GetArrayLength() > 0) if (root.TryGetProperty("memberships", out var mems) && mems.GetArrayLength() > 0)
{ {
var first = mems[0]; var first = mems[0];
@@ -239,13 +332,13 @@ public class UsageViewModel : INotifyPropertyChanged
orgId = uuid.GetString(); orgId = uuid.GetString();
} }
// Fall back to cached org ID // Path 2: organizations[0].uuid (flat list on root)
if (string.IsNullOrEmpty(orgId) && !string.IsNullOrEmpty(AppSettings.Default.OrgId)) if (string.IsNullOrEmpty(orgId) &&
orgId = AppSettings.Default.OrgId; root.TryGetProperty("organizations", out var orgs) && orgs.GetArrayLength() > 0)
{
// Last resort: dedicated organizations endpoint if (orgs[0].TryGetProperty("uuid", out var uuid))
if (string.IsNullOrEmpty(orgId)) orgId = uuid.GetString();
orgId = await FetchOrgIdFromListAsync(http); }
return (email, orgId); return (email, orgId);
} }
@@ -272,7 +365,7 @@ public class UsageViewModel : INotifyPropertyChanged
catch { return null; } catch { return null; }
} }
private List<AgentLimit> BuildLimits(UsageResponse? usage) private static List<AgentLimit> BuildLimits(UsageResponse? usage)
{ {
if (usage == null) return []; if (usage == null) return [];
var now = DateTime.Now; var now = DateTime.Now;
+59
View File
@@ -0,0 +1,59 @@
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
namespace ClaudeCheckerWindows;
// Invisible 1×1 window that hosts a WebView2 for authenticated API calls.
// Uses the same user data folder as LoginWindow so the session is shared.
internal sealed class WebViewFetchWindow : Window
{
private readonly WebView2 _wv = new();
public WebViewFetchWindow()
{
Width = 1;
Height = 1;
Left = -9999;
Top = -9999;
ShowInTaskbar = false;
WindowStyle = WindowStyle.None;
AllowsTransparency = true;
Opacity = 0;
Content = _wv;
}
public async Task<string?> FetchAsync(string navigateUrl, string script, int timeoutMs = 20000)
{
var env = await CoreWebView2Environment.CreateAsync(userDataFolder:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"ClaudeChecker", "WebView2"));
await _wv.EnsureCoreWebView2Async(env);
var tcs = new TaskCompletionSource<string?>();
EventHandler<CoreWebView2NavigationCompletedEventArgs>? handler = null;
handler = async (_, e) =>
{
_wv.CoreWebView2.NavigationCompleted -= handler;
if (!e.IsSuccess) { tcs.TrySetResult(null); return; }
try
{
var result = await _wv.CoreWebView2.ExecuteScriptAsync(script);
tcs.TrySetResult(result);
}
catch { tcs.TrySetResult(null); }
};
_wv.CoreWebView2.NavigationCompleted += handler;
_wv.CoreWebView2.Navigate(navigateUrl);
_ = Task.Delay(timeoutMs).ContinueWith(_ => tcs.TrySetResult(null));
return await tcs.Task;
}
}