Skip to content

Commit 8a38c63

Browse files
fix(web): thread navigation shortcuts work from the terminal and macOS composer (#26433)
1 parent 496856d commit 8a38c63

5 files changed

Lines changed: 114 additions & 3 deletions

‎apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,22 @@ import {
2626
type ComposerPromptEditorProps,
2727
} from "./ComposerPromptEditorTiptap";
2828

29+
vi.mock(import("../state/server"), async (original) => {
30+
const { Atom } = await import("effect/reactivity");
31+
const { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } =
32+
await import("@t3tools/shared/keybindings");
33+
return {
34+
...(await original()),
35+
primaryServerKeybindingsAtom: Atom.make(
36+
compileResolvedKeybindingsConfig([
37+
...DEFAULT_KEYBINDINGS,
38+
{ key: "mod+arrowup", command: "thread.previous" },
39+
{ key: "mod+arrowdown", command: "thread.next" },
40+
]),
41+
),
42+
};
43+
});
44+
2945
const babysit: ServerProviderSkill = {
3046
name: "babysit",
3147
path: "/skills/babysit/SKILL.md",
@@ -271,6 +287,29 @@ it.each([
271287
},
272288
);
273289

290+
// The mocked server keybindings bind Command-Up and Command-Down to thread navigation.
291+
it("leaves Command-arrow thread navigation bindings to the app on macOS", async () => {
292+
using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
293+
await using screen = await mountEditor("first\nsecond");
294+
const { editor } = screen;
295+
await act(async () => {
296+
editor.commands.focus("end");
297+
});
298+
await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
299+
const reachedApp: string[] = [];
300+
const onWindowKeyDown = (event: KeyboardEvent) => {
301+
if (!event.defaultPrevented && event.key.startsWith("Arrow")) reachedApp.push(event.key);
302+
};
303+
window.addEventListener("keydown", onWindowKeyDown);
304+
using _listener = {
305+
[Symbol.dispose]: () => window.removeEventListener("keydown", onWindowKeyDown),
306+
};
307+
308+
await userEvent.keyboard("{Meta>}{ArrowUp}{ArrowDown}{/Meta}");
309+
310+
expect(reachedApp).toEqual(["ArrowUp", "ArrowDown"]);
311+
});
312+
274313
it.each([
275314
["e", false, false],
276315
["i", false, false],

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,9 @@ import { collectInlineContextIds } from "~/lib/composerContextReferences";
114114
import { resolveDiffThemeName } from "~/lib/diffRendering";
115115
import { isRichTextFormattingShortcut } from "~/keybindings";
116116
import { cn, isMacPlatform } from "~/lib/utils";
117+
import { isThreadNavigationShortcut } from "~/keybindings";
118+
import { appAtomRegistry } from "~/rpc/atomRegistry";
119+
import { primaryServerKeybindingsAtom } from "~/state/server";
117120
import { hasCommandForKeyDown } from "~/shortcuts/dispatcher";
118121
import { basenameOfPath } from "~/pierre-icons";
119122
import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon";
@@ -1143,6 +1146,13 @@ function ComposerPromptEditorTiptapInner(
11431146
!event.ctrlKey &&
11441147
!event.isComposing
11451148
) {
1149+
if (
1150+
isThreadNavigationShortcut(event, appAtomRegistry.get(primaryServerKeybindingsAtom), {
1151+
context: { editableFocus: true },
1152+
})
1153+
) {
1154+
return false;
1155+
}
11461156
const selection = window.getSelection();
11471157
if (
11481158
selection?.anchorNode &&

‎apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,14 @@ import {
44
ThreadId,
55
type ScopedThreadRef,
66
type FilesystemEntryMetadata,
7+
type ResolvedKeybindingsConfig,
78
} from "@t3tools/contracts";
9+
import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings";
810
import { Atom, AsyncResult } from "effect/reactivity";
911
import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface";
1012
import { AppAtomRegistryProvider, appAtomRegistry } from "../rpc/atomRegistry";
13+
import { useRightPanelStore } from "../rightPanelStore";
14+
import { useTerminalUiStateStore } from "../terminalUiStateStore";
1115
import { extractTerminalLinks } from "../terminal-links";
1216
import { expect, it, vi } from "vite-plus/test";
1317
import { act, fakeTimers, render } from "../../test/render";
@@ -110,6 +114,7 @@ function Drawer(props: {
110114
threadRef: ScopedThreadRef;
111115
cwd?: string;
112116
onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
117+
keybindings?: ResolvedKeybindingsConfig;
113118
}) {
114119
return (
115120
<ThreadTerminalDrawer
@@ -128,7 +133,7 @@ function Drawer(props: {
128133
onCloseTerminal={props.onCloseTerminal}
129134
onHeightChange={() => {}}
130135
onAddTerminalContext={() => {}}
131-
keybindings={[]}
136+
keybindings={props.keybindings ?? []}
132137
/>
133138
);
134139
}
@@ -149,6 +154,8 @@ function setup() {
149154
fixture.pendingSurfaces = [];
150155
fixture.surfaceOptions = [];
151156
fixture.metadata.clear();
157+
useRightPanelStore.setState(useRightPanelStore.getInitialState());
158+
useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState());
152159
return { original, other };
153160
}
154161

@@ -170,6 +177,42 @@ it("closes an exited terminal on its own thread after navigating to one reusing
170177
expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]);
171178
});
172179

180+
// Thread navigation defaults have no `!terminalFocus`, so they apply in a focused terminal.
181+
it("hands thread navigation shortcuts from a focused terminal back to the app", async () => {
182+
const { other: threadRef } = setup();
183+
using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
184+
useRightPanelStore.getState().openBrowser(threadRef, null);
185+
await using _screen = await render(
186+
<Drawer
187+
threadRef={threadRef}
188+
onCloseTerminal={() => {}}
189+
keybindings={compileResolvedKeybindingsConfig([
190+
...DEFAULT_KEYBINDINGS,
191+
{ key: "ctrl+r", command: "thread.next", when: "!previewOpen" },
192+
{ key: "ctrl+g", command: "thread.previous", when: "terminalOpen" },
193+
])}
194+
/>,
195+
);
196+
await act(async () => {
197+
fixture.pendingSurfaces.shift()?.();
198+
});
199+
const terminalHandles = (key: string, code: string, shiftKey = true) =>
200+
fixture.surfaceOptions
201+
.at(-1)!
202+
.beforeKey(new KeyboardEvent("keydown", { key, code, ctrlKey: true, shiftKey }));
203+
204+
expect([terminalHandles("{", "BracketLeft"), terminalHandles("}", "BracketRight")]).toEqual([
205+
false,
206+
false,
207+
]);
208+
expect(terminalHandles("C", "KeyC")).toBe(true);
209+
// Sidebar sees the open preview and the closed drawer and rejects these, so the shell keeps them.
210+
expect([terminalHandles("r", "KeyR", false), terminalHandles("g", "KeyG", false)]).toEqual([
211+
true,
212+
true,
213+
]);
214+
});
215+
173216
it("only activates terminal paths confirmed to exist on their environment", async () => {
174217
const { other: threadRef } = setup();
175218
const key = (path: string) => JSON.stringify([threadRef.environmentId, path]);

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import {
6666
isTerminalSplitShortcut,
6767
isTerminalSplitVerticalShortcut,
6868
isTerminalToggleShortcut,
69+
isThreadNavigationShortcut,
6970
terminalDeleteShortcutData,
7071
terminalNavigationShortcutData,
7172
} from "../keybindings";
@@ -91,6 +92,7 @@ import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
9192
import { useAtomCommand } from "../state/use-atom-command";
9293
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
9394
import { observeResize } from "../lib/observeResize";
95+
import { threadShortcutContext } from "./Sidebar.logic";
9496
import {
9597
consumePendingTerminalFocus,
9698
focusTerminal,
@@ -575,6 +577,7 @@ function TerminalSessionViewport({
575577
const hasHandledExitRef = useRef(false);
576578
const selectionActionRequestIdRef = useRef(0);
577579
const readKeybindings = useEffectEvent(() => keybindings);
580+
const readThreadShortcutContext = useEffectEvent(() => threadShortcutContext(threadRef));
578581
const handleSessionExited = useEffectEvent(() => {
579582
if (hasTerminalWriteAccess()) onSessionExited();
580583
});
@@ -938,7 +941,11 @@ function TerminalSessionViewport({
938941
isTerminalSplitShortcut(event, currentKeybindings, options) ||
939942
isTerminalSplitVerticalShortcut(event, currentKeybindings, options) ||
940943
isTerminalNewShortcut(event, currentKeybindings, options) ||
941-
isDiffToggleShortcut(event, currentKeybindings, options)
944+
isDiffToggleShortcut(event, currentKeybindings, options) ||
945+
// Match Sidebar's context, or a key it will reject skips the shell.
946+
isThreadNavigationShortcut(event, currentKeybindings, {
947+
context: { ...readThreadShortcutContext(), terminalFocus: true },
948+
})
942949
) {
943950
return false;
944951
}

‎apps/web/src/keybindings.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,12 +281,24 @@ export function threadTraversalDirectionFromCommand(
281281
return null;
282282
}
283283

284+
export function isThreadNavigationShortcut(
285+
event: ShortcutEventLike,
286+
keybindings: ResolvedKeybindingsConfig,
287+
options?: ShortcutMatchOptions,
288+
): boolean {
289+
const command = resolveShortcutCommand(event, keybindings, options);
290+
return (
291+
threadTraversalDirectionFromCommand(command) !== null ||
292+
threadJumpIndexFromCommand(command ?? "") !== null
293+
);
294+
}
295+
284296
export function shouldShowThreadJumpHintsForModifiers(
285297
modifiers: ShortcutModifierStateLike,
286298
keybindings: ResolvedKeybindingsConfig,
287299
options?: ShortcutMatchOptions,
288300
): boolean {
289-
// Ghostty can write keys to the shell before window shortcuts run, regardless of the when clause.
301+
// Holding a modifier is routine in a shell (Ctrl+C, Ctrl+R), so don't flash hints over it.
290302
if (resolveContext(options).terminalFocus) {
291303
return false;
292304
}

0 commit comments

Comments
 (0)