Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Show provider account emails in subscription details (#1404)

Dee7476ac030300
diff --git a/cli/src/lib/accountUsage.spec.ts b/cli/src/lib/accountUsage.spec.ts
index 3138313a8..67c6a9e8d 100644
--- a/cli/src/lib/accountUsage.spec.ts
+++ b/cli/src/lib/accountUsage.spec.ts
@@ -74,7 +74,7 @@ describe('readAccountUsage', () => {
expect(calls).toHaveLength(0)
})
- it('asks Claude the way Claude Code does, and names the account without sending it', async () => {
+ it('asks Claude the way Claude Code does, with email display metadata and an opaque identity', async () => {
write('.claude/.credentials.json', { claudeAiOauth: { accessToken: CLAUDE_TOKEN } })
write('.claude.json', { oauthAccount: { accountUuid: 'uuid-1', emailAddress: '[email protected]' } })
const { calls, fetchImpl } = vendor(200, { seven_day: { utilization: 42 } })
@@ -84,6 +84,7 @@ describe('readAccountUsage', () => {
expect(claude).toEqual({
provider: 'claude',
account: accountKey('claude', 'uuid-1'),
+ email: '[email protected]',
outcome: 'answered',
httpStatus: 200,
body: { seven_day: { utilization: 42 } },
@@ -96,8 +97,8 @@ describe('readAccountUsage', () => {
})
})
- it('never puts a token, an id or an email in what goes back', async () => {
- // The reply crosses the relay and the desktop logs it. Only the hashed key may name the account.
+ it('returns display email without exposing tokens or raw account ids', async () => {
+ // The encrypted reply includes email for display; identity still uses the hashed key.
write('.claude/.credentials.json', { claudeAiOauth: { accessToken: CLAUDE_TOKEN } })
write('.claude.json', { oauthAccount: { accountUuid: 'uuid-1', emailAddress: '[email protected]' } })
write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN, account_id: 'codex-acct' } })
@@ -105,7 +106,8 @@ describe('readAccountUsage', () => {
const wire = JSON.stringify(await readAccountUsage(deps({ fetchImpl })))
- for (const secret of [CLAUDE_TOKEN, CODEX_TOKEN, 'uuid-1', '[email protected]', 'codex-acct']) {
+ expect(wire).toContain('[email protected]')
+ for (const secret of [CLAUDE_TOKEN, CODEX_TOKEN, 'uuid-1', 'codex-acct']) {
expect(wire).not.toContain(secret)
}
})
@@ -134,12 +136,15 @@ describe('readAccountUsage', () => {
})
it('scopes the Codex reading to its account', async () => {
- write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN, account_id: 'codex-acct' } })
+ const idToken = `e30.${Buffer.from(JSON.stringify({ email: '[email protected]' })).toString('base64url')}.signature`
+ write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN, account_id: 'codex-acct', id_token: idToken } })
const { calls, fetchImpl } = vendor()
const [, codex] = await readAccountUsage(deps({ fetchImpl }))
expect(codex).toMatchObject({ outcome: 'answered', account: accountKey('codex', 'codex-acct') })
+ expect(codex.email).toBe('[email protected]')
+ expect(JSON.stringify(codex)).not.toContain(idToken)
const call = calls.find((c) => c.url === CODEX_USAGE_URL)
expect(call?.headers).toEqual({
Authorization: `Bearer ${CODEX_TOKEN}`,
@@ -158,6 +163,15 @@ describe('readAccountUsage', () => {
expect(codex).toMatchObject({ outcome: 'answered', httpStatus: 401, account: null })
})
+ it.each([null, '', 42, 'not-a-jwt', 'a.%%%.b', 'a.bnVsbA.b', 'a.eyJlbWFpbCI6NDJ9.b'])(
+ 'keeps Codex usage readable with malformed ID-token metadata: %s', async (idToken) => {
+ write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN, account_id: 'codex-acct', id_token: idToken } })
+ const [, codex] = await readAccountUsage(deps({ fetchImpl: vendor().fetchImpl }))
+ expect(codex.outcome).toBe('answered')
+ expect(codex.email).toBeUndefined()
+ },
+ )
+
it('a vendor that cannot be reached is an outcome, not a throw', async () => {
write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN } })
const fetchImpl = (async () => {
diff --git a/cli/src/lib/accountUsage.ts b/cli/src/lib/accountUsage.ts
index 6421ef93c..704bea13e 100644
--- a/cli/src/lib/accountUsage.ts
+++ b/cli/src/lib/accountUsage.ts
@@ -8,8 +8,8 @@
* answer to `usage_read`.
*
* **The credential never leaves this machine.** The vendor is called from here, and what goes back
- * over the relay is the vendor's answer — its HTTP status and body — plus an opaque account key.
- * Never the token, never the account's email or id.
+ * over the encrypted relay is the vendor's answer, an opaque account key and an optional email
+ * for display. Never the token or raw account id. Clients redact email metadata from logs.
*
* **Deliberately a thin proxy, not a parser.** The body is returned as the vendor sent it, and the
* client interprets it with the SAME code that interprets its own local reading
@@ -48,6 +48,8 @@ export interface AccountUsageReading {
* as. The client compares these to show one figure per ACCOUNT rather than one per machine.
*/
account: string | null
+ /** Display label only; account identity and deduplication still use `account`. */
+ email?: string
outcome: UsageOutcome
httpStatus?: number
body?: unknown
@@ -65,8 +67,8 @@ const FETCH_TIMEOUT_MS = 8_000
* An account, as the wire names it: the first 16 hex characters of sha256(`<provider>:<id>`).
*
* Hashed rather than sent raw because the reply is LOGGED — the desktop writes every RPC answer to
- * `~/.harness/logs` — and an account id or email has no business there. Equality survives hashing,
- * which is all the client needs.
+ * `~/.harness/logs` — and a raw account id has no business there. Email display metadata is separate
+ * and redacted by clients; equality uses this stable key rather than a display label.
*
* ⚠️ **A cross-language contract.** The desktop computes the same key for its own account
* (`lib/usage/usage_account_key.dart`) and the two must agree byte for byte, or every remote reading
@@ -103,6 +105,7 @@ async function readClaude(deps: AccountUsageDeps): Promise<AccountUsageReading>
// records who it is signed in as, on every platform.
const profile = asRecord(asRecord(parseJson(await readText(join(home, '.claude.json'))))?.oauthAccount)
const accountId = stringField(profile?.accountUuid)
+ const email = emailField(profile?.emailAddress)
const account = accountId ? accountKey('claude', accountId) : null
if (!token) return { provider: 'claude', account, outcome: 'signedOut' }
@@ -121,7 +124,7 @@ async function readClaude(deps: AccountUsageDeps): Promise<AccountUsageReading>
Authorization: `Bearer ${token}`,
'anthropic-beta': 'oauth-2025-04-20',
'User-Agent': 'claude-code/2.1.0',
- }, deps)
+ }, deps, email)
}
async function readCodex(deps: AccountUsageDeps): Promise<AccountUsageReading> {
@@ -130,11 +133,12 @@ async function readCodex(deps: AccountUsageDeps): Promise<AccountUsageReading> {
const token = stringField(tokens?.access_token)
const accountId = stringField(tokens?.account_id)
const account = accountId ? accountKey('codex', accountId) : null
+ const email = tokenEmail(tokens?.id_token)
if (!token) return { provider: 'codex', account, outcome: 'signedOut' }
const headers: Record<string, string> = { Authorization: `Bearer ${token}` }
// The account the backend scopes the reading to — the same id the key above is made from.
if (accountId) headers['ChatGPT-Account-Id'] = accountId
- return ask('codex', account, CODEX_USAGE_URL, headers, deps)
+ return ask('codex', account, CODEX_USAGE_URL, headers, deps, email)
}
async function ask(
@@ -143,12 +147,13 @@ async function ask(
url: string,
headers: Record<string, string>,
deps: AccountUsageDeps,
+ email: string | null,
): Promise<AccountUsageReading> {
const fetchImpl = deps.fetchImpl ?? fetch
try {
const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
const text = await response.text()
- return { provider, account, outcome: 'answered', httpStatus: response.status, body: parseJson(text) }
+ return { provider, account, ...(email ? { email } : {}), outcome: 'answered', httpStatus: response.status, body: parseJson(text) }
} catch {
// No detail on purpose: a network error's message can carry the URL, and the client already
// knows which vendor it asked.
@@ -202,3 +207,15 @@ function asRecord(value: unknown): Record<string, unknown> | null {
function stringField(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 ? value : null
}
+
+function emailField(value: unknown): string | null {
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null
+}
+
+/** ID-token claims supply a display label only, never an authentication decision. */
+function tokenEmail(value: unknown): string | null {
+ if (typeof value !== 'string') return null
+ const parts = value.split('.')
+ if (parts.length !== 3) return null
+ return emailField(asRecord(parseJson(Buffer.from(parts[1]!, 'base64url').toString('utf8')))?.email)
+}
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 5fdac00ad..b64320703 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -542,6 +542,9 @@ add a kind there, not at the call site.
sha256(`<provider>:<id>`), `usageAccountKey` here and `accountKey` there, both suites pinning one
vector — decides whether a remote subscription is this one again (folded in, unlabelled) or
another (its own figure, labelled with the machine). Hashed because RPC replies are logged.
+ Subscription headings show the provider login's email when available; older readings without
+ an email show only the provider. Email is display metadata, redacted from structured logs.
+ Account grouping, search identity and model selection continue to use the full hashed key.
⚠️ A null key never matches, itself included, and a remote reading folds into this computer's
only when this computer HAS figures — otherwise a token that expired here would swallow a live
reading of the same account taken there. `readings` stays this computer's alone and `accounts`
diff --git a/desktop/design/review/subscription-email.png b/desktop/design/review/subscription-email.png
new file mode 100644
index 000000000..3eb829dc4
Binary files /dev/null and b/desktop/design/review/subscription-email.png differ
diff --git a/desktop/integration_test/subscription_email_native_test.dart b/desktop/integration_test/subscription_email_native_test.dart
new file mode 100644
index 000000000..f3a9aaf1a
--- /dev/null
+++ b/desktop/integration_test/subscription_email_native_test.dart
@@ -0,0 +1,15 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:integration_test/integration_test.dart';
+
+import '../test/desktop_search_polish_test.dart' as review;
+
+/// Run the shared picker journeys with synthetic subscriptions in a real window.
+/// Use --plain-name 'every search scope fits' for both themes and long email labels.
+void main() {
+ if (!kUnderTest)
+ throw StateError('Subscription fixtures require FLUTTER_TEST=1');
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized().framePolicy =
+ LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;
+ review.main();
+}
diff --git a/desktop/lib/logging/redact.dart b/desktop/lib/logging/redact.dart
index fdafab7cf..3d68c1432 100644
--- a/desktop/lib/logging/redact.dart
+++ b/desktop/lib/logging/redact.dart
@@ -16,7 +16,7 @@ library;
/// field that was not secret costs one unreadable line, missing one that was
/// costs a credential on disk.
final RegExp _secretKey = RegExp(
- r'key|token|secret|password|passphrase|credential|auth|bearer|cookie|session',
+ r'key|token|secret|password|passphrase|credential|auth|bearer|cookie|session|email',
caseSensitive: false,
);
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 6ccec089e..d7576cbb8 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -9,6 +9,7 @@ import '../models/api_connections_controller.dart'
show ApiConnection, ApiModel, agentOnApiModel;
import '../models/local_model.dart';
import '../models/model_search_catalog.dart';
+import '../usage/models_menu_controller.dart' show subscriptionSearchId;
import '../core/dsh_catalog.dart';
import '../store/experimental_harnesses.dart';
import '../core/machine_resources.dart';
@@ -600,7 +601,7 @@ class SwarmSearchController extends ChangeNotifier {
);
return available != null &&
available['status'] != 'Not signed in' &&
- available['account'] == subscription['account'];
+ subscriptionSearchId(available) == subscriptionSearchId(subscription);
}
return selectableGridModel(row) != null ||
selectableApiModel(row) != null ||
diff --git a/desktop/lib/usage/claude_usage_source.dart b/desktop/lib/usage/claude_usage_source.dart
index 4787f6ff6..c661c3057 100644
--- a/desktop/lib/usage/claude_usage_source.dart
+++ b/desktop/lib/usage/claude_usage_source.dart
@@ -33,6 +33,7 @@ class ClaudeUsageSource implements UsageSource {
final token = await _credentials.claude();
if (token == null) return signedOut(provider);
final accountId = await _credentials.claudeAccountId();
+ final email = await _credentials.claudeAccountEmail();
// An expired token is spent as a sign-in rather than as a round trip: this
// app does not refresh what the CLI owns, so the request could only fail.
if (token.isExpired) {
@@ -56,6 +57,7 @@ class ClaudeUsageSource implements UsageSource {
return claudeUsageFromAnswer(
statusCode: response.statusCode,
body: response.data,
+ email: email,
account: accountId == null
? null
: usageAccountKey(provider, accountId),
@@ -73,6 +75,7 @@ class ClaudeUsageSource implements UsageSource {
static ProviderUsage _mapWindows(
Map<Object?, Object?> data, {
String? account,
+ String? email,
}) {
final windows = <UsageWindow>[
?_window('Session', data['five_hour']),
@@ -97,6 +100,7 @@ class ClaudeUsageSource implements UsageSource {
windows: windows,
fetchedAt: DateTime.now(),
account: account,
+ email: email,
);
}
@@ -123,6 +127,7 @@ ProviderUsage claudeUsageFromAnswer({
required int? statusCode,
required Object? body,
String? account,
+ String? email,
}) {
final failure = usageFailureFor(UsageProvider.claude, statusCode);
if (failure != null) return failure;
@@ -133,5 +138,5 @@ ProviderUsage claudeUsageFromAnswer({
message: 'Claude answered in a shape this build cannot read',
);
}
- return ClaudeUsageSource._mapWindows(body, account: account);
+ return ClaudeUsageSource._mapWindows(body, account: account, email: email);
}
diff --git a/desktop/lib/usage/codex_usage_source.dart b/desktop/lib/usage/codex_usage_source.dart
index 25b5b59cd..b0dd0b918 100644
--- a/desktop/lib/usage/codex_usage_source.dart
+++ b/desktop/lib/usage/codex_usage_source.dart
@@ -35,6 +35,7 @@ class CodexUsageSource implements UsageSource {
final token = await _credentials.codex();
if (token == null) return signedOut(provider);
final accountId = await _credentials.codexAccountId();
+ final email = await _credentials.codexAccountEmail();
try {
final response = await _dio.getUri<Object?>(
Uri.parse(_url),
@@ -48,6 +49,7 @@ class CodexUsageSource implements UsageSource {
return codexUsageFromAnswer(
statusCode: response.statusCode,
body: response.data,
+ email: email,
account: accountId == null
? null
: usageAccountKey(provider, accountId),
@@ -60,6 +62,7 @@ class CodexUsageSource implements UsageSource {
static ProviderUsage _mapWindows(
Map<Object?, Object?> data, {
String? account,
+ String? email,
}) {
final limits = data['rate_limit'];
final windows = limits is Map
@@ -81,6 +84,7 @@ class CodexUsageSource implements UsageSource {
windows: windows,
fetchedAt: DateTime.now(),
account: account,
+ email: email,
);
}
@@ -120,6 +124,7 @@ ProviderUsage codexUsageFromAnswer({
required int? statusCode,
required Object? body,
String? account,
+ String? email,
}) {
final failure = usageFailureFor(UsageProvider.codex, statusCode);
if (failure != null) return failure;
@@ -130,5 +135,5 @@ ProviderUsage codexUsageFromAnswer({
message: 'Codex answered in a shape this build cannot read',
);
}
- return CodexUsageSource._mapWindows(body, account: account);
+ return CodexUsageSource._mapWindows(body, account: account, email: email);
}
diff --git a/desktop/lib/usage/models_menu_controller.dart b/desktop/lib/usage/models_menu_controller.dart
index 7eae47807..546d771a2 100644
--- a/desktop/lib/usage/models_menu_controller.dart
+++ b/desktop/lib/usage/models_menu_controller.dart
@@ -191,7 +191,7 @@ class ModelsMenuController extends ChangeNotifier {
}
return {
'title': provider,
- 'account': _accountLabel(reading),
+ 'account': reading.email?.trim() ?? '',
'accountKey': reading.account,
'local': account.isLocal,
'machines': account.machines,
@@ -203,16 +203,6 @@ class ModelsMenuController extends ChangeNotifier {
};
}
- static String _accountLabel(ProviderUsage reading) {
- // The same opaque identity is available locally and across machines.
- // Use it consistently instead of mixing emails with fallback IDs.
- final key = reading.account;
- if (key != null && RegExp(r'^[0-9a-f]{16}$').hasMatch(key)) {
- return key.substring(0, 6);
- }
- return '';
- }
-
static String _remaining(UsageWindow window) {
final left = (100 - window.usedPercent).clamp(0, 100);
// Never round a positive remainder to zero (or a partial balance to 100).
diff --git a/desktop/lib/usage/remote_usage.dart b/desktop/lib/usage/remote_usage.dart
index c4115473f..7ad6bd790 100644
--- a/desktop/lib/usage/remote_usage.dart
+++ b/desktop/lib/usage/remote_usage.dart
@@ -34,6 +34,10 @@ ProviderUsage? _readingFrom(Map<Object?, Object?> entry) {
if (provider == null) return null;
final account = entry['account'];
final accountKey = account is String && account.isNotEmpty ? account : null;
+ final rawEmail = entry['email'];
+ final email = rawEmail is String && rawEmail.trim().isNotEmpty
+ ? rawEmail.trim()
+ : null;
switch (entry['outcome']) {
case 'answered':
final status = entry['httpStatus'];
@@ -44,11 +48,13 @@ ProviderUsage? _readingFrom(Map<Object?, Object?> entry) {
statusCode: statusCode,
body: body,
account: accountKey,
+ email: email,
),
UsageProvider.codex => codexUsageFromAnswer(
statusCode: statusCode,
body: body,
account: accountKey,
+ email: email,
),
};
case 'signedOut':
diff --git a/desktop/lib/usage/usage_credentials.dart b/desktop/lib/usage/usage_credentials.dart
index 4c47ff306..b2c87ca39 100644
--- a/desktop/lib/usage/usage_credentials.dart
+++ b/desktop/lib/usage/usage_credentials.dart
@@ -5,7 +5,7 @@
/// would be a second thing to expire and to disagree about.
///
/// **Nothing in this file may be logged.** Every value it returns is a bearer
-/// token; the CLI transcript exists precisely so secrets stay out of argv, and
+/// token or account identity; the CLI transcript keeps secrets out of argv, and
/// a `print` here would undo that. Callers get the token and nothing else —
/// no wrapper carrying it into an error message.
library;
@@ -137,6 +137,32 @@ class UsageCredentials {
return id is String && id.isNotEmpty ? id : null;
}
+ /// Display metadata from the same profile that supplies [claudeAccountId].
+ Future<String?> claudeAccountEmail() async {
+ final profile = _decode(_readFile('.claude.json'))?['oauthAccount'];
+ return profile is Map ? _email(profile['emailAddress']) : null;
+ }
+
+ /// The ID token's email is a display label, never an authentication decision.
+ Future<String?> codexAccountEmail() async {
+ final tokens = _decode(_readFile('.codex/auth.json'))?['tokens'];
+ final token = tokens is Map ? tokens['id_token'] : null;
+ if (token is! String) return null;
+ final parts = token.split('.');
+ if (parts.length != 3) return null;
+ try {
+ final claims = _decode(
+ utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))),
+ );
+ return _email(claims?['email']);
+ } on FormatException {
+ return null;
+ }
+ }
+
+ String? _email(Object? value) =>
+ value is String && value.trim().isNotEmpty ? value.trim() : null;
+
UsageToken? _parseClaude(String? raw) {
if (raw == null) return null;
final oauth = _decode(raw)?['claudeAiOauth'];
diff --git a/desktop/lib/usage/usage_window.dart b/desktop/lib/usage/usage_window.dart
index 4548595c6..323afb629 100644
--- a/desktop/lib/usage/usage_window.dart
+++ b/desktop/lib/usage/usage_window.dart
@@ -92,6 +92,7 @@ class ProviderUsage {
this.message,
this.fetchedAt,
this.account,
+ this.email,
});
/// The state a provider is in before it has ever answered.
@@ -100,7 +101,8 @@ class ProviderUsage {
windows = const [],
message = null,
fetchedAt = null,
- account = null;
+ account = null,
+ email = null;
final UsageProvider provider;
final UsageStatus status;
@@ -126,6 +128,10 @@ class ProviderUsage {
/// are not provably one account, and merging them could hide a subscription.
final String? account;
+ /// The provider login's email, for display only. [account] remains the stable
+ /// identity used to group readings and select the correct subscription.
+ final String? email;
+
bool get hasFigures => status == UsageStatus.ok && windows.isNotEmpty;
/// The window closest to being spent — the limit that will actually stop the
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 59bf68b5f..8d819c656 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -1901,9 +1901,8 @@ class _SearchRowContentState extends State<_SearchRowContent> {
],
Expanded(
child: subscriptionAccount != null
- // A subscription names its provider, and the account after it in the quieter
- // colour: "Anthropic 315df1", not one run of text where the account reads
- // as part of the name.
+ // Keep the provider distinct from its email. Both must fit the available
+ // width: an email can be much longer than the old short account key.
? Row(
children: [
Flexible(
@@ -1916,11 +1915,14 @@ class _SearchRowContentState extends State<_SearchRowContent> {
),
),
const SizedBox(width: 8),
- SearchResultText(
- subscriptionAccount.account,
- key: ValueKey('model-row-account:${row.id}'),
- matches: matches.where((match) => match.title),
- style: DesktopChrome.text(color: muted),
+ Flexible(
+ flex: 2,
+ child: SearchResultText(
+ subscriptionAccount.account,
+ key: ValueKey('model-row-account:${row.id}'),
+ matches: matches.where((match) => match.title),
+ style: DesktopChrome.text(color: muted),
+ ),
),
],
)
diff --git a/desktop/test/desktop_search_polish_test.dart b/desktop/test/desktop_search_polish_test.dart
index 6f7e44cb7..fc99b12f3 100644
--- a/desktop/test/desktop_search_polish_test.dart
+++ b/desktop/test/desktop_search_polish_test.dart
@@ -160,18 +160,20 @@ class _Palette {
class _ReviewSubscriptions extends ModelsMenuController {
@override
List<Map<String, Object?>> get rows => const [
- {
- 'engine': 'codex',
- 'title': 'OpenAI',
- 'status': '71% remaining',
- 'remainingPercent': 71.0,
- 'details': ['Weekly usage · resets Friday'],
- },
{
'engine': 'claude',
'title': 'Anthropic',
+ 'account': '[email protected]',
+ 'accountKey': 'aabbccddeeff0011',
+ 'status': '8% remaining',
+ 'remainingPercent': 8.0,
+ 'details': ['Limiting window: Session', 'Session — 8% remaining · resets in 30m', 'Weekly — 58% remaining · resets in 5d 10h'],
+ },
+ {
+ 'engine': 'codex',
+ 'title': 'OpenAI',
'status': 'Not signed in',
- 'details': ['Sign in to Claude on this computer.'],
+ 'details': ['Sign in to Codex on this computer.'],
},
];
}
@@ -728,6 +730,14 @@ void main() {
);
if (name == 'models') {
final preview = find.byType(SwarmResourcePreview);
+ expect(
+ find.descendant(
+ of: preview,
+ matching: find.text('Anthropic · [email protected]'),
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('aabbcc'), findsNothing);
expect(
find.descendant(of: preview, matching: find.text('Machine')),
findsNothing,
diff --git a/desktop/test/log_redact_test.dart b/desktop/test/log_redact_test.dart
index d0771f91c..d17631073 100644
--- a/desktop/test/log_redact_test.dart
+++ b/desktop/test/log_redact_test.dart
@@ -35,6 +35,8 @@ void main() {
'sessionToken',
'password',
'secret',
+ 'email',
+ 'emailAddress',
]) {
final line = redactValue({
'a': {
diff --git a/desktop/test/model_search_catalog_test.dart b/desktop/test/model_search_catalog_test.dart
index 336bd688e..e9b4e9ada 100644
--- a/desktop/test/model_search_catalog_test.dart
+++ b/desktop/test/model_search_catalog_test.dart
@@ -30,13 +30,15 @@ class _MachineSubscriptions extends ModelsMenuController {
{
'engine': 'codex',
'title': 'OpenAI',
- 'account': 'local-account',
+ 'account': '[email protected]',
+ 'accountKey': 'local-account',
'status': signedOut ? 'Not signed in' : '50% remaining',
},
{
'engine': 'codex',
'title': 'OpenAI',
- 'account': 'remote-account',
+ 'account': '[email protected]',
+ 'accountKey': 'remote-account',
'status': '75% remaining',
},
];
@@ -374,7 +376,7 @@ void main() {
machineId: 'm',
);
final own = search.rows.singleWhere(
- (row) => row.title == 'OpenAI · local-account',
+ (row) => grouped.entries[row.modelId]?.subscription?['accountKey'] == 'local-account',
);
expect(search.canSelectModel(own), isTrue);
expect(search.modelRowStatus(own), '50% remaining');
@@ -525,7 +527,7 @@ void main() {
expect(catalog.entries.values.single.source, 'Shared · home');
});
- test('Use identifies only the subscription available on the pane host', () {
+ test('Use keeps accounts with the same email scoped to the pane host', () {
final usage = _MachineSubscriptions();
final accounts = ModelSearchCatalog(
app.modelManager,
@@ -538,12 +540,12 @@ void main() {
try {
final local = search.rows.firstWhere(
(row) =>
- accounts.entries[row.modelId]?.subscription?['account'] ==
+ accounts.entries[row.modelId]?.subscription?['accountKey'] ==
'local-account',
);
final remote = search.rows.firstWhere(
(row) =>
- accounts.entries[row.modelId]?.subscription?['account'] ==
+ accounts.entries[row.modelId]?.subscription?['accountKey'] ==
'remote-account',
);
expect(search.modelRowAction(local), 'Use');
diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dart
index a2babb03b..bd4e32637 100644
--- a/desktop/test/models_menu_test.dart
+++ b/desktop/test/models_menu_test.dart
@@ -130,10 +130,12 @@ void main() {
DateTime? reset,
DateTime? fetched,
String? account = 'aabbccddeeff0011',
+ String? email = '[email protected]',
}) => ProviderUsage(
provider: UsageProvider.claude,
status: UsageStatus.ok,
account: account,
+ email: email,
fetchedAt: fetched ?? instant,
windows: [
UsageWindow(label: 'Session', usedPercent: session, resetsAt: reset),
@@ -152,7 +154,13 @@ void main() {
MachineUsage(machineName: 'Shared Mac', readings: [reading()]),
MachineUsage(
machineName: 'Other Mac',
- readings: [reading(account: '1122334455667788', session: 50)],
+ readings: [
+ reading(
+ account: '1122334455667788',
+ email: '[email protected]',
+ session: 50,
+ ),
+ ],
),
],
);
@@ -164,11 +172,11 @@ void main() {
expect(menu.rows.first['title'], 'Anthropic');
expect(menu.rows.first['status'], '15% remaining');
expect(menu.rows.first['details'], contains('Weekly — 70% remaining'));
- expect(menu.rows.first['account'], 'aabbcc');
+ expect(menu.rows.first['account'], '[email protected]');
expect(menu.rows.first['machines'], ['Shared Mac']);
expect(menu.rows.first['accountKey'], 'aabbccddeeff0011');
expect(menu.rows.last['title'], 'Anthropic');
- expect(menu.rows.last['account'], '112233');
+ expect(menu.rows.last['account'], '[email protected]');
expect(menu.rows.last['status'], '50% remaining');
expect(
menu.rows.map((row) => row['details']).toString(),
@@ -204,19 +212,23 @@ void main() {
},
);
- test('unidentified accounts do not invent an account label', () async {
- final source = _Source(
- UsageProvider.claude,
- () async => reading(account: null),
- );
- final usage = UsageController(sources: [source], autoStart: false);
- final menu = ModelsMenuController(usage: usage, now: () => instant);
- addTearDown(usage.dispose);
- addTearDown(menu.dispose);
- await menu.refresh();
- expect(menu.rows.single['title'], 'Anthropic');
- expect(menu.rows.single['account'], '');
- });
+ test(
+ 'readings without email do not expose their internal account key',
+ () async {
+ final source = _Source(
+ UsageProvider.claude,
+ () async => reading(email: null),
+ );
+ final usage = UsageController(sources: [source], autoStart: false);
+ final menu = ModelsMenuController(usage: usage, now: () => instant);
+ addTearDown(usage.dispose);
+ addTearDown(menu.dispose);
+ await menu.refresh();
+ expect(menu.rows.single['title'], 'Anthropic');
+ expect(menu.rows.single['account'], '');
+ expect(menu.rows.single['accountKey'], 'aabbccddeeff0011');
+ },
+ );
test(
'unknown, expired and invalid readings never become made-up percentages',
diff --git a/desktop/test/new_harness_models_test.dart b/desktop/test/new_harness_models_test.dart
index b3b298ddb..423ca4722 100644
--- a/desktop/test/new_harness_models_test.dart
+++ b/desktop/test/new_harness_models_test.dart
@@ -572,16 +572,16 @@ void main() {
addTearDown(usage.dispose);
await menu.refresh();
expect(
- menu.subscriptionFor('codex', local: true, machineName: '')?['account'],
- '111111',
+ menu.subscriptionFor('codex', local: true, machineName: '')?['accountKey'],
+ '1111111111111111',
);
expect(
menu.subscriptionFor(
'codex',
local: false,
machineName: 'M2',
- )?['account'],
- '333333',
+ )?['accountKey'],
+ '3333333333333333',
);
expect(
menu.subscriptionFor('claude', local: false, machineName: 'M2'),
diff --git a/desktop/test/remote_usage_test.dart b/desktop/test/remote_usage_test.dart
index 24f19e6b2..2965de98a 100644
--- a/desktop/test/remote_usage_test.dart
+++ b/desktop/test/remote_usage_test.dart
@@ -28,6 +28,7 @@ void main() {
{
'provider': 'claude',
'account': 'k1',
+ 'email': '[email protected]',
'outcome': 'answered',
'httpStatus': 200,
'body': {
@@ -41,6 +42,7 @@ void main() {
final claude = readings.single;
expect(claude.status, UsageStatus.ok);
expect(claude.account, 'k1');
+ expect(claude.email, '[email protected]');
// Claude's `seven_day` is the Weekly window here exactly as it is for
// this computer's own reading — one mapper, two sources.
final weekly = claude.windows.singleWhere(
@@ -65,6 +67,30 @@ void main() {
expect(readings.single.status, UsageStatus.signedOut);
});
+ test('older and malformed email metadata leave usage readable', () {
+ for (final email in [null, '', ' ', 42, <String>[]]) {
+ final reading = parseUsageReadResult({
+ 'providers': [
+ {
+ 'provider': 'codex',
+ 'account': 'k2',
+ 'email': email,
+ 'outcome': 'answered',
+ 'httpStatus': 200,
+ 'body': {
+ 'rate_limit': {
+ 'primary_window': {'used_percent': 12},
+ },
+ },
+ },
+ ],
+ }).single;
+ expect(reading.hasFigures, isTrue);
+ expect(reading.account, 'k2');
+ expect(reading.email, isNull);
+ }
+ });
+
test("the machine's own sentence survives a sign-out", () {
final readings = parseUsageReadResult({
'providers': [
diff --git a/desktop/test/usage_credentials_test.dart b/desktop/test/usage_credentials_test.dart
index ca67d9c77..590a76c75 100644
--- a/desktop/test/usage_credentials_test.dart
+++ b/desktop/test/usage_credentials_test.dart
@@ -1,6 +1,7 @@
// How the app finds Claude Code's OAuth token in the macOS Keychain — the same lookup Claude Code
// itself performs, or it reads a different item than the CLI that is signed in.
import 'dart:io';
+import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/usage/usage_credentials.dart';
@@ -36,6 +37,46 @@ class _Keychain {
}
void main() {
+ test(
+ 'unavailable or malformed account emails do not break credential reads',
+ () async {
+ final home = Directory.systemTemp.createTempSync('usage-email-');
+ addTearDown(() => home.deleteSync(recursive: true));
+ final credentials = UsageCredentials(
+ home: home.path,
+ environment: const {},
+ );
+ expect(await credentials.claudeAccountEmail(), isNull);
+ expect(await credentials.codexAccountEmail(), isNull);
+ Directory('${home.path}/.codex').createSync();
+ for (final value in [
+ null,
+ '',
+ ' ',
+ 42,
+ 'not-a-jwt',
+ 'a.%%%.b',
+ 'a.bnVsbA.b',
+ ]) {
+ File('${home.path}/.claude.json').writeAsStringSync(
+ jsonEncode({
+ 'oauthAccount': {'accountUuid': 'account', 'emailAddress': value},
+ }),
+ );
+ File('${home.path}/.codex/auth.json').writeAsStringSync(
+ jsonEncode({
+ 'tokens': {'access_token': 'test-token', 'id_token': value},
+ }),
+ );
+ if (value is! String || value.trim().isEmpty) {
+ expect(await credentials.claudeAccountEmail(), isNull);
+ }
+ expect(await credentials.codexAccountEmail(), isNull);
+ expect((await credentials.codex())?.accessToken, 'test-token');
+ }
+ },
+ );
+
test(
'reads the item Claude Code itself reads: service AND this user\'s account',
() async {
diff --git a/desktop/test/usage_test.dart b/desktop/test/usage_test.dart
index 1772599ed..e3d0d8e2c 100644
--- a/desktop/test/usage_test.dart
+++ b/desktop/test/usage_test.dart
@@ -1,3 +1,4 @@
+import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
@@ -8,6 +9,7 @@ import 'package:harness/usage/usage_credentials.dart';
import 'package:harness/usage/usage_controller.dart';
import 'package:harness/usage/usage_source.dart';
import 'package:harness/usage/usage_window.dart';
+import 'package:harness/usage/usage_account_key.dart';
/// A Dio that answers every request with one canned payload, so a source can be
/// exercised without a socket or a credential.
@@ -42,7 +44,11 @@ Dio _dioAnswering(Object? body, {int status = 200}) {
/// The keychain stub stays, and always fails, for the opposite reason: without
/// it a macOS run would shell out to the real `security` and read whoever is
/// signed in on the machine.
-UsageCredentials _creds({String? claudeJson, String? codexJson}) {
+UsageCredentials _creds({
+ String? claudeJson,
+ String? claudeProfile,
+ String? codexJson,
+}) {
final dir = Directory.systemTemp.createTempSync('harness-usage-test');
addTearDown(() => dir.deleteSync(recursive: true));
void write(String folder, String file, String body) {
@@ -51,6 +57,8 @@ UsageCredentials _creds({String? claudeJson, String? codexJson}) {
}
if (claudeJson != null) write('.claude', '.credentials.json', claudeJson);
+ if (claudeProfile != null)
+ File('${dir.path}/.claude.json').writeAsStringSync(claudeProfile);
if (codexJson != null) write('.codex', 'auth.json', codexJson);
return UsageCredentials(
home: dir.path,
@@ -140,8 +148,6 @@ void main() {
expect(reading.tightest?.label, 'Weekly');
});
-
-
group('Claude source', () {
test('maps the three windows the CLI itself shows', () async {
final source = ClaudeUsageSource(
@@ -152,11 +158,17 @@ void main() {
}),
credentials: _creds(
claudeJson: '{"claudeAiOauth":{"accessToken":"t"}}',
+ claudeProfile: '{"oauthAccount":{"accountUuid":"acct-123","emailAddress":"[email protected]"}}',
),
);
final reading = await source.read();
expect(reading.status, UsageStatus.ok);
+ expect(reading.email, '[email protected]');
+ expect(
+ reading.account,
+ usageAccountKey(UsageProvider.claude, 'acct-123'),
+ );
expect(
reading.windows.map((w) => '${w.label} ${w.usedPercent.round()}'),
['Session 2', 'Weekly 16', 'Fable 0'],
@@ -248,12 +260,21 @@ void main() {
},
}),
credentials: _creds(
- codexJson: '{"tokens":{"access_token":"t","account_id":"acct"}}',
+ codexJson: jsonEncode({
+ 'tokens': {
+ 'access_token': 't',
+ 'account_id': 'acct',
+ 'id_token':
+ 'e30.${base64Url.encode(utf8.encode(jsonEncode({'email': '[email protected]'}))).replaceAll('=', '')}.signature',
+ },
+ }),
),
);
final reading = await source.read();
expect(reading.status, UsageStatus.ok);
+ expect(reading.email, '[email protected]');
+ expect(reading.account, usageAccountKey(UsageProvider.codex, 'acct'));
// 18000s is 5h; 604800s is the week, which earns the name rather than
// the arithmetic "7d".
expect(reading.windows.map((w) => w.label), ['5h', 'Weekly']);