Map thread panel into title bar and sidebar

- Add thread-panel presentation logic for inline vs popover layouts
- Move thread details controls into the chat header/sidebar flow
- Add shared wait-for-atom helper and workspace display name parsing

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-08-15 16:49:46 +02:00
1 parent 4d64e80184
commit c8aea5db0b
40 files changed
+1926 -869

No files matched your search

@@ -123,11 +123,7 @@ export function useThreadComposerState() {
return null;
}
return deriveActiveWorkStartedAt(
selectedThread.latestRun,
selectedThreadSessionActivity,
null,
);
return deriveActiveWorkStartedAt(selectedThread.latestRun, selectedThreadSessionActivity, null);
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
const activeThreadBusy = !!selectedThread && threadRuntimeIsActive(selectedThread.runtime);
@@ -13,10 +13,7 @@ import {
resolveBranchToolbarPrBranch,
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
resolveLocalCheckoutBranchMismatch,
resolvePreviousWorktreeLabel,
resolvePreviousWorktreeSeed,
sanitizeNewRefName,
resolveWorkspaceDisplayName,
shouldIncludeBranchPickerItem,
shouldShowComposerContextStrip,
shouldShowEnvironmentIndicator,
@@ -504,6 +501,18 @@ describe("resolveLockedWorkspaceLabel", () => {
});
});
describe("resolveWorkspaceDisplayName", () => {
it("returns the final folder for POSIX and Windows paths", () => {
expect(resolveWorkspaceDisplayName("/repo/.t3/worktrees/feature-a")).toBe("feature-a");
expect(resolveWorkspaceDisplayName("C:\\code\\project\\feature-b\\")).toBe("feature-b");
});
it("handles missing and root paths", () => {
expect(resolveWorkspaceDisplayName(null)).toBeNull();
expect(resolveWorkspaceDisplayName("/")).toBe("/");
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
@@ -730,93 +739,4 @@ describe("shouldIncludeBranchPickerItem", () => {
}),
).toBe(false);
});
// Typing a spaced name must still surface the ref it would have been created
// as, or the picker shows nothing at all for that query.
it("surfaces an existing ref matching the sanitized query", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "new-branch",
normalizedQuery: "new branch",
createBranchItemValue: null,
checkoutPullRequestItemValue: null,
}),
).toBe(true);
});
// A partial query has to reach the ref it would have been created as, so
// searching "hello w" still finds an existing hello-world.
it("surfaces a ref from a partial query containing a space", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "hello-world",
normalizedQuery: "hello w",
createBranchItemValue: null,
checkoutPullRequestItemValue: null,
}),
).toBe(true);
});
it("excludes refs matching neither the raw nor the sanitized query", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "main",
normalizedQuery: "new branch",
createBranchItemValue: null,
checkoutPullRequestItemValue: null,
}),
).toBe(false);
});
});
// Git rejects ASCII space and the ASCII control characters in ref names, so a
// typed name like "new branch" can only ever fail. Replacing exactly those can
// turn a failing name into a working one without touching a name git already
// accepts, including one holding non-ASCII whitespace such as U+00A0.
describe("sanitizeNewRefName", () => {
it("replaces a space with a dash", () => {
expect(sanitizeNewRefName("new branch")).toBe("new-branch");
});
it("collapses a run of whitespace into a single dash", () => {
expect(sanitizeNewRefName("new branch")).toBe("new-branch");
});
it("trims surrounding whitespace instead of turning it into dashes", () => {
expect(sanitizeNewRefName(" new branch ")).toBe("new-branch");
});
it("replaces tabs, which git rejects just like spaces", () => {
expect(sanitizeNewRefName("new\tbranch")).toBe("new-branch");
});
// git accepts U+00A0, U+2009 and other non-ASCII whitespace in ref names, so
// rewriting them would silently create a ref the user never typed.
it("preserves whitespace that git accepts", () => {
expect(sanitizeNewRefName("new\u00a0branch")).toBe("new\u00a0branch");
expect(sanitizeNewRefName("new\u2009branch")).toBe("new\u2009branch");
});
it("keeps slashes so nested ref names survive", () => {
expect(sanitizeNewRefName("feature/new thing")).toBe("feature/new-thing");
});
it("preserves case because git ref names are case sensitive", () => {
expect(sanitizeNewRefName("Feature/New Thing")).toBe("Feature/New-Thing");
});
it("leaves an already valid ref name untouched", () => {
expect(sanitizeNewRefName("feature/login")).toBe("feature/login");
});
it("returns an empty string for whitespace-only input", () => {
expect(sanitizeNewRefName(" ")).toBe("");
});
// Scoped deliberately to whitespace: git accepts consecutive dashes, so
// collapsing them would rewrite names the user may have typed on purpose.
it("does not collapse dashes the user typed", () => {
expect(sanitizeNewRefName("new - branch")).toBe("new---branch");
expect(sanitizeNewRefName("foo--bar")).toBe("foo--bar");
});
});
+5 -45
View File
@@ -74,51 +74,11 @@ export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null):
return activeWorktreePath ? "Worktree" : "Local checkout";
}
export interface PreviousWorktreeSeed {
branch: string | null;
worktreePath: string;
}
// The most recently touched worktree in the project that the composer isn't
// already pointing at. Backs the "Previous worktree" entry in the workspace
// selector so a follow-up thread can hop back into the worktree you just
// worked in without hunting for its branch. Archived threads don't compete —
// the rest of the UI hides them, so their worktrees shouldn't resurface here.
export function resolvePreviousWorktreeSeed(input: {
threads: ReadonlyArray<{
branch: string | null;
worktreePath: string | null;
updatedAt: string;
archivedAt?: string | null;
}>;
currentWorktreePath: string | null;
}): PreviousWorktreeSeed | null {
let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
for (const thread of input.threads) {
if (
!thread.worktreePath ||
thread.worktreePath === input.currentWorktreePath ||
(thread.archivedAt ?? null) !== null
) {
continue;
}
const updatedAt = toSortableTimestamp(thread.updatedAt);
if (updatedAt === null) {
continue;
}
if (latest === null || updatedAt > latest.updatedAt) {
latest = {
branch: thread.branch,
worktreePath: thread.worktreePath,
updatedAt,
};
}
}
return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
}
export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
export function resolveWorkspaceDisplayName(path: string | null): string | null {
if (!path) return null;
const normalizedPath = path.replace(/[\\/]+$/, "");
if (normalizedPath.length === 0) return path;
return normalizedPath.split(/[\\/]/).at(-1) ?? normalizedPath;
}
export function resolveEffectiveEnvMode(input: {
+38
View File
@@ -42,6 +42,8 @@ import {
import { Separator } from "./ui/separator";
interface BranchToolbarProps {
layout?: "composer" | "panel";
panelSection?: "all" | "workspace" | "branch";
environmentId: EnvironmentId;
threadId: ThreadId;
showGitControls: boolean;
@@ -374,6 +376,8 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
}
export const BranchToolbar = memo(function BranchToolbar({
layout = "composer",
panelSection = "all",
environmentId,
threadId,
showGitControls,
@@ -465,6 +469,40 @@ export const BranchToolbar = memo(function BranchToolbar({
if (!hasActiveThread || !activeProject) return null;
if (layout === "panel") {
return (
<div className="flex w-full flex-col" data-thread-panel-run-context>
{panelSection !== "branch" ? (
<BranchToolbarEnvModeSelector
displayMode="panel"
envLocked={envModeLocked}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
workspaceRoot={activeProject.workspaceRoot}
onEnvModeChange={onEnvModeChange}
/>
) : null}
{panelSection !== "workspace" ? (
<BranchToolbarBranchSelector
displayMode="panel"
className="w-full"
environmentId={environmentId}
threadId={threadId}
{...(draftId ? { draftId } : {})}
envLocked={envLocked}
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
/>
) : null}
</div>
);
}
return (
<div
ref={setStripElement}
@@ -32,6 +32,10 @@ import { threadEnvironment } from "../state/threads";
import { useAtomCommand } from "../state/use-atom-command";
import { vcsEnvironment } from "../state/vcs";
import { cn } from "../lib/utils";
import {
THREAD_DETAILS_PANEL_ICON_CLASS,
THREAD_DETAILS_PANEL_ROW_CLASS,
} from "./chat/threadDetailsPanelStyles";
import { parsePullRequestReference } from "../pullRequestReference";
import { getSourceControlPresentation } from "../sourceControlPresentation";
import {
@@ -68,6 +72,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
interface BranchToolbarBranchSelectorProps {
className?: string;
displayMode?: "toolbar" | "panel";
environmentId: EnvironmentId;
threadId: ThreadId;
draftId?: DraftId;
@@ -87,6 +92,7 @@ function toBranchActionErrorMessage(error: unknown): string {
export function BranchToolbarBranchSelector({
className,
displayMode = "toolbar",
environmentId,
threadId,
draftId,
@@ -728,8 +734,11 @@ export function BranchToolbarBranchSelector({
value={resolvedActiveBranch}
>
<div
className={cn("flex min-w-0 items-center gap-1", className)}
data-composer-context-control
className={cn(
"flex min-w-0 items-center gap-1",
displayMode === "panel" && "w-full",
className,
)}
>
{branchPr && branchPrStatus ? (
<Tooltip>
@@ -752,35 +761,39 @@ export function BranchToolbarBranchSelector({
<TooltipPopup side="top">{branchPrTooltip}</TooltipPopup>
</Tooltip>
) : null}
{/* Context menu lives on the wrapper: the disabled Button has
pointer-events-none, so the trigger itself never sees right-clicks
while refs are loading or a branch action is pending. */}
<span
className="flex min-w-0"
onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
<ComboboxTrigger
render={<Button variant="ghost" size={displayMode === "panel" ? "sm" : "xs"} />}
className={cn(
"min-w-0 text-muted-foreground/70 hover:text-foreground/80",
displayMode === "panel" && THREAD_DETAILS_PANEL_ROW_CLASS,
)}
disabled={isInitialBranchesLoadPending || isBranchActionPending}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="min-w-0 max-w-full text-muted-foreground/70 hover:text-foreground/80"
disabled={isInitialBranchesLoadPending || isBranchActionPending}
<GitBranchIcon
className={cn(
"size-3 shrink-0 opacity-70",
displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS,
)}
/>
<span
data-composer-label
className={cn(
"min-w-0 max-w-[240px] truncate",
displayMode === "panel"
? "max-w-none flex-1 text-left"
: "transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0",
)}
>
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
<span
data-composer-label
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
<span
data-composer-label-motion
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
>
{triggerLabel}
</span>
</span>
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</ComboboxTrigger>
</span>
{triggerLabel}
</span>
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</ComboboxTrigger>
</div>
<ComboboxPopup align="end" side="top" className="flex w-80 flex-col">
<ComboboxPopup
align={displayMode === "panel" ? "start" : "end"}
side={displayMode === "panel" ? "bottom" : "top"}
className="flex w-80 flex-col"
>
<div className="shrink-0 px-3 pt-2.5">
<div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
<SearchIcon
@@ -1,10 +1,17 @@
import { FolderGit2Icon, FolderGitIcon, FolderIcon, HistoryIcon } from "lucide-react";
import { memo, useMemo } from "react";
import { cn } from "../lib/utils";
import {
THREAD_DETAILS_PANEL_ICON_CLASS,
THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
THREAD_DETAILS_PANEL_ROW_CLASS,
} from "./chat/threadDetailsPanelStyles";
import {
resolveCurrentWorkspaceLabel,
resolveEnvModeLabel,
resolveLockedWorkspaceLabel,
resolveWorkspaceDisplayName,
type EnvMode,
} from "./BranchToolbar.logic";
import {
@@ -16,6 +23,7 @@ import {
SelectTrigger,
SelectValue,
} from "./ui/select";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
export const PREVIOUS_WORKTREE_SELECT_VALUE = "previous-worktree";
@@ -23,37 +31,40 @@ interface BranchToolbarEnvModeSelectorProps {
envLocked: boolean;
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
workspaceRoot?: string | null;
onEnvModeChange: (mode: EnvMode) => void;
previousWorktreeLabel?: string | null;
onUsePreviousWorktree?: () => void;
displayMode?: "toolbar" | "panel";
}
export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({
envLocked,
effectiveEnvMode,
activeWorktreePath,
workspaceRoot = null,
onEnvModeChange,
previousWorktreeLabel,
onUsePreviousWorktree,
displayMode = "toolbar",
}: BranchToolbarEnvModeSelectorProps) {
const showPreviousWorktree = Boolean(previousWorktreeLabel && onUsePreviousWorktree);
const workspacePath = displayMode === "panel" ? (activeWorktreePath ?? workspaceRoot) : null;
const workspaceDisplayName = resolveWorkspaceDisplayName(workspacePath);
const workspaceKind = activeWorktreePath ? "Worktree" : "Project folder";
const envModeItems = useMemo(
() => [
{ value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) },
{
value: "local",
label: workspaceDisplayName ?? resolveCurrentWorkspaceLabel(activeWorktreePath),
},
{ value: "worktree", label: resolveEnvModeLabel("worktree") },
...(showPreviousWorktree && previousWorktreeLabel
? [{ value: PREVIOUS_WORKTREE_SELECT_VALUE, label: previousWorktreeLabel }]
: []),
],
[activeWorktreePath, previousWorktreeLabel, showPreviousWorktree],
[activeWorktreePath, workspaceDisplayName],
);
if (envLocked) {
<<<<<<< HEAD
return (
<span
className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"
data-composer-context-control
>
<span className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
{activeWorktreePath ? (
<>
<FolderGitIcon className="size-3" />
@@ -64,9 +75,43 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
<FolderIcon className="size-3" />
{resolveLockedWorkspaceLabel(activeWorktreePath)}
</>
=======
const lockedRow = (
<span
className={cn(
"inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs",
displayMode === "panel" && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
)}
>
{activeWorktreePath ? (
<FolderGitIcon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
) : (
<FolderIcon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
)}
<span className="min-w-0 flex-1 truncate">
{workspaceDisplayName ?? resolveLockedWorkspaceLabel(activeWorktreePath)}
</span>
{displayMode === "panel" ? (
<span className="shrink-0 text-[10px] font-normal text-muted-foreground/70">
{workspaceKind}
</span>
) : null}
</span>
);
if (!workspacePath) return lockedRow;
return (
<Tooltip>
<TooltipTrigger render={lockedRow} />
<TooltipPopup side="left">{workspacePath}</TooltipPopup>
</Tooltip>
);
}
return (
@@ -82,32 +127,51 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
}}
items={envModeItems}
>
<SelectTrigger
variant="ghost"
size="xs"
className="min-w-0 shrink font-medium"
aria-label="Workspace"
data-composer-context-control
>
{effectiveEnvMode === "worktree" ? (
<FolderGit2Icon className="size-3" />
) : activeWorktreePath ? (
<FolderGitIcon className="size-3" />
) : (
<FolderIcon className="size-3" />
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
<Tooltip>
<TooltipTrigger
render={
<SelectTrigger
variant="ghost"
size={displayMode === "panel" ? "default" : "xs"}
className={cn(
"min-w-0 shrink font-medium",
displayMode === "panel" && THREAD_DETAILS_PANEL_ROW_CLASS,
)}
aria-label="Workspace"
/>
}
>
{effectiveEnvMode === "worktree" ? (
<FolderGit2Icon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
) : activeWorktreePath ? (
<FolderGitIcon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
) : (
<FolderIcon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
)}
<span
data-composer-label-motion
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
data-composer-label
className={
displayMode === "panel"
? undefined
: "min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
}
>
<SelectValue />
</span>
</span>
</SelectTrigger>
{displayMode === "panel" ? (
<span className="shrink-0 text-[10px] font-normal text-muted-foreground/70">
{effectiveEnvMode === "worktree" && !activeWorktreePath ? "Create" : workspaceKind}
</span>
) : null}
</TooltipTrigger>
{workspacePath ? <TooltipPopup side="left">{workspacePath}</TooltipPopup> : null}
</Tooltip>
<SelectPopup>
<SelectGroup>
<SelectGroupLabel>Workspace</SelectGroupLabel>
@@ -3,6 +3,12 @@ import { CloudIcon, MonitorIcon } from "lucide-react";
import { memo, useMemo } from "react";
import type { EnvironmentOption } from "./BranchToolbar.logic";
import { cn } from "../lib/utils";
import {
THREAD_DETAILS_PANEL_ICON_CLASS,
THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
THREAD_DETAILS_PANEL_ROW_CLASS,
} from "./chat/threadDetailsPanelStyles";
import {
Select,
SelectGroup,
@@ -17,9 +23,8 @@ interface BranchToolbarEnvironmentSelectorProps {
envLocked: boolean;
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[];
// Absent when there is only one environment to show: the indicator still
// renders (as a static label) so remote projects are always identifiable.
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
onEnvironmentChange: (environmentId: EnvironmentId) => void;
displayMode?: "toolbar" | "panel";
}
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
@@ -27,6 +32,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
environmentId,
availableEnvironments,
onEnvironmentChange,
displayMode = "toolbar",
}: BranchToolbarEnvironmentSelectorProps) {
const activeEnvironment = useMemo(() => {
return availableEnvironments.find((env) => env.environmentId === environmentId) ?? null;
@@ -48,25 +54,30 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
// only thing in the strip.
if (envLocked || onEnvironmentChange === undefined) {
return (
<<<<<<< HEAD
<span className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
=======
<span
className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"
data-composer-context-control
className={cn(
"inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs",
displayMode === "panel" && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
)}
>
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
{activeEnvironment?.isPrimary ? (
<MonitorIcon className="size-3 shrink-0" />
<MonitorIcon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
) : (
<CloudIcon className="size-3 shrink-0" />
<CloudIcon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
>
<span
data-composer-label-motion
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
>
{activeEnvironment?.label ?? "Run on"}
</span>
{activeEnvironment?.label ?? "Run on"}
</span>
</span>
);
@@ -81,26 +92,24 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
>
<SelectTrigger
variant="ghost"
size="xs"
className="min-w-0 max-w-full font-medium"
size={displayMode === "panel" ? "default" : "xs"}
className={cn("font-medium", displayMode === "panel" && THREAD_DETAILS_PANEL_ROW_CLASS)}
aria-label="Run on"
data-composer-context-control
>
{activeEnvironment?.isPrimary ? (
<MonitorIcon className="size-3 shrink-0" />
<MonitorIcon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
) : (
<CloudIcon className="size-3 shrink-0" />
<CloudIcon
className={displayMode === "panel" ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3"}
/>
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
>
<span
data-composer-label-motion
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
>
<SelectValue />
</span>
<SelectValue />
</span>
</SelectTrigger>
<SelectPopup>
+6 -37
View File
@@ -17,6 +17,7 @@ import { type ComposerImageAttachment, type DraftThreadState } from "../composer
import * as Schema from "effect/Schema";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentThreadDetails } from "../state/threads";
import { waitForAtomValue } from "../state/waitForAtomValue";
import {
filterTerminalContextsWithText,
stripInlineTerminalContextPlaceholders,
@@ -467,43 +468,11 @@ export async function waitForStartedServerThread(
timeoutMs = 1_000,
): Promise<boolean> {
const threadAtom = environmentThreadDetails.detailAtom(threadRef);
const getThread = () => appAtomRegistry.get(threadAtom);
const thread = getThread();
if (threadHasStarted(thread)) {
return true;
}
return await new Promise<boolean>((resolve) => {
let settled = false;
let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
const finish = (result: boolean) => {
if (settled) {
return;
}
settled = true;
if (timeoutId !== null) {
globalThis.clearTimeout(timeoutId);
}
unsubscribe();
resolve(result);
};
const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
if (!threadHasStarted(thread)) {
return;
}
finish(true);
});
if (threadHasStarted(getThread())) {
finish(true);
return;
}
timeoutId = globalThis.setTimeout(() => {
finish(false);
}, timeoutMs);
return waitForAtomValue({
registry: appAtomRegistry,
atom: threadAtom,
predicate: threadHasStarted,
timeoutMs,
});
}
+206 -93
View File
@@ -22,15 +22,7 @@ import {
TerminalOpenInput,
} from "@t3tools/contracts";
import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell";
import {
connectionStatusTitle,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import {
effectiveSettled,
effectiveSnoozed,
threadWokeAt,
} from "@t3tools/client-runtime/state/thread-settled";
import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import {
parseScopedThreadKey,
scopedThreadKey,
@@ -123,10 +115,16 @@ import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
import { useElementWidth } from "../hooks/useElementWidth";
import { usePreviewPanelInlineSize } from "../hooks/usePreviewPanelInlineSize";
import {
RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY,
resolveThreadPanelPresentation,
} from "../rightPanelLayout";
import {
selectActiveRightPanel,
selectActiveRightPanelSurface,
selectThreadPanelOpen,
selectThreadRightPanelState,
type RightPanelSurface,
updatePullRequestTabStatus,
@@ -157,16 +155,9 @@ import {
foldSubagentActivities,
} from "@t3tools/client-runtime/state/subagentRuntime";
import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import {
AlarmClockIcon,
CheckCircle2Icon,
ChevronDownIcon,
GitBranchIcon,
WifiOffIcon,
} from "lucide-react";
import { ChevronDownIcon } from "lucide-react";
import { cn, randomHex } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import { stackedThreadToast, toastManager } from "./ui/toast";
@@ -245,6 +236,7 @@ import {
useThreadProposedPlans,
useThreadRefs,
useThreadVisibleTurnItems,
waitForThreadShell,
} from "../state/entities";
import { environmentShell } from "../state/shell";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
@@ -254,8 +246,13 @@ import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
import { MessagesTimeline } from "./chat/MessagesTimeline";
import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic";
import { ChatHeader } from "./chat/ChatHeader";
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
import {
PanelLayoutControls,
type PanelLayoutControlsProps,
RightPanelMaximizeControl,
} from "./chat/PanelLayoutControls";
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { ThreadDetailsPanel, type ThreadDetailsPanelProps } from "./chat/ThreadDetailsPanel";
import { NoActiveThreadState } from "./NoActiveThreadState";
import {
resolveEffectiveEnvMode,
@@ -319,7 +316,6 @@ import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { RightPanelSheet } from "./RightPanelSheet";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { Button } from "./ui/button";
import {
AlertDialog,
AlertDialogClose,
@@ -1342,7 +1338,15 @@ function ChatViewContent(props: ChatViewProps) {
>({});
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const shouldUseRightPanelSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
const [workspaceLayoutRef, workspaceLayoutWidth] = useElementWidth<HTMLDivElement>();
const previewPanelInlineSize = usePreviewPanelInlineSize();
const threadPanelPopoverAnchorRef = useRef<HTMLElement | null>(null);
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
// When set, the thread-change reset effect will open the sidebar instead of closing it.
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
const planSidebarOpenOnNextThreadRef = useRef(false);
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
@@ -1639,7 +1643,19 @@ function ChatViewContent(props: ChatViewProps) {
const canMaximizeRightPanel = rightPanelOpen && !shouldUseRightPanelSheet;
const rightPanelMaximized =
canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey;
const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUseRightPanelSheet;
const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet;
const threadPanelPresentation = resolveThreadPanelPresentation(
workspaceLayoutWidth,
inlineRightPanelOwnsTitleBar ? previewPanelInlineSize.width : 0,
rightPanelMaximized,
);
const threadPanelOpen = useRightPanelStore((state) =>
selectThreadPanelOpen(
state.threadPanelVisibilityByThreadKey,
activeThreadRef,
threadPanelPresentation,
),
);
useEffect(() => {
if (!activeThreadRef) return;
@@ -1872,16 +1888,6 @@ function ChatViewContent(props: ChatViewProps) {
});
return envs;
}, [activeProject, allProjects, projectGroupingSettings, primaryEnvironmentId, environmentById]);
const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;
const activeEnvironmentOption =
logicalProjectEnvironments.find(
(environment) => environment.environmentId === activeThread?.environmentId,
) ?? null;
const showComposerEnvironmentIndicator = shouldShowEnvironmentIndicator({
activeEnvironment: activeEnvironmentOption,
canPickEnvironment: hasMultipleEnvironments,
});
const openPullRequestDialog = useCallback(
(reference?: string) => {
if (!canCheckoutPullRequestIntoThread) {
@@ -2188,6 +2194,18 @@ function ChatViewContent(props: ChatViewProps) {
versionMismatchSelfUpdate,
versionMismatchServerLabel,
]);
const reconnectActiveEnvironment = useCallback(() => {
if (!activeEnvironmentUnavailableState) return;
void handleReconnectActiveEnvironment(activeEnvironmentUnavailableState.environmentId);
}, [activeEnvironmentUnavailableState, handleReconnectActiveEnvironment]);
const openConnectionSettings = useCallback(() => {
void navigate({ to: "/settings/connections" });
}, [navigate]);
const handleDismissVersionMismatch = useCallback(() => {
if (!versionMismatchDismissKey) return;
dismissVersionMismatch(versionMismatchDismissKey);
setDismissedVersionMismatchKey(versionMismatchDismissKey);
}, [setDismissedVersionMismatchKey, versionMismatchDismissKey]);
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
const unlockedSelectedProvider = resolveSelectableProvider(
providerStatuses,
@@ -3288,6 +3306,9 @@ function ChatViewContent(props: ChatViewProps) {
useRightPanelStore.getState().open(activeThreadRef, "diff");
onDiffPanelOpen?.();
}, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]);
const openChangesFromThreadPanel = useCallback(() => {
addDiffSurface();
}, [addDiffSurface]);
const addFilesSurface = useCallback(() => {
if (!activeThreadRef || !activeProject) return;
useRightPanelStore.getState().open(activeThreadRef, "files");
@@ -3464,7 +3485,15 @@ function ChatViewContent(props: ChatViewProps) {
return;
}
useRightPanelStore.getState().toggleVisibility(activeThreadRef);
}, [activeThreadRef, closePreviewPanel, rightPanelOpen]);
}, [activeThreadRef, closePlanSidebar, closePreviewPanel, planSidebarOpen, rightPanelOpen]);
const toggleThreadPanel = useCallback(() => {
if (!activeThreadRef) return;
useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation);
}, [activeThreadRef, threadPanelPresentation]);
const closeThreadPanelPopover = useCallback(() => {
if (!activeThreadRef) return;
useRightPanelStore.getState().setThreadPanelOpen(activeThreadRef, "popover", false);
}, [activeThreadRef]);
const toggleRightPanelMaximized = useCallback(() => {
if (!canMaximizeRightPanel) return;
setMaximizedRightPanelThreadKey((threadKey) =>
@@ -4752,6 +4781,13 @@ function ChatViewContent(props: ChatViewProps) {
return;
}
if (command === "threadPanel.toggle") {
event.preventDefault();
event.stopPropagation();
toggleThreadPanel();
return;
}
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
@@ -4847,6 +4883,7 @@ function ChatViewContent(props: ChatViewProps) {
keybindings,
onToggleDiff,
toggleRightPanel,
toggleThreadPanel,
toggleTerminalVisibility,
composerRef,
]);
@@ -4981,6 +5018,7 @@ function ChatViewContent(props: ChatViewProps) {
async (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId }) => {
if (!activeThread || activeEnvironmentUnavailable) return;
const targetThreadId = newThreadId();
const targetThreadRef = scopeThreadRef(environmentId, targetThreadId);
const result = await forkThreadFromRun({
environmentId,
input: {
@@ -5000,9 +5038,17 @@ function ChatViewContent(props: ChatViewProps) {
}
return;
}
const targetThreadReady = await waitForThreadShell(targetThreadRef);
if (!targetThreadReady) {
setThreadError(
activeThread.id,
"The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.",
);
return;
}
await navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(scopeThreadRef(environmentId, targetThreadId)),
params: buildThreadRouteParams(targetThreadRef),
});
},
[
@@ -5826,6 +5872,8 @@ function ChatViewContent(props: ChatViewProps) {
setComposerDraftInteractionMode,
setThreadError,
startThreadTurn,
activeThreadRef,
autoOpenPlanSidebar,
environmentId,
composerRef,
],
@@ -6159,41 +6207,6 @@ function ChatViewContent(props: ChatViewProps) {
return <NoActiveThreadState />;
}
const panelToggleControls = (
<PanelLayoutControls
terminalAvailable={activeProject !== null}
terminalOpen={terminalUiState.terminalOpen}
terminalShortcutLabel={shortcutLabelForCommand(keybindings, "terminal.toggle")}
rightPanelAvailable={activeProject !== null}
rightPanelOpen={rightPanelOpen}
rightPanelShortcutLabel={shortcutLabelForCommand(keybindings, "rightPanel.toggle")}
// Suppressed while the Agents surface is visible: the roster itself is
// on screen, so the toggle badge would be pointing at nothing.
liveAgentCount={
rightPanelOpen && activeRightPanelSurface?.kind === "agents" ? 0 : agentPanelModel.liveCount
}
onToggleTerminal={toggleTerminalVisibility}
onToggleRightPanel={toggleRightPanel}
/>
);
const panelLayoutControls = (
<div
className={cn(
// One inset in both states: the controls move between containers when
// the right panel opens, and a different right offset made them jump
// sideways on every toggle.
"workspace-titlebar-controls z-50 mr-px gap-1 [-webkit-app-region:no-drag]",
)}
>
{rightPanelOpen && !shouldUseRightPanelSheet ? (
<RightPanelMaximizeControl
maximized={rightPanelMaximized}
onToggle={toggleRightPanelMaximized}
/>
) : null}
{panelToggleControls}
</div>
);
const rightPanelContent = activeThreadRef ? (
activeRightPanelSurface?.kind === "preview" ? (
<Suspense fallback={null}>
@@ -6306,10 +6319,117 @@ function ChatViewContent(props: ChatViewProps) {
</Suspense>
) : null
) : null;
const threadDetailsPanelProps: Omit<ThreadDetailsPanelProps, "mode"> = {
environmentId: activeThread.environmentId,
environmentConnection: activeEnvironment?.connection ?? null,
threadId: activeThread.id,
...(draftId ? { draftId } : {}),
activeProjectName: activeProject?.title,
activeProjectScripts: activeProject?.scripts,
preferredScriptId: activeProject
? (lastInvokedScriptByProjectId[activeProject.id] ?? null)
: null,
keybindings,
gitCwd,
isGitRepo,
envLocked,
availableEnvironments: logicalProjectEnvironments,
onEnvironmentChange,
onEnvModeChange,
...(canOverrideServerThreadEnvMode ? { effectiveEnvModeOverride: envMode } : {}),
...(canOverrideServerThreadEnvMode
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
}
: {}),
startFromOrigin,
onStartFromOriginChange,
...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {}),
onComposerFocusRequest: scheduleComposerFocus,
...(isServerThread && isGitRepo ? { onOpenChanges: openChangesFromThreadPanel } : {}),
onReconnectEnvironment: reconnectActiveEnvironment,
onOpenConnectionSettings: openConnectionSettings,
versionMismatch:
showVersionMismatchBanner && versionMismatch
? {
clientVersion: versionMismatch.clientVersion,
serverVersion: versionMismatch.serverVersion,
serverLabel: versionMismatchServerLabel,
}
: null,
onDismissVersionMismatch: handleDismissVersionMismatch,
onRunProjectScript: runProjectScript,
onAddProjectScript: saveProjectScript,
onUpdateProjectScript: updateProjectScript,
onDeleteProjectScript: deleteProjectScript,
};
const panelToggleControlProps = {
terminalAvailable: activeProject !== null,
terminalOpen: terminalUiState.terminalOpen,
terminalShortcutLabel: shortcutLabelForCommand(keybindings, "terminal.toggle"),
threadPanelOpen,
threadPanelPresentation,
threadPanelPopoverAnchor: threadPanelPopoverAnchorRef,
...(threadPanelPresentation === "popover"
? {
threadPanelPopoverContent: (
<ThreadDetailsPanel
mode="popover"
onClose={closeThreadPanelPopover}
{...threadDetailsPanelProps}
/>
),
}
: {}),
threadPanelShortcutLabel: shortcutLabelForCommand(keybindings, "threadPanel.toggle"),
threadPanelHasAttention:
activeEnvironmentUnavailableState !== null || showVersionMismatchBanner,
rightPanelAvailable: activeProject !== null,
rightPanelOpen,
rightPanelShortcutLabel: shortcutLabelForCommand(keybindings, "rightPanel.toggle"),
onToggleTerminal: toggleTerminalVisibility,
onToggleThreadPanel: toggleThreadPanel,
onToggleRightPanel: toggleRightPanel,
} satisfies PanelLayoutControlsProps;
const panelToggleControls = (
<PanelLayoutControls
{...panelToggleControlProps}
showThreadPanelControl={!inlineRightPanelOwnsTitleBar}
/>
);
const threadPanelHeaderControl = (
<div className="workspace-titlebar-controls z-50 [-webkit-app-region:no-drag]">
<PanelLayoutControls
{...panelToggleControlProps}
showTerminalControl={false}
showRightPanelControl={false}
/>
</div>
);
const panelLayoutControls = (
<div className="workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]">
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
<RightPanelMaximizeControl
maximized={rightPanelMaximized}
onToggle={toggleRightPanelMaximized}
/>
) : null}
{panelToggleControls}
</div>
);
return (
<div className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background">
{rightPanelOpen && !shouldUseRightPanelSheet ? panelLayoutControls : null}
<div
ref={workspaceLayoutRef}
className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background"
>
{isElectron && activeThreadRef ? (
<PreviewAutomationOwner threadRef={activeThreadRef} visible={previewPanelOpen} />
) : null}
{rightPanelOpen && !shouldUsePlanSidebarSheet ? panelLayoutControls : null}
<div
className={cn(
"flex min-h-0 min-w-0 flex-col overflow-x-hidden",
@@ -6319,9 +6439,10 @@ function ChatViewContent(props: ChatViewProps) {
>
{/* Top bar */}
<header
ref={threadPanelPopoverAnchorRef}
data-chat-header
className={cn(
"bg-background transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none",
"relative border-b border-border transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none",
isElectron
? cn(
"workspace-topbar drag-region relative px-3 sm:px-5",
@@ -6333,14 +6454,16 @@ function ChatViewContent(props: ChatViewProps) {
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
{!rightPanelOpen ? panelLayoutControls : null}
{inlineRightPanelOwnsTitleBar
? threadPanelHeaderControl
: !rightPanelOpen
? panelLayoutControls
: null}
<ChatHeader
{...(!supportsPullRequests || threadRepository === null
? {}
: { onOpenPullRequest: openThreadPullRequest })}
activeThreadEnvironmentId={activeThread.environmentId}
activeThreadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
activeThreadTitle={activeThread.title}
isServerThread={isServerThread}
changeRequestState={activeThreadPr?.state ?? null}
@@ -6348,19 +6471,9 @@ function ChatViewContent(props: ChatViewProps) {
activeProjectCwd={activeProject?.workspaceRoot ?? null}
activeProjectFaviconPath={activeProject?.faviconPath ?? null}
openInCwd={gitCwd}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
keybindings={keybindings}
availableEditors={availableEditors}
rightPanelOpen={rightPanelOpen}
gitCwd={gitCwd}
onNewThreadInProject={handleNewThreadInActiveProject}
onRunProjectScript={runProjectScript}
onAddProjectScript={saveProjectScript}
onUpdateProjectScript={updateProjectScript}
onDeleteProjectScript={deleteProjectScript}
rightPanelOpen={inlineRightPanelOwnsTitleBar}
/>
</header>
@@ -6470,7 +6583,6 @@ function ChatViewContent(props: ChatViewProps) {
threadId={activeThread.id}
/>
) : null}
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
<div className="relative z-10">
<ChatComposer
composerRef={composerRef}
@@ -6548,6 +6660,7 @@ function ChatViewContent(props: ChatViewProps) {
</div>
</div>
</div>
<div className="chat-composer-horizontal-inset chat-composer-lower-chrome relative z-10 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]" />
</div>
{activeThreadRef && activePreviewMiniPlayer ? (
@@ -6607,6 +6720,9 @@ function ChatViewContent(props: ChatViewProps) {
) : null}
</div>
{/* end chat column */}
{threadPanelOpen && threadPanelPresentation === "inline" ? (
<ThreadDetailsPanel mode="inline" {...threadDetailsPanelProps} />
) : null}
</div>
{/* end horizontal flex container */}
@@ -6634,6 +6750,7 @@ function ChatViewContent(props: ChatViewProps) {
<RightPanelTabs
mode="inline"
maximized={rightPanelMaximized}
inlineSize={previewPanelInlineSize}
surfaces={rightPanelState.surfaces}
activeSurfaceId={activeRightPanelSurface?.id ?? null}
pendingSurfaceIds={pendingFileSurfaceIds}
@@ -6667,11 +6784,8 @@ function ChatViewContent(props: ChatViewProps) {
<RightPanelSheet open onClose={closePreviewPanel}>
<RightPanelTabs
mode="sheet"
// Same effective inset as the closed-state titlebar controls
// (pr-3 in the tab bar plus this pixel equals the absolute
// right inset plus mr-px), so the cluster does not creep when
// the sheet opens.
layoutControls={<div className="mr-px flex items-center">{panelToggleControls}</div>}
inlineSize={previewPanelInlineSize}
layoutControls={panelToggleControls}
surfaces={rightPanelState.surfaces}
activeSurfaceId={activeRightPanelSurface?.id ?? null}
pendingSurfaceIds={pendingFileSurfaceIds}
@@ -6702,7 +6816,6 @@ function ChatViewContent(props: ChatViewProps) {
</RightPanelTabs>
</RightPanelSheet>
) : null}
{expandedImage && (
<ExpandedImageDialog
key={`${expandedImage.images[expandedImage.index]?.src ?? "image"}:${expandedImage.index}`}
+89 -10
View File
@@ -25,6 +25,7 @@ import {
CloudDownloadIcon,
CloudUploadIcon,
ExternalLinkIcon,
FileDiffIcon,
GitBranchPlusIcon,
GitCommitIcon,
InfoIcon,
@@ -89,6 +90,14 @@ import { randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { readLocalApi } from "~/localApi";
import {
THREAD_DETAILS_PANEL_ICON_CLASS,
THREAD_DETAILS_PANEL_ROW_CLASS,
THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS,
THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS,
THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
} from "./chat/threadDetailsPanelStyles";
import { getSourceControlPresentation } from "~/sourceControlPresentation";
import { openPullRequestLink } from "~/lib/openPullRequestLink";
@@ -96,11 +105,16 @@ interface GitActionsControlProps {
gitCwd: string | null;
activeThreadRef: ScopedThreadRef | null;
draftId?: DraftId;
<<<<<<< HEAD
/**
* Opens the thread's own change request beside it. Absent when the thread has no project to
* place it against, in which case it still opens in the browser.
*/
onOpenPullRequest?: ((number: number) => void) | undefined;
=======
displayMode?: "toolbar" | "panel";
onOpenChanges?: () => void;
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
}
interface PendingDefaultBranchAction {
@@ -351,11 +365,13 @@ function GitActionItemIcon({
function GitQuickActionIcon({
quickAction,
SourceControlIcon,
className = "size-3.5",
}: {
quickAction: GitQuickAction;
SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
className?: string;
}) {
const iconClassName = "size-3.5";
const iconClassName = className;
if (quickAction.kind === "open_pr") return <SourceControlIcon className={iconClassName} />;
if (quickAction.kind === "open_publish") return <CloudUploadIcon className={iconClassName} />;
if (quickAction.kind === "run_pull") return <CloudDownloadIcon className={iconClassName} />;
@@ -978,8 +994,15 @@ export default function GitActionsControl({
gitCwd,
activeThreadRef,
draftId,
<<<<<<< HEAD
onOpenPullRequest,
=======
displayMode = "toolbar",
onOpenChanges,
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
}: GitActionsControlProps) {
const isPanel = displayMode === "panel";
const ActionGroup = isPanel ? "div" : Group;
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread branch metadata update",
@@ -1675,6 +1698,7 @@ export default function GitActionsControl({
<Button
variant="outline"
size="xs"
className={isPanel ? THREAD_DETAILS_PANEL_ROW_CLASS : undefined}
disabled={initAction.isPending}
onClick={() => {
void (async () => {
@@ -1700,7 +1724,11 @@ export default function GitActionsControl({
</span>
</Button>
) : (
<Group aria-label="Git actions" className="shrink-0">
<ActionGroup
role="group"
aria-label="Git actions"
className={cn("shrink-0", isPanel && THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS)}
>
{quickActionDisabledReason ? (
<Popover>
<PopoverTrigger
@@ -1708,7 +1736,10 @@ export default function GitActionsControl({
render={
<Button
aria-disabled="true"
className="cursor-not-allowed rounded-e-none border-e-0 ps-[8.5px] opacity-64 before:rounded-e-none"
className={cn(
"cursor-not-allowed rounded-e-none border-e-0 opacity-64 before:rounded-e-none",
isPanel && THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS,
)}
size="xs"
variant="outline"
/>
@@ -1717,8 +1748,14 @@ export default function GitActionsControl({
<GitQuickActionIcon
quickAction={quickAction}
SourceControlIcon={SourceControlIcon}
{...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
/>
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
<span
className={cn(
"sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
isPanel && "not-sr-only ml-0.5 truncate",
)}
>
{quickAction.label}
</span>
</PopoverTrigger>
@@ -1730,17 +1767,30 @@ export default function GitActionsControl({
<Button
variant="outline"
size="xs"
className="ps-[8.5px]"
className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS : undefined}
disabled={isGitActionRunning || quickAction.disabled}
onClick={runQuickAction}
>
<GitQuickActionIcon quickAction={quickAction} SourceControlIcon={SourceControlIcon} />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
<GitQuickActionIcon
quickAction={quickAction}
SourceControlIcon={SourceControlIcon}
{...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
/>
<span
className={cn(
"sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
isPanel && "not-sr-only ml-0.5 truncate",
)}
>
{quickAction.label}
</span>
</Button>
)}
<GroupSeparator className="hidden @3xl/header-actions:block" />
{isPanel ? (
<span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
) : (
<GroupSeparator className="hidden @3xl/header-actions:block" />
)}
<Menu
onOpenChange={(open) => {
if (open) {
@@ -1749,7 +1799,14 @@ export default function GitActionsControl({
}}
>
<MenuTrigger
render={<Button aria-label="Git action options" size="icon-xs" variant="outline" />}
render={
<Button
aria-label="Git action options"
size={isPanel ? "sm" : "icon-xs"}
variant="outline"
className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS : undefined}
/>
}
disabled={isGitActionRunning}
>
<ChevronDownIcon aria-hidden="true" className="size-4" />
@@ -1829,9 +1886,31 @@ export default function GitActionsControl({
)}
</MenuPopup>
</Menu>
</Group>
</ActionGroup>
)}
{isPanel && isRepo ? (
<Button
type="button"
variant="ghost"
size="sm"
className={THREAD_DETAILS_PANEL_ROW_CLASS}
disabled={!onOpenChanges}
onClick={onOpenChanges}
>
<FileDiffIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} aria-hidden />
<span className="flex-1 text-left">Changes</span>
<span className="flex items-center gap-1 font-mono text-[11px] tabular-nums">
<span className="text-success">
+{gitStatusForActions?.workingTree.insertions ?? 0}
</span>
<span className="text-destructive">
-{gitStatusForActions?.workingTree.deletions ?? 0}
</span>
</span>
</Button>
) : null}
<Dialog
open={isCommitDialogOpen}
onOpenChange={(open) => {
@@ -34,12 +34,22 @@ import {
MenuTrigger,
} from "./ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { cn } from "~/lib/utils";
import {
THREAD_DETAILS_PANEL_ICON_CLASS,
THREAD_DETAILS_PANEL_ROW_CLASS,
THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS,
THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS,
THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
} from "./chat/threadDetailsPanelStyles";
export type { NewProjectScriptInput, ProjectScriptActionResult };
const NO_FILE_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
interface ProjectScriptsControlProps {
displayMode?: "toolbar" | "panel";
scripts: ReadonlyArray<ProjectScript>;
/** Scripts declared in the project's checked-in t3.json, offered for import. */
fileScripts?: ReadonlyArray<T3ProjectFileScript>;
@@ -55,6 +65,7 @@ interface ProjectScriptsControlProps {
}
export default function ProjectScriptsControl({
displayMode = "toolbar",
scripts,
fileScripts = NO_FILE_SCRIPTS,
keybindings,
@@ -64,6 +75,13 @@ export default function ProjectScriptsControl({
onUpdateScript,
onDeleteScript,
}: ProjectScriptsControlProps) {
<<<<<<< HEAD
=======
const isPanel = displayMode === "panel";
const ActionGroup = isPanel ? "div" : Group;
const addScriptFormId = React.useId();
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
const [actionsMenuOpen, setActionsMenuOpen] = useState({
scripts: false,
imports: false,
@@ -155,14 +173,18 @@ export default function ProjectScriptsControl({
return (
<>
{primaryScript ? (
<Group aria-label="Project scripts">
<ActionGroup
role="group"
aria-label="Project scripts"
{...(isPanel ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS } : {})}
>
<Tooltip>
<TooltipTrigger
render={
<Button
size="xs"
variant="outline"
className="w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS : undefined}
aria-label={`Run ${primaryScript.name}`}
// The tooltip wrapper replaces data-slot="button", so themed
// toolbar styling needs its own hook.
@@ -171,21 +193,36 @@ export default function ProjectScriptsControl({
/>
}
>
<ScriptIcon icon={primaryScript.icon} />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
<ScriptIcon
icon={primaryScript.icon}
{...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
/>
<span
className={cn(
"sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
isPanel && "not-sr-only ml-0.5 truncate",
)}
>
{primaryScript.name}
</span>
</TooltipTrigger>
<TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
</Tooltip>
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu
highlightItemOnHover={false}
open={actionsMenuOpen.scripts}
onOpenChange={(open) => setActionsMenuOpen({ scripts: open, imports: false })}
>
{isPanel ? (
<span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
) : (
<GroupSeparator className="hidden @3xl/header-actions:block" />
)}
<Menu highlightItemOnHover={false}>
<MenuTrigger
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
render={
<Button
size={isPanel ? "sm" : "icon-xs"}
variant="outline"
className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS : undefined}
aria-label="Script actions"
/>
}
>
<ChevronDownIcon className="size-4" />
</MenuTrigger>
@@ -236,32 +273,11 @@ export default function ProjectScriptsControl({
{importMenuItems}
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
<PlusIcon className="size-4" />
Add action
{isPanel ? "Add project script" : "Add action"}
</MenuItem>
</MenuPopup>
</Menu>
</Group>
) : importableScripts.length > 0 ? (
<Menu
highlightItemOnHover={false}
open={actionsMenuOpen.imports}
onOpenChange={(open) => setActionsMenuOpen({ scripts: false, imports: open })}
>
<MenuTrigger render={<Button size="xs" variant="outline" aria-label="Project actions" />}>
<PlusIcon className="size-3.5" />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
Add action
</span>
<ChevronDownIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end">
{importMenuItems}
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
<PlusIcon className="size-4" />
Add action
</MenuItem>
</MenuPopup>
</Menu>
</ActionGroup>
) : (
<Tooltip>
<TooltipTrigger
@@ -269,8 +285,12 @@ export default function ProjectScriptsControl({
<Button
size="xs"
variant="outline"
className="w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
aria-label="Add action"
className={
isPanel
? THREAD_DETAILS_PANEL_ROW_CLASS
: "w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
}
aria-label={isPanel ? "Add project script" : "Add action"}
// The tooltip wrapper replaces data-slot="button", so themed
// toolbar styling needs its own hook.
data-toolbar-control=""
@@ -279,11 +299,16 @@ export default function ProjectScriptsControl({
}
>
<PlusIcon className="size-3.5" />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
Add action
<span
className={cn(
"sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
isPanel && "not-sr-only ml-0.5",
)}
>
{isPanel ? "Add project script" : "Add action"}
</span>
</TooltipTrigger>
<TooltipPopup side="top">Add action</TooltipPopup>
<TooltipPopup side="top">{isPanel ? "Add project script" : "Add action"}</TooltipPopup>
</Tooltip>
)}
+9 -1
View File
@@ -33,7 +33,7 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
import { faviconUrlForOrigin } from "~/lib/favicon";
import { useTheme } from "~/hooks/useTheme";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import type { PreviewPanelInlineSize } from "~/hooks/usePreviewPanelInlineSize";
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
import { FaviconImage } from "./preview/PreviewFaviconIcon";
@@ -42,10 +42,14 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon";
interface RightPanelTabsProps {
mode: PreviewPanelMode;
maximized?: boolean;
<<<<<<< HEAD
/** Forwarded to PreviewPanelShell so this surface persists its own width. */
widthStorageKey?: string;
/** Forwarded to PreviewPanelShell as the initial width before a user resize. */
defaultWidth?: number;
=======
inlineSize?: PreviewPanelInlineSize;
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
layoutControls?: ReactNode;
surfaces: readonly RightPanelSurface[];
activeSurfaceId: string | null;
@@ -599,8 +603,12 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<PreviewPanelShell
mode={props.mode}
{...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
<<<<<<< HEAD
{...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
{...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
=======
{...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
>
<div
className={cn(
+29 -53
View File
@@ -1,34 +1,11 @@
import {
type EnvironmentId,
type EditorId,
type ProjectScript,
type ResolvedKeybindingsConfig,
type ThreadId,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { ChangeRequestStateLike } from "@t3tools/client-runtime/state/thread-settled";
import { ChevronDownIcon } from "lucide-react";
import {
memo,
useCallback,
useMemo,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
} from "react";
import GitActionsControl from "../GitActionsControl";
import { type DraftId } from "~/composerDraftStore";
import { memo } from "react";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
import ProjectScriptsControl, {
type NewProjectScriptInput,
type ProjectScriptActionResult,
} from "../ProjectScriptsControl";
import { SidebarTrigger } from "../ui/sidebar";
import { OpenInPicker } from "./OpenInPicker";
import { useRemoteOpenState, type RemoteOpenMode } from "../../remoteOpen";
import { usePrimaryEnvironmentId } from "../../state/environments";
@@ -43,12 +20,9 @@ import {
WorkspaceBreadcrumbSeparator,
} from "../WorkspaceBreadcrumb";
import { cn } from "~/lib/utils";
import { ThreadRelationshipsControl } from "./ThreadRelationshipsControl";
interface ChatHeaderProps {
activeThreadEnvironmentId: EnvironmentId;
activeThreadId: ThreadId;
draftId?: DraftId;
activeThreadTitle: string;
/** Drafts have no server thread yet, so the title carries no action menu. */
isServerThread: boolean;
@@ -58,11 +32,10 @@ interface ChatHeaderProps {
activeProjectCwd: string | null;
activeProjectFaviconPath: string | null;
openInCwd: string | null;
activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
rightPanelOpen: boolean;
<<<<<<< HEAD
gitCwd: string | null;
readonly onOpenPullRequest?: ((number: number) => void) | undefined;
onNewThreadInProject: () => void;
@@ -73,6 +46,8 @@ interface ChatHeaderProps {
input: NewProjectScriptInput,
) => Promise<ProjectScriptActionResult>;
onDeleteProjectScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
=======
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
}
/**
@@ -110,8 +85,6 @@ export function shouldShowOpenInPicker(input: {
export const ChatHeader = memo(function ChatHeader({
activeThreadEnvironmentId,
activeThreadId,
draftId,
activeThreadTitle,
isServerThread,
changeRequestState,
@@ -119,11 +92,10 @@ export const ChatHeader = memo(function ChatHeader({
activeProjectCwd,
activeProjectFaviconPath,
openInCwd,
activeProjectScripts,
preferredScriptId,
keybindings,
availableEditors,
rightPanelOpen,
<<<<<<< HEAD
gitCwd,
onOpenPullRequest,
onNewThreadInProject,
@@ -131,6 +103,8 @@ export const ChatHeader = memo(function ChatHeader({
onAddProjectScript,
onUpdateProjectScript,
onDeleteProjectScript,
=======
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
}: ChatHeaderProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const fileScripts = useT3ProjectFileScripts(
@@ -230,6 +204,7 @@ export const ChatHeader = memo(function ChatHeader({
className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"
onContextMenu={handleHeaderContextMenu}
>
<<<<<<< HEAD
<WorkspaceBreadcrumb ariaLabel="Thread breadcrumb" className="flex-1">
{/* The project always leads the header: knowing which project a
thread lives in is priority zero, and the thread title alone
@@ -306,6 +281,22 @@ export const ChatHeader = memo(function ChatHeader({
{activeThreadTitle}
</h2>
}
=======
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
<Tooltip>
<TooltipTrigger
render={
<h2
aria-label={activeThreadTitle}
className="min-w-0 flex-1 truncate text-sm font-medium text-foreground"
>
{activeThreadTitle}
</h2>
<ChevronDownIcon
aria-hidden
className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/thread-title:opacity-100 group-focus-visible/thread-title:opacity-100"
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
/>
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
</Tooltip>
@@ -316,27 +307,9 @@ export const ChatHeader = memo(function ChatHeader({
data-chat-header-actions
className={cn(
"flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
rightPanelOpen ? "pr-0" : "pr-16",
rightPanelOpen ? "pr-10" : "pr-24",
)}
>
{activeProjectScripts && (
<ProjectScriptsControl
scripts={activeProjectScripts}
fileScripts={fileScripts}
keybindings={keybindings}
preferredScriptId={preferredScriptId}
onRunScript={onRunProjectScript}
onAddScript={onAddProjectScript}
onUpdateScript={onUpdateProjectScript}
onDeleteScript={onDeleteProjectScript}
/>
)}
{!draftId ? (
<ThreadRelationshipsControl
environmentId={activeThreadEnvironmentId}
threadId={activeThreadId}
/>
) : null}
{showOpenInPicker && (
<OpenInPicker
environmentId={activeThreadEnvironmentId}
@@ -345,6 +318,7 @@ export const ChatHeader = memo(function ChatHeader({
openInCwd={openInCwd}
/>
)}
<<<<<<< HEAD
{activeProjectName && (
<GitActionsControl
gitCwd={gitCwd}
@@ -353,6 +327,8 @@ export const ChatHeader = memo(function ChatHeader({
{...(draftId ? { draftId } : {})}
/>
)}
=======
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
</div>
</div>
);
@@ -1,40 +1,134 @@
import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon } from "lucide-react";
import { memo } from "react";
import {
ListFilterIcon,
Maximize2Icon,
Minimize2Icon,
PanelBottomIcon,
PanelRightIcon,
} from "lucide-react";
import { memo, type ReactElement, type ReactNode, type RefObject } from "react";
import type { ThreadPanelPresentation } from "../../rightPanelLayout";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { Toggle } from "../ui/toggle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
<<<<<<< HEAD
interface PanelLayoutControlsProps {
showTerminalControl?: boolean;
=======
export interface PanelLayoutControlsProps {
showThreadPanelControl?: boolean;
showTerminalControl?: boolean;
showRightPanelControl?: boolean;
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
terminalAvailable: boolean;
terminalOpen: boolean;
terminalShortcutLabel: string | null;
threadPanelOpen: boolean;
threadPanelPresentation: ThreadPanelPresentation;
threadPanelPopoverAnchor?: RefObject<Element | null>;
threadPanelPopoverContent?: ReactNode;
threadPanelShortcutLabel: string | null;
threadPanelHasAttention: boolean;
rightPanelAvailable: boolean;
rightPanelOpen: boolean;
rightPanelShortcutLabel: string | null;
/** Running + waiting subagents in this thread; badges the right panel toggle. */
liveAgentCount: number;
onToggleTerminal: () => void;
onToggleThreadPanel: () => void;
onToggleRightPanel: () => void;
}
export const PanelLayoutControls = memo(function PanelLayoutControls({
<<<<<<< HEAD
showTerminalControl = true,
=======
showThreadPanelControl = true,
showTerminalControl = true,
showRightPanelControl = true,
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
terminalAvailable,
terminalOpen,
terminalShortcutLabel,
threadPanelOpen,
threadPanelPresentation,
threadPanelPopoverAnchor,
threadPanelPopoverContent,
threadPanelShortcutLabel,
threadPanelHasAttention,
rightPanelAvailable,
rightPanelOpen,
rightPanelShortcutLabel,
liveAgentCount,
onToggleTerminal,
onToggleThreadPanel,
onToggleRightPanel,
}: PanelLayoutControlsProps) {
const threadPanelToggle = (
<Toggle
className="relative shrink-0 [-webkit-app-region:no-drag]"
pressed={threadPanelOpen}
aria-label="Toggle thread details panel"
variant="ghost"
size="sm"
>
<ListFilterIcon className="size-3.5" />
{threadPanelHasAttention ? (
<span
className="absolute right-1 top-1 size-1.5 rounded-full bg-warning ring-2 ring-background"
aria-hidden="true"
/>
) : null}
</Toggle>
);
const threadPanelTooltip = (trigger: ReactElement) => (
<Tooltip>
<TooltipTrigger
render={trigger}
{...(threadPanelPresentation === "popover" ? {} : { onClick: onToggleThreadPanel })}
/>
<TooltipPopup side="bottom">
Toggle thread details
{threadPanelShortcutLabel ? ` (${threadPanelShortcutLabel})` : ""}
</TooltipPopup>
</Tooltip>
);
return (
<div
className="flex h-full shrink-0 items-center gap-1 [-webkit-app-region:no-drag]"
data-panel-layout-controls
>
<<<<<<< HEAD
=======
{showThreadPanelControl ? (
threadPanelPresentation === "popover" ? (
<Popover
open={threadPanelOpen}
onOpenChange={(open) => {
if (open !== threadPanelOpen) onToggleThreadPanel();
}}
>
{threadPanelTooltip(<PopoverTrigger render={threadPanelToggle} />)}
<PopoverPopup
anchor={threadPanelPopoverAnchor}
align="end"
alignOffset={8}
side="bottom"
sideOffset={8}
positionerClassName="w-[min(20rem,calc(var(--anchor-width)-1rem))]"
className="w-full border-0 bg-transparent shadow-none before:hidden [--viewport-inline-padding:0]"
viewportClassName="p-0"
>
{threadPanelPopoverContent}
</PopoverPopup>
</Popover>
) : (
threadPanelTooltip(threadPanelToggle)
)
) : null}
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
{showTerminalControl ? (
<Tooltip>
<TooltipTrigger
@@ -59,6 +153,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
</TooltipPopup>
</Tooltip>
) : null}
<<<<<<< HEAD
<Tooltip>
<TooltipTrigger
render={
@@ -97,6 +192,32 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
: "Right panel is unavailable"}
</TooltipPopup>
</Tooltip>
=======
{showRightPanelControl ? (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
pressed={rightPanelOpen}
onPressedChange={onToggleRightPanel}
aria-label="Toggle right panel"
variant="ghost"
size="sm"
disabled={!rightPanelAvailable}
>
<PanelRightIcon className="size-3.5" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{rightPanelAvailable
? `Toggle right panel${rightPanelShortcutLabel ? ` (${rightPanelShortcutLabel})` : ""}`
: "Right panel is unavailable"}
</TooltipPopup>
</Tooltip>
) : null}
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
</div>
);
});
@@ -0,0 +1,294 @@
import type {
EnvironmentId,
ProjectScript,
ResolvedKeybindingsConfig,
ThreadId,
} from "@t3tools/contracts";
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import { AlertTriangleIcon, XIcon } from "lucide-react";
import type { DraftId } from "../../composerDraftStore";
import type { EnvMode, EnvironmentOption } from "../BranchToolbar.logic";
import { BranchToolbar } from "../BranchToolbar";
import { BranchToolbarEnvironmentSelector } from "../BranchToolbarEnvironmentSelector";
import GitActionsControl from "../GitActionsControl";
import ProjectScriptsControl, {
type NewProjectScriptInput,
type ProjectScriptActionResult,
} from "../ProjectScriptsControl";
import { Button } from "../ui/button";
import { cn } from "../../lib/utils";
import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
interface VersionMismatchIssue {
readonly clientVersion: string;
readonly serverVersion: string;
readonly serverLabel: string;
}
export interface ThreadDetailsPanelProps {
mode: "inline" | "popover";
onClose?: () => void;
environmentId: EnvironmentId;
environmentConnection: EnvironmentConnectionPresentation | null;
threadId: ThreadId;
draftId?: DraftId;
activeProjectName: string | undefined;
activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
gitCwd: string | null;
isGitRepo: boolean;
envLocked: boolean;
availableEnvironments: readonly EnvironmentOption[];
onEnvironmentChange: (environmentId: EnvironmentId) => void;
onEnvModeChange: (mode: EnvMode) => void;
effectiveEnvModeOverride?: EnvMode;
activeThreadBranchOverride?: string | null;
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
startFromOrigin: boolean;
onStartFromOriginChange: (startFromOrigin: boolean) => void;
onCheckoutPullRequestRequest?: (reference: string) => void;
onComposerFocusRequest: () => void;
onOpenChanges?: () => void;
onReconnectEnvironment: () => void;
onOpenConnectionSettings: () => void;
versionMismatch: VersionMismatchIssue | null;
onDismissVersionMismatch: () => void;
onRunProjectScript: (script: ProjectScript) => void;
onAddProjectScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
onUpdateProjectScript: (
scriptId: string,
input: NewProjectScriptInput,
) => Promise<ProjectScriptActionResult>;
onDeleteProjectScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
}
function shortConnectionStatus(connection: EnvironmentConnectionPresentation | null): string {
switch (connection?.phase) {
case "connected":
return "Connected";
case "connecting":
return "Connecting";
case "reconnecting":
return "Reconnecting";
case "offline":
return "Offline";
case "error":
return "Connection issue";
case "available":
case undefined:
return "Available";
}
}
function connectionDotClass(connection: EnvironmentConnectionPresentation | null): string {
switch (connection?.phase) {
case "connected":
return "bg-success";
case "connecting":
case "reconnecting":
return "bg-warning animate-pulse";
case "error":
case "offline":
return "bg-destructive";
case "available":
case undefined:
return "bg-muted-foreground/50";
}
}
export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {
const connectionIssue =
props.environmentConnection !== null &&
props.environmentConnection.phase !== "connected" &&
props.environmentConnection.phase !== "available";
const isReconnecting =
props.environmentConnection?.phase === "connecting" ||
props.environmentConnection?.phase === "reconnecting";
const branchToolbarProps = {
environmentId: props.environmentId,
threadId: props.threadId,
...(props.draftId ? { draftId: props.draftId } : {}),
onEnvModeChange: props.onEnvModeChange,
startFromOrigin: props.startFromOrigin,
onStartFromOriginChange: props.onStartFromOriginChange,
...(props.effectiveEnvModeOverride
? { effectiveEnvModeOverride: props.effectiveEnvModeOverride }
: {}),
...(props.activeThreadBranchOverride !== undefined
? { activeThreadBranchOverride: props.activeThreadBranchOverride }
: {}),
...(props.onActiveThreadBranchOverrideChange
? { onActiveThreadBranchOverrideChange: props.onActiveThreadBranchOverrideChange }
: {}),
envLocked: props.envLocked,
onComposerFocusRequest: props.onComposerFocusRequest,
...(props.onCheckoutPullRequestRequest
? { onCheckoutPullRequestRequest: props.onCheckoutPullRequestRequest }
: {}),
};
const card = (
<div
className="overflow-hidden rounded-[18px] border border-border/75 bg-card/95 shadow-[0_8px_28px_rgba(0,0,0,0.045)] dark:shadow-[0_12px_30px_rgba(0,0,0,0.18)]"
data-thread-details-card
>
<section aria-labelledby="thread-details-project-heading">
<div className="flex min-h-10 items-center justify-between gap-3 px-3.5 pb-1 pt-3">
<h3
id="thread-details-project-heading"
className="text-[11px] font-medium text-muted-foreground"
>
Project / environment
</h3>
<div className="flex shrink-0 items-center gap-1">
<span className="inline-flex items-center gap-1.5 text-[11px] text-muted-foreground">
<span
className={cn(
"size-1.5 rounded-full",
connectionDotClass(props.environmentConnection),
)}
aria-hidden="true"
/>
{shortConnectionStatus(props.environmentConnection)}
</span>
{props.mode === "popover" && props.onClose ? (
<Button
size="icon-xs"
variant="ghost"
aria-label="Close thread details"
onClick={props.onClose}
>
<XIcon className="size-3.5" />
</Button>
) : null}
</div>
</div>
{connectionIssue ? (
<div className="mx-3 mb-2 rounded-xl border border-warning/30 bg-warning/6 p-3">
<div className="flex gap-2">
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
<div className="min-w-0 flex-1">
<p className="text-xs font-medium">Environment unavailable</p>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
{props.environmentConnection?.error ??
"Reconnect this environment before sending messages or running actions."}
</p>
<div className="mt-2 flex items-center gap-1.5">
<Button
size="xs"
disabled={isReconnecting}
onClick={props.onReconnectEnvironment}
>
{isReconnecting ? "Reconnecting..." : "Reconnect"}
</Button>
<Button size="xs" variant="ghost" onClick={props.onOpenConnectionSettings}>
Connections
</Button>
</div>
</div>
</div>
</div>
) : null}
{props.versionMismatch ? (
<div className="mx-3 mb-2 flex gap-2 rounded-xl border border-warning/30 bg-warning/6 p-3">
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
<div className="min-w-0 flex-1">
<p className="text-xs font-medium">Client and server versions differ</p>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
Client {props.versionMismatch.clientVersion} · {props.versionMismatch.serverLabel}{" "}
{props.versionMismatch.serverVersion}
</p>
</div>
<Button
size="icon-xs"
variant="ghost"
aria-label="Dismiss version mismatch warning"
onClick={props.onDismissVersionMismatch}
>
<XIcon className="size-3.5" />
</Button>
</div>
) : null}
<div className="flex flex-col px-2 pb-2.5">
{props.availableEnvironments.length > 1 ? (
<BranchToolbarEnvironmentSelector
displayMode="panel"
envLocked={props.envLocked}
environmentId={props.environmentId}
availableEnvironments={props.availableEnvironments}
onEnvironmentChange={props.onEnvironmentChange}
/>
) : null}
<BranchToolbar layout="panel" panelSection="workspace" {...branchToolbarProps} />
{props.activeProjectScripts ? (
<ProjectScriptsControl
displayMode="panel"
scripts={props.activeProjectScripts}
keybindings={props.keybindings}
preferredScriptId={props.preferredScriptId}
onRunScript={props.onRunProjectScript}
onAddScript={props.onAddProjectScript}
onUpdateScript={props.onUpdateProjectScript}
onDeleteScript={props.onDeleteProjectScript}
/>
) : null}
</div>
</section>
{props.gitCwd ? (
<section
aria-labelledby="thread-details-version-control-heading"
className="border-t border-border/65"
>
<div className="px-3.5 pb-1 pt-3">
<h3
id="thread-details-version-control-heading"
className="text-[11px] font-medium text-muted-foreground"
>
Version control
</h3>
</div>
<div className="flex flex-col px-2 pb-2.5">
{props.isGitRepo ? (
<BranchToolbar layout="panel" panelSection="branch" {...branchToolbarProps} />
) : null}
{props.activeProjectName ? (
<GitActionsControl
displayMode="panel"
gitCwd={props.gitCwd}
activeThreadRef={{ environmentId: props.environmentId, threadId: props.threadId }}
{...(props.draftId ? { draftId: props.draftId } : {})}
{...(props.onOpenChanges ? { onOpenChanges: props.onOpenChanges } : {})}
/>
) : null}
</div>
</section>
) : null}
{!props.draftId ? (
<ThreadRelationshipsPanel environmentId={props.environmentId} threadId={props.threadId} />
) : null}
</div>
);
if (props.mode === "popover") {
return <div data-thread-details-panel="popover">{card}</div>;
}
return (
<aside
aria-label="Thread details"
className="w-[clamp(18rem,24vw,21rem)] shrink-0 overflow-y-auto bg-background p-3 pl-0"
data-thread-details-panel="inline"
>
{card}
</aside>
);
}
@@ -1,59 +1,71 @@
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import { ArrowRightIcon, GitBranchIcon, GitForkIcon, NetworkIcon, UnplugIcon } from "lucide-react";
import { useMemo, useState } from "react";
import {
ArrowRightIcon,
BotIcon,
GitBranchIcon,
GitForkIcon,
GitMergeIcon,
LoaderCircleIcon,
MoreHorizontalIcon,
UnplugIcon,
} from "lucide-react";
import { useState } from "react";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import {
deriveThreadRelationshipGraph,
walkThreadRelationships,
immediateThreadRelationships,
resolveMergeBackTargetThreadId,
type ThreadRelationshipEdge,
} from "../../lib/threadRelationships";
import { buildThreadRouteParams } from "../../threadRoutes";
import { newThreadId } from "../../lib/utils";
import { threadEnvironment } from "../../state/threads";
import { buildThreadRouteParams } from "../../threadRoutes";
import { useThreadProjection, useThreadShells } from "../../state/entities";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
function relationshipLabel(
edge: ReturnType<typeof walkThreadRelationships>[number]["edge"],
currentThreadId: ThreadId,
) {
if (edge.kind === "transfer") return "context transfer";
function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) {
if (edge.kind === "transfer") return "Context transfer";
if (edge.kind === "subagent") {
return edge.sourceThreadId === currentThreadId ? "subagent" : "parent agent";
return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
}
return edge.sourceThreadId === currentThreadId ? "fork" : "source";
return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread";
}
export function ThreadRelationshipsControl(props: {
function statusDotClass(status: string | null): string {
if (status === "running" || status === "in_progress") return "bg-info";
if (status === "failed" || status === "error") return "bg-destructive";
if (status === "completed") return "bg-success";
return "bg-muted-foreground/45";
}
const MAX_VISIBLE_RELATIONSHIPS = 5;
export function ThreadRelationshipsPanel(props: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
}) {
const ref = scopeThreadRef(props.environmentId, props.threadId);
const projection = useThreadProjection(ref)?.projection ?? null;
const activeShells = useThreadShells().filter(
const threadShells = useThreadShells();
const activeShells = threadShells.filter(
(thread) => thread.environmentId === props.environmentId,
);
const archived = useArchivedThreadSnapshots([props.environmentId]);
const archivedShells =
archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot
.threads ?? [];
const shells = useMemo<ReadonlyArray<OrchestrationV2ThreadShell>>(
() => [...activeShells.map((thread) => thread.source), ...archivedShells],
[activeShells, archivedShells],
);
const graph = useMemo(
() => deriveThreadRelationshipGraph({ threads: shells, projection }),
[projection, shells],
);
const relationshipRows = useMemo(
() => walkThreadRelationships(graph, props.threadId),
[graph, props.threadId],
);
const archivedShells = archived.snapshots.find(
(entry) => entry.environmentId === props.environmentId,
)?.snapshot.threads;
const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
...activeShells.map((thread) => thread.source),
...(archivedShells ?? []),
];
const graph = deriveThreadRelationshipGraph({ threads: shells, projection });
const navigate = useNavigate();
const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun);
const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
@@ -79,19 +91,22 @@ export function ThreadRelationshipsControl(props: {
const canFork =
latestCompletedRun !== null &&
(canForkNatively || capabilities?.context.supportsFullThreadHandoff === true);
const parentThreadId =
projection?.thread.forkedFrom?.type === "run"
? projection.thread.forkedFrom.threadId
: (projection?.thread.lineage.parentThreadId ?? null);
const canMerge =
parentThreadId !== null &&
projection?.thread.lineage.relationshipToParent === "fork" &&
latestCompletedRun !== null;
const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
const relationshipRows = immediateThreadRelationships(graph, props.threadId).toSorted(
(left, right) =>
Number(right.threadId === mergeTargetThreadId) -
Number(left.threadId === mergeTargetThreadId),
);
const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null;
const canDetach =
projection?.providerSessions.some(
(session) => session.status !== "stopped" && session.status !== "error",
) ?? false;
if (relationshipRows.length === 0 && !canFork && mergeTargetThreadId === null && !canDetach) {
return null;
}
const openThread = (threadId: ThreadId) => {
void navigate({
to: "/$environmentId/$threadId",
@@ -117,18 +132,18 @@ export function ThreadRelationshipsControl(props: {
};
const merge = async () => {
if (!latestCompletedRun || parentThreadId === null || busyAction !== null) return;
if (!latestCompletedRun || mergeTargetThreadId === null || busyAction !== null) return;
setBusyAction("merge");
const result = await mergeBack({
environmentId: props.environmentId,
input: {
sourceThreadId: props.threadId,
targetThreadId: parentThreadId,
targetThreadId: mergeTargetThreadId,
runId: latestCompletedRun.id,
},
});
setBusyAction(null);
if (result._tag === "Success") openThread(parentThreadId);
if (result._tag === "Success") openThread(mergeTargetThreadId);
};
const detach = async () => {
@@ -141,103 +156,165 @@ export function ThreadRelationshipsControl(props: {
setBusyAction(null);
};
const visibleRows = relationshipRows.slice(0, MAX_VISIBLE_RELATIONSHIPS);
const hiddenRelationshipCount = relationshipRows.length - visibleRows.length;
const parentTitle =
mergeTargetThreadId === null
? null
: (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
return (
<Popover>
<Tooltip>
<TooltipTrigger
render={
<PopoverTrigger
render={
<Button
size="xs"
variant="outline"
aria-label="Thread relationships and V2 actions"
/>
}
<section
aria-labelledby="thread-details-lineage-heading"
className="border-t border-border/65 px-2 pb-2.5 pt-2"
data-thread-relationships-panel
>
<div className="mb-1 flex min-h-8 items-center justify-between gap-2 px-2">
<h3
id="thread-details-lineage-heading"
className="text-[11px] font-medium text-muted-foreground"
>
Lineage
</h3>
<div className="flex shrink-0 items-center gap-1">
{canFork ? (
<Button
size="xs"
variant="ghost"
disabled={busyAction !== null}
onClick={() => void fork()}
>
<NetworkIcon className="size-3.5" />
{relationshipRows.length > 0 ? <span>{relationshipRows.length}</span> : null}
</PopoverTrigger>
}
/>
<TooltipPopup>Thread relationships</TooltipPopup>
</Tooltip>
<PopoverPopup align="end" className="w-80" viewportClassName="p-0">
<div className="border-b border-border px-3 py-2.5">
<p className="text-sm font-medium">Thread relationships</p>
<p className="text-xs text-muted-foreground">
Forks, subagents, and context transfers in this environment.
</p>
<GitForkIcon className="size-3" />
{busyAction === "fork" ? "Forking..." : "Fork"}
</Button>
) : null}
{canDetach ? (
<Menu>
<MenuTrigger
render={
<Button
size="icon-xs"
variant="ghost"
aria-label="More thread actions"
disabled={busyAction !== null}
/>
}
>
<MoreHorizontalIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end">
<MenuItem onClick={() => void detach()}>
<UnplugIcon className="size-3.5" />
Disconnect agent session
</MenuItem>
</MenuPopup>
</Menu>
) : null}
</div>
<div className="max-h-72 overflow-auto p-2">
{relationshipRows.length === 0 ? (
<p className="px-2 py-4 text-center text-xs text-muted-foreground">
This thread has no related threads yet.
</p>
) : (
<ul className="space-y-1">
{relationshipRows.map(({ threadId, fromThreadId, depth, edge }) => {
const node = graph.nodes.get(threadId);
return (
<li key={threadId}>
<button
type="button"
disabled={node?.missing === true}
onClick={() => openThread(threadId)}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left hover:bg-muted disabled:cursor-not-allowed disabled:opacity-60"
style={{ paddingInlineStart: `${Math.min(depth, 6) * 0.75 + 0.5}rem` }}
>
<GitBranchIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1">
<span className="block truncate text-xs font-medium">
{node?.thread?.title ?? threadId}
</div>
{visibleRows.length > 0 ? (
<ul>
{visibleRows.map(({ threadId, edge }) => {
const node = graph.nodes.get(threadId);
const isSubagent = edge.kind === "subagent";
const isMergeTarget = threadId === mergeTargetThreadId;
const RelationshipIcon = isSubagent ? BotIcon : GitBranchIcon;
const relationship = relationshipLabel(edge, props.threadId);
const threadTitle = node?.thread?.title ?? threadId;
return (
<li
key={threadId}
className="group flex min-h-11 items-center rounded-lg transition-colors hover:bg-muted/65"
>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
disabled={node?.missing === true}
onClick={() => openThread(threadId)}
className="flex min-h-11 min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left disabled:cursor-not-allowed disabled:opacity-55"
>
<span className="relative grid size-7 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground">
<RelationshipIcon className="size-3.5" />
<span
className={cn(
"absolute -bottom-0.5 -right-0.5 size-2 rounded-full border-2 border-card",
statusDotClass(edge.status),
)}
aria-hidden="true"
/>
</span>
<span className="block text-[10px] text-muted-foreground">
{node?.missing
? "Missing from the current shell"
: relationshipLabel(edge, fromThreadId)}
{edge?.status ? ` · ${edge.status}` : ""}
<span className="min-w-0 flex-1">
<span className="block truncate text-[13px] font-medium leading-4 text-foreground/85">
{threadTitle}
</span>
<span className="block truncate text-[11px] leading-4 text-muted-foreground">
{node?.missing
? "Unavailable"
: `${relationship}${edge.status ? ` · ${edge.status.replaceAll("_", " ")}` : ""}`}
</span>
</span>
</span>
<ArrowRightIcon className="size-3 text-muted-foreground" />
</button>
</li>
);
})}
</ul>
)}
</div>
<div className="grid grid-cols-1 gap-1 border-t border-border p-2 sm:grid-cols-2">
<Button
size="xs"
variant="outline"
disabled={!canFork || busyAction !== null}
onClick={fork}
>
<GitForkIcon className="size-3" />
{busyAction === "fork" ? "Forking..." : "Fork latest"}
</Button>
<Button
size="xs"
variant="outline"
disabled={!canMerge || busyAction !== null}
onClick={merge}
>
<GitBranchIcon className="size-3" />
{busyAction === "merge" ? "Merging..." : "Merge back"}
</Button>
<Button
size="xs"
variant="outline"
disabled={!canDetach || busyAction !== null}
onClick={detach}
className="sm:col-span-2"
>
<UnplugIcon className="size-3" />
{busyAction === "detach" ? "Detaching..." : "Detach provider session"}
</Button>
</div>
</PopoverPopup>
</Popover>
<ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
</button>
}
/>
<TooltipPopup side="left">
{node?.missing
? "This related thread is unavailable"
: `Open ${relationship.toLowerCase()} in this chat`}
</TooltipPopup>
</Tooltip>
{isMergeTarget ? (
<Tooltip>
<TooltipTrigger
render={
<span className="mr-1 inline-flex shrink-0">
<Button
size="xs"
variant="outline"
className="gap-1 px-1.5 text-[11px]"
aria-label={
parentTitle
? `Merge back to ${parentTitle}`
: "Merge back to source conversation"
}
disabled={!canMerge || busyAction !== null}
onClick={() => void merge()}
>
{busyAction === "merge" ? (
<LoaderCircleIcon className="size-3 animate-spin" />
) : (
<GitMergeIcon className="size-3" />
)}
{busyAction === "merge" ? "Merging" : "Merge back"}
</Button>
</span>
}
/>
<TooltipPopup side="left">
{latestCompletedRun === null
? "Complete a run in this fork before merging it back"
: parentTitle
? `Merge this conversation back into ${parentTitle}`
: "Merge this conversation back into its source"}
</TooltipPopup>
</Tooltip>
) : null}
</li>
);
})}
</ul>
) : null}
{hiddenRelationshipCount > 0 ? (
<p className="px-2 pt-1 text-[10px] text-muted-foreground">
{hiddenRelationshipCount} more direct relationship
{hiddenRelationshipCount === 1 ? "" : "s"}
</p>
) : null}
</section>
);
}
@@ -0,0 +1,24 @@
/**
* Visual primitives shared by controls when they are rendered in the thread details panel.
*
* The core control variants intentionally become denser at the `sm` breakpoint. The panel has
* its own fixed density, so every size and type override here includes its desktop counterpart.
*/
export const THREAD_DETAILS_PANEL_ROW_CLASS =
"h-9 w-full justify-start gap-2.5 rounded-lg border-transparent bg-transparent px-2.5 text-[13px] font-medium text-foreground/80 shadow-none before:shadow-none sm:h-9 sm:text-[13px]";
export const THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS =
"h-9 w-full justify-start gap-2.5 rounded-lg border border-transparent px-2.5 text-[13px] font-medium text-foreground/80 sm:h-9 sm:text-[13px]";
export const THREAD_DETAILS_PANEL_ICON_CLASS = "size-4 shrink-0 text-muted-foreground";
export const THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS =
"group/thread-details-action flex w-full items-center rounded-lg transition-colors hover:bg-muted/65 focus-within:bg-muted/65";
export const THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS =
"h-9 min-w-0 flex-1 justify-start gap-2.5 rounded-e-none border-transparent bg-transparent px-2.5 pr-2 text-[13px] font-medium text-foreground/80 shadow-none before:shadow-none sm:h-9 sm:text-[13px] [&:hover]:bg-transparent [&[data-pressed]]:bg-transparent";
export const THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS =
"h-9 w-8 rounded-s-none border-transparent bg-transparent px-0 shadow-none before:shadow-none sm:h-9 sm:w-8 [&:hover]:bg-transparent [&[data-pressed]]:bg-transparent";
export const THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS = "h-4 w-px shrink-0 bg-border/65";
@@ -1,85 +1,50 @@
import {
type ReactNode,
type RefObject,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import { type ReactNode } from "react";
import { isElectron } from "~/env";
import { useResizableWidth } from "~/hooks/useResizableWidth";
import {
type PreviewPanelInlineSize,
usePreviewPanelInlineSize,
} from "~/hooks/usePreviewPanelInlineSize";
import { cn } from "~/lib/utils";
import { RightPanelResizeHandle } from "./RightPanelResizeHandle";
export type PreviewPanelMode = "inline" | "sheet" | "sidebar" | "embedded";
const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width";
const PREVIEW_PANEL_MIN_WIDTH = 360;
/**
* Upper bound as a fraction of the viewport; only binds on wide screens.
* On narrow windows the container clamp below is what preserves the
* sibling column's space.
*/
const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7;
const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
/**
* Width reserved for the sibling column (chat, pull-request list) sharing the
* panel's flex row. The viewport fraction alone is not enough: the app
* sidebar sits outside the row, so on narrow windows (any MacBook, even
* fullscreen) the remaining 30% of the viewport minus the sidebar left the
* sibling below its usable width and the composer overflowed.
*/
const SIBLING_COLUMN_MIN_WIDTH = 360;
export function getPreviewPanelMaxWidth(viewportWidth: number, containerWidth?: number): number {
const fractionCap = Math.floor(viewportWidth * PREVIEW_PANEL_MAX_WIDTH_FRACTION);
const containerCap =
containerWidth === undefined ? Infinity : Math.floor(containerWidth) - SIBLING_COLUMN_MIN_WIDTH;
// Never below the panel's own minimum: when the row cannot fit both
// columns' minimums the sibling yields, and useResizableWidth's clamp
// must not see max < min (it would resolve the inversion to min and,
// via drag-end persistence, overwrite the user's stored width).
return Math.max(PREVIEW_PANEL_MIN_WIDTH, Math.min(fractionCap, containerCap));
}
/**
* Shell for the preview panel. In inline mode the panel is user-resizable
* via a drag handle on the left edge; width persists per browser. In
* sheet/sidebar modes the parent owns the size.
*/
export function PreviewPanelShell(props: {
interface PreviewPanelShellProps {
mode: PreviewPanelMode;
maximized?: boolean;
/**
* Overrides the localStorage key used to persist the panel width. Callers
* embedding this shell for a different surface (e.g. the pull requests
* page) should pass their own key so resizing one panel doesn't clobber
* the other's remembered width.
*/
widthStorageKey?: string;
/** Overrides the initial width (px) before the user has resized the panel. */
defaultWidth?: number;
inlineSize?: PreviewPanelInlineSize;
children: ReactNode;
}) {
}
export function PreviewPanelShell(props: PreviewPanelShellProps) {
if (props.inlineSize) {
return <PreviewPanelShellFrame {...props} inlineSize={props.inlineSize} />;
}
return <ResizablePreviewPanelShell {...props} />;
}
function ResizablePreviewPanelShell(props: PreviewPanelShellProps) {
const inlineSize = usePreviewPanelInlineSize();
return <PreviewPanelShellFrame {...props} inlineSize={inlineSize} />;
}
function PreviewPanelShellFrame(
props: PreviewPanelShellProps & { inlineSize: PreviewPanelInlineSize },
) {
const useDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded";
const isInline = props.mode === "inline";
const hostRef = useRef<HTMLDivElement | null>(null);
// Only inline non-maximized mode applies `width`/`maxWidth`; skip the
// container measurement (and its re-renders) everywhere else.
const maxWidth = useClampedMaxWidth(hostRef, isInline && !props.maximized);
const { width, handlers } = useResizableWidth({
storageKey: props.widthStorageKey ?? PREVIEW_PANEL_WIDTH_STORAGE_KEY,
defaultWidth: props.defaultWidth ?? PREVIEW_PANEL_DEFAULT_WIDTH,
minWidth: PREVIEW_PANEL_MIN_WIDTH,
maxWidth,
edge: "left",
});
const { width, handlers } = props.inlineSize;
return (
<div
ref={hostRef}
className={cn(
"relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
isInline
@@ -98,54 +63,3 @@ export function PreviewPanelShell(props: {
</div>
);
}
/**
* Track viewport and flex-row widths to derive an upper bound for the panel.
* Resize-aware so dragging the OS window narrower (or expanding the app
* sidebar) re-clamps the stored width on the next render (the hook's clamp
* picks this up automatically). The row is observed rather than the panel
* itself because the panel competes with its sibling column for row space.
* Row measurement only runs when `enabled`; modes without a resize handle
* never apply the resulting width, so they skip the observer entirely.
*/
function useClampedMaxWidth(hostRef: RefObject<HTMLDivElement | null>, enabled: boolean): number {
const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
const [containerWidth, setContainerWidth] = useState<number | undefined>(undefined);
useEffect(() => {
if (typeof window === "undefined") return;
let frame = 0;
const onResize = () => {
// Coalesce rapid resize events into one rAF tick.
if (frame !== 0) return;
frame = window.requestAnimationFrame(() => {
frame = 0;
setVw(window.innerWidth);
});
};
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
if (frame !== 0) window.cancelAnimationFrame(frame);
};
}, []);
useLayoutEffect(() => {
if (!enabled) return;
const parent = hostRef.current?.parentElement;
if (!parent) return;
// Measure before first paint: the persisted width must be clamped
// against the row on the initial render, not one observer tick later
// (the panel would flash over-wide on every mount). clientWidth is
// integral, so sub-pixel resize deltas bail out of re-rendering.
const measure = () => {
setContainerWidth(parent.clientWidth);
};
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(parent);
return () => {
observer.disconnect();
};
}, [hostRef, enabled]);
return getPreviewPanelMaxWidth(vw, containerWidth);
}
@@ -27,7 +27,7 @@ const snapshot = (tabId: string): PreviewSessionSnapshot => ({
beforeEach(() => {
resetPreviewStateForTests();
useRightPanelStore.setState({ byThreadKey: {} });
useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
});
describe("addBrowserSurface", () => {
@@ -135,7 +135,7 @@ describe("KeybindingsSettings.logic", () => {
expect(options).not.toContain("customModeActive");
});
it("builds command options from built-in commands and resolved project bindings", () => {
it("builds command options from built-ins and resolved project bindings", () => {
const options = buildKeybindingCommandOptions([
{
command: "script.setup-db.run",
@@ -151,7 +151,7 @@ describe("KeybindingsSettings.logic", () => {
] satisfies ResolvedKeybindingsConfig);
expect(options).toEqual(
expect.arrayContaining(["chat.new", "rightPanel.toggleMaximized", "script.setup-db.run"]),
expect.arrayContaining(["chat.new", "threadPanel.toggle", "script.setup-db.run"]),
);
});
@@ -1,5 +1,5 @@
import {
STATIC_KEYBINDING_COMMANDS,
BUILT_IN_KEYBINDING_COMMANDS,
type KeybindingCommand,
type KeybindingShortcut,
type KeybindingWhenNode,
@@ -256,7 +256,7 @@ export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
export function buildKeybindingCommandOptions(
keybindings: ResolvedKeybindingsConfig,
): ReadonlyArray<KeybindingCommandOption> {
const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
const commands = new Set<KeybindingCommand>(BUILT_IN_KEYBINDING_COMMANDS);
for (const binding of keybindings) {
commands.add(binding.command);
}
+6 -1
View File
@@ -19,6 +19,7 @@ function PopoverTrigger({ className, children, ...props }: PopoverPrimitive.Trig
function PopoverPopup({
children,
className,
positionerClassName,
viewportClassName,
side = "bottom",
align = "center",
@@ -28,6 +29,7 @@ function PopoverPopup({
anchor,
...props
}: PopoverPrimitive.Popup.Props & {
positionerClassName?: string;
viewportClassName?: string;
side?: PopoverPrimitive.Positioner.Props["side"];
align?: PopoverPrimitive.Positioner.Props["align"];
@@ -42,7 +44,10 @@ function PopoverPopup({
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-[130] h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-transform data-instant:transition-none"
className={cn(
"z-[130] h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none",
positionerClassName,
)}
data-slot="popover-positioner"
side={side}
sideOffset={sideOffset}
+1 -1
View File
@@ -12,7 +12,7 @@ const THREAD_REF = scopeThreadRef(
describe("openDiffFilePrimaryAction", () => {
beforeEach(() => {
useRightPanelStore.setState({ byThreadKey: {} });
useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
});
it("opens diff files in the thread file viewer", () => {
+25
View File
@@ -0,0 +1,25 @@
import { useLayoutEffect, useState } from "react";
export function useElementWidth<T extends HTMLElement>() {
const [element, setElement] = useState<T | null>(null);
const [width, setWidth] = useState<number | null>(null);
useLayoutEffect(() => {
if (!element) return;
const update = (nextWidth: number) => {
setWidth((currentWidth) => (currentWidth === nextWidth ? currentWidth : nextWidth));
};
update(element.getBoundingClientRect().width);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(([entry]) => {
if (entry) update(entry.contentRect.width);
});
observer.observe(element);
return () => observer.disconnect();
}, [element]);
return [setElement, width] as const;
}
@@ -0,0 +1,49 @@
import { useEffect, useState } from "react";
import { type ResizableWidthHandlers, useResizableWidth } from "./useResizableWidth";
export interface PreviewPanelInlineSize {
readonly width: number;
readonly handlers: ResizableWidthHandlers;
}
const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width";
const PREVIEW_PANEL_MIN_WIDTH = 360;
/** Hard ceiling so a wide monitor can't yield a panel that swallows the chat. */
const PREVIEW_PANEL_MAX_WIDTH_PX = 1400;
/** Fraction of the viewport allowed; the panel is min(this · vw, MAX_PX). */
const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7;
const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
export function usePreviewPanelInlineSize(): PreviewPanelInlineSize {
const maxWidth = useViewportClampedMaxWidth();
return useResizableWidth({
storageKey: PREVIEW_PANEL_WIDTH_STORAGE_KEY,
defaultWidth: PREVIEW_PANEL_DEFAULT_WIDTH,
minWidth: PREVIEW_PANEL_MIN_WIDTH,
maxWidth,
edge: "left",
});
}
/** Keep the resizable panel's upper bound in sync with the current window. */
function useViewportClampedMaxWidth(): number {
const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
useEffect(() => {
if (typeof window === "undefined") return;
let frame = 0;
const onResize = () => {
if (frame !== 0) return;
frame = window.requestAnimationFrame(() => {
frame = 0;
setVw(window.innerWidth);
});
};
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
if (frame !== 0) window.cancelAnimationFrame(frame);
};
}, []);
return Math.min(PREVIEW_PANEL_MAX_WIDTH_PX, Math.floor(vw * PREVIEW_PANEL_MAX_WIDTH_FRACTION));
}
+6 -27
View File
@@ -536,37 +536,16 @@ describe("chat/editor shortcuts", () => {
);
});
it("matches filePicker.toggle shortcut outside terminal focus", () => {
assert.strictEqual(
resolveShortcutCommand(event({ key: "p", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: false },
}),
"filePicker.toggle",
);
assert.notStrictEqual(
resolveShortcutCommand(event({ key: "p", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: true },
}),
"filePicker.toggle",
);
});
it("resolves a user-configured thread panel shortcut without assigning a default", () => {
const bindings = compile([
{ shortcut: modShortcut("b", { shiftKey: true }), command: "threadPanel.toggle" },
]);
it("matches projectSearch.toggle shortcut outside terminal focus", () => {
assert.strictEqual(
resolveShortcutCommand(event({ key: "f", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
resolveShortcutCommand(event({ key: "b", metaKey: true, shiftKey: true }), bindings, {
platform: "MacIntel",
context: { terminalFocus: false },
}),
"projectSearch.toggle",
);
assert.notStrictEqual(
resolveShortcutCommand(event({ key: "f", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: true },
}),
"projectSearch.toggle",
"threadPanel.toggle",
);
});
@@ -3,7 +3,9 @@ import { ThreadId } from "@t3tools/contracts";
import {
deriveThreadRelationshipGraph,
immediateThreadRelationships,
relatedThreadIds,
resolveMergeBackTargetThreadId,
walkThreadRelationships,
} from "./threadRelationships";
@@ -41,5 +43,54 @@ describe("thread relationships", () => {
[child, 1],
[missing, 2],
]);
expect(immediateThreadRelationships(graph, root).map(({ threadId }) => threadId)).toEqual([
child,
]);
});
it("resolves merge-back only for forks and prefers the recorded fork source", () => {
const source = ThreadId.make("thread-source");
const fallbackParent = ThreadId.make("thread-parent");
const fork = ThreadId.make("thread-fork");
expect(
resolveMergeBackTargetThreadId({
thread: {
id: fork,
forkedFrom: { type: "run", threadId: source, runId: "run-source" },
lineage: {
rootThreadId: source,
parentThreadId: fallbackParent,
relationshipToParent: "fork",
},
},
} as never),
).toBe(source);
expect(
resolveMergeBackTargetThreadId({
thread: {
id: fork,
forkedFrom: null,
lineage: {
rootThreadId: source,
parentThreadId: fallbackParent,
relationshipToParent: "fork",
},
},
} as never),
).toBe(fallbackParent);
expect(
resolveMergeBackTargetThreadId({
thread: {
id: fork,
forkedFrom: null,
lineage: {
rootThreadId: source,
parentThreadId: fallbackParent,
relationshipToParent: "subagent",
},
},
} as never),
).toBeNull();
});
});
+31
View File
@@ -31,6 +31,15 @@ export interface ThreadRelationshipWalkRow {
readonly edge: ThreadRelationshipEdge;
}
export function resolveMergeBackTargetThreadId(
projection: Pick<OrchestrationV2ThreadProjection, "thread"> | null,
): ThreadId | null {
if (projection?.thread.lineage.relationshipToParent !== "fork") return null;
return projection.thread.forkedFrom?.type === "run"
? projection.thread.forkedFrom.threadId
: projection.thread.lineage.parentThreadId;
}
function edgeKey(edge: ThreadRelationshipEdge): string {
return `${edge.sourceThreadId}\u001f${edge.targetThreadId}\u001f${edge.kind}`;
}
@@ -137,3 +146,25 @@ export function walkThreadRelationships(
return rows;
}
export function immediateThreadRelationships(
graph: ThreadRelationshipGraph,
threadId: ThreadId,
): ReadonlyArray<ThreadRelationshipWalkRow> {
const visited = new Set<ThreadId>();
const rows: ThreadRelationshipWalkRow[] = [];
for (const edge of graph.edges) {
const relatedId =
edge.sourceThreadId === threadId
? edge.targetThreadId
: edge.targetThreadId === threadId
? edge.sourceThreadId
: null;
if (relatedId === null || visited.has(relatedId)) continue;
visited.add(relatedId);
rows.push({ threadId: relatedId, fromThreadId: threadId, depth: 1, edge });
}
return rows;
}
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveThreadPanelPresentation } from "./rightPanelLayout";
describe("resolveThreadPanelPresentation", () => {
it("uses the stable workspace width minus the real right panel width", () => {
expect(resolveThreadPanelPresentation(null, 0, false)).toBe("inline");
expect(resolveThreadPanelPresentation(960, 0, false)).toBe("inline");
expect(resolveThreadPanelPresentation(959, 0, false)).toBe("popover");
expect(resolveThreadPanelPresentation(1_400, 0, false)).toBe("inline");
expect(resolveThreadPanelPresentation(1_400, 540, false)).toBe("popover");
expect(resolveThreadPanelPresentation(1_500, 540, false)).toBe("inline");
});
it("uses a popover while the real right panel is maximized", () => {
expect(resolveThreadPanelPresentation(2_000, 0, true)).toBe("popover");
});
});
+14
View File
@@ -1,3 +1,17 @@
export const RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 980px)";
export const THREAD_PANEL_INLINE_MIN_WIDTH = 960;
export const RIGHT_PANEL_SHEET_CLASS_NAME =
"w-[min(42vw,28rem)] min-w-80 max-w-[28rem] p-0 max-[760px]:w-[min(88vw,24rem)] max-[760px]:min-w-0 wco:mt-[env(titlebar-area-height)] wco:h-[calc(100%-env(titlebar-area-height))] wco:max-h-[calc(100%-env(titlebar-area-height))]";
export type ThreadPanelPresentation = "inline" | "popover";
export function resolveThreadPanelPresentation(
workspaceWidth: number | null,
occupiedRightPanelWidth: number,
rightPanelMaximized: boolean,
): ThreadPanelPresentation {
if (workspaceWidth === null) return "inline";
const chatPaneWidth = rightPanelMaximized ? 0 : workspaceWidth - occupiedRightPanelWidth;
return chatPaneWidth < THREAD_PANEL_INLINE_MIN_WIDTH ? "popover" : "inline";
}
+67 -26
View File
@@ -8,6 +8,8 @@ import {
selectActiveRightPanel,
selectActiveRightPanelSurface,
selectSelectedRightPanelSurface,
selectThreadPanelOpen,
selectThreadPanelVisibility,
selectThreadRightPanelState,
updatePullRequestTabStatus,
useRightPanelStore,
@@ -17,7 +19,7 @@ const refA = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-A"))
const refB = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-B"));
beforeEach(() => {
useRightPanelStore.setState({ byThreadKey: {} });
useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
});
describe("rightPanelStore", () => {
@@ -42,6 +44,7 @@ describe("rightPanelStore", () => {
surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }],
},
},
threadPanelVisibilityByThreadKey: {},
});
});
@@ -72,6 +75,7 @@ describe("rightPanelStore", () => {
],
},
},
threadPanelVisibilityByThreadKey: {},
});
});
@@ -102,6 +106,7 @@ describe("rightPanelStore", () => {
],
},
},
threadPanelVisibilityByThreadKey: {},
});
});
@@ -178,40 +183,76 @@ describe("rightPanelStore", () => {
});
it("drops persisted plan surfaces and does not reopen an empty panel", () => {
it("persists inline preference without restoring an open popover", () => {
expect(
migratePersistedRightPanelState({
byThreadKey: {
"env-1:thread-A": {
isOpen: true,
activeSurfaceId: "plan",
surfaces: [{ id: "plan", kind: "plan" }],
},
"env-1:thread-B": {
isOpen: true,
activeSurfaceId: "plan",
surfaces: [
{ id: "plan", kind: "plan" },
{ id: "diff", kind: "diff" },
],
},
threadPanelVisibilityByThreadKey: {
"env-1:thread-A": { inlineOpen: false, popoverOpen: true },
"env-1:thread-B": { inlineOpen: true, popoverOpen: true },
},
}),
).toEqual({
byThreadKey: {
"env-1:thread-A": {
isOpen: false,
activeSurfaceId: null,
surfaces: [],
},
"env-1:thread-B": {
isOpen: true,
activeSurfaceId: "diff",
surfaces: [{ id: "diff", kind: "diff" }],
},
byThreadKey: {},
threadPanelVisibilityByThreadKey: {
"env-1:thread-A": { inlineOpen: false, popoverOpen: false },
},
});
});
it("tracks inline and popover visibility independently", () => {
const store = useRightPanelStore.getState();
expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "inline")).toBe(
true,
);
expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "popover")).toBe(
false,
);
store.setThreadPanelOpen(refA, "inline", false);
store.toggleThreadPanel(refA, "popover");
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: false, popoverOpen: true });
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refB,
),
).toEqual({ inlineOpen: true, popoverOpen: false });
});
it("closes the popover atomically when the real right panel opens", () => {
useRightPanelStore.getState().setThreadPanelOpen(refA, "popover", true);
useRightPanelStore.getState().open(refA, "plan");
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: true, popoverOpen: false });
});
it("keeps an open popover visible by promoting it to inline when the real panel closes", () => {
const store = useRightPanelStore.getState();
store.open(refA, "plan");
store.setThreadPanelOpen(refA, "inline", false);
store.setThreadPanelOpen(refA, "popover", true);
store.close(refA);
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: true, popoverOpen: true });
});
it("open sets the active panel for a thread", () => {
useRightPanelStore.getState().open(refA, "preview");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview");
+206 -64
View File
@@ -13,6 +13,7 @@ import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "./lib/storage";
import type { ThreadPanelPresentation } from "./rightPanelLayout";
export const RIGHT_PANEL_KINDS = [
"diff",
@@ -82,8 +83,14 @@ export interface ThreadRightPanelState {
surfaces: RightPanelSurface[];
}
export interface ThreadPanelVisibility {
inlineOpen: boolean;
popoverOpen: boolean;
}
interface RightPanelStoreState {
byThreadKey: Record<string, ThreadRightPanelState>;
threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
open: (
ref: ScopedThreadRef,
kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
@@ -117,6 +124,12 @@ interface RightPanelStoreState {
ref: ScopedThreadRef,
kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
) => void;
setThreadPanelOpen: (
ref: ScopedThreadRef,
presentation: ThreadPanelPresentation,
open: boolean,
) => void;
toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
removeThread: (ref: ScopedThreadRef) => void;
}
@@ -126,6 +139,11 @@ const EMPTY_THREAD_STATE: ThreadRightPanelState = {
surfaces: [],
};
const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
inlineOpen: true,
popoverOpen: false,
};
const singletonSurface = (
kind: Exclude<RightPanelKind, "file" | "preview" | "terminal" | "pull-request">,
): RightPanelSurface => {
@@ -224,7 +242,7 @@ const upsertSurface = (
activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
});
const updateThread = (
const updateThreadStateMap = (
byThreadKey: Record<string, ThreadRightPanelState>,
threadKey: string,
updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
@@ -240,6 +258,63 @@ const updateThread = (
return { ...byThreadKey, [threadKey]: next };
};
const updateThreadPanelVisibilityMap = (
byThreadKey: Record<string, ThreadPanelVisibility>,
threadKey: string,
updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
): Record<string, ThreadPanelVisibility> => {
const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
const next = updater(current);
if (next.inlineOpen && !next.popoverOpen) {
if (!(threadKey in byThreadKey)) return byThreadKey;
const { [threadKey]: _removed, ...rest } = byThreadKey;
return rest;
}
if (next === current) return byThreadKey;
return { ...byThreadKey, [threadKey]: next };
};
type RightPanelStoreData = Pick<
RightPanelStoreState,
"byThreadKey" | "threadPanelVisibilityByThreadKey"
>;
/**
* Applies a real right-panel mutation and its thread-panel transition atomically.
* This is the only path real panel actions use, so visibility never has to be
* reconciled after the fact in React.
*/
const updateThread = (
state: RightPanelStoreData,
ref: ScopedThreadRef,
updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
): RightPanelStoreData => {
const threadKey = scopedThreadKey(ref);
const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
if (!current.isOpen && next.isOpen) {
threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
threadPanelVisibilityByThreadKey,
threadKey,
(visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
);
} else if (current.isOpen && !next.isOpen) {
threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
threadPanelVisibilityByThreadKey,
threadKey,
(visibility) =>
visibility.popoverOpen && !visibility.inlineOpen
? { ...visibility, inlineOpen: true }
: visibility,
);
}
return { byThreadKey, threadPanelVisibilityByThreadKey };
};
function normalizeRevealLine(line: number | undefined): number | null {
if (line === undefined || !Number.isFinite(line)) return null;
return Math.max(1, Math.trunc(line));
@@ -247,9 +322,10 @@ function normalizeRevealLine(line: number | undefined): number | null {
export function migratePersistedRightPanelState(persistedState: unknown): {
byThreadKey: Record<string, ThreadRightPanelState>;
threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
} {
if (!persistedState || typeof persistedState !== "object") {
return { byThreadKey: {} };
return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
}
const byThreadKey =
"byThreadKey" in persistedState &&
@@ -357,42 +433,56 @@ export function migratePersistedRightPanelState(persistedState: unknown): {
}),
)
: {};
return { byThreadKey };
const threadPanelVisibilityByThreadKey =
"threadPanelVisibilityByThreadKey" in persistedState &&
persistedState.threadPanelVisibilityByThreadKey &&
typeof persistedState.threadPanelVisibilityByThreadKey === "object"
? Object.fromEntries(
Object.entries(
persistedState.threadPanelVisibilityByThreadKey as Record<string, unknown>,
).flatMap(([threadKey, value]) => {
if (!value || typeof value !== "object" || !("inlineOpen" in value)) return [];
return value.inlineOpen === false
? [[threadKey, { inlineOpen: false, popoverOpen: false }]]
: [];
}),
)
: {};
return { byThreadKey, threadPanelVisibilityByThreadKey };
}
export const useRightPanelStore = create<RightPanelStoreState>()(
persist(
(set) => ({
byThreadKey: {},
threadPanelVisibilityByThreadKey: {},
open: (ref, kind) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
if (kind === "preview") {
const existing = current.surfaces.find((surface) => surface.kind === "preview");
return upsertSurface(current, existing ?? browserSurface(null));
}
return upsertSurface(current, singletonSurface(kind));
}),
})),
),
openBrowser: (ref, tabId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
const surface = browserSurface(tabId);
const withoutPlaceholder = tabId
? current.surfaces.filter((entry) => entry.id !== "browser:new")
: current.surfaces;
return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
}),
})),
),
openPullRequest: (ref, target) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
return upsertSurface(current, pullRequestSurface(target));
}),
})),
set((state) =>
updateThread(state, ref, (current) => upsertSurface(current, pullRequestSurface(target))),
),
openFile: (ref, relativePath, line) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
const withoutStandaloneExplorer = current.surfaces.filter(
(surface) => surface.kind !== "files",
);
@@ -416,16 +506,16 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
: [...withoutStandaloneExplorer, surface],
};
}),
})),
),
openTerminal: (ref, terminalId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
set((state) =>
updateThread(state, ref, (current) =>
upsertSurface(current, terminalSurface(terminalId)),
),
})),
),
splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
set((state) =>
updateThread(state, ref, (current) => ({
...current,
isOpen: true,
activeSurfaceId: surfaceId,
@@ -442,10 +532,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
};
}),
})),
})),
),
activateTerminal: (ref, surfaceId, terminalId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
set((state) =>
updateThread(state, ref, (current) => ({
...current,
activeSurfaceId: surfaceId,
surfaces: current.surfaces.map((surface) =>
@@ -456,10 +546,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
: surface,
),
})),
})),
),
closeTerminal: (ref, surfaceId, terminalId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
const surface = current.surfaces.find(
(entry) => entry.id === surfaceId && entry.kind === "terminal",
);
@@ -495,18 +585,18 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
),
};
}),
})),
),
activateSurface: (ref, surfaceId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
set((state) =>
updateThread(state, ref, (current) =>
current.surfaces.some((surface) => surface.id === surfaceId)
? { ...current, isOpen: true, activeSurfaceId: surfaceId }
: current,
),
})),
),
closeSurface: (ref, surfaceId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
if (index < 0) return current;
const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
@@ -521,10 +611,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
activeSurfaceId: fallback?.id ?? null,
};
}),
})),
),
closeOtherSurfaces: (ref, surfaceId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
const surface = current.surfaces.find((entry) => entry.id === surfaceId);
if (!surface || current.surfaces.length === 1) return current;
return {
@@ -534,10 +624,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
activeSurfaceId: surface.id,
};
}),
})),
),
closeSurfacesToRight: (ref, surfaceId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
if (index < 0 || index === current.surfaces.length - 1) return current;
const surfaces = current.surfaces.slice(0, index + 1);
@@ -550,18 +640,18 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
};
}),
})),
),
closeAllSurfaces: (ref) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
set((state) =>
updateThread(state, ref, (current) =>
current.surfaces.length === 0
? current
: { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
),
})),
),
reconcileBrowserSurfaces: (ref, tabIds) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
const existingBrowser = current.surfaces.filter(
@@ -587,10 +677,10 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
: (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
};
}),
})),
),
reconcileFileSurfaces: (ref, workspaceAvailable) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
if (workspaceAvailable) return current;
const surfaces = current.surfaces.filter(
(surface) => surface.kind !== "files" && surface.kind !== "file",
@@ -608,29 +698,29 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
: (surfaces.at(-1)?.id ?? null),
};
}),
})),
),
show: (ref) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
set((state) =>
updateThread(state, ref, (current) =>
current.isOpen ? current : { ...current, isOpen: true },
),
})),
),
close: (ref) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
set((state) =>
updateThread(state, ref, (current) =>
current.isOpen ? { ...current, isOpen: false } : current,
),
})),
),
toggleVisibility: (ref) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
set((state) =>
updateThread(state, ref, (current) => ({
...current,
isOpen: !current.isOpen,
})),
})),
),
toggle: (ref, kind) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
set((state) =>
updateThread(state, ref, (current) => {
const active = current.surfaces.find(
(surface) => surface.id === current.activeSurfaceId,
);
@@ -643,13 +733,42 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
}
return upsertSurface(current, singletonSurface(kind));
}),
),
setThreadPanelOpen: (ref, presentation, open) =>
set((state) => ({
threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
state.threadPanelVisibilityByThreadKey,
scopedThreadKey(ref),
(visibility) => {
const key = presentation === "inline" ? "inlineOpen" : "popoverOpen";
return visibility[key] === open ? visibility : { ...visibility, [key]: open };
},
),
})),
toggleThreadPanel: (ref, presentation) =>
set((state) => ({
threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
state.threadPanelVisibilityByThreadKey,
scopedThreadKey(ref),
(visibility) =>
presentation === "inline"
? { ...visibility, inlineOpen: !visibility.inlineOpen }
: { ...visibility, popoverOpen: !visibility.popoverOpen },
),
})),
removeThread: (ref) =>
set((state) => {
const threadKey = scopedThreadKey(ref);
if (!(threadKey in state.byThreadKey)) return state;
const { [threadKey]: _removed, ...rest } = state.byThreadKey;
return { byThreadKey: rest };
if (
!(threadKey in state.byThreadKey) &&
!(threadKey in state.threadPanelVisibilityByThreadKey)
) {
return state;
}
const { [threadKey]: _removedPanel, ...byThreadKey } = state.byThreadKey;
const { [threadKey]: _removedVisibility, ...threadPanelVisibilityByThreadKey } =
state.threadPanelVisibilityByThreadKey;
return { byThreadKey, threadPanelVisibilityByThreadKey };
}),
}),
{
@@ -664,6 +783,12 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
([threadKey]) => !isPullRequestsPanelKey(threadKey),
),
),
threadPanelVisibilityByThreadKey: Object.fromEntries(
Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
([threadKey, visibility]) =>
visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
),
),
}),
migrate: migratePersistedRightPanelState,
},
@@ -678,6 +803,23 @@ export function selectThreadRightPanelState(
return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
}
export function selectThreadPanelVisibility(
byThreadKey: Record<string, ThreadPanelVisibility>,
ref: ScopedThreadRef | null | undefined,
): ThreadPanelVisibility {
if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY;
return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
}
export function selectThreadPanelOpen(
byThreadKey: Record<string, ThreadPanelVisibility>,
ref: ScopedThreadRef | null | undefined,
presentation: ThreadPanelPresentation,
): boolean {
const visibility = selectThreadPanelVisibility(byThreadKey, ref);
return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
}
export function selectActiveRightPanel(
byThreadKey: Record<string, ThreadRightPanelState>,
ref: ScopedThreadRef | null | undefined,
@@ -31,6 +31,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ProviderModelPicker } from "../components/chat/ProviderModelPicker";
import { usePrimarySettings } from "../hooks/useSettings";
import { resolveMergeBackTargetThreadId } from "../lib/threadRelationships";
import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils";
import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection";
import { deriveOrchestrationV2DebugProviderSnapshots } from "../orchestrationV2DebugProviders";
@@ -2715,13 +2716,8 @@ function latestCompletedRunInProjection(
function deriveMergeBackCandidate(
projection: OrchestrationV2ThreadProjection | null,
): MergeBackCandidate | null {
if (projection === null || projection.thread.lineage.relationshipToParent !== "fork") {
return null;
}
const targetThreadId =
projection.thread.forkedFrom?.type === "run"
? projection.thread.forkedFrom.threadId
: projection.thread.lineage.parentThreadId;
if (projection === null) return null;
const targetThreadId = resolveMergeBackTargetThreadId(projection);
if (targetThreadId === null) {
return null;
}
+8 -17
View File
@@ -19,6 +19,7 @@ import { environmentProjects } from "./projects";
import { environmentServerConfigsAtom } from "./server";
import { allEnvironmentShellsBootstrappedAtom } from "./shell";
import { environmentThreadDetails, environmentThreadShells } from "./threads";
import { waitForAtomValue } from "./waitForAtomValue";
const EMPTY_PROJECT_REFS: ReadonlyArray<ScopedProjectRef> = Object.freeze([]);
const EMPTY_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
@@ -218,23 +219,13 @@ export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell |
return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
}
/** Whether the environment's server understands thread.settle/unsettle.
False for pre-settlement servers (capability defaults false on decode),
so clients under version skew fall back instead of erroring. */
export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSettlement === true
);
}
/** Whether the environment's server understands thread.snooze/unsnooze.
Same version-skew contract as settlement. */
export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSnooze === true
);
export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
return waitForAtomValue({
registry: appAtomRegistry,
atom: environmentThreadShells.threadShellAtom(ref),
predicate: (thread) => thread !== null,
timeoutMs,
});
}
/** Whether the environment's server understands thread.pin/unpin.
@@ -0,0 +1,57 @@
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
import { describe, expect, it, vi } from "vite-plus/test";
import { waitForAtomValue } from "./waitForAtomValue";
describe("waitForAtomValue", () => {
it("returns immediately when the current value is ready", async () => {
const registry = AtomRegistry.make();
const atom = Atom.make("ready");
await expect(
waitForAtomValue({
registry,
atom,
predicate: (value) => value === "ready",
timeoutMs: 1_000,
}),
).resolves.toBe(true);
registry.dispose();
});
it("waits until a subscribed atom becomes ready", async () => {
const registry = AtomRegistry.make();
const atom = Atom.make("pending");
const result = waitForAtomValue({
registry,
atom,
predicate: (value) => value === "ready",
timeoutMs: 1_000,
});
registry.set(atom, "ready");
await expect(result).resolves.toBe(true);
registry.dispose();
});
it("returns false and unsubscribes when readiness times out", async () => {
vi.useFakeTimers();
const registry = AtomRegistry.make();
const atom = Atom.make("pending");
const result = waitForAtomValue({
registry,
atom,
predicate: (value) => value === "ready",
timeoutMs: 1_000,
});
await vi.advanceTimersByTimeAsync(1_000);
await expect(result).resolves.toBe(false);
registry.set(atom, "ready");
registry.dispose();
vi.useRealTimers();
});
});
+56
View File
@@ -0,0 +1,56 @@
import type { Atom, AtomRegistry } from "effect/unstable/reactivity";
export async function waitForAtomValue<A>(input: {
readonly registry: AtomRegistry.AtomRegistry;
readonly atom: Atom.Atom<A>;
readonly predicate: (value: A) => boolean;
readonly timeoutMs: number;
}): Promise<boolean> {
const read = () => input.registry.get(input.atom);
if (input.predicate(read())) {
return true;
}
return await new Promise<boolean>((resolve) => {
let settled = false;
let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
let unsubscribe: (() => void) | null = null;
let unsubscribeWhenReady = false;
const finish = (result: boolean) => {
if (settled) {
return;
}
settled = true;
if (timeoutId !== null) {
globalThis.clearTimeout(timeoutId);
}
if (unsubscribe === null) {
unsubscribeWhenReady = true;
} else {
unsubscribe();
}
resolve(result);
};
unsubscribe = input.registry.subscribe(input.atom, (value) => {
if (input.predicate(value)) {
finish(true);
}
});
if (unsubscribeWhenReady) {
unsubscribe();
return;
}
// Close the gap between the initial read and subscription registration.
if (input.predicate(read())) {
finish(true);
return;
}
timeoutId = globalThis.setTimeout(() => {
finish(false);
}, input.timeoutMs);
});
}
+1
View File
@@ -320,5 +320,6 @@ describe("uiStateStore persistence", () => {
localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",
) as PersistedUiState;
expect(resolveProjectExpanded(persisted.projectExpandedById ?? {}, ["unknown"])).toBe(true);
expect(persisted).not.toHaveProperty("threadPanelOpen");
});
});
@@ -74,10 +74,10 @@ describe("applyShellStreamEvent", () => {
});
it("leaves unknown future events unchanged", () => {
const next = applyShellStreamEvent(
v2ShellSnapshot,
{ kind: "future.event", sequence: 99 } as never,
);
const next = applyShellStreamEvent(v2ShellSnapshot, {
kind: "future.event",
sequence: 99,
} as never);
expect(next).toBe(v2ShellSnapshot);
});
+4 -4
View File
@@ -42,11 +42,11 @@ it.effect("parses keybinding rules", () =>
});
assert.strictEqual(parsedRightPanelToggle.command, "rightPanel.toggle");
const parsedRightPanelToggleMaximized = yield* decode(KeybindingRule, {
key: "mod+shift+m",
command: "rightPanel.toggleMaximized",
const parsedThreadPanelToggle = yield* decode(KeybindingRule, {
key: "mod+shift+b",
command: "threadPanel.toggle",
});
assert.strictEqual(parsedRightPanelToggleMaximized.command, "rightPanel.toggleMaximized");
assert.strictEqual(parsedThreadPanelToggle.command, "threadPanel.toggle");
const parsedClose = yield* decode(KeybindingRule, {
key: "mod+w",
+3 -3
View File
@@ -47,7 +47,7 @@ export const MODEL_PICKER_KEYBINDING_COMMANDS = [
] as const;
export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number];
export const STATIC_KEYBINDING_COMMANDS = [
export const BUILT_IN_KEYBINDING_COMMANDS = [
"sidebar.toggle",
"terminal.toggle",
"terminal.split",
@@ -55,7 +55,7 @@ export const STATIC_KEYBINDING_COMMANDS = [
"terminal.new",
"terminal.close",
"rightPanel.toggle",
"rightPanel.toggleMaximized",
"threadPanel.toggle",
"diff.toggle",
"preview.toggle",
"preview.refresh",
@@ -85,7 +85,7 @@ export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([
]);
export const KeybindingCommand = Schema.Union([
Schema.Literals(STATIC_KEYBINDING_COMMANDS),
Schema.Literals(BUILT_IN_KEYBINDING_COMMANDS),
SCRIPT_RUN_COMMAND_PATTERN,
]);
export type KeybindingCommand = typeof KeybindingCommand.Type;