Skip to content
TypeScript

fix(web): ⌘Z undoes a settle even when the composer has focus (#22607)

Theo Browne21da3061aa00
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx
index 89d52c87b28..311efa7e5f0 100644
--- a/apps/web/src/components/AppSidebarLayout.tsx
+++ b/apps/web/src/components/AppSidebarLayout.tsx
@@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
import * as Schema from "effect/Schema";
import {
useEffect,
+ useRef,
useState,
useSyncExternalStore,
type CSSProperties,
@@ -9,7 +10,13 @@ import {
} from "react";
import { useLocation, useNavigate } from "@tanstack/react-router";
+import { isCommandPaletteOpen } from "../commandPaletteBus";
import { isElectron } from "../env";
+import {
+ releaseThreadUndoShortcut,
+ threadUndoClaimsShortcut,
+ undoLatestThreadAction,
+} from "../hooks/showThreadUndoNotice";
import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
import {
isRichTextBoldShortcut,
@@ -199,6 +206,19 @@ function SidebarControl() {
);
}
+function routePanelsOpen(routeThreadRef: ReturnType<typeof useThreadRouteRef>) {
+ if (!routeThreadRef) return { terminalOpen: false, previewOpen: false };
+ return {
+ terminalOpen: selectThreadTerminalUiState(
+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
+ routeThreadRef,
+ ).terminalOpen,
+ previewOpen:
+ selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
+ "preview",
+ };
+}
+
function NavigationHistoryShortcuts() {
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const routeThreadRef = useThreadRouteRef();
@@ -215,17 +235,8 @@ function NavigationHistoryShortcuts() {
const command = resolveShortcutCommand(event, keybindings, {
context: {
terminalFocus: isTerminalFocused(),
- terminalOpen: routeThreadRef
- ? selectThreadTerminalUiState(
- useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
- routeThreadRef,
- ).terminalOpen
- : false,
previewFocus: isPreviewFocused(),
- previewOpen: routeThreadRef
- ? selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
- "preview"
- : false,
+ ...routePanelsOpen(routeThreadRef),
editableFocus: isEditableFocused(event.target),
modelPickerOpen: isModelPickerOpen(),
},
@@ -245,6 +256,67 @@ function NavigationHistoryShortcuts() {
return null;
}
+const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
+
+// Undoes the thread actions in the sidebar's notice. Mounted wherever the
+// thread sidebar can show; Settings replaces it. Listens in the capture phase
+// so mod+z reaches it before the composer's own undo handler consumes the key.
+function ThreadUndoShortcut() {
+ const keybindings = useAtomValue(primaryServerKeybindingsAtom);
+ const routeThreadRef = useThreadRouteRef();
+ // A collapsed sidebar hides the notice, so text fields keep their own undo.
+ const noticeVisible = useSidebarVisibility();
+ // Outlives the effect: undoing an archive navigates, which re-runs it mid-hold.
+ const heldUndoKey = useRef<string | null>(null);
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ // A held key undoes once. Cancel its repeats so they cannot fall through
+ // to the editor's own undo, even after the last notice is gone.
+ if (event.repeat) {
+ if (event.code === heldUndoKey.current) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ return;
+ }
+ // A modifier tapped mid-hold leaves the held key repeating.
+ if (!MODIFIER_KEYS.has(event.key)) heldUndoKey.current = null;
+ const command = resolveShortcutCommand(event, keybindings, {
+ context: {
+ terminalFocus: isTerminalFocused(),
+ previewFocus: isPreviewFocused(),
+ ...routePanelsOpen(routeThreadRef),
+ editableFocus:
+ isEditableFocused(event.target) && !(noticeVisible && threadUndoClaimsShortcut()),
+ modelPickerOpen: isModelPickerOpen(),
+ },
+ });
+ if (command !== "thread.undo") {
+ if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
+ return;
+ }
+ if (isCommandPaletteOpen() || isModelPickerOpen()) return;
+ if (undoLatestThreadAction()) {
+ heldUndoKey.current = event.code;
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ };
+ // Pastes from a menu, dictation and drops edit text without a keypress.
+ const onInput = () => releaseThreadUndoShortcut();
+
+ window.addEventListener("keydown", onKeyDown, true);
+ window.addEventListener("input", onInput, true);
+ return () => {
+ window.removeEventListener("keydown", onKeyDown, true);
+ window.removeEventListener("input", onInput, true);
+ };
+ }, [keybindings, noticeVisible, routeThreadRef]);
+
+ return null;
+}
+
// Settings swaps the thread sidebar out of the tree. Keep the lightweight
// project projection subscribed so returning to a draft never renders the
// zero-project state while the environment snapshot reconnects.
@@ -357,6 +429,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
{children}
<SidebarControl />
<NavigationHistoryShortcuts />
+ {isOnSettings ? null : <ThreadUndoShortcut />}
<MainAppLocationTracker />
</SidebarProvider>
</PanelAnimationSuppressionProvider>
diff --git a/apps/web/src/hooks/showThreadUndoNotice.test.ts b/apps/web/src/hooks/showThreadUndoNotice.test.ts
index dd50f5dbde4..568e4cc70ae 100644
--- a/apps/web/src/hooks/showThreadUndoNotice.test.ts
+++ b/apps/web/src/hooks/showThreadUndoNotice.test.ts
@@ -2,7 +2,12 @@ import { AsyncResult } from "effect/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { toastManager } from "../components/ui/toast";
-import { showThreadUndoNotice, useThreadUndoNotice } from "./showThreadUndoNotice";
+import {
+ releaseThreadUndoShortcut,
+ showThreadUndoNotice,
+ threadUndoClaimsShortcut,
+ useThreadUndoNotice,
+} from "./showThreadUndoNotice";
import * as ThreadUndo from "./threadUndo";
beforeEach(() => vi.useFakeTimers());
@@ -39,4 +44,25 @@ describe("thread undo notice", () => {
await notice().undo();
expect(undo).toHaveBeenCalledOnce();
});
+
+ it("claims mod+z from text fields until the user types, then again for a new notice", () => {
+ const { options } = setup();
+ expect(threadUndoClaimsShortcut()).toBe(false);
+ showThreadUndoNotice(options);
+ expect(threadUndoClaimsShortcut()).toBe(true);
+ releaseThreadUndoShortcut();
+ expect(threadUndoClaimsShortcut()).toBe(false);
+ showThreadUndoNotice({ ...options, claim: ThreadUndo.begin("pin", "env/next") });
+ expect(threadUndoClaimsShortcut()).toBe(true);
+ });
+
+ it("stops claiming mod+z once nothing is left to undo", async () => {
+ const { options } = setup();
+ showThreadUndoNotice(options);
+ await notice().undo();
+ expect(threadUndoClaimsShortcut()).toBe(false);
+ showThreadUndoNotice({ ...options, claim: ThreadUndo.begin("pin", "env/expiring") });
+ vi.advanceTimersByTime(5_000);
+ expect(threadUndoClaimsShortcut()).toBe(false);
+ });
});
diff --git a/apps/web/src/hooks/showThreadUndoNotice.ts b/apps/web/src/hooks/showThreadUndoNotice.ts
index c6124ba0372..2e430a906e3 100644
--- a/apps/web/src/hooks/showThreadUndoNotice.ts
+++ b/apps/web/src/hooks/showThreadUndoNotice.ts
@@ -26,6 +26,9 @@ export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => (
let liveUndos: UndoOptions[] = [];
let expiry: ReturnType<typeof setTimeout> | undefined;
+// A new notice owns mod+z even inside a text field, until the user presses
+// another key or edits text. After that, mod+z is the field's own undo again.
+let shortcutClaimed = false;
function refreshNotice() {
const stale = liveUndos.filter(({ claim }) => !claim.isCurrent());
@@ -91,9 +94,21 @@ export function undoLatestThreadAction(): boolean {
return true;
}
+/** Whether mod+z should undo the notice's actions even while a text field is focused. */
+export function threadUndoClaimsShortcut(): boolean {
+ return shortcutClaimed && useThreadUndoNotice.getState().notice !== null;
+}
+
+/** Called on any other keypress or text edit; hands mod+z back to text fields. */
+export function releaseThreadUndoShortcut() {
+ shortcutClaimed = false;
+}
+
+/** Shows one compact confirmation for the currently undoable thread actions. */
export function showThreadUndoNotice(options: UndoOptions) {
if (!options.claim.isCurrent()) return;
liveUndos.push(options);
+ shortcutClaimed = true;
refreshNotice();
clearTimeout(expiry);
expiry = setTimeout(() => {
diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx
index 53c11954cec..de99486f0f4 100644
--- a/apps/web/src/routes/_chat.tsx
+++ b/apps/web/src/routes/_chat.tsx
@@ -22,7 +22,6 @@ import { isPreviewFocused } from "../lib/previewFocus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isEditableFocused } from "../lib/editableFocus";
import { isModelPickerOpen } from "../modelPickerVisibility";
-import { undoLatestThreadAction } from "../hooks/showThreadUndoNotice";
import { resolveShortcutCommand } from "../keybindings";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
@@ -83,15 +82,6 @@ function ChatRouteGlobalShortcuts() {
return;
}
- if (command === "thread.undo") {
- if (event.repeat || isModelPickerOpen()) return;
- if (undoLatestThreadAction()) {
- event.preventDefault();
- event.stopPropagation();
- }
- return;
- }
-
if (event.key === "Escape" && selectedThreadKeysSize > 0) {
event.preventDefault();
clearSelection();
diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md
index 794cac90e7a..085dee90af3 100644
--- a/docs/user/keybindings.md
+++ b/docs/user/keybindings.md
@@ -150,8 +150,9 @@ shortcut; assign one in **Settings → Keybindings**.
bottom of the sidebar, such as unpin, settle, snooze, archive, or discarding a
draft. Consecutive
actions of the same kind undo together. The notice remains available for five
-seconds after the latest action. The default shortcut skips text fields and
-terminals so native undo keeps working there.
+seconds after the latest action. Right after an action, the shortcut works even
+in a text field such as the composer. Once you type or press another key, the
+field gets its own undo back. Terminals always keep their native shortcut.
`navigation.back` (`mod+[` by default) and `navigation.forward` (`mod+]`) move
through the pages you have visited, like a browser's back and forward buttons.
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index 33dfbb66ca2..c64e95ec529 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -51,7 +51,7 @@ On web and desktop, unpinning, settling, snoozing, and archiving a thread each s
a notification with **Undo** for five seconds. Undo restores the thread's previous
state, including its pinned position, and reopens an archived thread you were
viewing. Discarding an unsent draft from the sidebar works the same way: Undo brings
-back its text and attachments. `mod+z` triggers the most recent Undo when no text field is focused; see
+back its text and attachments. `mod+z` triggers the most recent Undo, even from the composer; see
[Keybindings](./keybindings.md#commands-with-special-behavior).
On web and desktop, you can also drag files from your computer onto any thread row: