+
+ Lineage
+
+
+ {canFork ? (
+
-
- );
- })}
-
- )}
-
-
-
-
- {busyAction === "fork" ? "Forking..." : "Fork latest"}
-
-
-
- {busyAction === "merge" ? "Merging..." : "Merge back"}
-
-
-
- {busyAction === "detach" ? "Detaching..." : "Detach provider session"}
-
-
-
-
+
+
+ }
+ />
+
+ {node?.missing
+ ? "This related thread is unavailable"
+ : `Open ${relationship.toLowerCase()} in this chat`}
+
+
+
+ {isMergeTarget ? (
+
+
+ void merge()}
+ >
+ {busyAction === "merge" ? (
+
+ ) : (
+
+ )}
+ {busyAction === "merge" ? "Merging" : "Merge back"}
+
+
+ }
+ />
+
+ {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"}
+
+
+ ) : null}
+
+ );
+ })}
+
+ ) : null}
+
+ {hiddenRelationshipCount > 0 ? (
+
+ {hiddenRelationshipCount} more direct relationship
+ {hiddenRelationshipCount === 1 ? "" : "s"}
+
+ ) : null}
+
);
}
diff --git a/apps/web/src/components/chat/threadDetailsPanelStyles.ts b/apps/web/src/components/chat/threadDetailsPanelStyles.ts
new file mode 100644
index 0000000000..6cdf4096b3
--- /dev/null
+++ b/apps/web/src/components/chat/threadDetailsPanelStyles.ts
@@ -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";
diff --git a/apps/web/src/components/preview/PreviewPanelShell.tsx b/apps/web/src/components/preview/PreviewPanelShell.tsx
index 6de828c1e6..a0b05e4934 100644
--- a/apps/web/src/components/preview/PreviewPanelShell.tsx
+++ b/apps/web/src/components/preview/PreviewPanelShell.tsx
@@ -1,41 +1,47 @@
-import { type ReactNode, useEffect, 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;
-/** 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;
-
/**
* 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;
+ inlineSize?: PreviewPanelInlineSize;
children: ReactNode;
-}) {
+}
+
+export function PreviewPanelShell(props: PreviewPanelShellProps) {
+ if (props.inlineSize) {
+ return
;
+ }
+
+ return
;
+}
+
+function ResizablePreviewPanelShell(props: PreviewPanelShellProps) {
+ const inlineSize = usePreviewPanelInlineSize();
+ return
;
+}
+
+function PreviewPanelShellFrame(
+ props: PreviewPanelShellProps & { inlineSize: PreviewPanelInlineSize },
+) {
const useDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded";
const isInline = props.mode === "inline";
- const maxWidth = useViewportClampedMaxWidth();
- const { width, handlers } = useResizableWidth({
- storageKey: PREVIEW_PANEL_WIDTH_STORAGE_KEY,
- defaultWidth: PREVIEW_PANEL_DEFAULT_WIDTH,
- minWidth: PREVIEW_PANEL_MIN_WIDTH,
- maxWidth,
- edge: "left",
- });
+ const { width, handlers } = props.inlineSize;
return (
);
}
-
-/**
- * Track viewport width to derive a sensible upper bound for the panel.
- * Resize-aware so dragging the OS window narrower re-clamps the stored
- * width on the next render (the hook's clamp picks this up automatically).
- */
-function useViewportClampedMaxWidth(): number {
- const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
- 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);
- };
- }, []);
- return Math.min(PREVIEW_PANEL_MAX_WIDTH_PX, Math.floor(vw * PREVIEW_PANEL_MAX_WIDTH_FRACTION));
-}
diff --git a/apps/web/src/components/preview/addBrowserSurface.test.ts b/apps/web/src/components/preview/addBrowserSurface.test.ts
index 5dfc1a42e9..3e8ed345e6 100644
--- a/apps/web/src/components/preview/addBrowserSurface.test.ts
+++ b/apps/web/src/components/preview/addBrowserSurface.test.ts
@@ -27,7 +27,7 @@ const snapshot = (tabId: string): PreviewSessionSnapshot => ({
beforeEach(() => {
resetPreviewStateForTests();
- useRightPanelStore.setState({ byThreadKey: {} });
+ useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} });
});
describe("addBrowserSurface", () => {
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
index 75235a0530..7c86e644ca 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
@@ -134,7 +134,7 @@ describe("KeybindingsSettings.logic", () => {
expect(options).not.toContain("customModeActive");
});
- it("builds command options from defaults and resolved project bindings", () => {
+ it("builds command options from built-ins and resolved project bindings", () => {
const options = buildKeybindingCommandOptions([
{
command: "script.setup-db.run",
@@ -149,7 +149,9 @@ describe("KeybindingsSettings.logic", () => {
},
] satisfies ResolvedKeybindingsConfig);
- expect(options).toEqual(expect.arrayContaining(["chat.new", "script.setup-db.run"]));
+ expect(options).toEqual(
+ expect.arrayContaining(["chat.new", "threadPanel.toggle", "script.setup-db.run"]),
+ );
});
it("reports unknown when variables without rejecting parseable expressions", () => {
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
index da54e86e42..80ac6ce0ad 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
@@ -1,4 +1,5 @@
import {
+ BUILT_IN_KEYBINDING_COMMANDS,
type KeybindingCommand,
type KeybindingShortcut,
type KeybindingWhenNode,
@@ -255,10 +256,7 @@ export function buildWhenVariableOptions(): ReadonlyArray
{
export function buildKeybindingCommandOptions(
keybindings: ResolvedKeybindingsConfig,
): ReadonlyArray {
- const commands = new Set();
- for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
- commands.add(binding.command);
- }
+ const commands = new Set(BUILT_IN_KEYBINDING_COMMANDS);
for (const binding of keybindings) {
commands.add(binding.command);
}
diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsx
index de0e2e55df..dd64bb2c14 100644
--- a/apps/web/src/components/ui/popover.tsx
+++ b/apps/web/src/components/ui/popover.tsx
@@ -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-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
+ className={cn(
+ "z-50 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}
diff --git a/apps/web/src/diffFileActions.test.ts b/apps/web/src/diffFileActions.test.ts
index 9c358ab1d2..37755b84c9 100644
--- a/apps/web/src/diffFileActions.test.ts
+++ b/apps/web/src/diffFileActions.test.ts
@@ -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", () => {
diff --git a/apps/web/src/hooks/useElementWidth.ts b/apps/web/src/hooks/useElementWidth.ts
new file mode 100644
index 0000000000..d3f60eeea1
--- /dev/null
+++ b/apps/web/src/hooks/useElementWidth.ts
@@ -0,0 +1,25 @@
+import { useLayoutEffect, useState } from "react";
+
+export function useElementWidth() {
+ const [element, setElement] = useState(null);
+ const [width, setWidth] = useState(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;
+}
diff --git a/apps/web/src/hooks/usePreviewPanelInlineSize.ts b/apps/web/src/hooks/usePreviewPanelInlineSize.ts
new file mode 100644
index 0000000000..0e5de1198f
--- /dev/null
+++ b/apps/web/src/hooks/usePreviewPanelInlineSize.ts
@@ -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));
+}
diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts
index c0d326edd5..3785bf6229 100644
--- a/apps/web/src/keybindings.test.ts
+++ b/apps/web/src/keybindings.test.ts
@@ -514,6 +514,19 @@ describe("chat/editor shortcuts", () => {
);
});
+ it("resolves a user-configured thread panel shortcut without assigning a default", () => {
+ const bindings = compile([
+ { shortcut: modShortcut("b", { shiftKey: true }), command: "threadPanel.toggle" },
+ ]);
+
+ assert.strictEqual(
+ resolveShortcutCommand(event({ key: "b", metaKey: true, shiftKey: true }), bindings, {
+ platform: "MacIntel",
+ }),
+ "threadPanel.toggle",
+ );
+ });
+
it("matches diff.toggle shortcut outside terminal focus", () => {
assert.isTrue(
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
diff --git a/apps/web/src/lib/threadRelationships.test.ts b/apps/web/src/lib/threadRelationships.test.ts
index f00c37def1..3b4206e1f0 100644
--- a/apps/web/src/lib/threadRelationships.test.ts
+++ b/apps/web/src/lib/threadRelationships.test.ts
@@ -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();
});
});
diff --git a/apps/web/src/lib/threadRelationships.ts b/apps/web/src/lib/threadRelationships.ts
index c126389c9b..d57c5a468b 100644
--- a/apps/web/src/lib/threadRelationships.ts
+++ b/apps/web/src/lib/threadRelationships.ts
@@ -31,6 +31,15 @@ export interface ThreadRelationshipWalkRow {
readonly edge: ThreadRelationshipEdge;
}
+export function resolveMergeBackTargetThreadId(
+ projection: Pick | 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 {
+ const visited = new Set();
+ 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;
+}
diff --git a/apps/web/src/rightPanelLayout.test.ts b/apps/web/src/rightPanelLayout.test.ts
new file mode 100644
index 0000000000..1440aa9a17
--- /dev/null
+++ b/apps/web/src/rightPanelLayout.test.ts
@@ -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");
+ });
+});
diff --git a/apps/web/src/rightPanelLayout.ts b/apps/web/src/rightPanelLayout.ts
index 5528072e57..e85f24e4a4 100644
--- a/apps/web/src/rightPanelLayout.ts
+++ b/apps/web/src/rightPanelLayout.ts
@@ -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";
+}
diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts
index b48f6e7ebb..94a22c5d61 100644
--- a/apps/web/src/rightPanelStore.test.ts
+++ b/apps/web/src/rightPanelStore.test.ts
@@ -6,6 +6,8 @@ import {
migratePersistedRightPanelState,
selectActiveRightPanel,
selectActiveRightPanelSurface,
+ selectThreadPanelOpen,
+ selectThreadPanelVisibility,
selectThreadRightPanelState,
useRightPanelStore,
} from "./rightPanelStore";
@@ -14,7 +16,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", () => {
@@ -39,6 +41,7 @@ describe("rightPanelStore", () => {
surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }],
},
},
+ threadPanelVisibilityByThreadKey: {},
});
});
@@ -69,6 +72,7 @@ describe("rightPanelStore", () => {
],
},
},
+ threadPanelVisibilityByThreadKey: {},
});
});
@@ -99,9 +103,80 @@ describe("rightPanelStore", () => {
],
},
},
+ threadPanelVisibilityByThreadKey: {},
});
});
+ it("persists inline preference without restoring an open popover", () => {
+ expect(
+ migratePersistedRightPanelState({
+ threadPanelVisibilityByThreadKey: {
+ "env-1:thread-A": { inlineOpen: false, popoverOpen: true },
+ "env-1:thread-B": { inlineOpen: true, popoverOpen: true },
+ },
+ }),
+ ).toEqual({
+ 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");
diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts
index 70d163306c..1d7af9a110 100644
--- a/apps/web/src/rightPanelStore.ts
+++ b/apps/web/src/rightPanelStore.ts
@@ -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 = ["plan", "diff", "files", "file", "preview", "terminal"] as const;
export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
@@ -40,7 +41,7 @@ export type RightPanelSurface =
| { id: "plan"; kind: "plan" };
const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
-const RIGHT_PANEL_STORAGE_VERSION = 7;
+const RIGHT_PANEL_STORAGE_VERSION = 8;
export interface ThreadRightPanelState {
isOpen: boolean;
@@ -48,8 +49,14 @@ export interface ThreadRightPanelState {
surfaces: RightPanelSurface[];
}
+export interface ThreadPanelVisibility {
+ inlineOpen: boolean;
+ popoverOpen: boolean;
+}
+
interface RightPanelStoreState {
byThreadKey: Record;
+ threadPanelVisibilityByThreadKey: Record;
open: (ref: ScopedThreadRef, kind: Exclude) => void;
openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
@@ -73,6 +80,12 @@ interface RightPanelStoreState {
close: (ref: ScopedThreadRef) => void;
toggleVisibility: (ref: ScopedThreadRef) => void;
toggle: (ref: ScopedThreadRef, kind: Exclude) => void;
+ setThreadPanelOpen: (
+ ref: ScopedThreadRef,
+ presentation: ThreadPanelPresentation,
+ open: boolean,
+ ) => void;
+ toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
removeThread: (ref: ScopedThreadRef) => void;
}
@@ -82,6 +95,11 @@ const EMPTY_THREAD_STATE: ThreadRightPanelState = {
surfaces: [],
};
+const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
+ inlineOpen: true,
+ popoverOpen: false,
+};
+
const singletonSurface = (
kind: Exclude,
): RightPanelSurface => {
@@ -132,7 +150,7 @@ const upsertSurface = (
activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
});
-const updateThread = (
+const updateThreadStateMap = (
byThreadKey: Record,
threadKey: string,
updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
@@ -148,6 +166,63 @@ const updateThread = (
return { ...byThreadKey, [threadKey]: next };
};
+const updateThreadPanelVisibilityMap = (
+ byThreadKey: Record,
+ threadKey: string,
+ updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
+): Record => {
+ 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));
@@ -155,9 +230,10 @@ function normalizeRevealLine(line: number | undefined): number | null {
export function migratePersistedRightPanelState(persistedState: unknown): {
byThreadKey: Record;
+ threadPanelVisibilityByThreadKey: Record;
} {
if (!persistedState || typeof persistedState !== "object") {
- return { byThreadKey: {} };
+ return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
}
const byThreadKey =
"byThreadKey" in persistedState &&
@@ -232,36 +308,52 @@ 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,
+ ).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()(
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);
}),
- })),
+ ),
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",
);
@@ -285,16 +377,16 @@ export const useRightPanelStore = create()(
: [...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,
@@ -311,10 +403,10 @@ export const useRightPanelStore = create()(
};
}),
})),
- })),
+ ),
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) =>
@@ -325,10 +417,10 @@ export const useRightPanelStore = create()(
: 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",
);
@@ -364,18 +456,18 @@ export const useRightPanelStore = create()(
),
};
}),
- })),
+ ),
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);
@@ -390,10 +482,10 @@ export const useRightPanelStore = create()(
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 {
@@ -403,10 +495,10 @@ export const useRightPanelStore = create()(
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);
@@ -419,18 +511,18 @@ export const useRightPanelStore = create()(
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(
@@ -456,10 +548,10 @@ export const useRightPanelStore = create()(
: (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",
@@ -477,29 +569,29 @@ export const useRightPanelStore = create()(
: (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,
);
@@ -512,13 +604,42 @@ export const useRightPanelStore = create()(
}
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 };
}),
}),
{
@@ -527,7 +648,15 @@ export const useRightPanelStore = create()(
storage: createJSONStorage(() =>
resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
),
- partialize: (state) => ({ byThreadKey: state.byThreadKey }),
+ partialize: (state) => ({
+ byThreadKey: state.byThreadKey,
+ threadPanelVisibilityByThreadKey: Object.fromEntries(
+ Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
+ ([threadKey, visibility]) =>
+ visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
+ ),
+ ),
+ }),
migrate: migratePersistedRightPanelState,
},
),
@@ -541,6 +670,23 @@ export function selectThreadRightPanelState(
return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
}
+export function selectThreadPanelVisibility(
+ byThreadKey: Record,
+ 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,
+ ref: ScopedThreadRef | null | undefined,
+ presentation: ThreadPanelPresentation,
+): boolean {
+ const visibility = selectThreadPanelVisibility(byThreadKey, ref);
+ return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
+}
+
export function selectActiveRightPanel(
byThreadKey: Record,
ref: ScopedThreadRef | null | undefined,
diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx
index 015c78eab0..dc83bf248d 100644
--- a/apps/web/src/routes/debug.orchestration-v2.tsx
+++ b/apps/web/src/routes/debug.orchestration-v2.tsx
@@ -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";
@@ -2694,13 +2695,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;
}
diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts
index 68e78b6407..9eac5dda7a 100644
--- a/apps/web/src/state/entities.ts
+++ b/apps/web/src/state/entities.ts
@@ -18,6 +18,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentProjects } from "./projects";
import { environmentServerConfigsAtom } from "./server";
import { environmentThreadDetails, environmentThreadShells } from "./threads";
+import { waitForAtomValue } from "./waitForAtomValue";
const EMPTY_PROJECT_REFS: ReadonlyArray = Object.freeze([]);
const EMPTY_THREAD_REFS: ReadonlyArray = Object.freeze([]);
@@ -198,6 +199,15 @@ export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell |
return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
}
+export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise {
+ return waitForAtomValue({
+ registry: appAtomRegistry,
+ atom: environmentThreadShells.threadShellAtom(ref),
+ predicate: (thread) => thread !== null,
+ timeoutMs,
+ });
+}
+
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
}
diff --git a/apps/web/src/state/waitForAtomValue.test.ts b/apps/web/src/state/waitForAtomValue.test.ts
new file mode 100644
index 0000000000..8b8f88a0a6
--- /dev/null
+++ b/apps/web/src/state/waitForAtomValue.test.ts
@@ -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();
+ });
+});
diff --git a/apps/web/src/state/waitForAtomValue.ts b/apps/web/src/state/waitForAtomValue.ts
new file mode 100644
index 0000000000..c472833365
--- /dev/null
+++ b/apps/web/src/state/waitForAtomValue.ts
@@ -0,0 +1,56 @@
+import type { Atom, AtomRegistry } from "effect/unstable/reactivity";
+
+export async function waitForAtomValue(input: {
+ readonly registry: AtomRegistry.AtomRegistry;
+ readonly atom: Atom.Atom;
+ readonly predicate: (value: A) => boolean;
+ readonly timeoutMs: number;
+}): Promise {
+ const read = () => input.registry.get(input.atom);
+ if (input.predicate(read())) {
+ return true;
+ }
+
+ return await new Promise((resolve) => {
+ let settled = false;
+ let timeoutId: ReturnType | 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);
+ });
+}
diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts
index 0fbbd79ec2..1d3a8da791 100644
--- a/apps/web/src/uiStateStore.test.ts
+++ b/apps/web/src/uiStateStore.test.ts
@@ -305,5 +305,6 @@ describe("uiStateStore persistence", () => {
localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",
) as PersistedUiState;
expect(resolveProjectExpanded(persisted.projectExpandedById ?? {}, ["unknown"])).toBe(true);
+ expect(persisted).not.toHaveProperty("threadPanelOpen");
});
});
diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts
index 80a68c21ad..f588f17347 100644
--- a/packages/client-runtime/src/state/shellReducer.test.ts
+++ b/packages/client-runtime/src/state/shellReducer.test.ts
@@ -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);
});
diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts
index 33ecd38039..bdbc120f3c 100644
--- a/packages/contracts/src/keybindings.test.ts
+++ b/packages/contracts/src/keybindings.test.ts
@@ -41,6 +41,12 @@ it.effect("parses keybinding rules", () =>
});
assert.strictEqual(parsedRightPanelToggle.command, "rightPanel.toggle");
+ const parsedThreadPanelToggle = yield* decode(KeybindingRule, {
+ key: "mod+shift+b",
+ command: "threadPanel.toggle",
+ });
+ assert.strictEqual(parsedThreadPanelToggle.command, "threadPanel.toggle");
+
const parsedClose = yield* decode(KeybindingRule, {
key: "mod+w",
command: "terminal.close",
diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts
index c7cff9943c..fcdc0820bd 100644
--- a/packages/contracts/src/keybindings.ts
+++ b/packages/contracts/src/keybindings.ts
@@ -47,7 +47,7 @@ export const MODEL_PICKER_KEYBINDING_COMMANDS = [
] as const;
export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number];
-const STATIC_KEYBINDING_COMMANDS = [
+export const BUILT_IN_KEYBINDING_COMMANDS = [
"sidebar.toggle",
"terminal.toggle",
"terminal.split",
@@ -55,6 +55,7 @@ const STATIC_KEYBINDING_COMMANDS = [
"terminal.new",
"terminal.close",
"rightPanel.toggle",
+ "threadPanel.toggle",
"diff.toggle",
"preview.toggle",
"preview.refresh",
@@ -80,7 +81,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;