Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions apps/web/src/components/ChatView.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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=",
Expand Down Expand Up @@ -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 router={router} />, {
// 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 router={router} />, {
// 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);
Expand Down
198 changes: 136 additions & 62 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -441,6 +442,7 @@ const DismissedFallbackWindowSchema = Schema.NullOr(Schema.String);
const ignoreComposerFocus = () => {};

export default function ChatView(props: ChatViewProps) {
const chatHeaderRef = useRef<ChatHeaderHandle>(null);
const {
environmentId,
threadId,
Expand Down Expand Up @@ -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,
);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Comment thread
LukasFB marked this conversation as resolved.
Resolved
});
}
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();
},
Expand Down Expand Up @@ -3373,10 +3439,13 @@ export default function ChatView(props: ChatViewProps) {
{!rightPanelControlsAtRoot && !rightPanelControlsInPanel ? panelLayoutControls : null}
{inlineRightPanelOwnsTitleBar ? threadPanelHeaderControl : null}
<ChatHeader
ref={chatHeaderRef}
activeThreadEnvironmentId={activeThread.environmentId}
activeThreadId={activeThread.id}
isServerThread={isServerThread}
activeThreadTitle={activeThread.title}
renamingTitle={renamingTitle}
onRenamingTitleChange={handleRenamingTitleChange}
activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}
activeProject={activeProject ?? null}
parentThreadLink={headerParentThreadLink}
Expand Down Expand Up @@ -3990,67 +4059,72 @@ export default function ChatView(props: ChatViewProps) {
</div>

{rightPanelPresent && activeThreadRef && !embedded ? (
<ChatRightPanel
sheet={shouldUsePlanSidebarSheet}
workspaceLayoutElement={workspaceLayoutElement}
widthStorageKey={`t3code:preview-panel-width:${activeThreadKey}`}
sheetAnimationDurationMs={panelAnimationsActive ? panelAnimationDurationMs : 0}
onCloseSheet={closePreviewPanelStable}
open={rightPanelOpen}
keybindings={keybindings}
getShortcutContext={getShortcutContextStable}
maximized={rightPanelMaximized}
layoutControls={
rightPanelOpen ? (
<div className="mr-px flex items-center gap-1">
<RightPanelMaximizeControl
maximized={rightPanelMaximized}
onToggle={toggleRightPanelMaximizedStable}
/>
{panelToggleControls}
</div>
) : 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}
<div
className={hidePanelForTitleRename ? "hidden" : "contents"}
inert={hidePanelForTitleRename}
>
{rightPanelContent}
</ChatRightPanel>
<ChatRightPanel
sheet={shouldUsePlanSidebarSheet}
workspaceLayoutElement={workspaceLayoutElement}
widthStorageKey={`t3code:preview-panel-width:${activeThreadKey}`}
sheetAnimationDurationMs={panelAnimationsActive ? panelAnimationDurationMs : 0}
onCloseSheet={closePreviewPanelStable}
open={rightPanelOpen && !hidePanelForTitleRename}
keybindings={keybindings}
getShortcutContext={getShortcutContextStable}
maximized={rightPanelMaximized}
layoutControls={
rightPanelOpen ? (
<div className="mr-px flex items-center gap-1">
<RightPanelMaximizeControl
maximized={rightPanelMaximized}
onToggle={toggleRightPanelMaximizedStable}
/>
{panelToggleControls}
</div>
) : 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}
</ChatRightPanel>
</div>
) : null}

<RevertConfirmHost
Expand Down
Loading
Loading