diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index a0458f9e80280..9db99ab6a8da2 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -26,6 +26,7 @@ import { selectThreadDiffPanelSelection, useDiffPanelStore } from "~/diffPanelSt import { __setClientSettingsForTests } from "~/hooks/useSettings"; import { environmentContextRecord } from "~/lib/composerContextRecords"; import { startWorkspaceFocus } from "~/lib/workspaceFocus"; +import * as keybindingCommands from "~/keybindings"; import { usePromptStashStore } from "~/promptStashStore"; import { useRightPanelStore } from "~/rightPanelStore"; import { getRouter } from "~/router"; @@ -48,6 +49,8 @@ import { } from "../../test/fakeEnvironment"; import { act, fakeTimers, render } from "../../test/render"; +vi.mock(import("~/keybindings"), { spy: true }); + const PNG = Uint8Array.from( atob( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", @@ -581,6 +584,99 @@ it("a mounted thread view lets go of the thread structures it has replaced", asy expect(kept).toEqual([]); }); +it("thread title shortcuts ignore closed dialogs but stop for open dialogs and confirmations", async () => { + const thread = threadWithHistory("thread-title-dialog-guard", 1); + using _environment = installFakeEnvironment([thread]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using screen = await render(, { + // AppRoot brings its own router. + router: false, + }); + using _command = vi + .spyOn(keybindingCommands, "resolveChatShortcutCommand") + .mockImplementation((...args) => + args[0].ctrlKey && args[0].shiftKey && args[0].key.toLowerCase() === "r" + ? "thread.rename" + : null, + ); + using overlays = new DisposableStack(); + const dialog = document.createElement("div"); + document.body.append(dialog); + overlays.defer(() => dialog.remove()); + const composer = screen.getByTestId("composer-editor"); + const title = screen.getByRole("textbox", { name: "Thread title", exact: true }); + for (const role of ["alertdialog", "dialog"]) { + dialog.setAttribute("role", role); + dialog.removeAttribute("data-closed"); + await composer.click(); + await userEvent.keyboard("{Control>}{Shift>}r{/Shift}{/Control}"); + await expect.element(title).not.toBeInTheDocument(); + + dialog.setAttribute("data-closed", ""); + await userEvent.keyboard("{Control>}{Shift>}r{/Shift}{/Control}"); + await expect.element(title).toBeVisible(); + await title.click(); + await userEvent.keyboard("{Escape}"); + await expect.element(title).not.toBeInTheDocument(); + } +}); + +it("renaming temporarily hides a maximized narrow panel and restores it on completion", async () => { + await page.viewport(900, 800); + const thread = threadWithHistory("thread-title-panel-focus", 1); + using _environment = installFakeEnvironment([thread]); + const threadRef = scopeThreadRef(ENVIRONMENT_ID, thread.id); + useRightPanelStore.getState().open(threadRef, "diff"); + useRightPanelStore.getState().setMaximized(threadRef, true); + const panelState = useRightPanelStore.getState().byThreadKey; + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using screen = await render(, { + // AppRoot brings its own router. + router: false, + }); + using _command = vi + .spyOn(keybindingCommands, "resolveChatShortcutCommand") + .mockImplementation((...args) => + args[0].ctrlKey && args[0].shiftKey && args[0].key.toLowerCase() === "r" + ? "thread.rename" + : null, + ); + await expect + .element(screen.getByRole("button", { name: "Toggle right panel", exact: true })) + .toBeVisible(); + const title = screen.getByRole("textbox", { name: "Thread title", exact: true }); + for (const finish of ["{Escape}", "{Enter}", "blur"]) { + await userEvent.keyboard("{Control>}{Shift>}r{/Shift}{/Control}"); + await expect.element(title).toBeVisible(); + await expect.element(title).toHaveFocus(); + await expect + .element(screen.getByRole("dialog", { name: "Workspace panel" })) + .not.toBeInTheDocument(); + expect(useRightPanelStore.getState().byThreadKey).toEqual(panelState); + if (finish === "blur") await screen.getByTestId("composer-editor").click(); + else await userEvent.keyboard(finish); + await expect.element(title).not.toBeInTheDocument(); + await expect + .element(screen.getByRole("button", { name: "Restore panel size", exact: true })) + .toBeVisible(); + expect(useRightPanelStore.getState().byThreadKey).toEqual(panelState); + } +}); + it("a shortcut conditioned on rightPanelOpen sees the thread's open right panel", async () => { await page.viewport(1280, 800); const thread = threadWithHistory("thread-panel-shortcut", 1); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1a50e7fdfa6b3..286956d71952c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -132,6 +132,7 @@ import { useRef, useState, } from "react"; +import { flushSync } from "react-dom"; import { BackgroundThreadContext } from "./chat/backgroundThread"; import { WorkspaceMutationIdContext } from "./chat/ChatMarkdownMedia"; import { useLocation, useNavigate } from "@tanstack/react-router"; @@ -300,7 +301,7 @@ import { NativeChildWorkDialog } from "./chat/NativeChildWorkDialog"; import { ProviderSubagentBar } from "./chat/ProviderSubagentBar"; import { getTriggerDisplayModelName } from "./chat/providerIconUtils"; import { resolveScrollToEndClearance } from "./composerFooterLayout"; -import { ChatHeader } from "./chat/ChatHeader"; +import { ChatHeader, type ChatHeaderHandle } from "./chat/ChatHeader"; import { useSideChat } from "./chat/useSideChat"; import { useRemoteOpenState } from "~/remoteOpen"; import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic"; @@ -441,6 +442,7 @@ const DismissedFallbackWindowSchema = Schema.NullOr(Schema.String); const ignoreComposerFocus = () => {}; export default function ChatView(props: ChatViewProps) { + const chatHeaderRef = useRef(null); const { environmentId, threadId, @@ -1023,6 +1025,25 @@ export default function ChatView(props: ChatViewProps) { })(); const activeThreadRef = useActiveThreadRef(activeThread); const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null; + const [renamingTitleState, setRenamingTitleState] = useState<{ + threadKey: string | null; + title: string; + } | null>(null); + if ( + renamingTitleState && + (renamingTitleState.threadKey !== activeThreadKey || !canOperateThread) + ) { + setRenamingTitleState(null); + } + const renamingTitle = + canOperateThread && renamingTitleState && renamingTitleState.threadKey === activeThreadKey + ? renamingTitleState.title + : null; + const handleRenamingTitleChange = (title: string | null) => { + setRenamingTitleState(title === null ? null : { threadKey: activeThreadKey, title }); + }; + const hidePanelForTitleRename = prefersPlanSidebarSheet && renamingTitle !== null; + const activeEnvironmentServerBrowser = useEnvironmentSupportsServerBrowser( activeThreadRef?.environmentId ?? null, ); @@ -1123,7 +1144,10 @@ export default function ChatView(props: ChatViewProps) { const canMaximizeRightPanel = rightPanelOpen; // An embedded side chat has no panel; a stale maximized flag would hide its own column. const rightPanelMaximized = - !embedded && canMaximizeRightPanel && rightPanelState.maximized === true; + !embedded && + !hidePanelForTitleRename && + canMaximizeRightPanel && + rightPanelState.maximized === true; const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet; const [threadPanelPopoverHandle] = useState(PopoverCreateHandle); const [chatCanvasStore] = useState(createChatCanvasStore); @@ -2762,6 +2786,48 @@ export default function ChatView(props: ChatViewProps) { ...terminalShortcuts, ...rightPanelShortcuts, ...threadLifecycleShortcuts, + "thread.rename": ({ event }) => { + if ( + !isServerThread || + !activeThreadId || + !canOperateThread || + document.querySelector( + '[role="dialog"]:not([data-closed]), [role="alertdialog"]:not([data-closed])', + ) + ) + return false; + if (event.repeat) return; + if (activeThreadRef && rightPanelMaximized && !prefersPlanSidebarSheet) { + flushSync(() => { + useRightPanelStore.getState().setMaximized(activeThreadRef, false); + }); + } + chatHeaderRef.current?.startRename(); + }, + "thread.regenerateTitle": ({ event }) => { + if ( + !isServerThread || + !activeThreadId || + !canOperateThread || + document.querySelector( + '[role="dialog"]:not([data-closed]), [role="alertdialog"]:not([data-closed])', + ) + ) + return false; + if (event.repeat || activeThreadShell?.titleRegeneration != null) return; + void updateThreadMetadata({ + environmentId, + input: { threadId: activeThreadId, regenerateTitle: true }, + }).then((result) => { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: "Failed to regenerate thread title", + description: error instanceof Error ? error.message : "An error occurred.", + }); + }); + }, "thread.copyReference": ({ event }) => { if (!event.repeat) copyActiveThreadReference(); }, @@ -3373,10 +3439,13 @@ export default function ChatView(props: ChatViewProps) { {!rightPanelControlsAtRoot && !rightPanelControlsInPanel ? panelLayoutControls : null} {inlineRightPanelOwnsTitleBar ? threadPanelHeaderControl : null} {rightPanelPresent && activeThreadRef && !embedded ? ( - - - {panelToggleControls} - - ) : null - } - surfaces={renderedRightPanelSurfaces} - environmentId={activeThreadRef.environmentId} - activeSurfaceId={renderedRightPanelSurface?.id ?? null} - pendingSurfaceIds={pendingFileSurfaceIds} - previewSessions={activePreviewState.sessions} - desktopByTabId={activePreviewState.desktopByTabId} - previewRuntimeTabId={resolvePreviewRuntimeTabId} - terminalLabelsById={activeTerminalLabelsById} - onActivate={activateRightPanelSurfaceStable} - onCloseSurface={closeRightPanelSurfaceStable} - onRenameDevice={(surfaceId, title) => { - if (activeThreadRef) - useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title); - }} - onCloseOtherSurfaces={closeOtherRightPanelSurfacesStable} - onCloseSurfacesToRight={closeRightPanelSurfacesToRightStable} - onCloseAllSurfaces={closeAllRightPanelSurfacesStable} - onMoveSurface={moveRightPanelSurfaceStable} - onCopyFilePath={copyRightPanelFilePathStable} - onAddBrowser={() => createBrowserSurface()} - onAddBrowserInProfile={createBrowserSurfaceStable} - onAddTerminal={addTerminalSurfaceStable} - onAddDiff={addDiffSurfaceStable} - onAddFiles={addFilesSurfaceStable} - onAddPullRequest={addPullRequestSurfaceStable} - onAddPullRequests={addPullRequestsSurfaceStable} - onAddDevice={addDeviceSurfaceStable} - onAddSideChat={sideChatsOffered ? openSideChatStable : undefined} - browserAvailable={canOperatePreview && browserAvailable} - terminalAvailable={activeProject !== null && canOperateTerminal} - diffAvailable={isServerThread && isGitRepo} - filesAvailable={activeProject !== null} - pullRequestAvailable={pullRequestSurfaceAvailable} - pullRequestsAvailable={pullRequestsSurfaceAvailable} - deviceAvailable={activeThreadRef !== null} - sideChatAvailable={sideChat.available} - sideChatDisabledReason={sideChatDisabledReason} +
- {rightPanelContent} - + + + {panelToggleControls} +
+ ) : null + } + surfaces={renderedRightPanelSurfaces} + environmentId={activeThreadRef.environmentId} + activeSurfaceId={renderedRightPanelSurface?.id ?? null} + pendingSurfaceIds={pendingFileSurfaceIds} + previewSessions={activePreviewState.sessions} + desktopByTabId={activePreviewState.desktopByTabId} + previewRuntimeTabId={resolvePreviewRuntimeTabId} + terminalLabelsById={activeTerminalLabelsById} + onActivate={activateRightPanelSurfaceStable} + onCloseSurface={closeRightPanelSurfaceStable} + onRenameDevice={(surfaceId, title) => { + if (activeThreadRef) + useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title); + }} + onCloseOtherSurfaces={closeOtherRightPanelSurfacesStable} + onCloseSurfacesToRight={closeRightPanelSurfacesToRightStable} + onCloseAllSurfaces={closeAllRightPanelSurfacesStable} + onMoveSurface={moveRightPanelSurfaceStable} + onCopyFilePath={copyRightPanelFilePathStable} + onAddBrowser={() => createBrowserSurface()} + onAddBrowserInProfile={createBrowserSurfaceStable} + onAddTerminal={addTerminalSurfaceStable} + onAddDiff={addDiffSurfaceStable} + onAddFiles={addFilesSurfaceStable} + onAddPullRequest={addPullRequestSurfaceStable} + onAddPullRequests={addPullRequestsSurfaceStable} + onAddDevice={addDeviceSurfaceStable} + onAddSideChat={sideChatsOffered ? openSideChatStable : undefined} + browserAvailable={canOperatePreview && browserAvailable} + terminalAvailable={activeProject !== null && canOperateTerminal} + diffAvailable={isServerThread && isGitRepo} + filesAvailable={activeProject !== null} + pullRequestAvailable={pullRequestSurfaceAvailable} + pullRequestsAvailable={pullRequestsSurfaceAvailable} + deviceAvailable={activeThreadRef !== null} + sideChatAvailable={sideChat.available} + sideChatDisabledReason={sideChatDisabledReason} + > + {rightPanelContent} +
+ ) : null} ({ import { render, stubGlobal } from "../../../test/render"; import { ChatHeader } from "./ChatHeader"; -function header(title: string) { +function Header({ title }: { title: string }) { + const [renamingTitle, setRenamingTitle] = useState(null); return ( <> ; +} + it.each(["blur", "Enter"] as const)( "preserves a concurrent title update when an untouched rename ends with %s", async (finish) => { diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 22e02b228a24d..e5a136491ab9b 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -14,6 +14,8 @@ import { ChevronDownIcon } from "lucide-react"; import { memo, useEffect, + useImperativeHandle, + type Ref, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, @@ -44,10 +46,17 @@ import { textDirection } from "~/textDirection"; import { useClientSettings } from "../../hooks/useSettings"; import { GuestShareIndicator } from "./GuestShareControls"; +export interface ChatHeaderHandle { + startRename: () => void; +} + interface ChatHeaderProps { + ref?: Ref; activeThreadEnvironmentId: EnvironmentId; activeThreadId: ThreadId; activeThreadTitle: string; + renamingTitle: string | null; + onRenamingTitleChange: (title: string | null) => void; activeThreadLinkOrigin?: string | null | undefined; isServerThread: boolean; activeProject: EnvironmentProject | null; @@ -70,9 +79,12 @@ function resolveRenameCommit(input: { } export const ChatHeader = memo(function ChatHeader({ + ref, activeThreadEnvironmentId, activeThreadId, activeThreadTitle, + renamingTitle, + onRenamingTitleChange: setRenaming, activeThreadLinkOrigin, isServerThread, activeProject, @@ -97,25 +109,6 @@ export const ChatHeader = memo(function ChatHeader({ const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, { reportFailure: false, }); - const [renaming, setRenaming] = useState<{ - threadId: ThreadId; - environmentId: EnvironmentId; - title: string; - } | null>(null); - if ( - renaming !== null && - (renaming.threadId !== activeThreadId || - renaming.environmentId !== activeThreadEnvironmentId || - !canOperateThread) - ) { - setRenaming(null); - } - const renamingTitle = - canOperateThread && - renaming?.threadId === activeThreadId && - renaming.environmentId === activeThreadEnvironmentId - ? renaming.title - : null; const isRenamingTitle = renamingTitle !== null; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the breadcrumb list DOM via ResizeObserver, a frame and font loads to collapse the parent title useEffect(() => { @@ -165,12 +158,9 @@ export const ChatHeader = memo(function ChatHeader({ ) return; renameCommittedRef.current = false; - setRenaming({ - environmentId: activeThreadEnvironmentId, - threadId: activeThreadId, - title: activeThreadTitle, - }); + setRenaming(activeThreadTitle); }; + useImperativeHandle(ref, () => ({ startRename })); const commitRename = (title: string) => { setRenaming(null); if (!readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)) return; diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsx index 4f27c18b75c7d..68cb4024af17b 100644 --- a/apps/web/src/components/chat/useThreadLifecycle.tsx +++ b/apps/web/src/components/chat/useThreadLifecycle.tsx @@ -181,7 +181,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { } = input; const navigate = useNavigate(); const router = useRouter(); - const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions(); + const { settleThread, pinThread, confirmAndUnpinThread, markThreadUnread } = useThreadActions(); const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope); const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false }); const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, { @@ -661,6 +661,17 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { ); }; const shortcuts = { + "thread.markUnread": ({ event }) => { + if ( + !activeThreadShell || + !activeThreadRef || + document.querySelector( + '[role="dialog"]:not([data-closed]), [role="alertdialog"]:not([data-closed])', + ) + ) + return false; + if (!event.repeat) markThreadUnread(activeThreadRef); + }, "thread.settle": () => { if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return; diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index e5db82230a6f0..0af02b339d365 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -382,6 +382,9 @@ export function buildKeybindingCommandOptions( } export function commandLabel(command: KeybindingCommand): string { + if (command === "thread.markUnread") return "Thread: Mark Unread"; + if (command === "thread.rename") return "Thread: Rename"; + if (command === "thread.regenerateTitle") return "Thread: Regenerate Name"; if (command === "workspace.focusNext") return "Focus Next Workspace Area"; if (command === "workspace.focusPrevious") return "Focus Previous Workspace Area"; if (command === "composer.sendAlternate") return "Composer: Opposite Queue or Steer Action"; diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index eda5138b760b9..727dc86ff413f 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -36,6 +36,8 @@ export type ModelPickerJumpKeybindingCommand = const THREAD_KEYBINDING_COMMANDS = [ "thread.stop", + "thread.rename", + "thread.markUnread", "thread.steerQueuedMessage", "thread.editQueuedMessage", "thread.previous",