Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 69 additions & 5 deletions apps/desktop-tauri/src/components/CodexAccountsMenu.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,17 @@ function account(id: string, extra: Partial<CodexAccount> = {}): CodexAccount {
};
}

function snapshot(usedPercent: number): CodexAccountUsageSnapshot {
function snapshot(
usedPercent: number,
resetAt: string | null = null,
): CodexAccountUsageSnapshot {
return {
email: "user@example.com",
providerAccountId: null,
plan: "free",
allowed: true,
limitReached: false,
primaryWindow: { usedPercent, resetAt: null, limitWindowSeconds: 3600 },
primaryWindow: { usedPercent, resetAt, limitWindowSeconds: 18_000 },
secondaryWindow: null,
credits: null,
updatedAt: "2024-01-01T00:00:00Z",
Expand All @@ -57,12 +60,19 @@ function snapshot(usedPercent: number): CodexAccountUsageSnapshot {
// Wrap the component so the `t` from useLocale is a stable identity that just
// returns the key (the component uses `t(key)` for locale strings and a badge
// label; returning the key is enough to assert rendering).
function renderMenu(hideEmail: boolean, state: CodexAccountsStateBridge) {
function renderMenu(
hideEmail: boolean,
state: CodexAccountsStateBridge,
resetTimeRelative = true,
) {
tauriMocks.getCodexAccountsState.mockResolvedValue(state);
tauriMocks.getLocaleStrings.mockResolvedValue(buildBundle({}));
return render(
<LocaleProvider>
<CodexAccountsMenu hideEmail={hideEmail} />
<CodexAccountsMenu
hideEmail={hideEmail}
resetTimeRelative={resetTimeRelative}
/>
</LocaleProvider>,
);
}
Expand Down Expand Up @@ -141,6 +151,30 @@ describe("CodexAccountsMenu", () => {
expect((fills[0] as HTMLElement).style.width).toBe("42%");
});

it("shows the five-hour usage and local reset time for each account", async () => {
const resetAt = "2030-01-02T03:04:00Z";
const expectedReset = new Intl.DateTimeFormat(undefined, {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
}).format(new Date(resetAt));

renderMenu(
false,
{
accounts: [account("1", { source: "ambient" }), account("2")],
snapshots: { "1": snapshot(30, resetAt), "2": snapshot(70, resetAt) },
},
false,
);

await screen.findByText("user-1@example.com");
expect(screen.getAllByText("5h")).toHaveLength(2);
expect(screen.getByText("30% PanelUsedSuffix")).toBeDefined();
expect(screen.getAllByText(`MetricResetsIn ${expectedReset}`)).toHaveLength(2);
});

it("switches an account and kicks a provider refresh", async () => {
renderMenu(false, {
accounts: [account("1", { source: "ambient" }), account("2")],
Expand All @@ -162,4 +196,34 @@ describe("CodexAccountsMenu", () => {
expect(tauriMocks.codexAccountSwitch).toHaveBeenCalledWith("2");
expect(tauriMocks.refreshProviders).toHaveBeenCalledTimes(1);
});
});
it("keeps the email tooltip masked while hideEmail is on and raw when off", async () => {
const { container: hidden } = renderMenu(true, {
accounts: [account("1", { source: "ambient" }), account("2")],
snapshots: {},
});
await waitFor(() => {
expect(
hidden.querySelectorAll(".codex-menu-accounts__email").length,
).toBe(2);
});
const hiddenEmail = hidden.querySelectorAll(
".codex-menu-accounts__email",
)[1] as HTMLElement;
expect(hiddenEmail.getAttribute("title")).toBe(hiddenEmail.textContent);

const { container: visible } = renderMenu(false, {
accounts: [account("1", { source: "ambient" }), account("2")],
snapshots: {},
});
await waitFor(() => {
expect(
visible.querySelectorAll(".codex-menu-accounts__email").length,
).toBe(2);
});
const rawEmail = visible.querySelectorAll(
".codex-menu-accounts__email",
)[1] as HTMLElement;
expect(rawEmail.getAttribute("title")).toBe("user-2@example.com");
});
});

175 changes: 119 additions & 56 deletions apps/desktop-tauri/src/components/CodexAccountsMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
CodexAccountUsageSnapshot,
} from "../types/bridge";
import { useLocale } from "../hooks/useLocale";
import { useFormattedResetTime } from "../hooks/useFormattedResetTime";
import { maskEmail } from "./MenuCard";
import {
codexAccountSwitch,
Expand All @@ -22,7 +23,13 @@ import {
* Switch action. Switching updates the ambient identity and triggers a
* provider refresh so the tray icon/menu reflect the now-active account.
*/
export default function CodexAccountsMenu({ hideEmail }: { hideEmail: boolean }) {
export default function CodexAccountsMenu({
hideEmail,
resetTimeRelative,
}: {
hideEmail: boolean;
resetTimeRelative: boolean;
}) {
const { t } = useLocale();
const [accounts, setAccounts] = useState<CodexAccount[]>([]);
const [snapshots, setSnapshots] = useState<
Expand Down Expand Up @@ -91,65 +98,121 @@ export default function CodexAccountsMenu({ hideEmail }: { hideEmail: boolean })
</div>
)}
<ul className="codex-menu-accounts__list">
{accounts.map((account) => {
const snapshot = snapshots[account.id];
// Prefer the primary (session) window, but accounts whose backend
// only returns a weekly window have primaryWindow: null — fall back
// to the next filled window in canonical order (primary →
// secondary; the account-snapshot bridge carries no tertiary or
// extra rate windows) so the usage bar still renders.
const usageWindow =
snapshot?.primaryWindow ?? snapshot?.secondaryWindow ?? null;
const pct = usageWindow
? Math.round(usageWindow.usedPercent)
: null;
const label =
account.nickname ??
account.emailHint ??
account.authSubject ??
shrink(account.id);
const shown = hideEmail ? maskEmail(label) : label;
const isAmbient = account.source === "ambient";
return (
<li key={account.id}>
<div
className={`codex-menu-accounts__row${isAmbient ? " codex-menu-accounts__row--active" : ""}`}
>
<div className="codex-menu-accounts__meta">
<span className="codex-menu-accounts__email" title={label}>
{shown}
{isAmbient && (
<span className="codex-menu-accounts__badge">
{t("CodexAccountsSourceAmbient")}
</span>
)}
</span>
{pct !== null && (
<span className="codex-menu-accounts__bar" aria-hidden>
<span
className="codex-menu-accounts__bar-fill"
style={{ width: `${Math.max(2, Math.min(100, pct))}%` }}
/>
</span>
)}
</div>
<button
type="button"
className="codex-menu-accounts__switch"
disabled={busy || isAmbient}
onClick={() => void handleSwitch(account.id)}
>
{t("CodexAccountsSwitchButton")}
</button>
</div>
</li>
);
})}
{accounts.map((account) => (
<CodexAccountRow
key={account.id}
account={account}
snapshot={snapshots[account.id]}
hideEmail={hideEmail}
resetTimeRelative={resetTimeRelative}
busy={busy}
onSwitch={handleSwitch}
/>
))}
</ul>
</details>
);
}

function CodexAccountRow({
account,
snapshot,
hideEmail,
resetTimeRelative,
busy,
onSwitch,
}: {
account: CodexAccount;
snapshot: CodexAccountUsageSnapshot | undefined;
hideEmail: boolean;
resetTimeRelative: boolean;
busy: boolean;
onSwitch: (id: string) => Promise<void>;
}) {
const { t } = useLocale();
// Prefer the primary (normally five-hour) window. Accounts whose backend
// only returns a weekly window have primaryWindow: null, so keep the
// existing secondary-window fallback for their bar and reset detail.
const usageWindow =
snapshot?.primaryWindow ?? snapshot?.secondaryWindow ?? null;
const pct = usageWindow ? Math.round(usageWindow.usedPercent) : null;
const resetText = useFormattedResetTime(
usageWindow?.resetAt ?? null,
null,
resetTimeRelative,
);
const resetLabel = resetText
? resetTimeRelative
? resetText
: `${t("MetricResetsIn")} ${resetText}`
: null;
const windowLabel = formatWindowLabel(usageWindow?.limitWindowSeconds);
const label =
account.nickname ??
account.emailHint ??
account.authSubject ??
shrink(account.id);
const shown = hideEmail ? maskEmail(label) : label;
const isAmbient = account.source === "ambient";

return (
<li>
<div
className={`codex-menu-accounts__row${isAmbient ? " codex-menu-accounts__row--active" : ""}`}
>
<div className="codex-menu-accounts__meta">
<span className="codex-menu-accounts__email" title={shown}>
{shown}
{isAmbient && (
<span className="codex-menu-accounts__badge">
{t("CodexAccountsSourceAmbient")}
</span>
)}
</span>
{(pct !== null || resetLabel) && (
<span className="codex-menu-accounts__usage">
{windowLabel && <span>{windowLabel}</span>}
{pct !== null && (
<span>{pct}% {t("PanelUsedSuffix")}</span>
)}
{resetLabel && <span>{resetLabel}</span>}
</span>
)}
{pct !== null && (
<span className="codex-menu-accounts__bar" aria-hidden>
<span
className="codex-menu-accounts__bar-fill"
style={{ width: `${Math.max(2, Math.min(100, pct))}%` }}
/>
</span>
)}
</div>
<button
type="button"
className="codex-menu-accounts__switch"
disabled={busy || isAmbient}
onClick={() => void onSwitch(account.id)}
>
{t("CodexAccountsSwitchButton")}
</button>
</div>
</li>
);
}

function formatWindowLabel(
limitWindowSeconds: number | null | undefined,
): string | null {
if (!limitWindowSeconds || limitWindowSeconds <= 0) return null;
if (limitWindowSeconds % 86_400 === 0) {
return `${limitWindowSeconds / 86_400}d`;
}
if (limitWindowSeconds % 3_600 === 0) {
return `${limitWindowSeconds / 3_600}h`;
}
return null;
}

function shrink(id: string): string {
return id.length <= 12 ? id : `${id.slice(0, 8)}…`;
}
}
5 changes: 4 additions & 1 deletion apps/desktop-tauri/src/components/MenuCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,10 @@ export default function MenuCard({
)}

{provider.providerId === "codex" && (
<CodexAccountsMenu hideEmail={hideEmail} />
<CodexAccountsMenu
hideEmail={hideEmail}
resetTimeRelative={resetTimeRelative}
/>
)}
</article>
);
Expand Down
18 changes: 18 additions & 0 deletions apps/desktop-tauri/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -4017,6 +4017,24 @@ html:has(.menu-surface--tray) {
color: var(--provider-status-ok, #4ade80);
}

.codex-menu-accounts__usage {
display: flex;
align-items: center;
gap: 0;
min-width: 0;
font-size: 0.66rem;
color: var(--provider-row-text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

.codex-menu-accounts__usage > span + span::before {
content: "·";
margin: 0 5px;
opacity: 0.65;
}

.codex-menu-accounts__bar {
display: block;
height: 4px;
Expand Down