Compare commits

...
Author SHA1 Message Date
Mohamed Boudra f694d0eab3 fix(app): return the previous pane to its last active tab when splitting or moving
Detaching a pane's active tab via splitPane or moveTabToPane previously dropped focusedTabId and fell back to the rightmost remaining tab in the strip, so dragging a file tab out after coming from tab A left the previous pane on tab B instead of putting A and the file side by side.

Track per-pane tab focus recency in memory and route both close and relocate focus transitions through one explicit policy table. Closing a tab keeps its existing parent-then-neighbor order, while splitting or moving a focused tab out of a pane returns the source pane to its most recently focused remaining tab (falling back to a same-pane parent tab and then an adjacent neighbor). Keeping the focus history in memory avoids adding a new key to the strict persisted layout schema.
2026-11-24 15:21:33 +01:00
6 changed files with 731 additions and 131 deletions
@@ -4,12 +4,15 @@
// never swallow entity tabs or lose the user's focus, and
// 2) splitting a tab out of a pane leaves a New tab behind, and the app must stay
// interactive in the [agent | New | explorer] state.
import { writeFileSync } from "node:fs";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { gotoWorkspace } from "../support/helpers/launcher";
import { seedCorruptedWorkspaceLayout } from "../support/helpers/workspace-layout";
import {
openChangesTreePanel,
openFilesPanel,
waitForWorkspaceTabsVisible,
} from "../support/helpers/workspace-tabs";
@@ -317,3 +320,75 @@ test("reloading a saved hidden generated Explorer recovers a usable workspace",
await gotoWorkspace(page, otherWorkspace.workspaceId);
await expect(draftTabChip(page)).toHaveCount(1);
});
test("dragging a file tab into a split returns the previous pane to the tab you came from", async ({
page,
withWorkspace,
e2eWorkerClient,
}) => {
const workspace = await withWorkspace({ prefix: "split-prev-tab-focus-" });
writeFileSync(path.join(workspace.repoPath, "notes.md"), "# Notes\nhello\n");
const agentA = await e2eWorkerClient.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Agent A",
});
const agentB = await e2eWorkerClient.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Agent B",
});
await gotoWorkspace(page, workspace.workspaceId);
await waitForWorkspaceTabsVisible(page);
const mainPane = page.getByTestId("workspace-pane-main");
await expect(mainPane.getByTestId(`workspace-tab-agent_${agentA.id}`)).toBeVisible({
timeout: 30_000,
});
await expect(mainPane.getByTestId(`workspace-tab-agent_${agentB.id}`)).toBeVisible({
timeout: 30_000,
});
const initialTabs = await mainPane
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-context-"])')
.evaluateAll((els) => els.map((el) => el.getAttribute("data-testid")));
const firstTab = mainPane.getByTestId(initialTabs[0]!);
const secondTab = mainPane.getByTestId(initialTabs[1]!);
// Open FILE while on B so B is the birth parent, then navigate A -> FILE before splitting.
await secondTab.click({ position: { x: 12, y: 13 } });
await expect(secondTab).toHaveAttribute("aria-selected", "true");
await openFilesPanel(page);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText("notes.md", { exact: true })
.click();
const fileTab = mainPane
.locator('[data-testid^="workspace-tab-file_"]:not([data-testid^="workspace-tab-context-"])')
.first();
await expect(fileTab).toBeVisible({ timeout: 15_000 });
await firstTab.click({ position: { x: 12, y: 13 } });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
await fileTab.click({ position: { x: 12, y: 13 } });
await expect(fileTab).toHaveAttribute("aria-selected", "true");
const mainBox = await mainPane.boundingBox();
if (!mainBox) throw new Error("mainPane has no bounding box");
await dragChipTo(page, fileTab, {
x: mainBox.x + mainBox.width * 0.92,
y: mainBox.y + mainBox.height * 0.5,
});
await expect(
page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true }),
).toHaveCount(2, { timeout: 10_000 });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
await expect(secondTab).toHaveAttribute("aria-selected", "false");
});
@@ -11,6 +11,10 @@ import {
workspaceTabTargetsEqual,
} from "@/workspace-tabs/identity";
import { createNewWorkspaceTab } from "@/workspace-tabs/new-tab";
import {
resolveTabDepartureSuccessor,
type PaneTabFocusHistory,
} from "@/stores/workspace-tab-focus-policy";
export interface SplitPane {
id: string;
@@ -75,6 +79,7 @@ interface InsertChildIntoGroupInput {
interface DetachTabFromTreeInput {
tabId: string;
preserveEmptyPaneId?: string | null;
replacementFocusedTabId?: string | null;
}
interface DetachTabFromTreeResult {
@@ -96,6 +101,7 @@ interface InsertSplitInternalInput {
tabId: string;
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
replacementFocusedTabId?: string | null;
}
interface InsertSplitInternalResult {
@@ -139,6 +145,7 @@ interface OpenTabInLayoutInput {
explorerSidebarPaneId: string | null;
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
reservedTabIds?: ReadonlySet<string>;
paneFocusHistory?: PaneTabFocusHistory;
}
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
@@ -207,6 +214,7 @@ interface SplitPaneInLayoutInput {
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
maxTreeDepth: number;
paneFocusHistory?: PaneTabFocusHistory;
}
interface SplitPaneInLayoutResult {
@@ -233,6 +241,7 @@ interface MoveTabToPaneInLayoutInput {
tabId: string;
toPaneId: string;
explorerSidebarPaneId?: string | null;
paneFocusHistory?: PaneTabFocusHistory;
}
interface FocusTabInLayoutInput {
@@ -815,6 +824,10 @@ function detachTabFromTree(
const nextPane = normalizePaneAfterTabChange({
...paneNode.pane,
tabs: paneNode.pane.tabs.filter((entry) => entry.tabId !== input.tabId),
focusedTabId:
paneNode.pane.focusedTabId === input.tabId
? (input.replacementFocusedTabId ?? paneNode.pane.focusedTabId)
: paneNode.pane.focusedTabId,
});
const nextRoot = replaceNodeAtPath(root, panePath, () => ({ kind: "pane", pane: nextPane }));
@@ -970,6 +983,7 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
const detached = detachTabFromTree(input.root, {
tabId: input.tabId,
preserveEmptyPaneId: input.targetPaneId,
replacementFocusedTabId: input.replacementFocusedTabId,
});
invariant(detached.tab, `Tab not found: ${input.tabId}`);
@@ -1165,6 +1179,14 @@ export function collectAllPanes(root: SplitNode): SplitPane[] {
return internalRoot.group.children.flatMap((child) => collectAllPanes(child));
}
export function collectAllPanesIncludingHidden(root: SplitNode): SplitPane[] {
const internalRoot = asInternalNode(root);
if (internalRoot.kind === "pane") {
return [internalRoot.pane];
}
return internalRoot.group.children.flatMap((child) => collectAllPanesIncludingHidden(child));
}
function isEphemeralTab(tab: WorkspaceTab): boolean {
return tab.target.kind === "commit_diff" || tab.target.kind === "new_tab";
}
@@ -1508,6 +1530,7 @@ export function openTabInLayoutFocused(input: OpenTabInLayoutInput): OpenTabInLa
layout: nextLayout,
tabId: existingTab.tabId,
placement: input.placement,
paneFocusHistory: input.paneFocusHistory,
}),
};
}
@@ -1534,6 +1557,7 @@ export function revealTargetInLayout(input: CreateTabInLayoutInput): OpenTabInLa
layout: updateExistingTabTarget(input.layout, existingTab, input.target),
tabId: existingTab.tabId,
placement: input.placement,
paneFocusHistory: input.paneFocusHistory,
}),
};
}
@@ -1551,6 +1575,7 @@ function revealExistingTab(input: {
layout: WorkspaceLayout;
tabId: string;
placement: WorkspaceTabPlacement;
paneFocusHistory?: PaneTabFocusHistory;
}): WorkspaceLayout {
if (input.placement.mode === "pane") {
const currentPane = findPaneContainingTab(asInternalNode(input.layout.root), input.tabId);
@@ -1559,6 +1584,7 @@ function revealExistingTab(input: {
layout: input.layout,
tabId: input.tabId,
toPaneId: input.placement.paneId,
paneFocusHistory: input.paneFocusHistory,
});
if (moved) {
return moved;
@@ -1600,9 +1626,9 @@ export function closeTabInLayout(input: CloseTabInLayoutInput): WorkspaceLayout
? pane.id
: null;
const closeSuccessorTabId = getCloseSuccessorTabId({
const closeSuccessorTabId = resolveTabDepartureSuccessor("close", {
pane,
tabId: input.tabId,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(internalLayout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
});
@@ -1986,16 +2012,26 @@ export function splitPaneInLayout(input: SplitPaneInLayoutInput): SplitPaneInLay
if (!findPaneById(layout.root, input.targetPaneId)) {
return null;
}
if (!findPaneContainingTab(layout.root, input.tabId)) {
const sourcePane = findPaneContainingTab(layout.root, input.tabId);
if (!sourcePane) {
return null;
}
const replacementFocusedTabId = resolveTabDepartureSuccessor("relocate", {
pane: sourcePane,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(layout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
paneFocusHistory: input.paneFocusHistory,
});
const result = insertSplitInternal({
root: layout.root,
targetPaneId: input.targetPaneId,
tabId: input.tabId,
position: input.position,
createNodeId: input.createNodeId,
replacementFocusedTabId,
});
if (getTreeDepth(result.root) > input.maxTreeDepth) {
return null;
@@ -2115,6 +2151,17 @@ export function moveTabToPaneInLayout(input: MoveTabToPaneInLayoutInput): Worksp
});
}
const replacementFocusedTabId =
sourcePane.id === input.toPaneId
? null
: resolveTabDepartureSuccessor("relocate", {
pane: sourcePane,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(layout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
paneFocusHistory: input.paneFocusHistory,
});
const detached = detachTabFromTree(layout.root, {
tabId: input.tabId,
// Crossing into or out of Explorer cannot remove either host shell.
@@ -2124,6 +2171,7 @@ export function moveTabToPaneInLayout(input: MoveTabToPaneInLayoutInput): Worksp
input.toPaneId === input.explorerSidebarPaneId
? sourcePane.id
: null,
replacementFocusedTabId,
});
if (!detached.tab) {
return null;
@@ -2280,29 +2328,6 @@ function withNormalizedParentTabMap(layout: WorkspaceLayout): WorkspaceLayout {
: { root: layout.root, focusedPaneId: layout.focusedPaneId };
}
function getCloseSuccessorTabId(input: {
pane: SplitPane;
tabId: string;
openTabIds: ReadonlySet<string>;
parentTabIdByTabId?: Record<string, string>;
}): string | null {
if (input.pane.focusedTabId !== input.tabId) {
return null;
}
const tabIndex = input.pane.tabIds.indexOf(input.tabId);
const parentTabId = input.parentTabIdByTabId?.[input.tabId] ?? null;
if (parentTabId && input.openTabIds.has(parentTabId)) {
return parentTabId;
}
return (
input.pane.tabIds[tabIndex + 1] ??
(tabIndex > 0 ? input.pane.tabIds[tabIndex - 1] : null) ??
null
);
}
function getFocusedPaneIdAfterTabClose(input: {
root: SplitNode;
focusedPaneId: string | null;
@@ -5496,3 +5496,245 @@ it("reentering a workspace restores its suspended pane without choosing another
expect(store.getState().layoutByWorkspace[workspaceKey]!.focusedPaneId).toBe(paneId);
expect(store.getState().focusRequest).toEqual({ workspaceKey, tabId });
});
describe("tab departure focus policy", () => {
it("splitPane returns the source pane to the most recently focused tab instead of the rightmost tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:split-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
// Open FILE while B is active (parentTabId = B) to prove focus recency wins over birth parent.
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
parentTabId: tabB,
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
const newPaneId = store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(newPaneId).toBeTruthy();
expect(layout.focusedPaneId).toBe(newPaneId);
expect(findPaneById(layout.root, newPaneId)?.focusedTabId).toBe(tabFile);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual([tabA, tabB]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
});
it("moveTabToPane returns the source pane to the most recently focused remaining tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:move-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
const sidePaneId = store.getState().splitPaneEmpty(workspaceKey, {
targetPaneId: "main",
position: "right",
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
store.getState().moveTabToPane(workspaceKey, tabFile, sidePaneId);
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(layout.focusedPaneId).toBe(sidePaneId);
expect(findPaneById(layout.root, sidePaneId)?.focusedTabId).toBe(tabFile);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual([tabA, tabB]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
});
it("explicit pane-local reveal returns the source pane to its most recently focused tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:pane-reveal-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
});
const fileTarget = { kind: "file", path: "/repo/notes.md" } as const;
const tabFile = store.getState().openTab({
workspaceKey,
target: fileTarget,
intent: "reveal",
})!;
const sidePaneId = store.getState().ensureSidePane(workspaceKey, { focus: false })!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
store.getState().openTab({
workspaceKey,
target: fileTarget,
intent: "reveal",
placement: { mode: "pane", paneId: sidePaneId },
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
expect(findPaneById(layout.root, sidePaneId)?.focusedTabId).toBe(tabFile);
});
it("seeds focus recency from a hydrated layout on the first tab switch", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:hydrated-recency";
store.setState((state) => ({
...state,
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: {
root: createPane({
id: "main",
tabIds: ["agent_a", "agent_b", "file_/repo/notes.md"],
focusedTabId: "agent_a",
}),
focusedPaneId: "main",
},
},
}));
store.getState().focusTab(workspaceKey, "file_/repo/notes.md");
store.getState().splitPane(workspaceKey, {
tabId: "file_/repo/notes.md",
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("agent_a");
});
it("falls back to a same-pane parent tab when relocating immediately after hydration", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:hydrated-parent-fallback";
store.setState((state) => ({
...state,
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: {
root: createPane({
id: "main",
tabIds: ["agent_a", "agent_b", "file_/repo/notes.md"],
focusedTabId: "file_/repo/notes.md",
}),
focusedPaneId: "main",
parentTabIdByTabId: { "file_/repo/notes.md": "agent_a" },
},
},
}));
store.getState().splitPane(workspaceKey, {
tabId: "file_/repo/notes.md",
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("agent_a");
});
it("tracks multi-step recency and preserves history across convertDraftToAgent", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:multi-step-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "draft", draftId: "draft-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
store.getState().focusTab(workspaceKey, tabB);
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
const convertedA = store.getState().convertDraftToAgent(workspaceKey, tabA, "agent-a")!;
store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(convertedA);
store.getState().focusTab(workspaceKey, convertedA);
store.getState().splitPane(workspaceKey, {
tabId: convertedA,
targetPaneId: "main",
position: "bottom",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(tabB);
});
it("keeps the source pane focused tab unchanged when dragging an unfocused tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:unfocused-drag";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
});
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(tabA);
});
});
+103 -105
View File
@@ -18,6 +18,7 @@ import {
closePaneInLayout,
closeTabInLayout,
collectAllPanes,
collectAllPanesIncludingHidden,
collectAllTabs,
convertDraftToAgentInLayout,
createTabInLayout,
@@ -69,6 +70,10 @@ import { isSheetTabModified, resolveCompactSheetPolicy } from "@/workspace-tabs/
import { panelResourceKey, type CompactSheetPolicy } from "@/panels/panel-manifest";
import { createValidatedPersistStorage } from "@/storage/validated-persist-storage";
import { panelTargetSupportsHostForWorkspaceKey } from "@/plugins/workspace-panels/locations";
import {
syncPaneTabFocusHistory,
type PaneTabFocusHistory,
} from "@/stores/workspace-tab-focus-policy";
export {
AMBIENT_PLACEMENT,
@@ -153,6 +158,7 @@ interface WorkspaceLayoutStore {
pinnedAgentIdsByWorkspace: Record<string, Set<string>>;
hiddenAgentIdsByWorkspace: Record<string, Set<string>>;
focusRestorationByWorkspace: Record<string, WorkspaceFocusRestorationState>;
paneTabFocusHistoryByWorkspace: Record<string, PaneTabFocusHistory>;
explorerSidebarPaneIdByWorkspace: Record<string, string | null>;
sidePaneIdByWorkspace: Record<string, string | null>;
/** Workspaces where PR detection already added its tab once; a closed tab never returns. */
@@ -689,6 +695,35 @@ function withoutFocusRestoration(
return { focusRestorationByWorkspace };
}
function withUpdatedWorkspaceLayout(
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "paneTabFocusHistoryByWorkspace">,
workspaceKey: string,
nextLayout: WorkspaceLayout,
renamedTab?: { from: string; to: string } | null,
): Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "paneTabFocusHistoryByWorkspace"> {
const previousLayout = state.layoutByWorkspace[workspaceKey] ?? null;
const previousHistory = state.paneTabFocusHistoryByWorkspace[workspaceKey];
const nextHistory = syncPaneTabFocusHistory({
previousHistory,
previousPanes: previousLayout ? collectAllPanesIncludingHidden(previousLayout.root) : [],
nextPanes: collectAllPanesIncludingHidden(nextLayout.root),
renamedTab,
});
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: nextLayout,
},
paneTabFocusHistoryByWorkspace:
nextHistory === previousHistory
? state.paneTabFocusHistoryByWorkspace
: {
...state.paneTabFocusHistoryByWorkspace,
[workspaceKey]: nextHistory,
},
};
}
function reconcileRememberedSidePane(
state: WorkspaceLayoutStore,
workspaceKey: string,
@@ -873,6 +908,7 @@ function promoteSheetToTab(
now: tab.createdAt,
createTabId: () => tab.tabId,
state: tab.state,
paneFocusHistory: state.paneTabFocusHistoryByWorkspace[workspaceKey],
};
const result = isTargetOpenAsTab(placement.layout, tab.target)
? revealTargetInLayout(input)
@@ -900,7 +936,7 @@ function promoteSheetToTab(
tab.target.agentId,
)
: state.hiddenAgentIdsByWorkspace,
layoutByWorkspace: { ...state.layoutByWorkspace, [workspaceKey]: nextLayout },
...withUpdatedWorkspaceLayout(state, workspaceKey, nextLayout),
},
};
}
@@ -1109,6 +1145,7 @@ export function createWorkspaceLayoutStore(
pinnedAgentIdsByWorkspace: {},
hiddenAgentIdsByWorkspace: {},
focusRestorationByWorkspace: {},
paneTabFocusHistoryByWorkspace: {},
explorerSidebarPaneIdByWorkspace: {},
sidePaneIdByWorkspace: {},
pullRequestTabAutoOpenedByWorkspace: {},
@@ -1199,6 +1236,7 @@ export function createWorkspaceLayoutStore(
target: normalizedTarget,
now: Date.now(),
createTabId: createWorkspaceTabInstanceId,
paneFocusHistory: get().paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
}
if (!result) {
@@ -1220,6 +1258,13 @@ export function createWorkspaceLayoutStore(
placement.layout.focusedPaneId,
);
const shouldPinAgent = input.pin === true && normalizedTarget.kind === "agent";
const finalLayout = parentTabId
? attachParentTab({
layout: nextLayout,
childTabId: result.tabId,
parentTabId,
})
: nextLayout;
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...advancePanelRevision(state, normalizedWorkspaceKey, result.tabId, normalizedTarget),
@@ -1243,16 +1288,7 @@ export function createWorkspaceLayoutStore(
normalizedTarget.agentId,
)
: state.pinnedAgentIdsByWorkspace,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: parentTabId
? attachParentTab({
layout: nextLayout,
childTabId: result.tabId,
parentTabId,
})
: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, finalLayout),
}));
return result.tabId;
},
@@ -1304,14 +1340,15 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
);
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: keepWorkspaceFocusOutOfExplorerSidebar(
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
keepWorkspaceFocusOutOfExplorerSidebar(
currentLayout,
paneId,
currentLayout.focusedPaneId,
),
},
),
explorerSidebarPaneIdByWorkspace: {
...state.explorerSidebarPaneIdByWorkspace,
[normalizedWorkspaceKey]: paneId,
@@ -1326,9 +1363,7 @@ export function createWorkspaceLayoutStore(
set((state) => {
const layout = state.layoutByWorkspace[workspaceKey];
const next = setPaneHiddenInLayout({ layout, paneId, hidden: false });
return next
? { layoutByWorkspace: { ...state.layoutByWorkspace, [workspaceKey]: next } }
: state;
return next ? withUpdatedWorkspaceLayout(state, workspaceKey, next) : state;
});
return paneId;
},
@@ -1351,12 +1386,7 @@ export function createWorkspaceLayoutStore(
return state;
}
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout);
});
},
ensureSidePane: (workspaceKey, options) => {
@@ -1388,13 +1418,13 @@ export function createWorkspaceLayoutStore(
}
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]:
options?.focus === false
? { ...result.layout, focusedPaneId: layout.focusedPaneId }
: result.layout,
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
options?.focus === false
? { ...result.layout, focusedPaneId: layout.focusedPaneId }
: result.layout,
),
sidePaneIdByWorkspace: {
...state.sidePaneIdByWorkspace,
[normalizedWorkspaceKey]: result.paneId,
@@ -1441,10 +1471,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...reconcileRememberedSidePane(state, normalizedWorkspaceKey, nextLayout),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
}
const closedLayout = closeTabInLayout({
@@ -1476,10 +1503,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...reconcileRememberedSidePane(state, normalizedWorkspaceKey, nextLayout),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -1541,9 +1565,9 @@ export function createWorkspaceLayoutStore(
...withoutFocusRestoration(state, normalizedWorkspaceKey),
// Choosing a tab dismisses the sheets that cover it.
...dismissSheets(state, normalizedWorkspaceKey),
layoutByWorkspace: nextLayout
? { ...state.layoutByWorkspace, [normalizedWorkspaceKey]: nextLayout }
: state.layoutByWorkspace,
...(nextLayout
? withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout)
: {}),
};
});
},
@@ -1567,10 +1591,11 @@ export function createWorkspaceLayoutStore(
focusRequest: { workspaceKey: normalizedWorkspaceKey, tabId: normalizedTabId },
// Choosing a tab dismisses the sheets that cover it.
...dismissSheets(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout ?? layout,
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
nextLayout ?? layout,
),
}
: state;
});
@@ -1622,6 +1647,8 @@ export function createWorkspaceLayoutStore(
state: tabState,
});
if (!result) return null;
const renamedTab =
result.tabId !== normalizedTabId ? { from: normalizedTabId, to: result.tabId } : null;
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...advancePanelRevision(state, normalizedWorkspaceKey, result.tabId, normalizedTarget),
@@ -1633,10 +1660,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
normalizedTarget.agentId,
),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout, renamedTab),
}));
return result.tabId;
},
@@ -1660,12 +1684,7 @@ export function createWorkspaceLayoutStore(
state: tabState,
});
if (!layout) return state;
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: layout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, layout);
});
},
convertDraftToAgent: (workspaceKey, tabId, agentId) => {
@@ -1690,6 +1709,8 @@ export function createWorkspaceLayoutStore(
return null;
}
const renamedTab =
result.tabId !== normalizedTabId ? { from: normalizedTabId, to: result.tabId } : null;
set((state) => ({
...(result.layout.focusedPaneId !== null
? (withoutFocusRestoration(state, normalizedWorkspaceKey) ?? {})
@@ -1699,10 +1720,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
normalizedAgentId,
),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout, renamedTab),
}));
return result.tabId;
@@ -1766,10 +1784,7 @@ export function createWorkspaceLayoutStore(
return {
...(sheetAgentGone ? withSheets(state, normalizedWorkspaceKey, fittingSheets) : {}),
pinnedAgentIdsByWorkspace,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -1788,12 +1803,7 @@ export function createWorkspaceLayoutStore(
return state;
}
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout);
});
},
getWorkspaceTabs: (workspaceKey) => {
@@ -1842,6 +1852,7 @@ export function createWorkspaceLayoutStore(
position: input.position,
maxTreeDepth: MAX_TREE_DEPTH,
createNodeId: ids.createNodeId,
paneFocusHistory: get().paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
if (!result) {
return null;
@@ -1849,10 +1860,7 @@ export function createWorkspaceLayoutStore(
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
}));
return result.paneId;
@@ -1886,10 +1894,7 @@ export function createWorkspaceLayoutStore(
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
}));
return result.paneId;
@@ -1928,6 +1933,7 @@ export function createWorkspaceLayoutStore(
tabId: normalizedTabId,
toPaneId: normalizedToPaneId,
explorerSidebarPaneId,
paneFocusHistory: state.paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
if (!nextLayout) {
return state;
@@ -1945,10 +1951,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: normalizedNextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, normalizedNextLayout),
sidePaneIdByWorkspace:
rememberedSidePaneId &&
!findPaneById(normalizedNextLayout.root, rememberedSidePaneId)
@@ -1986,10 +1989,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
sidePaneIdByWorkspace:
state.sidePaneIdByWorkspace[normalizedWorkspaceKey] === normalizedPaneId
? {
@@ -2035,9 +2035,9 @@ export function createWorkspaceLayoutStore(
? { workspaceKey: normalizedWorkspaceKey, tabId: pane.focusedTabId }
: null,
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: nextLayout
? { ...state.layoutByWorkspace, [normalizedWorkspaceKey]: nextLayout }
: state.layoutByWorkspace,
...(nextLayout
? withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout)
: {}),
};
});
},
@@ -2061,11 +2061,11 @@ export function createWorkspaceLayoutStore(
tokens: [...(currentRestoration?.tokens ?? []), token],
},
},
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]:
layout.focusedPaneId === null ? layout : { ...layout, focusedPaneId: null },
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
layout.focusedPaneId === null ? layout : { ...layout, focusedPaneId: null },
),
};
});
return token;
@@ -2116,13 +2116,10 @@ export function createWorkspaceLayoutStore(
return {
focusRestorationByWorkspace: remainingRestorations,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: {
...layout,
focusedPaneId: restorePaneId,
},
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, {
...layout,
focusedPaneId: restorePaneId,
}),
};
});
},
@@ -2175,10 +2172,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -2276,6 +2270,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey in state.pinnedAgentIdsByWorkspace ||
normalizedWorkspaceKey in state.hiddenAgentIdsByWorkspace ||
normalizedWorkspaceKey in state.focusRestorationByWorkspace ||
normalizedWorkspaceKey in state.paneTabFocusHistoryByWorkspace ||
normalizedWorkspaceKey in state.explorerSidebarPaneIdByWorkspace ||
normalizedWorkspaceKey in state.sidePaneIdByWorkspace ||
normalizedWorkspaceKey in state.pullRequestTabAutoOpenedByWorkspace ||
@@ -2303,6 +2298,8 @@ export function createWorkspaceLayoutStore(
state.hiddenAgentIdsByWorkspace;
const { [normalizedWorkspaceKey]: _restoration, ...focusRestorationByWorkspace } =
state.focusRestorationByWorkspace;
const { [normalizedWorkspaceKey]: _focusHistory, ...paneTabFocusHistoryByWorkspace } =
state.paneTabFocusHistoryByWorkspace;
const {
[normalizedWorkspaceKey]: _explorerSidebarPane,
...explorerSidebarPaneIdByWorkspace
@@ -2319,6 +2316,7 @@ export function createWorkspaceLayoutStore(
pinnedAgentIdsByWorkspace,
hiddenAgentIdsByWorkspace,
focusRestorationByWorkspace,
paneTabFocusHistoryByWorkspace,
explorerSidebarPaneIdByWorkspace,
sidePaneIdByWorkspace,
};
@@ -0,0 +1,115 @@
import { describe, expect, it } from "vitest";
import {
resolveTabDepartureSuccessor,
syncPaneTabFocusHistory,
} from "./workspace-tab-focus-policy";
describe("workspace tab departure focus policy", () => {
it("relocate prefers most recently focused remaining tab over parent and neighbor", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
parentTabIdByTabId: { file: "b" },
paneFocusHistory: { main: ["file", "a", "b"] },
});
expect(successor).toBe("a");
});
it("relocate falls back to same-pane parent when focus history has no remaining tab", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
parentTabIdByTabId: { file: "a" },
});
expect(successor).toBe("a");
});
it("relocate ignores a parent tab in another pane and falls back to source-pane neighbor", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["other-pane-parent", "a", "b", "file"]),
parentTabIdByTabId: { file: "other-pane-parent" },
});
expect(successor).toBe("b");
});
it("close prefers open parent tab anywhere, then right neighbor, then left neighbor", () => {
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "file", "b"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["other-parent", "a", "file", "b"]),
parentTabIdByTabId: { file: "other-parent" },
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("other-parent");
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "file", "b"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "file", "b"]),
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("b");
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("b");
});
it("returns null when the departing tab is not focused", () => {
expect(
resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "a" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
}),
).toBeNull();
});
it("syncPaneTabFocusHistory seeds from prior focused tab, renames tabs, prunes closed tabs, and preserves identity when unchanged", () => {
const initial = syncPaneTabFocusHistory({
previousHistory: undefined,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "a" }],
nextPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
});
expect(initial).toEqual({ main: ["file", "a"] });
const unchanged = syncPaneTabFocusHistory({
previousHistory: initial,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
nextPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
});
expect(unchanged).toBe(initial);
const renamed = syncPaneTabFocusHistory({
previousHistory: initial,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
nextPanes: [{ id: "main", tabIds: ["agent-a", "b", "file"], focusedTabId: "file" }],
renamedTab: { from: "a", to: "agent-a" },
});
expect(renamed).toEqual({ main: ["file", "agent-a"] });
const pruned = syncPaneTabFocusHistory({
previousHistory: renamed,
previousPanes: [{ id: "main", tabIds: ["agent-a", "b", "file"], focusedTabId: "file" }],
nextPanes: [
{ id: "main", tabIds: ["agent-a", "b"], focusedTabId: "agent-a" },
{ id: "split", tabIds: ["file"], focusedTabId: "file" },
],
});
expect(pruned).toEqual({ main: ["agent-a"], split: ["file"] });
});
});
@@ -0,0 +1,145 @@
/**
* Per-pane tab focus recency, ordered most-recently-focused first.
* Kept in memory rather than persisted so strict layout storage stays unchanged.
*/
export type PaneTabFocusHistory = Record<string, readonly string[]>;
/**
* Why a pane is losing its currently focused tab:
* - "close": browser-style close returns to the tab's parent (if still open anywhere),
* otherwise steps to the adjacent neighbor (right, then left).
* - "relocate": split or move keeps the user's working context visible in the source pane
* by returning to the most recently focused remaining tab in that pane, then a same-pane
* parent tab (for example immediately after reload), then the adjacent neighbor.
*/
export type TabDepartureReason = "close" | "relocate";
export interface PaneFocusSnapshot {
id: string;
tabIds: readonly string[];
focusedTabId: string | null;
}
export interface TabDepartureContext {
pane: PaneFocusSnapshot;
departingTabId: string;
openTabIds: ReadonlySet<string>;
parentTabIdByTabId?: Record<string, string>;
paneFocusHistory?: PaneTabFocusHistory;
}
type TabSuccessorRule = (context: TabDepartureContext) => string | null;
function isRemainingInSourcePane(context: TabDepartureContext, tabId: string | null): boolean {
return Boolean(tabId && tabId !== context.departingTabId && context.pane.tabIds.includes(tabId));
}
const mostRecentlyFocusedInSourcePane: TabSuccessorRule = (context) => {
const recent = context.paneFocusHistory?.[context.pane.id];
return recent?.find((tabId) => isRemainingInSourcePane(context, tabId)) ?? null;
};
const openParentTabAnywhere: TabSuccessorRule = (context) => {
const parentTabId = context.parentTabIdByTabId?.[context.departingTabId] ?? null;
return parentTabId &&
parentTabId !== context.departingTabId &&
context.openTabIds.has(parentTabId)
? parentTabId
: null;
};
const parentTabInSourcePane: TabSuccessorRule = (context) => {
const parentTabId = context.parentTabIdByTabId?.[context.departingTabId] ?? null;
return isRemainingInSourcePane(context, parentTabId) ? parentTabId : null;
};
const adjacentNeighborInSourcePane: TabSuccessorRule = (context) => {
const tabIndex = context.pane.tabIds.indexOf(context.departingTabId);
if (tabIndex < 0) {
return null;
}
return (
context.pane.tabIds[tabIndex + 1] ??
(tabIndex > 0 ? context.pane.tabIds[tabIndex - 1] : null) ??
null
);
};
export const TAB_DEPARTURE_POLICIES: Record<TabDepartureReason, readonly TabSuccessorRule[]> = {
close: [openParentTabAnywhere, adjacentNeighborInSourcePane],
relocate: [mostRecentlyFocusedInSourcePane, parentTabInSourcePane, adjacentNeighborInSourcePane],
};
export function resolveTabDepartureSuccessor(
reason: TabDepartureReason,
context: TabDepartureContext,
): string | null {
if (context.pane.focusedTabId !== context.departingTabId) {
return null;
}
for (const rule of TAB_DEPARTURE_POLICIES[reason]) {
const candidate = rule(context);
if (candidate) {
return candidate;
}
}
return null;
}
function mapRenamedTabId(
tabId: string | null | undefined,
renamedTab: { from: string; to: string } | null | undefined,
): string | null {
if (!tabId) {
return null;
}
return renamedTab && tabId === renamedTab.from ? renamedTab.to : tabId;
}
export function syncPaneTabFocusHistory(input: {
previousHistory: PaneTabFocusHistory | undefined;
previousPanes: readonly PaneFocusSnapshot[];
nextPanes: readonly PaneFocusSnapshot[];
renamedTab?: { from: string; to: string } | null;
}): PaneTabFocusHistory {
const previous = input.previousHistory ?? {};
const previousFocusedByPaneId = new Map(
input.previousPanes.map((pane) => [pane.id, pane.focusedTabId]),
);
const next: Record<string, readonly string[]> = {};
let changed = Object.keys(previous).length !== input.nextPanes.length;
for (const pane of input.nextPanes) {
const openInPane = new Set(pane.tabIds);
const priorEntries = previous[pane.id] ?? [];
const updated: string[] = [];
const seen = new Set<string>();
const pushIfOpen = (tabId: string | null | undefined) => {
if (!tabId || seen.has(tabId) || !openInPane.has(tabId)) {
return;
}
seen.add(tabId);
updated.push(tabId);
};
pushIfOpen(pane.focusedTabId);
// Seed from the pane's prior focused tab so the first switch after hydration remembers it.
pushIfOpen(mapRenamedTabId(previousFocusedByPaneId.get(pane.id), input.renamedTab));
for (const entry of priorEntries) {
pushIfOpen(mapRenamedTabId(entry, input.renamedTab));
}
if (
!changed &&
(priorEntries.length !== updated.length ||
priorEntries.some((entry, index) => entry !== updated[index]))
) {
changed = true;
}
next[pane.id] = updated;
}
return changed ? next : previous;
}