Compare commits

..
7 changed files with 157 additions and 43 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),
+57 -14
View File
@@ -47,7 +47,6 @@ public partial class LoginWindow : Window
: "Complete sign-in, then click Done."; : "Complete sign-in, then click Done.";
}); });
// Auto-close once we land on any claude.ai page that isn't the login flow
if (!uri.Contains("/login") && !uri.Contains("/signin") && signedIn) if (!uri.Contains("/login") && !uri.Contains("/signin") && signedIn)
await SaveAndClose(cookies); await SaveAndClose(cookies);
}; };
@@ -67,21 +66,49 @@ 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 var tcs = new TaskCompletionSource<string?>(TaskCreationOptions.RunContinuationsAsynchronously);
||b?.default_organization?.uuid||null; EventHandler<CoreWebView2WebMessageReceivedEventArgs>? msgHandler = null;
const e=b?.account?.email_address||b?.account?.email||b?.email||null; msgHandler = (_, args) =>
if(!id)return{email:e,orgId:null,usage:null}; {
const u=await(await fetch('/api/organizations/'+id+'/usage',{headers:{accept:'application/json'}})).json(); Browser.CoreWebView2.WebMessageReceived -= msgHandler;
return{email:e,orgId:id,usage:u}; tcs.TrySetResult(args.WebMessageAsString);
}catch(ex){return{error:String(ex)};}})()"; };
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 bkeys=Object.keys(b||{}).join(',');
const akeys=Object.keys(b?.account||{}).join(',');
let id=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(JSON.stringify({email:e,orgId:null,usage:(pu&&!pu.error?pu:null),debug:'no-org|bkeys:'+bkeys+'|akeys:'+akeys}));
return;
}
const u=await(await fetch('/api/organizations/'+id+'/usage',h)).json();
window.chrome.webview.postMessage(JSON.stringify({email:e,orgId:id,usage:u,debug:'orgSrc:'+orgSrc+'|bkeys:'+bkeys+'|akeys:'+akeys}));
}catch(ex){window.chrome.webview.postMessage(JSON.stringify({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;
@@ -95,10 +122,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);
} }
+4
View File
@@ -185,6 +185,10 @@
</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>
+22 -4
View File
@@ -283,6 +283,17 @@ 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;
}
else
{
DebugText.Visibility = Visibility.Collapsed;
}
} }
// ── Event handlers ─────────────────────────────────────────────── // ── Event handlers ───────────────────────────────────────────────
@@ -333,11 +344,18 @@ public partial class PopupWindow : Window
var login = new LoginWindow { Owner = this }; var login = new LoginWindow { Owner = this };
if (login.ShowDialog() == true) if (login.ShowDialog() == true)
{ {
// Brief pause so the LoginWindow WebView2 fully releases its user data folder lock // Show cached data from SaveAndClose immediately (no WebView2 needed)
// before RefreshAsync may create another WebView2 on the same folder. await VM.LoadFromCacheAsync();
await Task.Delay(1500);
await VM.RefreshAsync();
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);
});
} }
Show(); Show();
Activate(); Activate();
+3 -6
View File
@@ -1,7 +1,4 @@
## What's new in beta.23 ## What's new in beta.26
- About section now shows "vX.X.X available" label when an update is available (not just button label change) - Fixed: script results now use window.chrome.webview.postMessage instead of async IIFE return value — older WebView2 runtimes don't await Promises from ExecuteScriptAsync, so data was never received
- Sign-in: fixed app showing signed out after login window closes — cookies and cached auth now correctly set IsSignedIn=true - Debug text in Settings will now always show what happened during sign-in
- Sign-in: added brief delay before refresh so WebView2 user data folder is fully released by LoginWindow before reuse
- Wider cookie domain filter (anthropic.com included alongside claude.ai)
- Broader JS paths for email and org ID in bootstrap response
+49 -7
View File
@@ -191,14 +191,24 @@ 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 const b=await(await fetch('/api/bootstrap',h)).json();
||b?.default_organization?.uuid||null; let id=b?.memberships?.[0]?.organization?.uuid||b?.organizations?.[0]?.uuid
||b?.default_organization?.uuid||null;
const em=b?.account?.email_address||b?.account?.email||b?.email||null; const em=b?.account?.email_address||b?.account?.email||b?.email||null;
if(!id)return{email:em,orgId:null,usage:null}; if(!id){
const u=await(await fetch('/api/organizations/'+id+'/usage',{headers:{accept:'application/json'}})).json(); try{const ol=await(await fetch('/api/organizations',h)).json();
return{email:em,orgId:id,usage:u}; if(Array.isArray(ol)&&ol.length>0)id=ol[0]?.uuid||null;}catch(e2){}
}catch(ex){return null;}})()"; }
if(!id){
let pu=null;
try{pu=await(await fetch('/api/usage',h)).json();}catch(e3){}
window.chrome.webview.postMessage(JSON.stringify({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(JSON.stringify({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 () =>
{ {
@@ -237,6 +247,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 = "";
+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.WebMessageAsString);
};
_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;
} }