Compare commits

..
Author SHA1 Message Date
SuperDooper bcd208684b chore: release notes for beta.29 2026-05-08 16:29:03 +02:00
SuperDooper 2bdbe4943d fix: same org ID path fix in ParseBootstrap and WebView2 refresh script 2026-05-08 16:28:48 +02:00
SuperDooper 1c365a55a8 fix: org ID is at b.account.memberships[0].organization.uuid, not b.memberships 2026-05-08 16:28:47 +02:00
SuperDooper 8b367ee539 chore: release notes for beta.28 2026-05-08 16:24:42 +02:00
SuperDooper 9134b8945d fix: don't wipe existing limits when refresh returns no data 2026-05-08 16:24:31 +02:00
SuperDooper 19b1751e78 debug: wire DebugBanner in InitSettings 2026-05-08 16:24:30 +02:00
SuperDooper a20956cde2 debug: show debug banner on main panel so it's always visible 2026-05-08 16:24:29 +02:00
SuperDooper 659171bf0a debug: capture raw bootstrap JSON in debug field, try account.uuid as org ID fallback 2026-05-08 16:24:28 +02:00
SuperDooper f5b3accc13 chore: release notes for beta.27 2026-05-08 16:15:17 +02:00
SuperDooper 22e9096f7c fix: post plain objects in WebView2 refresh script 2026-05-08 16:15:07 +02:00
SuperDooper 6aee17fad2 fix: use WebMessageAsJson 2026-05-08 16:15:05 +02:00
SuperDooper b594889239 fix: use WebMessageAsJson and post plain objects (not JSON strings) 2026-05-08 16:15:04 +02:00
SuperDooper 0300e4a72e chore: release notes for beta.26 2026-05-08 16:12:06 +02:00
SuperDooper 7febb0384f fix: update WebView2 refresh script to use postMessage 2026-05-08 16:11:55 +02:00
SuperDooper 55e1f754c5 fix: switch WebViewFetchWindow to WebMessageReceived for script results 2026-05-08 16:11:54 +02:00
SuperDooper 03676a980f fix: use WebMessageReceived instead of ExecuteScriptAsync return value for async script results 2026-05-08 16:11:53 +02:00
SuperDooper a74d0cece5 chore: release notes for beta.25 2026-05-08 16:06:16 +02:00
SuperDooper b5cd7b1bc9 debug: show DebugInfo in settings panel after login 2026-05-08 16:06:06 +02:00
SuperDooper 3249dbd4aa debug: add DebugText block in settings panel 2026-05-08 16:06:05 +02:00
SuperDooper 189c513677 debug: capture bootstrap keys and save to DebugInfo 2026-05-08 16:06:04 +02:00
SuperDooper 05e66b22d1 feat: add DebugInfo field to AppSettings 2026-05-08 16:06:03 +02:00
SuperDooper 48e6f64c9a chore: release notes for beta.24 2026-05-08 16:00:28 +02:00
SuperDooper d55a92623c fix: add LoadFromCacheAsync, same JS fallbacks in WebView2 refresh path 2026-05-08 16:00:04 +02:00
SuperDooper c70a090983 fix: load from cache immediately after login, background refresh after 3s 2026-05-08 16:00:01 +02:00
SuperDooper cc0270326e fix: add /api/organizations + personal /api/usage fallbacks in login JS 2026-05-08 16:00:00 +02:00
SuperDooper 7601452f93 chore: release notes for beta.23 2026-05-08 15:50:04 +02:00
SuperDooper 5a78a021cb fix: trust cookies/cached auth for IsSignedIn, wider cookie domain filter 2026-05-08 15:49:47 +02:00
SuperDooper 7d465c13d8 fix: show update label in About, delay before refresh after login 2026-05-08 15:49:47 +02:00
SuperDooper ca67039e3e feat: add update-available label in About section 2026-05-08 15:49:46 +02:00
SuperDooper 1e4cdc09b3 fix: broaden JS orgId/email paths, URL-only auto-close 2026-05-08 15:49:45 +02:00
SuperDooper 4e154bcaa7 chore: release notes for beta.22 2026-05-08 15:30:34 +02:00
SuperDooper ea784384c1 fix: remove unused _dialogOpen field 2026-05-08 15:30:27 +02:00
SuperDooper 4e813995c9 fix: Unwrap Task<Task<string>> from Dispatcher.InvokeAsync with async lambda 2026-05-08 15:30:26 +02:00
7 changed files with 235 additions and 79 deletions
+1
View File
@@ -14,6 +14,7 @@ public class AppSettings
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;
public string DebugInfo { get; set; } = "";
private static readonly string FilePath = Path.Combine( private static readonly string FilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
+59 -14
View File
@@ -47,8 +47,7 @@ public partial class LoginWindow : Window
: "Complete sign-in, then click Done."; : "Complete sign-in, then click Done.";
}); });
// Auto-close as soon as we detect sign-in on any claude.ai page if (!uri.Contains("/login") && !uri.Contains("/signin") && signedIn)
if (signedIn && !uri.Contains("/login") && !uri.Contains("/signin"))
await SaveAndClose(cookies); await SaveAndClose(cookies);
}; };
} }
@@ -67,20 +66,50 @@ public partial class LoginWindow : Window
UsageViewModel.SaveCookies(cookies); UsageViewModel.SaveCookies(cookies);
// Fetch bootstrap + usage from within WebView2 (already authenticated, no header issues)
try try
{ {
const string script = @"(async()=>{try{ // Use WebMessageReceived so the async script can post back without relying
const b=await(await fetch('/api/bootstrap',{headers:{accept:'application/json'}})).json(); // on Promise-awaiting support in the WebView2 runtime version.
const id=b?.memberships?.[0]?.organization?.uuid||b?.organizations?.[0]?.uuid||null; var tcs = new TaskCompletionSource<string?>(TaskCreationOptions.RunContinuationsAsynchronously);
const e=b?.account?.email_address||null; EventHandler<CoreWebView2WebMessageReceivedEventArgs>? msgHandler = null;
if(!id)return{email:e,orgId:null,usage:null}; msgHandler = (_, args) =>
const u=await(await fetch('/api/organizations/'+id+'/usage',{headers:{accept:'application/json'}})).json(); {
return{email:e,orgId:id,usage:u}; Browser.CoreWebView2.WebMessageReceived -= msgHandler;
}catch(ex){return{error:String(ex)};}})()"; tcs.TrySetResult(args.WebMessageAsJson);
};
Browser.CoreWebView2.WebMessageReceived += msgHandler;
var json = await Browser.CoreWebView2.ExecuteScriptAsync(script); const string script = @"(async()=>{try{
if (json != "null" && !string.IsNullOrEmpty(json)) const h={headers:{accept:'application/json'}};
const b=await(await fetch('/api/bootstrap',h)).json();
const rawB=JSON.stringify(b).slice(0,600);
let id=b?.account?.memberships?.[0]?.organization?.uuid
||b?.memberships?.[0]?.organization?.uuid||b?.organizations?.[0]?.uuid
||b?.default_organization?.uuid||null;
const e=b?.account?.email_address||b?.account?.email||b?.email||null;
let orgSrc='bootstrap';
if(!id){
try{const ol=await(await fetch('/api/organizations',h)).json();
if(Array.isArray(ol)&&ol.length>0){id=ol[0]?.uuid||null;orgSrc='orgs-list';}}catch(e2){}
}
if(!id){
let pu=null;
try{pu=await(await fetch('/api/usage',h)).json();}catch(e3){}
window.chrome.webview.postMessage({email:e,orgId:null,usage:(pu&&!pu.error?pu:null),debug:'no-org|raw:'+rawB});
return;
}
const u=await(await fetch('/api/organizations/'+id+'/usage',h)).json();
const rawU=JSON.stringify(u).slice(0,300);
window.chrome.webview.postMessage({email:e,orgId:id,usage:u,debug:'src:'+orgSrc+'|ukeys:'+Object.keys(u||{}).join(',')+'|raw:'+rawB});
}catch(ex){window.chrome.webview.postMessage({error:String(ex)});}})()";
await Browser.CoreWebView2.ExecuteScriptAsync(script);
// Wait up to 15 s for the script to post its message
var completed = await Task.WhenAny(tcs.Task, Task.Delay(15000));
var json = completed == tcs.Task ? tcs.Task.Result : null;
if (!string.IsNullOrEmpty(json))
{ {
using var doc = JsonDocument.Parse(json); using var doc = JsonDocument.Parse(json);
var root = doc.RootElement; var root = doc.RootElement;
@@ -94,10 +123,26 @@ public partial class LoginWindow : Window
if (root.TryGetProperty("usage", out var us) && us.ValueKind == JsonValueKind.Object) if (root.TryGetProperty("usage", out var us) && us.ValueKind == JsonValueKind.Object)
AppSettings.Default.UsageJson = us.GetRawText(); AppSettings.Default.UsageJson = us.GetRawText();
if (root.TryGetProperty("debug", out var dbg) && dbg.ValueKind == JsonValueKind.String)
AppSettings.Default.DebugInfo = dbg.GetString() ?? "";
else if (root.TryGetProperty("error", out var err))
AppSettings.Default.DebugInfo = "JS error: " + err.GetRawText();
else
AppSettings.Default.DebugInfo = "timeout or empty message";
AppSettings.Default.Save();
}
else
{
AppSettings.Default.DebugInfo = json == null ? "script timeout (15s)" : "empty message";
AppSettings.Default.Save(); AppSettings.Default.Save();
} }
} }
catch { } catch (Exception ex)
{
AppSettings.Default.DebugInfo = "exception: " + ex.Message;
AppSettings.Default.Save();
}
await Dispatcher.InvokeAsync(() => DialogResult = true); await Dispatcher.InvokeAsync(() => DialogResult = true);
} }
+23 -4
View File
@@ -66,7 +66,16 @@
<!-- Cards scroll area --> <!-- Cards scroll area -->
<ScrollViewer VerticalScrollBarVisibility="Auto"> <ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel x:Name="CardsPanel" Margin="0,4,0,4"/> <StackPanel Margin="0,4,0,4">
<Border x:Name="DebugBanner" Visibility="Collapsed"
Background="{DynamicResource CardBrush}"
BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1"
CornerRadius="6" Margin="12,4,12,4" Padding="12,8">
<TextBlock x:Name="DebugBannerText" FontSize="10" FontFamily="Consolas"
Foreground="{DynamicResource SecondaryBrush}" TextWrapping="Wrap"/>
</Border>
<StackPanel x:Name="CardsPanel"/>
</StackPanel>
</ScrollViewer> </ScrollViewer>
</DockPanel> </DockPanel>
@@ -173,12 +182,22 @@
<TextBlock Text="Built by superdooper86 &amp; claude" <TextBlock Text="Built by superdooper86 &amp; claude"
FontSize="11" Foreground="{DynamicResource SecondaryBrush}"/> FontSize="11" Foreground="{DynamicResource SecondaryBrush}"/>
</StackPanel> </StackPanel>
<Button Grid.Column="2" x:Name="CheckUpdateButton" <StackPanel Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Right">
Style="{StaticResource SmallButton}" <Button x:Name="CheckUpdateButton"
Click="CheckUpdate_Click" VerticalAlignment="Center"/> Style="{StaticResource SmallButton}"
Click="CheckUpdate_Click"/>
<TextBlock x:Name="UpdateAvailableText" FontSize="10"
Foreground="{DynamicResource BlueBrush}"
HorizontalAlignment="Center"
Visibility="Collapsed" Margin="0,4,0,0"/>
</StackPanel>
</Grid> </Grid>
</Border> </Border>
<TextBlock x:Name="DebugText" FontSize="10" Foreground="{DynamicResource SecondaryBrush}"
TextWrapping="Wrap" Margin="0,12,0,0" FontFamily="Consolas"
Visibility="Collapsed"/>
</StackPanel> </StackPanel>
</ScrollViewer> </ScrollViewer>
</DockPanel> </DockPanel>
+45 -5
View File
@@ -14,7 +14,7 @@ public partial class PopupWindow : Window
private static readonly UsageViewModel VM = App.ViewModel; private static readonly UsageViewModel VM = App.ViewModel;
private static readonly UpdateManager Updater = App.Updater; private static readonly UpdateManager Updater = App.Updater;
private readonly DispatcherTimer _clockTimer; private readonly DispatcherTimer _clockTimer;
private bool _dialogOpen;
[DllImport("dwmapi.dll")] [DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int value, int size); private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int value, int size);
@@ -199,7 +199,10 @@ public partial class PopupWindow : Window
private void OnUpdaterChanged(string? prop) private void OnUpdaterChanged(string? prop)
{ {
if (prop is nameof(UpdateManager.UpdateAvailable) or nameof(UpdateManager.LatestVersion)) if (prop is nameof(UpdateManager.UpdateAvailable) or nameof(UpdateManager.LatestVersion))
{
UpdateBannerState(); UpdateBannerState();
UpdateAboutSection();
}
if (prop is nameof(UpdateManager.DownloadProgress)) if (prop is nameof(UpdateManager.DownloadProgress))
UpdateProgress.Value = Updater.DownloadProgress * 100; UpdateProgress.Value = Updater.DownloadProgress * 100;
if (prop is nameof(UpdateManager.StatusMessage)) if (prop is nameof(UpdateManager.StatusMessage))
@@ -208,6 +211,21 @@ public partial class PopupWindow : Window
InstallButton.Visibility = Visibility.Collapsed; InstallButton.Visibility = Visibility.Collapsed;
} }
private void UpdateAboutSection()
{
if (Updater.UpdateAvailable)
{
UpdateAvailableText.Text = $"v{Updater.LatestVersion} available";
UpdateAvailableText.Visibility = Visibility.Visible;
CheckUpdateButton.Content = "Install";
}
else
{
UpdateAvailableText.Visibility = Visibility.Collapsed;
CheckUpdateButton.Content = "Check";
}
}
private void UpdateBannerState() private void UpdateBannerState()
{ {
var visible = Updater.UpdateAvailable; var visible = Updater.UpdateAvailable;
@@ -236,7 +254,7 @@ public partial class PopupWindow : Window
{ {
VersionLabel.Text = $"v{Updater.CurrentVersion}"; VersionLabel.Text = $"v{Updater.CurrentVersion}";
BetaToggle.IsChecked = Updater.BetaChannel; BetaToggle.IsChecked = Updater.BetaChannel;
CheckUpdateButton.Content = Updater.UpdateAvailable ? "Install" : "Check"; UpdateAboutSection();
var intervals = new[] { ("1 min", 60), ("2 min", 120), ("3 min", 180), var intervals = new[] { ("1 min", 60), ("2 min", 120), ("3 min", 180),
("4 min", 240), ("5 min", 300), ("10 min", 600) }; ("4 min", 240), ("5 min", 300), ("10 min", 600) };
@@ -265,6 +283,20 @@ public partial class PopupWindow : Window
SignOutButton.Visibility = VM.IsSignedIn ? Visibility.Visible : Visibility.Collapsed; SignOutButton.Visibility = VM.IsSignedIn ? Visibility.Visible : Visibility.Collapsed;
SignInButton.Content = VM.IsSignedIn ? "Re-authenticate" : "Sign In"; SignInButton.Content = VM.IsSignedIn ? "Re-authenticate" : "Sign In";
var dbg = AppSettings.Default.DebugInfo;
if (!string.IsNullOrEmpty(dbg))
{
DebugText.Text = dbg;
DebugText.Visibility = Visibility.Visible;
DebugBannerText.Text = dbg;
DebugBanner.Visibility = Visibility.Visible;
}
else
{
DebugText.Visibility = Visibility.Collapsed;
DebugBanner.Visibility = Visibility.Collapsed;
}
} }
// ── Event handlers ─────────────────────────────────────────────── // ── Event handlers ───────────────────────────────────────────────
@@ -312,14 +344,22 @@ public partial class PopupWindow : Window
private async void SignIn_Click(object s, RoutedEventArgs e) private async void SignIn_Click(object s, RoutedEventArgs e)
{ {
_dialogOpen = true;
var login = new LoginWindow { Owner = this }; var login = new LoginWindow { Owner = this };
if (login.ShowDialog() == true) if (login.ShowDialog() == true)
{ {
await VM.RefreshAsync(); // Show cached data from SaveAndClose immediately (no WebView2 needed)
await VM.LoadFromCacheAsync();
InitSettings(); InitSettings();
ShowMain();
// Full refresh in background after WebView2 folder is definitely released
_ = Task.Run(async () =>
{
await Task.Delay(3000);
await VM.RefreshAsync();
await Application.Current.Dispatcher.InvokeAsync(InitSettings);
});
} }
_dialogOpen = false;
Show(); Show();
Activate(); Activate();
} }
+3 -5
View File
@@ -1,6 +1,4 @@
## What's new in beta.21 ## What's new in beta.29
- Fixed: clicking Sign In now auto-closes as soon as you are detected as signed in (no need to click Done) - Fix: org ID is now correctly read from b.account.memberships[0].organization.uuid — bootstrap nests memberships inside account, not at the root
- Fixed: login now fetches and caches your data directly via the browser session (no more authentication failures) - This was preventing usage limits from loading for all accounts
- Fixed: periodic refresh falls back to browser-session API calls when HttpClient is rejected
- Fixed: cached usage from login is shown immediately while refreshing
+83 -39
View File
@@ -78,7 +78,13 @@ public class UsageViewModel : INotifyPropertyChanged
try try
{ {
var cookies = await GetCookiesAsync(); var cookies = await GetCookiesAsync();
if (cookies.Count == 0)
// Check if we have any persistent proof that the user authenticated
bool hasCookies = cookies.Count > 0;
bool hasCachedAuth = !string.IsNullOrEmpty(AppSettings.Default.Email) ||
!string.IsNullOrEmpty(AppSettings.Default.OrgId);
if (!hasCookies && !hasCachedAuth)
{ {
await Application.Current.Dispatcher.InvokeAsync(() => await Application.Current.Dispatcher.InvokeAsync(() =>
{ {
@@ -89,20 +95,18 @@ public class UsageViewModel : INotifyPropertyChanged
return; return;
} }
// Try HttpClient first (fast path) // Try HttpClient first (fast path) — may be rejected by server CORS/header checks
var (limits, overage, prepaid, email, orgId, ok) = await TryHttpRefreshAsync(cookies); var (limits, overage, prepaid, email, orgId, ok) = hasCookies
? await TryHttpRefreshAsync(cookies)
: ([], null, null, null, null, false);
// If HttpClient failed, fall back to WebView2 (uses existing browser session) // Fall back to WebView2 (uses the shared browser session, not HttpClient)
if (!ok) if (!ok)
(limits, email, orgId) = await TryWebView2RefreshAsync(); (limits, email, orgId) = await TryWebView2RefreshAsync();
// Still no org ID? Use cached values from last successful login // Fill in any blanks from cached values saved at login time
if (string.IsNullOrEmpty(orgId) && !string.IsNullOrEmpty(AppSettings.Default.OrgId)) if (string.IsNullOrEmpty(email)) email = AppSettings.Default.Email;
orgId = AppSettings.Default.OrgId; if (string.IsNullOrEmpty(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)) if (limits.Count == 0 && !string.IsNullOrEmpty(AppSettings.Default.UsageJson))
{ {
try try
@@ -114,19 +118,6 @@ public class UsageViewModel : INotifyPropertyChanged
catch { } 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(() =>
{
IsSignedIn = false;
ErrorMessage = "Session expired — click Sign In to re-authenticate.";
IsLoading = false;
});
return;
}
foreach (var limit in limits) foreach (var limit in limits)
{ {
var key = limit.Window.ToString(); var key = limit.Window.ToString();
@@ -140,9 +131,7 @@ public class UsageViewModel : INotifyPropertyChanged
await Application.Current.Dispatcher.InvokeAsync(() => await Application.Current.Dispatcher.InvokeAsync(() =>
{ {
Limits = limits; if (limits.Count > 0) { Limits = limits; Overage = overage; Prepaid = prepaid; }
Overage = overage;
Prepaid = prepaid;
if (!string.IsNullOrEmpty(email)) UserEmail = email; if (!string.IsNullOrEmpty(email)) UserEmail = email;
IsSignedIn = true; IsSignedIn = true;
ErrorMessage = null; ErrorMessage = null;
@@ -198,13 +187,25 @@ public class UsageViewModel : INotifyPropertyChanged
try try
{ {
const string script = @"(async()=>{try{ const string script = @"(async()=>{try{
const b=await(await fetch('/api/bootstrap',{headers:{accept:'application/json'}})).json(); const h={headers:{accept:'application/json'}};
const id=b?.memberships?.[0]?.organization?.uuid||b?.organizations?.[0]?.uuid||null; const b=await(await fetch('/api/bootstrap',h)).json();
const em=b?.account?.email_address||null; let id=b?.account?.memberships?.[0]?.organization?.uuid
if(!id)return{email:em,orgId:null,usage:null}; ||b?.memberships?.[0]?.organization?.uuid||b?.organizations?.[0]?.uuid
const u=await(await fetch('/api/organizations/'+id+'/usage',{headers:{accept:'application/json'}})).json(); ||b?.default_organization?.uuid||null;
return{email:em,orgId:id,usage:u}; const em=b?.account?.email_address||b?.account?.email||b?.email||null;
}catch(ex){return null;}})()"; if(!id){
try{const ol=await(await fetch('/api/organizations',h)).json();
if(Array.isArray(ol)&&ol.length>0)id=ol[0]?.uuid||null;}catch(e2){}
}
if(!id){
let pu=null;
try{pu=await(await fetch('/api/usage',h)).json();}catch(e3){}
window.chrome.webview.postMessage({email:em,orgId:null,usage:(pu&&!pu.error?pu:null)});
return;
}
const u=await(await fetch('/api/organizations/'+id+'/usage',h)).json();
window.chrome.webview.postMessage({email:em,orgId:id,usage:u});
}catch(ex){window.chrome.webview.postMessage(null);}})();";
var resultJson = await Application.Current.Dispatcher.InvokeAsync(async () => var resultJson = await Application.Current.Dispatcher.InvokeAsync(async () =>
{ {
@@ -212,7 +213,7 @@ public class UsageViewModel : INotifyPropertyChanged
host.Show(); host.Show();
try { return await host.FetchAsync("https://claude.ai", script); } try { return await host.FetchAsync("https://claude.ai", script); }
finally { host.Close(); } finally { host.Close(); }
}).Task; }).Task.Unwrap();
if (resultJson == null || resultJson == "null") return ([], null, null); if (resultJson == null || resultJson == "null") return ([], null, null);
@@ -243,6 +244,38 @@ public class UsageViewModel : INotifyPropertyChanged
catch { return ([], null, null); } catch { return ([], null, null); }
} }
public async Task LoadFromCacheAsync()
{
var email = AppSettings.Default.Email;
var orgId = AppSettings.Default.OrgId;
var cookie = AppSettings.Default.CookieStore;
bool isAuth = !string.IsNullOrEmpty(email) || !string.IsNullOrEmpty(orgId)
|| !string.IsNullOrEmpty(cookie);
if (!isAuth) return;
List<AgentLimit> limits = [];
if (!string.IsNullOrEmpty(AppSettings.Default.UsageJson))
{
try
{
var cached = JsonSerializer.Deserialize<UsageResponse>(
AppSettings.Default.UsageJson, JsonOpts);
limits = BuildLimits(cached);
}
catch { }
}
await Application.Current.Dispatcher.InvokeAsync(() =>
{
if (!string.IsNullOrEmpty(email)) UserEmail = email;
if (limits.Count > 0) Limits = limits;
IsSignedIn = true;
ErrorMessage = limits.Count == 0 ? "Signed in — refreshing data…" : null;
LastUpdated = limits.Count > 0 ? DateTime.Now : LastUpdated;
});
}
public async Task SignOutAsync() public async Task SignOutAsync()
{ {
AppSettings.Default.CookieStore = ""; AppSettings.Default.CookieStore = "";
@@ -276,7 +309,7 @@ public class UsageViewModel : INotifyPropertyChanged
public static void SaveCookies(IEnumerable<CoreWebView2Cookie> cookies) public static void SaveCookies(IEnumerable<CoreWebView2Cookie> cookies)
{ {
var entries = cookies var entries = cookies
.Where(c => c.Domain.Contains("claude.ai")) .Where(c => c.Domain.Contains("claude.ai") || c.Domain.Contains("anthropic.com"))
.Select(c => new CookieEntry { Name = c.Name, Value = c.Value, Domain = c.Domain, Path = c.Path }) .Select(c => new CookieEntry { Name = c.Name, Value = c.Value, Domain = c.Domain, Path = c.Path })
.ToList(); .ToList();
AppSettings.Default.CookieStore = JsonSerializer.Serialize(entries); AppSettings.Default.CookieStore = JsonSerializer.Serialize(entries);
@@ -323,8 +356,9 @@ public class UsageViewModel : INotifyPropertyChanged
acct.TryGetProperty("email_address", out var em)) acct.TryGetProperty("email_address", out var em))
email = em.GetString(); email = em.GetString();
// Path 1: memberships[0].organization.uuid // Path 1: account.memberships[0].organization.uuid (Claude.ai personal/pro accounts)
if (root.TryGetProperty("memberships", out var mems) && mems.GetArrayLength() > 0) if (root.TryGetProperty("account", out var acctNode) &&
acctNode.TryGetProperty("memberships", out var mems) && mems.GetArrayLength() > 0)
{ {
var first = mems[0]; var first = mems[0];
if (first.TryGetProperty("organization", out var org) && if (first.TryGetProperty("organization", out var org) &&
@@ -332,7 +366,17 @@ public class UsageViewModel : INotifyPropertyChanged
orgId = uuid.GetString(); orgId = uuid.GetString();
} }
// Path 2: organizations[0].uuid (flat list on root) // Path 2: memberships[0].organization.uuid (root-level, older API shape)
if (string.IsNullOrEmpty(orgId) &&
root.TryGetProperty("memberships", out var rootMems) && rootMems.GetArrayLength() > 0)
{
var first = rootMems[0];
if (first.TryGetProperty("organization", out var org) &&
org.TryGetProperty("uuid", out var uuid))
orgId = uuid.GetString();
}
// Path 3: organizations[0].uuid (flat list on root)
if (string.IsNullOrEmpty(orgId) && if (string.IsNullOrEmpty(orgId) &&
root.TryGetProperty("organizations", out var orgs) && orgs.GetArrayLength() > 0) root.TryGetProperty("organizations", out var orgs) && orgs.GetArrayLength() > 0)
{ {
+21 -12
View File
@@ -34,25 +34,34 @@ internal sealed class WebViewFetchWindow : Window
await _wv.EnsureCoreWebView2Async(env); await _wv.EnsureCoreWebView2Async(env);
var tcs = new TaskCompletionSource<string?>(); var tcs = new TaskCompletionSource<string?>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<CoreWebView2NavigationCompletedEventArgs>? handler = null; // Use WebMessageReceived so the script can post back asynchronously without
handler = async (_, e) => // relying on Promise-awaiting support in the WebView2 runtime version.
EventHandler<CoreWebView2WebMessageReceivedEventArgs>? msgHandler = null;
msgHandler = (_, args) =>
{ {
_wv.CoreWebView2.NavigationCompleted -= handler; _wv.CoreWebView2.WebMessageReceived -= msgHandler;
tcs.TrySetResult(args.WebMessageAsJson);
};
_wv.CoreWebView2.WebMessageReceived += msgHandler;
EventHandler<CoreWebView2NavigationCompletedEventArgs>? navHandler = null;
navHandler = async (_, e) =>
{
_wv.CoreWebView2.NavigationCompleted -= navHandler;
if (!e.IsSuccess) { tcs.TrySetResult(null); return; } if (!e.IsSuccess) { tcs.TrySetResult(null); return; }
try try { await _wv.CoreWebView2.ExecuteScriptAsync(script); }
{
var result = await _wv.CoreWebView2.ExecuteScriptAsync(script);
tcs.TrySetResult(result);
}
catch { tcs.TrySetResult(null); } catch { tcs.TrySetResult(null); }
}; };
_wv.CoreWebView2.NavigationCompleted += navHandler;
_wv.CoreWebView2.NavigationCompleted += handler;
_wv.CoreWebView2.Navigate(navigateUrl); _wv.CoreWebView2.Navigate(navigateUrl);
_ = Task.Delay(timeoutMs).ContinueWith(_ => tcs.TrySetResult(null)); _ = Task.Delay(timeoutMs).ContinueWith(_ =>
{
_wv.CoreWebView2.WebMessageReceived -= msgHandler;
tcs.TrySetResult(null);
});
return await tcs.Task; return await tcs.Task;
} }