diff --git a/AGENTS.md b/AGENTS.md index 920fa232af7ca..b133ebc00e0b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,7 +149,7 @@ Read the matching doc before changing code in that area; code review enforces th - Client mutations use `createEnvironmentRpcCommand`, declare protected methods in `CLIENT_GUARDED_RPC_SCOPES`, and gate UI with `permissionAtom` (server stays authoritative). Keep raw RPC clients inside `rpc/`. - Server features are Effect services using `Effect.fn("Service.operation")` with thin transport handlers; see [02_effect-services.md](docs/internals/02_effect-services.md). - `apps/web/src/components/ui` exports own their look (`shadcn/no-restyle` enforces this); see [10_web-ui.md](docs/internals/10_web-ui.md). -- Before building UI, open `/design-system` in a dev build: it renders every primitive, variant and type role. Text takes a role (`` or `text-title` … `text-micro`), not `text-sm` or `font-medium`; a clickable thing is a `components/ui` control, not a styled ` + {open ? ( + + {}} /> + + + ) : null} + + ); +} + +it.each(["Escape", "Close"])("returns focus to the launcher on %s", async (method) => { + await using screen = await render(); + const launcher = screen.getByRole("button", { name: "Settings launcher" }); + await launcher.click(); + await expect.element(page.getByRole("dialog", { name: "Settings" })).toBeVisible(); + if (method === "Escape") await userEvent.keyboard("{Escape}"); + else + ( + page.getByRole("button", { name: "Close", exact: true }).element() as HTMLButtonElement + ).click(); + await expect.element(launcher).toHaveFocus(); +}); diff --git a/apps/web/src/components/AppSidebarLayout.browser.test.tsx b/apps/web/src/components/AppSidebarLayout.browser.test.tsx index c97ea5e6412aa..1535be4eb8d2d 100644 --- a/apps/web/src/components/AppSidebarLayout.browser.test.tsx +++ b/apps/web/src/components/AppSidebarLayout.browser.test.tsx @@ -1,5 +1,6 @@ import { page, userEvent } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; +import type { ReactNode } from "react"; import { render } from "../../test/render"; @@ -14,11 +15,15 @@ vi.mock(import("../state/server"), async (original) => { }); // The thread list needs live environments; the shortcut lives in the shell around it. vi.mock(import("./Sidebar"), () => ({ default: (() => null) as never })); +// Pane routing is outside this shell shortcut test. +vi.mock(import("../layout/WorkspacePlane"), () => ({ + WorkspacePlane: ({ children }: { children: ReactNode }) => <>{children}, +})); import { AppSidebarLayout } from "./AppSidebarLayout"; describe("sidebar toggle shortcut", () => { - it("leaves the key to a focused terminal when its rule excludes terminalFocus", async () => { + it("leaves the key to a focused terminal when its rule excludes terminalFocus, and swallows held repeats", async () => { await page.viewport(1280, 800); using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); await using screen = await render( @@ -38,5 +43,19 @@ describe("sidebar toggle shortcut", () => { await userEvent.click(screen.getByRole("button", { name: "Outside" })); await userEvent.keyboard("{Control>}b{/Control}"); await vi.waitFor(() => expect(wrapper.getAttribute("data-sidebar-state")).toBe("collapsed")); + + const repeat = new KeyboardEvent("keydown", { + key: "b", + code: "KeyB", + ctrlKey: true, + repeat: true, + bubbles: true, + cancelable: true, + }); + expect(screen.getByRole("button", { name: "Outside" }).element().dispatchEvent(repeat)).toBe( + false, + ); + await userEvent.keyboard("{Control>}b{/Control}"); + await vi.waitFor(() => expect(wrapper.getAttribute("data-sidebar-state")).toBe("expanded")); }); }); diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 644371af8f078..c4b890cfdcec8 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -10,7 +10,7 @@ import { type CSSProperties, type ReactNode, } from "react"; -import { useLocation, useRouter, type AnyRouter } from "@tanstack/react-router"; +import { useLocation, useParams, useRouter, type AnyRouter } from "@tanstack/react-router"; import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react"; import { moveWorkspaceFocus, workspaceAreaProps } from "../lib/workspaceFocus"; @@ -55,8 +55,19 @@ import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer"; import { HistorySwipeNavigation } from "./HistorySwipeNavigation"; import ThreadSidebar from "./Sidebar"; import { isAppModalPage } from "./sidebar/mainAppLocation"; -import { SidebarChromeHeader } from "./sidebar/SidebarChrome"; +import { resolveThreadRouteTarget } from "../threadRoutes"; +import { selectFocusedTab } from "../layout/layoutModel"; +import { useLayoutStore } from "../layout/layoutStore"; +import { isLayoutDragActive } from "../layout/layoutDrag"; +import { isModalDialogOpen } from "../lib/modalDialog"; +import { SidebarChromeBrand, SidebarChromeHeader } from "./sidebar/SidebarChrome"; import type { SidebarRouteReveal } from "./sidebar/routeReveal"; +import { WorkspacePlane } from "../layout/WorkspacePlane"; +import { + onOverviewBackgroundPointerDown, + overviewZoomTransition, + useOverviewPhase, +} from "../layout/Overview"; import { ChromeChannelArt, useSidebarStageBackdropVariant } from "./SidebarStageBackdrop"; import { clampThreadSidebarWidth, @@ -81,6 +92,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { registerCommands, registerMenuAction } from "../shortcuts/dispatcher"; import { resolveThreadRouteRef } from "../threadRoutes"; +import { CLOSED_SIDEBAR_CONTROLS_SURFACE_CLASS } from "../workspaceTitlebar"; import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome"; const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)"; @@ -215,7 +227,7 @@ function registerWorkspaceFocusCommands(router: AnyRouter): () => void { }; } -// Escape leaves the pull requests page when no scope (a selection, a dialog, +// Escape leaves the pull requests or issues page when no scope (a selection, a dialog, // a drag) claimed it, so it observes after every other scope. function registerPullRequestsEscapeCommand(router: AnyRouter): () => void { return registerCommands( @@ -223,7 +235,21 @@ function registerPullRequestsEscapeCommand(router: AnyRouter): () => void { { observe: (event, consumed) => { if (consumed || event.repeat || event.isComposing || event.key !== "Escape") return; - if (router.state.location.pathname !== "/pull-requests") return; + const page = router.state.location.pathname; + if ( + (page !== "/pull-requests" && page !== "/issues" && page !== "/workflows") || + isCommandPaletteOpen() || + isModalDialogOpen() || + isLayoutDragActive() + ) + return; + const focusedKind = selectFocusedTab(useLayoutStore.getState().layout)?.content.kind; + if ( + focusedKind !== "pull-requests" && + focusedKind !== "issues" && + focusedKind !== "workflows" + ) + return; event.preventDefault(); const activeElement = document.activeElement; if (activeElement instanceof HTMLElement) activeElement.blur(); @@ -321,7 +347,7 @@ function registerAppShellCommands(router: AnyRouter, shellElement: Element): () registerPullRequestsEscapeCommand(router), registerMenuAction("open-settings", () => { if (!/^\/settings(\/|$)/.test(router.state.location.pathname)) - void router.navigate({ to: "/settings" }); + void router.navigate({ to: "/settings", search: { pane: undefined } }); }), ]; return () => { @@ -343,11 +369,16 @@ function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { context: { usagePageOpen }, }); const onStageBackdrop = isSidebarVisible && stageBackdropVariant !== null; + const overviewPhase = useOverviewPhase(); + const overviewShown = overviewPhase === "opening" || overviewPhase === "open"; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener that toggles the sidebar on its shortcut useEffect(() => { // A hidden sidebar would still save the toggle, so the shortcut does nothing without one. if (!showSidebar) return; + const toggleOutsideOverview = () => { + if (!useLayoutStore.getState().overviewOpen) toggleSidebar(); + }; const onKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented) return; if ( @@ -356,13 +387,19 @@ function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { ) { return; } + const composer = + event.target instanceof HTMLElement + ? event.target.closest('[data-composer-rich-text="true"]') + : null; + const selection = window.getSelection(); if ( - isRichTextBoldShortcut(event, window.getSelection()) && - event.target instanceof HTMLElement && - event.target.closest('[data-composer-rich-text="true"]') + isRichTextBoldShortcut(event, selection) && + composer && + selection && + composer.contains(selection.anchorNode) ) { - // The rich-text composer claims Mod+B only to bold selected text; - // the toggle stays available everywhere else. + // The rich-text composer claims Mod+B to bold text selected in it; + // with just a caret, and everywhere else, it toggles the sidebar. return; } if ( @@ -379,12 +416,12 @@ function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { event.preventDefault(); event.stopPropagation(); - toggleSidebar(); + if (!event.repeat) toggleOutsideOverview(); }; window.addEventListener("keydown", onKeyDown, true); const unsubscribe = window.desktopBridge?.onMenuAction((action) => { - if (action === "sidebar.toggle") toggleSidebar(); + if (action === "sidebar.toggle") toggleOutsideOverview(); }); return () => { window.removeEventListener("keydown", onKeyDown, true); @@ -404,6 +441,7 @@ function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { ref={appShellCommandsRef} className={cn( "pointer-events-none fixed left-[var(--workspace-controls-left)] top-[var(--workspace-controls-top)] z-50 ml-px flex h-[var(--workspace-topbar-height)] items-center", + CLOSED_SIDEBAR_CONTROLS_SURFACE_CLASS, mobileSidebarSheetMounted && "hidden", )} // Sits on the window chrome, so it takes the black chrome tokens too. @@ -411,25 +449,56 @@ function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { data-sidebar-control="" > {showSidebar ? ( - - - } - /> - - {shortcutLabel - ? gt("Toggle main sidebar ({shortcut})", { shortcut: shortcutLabel }) - : gt("Toggle main sidebar")} - - +
+ + + } + /> + + {shortcutLabel + ? gt("Toggle main sidebar ({shortcut})", { shortcut: shortcutLabel }) + : gt("Toggle main sidebar")} + + +
+ ) : null} + {showSidebar ? ( +
+
+ +
+
) : null} {/* Phones keep the header for the page; the system back gesture covers them. */}
@@ -521,8 +590,16 @@ export function AppSidebarLayout({ const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } = usePanelAnimationSettings(); const pathname = useLocation({ select: (location) => location.pathname }); - const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname); - const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed; + // Each chat suppresses its own panels (SurfaceHost). A flip here on a chat switch would + // re-render every mounted chat twice and restyle the shell, whose eased sizes stay put. + const onChatRoute = useParams({ + strict: false, + select: (params) => resolveThreadRouteTarget(params) !== null, + }); + const pagePanelAnimationsSuppressed = usePanelNavigationSuppression( + onChatRoute ? "chat" : pathname, + ); + const routePanelAnimationsActive = panelAnimationsActive && !pagePanelAnimationsSuppressed; const isOnDesignSystem = DesignSystemSidebarNav !== null && (pathname === "/design-system" || pathname.startsWith("/design-system/")); @@ -554,6 +631,12 @@ export function AppSidebarLayout({ }); const environmentIdentificationMode = useEnvironmentIdentificationMode(); const chromeArtVariant = useSidebarStageBackdropVariant(environmentIdentificationMode); + const overviewPhase = useOverviewPhase(); + const overviewStaged = overviewPhase !== "closed" && !isMobileLayout; + const overviewShown = overviewPhase === "opening" || overviewPhase === "open"; + // Set on the app's root whether staged or not: an inherited variable that + // changes there restyles every element in the app. + const overviewTransition = overviewZoomTransition(); const hideWindowControlsWhenSidebarCollapsed = useHideWindowControlsWhenSidebarCollapsed(); const isWindowFullscreen = useSyncExternalStore( subscribeToWindowFullscreen, @@ -578,6 +661,8 @@ export function AppSidebarLayout({ : {} ) as CSSProperties; const sidebarProviderStyle = { + "--overview-sidebar-duration": overviewTransition.transitionDuration, + "--overview-sidebar-easing": overviewTransition.transitionTimingFunction, "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`, "--panel-animation-duration": `${panelAnimationDurationMs}ms`, ...windowControlsInsetStyle, @@ -596,66 +681,95 @@ export function AppSidebarLayout({ }, [isMacosDesktop, windowControlsHidden]); return ( - - +
[data-slot=sidebar-inner]]:transition-opacity md:[&_[data-app-sidebar][data-overview-zoom]>[data-slot=sidebar-inner]]:duration-(--overview-sidebar-duration) md:[&_[data-app-sidebar][data-overview-zoom]>[data-slot=sidebar-inner]]:ease-(--overview-sidebar-easing)", + "md:[&_[data-app-sidebar][data-overview-zoom=opening]>[data-slot=sidebar-inner]]:opacity-0 md:[&_[data-app-sidebar][data-overview-zoom=open]>[data-slot=sidebar-inner]]:opacity-0", + )} > - {showSidebar ? ( - <> - - {chromeArtVariant ? : null} - - nextWidth <= currentWidth || - wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH, - storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY, - onResize: setSidebarWidth, - }} - style={windowControlsInsetStyle} - > - {isOnDesignSystem && DesignSystemSidebarNav ? ( - <> - - - - - - ) : ( - - )} - - - - ) : null} - {children} - - {isElectron ? ( - // The chrome strip above the inset pane moves the window like the - // header rows on either side of it. -
- ) : null} - - {isElectron ? : null} - + + {showSidebar ? ( + <> + + {chromeArtVariant ? : null} + + nextWidth <= currentWidth || + wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH, + storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY, + onResize: setSidebarWidth, + }} + className={cn(overviewStaged && "z-35")} + data-overview-zoom={overviewStaged ? overviewPhase : undefined} + // Not inert: flipping inert restyles the whole thread list. The + // overview owns the keyboard, and the cover below takes presses. + aria-hidden={(overviewStaged && overviewShown) || undefined} + style={ + overviewStaged + ? { + ...windowControlsInsetStyle, + ...overviewTransition, + } + : windowControlsInsetStyle + } + > + {isOnDesignSystem && DesignSystemSidebarNav ? ( + <> + + + + + + ) : ( + + )} + + {overviewStaged && overviewShown ? ( + // A press on the faded sidebar is a press on the overview's backdrop. +
+ ) : null} + + + ) : null} + {children} + + {isElectron ? ( + // The chrome strip above the inset pane moves the window like the + // header rows on either side of it. +
+ ) : null} + + {isElectron ? : null} + +
); } diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index 550fbea828b81..56dff85fa6654 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -111,18 +111,20 @@ const CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX = 16; export type ContextStripCompaction = "none" | "labels" | "branch"; +export function readContextStripCompaction(value: string | undefined): ContextStripCompaction { + return value === "labels" || value === "branch" ? value : "none"; +} + export function resolveContextStripCompaction(input: { current: ContextStripCompaction; neededWidth: number; + labelsNeededWidth: number; availableWidth: number; - labelsSavedWidth: number; }): ContextStripCompaction { const fits = (width: number, expanding: boolean) => width <= input.availableWidth - (expanding ? CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX : 0); if (fits(input.neededWidth, input.current !== "none")) return "none"; - if (fits(input.neededWidth - input.labelsSavedWidth, input.current === "branch")) { - return "labels"; - } + if (fits(input.labelsNeededWidth, input.current === "branch")) return "labels"; return "branch"; } diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index acd420fd6876b..8eb9c72a4e59d 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -9,6 +9,7 @@ import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-action import { readLocalApi } from "../localApi"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; import { msg, T, useGT, useMessages } from "gt-react"; import { m as resolveMessage } from "../i18n/messages"; @@ -35,11 +36,12 @@ import { flushSync } from "react-dom"; import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; -import { useProject, useThreadShellsForProjectRefs } from "../state/entities"; +import { useProject, useServerConfigs, useThreadShellsForProjectRefs } from "../state/entities"; import { ADD_TO_MACHINE_LABEL_CLASS, type EnvMode, type EnvironmentOption, + readContextStripCompaction, resolveContextStripCompaction, type ContextStripCompaction, resolveCurrentWorkspaceLabel, @@ -64,7 +66,6 @@ import { useEnvironmentQuery } from "../state/query"; import { vcsEnvironment } from "../state/vcs"; import { PreviousWorktreeItemContent } from "./PreviousWorktreeItemContent"; import { WorktreeRepositoriesControl } from "./WorktreeRepositoriesControl"; -import { useWorktreeBaseBranch } from "../worktreeRepositoryChoiceStore"; import { ThreadDetailsControl } from "./chat/ThreadDetailsControl"; import { THREAD_DETAILS_PANEL_ICON_CLASS, @@ -89,9 +90,10 @@ import { MiddleTruncate } from "./ui/middle-truncate"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ComposerSurface } from "./chat/ComposerSurface"; import { measureRestingComposerControls } from "./chat/restingComposerControlsMeasurement"; +import { contextStripGroupWidth } from "./contextStripMeasurement"; import { resolveRestingComposerControlsMinimumWidth, - resolveRestingComposerControlsNaturalWidth, + resolveRestingComposerControlsNarrowestWidth, } from "./composerFooterLayout"; import { useComposerMenuProps } from "./chat/composerEventScope"; import { cn } from "~/lib/utils"; @@ -103,11 +105,13 @@ const isClipboardWriteError = Schema.is(ClipboardWriteError); export interface BranchToolbarHandle { openBranchPicker: () => void; + focusBranchPicker: () => void; usePreviousWorktree: () => void; } interface BranchToolbarProps { layout?: "composer" | "panel"; + onOpenWorkspaceDetails?: (() => void) | undefined; panelSection?: "all" | "workspace" | "branch"; forceNewWorktree?: boolean; ref?: Ref; @@ -141,6 +145,8 @@ interface BranchToolbarProps { environmentUnavailable?: boolean; /** Panel only: where the branch picker renders the thread's PR rows. */ panelPrRowsContainer?: HTMLElement | null; + /** Panel-only actions that belong to the environment, such as opening its editor. */ + panelEnvironmentActions?: ReactNode; } interface WorkspaceMenuProps { @@ -153,40 +159,30 @@ interface WorkspaceMenuProps { children: ReactNode; onContextMenu: (event: ReactMouseEvent) => void; }; - /** List Run on here because no machine chip is shown, as on local threads. */ - showRunOn: boolean; forceNewWorktree: boolean; - autoEnvironmentLabel?: string | undefined; - onAutoEnvironment?: (() => void) | undefined; - envLocked: boolean; envModeLocked: boolean; environmentId: EnvironmentId; - availableEnvironments: readonly EnvironmentOption[] | undefined; - showEnvironmentPicker: boolean; - onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined; effectiveEnvMode: EnvMode; activeWorktreePath: string | null; onEnvModeChange: (mode: EnvMode) => void; workspaceRoot: string; previousWorktree: PreviousWorktreeSeed | null; onUsePreviousWorktree: () => void; +} + +interface MachineMenuProps { + autoEnvironmentLabel?: string | undefined; + onAutoEnvironment?: (() => void) | undefined; + envLocked: boolean; + environmentId: EnvironmentId; + availableEnvironments: readonly EnvironmentOption[] | undefined; + showEnvironmentPicker: boolean; + onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined; + environmentUnavailable: boolean; addTargets: readonly AddProjectTarget[]; onAddToMachine: (environmentId: EnvironmentId) => void; } -type MachineMenuProps = Pick< - WorkspaceMenuProps, - | "autoEnvironmentLabel" - | "onAutoEnvironment" - | "envLocked" - | "environmentId" - | "availableEnvironments" - | "showEnvironmentPicker" - | "onEnvironmentChange" - | "addTargets" - | "onAddToMachine" -> & { environmentUnavailable: boolean }; - /** "2h ago · 3 files changed" for the previous worktree row; the count is read while open. */ function PreviousWorktreeMeta({ environmentId, @@ -224,29 +220,19 @@ function PreviousWorktreeMeta({ /** The composer's workspace and branch chip. Machines have their own chip, `MachineMenu`. */ const WorkspaceMenu = memo(function WorkspaceMenu({ branch, - showRunOn, forceNewWorktree, - autoEnvironmentLabel, - onAutoEnvironment, - envLocked, envModeLocked, environmentId, - availableEnvironments, - showEnvironmentPicker, - onEnvironmentChange, effectiveEnvMode, activeWorktreePath, onEnvModeChange, workspaceRoot, previousWorktree, onUsePreviousWorktree, - addTargets, - onAddToMachine, }: WorkspaceMenuProps) { const gt = useGT(); const m = useMessages(); const composerFloatingLayerProps = useComposerMenuProps(); - const connectedEnvironmentIds = useConnectedEnvironmentIds(); const [workspaceOpen, setWorkspaceOpen] = useState(false); const popupRef = useRef(null); const open = branch?.open ?? workspaceOpen; @@ -260,22 +246,23 @@ const WorkspaceMenu = memo(function WorkspaceMenu({ : effectiveEnvMode === "worktree" ? resolveEnvModeLabel("worktree", m) : resolveCurrentWorkspaceLabel(activeWorktreePath, m); - const canPickEnvironment = (showEnvironmentPicker && !envLocked) || addTargets.length > 0; const icon = ; - if (envModeLocked && !(showRunOn && canPickEnvironment) && !branch) { + if (envModeLocked && !branch) { return ( } > {icon} + {workspaceLabel} {workspaceLabel} @@ -304,6 +291,7 @@ const WorkspaceMenu = memo(function WorkspaceMenu({ render={ } + data-pressed={open ? "" : undefined} className={branch ? "min-w-0 max-w-full" : envModeLocked ? "ps-2 pe-0.5" : "ps-2"} aria-label={ branch @@ -312,10 +300,7 @@ const WorkspaceMenu = memo(function WorkspaceMenu({ } onContextMenu={branch?.onContextMenu} data-composer-context-control - data-composer-shortcut={[ - showRunOn && canPickEnvironment ? "composer.host" : "", - !envModeLocked ? "composer.workspace" : "", - ].join(" ")} + data-composer-shortcut={envModeLocked ? undefined : "composer.workspace"} /> } > @@ -323,7 +308,11 @@ const WorkspaceMenu = memo(function WorkspaceMenu({ {envModeLocked && !branch ? null : ( <> - {branch?.label ?? workspaceLabel} + {branch ? ( + + ) : ( + workspaceLabel + )} - {showRunOn && availableEnvironments && availableEnvironments.length > 0 ? ( - - - Run on - - - value === "auto" - ? onAutoEnvironment?.() - : onEnvironmentChange?.(value as EnvironmentId) - } - > - {availableEnvironments.map((env) => ( - - - - {env.label} - {env.isPrimary ? null : connectedEnvironmentIds.includes(env.environmentId) ? ( - - Online - - ) : ( - - Offline - - )} - - - ))} - {onAutoEnvironment && ( - { - if (autoEnvironmentLabel) onAutoEnvironment?.(); - }} - > - - - - )} - - {addTargets.length > 0 ? ( - - - - - - Add to another machine - - - - - {addTargets.map((target) => ( - onAddToMachine(target.environmentId)} - > - - - {target.label} - - - ))} - - - ) : null} - - ) : null} Workspace @@ -448,7 +348,7 @@ const WorkspaceMenu = memo(function WorkspaceMenu({ onValueChange={(value) => onEnvModeChange(value as EnvMode)} > - + {activeWorktreePath ? ( ) : ( @@ -464,7 +364,7 @@ const WorkspaceMenu = memo(function WorkspaceMenu({ - + {resolveEnvModeLabel("worktree", m)} @@ -566,7 +466,7 @@ const MachineMenu = memo(function MachineMenu({ render={ } className={cn( - "min-w-0 max-w-full", + "max-w-full shrink-0", environmentUnavailable && "text-warning-foreground", )} aria-label={gt("Run on: {environment}", { environment: environmentLabel })} @@ -751,6 +651,7 @@ function showWorkspaceContextMenu(event: ReactMouseEvent, workspacePath: string) interface RunContextSelectorProps { displayMode?: "toolbar" | "panel"; + panelEnvironmentActions?: ReactNode; workspaceRoot?: string; forceNewWorktree: boolean; /** False when the folder has no repository a worktree could come from. */ @@ -772,10 +673,16 @@ interface RunContextSelectorProps { onUsePreviousWorktree: () => void; addTargets: readonly AddProjectTarget[]; onAddToMachine: (environmentId: EnvironmentId) => void; + /** A scratch thread with no project: the row names the folder as "No project". */ + noProject?: boolean; + /** Panel only: the machine row lists Run on, the workspace row lists the workspace modes. */ + section?: "machine" | "workspace"; } const RunContextSelector = memo(function RunContextSelector({ displayMode = "toolbar", + section, + panelEnvironmentActions, workspaceRoot, forceNewWorktree: requestedForceNewWorktree, offersWorkspaceModes, @@ -796,6 +703,7 @@ const RunContextSelector = memo(function RunContextSelector({ onUsePreviousWorktree, addTargets, onAddToMachine, + noProject = false, }: RunContextSelectorProps) { const gt = useGT(); const m = useMessages(); @@ -805,26 +713,51 @@ const RunContextSelector = memo(function RunContextSelector({ // A folder no worktree can come from runs threads in place, whatever mode was requested. const forceNewWorktree = offersWorkspaceModes && requestedForceNewWorktree; const effectiveEnvMode = offersWorkspaceModes ? requestedEnvMode : "local"; - const WorkspaceIcon = - effectiveEnvMode === "worktree" + const WorkspaceIcon = noProject + ? FolderIcon + : effectiveEnvMode === "worktree" ? FolderGit2Icon : activeWorktreePath && offersWorkspaceModes ? FolderGitIcon : FolderIcon; - const workspaceLabel = forceNewWorktree - ? resolveEnvModeLabel("worktree", m) - : envModeLocked - ? resolveLockedWorkspaceLabel(activeWorktreePath, effectiveEnvMode, m) - : effectiveEnvMode === "worktree" - ? resolveEnvModeLabel("worktree", m) - : resolveCurrentWorkspaceLabel(activeWorktreePath, m); + const workspaceLabel = noProject + ? gt("No project") + : forceNewWorktree + ? resolveEnvModeLabel("worktree", m) + : envModeLocked + ? resolveLockedWorkspaceLabel(activeWorktreePath, effectiveEnvMode, m) + : effectiveEnvMode === "worktree" + ? resolveEnvModeLabel("worktree", m) + : resolveCurrentWorkspaceLabel(activeWorktreePath, m); const isPanel = displayMode === "panel"; const workspaceModesLocked = envModeLocked || !offersWorkspaceModes; - const isLocked = !isPanel && (envLocked || workspaceModesLocked); + const isLocked = isPanel + ? section === "workspace" && workspaceModesLocked + : envLocked || workspaceModesLocked; const workspacePath = forceNewWorktree || (effectiveEnvMode === "worktree" && !activeWorktreePath) ? null : (activeWorktreePath ?? workspaceRoot); + const runOnEnvironments = + section !== "workspace" && + ((showEnvironmentPicker && onEnvironmentChange) || addTargets.length > 0) + ? availableEnvironments + : undefined; + const showWorkspaceGroup = section !== "machine" && offersWorkspaceModes; + const showPathGroup = isPanel && workspacePath !== null && section !== "workspace"; + const environmentActions = isPanel && section !== "workspace" ? panelEnvironmentActions : null; + const runContextLabel = + section === "workspace" + ? gt("Workspace: {workspace}", { workspace: workspaceLabel }) + : section === "machine" + ? gt("Run on: {environment}", { + environment: autoEnvironmentLabel ?? activeEnvironment?.label ?? gt("Run on"), + }) + : gt("Run context: {context}", { + context: [autoEnvironmentLabel ?? activeEnvironment?.label, workspaceLabel] + .filter(Boolean) + .join(", "), + }); const handleContextMenu = (event: ReactMouseEvent) => { if (isPanel && workspacePath) { showWorkspaceContextMenu(event, workspacePath); @@ -837,7 +770,7 @@ const RunContextSelector = memo(function RunContextSelector({ {isPanel - ? forceNewWorktree + ? forceNewWorktree && !noProject ? gt("Each model starts in its own worktree.") : (workspacePath ?? workspaceLabel) : workspaceLabel} @@ -871,7 +804,9 @@ const RunContextSelector = memo(function RunContextSelector({ const triggerContent = ( <> {isPanel ? ( - autoEnvironmentLabel ? ( + section === "workspace" ? ( + + ) : autoEnvironmentLabel ? ( ) : ( - {autoEnvironmentLabel ?? - (isPanel || showEnvironmentIndicator - ? (activeEnvironment?.label ?? gt("Run on")) - : workspaceLabel)} + {section === "workspace" + ? workspaceLabel + : (autoEnvironmentLabel ?? + (isPanel || showEnvironmentIndicator + ? (activeEnvironment?.label ?? gt("Run on")) + : workspaceLabel))} ); + const hasMenuContent = + showPathGroup || + runOnEnvironments !== undefined || + showWorkspaceGroup || + Boolean(environmentActions); - if (isLocked) { - return ( + if (isLocked || !hasMenuContent) { + const row = ( {triggerContent} ); + return isPanel ? ( + + + {workspacePath ?? workspaceLabel} + + ) : ( + row + ); } return ( @@ -929,15 +871,7 @@ const RunContextSelector = memo(function RunContextSelector({ } : undefined } - aria-label={ - isPanel - ? gt("Run context: {context}", { - context: [autoEnvironmentLabel ?? activeEnvironment?.label, workspaceLabel] - .filter(Boolean) - .join(", "), - }) - : undefined - } + aria-label={isPanel ? runContextLabel : undefined} data-composer-context-control data-composer-shortcut={[ showEnvironmentPicker && !envLocked ? "composer.host" : "", @@ -952,6 +886,9 @@ const RunContextSelector = memo(function RunContextSelector({ - {isPanel && workspacePath ? ( + {showPathGroup ? ( {activeEnvironment?.label ?? gt("Environment")}
@@ -969,8 +906,7 @@ const RunContextSelector = memo(function RunContextSelector({
) : null} - {availableEnvironments && - ((showEnvironmentPicker && onEnvironmentChange) || addTargets.length > 0) ? ( + {runOnEnvironments ? ( <> @@ -1001,7 +937,7 @@ const RunContextSelector = memo(function RunContextSelector({
)} - {availableEnvironments.map((env) => ( + {runOnEnvironments.map((env) => ( ) : null}
- {offersWorkspaceModes ? : null} + {showWorkspaceGroup ? : null} ) : null} - {offersWorkspaceModes ? ( + {showWorkspaceGroup ? ( Workspace @@ -1089,6 +1025,12 @@ const RunContextSelector = memo(function RunContextSelector({ ) : null} + {environmentActions ? ( + <> + {showPathGroup || runOnEnvironments || showWorkspaceGroup ? : null} + {environmentActions} + + ) : null} ); @@ -1099,9 +1041,11 @@ const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)"; const COMPOSER_CONTEXT_LABEL_SELECTOR = "[data-composer-label]"; const RESTING_CONTROLS_SELECTOR = '[data-chat-composer-resting-controls="true"]'; -function readStripCompaction(strip: HTMLElement): ContextStripCompaction { - const value = strip.dataset.compact; - return value === "labels" || value === "branch" ? value : "none"; +function flexGap(element: HTMLElement | null): number { + while (element && getComputedStyle(element).display === "contents") { + element = element.parentElement; + } + return element ? Number.parseFloat(getComputedStyle(element).columnGap) || 0 : 0; } /** A hidden or squeezed label's scrollWidth loses its tail, causing label/icon flapping. */ @@ -1165,11 +1109,14 @@ function useStripCompaction(): readonly [ const attach = (current: HTMLDivElement | null) => { if (!current) return; + let measured = false; const labelAnimations = new Map(); const measure = () => { + // Hidden tabs retain stage layout but must keep their last label mode. + if (!current.checkVisibility()) return; // The committed attribute, not render state, so a stale closure cannot misread it. - const compact = readStripCompaction(current); + const compact = readContextStripCompaction(current.dataset.compact); const stripWidth = current.clientWidth; if (stripWidth === 0) return; const stripStyle = getComputedStyle(current); @@ -1177,26 +1124,9 @@ function useStripCompaction(): readonly [ stripWidth - (Number.parseFloat(stripStyle.paddingInlineStart) || 0) - (Number.parseFloat(stripStyle.paddingInlineEnd) || 0); - const contentWidth = (parent: Element): number => { - const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0; - let width = 0; - let counted = 0; - for (const child of parent.children) { - if (!(child instanceof HTMLElement)) continue; - if (child.offsetWidth === 0) continue; - const style = getComputedStyle(child); - const position = style.position; - if (position === "absolute" || position === "fixed") continue; - width += - child.offsetWidth + - (Number.parseFloat(style.marginInlineStart) || 0) + - (Number.parseFloat(style.marginInlineEnd) || 0); - counted += 1; - } - return width + gap * Math.max(0, counted - 1); - }; const stripGap = Number.parseFloat(stripStyle.columnGap) || 0; let needed = 0; + let labelsNeeded = 0; let groups = 0; for (const child of current.children) { if (!(child instanceof HTMLElement)) continue; @@ -1204,28 +1134,43 @@ function useStripCompaction(): readonly [ const controlsMeasurement = controls ? measureRestingComposerControls(controls) : null; if (controlsMeasurement) { child.style.minWidth = `${resolveRestingComposerControlsMinimumWidth(controlsMeasurement)}px`; + groups += 1; + needed += resolveRestingComposerControlsNarrowestWidth(controlsMeasurement, "none"); + labelsNeeded += resolveRestingComposerControlsNarrowestWidth( + controlsMeasurement, + "labels", + ); + continue; } - const width = controlsMeasurement - ? resolveRestingComposerControlsNaturalWidth(controlsMeasurement) - : contentWidth(child); + const width = contextStripGroupWidth(child); if (width <= 1) continue; groups += 1; needed += width; + labelsNeeded += width; } needed += stripGap * Math.max(0, groups - 1); + labelsNeeded += stripGap * Math.max(0, groups - 1); const range = document.createRange(); - let labelsSavedWidth = 0; for (const label of current.querySelectorAll(COMPOSER_CONTEXT_LABEL_SELECTOR)) { const textWidth = labelTextWidth(label, range); - needed += Math.max(0, textWidth - label.getBoundingClientRect().width); - if (label.dataset.composerLabel === "hide") labelsSavedWidth += textWidth; + const renderedWidth = + label.getBoundingClientRect().width + + (Number.parseFloat(getComputedStyle(label).marginInlineStart) || 0); + const missingWidth = Math.max(0, textWidth - renderedWidth); + needed += missingWidth; + labelsNeeded += + label.dataset.composerLabel === "hide" + ? -renderedWidth - flexGap(label.parentElement) + : missingWidth; } const nextCompaction = resolveContextStripCompaction({ current: compact, neededWidth: needed, + labelsNeededWidth: labelsNeeded, availableWidth: available, - labelsSavedWidth, }); + const firstMeasure = !measured; + measured = true; if (nextCompaction === compact) return; const previousRects = new Map( Array.from(current.querySelectorAll(COMPOSER_CONTEXT_LABEL_SELECTOR)).map( @@ -1233,7 +1178,7 @@ function useStripCompaction(): readonly [ ), ); flushSync(() => setCompaction(nextCompaction)); - animateLabelWidths(previousRects, labelAnimations); + if (!firstMeasure) animateLabelWidths(previousRects, labelAnimations); }; let stopResize = () => {}; @@ -1274,6 +1219,7 @@ function useStripCompaction(): readonly [ export const BranchToolbar = memo(function BranchToolbar({ layout = "composer", + onOpenWorkspaceDetails, panelSection = "all", forceNewWorktree = false, ref, @@ -1302,6 +1248,7 @@ export const BranchToolbar = memo(function BranchToolbar({ afterBranch, environmentUnavailable = false, panelPrRowsContainer, + panelEnvironmentActions, }: BranchToolbarProps) { const m = useMessages(); const branchSelectorRef = useRef(null); @@ -1310,6 +1257,7 @@ export const BranchToolbar = memo(function BranchToolbar({ // The composer retains resolved thread details while bootstrap cleanup can remove its shell. const activeProjectRef = scopeProjectRef(environmentId, projectId); const activeProject = useProject(activeProjectRef); + const scratchWorkspaceRoot = useServerConfigs().get(environmentId)?.scratchWorkspaceRoot; const activeWorktreePath = forceNewWorktree ? null : worktreePath; const effectiveEnvMode = forceNewWorktree ? "worktree" : envMode; const envModeLocked = envLocked || (isServerThread && activeWorktreePath !== null); @@ -1337,7 +1285,11 @@ export const BranchToolbar = memo(function BranchToolbar({ useImperativeHandle( ref, () => ({ - openBranchPicker: () => branchSelectorRef.current?.open(), + focusBranchPicker: () => branchSelectorRef.current?.focus(), + openBranchPicker: () => { + if (onOpenWorkspaceDetails) onOpenWorkspaceDetails(); + else branchSelectorRef.current?.open(); + }, usePreviousWorktree: () => { if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return; onUsePreviousWorktree(); @@ -1346,6 +1298,7 @@ export const BranchToolbar = memo(function BranchToolbar({ }), [ canUsePreviousWorktree, + onOpenWorkspaceDetails, onComposerFocusRequest, onUsePreviousWorktree, previousWorktreeSeed, @@ -1362,7 +1315,6 @@ export const BranchToolbar = memo(function BranchToolbar({ const activeEnvironmentOption = availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null; const [attachStrip, stripCompaction] = useStripCompaction(); - const plainProjectBaseBranch = useWorktreeBaseBranch(activeProject ?? null); if (!activeProject) return null; @@ -1377,36 +1329,48 @@ export const BranchToolbar = memo(function BranchToolbar({ if (layout === "panel") { return (
- {panelSection !== "branch" ? ( - - ) : null} + {panelSection !== "branch" + ? // Without Git there is no worktree to make, so only the machine row is left. + (showGitControls ? (["machine", "workspace"] as const) : (["machine"] as const)).map( + (section) => ( + + ), + ) + : null} {panelSection !== "workspace" ? ( {machineMenu} - {showGitControls && !showBranchControls ? : null} + {showGitControls && !showBranchControls && !onOpenWorkspaceDetails ? ( + + ) : null} {offersRepositoryChoice ? ( ) : null} - {!showGitControls ? null : !showBranchControls ? ( - startsNewWorktree ? ( - - {plainProjectBaseBranch === "" - ? m(msg("Each repository starts from its own default branch")) - : m( - msg("Repositories start from {branch} where they have it", { - branch: plainProjectBaseBranch, - }), - )} - - ) : null - ) : ( + {!showGitControls || !showBranchControls || onOpenWorkspaceDetails ? null : ( void; + focus: () => void; } interface BranchToolbarBranchSelectorProps { @@ -223,6 +224,7 @@ export function BranchToolbarBranchSelector({ const messages = useMessages(); const composerFloatingLayerProps = useComposerMenuProps(); const toolbarAnchorRef = useRef(null); + const triggerRef = useRef(null); const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope); const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop"); @@ -805,6 +807,7 @@ export function BranchToolbarBranchSelector({ useImperativeHandle( ref, () => ({ + focus: () => triggerRef.current?.focus({ preventScroll: true }), open: () => { if (isInitialBranchesLoadPending || isBranchActionPending) return; setFocusBranchSearch(true); @@ -849,6 +852,13 @@ export function BranchToolbarBranchSelector({ }); const openPrLink = useOpenPrLink(threadRef); const linkedIssues = serverThread?.issues ?? []; + // The rows below show nothing without one of these. + const mayShowPanelRows = + branchPr !== null || + linkedIssues.length > 0 || + (serverThread?.pullRequests?.length ?? 0) > 0 || + serverThread?.linkedPullRequest != null || + serverThread?.branchPullRequest != null; function selectPickerItem(itemValue: string) { if (isInitialBranchesLoadPending || isBranchActionPending) return; @@ -1039,12 +1049,16 @@ export function BranchToolbarBranchSelector({ ...(displayMode === "toolbar" ? { anchor: () => - toolbarAnchorRef.current?.closest('[data-slot="composer-shell"]') ?? + toolbarAnchorRef.current?.closest('[data-slot="composer-host"]') ?? toolbarAnchorRef.current, } : {}), align: "start", side: displayMode === "panel" ? "right" : "top", + collisionAvoidance: + displayMode === "panel" + ? { side: "flip", align: "shift", fallbackAxisSide: "end" } + : undefined, className: cn( "flex flex-col", displayMode === "panel" ? "w-(--anchor-width)" : "min-w-0 w-90", @@ -1071,6 +1085,7 @@ export function BranchToolbarBranchSelector({ > {displayMode === "toolbar" && renderWorkspaceMenu ? null : ( @@ -1111,7 +1126,8 @@ export function BranchToolbarBranchSelector({ )} - {displayMode === "panel" && prRowsContainer !== null + {/* Each portal host takes React's whole delegated listener set, so a thread with no row to show mounts none. */} + {displayMode === "panel" && prRowsContainer !== null && mayShowPanelRows ? portalTo( prRowsContainer, <> diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index b0aa293812d6d..8af0d8ef7373c 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -8,6 +8,7 @@ import { commands, page, userEvent } from "vite-plus/test/browser"; import { act, render } from "../../test/render"; import "../index.css"; +import type { LayoutDragContentSource } from "../layout/layoutDrag"; import { filesystemEnvironment } from "../state/filesystem"; import { hostRightPanel, @@ -24,6 +25,13 @@ const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ filesystemMetadata: vi.fn(), })); const parsedSources = vi.hoisted(() => [] as string[]); +const dragSources = vi.hoisted(() => [] as LayoutDragContentSource[]); +vi.mock(import("../layout/layoutDrag"), async (original) => ({ + ...(await original()), + beginLayoutContentDrag: (_event, source) => { + dragSources.push(source); + }, +})); vi.mock(import("../markdown/wordsHast"), async (original) => { const actual = await original(); return { @@ -179,6 +187,7 @@ it("keeps compact audio playback loaded across signed URL renewals", async () => function setup() { appearance.value = "light"; parsedSources.length = 0; + dragSources.length = 0; settingsOverrides.mathRenderingEnabled = false; renderDiagram.mockReset(); threadWorktrees.clear(); @@ -571,6 +580,49 @@ describe("ChatMarkdown workspace file opens", () => { expect(workspaceSearch).toHaveBeenCalledOnce(); }); + it("resolves each dragged file link on its own, and a click does not cancel it", async () => { + setup(); + const lookups = new Map void>(); + workspaceSearch.mockImplementation( + ({ input }: { input: { query: string } }) => + new Promise((resolve) => lookups.set(input.query, resolve)), + ); + using openFile = vi + .spyOn(useRightPanelStore.getState(), "openFile") + .mockImplementation(() => {}); + await using screen = await renderText( + "[A](physics/notes/a.md) and [B](physics/notes/b.md) and [Other](/elsewhere/c.md:9)", + { cwd: "/school/physics", threadRef }, + ); + const [first, second, other] = screen.container.querySelectorAll("a"); + for (const link of [first!, second!]) { + link.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, button: 0, pointerType: "mouse" }), + ); + } + const resolves = dragSources.map((source) => + source.kind === "surface" ? source.resolve?.() : undefined, + ); + expect(resolves).toHaveLength(2); + await vi.waitFor(() => expect(lookups.size).toBe(2)); + + await act(async () => other!.click()); + expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/c.md", 9); + for (const [query, resolve] of lookups) { + resolve( + AsyncResult.success({ + entries: [{ path: `notes/${query.endsWith("b.md") ? "b" : "a"}.md`, kind: "file" }], + truncated: false, + }), + ); + } + + expect(await Promise.all(resolves)).toEqual([ + expect.objectContaining({ relativePath: expect.stringContaining("notes/a.md") }), + expect.objectContaining({ relativePath: expect.stringContaining("notes/b.md") }), + ]); + }); + it("opens a path from markdown rendered in another checkout under that checkout", async () => { setup(); const scratchThread = { ...threadRef, threadId: ThreadId.make("scratch-thread") }; diff --git a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx index a072ecc107e26..f4af808888d76 100644 --- a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx @@ -309,6 +309,7 @@ it("preserves keyboard activation of a file-options button", async () => { theme="dark" onOpenInPanel={vi.fn()} resolveDragPath={async () => "/work/readme.md"} + resolvePanelPath={(path) => path} resolveCopyPaths={async () => ({ relativePath: "readme.md", fullPath: "/work/readme.md" })} openInEditorMenuLabel="Open in editor" />, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 5cdff7e8c2a0c..a2f9e7b32135a 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -941,6 +941,19 @@ function useChatMarkdownState( } return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot); }; + const resolvePanelPath = ( + fileLinkMeta: MarkdownFileLinkMeta, + panelPath: string, + ): string | Promise => { + if ( + fileLinkMeta.workspaceLookupPath === null || + !cwd || + workspaceLinkLookupQuery(panelPath, cwd) === null + ) { + return panelPath; + } + return findWorkspaceFileMatch(fileLinkMeta).then((match) => match ?? panelPath); + }; const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => { if (!threadRef) return; // The panel reads relative paths from the thread's folder. A pull request body's `cwd` is the @@ -961,27 +974,23 @@ function useChatMarkdownState( : path, fileLinkMeta.line, ); - if ( - fileLinkMeta.workspaceLookupPath === null || - !cwd || - workspaceLinkLookupQuery(panelPath, cwd) === null - ) { - openAt(panelPath); + const path = resolvePanelPath(fileLinkMeta, panelPath); + if (typeof path === "string") { + openAt(path); return; } // Anything the user opens in this panel meanwhile, such as a file from the picker, wins. const panelRef = rightPanelHostRef(threadRef); const panelKey = scopedThreadKey(panelRef); const userActionRevision = useRightPanelStore.getState().markUserAction(panelRef); - void (async () => { - const match = await findWorkspaceFileMatch(fileLinkMeta); + void path.then((resolved) => { if ( scopedThreadKey(rightPanelHostRef(threadRef)) !== panelKey || useRightPanelStore.getState().getUserActionRevision(panelRef) !== userActionRevision ) return; - openAt(match ?? panelPath); - })(); + openAt(resolved); + }); }; const fileLinkChip = ( fileLinkMeta: MarkdownFileLinkMeta, @@ -1057,6 +1066,7 @@ function useChatMarkdownState( markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd) } onOpenInPanel={(path) => openFileInPanel(fileLinkMeta, path)} + resolvePanelPath={(path) => resolvePanelPath(fileLinkMeta, path)} onOpenMedia={ threadRef && canPreviewMedia ? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath) diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 62d04e18f67d9..bb4f0b69810a5 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -6,8 +6,12 @@ import { EnvironmentId, IssueTrackerKind, ORCHESTRATION_V2_WS_METHODS, + NodeId, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, RunId, + RuntimeRequestId, ThreadId, + TurnItemId, WS_METHODS, type AgentSessionImportInput, type IssueDetail, @@ -20,6 +24,7 @@ import { mergeWithDefaultKeybindings, } from "@t3tools/shared/keybindings"; import type * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import { expect, it, vi } from "vite-plus/test"; @@ -36,8 +41,9 @@ import stylesheet from "~/index.css?inline"; import { environmentContextRecord } from "~/lib/composerContextRecords"; import { startWorkspaceFocus } from "~/lib/workspaceFocus"; import { usePromptStashStore } from "~/promptStashStore"; -import { useRightPanelStore } from "~/rightPanelStore"; +import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore"; import { getRouter } from "~/router"; +import { useLayoutStore } from "~/layout/layoutStore"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { environmentThreadDetails } from "~/state/threads"; import { @@ -258,7 +264,7 @@ it("opens a linked Linear issue from an inactive thread's sidebar badge", async await userEvent.hover(badge); const issueName = `Issue ${issue.displayKey}: ${liveTitle}`; const previewLink = page.getByRole("link", { name: issueName }); - await userEvent.hover(previewLink.getByText("sam", { exact: true })); + await userEvent.hover(previewLink); await expect.element(previewLink).toBeVisible(); const contextMenu = new MouseEvent("contextmenu", { bubbles: true, cancelable: true }); await act(() => previewLink.element().dispatchEvent(contextMenu)); @@ -403,6 +409,8 @@ it("a question that opens while a stashed file is checked keeps a machine stash" it("imports Pi conversations through the environment RPC and can retry a changed project", async () => { await using _viewport = await appViewport(); + useLayoutStore.getState().reset(); + using _layout = { [Symbol.dispose]: () => useLayoutStore.getState().reset() }; using _environment = installFakeEnvironment([], { acceptCommands: true }); const scan = vi.fn(() => Effect.succeed({ @@ -482,6 +490,7 @@ it("imports Pi conversations through the environment RPC and can retry a changed await expect .element(page.getByRole("heading", { name: "Welcome to T3 Code" })) .not.toBeInTheDocument(); + await vi.waitFor(() => expect(router.state.location.pathname).not.toBe("/welcome")); changed = false; await router.navigate({ to: "/welcome" }); await expect.element(page.getByRole("heading", { name: "Welcome to T3 Code" })).toBeVisible(); @@ -580,6 +589,86 @@ it("a failed image-only first send of a new thread keeps the new draft", async ( expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); }); +it("answers a pending question while an oversized message draft is set aside", async () => { + await using _viewport = await appViewport(); + const thread = threadWithHistory("oversized-question-draft", 0); + using _environment = installFakeEnvironment([thread]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const target = scopeThreadRef(ENVIRONMENT_ID, thread.id); + const oversizedDraft = "x".repeat(PROVIDER_SEND_TURN_MAX_INPUT_CHARS + 1); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + // AppRoot owns the router. + await using _app = await render(, { + container: appContainer(), + router: false, + }); + await expect.element(page.getByTestId("composer-editor")).toBeVisible(); + + const requestId = RuntimeRequestId.make("oversized-draft-question"); + const nodeId = NodeId.make("oversized-draft-node"); + const now = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z"); + await act(async () => { + await emitThreadEvent(thread.id, { + type: "runtime-request.updated", + payload: { + id: requestId, + nodeId, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status: "pending", + responseCapability: { type: "message" }, + createdAt: now, + resolvedAt: null, + }, + }); + await emitThreadEvent(thread.id, { + type: "turn-item.updated", + payload: { + id: TurnItemId.make("oversized-draft-question-card"), + threadId: thread.id, + runId: null, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "user_input_request", + requestId, + questions: [ + { + id: "scope", + header: "Scope", + question: "Which scope should we use?", + options: [], + initialAnswer: "Composer", + }, + ], + }, + }); + }); + await expect.element(page.getByText("Which scope should we use?", { exact: true })).toBeVisible(); + await act(() => { + useComposerDraftStore.getState().setPrompt(target, oversizedDraft); + }); + await expect.element(page.getByText(/Prompt is 1 character over/)).not.toBeInTheDocument(); + await page.getByRole("button", { name: "Answer", exact: true }).click(); + await expect.element(page.getByRole("button", { name: /Submitting/ }).first()).toBeVisible(); + expect(useComposerDraftStore.getState().getComposerDraft(target)?.prompt).toBe(oversizedDraft); +}); + it.each(["new", "existing"] as const)( "Enter while an image compresses shows a cancellable banner, cancels on edit or Esc, and still sends after leaving a %s thread", async (kind) => { @@ -1025,11 +1114,13 @@ it("a shortcut conditioned on rightPanelOpen sees the thread's open right panel" using _environment = installFakeEnvironment([thread], { keybindings: mergeWithDefaultKeybindings( compileResolvedKeybindingsConfig([ - { key: "ctrl+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" }, + { key: "ctrl+t", command: "threadPanel.toggle", when: "rightPanelOpen && !terminalFocus" }, { key: "ctrl+t", command: "rightPanel.toggle", when: "!rightPanelOpen" }, ]), ), }); + // Reconnect so this test's keybindings replace a previous app's live config. + appAtomRegistry.reset(); __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, onboardingCompletedAt: "2026-01-01T00:00:00.000Z", @@ -1042,15 +1133,23 @@ it("a shortcut conditioned on rightPanelOpen sees the thread's open right panel" // AppRoot brings its own router. router: false, }); + // Panes retired rightPanel.new; the side pane is the thread's right panel. + const threadRef = scopeThreadRef(ENVIRONMENT_ID, thread.id); + const sidePaneOpen = () => + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef).isOpen; const composer = page.getByTestId("composer-editor"); - const toggle = page.getByRole("button", { name: "Toggle right panel", exact: true }); - await expect.element(toggle).toHaveAttribute("aria-pressed", "false"); - await toggle.click(); - await page.getByRole("button", { name: /^Files/ }).click(); + const details = page.getByRole("button", { name: "Toggle thread details panel", exact: true }); + await expect.element(details).toBeVisible(); + // As clicking the panel toggle and its Files tab did. + await act(() => useRightPanelStore.getState().open(threadRef, "files")); + await vi.waitFor(() => expect(sidePaneOpen()).toBe(true)); + const detailsOpen = details.element().getAttribute("aria-expanded"); await composer.click(); await userEvent.keyboard("{Control>}t{/Control}"); - await expect.element(page.getByRole("menuitem", { name: /Files/ })).toBeVisible(); - await expect.element(toggle).toHaveAttribute("aria-pressed", "true"); + await expect + .element(details) + .toHaveAttribute("aria-expanded", detailsOpen === "true" ? "false" : "true"); + expect(sidePaneOpen()).toBe(true); }); it("selecting a side-chat tab focuses that side chat's composer", async () => { @@ -1070,8 +1169,6 @@ it("selecting a side-chat tab focuses that side chat's composer", async () => { onboardingCompletedAt: "2026-01-01T00:00:00.000Z", }); const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id); - useRightPanelStore.getState().openThread(parentRef, otherSide.id); - useRightPanelStore.getState().openThread(parentRef, side.id); const router = getRouter( createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }), ); @@ -1081,6 +1178,10 @@ it("selecting a side-chat tab focuses that side chat's composer", async () => { router: false, }); using _focus = { [Symbol.dispose]: startWorkspaceFocus(router) }; + await act(() => { + useRightPanelStore.getState().openThread(parentRef, otherSide.id); + useRightPanelStore.getState().openThread(parentRef, side.id); + }); const mainEditor = screen.getByRole("textbox", { name: `Message ${parent.title}`, exact: true }); const sideEditor = screen.getByRole("textbox", { name: `Message ${side.title}`, exact: true }); await expect.element(sideEditor).toBeVisible(); @@ -1099,6 +1200,12 @@ it("selecting a side-chat tab focuses that side chat's composer", async () => { await userEvent.click(screen.getByRole("button", { name: side.title, exact: true })); await expect.element(sideEditor).toHaveFocus(); await expect.element(mainEditor).toHaveTextContent("main draft"); + + // Shift+F6 goes straight back to the main chat; its tab, already showing, brings the box back. + await userEvent.keyboard("{Shift>}{F6}{/Shift}"); + await expect.element(mainEditor).toHaveFocus(); + await userEvent.click(screen.getByRole("button", { name: side.title, exact: true })); + await expect.element(sideEditor).toHaveFocus(); }); it("a subagent tab shows its read-only bar under no header of its own", async () => { @@ -1115,7 +1222,6 @@ it("a subagent tab shows its read-only bar under no header of its own", async () onboardingCompletedAt: "2026-01-01T00:00:00.000Z", }); const parentRef = scopeThreadRef(ENVIRONMENT_ID, parent.id); - useRightPanelStore.getState().openThread(parentRef, subagent.id); const router = getRouter( createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${parent.id}`] }), ); @@ -1124,6 +1230,9 @@ it("a subagent tab shows its read-only bar under no header of its own", async () // AppRoot brings its own router. router: false, }); + await act(() => { + useRightPanelStore.getState().openThread(parentRef, subagent.id); + }); const pane = screen.getByTestId("side-thread-pane"); // No header of its own: the tab names it, and only a side chat has actions to put in one. await expect.element(pane.getByRole("heading", { name: subagent.title })).not.toBeInTheDocument(); @@ -1139,6 +1248,9 @@ it("a subagent tab shows its read-only bar under no header of its own", async () it("/side sends the draft's attachments and context, and keeps them when it does not start", async () => { await page.viewport(1400, 900); + // Side chats an earlier test left in the pane layout would count as open tabs. + useLayoutStore.getState().reset(); + using _layout = { [Symbol.dispose]: () => useLayoutStore.getState().reset() }; const thread = threadWithHistory("side-attachments", 1); let holdFork = false; using _environment = installFakeEnvironment([thread], { diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index a79fed15935d0..ff4e17ec0d071 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -75,6 +75,7 @@ import { deriveLockedProvider, hasCompactableConversation, hasServerAcknowledgedLocalDispatch, + shouldShowComposerTasks, waitForRevertedMessage, } from "./ChatView.logic"; @@ -188,6 +189,18 @@ describe("buildExpiredTerminalContextToastCopy", () => { }); }); +describe("shouldShowComposerTasks", () => { + it("hides a settled run's finished plan while the next send is pending", () => { + expect( + shouldShowComposerTasks({ + steps: [{ status: "completed" }], + planRunSettled: true, + isSendBusy: true, + }), + ).toBe(false); + }); +}); + describe("hasServerAcknowledgedLocalDispatch", () => { it("acknowledges a settled newer background turn", () => { const localDispatch = createLocalDispatchSnapshot( @@ -269,6 +282,15 @@ describe("hasServerAcknowledgedLocalDispatch", () => { threadError: null, }), ).toBe(acknowledged); + + expect( + deriveTimelineWorking({ + phase: derivePhase({ ...readySession, status }), + isSendBusy: !acknowledged, + isCompacting: false, + runlessWorkStartedAt: null, + }), + ).toBe(true); }); it("waits for the matching running turn before acknowledging", () => { diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 160aed0a7093e..59ab7e174470f 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -37,7 +37,6 @@ import { type ProviderInstanceId, type ProviderThreadId, type ServerProvider, - type ScopedProjectRef, type ScopedThreadRef, type ThreadContextRecord, type EnvironmentContextRecord, @@ -111,7 +110,6 @@ type ThreadProjection = EnvironmentThread["projection"]; type ThreadStructureRow = ThreadStructure["visibleTurnItems"][number]; export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project"; -export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10; export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000; @@ -234,6 +232,15 @@ export function shouldOpenProactiveTurnDiff(input: { ); } +export function shouldShowComposerTasks(input: { + steps: ReadonlyArray<{ status: string }>; + planRunSettled: boolean; + isSendBusy: boolean; +}): boolean { + if (!input.planRunSettled) return true; + return !input.isSendBusy && input.steps.some((step) => step.status !== "completed"); +} + export function resolveProactiveTurnDiffAction(input: { checkpoint: Pick | undefined; isGitRepo: boolean | undefined; @@ -415,16 +422,6 @@ export function resolveThreadSwitchTimeline(input: return input.nextEntries; } -export function startNewThreadForProject( - projectRef: ScopedProjectRef | null, - handleNewThread: (projectRef: ScopedProjectRef) => Promise, -): boolean { - if (projectRef === null) return false; - void handleNewThread(projectRef); - - return true; -} - export function resolveThreadMetadataUpdateForNextTurn(input: { currentModelSelection: ModelSelection; nextModelSelection?: ModelSelection; @@ -579,37 +576,6 @@ export function getAntigravitySendBlockReason( return null; } -export function reconcileMountedTerminalThreadIds(input: { - currentThreadIds: ReadonlyArray; - openThreadIds: ReadonlyArray; - activeThreadId: string | null; - activeThreadTerminalOpen: boolean; - maxHiddenThreadCount?: number; -}): string[] { - const openThreadIdSet = new Set(input.openThreadIds); - const hiddenThreadIds = input.currentThreadIds.filter( - (threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId), - ); - const maxHiddenThreadCount = Math.max( - 0, - input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, - ); - const nextThreadIds = - hiddenThreadIds.length > maxHiddenThreadCount - ? hiddenThreadIds.slice(-maxHiddenThreadCount) - : hiddenThreadIds; - - if ( - input.activeThreadId && - input.activeThreadTerminalOpen && - !nextThreadIds.includes(input.activeThreadId) - ) { - nextThreadIds.push(input.activeThreadId); - } - - return nextThreadIds; -} - // Null identifies the project checkout when a launch or session is known. export function resolveTerminalWorktreePath(input: { launchContext: { readonly worktreePath: string | null } | null; @@ -1144,6 +1110,10 @@ export function hasServerAcknowledgedLocalDispatch(input: { ); } +export function isCoveredByModal(element: Pick | null): boolean { + return element?.closest('[aria-hidden="true"]') != null; +} + // Window return puts the caret in the composer unless focus or a selection is deliberate: another // text field, a terminal, an open dialog, menu, or popup, a region, timeline, or sidebar row reached // from the keyboard, a region with its own keys (aria-keyshortcuts), or selected text the composer diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6995d1757d969..45212785a79e0 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,9 +1,8 @@ import { m } from "../i18n/messages"; import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { msg, useGT, useMessages } from "gt-react"; -import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; import { ComposerTaskStatus } from "./chat/ComposerTaskStatus"; -import { workspaceAreaProps } from "../lib/workspaceFocus"; +import { isReturnedSurfaceFocus, workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit"; @@ -48,11 +47,15 @@ import { resolveThreadErrorBanner, } from "./ChatView.logic"; import { useQueuedRunEdit } from "./chat/useQueuedRunEdit"; -import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic"; +import { + recallCheckoutIsRepo, + rememberCheckoutIsRepo, + shouldShowComposerTasks, +} from "./ChatView.logic"; import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments"; import { useStableCallback } from "../hooks/useStableCallback"; +import { DeferredChatContext } from "../layout/chatRenderGate"; import { useProjectScriptEditing } from "./chat/useProjectScriptEditing"; -import { RightPanelSurfaceContent } from "./chat/RightPanelSurfaceContent"; import { usePendingThreadRequests } from "./chat/usePendingThreadRequests"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { resolveWorktreeRepositorySelection } from "@t3tools/client-runtime/state/thread-repositories"; @@ -81,6 +84,8 @@ import { type ModelSelection, type PreviewAnnotationPayload, ProviderInstanceId, + type ProviderApprovalDecision, + type RuntimeRequestId, type ServerProvider, type ScopedThreadRef, type ThreadId, @@ -133,7 +138,10 @@ import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabelsCopy"; import { useAtomValue } from "@effect/atom-react"; import { + type ComponentProps, + type CSSProperties, type MouseEvent as ReactMouseEvent, + type ReactNode, type SetStateAction, use, useEffect, @@ -146,6 +154,7 @@ import { WorkspaceMutationIdContext } from "./chat/ChatMarkdownMedia"; import { useLocation, useNavigate } from "@tanstack/react-router"; import { assistantCitationFromLocation, + assistantCitationScopeFromLocation, useSideChatCitationReveal, } from "../lib/assistantCitationNavigation"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; @@ -188,14 +197,12 @@ import { useRightPanelStore, } from "../rightPanelStore"; import { isPreviewSupportedInRuntime, useThreadPreviewState } from "../previewStateStore"; -import { previewRuntimeTabId } from "../browser/previewRuntimeTabId"; import { ThreadPreviewMiniPlayer, useThreadPreviewCanvasSource, } from "./preview/ThreadPreviewMiniPlayer"; import { createChatCanvasStore, resolveChatCanvasModel } from "./chat/canvasStore"; import { usePreviewSession } from "./preview/usePreviewSession"; -import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic"; import { previewMiniPlayerSourceKey, @@ -212,7 +219,6 @@ import { isEditableFocused } from "../lib/editableFocus"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; import { shortcutLabelForCommand } from "../keybindings"; import { cn } from "~/lib/utils"; -import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { projectScriptIdFromCommand } from "~/projectScripts"; import { newMessageId } from "~/lib/utils"; @@ -239,7 +245,7 @@ import { useNewThreadHandler } from "../hooks/useHandleNewThread"; import { useWorktreeRepositoryChoices } from "../hooks/useWorktreeRepositoryChoices"; import { useRememberedWorktreeRepositories } from "../worktreeRepositoryChoiceStore"; import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl"; -import { isPreviewFocused } from "../lib/previewFocus"; +import { isBrowserFocused } from "../lib/previewFocus"; import { getTerminalFocusOwner } from "../lib/terminalFocus"; import { draftModelSelectionApplies, threadHasStarted } from "../lib/chatThreadActions"; import { @@ -259,6 +265,7 @@ import { useComposerDraftStore, DraftId, } from "../composerDraftStore"; +import { useDraftSendOnOpenStore } from "../draftSendOnOpenStore"; import { type TerminalContextDraft } from "../lib/terminalContext"; import { collectInlineContextIds } from "../lib/composerContextReferences"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; @@ -268,7 +275,7 @@ import { revisionedQuery } from "../state/revisionedQuery"; import { useEnvironmentScope } from "~/state/session"; import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server"; import { hostEnvironmentIdAtom } from "../state/primaryEnvironment"; -import { threadEnvironment } from "../state/threads"; +import { childThreadApprovalsAtom, threadEnvironment } from "../state/threads"; import { resolveProviderSkillsForCwd, resolveProvidersForCwd, @@ -324,24 +331,25 @@ import { ProviderSubagentBar } from "./chat/ProviderSubagentBar"; import { getTriggerDisplayModelName } from "./chat/providerIconUtils"; import { pendingApprovalSlotLabel } from "./chat/MessagesTimeline.logic"; import { resolveScrollToEndClearance } from "./composerFooterLayout"; -import { ChatHeader } from "./chat/ChatHeader"; +import { ChatHeader, type HiddenTerminalChip } from "./chat/ChatHeader"; import { useSideChat } from "./chat/useSideChat"; import { sideThreadComposer, sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; -import { useOpenSurfaceInMainView } from "../hooks/useOpenSurfaceInMainView"; import { useRemoteOpenState } from "~/remoteOpen"; import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic"; -import { PaneHeaderActions } from "./chat/PaneHeaderActions"; +import { + ChatPaneHeader, + ChatPaneHeaderControls, + useHeaderControlsInset, +} from "./chat/ChatPaneHeader"; import GitActionsControl from "./GitActionsControl"; import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut"; -import { - PanelLayoutControls, - type PanelLayoutControlsProps, - RightPanelMaximizeControl, - ThreadPanelHeaderControl, - WorkspaceTitlebarControls, -} from "./chat/PanelLayoutControls"; +import { PanelLayoutControls, type PanelLayoutControlsProps } from "./chat/PanelLayoutControls"; import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview"; -import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel"; +import { ThreadDetailsPanel, type ThreadDetailsPanelHandle } from "./chat/ThreadDetailsPanel"; +import { + resolveThreadDetailsVisibility, + shouldShowComposerWorkspace, +} from "./chat/threadDetailsItems"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { offersWorkspaceModes, @@ -364,8 +372,7 @@ import { QueuedRunsControl, type QueuedRunsControlHandle } from "./chat/QueuedRu import { useThreadLinkedPullRequest } from "./pullRequest/useThreadLinkedPullRequest"; import { useProactivePanels } from "../hooks/useProactivePanels"; import { useIncrementalTimelineEntries } from "../hooks/useIncrementalTimelineEntries"; -import { useRightPanelSurfaceClose } from "../hooks/useRightPanelSurfaceClose"; -import { type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; +import type { ComposerBannerStackItem } from "./chat/ComposerBannerStack"; import { modelFallbackBannerItem } from "./chat/ComposerUsageLimits"; import { ComposerSurface } from "./chat/ComposerSurface"; import { resolveThreadSyncPhase } from "../threadSync"; @@ -391,13 +398,16 @@ import { resolveComposerProviderSelection, resolveThreadMetadataUpdateForNextTurn, resolveSendEnvMode, - startNewThreadForProject, codexArtifactTemplatePromptToAppend, + isCoveredByModal, shouldRefocusComposerOnWindowFocus, hasCompactableConversation, } from "./ChatView.logic"; import { useLocalStorage } from "~/hooks/useLocalStorage"; import { useComposerHandleContext } from "../composerHandleContext"; +import { useLayoutPane, useLayoutPaneFocusedRef } from "../layout/layoutPaneContext"; +import { publishThreadChatBridge } from "../layout/threadSurfaceBridge"; +import { runInNewLayoutTab } from "../layout/layoutStore"; import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { assetEnvironment } from "../state/assets"; @@ -407,8 +417,6 @@ import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; import { observeResize } from "~/lib/observeResize"; import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark"; -import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers"; -import { ChatRightPanel } from "./chat/ChatRightPanel"; import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting"; import { branchMismatchBannerItem, extensionStatusBannerItem } from "./chat/ThreadActivityBanners"; import { ThreadNow } from "./chat/ThreadNow"; @@ -440,8 +448,22 @@ const EMPTY_RUNS: ThreadStructure["runs"] = []; const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray = []; const EMPTY_COMPOSER_BANNER_ITEMS: ReadonlyArray = []; const EMPTY_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = []; +const EMPTY_RESOLVED_APPROVAL_DECISIONS: ReadonlyMap = + new Map(); -const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet = new Set(); +function deriveResolvedApprovalDecisions( + requests: ThreadStructure["runtimeRequests"] | undefined, +): ReadonlyMap { + if (!requests || requests.length === 0) return EMPTY_RESOLVED_APPROVAL_DECISIONS; + let map: Map | null = null; + for (const request of requests) { + if (request.status === "resolved" && request.decision !== undefined) { + if (map === null) map = new Map(); + map.set(request.id, request.decision); + } + } + return map ?? EMPTY_RESOLVED_APPROVAL_DECISIONS; +} type ChatViewProps = | { @@ -557,7 +579,11 @@ export default function ChatView(props: ChatViewProps) { }); const promptRef = useRef(""); const localComposerRef = useRef(null); - const composerRef = useComposerHandleContext() ?? localComposerRef; + const layoutPane = useLayoutPane(); + const layoutPaneFocusedRef = useLayoutPaneFocusedRef(); + const ownsThread = layoutPane.focused || layoutPane.related; + const paletteComposerRef = useComposerHandleContext(); + const composerRef = (ownsThread ? paletteComposerRef : null) ?? localComposerRef; const queuedRunEdit = useQueuedRunEdit({ environmentId, routeThreadRef, @@ -625,23 +651,42 @@ export default function ChatView(props: ChatViewProps) { const clientSettingsHydrated = useClientSettingsHydrated(); const timestampFormat = settings.timestampFormat; const navigate = useNavigate(); - // Selects primitives: an object here is new on every router store update, which - // re-renders ChatView on unrelated navigation state changes. - const citationHref = useLocation({ select: (location) => location.href }); - const citationKey = useLocation({ - select: (location) => location.state.assistantCitationActivation ?? location.state.__TSR_key, + const citationLocation = useLocation({ + // Other panes navigating must not rerender this thread's timeline. + select: (location) => { + const citation = assistantCitationFromLocation(location.href); + return citation && + citation.environmentId === environmentId && + (citation.threadId === threadId || (!embedded && layoutPane.focused)) + ? { + href: location.href, + key: + location.state.assistantCitationActivation ?? + location.state.__TSR_key ?? + location.href, + } + : null; + }, + structuralSharing: true, }); - const citationLocation = { href: citationHref, key: citationKey }; - const locationCitation = assistantCitationFromLocation(citationLocation.href); - const citationActivation = citationLocation.key ?? citationLocation.href; + const locationCitation = citationLocation + ? assistantCitationFromLocation(citationLocation.href) + : null; + const citationActivation = citationLocation?.key ?? ""; const citationRequest = ( - locationCitation && - locationCitation.environmentId === environmentId && - locationCitation.threadId === threadId - ? { citation: locationCitation, key: citationActivation } + citationLocation && locationCitation && locationCitation.threadId === threadId + ? { + citation: locationCitation, + scope: assistantCitationScopeFromLocation(citationLocation.href), + key: citationActivation, + } : null ) as AssistantCitationRequest | null; - useSideChatCitationReveal(embedded ? null : routeThreadRef, locationCitation, citationActivation); + useSideChatCitationReveal( + embedded || !layoutPane.focused ? null : routeThreadRef, + locationCitation, + citationActivation, + ); const citationHistory = useCitedHistory(citationRequest); const { resolvedTheme } = useTheme(); const composerRuntimeMode = useComposerDraftStore( @@ -681,7 +726,10 @@ export default function ChatView(props: ChatViewProps) { const composerImagesRef = useRef([]); const composerFilesRef = useRef([]); const composerTerminalContextsRef = useRef([]); + const [headerControlsInset, measureHeaderControls] = useHeaderControlsInset(); const branchToolbarRef = useRef(null); + const threadDetailsPanelRef = useRef(null); + const detailsVisibility = useClientSettings(resolveThreadDetailsVisibility); const [composerStashHost, setComposerStashHost] = useState(null); const [composerTrayControlsHost, setComposerTrayControlsHost] = useState( null, @@ -773,6 +821,9 @@ export default function ChatView(props: ChatViewProps) { return () => window.removeEventListener("dragend", clearWorkspaceFileDrag); }, [isWorkspaceFileDragActive]); const prefersPlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY); + // Layout opens are tabs at every viewport size. Only explicit shortcuts + // create splits; the legacy drawer/sheet is for views outside the layout. + const companionPanes = layoutPane.tabId !== null; const isMobileViewport = useMediaQuery("max-sm"); // Focusing the composer without a tap raises the on-screen keyboard on touch devices. const isCoarsePointer = useMediaQuery({ pointer: "coarse" }); @@ -1168,15 +1219,14 @@ export default function ChatView(props: ChatViewProps) { const rightPanelState = useRightPanelStore((state) => selectThreadRightPanelState(state.byThreadKey, activeThreadRef), ); - const shouldUsePlanSidebarSheet = prefersPlanSidebarSheet && rightPanelState.maximized !== true; + const shouldUsePlanSidebarSheet = + !companionPanes && + (prefersPlanSidebarSheet || layoutPane.narrow) && + rightPanelState.maximized !== true; const activeRightPanelSurface = useRightPanelStore((state) => selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef), ); const activePreviewState = useThreadPreviewState(activeThreadRef); - const activePreviewServerEpoch = activePreviewState.serverEpoch; - const resolvePreviewRuntimeTabId = activeThreadRef - ? (tabId: string) => previewRuntimeTabId(activeThreadRef, activePreviewServerEpoch, tabId) - : undefined; const activePreviewMiniPlayer = usePreviewMiniPlayerStore((state) => selectThreadPreviewMiniPlayer(state.byThreadKey, activeThreadRef), ); @@ -1202,25 +1252,23 @@ export default function ChatView(props: ChatViewProps) { panelAnimationDurationMs, ); const rightPanelPresent = rightPanelPresence.present; + const rightPanelControlsInPanel = shouldUsePlanSidebarSheet && rightPanelPresent && rightPanelOpen; - const rightPanelControlsAtRoot = rightPanelPresent && !shouldUsePlanSidebarSheet; + const rightPanelControlsAtRoot = + rightPanelPresent && !shouldUsePlanSidebarSheet && !companionPanes; const renderedRightPanelSurface = rightPanelPresence.value?.activeSurface ?? null; - const renderedRightPanelSurfaces = rightPanelPresence.value?.surfaces ?? []; - const previewMiniPlayerVisible = shouldRenderPreviewMiniPlayer( - activePreviewMiniPlayer?.source ?? null, - renderedRightPanelSurface, - ); - 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; - const toggleRightPanelMaximizedStable = useStableCallback(() => { - if (canMaximizeRightPanel && activeThreadRef) { - useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized); - } - }); - const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet; + // In a layout pane every shown surface is a tab of its own, not only the active one. + const previewMiniPlayerVisible = companionPanes + ? (rightPanelOpen ? rightPanelState.surfaces : [null]).every((surface) => + shouldRenderPreviewMiniPlayer(activePreviewMiniPlayer?.source ?? null, surface), + ) + : shouldRenderPreviewMiniPlayer( + activePreviewMiniPlayer?.source ?? null, + renderedRightPanelSurface, + ); + const inlineRightPanelOwnsTitleBar = + rightPanelOpen && !shouldUsePlanSidebarSheet && !companionPanes; const [threadPanelPopoverHandle] = useState(PopoverCreateHandle); const [chatCanvasStore] = useState(createChatCanvasStore); @@ -1244,10 +1292,11 @@ export default function ChatView(props: ChatViewProps) { !isServerThread && draftFallback ? draftFallback.selection : activeProjectSettings.settings.defaultModelSelection; + // A new thread in this project, in a new tab of this pane. const handleNewThreadInActiveProject = () => { - startNewThreadForProject(activeProjectRef, handleNewThread); + if (activeProjectRef === null) return; + void runInNewLayoutTab(() => handleNewThread(activeProjectRef)); }; - const handleNewThreadInActiveProjectStable = useStableCallback(handleNewThreadInActiveProject); const projectGroupingSettings = selectProjectGroupingSettings(settings); const activeDraftLogicalProjectKey = !isServerThread && activeProject @@ -1267,29 +1316,6 @@ export default function ChatView(props: ChatViewProps) { const activeProjectKey = activeProject ? `${activeProject.environmentId}:${activeProject.workspaceRoot}` : null; - const [pendingFileSurfaceIdsByProject, setPendingFileSurfaceIdsByProject] = useState< - ReadonlyMap> - >(() => new Map()); - const pendingFileSurfaceIds = activeProjectKey - ? (pendingFileSurfaceIdsByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS) - : EMPTY_PENDING_FILE_SURFACE_IDS; - const handleFilePendingChange = (relativePath: string, pending: boolean) => { - if (!activeProjectKey) return; - setPendingFileSurfaceIdsByProject((currentByProject) => { - const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS; - const surfaceId = `file:${relativePath}`; - if (current.has(surfaceId) === pending) return currentByProject; - const next = new Set(current); - if (pending) next.add(surfaceId); - else next.delete(surfaceId); - const nextByProject = new Map(currentByProject); - if (next.size === 0) nextByProject.delete(activeProjectKey); - else nextByProject.set(activeProjectKey, next); - return nextByProject; - }); - }; - const handleFilePendingChangeStable = useStableCallback(handleFilePendingChange); - const configuredPreviewUrls = getConfiguredPreviewUrls(activeProjectScripts); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drops file surfaces from the right panel store once bootstrap shows the thread has no workspace useEffect(() => { @@ -1476,17 +1502,20 @@ export default function ChatView(props: ChatViewProps) { const phase = derivePhase(activeRuntime); const serverThreadId = serverThread?.id; const serverThreadEnvironmentId = serverThread?.environmentId; - const setThreadError = makeThreadErrorSetter({ - routeThreadRef, - routeThreadKey, - draftId, - serverThreadRef: - serverThreadId !== undefined && serverThreadEnvironmentId !== undefined - ? { threadId: serverThreadId, environmentId: serverThreadEnvironmentId } - : null, - setLocalServerErrorsByThreadKey, - setLocalDraftErrorsByDraftId, - }); + // Stable, so a chat view render does not re-render the composer and every hook it feeds. + const setThreadError = useStableCallback( + makeThreadErrorSetter({ + routeThreadRef, + routeThreadKey, + draftId, + serverThreadRef: + serverThreadId !== undefined && serverThreadEnvironmentId !== undefined + ? { threadId: serverThreadId, environmentId: serverThreadEnvironmentId } + : null, + setLocalServerErrorsByThreadKey, + setLocalDraftErrorsByDraftId, + }), + ); const { pendingApprovals, pendingUserInputs, @@ -1518,6 +1547,18 @@ export default function ChatView(props: ChatViewProps) { const onHeldRequestIdsChange = useStableCallback((requestIds: ReadonlySet) => { setHeldApprovalRequestIds((current) => (shallow(current, requestIds) ? current : requestIds)); }); + const resolvedApprovalDecisions = deriveResolvedApprovalDecisions( + serverProjection?.runtimeRequests, + ); + const childThreadApprovals = useAtomValue(childThreadApprovalsAtom(activeThreadRef)); + const visiblePendingApprovalCount = pendingApprovals.filter( + (approval) => !heldApprovalRequestIds.has(approval.requestId), + ).length; + const onApprovalAnsweredStable = useStableCallback(() => { + if (visiblePendingApprovalCount + childThreadApprovals.length <= 1 && layoutPane.focused) { + requestAnimationFrame(() => composerRef.current?.focusAtEnd()); + } + }); // Answering an approval or question on any client resumes quota spending, so include it in the key. const usageLimitsKey = activeProviderInstanceId === null || (isServerThread && activeThread === undefined) @@ -1706,6 +1747,17 @@ export default function ChatView(props: ChatViewProps) { ); const timelineEmpty = timelineEntries.length === 0 && !hasStreamedTimelineRows; const displayedTimelineKey = activeThreadKey ?? routeThreadKey; + const deferredChat = use(DeferredChatContext); + const [timelineInstance, setTimelineInstance] = useState({ + threadKey: displayedTimelineKey, + revision: 0, + }); + if (timelineInstance.threadKey !== displayedTimelineKey) { + setTimelineInstance({ + threadKey: displayedTimelineKey, + revision: timelineInstance.revision + (deferredChat ? 1 : 0), + }); + } const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey); const { worktreeSetup, @@ -1800,6 +1852,9 @@ export default function ChatView(props: ChatViewProps) { }; const keybindings = useAtomValue(primaryServerKeybindingsAtom); const backgroundThread = use(BackgroundThreadContext); + // The details panel's git control takes the commit and push shortcut while it shows, so the + // hidden "shortcut" control (a second copy of its queries and dialogs) mounts only without it. + const [panelGitHostsShortcut, setPanelGitHostsShortcut] = useState(false); const scriptKeybindings = useAtomValue(serverEnvironment.configValueAtom(environmentId))?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS; @@ -1875,6 +1930,7 @@ export default function ChatView(props: ChatViewProps) { const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined; const activeTerminalLaunchContext = terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null; + // A draft without a project (the scratch folder) never shows git controls. const liveIsGitRepo = gitStatusQuery.data?.isRepo; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records live git repo status in the session cache read while the status query is unavailable useEffect(() => { @@ -1882,7 +1938,14 @@ export default function ChatView(props: ChatViewProps) { rememberCheckoutIsRepo(environmentId, gitStatusCwd, liveIsGitRepo); } }, [environmentId, gitStatusCwd, liveIsGitRepo]); - const isGitRepo = liveIsGitRepo ?? recallCheckoutIsRepo(environmentId, gitStatusCwd) ?? true; + const gitProjectIsScratch = + activeProject !== null && isScratchProject(activeProject, serverConfig?.scratchWorkspaceRoot); + const isGitRepo = + gitProjectIsScratch && !isServerThread + ? false + : (liveIsGitRepo ?? + recallCheckoutIsRepo(environmentId, gitStatusCwd) ?? + !gitProjectIsScratch); // A plain folder holding tracked repositories has turn diffs without being a Git repository. const diffAvailable = isGitRepo || @@ -1923,32 +1986,6 @@ export default function ChatView(props: ChatViewProps) { isGitRepo, showEnvironmentIndicator: showComposerEnvironmentIndicator, }); - const terminalShortcutLabelOptions = { - context: { - terminalFocus: true, - terminalOpen: Boolean(terminalUiState.terminalOpen), - }, - }; - const splitTerminalShortcutLabel = shortcutLabelForCommand( - keybindings, - "terminal.split", - terminalShortcutLabelOptions, - ); - const splitTerminalVerticalShortcutLabel = shortcutLabelForCommand( - keybindings, - "terminal.splitVertical", - terminalShortcutLabelOptions, - ); - const newTerminalShortcutLabel = shortcutLabelForCommand( - keybindings, - "terminal.new", - terminalShortcutLabelOptions, - ); - const closeTerminalShortcutLabel = shortcutLabelForCommand( - keybindings, - "terminal.close", - terminalShortcutLabelOptions, - ); const { needsLoadBalancing, @@ -1979,7 +2016,7 @@ export default function ChatView(props: ChatViewProps) { }); const { focusComposer: focusComposerStable, scheduleComposerFocus: scheduleComposerFocusStable } = - useComposerFocus(composerRef); + useComposerFocus(composerRef, layoutPaneFocusedRef); const canInterruptRunningThread = canOperateThread && deriveCanInterruptRunningThread(activeThread !== undefined, activeRuntime); const onInterrupt = async () => { @@ -2046,17 +2083,13 @@ export default function ChatView(props: ChatViewProps) { const queuedRunsControlRef = useRef(null); const { - activatePanelTerminalStable, + startTerminal, addTerminalContextToDraftStable, - addTerminalSurfaceStable, - closePanelTerminalStable, lastInvokedScriptByProjectId, runProjectScriptStable, runShellCommandStable, - setTerminalOpenStable, - splitPanelTerminalStable, - splitPanelTerminalVerticalStable, toggleTerminalVisibilityStable, + setTerminalOpenStable, shortcuts: terminalShortcuts, } = useChatTerminalActions({ environmentId, @@ -2066,7 +2099,6 @@ export default function ChatView(props: ChatViewProps) { activeThreadId, activeThreadRef, activeProject, - activeRightPanelSurface, runningTerminalIds, activeServerOrderedTerminalIds, activeTerminalLabelsById, @@ -2076,6 +2108,24 @@ export default function ChatView(props: ChatViewProps) { setTerminalUiLaunchContext, setThreadError, }); + // A hidden terminal pane stays in the chat's notch until cmd+J brings it back. + const terminalToggleShortcutLabel = shortcutLabelForCommand(keybindings, "terminal.toggle"); + const hasHiddenTerminal = + companionPanes && !terminalUiState.terminalOpen && terminalUiState.terminalIds.length > 0; + const hiddenTerminalChip = ( + hasHiddenTerminal + ? { + shortcutLabel: terminalToggleShortcutLabel, + running: activeThreadKnownSessions.some( + (session) => + terminalUiState.terminalIds.includes(session.target.terminalId) && + session.state.status === "running", + ), + onShow: toggleTerminalVisibilityStable, + } + : null + ) as HiddenTerminalChip | null; + const { saveProjectScript: saveProjectScriptStable, updateProjectScript: updateProjectScriptStable, @@ -2091,6 +2141,8 @@ export default function ChatView(props: ChatViewProps) { AuthPreviewOperateScope, ); const shownPreviewMiniPlayer = + layoutPane.visible && + !backgroundThread && activeThreadRef && activePreviewMiniPlayer && previewMiniPlayerVisible && @@ -2114,6 +2166,18 @@ export default function ChatView(props: ChatViewProps) { detailsCardInlineOpen: threadPanelInlineOpen, }).detailsCardMode, ); + const workspaceInDetails = !shouldShowComposerWorkspace({ + isServerThread, + embedded, + visibility: detailsVisibility, + }); + const openWorkspaceDetailsStable = useStableCallback(() => { + threadDetailsPanelRef.current?.openBranch(threadPanelPresentation); + }); + const openStartedWorkspaceStable = useStableCallback(() => { + if (workspaceInDetails) openWorkspaceDetailsStable(); + else branchToolbarRef.current?.openBranchPicker(); + }); const threadPanelOpen = useRightPanelStore((state) => selectThreadPanelOpen( state.threadPanelVisibilityByThreadKey, @@ -2179,16 +2243,6 @@ export default function ChatView(props: ChatViewProps) { visiblePullRequestCount, onDiffPanelOpen, }); - const { - closeSurface: closeRightPanelSurface, - closeOtherSurfaces: closeOtherRightPanelSurfacesStable, - closeSurfacesToRight: closeRightPanelSurfacesToRightStable, - closeAllSurfaces: closeAllRightPanelSurfacesStable, - } = useRightPanelSurfaceClose({ - threadRef: activeThreadRef, - terminalLabelsById: activeTerminalLabelsById, - }); - const closeRightPanelSurfaceStable = closeRightPanelSurface; const persistThreadSettingsForNextTurn = async (input: { threadId: ThreadId; createdAt: string; @@ -2284,13 +2338,32 @@ export default function ChatView(props: ChatViewProps) { setTimelineAnchor, }); + // Moving between panes keeps the workspace control the user chose in the pane it enters. + const threadEntryPaneFocusedRef = useRef(layoutPane.focused); + const keepsEnteredPaneFocus = useStableCallback(() => { + if (isReturnedSurfaceFocus()) return true; + if (threadEntryPaneFocusedRef.current || layoutPane.tabId === null) return false; + const activeArea = document.activeElement?.closest("[data-workspace-area]"); + return ( + activeArea?.closest("[data-layout-tab-id]")?.dataset.layoutTabId === + layoutPane.tabId + ); + }); + const focusOpenedThreadComposer = useStableCallback(() => { + if (!isCoveredByModal(composerOverlayElement)) focusComposerStable(); + }); useFocusComposerOnThreadOpen( activeThreadRef, workspaceLayoutElement, - !embedded, + !embedded && layoutPane.focused && !backgroundThread, terminalUiState.terminalOpen, - isCoarsePointer ? ignoreComposerFocus : focusComposerStable, + isCoarsePointer ? ignoreComposerFocus : focusOpenedThreadComposer, + keepsEnteredPaneFocus, ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records pane focus after thread entry reads it, so the next entry knows it moved between panes + useEffect(() => { + threadEntryPaneFocusedRef.current = layoutPane.focused; + }, [layoutPane.focused]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus listener that refocuses the composer after the window regains focus on a fine pointer useEffect(() => { @@ -2305,6 +2378,7 @@ export default function ChatView(props: ChatViewProps) { } let frame: number | null = null; const onWindowFocus = () => { + if (!layoutPaneFocusedRef.current) return; if (frame !== null) window.cancelAnimationFrame(frame); // Wait an extra frame after window focus so the composer treats focus as an expansion request. frame = window.requestAnimationFrame(() => { @@ -2332,6 +2406,7 @@ export default function ChatView(props: ChatViewProps) { isCoarsePointer, isMobileViewport, terminalUiState.terminalOpen, + layoutPaneFocusedRef, ]); // Promotion drops draftId while a send may still be dispatching, so key by thread. @@ -2387,7 +2462,11 @@ export default function ChatView(props: ChatViewProps) { ? (pendingServerThreadStartFromOriginByThreadId[activeThread?.id ?? ""] ?? activeProjectSettings.settings.newWorktreesStartFromOrigin) : false; - const worktreeRepositoryChoices = useWorktreeRepositoryChoices(activeProject); + // The server launches a No project worktree request in the thread's own folder, so the + // repositories found in other No project threads' folders are never a choice. + const worktreeRepositoryChoices = useWorktreeRepositoryChoices( + activeProjectIsScratch ? null : activeProject, + ); const workspaceModesOffered = offersWorkspaceModes({ isScratchProject: activeProjectIsScratch, isGitRepo, @@ -2479,11 +2558,15 @@ export default function ChatView(props: ChatViewProps) { useLayoutEffect(() => { if (!composerOverlayElement) return; - const updateHeight = () => { - publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height); + const updateHeight = (entries: readonly ResizeObserverEntry[]) => { + const overlayEntry = entries.find((entry) => entry.target === composerOverlayElement); + publishComposerOverlayHeightStable( + overlayEntry?.borderBoxSize[0]?.blockSize ?? + composerOverlayElement.getBoundingClientRect().height, + ); }; - updateHeight(); + updateHeight([]); // The hero overlay fills the pane, so the composer's own growth only shows on its stack. const stack = isDraftHeroState ? composerOverlayElement.querySelector('[data-chat-composer-stack="true"]') @@ -2527,26 +2610,13 @@ export default function ChatView(props: ChatViewProps) { }) : null; const { - activateRightPanelSurfaceStable, - addDeviceSurfaceStable, - addDiffSurfaceStable, - addFilesSurfaceStable, - addPullRequestSurfaceStable, - addPullRequestsSurfaceStable, - closePreviewPanelStable, - copyRightPanelFilePathStable, - createBrowserSurface, - createBrowserSurfaceStable, - duplicateBrowserSurfaceStable, - moveRightPanelSurfaceStable, onOpenToolDiffStable, onOpenTurnDiffStable, openChangesFromThreadPanelStable, - openFileSurfaceStable, - toggleRightPanelStable, toggleThreadPanelStable, shortcuts: rightPanelShortcuts, } = useRightPanelActions({ + startTerminal, activeThreadRef, activeProject, activeRightPanelSurface, @@ -2562,15 +2632,10 @@ export default function ChatView(props: ChatViewProps) { canOperatePreview, diffOpen, previewPanelOpen, - rightPanelOpen, supportsPullRequests, pullRequestsSurfaceAvailable: linkedItemsSurfaceAvailable, - gitCwd, - activeProjectCwd, onDiffPanelOpen, - closeRightPanelSurface, }); - const pullRequestSurfaceAvailable = supportsPullRequests && pullRequestPanelTarget !== null; const { acknowledgeActiveThreadWoke, activeBranchMismatchKey, @@ -2639,9 +2704,12 @@ export default function ChatView(props: ChatViewProps) { entry.enabled && entry.isAvailable, ); + const usablePendingHandoffSelection = pendingHandoffSelectionUsable + ? pendingHandoffSelection + : null; const pendingHandoff = resolvePendingHandoff( serverProjection, - pendingHandoffSelectionUsable ? pendingHandoffSelection : null, + usablePendingHandoffSelection, providerStatuses, ); const compactThreadUnavailable = @@ -2660,15 +2728,17 @@ export default function ChatView(props: ChatViewProps) { pendingApprovals.length > 0 || pendingUserInputs.length > 0; const compactDisabled = compactThreadUnavailable; - const compactDisabledReason = compactDisabled - ? !canOperateThread - ? gt("This connection cannot change threads.") - : !activeProject - ? gt("Choose a project before compacting") + const compactUnavailableReason = !compactThreadUnavailable + ? null + : isWorking + ? gt("Compact when the agent finishes") + : pendingApprovals.length > 0 || pendingUserInputs.length > 0 + ? gt("Answer the pending request first") : !manualCompactionProviderAvailable - ? gt("Compaction is unavailable for this provider") - : gt("Compacting is unavailable right now") - : null; + ? gt("This provider cannot compact on request") + : !activeThreadHasCompactableConversation + ? gt("Nothing to compact yet") + : gt("Compacting is unavailable right now"); const freshSessionAvailable = activeMessageCount > 0 && serverConfig?.environment.capabilities.freshContext === true; const freshSessionArmed = useFreshSessionArmed(routeThreadKey); @@ -2784,7 +2854,7 @@ export default function ChatView(props: ChatViewProps) { ); // The working bar names the request while its row stays actionable. const firstPendingApproval = pendingApprovals[0] ?? null; - const timelinePendingRequest = ((): TimelinePendingRequest | null => { + const timelinePendingRequest = (() => { if (firstPendingApproval) { return { kind: "approval", @@ -2803,7 +2873,7 @@ export default function ChatView(props: ChatViewProps) { activeThreadShell?.hasPendingUserInput !== false, } : null; - })(); + })() as TimelinePendingRequest | null; const limitRecovery = activeThreadShell?.limitRecovery ?? null; const limitedRunId = serverRuntime?.status === "failed" && serverRuntime.lastErrorClass === "usage_limit" @@ -2856,7 +2926,7 @@ export default function ChatView(props: ChatViewProps) { const onToggleTimelineUsageLimitSnoozeStable = useStableCallback( onToggleTimelineUsageLimitSnooze, ); - const timelineUsageLimit = ((): TimelineUsageLimit | null => { + const timelineUsageLimit = (() => { if (limitedRunId === null || limitThreadId === null) return null; return { runId: limitedRunId, @@ -2864,7 +2934,7 @@ export default function ChatView(props: ChatViewProps) { snoozed: limitSnoozed, onToggleSnooze: limitResetAt === null ? null : onToggleTimelineUsageLimitSnoozeStable, }; - })(); + })() as TimelineUsageLimit | null; const focusComposerAtEnd = () => composerRef.current?.focusAtEnd(); const focusComposerAtEndStable = useStableCallback(focusComposerAtEnd); const composerBannerItems = (() => { @@ -2993,7 +3063,9 @@ export default function ChatView(props: ChatViewProps) { const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({ terminalFocus: getTerminalFocusOwner() !== null, terminalOpen: Boolean(terminalUiState.terminalOpen), - previewFocus: isPreviewFocused(), + // A thread's own toggles answer from its diff, files and pull request tabs; only a + // browser keeps the keys it shares with them (mod+l). + previewFocus: isBrowserFocused(), previewOpen: previewPanelOpen, rightPanelOpen, editableFocus: isEditableFocused(eventTarget), @@ -3087,20 +3159,6 @@ export default function ChatView(props: ChatViewProps) { }, }); - const closeActiveRightPanelSurfaceStable = useStableCallback(() => { - if (activeRightPanelSurface) closeRightPanelSurface(activeRightPanelSurface); - }); - - // A focused desktop browser page forwards these chords as menu actions. - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to desktop bridge menu actions that toggle or close the right panel - useEffect(() => { - if (embedded || backgroundThread) return; - return window.desktopBridge?.onMenuAction((action) => { - if (action === "rightPanel.toggle") toggleRightPanelStable(); - else if (action === "rightPanel.close") closeActiveRightPanelSurfaceStable(); - }); - }, [embedded, backgroundThread, toggleRightPanelStable, closeActiveRightPanelSurfaceStable]); - usePasteToFocusComposer(embedded ? null : activeThreadId, composerRef); // A delegated task is a remote thread's subagent. const isSubagentThread = @@ -3125,11 +3183,6 @@ export default function ChatView(props: ChatViewProps) { // An embedded thread's commands run in its host's terminal, which is the host's checkout. const runsOutsideHostCheckout = embedded && (activeThread?.worktreePath ?? null) !== (panelHostShell?.worktreePath ?? null); - // A maximized panel covers the terminal drawer the command runs in. - const runSideChatShellCommandStable = useStableCallback((command: string) => { - if (activeThreadRef) useRightPanelStore.getState().setMaximized(activeThreadRef, false); - runShellCommandStable(command); - }); // Main-thread surfaces show this reason; `/side` sent anyway gets it as a toast. const sideChatDisabledReason = activeThread?.lineage.sideChat === true @@ -3149,9 +3202,8 @@ export default function ChatView(props: ChatViewProps) { ) ? gt("Available once the thread's worktree is set up.") : null; - const openSideChatStable = useStableCallback(() => void sideChat.open()); - const openSurfaceInMainView = useOpenSurfaceInMainView(activeThreadRef); const sendSideChatStable = useStableCallback(sideChat.open); + const openNewSideChatStable = useStableCallback(() => void sideChat.open()); const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } = useTimelineRewind({ environmentId, @@ -3236,86 +3288,89 @@ export default function ChatView(props: ChatViewProps) { : (timelineMessages.findLast( (message) => message.role === "user" && message.runId === failedRunId, ) ?? null); - const { onSend, captureDetachedSend, onRetryFailedRun, retryingFailedRunId } = useComposerSend({ - environmentId, - routeThreadKey, - currentRouteThreadKeyRef, - draftId, - draftThread, - activeThread, - activeThreadKey, - activeThreadBranch, - activeProject, - activeProjectIsScratch, - activeProjectDefaultModelSelection, - activeMessageCount, - isServerThread, - isLocalDraftThread, - isGitRepo, - phase, - failedRunId, - failedRunMessage, - runtimeMode, - sendEnvMode, - worktreeRepositories, - startFromOrigin, - localCheckoutBranchMismatch, - logicalProjectEnvironments, - providerInstanceEntries, - composerRef, - composerDraftTarget, - promptRef, - composerImagesRef, - composerFilesRef, - composerTerminalContextsRef, - feedbackUploadsInFlightRef, - queuedRunEdit, - isRevertingCheckpoint, - threadDetailLoading, - activeEnvironmentUnavailable, - isSendBusy, - sendQueuesBehindSetup, - isDraftHeroState, - panelAnimationsActive, - panelAnimationDurationMs, - keepFullHistory, - freshSessionAvailable: freshSessionCommandAvailable, - resumeCompactionTokens, - usageLimitsKey, - usageLimitsOffered, - openUsageLimits, - clearUsageLimitsFor, - needsLoadBalancing, - loadBalancing, - refreshBeforeSend, - readPendingEnvironmentChange, - pendingApprovals, - respondingRequestIds, - activePendingUserInput, - onAdvanceActivePendingUserInput, - onRespondToApproval: onRespondToApprovalStable, - beginLocalDispatch, - resetLocalDispatch, - beginWorktreeSetup, - captureDraftHeroComposerRect, - setDockedDraftHeroThreadKey, - setSetupQueueSendThreadKey, - setOptimisticUserMessages, - optimisticBlobPreviews: { - track: (message) => optimisticBlobPreviews.track(threadId, message), - release: (message) => optimisticBlobPreviews.release(threadId, message), - }, - setFeedbackSubmissionsByThreadKey, - setThreadError, - setKeepFullHistory, - anchorNewTurn, - acknowledgeActiveThreadWoke, - onSideChat: sideChat.available ? sendSideChatStable : undefined, - sideChatDisabledReason, - handleNewThreadInActiveProject, - persistThreadSettingsForNextTurn, - linkCheckoutPullRequest, - }); + const { onSend, withdrawQueuedSend, captureDetachedSend, onRetryFailedRun, retryingFailedRunId } = + useComposerSend({ + environmentId, + routeThreadKey, + currentRouteThreadKeyRef, + draftId, + draftThread, + activeThread, + activeThreadKey, + activeThreadBranch, + activeProject, + activeProjectIsScratch, + activeProjectDefaultModelSelection, + activeMessageCount, + isServerThread, + isLocalDraftThread, + isGitRepo, + phase, + failedRunId, + failedRunMessage, + runtimeMode, + sendEnvMode, + worktreeRepositories, + startFromOrigin, + localCheckoutBranchMismatch, + logicalProjectEnvironments, + providerInstanceEntries, + composerRef, + composerDraftTarget, + promptRef, + composerImagesRef, + composerFilesRef, + composerTerminalContextsRef, + feedbackUploadsInFlightRef, + queuedRunEdit, + isRevertingCheckpoint, + threadDetailLoading, + activeEnvironmentUnavailable, + isSendBusy, + sendQueuesBehindSetup, + isDraftHeroState, + panelAnimationsActive, + panelAnimationDurationMs, + keepFullHistory, + freshSessionAvailable: freshSessionCommandAvailable, + resumeCompactionTokens, + usageLimitsKey, + usageLimitsOffered, + openUsageLimits, + clearUsageLimitsFor, + needsLoadBalancing, + loadBalancing, + refreshBeforeSend, + readPendingEnvironmentChange, + pendingApprovals, + respondingRequestIds, + activePendingUserInput, + onAdvanceActivePendingUserInput, + onRespondToApproval: onRespondToApprovalStable, + beginLocalDispatch, + resetLocalDispatch, + beginWorktreeSetup, + captureDraftHeroComposerRect, + setDockedDraftHeroThreadKey, + setSetupQueueSendThreadKey, + setOptimisticUserMessages, + optimisticBlobPreviews: { + track: (message) => optimisticBlobPreviews.track(threadId, message), + release: (message) => optimisticBlobPreviews.release(threadId, message), + }, + setFeedbackSubmissionsByThreadKey, + setThreadError, + setKeepFullHistory, + anchorNewTurn, + acknowledgeActiveThreadWoke, + onSideChat: sideChat.available ? sendSideChatStable : undefined, + sideChatDisabledReason, + handleNewThreadInActiveProject, + persistThreadSettingsForNextTurn, + linkCheckoutPullRequest, + layoutTabId: layoutPane.tabId, + }); + const withdrawQueuedSendStable = useStableCallback(withdrawQueuedSend); const onRetryFailedRunStable = useStableCallback(onRetryFailedRun); const canRetryFailedRun = @@ -3327,8 +3382,9 @@ export default function ChatView(props: ChatViewProps) { const trayStatusItems = useChatBannerLane({ environmentId, activeProviderStatus, + selectedModel: composerSelectedModelSelection?.model ?? activeThread?.modelSelection.model, providerStatuses, - usageLimitSources, + usageLimitSources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES, canSwitchProvider: lockedProvider === null || supportsProviderSwitchingViaHandoff, providerStatus: visibleProviderStatus, providerStatusDismissalKey, @@ -3345,14 +3401,19 @@ export default function ChatView(props: ChatViewProps) { ? (serverRuntime?.lastErrorCode ?? null) : null, threadErrorBannerKey, - onRetry: canRetryFailedRun ? () => void onRetryFailedRunStable() : null, + onRetry: !canRetryFailedRun + ? null + : failedRunId !== null && retryableWorkspacePreparationRunIds.has(failedRunId) + ? () => onRetryWorkspacePreparationStable(failedRunId) + : () => void onRetryFailedRunStable(), retrying: retryingFailedRunId !== null, setThreadError, setThreadErrorBannerDismissTick, }); + // The empty list is the shared constant, so an empty tray keeps the composer element memoized. const trayBannerItems = - trayStatusItems.length === 0 - ? composerBannerItems + trayStatusItems.length === 0 && composerBannerItems.length === 0 + ? EMPTY_COMPOSER_BANNER_ITEMS : [...trayStatusItems, ...composerBannerItems]; const onWorktreeSetupWorkLocally = () => { @@ -3428,21 +3489,15 @@ export default function ChatView(props: ChatViewProps) { )} onEditQueuedRun={queuedRunEdit.beginEdit} onCancelEdit={queuedRunEdit.cancelEdit} + onRemovePending={withdrawQueuedSendStable} timestampFormat={timestampFormat} onOpenThread={onOpenRelatedThreadStable} onImageExpand={onExpandTimelineImageStable} /> ) : null; - const resendAfterWorkLocally = () => { - setWorkLocallyResendDraftId(null); - void onComposerSendStable(); - }; - const resendAfterWorkLocallyStable = useStableCallback(resendAfterWorkLocally); - const workLocallyResendReady = - workLocallyResendDraftId !== null && - workLocallyResendDraftId === draftId && - isLocalDraftThread && + // Transient send blockers must also hold surface annotations until the chat can send. + const chatSendReady = !isSendBusy && !isRevertingCheckpoint && !threadDetailLoading && @@ -3451,6 +3506,39 @@ export default function ChatView(props: ChatViewProps) { !activeEnvironmentUnavailable && !activePendingUserInput && !feedbackUploading; + // The thread's surface tabs reach this chat through its bridge: diffs and + // files refresh on its workspace changes, browser annotations send from its + // composer, terminal selections go into it. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the mounted chat bridge to the external surface registry and releases it on cleanup + useEffect(() => { + if (!activeThreadRef) return; + return publishThreadChatBridge(activeThreadRef, { + workspaceMutationId, + workspaceRevision: workspaceRevision.revision, + sendReady: chatSendReady, + sendAnnotation: (annotation, image) => { + sendPreviewAnnotationStable(annotation, image); + }, + addTerminalContext: addTerminalContextToDraftStable, + terminalLaunchContext: activeTerminalLaunchContext ?? null, + }); + }, [ + activeTerminalLaunchContext, + activeThreadRef, + addTerminalContextToDraftStable, + chatSendReady, + workspaceMutationId, + workspaceRevision.revision, + sendPreviewAnnotationStable, + ]); + // `chatSendReady` (above) holds every state that makes `onSend` bail and wait. + const draftSendReady = isLocalDraftThread && chatSendReady; + const resendAfterWorkLocallyStable = useStableCallback(() => { + setWorkLocallyResendDraftId(null); + void onComposerSendStable(); + }); + const workLocallyResendReady = + workLocallyResendDraftId !== null && workLocallyResendDraftId === draftId && draftSendReady; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- switches the draft to local mode, then resends the waiting message once sending is idle useEffect(() => { if ( @@ -3475,6 +3563,30 @@ export default function ChatView(props: ChatViewProps) { setDraftThreadContext, workLocallyResendReady, ]); + // Send on the no-projects home lands here with the message carried in; + // send it once, as soon as the same readiness holds. + const sendOnOpenDraftId = useDraftSendOnOpenStore((store) => store.draftId); + const sendOnOpenReady = + sendOnOpenDraftId !== null && sendOnOpenDraftId === draftId && draftSendReady; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- delivers the pending cross-pane send request to the mounted composer once its provider is ready + useEffect(() => { + if ( + !sendOnOpenReady || + sendInFlightRef.current || + feedbackUploadsInFlightRef.current.has(routeThreadKey) + ) { + return; + } + useDraftSendOnOpenStore.setState({ draftId: null }); + // Out of the commit: sending flushes the composer synchronously. + queueMicrotask(() => void onComposerSendStable()); + }, [ + routeThreadKey, + sendOnOpenReady, + sendInFlightRef, + feedbackUploadsInFlightRef, + onComposerSendStable, + ]); const shownThreadSyncPhase = activeEnvironmentUnavailable ? null : delayedThreadSyncPhase; const hasThreadNow = @@ -3497,35 +3609,6 @@ export default function ChatView(props: ChatViewProps) { count: queuedRunCount, }), ].filter((part) => part !== null); - // The end of the timeline holds the thread's present and next turns: what it is doing now, - // its lifecycle status, guest messages awaiting you, then your queued messages. - const timelineFooter = - pendingHandoff === null && - !hasThreadNow && - threadStatusLine === null && - pendingGuestMessageCount === 0 && - !hasQueuedTurns ? null : ( - <> - {pendingHandoff === null ? null : ( -
- -
- )} - {threadStatusLine} - {pendingGuestMessageCount > 0 && isServerThread && activeThread ? ( - - ) : null} - - ); const pendingSidebarFileDrops = useSidebarPendingFileDropStore((state) => state.pending); const consumePendingFileDrop = useSidebarPendingFileDropStore( @@ -3569,85 +3652,41 @@ export default function ChatView(props: ChatViewProps) { (folders: Parameters[0]) => composerRef.current?.addDroppedFolders(folders), ); - // Above the early return, where React Compiler can cache it for the side chat pane. - const sideChatParentPanel = { - hostRef: scopeThreadRef(environmentId, threadId), - openToolDiff: onOpenToolDiffStable, - runShellCommand: runSideChatShellCommandStable, - }; if (!activeThread) { return embedded ? null : ; } - const rightPanelContent = activeThreadRef ? ( - 1 - ? addPullRequestsSurfaceStable - : undefined, - }} - issuesSupported={serverConfig?.environment.capabilities.issues === true} - files={{ - projectId: activeProject?.id, - projectName: activeProject?.title ?? null, - workspaceRoot: activeWorkspaceRoot, - availableEditors, - pendingSurfaceIds: pendingFileSurfaceIds, - onOpenFile: openFileSurfaceStable, - onPendingChange: handleFilePendingChangeStable, - }} + // The end of the timeline holds the thread's present and next turns: what it is doing now, + // its lifecycle status, guest messages awaiting you, then your queued messages. + // Built outside the condition, where the compiler memoizes it. + const timelineFooterContent = ( + 0 && isServerThread ? activeThreadRef : null} + onImageExpand={onExpandTimelineImageStable} + onFileOpen={openFileAttachmentStable} /> - ) : null; + ); + const timelineFooter = + pendingHandoff === null && + !hasThreadNow && + threadStatusLine === null && + pendingGuestMessageCount === 0 && + !hasQueuedTurns + ? null + : timelineFooterContent; + const panelToggleControlProps = { - terminalAvailable: activeProject !== null, - terminalOpen: terminalUiState.terminalOpen, - terminalShortcutLabel: shortcutLabelForCommand(keybindings, "terminal.toggle"), threadPanelOpen, threadPanelPresentation, threadPanelPopoverHandle, threadPanelShortcutLabel: shortcutLabelForCommand(keybindings, "threadPanel.toggle"), - rightPanelAvailable: activeProject !== null, - rightPanelOpen, - rightPanelShortcutLabel: shortcutLabelForCommand(keybindings, "rightPanel.toggle"), - onToggleTerminal: toggleTerminalVisibilityStable, onToggleThreadPanel: toggleThreadPanelStable, - onToggleRightPanel: toggleRightPanelStable, } satisfies PanelLayoutControlsProps; const panelToggleControls = ( ); - const threadPanelHeaderControl = ; + const threadPanelHeaderControl = ( + + + + ); const panelLayoutControls = ( - - + {panelToggleControls} - + ); const workspaceFileDropHandlers = makeWorkspaceFileDropHandlers({ setDragActive: setIsWorkspaceFileDragActive, @@ -3689,35 +3725,28 @@ export default function ChatView(props: ChatViewProps) { {rightPanelControlsAtRoot && !embedded ? panelLayoutControls : null}
{embedded ? null : ( -
{isElectron && rightPanelControlsAtRoot ? ( ) : null} {!rightPanelControlsAtRoot && !rightPanelControlsInPanel ? panelLayoutControls : null} @@ -3732,13 +3761,17 @@ export default function ChatView(props: ChatViewProps) { parentThreadLink={headerParentThreadLink} onOpenThread={onOpenRelatedThreadStable} rightPanelOpen={inlineRightPanelOwnsTitleBar} - onNewThreadInProject={handleNewThreadInActiveProjectStable} + trailingInset={ + !rightPanelControlsAtRoot && !rightPanelControlsInPanel ? headerControlsInset : null + } + hiddenTerminal={hiddenTerminalChip} + onNewSideChat={sideChat.available ? openNewSideChatStable : undefined} {...(activeDraftLogicalProjectKey ? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable } : {})} {...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})} /> -
+ )}
@@ -3763,14 +3796,20 @@ export default function ChatView(props: ChatViewProps) {
- {showScrollToBottom && !isThreadFindActive && ( - scrollToEnd(true)} - /> - )} + { + if (visiblePendingApprovalCount === 0 && childThreadApprovals.length > 0) { + const target = legendListRef.current + ?.getScrollableNode() + ?.querySelector("[data-approval-request-id]"); + if (target) { + target.scrollIntoView({ block: "center", behavior: "smooth" }); + return; + } + } + scrollToEnd(true); + }} + />
{/* Input bar — docked at the bottom; an empty draft centers its headline above it. */} @@ -3907,14 +3963,15 @@ export default function ChatView(props: ChatViewProps) { data-chat-composer-overlay="true" className={ isDraftHeroState - ? "pointer-events-none absolute inset-0 z-20 flex flex-col justify-end pt-1.5 sm:pt-2" + ? "pointer-events-none absolute inset-0 z-20 flex flex-col justify-end pt-1.5 [container:draft-hero/size] sm:pt-2" : "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2" } > {isDraftHeroState ? ( -
+ // A short split pane has no room above the composer. +
-
{hasThreadNow ? ( -
+
step.status !== "completed")) ? ( + shouldShowComposerTasks({ + steps: composerTasks.steps, + planRunSettled: isLatestRunSettled( + activeActivityRun ?? activeLatestRun, + activeRuntime, + ), + isSendBusy, + }) ? ( -
+
{showProviderSubagentBar ? (
- - {embedded ? 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} - onOpenInMainView={openSurfaceInMainView} - 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} - onDuplicateBrowser={duplicateBrowserSurfaceStable} - 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 && diffAvailable} - filesAvailable={activeProject !== null} - pullRequestAvailable={pullRequestSurfaceAvailable} - pullRequestsAvailable={linkedItemsSurfaceAvailable} - deviceAvailable={activeThreadRef !== null} - sideChatAvailable={sideChat.available} - sideChatDisabledReason={sideChatDisabledReason} - > - {rightPanelContent} - - ) : null} - } - {gitCwd && isGitRepo ? ( + {gitCwd && isGitRepo && !panelGitHostsShortcut ? ( [0]; + readonly handoffSelection: Parameters[1]; + readonly providerEnvironmentId: EnvironmentId; + readonly statusLine: ReactNode; + readonly guestThreadRef: ScopedThreadRef | null; + readonly onImageExpand: ComponentProps["onImageExpand"]; + readonly onFileOpen: ComponentProps["onFileOpen"]; +}) { + const providersByEnvironment = useEnvironmentProviders(); + const providers = providersByEnvironment.get(props.providerEnvironmentId) ?? EMPTY_PROVIDERS; + const pendingHandoff = resolvePendingHandoff(props.projection, props.handoffSelection, providers); + return ( + <> + {pendingHandoff === null ? null : ( +
+ +
+ )} + {props.statusLine} + {props.guestThreadRef === null ? null : ( + + )} + + ); +} + function PreviewSessionSync(props: { readonly threadRef: ScopedThreadRef }) { usePreviewSession(props.threadRef); return null; diff --git a/apps/web/src/components/CommandPalette.composition.browser.test.tsx b/apps/web/src/components/CommandPalette.composition.browser.test.tsx index be89854fb1d5e..6d95722e594e0 100644 --- a/apps/web/src/components/CommandPalette.composition.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.composition.browser.test.tsx @@ -54,7 +54,10 @@ vi.mock("../hooks/useSettings", async (original) => ({ useUpdateEnvironmentSettings: () => () => undefined, })); vi.mock("../hooks/useScratchProject", () => ({ - useScratchProject: () => ({ scratchEnvironmentId: () => null }), + useScratchProject: () => ({ + scratchEnvironmentId: () => null, + scratchUnavailableReason: () => null, + }), })); vi.mock("../hooks/useNewProject", () => ({ useNewProject: () => async () => undefined })); vi.mock("../hooks/useHandleNewThread", () => ({ diff --git a/apps/web/src/components/CommandPalette.drag.ts b/apps/web/src/components/CommandPalette.drag.ts index 090bab6efbd02..ee714cab4bc77 100644 --- a/apps/web/src/components/CommandPalette.drag.ts +++ b/apps/web/src/components/CommandPalette.drag.ts @@ -1,6 +1,7 @@ import type { ScopedThreadRef } from "@t3tools/contracts"; import { flushSync } from "react-dom"; import { dispatchCommandPalette } from "../commandPaletteStore"; +import { cancelLayoutDrag, dropLayoutDrag, moveLayoutDrag } from "../layout/layoutDrag"; import { SidebarPointerSensor } from "./Sidebar.pointer"; import { dropThreadContext, @@ -21,13 +22,19 @@ export function startPaletteThreadDrag( options: { distance: 6, onAttach: () => {}, - onFinish: endThreadContextDrag, - onDrop: (point) => dropThreadContext(point, [{ ...thread, title }]), + onFinish: () => { + endThreadContextDrag(); + cancelLayoutDrag(); + }, + onDrop: (point) => dropThreadContext(point, [{ ...thread, title }]) || dropLayoutDrag(), }, onStart: () => { flushSync(() => dispatchCommandPalette({ _tag: "SetOpen", open: false })); }, - onMove: (point) => moveThreadContextDrag(point, { title, count: 1 }), + onMove: (point) => + moveLayoutDrag({ kind: "thread", threadRef: thread }, point, { + composer: moveThreadContextDrag(point, { title, count: 1 }), + }), onPending: () => {}, onAbort: () => {}, onCancel: () => {}, diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index b788687397351..9d101e955e647 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -11,6 +11,8 @@ import { buildLinkedThreadActionItems, filterPinnedBrowseEntries, filterCommandPaletteGroups, + buildRootGroups, + RECENT_THREAD_LIMIT, reduceCommandPaletteUiState, resolveAddProjectEntry, createCommandPaletteSearchState, @@ -164,6 +166,47 @@ function makeThread(overrides: Partial = {}): Thread { } describe("buildThreadActionItems", () => { + it("keeps main's empty-query actions and twelve recent threads in order", () => { + const items = buildThreadActionItems({ + threads: Array.from({ length: 13 }, (_, index) => + makeThread({ + id: ThreadId.make(`daily-${index}`), + title: "Daily T3 Code trace hotspot check", + latestUserMessageAt: `2026-03-${String(index + 1).padStart(2, "0")}T00:00:00.000Z`, + }), + ), + projectByKey: new Map(), + icon: null, + runThread: async () => undefined, + }); + const action = { ...items[0]!, value: "action:settings", title: "Open settings" }; + const groups = filterCommandPaletteGroups({ + activeGroups: buildRootGroups({ + actionItems: [action], + recentThreadItems: items.slice(0, RECENT_THREAD_LIMIT), + }), + query: "", + isInSubmenu: false, + projectSearchItems: [], + threadSearchItems: items, + }); + expect(groups.flatMap((group) => group.items.map((item) => item.value))).toEqual([ + action.value, + ...items.slice(0, 12).map((item) => item.value), + ]); + const matches = filterCommandPaletteGroups({ + activeGroups: [], + query: "dail", + isInSubmenu: false, + projectSearchItems: [], + threadSearchItems: items, + now: Date.parse("2026-03-14T00:00:00.000Z"), + }); + expect(matches.flatMap((group) => group.items.map((item) => item.value))).toEqual( + items.toReversed().map((item) => item.value), + ); + }); + it("keeps threads apart when two environments share a thread ID", async () => { const local = makeThread(); const remote = makeThread({ environmentId: EnvironmentId.make("remote-copy") }); diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 700ef91673389..c8cd2f59567cd 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -39,7 +39,7 @@ import { formatRelativeTimeLabel } from "../timestampFormat"; import { type Project, type SidebarThreadSummary, type Thread } from "../types"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -export const RECENT_THREAD_LIMIT = 3; +export const RECENT_THREAD_LIMIT = 12; const NO_THREAD_KEYS: ReadonlySet = new Set(); export const ITEM_ICON_CLASS = "size-3.5 text-icon-muted"; export const ADDON_ICON_CLASS = "size-4"; @@ -635,19 +635,16 @@ export function filterCommandPaletteGroups( const searchQuery = isActionsFilter ? input.query.slice(1) : input.query; const normalizedQuery = foldSearchQuery(searchQuery); - const isActionGroup = (group: CommandPaletteGroup) => - group.value === "actions" || group.value === "settings"; - if (normalizedQuery.length === 0) { if (isActionsFilter) { - return input.activeGroups.filter(isActionGroup); + return input.activeGroups.filter((group) => group.value === "actions"); } return [...input.activeGroups]; } let baseGroups = [...input.activeGroups]; if (isActionsFilter) { - baseGroups = baseGroups.filter(isActionGroup); + baseGroups = baseGroups.filter((group) => group.value === "actions"); } else if (!input.isInSubmenu) { baseGroups = baseGroups.filter((group) => group.value !== "recent-threads"); } @@ -679,21 +676,11 @@ export function filterCommandPaletteGroups( }); } if (input.settingsSearchItems && input.settingsSearchItems.length > 0) { - // Settings matches join the root Settings actions so the list shows one Settings group. - const settingsIndex = searchableGroups.findIndex((group) => group.value === "settings"); - const settingsGroup = searchableGroups[settingsIndex]; - if (settingsGroup) { - searchableGroups[settingsIndex] = { - ...settingsGroup, - items: [...settingsGroup.items, ...input.settingsSearchItems], - }; - } else { - searchableGroups.push({ - value: "settings-search", - label: resolve(msg("Settings")), - items: input.settingsSearchItems, - }); - } + searchableGroups.push({ + value: "settings-search", + label: resolve(msg("Settings")), + items: input.settingsSearchItems, + }); } } @@ -851,11 +838,13 @@ export function buildRootGroups( input: { actionItems: ReadonlyArray; recentThreadItems: ReadonlyArray; - settingsItems?: ReadonlyArray; }, resolve: MessageResolver = m, ): CommandPaletteGroup[] { const groups: CommandPaletteGroup[] = []; + if (input.actionItems.length > 0) { + groups.push({ value: "actions", label: resolve(msg("Actions")), items: input.actionItems }); + } if (input.recentThreadItems.length > 0) { groups.push({ value: "recent-threads", @@ -863,12 +852,6 @@ export function buildRootGroups( items: input.recentThreadItems, }); } - if (input.actionItems.length > 0) { - groups.push({ value: "actions", label: resolve(msg("Actions")), items: input.actionItems }); - } - if (input.settingsItems && input.settingsItems.length > 0) { - groups.push({ value: "settings", label: resolve(msg("Settings")), items: input.settingsItems }); - } return groups; } diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index e1c6f0992d4ba..ff8eb6a0dbc59 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -77,6 +77,8 @@ import { RotateCcwIcon, SettingsIcon, MonitorIcon, + SquareSplitHorizontalIcon, + SquareSplitVerticalIcon, PinIcon, PinOffIcon, PlugIcon, @@ -116,7 +118,7 @@ import { copyPromptLink, promptLinkRepositoryOf, } from "./promptLinks/copyPromptLink"; -import { useClientSettings } from "../hooks/useSettings"; +import { useClientSettings, useScrollingWorkspacesEnabled } from "../hooks/useSettings"; import { useStableCallback } from "../hooks/useStableCallback"; import { readLocalApi } from "../localApi"; import { configuredHostedAppUrl } from "../hostedPairing"; @@ -175,6 +177,7 @@ import { resolvePastedPath } from "@t3tools/shared/path"; import { dispatchCommandPalette, getCommandPaletteReturnFocus, + commandPaletteFocus, useCommandPaletteMount, useCommandPaletteStore, } from "../commandPaletteStore"; @@ -237,6 +240,12 @@ import { } from "./CommandPalette.logic"; import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic"; import { CommandPaletteContent, type PendingInputSelection } from "./CommandPaletteContent"; +import { buildLayoutPaletteItems, buildOpenBesidePaletteItem } from "../layout/layoutPaletteItems"; +import { + findTerminalSplitTarget, + queueTerminalFocusFromPalette, + restoreTerminalFocusFromPalette, +} from "../lib/terminalFocus"; import { selectCommandPaletteClientSettings, useEnvironmentLookups, @@ -282,6 +291,8 @@ import { stackedThreadToast, toastManager } from "./ui/toast"; import { suggestAppAccessForRemote } from "./sourceControlAppAccessToast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext"; +import { returnKeyboardToFocusedPane } from "../layout/layoutPaneContext"; +import { useOpenLayoutPage } from "../layout/pageNavigation"; import type { ChatComposerHandle } from "./chat/ChatComposer"; import { isPickableProjectMember, @@ -289,20 +300,9 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { buildSidebarProjectPickerEntries } from "../sidebarProjectGrouping"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; -import { readIssueListPreferences } from "~/components/issue/issueListPreferences"; import { IssueGlyph } from "~/components/issue/issuePresentation"; -import { readPullRequestListPreferences } from "~/components/pullRequest/pullRequestListPreferences"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; -// Root actions listed under Settings, after Actions. -const SETTINGS_ACTION_VALUES: ReadonlySet = new Set([ - "action:change-theme", - "action:change-appearance", - "action:theme-editor", - "action:settings", - "action:project-settings", -]); - const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = []; const ADD_PROJECT_ENTRY_GROUP = "add-project"; const NEW_THREAD_IN_GROUP = "projects"; @@ -344,6 +344,14 @@ export function CommandPalette({ children }: { children: ReactNode }) { const openChildSearch = (mode: "files" | "content", context: CommandPaletteReturnContext) => dispatchCommandPalette({ _tag: "OpenChildSearch", mode, context }); const composerHandleRef = useRef(null); + const dismiss = () => { + setOpen(false); + commandPaletteFocus.dismissedRef.current = true; + }; + const leaveOverlay = () => { + if (state.parentSearch) dispatchCommandPalette({ _tag: "BackToCommand" }); + else dismiss(); + }; return ( @@ -353,10 +361,11 @@ export function CommandPalette({ children }: { children: ReactNode }) { onOpenChange={(open, eventDetails) => { if (!open && eventDetails.reason === "escape-key" && state.mode !== "command") { eventDetails.cancel(); - dispatchCommandPalette({ _tag: "BackToCommand" }); + leaveOverlay(); return; } - setOpen(open); + if (open) setOpen(true); + else dismiss(); }} >
@@ -366,6 +375,7 @@ export function CommandPalette({ children }: { children: ReactNode }) { mode={state.mode} session={state.session} openIntent={state.openIntent} + dismiss={dismiss} setOpen={setOpen} openChildSearch={openChildSearch} initialContext={state.restoredSearch} @@ -384,6 +394,7 @@ function CommandPaletteDialog(props: { readonly mode: SearchOverlayMode; readonly session: number; readonly openIntent: CommandPaletteOpenIntent | null; + readonly dismiss: () => void; readonly setOpen: (open: boolean) => void; readonly openChildSearch: ( mode: "files" | "content", @@ -412,18 +423,29 @@ function CommandPaletteDialog(props: { data-testid="command-palette" // Focus goes to the composer, or back to what opened the palette (Settings' Add project) when there is none. finalFocus={() => { - if (restoreWorkspaceFocusFromPalette()) return false; + if (restoreWorkspaceFocusFromPalette() || restoreTerminalFocusFromPalette()) return false; const returnFocus = getCommandPaletteReturnFocus(); if (returnFocus === false) return false; + const opener = commandPaletteFocus.openerRef.current; + // Dismissed, it gives the keyboard back to an opener outside the panes (the sidebar). + if ( + commandPaletteFocus.dismissedRef.current && + opener?.isConnected && + !opener.closest("[data-layout-strip]") + ) { + return opener; + } + // In the layout the keyboard goes back to the focused pane, which an + // action may have changed (a surface opened beside the chat). + if (returnKeyboardToFocusedPane()) return false; const composer = composerHandleRef?.current; - // Behind the Settings modal the composer is inert and cannot take focus. - if (!composer || document.querySelector("[data-app-modal]")) return returnFocus; - composer.focusAtEnd(); - return false; - }} - onBackdropPointerDown={() => { - props.setOpen(false); + if (composer && !document.querySelector("[data-app-modal]")) { + composer.focusAtEnd(); + return false; + } + return returnFocus; }} + onBackdropPointerDown={props.dismiss} > {props.mode === "files" ? ( @@ -454,9 +476,11 @@ function OpenCommandPaletteDialog(props: { ) => void; readonly initialContext: CommandPaletteReturnContext | undefined; }) { + const composerHandleRef = useComposerHandleContext(); const gt = useGT(); const messages = useMessages(); const navigate = useNavigate(); + const openLayoutPage = useOpenLayoutPage(); const pathname = useLocation({ select: (location) => location.pathname }); const { openChildSearch, setOpen } = props; // Keyed by palette session: the intent and restored search only seed this @@ -485,6 +509,7 @@ function OpenCommandPaletteDialog(props: { const deferredQuery = useDeferredValue(query); const isActionsOnly = deferredQuery.startsWith(">"); const [highlightedItemValue, setHighlightedItemValue] = useState(null); + const [opener] = useState(() => commandPaletteFocus.openerRef.current); const resultListRef = useRef(null); // A pushed view drops the typed highlight until the user moves it again. const highlightClearedRef = useRef(viewStack.length > 0); @@ -495,13 +520,19 @@ function OpenCommandPaletteDialog(props: { setHighlightedItemValue(null); } const clientSettings = useClientSettings(selectCommandPaletteClientSettings); + const scrollingWorkspaces = useScrollingWorkspacesEnabled(); const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false, }); const updateProject = useOrchestrationCommand(projectEnvironment.update, { label: "project unarchive", }); - const { scratchEnvironmentId, scratchWorkspaceRootFor, startScratchThread } = useScratchProject(); + const { + scratchEnvironmentId, + scratchWorkspaceRootFor, + scratchUnavailableReason, + startScratchThread, + } = useScratchProject(); const startTriage = useStartTriage(); const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, { reportFailure: false, @@ -574,7 +605,8 @@ function OpenCommandPaletteDialog(props: { ); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const providersByEnvironment = useEnvironmentProviders(); - const { changeThemeItem, changeAppearanceItem, themeEditorItem } = useCommandPaletteThemeItems(); + const { changeThemeItem, changeAppearanceItem, changeAppIconItem, themeEditorItem } = + useCommandPaletteThemeItems(); const portForwardItem = useCommandPalettePortForwardItem({ activeThread: activeThread ?? null, query: deferredQuery, @@ -772,6 +804,10 @@ function OpenCommandPaletteDialog(props: { const canTriage = useAtomValue(serverEnvironment.prepareTriage.permissionAtom(triageEnvironmentId)) && supportsTriage(triageEnvironmentId); + const scratchOffReason = scratchUnavailableReason( + currentProjectEnvironmentId ?? primaryEnvironmentId, + messages, + ); const currentProject = resolveCommandPaletteProject( projectByKey, currentProjectEnvironmentId, @@ -947,7 +983,30 @@ function OpenCommandPaletteDialog(props: { ); }, }); - if (scratchTargetEnvironmentId === null) return projectItems; + const noProjectItem = + scratchTargetEnvironmentId !== null + ? { + kind: "action" as const, + value: NEW_THREAD_NO_PROJECT_VALUE, + searchTerms: ["no project", "without project", "none"], + title: gt("No project"), + icon: , + shortcutCommand: "chat.newWithoutProject" as const, + run: () => startScratchThread(scratchTargetEnvironmentId), + } + : scratchOffReason !== null + ? { + kind: "action" as const, + value: NEW_THREAD_NO_PROJECT_VALUE, + searchTerms: ["no project", "without project", "none"], + title: gt("No project"), + description: scratchOffReason, + disabled: true, + icon: , + run: async () => {}, + } + : null; + if (noProjectItem === null) return projectItems; const noProjectIndex = newThreadNoProjectIndex( projectPickerEntries.map(({ group, targetProject, isPreferred }) => ({ @@ -961,15 +1020,7 @@ function OpenCommandPaletteDialog(props: { ); return [ ...projectItems.slice(0, noProjectIndex), - { - kind: "action" as const, - value: NEW_THREAD_NO_PROJECT_VALUE, - searchTerms: ["no project", "without project", "none"], - title: gt("No project"), - icon: , - shortcutCommand: "chat.newWithoutProject" as const, - run: () => startScratchThread(scratchTargetEnvironmentId), - }, + noProjectItem, ...projectItems.slice(noProjectIndex), ]; })(), @@ -986,6 +1037,28 @@ function OpenCommandPaletteDialog(props: { (item) => projectJumpItems.get(item.value) ?? item, ); + const submenuGroups = + currentView?.groups[0]?.value === NEW_THREAD_IN_GROUP + ? [{ value: NEW_THREAD_IN_GROUP, label: gt("Projects"), items: projectThreadItems }] + : currentView?.groups[0]?.value === "themes" + ? changeThemeItem.groups + : currentView?.groups[0]?.value === "appearance" + ? changeAppearanceItem.groups + : currentView?.groups; + const searchesAllThreads = + deferredQuery.trim().length > 0 && + !isActionsOnly && + (currentView?.groups[0]?.value === ADD_PROJECT_ENTRY_GROUP || + currentView?.groups[0]?.value === `sources:${addProjectEnvironmentId}` || + submenuGroups === undefined || + filterCommandPaletteGroups({ + activeGroups: submenuGroups, + query: deferredQuery, + isInSubmenu: true, + projectSearchItems: [], + threadSearchItems: [], + }).length === 0); + const { threadItems: allThreadItems, recentThreadItems, @@ -993,7 +1066,11 @@ function OpenCommandPaletteDialog(props: { now: searchNow, isSearchPending: isThreadSearchPending, isSearchFailed: isThreadSearchFailed, - } = useCommandPaletteThreadItems({ activeThread: activeThread ?? null, threadSearchQuery }); + } = useCommandPaletteThreadItems({ + activeThread: activeThread ?? null, + threadSearchQuery, + includeAllThreads: searchesAllThreads, + }); const pushPaletteView = useStableCallback((view: CommandPaletteView): void => { browseNavigation.invalidate(); dispatchSearch({ type: "push", view }); @@ -1099,7 +1176,7 @@ function OpenCommandPaletteDialog(props: { const openSourceControlSettings = () => { setOpen(false); - void navigate({ to: "/settings/source-control" }); + void navigate({ to: "/settings/source-control", search: { pane: undefined } }); }; const buildAddProjectSourceGroups = ( @@ -1281,7 +1358,7 @@ function OpenCommandPaletteDialog(props: { const openConnectionSettings = () => { setOpen(false); - void navigate({ to: "/settings/connections" }); + void navigate({ to: "/settings/connections", search: { pane: undefined } }); }; const addProjectEntry = resolveAddProjectEntry( addProjectEnvironmentOptions, @@ -1350,8 +1427,23 @@ function OpenCommandPaletteDialog(props: { if (firstOption) startNewProject(firstOption.environmentId, null); }; + const chooseWorkspace = useStableCallback(async () => { + composerHandleRef?.current?.openControl("composer.workspace"); + }); const actionItems: Array = []; + if (activeThread || activeDraftThread) { + actionItems.push({ + kind: "action", + value: "action:choose-workspace", + title: gt("Choose workspace"), + searchTerms: ["branch", "worktree", "checkout", "workspace"], + icon: , + shortcutCommand: "composer.workspace", + run: chooseWorkspace, + }); + } + if (projects.length > 0) { const activeProjectTitle = projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ?? @@ -1406,6 +1498,17 @@ function OpenCommandPaletteDialog(props: { shortcutCommand: "chat.newWithoutProject", run: () => startScratchThread(scratchTargetEnvironmentId), }); + } else if (scratchOffReason !== null) { + actionItems.push({ + kind: "action", + value: "action:new-thread-without-project", + searchTerms: ["new thread", "no project", "without project", "none", "chat"], + title: gt("New thread without a project"), + description: scratchOffReason, + disabled: true, + icon: , + run: async () => {}, + }); } if (triageEnvironmentId !== null && canTriage) { @@ -1600,6 +1703,52 @@ function OpenCommandPaletteDialog(props: { }); } + // What the terminal's split keys act on, from where focus was when the palette opened. + const terminalSplitTarget = findTerminalSplitTarget( + opener, + previewPanelThreadRef ? scopedThreadKey(previewPanelThreadRef) : null, + ); + if (terminalSplitTarget !== null) { + const target = terminalSplitTarget; + actionItems.push( + { + kind: "action", + value: "action:terminal-split", + searchTerms: ["split terminal", "terminal", "split", "horizontal"], + title: gt("Split terminal"), + icon: , + shortcutCommand: "terminal.split", + disabled: !target.canSplit(), + run: async () => { + target.split("horizontal"); + queueTerminalFocusFromPalette(target.focusActive); + }, + }, + { + kind: "action", + value: "action:terminal-split-vertical", + searchTerms: ["split terminal vertically", "terminal", "split", "vertical"], + title: gt("Split terminal vertically"), + icon: , + shortcutCommand: "terminal.splitVertical", + disabled: !target.canSplit(), + run: async () => { + target.split("vertical"); + queueTerminalFocusFromPalette(target.focusActive); + }, + }, + ); + } + + // The side pane's tabs and the terminal, beside the focused chat. + const openBesideItem = + activeThread || activeDraftThread ? buildOpenBesidePaletteItem(messages) : null; + if (openBesideItem) actionItems.push(openBesideItem); + // The index shows the layout too once there is a project. + if (activeThread || activeDraftThread || (pathname === "/" && projects.length > 0)) { + actionItems.push(...buildLayoutPaletteItems(scrollingWorkspaces, messages)); + } + actionItems.push({ kind: "action", value: "action:open-file-picker", @@ -1688,6 +1837,7 @@ function OpenCommandPaletteDialog(props: { actionItems.push(changeThemeItem); actionItems.push(changeAppearanceItem); + actionItems.push(changeAppIconItem); actionItems.push(themeEditorItem); @@ -1714,7 +1864,7 @@ function OpenCommandPaletteDialog(props: { title: gt("Open pull requests"), icon: , run: async () => { - await navigate({ to: "/pull-requests", search: readPullRequestListPreferences() }); + await openLayoutPage("pull-requests"); }, }); } @@ -1731,7 +1881,7 @@ function OpenCommandPaletteDialog(props: { title: gt("Open issues"), icon: , run: async () => { - await navigate({ to: "/issues", search: readIssueListPreferences() }); + await openLayoutPage("issues"); }, }); } @@ -1772,7 +1922,7 @@ function OpenCommandPaletteDialog(props: { title: gt("Open workflows"), icon: , run: async () => { - await navigate({ to: "/workflows" }); + await openLayoutPage("workflows"); }, }); } @@ -1812,7 +1962,7 @@ function OpenCommandPaletteDialog(props: { title: gt("Open settings"), icon: , run: async () => { - await navigate({ to: "/settings" }); + await navigate({ to: "/settings", search: { pane: undefined } }); }, }); @@ -1886,14 +2036,7 @@ function OpenCommandPaletteDialog(props: { }); } - const rootGroups = buildRootGroups( - { - actionItems: actionItems.filter((item) => !SETTINGS_ACTION_VALUES.has(item.value)), - recentThreadItems, - settingsItems: actionItems.filter((item) => SETTINGS_ACTION_VALUES.has(item.value)), - }, - messages, - ); + const rootGroups = buildRootGroups({ actionItems, recentThreadItems }, messages); // Settings use the same matcher as threads, including word starts and typo tolerance. const settingsSearchItems: CommandPaletteActionItem[] = settingsForThisPlatform( availableSettingsSearchItems, @@ -1913,6 +2056,7 @@ function OpenCommandPaletteDialog(props: { run: async () => { await navigate({ to: item.to, + search: { pane: undefined }, hash: item.targetId ?? item.id, replace: pathname === item.to, hashScrollIntoView: false, @@ -1946,7 +2090,9 @@ function OpenCommandPaletteDialog(props: { ? changeThemeItem.groups : currentView?.groups[0]?.value === "appearance" ? changeAppearanceItem.groups - : (currentView?.groups ?? rootGroups); + : currentView?.groups[0]?.value === "app-icons" + ? changeAppIconItem.groups + : (currentView?.groups ?? rootGroups); const isLinkedThreadSearch = linkedThreadSearch?.linkedThreads !== undefined && deferredQuery === linkedThreadSearch.query; @@ -3142,14 +3288,9 @@ function OpenCommandPaletteDialog(props: { ...(isSubmenu ? { startAddon: ( - + ), } : isBrowsing diff --git a/apps/web/src/components/CommandPaletteAddProject.tsx b/apps/web/src/components/CommandPaletteAddProject.tsx index 04cc73696a587..01e99732ddab2 100644 --- a/apps/web/src/components/CommandPaletteAddProject.tsx +++ b/apps/web/src/components/CommandPaletteAddProject.tsx @@ -111,7 +111,7 @@ export function NewProjectPublishHostPicker(props: { {props.targets.map((target) => ( - + {sourceControlHostIcon(target.definition, "size-3.5")} {target.definition.label} diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsx index 4bb48d0329c55..71ccd9edd87f5 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -206,7 +206,7 @@ function ThreadRowContext({ render={ } > @@ -260,7 +260,12 @@ function CommandPaletteRowContent({ item }: { item: CommandPaletteResultItem }) ) : item.matchHint ? ( ) : item.description ? ( - + {item.description} ) : null} @@ -288,8 +293,12 @@ function CommandPaletteResultRow(props: { keybindings: ResolvedKeybindingsConfig; onExecuteItem: (item: CommandPaletteResultItem) => void; }) { + // Terminal-only keys (splits) have no binding outside a terminal; show the terminal's. const shortcutLabel = props.item.shortcutCommand - ? shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand) + ? (shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand) ?? + shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand, { + context: { terminalFocus: true }, + })) : null; return ( diff --git a/apps/web/src/components/CommandPaletteThemeItems.tsx b/apps/web/src/components/CommandPaletteThemeItems.tsx index 9ec00de119ba6..b88ca4a0111db 100644 --- a/apps/web/src/components/CommandPaletteThemeItems.tsx +++ b/apps/web/src/components/CommandPaletteThemeItems.tsx @@ -2,9 +2,11 @@ import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes"; import { msg, T, useGT, useMessages } from "gt-react"; import { AppWindowIcon, MonitorIcon, MoonIcon, PaletteIcon, SunIcon } from "lucide-react"; +import { APP_ICON_OPTIONS, appIconOption } from "../appIcon"; import { m } from "../i18n/messages"; import { useCustomThemes } from "../hooks/useCustomThemes"; import { useEnvironmentThemeDefinitions } from "../hooks/useEnvironmentTheme"; +import { updateClientSettings, useClientSettings } from "../hooks/useSettings"; import { APPEARANCE_CHOICES, useTheme, type AppearanceChoice } from "../hooks/useTheme"; import { getThemeDefinition } from "../themePalette"; import { @@ -70,6 +72,7 @@ export function useCommandPaletteThemeItems() { const themeCards = useThemeCards(); const gt = useGT(); const messages = useMessages(); + const currentAppIcon = appIconOption(useClientSettings((settings) => settings.appIcon)); const changeThemeItem: CommandPaletteSubmenuItem = { kind: "submenu", @@ -177,5 +180,34 @@ export function useCommandPaletteThemeItems() { }, }; - return { changeThemeItem, changeAppearanceItem, themeEditorItem }; + const changeAppIconItem: CommandPaletteSubmenuItem = { + kind: "submenu", + value: "action:change-app-icon", + searchTerms: ["change app icon", "dock", "taskbar", "favicon", "logo", "nightly"], + title: gt("Change app icon"), + icon: , + addonIcon: , + groups: [ + { + value: "app-icons", + label: gt("Change app icon"), + items: APP_ICON_OPTIONS.map((option) => ({ + kind: "action", + value: `app-icon:${option.id}`, + title: messages(option.label), + searchTerms: [messages(option.label), option.label, "app icon"], + icon: , + titleTrailingContent: + currentAppIcon.id === option.id ? ( + + Current + + ) : undefined, + run: () => updateClientSettings({ appIcon: option.id }), + })), + }, + ], + }; + + return { changeThemeItem, changeAppearanceItem, changeAppIconItem, themeEditorItem }; } diff --git a/apps/web/src/components/CommandPaletteThreadItems.tsx b/apps/web/src/components/CommandPaletteThreadItems.tsx index cfc62335d0100..4513a9a4e78b5 100644 --- a/apps/web/src/components/CommandPaletteThreadItems.tsx +++ b/apps/web/src/components/CommandPaletteThreadItems.tsx @@ -1,8 +1,10 @@ import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore"; import { claimThreadOpen, nextShownOrder, + threadSearchSubject, type EnvironmentThreadSearchMatch, type ShownOrder, } from "@t3tools/client-runtime/state/thread-search"; @@ -98,6 +100,37 @@ function useConnectedThreadSearch(query: string) { ); } +function useRecentThreads( + activeThread: { readonly environmentId: EnvironmentId; readonly id: ThreadId } | null, + delegatedUnderParent: ReadonlySet, +) { + const threads = useVisibleThreadShells(); + const { projectByKey } = useProjectLookups(); + return threads + .filter( + (thread) => + thread.archivedAt === null && + !isShownUnderParent( + { environmentId: thread.environmentId, threadId: thread.id }, + thread.lineage, + delegatedUnderParent, + ) && + !(thread.id === activeThread?.id && thread.environmentId === activeThread.environmentId), + ) + .map((thread) => ({ + thread, + usedAt: threadRecentUse( + threadSearchSubject( + thread, + projectByKey.get(`${thread.environmentId}:${thread.projectId}`)?.title, + ), + ), + })) + .toSorted((left, right) => right.usedAt - left.usedAt) + .slice(0, RECENT_THREAD_LIMIT) + .map(({ thread }) => thread); +} + /** * Every visible thread as a palette item, plus, for a non-empty * `threadSearchQuery`, the threads whose messages match, best first. @@ -105,13 +138,15 @@ function useConnectedThreadSearch(query: string) { export function useCommandPaletteThreadItems(input: { readonly activeThread: { readonly environmentId: EnvironmentId; readonly id: ThreadId } | null; readonly threadSearchQuery: string; + readonly includeAllThreads: boolean; }) { - const { activeThread, threadSearchQuery } = input; + const { activeThread, threadSearchQuery, includeAllThreads } = input; const messages = useMessages(); const gt = useGT(); const navigate = useNavigate(); const threads = useVisibleThreadShells(); const delegatedUnderParent = useDelegatedUnderParent(); + const recentThreads = useRecentThreads(activeThread, delegatedUnderParent); const { projectEnvironmentLocationById } = useEnvironmentLookups(); const providerEntryByEnvironmentAndInstanceId = useProviderEntryByEnvironmentAndInstanceId(); const messageSearch = useConnectedThreadSearch(threadSearchQuery); @@ -121,11 +156,11 @@ export function useCommandPaletteThreadItems(input: { const [now] = useState(() => Date.now()); const nowMinute = useNowMinute(); - const nowMs = Date.parse(`${nowMinute}:00.000Z`); const { environments } = useEnvironments(); + const nowMs = Date.parse(`${nowMinute}:00.000Z`); const threadItems = buildThreadActionItems( { - threads, + threads: includeAllThreads ? threads : recentThreads, delegatedUnderParent, ...(environments.length > 1 ? { @@ -264,56 +299,41 @@ export function useCommandPaletteThreadItems(input: { .flatMap((value) => messageItemByValue.get(value) ?? []); // Recent threads stay on one line: provider logo, title, then the dim branch. - const recentThreadItems = (() => { - const threadByValue = new Map( - threads.map((thread) => [`thread:${thread.environmentId}:${thread.id}`, thread]), - ); - const activeThreadValue = activeThread - ? `thread:${activeThread.environmentId}:${activeThread.id}` - : null; - return threadItems - .filter((item) => item.value !== activeThreadValue) - .toSorted( - (left, right) => - (right.threadSearch ? threadRecentUse(right.threadSearch) : 0) - - (left.threadSearch ? threadRecentUse(left.threadSearch) : 0), - ) - .slice(0, RECENT_THREAD_LIMIT) - .map(({ description: _description, ...item }): CommandPaletteActionItem => { - const thread = threadByValue.get(item.value); - if (!thread) return item; - const modelInstanceId = - thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; - const providerEntry = - providerEntryByEnvironmentAndInstanceId.get( - `${thread.environmentId}:${modelInstanceId}`, - ) ?? null; - return { - ...item, - icon: providerEntry ? ( - - ) : ( - item.icon - ), - title: ( - <> - {thread.title} - {thread.branch ? ( - - {thread.branch} - - ) : null} - - ), - }; - }); - })(); + const recentThreadItems = recentThreads.flatMap((thread): CommandPaletteActionItem[] => { + const original = itemByValue.get(`thread:${thread.environmentId}:${thread.id}`); + if (!original) return []; + const { description: _description, ...item } = original; + const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; + const providerEntry = + providerEntryByEnvironmentAndInstanceId.get(`${thread.environmentId}:${modelInstanceId}`) ?? + null; + return [ + { + ...item, + icon: providerEntry ? ( + + ) : ( + item.icon + ), + title: ( + <> + {thread.title} + {thread.branch ? ( + + {thread.branch} + + ) : null} + + ), + }, + ]; + }); return { threadItems, diff --git a/apps/web/src/components/ComposerContextLabel.tsx b/apps/web/src/components/ComposerContextLabel.tsx index 0dbcb574a6e11..d3ab5ee79df37 100644 --- a/apps/web/src/components/ComposerContextLabel.tsx +++ b/apps/web/src/components/ComposerContextLabel.tsx @@ -22,8 +22,8 @@ export function ComposerContextLabel({ displayMode === "panel" ? "flex-1 overflow-x-clip overflow-y-visible text-left" : compactable - ? "max-w-[240px] group-data-[compact]/composer-context:max-w-0" - : "max-w-[240px] group-data-[compact=branch]/composer-context:max-w-24", + ? "max-w-[240px] transition-[margin-inline-start] duration-180 ease-drawer group-data-[compact]/composer-context:-ms-1.5 group-data-[compact]/composer-context:max-w-0 motion-reduce:transition-none" + : "group-data-[compact=branch]/composer-context:max-w-24", )} > false, importContextFragment, literalText = false, - disabled = false, placeholder = "", + disabled = false, placeholderSuffix, }: { value: string; + placeholder?: string; richTextEnabled: boolean; skills: ReadonlyArray; onChange?: ComposerPromptEditorProps["onChange"] | undefined; @@ -79,7 +82,6 @@ function Composer({ importContextFragment?: ComposerPromptEditorProps["importContextFragment"]; literalText?: boolean; disabled?: boolean; - placeholder?: string; placeholderSuffix?: ComposerPromptEditorProps["placeholderSuffix"]; }) { const [prompt, setPrompt] = useState({ value, cursor: value.length }); @@ -419,6 +421,27 @@ it.each([false, true])( }, ); +it("draws typed text on the placeholder's pixels", async () => { + const text = "Run the tests again"; + await using screen = await render( + , + ); + const textRect = (root: Element | null) => { + const node = root && document.createTreeWalker(root, NodeFilter.SHOW_TEXT).nextNode(); + if (!node) throw new Error("Text is missing"); + const range = document.createRange(); + range.selectNodeContents(node); + const { x, y, width, height } = range.getBoundingClientRect(); + return { x, y, width, height }; + }; + const shown = textRect(screen.container.querySelector("[data-composer-placeholder]")); + const editor = editorIn(screen.container); + await act(async () => { + editor.commands.insertContent(text); + }); + expect(textRect(editor.view.dom.querySelector("p"))).toEqual(shown); +}); + it("lets composition replace selected text without surrounding it", async () => { await using screen = await mountEditor("word"); const { editor } = screen; diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 3d8a127a787aa..133ba47a1ba80 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -268,6 +268,9 @@ function resolvedThemeFromDocument(): "light" | "dark" { return document.documentElement.classList.contains("dark") ? "dark" : "light"; } +// The editor and its placeholder share one text box, so accepted text lands on the placeholder's pixels. +const COMPOSER_TEXT_CLASS_NAME = "composer-text -m-1 p-1"; + const CHIP_NODE_SELECTION_CLASS_NAME = "relative inline-flex min-w-0 max-w-full select-none items-baseline data-[composer-chip-selected]:after:pointer-events-none data-[composer-chip-selected]:after:absolute data-[composer-chip-selected]:after:inset-0 data-[composer-chip-selected]:after:rounded-sm data-[composer-chip-selected]:after:bg-[Highlight] data-[composer-chip-selected]:after:opacity-30 data-[composer-chip-selected]:after:content-['']"; @@ -1138,7 +1141,8 @@ function ComposerPromptEditorTiptapInner( const editorAttributes = { class: cn( - "composer-tiptap -m-1 block max-h-42 min-h-5 overflow-y-auto p-1 whitespace-pre-wrap wrap-break-word bg-transparent leading-5 text-foreground focus:outline-none", + "composer-tiptap block max-h-42 min-h-5 overflow-y-auto bg-transparent text-foreground focus:outline-none", + COMPOSER_TEXT_CLASS_NAME, className, ), "data-testid": "composer-editor", @@ -1607,7 +1611,7 @@ function ComposerPromptEditorTiptapInner( // Push attributes before layout measurements; Tiptap updates them later in a passive effect. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes DOM attributes into the ProseMirror view before layout measurements read them useLayoutEffect(() => { - if (!editor?.isInitialized) return; + if (!editor?.isInitialized || editor.isDestroyed) return; editor.view.setProps({ attributes: editorAttributes }); }, [editor, editorAttributes]); @@ -1669,7 +1673,7 @@ function ComposerPromptEditorTiptapInner( // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reconciles the controlled Tiptap document before paint, outside React's commit useLayoutEffect(() => { latestValueRef.current = value; - if (!editor) return; + if (!editor || editor.isDestroyed) return; // Tiptap mounts React node views with flushSync; leave React's commit before updating them. let active = true; const applyControlledUpdate = () => { @@ -1781,20 +1785,46 @@ function ComposerPromptEditorTiptapInner( // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the mounted editor's visible text anchored while its DOM width changes useLayoutEffect(() => { - if (editor) return preserveReadingPosition(editor.view.dom); + if (!editor || editor.isDestroyed) return; + let stop: (() => void) | undefined; + const detach = () => { + stop?.(); + stop = undefined; + }; + const attach = () => { + detach(); + if (editor.isDestroyed) return; + // An reappear can fire layout effects before EditorContent mounts the ProseMirror view. + let dom: HTMLElement; + try { + dom = editor.view.dom; + } catch { + return; + } + stop = preserveReadingPosition(dom); + }; + attach(); + editor.on("mount", attach); + editor.on("unmount", detach); + return () => { + editor.off("mount", attach); + editor.off("unmount", detach); + detach(); + }; }, [editor]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown useLayoutEffect(() => { if (!editor) return; - if (restoreFocusRef.current) { + if (restoreFocusRef.current && !editor.isDestroyed) { restoreFocusRef.current = false; editor.view.focus(); scrollTiptapCaretIntoView(editor); } return () => { - // Capture focus before the keyed editor's DOM is removed. - restoreFocusRef.current = editor.view.hasFocus(); + // Capture focus before the keyed editor's DOM is removed. A pane move can unmount + // the view first; reading it then throws. + restoreFocusRef.current = !editor.isDestroyed && editor.view.hasFocus(); }; }, [editor, restoreFocusRef]); @@ -1945,14 +1975,15 @@ function ComposerPromptEditorTiptapInner(
{ if ( event.key === "Control" || @@ -1998,21 +2029,32 @@ function ComposerPromptEditorTiptapInner(
- {narrowPlaceholder ? ( - <> - {placeholder} - - {narrowPlaceholder} +
+ {narrowPlaceholder ? ( + <> + {placeholder} + + {narrowPlaceholder} + + + ) : ( + placeholder + )} + {placeholderSuffix ? ( + // No width and one top-aligned line tall: a suffix can neither wrap onto a line of + // its own nor push the baseline, so accepted text keeps the placeholder's layout. + + {placeholderSuffix} - - ) : ( - placeholder - )} - {placeholderSuffix} + ) : null} +
) : null}
diff --git a/apps/web/src/components/ConfirmDialogHost.tsx b/apps/web/src/components/ConfirmDialogHost.tsx index a836aeebbf3ab..8eaf0a02d7be7 100644 --- a/apps/web/src/components/ConfirmDialogHost.tsx +++ b/apps/web/src/components/ConfirmDialogHost.tsx @@ -1,6 +1,6 @@ import { msg, T, useMessages } from "gt-react"; import { Trash2Icon } from "lucide-react"; -import { useSyncExternalStore } from "react"; +import { useRef, useSyncExternalStore } from "react"; import { completeConfirmDialogClose, @@ -8,6 +8,7 @@ import { respondToConfirmDialog, subscribeConfirmDialogHost, } from "../confirmDialog"; +import { returnKeyboardToFocusedPane } from "../layout/layoutPaneContext"; import { AlertDialog, AlertDialogClose, @@ -20,6 +21,7 @@ import { } from "./ui/alert-dialog"; import { Button } from "./ui/button"; import type { MessageResolver } from "../i18n/messages"; +import { useDialogActionInitialFocus } from "./ui/dialog"; type ConfirmationCopy = { readonly title: string; @@ -65,6 +67,9 @@ export function ConfirmDialogHost() { readConfirmDialogState, ); + const openerRef = useRef(null); + const { popupRef, initialFocus } = useDialogActionInitialFocus(); + const copy = state.status !== "idle" && state.title ? { title: state.title, description: state.message.trim() || null } @@ -88,7 +93,25 @@ export function ConfirmDialogHost() { if (!open) completeConfirmDialogClose(); }} > - + { + openerRef.current = document.activeElement; + return initialFocus(openType); + }} + finalFocus={() => { + const opener = openerRef.current; + if (opener?.isConnected && !opener.closest("[data-layout-strip]")) return true; + if (returnKeyboardToFocusedPane()) return false; + // A chat pane takes it in its composer. + return ( + document.querySelector( + "[data-layout-pane-focused] [contenteditable='true']", + ) ?? true + ); + }} + > {copy.title} {copy.description ? ( diff --git a/apps/web/src/components/ConnectionStatusDot.tsx b/apps/web/src/components/ConnectionStatusDot.tsx deleted file mode 100644 index f365a03c872a1..0000000000000 --- a/apps/web/src/components/ConnectionStatusDot.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; - -import { cn } from "~/lib/utils"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; - -export function connectionPhaseDotClassName(phase: EnvironmentConnectionPhase): string { - switch (phase) { - case "connected": - return "bg-success"; - case "connecting": - case "reconnecting": - return "bg-warning"; - case "error": - return "bg-error"; - default: - return "bg-dim-foreground"; - } -} - -export function connectionPhasePingClassName(phase: EnvironmentConnectionPhase): string | null { - return phase === "connecting" || phase === "reconnecting" ? "bg-warning/60 duration-2000" : null; -} - -type ConnectionStatusDotProps = { - tooltipText?: string | null; - dotClassName: string; - pingClassName?: string | null; -}; - -export function ConnectionStatusDot({ - tooltipText, - dotClassName, - pingClassName, -}: ConnectionStatusDotProps) { - const dotContent = ( - <> - {pingClassName ? ( - - ) : null} - - - ); - - if (!tooltipText) { - return ( - - {dotContent} - - ); - } - - const dot = ( - - ); - - return ( - - - - {tooltipText} - - - ); -} diff --git a/apps/web/src/components/DevReplayHost.tsx b/apps/web/src/components/DevReplayHost.tsx index 376a836c0c0a7..bf57c6f0b17ef 100644 --- a/apps/web/src/components/DevReplayHost.tsx +++ b/apps/web/src/components/DevReplayHost.tsx @@ -97,6 +97,7 @@ export function DevReplayHost() { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- exposes the console API on window and listens for the hidden window hotkey useEffect(() => { window.t3dev = { + ...window.t3dev, replayScenarios: () => listScenarios(), replay: (scenario) => replayFromConsole(scenario), }; @@ -109,7 +110,10 @@ export function DevReplayHost() { }; window.addEventListener("keydown", onKeyDown); return () => { - delete window.t3dev; + if (window.t3dev) { + delete window.t3dev.replay; + delete window.t3dev.replayScenarios; + } window.removeEventListener("keydown", onKeyDown); }; }, []); diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index c663d690b5344..bd0cf0d5a2cf5 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -108,6 +108,7 @@ vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null })); vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null })); import DiffPanel from "./DiffPanel"; +import { PanelTabSlotsContext } from "./PanelTabBreadcrumb"; import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore"; import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore"; @@ -233,10 +234,17 @@ it.each([ using context = setup(failedBaseRef); await using screen = await render( - + () => {} }} + > + + , ); await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Diff scope: Branch changes" })) + .toBeVisible(); const selector = screen.getByRole("combobox", { name: /Change comparison target/ }); await vi.waitFor(() => expect(selector.query()).not.toBeNull()); await userEvent.click(selector); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index a991c6e63e007..44216c70df3fc 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -10,6 +10,7 @@ import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { CHECKPOINT_DIFF_TRUNCATED_MARKER, type ReviewBranchCommitsResult, + type ScopedProjectRef, type ScopedThreadRef, type RunId, } from "@t3tools/contracts"; @@ -54,6 +55,7 @@ import { useStableCallback } from "../hooks/useStableCallback"; import { buildFileDiffEntries, getDiffCollapseIconClassName, + getDiffLineStat, getRenderablePatch, getRenderablePatchSections, resolveDiffThemeName, @@ -82,6 +84,7 @@ import { DiffViewControls } from "./diffs/DiffViewControls"; import { diffFileTreeEntries } from "./diffs/diffFileTree.logic"; import { getDiffHeaderClickAction } from "./diffs/diffHeaderClick"; import { Button, InlineButton } from "./ui/button"; +import { PanelFrame } from "./ui/panel-frame"; import { Switch } from "./ui/switch"; import { Combobox, @@ -136,7 +139,6 @@ import { DiffFileChangeIcon, DiffFileHeaderStat, diffHeaderTitlePath, - fileDiffLineStat, } from "./diffs/DiffFileHeaderParts"; type DiffThemeType = "light" | "dark"; @@ -237,9 +239,19 @@ function DiffFileHeaderSuffix({ interface DiffPanelProps { mode?: DiffPanelMode; - composerDraftTarget: ScopedThreadRef | DraftId; + /** The composer comments go to; without one (a threadless surface) there are none. */ + composerDraftTarget?: ScopedThreadRef | DraftId | undefined; workspaceMutationId: string | null; visible: boolean; + /** + * The thread whose changes to show. A chat beside others in the layout + * passes its own; unset follows the route, as a lone thread view does. + */ + threadRef?: ScopedThreadRef | null | undefined; + /** With no thread to follow (a threadless surface), the project checkout whose changes to show. */ + projectRef?: ScopedProjectRef | null | undefined; + /** With no project either, the folder whose changes to show: the server's home. */ + folder?: string | null | undefined; } export default function DiffPanel({ @@ -247,6 +259,9 @@ export default function DiffPanel({ composerDraftTarget, workspaceMutationId, visible, + threadRef, + projectRef, + folder, }: DiffPanelProps) { const gt = useGT(); const messages = useMessages(); @@ -276,9 +291,11 @@ export default function DiffPanel({ // The comments written here since the review tray was last dismissed, for its one-press Undo. // Tied to the draft they went into, so switching threads does not carry a batch across. const composerDraftKey = - typeof composerDraftTarget === "string" - ? composerDraftTarget - : scopedThreadKey(composerDraftTarget); + composerDraftTarget === undefined + ? "" + : typeof composerDraftTarget === "string" + ? composerDraftTarget + : scopedThreadKey(composerDraftTarget); const [reviewBatch, setReviewBatch] = useState<{ draftKey: string; commentIds: ReadonlyArray; @@ -292,9 +309,21 @@ export default function DiffPanel({ })); const dismissReviewBatch = () => setReviewBatch(null); - const routeThreadRef = useThreadRouteRef(); + const urlThreadRef = useThreadRouteRef(); + const routeThreadRef = threadRef === undefined ? urlThreadRef : threadRef; const activeThreadId = routeThreadRef?.threadId ?? null; - const activeThread = useQuietThreadShell(routeThreadRef); + const threadShell = useQuietThreadShell(routeThreadRef); + const projectEnvironmentId = projectRef?.environmentId ?? null; + const projectCheckoutId = projectRef?.projectId ?? null; + const folderEnvironmentId = folder ? (routeThreadRef?.environmentId ?? null) : null; + // A project's own checkout, or a folder, stands in for a thread's; it has no turns. + const projectCheckout = + projectEnvironmentId !== null && projectCheckoutId !== null + ? { environmentId: projectEnvironmentId, projectId: projectCheckoutId, worktreePath: null } + : folder && folderEnvironmentId !== null + ? { environmentId: folderEnvironmentId, projectId: null, worktreePath: folder } + : null; + const activeThread = threadShell ?? projectCheckout; const fileAccess = useFilesystemReadAccess(activeThread?.environmentId ?? null, messages); const { canReadFiles } = fileAccess; const activeProjectId = activeThread?.projectId ?? null; @@ -346,7 +375,11 @@ export default function DiffPanel({ : null, ); const projectFoldersQuery = useEnvironmentQuery( - visible && tracksFolders && activeThread != null && threadWorktreePath === null + visible && + tracksFolders && + activeThread != null && + activeThread.projectId !== null && + threadWorktreePath === null ? filesystemEnvironment.listFolders({ environmentId: activeThread.environmentId, input: { projectId: activeThread.projectId }, @@ -368,7 +401,7 @@ export default function DiffPanel({ (threadFolderIsRepo ? null : (gitRepositories[0] ?? null)); const gitCwd = gitRepository?.cwd ?? activeCwd; const isGitRepo = threadFolderIsRepo || gitRepository !== null; - const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef); + const turnDiffSummaries = useThreadCheckpointSummaries(projectCheckout ? null : routeThreadRef); const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => { if (left.checkpointTurnCount !== right.checkpointTurnCount) { return right.checkpointTurnCount - left.checkpointTurnCount; @@ -994,455 +1027,450 @@ export default function DiffPanel({ } }; - const headerRow = ( - <> -
- - } - className={cn( - "max-w-full", - headerCommitSha !== null && "min-w-0 shrink", - repositorySections.length > 0 && "min-w-14 shrink", + const scopeCrumb = ( + + + } + className={cn( + headerCommitSha === null ? "shrink-0" : "min-w-0 shrink", + repositorySections.length > 0 && "min-w-14 shrink", + )} + title={selectedScopeLabel} + aria-label={gt("Diff scope: {scope}", { scope: selectedScopeLabel })} + data-workspace-focus-default + > + {selectedScopeLabel} + + + {headerCommitSha !== null ? ( + selectedCommitUrl ? ( + + + } + onClick={(event) => openCommitUrl(event, selectedCommitUrl)} + /> + } + > + + {headerCommitSha.slice(0, 7)} + + + {selectedCommitUrl} + + ) : ( + + {headerCommitSha.slice(0, 7)} + + ) + ) : null} + + + {turnDiffsOnly ? null : ( + <> + + + Working tree + + + + + Branch changes + + + )} - aria-label={gt("Diff scope: {scope}", { scope: selectedScopeLabel })} - data-workspace-focus-default - > - {selectedScopeLabel} - - - {headerCommitSha !== null ? ( - selectedCommitUrl ? ( - - - } - onClick={(event) => openCommitUrl(event, selectedCommitUrl)} - /> - } - > - - {headerCommitSha.slice(0, 7)} - - - {selectedCommitUrl} - - ) : ( - - {headerCommitSha.slice(0, 7)} + + + Latest turn - ) - ) : null} - - - {turnDiffsOnly ? null : ( - <> - - - Working tree - - - - - Branch changes - - - - )} - - - Latest turn - - - - - + + + + + + Turn + + + + {orderedTurnDiffSummaries.map((summary) => { + const turnCount = summary.checkpointTurnCount; + return ( + + + + + Turn {turnCount} + + + + {formatShortTimestamp(summary.completedAt, settings.timestampFormat)} + + + + ); + })} + + + + {turnDiffsOnly ? null : ( + { + setOpenCommitMenu(open ? (branchCommitsQuery.data ?? null) : null); + if (!open) return; + // The menu keeps the list it opened with; the refreshed one shows next time. + branchCommitsQuery.refresh(); + }} + > - Turn + Commits - - - {orderedTurnDiffSummaries.map((summary) => { - const turnCount = summary.checkpointTurnCount; + + + {branchCommits?.commits.map((commit) => { + const commitUrl = projectCommitUrl(commitLinkIdentity, commit.sha); return ( - - - - - Turn {turnCount} - - - - {formatShortTimestamp(summary.completedAt, settings.timestampFormat)} + + + } + > + + {commit.subject} + + {formatRelativeTimeLabel( + commit.committedAt, + Date.parse(now), + messages, + )} + + + + + {commit.subject} + + + {commitUrl ? ( + + } + onClick={(event) => openCommitUrl(event, commitUrl)} + > + + {commit.sha.slice(0, 7)} + + + ) : ( + + {commit.sha.slice(0, 7)} - - + )} +
); })} + {branchCommitsQuery.error ? ( + {branchCommitsQuery.error} + ) : !canReadFiles ? ( + + {fileAccess.isPending + ? gt("Checking file access...") + : (fileAccess.error ?? gt("This connection cannot read local diffs."))} + + ) : branchCommits === null ? ( + + Loading commits... + + ) : branchCommits.commits.length === 0 ? ( + + No commits on this branch. + + ) : branchCommits.truncated ? ( + + {gt( + "{count, plural, one {Showing latest {count} commits} other {Showing latest {count} commits}}", + { count: branchCommits.commits.length }, + )} + + ) : null} - {turnDiffsOnly ? null : ( - { - setOpenCommitMenu(open ? (branchCommitsQuery.data ?? null) : null); - if (!open) return; - // The menu keeps the list it opened with; the refreshed one shows next time. - branchCommitsQuery.refresh(); - }} - > - - Commits - - - - {branchCommits?.commits.map((commit) => { - const commitUrl = projectCommitUrl(commitLinkIdentity, commit.sha); - return ( -
- - - } - > - - {commit.subject} - - {formatRelativeTimeLabel( - commit.committedAt, - Date.parse(now), - messages, - )} - - - - - {commit.subject} - - - {commitUrl ? ( - - } - onClick={(event) => openCommitUrl(event, commitUrl)} - > - - {commit.sha.slice(0, 7)} - - - ) : ( - - {commit.sha.slice(0, 7)} - - )} -
- ); - })} -
- {branchCommitsQuery.error ? ( - {branchCommitsQuery.error} - ) : !canReadFiles ? ( - - {fileAccess.isPending - ? gt("Checking file access...") - : (fileAccess.error ?? gt("This connection cannot read local diffs."))} - - ) : branchCommits === null ? ( - - Loading commits... - - ) : branchCommits.commits.length === 0 ? ( - - No commits on this branch. - - ) : branchCommits.truncated ? ( - - {gt( - "{count, plural, one {Showing latest {count} commits} other {Showing latest {count} commits}}", - { count: branchCommits.commits.length }, - )} - - ) : null} -
-
- )} + )} + + + {isGitSelection && gitRepositories.length > 0 && ( + + } + className="min-w-14 max-w-48 shrink" + aria-label={gt("Repository: {name}", { + name: gitRepository?.name ?? threadFolderName, + })} + > + {gitRepository?.name ?? threadFolderName} + + + + + {threadFolderIsRepo ? ( + + {threadFolderName} + + ) : null} + {gitRepositories.map((repository) => ( + + {repository.name} + + ))} + - {isGitSelection && gitRepositories.length > 0 && ( - - } - className="min-w-14 max-w-48 shrink" - aria-label={gt("Repository: {name}", { - name: gitRepository?.name ?? threadFolderName, - })} - > - {gitRepository?.name ?? threadFolderName} - - - - - {threadFolderIsRepo ? ( - - {threadFolderName} - - ) : null} - {gitRepositories.map((repository) => ( - - {repository.name} - - ))} - - - - )} - {repositorySections.length > 0 && ( - - } - className="min-w-14 max-w-48 shrink" - aria-label={gt("Repository: {name}", { - name: selectedSection?.name ?? gt("All repositories"), - })} + )} + {repositorySections.length > 0 && ( + + } + className="min-w-14 max-w-48 shrink" + aria-label={gt("Repository: {name}", { + name: selectedSection?.name ?? gt("All repositories"), + })} + > + {selectedSection?.name ?? gt("All repositories")} + + + + - {selectedSection?.name ?? gt("All repositories")} - - - - - - - All repositories + + + All repositories + + + {repositorySections.map((section) => ( + + + {section.name} + {section.relativePath !== "" && section.relativePath !== section.name ? ( + + {section.relativePath} + + ) : null} - {repositorySections.map((section) => ( - - - {section.name} - {section.relativePath !== "" && section.relativePath !== section.name ? ( - - {section.relativePath} - - ) : null} - - - ))} - - - - )} - {canSelectBranchBase && ( -
+ + + )} + {canSelectBranchBase && ( +
+ + + } + > + {comparisonHeadRef} + + + {`${comparisonHeadRef} → ${comparisonBaseRef}`} + + + }>vs + {`${comparisonHeadRef} → ${comparisonBaseRef}`} + + { + if (!open) setBaseRefQuery(""); + }} + onValueChange={(value) => { + if (!value) return; + selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value); + }} > - - - } - > - {comparisonHeadRef} - - - - {`${comparisonHeadRef} → ${comparisonBaseRef}`} - - - - } - > - vs - - - {`${comparisonHeadRef} → ${comparisonBaseRef}`} - - - { - if (!open) setBaseRefQuery(""); - }} - onValueChange={(value) => { - if (!value) return; - selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value); - }} + } + className="min-w-9 max-w-48 shrink" + aria-label={gt("Change comparison target. Currently {base}", { + base: comparisonBaseRef, + })} > - } - className="min-w-9 max-w-48 shrink-0" - aria-label={gt("Change comparison target. Currently {base}", { - base: comparisonBaseRef, - })} - > - {comparisonBaseRef} - - - - setBaseRefQuery(event.target.value)} - /> -
-
+ + No matching refs. + + + + + Automatic + + + {baseRefChoices.map((choice) => { + const item = valueForBaseRefChoice(choice); + const hasBoth = choice.local !== null && choice.remote !== null; + const useRemote = choice.remote?.name === item; + return ( + +
+ {choice.label} + {hasBoth ? ( +
event.stopPropagation()} + onPointerDown={(event) => event.stopPropagation()} + > + { + const nextRef = checked ? choice.remote?.name : choice.local?.name; + if (nextRef) selectBranchBaseRef(nextRef); + }} + /> +
+ ) : choice.remote ? ( + + + + + } + /> + + Remote only + + + ) : null} +
+
+ ); + })} +
+
+
+
+ )} + + ); + const viewControls = ( + + useDiffPanelSessionStore.getState().setIgnoreWhitespace(value) + } + hasFiles={diffFileKeys.length > 0} + testFileCount={testFileCount} + hideTestFiles={hideTestFiles} + onHideTestFilesChange={setHideTestFiles} + foldBelow="2xl" + fileTreeOpen={fileTreeOpen} + onFileTreeOpenChange={setFileTreeOpen} + allFilesCollapsed={allDiffFilesCollapsed} + onToggleAllFiles={toggleDiffFileCollapse} + refresh={ + canRefreshGitDiff + ? { refreshing: isRefreshingDiff, onRefresh: refreshDiffFromUserAction } + : undefined + } + /> + ); + const headerRow = ( + <> +
+ {scopeCrumb}
- - useDiffPanelSessionStore.getState().setIgnoreWhitespace(value) - } - hasFiles={diffFileKeys.length > 0} - testFileCount={testFileCount} - hideTestFiles={hideTestFiles} - onHideTestFilesChange={setHideTestFiles} - fileTreeOpen={fileTreeOpen} - onFileTreeOpenChange={setFileTreeOpen} - allFilesCollapsed={allDiffFilesCollapsed} - onToggleAllFiles={toggleDiffFileCollapse} - refresh={ - canRefreshGitDiff - ? { refreshing: isRefreshingDiff, onRefresh: refreshDiffFromUserAction } - : undefined - } - /> + {viewControls}
); @@ -1459,7 +1487,7 @@ export default function DiffPanel({ } title={gt("Not a git repository")} - description={gt("Diffs compare git checkpoints, so this project has none to show.")} + description={gt("Diffs compare git checkpoints, so this folder has none to show.")} /> ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? ( -
+
{preview?.incomplete && ( -

+ }> {selectedPatchError ? gt( "Showing tracked changes. Untracked changes could not be loaded. Refresh to retry.", ) : gt("Showing tracked changes. Checking untracked files...")} -

+ )} {isSelectedPatchTruncated && !lazySource && ( -

+ }> {isGitSelection && selectedGitSource?.files && !preview?.incomplete ? gt( "This preview exceeds the size limit. Changes shown are incomplete. Totals include all changes.", ) : gt("This preview exceeds the size limit. Changes shown are incomplete.")} -

+ )} {selectedPatchError && lazySource ? (

@@ -1502,7 +1537,7 @@ export default function DiffPanel({

) : null} {omittedToolCallFiles > 0 && ( -

+ }> {gt( "This tool call changed {recorded} files. The recorded patch omits {omitted} of them.", { @@ -1510,7 +1545,7 @@ export default function DiffPanel({ omitted: omittedToolCallFiles, }, )} -

+ )} {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? (
@@ -1656,7 +1691,7 @@ export default function DiffPanel({ // A lazily loaded file's hunks may not be here yet; the scope's stats are. const stat = lazySource ? fileStats.get(resolveFileDiffPath(fileDiff)) - : fileDiffLineStat(fileDiff); + : getDiffLineStat([fileDiff]); return stat ? ( ) : null; @@ -1700,6 +1735,7 @@ export default function DiffPanel({
{fileTreeOpen ? ( ) : ( -
+

{renderablePatch?.kind === "raw" ? renderablePatch.reason : null} @@ -1734,11 +1770,13 @@ export default function DiffPanel({

)} - + {composerDraftTarget ? ( + + ) : null}
)} diff --git a/apps/web/src/components/DiffPanelShell.tsx b/apps/web/src/components/DiffPanelShell.tsx index 99d4f2e5ee7ec..4823fe9cf181d 100644 --- a/apps/web/src/components/DiffPanelShell.tsx +++ b/apps/web/src/components/DiffPanelShell.tsx @@ -93,7 +93,7 @@ function DiffCodeLineSkeleton({ width }: { width: "short" | "medium" | "long" }) export function DiffPanelLoadingState(props: { label: string }) { return (
{ }); describe("when: local changes are behind upstream", () => { + it("blocks pulling a diverged branch until it is rebased or merged", () => { + const diverged = status({ aheadCount: 1, behindCount: 1 }); + const items = buildSyncMenuItems(diverged, false); + assert.isTrue(items.pull?.disabled); + assert.equal( + items.pull?.disabledReason, + "Branch has diverged from upstream. Rebase/merge first.", + ); + assert.isFalse(buildSyncMenuItems(status({ behindCount: 1 }), false).pull?.disabled); + }); + it("keeps the commit action available without pushing, with or without an open PR", () => { const behind = status({ hasWorkingTreeChanges: true, behindCount: 2 }); const commit = { @@ -251,6 +264,18 @@ describe("requiresDefaultBranchConfirmation", () => { }); }); +describe("commitPushShortcutPressActs", () => { + it("acts once, only for the control in the focused pane", () => { + const press = { defaultPrevented: false, repeat: false }; + assert.isTrue(commitPushShortcutPressActs({ ...press, paneFocused: true })); + assert.isFalse(commitPushShortcutPressActs({ ...press, paneFocused: false })); + assert.isFalse( + commitPushShortcutPressActs({ ...press, paneFocused: true, defaultPrevented: true }), + ); + assert.isFalse(commitPushShortcutPressActs({ ...press, paneFocused: true, repeat: true })); + }); +}); + describe("resolveLiveThreadBranchUpdate", () => { it("returns a branch update when live git status differs from stored thread metadata", () => { const update = resolveLiveThreadBranchUpdate({ diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index e3d5e39383aed..e5806d05712e6 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -59,6 +59,18 @@ export interface GitActionResultToastTiming { export const GIT_ACTION_SUCCESS_VISIBLE_MS = 10_000; +/** + * Every chat's git control listens on the window; only the one in the focused pane + * (`useLayoutPaneFocusedRef`, false for background threads) commits and pushes. + */ +export function commitPushShortcutPressActs(input: { + readonly paneFocused: boolean; + readonly defaultPrevented: boolean; + readonly repeat: boolean; +}): boolean { + return input.paneFocused && !input.defaultPrevented && !input.repeat; +} + export function resolveGitActionResultToastTiming( type: "error" | "success", ): GitActionResultToastTiming { @@ -793,11 +805,13 @@ export function buildSyncMenuItems( resolve(msg("Pull")), busyReason ?? detachedReason ?? - (!isBehind - ? resolve(msg("Already up to date with upstream.")) - : hasChanges - ? resolve(msg("Commit or stash local changes before pulling.")) - : null), + (isAhead && isBehind + ? resolve(msg("Branch has diverged from upstream. Rebase/merge first.")) + : !isBehind + ? resolve(msg("Already up to date with upstream.")) + : hasChanges + ? resolve(msg("Commit or stash local changes before pulling.")) + : null), ); const sync = syncMenuItem( "sync", diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 922548659911d..8ae38079f19ed 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -36,6 +36,7 @@ import { EllipsisIcon, BookUp2Icon, CheckIcon, + ChevronDownIcon, CloudDownloadIcon, CloudUploadIcon, FileDiffIcon, @@ -49,9 +50,11 @@ import { import { Spinner } from "~/components/ui/spinner"; import { cn } from "~/lib/utils"; import { useOpenPrLink } from "~/lib/openPullRequestLink"; +import { useLayoutPaneFocusedRef } from "~/layout/layoutPaneContext"; import { buildMenuItems, buildSyncMenuItems, + commitPushShortcutPressActs, formatGitActionElapsed, GIT_ACTION_SUCCESS_VISIBLE_MS, hasUsableGitMenuContent, @@ -75,6 +78,7 @@ import { import { GitCommitDialog, type GitCommitDialogSubmission } from "./GitCommitDialog"; import { PublishRepositoryDialog } from "./PublishRepositoryDialog"; import { Button } from "~/components/ui/button"; +import { Group, GroupSeparator } from "~/components/ui/group"; import { Dialog, DialogDescription, @@ -129,7 +133,9 @@ import { type DraftId, useComposerDraftStore } from "~/composerDraftStore"; import { THREAD_DETAILS_PANEL_LABEL_CLASS } from "./chat/threadDetailsPanelStyles"; import { getSourceControlPresentation } from "~/sourceControlPresentation"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { PullRequestGlyph } from "./pullRequest/pullRequestIcons"; import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; +import { ChangeBreakdownGrid } from "./pullRequest/ChangeBreakdownGrid"; /** The folder a Git actions control acts on: a thread's own folder or a tracked repository. */ export interface GitActionsTarget { @@ -148,10 +154,15 @@ export interface GitActionsBranchFollower { interface GitActionsViewProps { /** "shortcut" keeps the commit and push shortcut and its dialogs live. */ - presentation?: "shortcut"; + presentation?: "shortcut" | "toolbar"; displayMode?: "panel"; compact?: boolean; listenForShortcuts?: boolean; + /** + * The panel's control reports while it can take the commit and push shortcut, so the chat + * does not keep a "shortcut" copy mounted beside it. + */ + onShortcutHostChange?: (hosting: boolean) => void; showActions?: boolean; showChanges?: boolean; onOpenChanges?: () => void; @@ -171,6 +182,15 @@ interface GitActionsControlProps extends GitActionsViewProps { quietUntilWork?: boolean; /** The ref the Changes row compares against, when the viewer picked one. */ changesBaseRef?: string | null; + /** Passive repository rows subscribe to local status and refresh remote status when their menu opens. */ + includeRemote?: boolean; + /** Keep non-repository panel rows inside the trailing menu instead of expanding an inline Initialize Git row. */ + compactNonRepo?: boolean; + /** Extra items appended to the panel options menu, such as removing a pinned repository. */ + menuFooter?: ReactNode; + /** Controlled open state for the panel options menu when an adjacent row button also opens it. */ + menuOpen?: boolean; + onMenuOpenChange?: (open: boolean) => void; } interface ThreadGitActionsControlProps extends GitActionsViewProps { @@ -187,6 +207,7 @@ interface PendingDefaultBranchAction { commitMessage?: string; onConfirmed?: () => void; filePaths?: string[]; + fromShortcut?: boolean; } type GitActionToastId = ReturnType; @@ -199,6 +220,8 @@ interface RunGitActionWithToastInput { statusOverride?: VcsStatusResult | null; featureBranch?: boolean; filePaths?: string[]; + /** A shortcut press reports its result in a toast, as the "shortcut" control does. */ + fromShortcut?: boolean; } interface InlineGitActionSuccess { @@ -391,12 +414,21 @@ export const GitActionsControl = memo(function GitActionsControl(props: GitActio props.target?.key ?? null, props.target?.cwd ?? null, ]); + // Reported here, above the checkout key, so a project change does not hand the shortcut back and forth. + const { onShortcutHostChange, showActions = true } = props; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the chat this mounted panel control (with its publish dialog) takes the shortcut + useEffect(() => { + if (!onShortcutHostChange || !showActions) return; + onShortcutHostChange(true); + return () => onShortcutHostChange(false); + }, [onShortcutHostChange, showActions]); return ; }); function CheckoutGitActionsControl({ presentation, listenForShortcuts = true, + onShortcutHostChange, displayMode, target, threadRef: activeThreadRef, @@ -404,16 +436,20 @@ function CheckoutGitActionsControl({ branchFollower, quietUntilWork = false, changesBaseRef = null, + includeRemote = true, + compactNonRepo = false, + menuFooter, + menuOpen, + onMenuOpenChange, showActions = true, showChanges = true, onOpenChanges, workspaceMutationId = null, - keybindings: panelKeybindings, }: GitActionsControlProps) { const gt = useGT(); const messages = useMessages(); const progressLabelId = useId(); - const isPanel = presentation !== "shortcut"; + const isPanel = presentation === undefined; const gitCwd = target?.cwd ?? null; const activeEnvironmentId = activeThreadRef?.environmentId ?? null; const canWriteSourceControl = useEnvironmentScope( @@ -445,7 +481,7 @@ function CheckoutGitActionsControl({ activeEnvironmentId !== null && gitCwd !== null ? vcsEnvironment.status({ environmentId: activeEnvironmentId, - input: { cwd: gitCwd }, + input: includeRemote ? { cwd: gitCwd } : { cwd: gitCwd, includeRemote: false }, }) : null, ); @@ -455,7 +491,10 @@ function CheckoutGitActionsControl({ const { data: gitStatus, error: gitStatusError } = gitStatusQuery; const sourceControlPresentation = getSourceControlPresentation(gitStatus?.sourceControlProvider); const changeRequestTerminology = sourceControlPresentation.terminology; - const SourceControlIcon = sourceControlPresentation.Icon; + const SourceControlIcon = + gitStatus?.sourceControlProvider?.kind === "gitcafe" + ? PullRequestGlyph.pullRequest + : sourceControlPresentation.Icon; const isRepo = gitStatus?.isRepo ?? true; const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false; const gitStatusForActions = gitStatus; @@ -504,6 +543,7 @@ function CheckoutGitActionsControl({ changesPreview.data?.sources.find((source) => source.kind === "branch-range"), ); const changesTotals = resolvedChangesTotals ?? { insertions: 0, deletions: 0 }; + const changesBreakdown = resolvedChangesTotals?.breakdown ?? null; const changesBaseLabel = resolvedChangesTotals ? resolvedChangesTotals.baseRef === null ? gt("Uncommitted") @@ -579,7 +619,7 @@ function CheckoutGitActionsControl({ useAtomMount( vcsStatusRevalidation( - activeEnvironmentId !== null && gitCwd !== null + includeRemote && activeEnvironmentId !== null && gitCwd !== null ? { environmentId: activeEnvironmentId, cwd: gitCwd } : null, ), @@ -593,6 +633,7 @@ function CheckoutGitActionsControl({ statusOverride, featureBranch = false, filePaths, + fromShortcut = false, }: RunGitActionWithToastInput) { if ( activeEnvironmentId === null || @@ -628,6 +669,7 @@ function CheckoutGitActionsControl({ ...(commitMessage ? { commitMessage } : {}), ...(onConfirmed ? { onConfirmed } : {}), ...(filePaths ? { filePaths } : {}), + fromShortcut, }); return false; } @@ -671,7 +713,7 @@ function CheckoutGitActionsControl({ const actionResult = result.value; const branchUpdate = resolveThreadBranchUpdate(actionResult); if (branchUpdate) branchFollower?.follow(branchUpdate.branch); - if (isPanel) { + if (isPanel && !fromShortcut) { const createdPullRequest = actionResult.pr.status === "created"; setInlineSuccess({ title: createdPullRequest @@ -735,14 +777,6 @@ function CheckoutGitActionsControl({ data: successToastData, }), ); - } else { - resultToastId = toastManager.add({ - type: "success", - title: actionResult.toast.title, - description: actionResult.toast.description, - timeout: successToastTiming.timeout, - data: successToastData, - }); } return true; } @@ -751,13 +785,15 @@ function CheckoutGitActionsControl({ if (!pendingDefaultBranchAction || !canWriteSourceControl) return; if (featureBranch && (!canCreateFeatureBranch || featureBranchUnavailableReason !== null)) return; - const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction; + const { action, commitMessage, onConfirmed, filePaths, fromShortcut } = + pendingDefaultBranchAction; setPendingDefaultBranchAction(null); void runGitActionWithToast({ action, ...(commitMessage ? { commitMessage } : {}), ...(onConfirmed ? { onConfirmed } : {}), ...(filePaths ? { filePaths } : {}), + ...(fromShortcut ? { fromShortcut } : {}), featureBranch, skipDefaultBranchPrompt: true, }); @@ -797,26 +833,10 @@ function CheckoutGitActionsControl({ }) : gt("Updated {ref} from upstream", { ref: pullResult.refName }) : gt("{ref} is already synchronized.", { ref: pullResult.refName }); - if (isPanel) { - setInlineSuccess({ - title, - description, - expiresAtMs: inlineSuccessExpiresAt(), - }); - return; - } - const successToastTiming = resolveGitActionResultToastTiming("success"); - toastManager.add({ - type: "success", + setInlineSuccess({ title, description, - timeout: successToastTiming.timeout, - data: { - ...threadToastData, - ...(successToastTiming.dismissAfterVisibleMs !== null - ? { dismissAfterVisibleMs: successToastTiming.dismissAfterVisibleMs } - : {}), - }, + expiresAtMs: inlineSuccessExpiresAt(), }); })(); }; @@ -844,9 +864,12 @@ function CheckoutGitActionsControl({ } }; - const runCommitPush = () => { + const runCommitPush = (fromShortcut?: true) => { if (!syncMenuItems.commitPush || syncMenuItems.commitPush.disabled) return; - void runGitActionWithToast({ action: "commit_push" }); + void runGitActionWithToast({ + action: "commit_push", + ...(fromShortcut ? { fromShortcut } : {}), + }); }; // Sync ref pulls what upstream has, then pushes what the branch still has ahead. @@ -859,13 +882,20 @@ function CheckoutGitActionsControl({ void runGitActionWithToast({ action: "push" }); }; - const runCommitPushFromShortcut = useEffectEvent(runCommitPush); - const handlesCommitPushShortcut = presentation === "shortcut" && isRepo; + const runCommitPushFromShortcut = useEffectEvent(() => runCommitPush(true)); + const paneFocusedRef = useLayoutPaneFocusedRef(); + const handlesCommitPushShortcut = + (presentation !== undefined || onShortcutHostChange !== undefined) && isRepo; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown for the mounted git control's commit and push shortcuts useEffect(() => { if (!listenForShortcuts || !handlesCommitPushShortcut) return; const onKeyDown = (event: KeyboardEvent) => { - if (event.defaultPrevented || event.repeat) return; + const press = { + paneFocused: paneFocusedRef.current, + defaultPrevented: event.defaultPrevented, + repeat: event.repeat, + }; + if (!commitPushShortcutPressActs(press)) return; const command = resolveShortcutCommand(event, keybindings, { context: { terminalFocus: isTerminalFocused() }, }); @@ -875,7 +905,7 @@ function CheckoutGitActionsControl({ }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [handlesCommitPushShortcut, keybindings, listenForShortcuts]); + }, [handlesCommitPushShortcut, keybindings, listenForShortcuts, paneFocusedRef]); const openDialogForMenuItem = (item: GitActionMenuItem) => { if (!canWriteSourceControl || item.disabled) return; @@ -985,24 +1015,24 @@ function CheckoutGitActionsControl({ readonly disabledReason: string | null; readonly trailing?: ReactNode; readonly onClick: () => void; - }) => ( -
- + }) => { + const disabled = !canWriteSourceControl || row.disabled; + const item = ( + {row.icon} {row.label} {row.trailing} - {row.disabled && row.disabledReason ? ( -

- {row.disabledReason} -

- ) : null} -
- ); + ); + return disabled && row.disabledReason ? ( + + }>{item} + {row.disabledReason} + + ) : ( + item + ); + }; const renderActionMenuItem = (item: GitActionMenuItem) => renderMenuRow({ key: `${item.id}-${item.label}`, @@ -1055,10 +1085,10 @@ function CheckoutGitActionsControl({ label: syncMenuItems.commitPush.label, disabled: syncMenuItems.commitPush.disabled, disabledReason: syncMenuItems.commitPush.disabledReason, - ...(commitPushShortcutLabel + ...(handlesCommitPushShortcut && commitPushShortcutLabel ? { trailing: {commitPushShortcutLabel} } : {}), - onClick: runCommitPush, + onClick: () => runCommitPush(), }) : null} {pushItem ? renderActionMenuItem(pushItem) : null} @@ -1162,59 +1192,141 @@ function CheckoutGitActionsControl({ return ( <> - {presentation === "shortcut" ? null : displayMode === "panel" && isRepo ? ( -
+ {isRepo && showActions ? ( + + void runGitActionWithToast({ action: "push" })} + /> + } + > + {gitActionProgress ? : } + + + Push branch + + + ) : null} + { + onMenuOpenChange?.(open); + if (open && isRepo && showActions) { + requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd); + } + }} + > + + + } + /> + } + > + + + + Git action options + + + + {showActions ? ( + isRepo ? ( + gitItems + ) : ( + + + + {initAction.isPending ? Initializing... : Initialize Git} + + + ) + ) : null} + {showActions && menuFooter ? : null} + {menuFooter} + + +
+ ) : null + ) : presentation === "toolbar" && isRepo ? ( + - {showActions ? ( + + + { + if (open) requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd); + }} + > } - onClick={() => void runGitActionWithToast({ action: "push" })} /> } > - {gitActionProgress ? : } + - - Push branch + + Git action options - ) : null} - { - if (open) requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd); - }} - > - } - > - - - {showChanges ? ( - - - - View changes - - {changesSummary} - - ) : null} - {showActions ? gitItems : null} + {gitItems} -
+ ) : !isRepo ? ( showActions ? ( - - - View changes - - {!showActions ? changesSummary : null} - {keybindings && ( - - {shortcutLabelForCommand(panelKeybindings ?? keybindings, "diff.toggle")} - - )} - - )} {showActions ? ( { @@ -1290,7 +1388,11 @@ function CheckoutGitActionsControl({ Git actions - + {gitItems} @@ -1298,6 +1400,61 @@ function CheckoutGitActionsControl({
)} + {isPanel && showChanges && isRepo && (displayMode === "panel" || !quietEmptyDraft) ? ( +
+ + } + > + + + + Changes + + {changesBaseLabel ? ( + + } + > + {changesBaseLabel} + + {changesBaseLabel} + + ) : null} + + + +{formatDiffCount(changesTotals?.insertions ?? 0)} + + + -{formatDiffCount(changesTotals?.deletions ?? 0)} + + + + + {changesBreakdown && (changesTotals.insertions > 0 || changesTotals.deletions > 0) ? ( + // Base UI fixes the popup width on open; remeasure when the breakdown changes. + + + + ) : null} + +
+ ) : null} + ; + canOpenFiles: boolean; + onToggleFile: (path: string) => void; + onOpenFile: (path: string) => void; +}) { + const gt = useGT(); + return ( + <> + {files.map((file) => { + const isExcluded = excludedFiles.has(file.path); + const { name, directory } = splitFilePath(file.path); + return ( +
+ onToggleFile(file.path)} + /> + + + {file.insertions > 0 ? `+${formatDiffCount(file.insertions)}` : ""} + {file.insertions > 0 && file.deletions > 0 ? " " : ""} + {file.deletions > 0 ? `−${formatDiffCount(file.deletions)}` : ""} + +
+ ); + })} + + ); +} + /** * Review and commit the working tree: pick the branch to commit on, include or exclude files, * and write an optional message. The caller runs the commit. @@ -217,60 +284,13 @@ export function GitCommitDialog({

) : (
- {allFiles.map((file) => { - const isExcluded = excludedFiles.has(file.path); - const { name, directory } = splitFilePath(file.path); - return ( -
- toggleFile(file.path)} - /> - - - {file.insertions > 0 ? `+${formatDiffCount(file.insertions)}` : ""} - {file.insertions > 0 && file.deletions > 0 ? " " : ""} - {file.deletions > 0 ? `−${formatDiffCount(file.deletions)}` : ""} - -
- ); - })} +
)}
diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx index 09b363c2d1f7e..407ca87a9374e 100644 --- a/apps/web/src/components/HistorySwipeNavigation.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -146,7 +146,9 @@ export function HistorySwipeNavigation() { } if (gesture === null) { gesture = - event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL + event.ctrlKey || + (event.metaKey && event.altKey) || + event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL ? { kind: "ignored" } : { kind: "pending", path: event.composedPath(), y: event.clientY, sumX: 0, sumY: 0 }; } diff --git a/apps/web/src/components/NoProjectsHero.tsx b/apps/web/src/components/NoProjectsHero.tsx index 7d9b659337b5b..9a74a3c4911cb 100644 --- a/apps/web/src/components/NoProjectsHero.tsx +++ b/apps/web/src/components/NoProjectsHero.tsx @@ -1,8 +1,15 @@ import { workspaceAreaProps } from "../lib/workspaceFocus"; import { useAtomValue } from "@effect/atom-react"; -import { T, useGT } from "gt-react"; -import { DownloadIcon, FolderPlusIcon, MessageSquareDashedIcon } from "lucide-react"; +import { T, useGT, useMessages } from "gt-react"; +import { + DownloadIcon, + FolderPlusIcon, + MessageSquareDashedIcon, + PlusIcon, + SquarePenIcon, +} from "lucide-react"; import { useNavigate } from "@tanstack/react-router"; +import type { ReactNode } from "react"; import { openCommandPalette } from "../commandPaletteBus"; import { isElectron } from "../env"; @@ -11,7 +18,13 @@ import { shortcutLabelForCommand } from "../keybindings"; import { usePrimaryEnvironmentId } from "../state/environments"; import { primaryServerKeybindingsAtom } from "../state/server"; import { DraftProjectGroupLabel, DraftProjectRow } from "./chat/DraftHeroHeadline"; +import { NoProjectsComposer } from "./chat/NoProjectsComposer"; +import { PanelLayoutControls } from "./chat/PanelLayoutControls"; +import { ChatPaneHeaderControls } from "./chat/ChatPaneHeader"; +import { PANE_TAB_CLASS, PaneNotch } from "./PaneNotch"; +import { Button } from "./ui/button"; import { SidebarInset } from "./ui/sidebar"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { WorkspacePageHeader } from "./WorkspacePageHeader"; /** @@ -20,24 +33,21 @@ import { WorkspacePageHeader } from "./WorkspacePageHeader"; */ export function NoProjectsHero() { const gt = useGT(); + const messages = useMessages(); const navigate = useNavigate(); - const contentArea = workspaceAreaProps("home", 1, gt("Home")); const primaryEnvironmentId = usePrimaryEnvironmentId(); - const { scratchEnvironmentId, startScratchThread } = useScratchProject(); + const { scratchEnvironmentId, scratchUnavailableReason, startScratchThread } = + useScratchProject(); const scratchTargetEnvironmentId = scratchEnvironmentId(primaryEnvironmentId); + const scratchOffReason = scratchUnavailableReason(primaryEnvironmentId, messages); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const openAddProject = () => openCommandPalette({ open: "add-project" }); return ( - -
- {/* The desktop window only moves where CSS opts in, so keep a titlebar strip. */} - {isElectron ? : null} -
+ + {/* Like a draft: the list centered above the composer docked at the bottom. */} +
+

Add a project to start @@ -60,7 +70,7 @@ export function NoProjectsHero() { })} onSelect={() => void navigate({ to: "/welcome" })} /> - {scratchTargetEnvironmentId === null ? null : ( + {scratchTargetEnvironmentId === null && scratchOffReason === null ? null : ( <>
} label={gt("No project")} - detail={gt("Its own folder, no git")} - shortcut={shortcutLabelForCommand(keybindings, "chat.newWithoutProject")} - onSelect={() => void startScratchThread(scratchTargetEnvironmentId)} + detail={scratchOffReason ?? gt("Its own folder, no git")} + disabled={scratchTargetEnvironmentId === null} + shortcut={ + scratchTargetEnvironmentId === null + ? null + : shortcutLabelForCommand(keybindings, "chat.newWithoutProject") + } + onSelect={() => { + if (scratchTargetEnvironmentId !== null) { + void startScratchThread(scratchTargetEnvironmentId); + } + }} /> )}

+ {primaryEnvironmentId === null ? null : ( +
+
+ + void startScratchThread(scratchTargetEnvironmentId, { + sendCarriedDraft: true, + }) + } + startUnavailableReason={scratchOffReason} + /> +
+
+
+ )} +
+ + ); +} + +/** + * The pane a new draft opens in, with its one "New thread" tab in the notch. + * Empty, it holds the place while the app loads its projects. + */ +function NewThreadPane({ + addDisabledReason, + children, +}: { + readonly addDisabledReason: string; + readonly children?: ReactNode; +}) { + const gt = useGT(); + return ( + +
+ {/* The pane header a draft would have, with its one tab in the notch. */} + +
+ +
+ + New thread +
+ {/* A draft's "+" and details toggle, with nothing to act on yet. */} + + }> + + + {addDisabledReason} + +
+
+ + {}} + disabledReason={gt("No thread yet")} + /> + +
+ {children}
); diff --git a/apps/web/src/components/PaneNotch.tsx b/apps/web/src/components/PaneNotch.tsx index 7c337e734836e..275dbdff2c811 100644 --- a/apps/web/src/components/PaneNotch.tsx +++ b/apps/web/src/components/PaneNotch.tsx @@ -1,9 +1,13 @@ import { mergeProps } from "@base-ui/react/merge-props"; import { useRender } from "@base-ui/react/use-render"; -import type { ReactNode } from "react"; +import { useLayoutEffect, useRef, type ReactNode } from "react"; import { useMediaQuery } from "../hooks/useMediaQuery"; +import { useTheme } from "../hooks/useTheme"; +import { useLayoutPane } from "../layout/layoutPaneContext"; +import { observeResize } from "../lib/observeResize"; import { cn } from "../lib/utils"; +import { holdEndCornerWhileSliding } from "../motion/paneMotion"; /** * A tab in the notch (pen N1JIfM): 28px, r8, 10px sides, 7px from the icon to @@ -11,8 +15,16 @@ import { cn } from "../lib/utils"; * tooltips keep working in Electron. The focus ring is inset because the tab * sits on the pane edge, where the pane clip would cut an outer ring. */ -export const PANE_TAB_CLASS = +export const PANE_TAB_SHAPE_CLASS = "inline-flex h-7 min-w-0 max-w-80 items-center gap-1.75 rounded-control px-2.5 text-control text-strong-foreground outline-none [-webkit-app-region:no-drag] focus-visible:inset-ring-2 focus-visible:inset-ring-ring"; +export const PANE_TAB_CLASS = `${PANE_TAB_SHAPE_CLASS} surface-pane-tab`; + +export const PANE_TAB_TITLE_CLASS = "max-w-68 truncate"; +/** The connected pane tabs widen it to the active title's, so activating a tab moves nothing. */ +export const PANE_INACTIVE_TAB_TITLE_CLASS = + "max-w-[var(--pane-inactive-tab-title-max,10rem)] truncate"; +/** A ghost tab's title (`LayoutTab.ghostOf`): italic until the tab is kept, as preview tabs are. */ +export const PANE_GHOST_TAB_TITLE_CLASS = "italic pe-0.5 -me-0.5"; /** The thread tab opens its action menu while keeping the notch's tab geometry. */ export function PaneTabButton({ className, render, ...props }: useRender.ComponentProps<"button">) { @@ -24,7 +36,7 @@ export function PaneTabButton({ className, render, ...props }: useRender.Compone type: render ? undefined : "button", className: cn( PANE_TAB_CLASS, - "cursor-pointer text-left hover:surface-ghost-hover", + "cursor-pointer text-left hover:surface-ghost-hover group-hover/tab:surface-ghost-hover", className, ), }, @@ -33,20 +45,184 @@ export function PaneTabButton({ className, render, ...props }: useRender.Compone }); } -/** Render first in a positioned pane header; index.css paints the notch on inset panes. - * The final child may use data-pane-notch-add to retain tab-end padding without a surface. +/** + * The body under a pane header that has no surface of its own (a surface tab's, + * the launcher's, Settings'): it may reach up under the header by + * --pane-surface-reach (see [data-surface-reaches-under-header] in index.css), + * and stays a layer below it whatever its own z-indexes. */ -export function PaneNotch({ children }: { readonly children: ReactNode }) { +export const PANE_BODY_UNDER_HEADER_CLASS = + "isolate [--pane-surface-reach:var(--pane-header-overlap,0px)]"; + +// Notches inside each pane or inset. index.css squares the corner of a host +// marked data-pane-notched; matching hosts with :has([data-pane-notch]) +// instead had the browser recheck their whole subtree on every DOM change. +const notchCounts = { + left: new WeakMap(), + right: new WeakMap(), +}; + +function markNotchHost(host: Element | null, side: "left" | "right"): () => void { + if (!host) return () => {}; + const counts = notchCounts[side]; + const attribute = side === "left" ? "data-pane-notched" : "data-pane-notched-right"; + counts.set(host, (counts.get(host) ?? 0) + 1); + host.setAttribute(attribute, ""); + return () => { + const count = (counts.get(host) ?? 1) - 1; + counts.set(host, count); + if (count === 0) host.removeAttribute(attribute); + }; +} + +/* ── The notch: light, black chrome only. Elsewhere the row is a bar and the + tabs join the pane there (index.css, connected pane tabs). Close notches of + one header merge into one chrome row. ── */ +const PANE_NOTCH_MERGE_MARGIN_PX = 4; +const notchHeaders = new WeakMap< + HTMLElement, + { + readonly notches: Map; + readonly refresh: () => void; + } +>(); + +/** One subscription per header, including breakpoint-switched controls. */ +function observeNotchGap(notch: HTMLDivElement, side: "left" | "right"): () => void { + const header = notch.closest("[data-pane-header]"); + if (!header) return () => {}; + let registration = notchHeaders.get(header); + if (!registration) { + const notches = new Map(); + let stopObserving = () => {}; + const update = () => { + let left: HTMLDivElement | undefined; + let right: HTMLDivElement | undefined; + for (const [element, notchSide] of notches) { + if (element.offsetWidth === 0) continue; + if (notchSide === "left") left = element; + else right = element; + } + let merged = false; + if (left && right) { + const leftRect = left.getBoundingClientRect(); + const rightRect = right.getBoundingClientRect(); + // The pseudo-element resolves --pane-notch-tail to pixels, including rem sizing. + const tail = Number.parseFloat(getComputedStyle(left, "::after").width); + const mergeGap = 2 * tail + PANE_NOTCH_MERGE_MARGIN_PX; + // Compare in layout pixels even when the overview scales the pane. + const scale = leftRect.width / left.offsetWidth; + merged = scale > 0 && (rightRect.left - leftRect.right) / scale < mergeGap; + } + if (header.hasAttribute("data-pane-notches-merged") !== merged) { + header.toggleAttribute("data-pane-notches-merged", merged); + } + }; + const refresh = () => { + stopObserving(); + const sides = new Set(notches.values()); + // Header resizing moves fixed-width notches without resizing either notch. + stopObserving = + sides.size === 2 ? observeResize([header, ...notches.keys()], update) : () => {}; + update(); + }; + registration = { notches, refresh }; + notchHeaders.set(header, registration); + } + const { notches, refresh } = registration; + notches.set(notch, side); + refresh(); + return () => { + notches.delete(notch); + refresh(); + if (notches.size === 0) notchHeaders.delete(header); + }; +} + +/** + * Whether pane tabs sit on a bar and the active one joins its pane (index.css, + * connected pane tabs): from md up, except under light, black chrome, which + * keeps the notch. + */ +function useConnectedPaneTabs(): boolean { + const isMobile = useMediaQuery("max-md"); + const { blackChrome, resolvedTheme } = useTheme(); + return !isMobile && !(blackChrome && resolvedTheme === "light"); +} + +/** Render first inside a positioned pane header starting at the pane edge. Keep the plus last so the + * notch includes its trailing padding. */ +export function PaneNotch({ + children, + side = "left", + marksHost = true, + className, +}: { + readonly children: ReactNode; + readonly side?: "left" | "right"; + /** Off for a notch drawn where it cannot show (a hidden overview thumbnail). */ + readonly marksHost?: boolean; + readonly className?: string; +}) { // The tab sits on the window chrome where the notch shows, so light, black // chrome gives it the dark tokens there (index.css). const isMobile = useMediaQuery("max-md"); + // Only the notch has two ends that may merge; the bar spans the row. + const connected = useConnectedPaneTabs(); + const notchRef = useRef(null); + const { split, focused, visible } = useLayoutPane(); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Mark the mounted notch ancestors and remove those external DOM markers on cleanup. + useLayoutEffect(() => { + const notch = notchRef.current; + if (!notch || !marksHost || !visible) return; + const unmarkPane = markNotchHost( + notch.closest( + side === "right" ? "[data-layout-tab-id], [data-pane-notch-host]" : "[data-layout-tab-id]", + ), + side, + ); + const unmarkInset = markNotchHost(notch.closest('[data-slot="sidebar-inset"]'), side); + return () => { + unmarkPane(); + unmarkInset(); + }; + }, [marksHost, side, visible]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Observe the notch DOM gap before paint and stop observing when its host changes. + useLayoutEffect(() => { + const notch = notchRef.current; + if (!notch || !marksHost || isMobile || connected) return; + return observeNotchGap(notch, side); + }, [connected, isMobile, marksHost, side]); return ( <> - + + {side === "left" ? ( + <> + + + + ) : null}
[data-pane-notch-add]]:pe-3.5" + : "md:ps-(--pane-notch-tail)", + className, + )} > {children}
diff --git a/apps/web/src/components/PanelTabBreadcrumb.browser.test.tsx b/apps/web/src/components/PanelTabBreadcrumb.browser.test.tsx new file mode 100644 index 0000000000000..674dcf6648151 --- /dev/null +++ b/apps/web/src/components/PanelTabBreadcrumb.browser.test.tsx @@ -0,0 +1,63 @@ +import { useState, type ReactNode } from "react"; +import { expect, it } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { + PanelTabActions, + PanelTabSlotsContext, + usePanelTabActionsHost, +} from "./PanelTabBreadcrumb"; + +function TabBar({ children }: { children: ReactNode }) { + const { hasActions, registerActions } = usePanelTabActionsHost(); + const [actions, setActions] = useState(null); + return ( + <> + {hasActions ?
: null} + + {children} + + + ); +} + +function Surface({ actions }: { actions: readonly string[] }) { + return actions.map((label) => ( + + + + )); +} + +it("draws the actions notch only while a surface provides actions", async () => { + await using screen = await render( + + + , + { router: false }, + ); + const notch = screen.getByTestId("actions-notch"); + await expect.element(notch).not.toBeInTheDocument(); + + await screen.rerender( + + + , + ); + await expect.element(notch.getByRole("button", { name: "Wrap" })).toBeVisible(); + await expect.element(notch.getByRole("button", { name: "Refresh" })).toBeVisible(); + + await screen.rerender( + + + , + ); + await expect.element(notch.getByRole("button", { name: "Refresh" })).toBeVisible(); + + await screen.rerender( + + + , + ); + await expect.element(notch).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/PanelTabBreadcrumb.tsx b/apps/web/src/components/PanelTabBreadcrumb.tsx new file mode 100644 index 0000000000000..dd7c2347816dc --- /dev/null +++ b/apps/web/src/components/PanelTabBreadcrumb.tsx @@ -0,0 +1,54 @@ +import { createContext, useContext, useLayoutEffect, useState, type ReactNode } from "react"; +import { createPortal } from "react-dom"; + +/** Header action slots shared by terminal and side chat surfaces. */ +export interface PanelTabSlots { + readonly breadcrumb: HTMLElement | null; + readonly actions: HTMLElement | null; + readonly registerActions: () => () => void; +} + +export const PanelTabSlotsContext = createContext(null); + +/** + * Whether the surface renders inside a panel tab bar, which then carries its + * actions. A surface drops its own header row when it does. + */ +export function useInPanelTabBar(): boolean { + return useContext(PanelTabSlotsContext) !== null; +} + +export function usePanelTabActionsHost(): { + hasActions: boolean; + registerActions: () => () => void; +} { + const [count, setCount] = useState(0); + const registerActions = () => { + setCount((current) => current + 1); + return () => setCount((current) => current - 1); + }; + return { hasActions: count > 0, registerActions }; +} + +function PanelTabPortal({ + slot, + children, +}: { + slot: "breadcrumb" | "actions"; + children: ReactNode; +}) { + const slots = useContext(PanelTabSlotsContext); + if (!slots) return children; + const element = slots[slot]; + return element ? createPortal(children, element) : null; +} + +/** + * Surface actions render at the end of the tab row, or in place outside it. + */ +export function PanelTabActions({ children }: { children: ReactNode }) { + const registerActions = useContext(PanelTabSlotsContext)?.registerActions; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Tell the tab bar before paint, so its actions notch never draws empty. + useLayoutEffect(() => registerActions?.(), [registerActions]); + return {children}; +} diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsx deleted file mode 100644 index 5b1e75f573f44..0000000000000 --- a/apps/web/src/components/PersistentThreadTerminals.tsx +++ /dev/null @@ -1,386 +0,0 @@ -import { - AuthTerminalOperateScope, - type EnvironmentId, - type ResolvedKeybindingsConfig, - type ScopedThreadRef, - type ThreadId, -} from "@t3tools/contracts"; -import { useMessages } from "gt-react"; -import { - resolveTerminalActivityStatus, - type TerminalActivityStatus, -} from "@t3tools/client-runtime/state/terminal"; -import { scopeProjectRef } from "@t3tools/client-runtime/environment"; -import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; -import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabelsCopy"; -import { memo, useEffect } from "react"; -import { useComposerDraftStore } from "../composerDraftStore"; -import { useStableCallback } from "../hooks/useStableCallback"; -import type { TerminalContextSelection } from "../lib/terminalContext"; -import { focusActiveDrawerTerminal, focusTerminal } from "../lib/terminalFocus"; -import { cn } from "~/lib/utils"; -import { - selectThreadRightPanelState, - useRightPanelStore, - type RightPanelSurface, -} from "../rightPanelStore"; -import { useProject, useQuietThreadShell } from "../state/entities"; -import { useEnvironmentScope } from "../state/session"; -import { useKnownTerminalSessions, useTerminalDrawerSessions } from "../state/terminalSessions"; -import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; -import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions"; -import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; -import { resolveTerminalWorktreePath } from "./ChatView.logic"; - -/** Where a drawer or panel opens new terminals when a script run overrides the thread's own. */ -export type PersistentTerminalLaunchContext = { - readonly cwd: string; - readonly worktreePath: string | null; -}; - -interface TerminalLaunchLocationWithEnv { - readonly cwd: string; - readonly worktreePath: string | null; - readonly runtimeEnv: Record; -} - -interface PersistentThreadTerminalDrawerProps { - threadRef: { environmentId: EnvironmentId; threadId: ThreadId }; - threadId: ThreadId; - active: boolean; - composerHeight: number; - launchContext: PersistentTerminalLaunchContext | null; - splitShortcutLabel: string | undefined; - splitVerticalShortcutLabel: string | undefined; - newShortcutLabel: string | undefined; - closeShortcutLabel: string | undefined; - keybindings: ResolvedKeybindingsConfig; - onAddTerminalContext: (selection: TerminalContextSelection) => void; -} - -export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDrawer({ - threadRef, - threadId, - active, - composerHeight, - launchContext, - splitShortcutLabel, - splitVerticalShortcutLabel, - newShortcutLabel, - closeShortcutLabel, - keybindings, - onAddTerminalContext, -}: PersistentThreadTerminalDrawerProps) { - const messages = useMessages(); - const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope); - const terminalActions = useThreadTerminalActions(threadRef); - const serverThread = useQuietThreadShell(threadRef); - const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); - const projectRef = serverThread - ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) - : draftThread - ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) - : null; - const project = useProject(projectRef); - const terminalUiState = useTerminalUiStateStore((state) => - selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef), - ); - const visible = active && terminalUiState.terminalOpen; - const metadata = useTerminalDrawerSessions(threadRef.environmentId, threadId); - const knownTerminalSessions = metadata?.sessions; - const snapshotId = metadata?.snapshotId; - const panelSurfaces = useRightPanelStore( - (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces, - ); - const panelTerminalIds = new Set( - panelSurfaces.flatMap((surface) => (surface.kind === "terminal" ? surface.terminalIds : [])), - ); - const drawerTerminalSessions = - knownTerminalSessions?.filter((session) => !panelTerminalIds.has(session.target.terminalId)) ?? - []; - const terminalLabelsById = new Map(); - for (const session of drawerTerminalSessions) { - terminalLabelsById.set( - session.target.terminalId, - resolveTerminalSessionLabel(session.target.terminalId, session.state.summary, messages), - ); - } - const terminalStatusById = new Map(); - for (const session of drawerTerminalSessions) { - terminalStatusById.set(session.target.terminalId, resolveTerminalActivityStatus(session.state)); - } - const terminalLaunchLocationsById = new Map(); - for (const session of drawerTerminalSessions) { - const summary = session.state.summary; - if (!project || !summary) continue; - const worktreePathForLaunch = - launchContext !== null ? launchContext.worktreePath : summary.worktreePath; - terminalLaunchLocationsById.set(session.target.terminalId, { - cwd: launchContext?.cwd ?? summary.cwd, - worktreePath: worktreePathForLaunch, - runtimeEnv: projectScriptRuntimeEnv({ - project: { cwd: project.workspaceRoot }, - worktreePath: worktreePathForLaunch, - }), - }); - } - const serverOrderedTerminalIds = drawerTerminalSessions.map( - (session) => session.target.terminalId, - ); - const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight); - const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal); - const storeSplitTerminalVertical = useTerminalUiStateStore( - (state) => state.splitTerminalVertical, - ); - const storeNewTerminal = useTerminalUiStateStore((state) => state.newTerminal); - const storeSetActiveTerminal = useTerminalUiStateStore((state) => state.setActiveTerminal); - const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal); - const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- feeds the server's terminal list into the terminal UI store, which owns how local ids follow it - useEffect(() => { - if (snapshotId === undefined) return; - reconcileTerminalIds(threadRef, serverOrderedTerminalIds, snapshotId); - }, [reconcileTerminalIds, serverOrderedTerminalIds, snapshotId, threadRef]); - const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; - const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath; - const cwd = - launchContext?.cwd ?? - (project - ? projectScriptCwd({ - project: { cwd: project.workspaceRoot }, - worktreePath: effectiveWorktreePath, - }) - : null); - const runtimeEnv = project - ? projectScriptRuntimeEnv({ - project: { cwd: project.workspaceRoot }, - worktreePath: effectiveWorktreePath, - }) - : {}; - - const setTerminalHeight = (height: number) => { - storeSetTerminalHeight(threadRef, height); - }; - - const launchDrawerTerminal = (place: (terminalId: string) => void) => { - if (!cwd) return; - const launched = terminalActions.launchTerminal({ - place, - location: { cwd, worktreePath: effectiveWorktreePath }, - }); - if (!launched) return; - if (visible) focusTerminal(threadRef, launched.terminalId); - void launched.result; - }; - const splitTerminal = useStableCallback(() => - launchDrawerTerminal((terminalId) => storeSplitTerminal(threadRef, terminalId)), - ); - const splitTerminalVertical = useStableCallback(() => - launchDrawerTerminal((terminalId) => storeSplitTerminalVertical(threadRef, terminalId)), - ); - const createNewTerminal = useStableCallback(() => - launchDrawerTerminal((terminalId) => storeNewTerminal(threadRef, terminalId)), - ); - - const activateTerminal = (terminalId: string) => { - storeSetActiveTerminal(threadRef, terminalId); - if (visible) focusTerminal(threadRef, terminalId); - }; - - const closeTerminal = useStableCallback((terminalId: string) => { - if (!terminalActions.canWrite()) return; - terminalActions.closeTerminalSession(terminalId); - storeCloseTerminal(threadRef, terminalId); - if (visible) focusActiveDrawerTerminal(threadRef); - }); - - const handleAddTerminalContext = (selection: TerminalContextSelection) => { - if (!visible) { - return; - } - onAddTerminalContext(selection); - }; - - if (!project || (!terminalUiState.terminalOpen && !active) || !cwd) { - return null; - } - - return ( -
-
- -
-
- ); -}); - -export interface PersistentThreadTerminalPanelProps { - visible: boolean; - threadRef: ScopedThreadRef; - surface: Extract; - launchContext: PersistentTerminalLaunchContext | null; - keybindings: ResolvedKeybindingsConfig; - onAddTerminalContext: (selection: TerminalContextSelection) => void; - onSplitTerminal: () => void; - onSplitTerminalVertical: () => void; - onNewTerminal: () => void; - onActiveTerminalChange: (terminalId: string) => void; - onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; - splitShortcutLabel?: string | undefined; - splitVerticalShortcutLabel?: string | undefined; - newShortcutLabel?: string | undefined; - closeShortcutLabel?: string | undefined; -} - -export const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPanel({ - visible, - threadRef, - surface, - launchContext, - keybindings, - onAddTerminalContext, - onSplitTerminal, - onSplitTerminalVertical, - onNewTerminal, - onActiveTerminalChange, - onCloseTerminal, - splitShortcutLabel, - splitVerticalShortcutLabel, - newShortcutLabel, - closeShortcutLabel, -}: PersistentThreadTerminalPanelProps) { - const messages = useMessages(); - const serverThread = useQuietThreadShell(threadRef); - const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); - const projectRef = serverThread - ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) - : draftThread - ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) - : null; - const project = useProject(projectRef); - const knownTerminalSessions = useKnownTerminalSessions({ - environmentId: threadRef.environmentId, - threadId: threadRef.threadId, - }); - const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; - const activeSummary = - knownTerminalSessions?.find((session) => session.target.terminalId === surface.activeTerminalId) - ?.state.summary ?? null; - const worktreePath = resolveTerminalWorktreePath({ - launchContext, - summary: activeSummary, - threadWorktreePath, - }); - const cwd = - launchContext?.cwd ?? - activeSummary?.cwd ?? - (project ? projectScriptCwd({ project: { cwd: project.workspaceRoot }, worktreePath }) : null); - const runtimeEnv = project - ? projectScriptRuntimeEnv({ project: { cwd: project.workspaceRoot }, worktreePath }) - : {}; - const terminalLabelsById = new Map(); - const terminalLaunchLocationsById = new Map(); - for (const terminalId of surface.terminalIds) { - const summary = - knownTerminalSessions?.find((session) => session.target.terminalId === terminalId)?.state - .summary ?? null; - terminalLabelsById.set(terminalId, resolveTerminalSessionLabel(terminalId, summary, messages)); - if (!project) continue; - const terminalWorktreePath = resolveTerminalWorktreePath({ - launchContext, - summary, - threadWorktreePath, - }); - terminalLaunchLocationsById.set(terminalId, { - cwd: - launchContext?.cwd ?? - summary?.cwd ?? - projectScriptCwd({ - project: { cwd: project.workspaceRoot }, - worktreePath: terminalWorktreePath, - }), - worktreePath: terminalWorktreePath, - runtimeEnv: projectScriptRuntimeEnv({ - project: { cwd: project.workspaceRoot }, - worktreePath: terminalWorktreePath, - }), - }); - } - - if (!project || !cwd) return null; - - return ( - undefined} - onAddTerminalContext={onAddTerminalContext} - terminalLabelsById={terminalLabelsById} - terminalLaunchLocationsById={terminalLaunchLocationsById} - keybindings={keybindings} - /> - ); -}); diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index 7097de41e7af8..b292a6a33b24b 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -64,6 +64,7 @@ import { MenuSubPopup, } from "./ui/menu"; import { stackedThreadToast, toastManager } from "./ui/toast"; +import { StatusDot } from "./ui/status-dot"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; export type { NewProjectScriptInput, ProjectScriptActionResult }; @@ -455,9 +456,10 @@ export default function ProjectScriptsControl({ )} ) : isPanel ? ( -
+
{primaryScript ? ( onRunScript?.(primaryScript)} @@ -465,13 +467,15 @@ export default function ProjectScriptsControl({ {runningScriptServer ? ( - + + + ) : null} {primaryScript.name} ) : ( - + Add project action… @@ -479,21 +483,28 @@ export default function ProjectScriptsControl({ )} {supportsStop && runningScriptServer?.pid != null ? ( - { - setStoppingServer(true); - await stopServer({ - environmentId, - input: { pid: runningScriptServer.pid!, port: runningScriptServer.port }, - }); - setStoppingServer(false); - }} - > - - + + { + setStoppingServer(true); + await stopServer({ + environmentId, + input: { pid: runningScriptServer.pid!, port: runningScriptServer.port }, + }); + setStoppingServer(false); + }} + /> + } + > + + + {gt("Stop {name}", { name: primaryScript?.name ?? "" })} + ) : null} - } - > - - + + } + /> + } + > + + + + Project actions + + {scriptItems} diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx b/apps/web/src/components/ProviderUpdateLaunchNotification.tsx deleted file mode 100644 index 16d2dfaccba32..0000000000000 --- a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import { useAtomValue } from "@effect/atom-react"; -import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; -import { msg } from "gt-react"; -import { useEffect, useRef } from "react"; - -import { writeTextToClipboard } from "../hooks/useCopyToClipboard"; -import { m } from "../i18n/messages"; -import { primaryServerProvidersAtom } from "../state/server"; -import { CommandBlock } from "./CommandBlock"; -import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon"; -import { - collectProviderUpdateCandidates, - isProviderUpdateActive, -} from "./ProviderUpdateLaunchNotification.logic"; -import { toastManager } from "./ui/toast"; - -/** Announce each available provider version once per client session, using the server's command. */ -export function ProviderUpdateLaunchNotification() { - const providers = useAtomValue(primaryServerProvidersAtom); - const shown = useRef(new Set()); - const notices = useRef(new Map>()); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reconciles server version advisories with the external toast manager - useEffect(() => { - const candidates = collectProviderUpdateCandidates(providers).filter( - (provider) => !isProviderUpdateActive(provider), - ); - const active = new Set( - candidates.map((provider) => `${provider.driver}:${provider.versionAdvisory.latestVersion}`), - ); - for (const [key, id] of notices.current) { - if (!active.has(key)) { - toastManager.close(id); - notices.current.delete(key); - } - } - for (const provider of candidates) { - const advisory = provider.versionAdvisory; - const key = `${provider.driver}:${advisory.latestVersion}`; - const command = advisory.updateCommand; - if (shown.current.has(key) || command === null) continue; - shown.current.add(key); - const name = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver; - const current = advisory.currentVersion ?? provider.version; - notices.current.set( - key, - toastManager.add({ - type: "info", - title: m( - msg("{provider} {version} is available", { - provider: name, - version: advisory.latestVersion, - }), - ), - description: current - ? m( - msg("You''re on {version}. New sessions will use the updated provider.", { - version: current, - }), - ) - : m(msg("New sessions will use the updated provider.")), - timeout: 0, - actionProps: { - children: m(msg("Copy update command")), - onClick: () => { - void writeTextToClipboard(command, { - target: "update command", - unavailableMessage: msg( - "Clipboard API is unavailable while copying update command.", - ), - failureMessage: msg("Failed to copy update command to the clipboard."), - }); - }, - }, - data: { - variant: "notification", - leadingIcon: ( - - ), - body: , - }, - }), - ); - } - }, [providers]); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- removes this coordinator's external notices when its authenticated shell unmounts - useEffect(() => { - const owned = notices.current; - return () => { - for (const id of owned.values()) toastManager.close(id); - }; - }, []); - return null; -} diff --git a/apps/web/src/components/RelativeTime.tsx b/apps/web/src/components/RelativeTime.tsx index f559b4a48d8c2..08b2b6e9dc92d 100644 --- a/apps/web/src/components/RelativeTime.tsx +++ b/apps/web/src/components/RelativeTime.tsx @@ -1,8 +1,6 @@ -import { useRelativeTimeState } from "../hooks/useRelativeTimeState"; +import { useRelativeTimeLabel } from "../hooks/useRelativeTimeState"; // Use a live clock because the compiler caches inline formatting on the timestamp. export function RelativeTime(props: { timestamp: string }) { - const relative = useRelativeTimeState(props.timestamp); - if (relative.status !== "relative") return null; - return relative.label; + return useRelativeTimeLabel(props.timestamp); } diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 2b3e9bfb96c14..da956479ba2b9 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -157,6 +157,33 @@ function press(target: Element = document.body) { } describe("root reopen shortcut", () => { + it.each(["dialog", "alert-dialog", "app"])("yields to an open %s modal", async (kind) => { + setup(); + const entry = useClosedViewStore + .getState() + .remember({ kind: "browser", threadRef: ref, snapshot }); + state.openPreview.mockResolvedValue(AsyncResult.success({ ...snapshot, tabId: "new-tab" })); + await using view = await renderShortcut(); + const modal = view.append(document.createElement("div")); + if (kind === "app") modal.setAttribute("data-app-modal", ""); + else { + modal.setAttribute("data-slot", `${kind}-popup`); + modal.setAttribute("data-open", ""); + } + await act(() => { + press(modal); + menuAction?.("view.reopenClosed"); + }); + expect(state.openPreview).not.toHaveBeenCalled(); + expect(useClosedViewStore.getState().entries.map((item) => item.id)).toEqual([entry]); + modal.remove(); + await act(() => { + press(); + }); + expect(state.openPreview).toHaveBeenCalledOnce(); + expect(useClosedViewStore.getState().entries).toEqual([]); + }); + it.each([ { action: "switch routes", goBack: false, expectedPath: "/newer" }, { action: "leave and return", goBack: true, expectedPath: "/" }, @@ -358,19 +385,15 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }, ); - it("forwards address-bar focus, zoom, and panel new and close from a focused desktop page", async () => { + // The layout host forwards tab close and new tab from a focused page as key chords. + it("forwards address-bar focus and zoom from a focused desktop page", async () => { setup(); await using _shortcut = await renderShortcut(); expect(state.setShortcuts).toHaveBeenLastCalledWith( expect.arrayContaining( - [ - "preview.focusUrl", - "preview.zoomIn", - "preview.zoomOut", - "preview.resetZoom", - "rightPanel.new", - "rightPanel.close", - ].map((command) => expect.objectContaining({ command })), + ["preview.focusUrl", "preview.zoomIn", "preview.zoomOut", "preview.resetZoom"].map( + (command) => expect.objectContaining({ command }), + ), ), ); }); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 788aa5e127a06..2be3c38152730 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -17,11 +17,13 @@ import { useComposerDraftStore } from "../composerDraftStore"; import { environmentCatalog } from "../connection/catalog"; import { effectiveShortcutsForCommand, resolveShortcutCommand } from "../keybindings"; import { isEditableFocused } from "../lib/editableFocus"; +import { isModalDialogOpen } from "../lib/modalDialog"; import { isPreviewFocused } from "../lib/previewFocus"; import { isTerminalFocused } from "../lib/terminalFocus"; import { isModelPickerOpen } from "../modelPickerVisibility"; import { planNextReopen, + closedChatTarget, pullRequestsSearchForRestore, reopenClosedView, } from "../reopenClosedView"; @@ -41,6 +43,11 @@ import { primaryServerKeybindingsAtom } from "../state/server"; import { environmentShell } from "../state/shell"; import { useAtomCommand } from "../state/use-atom-command"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; +import { + isThreadlessSurfacesRef, + readThreadlessHome, + threadlessSurfacesProjectRef, +} from "../threadlessSurfaces"; import { buildDraftThreadRouteParams, buildThreadRouteParams, @@ -48,6 +55,9 @@ import { } from "../threadRoutes"; import { toastManager } from "./ui/toast"; import { readIssueListPreferences } from "./issue/issueListPreferences"; +import { findLayoutTabByContent, isLayoutPageContent } from "../layout/layoutModel"; +import { useLayoutStore } from "../layout/layoutStore"; +import { layoutPageHref } from "../layout/pageNavigation"; declare module "@tanstack/react-router" { interface HistoryState { @@ -59,9 +69,6 @@ const PREVIEW_FORWARDED_COMMANDS = [ "workspace.focusNext", "workspace.focusPrevious", "sidebar.toggle", - "rightPanel.toggle", - "rightPanel.new", - "rightPanel.close", "preview.focusUrl", "preview.zoomIn", "preview.zoomOut", @@ -120,10 +127,18 @@ export function ReopenClosedViewShortcut() { panel, }; } + // A threadless surface's owner is its project, or nothing to lose. + const threadlessProject = threadlessSurfacesProjectRef(ref); return { environmentKnown: catalog.entries.has(ref.environmentId), catalogReady: catalog.isReady, - ownerExists: readThreadShell(ref) !== null || drafts.getDraftThreadByRef(ref) !== null, + ownerExists: isThreadlessSurfacesRef(ref) + ? threadlessProject === null || readProject(threadlessProject) !== null + : readThreadShell(ref) !== null || + drafts.getDraftThreadByRef(ref) !== null || + (entry.kind === "chat" && + entry.draftId !== undefined && + drafts.getDraftSession(entry.draftId) !== null), sideChatExists: entry.kind !== "panel-tab" || entry.surface.kind !== "thread" || @@ -144,16 +159,41 @@ export function ReopenClosedViewShortcut() { const globalIssues = isGlobalIssues(ref); const thread = globalPullRequests || globalIssues ? null : readThreadShell(ref); const owner = thread ?? drafts.getDraftThreadByRef(ref); - const project = owner ? readProject(scopeProjectRef(ref.environmentId, owner.projectId)) : null; - if (!(await reopenClosedView(restore, { openPreview, workspaceAvailable: project !== null }))) { + const ownerProject = owner + ? scopeProjectRef(ref.environmentId, owner.projectId) + : threadlessSurfacesProjectRef(ref); + const project = ownerProject ? readProject(ownerProject) : null; + // A project-less threadless ref's files are the server's home. + const workspaceAvailable = project !== null || readThreadlessHome(ref) !== null; + if (!(await reopenClosedView(restore, { openPreview, workspaceAvailable }))) { useClosedViewStore.getState().defer(restore.id); return; } useClosedViewStore.getState().remove(restore.id); if (router.history.location !== request.location) return; + if (restore.kind === "page") { + const content = findLayoutTabByContent(useLayoutStore.getState().layout, { + kind: restore.page, + })?.tab.content; + if (content && isLayoutPageContent(content)) + await navigate({ href: layoutPageHref(content) }); + return; + } let destination; - if (globalPullRequests) { + if (restore.kind === "chat") { + const target = closedChatTarget(restore); + destination = + target.kind === "draft" + ? linkOptions({ + to: "/draft/$draftId", + params: buildDraftThreadRouteParams(target.draftId), + }) + : linkOptions({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(target.threadRef), + }); + } else if (globalPullRequests) { const selected = selectSelectedRightPanelSurface( useRightPanelStore.getState().byThreadKey, ref, @@ -164,6 +204,9 @@ export function ReopenClosedViewShortcut() { }); } else if (globalIssues) { destination = linkOptions({ to: "/issues", search: readIssueListPreferences() }); + } else if (isThreadlessSurfacesRef(ref)) { + // A threadless surface has no route; its tab shows it. + return; } else { const draftId = thread === null ? drafts.getDraftIdByRef(ref) : null; destination = @@ -218,6 +261,7 @@ export function ReopenClosedViewShortcut() { if ( event.defaultPrevented || isCommandPaletteOpen() || + isModalDialogOpen() || useClosedViewStore.getState().entries.length === 0 || (event.target instanceof HTMLElement && event.target.closest("[data-keybinding-capture]")) ) @@ -239,7 +283,8 @@ export function ReopenClosedViewShortcut() { }; window.addEventListener("keydown", onKeyDown, true); const unsubscribe = window.desktopBridge?.onMenuAction((action) => { - if (action === "view.reopenClosed" && !isCommandPaletteOpen()) enqueueReopen(); + if (action === "view.reopenClosed" && !isCommandPaletteOpen() && !isModalDialogOpen()) + enqueueReopen(); }); return () => { window.removeEventListener("keydown", onKeyDown, true); diff --git a/apps/web/src/components/RightPanelSheet.browser.test.tsx b/apps/web/src/components/RightPanelSheet.browser.test.tsx deleted file mode 100644 index c99e1e218b41c..0000000000000 --- a/apps/web/src/components/RightPanelSheet.browser.test.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { expect, it } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; - -import { render } from "../../test/render"; -import { RightPanelSheet } from "./RightPanelSheet"; - -it("names the open right-panel dialog", async () => { - await using _screen = await render( - {}}> -
Panel content
-
, - ); - const dialog = page.getByRole("dialog"); - await expect.element(dialog).toBeVisible(); - await expect.element(dialog).not.toHaveAccessibleName(""); -}); diff --git a/apps/web/src/components/RightPanelSheet.tsx b/apps/web/src/components/RightPanelSheet.tsx deleted file mode 100644 index d12ea9508198b..0000000000000 --- a/apps/web/src/components/RightPanelSheet.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { T } from "gt-react"; -import { type ReactNode } from "react"; - -import { Sheet, SheetHeader, SheetPopup, SheetTitle } from "./ui/sheet"; - -export function RightPanelSheet(props: { - animationDurationMs: number; - children: ReactNode; - open: boolean; - onClose: () => void; -}) { - return ( - { - if (!open) { - props.onClose(); - } - }} - > - - - - Workspace panel - - - {props.children} - - - ); -} diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index 347971993c7c3..1f8c56d53f26f 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -68,79 +68,81 @@ const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ( })); describe("RightPanelTabs", () => { - it("a flick that scrolls the tab strip to its left edge keeps the thread, and so does a swipe from the edge", async () => { - navigateHistory.mockReset(); - const { bridge, scroll } = trackpad(); - using _bridge = stubGlobal("desktopBridge", bridge); - using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); - const panel = document.createElement("div"); - panel.style.cssText = "width: 320px; height: 200px; display: flex"; - const noop = () => {}; - await using screen = await render( - <> - - ({ - terminalFocus: false, - terminalOpen: false, - previewFocus: false, - previewOpen: false, - isWeb: true, - isDesktop: false, - })} - surfaces={surfaces} - environmentId={null} - activeSurfaceId={null} - pendingSurfaceIds={new Set()} - previewSessions={{}} - desktopByTabId={{}} - terminalLabelsById={new Map(surfaces.map((surface) => [surface.id, "Terminal"]))} - onActivate={noop} - onCloseSurface={noop} - onCloseOtherSurfaces={noop} - onCloseSurfacesToRight={noop} - onCloseAllSurfaces={noop} - onCopyFilePath={noop} - onAddBrowser={noop} - onAddBrowserInProfile={noop} - onAddTerminal={noop} - onAddDiff={noop} - onAddFiles={noop} - onAddPullRequest={noop} - onAddPullRequests={noop} - onAddDevice={noop} - browserAvailable={false} - terminalAvailable - diffAvailable={false} - filesAvailable={false} - pullRequestAvailable={false} - pullRequestsAvailable={false} - deviceAvailable={false} - > - {null} - - , - { container: panel }, - ); - const viewport = screen.container.querySelector( - '[data-right-panel-tab-list] [data-slot="scroll-area-viewport"]', - )!; - expect(viewport.scrollWidth - viewport.clientWidth).toBeGreaterThan(120); - viewport.scrollLeft = 120; + it.each(["embedded", "inline"] as const)( + "%s: a flick that scrolls the tab strip to its left edge keeps the thread, and so does a swipe from the edge", + async (mode) => { + navigateHistory.mockReset(); + const { bridge, scroll } = trackpad(); + using _bridge = stubGlobal("desktopBridge", bridge); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + const panel = document.createElement("div"); + panel.style.cssText = "width: 320px; height: 200px; display: flex"; + const noop = () => {}; + await using screen = await render( + <> + + [surface.id, "Terminal"]))} + onActivate={noop} + onCloseSurface={noop} + onCloseOtherSurfaces={noop} + onCloseSurfacesToRight={noop} + onCloseAllSurfaces={noop} + onCopyFilePath={noop} + onAddBrowser={noop} + onAddBrowserInProfile={noop} + onAddTerminal={noop} + onAddDiff={noop} + onAddFiles={noop} + onAddPullRequest={noop} + onAddPullRequests={noop} + onAddDevice={noop} + browserAvailable={false} + terminalAvailable + diffAvailable={false} + filesAvailable={false} + pullRequestAvailable={false} + pullRequestsAvailable={false} + deviceAvailable={false} + > + {null} + + , + { container: panel }, + ); + const viewport = screen.container.querySelector( + '[data-layout-tab-strip], [data-right-panel-tab-list] [data-slot="scroll-area-viewport"]', + )!; + expect(viewport.scrollWidth - viewport.clientWidth).toBeGreaterThan(120); + if (mode === "inline") { + viewport.scrollLeft = 120; + await userEvent.wheel(screen.getByRole("button", { name: "Scroll tabs right" }), { + delta: { x: 40 }, + }); + await vi.waitFor(() => expect(viewport.scrollLeft).toBe(160)); + } + viewport.scrollLeft = 120; - const momentum = Array.from({ length: 24 }, (_, index) => -60 * 0.85 ** index); - scroll(viewport.querySelector("[data-active-tab]")!, [-10, -20, -30, ...momentum]); + const momentum = Array.from({ length: 24 }, (_, index) => -60 * 0.85 ** index); + scroll(viewport.querySelector("[data-active-tab]")!, [-10, -20, -30, ...momentum]); - expect(viewport.scrollLeft).toBe(0); - expect(navigateHistory).not.toHaveBeenCalled(); + expect(viewport.scrollLeft).toBe(0); + expect(navigateHistory).not.toHaveBeenCalled(); - viewport.scrollLeft = 0; - scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]); + viewport.scrollLeft = 0; + scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]); - expect(navigateHistory).not.toHaveBeenCalled(); - }); + expect(navigateHistory).not.toHaveBeenCalled(); + }, + ); }); const BROWSER_SURFACE: RightPanelSurface = { @@ -155,14 +157,6 @@ function panel(activeSurface: RightPanelSurface) { const props: RightPanelTabsProps = { mode: "inline", keybindings: [], - getShortcutContext: () => ({ - terminalFocus: false, - terminalOpen: false, - previewFocus: false, - previewOpen: true, - isWeb: true, - isDesktop: false, - }), surfaces: [BROWSER_SURFACE, DIFF_SURFACE], environmentId: EnvironmentId.make("environment-local"), activeSurfaceId: activeSurface.id, diff --git a/apps/web/src/components/RightPanelTabs.test.tsx b/apps/web/src/components/RightPanelTabs.test.tsx index 88793cce44850..65cb25c4c7372 100644 --- a/apps/web/src/components/RightPanelTabs.test.tsx +++ b/apps/web/src/components/RightPanelTabs.test.tsx @@ -1,11 +1,8 @@ import { EnvironmentId, type ThreadPullRequestLink } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { - resolvePullRequestTabLink, - surfaceShortcutActionForKey, - surfaceShortcutTargetsTypingContext, -} from "./RightPanelTabs"; +import { surfaceShortcutActionForKey, surfaceShortcutTargetsTypingContext } from "./RightPanelTabs"; +import { resolvePullRequestTabLink } from "./SurfaceTabIcon"; function shortcutEvent( key: string, diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index c273dfae5f061..7aa155bb6f49b 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1,33 +1,27 @@ -import { msg, T, useGT, useMessages } from "gt-react"; -import { m, type MessageResolver } from "../i18n/messages"; -import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; +import { useQuietThreadShell } from "~/state/entities"; +import { useLayoutPane, useLayoutPaneFocusedRef } from "../layout/layoutPaneContext"; +import { beginLayoutTabDrag } from "../layout/layoutDrag"; +import { useLayoutStore } from "../layout/layoutStore"; import { - threadRuntimeIsActive, - type EnvironmentThreadShell, -} from "@t3tools/client-runtime/state/shell"; -import { - useProjects, - useQuietThreadShell, - useServerConfigs, - useThreadShells, -} from "~/state/entities"; -import { - threadPullRequestKeysEqual, - visibleThreadPullRequests, -} from "@t3tools/client-runtime/thread-pull-requests"; + finishLayoutTabRename, + LayoutNewTabButton, + LayoutPaneTab, + LayoutPaneTabStrip, + showLayoutTabMenu, + tabMuteMenuItem, + useLayoutPaneSiblingTabs, + useLayoutTabLabel, + useLayoutTabRenameRequested, +} from "../layout/PaneTabs"; +import { findLayoutTab, type LayoutTab } from "../layout/layoutModel"; import type { ContextMenuItem, EnvironmentId, - IssueTrackerKind, PreviewSessionSnapshot, - ProjectId, - PullRequestState, ResolvedKeybindingsConfig, - ThreadId, } from "@t3tools/contracts"; -import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy"; -import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { closestCenter, DndContext, @@ -40,90 +34,95 @@ import { restrictToFirstScrollableAncestor, restrictToHorizontalAxis } from "@dn import { horizontalListSortingStrategy, SortableContext, useSortable } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { - Bot, - CircleDotIcon, - Smartphone, - ChevronDown, ChevronLeft, ChevronRight, - FileDiff, - Files, - Globe2, - MessagesSquare, + EllipsisIcon, Plus, - TerminalSquare, Volume2Icon, VolumeOffIcon, } from "lucide-react"; +import { msg, T, useGT, useMessages } from "gt-react"; + import { type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, - type ReactElement, type ReactNode, - useEffect, - useEffectEvent, + type Ref, useRef, useState, } from "react"; import { isElectron } from "~/env"; import type { DesktopPreviewOverlay } from "~/previewStateStore"; -import { linkedThreadTitle } from "~/linkedThreadSurface"; import type { RightPanelSurface } from "~/rightPanelStore"; import { cn } from "~/lib/utils"; -import { issueStatePresentation } from "~/components/issue/issuePresentation"; -import { issueEnvironment } from "~/state/issues"; -import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings"; import { readLocalApi } from "~/localApi"; import { useStableCallback } from "~/hooks/useStableCallback"; import { Button } from "~/components/ui/button"; -import { AndroidIcon, AppleIcon } from "~/components/Icons"; import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; -import { Kbd } from "~/components/ui/kbd"; -import { - Menu, - MenuItem, - MenuPopup, - MenuShortcut, - MenuSub, - MenuSubPopup, - MenuSubTrigger, - MenuTrigger, -} from "~/components/ui/menu"; +import { Menu, MenuPopup, MenuTrigger } from "~/components/ui/menu"; import { useBrowserDefaults } from "~/browser/browserDefaults"; import { ScrollArea } from "~/components/ui/scroll-area"; +import { scrollLeftByWheel, scrollTabStripFromRow } from "../motion/gesture"; import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button"; -import { faviconUrlForOrigin } from "@t3tools/shared/favicon"; import { useTheme } from "~/hooks/useTheme"; +import { useMediaQuery } from "~/hooks/useMediaQuery"; +import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { useDeviceState } from "~/state/device"; import type { PreviewPanelInlineSize } from "~/hooks/usePreviewPanelInlineSize"; +import { useRevealActiveTab } from "~/hooks/useRevealActiveTab"; import { - newestPullRequestSummary, - pullRequestEnvironment, - useSharedPullRequestSummary, -} from "~/state/pullRequests"; -import { useEnvironmentQuery } from "~/state/query"; -import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; + COLLAPSED_SIDEBAR_INSET_EASE_CLASS, + COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS, +} from "~/workspaceTitlebar"; import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell"; -import { FaviconImage } from "./preview/PreviewFaviconIcon"; +import { PanelTabSlotsContext, usePanelTabActionsHost } from "./PanelTabBreadcrumb"; +import { + PANE_BODY_UNDER_HEADER_CLASS, + PANE_INACTIVE_TAB_TITLE_CLASS, + PANE_TAB_TITLE_CLASS, + PaneNotch, +} from "./PaneNotch"; import { previewBridge } from "./preview/previewBridge"; import { dispatchPreviewAction } from "./preview/previewActionBus"; import { preventThumbButtonFocus, takeThumbButtonNavigation } from "./preview/thumbButtons"; -import { PierreEntryIcon } from "./chat/PierreEntryIcon"; -import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation"; -import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; -import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey"; +import { + previewFaviconOf, + SurfaceIcon, + surfaceTitle, + type PullRequestTabStatusSeed, +} from "./SurfaceTabIcon"; +import { + SurfaceLauncherRows, + SurfaceMenuItems, + surfaceMenuActions, + surfaceShortcutActionForKey, + useLauncherElement, + useSurfaceLauncherKeys, + type SurfaceLauncherAction, +} from "./SurfaceLauncher"; + +export { + surfaceShortcutActionForKey, + surfaceShortcutTargetsTypingContext, +} from "./SurfaceLauncher"; export interface RightPanelTabsProps { mode: PreviewPanelMode; maximized?: boolean; open?: boolean; keybindings: ResolvedKeybindingsConfig; - getShortcutContext: () => ShortcutMatchContext; widthStorageKey?: string; defaultWidth?: number; + /** + * An inline panel drawn as its own inset pane, notch and all, beside a page's pane (the + * pull requests page's review, pen bETcv). + */ + pane?: boolean; + /** The page's list is maximized away, so this pane's notch carries the layout pane's own tabs. */ + holdsPaneTabs?: boolean; inlineSize?: PreviewPanelInlineSize; layoutControls?: ReactNode; surfaces: readonly RightPanelSurface[]; @@ -147,10 +146,14 @@ export interface RightPanelTabsProps { onCloseAllSurfaces: () => void; onMoveSurface?: (surfaceId: string, toIndex: number) => void; onCopyFilePath: (relativePath: string) => void; + /** Escape on the empty pane's chooser closes the pane; the sheet closes itself. */ + onClose?: () => void; onDuplicateBrowser?: (surface: RightPanelSurface) => void; onAddBrowser: () => void; /** Keep separate from the DOM click handler so a MouseEvent cannot become a profile id. */ onAddBrowserInProfile: (profileId: string) => void; + /** The "+" menu's New thread, in the thread's project; omitted, it has none. */ + onNewThread?: (() => void) | undefined; onAddTerminal: () => void; onAddDiff: () => void; onAddFiles: () => void; @@ -160,6 +163,8 @@ export interface RightPanelTabsProps { /** Absent where side chats are not offered. */ onAddSideChat?: (() => void) | undefined; browserAvailable: boolean; + /** Why the browser cannot open, when it cannot. */ + browserUnavailableReason?: string | null; terminalAvailable: boolean; diffAvailable: boolean; filesAvailable: boolean; @@ -170,23 +175,11 @@ export interface RightPanelTabsProps { /** Overrides the default reason while side chats are available but cannot start. */ sideChatDisabledReason?: string | null; pullRequestStatusSeeds?: Readonly>; + /** The linked thread stays in the tab's tooltip when its surface moves elsewhere. */ + threadTitle?: string | null; children: ReactNode; } -export interface PullRequestTabStatus { - projectId: string; - repository: string; - number: number; - state: PullRequestState; - isDraft: boolean; -} - -export type PullRequestTabStatusSeed = Pick; - -function shouldOpenDefaultBrowserProfileFromMenuClick(pointerType: string | undefined): boolean { - return pointerType !== "touch"; -} - const SURFACE_DISABLED_REASONS = { browser: msg("Browser previews are only available in the T3 Code desktop app."), terminal: msg("Terminal surfaces are only available from a project thread."), @@ -198,31 +191,6 @@ const SURFACE_DISABLED_REASONS = { sideChat: msg("Side chats start after the first message."), } as const; -// Closed keepMounted popups must stop blocking shortcuts once their exit transition ends. -const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [ - "dialog-popup", - "alert-dialog-popup", - "command-dialog-popup", - "menu-popup", - "select-popup", - "popover-popup", - "combobox-popup", - "autocomplete-popup", -] - .map((slot) => `[data-slot="${slot}"]:is([data-open],[data-ending-style])`) - .join(","); - -const SURFACE_UNAVAILABLE_HINTS = { - browser: msg("Only available in the desktop app."), - terminal: msg("Available when a project is open."), - files: msg("Available when a project is open."), - diff: msg("Available for Git repositories."), - pullRequest: msg("No pull request on this branch yet."), - pullRequests: msg("No linked items available."), - device: msg("Available from a thread."), - sideChat: msg("Available after the first message."), -} as const; - type TabContextMenuAction = | "open-in-main-view" | "rename" @@ -249,25 +217,6 @@ function previewTabIdOf( return sessions[surface.resourceId]?.tabId ?? null; } -/** - * Stays disabled until desktop overlay state arrives: a server session id can - * resolve while the preview manager's createTab is still in flight, and muting - * then fails with a PreviewTabNotFoundError nothing surfaces to the user. - */ -function tabMuteMenuItem( - input: { - overlay: DesktopPreviewOverlay | null; - canResolveRuntimeTabId: boolean; - }, - resolve: MessageResolver = m, -): { label: string; disabled: boolean } { - const muted = input.overlay?.audioMuted ?? false; - return { - label: muted ? resolve(msg("Unmute tab")) : resolve(msg("Mute tab")), - disabled: input.overlay === null || !input.canResolveRuntimeTabId, - }; -} - type TabAudioState = "none" | "audible" | "muted"; function tabAudioState(overlay: DesktopPreviewOverlay | null): TabAudioState { @@ -275,65 +224,104 @@ function tabAudioState(overlay: DesktopPreviewOverlay | null): TabAudioState { return overlay.audioMuted ? "muted" : "audible"; } -type SurfaceShortcutEvent = Pick< - KeyboardEvent, - "altKey" | "ctrlKey" | "defaultPrevented" | "isComposing" | "key" | "metaKey" -> & - Partial>; - -export function surfaceShortcutActionForKey< - const Action extends { available: boolean; shortcut: string }, ->(actions: readonly Action[], event: SurfaceShortcutEvent): Action | null { - if (event.defaultPrevented || event.isComposing) return null; - if (event.metaKey || event.ctrlKey || event.altKey) return null; - const key = surfaceShortcutKey(event); +/** + * A layout pane's tabs sit in its notch with "+" as the notch's last child, + * like a chat's and the terminal's; the sheet and inline panel keep a plain row. + */ +function PanelTabStrip({ + notched, + noDrag, + ref, + children, +}: { + notched: boolean; + noDrag: boolean; + ref: Ref; + children: ReactNode; +}) { + if (notched) { + return ( +
+ {children} +
+ ); + } return ( - actions.find((action) => action.available && action.shortcut.toLowerCase() === key) ?? null + +
{children}
+
); } -/** Skip contenteditable=false islands to find their editable host, matching the composer typing guard. */ -export function surfaceShortcutTargetsTypingContext( - target: { closest(selectors: string): unknown } | null, -): boolean { +function PanelTabsNotch(props: { + notched: boolean; + /** A pane's second strip, beside its own (the pull request beside its list). */ + secondStrip: boolean; + addButton: ReactNode; + pinnedTab: ReactNode; + children: ReactNode; +}) { + if (!props.notched) return props.children; return ( - target?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])') != - null + + {props.pinnedTab} + + {props.children} + + {props.addButton ? ( + + {props.addButton} + + ) : null} + ); } -function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) { +function PanelActionsNotch(props: { notched: boolean; hasActions: boolean; children: ReactNode }) { + const gt = useGT(); + const isMobile = useMediaQuery("max-md"); + if (!props.notched) return props.children; + if (!props.hasActions) return null; + if (isMobile) { + return ( + + } + > + + + +
+ {props.children} +
+
+
+ ); + } return ( - - - {props.reason} - - ); -} - -function SurfaceMenuItem(props: { - available: boolean; - disabledReason?: string; - shortcut: string; - onClick: () => void; - children: ReactNode; -}) { - const item = ( - + {props.children} - {props.shortcut} - + ); - if (props.available || !props.disabledReason) return item; - return ; } +/** + * Pane-wide letter shortcuts must yield to typing contexts. + * The focused launcher also supports arrows and explains unavailable surfaces. + */ function RightPanelEmptyState(props: { + onClose: (() => void) | undefined; onAddBrowser: () => void; onAddBrowserInProfile: (profileId: string) => void; browserProfiles: ReadonlyArray<{ readonly id: string; readonly name: string }>; @@ -346,6 +334,7 @@ function RightPanelEmptyState(props: { /** Absent where side chats are not offered. */ onAddSideChat?: (() => void) | undefined; browserAvailable: boolean; + browserUnavailableReason: string | null | undefined; terminalAvailable: boolean; diffAvailable: boolean; filesAvailable: boolean; @@ -356,557 +345,85 @@ function RightPanelEmptyState(props: { sideChatDisabledReason: string | null; }) { const gt = useGT(); - const messages = useMessages(); - const [highlight, setHighlight] = useState(-1); - - const actions = [ + const actions: SurfaceLauncherAction[] = [ { - label: msg("Browser"), - icon: Globe2, + kind: "browser", shortcut: "B", available: props.browserAvailable, - disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.browser), + ...(props.browserUnavailableReason ? { disabledReason: props.browserUnavailableReason } : {}), onClick: props.onAddBrowser, }, { - label: msg("Terminal"), - icon: TerminalSquare, + kind: "terminal", shortcut: "T", available: props.terminalAvailable, - disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.terminal), onClick: props.onAddTerminal, }, + { kind: "files", shortcut: "F", available: props.filesAvailable, onClick: props.onAddFiles }, + { kind: "diff", shortcut: "D", available: props.diffAvailable, onClick: props.onAddDiff }, { - label: msg("Files"), - icon: Files, - shortcut: "F", - available: props.filesAvailable, - disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.files), - onClick: props.onAddFiles, - }, - { - label: msg("Diff"), - icon: FileDiff, - shortcut: "D", - available: props.diffAvailable, - disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.diff), - onClick: props.onAddDiff, - }, - { - label: msg("Pull request"), - icon: PullRequestGlyph.pullRequest, + kind: "pull-request", shortcut: "P", available: props.pullRequestAvailable, - disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.pullRequest), onClick: props.onAddPullRequest, }, { - label: msg("Linked items"), - icon: PullRequestGlyph.link, + kind: "pull-requests", shortcut: "L", available: props.pullRequestsAvailable, - disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.pullRequests), onClick: props.onAddPullRequests, }, - { - label: msg("Device"), - description: msg("Watch an iOS Simulator or Android Emulator."), - icon: Smartphone, - shortcut: "M", - available: props.deviceAvailable, - disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.device), - onClick: props.onAddDevice, - }, + { kind: "device", shortcut: "M", available: props.deviceAvailable, onClick: props.onAddDevice }, ...(props.onAddSideChat ? [ { - label: msg("Side chat"), - description: msg("Ask a side question while this thread keeps working."), - icon: MessagesSquare, + kind: "side-chat" as const, shortcut: "S", available: props.sideChatAvailable && !props.sideChatDisabledReason, - disabledReason: - props.sideChatDisabledReason ?? messages(SURFACE_UNAVAILABLE_HINTS.sideChat), onClick: props.onAddSideChat, }, ] : []), - ] as const; - - type SurfaceAction = (typeof actions)[number]; - - const availableActions = actions.filter((action) => action.available); - const highlightIndex = - availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1); - - const handleShortcut = useEffectEvent((event: KeyboardEvent) => { - const action = surfaceShortcutActionForKey(availableActions, event); - if (!action) return; - if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return; - const target = event.composedPath()[0] ?? event.target; - if (target instanceof Element && surfaceShortcutTargetsTypingContext(target)) return; - event.preventDefault(); - event.stopPropagation(); - action.onClick(); + ]; + const paneFocusedRef = useLayoutPaneFocusedRef(); + const [launcherRef, attachLauncher] = useLauncherElement(paneFocusedRef, false); + useSurfaceLauncherKeys({ + launcherRef, + activeRef: paneFocusedRef, + actions, + onClose: props.onClose, }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a capture-phase window keydown listener for surface shortcuts while the menu is mounted - useEffect(() => { - const handler = (event: KeyboardEvent) => handleShortcut(event); - window.addEventListener("keydown", handler, true); - return () => window.removeEventListener("keydown", handler, true); - }, []); - - const handleKeyDown = (event: ReactKeyboardEvent) => { - if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return; - if (availableActions.length === 0) return; - if (event.key === "ArrowDown" || event.key === "ArrowRight") { - event.preventDefault(); - setHighlight((highlightIndex + 1) % availableActions.length); - return; - } - if (event.key === "ArrowUp" || event.key === "ArrowLeft") { - event.preventDefault(); - setHighlight( - highlightIndex === -1 - ? availableActions.length - 1 - : (highlightIndex - 1 + availableActions.length) % availableActions.length, - ); - return; - } - if (event.key === "Enter") { - if (event.target !== event.currentTarget) return; - const action = availableActions[highlightIndex]; - if (!action) return; - event.preventDefault(); - action.onClick(); - } - }; - - const isHighlighted = (action: SurfaceAction) => - highlightIndex !== -1 && availableActions[highlightIndex] === action; - - const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => { - const Icon = action.icon; - return ( - - - - ); - }; return (
action.shortcut).join("")} + data-surface-launcher-keys={actions + .filter((action) => action.available) + .map((action) => action.shortcut) + .join("")} className={cn( - "scrollbar-gutter-both flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 outline-none", + "scrollbar-gutter-both flex min-h-0 flex-1 items-center-safe justify-center overflow-y-auto px-4 outline-none", "pb-(--workspace-topbar-height)", )} > -
-

- Open a surface -

-
- {actions.map((action) => - action.available ? ( -
setHighlight(availableActions.indexOf(action))} - onMouseLeave={() => - setHighlight((current) => - current === availableActions.indexOf(action) ? -1 : current, - ) - } - > - - {action.label === "Browser" && props.browserProfiles.length > 1 ? ( - - - } - > - - - - {props.browserProfiles.map((profile) => ( - props.onAddBrowserInProfile(profile.id)} - > - {profile.name} - - ))} - - - ) : null} -
- ) : ( - - {actionIcon(action, "size-4")} - {messages(action.label)} - {action.shortcut} -
- } - /> - ), - )} -
+
+
); } -function surfaceTitle( - surface: RightPanelSurface, - sessions: Readonly>, - terminalLabelsById: ReadonlyMap, - resolve: MessageResolver = m, -): string { - switch (surface.kind) { - case "diff": - return resolve(msg("Diff")); - case "files": - return resolve(msg("Files")); - case "file": - return surface.relativePath.slice( - Math.max(surface.relativePath.lastIndexOf("/"), surface.relativePath.lastIndexOf("\\")) + 1, - ); - case "terminal": - return ( - terminalLabelsById.get(surface.activeTerminalId) ?? - getTerminalLabel(surface.activeTerminalId, resolve) - ); - case "pull-request": - return `#${surface.number}`; - case "pull-requests": - return resolve(msg("Linked items")); - case "issue": - // A git host numbers its issues; a tracker with keys of its own, such as Linear, names them. - return /^\d+$/.test(surface.key) ? `#${surface.key}` : surface.key; - case "device": - return surface.title ?? surface.target?.name ?? resolve(msg("Device")); - case "thread": - // Until the thread's own title loads. - return resolve(msg("Thread")); - case "linked-thread": - return linkedThreadTitle( - surface, - resolve(msg("Thread on {label}", { label: surface.label })), - ); - case "preview": { - const snapshot = surface.resourceId ? sessions[surface.resourceId] : null; - if (!snapshot || snapshot.navStatus._tag === "Idle") return resolve(msg("Browser")); - if (snapshot.navStatus.title.trim().length > 0) return snapshot.navStatus.title; - try { - return new URL(snapshot.navStatus.url).host || resolve(msg("Browser")); - } catch { - return resolve(msg("Browser")); - } - } - } -} - -function PreviewFavicon({ capturedUrl, url }: { capturedUrl: string | null; url: string | null }) { - const publicProviderUrl = faviconUrlForOrigin(url, 32); - return ( - } - className="size-3 shrink-0 rounded-sm object-contain" - /> - ); -} - -function sameOrigin(left: string, right: string): boolean { - try { - return new URL(left).origin === new URL(right).origin; - } catch { - return false; - } -} - -function previewFaviconOf( - surface: RightPanelSurface, - sessions: Readonly>, - desktopByTabId: Readonly>, -): { url: string | null; capturedUrl: string | null } { - const snapshot = - surface.kind === "preview" && surface.resourceId ? sessions[surface.resourceId] : null; - const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url; - const favicon = snapshot ? (desktopByTabId[snapshot.tabId]?.favicon ?? null) : null; - const capturedUrl = favicon && url && sameOrigin(favicon.pageUrl, url) ? favicon.dataUrl : null; - return { url, capturedUrl }; -} - -function SurfaceIcon({ - surface, - previewUrl, - previewCapturedUrl, - theme, - environmentId, - pullRequestStatusSeed, -}: { - surface: RightPanelSurface; - previewUrl: string | null; - previewCapturedUrl: string | null; - theme: "light" | "dark"; - environmentId: EnvironmentId | null; - pullRequestStatusSeed: PullRequestTabStatusSeed | undefined; -}) { - switch (surface.kind) { - case "preview": - return ; - case "diff": - return ( - - ); - case "files": - return ( - - ); - case "file": - return ( - - ); - case "terminal": - return ( - - ); - case "pull-request": - return ( - - ); - case "pull-requests": - return ( - - ); - case "issue": - return ; - case "thread": - return ; - case "linked-thread": - return ; - case "device": - return surface.target?.platform === "ios" ? ( - - ) : surface.target?.platform === "android" ? ( - - ) : ( - - ); - } -} - -const SIDE_CHAT_STATE_LABELS = { - "needs approval": msg("needs approval"), - "needs input": msg("needs input"), - running: msg("running", { $context: "side chat status" }), -} as const; - -/** What a side chat tab's dot shows and its title's accessible name says. */ -function sideChatTabState(shell: EnvironmentThreadShell | null) { - if (shell === null) return null; - if (shell.hasPendingApprovals || shell.pendingSubagentRequest === "approval") { - return "needs approval"; - } - if (shell.hasPendingUserInput || shell.pendingSubagentRequest === "user_input") { - return "needs input"; - } - return threadRuntimeIsActive(shell.runtime) ? "running" : null; -} - -// Static dots: a side chat or subagent tab can stay open for a whole run. -function SideChatTabIcon(props: { environmentId: EnvironmentId | null; threadId: ThreadId }) { - const shell = useQuietThreadShell( - props.environmentId === null ? null : scopeThreadRef(props.environmentId, props.threadId), - ); - const state = sideChatTabState(shell); - const Icon = shell !== null && shell.lineage.sideChat !== true ? Bot : MessagesSquare; - return ( - <> - - {state === null ? null : ( - - )} - - ); -} - -export function resolvePullRequestTabLink( - threads: readonly Pick[], - environmentId: EnvironmentId | null, - host: string | null, - reference: { repository: string; number: number }, -) { - if (environmentId === null || host === null) return undefined; - // Keys are cached per object, so one target normalizes once instead of once per link. - const target = { host, repository: reference.repository, number: reference.number }; - let newest: EnvironmentThreadShell["pullRequests"][number] | undefined; - for (const thread of threads) { - if (thread.environmentId !== environmentId) continue; - for (const link of visibleThreadPullRequests(thread.pullRequests)) { - if (!threadPullRequestKeysEqual(link, target)) continue; - if ( - newest === undefined || - (link.snapshot?.syncedAt ?? "") > (newest.snapshot?.syncedAt ?? "") - ) - newest = link; - } - } - return newest; -} - -/** The issue's own state mark, from the detail its panel already reads; a plain dot until then. */ -function IssueSurfaceIcon({ - surface, - environmentId, -}: { - surface: Extract; - environmentId: EnvironmentId | null; -}) { - const resolvedEnvironmentId = - (surface.environmentId as EnvironmentId | undefined) ?? environmentId; - const detail = useEnvironmentQuery( - resolvedEnvironmentId === null - ? null - : issueEnvironment.detail({ - environmentId: resolvedEnvironmentId, - input: { - projectId: surface.projectId as ProjectId, - tracker: surface.tracker as IssueTrackerKind, - ...(surface.host ? { host: surface.host } : {}), - scope: surface.scope, - key: surface.key, - }, - }), - ).data; - if (detail === null) return ; - const presentation = issueStatePresentation(detail.state); - return ( - - ); -} - -function PullRequestSurfaceIcon({ - surface, - environmentId, - seed, -}: { - surface: Extract; - environmentId: EnvironmentId | null; - seed: PullRequestTabStatusSeed | undefined; -}) { - const resolvedEnvironmentId = - (surface.environmentId as EnvironmentId | undefined) ?? environmentId; - const projects = useProjects(); - const threads = useThreadShells(); - const project = projects.find( - (entry) => entry.environmentId === resolvedEnvironmentId && entry.id === surface.projectId, - ); - const identity = project?.repositoryIdentity; - const host = - surface.host ?? - (identity?.provider - ? sourceControlClients.changeRequestHost(identity, identity.provider) - : null); - const configs = useServerConfigs(); - const capabilities = - resolvedEnvironmentId === null - ? undefined - : configs.get(resolvedEnvironmentId)?.environment.capabilities; - const linkedSnapshot = - capabilities !== undefined - ? (resolvePullRequestTabLink(threads, resolvedEnvironmentId, host, surface)?.snapshot ?? null) - : null; - const detail = useEnvironmentQuery( - resolvedEnvironmentId === null || capabilities === undefined || linkedSnapshot !== null - ? null - : pullRequestEnvironment.detail({ - environmentId: resolvedEnvironmentId, - input: { - projectId: surface.projectId as ProjectId, - ...(capabilities !== undefined && surface.host !== undefined - ? { host: surface.host } - : {}), - repository: surface.repository, - number: surface.number, - allowStale: false, - }, - }), - ).data; - const reference = { - projectId: surface.projectId as ProjectId, - repository: surface.repository, - number: surface.number, - }; - const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference); - const status = linkedSnapshot ?? newestPullRequestSummary(detail, sharedSummary) ?? seed ?? null; - if (status === null) { - return ; - } - const presentation = resolvePullRequestState({ - state: status.state, - isDraft: status.isDraft ?? detail?.isDraft ?? seed?.isDraft ?? false, - }); - return ; -} - function SortableTabList(props: { surfaces: readonly RightPanelSurface[]; onMove: ((surfaceId: string, toIndex: number) => void) | undefined; @@ -943,6 +460,11 @@ interface RightPanelTabHandlers { onFinishRename: (surfaceId: string, title: string) => void; } +const NO_LAYOUT_TAB: LayoutTab = { + id: "panel", + content: { kind: "launcher", id: "panel", context: null }, +}; + // Chromium on Linux only suppresses primary-selection paste when mouseup is cancelled. function preventTabMiddleButtonDefault(event: ReactMouseEvent) { if (event.button !== 1) return; @@ -967,14 +489,30 @@ function RightPanelTab( renaming: boolean; canRename: boolean; ownsDesktopTitleBar: boolean; + notched: boolean; + layoutTabId: string | null; + threadTitle: string | null; }, ) { const gt = useGT(); - const messages = useMessages(); const { + dragDisabled, + previewUrl, + previewCapturedUrl, + theme, + environmentId, + pullRequestStatusSeed, + renaming, + canRename, + threadTitle, surface, audio, audioRuntimeTabId, + active, + pending, + notched, + layoutTabId, + ownsDesktopTitleBar, onActivate, onClose, onAuxClick, @@ -984,151 +522,200 @@ function RightPanelTab( } = props; const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: surface.id, - disabled: props.dragDisabled, + disabled: dragDisabled, }); const sideChatShell = useQuietThreadShell( surface.kind === "thread" && props.environmentId !== null ? scopeThreadRef(props.environmentId, surface.threadId) : null, ); - const title = + const layoutTab = useLayoutStore((state) => + layoutTabId === null + ? null + : (findLayoutTab(state.layout, (tab) => tab.id === layoutTabId)?.tab ?? null), + ); + const layoutLabel = useLayoutTabLabel(layoutTab ?? NO_LAYOUT_TAB); + const shellTitle = sideChatShell === null ? props.title : sideChatShell.lineage.sideChat === true ? sideChatShell.title : formatSubagentDisplayTitle(sideChatShell.title); - const sideChatState = sideChatTabState(sideChatShell); - const content = ( - <> - onClose(surface)}> - - {props.pending ? ( - - ) : null} - - {audio === "none" || !audioRuntimeTabId ? null : ( - - { - event.stopPropagation(); - void previewBridge - ?.setAudioMuted(audioRuntimeTabId, audio !== "muted") - .catch(() => undefined); - }} - > - {audio === "muted" ? ( - - ) : ( - - )} - - } - /> - {audio === "muted" ? gt("Unmute tab") : gt("Mute tab")} - - )} - {props.renaming ? ( - { - element?.focus(); - element?.select(); - }} - onBlur={(event) => onFinishRename(surface.id, event.currentTarget.value)} - onKeyDown={(event) => { - event.stopPropagation(); - if (event.nativeEvent.isComposing || event.keyCode === 229) return; - if (event.key === "Enter") event.currentTarget.blur(); - if (event.key === "Escape") { - event.currentTarget.value = title; - event.currentTarget.blur(); - } - }} - /> - ) : ( - - { - if (surface.kind === "device" && props.canRename) onStartRename(surface.id); - }} - className="cursor-pointer flex min-w-0 items-center" - aria-label={ - sideChatState === null - ? undefined - : gt("{title}, {state}", { - title, - state: messages(SIDE_CHAT_STATE_LABELS[sideChatState]), - }) - } - onClick={() => onActivate(surface)} - > - {title} - - } - /> - - {surface.kind === "device" ? ( - - ) : ( - title - )} - - - )} - - ); + const title = layoutTab ? layoutLabel.title : shellTitle; + const tooltip = layoutTab + ? layoutLabel.tooltip + : [title, threadTitle, previewUrl, surface.kind === "file" ? surface.relativePath : null] + .filter(Boolean) + .join("\n"); return (
beginLayoutTabDrag(event, layoutTabId) : undefined + } onMouseDown={preventTabMiddleButtonDefault} onMouseUp={preventTabMiddleButtonDefault} onAuxClick={(event) => onAuxClick(event, surface)} onContextMenu={(event) => onContextMenu(event, surface)} {...listeners} - ref={setNodeRef} - style={{ transform: CSS.Translate.toString(transform), transition }} className={cn( - "cursor-pointer group/tab flex h-6 max-w-36 shrink-0 items-center gap-0.5 rounded-item pr-2 pl-1.5 text-xs", - props.ownsDesktopTitleBar && "[-webkit-app-region:no-drag]", - props.active - ? "font-medium text-strong-foreground" - : "text-muted-foreground hover:surface-ghost-hover hover:text-foreground", + "cursor-pointer group/tab flex shrink-0 items-center", + notched && "max-md:min-w-0 max-md:shrink", isDragging && "relative z-10", + // In the notch a tab is the chat's 28px notch tab (pen JiaZk). + notched + ? "h-7 gap-1.75 rounded-control px-2.5 text-label" + : "h-6 gap-0.5 rounded-item pr-2 pl-1.5 text-xs", + // The active tab title caps below. + !active && !notched && "max-w-36", + ownsDesktopTitleBar && "[-webkit-app-region:no-drag]", + active + ? cn("text-strong-foreground", !notched && "font-medium") + : "text-muted-foreground hover:surface-ghost-hover hover:text-foreground", )} > - {content} + <> + onClose(surface)} + showOnPhone={notched} + > + {surface.kind === "terminal" && layoutTab ? ( + layoutLabel.icon + ) : ( + + )} + {pending ? ( + + ) : null} + + {audio === "none" || !audioRuntimeTabId ? null : ( + + { + event.stopPropagation(); + void previewBridge + ?.setAudioMuted(audioRuntimeTabId, audio !== "muted") + .catch(() => undefined); + }} + > + {audio === "muted" ? ( + + ) : ( + + )} + + } + /> + {audio === "muted" ? gt("Unmute tab") : gt("Mute tab")} + + )} + {renaming ? ( + { + element?.focus(); + element?.select(); + }} + onBlur={(event) => onFinishRename(surface.id, event.currentTarget.value)} + onKeyDown={(event) => { + event.stopPropagation(); + if (event.nativeEvent.isComposing || event.keyCode === 229) return; + if (event.key === "Enter") event.currentTarget.blur(); + if (event.key === "Escape") { + event.currentTarget.value = title; + event.currentTarget.blur(); + } + }} + /> + ) : ( + + { + if (surface.kind === "device" && canRename) onStartRename(surface.id); + }} + className={cn( + "cursor-pointer flex min-w-0 items-center outline-none focus-visible:inset-ring-2 focus-visible:inset-ring-ring", + active && surface.kind === "diff" && "shrink-0", + )} + aria-label={ + surface.kind === "terminal" && threadTitle + ? `${title}, ${threadTitle}` + : undefined + } + onClick={() => onActivate(surface)} + > + + {title} + + + } + /> + + {surface.kind === "device" ? ( + <> + {threadTitle ? ( + <> + {threadTitle} +
+ + ) : null} + + + ) : ( + tooltip + )} +
+
+ )} +
); } +const PANE_BODY_SURFACE_CLASS: Partial> = { + "pull-request": "bg-(--code-surface)", + "pull-requests": "bg-transparent", + file: "bg-(--code-surface)", + terminal: "bg-(--terminal-background)", +}; + export function RightPanelTabs(props: RightPanelTabsProps) { const gt = useGT(); const messages = useMessages(); @@ -1137,8 +724,36 @@ export function RightPanelTabs(props: RightPanelTabsProps) { const browserProfiles = useBrowserDefaults().profiles; const { resolvedTheme } = useTheme(); const tabListRef = useRef(null); - const addSurfaceTriggerRef = useRef(null); + // Embedded, this is one surface's tab in the layout: it drags like any tab + // and its pane's other tabs sit around it in the notch. + const { tabId: layoutPaneTabId, leadingEdge } = useLayoutPane(); + const layoutTabId = props.mode === "embedded" ? layoutPaneTabId : null; + const siblingTabs = useLayoutPaneSiblingTabs(); + const pageTab = useLayoutStore((state) => + props.mode === "embedded" || !props.holdsPaneTabs || layoutPaneTabId === null + ? null + : (findLayoutTab(state.layout, (tab) => tab.id === layoutPaneTabId)?.tab ?? null), + ); + const paneTabsId = layoutTabId ?? pageTab?.id ?? null; + const isMobile = useMediaQuery("max-md"); + const pinnedChatTab = + isMobile && layoutTabId !== null + ? [...siblingTabs.before, ...siblingTabs.after].find((tab) => tab.content.kind === "chat") + : undefined; const [renamingDevice, setRenamingDevice] = useState(null); + const renameRequested = useLayoutTabRenameRequested(layoutTabId); + const renamingDeviceId = renamingDevice ?? (renameRequested ? props.activeSurfaceId : null); + const [mobileBreadcrumbSlot, setMobileBreadcrumbSlot] = useState(null); + const [actionsSlot, setActionsSlot] = useState(null); + const { hasActions, registerActions } = usePanelTabActionsHost(); + const mobileDiff = isMobile && props.mode === "embedded" && focusedSurface?.kind === "diff"; + // A layout pane's tabs sit in its notch (pen JiaZk), like a chat's. + const notched = props.mode === "embedded" || props.pane === true; + const tabSlots = { + breadcrumb: mobileDiff ? mobileBreadcrumbSlot : null, + actions: actionsSlot, + registerActions, + }; const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false); const [tabScrollState, setTabScrollState] = useState({ hasOverflow: false, @@ -1148,40 +763,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) { if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); - const addSurfaceMenuBlocked = () => - !addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS) !== null; - const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => { - if (event.defaultPrevented || event.isComposing) return; - if ( - resolveShortcutCommand(event, props.keybindings, { - context: { ...props.getShortcutContext(), rightPanelOpen: true }, - }) !== "rightPanel.new" - ) - return; - if (addSurfaceMenuBlocked()) return; - event.preventDefault(); - event.stopPropagation(); - if (!event.repeat) { - addSurfaceTriggerRef.current?.focus(); - setAddSurfaceMenuOpen(true); - } - }); - // Forwarded from a focused browser page. Focusing the trigger here would let ChatView's - // window-focus handler see a plain button and refocus the composer, closing the menu. - const onMenuAction = useEffectEvent((action: string) => { - if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true); - }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open - useEffect(() => { - if (props.open === false) return; - document.addEventListener("keydown", onNewSurfaceKeyDown, true); - const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction); - return () => { - document.removeEventListener("keydown", onNewSurfaceKeyDown, true); - unsubscribe?.(); - }; - }, [props.open]); - const updateTabScrollState = (viewport: HTMLDivElement) => { const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE; const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE; @@ -1210,77 +791,57 @@ export function RightPanelTabs(props: RightPanelTabsProps) { }); }; - const addSurfaceActions = [ - { - label: msg("Browser"), - icon: Globe2, - shortcut: "B", - available: props.browserAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.browser), - onClick: props.onAddBrowser, - }, - { - label: msg("Terminal"), - icon: TerminalSquare, - shortcut: "T", - available: props.terminalAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.terminal), - onClick: props.onAddTerminal, - }, - { - label: msg("Files"), - icon: Files, - shortcut: "F", - available: props.filesAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.files), - onClick: props.onAddFiles, - }, - { - label: msg("Diff"), - icon: FileDiff, - shortcut: "D", - available: props.diffAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.diff), - onClick: props.onAddDiff, - }, - { - label: msg("Pull request"), - icon: PullRequestGlyph.pullRequest, - shortcut: "P", - available: props.pullRequestAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.pullRequest), - onClick: props.onAddPullRequest, - }, - { - label: msg("Linked items"), - icon: PullRequestGlyph.link, - shortcut: "L", - available: props.pullRequestsAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.pullRequests), - onClick: props.onAddPullRequests, - }, - { - label: msg("Device"), - icon: Smartphone, - shortcut: "M", - available: props.deviceAvailable, - disabledReason: messages(SURFACE_DISABLED_REASONS.device), - onClick: props.onAddDevice, + const addSurfaceActions = surfaceMenuActions({ + onNewThread: props.onNewThread, + surfaces: { + browser: { + available: props.browserAvailable, + disabledReason: + props.browserUnavailableReason ?? messages(SURFACE_DISABLED_REASONS.browser), + onClick: props.onAddBrowser, + }, + terminal: { + available: props.terminalAvailable, + disabledReason: messages(SURFACE_DISABLED_REASONS.terminal), + onClick: props.onAddTerminal, + }, + files: { + available: props.filesAvailable, + disabledReason: messages(SURFACE_DISABLED_REASONS.files), + onClick: props.onAddFiles, + }, + diff: { + available: props.diffAvailable, + disabledReason: messages(SURFACE_DISABLED_REASONS.diff), + onClick: props.onAddDiff, + }, + "pull-request": { + available: props.pullRequestAvailable, + disabledReason: messages(SURFACE_DISABLED_REASONS.pullRequest), + onClick: props.onAddPullRequest, + }, + "pull-requests": { + available: props.pullRequestsAvailable, + disabledReason: messages(SURFACE_DISABLED_REASONS.pullRequests), + onClick: props.onAddPullRequests, + }, + device: { + available: props.deviceAvailable, + disabledReason: messages(SURFACE_DISABLED_REASONS.device), + onClick: props.onAddDevice, + }, + ...(props.onAddSideChat + ? { + "side-chat": { + available: props.sideChatAvailable === true && !props.sideChatDisabledReason, + disabledReason: + props.sideChatDisabledReason ?? messages(SURFACE_DISABLED_REASONS.sideChat), + onClick: props.onAddSideChat, + }, + } + : {}), }, - ...(props.onAddSideChat - ? [ - { - label: msg("Side chat"), - icon: MessagesSquare, - shortcut: "S", - available: props.sideChatAvailable === true && !props.sideChatDisabledReason, - disabledReason: - props.sideChatDisabledReason ?? messages(SURFACE_DISABLED_REASONS.sideChat), - onClick: props.onAddSideChat, - }, - ] - : []), - ] as const; + }); const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent) => { const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent); @@ -1295,6 +856,16 @@ export function RightPanelTabs(props: RightPanelTabsProps) { event.preventDefault(); event.stopPropagation(); + if (layoutTabId !== null) { + void showLayoutTabMenu( + layoutTabId, + { x: event.clientX, y: event.clientY }, + props.keybindings, + () => setRenamingDevice(surface.id), + ); + return; + } + const api = readLocalApi(); if (!api) return; @@ -1411,22 +982,25 @@ export function RightPanelTabs(props: RightPanelTabsProps) { const onFinishRenameTab = useStableCallback((surfaceId: string, title: string) => { props.onRenameDevice?.(surfaceId, title); setRenamingDevice(null); + finishLayoutTabRename(layoutTabId); }); - // A newly active tab, or tabs that start overflowing, can sit outside the scrolled strip. - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the active tab DOM node into view after it changes or the tab strip starts overflowing - useEffect(() => { - if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return; - const activeTab = tabListRef.current?.querySelector("[data-active-tab='true']"); - activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" }); - }, [props.activeSurfaceId, tabScrollState.hasOverflow]); + useRevealActiveTab(tabListRef, layoutTabId === null ? props.activeSurfaceId : null); const attachTabList = (root: HTMLDivElement | null) => { tabListRef.current = root; const viewport = tabScrollViewport(root); if (!viewport) return; - const update = () => updateTabScrollState(viewport); + const row = root?.closest("[data-right-panel-tabbar]"); + const update = () => { + updateTabScrollState(viewport); + const overflow = viewport.scrollWidth > viewport.clientWidth; + if (row && row.hasAttribute("data-tab-row-overflow") !== overflow) { + row.toggleAttribute("data-tab-row-overflow", overflow); + } + }; + const rowWheel = (event: WheelEvent) => scrollTabStripFromRow(event, viewport); // Only a vertical mouse wheel is translated. Horizontal input scrolls natively, since // consuming it keeps Chromium from starting the gesture scroll that swipe navigation tracks. const handleWheel = (event: WheelEvent) => { @@ -1435,17 +1009,15 @@ export function RightPanelTabs(props: RightPanelTabsProps) { if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= 16; if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) delta *= viewport.clientWidth; - const previousScrollLeft = viewport.scrollLeft; - viewport.scrollLeft += delta; - if (viewport.scrollLeft === previousScrollLeft) return; + if (!scrollLeftByWheel(viewport, event, delta)) return; event.preventDefault(); - update(); }; const content = viewport.firstElementChild; const stopObserving = observeResize(content ? [viewport, content] : viewport, update); viewport.addEventListener("scroll", update, { passive: true }); viewport.addEventListener("wheel", handleWheel, { passive: false }); + row?.addEventListener("wheel", rowWheel, { passive: false }); update(); return () => { @@ -1453,9 +1025,45 @@ export function RightPanelTabs(props: RightPanelTabsProps) { stopObserving(); viewport.removeEventListener("scroll", update); viewport.removeEventListener("wheel", handleWheel); + row?.removeEventListener("wheel", rowWheel); + row?.removeAttribute("data-tab-row-overflow"); }; }; + const addSurfaceMenu = + paneTabsId !== null ? ( + + ) : // A notch keeps it while empty too: an empty notch reads as a broken corner. + props.open !== false || props.surfaces.length > 0 || notched ? ( + + + } + > + + + + setAddSurfaceMenuOpen(false)} + /> + + + ) : null; + return ( @@ -1488,26 +1097,51 @@ export function RightPanelTabs(props: RightPanelTabsProps) { >
- + + + ) : null + } > -
+ {paneTabsId !== null + ? [...siblingTabs.before, ...(pageTab ? [pageTab] : [])] + .filter((tab) => tab.id !== pinnedChatTab?.id) + .map((tab) => ) + : null} + {props.surfaces.map((surface) => { const previewTabId = previewTabIdOf(surface, props.previewSessions); @@ -1520,7 +1154,12 @@ export function RightPanelTabs(props: RightPanelTabsProps) { - {props.open !== false ? ( - - - } - > - - - - {addSurfaceActions.map((action) => { - const Icon = action.icon; - if (action.label === "Browser" && action.available) { - return ( - - { - const pointerType = - "pointerType" in event.nativeEvent && - typeof event.nativeEvent.pointerType === "string" - ? event.nativeEvent.pointerType - : undefined; - if (!shouldOpenDefaultBrowserProfileFromMenuClick(pointerType)) - return; - setAddSurfaceMenuOpen(false); - action.onClick(); - }} - > - - {messages(action.label)} - {action.shortcut} - - - {browserProfiles.map((profile) => ( - props.onAddBrowserInProfile(profile.id)} - > - {profile.name} - - ))} - - - ); - } - return ( - - - {messages(action.label)} - - ); - })} - - - ) : null} -
-
- {tabScrollState.hasOverflow ? ( + {notched ? null : addSurfaceMenu} + + {paneTabsId !== null + ? siblingTabs.after + .filter((tab) => tab.id !== pinnedChatTab?.id) + .map((tab) => ) + : null} + + {/* In the notch the tabs scroll by wheel and ctrl+Tab; the actions need the room. */} + {!notched && tabScrollState.hasOverflow ? (
) : null} - {props.layoutControls} + + {mobileDiff ? ( + + ) : null} +
+ {props.layoutControls} + {ownsDesktopTitleBar && !props.layoutControls ? ( ) : null} @@ -1688,9 +1276,14 @@ export function RightPanelTabs(props: RightPanelTabsProps) { /> ) : null}
-
+
{props.activeSurfaceId === null ? ( ) : ( - props.children + {props.children} )}
diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 8403ffb6b16b9..1890cfcdfdada 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -58,6 +58,17 @@ vi.mock(import("../state/server"), async (original) => { ]); return { ...(await original()), primaryServerKeybindingsAtom: Atom.make(keybindings) }; }); +vi.mock(import("../connection/catalog"), async (original) => { + const actual = await original(); + const { Atom } = await import("effect/reactivity"); + return { + ...actual, + environmentCatalog: { + ...actual.environmentCatalog, + catalogValueAtom: Atom.make({ isReady: true, entries: new Map() }) as never, + }, + }; +}); vi.mock("../commandPaletteBus", () => ({ openCommandPalette: vi.fn(), isCommandPaletteOpen: () => false, @@ -82,6 +93,40 @@ function project(id: string): Project { } describe("sidebar header new thread", () => { + it("does not render the thread list when terminal focus changes without held modifiers", async () => { + vi.mocked(useProjects).mockReturnValue([]); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: null, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef: null, + }); + await using screen = await render( + + + +
+ +
+
, + ); + await act(() => + screen.container.querySelector('[aria-label="Outside"]')!.focus(), + ); + vi.mocked(useProjects).mockClear(); + + await act(() => + screen.container.querySelector('[aria-label="Terminal"]')!.focus(), + ); + await act(() => + screen.container.querySelector('[aria-label="Outside"]')!.focus(), + ); + + expect(useProjects).not.toHaveBeenCalled(); + }); it.each([ { mode: "normal", count: 2, shift: false, picker: false }, { mode: "boring", count: 2, shift: false, picker: false }, diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 178f33c37cc7f..b51e3475f749e 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -9,6 +9,7 @@ import { AsyncResult } from "effect/reactivity"; import { ADD_PROJECT_SCOPE_ITEM_VALUE, filterSidebarProjectScopeItems, + shouldCreateNewThreadInCurrentProject, resolveScopedNewThreadProjectRef, deleteSelectedThreadEntries, getFallbackThreadIdAfterDelete, @@ -59,6 +60,7 @@ import { makeThreadFixture, type ThreadFixtureOverrides } from "../test-fixtures import { completeSidebarRouteReveal, pendingSidebarRouteReveal, + observeSidebarDraftPromotion, resolveSidebarRouteReveal, } from "./sidebar/routeReveal"; @@ -1600,6 +1602,22 @@ describe("resolveSidebarRouteReveal", () => { ).toEqual({ pendingKey: null, widensScope: false }); }); + it("never reveals the thread an open draft became", () => { + const reveal = { observedKey: "environment-test:other", pendingKey: null }; + observeSidebarDraftPromotion(reveal, hiddenKey); + expect( + resolveSidebarRouteReveal({ + reveal, + routeKey: hiddenKey, + routeKeyInPlace: false, + isSearching: false, + scopedProjectKeys, + delegatedUnderParent: new Set(), + findThread, + }), + ).toEqual({ pendingKey: null, widensScope: false }); + }); + it("widens again for a thread reopened before the thread between them listed its row", () => { // The user scoped away from the open thread, then went to a thread whose row // never mounted, then came back. @@ -1740,6 +1758,16 @@ describe("resolveSidebarFolderDot", () => { }); }); +describe("shouldCreateNewThreadInCurrentProject", () => { + it("opens the picker when several projects are open, or only archived ones exist", () => { + expect(shouldCreateNewThreadInCurrentProject(false, 2, 3)).toBe(false); + expect(shouldCreateNewThreadInCurrentProject(false, 0, 2)).toBe(false); + expect(shouldCreateNewThreadInCurrentProject(false, 1, 3)).toBe(true); + expect(shouldCreateNewThreadInCurrentProject(false, 0, 0)).toBe(true); + expect(shouldCreateNewThreadInCurrentProject(true, 2, 2)).toBe(true); + }); +}); + describe("resolveScopedNewThreadProjectRef", () => { const local = { environmentId: "env-local", projectId: "api" }; const remote = { environmentId: "env-remote", projectId: "api-remote" }; diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 06788c6271cd0..ccb2eafe13c1d 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -812,6 +812,15 @@ export function isSidebarNestedLinkClick(target: EventTarget | null): boolean { return nodeClosest(parent, "a[href]") !== null; } +/** The "New thread in" picker opens unless there is one open project or none; then the current context decides. */ +export function shouldCreateNewThreadInCurrentProject( + shiftKey: boolean, + openProjectGroupCount: number, + projectGroupCount: number, +): boolean { + return shiftKey || openProjectGroupCount === 1 || projectGroupCount === 0; +} + /** * A sidebar filtered to one project already says where the next thread belongs, * so New skips the picker there. A project grouped across environments keeps the diff --git a/apps/web/src/components/Sidebar.motion.browser.test.ts b/apps/web/src/components/Sidebar.motion.browser.test.ts index 2eae3d4f83fb9..b2b0e5a4b22f8 100644 --- a/apps/web/src/components/Sidebar.motion.browser.test.ts +++ b/apps/web/src/components/Sidebar.motion.browser.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { render } from "../../test/render"; -import { createSidebarListMotion } from "./Sidebar.motion"; +import { createSidebarListMotion, sidebarListScrolled } from "./Sidebar.motion"; describe("sidebar list motion", () => { it("slides rows above a removal at the bottom instead of jumping with the scroll clamp", async () => { @@ -27,9 +27,42 @@ describe("sidebar list motion", () => { const before = above.getBoundingClientRect().top; rows[8]!.remove(); + // The clamp's scroll event can land while the update waits for its frame. + motion.scheduleUpdate(true); + viewport.dispatchEvent(new Event("scroll")); motion.update(true); for (const animation of above.getAnimations()) animation.pause(); expect(above.getBoundingClientRect().top).toBe(before); }); + + it("lands rows in place when the app scrolls right after a clamped update", async () => { + await using screen = await render(null); + const viewport = document.createElement("div"); + viewport.dataset.slot = "scroll-area-viewport"; + viewport.style.cssText = "height: 200px; overflow-y: auto; overflow-anchor: none"; + const list = document.createElement("ul"); + list.style.cssText = "position: relative; margin: 0; padding: 0; list-style: none"; + const rows = Array.from({ length: 10 }, () => { + const row = document.createElement("li"); + row.style.height = "64px"; + list.append(row); + return row; + }); + viewport.append(list); + screen.container.append(viewport); + const motion = createSidebarListMotion(list); + using _motion = { [Symbol.dispose]: () => motion.dispose() }; + motion.update(false); + viewport.scrollTop = viewport.scrollHeight; + viewport.dispatchEvent(new Event("scroll")); + + rows[8]!.remove(); + motion.update(true); + viewport.scrollTop = 0; + sidebarListScrolled(list); + for (const animation of rows[0]!.getAnimations()) animation.pause(); + + expect(rows[0]!.getBoundingClientRect().top).toBe(viewport.getBoundingClientRect().top); + }); }); diff --git a/apps/web/src/components/Sidebar.motion.ts b/apps/web/src/components/Sidebar.motion.ts index da0e7de3201b2..710a56f4af172 100644 --- a/apps/web/src/components/Sidebar.motion.ts +++ b/apps/web/src/components/Sidebar.motion.ts @@ -1,16 +1,53 @@ const motionTiming = { duration: 150, easing: "ease-out" }; const rowTravel = (height: number) => Math.min(height, 40); +const EXIT_FADE_END = 0.4; +const ENTRY_FADE_START = 0.6; +const MAX_SLIDE_ROWS = 1.5; // Fades clone removed rows and animate clones and entries; intervening layout reads force reflows. const MAX_FADED_ROWS_PER_UPDATE = 40; type RowPosition = { top: number; left: number; width: number; height: number }; +const motions = new WeakMap(); + +/** After the app scrolls a list's viewport, a scroll clamp still sliding out no longer applies. */ +export function sidebarListScrolled(list: Element) { + motions.get(list)?.scrolled(); +} + function progress(animation: Animation) { return animation.playState === "finished" ? 1 : (animation.effect?.getComputedTiming().progress ?? 0); } +function entryOpacity(animation: Animation) { + return Math.max(0, (progress(animation) - ENTRY_FADE_START) / (1 - ENTRY_FADE_START)); +} + +function crossingRows(order: readonly HTMLElement[], previousIndex: Map) { + const retained = order.filter((node) => previousIndex.has(node)); + const tails: number[] = []; + const previous: number[] = []; + for (const [index, node] of retained.entries()) { + const value = previousIndex.get(node)!; + let low = 0; + let high = tails.length; + while (low < high) { + const middle = (low + high) >> 1; + if (previousIndex.get(retained[tails[middle]!]!)! < value) low = middle + 1; + else high = middle; + } + previous[index] = low > 0 ? tails[low - 1]! : -1; + tails[low] = index; + } + const ordered = new Set(); + for (let index = tails.at(-1) ?? -1; index >= 0; index = previous[index]!) { + ordered.add(retained[index]!); + } + return new Set(retained.filter((node) => !ordered.has(node))); +} + /** Position the list so all direct children's offsetTop share an origin. */ export function createSidebarListMotion(parent: HTMLUListElement) { let positions: Map | null = null; @@ -21,10 +58,15 @@ export function createSidebarListMotion(parent: HTMLUListElement) { const running = new Map(); const entering = new Map(); const exiting = new Map(); + // The scroll clamp's part of a row's offset, added on top of its own motion so an app + // scroll can drop it alone. + const shifted = new Map(); let released: Map | null = null; const scroller = parent.closest('[data-slot="scroll-area-viewport"]'); let scrollTop = scroller?.scrollTop ?? 0; const trackScroll = () => { + // A scheduled update measures the scroll clamp from the scrollTop its last run left. + if (frame !== 0) return; scrollTop = scroller?.scrollTop ?? 0; }; scroller?.addEventListener("scroll", trackScroll, { passive: true }); @@ -34,7 +76,8 @@ export function createSidebarListMotion(parent: HTMLUListElement) { const run = current ? current.offset * (1 - progress(current.animation)) : 0; const entry = entering.get(node); const enter = entry ? entry.travel * (1 - progress(entry.animation)) : 0; - return run + enter; + const clamp = shifted.get(node); + return run + enter + (clamp ? clamp.shift * (1 - progress(clamp.animation)) : 0); }; const clearFades = () => { for (const entry of entering.values()) entry.animation.cancel(); @@ -75,10 +118,10 @@ export function createSidebarListMotion(parent: HTMLUListElement) { }); parent.append(clone); const entry = entering.get(node); - const entryProgress = entry ? progress(entry.animation) : 1; const animation = clone.animate( [ - { opacity: entryProgress, transform: "translateY(0px)" }, + { opacity: entry ? entryOpacity(entry.animation) : 1, transform: "translateY(0px)" }, + { opacity: 0, offset: EXIT_FADE_END }, { opacity: 0, transform: `translateY(${travel}px)` }, ], motionTiming, @@ -97,9 +140,11 @@ export function createSidebarListMotion(parent: HTMLUListElement) { const cancel = (node: HTMLElement) => { running.get(node)?.animation.cancel(); running.delete(node); + shifted.get(node)?.animation.cancel(); + shifted.delete(node); }; const suspend = () => { - for (const node of running.keys()) cancel(node); + for (const node of [...running.keys(), ...shifted.keys()]) cancel(node); clearFades(); positions = null; released = null; @@ -122,8 +167,27 @@ export function createSidebarListMotion(parent: HTMLUListElement) { { once: true }, ); }; + const shiftBy = (node: HTMLElement, shift: number) => { + const animation = node.animate( + [{ transform: `translateY(${shift}px)` }, { transform: "translateY(0px)" }], + { ...motionTiming, composite: "add" }, + ); + shifted.set(node, { animation, shift }); + animation.addEventListener( + "finish", + () => { + if (shifted.get(node)?.animation === animation) shifted.delete(node); + }, + { once: true }, + ); + }; + + let frame = 0; + let frameAnimates = false; + const view = parent.ownerDocument.defaultView; - return { + const api = { + /** Read every row's position and animate rows that moved. Reads layout. */ update(animate: boolean) { if (disposed) return; // A hidden list (the closed narrow sheet stays mounted) reports zero @@ -154,6 +218,21 @@ export function createSidebarListMotion(parent: HTMLUListElement) { if (!positions.has(node) && position.height > 0) fadeCount++; } } + const nextOrder = [...next.keys()]; + const oldOrder = positions === null ? [] : [...positions.keys()]; + const crossing = crossingRows(nextOrder, new Map(oldOrder.map((n, i) => [n, i] as const))); + for (const [node, position] of next) { + const previousTop = positions?.get(node)?.top; + if ( + previousTop !== undefined && + position.height > 0 && + Math.abs(previousTop + remainingOffset(node) - position.top) > + position.height * MAX_SLIDE_ROWS + ) { + crossing.add(node); + } + } + fadeCount += crossing.size * 2; const shouldAnimate = animate && positions !== null && @@ -168,8 +247,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { shift = scroller.scrollTop - scrollTop; } const movedDelta = new Map(); - const nextOrder = [...next.keys()]; - const oldOrder = positions === null ? [] : [...positions.keys()]; + const stays = (node: HTMLElement) => next.has(node) && !crossing.has(node); const ridingDelta = ( order: readonly HTMLElement[], index: number, @@ -187,12 +265,18 @@ export function createSidebarListMotion(parent: HTMLUListElement) { else { for (const [node, position] of next) { const previousTop = positions!.get(node)?.top; - if (previousTop === undefined || previousTop + shift === position.top) continue; + if ( + previousTop === undefined || + previousTop + shift === position.top || + crossing.has(node) + ) { + continue; + } movedDelta.set(node, previousTop + remainingOffset(node) - position.top + shift); } for (const [node, position] of positions!) { - if (next.has(node)) continue; - const delta = ridingDelta(oldOrder, oldOrder.indexOf(node), (n) => next.has(n)); + if (stays(node)) continue; + const delta = ridingDelta(oldOrder, oldOrder.indexOf(node), stays); fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta, shift); } } @@ -202,20 +286,28 @@ export function createSidebarListMotion(parent: HTMLUListElement) { entering.delete(node); } } - for (const node of running.keys()) { + for (const node of [...running.keys(), ...shifted.keys()]) { if (!shouldAnimate || !next.has(node)) cancel(node); } if (shouldAnimate) { for (const [index, node] of nextOrder.entries()) { const position = next.get(node)!; const previousTop = positions!.get(node)?.top; - if (previousTop === undefined) { + if (previousTop === undefined || crossing.has(node)) { + cancel(node); + entering.get(node)?.animation.cancel(); + entering.delete(node); if (position.height > 0) { - const delta = ridingDelta(nextOrder, index, (n) => positions!.has(n)); - const travel = delta === undefined ? -rowTravel(position.height) : delta; + const delta = ridingDelta( + nextOrder, + index, + (n) => positions!.has(n) && !crossing.has(n), + ); + const travel = delta === undefined ? -rowTravel(position.height) : delta - shift; const animation = node.animate( [ { opacity: 0, transform: `translateY(${travel}px)` }, + { opacity: 0, offset: ENTRY_FADE_START }, { opacity: 1, transform: "translateY(0px)" }, ], motionTiming, @@ -228,13 +320,16 @@ export function createSidebarListMotion(parent: HTMLUListElement) { }, { once: true }, ); + if (delta !== undefined && shift !== 0) shiftBy(node, shift); } continue; } const delta = movedDelta.get(node); // Computed progress includes easing; carry forward only our translation, never dnd-kit's // transforms. - if (delta !== undefined) move(node, delta); + if (delta === undefined) continue; + move(node, delta - shift); + if (shift !== 0) shiftBy(node, shift); } } if (released !== null) { @@ -249,6 +344,19 @@ export function createSidebarListMotion(parent: HTMLUListElement) { positions = next; if (scroller !== null) scrollTop = scroller.scrollTop; }, + /** `update` in the next frame, before it paints, so a commit's own layout + * pass is the one read instead of a forced one mid-commit. A chat + * mounting in the same commit made that forced layout expensive. Calls + * before the frame coalesce; the last one decides whether rows animate. */ + scheduleUpdate(animate: boolean) { + if (disposed || !view) return; + frameAnimates = animate; + if (frame !== 0) return; + frame = view.requestAnimationFrame(() => { + frame = 0; + api.update(frameAnimates); + }); + }, release() { suspend(); const origin = parent.getBoundingClientRect().top; @@ -259,10 +367,20 @@ export function createSidebarListMotion(parent: HTMLUListElement) { ); }, suspend, + /** Drop the clamp shift: rows an app scroll brings on screen land where they belong. */ + scrolled() { + for (const { animation } of shifted.values()) animation.cancel(); + shifted.clear(); + if (scroller !== null) scrollTop = scroller.scrollTop; + }, dispose() { suspend(); + if (frame !== 0) view?.cancelAnimationFrame(frame); scroller?.removeEventListener("scroll", trackScroll); + if (motions.get(parent) === api) motions.delete(parent); disposed = true; }, }; + motions.set(parent, api); + return api; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index b5c2e67b5804a..19808baa8ae87 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -2,6 +2,7 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { msg, T, useGT, useMessages } from "gt-react"; import { m } from "../i18n/messages"; import { deleteConfirm } from "../confirmDialog"; +import { ThreadContextDragGhost } from "./chat/ThreadContextDragGhost"; import { attachSidebarTree } from "../lib/sidebarTree"; import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; @@ -10,7 +11,25 @@ import { endThreadContextDrag, moveThreadContextDrag as moveThreadContextDragGhost, } from "./chat/threadContextDrag"; -import { appearanceFontStack } from "../appearanceFonts"; +import { + isLayoutGhostTabShown, + selectFocusedLayoutGhostId, + selectFocusedTab, + selectLayoutThreadKeys, +} from "../layout/layoutModel"; +import { followLayoutCompanions } from "../layout/openRules"; +import { isThreadlessSurfacesRef } from "../threadlessSurfaces"; +import { useLayoutStore } from "../layout/layoutStore"; +import { + cancelLayoutDrag, + dropLayoutDrag, + moveLayoutDrag, + OPEN_THREAD_TO_THE_SIDE_MENU_ID, + openThreadToTheSide, + withOpenThreadToTheSideItem, +} from "../layout/layoutDrag"; +import { appearanceFontStack, DEFAULT_SANS_FONT_STACK } from "../appearanceFonts"; +import { wasThreadSettledByUser } from "../layout/settledByUser"; import { discardComposerDraft } from "../lib/discardComposerDraft"; import { requestCustomSnooze } from "./CustomSnoozeDialog"; import { useAtomValue } from "@effect/atom-react"; @@ -83,6 +102,7 @@ import { type MouseEvent as ReactMouseEvent, type ReactNode, } from "react"; +import { flushSync } from "react-dom"; import { type AnyRouter, useRouter } from "@tanstack/react-router"; import { @@ -220,7 +240,7 @@ import { restrictBelowSidebarLabel, } from "./Sidebar.drag"; import { SidebarPointerSensor } from "./Sidebar.pointer"; -import { createSidebarListMotion } from "./Sidebar.motion"; +import { createSidebarListMotion, sidebarListScrolled } from "./Sidebar.motion"; import { createSidebarShiftGuard } from "./Sidebar.shiftGuard"; import { pickSnoozePreset, resolveSnoozePresets, type SnoozePreset } from "./Sidebar.snooze"; import { ProjectFavicon } from "./ProjectFavicon"; @@ -229,6 +249,7 @@ import { useStableCallback } from "../hooks/useStableCallback"; import { resolveSidebarRouteReveal, type SidebarRouteReveal, + observeSidebarDraftPromotion, useActiveRowReveal, } from "./sidebar/routeReveal"; import { stackedThreadToast, toastManager } from "./ui/toast"; @@ -255,6 +276,7 @@ import { DraftId, useComposerDraftStore, usePromotingDraftThreadKeys } from "../ import { useShownThreadRouteTarget } from "../hooks/useShownThreadRouteTarget"; import { SidebarSearchResultRow, + SidebarThreadRow, SortableThreadRow, type SidebarProviderEntry, type SidebarSweepAction, @@ -354,6 +376,7 @@ interface SidebarThreadPartitionInput { readonly serverConfigs: ReadonlyMap; readonly connectedEnvironmentIds: readonly EnvironmentId[]; readonly optimisticDrop: SidebarOptimisticDrop | null; + readonly layoutThreadKeys: ReadonlySet; readonly workingShelfEnabled: boolean; /** Boring mode: folders list active threads by the user's latest message. */ readonly sortActiveBySend: boolean; @@ -427,6 +450,7 @@ function useSidebarThreads(input: { readonly folderGroups: readonly SidebarProjectSnapshot[] | null; // Keeps folders with no active threads, so a project the user filtered to or pinned can start one. readonly keepEmptyFolders: (group: SidebarProjectSnapshot) => boolean; + readonly layoutThreadKeys: ReadonlySet; }) { const { projectScopeKey, @@ -440,6 +464,7 @@ function useSidebarThreads(input: { departingThreadKey, folderGroups, keepEmptyFolders: keepEmpty, + layoutThreadKeys, } = input; const shelfRouteThreadKey = routeRowThreadKey === departingThreadKey ? null : routeRowThreadKey; // Folders already separate the work, so boring mode has no Working shelf. @@ -487,6 +512,7 @@ function useSidebarThreads(input: { serverConfigs, connectedEnvironmentIds, optimisticDrop, + layoutThreadKeys, workingShelfEnabled, sortActiveBySend: folderGroups !== null, clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, @@ -643,9 +669,18 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { serverConfigs, connectedEnvironmentIds: input.connectedEnvironmentIds, }); + const { layoutThreadKeys } = input; + for (const key of settledWhenOpened.keys()) { + if (!layoutThreadKeys.has(key)) settledWhenOpened.delete(key); + } for (const thread of visible) { const configLoaded = serverConfigs.has(thread.environmentId); const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + // A thread seen active while open stays active after automatic settlement. + if (layoutThreadKeys.has(threadKey)) { + if (thread.settledOverride !== "settled") settledWhenOpened.set(threadKey, false); + else if (!settledWhenOpened.has(threadKey)) settledWhenOpened.set(threadKey, true); + } if (optimisticDrop?.key === threadKey) { const projected = applySidebarThreadDrop( thread, @@ -666,7 +701,12 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { } else { const section = resolveSidebarThreadSection({ snoozed: configLoaded && effectiveSnoozed(thread, { now: preciseNow }), - settled: configLoaded && thread.settledOverride === "settled", + settled: + configLoaded && + thread.settledOverride === "settled" && + (!layoutThreadKeys.has(threadKey) || + settledWhenOpened.get(threadKey) !== false || + wasThreadSettledByUser(threadKey)), pinned: thread.pinnedAt != null, }); (section === "snoozed" @@ -943,7 +983,32 @@ function revealSidebarRow(viewport: HTMLElement, row: HTMLElement) { target = bottom(item) <= withPrevious + clientHeight - SIDEBAR_LIST_FADE_PX ? withPrevious : top(item); } - if (target !== scrollTop) viewport.scrollTop = Math.min(maxScroll, Math.max(0, target)); + const next = Math.min(maxScroll, Math.max(0, target)); + if (next === scrollTop) return; + viewport.scrollTop = next; + sidebarListScrolled(list); +} + +/** + * Whether each open thread was settled every time the sidebar saw it while its tab was open. Only + * one settled while open (a merge) stays in the active list; opening a settled thread to read it + * leaves it on the shelf. Module scope: the sidebar unmounts on Settings routes, and the answer + * must outlive that. + */ +const settledWhenOpened = new Map(); + +function revealSidebarShelf(header: HTMLElement) { + const viewport = header.closest('[data-slot="scroll-area-viewport"]'); + const lastRow = Array.from( + header + .closest("ul") + ?.querySelectorAll( + `[data-sidebar-parent="${CSS.escape(header.dataset.sidebarRow ?? "")}"]`, + ) ?? [], + ).at(-1); + if (!viewport || !lastRow) return; + revealSidebarRow(viewport, lastRow); + revealSidebarRow(viewport, header); } export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) { @@ -1084,6 +1149,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : null; const [renamingTitle, setRenamingTitle] = useState(""); const renamingOriginalTitleRef = useRef(""); + const drawnGhostKeptByClickRef = useRef(null); const settlingThreadKeysRef = useRef(new Set()); const threadListRef = useRef(null); const searchResultsListRef = useRef(null); @@ -1115,6 +1181,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve routeDraftRedirect, ); const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; + // The URL stays on the last chat while a surface has focus; the current row is the surface's. + const focusedSurfaceThreadRef = useLayoutStore((state) => { + const content = selectFocusedTab(state.layout)?.content; + return content?.kind === "surface" && !isThreadlessSurfacesRef(content.threadRef) + ? content.threadRef + : null; + }); + const currentThreadRef = focusedSurfaceThreadRef ?? routeThreadRef; // A selection made under one scope can hold threads the next scope hides. // The viewport outlives the scope and does not anchor, so a new list starts at the top. @@ -1160,14 +1234,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : thread, ); const routeRowThreadKey = - routeThreadRef === null + currentThreadRef === null ? null - : scopedThreadKey(resolveListedAncestorThreadRef(routeThreadRef, threads)); + : scopedThreadKey(resolveListedAncestorThreadRef(currentThreadRef, threads)); const isSearchingThreads = threadSearchQuery.trim().length > 0; // The open draft's first send names its thread in place; a finalized draft reached by // navigation resolves through its redirect instead, and still reveals. const routeKeyInPlace = routeDraftThread?.promotedTo != null; + if (routeTarget?.kind === "draft" && routeKeyInPlace) { + observeSidebarDraftPromotion(routeReveal, routeRowThreadKey); + } // History, the palette and links can open a thread the scope hides or the list // scrolled away; a remount starts at the top, so each mount scrolls to the open // thread once. Render decides the widening, so the first frame of the new route @@ -1305,8 +1382,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const clicked = await settlePromise(() => api.contextMenu.show( [ - { id: "new-thread", label: gt("New thread") }, - { id: "copy-path", label: gt("Copy path") }, + { id: "new-thread", label: gt("New thread"), icon: "square-pen" }, + { id: "copy-path", label: gt("Copy path"), icon: "copy" }, ...(canPinProject(group) ? [ group.pinned @@ -1340,6 +1417,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, ); + // A signature avoids sidebar updates for pane focus and resize alone. + const onScreenThreadKeys = useLayoutStore((state) => state.onScreenThreadKeys); + const layoutThreadKeysSignature = useLayoutStore((state) => + selectLayoutThreadKeys(state.layout).join("\n"), + ); + const layoutThreadKeys = new Set( + layoutThreadKeysSignature === "" ? [] : layoutThreadKeysSignature.split("\n"), + ); const { workingShelfEnabled, pinnedThreads, @@ -1394,6 +1479,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : null, keepEmptyFolders: (group) => scopedProjectGroups.length > 0 || (group.pinned && !group.archived), + layoutThreadKeys, }); // Ranked across environments as the palette ranks them, so one @@ -1502,12 +1588,34 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (isMobile) { setOpenMobile(false); } + // A tab already open in the layout takes focus even if its URL is current. + followLayoutCompanions(() => + useLayoutStore.getState().focusChat({ kind: "server", threadRef }), + ); return router.navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(threadRef), }); }; + const keepFocusedGhostChatWasDrawn = (threadRef: ScopedThreadRef) => { + const store = useLayoutStore.getState(); + const ghostId = selectFocusedLayoutGhostId(store.layout, { + kind: "chat", + target: { kind: "server", threadRef }, + }); + if (ghostId === null) return false; + const wasShown = isLayoutGhostTabShown(store.layout, ghostId); + store.keepTab(ghostId); + return wasShown; + }; + + const openThreadFromRow = (threadRef: ScopedThreadRef) => { + const keptDrawnGhost = keepFocusedGhostChatWasDrawn(threadRef); + void navigateToThread(threadRef); + return keptDrawnGhost; + }; + const handleThreadFileDrop = async (threadRef: ScopedThreadRef, files: File[]) => { const dropId = queuePendingFileDrop({ threadRef, files }); const landedBefore = @@ -1616,27 +1724,51 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }; const readOpensPullRequestsInRightPanel = useStableCallback(() => routeThreadRef !== null); - const handleThreadClick = (event: ReactMouseEvent, threadRef: ScopedThreadRef) => { - if (isSidebarNestedLinkClick(event.target)) return; - const isMac = isMacPlatform(navigator.platform); - const isModClick = isMac ? event.metaKey : event.ctrlKey; - const threadKey = scopedThreadKey(threadRef); - if (isModClick) { - event.preventDefault(); - toggleThreadSelection(threadKey); - return; - } - if (event.shiftKey) { - event.preventDefault(); - rangeSelectTo(threadKey, orderedThreadKeysRef.current); - return; - } - // macOS keeps counting quick clicks across rows, so only the open row's trailing click is a double-click. - if (isTrailingDoubleClick(event.detail) && routeThreadKey === threadKey) { - return; - } - navigateToThread(threadRef); - }; + const handleThreadClick = useStableCallback( + (event: ReactMouseEvent, threadRef: ScopedThreadRef) => { + if (isSidebarNestedLinkClick(event.target)) return; + const isMac = isMacPlatform(navigator.platform); + const isModClick = isMac ? event.metaKey : event.ctrlKey; + const threadKey = scopedThreadKey(threadRef); + if (isModClick) { + event.preventDefault(); + toggleThreadSelection(threadKey); + return; + } + if (event.shiftKey) { + event.preventDefault(); + rangeSelectTo(threadKey, orderedThreadKeysRef.current); + return; + } + // macOS keeps counting quick clicks across rows, so only the open row's trailing click is a double-click. + if (isTrailingDoubleClick(event.detail) && routeThreadKey === threadKey) { + return; + } + if (event.button === 1) { + // Middle click keeps the thread open as a tab; the URL follows the focused tab. + event.preventDefault(); + followLayoutCompanions(() => + useLayoutStore + .getState() + .openKeptTab({ kind: "chat", target: { kind: "server", threadRef } }), + ); + return; + } + if (event.altKey) { + event.preventDefault(); + openThreadToTheSide(threadRef); + return; + } + drawnGhostKeptByClickRef.current = openThreadFromRow(threadRef) ? threadKey : null; + }, + ); + + const handleThreadDoubleClick = useStableCallback((threadRef: ScopedThreadRef, title: string) => { + const keptDrawnGhostByClick = drawnGhostKeptByClickRef.current === scopedThreadKey(threadRef); + drawnGhostKeptByClickRef.current = null; + if (keepFocusedGhostChatWasDrawn(threadRef) || keptDrawnGhostByClick) return; + startThreadRename(threadRef, title); + }); // Snapshot navigation before partition mutation; background parks use a null plan. const planForwardNavigation = ( @@ -1644,6 +1776,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve coParkingKeys?: ReadonlySet, ): (() => void) | null => { if (readRouteThreadKey(router) !== threadKey) return null; + // Closing a parked thread's layout tabs chooses the neighboring pane or launcher. + if (selectLayoutThreadKeys(useLayoutStore.getState().layout).includes(threadKey)) return null; const shell = threadByKeyRef.current.get(threadKey); const orderedKeys = orderedThreadKeysRef.current; const settledKeys = settledThreadKeysRef.current; @@ -1791,6 +1925,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve contextDragKeyRef.current = null; dragScrollRef.current = null; endThreadContextDrag(); + cancelLayoutDrag(); if (started) { listMotionRef.current?.release(); setDragState(null); @@ -1832,19 +1967,32 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); if (!contextDrag) { endThreadContextDrag(); + cancelLayoutDrag(); return false; } restoreDragScroll(); const threads = contextDragThreads(); const threadRef = parseScopedThreadKey(contextDragKeyRef.current ?? ""); const title = (threadRef && readThreadShell(threadRef)?.title.trim()) || gt("Thread"); - moveThreadContextDragGhost(point, { title, count: threads.length }); + const composer = moveThreadContextDragGhost(point, { + title, + count: threads.length, + width: threadListRef.current?.getBoundingClientRect().width ?? 0, + }); + // One thread can also land in the layout (pen jVRc4). A composer under + // the pointer keeps the drop as context. + const [thread] = threads; + if (threads.length === 1 && thread) { + moveLayoutDrag({ kind: "thread", threadRef: thread }, point, { composer }); + } else { + cancelLayoutDrag(); + } return true; }; const dropThreadContextDrag = (point: { x: number; y: number }) => { if (!pointerOutsideThreadList(point)) return false; restoreDragScroll(); - dropThreadContext(point, contextDragThreads()); + if (!dropThreadContext(point, contextDragThreads())) dropLayoutDrag(); return true; }; // useSensor memoizes options identity; fresh options rebuild DndContext and every sortable row. @@ -2079,7 +2227,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve // Shelf rows would travel over stationary headers below the bottom-anchored shelf. const shelvesUnchanged = previousShelfExpansionKeyRef.current === shelfExpansionKey; previousShelfExpansionKeyRef.current = shelfExpansionKey; - listMotionRef.current?.update(listMotionPass.animate && shelvesUnchanged); + listMotionRef.current?.scheduleUpdate(listMotionPass.animate && shelvesUnchanged); }, [listMotionPass, shelfExpansionKey]); const handleThreadDragOver = (event: DragOverEvent) => { const target = event.over @@ -2124,6 +2272,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Keep the active row visible as layout changes until the user scrolls. useEffect(() => { if (routeRowThreadKey === null || routeRowSection === null || isSearchingThreads) return; + if (routeReveal.quietKey === routeRowThreadKey) return; const list = threadListRef.current; const viewport = list?.closest('[data-slot="scroll-area-viewport"]'); if (!list || !viewport) return; @@ -2148,7 +2297,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve release(); for (const type of userInput) viewport.removeEventListener(type, release); }; - }, [isSearchingThreads, routeRowSection, routeRowThreadKey]); + }, [isSearchingThreads, routeReveal, routeRowSection, routeRowThreadKey]); const draggedThreadKey = dragState?.activeKey; const draggedFromSection = dragState?.activeSection; const dragActivationY = dragState?.activationY; @@ -2756,47 +2905,53 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) ?? null; const clicked = await settlePromise(() => api.contextMenu.show( - buildThreadActionMenuItems({ - canOperate: readEnvironmentScope( - threadRef.environmentId, - AuthOrchestrationOperateScope, - ), - branch: thread.branch ?? null, - // An archived project is not a filter choice. - projectFilter: - threadProjectGroup && !threadProjectGroup.archived - ? { - label: threadProjectGroup.displayName, - isActive: projectScopeKeys.includes(threadProjectGroup.projectKey), - } - : null, - isPinned, - isSettled, - autoSettleEnabled: thread.autoSettleDisabledAt == null, - isSnoozed, - canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), - isRegeneratingTitle, - isRunning: !threadRuntimeCanArchive(thread.runtime), - hasCompletedRun: thread.latestRun?.completedAt != null, - canShareWithGuest: appAtomRegistry.get( - canShareWithGuestAtom(threadRef.environmentId), - ), - canTurnIntoProject: canTurnThreadIntoProject(threadRef), - canRename: !fromSearch, - supports: { - settlement: configLoaded, - autoSettleOptOut: supportsAutoSettleOptOut, - snooze: configLoaded, - pinning: configLoaded, - titleRegeneration: configLoaded, - }, - snoozePresets, - }), + withOpenThreadToTheSideItem( + threadRef, + buildThreadActionMenuItems({ + canOperate: readEnvironmentScope( + threadRef.environmentId, + AuthOrchestrationOperateScope, + ), + branch: thread.branch ?? null, + projectFilter: + threadProjectGroup && !threadProjectGroup.archived + ? { + label: threadProjectGroup.displayName, + isActive: projectScopeKeys.includes(threadProjectGroup.projectKey), + } + : null, + isPinned, + isSettled, + autoSettleEnabled: thread.autoSettleDisabledAt == null, + isSnoozed, + canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), + isRegeneratingTitle, + isRunning: !threadRuntimeCanArchive(thread.runtime), + hasCompletedRun: thread.latestRun?.completedAt != null, + canShareWithGuest: appAtomRegistry.get( + canShareWithGuestAtom(threadRef.environmentId), + ), + canTurnIntoProject: canTurnThreadIntoProject(threadRef), + canRename: !fromSearch, + supports: { + settlement: configLoaded, + autoSettleOptOut: supportsAutoSettleOptOut, + snooze: configLoaded, + pinning: configLoaded, + titleRegeneration: configLoaded, + }, + snoozePresets, + }), + ), position, source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; + if (clicked.value === OPEN_THREAD_TO_THE_SIDE_MENU_ID) { + openThreadToTheSide(threadRef); + return; + } if (threadActionRequiresOperate(clicked.value) && !checkThreadOperations([thread])) return; if (clicked.value?.startsWith("snooze:")) { const preset = @@ -3449,7 +3604,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve snoozedThreads.length === 0 && (settledCount === 0 || scopedProjectGroups.length > 0) ? ( -
+
{projects.length === 0 ? gt("No projects yet") @@ -3497,10 +3657,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
+ + + ); +} + +function ThreadSurfaceContent({ + threadRef, + surface, + context, + visible, + openers, + openInPane, + getShortcutContext, +}: { + threadRef: ScopedThreadRef; + surface: RightPanelSurface; + context: ReturnType; + visible: boolean; + openers: ReturnType; + openInPane: (kind: LauncherSurfaceKind) => void; + getShortcutContext: () => { + terminalFocus: boolean; + terminalOpen: boolean; + previewFocus: boolean; + previewOpen: boolean; + isWeb: boolean; + isDesktop: boolean; + }; +}) { + const gt = useGT(); + const bridge = useThreadChatBridge(threadRef); + const { paneId } = useLayoutPane(); + const keybindings = useAtomValue(primaryServerKeybindingsAtom); + const availableEditors = + useAtomValue(serverEnvironment.configValueAtom(threadRef.environmentId))?.availableEditors ?? + []; + const workspaceMutationId = bridge?.workspaceMutationId ?? null; + const [pendingFiles, setPendingFiles] = useState>(EMPTY_PENDING); + const onPendingChange = (relativePath: string, pending: boolean) => { + setPendingFiles((current) => { + const id = `file:${relativePath}`; + if (current.has(id) === pending) return current; + const next = new Set(current); + if (pending) next.add(id); + else next.delete(id); + return next; + }); + }; + const configuredUrls = getConfiguredPreviewUrls(context.projectScripts); + const terminal = useTerminalSurfaceActions(threadRef, surface, context); + const shortcutLabels = useTerminalShortcutLabels(); + const shell = context.serverThread; + const sideChatParentPanel: SideChatParentPanel = { + hostRef: threadRef, + openToolDiff: (target) => { + useDiffPanelStore.getState().selectToolCall(threadRef, target); + useRightPanelStore.getState().open(threadRef, "diff"); + }, + runShellCommand: openers.runShellCommand, + }; + + switch (surface.kind) { + case "thread": + return ( + + void closeThreadSurface(threadRef, surface.id)} + /> + + ); + case "linked-thread": + return ( + + + + ); + case "preview": + return ( + + void sendAnnotationFromChat(threadRef, paneId, annotation, image), + })} + /> + + ); + case "terminal": + return ( + addTerminalContextFromChat(threadRef, paneId, selection) + } + onSplitTerminal={terminal.split} + onSplitTerminalVertical={terminal.splitVertical} + onNewTerminal={() => openInPane("terminal")} + onActiveTerminalChange={terminal.activate} + onCloseTerminal={terminal.close} + {...shortcutLabels} + /> + ); + case "diff": + return ( + + + + ); + case "pull-request": + if (!context.serverConfig) return ; + return ( + }> + { + useRightPanelStore + .getState() + .settlePullRequestReveal(threadRef, surface.id, revealUrl); + }} + onTabChange={(tab) => + useRightPanelStore.getState().setPullRequestDetailTab(threadRef, surface.id, tab) + } + getShortcutContext={getShortcutContext} + shortcutsEnabled={visible} + environmentId={ + (surface.environmentId as EnvironmentId | undefined) ?? threadRef.environmentId + } + onSelectPullRequest={(reference) => + useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + projectId: reference.projectId, + repository: reference.repository, + number: reference.number, + ...(reference.host ? { host: reference.host } : {}), + }) + } + threadRef={context.threadless ? null : threadRef} + reference={{ + projectId: surface.projectId as ProjectId, + ...(surface.host ? { host: surface.host } : {}), + repository: surface.repository, + number: surface.number, + }} + context={pullRequestPanelContext( + { + projectId: shell?.projectId ?? context.project?.id ?? null, + pullRequests: visibleThreadPullRequests(shell?.pullRequests ?? []), + linkedPullRequest: shell?.linkedPullRequest ?? null, + branchPullRequest: shell?.branchPullRequest ?? null, + }, + surface, + )} + // Threadless, its hand-offs start a thread, as the pull requests page's do. + {...(context.composerDraftTarget + ? { composerDraftTarget: context.composerDraftTarget } + : {})} + onBack={ + openers.available["pull-requests"] && + visibleThreadPullRequests(shell?.pullRequests ?? []).length > 1 + ? () => openInPane("pull-requests") + : undefined + } + /> + + ); + case "issue": + if (!context.serverConfig) return ; + if (context.serverConfig.environment.capabilities.issues !== true) { + return ( + + ); + } + return ( + }> + + useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + projectId: reference.projectId, + repository: reference.repository, + number: reference.number, + ...(reference.host ? { host: reference.host } : {}), + }) + } + onSelectIssue={({ host, ...reference }) => + useRightPanelStore.getState().openIssue(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + ...reference, + ...(host ? { host } : {}), + }) + } + // Back to the linked items, as a pull request among several goes back to them. + {...(openers.available["pull-requests"] && + visibleThreadPullRequests(shell?.pullRequests ?? []).length + + (shell?.issues?.length ?? 0) > + 1 + ? { + onBack: () => openInPane("pull-requests"), + backLabel: gt("Back to linked items"), + } + : {})} + /> + + ); + + case "pull-requests": + return ; + case "device": + return ( + + + + ); + case "files": + case "file": { + const attachment = surface.kind === "file" ? surface.attachment : undefined; + if (!context.workspaceRoot && !attachment) { + return ( + } + title={gt("No project folder")} + description={gt("This thread has no workspace folder, so there are no files to show.")} + /> + ); + } + return ( + + + useRightPanelStore.getState().openFile(threadRef, relativePath) + } + onNavigateFolder={(relativePath, folderTrail, keepSource) => + useRightPanelStore + .getState() + .navigateFolder(threadRef, surface.id, relativePath, folderTrail, keepSource) + } + folderTrail={surface.folderTrail} + onPendingChange={onPendingChange} + selectedFilePending={surface.kind === "file" && pendingFiles.has(surface.id)} + workspaceMutationId={workspaceMutationId} + /> + + ); + } + } +} + +async function addTerminalContextFromChat( + threadRef: ScopedThreadRef, + paneId: string | null, + selection: TerminalContextSelection, +): Promise { + let bridge = useThreadChatBridgeStore.getState().byThreadKey[scopedThreadKey(threadRef)] ?? null; + if (!bridge) { + showThreadChatBeside(threadRef, paneId); + bridge = await waitForThreadChatSendReady(threadRef, 15_000); + } + if (bridge) { + bridge.addTerminalContext(selection); + return true; + } + toastManager.add({ + type: "error", + title: m(msg("Could not add terminal output to chat")), + description: m( + msg("The chat is not ready. Your terminal selection is still available to add again."), + ), + }); + return false; +} + +/** + * Send a browser annotation the way the chat sends anything: from its + * composer, which already holds the annotation. A closed chat opens beside + * the browser first and sends once it can. + */ +async function sendAnnotationFromChat( + threadRef: ScopedThreadRef, + paneId: string | null, + annotation: PreviewAnnotationPayload, + image: ComposerImageAttachment | null, +): Promise { + const open = useThreadChatBridgeStore.getState().byThreadKey[scopedThreadKey(threadRef)]; + if (open) { + open.sendAnnotation(annotation, image); + return; + } + showThreadChatBeside(threadRef, paneId); + const bridge = await waitForThreadChatSendReady(threadRef, 15_000); + if (bridge) { + bridge.sendAnnotation(annotation, image); + return; + } + toastManager.add( + stackedThreadToast({ + type: "info", + title: m(msg("Annotation attached to draft")), + description: m(msg("The chat could not send it yet. Send it from the chat.")), + }), + ); +} + +/** A terminal surface's own split, switch and close, as ChatView's panel had them. */ +function useTerminalSurfaceActions( + threadRef: ScopedThreadRef, + surface: RightPanelSurface, + context: ReturnType, +) { + const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open"); + const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close"); + const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); + const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal); + const allocateTerminalId = useTerminalIdAllocator(threadRef); + const canWrite = () => readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope); + const split = (direction: "horizontal" | "vertical" = "horizontal") => { + if ( + !canWrite() || + surface.kind !== "terminal" || + surface.terminalIds.length >= MAX_TERMINALS_PER_GROUP + ) { + return; + } + const terminalId = allocateTerminalId(); + const input = terminalOpenInput(threadRef, terminalId, context); + if (input === null) return; + useRightPanelStore.getState().splitTerminal(threadRef, surface.id, terminalId, direction); + focusTerminal(threadRef, terminalId); + void openTerminal({ environmentId: threadRef.environmentId, input }); + }; + return { + split: () => split("horizontal"), + splitVertical: () => split("vertical"), + activate: (terminalId: string) => { + if (surface.kind !== "terminal") return; + useRightPanelStore.getState().activateTerminal(threadRef, surface.id, terminalId); + focusTerminal(threadRef, terminalId); + }, + close: (terminalId: string) => { + if (!canWrite() || surface.kind !== "terminal") return; + void closeTerminalMutation({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, terminalId, deleteHistory: true }, + }).then((result) => { + if ( + result._tag === "Failure" && + !isAtomCommandInterrupted(result) && + readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope) + ) { + return writeTerminal({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, terminalId, data: "exit\n" }, + }); + } + }); + storeCloseTerminal(threadRef, terminalId); + useRightPanelStore.getState().closeTerminal(threadRef, surface.id, terminalId); + focusActivePanelTerminal(threadRef); + }, + }; +} + +// Closing + +type SurfaceCloser = (threadRef: ScopedThreadRef, surfaces: readonly RightPanelSurface[]) => void; +/** Registered by `ThreadSurfaceServices`: ends what closed surfaces ran. */ +let surfaceServices: { + cleanup: SurfaceCloser; + endTerminals: (threadRef: ScopedThreadRef, terminalIds: readonly string[]) => void; +} | null = null; + +function readTerminalTabTitles( + threadRef: ScopedThreadRef, + terminalIds: readonly string[], +): string[] { + const sessions = readEnvironmentScope(threadRef.environmentId, AuthTerminalReadScope) + ? appAtomRegistry.get(knownTerminalSessionsAtom(threadRef.environmentId, threadRef.threadId)) + : null; + return terminalIds.map((terminalId) => + terminalTabTitle( + terminalId, + resolveTerminalSessionLabel( + terminalId, + sessions?.find((session) => session.target.terminalId === terminalId)?.state.summary, + m, + ), + m, + ), + ); +} + +/** Closing a surface ends its resources; cmd+J preserves the thread terminal's shells. */ +export async function closeThreadSurface( + threadRef: ScopedThreadRef, + surfaceId: string, + options: { bulk?: boolean } = {}, +): Promise { + if (surfaceId === THREAD_TERMINAL_SURFACE_ID) { + if (readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) { + const { terminalIds } = selectThreadTerminalUiState( + useTerminalUiStateStore.getState().terminalUiStateByThreadKey, + threadRef, + ); + const [first, ...rest] = readTerminalTabTitles(threadRef, terminalIds); + if (first !== undefined) { + if (!options.bulk && !(await confirmTerminalClose([first, ...rest]))) return; + surfaceServices?.endTerminals(threadRef, terminalIds); + } + } + useTerminalUiStateStore.getState().setTerminalOpen(threadRef, false); + return; + } + const surface = selectThreadRightPanelState( + useRightPanelStore.getState().byThreadKey, + threadRef, + ).surfaces.find((candidate) => candidate.id === surfaceId); + if (!surface) return; + const finish = () => { + surfaceServices?.cleanup(threadRef, [surface]); + useRightPanelStore.getState().closeSurface(threadRef, surface.id); + }; + if (surface.kind === "preview") { + const message = agentControlledBrowserCloseConfirmation( + [surface], + readThreadPreviewState(threadRef).desktopByTabId, + ); + if (message) { + const confirmed = await readLocalApi() + ?.dialogs.confirm(message, { variant: "destructive" }) + .catch(() => false); + if (!confirmed) return; + } + finish(); + return; + } + if ( + surface.kind === "terminal" && + !options.bulk && + readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope) + ) { + const [first = m(msg("Terminal")), ...rest] = readTerminalTabTitles( + threadRef, + surface.terminalIds, + ); + if (!(await confirmTerminalClose([first, ...rest]))) return; + } + finish(); +} + +/** + * Take a thread's surface tabs off the layout, its terminal tab included. + * Nothing they run ends; alt+cmd+B and cmd+J bring them back. + */ +export function hideThreadSurfaceTabs(threadRef: ScopedThreadRef): void { + useRightPanelStore.getState().close(threadRef); + useTerminalUiStateStore.getState().setTerminalOpen(threadRef, false); +} + +/** + * Close every surface of a thread without asking, because the thread itself is + * being discarded: browsers and terminals end, and its terminal tab hides. + */ +export function discardThreadSurfaces(threadRef: ScopedThreadRef): void { + const { surfaces } = selectThreadRightPanelState( + useRightPanelStore.getState().byThreadKey, + threadRef, + ); + surfaceServices?.cleanup(threadRef, surfaces); + useRightPanelStore.getState().closeAllSurfaces(threadRef); + useTerminalUiStateStore.getState().setTerminalOpen(threadRef, false); +} + +/** + * Hide a thread's surfaces (alt+cmd+B): a live browser or device on screen + * floats in its mini player instead of disappearing. + */ +export function hideThreadSurfaces(threadRef: ScopedThreadRef): void { + const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef); + const active = state.surfaces.find((surface) => surface.id === state.activeSurfaceId); + if (active?.kind === "preview" && active.resourceId) { + usePreviewMiniPlayerStore + .getState() + .open(threadRef, browserMiniPlayerSource(active.resourceId)); + } else if (active?.kind === "device" && active.target) { + usePreviewMiniPlayerStore.getState().open(threadRef, { kind: "device", ...active.target }); + } + useRightPanelStore.getState().close(threadRef); +} + +/** + * Mounted once with the layout host: ends what closed surfaces ran (preview + * sessions, terminal sessions) through this client's connections. + */ +export function ThreadSurfaceServices() { + const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false }); + const closePreview = useAtomCommand(previewEnvironment.close, "preview close"); + const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close"); + const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); + const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Register mounted surface resource closers with the external lifecycle registry. + useEffect(() => { + const end = (threadRef: ScopedThreadRef, terminalIds: readonly string[]) => { + if (!readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) return; + for (const terminalId of terminalIds) { + storeCloseTerminal(threadRef, terminalId); + void closeTerminalMutation({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, terminalId, deleteHistory: true }, + }).then((result) => { + if ( + result._tag === "Failure" && + !isAtomCommandInterrupted(result) && + readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope) + ) { + return writeTerminal({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, terminalId, data: "exit\n" }, + }); + } + }); + } + }; + const closer: SurfaceCloser = (threadRef, surfaces) => { + for (const surface of surfaces) { + if ( + surface.kind === "thread" && + // Only a side chat the shell still lists is thrown away with its tab; a subagent belongs + // to its parent's work, and an unlisted side chat is already deleted. + readThreadShell(scopeThreadRef(threadRef.environmentId, surface.threadId))?.lineage + .sideChat === true && + readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) + ) { + void deleteThread({ + environmentId: threadRef.environmentId, + input: { threadId: surface.threadId, onlyIfUnused: true }, + }); + } + if ( + surface.kind === "preview" && + surface.resourceId && + readEnvironmentScope(threadRef.environmentId, AuthPreviewOperateScope) + ) { + void closePreviewSession({ + closePreview, + snapshot: readThreadPreviewState(threadRef).sessions[surface.resourceId] ?? null, + tabId: surface.resourceId, + threadRef, + }); + } + if ( + surface.kind === "terminal" && + readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope) + ) { + end(threadRef, surface.terminalIds); + } + } + }; + const services = { cleanup: closer, endTerminals: end }; + surfaceServices = services; + return () => { + if (surfaceServices === services) surfaceServices = null; + }; + }, [closePreview, closeTerminalMutation, storeCloseTerminal, writeTerminal, deleteThread]); + return null; +} diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index 7632d01b5f907..8871843f159b5 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -20,6 +20,7 @@ import { extractTerminalLinks } from "../terminal-links"; import { expect, it, vi } from "vite-plus/test"; import { act, fakeTimers, render } from "../../test/render"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; +import type { TerminalContextSelection } from "../lib/terminalContext"; const fixture = vi.hoisted(() => ({ statusByThreadId: new Map(), @@ -46,6 +47,10 @@ const fixture = vi.hoisted(() => ({ string, Atom.Writable> >(), + contextMenu: undefined as ((event: MouseEvent) => void) | undefined, + showContextMenu: vi.fn(), + selection: "", + clearSelection: vi.fn(), })); // Every other surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it. @@ -58,6 +63,14 @@ const fakeSurface: object = new Proxy( const size = fixture.reportedSize; if (size) fixture.surfaceOptions.at(-1)!.onResize(size.cols, size.rows); }, + hasSelection: () => fixture.selection.length > 0, + getSelection: () => fixture.selection, + getSelectionPosition: () => ({ start: { y: 0 }, end: { y: 1 } }), + getSelectionEndClientRect: () => null, + clearSelection: () => { + fixture.clearSelection(); + fixture.selection = ""; + }, }, { get: (target, key) => @@ -69,6 +82,7 @@ vi.mock("~/terminal/ghostty/surface", () => ({ create: (_mount: HTMLElement, options: GhosttyTerminalSurfaceOptions) => new Promise((resolve) => { fixture.surfaceOptions.push(options); + fixture.contextMenu = options.onContextMenu; fixture.pendingSurfaces.push(() => { fixture.typeIntoSurface = options.onData; fixture.pressKey = options.beforeKey ?? null; @@ -170,8 +184,14 @@ vi.mock("../state/use-atom-command", () => ({ vi.mock("../state/server", async () => { const Atom = await import("effect/reactivity/Atom"); const config = Atom.make(null); - return { serverEnvironment: { configValueAtom: () => config } }; + return { + serverEnvironment: { configValueAtom: () => config }, + // The pane notch reads the theme (black chrome keeps the notch), which reads server themes. + themeServerEnvironmentThemesAtom: Atom.make([]), + }; }); +// The pane notch's theme loads main's theme background, which needs the real environment state. +vi.mock("../themeBackground", () => ({ applyThemeBackground: () => {} })); vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: fixture.resizeCommand }, })); @@ -200,9 +220,16 @@ vi.mock("../state/projects", async () => { }, }; }); +vi.mock("../layout/PaneTabs", () => ({ + LayoutPaneTab: () => null, + LayoutPaneTabStrip: ({ children }: { children: React.ReactNode }) => children, + useLayoutPaneSiblingTabs: () => ({ before: [], after: [] }), +})); vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} })); vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} })); -vi.mock("~/localApi", () => ({ readLocalApi: () => null })); +vi.mock("~/localApi", () => ({ + readLocalApi: () => ({ contextMenu: { show: fixture.showContextMenu } }), +})); vi.mock("../hooks/useSettings", async () => { const { DEFAULT_CLIENT_SETTINGS } = await import("@t3tools/contracts/settings"); return { @@ -218,6 +245,7 @@ function Drawer(props: { cwd?: string; onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; keybindings?: ResolvedKeybindingsConfig; + onAddTerminalContext?: (selection: TerminalContextSelection) => Promise; }) { return ( {}} onCloseTerminal={props.onCloseTerminal} onHeightChange={() => {}} - onAddTerminalContext={() => {}} + onAddTerminalContext={props.onAddTerminalContext} keybindings={props.keybindings ?? []} /> ); @@ -267,6 +295,10 @@ function setup(originalStatus: "starting" | "exited" = "exited") { fixture.metadata.clear(); useRightPanelStore.setState(useRightPanelStore.getInitialState()); useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState()); + fixture.contextMenu = undefined; + fixture.showContextMenu.mockReset().mockResolvedValue("add-to-chat"); + fixture.selection = "selected output"; + fixture.clearSelection.mockReset(); return { original, other }; } @@ -554,3 +586,29 @@ it("resends a failed resize once in each writable session", async () => { }; expect(resizes).toEqual([resize, resize, resize]); }); + +it.each([false, true])("clears selected output only after chat accepts it: %s", async (added) => { + const { other } = setup(); + let accept: (added: boolean) => void = () => {}; + const onAddTerminalContext = vi.fn( + () => + new Promise((resolve) => { + accept = resolve; + }), + ); + await using _screen = await render( + {}} + onAddTerminalContext={onAddTerminalContext} + />, + ); + await act(() => fixture.pendingSurfaces.shift()?.()); + await act(() => fixture.contextMenu?.(new MouseEvent("contextmenu", { cancelable: true }))); + expect(onAddTerminalContext).toHaveBeenCalledWith( + expect.objectContaining({ text: "selected output" }), + ); + expect(fixture.clearSelection).not.toHaveBeenCalled(); + await act(() => accept(added)); + expect(fixture.clearSelection).toHaveBeenCalledTimes(added ? 1 : 0); +}); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 71886cb135db2..bf485f531b4d3 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -13,13 +13,8 @@ import { type TerminalOutputUpdate, type TerminalSessionState, } from "@t3tools/client-runtime/state/terminal"; -import { - Plus, - SquareSplitHorizontal, - SquareSplitVertical, - SquareTerminal, - Trash2, -} from "lucide-react"; +import { Plus, SquareTerminal } from "lucide-react"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { AuthPreviewOperateScope, AuthFilesystemReadScope, @@ -35,11 +30,14 @@ import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy"; import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { msg, T, useGT, useMessages } from "gt-react"; import { m, type MessageResolver } from "../i18n/messages"; +import { terminalTabTitle } from "../layout/surfaceTabLabels"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; import { + type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode, + type RefObject, useEffect, useContext, useEffectEvent, @@ -50,11 +48,20 @@ import { import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { Button } from "~/components/ui/button"; import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button"; +import { PaneNotch } from "~/components/PaneNotch"; +import { beginLayoutTabDrag } from "~/layout/layoutDrag"; +import { useLayoutStore } from "~/layout/layoutStore"; +import { useLayoutPane, useLayoutPaneFocusedRef } from "~/layout/layoutPaneContext"; +import { LayoutPaneTab, LayoutPaneTabStrip, useLayoutPaneSiblingTabs } from "~/layout/PaneTabs"; import { ScrollArea } from "~/components/ui/scroll-area"; import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { stackedThreadToast, toastManager } from "~/components/ui/toast"; import { readTextFromClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard"; import { cn } from "~/lib/utils"; +import { + COLLAPSED_SIDEBAR_INSET_EASE_CLASS, + COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS, +} from "~/workspaceTitlebar"; import { type TerminalContextSelection } from "~/lib/terminalContext"; import { GhosttyTerminalSurface, @@ -62,6 +69,7 @@ import { } from "~/terminal/ghostty/surface"; import { type GhosttyColor, type GhosttyTheme } from "~/terminal/ghostty/core"; import { useOpenInPreferredEditor } from "../editorPreferences"; +import { useStableCallback } from "../hooks/useStableCallback"; import { isTerminalUrl, resolveTerminalLinkTarget } from "../terminal-links"; import { isDiffToggleShortcut, @@ -71,6 +79,7 @@ import { isTerminalSplitVerticalShortcut, isTerminalToggleShortcut, isThreadNavigationShortcut, + resolveShortcutCommand, terminalDeleteShortcutData, terminalNavigationShortcutData, } from "../keybindings"; @@ -80,13 +89,15 @@ import { type ThreadTerminalGroup, } from "../types"; import { readLocalApi } from "~/localApi"; -import { confirmTerminalClose } from "~/lib/terminalCloseConfirm"; +import { confirmTerminalClose, isTerminalCloseConfirmPending } from "~/lib/terminalCloseConfirm"; +import { getTerminalFocusOwner, registerTerminalSplitTarget } from "~/lib/terminalFocus"; import { useClientSettings } from "../hooks/useSettings"; import { getFileMetadataQueryAtom } from "../hooks/useFileMetadata"; import { FileMetadataThreadContext } from "../hooks/FileMetadataThreadProvider"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { attachedTerminalSessionAtom } from "../state/terminalSessions"; import { appAtomRegistry } from "../rpc/atomRegistry"; +import { useRevealActiveTab } from "../hooks/useRevealActiveTab"; import { serverEnvironment } from "../state/server"; import { previewEnvironment } from "../state/preview"; import { readEnvironmentScope } from "../state/session"; @@ -480,7 +491,9 @@ interface TerminalViewportProps { runtimeEnv?: Record; providerInstanceId?: ProviderInstanceId; onSessionExited: () => void; - onAddTerminalContext?: (selection: TerminalContextSelection) => void; + onAddTerminalContext?: + | ((selection: TerminalContextSelection) => void | Promise) + | undefined; /** Focuses the viewport when it mounts; otherwise focus arrives through `focusTerminal`. */ autoFocus?: boolean; visible: boolean; @@ -525,6 +538,7 @@ function TerminalSessionViewport({ const autoFocusedRef = useRef(false); const terminalRef = useRef(null); const visibleRef = useRef(visible); + const paneFocusedRef = useLayoutPaneFocusedRef(); const environmentId = threadRef.environmentId; const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope); const hasTerminalWriteAccess = useEffectEvent(() => @@ -598,7 +612,7 @@ function TerminalSessionViewport({ if (hasTerminalWriteAccess()) onSessionExited(); }); const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => { - onAddTerminalContext?.(selection); + return onAddTerminalContext?.(selection); }); const canAddSelectionToChat = useEffectEvent(() => onAddTerminalContext !== undefined); const readTerminalLabel = useEffectEvent(() => terminalLabel); @@ -841,14 +855,21 @@ function TerminalSessionViewport({ }; }; - const addSelectionToChat = (clipboardText: string) => { + const addSelectionToChat = async (clipboardText: string) => { // Output keeps moving the selected rows while a menu is open, so take // the line numbers now, and only if the same text is still selected. const current = readSelectionAction(); if (current?.clipboardText !== clipboardText) return; - handleAddTerminalContext(current.selection); - terminalRef.current?.clearSelection(); - terminalRef.current?.focus(); + const activeTerminal = terminalRef.current; + const added = await handleAddTerminalContext(current.selection); + if ( + added === false || + terminalRef.current !== activeTerminal || + activeTerminal?.getSelection() !== clipboardText + ) + return; + activeTerminal.clearSelection(); + activeTerminal.focus(); }; const reportIfCurrent = (requestId: number, error: unknown, fallback: string) => { @@ -932,7 +953,7 @@ function TerminalSessionViewport({ switch (clicked) { case "add-to-chat": if (selectionAction && canAddSelectionToChat()) { - addSelectionToChat(selectionAction.clipboardText); + await addSelectionToChat(selectionAction.clipboardText); } return; case "copy": @@ -1041,6 +1062,9 @@ function TerminalSessionViewport({ ) { return false; } + // Tab switching belongs to the layout, so it bubbles to the app's handler. + const command = resolveShortcutCommand(event, currentKeybindings, options); + if (command === "tab.next" || command === "tab.previous") return false; const navigationData = terminalNavigationShortcutData(event); if (navigationData !== null) { @@ -1194,7 +1218,8 @@ function TerminalSessionViewport({ focusTerminalViewport({ mount, surface: terminalRef.current, - canOperate: readEnvironmentScope(environmentId, AuthTerminalOperateScope), + canOperate: + paneFocusedRef.current && readEnvironmentScope(environmentId, AuthTerminalOperateScope), visible: visibleRef.current, }); // Once per viewport: a re-attached ref (a fresh callback identity) must not @@ -1226,9 +1251,11 @@ function TerminalSessionViewport({ } interface ThreadTerminalDrawerProps { - mode?: "drawer" | "panel"; + /** "pane" fills a layout pane (cmd+J) and still owns the drawer's terminals. */ + mode?: "drawer" | "panel" | "pane"; threadRef: ScopedThreadRef; threadId: ThreadId; + threadTitle?: string | null; cwd: string; worktreePath?: string | null; runtimeEnv?: Record; @@ -1243,65 +1270,21 @@ interface ThreadTerminalDrawerProps { onSplitTerminal: () => void; onSplitTerminalVertical: () => void; onNewTerminal: () => void; - splitShortcutLabel?: string | undefined; - splitVerticalShortcutLabel?: string | undefined; newShortcutLabel?: string | undefined; closeShortcutLabel?: string | undefined; onActiveTerminalChange: (terminalId: string) => void; onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; onHeightChange: (height: number) => void; - onAddTerminalContext: (selection: TerminalContextSelection) => void; + onAddTerminalContext: + | ((selection: TerminalContextSelection) => void | Promise) + | undefined; keybindings: ResolvedKeybindingsConfig; terminalLabelsById?: ReadonlyMap; /** Run status per terminal for the tab's tooltip; missing ids read as an idle shell. */ terminalStatusById?: ReadonlyMap; terminalLaunchLocationsById?: ReadonlyMap; -} - -interface TerminalActionButtonProps { - label: string; - onClick: () => void; - /** Keeps the tooltip reachable (it explains the limit), unlike `disabled`. */ - unavailable?: boolean; - children: ReactNode; - disabled?: boolean; -} - -function TerminalActionButton({ - label, - onClick, - unavailable, - children, -}: TerminalActionButtonProps) { - return ( - - { - if (!unavailable) onClick(); - }} - aria-label={label} - aria-disabled={unavailable || undefined} - /> - } - > - {children} - - - {label} - - - ); + /** Its sessions are still loading: with none to show yet, it draws just its background. */ + attaching?: boolean; } function TerminalSplitPanes({ @@ -1329,7 +1312,9 @@ function TerminalSplitPanes({ advancedTypography: boolean; threadRef: ScopedThreadRef; threadId: ThreadId; - onAddTerminalContext: (selection: TerminalContextSelection) => void; + onAddTerminalContext: + | ((selection: TerminalContextSelection) => void | Promise) + | undefined; visible: boolean; keybindings: ResolvedKeybindingsConfig; }) { @@ -1390,10 +1375,119 @@ function TerminalSplitPanes({ ); } +interface TerminalActionButtonProps { + label: string; + onClick: () => void; + unavailable?: boolean; + children: ReactNode; + /** "bare" for the notch's "+", which matches the chat tab strip's. */ + variant?: "ghost-muted" | "bare"; +} + +/** + * The terminal pane's tabs: in a layout pane they sit in the pane's notch with + * "+" as its last child, like a chat's tabs. The drawer keeps a plain row. + */ +function TerminalTabsNotch({ + notch, + newTerminalButton, + children, +}: { + notch: boolean; + newTerminalButton: ReactNode; + children: ReactNode; +}) { + if (!notch) return children; + return ( + + {children} + + {newTerminalButton} + + + ); +} + +function TerminalTabStrip({ + notch, + ref, + children, +}: { + notch: boolean; + ref: RefObject; + children: ReactNode; +}) { + const gt = useGT(); + const { tabId } = useLayoutPane(); + if (notch) { + return ( +
+ {children} +
+ ); + } + return ( + +
+ {children} +
+
+ ); +} + +function TerminalActionButton({ + label, + onClick, + unavailable, + children, + variant = "ghost-muted", +}: TerminalActionButtonProps) { + return ( + + { + if (!unavailable) onClick(); + }} + aria-label={label} + aria-disabled={unavailable || undefined} + /> + } + > + {children} + + + {label} + + + ); +} + export default function ThreadTerminalDrawer({ mode = "drawer", threadRef, threadId, + threadTitle, cwd, worktreePath, runtimeEnv, @@ -1407,8 +1501,6 @@ export default function ThreadTerminalDrawer({ onSplitTerminal, onSplitTerminalVertical, onNewTerminal, - splitShortcutLabel, - splitVerticalShortcutLabel, newShortcutLabel, closeShortcutLabel, onActiveTerminalChange, @@ -1419,12 +1511,18 @@ export default function ThreadTerminalDrawer({ terminalLabelsById, terminalStatusById, terminalLaunchLocationsById, + attaching = false, }: ThreadTerminalDrawerProps) { const gt = useGT(); const messages = useMessages(); const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope); const terminalArea = workspaceAreaProps("terminal", 5, gt("Terminal")); const isPanel = mode === "panel"; + const fillsContainer = mode !== "drawer"; + const terminalOwner = mode === "panel" ? "right-panel" : "drawer"; + // As a pane, this is a layout tab: dragging one of its terminals moves it. + const { tabId: layoutTabId, leadingEdge, trailingEdge } = useLayoutPane(); + const siblingTabs = useLayoutPaneSiblingTabs(); const [advancedTypography] = useLocalStorage( TYPOGRAPHY_ADVANCED_STORAGE_KEY, false, @@ -1567,44 +1665,24 @@ export default function ThreadTerminalDrawer({ const splitDirection = resolvedTerminalGroups[resolvedActiveGroupIndex]?.splitDirection ?? "horizontal"; const isSplitView = visibleTerminalIds.length > 1; + const tabStripRef = useRef(null); + useRevealActiveTab(tabStripRef, resolvedActiveTerminalId); const resolveTerminalLaunchLocation = (terminalId: string): TerminalLaunchLocation => terminalLaunchLocationsById?.get(terminalId) ?? { cwd, ...(worktreePath !== undefined ? { worktreePath } : {}), ...(runtimeEnv ? { runtimeEnv } : {}), }; - const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP; - const splitTerminalActionLabel = hasReachedSplitLimit - ? gt("Split Terminal Horizontally (max {max} per group)", { max: MAX_TERMINALS_PER_GROUP }) - : splitShortcutLabel - ? gt("Split Terminal Horizontally ({shortcut})", { shortcut: splitShortcutLabel }) - : gt("Split Terminal Horizontally"); - const splitTerminalVerticalActionLabel = hasReachedSplitLimit - ? gt("Split Terminal Vertically (max {max} per group)", { max: MAX_TERMINALS_PER_GROUP }) - : splitVerticalShortcutLabel - ? gt("Split Terminal Vertically ({shortcut})", { shortcut: splitVerticalShortcutLabel }) - : gt("Split Terminal Vertically"); - const onSplitTerminalAction = () => { - if (!canOperateTerminal || hasReachedSplitLimit) return; - onSplitTerminal(); - }; - const onSplitTerminalVerticalAction = () => { - if (!canOperateTerminal || hasReachedSplitLimit) return; - onSplitTerminalVertical(); - }; const newTerminalActionLabel = newShortcutLabel ? gt("New Terminal ({shortcut})", { shortcut: newShortcutLabel }) : gt("New Terminal"); - const closeTerminalActionLabel = closeShortcutLabel - ? gt("Close Terminal ({shortcut})", { shortcut: closeShortcutLabel }) - : gt("Close Terminal"); const onNewTerminalAction = () => { if (!canOperateTerminal) return; onNewTerminal(); }; const confirmCloseTerminal = (terminalId: string) => { if (!canOperateTerminal) return; - const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId); + const label = terminalTabTitle(terminalId, terminalLabelById.get(terminalId)); void confirmTerminalClose([label]).then((confirmed) => { if (confirmed && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) { onCloseTerminal(terminalId, threadRef); @@ -1612,6 +1690,77 @@ export default function ThreadTerminalDrawer({ }); }; + // The terminal's own keys answer here, so they work whether or not its + // thread's chat is open. Without operate access they keep their native meaning. + const onShortcutKeyDown = (event: ReactKeyboardEvent) => { + if (!canOperateTerminal || getTerminalFocusOwner() === null) return; + const command = resolveShortcutCommand(event.nativeEvent, keybindings, { + context: { terminalFocus: true, terminalOpen: true }, + }); + if ( + command !== "terminal.split" && + command !== "terminal.splitVertical" && + command !== "terminal.new" && + command !== "terminal.close" + ) { + return; + } + event.preventDefault(); + event.stopPropagation(); + if (command === "terminal.split") onSplitTerminal(); + else if (command === "terminal.splitVertical") onSplitTerminalVertical(); + else if (command === "terminal.new") onNewTerminalAction(); + else if (!event.repeat && !isTerminalCloseConfirmPending()) { + confirmCloseTerminal(resolvedActiveTerminalId); + } + }; + + const hasTerminal = useStableCallback(() => visibleTerminalIds.length > 0); + const canSplitTerminal = useStableCallback( + () => canOperateTerminal && visibleTerminalIds.length < MAX_TERMINALS_PER_GROUP, + ); + const paneFocusedRef = useLayoutPaneFocusedRef(); + const threadKey = scopedThreadKey(threadRef); + const splitTerminalFromPalette = useStableCallback((direction: "horizontal" | "vertical") => { + if (direction === "vertical") onSplitTerminalVertical(); + else onSplitTerminal(); + }); + // A terminal takes focus only in the focused pane, so a terminal pane claims it first. + const focusActiveTerminalNow = useStableCallback(() => { + if (resolvedActiveTerminalId) focusTerminal(threadRef, resolvedActiveTerminalId); + }); + const focusActiveTerminal = useStableCallback(() => { + if (layoutTabId === null || paneFocusedRef.current) { + focusActiveTerminalNow(); + return; + } + useLayoutStore.getState().focusTab(layoutTabId); + window.requestAnimationFrame(focusActiveTerminalNow); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- The command palette reaches this pane's split, the one its keys run, while the pane is mounted. + useEffect( + () => + registerTerminalSplitTarget({ + threadKey, + contains: (element) => drawerRef.current?.contains(element) ?? false, + inFocusedPane: () => visible && paneFocusedRef.current, + visible: () => visible, + hasTerminal, + canSplit: canSplitTerminal, + split: splitTerminalFromPalette, + focusActive: focusActiveTerminal, + }), + [ + canSplitTerminal, + focusActiveTerminal, + hasTerminal, + paneFocusedRef, + splitTerminalFromPalette, + threadKey, + visible, + ], + ); + const handleResizePointerDown = (event: ReactPointerEvent) => { if (event.button !== 0) return; event.preventDefault(); @@ -1688,7 +1837,7 @@ export default function ThreadTerminalDrawer({ } // The column and window may have resized while the drawer was hidden and // not listening, so measure before the first visible paint. - const column = isPanel ? null : chatColumnOf(drawerRef.current); + const column = fillsContainer ? null : chatColumnOf(drawerRef.current); const onWindowResize = () => updateDrawerLayout(column, "window"); onWindowResize(); const header = column?.querySelector("[data-chat-header]"); @@ -1702,9 +1851,9 @@ export default function ThreadTerminalDrawer({ stopObserving?.(); window.removeEventListener("resize", onWindowResize); }; - }, [isPanel, visible]); + }, [fillsContainer, visible]); - const resizeHandle = isPanel ? null : ( + const resizeHandle = fillsContainer ? null : (
{resizeHandle} -
-

- No terminal sessions for this thread yet. -

- -
+ {attaching ? null : ( +
+

+ No terminal sessions for this thread yet. +

+ +
+ )} ); } @@ -1760,59 +1912,52 @@ export default function ThreadTerminalDrawer({ ); - // Keep every terminal action in the header so controls never cover shell output. - const terminalActions = ( -
- - - - - - - {newTerminalButton} - confirmCloseTerminal(resolvedActiveTerminalId)} - unavailable={!canOperateTerminal} - > - - -
- ); - return (