Skip to content

Commit 0ea2f00

Browse files
committed
Merge remote-tracking branch 'origin/main' into fix/mobile-autolink-keep-trailing-marks
2 parents 632891a + daafcc4 commit 0ea2f00

20 files changed

Lines changed: 811 additions & 99 deletions

‎apps/web/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575
"@vitejs/plugin-react": "^6.0.0",
7676
"babel-plugin-react-compiler": "1.0.0",
7777
"compression": "^1.8.1",
78+
"jsdom": "^30.0.1",
7879
"react-test-renderer": "19.2.6",
7980
"tailwindcss": "^4.0.0",
8081
"unified": "^11.0.5",

‎apps/web/src/components/AppSidebarLayout.tsx‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,14 +79,17 @@ function readInitialThreadSidebarWidth(): number {
7979
}
8080

8181
function SidebarControl() {
82+
const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
8283
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
8384
const { toggleSidebar } = useSidebar();
8485
const isSidebarVisible = useSidebarVisibility();
8586
const environmentIdentificationMode = useEnvironmentIdentificationMode();
8687
const stageBackdropVariant = useSidebarStageBackdropVariant(
8788
environmentIdentificationMode === "artwork",
8889
);
89-
const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle");
90+
const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
91+
context: { usagePageOpen },
92+
});
9093

9194
useEffect(() => {
9295
const onKeyDown = (event: KeyboardEvent) => {
@@ -106,7 +109,11 @@ function SidebarControl() {
106109
// available everywhere else, including the plain-text composer.
107110
return;
108111
}
109-
if (resolveShortcutCommand(event, keybindings) !== "sidebar.toggle") return;
112+
if (
113+
resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
114+
"sidebar.toggle"
115+
)
116+
return;
110117

111118
event.preventDefault();
112119
event.stopPropagation();
@@ -116,7 +123,7 @@ function SidebarControl() {
116123
// Capture before focused editors consume commands such as Mod+B for rich-text formatting.
117124
window.addEventListener("keydown", onKeyDown, true);
118125
return () => window.removeEventListener("keydown", onKeyDown, true);
119-
}, [keybindings, toggleSidebar]);
126+
}, [keybindings, toggleSidebar, usagePageOpen]);
120127

121128
return (
122129
// The right-side layout controls carry mr-px (border compensation inside

‎apps/web/src/components/settings/KeybindingsSettings.logic.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,24 @@ describe("KeybindingsSettings.logic", () => {
4646
);
4747
},
4848
);
49+
it("orders Usage bindings and command choices like the page", () => {
50+
const expected = [
51+
"usage.cost",
52+
"usage.open",
53+
"usage.tokens",
54+
"usage.limits",
55+
"usage.period.day",
56+
"usage.period.week",
57+
"usage.period.month",
58+
"usage.period.quarter",
59+
];
60+
const bindings = DEFAULT_RESOLVED_KEYBINDINGS.toReversed();
61+
expect(buildKeybindingRows(bindings, "usage").map((row) => row.command)).toEqual(expected);
62+
expect(
63+
buildKeybindingCommandOptions(bindings).filter((command) => command.startsWith("usage.")),
64+
).toEqual(expected);
65+
});
66+
4967
it("builds searchable rows with readable key and when values", () => {
5068
const rows = buildKeybindingRows(
5169
[

‎apps/web/src/components/settings/KeybindingsSettings.logic.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,17 @@ import {
1313

1414
import { shortcutKeyFromEvent } from "../../keybindings";
1515
import { isMacPlatform } from "../../lib/utils";
16+
import { METRIC_OPTIONS, WINDOW_OPTIONS } from "../usage/usageShortcuts";
17+
18+
const usageCommandOrder = new Map<KeybindingCommand, number>(
19+
[...METRIC_OPTIONS, ...WINDOW_OPTIONS].map((option, index) => [option.command, index]),
20+
);
21+
22+
function compareUsageCommands(left: KeybindingCommand, right: KeybindingCommand): number | null {
23+
const leftIndex = usageCommandOrder.get(left);
24+
const rightIndex = usageCommandOrder.get(right);
25+
return leftIndex !== undefined && rightIndex !== undefined ? leftIndex - rightIndex : null;
26+
}
1627

1728
export type KeybindingSource = "Default" | "Custom" | "Project";
1829

@@ -204,7 +215,9 @@ export function buildKeybindingRows(
204215
});
205216

206217
rowsWithConflicts.sort((left, right) => {
207-
const commandCompare = left.command.localeCompare(right.command);
218+
const commandCompare =
219+
compareUsageCommands(left.command, right.command) ??
220+
left.command.localeCompare(right.command);
208221
if (commandCompare !== 0) return commandCompare;
209222
return left.key.localeCompare(right.key);
210223
});
@@ -277,13 +290,18 @@ export function buildKeybindingCommandOptions(
277290
for (const binding of keybindings) {
278291
commands.add(binding.command);
279292
}
280-
return [...commands].toSorted((left, right) =>
281-
commandLabel(left).localeCompare(commandLabel(right)),
293+
return [...commands].toSorted(
294+
(left, right) =>
295+
compareUsageCommands(left, right) ?? commandLabel(left).localeCompare(commandLabel(right)),
282296
);
283297
}
284298

285299
export function commandLabel(command: KeybindingCommand): string {
286300
if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread ID";
301+
const usageMetric = METRIC_OPTIONS.find((option) => option.command === command);
302+
if (usageMetric) return `Usage: ${usageMetric.label}`;
303+
const usagePeriod = WINDOW_OPTIONS.find((option) => option.command === command);
304+
if (usagePeriod) return `Usage: Period: ${usagePeriod.label}`;
287305
const raw = String(command);
288306
if (raw.startsWith("script.") && raw.endsWith(".run")) {
289307
return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;

‎apps/web/src/components/usage/UsagePage.refresh.test.tsx‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { EnvironmentId, ProviderInstanceId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
22
import { mergeUsage } from "@t3tools/shared/usageMerge";
33
import { StrictMode, act } from "react";
4+
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
45
import { create, type ReactTestRenderer } from "react-test-renderer";
56
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
67

@@ -9,11 +10,21 @@ const state = vi.hoisted(() => ({
910
refreshProviders: vi.fn(async () => undefined),
1011
metric: "limits",
1112
}));
12-
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.presentations }));
13+
vi.mock("@effect/atom-react", () => ({
14+
useAtomValue: (atom: unknown) =>
15+
atom === "keybindings" ? DEFAULT_RESOLVED_KEYBINDINGS : state.presentations,
16+
}));
17+
vi.mock("@tanstack/react-router", () => ({
18+
useNavigate: () => vi.fn(),
19+
useCanGoBack: () => false,
20+
}));
1321
vi.mock("../../state/presentation", () => ({
1422
environmentPresentations: { presentationsAtom: null },
1523
}));
16-
vi.mock("../../state/server", () => ({ serverEnvironment: { refreshProviders: null } }));
24+
vi.mock("../../state/server", () => ({
25+
serverEnvironment: { refreshProviders: null },
26+
primaryServerKeybindingsAtom: "keybindings",
27+
}));
1728
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.refreshProviders }));
1829
vi.mock("../../env", () => ({ isElectron: false }));
1930
vi.mock("../../hooks/useSettings", () => ({ usePrimarySettings: () => "24h" }));
@@ -86,6 +97,7 @@ import { UsagePage } from "./UsagePage";
8697
let renderer: ReactTestRenderer;
8798
let environmentNumber = 0;
8899
beforeEach(() => {
100+
vi.stubGlobal("window", new EventTarget());
89101
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
90102
vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-09-11T12:00:00Z"));
91103
environmentNumber += 1;
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
import { EnvironmentId, UsageDay, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
2+
import { mergeUsage } from "@t3tools/shared/usageMerge";
3+
import { act } from "react";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6+
7+
const testState = vi.hoisted(() => ({
8+
useUsage: vi.fn(),
9+
navigate: vi.fn(),
10+
canGoBack: true,
11+
}));
12+
13+
vi.mock("../../env", () => ({ isElectron: false }));
14+
vi.mock("@tanstack/react-router", () => ({
15+
useNavigate: () => testState.navigate,
16+
useCanGoBack: () => testState.canGoBack,
17+
}));
18+
vi.mock("../../state/usage", () => ({ useUsage: testState.useUsage }));
19+
vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
20+
vi.mock("../ui/select", () => ({
21+
Select: "div",
22+
SelectItem: "div",
23+
SelectPopup: "div",
24+
SelectTrigger: "div",
25+
SelectValue: "div",
26+
}));
27+
vi.mock("../ui/sidebar", () => ({ SidebarInset: "div" }));
28+
vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));
29+
vi.mock("../WorkspaceBreadcrumb", () => ({
30+
WorkspaceBreadcrumb: "div",
31+
WorkspaceBreadcrumbItem: "div",
32+
WorkspaceBreadcrumbSeparator: "span",
33+
}));
34+
vi.mock("../WorkspacePageContainer", () => ({ WorkspacePageContainer: "main" }));
35+
vi.mock("../WorkspacePageHeader", () => ({ WorkspacePageHeader: "header" }));
36+
vi.mock("./UsageProviderChart", () => ({ UsageProviderChart: "div" }));
37+
vi.mock("./UsagePriceOverrides", () => ({ UsagePriceOverrides: () => null }));
38+
vi.mock("./usageProviders", async (importOriginal) => {
39+
const actual = await importOriginal<typeof import("./usageProviders")>();
40+
return {
41+
...actual,
42+
PROVIDER_PRESENTATION: {
43+
codex: { color: "white", label: "Codex", mark: "span" },
44+
claude: { color: "orange", label: "Claude Code", mark: "span" },
45+
},
46+
};
47+
});
48+
49+
import { UsagePage } from "./UsagePage";
50+
const environments = [
51+
{
52+
environmentId: EnvironmentId.make("test-environment"),
53+
label: "Test environment",
54+
isPending: false,
55+
error: null,
56+
summary: {
57+
contractVersion: USAGE_CONTRACT_VERSION,
58+
readAt: "2026-08-11T12:37:00.000Z",
59+
sinceDay: UsageDay.make("2026-08-10"),
60+
untilDay: UsageDay.make("2026-08-11"),
61+
timeZone: "UTC",
62+
buckets: [],
63+
sources: [],
64+
pricing: { status: "fresh", source: "test", fetchedAt: null, knownModels: 1 },
65+
scanDurationMs: 1,
66+
},
67+
},
68+
];
69+
70+
beforeEach(() => {
71+
testState.useUsage.mockReturnValue({
72+
merged: mergeUsage([], USAGE_CONTRACT_VERSION),
73+
environments,
74+
selectedEnvironments: environments,
75+
isPending: false,
76+
isPartial: false,
77+
refresh: vi.fn(),
78+
});
79+
});
80+
81+
describe("UsagePage Escape navigation", () => {
82+
let renderer: Root;
83+
let container: HTMLDivElement;
84+
let back: ReturnType<typeof vi.spyOn>;
85+
86+
beforeEach(async () => {
87+
back = vi.spyOn(window.history, "back").mockImplementation(() => {});
88+
testState.navigate.mockClear();
89+
testState.canGoBack = true;
90+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
91+
container = document.createElement("div");
92+
document.body.append(container);
93+
renderer = createRoot(container);
94+
await act(() => {
95+
renderer.render(<UsagePage />);
96+
});
97+
});
98+
99+
afterEach(async () => {
100+
await act(() => renderer.unmount());
101+
container.remove();
102+
back.mockRestore();
103+
vi.unstubAllGlobals();
104+
});
105+
106+
function escape(properties: { repeat?: boolean; isComposing?: boolean } = {}) {
107+
return new KeyboardEvent("keydown", {
108+
bubbles: true,
109+
cancelable: true,
110+
key: "Escape",
111+
...properties,
112+
});
113+
}
114+
115+
it("returns to the previous page on Escape", () => {
116+
document.body.dispatchEvent(escape());
117+
expect(back).toHaveBeenCalledOnce();
118+
expect(testState.navigate).not.toHaveBeenCalled();
119+
});
120+
121+
it("returns home when there is no previous app page", async () => {
122+
testState.canGoBack = false;
123+
await act(() => renderer.render(<UsagePage />));
124+
125+
document.body.dispatchEvent(escape());
126+
expect(testState.navigate).toHaveBeenCalledWith({ to: "/" });
127+
expect(back).not.toHaveBeenCalled();
128+
});
129+
130+
it("closes the environment menu before Escape navigates back", async () => {
131+
const trigger = container.querySelector<HTMLButtonElement>('[data-slot="menu-trigger"]')!;
132+
await act(() => trigger.click());
133+
expect(document.querySelector('[role="menu"]')).not.toBeNull();
134+
135+
await act(() => {
136+
document.activeElement!.dispatchEvent(escape());
137+
});
138+
expect(trigger.getAttribute("aria-expanded")).toBe("false");
139+
expect(back).not.toHaveBeenCalled();
140+
141+
document.body.dispatchEvent(escape());
142+
expect(back).toHaveBeenCalledOnce();
143+
});
144+
145+
it.each([{ repeat: true }, { isComposing: true }])("ignores Escape with %j", (properties) => {
146+
document.body.dispatchEvent(escape(properties));
147+
expect(back).not.toHaveBeenCalled();
148+
expect(testState.navigate).not.toHaveBeenCalled();
149+
});
150+
});
151+
152+
// @vitest-environment jsdom

0 commit comments

Comments
 (0)