@devries-cameron20 / t3code Mirror · read-only / commits / 054337764a
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 08:00 UTC

refactor(web): move ChatView's keyboard shortcuts into a command map (#20393)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 16, 2026 at 17:43 UTC 054337764ae8cbb4cb2ba373f2335e8c1e2aefee
6 files changed +300 -413
apps/web/reactCompiledFiles.ts
+2
@@ -7,6 +7,8 @@
7 export const REACT_COMPILED_FILES = [
8 "apps/web/src/components/PersistentThreadTerminals.tsx",
9 "apps/web/src/components/chat/usePendingThreadRequests.ts",
10 + "apps/web/src/components/chat/composerFocusRedirect.ts",
11 + "apps/web/src/components/chat/useChatShortcuts.ts",
12 "apps/web/src/components/chat/useQueuedRunEdit.ts",
13 "apps/web/src/components/chat/useUsageLimitsPanel.ts",
14 "apps/web/src/components/chat/useWorktreeSetup.ts",
apps/web/src/components/ChatView.tsx
+116 -404
@@ -38,6 +38,14 @@ import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits";
38 import { feedbackBannerItem } from "./chat/ComposerFeedback";
39 import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";
40 import { useWorktreeSetup } from "./chat/useWorktreeSetup";
41 +import { useChatShortcuts, type ChatShortcutHandler } from "./chat/useChatShortcuts";
42 +import {
43 + eventPathContainsSelector,
44 + pasteTextToFocusComposer,
45 + shouldRedirectInputToComposer,
46 + TYPE_TO_FOCUS_EDITABLE_SELECTOR,
47 + TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
48 +} from "./chat/composerFocusRedirect";
49 import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
50 import * as Schema from "effect/Schema";
51 import {
@@ -74,7 +82,6 @@ import {
82 RuntimeMode,
83 } from "@t3tools/contracts";
84 import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
77 -import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
85 import {
86 wasBootstrapThreadDeleted,
87 wasBootstrapThreadNotCreated,
@@ -202,8 +209,6 @@ import {
209 DEFAULT_THREAD_TERMINAL_ID,
210 MAX_TERMINALS_PER_GROUP,
211 type ChatMessage,
205 - isBrowserPreviewAttachment,
206 - isImageAttachment,
212 type SessionPhase,
213 type Thread,
214 } from "../types";
@@ -267,7 +272,7 @@ import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";
272 import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";
273 import { isEditableFocused } from "../lib/editableFocus";
274 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
270 -import { resolveChatShortcutCommand, shortcutLabelForCommand } from "../keybindings";
275 +import { shortcutLabelForCommand } from "../keybindings";
276 import {
277 PersistentThreadTerminalDrawer,
278 PersistentThreadTerminalPanel,
@@ -324,13 +329,9 @@ import {
329 getComposerPromptInjectionState,
330 getComposerProviderState,
331 } from "./chat/composerProviderState";
327 -import { confirmTerminalClose, isTerminalCloseConfirmPending } from "../lib/terminalCloseConfirm";
332 +import { confirmTerminalClose } from "../lib/terminalCloseConfirm";
333 import { isPreviewFocused } from "../lib/previewFocus";
334 import { getTerminalFocusOwner } from "../lib/terminalFocus";
330 -import {
331 - preventRepeatedTerminalCloseShortcut,
332 - preventTerminalCloseShortcut,
333 -} from "../lib/terminalCloseShortcut";
335 import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
336 import {
337 deriveLogicalProjectKeyFromSettings,
@@ -662,85 +663,12 @@ const DevicePanel = lazy(() =>
663 );
664 const FilePreviewPanel = lazy(() => import("./files/FilePreviewPanel"));
665 const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet<string> = new Set();
665 -const TYPE_TO_FOCUS_EDITABLE_SELECTOR = [
666 - "input",
667 - "textarea",
668 - "select",
669 - '[contenteditable="true"]',
670 - '[contenteditable="plaintext-only"]',
671 - '[role="textbox"]',
672 -].join(",");
673 -const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [
674 - "button",
675 - "a[href]",
676 - "summary",
677 - '[role="button"]',
678 - '[role="checkbox"]',
679 - '[role="menuitem"]',
680 - '[role="option"]',
681 - '[role="radio"]',
682 - '[role="switch"]',
683 - '[role="tab"]',
684 -].join(",");
685 -// Popups match only while open or closing: some stay mounted when closed,
686 -// such as the chat header actions menu.
687 -const TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR = [
688 - '[role="dialog"][aria-modal="true"]',
689 - '[data-slot="alert-dialog-popup"]:is([data-open],[data-ending-style])',
690 - '[data-slot="command-dialog-popup"]:is([data-open],[data-ending-style])',
691 - '[data-slot="dialog-popup"]:is([data-open],[data-ending-style])',
692 - '[data-slot="sheet-popup"]:is([data-open],[data-ending-style])',
693 - '[data-slot="sidebar"][data-mobile="true"]:is([data-open],[data-ending-style])',
694 - '[data-slot="menu-popup"]:is([data-open],[data-ending-style])',
695 - '[data-slot="select-popup"]:is([data-open],[data-ending-style])',
696 - '[data-slot="popover-popup"]:is([data-open],[data-ending-style])',
697 - '[data-slot="combobox-popup"]:is([data-open],[data-ending-style])',
698 - '[data-slot="autocomplete-popup"]:is([data-open],[data-ending-style])',
699 -].join(",");
700 -
666 type EnvironmentUnavailableState = {
667 readonly environmentId: EnvironmentId;
668 readonly label: string;
669 readonly connection: EnvironmentConnectionPresentation;
670 };
671
707 -function eventPathContainsSelector(event: Event, selector: string): boolean {
708 - const path = event.composedPath();
709 - if (path.length === 0 && event.target) {
710 - path.push(event.target);
711 - }
712 - return path.some((target) => target instanceof Element && target.closest(selector));
713 -}
714 -
715 -const SECRET_REQUEST_SELECTOR = '[data-v2-item-type="secret_request"]';
716 -
717 -function shouldRedirectInputToComposer(event: Event): boolean {
718 - if (event.defaultPrevented) return false;
719 - // Near a pending secret request, input is meant for its private field: it
720 - // must never land in the composer draft, which is persisted and sent.
721 - if (eventPathContainsSelector(event, SECRET_REQUEST_SELECTOR)) return false;
722 - if (eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false;
723 - if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
724 - if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;
725 - return true;
726 -}
727 -
728 -function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
729 - if (event.isComposing) return false;
730 - if (event.metaKey || event.ctrlKey || event.altKey) return false;
731 - if (event.key.length !== 1) return false;
732 - if (!shouldRedirectInputToComposer(event)) return false;
733 -
734 - return true;
735 -}
736 -
737 -function pasteTextToFocusComposer(event: ClipboardEvent): string | null {
738 - if (!event.clipboardData || event.clipboardData.files.length > 0) return null;
739 - if (!shouldRedirectInputToComposer(event)) return null;
740 - const text = event.clipboardData.getData("text/plain");
741 - return text.length > 0 ? text : null;
742 -}
743 -
672 // Kept per route so a send in flight, and the multiple-model selections, survive
673 // ChatView remounting while the user navigates.
674 const draftFanoutSelectionsAtom = Atom.family((_routeKey: string) =>
@@ -6069,229 +5997,112 @@ export default function ChatView(props: ChatViewProps) {
5997 const closeThreadFind = () => threadFindControlsRef.current?.close();
5998 const closeThreadFindStable = useStableCallback(closeThreadFind);
5999
6072 - useEffect(() => {
6073 - const handler = (event: globalThis.KeyboardEvent) => {
6074 - if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
6075 - event.stopPropagation();
6076 - return;
6077 - }
6078 - if (isThreadFindActive && event.key === "Escape") return;
6079 - if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {
6080 - event.stopPropagation();
6081 - return;
6082 - }
6083 - if (!activeThreadId || isCommandPaletteOpen()) {
6084 - return;
6085 - }
6086 - const terminalFocusOwner = getTerminalFocusOwner();
6087 - if (event.defaultPrevented && terminalFocusOwner === null) {
6088 - return;
6089 - }
6090 - const shortcutContext = getShortcutContextStable(event.target);
6091 -
6092 - if (
6093 - !shortcutContext.terminalFocus &&
6094 - !shortcutContext.modelPickerOpen &&
6095 - shouldTypeToFocusComposer(event)
6096 - ) {
6097 - if (composerRef.current?.insertTextAtEnd(event.key)) {
6098 - event.preventDefault();
6099 - event.stopPropagation();
6100 - return;
6101 - }
6102 - }
6103 -
6104 - const command = resolveChatShortcutCommand(event, keybindings, scriptKeybindings, {
6105 - context: shortcutContext,
6106 - });
6107 - if (!command) return;
6108 -
6109 - if (command === "thread.copyReference") {
6110 - event.preventDefault();
6111 - event.stopPropagation();
6000 + const toastPinFailure = (title: string) => (result: AtomCommandResult<unknown, unknown>) => {
6001 + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
6002 + const error = squashAtomCommandFailure(result);
6003 + toastManager.add(
6004 + stackedThreadToast({
6005 + type: "error",
6006 + title,
6007 + description: error instanceof Error ? error.message : "An error occurred.",
6008 + }),
6009 + );
6010 + };
6011 + const openTerminalIfClosed = () => {
6012 + if (!terminalUiState.terminalOpen) setTerminalOpenStable(true);
6013 + };
6014 + const openComposerControl = (command: Parameters<ChatComposerHandle["openControl"]>[0]) =>
6015 + (({ event }) => {
6016 + if (!event.repeat) composerRef.current?.openControl(command);
6017 + }) satisfies ChatShortcutHandler;
6018 + useChatShortcuts({
6019 + enabled: activeThreadId !== null,
6020 + keybindings,
6021 + scriptKeybindings,
6022 + getShortcutContext: getShortcutContextStable,
6023 + threadFindActive: isThreadFindActive,
6024 + typeIntoComposer: (key) => composerRef.current?.insertTextAtEnd(key) === true,
6025 + closeThreadFind: () => {
6026 + closeThreadFindStable();
6027 + focusComposerStable();
6028 + },
6029 + commands: {
6030 + "thread.copyReference": ({ event }) => {
6031 if (!event.repeat) copyActiveThreadReferenceStable();
6113 - return;
6114 - }
6115 -
6116 - if (command === "thread.settle") {
6117 - if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
6118 - event.preventDefault();
6119 - event.stopPropagation();
6032 + },
6033 + "thread.settle": () => {
6034 + if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
6035 if (!isServerThread || !activeThreadRef || !supportsSettlement) return;
6036 if (activeThreadSettled) {
6037 void handleUnsettleActiveThreadStable();
6038 return;
6039 }
6040 if (settleAndAdvance(activeThreadRef)) return;
6126 -
6127 - void settleThread(activeThreadRef).then((result) => {
6128 - if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
6129 - const error = squashAtomCommandFailure(result);
6130 - toastManager.add(
6131 - stackedThreadToast({
6132 - type: "error",
6133 - title: "Failed to settle thread",
6134 - description: error instanceof Error ? error.message : "An error occurred.",
6135 - }),
6136 - );
6137 - });
6138 - return;
6139 - }
6140 -
6141 - if (command === "thread.pin") {
6142 - if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
6143 - event.preventDefault();
6144 - event.stopPropagation();
6041 + void settleThread(activeThreadRef).then(toastPinFailure("Failed to settle thread"));
6042 + },
6043 + "thread.pin": () => {
6044 + if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
6045 if (!isServerThread || !activeThreadRef || !supportsPinning) return;
6146 - const pinned = activeThreadPinned;
6147 - void (pinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef)).then(
6148 - (result) => {
6149 - if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
6150 - const error = squashAtomCommandFailure(result);
6151 - toastManager.add(
6152 - stackedThreadToast({
6153 - type: "error",
6154 - title: pinned ? "Failed to unpin thread" : "Failed to pin thread",
6155 - description: error instanceof Error ? error.message : "An error occurred.",
6156 - }),
6157 - );
6158 - },
6046 + void (
6047 + activeThreadPinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef)
6048 + ).then(
6049 + toastPinFailure(activeThreadPinned ? "Failed to unpin thread" : "Failed to pin thread"),
6050 );
6160 - return;
6161 - }
6162 -
6163 - if (command === "terminal.toggle") {
6164 - if (!terminalUiState.terminalOpen && !canReadTerminal && !canOperateTerminal) return;
6165 - event.preventDefault();
6166 - event.stopPropagation();
6051 + },
6052 + "terminal.toggle": () => {
6053 + if (!terminalUiState.terminalOpen && !canReadTerminal && !canOperateTerminal) return false;
6054 toggleTerminalVisibilityStable();
6168 - return;
6169 - }
6170 -
6171 - if (command === "chat.find" && isServerThread && serverConfig?.threadFind === true) {
6172 - event.preventDefault();
6173 - event.stopPropagation();
6055 + },
6056 + "chat.find": () => {
6057 + if (!isServerThread || serverConfig?.threadFind !== true) return false;
6058 openThreadFindStable();
6175 - return;
6176 - }
6177 -
6178 - if (command === "rightPanel.toggle") {
6179 - event.preventDefault();
6180 - event.stopPropagation();
6181 - toggleRightPanelStable();
6182 - return;
6183 - }
6184 -
6185 - if (command === "rightPanel.toggleMaximized") {
6186 - event.preventDefault();
6187 - event.stopPropagation();
6059 + },
6060 + "rightPanel.toggle": () => toggleRightPanelStable(),
6061 + "rightPanel.toggleMaximized": ({ event }) => {
6062 if (!event.repeat) toggleRightPanelMaximizedStable();
6189 - return;
6190 - }
6191 -
6192 - if (command === "threadPanel.toggle") {
6193 - event.preventDefault();
6194 - event.stopPropagation();
6195 - toggleThreadPanelStable();
6196 - return;
6197 - }
6198 -
6199 - if (command === "rightPanel.close") {
6200 - if (!activeRightPanelSurface) return;
6201 - event.preventDefault();
6202 - event.stopPropagation();
6063 + },
6064 + "threadPanel.toggle": () => toggleThreadPanelStable(),
6065 + "rightPanel.close": ({ event }) => {
6066 + if (!activeRightPanelSurface) return false;
6067 if (!event.repeat) closeRightPanelSurfaceStable(activeRightPanelSurface);
6204 - return;
6205 - }
6206 -
6207 - if (command === "terminal.split") {
6208 - if (!canOperateTerminal) return;
6209 - event.preventDefault();
6210 - event.stopPropagation();
6211 - if (terminalFocusOwner === "right-panel") {
6212 - splitPanelTerminalStable();
6213 - return;
6214 - }
6215 - if (!terminalUiState.terminalOpen) {
6216 - setTerminalOpenStable(true);
6217 - }
6068 + },
6069 + "terminal.split": ({ terminalFocusOwner }) => {
6070 + if (!canOperateTerminal) return false;
6071 + if (terminalFocusOwner === "right-panel") return void splitPanelTerminalStable();
6072 + openTerminalIfClosed();
6073 splitTerminalStable();
6219 - return;
6220 - }
6221 -
6222 - if (command === "terminal.splitVertical") {
6223 - if (!canOperateTerminal) return;
6224 - event.preventDefault();
6225 - event.stopPropagation();
6226 - if (terminalFocusOwner === "right-panel") {
6227 - splitPanelTerminalStable("vertical");
6228 - return;
6229 - }
6230 - if (!terminalUiState.terminalOpen) {
6231 - setTerminalOpenStable(true);
6232 - }
6074 + },
6075 + "terminal.splitVertical": ({ terminalFocusOwner }) => {
6076 + if (!canOperateTerminal) return false;
6077 + if (terminalFocusOwner === "right-panel") return void splitPanelTerminalStable("vertical");
6078 + openTerminalIfClosed();
6079 splitTerminalStable("vertical");
6234 - return;
6235 - }
6236 -
6237 - if (command === "terminal.close") {
6238 - if (!canOperateTerminal) return;
6239 - event.preventDefault();
6240 - event.stopPropagation();
6080 + },
6081 + "terminal.close": ({ terminalFocusOwner }) => {
6082 + if (!canOperateTerminal) return false;
6083 if (terminalFocusOwner === "right-panel" && activeRightPanelSurface?.kind === "terminal") {
6084 requestClosePanelTerminalStable(activeRightPanelSurface.activeTerminalId);
6085 return;
6086 }
6245 - if (!terminalUiState.terminalOpen) return;
6246 - requestCloseTerminalStable(terminalUiState.activeTerminalId);
6247 - return;
6248 - }
6249 -
6250 - if (command === "terminal.new") {
6251 - if (!canOperateTerminal) return;
6252 - event.preventDefault();
6253 - event.stopPropagation();
6254 - if (terminalFocusOwner === "right-panel") {
6255 - addTerminalSurfaceStable();
6256 - return;
6257 - }
6258 - if (!terminalUiState.terminalOpen) {
6259 - setTerminalOpenStable(true);
6260 - }
6087 + if (terminalUiState.terminalOpen)
6088 + requestCloseTerminalStable(terminalUiState.activeTerminalId);
6089 + },
6090 + "terminal.new": ({ terminalFocusOwner }) => {
6091 + if (!canOperateTerminal) return false;
6092 + if (terminalFocusOwner === "right-panel") return void addTerminalSurfaceStable();
6093 + openTerminalIfClosed();
6094 createNewTerminalStable();
6262 - return;
6263 - }
6264 -
6265 - if (command === "diff.toggle") {
6266 - event.preventDefault();
6267 - event.stopPropagation();
6268 - onToggleDiffStable();
6269 - return;
6270 - }
6271 -
6272 - if (command === "modelPicker.toggle") {
6273 - event.preventDefault();
6274 - event.stopPropagation();
6095 + },
6096 + "diff.toggle": () => onToggleDiffStable(),
6097 + "modelPicker.toggle": ({ event }) => {
6098 if (!event.repeat) composerRef.current?.toggleModelPicker();
6276 - return;
6277 - }
6278 -
6279 - if (
6280 - command === "composer.host" ||
6281 - command === "composer.effort" ||
6282 - command === "composer.mode" ||
6283 - command === "composer.workspace"
6284 - ) {
6285 - event.preventDefault();
6286 - event.stopPropagation();
6287 - if (!event.repeat) composerRef.current?.openControl(command);
6288 - return;
6289 - }
6290 -
6291 - if (command === "composer.cycleHost") {
6292 - if (envLocked || !draftId || !hasMultipleEnvironments) return;
6293 - event.preventDefault();
6294 - event.stopPropagation();
6099 + },
6100 + "composer.host": openComposerControl("composer.host"),
6101 + "composer.effort": openComposerControl("composer.effort"),
6102 + "composer.mode": openComposerControl("composer.mode"),
6103 + "composer.workspace": openComposerControl("composer.workspace"),
6104 + "composer.cycleHost": ({ event }) => {
6105 + if (envLocked || !draftId || !hasMultipleEnvironments) return false;
6106 if (event.repeat) return;
6107 const currentId = environmentChangeRef.current?.environmentId ?? environmentId;
6108 const index = logicalProjectEnvironments.findIndex(
@@ -6299,130 +6110,31 @@ export default function ChatView(props: ChatViewProps) {
6110 );
6111 const next = logicalProjectEnvironments[(index + 1) % logicalProjectEnvironments.length];
6112 if (next) onEnvironmentChangeStable(next.environmentId);
6302 - return;
6303 - }
6304 -
6305 - if (command === "composer.branch") {
6306 - event.preventDefault();
6307 - event.stopPropagation();
6113 + },
6114 + "composer.branch": ({ event }) => {
6115 if (!event.repeat) branchToolbarRef.current?.openBranchPicker();
6309 - return;
6310 - }
6311 -
6312 - if (command === "composer.previousWorktree") {
6313 - event.preventDefault();
6314 - event.stopPropagation();
6116 + },
6117 + "composer.previousWorktree": ({ event }) => {
6118 if (!event.repeat) branchToolbarRef.current?.usePreviousWorktree();
6316 - return;
6317 - }
6318 -
6319 - if (command === "thread.steerQueuedMessage") {
6320 - if (routeKind === "draft") return;
6321 - if (!queuedRunsControlRef.current?.steerNext(event.repeat)) return;
6322 - event.preventDefault();
6323 - event.stopPropagation();
6324 - return;
6325 - }
6326 -
6327 - if (command === "thread.editQueuedMessage") {
6328 - if (routeKind === "draft") return;
6329 - if (!composerRef.current?.isCaretAtStart()) return;
6330 - if (!queuedRunsControlRef.current?.editLatest(event.repeat)) return;
6331 - event.preventDefault();
6332 - event.stopPropagation();
6333 - return;
6334 - }
6335 -
6336 - if (command === "thread.stop") {
6337 - if (!canInterruptRunningThread) return;
6338 - event.preventDefault();
6339 - event.stopPropagation();
6340 - if (event.repeat) return;
6341 - void onInterruptStable();
6342 - return;
6343 - }
6344 -
6119 + },
6120 + "thread.steerQueuedMessage": ({ event }) =>
6121 + routeKind !== "draft" && queuedRunsControlRef.current?.steerNext(event.repeat) === true,
6122 + "thread.editQueuedMessage": ({ event }) =>
6123 + routeKind !== "draft" &&
6124 + composerRef.current?.isCaretAtStart() === true &&
6125 + queuedRunsControlRef.current?.editLatest(event.repeat) === true,
6126 + "thread.stop": ({ event }) => {
6127 + if (!canInterruptRunningThread) return false;
6128 + if (!event.repeat) void onInterruptStable();
6129 + },
6130 + },
6131 + fallback: (command) => {
6132 const scriptId = projectScriptIdFromCommand(command);
6346 - if (!scriptId || !activeProject || !canOperateTerminal) return;
6133 + if (!scriptId || !activeProject || !canOperateTerminal) return undefined;
6134 const script = activeProjectScripts.find((entry) => entry.id === scriptId);
6348 - if (!script) return;
6349 - event.preventDefault();
6350 - event.stopPropagation();
6351 - void runProjectScriptStable(script);
6352 - };
6353 - const dismissFind = (event: KeyboardEvent) => {
6354 - if (
6355 - event.key !== "Escape" ||
6356 - !isThreadFindActive ||
6357 - event.defaultPrevented ||
6358 - event.isComposing ||
6359 - event.keyCode === 229 ||
6360 - isCommandPaletteOpen()
6361 - )
6362 - return;
6363 - const context = getShortcutContextStable(event.target);
6364 - if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return;
6365 - event.preventDefault();
6366 - closeThreadFindStable();
6367 - focusComposerStable();
6368 - };
6369 - window.addEventListener("keydown", handler, true);
6370 - window.addEventListener("keydown", dismissFind);
6371 - return () => {
6372 - window.removeEventListener("keydown", handler, true);
6373 - window.removeEventListener("keydown", dismissFind);
6374 - };
6375 - }, [
6376 - activeProject,
6377 - activeRightPanelSurface,
6378 - activeProjectScripts,
6379 - canReadTerminal,
6380 - canOperateTerminal,
6381 - addTerminalSurfaceStable,
6382 - activeThreadRef,
6383 - activeThreadPinned,
6384 - activeThreadSettled,
6385 - canInterruptRunningThread,
6386 - terminalUiState.terminalOpen,
6387 - terminalUiState.activeTerminalId,
6388 - activeThreadId,
6389 - closeRightPanelSurfaceStable,
6390 - requestCloseTerminalStable,
6391 - requestClosePanelTerminalStable,
6392 - createNewTerminalStable,
6393 - setTerminalOpenStable,
6394 - runProjectScriptStable,
6395 - splitTerminalStable,
6396 - splitPanelTerminalStable,
6397 - keybindings,
6398 - scriptKeybindings,
6399 - handleUnsettleActiveThreadStable,
6400 - isServerThread,
6401 - serverConfig?.threadFind,
6402 - onInterruptStable,
6403 - onToggleDiffStable,
6404 - pinThread,
6405 - settleThread,
6406 - supportsPinning,
6407 - supportsSettlement,
6408 - confirmAndUnpinThread,
6409 - copyActiveThreadReferenceStable,
6410 - getShortcutContextStable,
6411 - openThreadFindStable,
6412 - closeThreadFindStable,
6413 - isThreadFindActive,
6414 - toggleRightPanelStable,
6415 - toggleRightPanelMaximizedStable,
6416 - toggleThreadPanelStable,
6417 - toggleTerminalVisibilityStable,
6418 - composerRef,
6419 - draftId,
6420 - environmentId,
6421 - envLocked,
6422 - hasMultipleEnvironments,
6423 - logicalProjectEnvironments,
6424 - onEnvironmentChangeStable,
6425 - ]);
6135 + return script ? () => void runProjectScriptStable(script) : undefined;
6136 + },
6137 + });
6138
6139 // A focused desktop browser page forwards these chords as menu actions.
6140 useEffect(() => {
apps/web/src/components/chat/composerFocusRedirect.ts new
+75
@@ -0,0 +1,75 @@
1 +// Type-to-focus: printable keys and pastes that land on no editable target go to
2 +// the composer, so the user can start typing anywhere in the chat.
3 +
4 +export const TYPE_TO_FOCUS_EDITABLE_SELECTOR = [
5 + "input",
6 + "textarea",
7 + "select",
8 + '[contenteditable="true"]',
9 + '[contenteditable="plaintext-only"]',
10 + '[role="textbox"]',
11 +].join(",");
12 +const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [
13 + "button",
14 + "a[href]",
15 + "summary",
16 + '[role="button"]',
17 + '[role="checkbox"]',
18 + '[role="menuitem"]',
19 + '[role="option"]',
20 + '[role="radio"]',
21 + '[role="switch"]',
22 + '[role="tab"]',
23 +].join(",");
24 +// Popups match only while open or closing: some stay mounted when closed,
25 +// such as the chat header actions menu.
26 +export const TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR = [
27 + '[role="dialog"][aria-modal="true"]',
28 + '[data-slot="alert-dialog-popup"]:is([data-open],[data-ending-style])',
29 + '[data-slot="command-dialog-popup"]:is([data-open],[data-ending-style])',
30 + '[data-slot="dialog-popup"]:is([data-open],[data-ending-style])',
31 + '[data-slot="sheet-popup"]:is([data-open],[data-ending-style])',
32 + '[data-slot="sidebar"][data-mobile="true"]:is([data-open],[data-ending-style])',
33 + '[data-slot="menu-popup"]:is([data-open],[data-ending-style])',
34 + '[data-slot="select-popup"]:is([data-open],[data-ending-style])',
35 + '[data-slot="popover-popup"]:is([data-open],[data-ending-style])',
36 + '[data-slot="combobox-popup"]:is([data-open],[data-ending-style])',
37 + '[data-slot="autocomplete-popup"]:is([data-open],[data-ending-style])',
38 +].join(",");
39 +
40 +export function eventPathContainsSelector(event: Event, selector: string): boolean {
41 + const path = event.composedPath();
42 + if (path.length === 0 && event.target) {
43 + path.push(event.target);
44 + }
45 + return path.some((target) => target instanceof Element && target.closest(selector));
46 +}
47 +
48 +const SECRET_REQUEST_SELECTOR = '[data-v2-item-type="secret_request"]';
49 +
50 +export function shouldRedirectInputToComposer(event: Event): boolean {
51 + if (event.defaultPrevented) return false;
52 + // Near a pending secret request, input is meant for its private field: it
53 + // must never land in the composer draft, which is persisted and sent.
54 + if (eventPathContainsSelector(event, SECRET_REQUEST_SELECTOR)) return false;
55 + if (eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false;
56 + if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
57 + if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;
58 + return true;
59 +}
60 +
61 +export function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
62 + if (event.isComposing) return false;
63 + if (event.metaKey || event.ctrlKey || event.altKey) return false;
64 + if (event.key.length !== 1) return false;
65 + if (!shouldRedirectInputToComposer(event)) return false;
66 +
67 + return true;
68 +}
69 +
70 +export function pasteTextToFocusComposer(event: ClipboardEvent): string | null {
71 + if (!event.clipboardData || event.clipboardData.files.length > 0) return null;
72 + if (!shouldRedirectInputToComposer(event)) return null;
73 + const text = event.clipboardData.getData("text/plain");
74 + return text.length > 0 ? text : null;
75 +}
apps/web/src/components/chat/useChatShortcuts.ts new
+106
@@ -0,0 +1,106 @@
1 +import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2 +import { useEffect, useLayoutEffect, useRef } from "react";
3 +import { isCommandPaletteOpen } from "../../commandPaletteBus";
4 +import { resolveChatShortcutCommand, type ShortcutMatchContext } from "../../keybindings";
5 +import { isTerminalCloseConfirmPending } from "../../lib/terminalCloseConfirm";
6 +import {
7 + preventRepeatedTerminalCloseShortcut,
8 + preventTerminalCloseShortcut,
9 +} from "../../lib/terminalCloseShortcut";
10 +import { getTerminalFocusOwner, type TerminalFocusOwner } from "../../lib/terminalFocus";
11 +import { shouldTypeToFocusComposer } from "./composerFocusRedirect";
12 +
13 +/** Runs a command. Returning false lets the key event through untouched. */
14 +export type ChatShortcutHandler = (context: {
15 + readonly event: KeyboardEvent;
16 + readonly terminalFocusOwner: TerminalFocusOwner | null;
17 +}) => boolean | void;
18 +
19 +export interface ChatShortcutsInput {
20 + readonly enabled: boolean;
21 + readonly keybindings: ResolvedKeybindingsConfig;
22 + readonly scriptKeybindings: ResolvedKeybindingsConfig;
23 + readonly getShortcutContext: (target: EventTarget | null) => ShortcutMatchContext & {
24 + readonly modelPickerOpen: boolean;
25 + };
26 + readonly threadFindActive: boolean;
27 + /** Types a printable key into the composer; false when it could not take it. */
28 + readonly typeIntoComposer: (key: string) => boolean;
29 + readonly closeThreadFind: () => void;
30 + readonly commands: Partial<Record<KeybindingCommand, ChatShortcutHandler>>;
31 + /** Handles commands not in `commands`, such as project scripts. */
32 + readonly fallback: (command: KeybindingCommand) => ChatShortcutHandler | undefined;
33 +}
34 +
35 +/**
36 + * The chat's window keyboard shortcuts, plus Escape closing thread find.
37 + * Listeners attach once and read the latest input on each event, so handlers
38 + * act on the current render without re-registering on every change.
39 + */
40 +export function useChatShortcuts(input: ChatShortcutsInput) {
41 + const latest = useRef(input);
42 + useLayoutEffect(() => {
43 + latest.current = input;
44 + });
45 + useEffect(() => {
46 + const handler = (event: KeyboardEvent) => {
47 + const current = latest.current;
48 + const { keybindings } = current;
49 + if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
50 + event.stopPropagation();
51 + return;
52 + }
53 + if (current.threadFindActive && event.key === "Escape") return;
54 + if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {
55 + event.stopPropagation();
56 + return;
57 + }
58 + if (!current.enabled || isCommandPaletteOpen()) return;
59 + const terminalFocusOwner = getTerminalFocusOwner();
60 + if (event.defaultPrevented && terminalFocusOwner === null) return;
61 + const shortcutContext = current.getShortcutContext(event.target);
62 +
63 + if (
64 + !shortcutContext.terminalFocus &&
65 + !shortcutContext.modelPickerOpen &&
66 + shouldTypeToFocusComposer(event) &&
67 + current.typeIntoComposer(event.key)
68 + ) {
69 + event.preventDefault();
70 + event.stopPropagation();
71 + return;
72 + }
73 +
74 + const command = resolveChatShortcutCommand(event, keybindings, current.scriptKeybindings, {
75 + context: shortcutContext,
76 + });
77 + if (!command) return;
78 + const run = current.commands[command] ?? current.fallback(command);
79 + if (!run || run({ event, terminalFocusOwner }) === false) return;
80 + event.preventDefault();
81 + event.stopPropagation();
82 + };
83 + const dismissFind = (event: KeyboardEvent) => {
84 + const current = latest.current;
85 + if (
86 + event.key !== "Escape" ||
87 + !current.threadFindActive ||
88 + event.defaultPrevented ||
89 + event.isComposing ||
90 + event.keyCode === 229 ||
91 + isCommandPaletteOpen()
92 + )
93 + return;
94 + const context = current.getShortcutContext(event.target);
95 + if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return;
96 + event.preventDefault();
97 + current.closeThreadFind();
98 + };
99 + window.addEventListener("keydown", handler, true);
100 + window.addEventListener("keydown", dismissFind);
101 + return () => {
102 + window.removeEventListener("keydown", handler, true);
103 + window.removeEventListener("keydown", dismissFind);
104 + };
105 + }, []);
106 +}
apps/web/src/types.ts
-9
@@ -80,15 +80,6 @@ export function isVideoAttachment(attachment: ChatFileAttachment): boolean {
80 return videoMimeType(attachment) !== null;
81 }
82
83 -export function isBrowserPreviewAttachment(attachment: ChatFileAttachment): boolean {
84 - const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase();
85 - return (
86 - /\.(?:html?|pdf)$/i.test(attachment.name) ||
87 - mimeType === "application/pdf" ||
88 - mimeType === "text/html"
89 - );
90 -}
91 -
83 export interface ChatMessage {
84 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
85 readonly id: MessageId;
packages/client-runtime/src/state/threadCommands.ts
+1
@@ -116,6 +116,7 @@ export type {
116 RespondToThreadApprovalInput,
117 RespondToThreadUserInputInput,
118 DismissThreadUserInputInput,
119 + RetryWorkspacePreparationInput,
120 RevertThreadCheckpointInput,
121 SetThreadInteractionModeInput,
122 SetThreadRuntimeModeInput,