Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import * as PersistedStateModule from "@/browser/hooks/usePersistedState";
import * as PopoverErrorHookModule from "@/browser/hooks/usePopoverError";
import * as DesktopTitlebarModule from "@/browser/hooks/useDesktopTitlebar";
import * as TutorialContextModule from "@/browser/contexts/TutorialContext";
import * as AppConfigStoreModule from "@/browser/stores/AppConfigStore";
import * as ChatCommandsModule from "@/browser/utils/chatCommands";
import * as FeedbackToastModule from "@/browser/utils/feedbackToast";
import type { WorkspaceMenuBar as WorkspaceMenuBarComponent } from "./WorkspaceMenuBar";
Expand Down Expand Up @@ -1058,6 +1059,24 @@ describe("WorkspaceMenuBar archive confirmations", () => {
});
});

it("tells screen readers whether the bell notifies on all responses", () => {
// A click only opens the settings, so the state cannot be a pressed state (#5761).
const bellDescription = () =>
render(<WorkspaceMenuBar {...defaultProps} />)
.getByRole("button", { name: "Notifications" })
.getAttribute("aria-description");
expect(bellDescription()).toBe("Notify on all responses: off");
cleanup();

const on = {
notifications: { notifyOnResponseByWorkspace: { [defaultProps.workspaceId]: true } },
};
spyOn(AppConfigStoreModule, "useUserPreferences").mockImplementation(((
select: (preferences: typeof on) => unknown
) => select(on)) as unknown as typeof AppConfigStoreModule.useUserPreferences);
expect(bellDescription()).toBe("Notify on all responses: on");
});

it("lets global shortcuts through while the Workspace details button has focus", () => {
const seen: string[] = [];
const recordKey = (e: KeyboardEvent) => seen.push(e.key);
Expand All @@ -1068,7 +1087,7 @@ describe("WorkspaceMenuBar archive confirmations", () => {
details.focus();

// Radix returns focus here when the popover closes; window shortcuts must still see keys,
// Escape included (it interrupts a stream).
// the stream-interrupt shortcut included.
fireEvent.keyDown(details, { key: ",", code: "Comma", ctrlKey: true, shiftKey: true });
fireEvent.keyDown(details, { key: "Escape" });
// A modified Enter is another shortcut (run the latest plan), not the button's activation.
Expand Down
11 changes: 8 additions & 3 deletions src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,933 +181,938 @@
);
}

export const WorkspaceMenuBar: React.FC<WorkspaceMenuBarProps> = ({
workspaceId,
projectName,
projectPath,
workspaceName,
workspaceTitle,
namedWorkspacePath,
runtimeConfig,
leftSidebarCollapsed,
onOpenTerminal,
onOpenSidebar,
sidebarFullscreen = false,
}) => {
const liveApi = useLiveAPI();
const { preflightArchiveWorkspace, archiveWorkspace, archivingWorkspaceIds, setWorkspacePinned } =
useWorkspaceActions();
const isArchiving = archivingWorkspaceIds.has(workspaceId);
const { workspaceMetadata } = useWorkspaceContext();
const artifactsExperimentEnabled = useExperimentValue(EXPERIMENT_IDS.ARTIFACTS);
const mcpAppsExperimentEnabled = useExperimentValue(EXPERIMENT_IDS.MCP_APPS);
const openTerminalPopout = useOpenTerminal();
const openInEditor = useOpenInEditor();
const runtimeStatus = useRuntimeStatus(workspaceId);
const workspaceEntry = workspaceMetadata.get(workspaceId);
// Heartbeats never fire for sub-agent workspaces.
const canConfigureHeartbeat = workspaceEntry?.parentWorkspaceId == null;
// The workspace's metadata.projectName is the parent project (since worktrees
// are owned by the top-most parent). When the workspace is scoped to a
// sub-project we surface the hierarchy as "parent / child" so the menu bar
// alone reveals the sub-project context.
const { userProjects } = useProjectContext();
const subProjectPath = workspaceEntry?.subProjectPath;
const projectLabel =
workspaceEntry?.kind === "scratch"
? SCRATCH_PROJECT_NAME
: subProjectPath && userProjects.has(subProjectPath)
? formatProjectHierarchyLabel(subProjectPath, userProjects)
: projectName;
const runtimeStatusStore = useRuntimeStatusStoreRaw();
const { canInterrupt, isStarting, awaitingUserQuestion, loadedSkills, skillLoadErrors } =
useWorkspaceSidebarState(workspaceId);
const isWorking = (canInterrupt || isStarting) && !awaitingUserQuestion;
const { startSequence: startTutorial } = useTutorial();
const [editorError, setEditorError] = useState<string | null>(null);
const [debugLlmRequestOpen, setDebugLlmRequestOpen] = useState(false);
const [mcpModalOpen, setMcpModalOpen] = useState(false);
const [heartbeatModalOpen, setHeartbeatModalOpen] = useState(false);
// Keyed by workspace: consent is granted per
// recipient workspace, so switching workspaces while the dialog is open must close it
// rather than let the switch be flipped against the workspace the user navigated to.
const [unrelatedMessagingWorkspaceId, setUnrelatedMessagingWorkspaceId] = useState<string | null>(
null
);
if (unrelatedMessagingWorkspaceId !== null && unrelatedMessagingWorkspaceId !== workspaceId) {
setUnrelatedMessagingWorkspaceId(null);
}
const unrelatedMessagingModalOpen = unrelatedMessagingWorkspaceId === workspaceId;
const skillList = useAgentSkills({ workspaceId, disableWorkspaceAgents: false });
const skillListLoaded = useAgentSkillsLoaded({ workspaceId, disableWorkspaceAgents: false });
const moreActionsButtonRef = useRef<HTMLButtonElement | null>(null);
const menuBarRef = useRef<HTMLDivElement | null>(null);
const [moreMenuOpen, setMoreMenuOpen] = useState(false);
const titleEdit = useHeaderTitleEdit(workspaceId, moreActionsButtonRef);
const archiveError = usePopoverError();
const forkError = usePopoverError();
const stopRuntimeError = usePopoverError();

const [rightSidebarCollapsed] = usePersistedState<boolean>(
RIGHT_SIDEBAR_COLLAPSED_KEY,
RIGHT_SIDEBAR_DEFAULT_COLLAPSED,
{
// This state is toggled from RightSidebar, so we need cross-component updates.
listener: true,
}
);

// Notification on response toggle (workspace-level) - defaults to disabled
const notifyOnResponse =
useUserPreferences(
(preferences) => preferences.notifications?.notifyOnResponseByWorkspace?.[workspaceId]
) ?? false;
// Shown in the bell's tooltip and given to screen readers: the icon is the only other cue.
const notifyOnResponseLabel = `Notify on all responses: ${notifyOnResponse ? "on" : "off"}`;
const setNotifyOnResponse = (enabled: boolean) =>
setWorkspaceNotifyOnResponse(workspaceId, enabled);

const notificationScope =
workspaceEntry?.kind === "scratch" ? SCRATCH_PROJECT_CONFIG_KEY : projectPath;
// Auto-enable notifications for new workspaces (project-level)
const autoEnableNotifications =
useUserPreferences(
(preferences) =>
preferences.workspaceCreation?.byProject?.[notificationScope]?.notifyOnResponseAutoEnable
) ?? false;
const setAutoEnableNotifications = (enabled: boolean) => {
updateUserPreferences({
workspaceCreation: {
byProject: { [notificationScope]: { notifyOnResponseAutoEnable: enabled || null } },
},
});
};

// Popover state for notification settings (interactive on click)
const [notificationPopoverOpen, setNotificationPopoverOpen] = useState(false);
const [detailsPopoverOpen, setDetailsPopoverOpen] = useState(false);
const [detailsTooltipOpen, setDetailsTooltipOpen] = useState(false);

const handleOpenTerminal = useCallback(() => {
if (onOpenTerminal) {
// WorkspaceShell picks a sidebar tab or a popout from the right sidebar's real visibility.
onOpenTerminal();
} else {
// Fallback to popout if no integrated terminal callback provided
void openTerminalPopout(workspaceId, runtimeConfig);
}
}, [workspaceId, openTerminalPopout, runtimeConfig, onOpenTerminal]);

const isPhoneHeader = useSyncExternalStore(
subscribePhoneHeader,
getPhoneHeaderSnapshot,
() => false
);
const isTouchMobileScreen =
typeof window !== "undefined" &&
window.matchMedia("(max-width: 768px) and (pointer: coarse)").matches;

// The right sidebar (home of the Timeline tab) is CSS-hidden by a viewport media query and by
// the workspace-shell container query. Read its actual computed visibility so the timeline
// dialog gate matches the CSS truth (see isWorkspaceRightSidebarHidden).
// the workspace-shell container query. Read its actual computed visibility so the full-screen
// gate matches the CSS truth (see isWorkspaceRightSidebarHidden).
const isTimelineSidebarHidden = useCallback((): boolean => {
if (typeof window === "undefined") {
return false;
}
return isWorkspaceRightSidebarHidden(menuBarRef.current?.closest("[data-workspace-shell]"));
}, []);

// Keep the gate reactive: resizing re-evaluates CSS instantly, but a render-time read
// would leave the More menu stale until an unrelated state update. The media-query
// listener covers viewport transitions and the ResizeObserver covers the shell
// container query (e.g. expanding the left sidebar squeezes the shell under 684px).
const [timelineSidebarHidden, setTimelineSidebarHidden] = useState(false);
// While the sidebar is hidden, the Timeline, Stats and Artifacts entry points (header buttons,
// shortcuts, palette and "Open in Artifacts") open their tab in the sidebar itself, shown
// full-screen, like every other tab. They used to open dialogs of their own (#5767, #5795).
// Focus returns to `returnFocusTo` when the view closes.
// Already open (Shift+T from another full-screen tab): only switch the tab, so focus still
// returns to the control that opened the view. The switch unmounts the old tab's panel, so if
// focus was in it, it moves to the new tab instead of falling out of the view. flushSync
// commits the switch first, so that tab is in the DOM.
const openSidebarTab = useCallback(
(tab: TabType, returnFocusTo: HTMLElement | null) => {
if (onOpenSidebar == null) return;
if (!sidebarFullscreen) {
focusRightSidebarTab(workspaceId, tab);
onOpenSidebar(returnFocusTo);
return;
}
flushSync(() => focusRightSidebarTab(workspaceId, tab));
if (document.activeElement == null || document.activeElement === document.body) {
menuBarRef.current
?.closest("[data-workspace-shell]")
?.querySelector<HTMLElement>(`[role="tab"][aria-selected="true"][id$="-tab-${tab}"]`)
?.focus();
}
},
[onOpenSidebar, sidebarFullscreen, workspaceId]
);
const activeElement = () =>
document.activeElement instanceof HTMLElement ? document.activeElement : null;
useEffect(() => {
const compute = () => setTimelineSidebarHidden(isTimelineSidebarHidden());
compute();
const mql = window.matchMedia(`(max-width: ${NARROW_VIEWPORT_MAX_WIDTH_PX}px)`);
mql.addEventListener("change", compute);
const shell = menuBarRef.current?.closest("[data-workspace-shell]");
let resizeObserver: ResizeObserver | undefined;
if (shell instanceof HTMLElement && typeof ResizeObserver !== "undefined") {
resizeObserver = new ResizeObserver(compute);
resizeObserver.observe(shell);
}
return () => {
mql.removeEventListener("change", compute);
resizeObserver?.disconnect();
};
// sidebarFullscreen: opening or closing the full-screen sidebar changes its visibility
// without resizing the shell, so re-read it then too.
}, [isTimelineSidebarHidden, sidebarFullscreen]);

// Remote desktop and browser viewports own their keystrokes: in the full-screen view they can
// have focus, and a capital T or S typed there must not switch tabs.
const isViewportTarget = (target: EventTarget | null) =>
isDesktopViewportFocused(target) || isBrowserViewportFocused(target);

// The Timeline shortcut while the sidebar is hidden. Evaluated at keydown time so the gate
// tracks live viewport/layout changes without a resize subscription.
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (
!matchesKeybind(e, KEYBINDS.OPEN_TIMELINE_DIALOG) ||
isDialogOpen() ||
isEditableElement(e.target) ||
isViewportTarget(e.target) ||
// Shown full-screen, the sidebar is visible, and the shortcut switches its tab.
!(isTimelineSidebarHidden() || sidebarFullscreen)
) {
return;
}
e.preventDefault();
openSidebarTab("timeline", activeElement());
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [isTimelineSidebarHidden, openSidebarTab, sidebarFullscreen]);

// Stats while the sidebar is hidden: its shortcut, and the palette's "Add Tool: Stats" (which
// also adds the tab to the hidden layout, so wide layouts keep their old behavior).
useEffect(() => {
const open = () => openSidebarTab("costs", activeElement());
const onKeyDown = (e: KeyboardEvent) => {
if (
matchesKeybind(e, KEYBINDS.OPEN_STATS_DIALOG) &&
!isDialogOpen() &&
!isEditableElement(e.target) &&
!isViewportTarget(e.target) &&
(isTimelineSidebarHidden() || sidebarFullscreen)
) {
e.preventDefault();
open();
}
};
// The palette already selected the tab; only a hidden sidebar needs showing.
const onPalette = (event: Event) => {
const detail = (event as CustomEvent<{ workspaceId: string }>).detail;
if (detail?.workspaceId === workspaceId && isTimelineSidebarHidden()) open();
};
window.addEventListener("keydown", onKeyDown);
window.addEventListener(CUSTOM_EVENTS.OPEN_STATS_DIALOG, onPalette);
return () => {
window.removeEventListener("keydown", onKeyDown);
window.removeEventListener(CUSTOM_EVENTS.OPEN_STATS_DIALOG, onPalette);
};
}, [isTimelineSidebarHidden, openSidebarTab, sidebarFullscreen, workspaceId]);

// Ctrl+Shift+K normally opens the Artifacts tab (RightSidebar owns that handler); while the
// sidebar is hidden it shows that tab full-screen instead.
useEffect(() => {
if (!artifactsExperimentEnabled) {
return;
}
const handler = (e: KeyboardEvent) => {
if (
!matchesKeybind(e, KEYBINDS.OPEN_ARTIFACTS_TAB) ||
isDialogOpen() ||
!isTimelineSidebarHidden() ||
// Same exclusions as the wide-layout handler in RightSidebar: remote desktops and
// terminals own their keystrokes on every layout.
isTerminalFocused(e.target) ||
isDesktopViewportFocused(e.target)
) {
return;
}
e.preventDefault();
openSidebarTab("artifacts", activeElement());
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [artifactsExperimentEnabled, isTimelineSidebarHidden, openSidebarTab]);

// openArtifact() (chat cards, file cards, Review, palette) and "Open in tab" on an MCP Apps
// tool card: while the sidebar is hidden, they show their tab full-screen (RightSidebar
// handles the same events on wider layouts).
// Each event listens only while its own experiment is on (MCP Apps are independent, #6760).
useEffect(() => {
const handler = (event: Event) => {
const detail = (event as CustomEvent<{ workspaceId: string }>).detail;
if (detail?.workspaceId !== workspaceId || !isTimelineSidebarHidden()) {
return;
}
openSidebarTab("artifacts", activeElement());
};
// "Open in tab" shows the view's own app tab full-screen: the tab RightSidebar opens or
// focuses on wider layouts, so the view still runs in one place.
const appViewHandler = (event: Event) => {
const detail = (event as CustomEvent<{ workspaceId: string; toolCallId: string }>).detail;
if (detail?.workspaceId !== workspaceId || !isTimelineSidebarHidden()) {
return;
}
openSidebarTab(appViewTabFor(detail.toolCallId), activeElement());
};
const removeAppView = addWindowListenerWhile(
mcpAppsExperimentEnabled,
CUSTOM_EVENTS.OPEN_MCP_APP_VIEW,
appViewHandler
);
const removeArtifact = addWindowListenerWhile(
artifactsExperimentEnabled,
CUSTOM_EVENTS.OPEN_ARTIFACT,
handler
);
return () => {
removeAppView();
removeArtifact();
};
}, [
artifactsExperimentEnabled,
mcpAppsExperimentEnabled,
isTimelineSidebarHidden,
openSidebarTab,
workspaceId,
]);

const isDevcontainerWorkspace = isDevcontainerRuntime(runtimeConfig);
const isRuntimeRunning = isDevcontainerWorkspace && runtimeStatus === "running";
const handleOpenTouchFullscreenReview = useCallback(() => {
window.dispatchEvent(
createCustomEvent(CUSTOM_EVENTS.OPEN_TOUCH_REVIEW_IMMERSIVE, {
workspaceId,
})
);
}, [workspaceId]);

const handleEnterImmersiveReview = useCallback(() => {
window.dispatchEvent(createCustomEvent(CUSTOM_EVENTS.OPEN_REVIEW_IMMERSIVE, { workspaceId }));
}, [workspaceId]);

const handleOpenInEditor = useCallback(async () => {
setEditorError(null);
const result = await openInEditor(workspaceId, namedWorkspacePath, runtimeConfig);
if (!result.success && result.error) {
setEditorError(result.error);
// Clear error after 3 seconds
setTimeout(() => setEditorError(null), 3000);
}
}, [workspaceId, namedWorkspacePath, openInEditor, runtimeConfig]);

// Same archive flow as the sidebar rows so the two entry points cannot drift apart.
const archiveFlow = useArchiveWorkspaceConfirmation({
preflightArchiveWorkspace,
archiveWorkspace,
isArchiving: () => isArchiving,
isStreaming: () => isWorking,
getDisplayTitle: () => workspaceTitle,
showError: (errorWorkspaceId, error, anchorEl) => {
const rect = anchorEl?.getBoundingClientRect();
archiveError.showError(
errorWorkspaceId,
error,
rect ? { top: rect.top + window.scrollY, left: rect.right + 10 } : undefined
);
},
});
// The menu bar is reused across workspaces. Render-time adjustment (not an effect): a
// confirmation for another workspace, including one opened by a preflight that resolved after
// navigation, must never show over (or be confirmed from) the workspace now in view.
if (
archiveFlow.confirmationWorkspaceId !== null &&
archiveFlow.confirmationWorkspaceId !== workspaceId
) {
archiveFlow.cancel();
}
const handleArchiveChat = (anchorEl?: HTMLElement) =>
archiveFlow.requestArchive(workspaceId, anchorEl);

const handleForkWorkspace = async (anchorEl: HTMLElement) => {
const anchor = getErrorAnchor(anchorEl);
const error = await forkWorkspaceFromMenu(liveApi, workspaceId);
if (error) forkError.showError(workspaceId, error, anchor);
};

const handleStopRuntime = async () => {
const error = await stopWorkspaceRuntime(liveApi, runtimeStatusStore, workspaceId);
if (error) {
stopRuntimeError.showError(workspaceId, error, getErrorAnchor(moreActionsButtonRef.current));
}
};

// Start workspace tutorial on first entry
useEffect(() => {
// Small delay to ensure UI is rendered
const timer = setTimeout(() => {
// Its only step points at the header terminal button, which touch phones move into the
// More menu. Without a target the tutorial would show only an empty dimmed backdrop.
if (getPhoneHeaderSnapshot()) return;
startTutorial("workspace");
}, 300);
return () => clearTimeout(timer);
}, [startTutorial]);

// Listen for /debug-llm-request command to open modal
useEffect(() => {
const handler = () => setDebugLlmRequestOpen(true);
window.addEventListener(CUSTOM_EVENTS.OPEN_DEBUG_LLM_REQUEST, handler);
return () => window.removeEventListener(CUSTOM_EVENTS.OPEN_DEBUG_LLM_REQUEST, handler);
}, []);

// Keybind for toggling notifications
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (matchesKeybind(e, KEYBINDS.TOGGLE_NOTIFICATIONS)) {
e.preventDefault();
setWorkspaceNotifyOnResponse(
workspaceId,
!getUserPreferences().notifications?.notifyOnResponseByWorkspace?.[workspaceId]
);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [workspaceId]);

useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (matchesKeybind(e, KEYBINDS.SHOW_WORKSPACE_DETAILS)) {
e.preventDefault();
setDetailsPopoverOpen((prev) => !prev);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, []);

// Keybind for opening MCP configuration
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (matchesKeybind(e, KEYBINDS.CONFIGURE_MCP)) {
e.preventDefault();
setMcpModalOpen(true);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, []);

// Keybind for opening heartbeat configuration
useEffect(() => {
if (!canConfigureHeartbeat) return;
const handler = (e: KeyboardEvent) => {
if (matchesKeybind(e, KEYBINDS.CONFIGURE_HEARTBEAT)) {
e.preventDefault();
setHeartbeatModalOpen(true);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [canConfigureHeartbeat]);

// Keybind for the cross-workspace messaging consent dialog (same shape as the MCP keybind:
// a window listener subscribing to an external event source, not derived state). Like the
// timeline shortcut, it yields to any modal already open so it cannot stack a consent dialog
// over another dialog's focus trap.
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (matchesKeybind(e, KEYBINDS.CONFIGURE_UNRELATED_MESSAGING) && !isDialogOpen()) {
e.preventDefault();
setUnrelatedMessagingWorkspaceId(workspaceId);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [workspaceId]);

// On Windows/Linux, the native window controls overlay the top-right of the app.
// When the right sidebar is collapsed (20px), this header stretches underneath
// those controls and the MCP/editor/terminal buttons become unclickable.
const isDesktop = isDesktopMode();

const workspaceIsPinned = workspaceEntry ? isWorkspacePinned(workspaceEntry) : false;
// Mirror sidebar share/archive actions in the workspace menu bar for quick access.
const moreActionsMenu = (
<Popover
open={moreMenuOpen}
onOpenChange={(open) => {
preloadSettingsModals(); // the first open starts the imports, later calls reuse them
setMoreMenuOpen(open);
}}
>
<Tooltip {...(moreMenuOpen ? { open: false } : {})}>
<TooltipTrigger asChild>
<PopoverTrigger asChild>
<Button
ref={moreActionsButtonRef}
variant="ghost"
size="icon"
// A sibling of the actions group (not inside it) so phones can keep it at
// the top right of the title row while the other actions wrap below.
// ml-3 matches the group's gap-2 + ml-1 spacing on wider screens.
className={cn(
"text-muted hover:text-foreground ml-3 h-6 w-6 shrink-0",
isDesktop && "titlebar-no-drag"
)}
aria-label="Workspace actions"
data-testid="workspace-more-actions"
>
<Ellipsis className="h-3.5 w-3.5" />
</Button>
</PopoverTrigger>
</TooltipTrigger>
{/* Same words as the button's aria-label, so sighted and screen-reader users get one
name for this control (#5681). */}
<TooltipContent side="bottom" align="end">
Workspace actions
</TooltipContent>
</Tooltip>

<PopoverContent
side="bottom"
align="end"
sideOffset={6}
// Size to the widest row ("Messages from other workspaces" + shortcut
// overflowed a fixed 240px), but never wider than the viewport. On short screens (a
// landscape phone) it scrolls within the room below the button instead of hiding its
// last actions.
className="max-h-(--radix-popover-content-available-height) w-max max-w-[calc(100vw-1rem)] !min-w-[240px] overflow-y-auto p-1"
onClick={(event: React.MouseEvent<HTMLDivElement>) => {
event.stopPropagation();
}}
onCloseAutoFocus={titleEdit.onMenuCloseAutoFocus}
>
{/* Keep MCP configuration in the more actions menu to keep the workspace menu bar lean. */}
<WorkspaceActionsMenuContent
state={{
surface: "topbar",
workspace: workspaceEntry,
showsSubAgent: workspaceEntry?.parentWorkspaceId != null,
isRuntimeRunning,
isTouchMobileScreen,
isPhoneHeader,
isRightSidebarHidden: timelineSidebarHidden,
}}
actions={{
editTitle: titleEdit.start,
generateTitle: () => requestGenerateWorkspaceTitle(workspaceId),
configureMcp: () => setMcpModalOpen(true),
configureHeartbeat: () => setHeartbeatModalOpen(true),
configureMessaging: () => setUnrelatedMessagingWorkspaceId(workspaceId),
immersiveReview: handleEnterImmersiveReview,
touchFullscreenReview: handleOpenTouchFullscreenReview,
openSidebar:
onOpenSidebar != null ? () => onOpenSidebar(moreActionsButtonRef.current) : undefined,
openTerminal: handleOpenTerminal,
togglePinned: () => {
void setWorkspacePinned(workspaceId, !workspaceIsPinned);
},
fork: (anchorEl) => void handleForkWorkspace(anchorEl),
stopRuntime: () => void handleStopRuntime(),
// Runs preflight and opens a confirmation dialog when streaming or untracked files
// are detected.
archive: (anchorEl) => void handleArchiveChat(anchorEl),
}}
isPinned={workspaceIsPinned}
onCloseMenu={() => setMoreMenuOpen(false)}
/>
</PopoverContent>
</Popover>
);

return (
<div
ref={menuBarRef}
data-testid="workspace-menu-bar"
className={cn(
"bg-sidebar border-border-light flex items-center justify-between border-b px-2",
isDesktop ? DESKTOP_TITLEBAR_HEIGHT_CLASS : "h-8",
// A collapsed right sidebar floats below the header, so the header reaches the window's
// right edge and must clear the titlebar overlay controls itself.
rightSidebarCollapsed && "titlebar-safe-right titlebar-safe-right-gutter-2",
// The collapsed left sidebar is zero-width, so the header reaches the window's left edge,
// under the app shell's fixed toggle bar: its spacer starts at the edge.
leftSidebarCollapsed && "pl-0",
// In desktop mode, make header draggable for window movement
isDesktop && "titlebar-drag",
// Keep header visible when iOS keyboard opens and causes scroll
"mobile-sticky-header"
)}
>
<div
className={cn(
// flex-1 (zero basis) lets a long title truncate instead of pushing the actions
// onto a second row on touch phones, where the header wraps.
"text-foreground flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",
isDesktop && "titlebar-no-drag"
)}
>
{leftSidebarCollapsed && <LeftSidebarToggleBarSpacer showNewChat />}
<WorkspaceHeaderTitle
workspaceId={workspaceId}
title={workspaceTitle ?? workspaceName}
edit={titleEdit}
/>
{/* Touch and keyboard users need a focusable control for workspace details. */}
<Popover open={detailsPopoverOpen} onOpenChange={setDetailsPopoverOpen}>
<Tooltip
open={detailsTooltipOpen && !detailsPopoverOpen}
onOpenChange={setDetailsTooltipOpen}
>
<TooltipTrigger asChild>
<PopoverTrigger asChild>
<button
type="button"
className="text-muted hover:text-foreground focus-visible:ring-accent flex shrink-0 cursor-pointer items-center border-0 bg-transparent p-0 transition-colors focus-visible:ring-1"
aria-label="Workspace details"
onKeyDown={(e) => {
// Stop only the keys this button owns: unmodified Enter and Space activate
// it. Stopping every key also hid global shortcuts from the window
// listeners while the button had focus, which it gets back every time the
// popover closes (#5671). Modified keys are other shortcuts. The popover's
// dismiss key is not the button's either: the open popover marks it handled,
// and with the popover closed the stream-interrupt shortcut must still work.
const modified = e.altKey || e.ctrlKey || e.metaKey || e.shiftKey;
if (!modified && (e.key === "Enter" || e.key === " ")) {
stopKeyboardPropagation(e);
}
}}
>
<Info className="h-3.5 w-3.5" />
</button>
</PopoverTrigger>
</TooltipTrigger>
<TooltipContent>
Workspace details ({formatKeybind(KEYBINDS.SHOW_WORKSPACE_DETAILS)})
</TooltipContent>
</Tooltip>
<PopoverContent align="start" className="flex flex-col gap-0.5 p-2 text-xs">
<span className="font-mono">{projectLabel}</span>
<span>{workspaceName}</span>
<span className="text-muted">{namedWorkspacePath}</span>
<WorkspaceDetailsBranch
workspaceId={workspaceId}
workspaceName={workspaceName}
hasRepository={hasWorkspaceRepository(workspaceEntry)}
/>
</PopoverContent>
</Popover>
{isArchiving && (
<span
role="status"
className="text-muted flex shrink-0 items-center gap-1 text-xs whitespace-nowrap"
data-testid="workspace-archiving-status"
>
<ArchiveIcon className="h-3 w-3 shrink-0" />
Archiving...
</span>
)}
</div>
{/* On touch phones the 44px buttons do not fit beside the title, so the header wraps.
The menu stays at the top right of the title row and the other actions move to the
row below. The DOM order changes too (not only CSS order), so keyboard focus follows
the visual order. */}
{isPhoneHeader && moreActionsMenu}
<div
className={cn(
"flex items-center gap-2",
// Phones give these actions their own row below the title and the menu. The header
// stays at two rows: a full row (PR and stack badges, skills, Stats, Artifacts) is wider
// than a 375px screen, so it scrolls sideways like the footer bar instead of wrapping
// into a third row or pushing the last 44px touch targets past the right edge.
isPhoneHeader && "scrollbar-none scroll-fade-x min-w-0 basis-full overflow-x-auto",
isDesktop && "titlebar-no-drag"
)}
>
{/* The footer hides these links at this width, so the header carries them. */}
<WorkspaceLinks
workspaceId={workspaceId}
className="hidden [@media(max-width:768px)]:inline-flex"
menuDirection="down"
/>
<Popover open={notificationPopoverOpen} onOpenChange={setNotificationPopoverOpen}>
<Tooltip {...(notificationPopoverOpen ? { open: false } : {})}>
<TooltipTrigger asChild>
<PopoverTrigger asChild>
{/* A click only opens the settings: it used to also flip "Notify on all
responses", so nobody could look at the settings without changing them
(#5691). The checkbox and the shortcut toggle it. */}
<button
type="button"
className={cn(
"flex h-6 w-6 shrink-0 items-center justify-center rounded",
notifyOnResponse
? "text-foreground"
: "text-muted hover:bg-sidebar-hover hover:text-foreground"
)}
data-testid="notify-on-response-button"
aria-label="Notifications"
// The icon is the only visible state, and a click does not toggle it, so the
// state cannot be aria-pressed (#5761).
aria-description={notifyOnResponseLabel}
>
{notifyOnResponse ? (
<Bell className="h-3.5 w-3.5" />
) : (
<BellOff className="h-3.5 w-3.5" />
)}
</button>
</PopoverTrigger>
</TooltipTrigger>
{/* A plain label: the settings live only in the popover. When the tooltip repeated
them, Radix reopened it on the refocused bell after Escape closed the popover,
and a second copy of the settings appeared (#5691). */}
<TooltipContent side="bottom" align="end">
Notifications
<br />
Notify on all responses: {notifyOnResponse ? "on" : "off"}
{notifyOnResponseLabel}
<span className="mobile-hide-shortcut-hints">
{" "}
({formatKeybind(KEYBINDS.TOGGLE_NOTIFICATIONS)})
</span>
</TooltipContent>
</Tooltip>

<PopoverContent
side="bottom"
align="end"
className="bg-modal-bg border-separator-light w-64 overflow-visible rounded px-[10px] py-[6px] text-[11px] font-normal shadow-[0_2px_8px_rgba(0,0,0,0.4)]"
>
<div className="flex flex-col gap-2">
<label className="flex cursor-pointer items-center gap-2">
<Checkbox
checked={notifyOnResponse}
onCheckedChange={(checked) => setNotifyOnResponse(checked === true)}
/>
<span className="text-foreground">
Notify on all responses{" "}
<span className="text-muted-foreground mobile-hide-shortcut-hints">
({formatKeybind(KEYBINDS.TOGGLE_NOTIFICATIONS)})
</span>
</span>
</label>
<label className="flex cursor-pointer items-start gap-2">
<Checkbox
checked={autoEnableNotifications}
onCheckedChange={(checked) => setAutoEnableNotifications(checked === true)}
/>
<span className="text-muted-foreground">
Auto-enable for new workspaces in this project
</span>
</label>
<p className="text-muted-foreground border-separator-light border-t pt-2">
Agents can also notify on specific events.{" "}
<a
href="https://mux.coder.com/config/notifications"
target="_blank"
rel="noopener noreferrer"
className="text-accent-text hover:underline"
>
Learn more
</a>
</p>
</div>
</PopoverContent>
</Popover>
<SkillIndicator
loadedSkills={loadedSkills}
availableSkills={listInvocableSkills(skillList)}
invalidSkills={skillList.invalidSkills}
skillWarnings={skillList.skillWarnings}
unavailableSources={skillList.unavailableSources}
skillLoadErrors={skillLoadErrors}
loading={!skillListLoaded}
/>
{editorError && <span className="text-danger-soft text-xs">{editorError}</span>}
<div className="max-[480px]:hidden">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={() => void handleOpenInEditor()}
aria-label="Open in editor"
className="text-muted hover:text-foreground ml-1 h-6 w-6 shrink-0"
>
<Pencil className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" align="center">
Open in editor ({formatKeybind(KEYBINDS.OPEN_IN_EDITOR)})
</TooltipContent>
</Tooltip>
</div>
{isPhoneHeader ? (
// Touch phones: the terminal opens as a pop-out window, which mobile Safari does not
// show, so the header row offers Stats and Artifacts (the hidden right sidebar's tabs)
// and New terminal moves into the More menu. Not gated on the sidebar being hidden: at
// phone widths it always is, except while the full-screen view shows it, and the
// buttons must stay mounted then so focus can return to them when it closes.
<>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={(e) => openSidebarTab("costs", e.currentTarget)}
className="text-muted hover:text-foreground ml-1 h-6 w-6 shrink-0"
aria-label="Stats"
data-testid="workspace-header-stats-button"
>
<BarChart3 className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" align="center">
Stats
</TooltipContent>
</Tooltip>
{artifactsExperimentEnabled && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={(e) => openSidebarTab("artifacts", e.currentTarget)}
className="text-muted hover:text-foreground ml-1 h-6 w-6 shrink-0"
aria-label="Artifacts"
data-testid="workspace-header-artifacts-button"
>
<AppWindow className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" align="center">
Artifacts
</TooltipContent>
</Tooltip>
)}
</>
) : (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={handleOpenTerminal}
className="text-muted hover:text-foreground ml-1 h-6 w-6 shrink-0 [&_svg]:h-4 [&_svg]:w-4"
data-tutorial="terminal-button"
aria-label="New terminal"
>
<WorkspaceTerminalIcon />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" align="center">
New terminal ({formatKeybind(KEYBINDS.OPEN_TERMINAL)})
</TooltipContent>
</Tooltip>
)}
</div>
{!isPhoneHeader && moreActionsMenu}
{rightSidebarCollapsed && !isPhoneHeader && (
// Stands in for the collapsed sidebar's overview card where the card does not fit beside
// the transcript: globals.css shows exactly one of the two.
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={() =>
window.dispatchEvent(
createCustomEvent(CUSTOM_EVENTS.EXPAND_RIGHT_SIDEBAR, { workspaceId })
)
}
aria-label="Expand right sidebar"
className={cn(
"right-sidebar-overview-expand text-muted hover:text-foreground ml-1 h-6 w-6 shrink-0",
isDesktop && "titlebar-no-drag"
)}
>
<PanelRightOpen className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" align="end">
Expand right sidebar
</TooltipContent>
</Tooltip>
)}
<LazySettingsModal
name="Heartbeat settings"
open={heartbeatModalOpen}
onClose={() => setHeartbeatModalOpen(false)}
>
<WorkspaceHeartbeatModal
workspaceId={workspaceId}
open={heartbeatModalOpen}
onOpenChange={setHeartbeatModalOpen}
/>
</LazySettingsModal>
<LazySettingsModal
name="Messaging settings"
open={unrelatedMessagingModalOpen}
onClose={() => setUnrelatedMessagingWorkspaceId(null)}
>
<WorkspaceUnrelatedMessagingDialog
// Remount per workspace: the keyed open state above only closes the dialog, while
// the modal's own pending/error state and in-flight request id would otherwise
// survive the switch and surface in the next workspace's dialog.
key={workspaceId}
workspaceId={workspaceId}
runtimeConfig={runtimeConfig}
workspace={workspaceEntry}
open={unrelatedMessagingModalOpen}
onOpenChange={(open) => setUnrelatedMessagingWorkspaceId(open ? workspaceId : null)}
/>
</LazySettingsModal>
<LazySettingsModal
name="MCP settings"
open={mcpModalOpen}
onClose={() => setMcpModalOpen(false)}
>
<WorkspaceMCPModal
workspaceId={workspaceId}
projectPath={projectPath}
open={mcpModalOpen}
onOpenChange={setMcpModalOpen}
/>
</LazySettingsModal>
<DebugLlmRequestModal
workspaceId={workspaceId}
open={debugLlmRequestOpen}
onOpenChange={setDebugLlmRequestOpen}
/>
{/* Combined confirmation for archive warnings (streaming + untracked files). */}
<ConfirmationModal {...archiveFlow.modalProps} />
<PopoverError
error={stopRuntimeError.error}
prefix="Failed to stop container"
onDismiss={stopRuntimeError.clearError}
/>
<PopoverError
error={forkError.error}
prefix="Failed to fork workspace"
onDismiss={forkError.clearError}
/>
<PopoverError
error={archiveError.error}
prefix="Failed to archive workspace"
onDismiss={archiveError.clearError}
/>
</div>
);
};

Check warning on line 1118 in src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx

View workflow job for this annotation

GitHub Actions / Quality / CRAP

CRAP crap-tax (warning)

src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx:184-1118 WorkspaceMenuBar: touched hotspot, CC 119 unchanged: consider shrinking it
6 changes: 4 additions & 2 deletions src/browser/features/Messages/ChatBarrier/RetryBarrier.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,14 @@ const RetryButton: React.FC<{ disabled: boolean; onRetry: () => void }> = (props

return (
<button
className="bg-warning font-primary text-background cursor-pointer rounded border-none px-4 py-2 text-xs font-semibold whitespace-nowrap transition-all duration-200 hover:-translate-y-px hover:brightness-120 active:translate-y-0 disabled:cursor-not-allowed disabled:opacity-50"
className="bg-warning font-primary text-background cursor-pointer rounded border-none px-4 py-2 text-xs font-semibold transition-all duration-200 hover:-translate-y-px hover:brightness-120 active:translate-y-0 disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
onClick={props.onRetry}
>
{/* The hint wraps under "Retry" as a whole, so the button fits the retry card in the
narrowest VS Code sidebar (#5645). */}
Retry{" "}
<span aria-hidden="true" className="mobile-hide-shortcut-hints">
<span aria-hidden="true" className="mobile-hide-shortcut-hints whitespace-nowrap">
({formatKeybind(KEYBINDS.RESUME_STREAM)})
</span>
</button>
Expand Down
54 changes: 44 additions & 10 deletions src/browser/features/Messages/StreamErrorMessage.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ type StreamErrorRow = Extract<DisplayedMessage, { type: "stream-error" }>;

/** About the narrowest VS Code sidebar the webview transcript was measured at (#5151). */
const NARROW_PANE_WIDTH = 200;
/** VS Code's minimum sidebar width: the narrowest pane the webview can get (#5645). */
const VSCODE_MIN_SIDEBAR_WIDTH = 170;

const OVERLOADED: StreamErrorRow = {
type: "stream-error",
Expand Down Expand Up @@ -43,7 +45,9 @@ function NarrowPane() {
const [client] = useState(() => createMockORPCClient());
return (
<APIProvider client={client}>
<div data-narrow-pane style={{ width: NARROW_PANE_WIDTH, padding: 0 }}>
{/* p-3: the VS Code webview transcript's padding (vscode/src/webview/App.tsx), so the cards
get the width they have there (#5645). */}
<div data-narrow-pane className="p-3" style={{ width: NARROW_PANE_WIDTH }}>
<StreamErrorMessage message={OVERLOADED} />
<StreamErrorMessage message={REPEATED_QUOTA} />
<RetryBarrierContent
Expand All @@ -68,8 +72,8 @@ export default meta;
type Story = StoryObj<typeof meta>;

/**
* Narrow-pane contract (#5151): the error cards' header actions and the retry card's Retry wrap
* instead of overflowing a VS Code sidebar-sized pane. The pane has a fixed width, so the fit
* Narrow-pane contract (#5151, #5645): the error cards' header actions and the retry card's Retry
* wrap instead of overflowing a VS Code sidebar-sized pane with the transcript's padding. The pane has a fixed width, so the fit
* holds at any window size, including the desktop-sized test-runner; Pixel pins the phone viewport.
*/
export const NarrowPane200: Story = {
Expand All @@ -88,14 +92,44 @@ export const NarrowPane200: Story = {
if (paneRect.width !== NARROW_PANE_WIDTH) {
throw new Error(`Pane is ${paneRect.width}px wide; expected ${NARROW_PANE_WIDTH}px`);
}
for (const element of pane.querySelectorAll<HTMLElement>("*")) {
const rect = element.getBoundingClientRect();
if (rect.width > 0 && rect.right > paneRect.right + 0.5) {
throw new Error(
`<${element.tagName.toLowerCase()} class="${element.className.toString()}"> ends at ` +
`${rect.right}px, past the ${NARROW_PANE_WIDTH}px pane (right edge ${paneRect.right}px)`
);
// Nothing may reach into its parent's right padding. In the webview, Retry with its shortcut
// hint ran into the retry card's padding in a narrow sidebar (#5645), so the retry card is also
// checked at the narrowest sidebar; then the width is restored for the snapshot.
const retryCard = [...pane.children].at(-1);
if (!(retryCard instanceof HTMLElement) || !retryCard.textContent?.includes("Retry")) {
throw new Error("The retry card is not the pane's last child");
}
const overflows = (root: HTMLElement) => {
for (const element of root.querySelectorAll<HTMLElement>("*")) {
const rect = element.getBoundingClientRect();
const parent = element.parentElement;
if (rect.width === 0 || !parent) continue;
const parentStyle = getComputedStyle(parent);
const contentRight =
parent.getBoundingClientRect().right -
parseFloat(parentStyle.paddingRight) -
parseFloat(parentStyle.borderRightWidth);
if (rect.right > contentRight + 0.5) {
return (
`${pane.style.width} pane: <${element.tagName.toLowerCase()} ` +
`class="${element.className.toString()}"> ends at ${rect.right}px, past its parent's ` +
`content box (right edge ${contentRight}px)`
);
}
}
return null;
};
try {
for (const [width, root] of [
[NARROW_PANE_WIDTH, pane],
[VSCODE_MIN_SIDEBAR_WIDTH, retryCard],
] as const) {
pane.style.width = `${width}px`;
const overflow = overflows(root);
if (overflow) throw new Error(overflow);
}
} finally {
pane.style.width = `${NARROW_PANE_WIDTH}px`;
}
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import * as ContextUsageSectionModule from "./ContextUsageSection";
import * as StatsTabModule from "./StatsTab";
import { StatsContainer } from "./StatsContainer";

// While the right sidebar is CSS-hidden it stays mounted with its Stats tab, and the Stats dialog
// (#5767) mounts a second StatsContainer. A choice made in one must show in the other.
// Two mounted StatsContainers share the sub-tab choice: a choice made in one must show in the
// other. The Stats dialog that needed this is gone (#6140); the sync stays for any second mount.
describe("StatsContainer copies", () => {
let cleanupDom: (() => void) | null = null;

Expand Down
4 changes: 2 additions & 2 deletions src/browser/features/RightSidebar/StatsContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ interface StatsContainerProps {
}

export function StatsContainer(props: StatsContainerProps) {
// listener: every mounted copy shows the same choice. The panels' view preferences listen for
// the same reason.
// listener: every mounted copy, in this window or another tab, shows the same choice. The
// panels' view preferences listen for the same reason.
const [subTab, setSubTab] = usePersistedState<StatsSubTab>(STATS_CONTAINER_SUB_TAB_KEY, "cost", {
listener: true,
});
Expand Down
6 changes: 3 additions & 3 deletions src/browser/features/RightSidebar/rightSidebarVisibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { NARROW_VIEWPORT_MAX_WIDTH_PX } from "@/constants/layout";
/**
* True when the right sidebar container is hidden by the responsive (narrow) layout. Immersive
* review hides it too, with the same display:none, but marks it aria-hidden: that is not a
* responsive hide, so the dialog entry points stay off and the sidebar keeps its shortcuts.
* WorkspaceMenuBar (dialog fallbacks) and RightSidebar (its own shortcuts) both read this, so
* exactly one of them acts on a shortcut such as Ctrl+Shift+K.
* responsive hide, so the full-screen entry points stay off and the sidebar keeps its shortcuts.
* WorkspaceMenuBar (opens a tab full-screen while the sidebar is hidden) and RightSidebar (its
* own shortcuts) both read this, so exactly one of them acts on a sidebar shortcut.
*/
export function isRightSidebarResponsivelyHidden(sidebar: HTMLElement): boolean {
if (sidebar.getAttribute("aria-hidden") === "true") {
Expand Down
2 changes: 1 addition & 1 deletion src/browser/hooks/useAIViewKeybinds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,179 +55,179 @@
*
* Note: In vim mode, Ctrl+C always interrupts streams. Use vim yank (y) commands for copying.
*/
export function useAIViewKeybinds({
workspaceId,
canInterrupt,
showRetryBarrier,
chatInputAPI,
jumpToBottom,
loadOlderHistory,
showNewerMessages = null,
handleOpenTerminal,
handleOpenInEditor,
aggregator,
setEditingMessage,
vimEnabled,
canResumeInterruptedStream = false,
resumeInterruptedStream,
}: UseAIViewKeybindsParams): void {
const { api } = useAPI();
// The main chat and the /side chat tab both mount these window listeners; only the pane that
// owns the event's target acts, so Esc/Ctrl+I/Shift+G never hit both chats at once.
const paneScope = useChatPaneScope();

useEffect(() => {
const handleInterruptKeyDown = (e: KeyboardEvent) => {
if (!paneHandlesKeyEvent(paneScope, e.target)) return;
// Check vim-aware interrupt keybind
const interruptKeybind = vimEnabled
? KEYBINDS.INTERRUPT_STREAM_VIM
: KEYBINDS.INTERRUPT_STREAM_NORMAL;

const browserViewportOwnsInterrupt = vimEnabled && isBrowserViewportFocused(e.target);

// Interrupt stream: Ctrl+C in vim mode, Esc in normal mode.
// Skip if the terminal owns Ctrl+C first, or if the focused browser viewport is using
// the vim-mode Ctrl+C keystroke itself. Keep Escape behavior unchanged for browser tabs.
//
// IMPORTANT: This handler runs in **bubble phase** so dialogs/popovers can stopPropagation()
// on Escape without accidentally interrupting a stream.
if (
matchesKeybind(e, interruptKeybind) &&
!isTerminalFocused(e.target) &&
!isDesktopViewportFocused(e.target) &&
!browserViewportOwnsInterrupt
) {
// If something else already claimed this key event, skip.
if (e.defaultPrevented) {
return;
}

// An open overlay (tutorial, narrow-screen drawer) takes this Escape to close itself.
// An open overlay (the narrow-screen drawer) takes this Escape to close itself.
if (interruptKeybind === KEYBINDS.INTERRUPT_STREAM_NORMAL && isEscapeDismissOverlayOpen()) {
return;
}

// Normal mode uses Escape; skip when typing in inputs unless explicitly opted in.
if (
interruptKeybind === KEYBINDS.INTERRUPT_STREAM_NORMAL &&
isEditableElement(e.target) &&
!allowsEscapeToInterruptStream(e.target)
) {
return;
}

// ask_user_question is a special waiting state: don't interrupt it with Esc/Ctrl+C.
// Users can still respond via the questions UI, or type in chat to cancel.
if (aggregator?.hasAwaitingUserQuestion()) {
return;
}

if (canInterrupt && aggregator && isCompactingStream(aggregator)) {
// Ctrl+C during compaction: restore original state and enter edit mode
// Stores cancellation marker in localStorage (persists across reloads)
e.preventDefault();
if (api) {
void cancelCompaction(api, workspaceId, aggregator, setEditingMessage);
}
return;
}

// Normal stream interrupt (non-compaction)
// Vim mode: Ctrl+C always interrupts (vim uses yank for copy, not Ctrl+C)
// Non-vim mode: Esc interrupts (except when typing in inputs, unless explicitly opted in)
if (canInterrupt || showRetryBarrier) {
e.preventDefault();
if (api) {
void stopStream(api, workspaceId, { disableAutoRetry: true });
}
return;
}
}
};

const handleKeyDownCapture = (e: KeyboardEvent) => {
if (!paneHandlesKeyEvent(paneScope, e.target)) return;
// Remote desktops own their keyboard, including chat/editor shortcuts.
if (isDesktopViewportFocused(e.target)) return;
const dialogOpen = isDialogOpen();

// Focus chat input works anywhere (even in input fields)
if (matchesKeybind(e, KEYBINDS.FOCUS_CHAT)) {
e.preventDefault();
// Same rule as the creation screen: focus must not move behind the command palette (#5752).
if (!dialogOpen && !isCommandPaletteTarget(e.target)) chatInputAPI.current?.focus();
return;
}

// Open in editor / terminal - work even in input fields (global feel, like TOGGLE_AGENT)
if (matchesKeybind(e, KEYBINDS.OPEN_IN_EDITOR)) {
e.preventDefault();
if (!dialogOpen) handleOpenInEditor();
return;
}
if (matchesKeybind(e, KEYBINDS.OPEN_TERMINAL)) {
e.preventDefault();
if (!dialogOpen) handleOpenTerminal();
return;
}

// Don't handle other shortcuts if user is typing in an input field
if (dialogOpen || isEditableElement(e.target)) {
return;
}

// Resume an interrupted stream. Like Shift+G/Shift+H, this is a
// transcript-scoped key: gated below the editable guard so Shift+R types
// normally while composing. Only acts when a resumable turn is shown.
if (
matchesKeybind(e, KEYBINDS.RESUME_STREAM) &&
canResumeInterruptedStream &&
resumeInterruptedStream
) {
e.preventDefault();
resumeInterruptedStream();
return;
}

const transcriptAction = [
{ keybind: KEYBINDS.LOAD_OLDER_MESSAGES, run: loadOlderHistory },
{ keybind: KEYBINDS.SHOW_NEWER_MESSAGES, run: showNewerMessages },
{ keybind: KEYBINDS.JUMP_TO_BOTTOM, run: jumpToBottom },
].find((action) => matchesKeybind(e, action.keybind))?.run;
if (transcriptAction) {
e.preventDefault();
transcriptAction();
}
};

// Use capture phase for non-destructive keybinds so they work even when terminal is focused
// (terminal components may consume events in bubble phase).
window.addEventListener("keydown", handleKeyDownCapture, { capture: true });

// Interrupt keybind is handled separately in bubble phase (see comment above).
window.addEventListener("keydown", handleInterruptKeyDown);

return () => {
window.removeEventListener("keydown", handleKeyDownCapture, { capture: true });
window.removeEventListener("keydown", handleInterruptKeyDown);
};
}, [
jumpToBottom,
loadOlderHistory,
showNewerMessages,
handleOpenTerminal,
handleOpenInEditor,
workspaceId,
canInterrupt,
showRetryBarrier,
chatInputAPI,
aggregator,
setEditingMessage,
vimEnabled,
canResumeInterruptedStream,
resumeInterruptedStream,
api,
paneScope,
]);
}

Check warning on line 233 in src/browser/hooks/useAIViewKeybinds.ts

View workflow job for this annotation

GitHub Actions / Quality / CRAP

CRAP crap-tax (warning)

src/browser/hooks/useAIViewKeybinds.ts:58-233 useAIViewKeybinds: touched hotspot, CC 40 unchanged: consider shrinking it
20 changes: 10 additions & 10 deletions src/browser/stories/App.phoneViewports.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -553,15 +553,15 @@ export const IPhone17ProMaxTouchReviewImmersive: AppStory = {
},
};

const TIMELINE_DIALOG_WORKSPACE_ID = "ws-iphone-16e-timeline";
const TIMELINE_DIALOG_BASE_TS = Date.UTC(2020, 0, 15, 15, 0, 0);
const TIMELINE_DIALOG_EVENTS: TimelineEvent[] = [
const TIMELINE_FULLSCREEN_WORKSPACE_ID = "ws-iphone-16e-timeline";
const TIMELINE_FULLSCREEN_BASE_TS = Date.UTC(2020, 0, 15, 15, 0, 0);
const TIMELINE_FULLSCREEN_EVENTS: TimelineEvent[] = [
{
v: 1,
id: "turn-completed",
kind: "turn.completed",
seq: 3,
ts: TIMELINE_DIALOG_BASE_TS,
ts: TIMELINE_FULLSCREEN_BASE_TS,
source: { system: "chat" },
status: "completed",
data: { model: "anthropic/claude-sonnet-4", mode: "exec", durationMs: 84_000 },
Expand All @@ -572,10 +572,10 @@ const TIMELINE_DIALOG_EVENTS: TimelineEvent[] = [
id: "agent-milestone",
kind: "agent.event",
seq: 2,
ts: TIMELINE_DIALOG_BASE_TS - 45_000,
ts: TIMELINE_FULLSCREEN_BASE_TS - 45_000,
source: { system: "agent", key: "timeline-event:milestone" },
data: {
description: "Wired the mobile timeline dialog behind the workspace actions menu",
description: "Opened the Timeline tab full-screen from the workspace actions menu",
category: "milestone",
},
},
Expand All @@ -584,7 +584,7 @@ const TIMELINE_DIALOG_EVENTS: TimelineEvent[] = [
id: "goal-set",
kind: "goal.set",
seq: 1,
ts: TIMELINE_DIALOG_BASE_TS - 90_000,
ts: TIMELINE_FULLSCREEN_BASE_TS - 90_000,
source: { system: "goal" },
status: "started",
data: { digest: "Make the timeline reachable at phone widths" },
Expand All @@ -604,11 +604,11 @@ export const IPhone16eTimeline: AppStory = {
<AppWithMocks
setup={() => {
const client = setupSimpleChatStory({
workspaceId: TIMELINE_DIALOG_WORKSPACE_ID,
workspaceId: TIMELINE_FULLSCREEN_WORKSPACE_ID,
workspaceName: "mobile-timeline",
projectName: "mux",
messages: [...MESSAGES],
timelineEvents: TIMELINE_DIALOG_EVENTS,
timelineEvents: TIMELINE_FULLSCREEN_EVENTS,
});
return client;
}}
Expand All @@ -635,7 +635,7 @@ export const IPhone16eTimeline: AppStory = {
const sidebar = await canvas.findByRole("complementary", { name: "Workspace insights" });
await userEvent.click(await within(sidebar).findByRole("button", { name: /^Timeline/ }));
await within(sidebar).findByText(
"Wired the mobile timeline dialog behind the workspace actions menu",
"Opened the Timeline tab full-screen from the workspace actions menu",
undefined,
{ timeout: 10_000 }
);
Expand Down
2 changes: 1 addition & 1 deletion src/browser/utils/commands/sources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2527,7 +2527,7 @@ describe("explicit sidebar navigation from a collapsed chat", () => {
});

describe("Right Sidebar: Add Tool palette action (#5767)", () => {
test("Stats also asks for the Stats dialog; other tools do not", async () => {
test("Stats also asks to show the Stats tab full-screen; other tools do not", async () => {
await withTestWindow(async () => {
const action = getActions().find(
(candidate) => candidate.id === CommandIds.navRightSidebarAddTool()
Expand Down
34 changes: 24 additions & 10 deletions tests/bugbash/repros/detailsShortcuts.e2e.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// #5671: after Ctrl+Shift+D and Escape, focus returns to the Workspace details button. The button
// stopped every key, so global shortcuts did nothing until you clicked elsewhere.
// #5671: after the Workspace details shortcut opens the popover and the dismiss key closes it,
// focus returns to the Workspace details button. The button stopped every key, so global
// shortcuts did nothing until you clicked elsewhere.
import { test } from "@e2e-dev/web";
import { expect } from "e2e";
import {
Expand Down Expand Up @@ -32,13 +33,26 @@ test(
// The precondition of the bug: Radix returns focus to the trigger.
await expect(screen.getByRole("button", "Workspace details")).toBeFocused();

// Any global shortcut shows it; this one toggles notifications (see notificationsShortcut).
await browser.keyboard.press("Control+Shift+Comma");
await expectNotifyOnAllResponses(screen, browser, true);

// Every repro in a run shares this workspace: turn the setting back off.
await screen.getByRole("textbox", "Message").tap();
await browser.keyboard.press("Control+Shift+Comma");
await expectNotifyOnAllResponses(screen, browser, false);
try {
// Any global shortcut shows it; this one toggles notifications (see notificationsShortcut).
await browser.keyboard.press("Control+Shift+Comma");
await expectNotifyOnAllResponses(screen, browser, true);
} finally {
// Every repro in a run shares this workspace: turn the setting back off, also after a
// failure, or later repros fail as knock-on failures (#5761). The shortcut may not have
// turned it on, so toggle only when the bell says it is on.
const notifying = await browser.evaluate(
() =>
document
.querySelector('[data-testid="notify-on-response-button"]')
?.getAttribute("aria-description")
?.endsWith(": on") ?? false
);
if (notifying) {
await screen.getByRole("textbox", "Message").tap();
await browser.keyboard.press("Control+Shift+Comma");
await expectNotifyOnAllResponses(screen, browser, false);
}
}
}
);
6 changes: 3 additions & 3 deletions tests/ui/rightSidebar/timeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -875,9 +875,9 @@ describe("TimelinePanel", () => {
});

test("ignores the reveal shortcut in a panel hidden behind an open modal", async () => {
// A CSS-hidden sidebar keeps its panel mounted while the mobile timeline dialog mounts a
// second one; Radix marks content outside the open modal aria-hidden. The hidden panel's
// window-level shortcut listener must not fire a competing reveal.
// A CSS-hidden sidebar keeps its panel mounted while a modal is open; Radix marks content
// outside the open modal aria-hidden. The hidden panel's window-level shortcut listener must
// not fire a reveal behind the modal.
const event = makeEvent("anchored", "turn.completed", 1, {
anchor: { messageId: "loaded-message" },
});
Expand Down
Loading