Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex b96a27717d fix(vcs): extend worktree cleanup deadline (#3593)
Allow filesystem-bound worktree removal enough time for large dependency trees while retaining a bounded five-minute deadline.

Co-authored-by: codex <[email protected]>
2026-07-20 18:49:55 +02:00
26 changed files with 165 additions and 1352 deletions

No files matched your search

@@ -78,7 +78,6 @@ function makePoolLayer(
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
dispatchMenuActionToMainWindow: () => Effect.die("unexpected menu action"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
+7 -45
View File
@@ -7,22 +7,17 @@ import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const {
buildFromTemplateMock,
createFromNamedImageMock,
sendActionToFirstResponderMock,
setApplicationMenuMock,
} = vi.hoisted(() => ({
buildFromTemplateMock: vi.fn(),
createFromNamedImageMock: vi.fn(),
sendActionToFirstResponderMock: vi.fn(),
setApplicationMenuMock: vi.fn(),
}));
const { buildFromTemplateMock, createFromNamedImageMock, setApplicationMenuMock } = vi.hoisted(
() => ({
buildFromTemplateMock: vi.fn(),
createFromNamedImageMock: vi.fn(),
setApplicationMenuMock: vi.fn(),
}),
);
vi.mock("electron", () => ({
Menu: {
buildFromTemplate: buildFromTemplateMock,
sendActionToFirstResponder: sendActionToFirstResponderMock,
setApplicationMenu: setApplicationMenuMock,
},
nativeImage: {
@@ -46,7 +41,6 @@ describe("ElectronMenu", () => {
beforeEach(() => {
buildFromTemplateMock.mockReset();
createFromNamedImageMock.mockReset();
sendActionToFirstResponderMock.mockReset();
setApplicationMenuMock.mockReset();
});
@@ -166,38 +160,6 @@ describe("ElectronMenu", () => {
}).pipe(Effect.provide(TestLayer)),
);
it.effect("sends native actions to the first responder", () =>
Effect.gen(function* () {
const electronMenu = yield* ElectronMenu.ElectronMenu;
yield* electronMenu.sendActionToFirstResponder("performClose:");
assert.deepEqual(sendActionToFirstResponderMock.mock.calls, [["performClose:"]]);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves first-responder failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("native action failed");
sendActionToFirstResponderMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(electronMenu.sendActionToFirstResponder("performClose:"));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "send-action-to-first-responder");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.equal(error.itemCount, 0);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves popup-template failures with window context", () =>
Effect.gen(function* () {
const cause = new Error("popup failed");
-14
View File
@@ -26,7 +26,6 @@ export interface ElectronMenuTemplateInput {
const ElectronMenuOperation = Schema.Literals([
"set-application-menu",
"send-action-to-first-responder",
"popup-template",
"show-context-menu",
]);
@@ -53,7 +52,6 @@ export class ElectronMenu extends Context.Service<
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly sendActionToFirstResponder: (action: string) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
@@ -187,18 +185,6 @@ export const make = Effect.gen(function* () {
cause,
}),
}).pipe(Effect.orDie),
sendActionToFirstResponder: (action) =>
Effect.try({
try: () => Electron.Menu.sendActionToFirstResponder(action),
catch: (cause) =>
new ElectronMenuOperationError({
operation: "send-action-to-first-responder",
platform,
windowId: null,
itemCount: 0,
cause,
}),
}).pipe(Effect.orDie),
popupTemplate: (input) =>
input.template.length === 0
? Effect.void
@@ -66,10 +66,7 @@ const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
install: Effect.die("unexpected install"),
} satisfies DesktopUpdates.DesktopUpdates["Service"]);
const makeDesktopWindowLayer = (
selectedAction: Deferred.Deferred<string>,
mainWindowActionsHandled: boolean,
) =>
const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected createMain"),
ensureMain: Effect.die("unexpected ensureMain"),
@@ -81,55 +78,19 @@ const makeDesktopWindowLayer = (
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
dispatchMenuActionToMainWindow: (_window, action) =>
mainWindowActionsHandled
? Deferred.succeed(selectedAction, action).pipe(Effect.as(true))
: Effect.succeed(false),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
const makeElectronMenuLayer = (
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
nativeActions: string[] = [],
) =>
Layer.succeed(ElectronMenu.ElectronMenu, {
setApplicationMenu: (template) =>
Deferred.succeed(applicationMenuTemplate, template).pipe(Effect.asVoid),
sendActionToFirstResponder: (action) =>
Effect.sync(() => {
nativeActions.push(action);
}),
popupTemplate: () => Effect.void,
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
const configureMenu = (
platform: "darwin" | "linux",
selectedAction: Deferred.Deferred<string>,
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
nativeActions: string[] = [],
mainWindowActionsHandled = true,
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate, nativeActions)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction, mainWindowActionsHandled)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer({ ...environmentInput, platform }).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
Effect.gen(function* () {
@@ -137,7 +98,25 @@ describe("DesktopApplicationMenu", () => {
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu("linux", selectedAction, applicationMenuTemplate);
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
@@ -156,86 +135,4 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
it.effect("routes the macOS close shortcut through the renderer", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu("darwin", selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
assert.isDefined(fileMenu);
if (!Array.isArray(fileMenu.submenu)) {
throw new Error("Expected File menu submenu to be an array.");
}
const closeItem = fileMenu.submenu.find((item) => item.label === "Close Window");
assert.isDefined(closeItem);
assert.equal(closeItem.accelerator, "Cmd+W");
const closeClick = closeItem.click;
if (typeof closeClick !== "function") {
throw new Error("Expected Close Window menu item to have a click handler.");
}
closeClick({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.equal(yield* Deferred.await(selectedAction), "close-window-or-right-panel");
}),
);
it.effect("preserves native close behavior when system UI owns focus", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
const nativeActions: string[] = [];
yield* configureMenu("darwin", selectedAction, applicationMenuTemplate, nativeActions);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
assert.isDefined(fileMenu);
if (!Array.isArray(fileMenu.submenu)) {
throw new Error("Expected File menu submenu to be an array.");
}
const closeItem = fileMenu.submenu.find((item) => item.label === "Close Window");
assert.isDefined(closeItem);
const closeClick = closeItem.click;
if (typeof closeClick !== "function") {
throw new Error("Expected Close Window menu item to have a click handler.");
}
closeClick({} as Electron.MenuItem, undefined, {} as KeyboardEvent);
assert.deepEqual(nativeActions, ["performClose:"]);
}),
);
it.effect("preserves native close behavior for a non-main browser window", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
const nativeActions: string[] = [];
yield* configureMenu("darwin", selectedAction, applicationMenuTemplate, nativeActions, false);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
assert.isDefined(fileMenu);
if (!Array.isArray(fileMenu.submenu)) {
throw new Error("Expected File menu submenu to be an array.");
}
const closeItem = fileMenu.submenu.find((item) => item.label === "Close Window");
assert.isDefined(closeItem);
const closeClick = closeItem.click;
if (typeof closeClick !== "function") {
throw new Error("Expected Close Window menu item to have a click handler.");
}
closeClick({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
yield* Effect.yieldNow;
assert.deepEqual(nativeActions, ["performClose:"]);
}),
);
});
@@ -127,31 +127,6 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
const closeWindowClick: NonNullable<Electron.MenuItemConstructorOptions["click"]> = (
_menuItem,
browserWindow,
) => {
if (!browserWindow) {
runMenuEffect(
"close-focused-native-window",
electronMenu.sendActionToFirstResponder("performClose:"),
);
return;
}
runMenuEffect(
"close-window-or-right-panel",
Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const handled = yield* desktopWindow.dispatchMenuActionToMainWindow(
browserWindow,
"close-window-or-right-panel",
);
if (!handled) {
yield* electronMenu.sendActionToFirstResponder("performClose:");
}
}),
);
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -195,15 +170,7 @@ export const make = Effect.gen(function* () {
},
{ type: "separator" as const },
]),
...(environment.platform === "darwin"
? [
{
label: "Close Window",
accelerator: "Cmd+W",
click: closeWindowClick,
},
]
: [{ role: "quit" as const }]),
{ role: environment.platform === "darwin" ? "close" : "quit" },
],
},
{ role: "editMenu" },
@@ -148,7 +148,6 @@ const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopSe
const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
setApplicationMenu: () => Effect.void,
sendActionToFirstResponder: () => Effect.void,
popupTemplate: () => Effect.void,
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
@@ -1097,27 +1096,4 @@ describe("DesktopWindow", () => {
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect("dispatches targeted menu actions only to the registered main window", () =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const main = makeFakeBrowserWindow();
const scenario = yield* makeSplashScenario([splash.window]);
yield* Ref.set(scenario.mainWindow, Option.some(main.window));
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
assert.isTrue(
yield* desktopWindow.dispatchMenuActionToMainWindow(main.window, "close-window"),
);
assert.isFalse(
yield* desktopWindow.dispatchMenuActionToMainWindow(splash.window, "close-window"),
);
assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "close-window"]]);
assert.equal(splash.send.mock.calls.length, 0);
assert.deepEqual(yield* Ref.get(scenario.revealedWindows), []);
}).pipe(Effect.provide(scenario.layer));
}),
);
});
+13 -31
View File
@@ -80,10 +80,6 @@ export class DesktopWindow extends Context.Service<
readonly handleBackendNotReady: Effect.Effect<void>;
readonly flushMainWindowBounds: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly dispatchMenuActionToMainWindow: (
window: Electron.BaseWindow,
action: string,
) => Effect.Effect<boolean, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
>()("@t3tools/desktop/window/DesktopWindow") {}
@@ -290,24 +286,6 @@ export const make = Effect.gen(function* () {
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const sendMenuAction = Effect.fn("desktop.window.sendMenuAction")(
(targetWindow: Electron.BrowserWindow, action: string, reveal: boolean) =>
Effect.sync(() => {
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
if (reveal) void runPromise(electronWindow.reveal(targetWindow));
};
if (targetWindow.webContents.isLoadingMainFrame()) {
targetWindow.webContents.once("did-finish-load", send);
return;
}
send();
}),
);
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
Electron.BrowserWindow,
DesktopWindowError
@@ -794,16 +772,20 @@ export const make = Effect.gen(function* () {
return;
}
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
yield* sendMenuAction(targetWindow, action, true);
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
void runPromise(electronWindow.reveal(targetWindow));
};
if (targetWindow.webContents.isLoadingMainFrame()) {
targetWindow.webContents.once("did-finish-load", send);
return;
}
send();
}),
dispatchMenuActionToMainWindow: Effect.fn("desktop.window.dispatchMenuActionToMainWindow")(
function* (window, action) {
const mainWindow = yield* electronWindow.main;
if (Option.isNone(mainWindow) || mainWindow.value !== window) return false;
yield* sendMenuAction(mainWindow.value, action, false);
return true;
},
),
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
yield* electronWindow.syncAllAppearance((window) =>
+103 -1
View File
@@ -1,5 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, describe } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -8,11 +9,16 @@ import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import { splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
import {
makeGitVcsDriverCore,
splitNullSeparatedGitStdoutPaths,
WORKTREE_REMOVE_TIMEOUT_MS,
} from "./GitVcsDriverCore.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
@@ -38,6 +44,55 @@ const makeNonRepositoryHandle = () =>
getOutputFd: () => Stream.empty,
});
const makeWorktreeRemovalLayer = (input: {
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly commands: Array<ReadonlyArray<string>>;
readonly timeoutMs?: number;
}) => {
const spawner = ChildProcessSpawner.make((command) =>
Effect.sync(() => {
if (!ChildProcess.isStandardCommand(command)) {
return assert.fail("expected a standard Git command");
}
input.commands.push(command.args);
let running = true;
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: input.exitCode.pipe(
Effect.tap(() =>
Effect.sync(() => {
running = false;
}),
),
),
isRunning: Effect.sync(() => running),
kill: () =>
Effect.sync(() => {
running = false;
}),
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}),
);
const nodeServicesLayer = Layer.merge(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return Layer.effect(
GitVcsDriver.GitVcsDriver,
makeGitVcsDriverCore(
input.timeoutMs === undefined ? {} : { worktreeRemoveTimeoutMs: input.timeoutMs },
),
).pipe(Layer.provide(ServerConfigLayer), Layer.provideMerge(nodeServicesLayer));
};
const makeTmpDir = (
prefix = "git-vcs-driver-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
@@ -641,6 +696,53 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
});
describe("worktree operations", () => {
it.effect("uses the extended deadline while allowing a slow worktree removal", () => {
const commands: Array<ReadonlyArray<string>> = [];
const layer = makeWorktreeRemovalLayer({
commands,
exitCode: Effect.sleep(Duration.millis(50)).pipe(
Effect.as(ChildProcessSpawner.ExitCode(0)),
),
timeoutMs: 100,
});
return TestClock.withLive(
Effect.gen(function* () {
assert.equal(WORKTREE_REMOVE_TIMEOUT_MS, 300_000);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* driver.removeWorktree({ cwd: "/repo", path: "/repo-worktrees/feature" });
assert.deepStrictEqual(commands, [["worktree", "remove", "/repo-worktrees/feature"]]);
}).pipe(Effect.provide(layer)),
);
});
it.effect("still fails a worktree removal that exceeds its cleanup deadline", () => {
const commands: Array<ReadonlyArray<string>> = [];
const layer = makeWorktreeRemovalLayer({
commands,
exitCode: Effect.never,
timeoutMs: 25,
});
return TestClock.withLive(
Effect.gen(function* () {
const driver = yield* GitVcsDriver.GitVcsDriver;
const error = yield* driver
.removeWorktree({ cwd: "/repo", path: "/repo-worktrees/stuck" })
.pipe(Effect.flip);
assert.deepInclude(error, {
_tag: "GitCommandError",
operation: "GitVcsDriver.removeWorktree",
detail: "Git command timed out.",
cwd: "/repo",
});
assert.deepStrictEqual(commands, [["worktree", "remove", "/repo-worktrees/stuck"]]);
}).pipe(Effect.provide(layer)),
);
});
it.effect("creates and removes a worktree for a new refName", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+12 -2
View File
@@ -38,6 +38,7 @@ import {
import { ServerConfig } from "../config.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;
@@ -642,7 +643,13 @@ const collectOutput = Effect.fnUntraced(function* (
};
});
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* () {
export interface GitVcsDriverCoreOptions {
readonly worktreeRemoveTimeoutMs?: number;
}
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (
options: GitVcsDriverCoreOptions = {},
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -2395,7 +2402,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}
args.push(input.path);
yield* executeGit("GitVcsDriver.removeWorktree", input.cwd, args, {
timeoutMs: 15_000,
// Removing untracked dependency trees is filesystem-bound and can take
// minutes on Windows. Keep the operation supervised, but give it a
// cleanup-specific ceiling instead of the short interactive deadline.
timeoutMs: options.worktreeRemoveTimeoutMs ?? WORKTREE_REMOVE_TIMEOUT_MS,
fallbackErrorDetail: "git worktree remove failed",
});
});
@@ -6,7 +6,6 @@ import { useLocation, useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { requestCloseActiveRightPanelSurface } from "../lib/rightPanelCloseRequest";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
import ThreadSidebar from "./Sidebar";
@@ -145,13 +144,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
if (!isSettingsRoute) {
void navigate({ to: "/settings" });
}
return;
}
if (action === "close-window-or-right-panel") {
if (!requestCloseActiveRightPanelSurface()) {
window.close();
}
}
});
+1 -152
View File
@@ -48,7 +48,6 @@ import {
Suspense,
useCallback,
useEffect,
useEffectEvent,
useLayoutEffect,
useMemo,
useRef,
@@ -156,21 +155,6 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
import { useEnvironmentSettings } from "../hooks/useSettings";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import {
clearNativeCloseFocusOwner,
finishNativeClosePointer,
getNativeCloseFocusOwner,
recordNativeCloseFocus,
recordNativeCloseFocusOut,
recordNativeClosePointer,
} from "../lib/nativeCloseFocus";
import { isRightPanelFocused } from "../lib/rightPanelFocus";
import {
CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT,
resolveNativeCloseTarget,
resolveRightPanelCloseTarget,
shouldDeferCloseCommandToDesktopMenu,
} from "../lib/rightPanelCloseRequest";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
deriveLogicalProjectKeyFromSettings,
@@ -224,11 +208,7 @@ import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
import { MessagesTimeline } from "./chat/MessagesTimeline";
import { ChatHeader } from "./chat/ChatHeader";
import {
PanelLayoutControls,
RightPanelCloseControl,
RightPanelMaximizeControl,
} from "./chat/PanelLayoutControls";
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { NoActiveThreadState } from "./NoActiveThreadState";
import { resolveEffectiveEnvMode } from "./BranchToolbar.logic";
@@ -1479,13 +1459,6 @@ function ChatViewContent(props: ChatViewProps) {
canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey;
const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet;
useEffect(() => {
if (rightPanelOpen) return;
setMaximizedRightPanelThreadKey((threadKey) =>
threadKey === routeThreadKey ? null : threadKey,
);
}, [rightPanelOpen, routeThreadKey]);
useEffect(() => {
if (!activeThreadRef) return;
useRightPanelStore
@@ -3173,103 +3146,6 @@ function ChatViewContent(props: ChatViewProps) {
},
[activeThreadRef, cleanupRightPanelSurfaces, syncActivePreviewSurface],
);
const activeRightPanelPreviewTabId =
activeRightPanelSurface?.kind === "preview"
? (activeRightPanelSurface.resourceId ?? null)
: null;
const closeActiveRightPanelTarget = useCallback(
(terminalFocusOwner = getTerminalFocusOwner()) => {
const target = resolveRightPanelCloseTarget({
isOpen: rightPanelOpen,
hasActiveSurface: activeRightPanelSurface !== null,
hasFocusedTerminal:
activeRightPanelSurface?.kind === "terminal" && terminalFocusOwner === "right-panel",
});
if (target === "terminal" && activeRightPanelSurface?.kind === "terminal") {
closePanelTerminal(activeRightPanelSurface.activeTerminalId);
} else if (target === "surface" && activeRightPanelSurface) {
closeRightPanelSurface(activeRightPanelSurface);
} else if (target === "panel" && activeThreadRef) {
setMaximizedRightPanelThreadKey(null);
useRightPanelStore.getState().close(activeThreadRef);
}
return target !== null;
},
[
activeRightPanelSurface,
activeThreadRef,
closePanelTerminal,
closeRightPanelSurface,
rightPanelOpen,
],
);
const handleCloseRequest = useEffectEvent((event: Event) => {
const target = resolveNativeCloseTarget({
focusOwner: getNativeCloseFocusOwner(activeRightPanelPreviewTabId),
drawerTerminalOpen: terminalUiState.terminalOpen,
rightPanelOpen,
hasActiveRightPanelSurface: activeRightPanelSurface !== null,
activeRightPanelSurfaceIsTerminal: activeRightPanelSurface?.kind === "terminal",
});
if (target === "drawer-terminal") {
closeTerminal(terminalUiState.activeTerminalId);
} else if (target === "right-panel-terminal" && activeRightPanelSurface?.kind === "terminal") {
closePanelTerminal(activeRightPanelSurface.activeTerminalId);
} else if (target === "right-panel-surface" && activeRightPanelSurface) {
closeRightPanelSurface(activeRightPanelSurface);
} else if (target === "right-panel" && activeThreadRef) {
setMaximizedRightPanelThreadKey(null);
useRightPanelStore.getState().close(activeThreadRef);
} else {
return;
}
event.preventDefault();
});
useEffect(() => {
const listener = (event: Event) => handleCloseRequest(event);
window.addEventListener(CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT, listener);
return () => {
window.removeEventListener(CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT, listener);
};
}, []);
useEffect(() => {
const recordFocus = (event: FocusEvent | PointerEvent) => {
recordNativeCloseFocus(event.target, activeRightPanelPreviewTabId);
};
const recordFocusOut = (event: FocusEvent) => {
recordNativeCloseFocusOut(
event.relatedTarget,
document.hasFocus(),
activeRightPanelPreviewTabId,
);
};
const recordPointer = (event: PointerEvent) => {
recordNativeClosePointer(event.target, activeRightPanelPreviewTabId);
};
recordNativeCloseFocus(document.activeElement, activeRightPanelPreviewTabId);
window.addEventListener("focusin", recordFocus, true);
window.addEventListener("focusout", recordFocusOut, true);
window.addEventListener("pointerdown", recordPointer, true);
window.addEventListener("pointerup", finishNativeClosePointer, true);
window.addEventListener("pointercancel", finishNativeClosePointer, true);
return () => {
window.removeEventListener("focusin", recordFocus, true);
window.removeEventListener("focusout", recordFocusOut, true);
window.removeEventListener("pointerdown", recordPointer, true);
window.removeEventListener("pointerup", finishNativeClosePointer, true);
window.removeEventListener("pointercancel", finishNativeClosePointer, true);
clearNativeCloseFocusOwner();
};
}, [activeRightPanelPreviewTabId, routeThreadKey]);
useEffect(() => {
if (!terminalUiState.terminalOpen) clearNativeCloseFocusOwner("drawer-terminal");
if (!rightPanelOpen) {
clearNativeCloseFocusOwner("right-panel-terminal");
clearNativeCloseFocusOwner("right-panel");
}
}, [rightPanelOpen, terminalUiState.terminalOpen]);
const closeOtherRightPanelSurfaces = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
@@ -3956,10 +3832,6 @@ function ChatViewContent(props: ChatViewProps) {
terminalFocus: terminalFocusOwner !== null,
terminalOpen: Boolean(terminalUiState.terminalOpen),
modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
rightPanelFocus: isRightPanelFocused({
rightPanelOpen,
activePreviewTabId: activeRightPanelPreviewTabId,
}),
};
if (
@@ -3979,18 +3851,6 @@ function ChatViewContent(props: ChatViewProps) {
});
if (!command) return;
if (
shouldDeferCloseCommandToDesktopMenu({
command,
desktop: isElectron,
platform: navigator.platform,
event,
terminalFocused: terminalFocusOwner !== null,
})
) {
return;
}
if (command === "terminal.toggle") {
event.preventDefault();
event.stopPropagation();
@@ -4005,13 +3865,6 @@ function ChatViewContent(props: ChatViewProps) {
return;
}
if (command === "rightPanel.closeActiveSurface") {
if (!closeActiveRightPanelTarget()) return;
event.preventDefault();
event.stopPropagation();
return;
}
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
@@ -4099,7 +3952,6 @@ function ChatViewContent(props: ChatViewProps) {
activeThreadId,
closeTerminal,
closePanelTerminal,
closeActiveRightPanelTarget,
createNewTerminal,
setTerminalOpen,
runProjectScript,
@@ -5258,9 +5110,6 @@ function ChatViewContent(props: ChatViewProps) {
/>
) : null}
{panelToggleControls}
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
<RightPanelCloseControl onClose={toggleRightPanel} />
) : null}
</div>
);
const rightPanelContent = activeThreadRef ? (
@@ -1,104 +0,0 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { handleSurfaceTabAuxClick } from "~/lib/rightPanelTabPointer";
import { RightPanelTabs } from "./RightPanelTabs";
import {
PanelLayoutControls,
RightPanelCloseControl,
RightPanelMaximizeControl,
} from "./chat/PanelLayoutControls";
vi.mock("~/env", () => ({ isElectron: false }));
function renderTabs(mode: "inline" | "sheet"): string {
return renderToStaticMarkup(
<RightPanelTabs
mode={mode}
surfaces={[]}
activeSurfaceId={null}
pendingSurfaceIds={new Set()}
previewSessions={{}}
terminalLabelsById={new Map()}
onActivate={vi.fn()}
onCloseSurface={vi.fn()}
onCloseOtherSurfaces={vi.fn()}
onCloseSurfacesToRight={vi.fn()}
onCloseAllSurfaces={vi.fn()}
onCopyFilePath={vi.fn()}
onAddBrowser={vi.fn()}
onAddTerminal={vi.fn()}
onAddDiff={vi.fn()}
onAddFiles={vi.fn()}
browserAvailable
diffAvailable
filesAvailable
>
<div>Active surface</div>
</RightPanelTabs>,
);
}
describe("RightPanelTabs", () => {
it("closes the clicked surface on middle mouse button", () => {
const surface = { id: "files", kind: "files" } as const;
const event = {
button: 1,
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
};
const onCloseSurface = vi.fn();
handleSurfaceTabAuxClick(event, surface, onCloseSurface);
expect(event.preventDefault).toHaveBeenCalledOnce();
expect(event.stopPropagation).toHaveBeenCalledOnce();
expect(onCloseSurface).toHaveBeenCalledOnce();
expect(onCloseSurface).toHaveBeenCalledWith(surface);
});
it.each([0, 2])("ignores auxiliary click button %s", (button) => {
const event = {
button,
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
};
const onCloseSurface = vi.fn();
handleSurfaceTabAuxClick(event, { id: "files", kind: "files" }, onCloseSurface);
expect(event.preventDefault).not.toHaveBeenCalled();
expect(event.stopPropagation).not.toHaveBeenCalled();
expect(onCloseSurface).not.toHaveBeenCalled();
});
it("marks the panel content region", () => {
const markup = renderTabs("inline");
expect(markup).toContain("data-right-panel-content");
});
it("places the whole-panel close control after the other title-bar controls", () => {
const markup = renderToStaticMarkup(
<div>
<RightPanelMaximizeControl maximized={false} onToggle={vi.fn()} />
<PanelLayoutControls
terminalAvailable
terminalOpen={false}
terminalShortcutLabel={null}
rightPanelAvailable
rightPanelOpen
rightPanelShortcutLabel={null}
onToggleTerminal={vi.fn()}
onToggleRightPanel={vi.fn()}
/>
<RightPanelCloseControl onClose={vi.fn()} />
</div>,
);
expect(markup.indexOf('aria-label="Close right panel"')).toBeGreaterThan(
markup.indexOf('aria-label="Toggle right panel"'),
);
});
});
+7 -5
View File
@@ -19,7 +19,6 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
import { faviconUrlForOrigin } from "~/lib/favicon";
import { handleSurfaceTabAuxClick } from "~/lib/rightPanelTabPointer";
import { useTheme } from "~/hooks/useTheme";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
@@ -338,7 +337,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
}, []);
const handleTabAuxClick = useCallback(
(event: ReactMouseEvent, surface: RightPanelSurface) => {
handleSurfaceTabAuxClick(event, surface, props.onCloseSurface);
if (event.button !== 1) return;
event.preventDefault();
event.stopPropagation();
props.onCloseSurface(surface);
},
[props],
);
@@ -356,8 +358,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<div
className={cn(
"workspace-topbar gap-1 pl-2",
props.mode === "inline" ? "pr-36" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+8rem)]",
props.mode === "inline" ? "pr-28" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
data-right-panel-tabbar
@@ -475,7 +477,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
</ScrollArea>
{props.layoutControls}
</div>
<div className="flex min-h-0 flex-1 flex-col" data-right-panel-content>
<div className="flex min-h-0 flex-1 flex-col">
{props.activeSurfaceId === null ? (
<RightPanelEmptyState
onAddBrowser={props.onAddBrowser}
@@ -1,7 +1,6 @@
import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon, XIcon } from "lucide-react";
import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon } from "lucide-react";
import { memo } from "react";
import { Button } from "../ui/button";
import { Toggle } from "../ui/toggle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -58,7 +57,6 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
data-right-panel-control
pressed={rightPanelOpen}
onPressedChange={onToggleRightPanel}
aria-label="Toggle right panel"
@@ -94,7 +92,6 @@ export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
data-right-panel-control
pressed={maximized}
onPressedChange={onToggle}
aria-label={label}
@@ -113,29 +110,3 @@ export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl
</Tooltip>
);
});
export const RightPanelCloseControl = memo(function RightPanelCloseControl({
onClose,
}: {
onClose: () => void;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Button
className="[-webkit-app-region:no-drag]"
data-right-panel-control
variant="ghost"
size="icon-sm"
aria-label="Close right panel"
onClick={onClose}
>
<XIcon className="size-4" />
</Button>
}
/>
<TooltipPopup side="bottom">Close right panel</TooltipPopup>
</Tooltip>
);
});
-33
View File
@@ -108,11 +108,6 @@ const DEFAULT_BINDINGS = compile([
command: "terminal.close",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("w"),
command: "rightPanel.closeActiveSurface",
whenAst: whenAnd(whenIdentifier("rightPanelFocus"), whenNot(whenIdentifier("terminalFocus"))),
},
{
shortcut: modShortcut("d"),
command: "diff.toggle",
@@ -294,34 +289,6 @@ describe("split/new/close terminal shortcuts", () => {
});
});
describe("right panel close shortcut", () => {
it("matches Cmd+W only while the right panel owns focus", () => {
assert.strictEqual(
resolveShortcutCommand(event({ key: "w", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { rightPanelFocus: true },
}),
"rightPanel.closeActiveSurface",
);
assert.isNull(
resolveShortcutCommand(event({ key: "w", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { rightPanelFocus: false },
}),
);
});
it("keeps terminal close active for a focused right-panel terminal", () => {
assert.strictEqual(
resolveShortcutCommand(event({ key: "w", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { rightPanelFocus: true, terminalFocus: true },
}),
"terminal.close",
);
});
});
describe("shortcutLabelForCommand", () => {
it("returns the effective binding label", () => {
const bindings = compile([
-2
View File
@@ -32,7 +32,6 @@ export interface ShortcutMatchContext {
terminalOpen: boolean;
previewFocus: boolean;
previewOpen: boolean;
rightPanelFocus: boolean;
[key: string]: boolean;
}
@@ -121,7 +120,6 @@ function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatc
terminalOpen: false,
previewFocus: false,
previewOpen: false,
rightPanelFocus: false,
...options?.context,
};
}
-166
View File
@@ -1,166 +0,0 @@
import { afterEach, describe, expect, it } from "vite-plus/test";
import {
clearNativeCloseFocusOwner,
finishNativeClosePointer,
getNativeCloseFocusOwner,
recordNativeCloseFocus,
recordNativeCloseFocusOut,
recordNativeClosePointer,
} from "./nativeCloseFocus";
class MockElement extends EventTarget {
isConnected = true;
owner: "drawer" | "right-panel" | null = null;
inRightPanel = false;
inPreviewViewport = false;
previewTabId: string | null = null;
tagName = "div";
closest(selector: string): MockElement | null {
if (!this.isConnected) return null;
if (selector === "[data-terminal-owner]" && this.owner !== null) return this;
if (selector.includes("[data-right-panel-tabbar]") && this.inRightPanel) return this;
if (selector === "[data-preview-viewport]" && this.inPreviewViewport) return this;
return null;
}
get dataset(): DOMStringMap {
return { terminalOwner: this.owner ?? undefined } as DOMStringMap;
}
getAttribute(name: string): string | null {
if (name === "data-preview-tab" || name === "data-preview-viewport") {
return this.previewTabId;
}
return null;
}
}
const originalDocument = globalThis.document;
const originalElement = globalThis.Element;
afterEach(() => {
clearNativeCloseFocusOwner();
if (originalDocument === undefined) {
delete (globalThis as { document?: Document }).document;
} else {
globalThis.document = originalDocument;
}
if (originalElement === undefined) {
delete (globalThis as { Element?: typeof Element }).Element;
} else {
globalThis.Element = originalElement;
}
});
function installDom(activeElement: MockElement, body = new MockElement()): void {
globalThis.Element = MockElement as unknown as typeof Element;
globalThis.document = { activeElement, body } as unknown as Document;
}
describe("native close focus", () => {
it("distinguishes drawer terminals, right-panel terminals, and other panel focus", () => {
const drawer = new MockElement();
drawer.owner = "drawer";
installDom(drawer);
expect(getNativeCloseFocusOwner(null)).toBe("drawer-terminal");
const panelTerminal = new MockElement();
panelTerminal.owner = "right-panel";
installDom(panelTerminal);
expect(getNativeCloseFocusOwner(null)).toBe("right-panel-terminal");
const panelControl = new MockElement();
panelControl.inRightPanel = true;
installDom(panelControl);
expect(getNativeCloseFocusOwner(null)).toBe("right-panel");
});
it("retains ownership only while focus is obscured by native UI", () => {
const terminal = new MockElement();
terminal.owner = "drawer";
const body = new MockElement();
installDom(body, body);
recordNativeCloseFocus(terminal, null);
recordNativeCloseFocusOut(null, false, null);
expect(getNativeCloseFocusOwner(null)).toBe("drawer-terminal");
recordNativeCloseFocusOut(null, true, null);
expect(getNativeCloseFocusOwner(null)).toBeNull();
});
it("preserves pointer ownership until the pointer gesture finishes", async () => {
const panelChrome = new MockElement();
panelChrome.inRightPanel = true;
const body = new MockElement();
installDom(body, body);
recordNativeClosePointer(panelChrome, null);
await Promise.resolve();
recordNativeCloseFocusOut(null, true, null);
finishNativeClosePointer();
expect(getNativeCloseFocusOwner(null)).toBe("right-panel");
});
it("clears retained ownership on focus or pointer movement outside the panel", () => {
const panel = new MockElement();
panel.inRightPanel = true;
const outside = new MockElement();
installDom(outside);
recordNativeCloseFocus(panel, null);
recordNativeCloseFocus(outside, null);
expect(getNativeCloseFocusOwner(null)).toBeNull();
});
it("updates ownership directly from a focusout related target", () => {
const drawer = new MockElement();
drawer.owner = "drawer";
const panel = new MockElement();
panel.inRightPanel = true;
installDom(panel);
recordNativeCloseFocus(drawer, null);
recordNativeCloseFocusOut(panel, true, null);
expect(getNativeCloseFocusOwner(null)).toBe("right-panel");
});
it("treats hosted preview webviews and viewport chrome as right-panel focus", () => {
const webview = new MockElement();
webview.tagName = "webview";
webview.previewTabId = "active-preview";
installDom(webview);
expect(getNativeCloseFocusOwner("active-preview")).toBe("right-panel");
const viewport = new MockElement();
viewport.inPreviewViewport = true;
viewport.previewTabId = "active-preview";
installDom(viewport);
expect(getNativeCloseFocusOwner("active-preview")).toBe("right-panel");
});
it("ignores previews that are not the active right-panel preview", () => {
const webview = new MockElement();
webview.tagName = "webview";
webview.previewTabId = "standalone-preview";
installDom(webview);
recordNativeClosePointer(webview, "right-panel-preview");
expect(getNativeCloseFocusOwner("right-panel-preview")).toBeNull();
});
it("ignores detached retained targets", () => {
const terminal = new MockElement();
terminal.owner = "drawer";
terminal.isConnected = false;
const body = new MockElement();
installDom(body, body);
recordNativeCloseFocus(terminal, null);
expect(getNativeCloseFocusOwner(null)).toBeNull();
});
});
-92
View File
@@ -1,92 +0,0 @@
export type NativeCloseFocusOwner = "drawer-terminal" | "right-panel-terminal" | "right-panel";
const RIGHT_PANEL_SELECTOR =
"[data-right-panel-tabbar], [data-right-panel-content], [data-right-panel-control]";
let retainedOwner: NativeCloseFocusOwner | null = null;
let pointerTransitionActive = false;
function ownerForElement(
element: Element,
activePreviewTabId: string | null,
): NativeCloseFocusOwner | null {
if (!element.isConnected) return null;
const terminalOwner =
element.closest<HTMLElement>("[data-terminal-owner]")?.dataset.terminalOwner;
if (terminalOwner === "drawer") return "drawer-terminal";
if (terminalOwner === "right-panel") return "right-panel-terminal";
const previewViewport = element.closest<HTMLElement>("[data-preview-viewport]");
const focusedPreviewTabId =
element.tagName.toLowerCase() === "webview"
? element.getAttribute("data-preview-tab")
: (previewViewport?.getAttribute("data-preview-viewport") ?? null);
if (focusedPreviewTabId !== null) {
return focusedPreviewTabId === activePreviewTabId ? "right-panel" : null;
}
if (element.closest(RIGHT_PANEL_SELECTOR)) return "right-panel";
return null;
}
/** Records an in-document focus or pointer transition before native UI can obscure DOM focus. */
export function recordNativeCloseFocus(
target: EventTarget | null,
activePreviewTabId: string | null,
): void {
retainedOwner = target instanceof Element ? ownerForElement(target, activePreviewTabId) : null;
}
/** Records pointer intent before a non-focusable target can blur the previous owner to body. */
export function recordNativeClosePointer(
target: EventTarget | null,
activePreviewTabId: string | null,
): void {
pointerTransitionActive = true;
recordNativeCloseFocus(target, activePreviewTabId);
}
export function finishNativeClosePointer(): void {
pointerTransitionActive = false;
}
/**
* Clears real in-document focus exits while preserving ownership when focus
* temporarily moves into native application UI such as the macOS menu bar.
*/
export function recordNativeCloseFocusOut(
relatedTarget: EventTarget | null,
documentHasFocus: boolean,
activePreviewTabId: string | null,
): void {
if (relatedTarget instanceof Element) {
retainedOwner = ownerForElement(relatedTarget, activePreviewTabId);
return;
}
if (documentHasFocus && !pointerTransitionActive) retainedOwner = null;
}
export function getNativeCloseFocusOwner(
activePreviewTabId: string | null,
): NativeCloseFocusOwner | null {
const activeElement = document.activeElement;
if (activeElement instanceof Element && activeElement.isConnected) {
const liveOwner = ownerForElement(activeElement, activePreviewTabId);
if (liveOwner !== null) {
retainedOwner = liveOwner;
return liveOwner;
}
if (activeElement !== document.body) {
retainedOwner = null;
return null;
}
}
return retainedOwner;
}
export function clearNativeCloseFocusOwner(owner?: NativeCloseFocusOwner): void {
if (owner !== undefined && retainedOwner !== owner) return;
retainedOwner = null;
pointerTransitionActive = false;
}
@@ -1,216 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT,
requestCloseActiveRightPanelSurface,
resolveNativeCloseTarget,
resolveRightPanelCloseTarget,
shouldDeferCloseCommandToDesktopMenu,
shouldDeferCloseShortcutToDesktopMenu,
} from "./rightPanelCloseRequest";
const keyboardEvent = (overrides: Partial<KeyboardEvent> = {}) =>
({
code: "KeyW",
key: "w",
metaKey: true,
ctrlKey: false,
shiftKey: false,
altKey: false,
...overrides,
}) as KeyboardEvent;
describe("requestCloseActiveRightPanelSurface", () => {
it("reports when the active right-panel surface handles the request", () => {
const target = new EventTarget();
target.addEventListener(CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT, (event) => {
event.preventDefault();
});
expect(requestCloseActiveRightPanelSurface(target)).toBe(true);
});
it("leaves an unhandled request available for window closing", () => {
expect(requestCloseActiveRightPanelSurface(new EventTarget())).toBe(false);
});
it("defers the native Cmd+W accelerator only in the macOS desktop app", () => {
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "MacIntel",
event: keyboardEvent(),
}),
).toBe(true);
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: false,
platform: "MacIntel",
event: keyboardEvent(),
}),
).toBe(false);
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "Win32",
event: keyboardEvent(),
}),
).toBe(false);
});
it("keeps rebound macOS shortcuts in the renderer", () => {
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "MacIntel",
event: keyboardEvent({ code: "KeyK", key: "k" }),
}),
).toBe(false);
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "MacIntel",
event: keyboardEvent({ shiftKey: true }),
}),
).toBe(false);
});
it("defers Cmd+W when the physical key and layout character differ", () => {
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "MacIntel",
event: keyboardEvent({ key: "z" }),
}),
).toBe(true);
});
it("defers native Cmd+W for focused terminal close commands", () => {
expect(
shouldDeferCloseCommandToDesktopMenu({
command: "terminal.close",
desktop: true,
event: keyboardEvent(),
platform: "MacIntel",
terminalFocused: true,
}),
).toBe(true);
expect(
shouldDeferCloseCommandToDesktopMenu({
command: "terminal.close",
desktop: true,
event: keyboardEvent(),
platform: "MacIntel",
terminalFocused: false,
}),
).toBe(false);
});
});
describe("resolveRightPanelCloseTarget", () => {
it("closes the active surface when the open panel has one", () => {
expect(
resolveRightPanelCloseTarget({
isOpen: true,
hasActiveSurface: true,
hasFocusedTerminal: false,
}),
).toBe("surface");
});
it("closes the focused terminal pane before its containing surface", () => {
expect(
resolveRightPanelCloseTarget({
isOpen: true,
hasActiveSurface: true,
hasFocusedTerminal: true,
}),
).toBe("terminal");
});
it("closes the panel itself when it is open without a surface", () => {
expect(
resolveRightPanelCloseTarget({
isOpen: true,
hasActiveSurface: false,
hasFocusedTerminal: false,
}),
).toBe("panel");
});
it("does not intercept window close when the panel is hidden", () => {
expect(
resolveRightPanelCloseTarget({
isOpen: false,
hasActiveSurface: true,
hasFocusedTerminal: false,
}),
).toBeNull();
});
});
describe("resolveNativeCloseTarget", () => {
const defaults = {
focusOwner: null,
drawerTerminalOpen: true,
rightPanelOpen: true,
hasActiveRightPanelSurface: true,
activeRightPanelSurfaceIsTerminal: false,
} as const;
it("does not intercept window close when focus is outside an open panel", () => {
expect(resolveNativeCloseTarget(defaults)).toBeNull();
});
it("closes a focused drawer terminal before an open right panel", () => {
expect(resolveNativeCloseTarget({ ...defaults, focusOwner: "drawer-terminal" })).toBe(
"drawer-terminal",
);
});
it("ignores stale drawer ownership after the drawer closes", () => {
expect(
resolveNativeCloseTarget({
...defaults,
focusOwner: "drawer-terminal",
drawerTerminalOpen: false,
}),
).toBeNull();
});
it("closes only the focused pane in a right-panel terminal group", () => {
expect(
resolveNativeCloseTarget({
...defaults,
focusOwner: "right-panel-terminal",
activeRightPanelSurfaceIsTerminal: true,
}),
).toBe("right-panel-terminal");
});
it("closes the active surface for other right-panel focus", () => {
expect(resolveNativeCloseTarget({ ...defaults, focusOwner: "right-panel" })).toBe(
"right-panel-surface",
);
});
it("closes an empty focused panel without closing the window", () => {
expect(
resolveNativeCloseTarget({
...defaults,
focusOwner: "right-panel",
hasActiveRightPanelSurface: false,
}),
).toBe("right-panel");
});
it("does not intercept after the right panel closes", () => {
expect(
resolveNativeCloseTarget({
...defaults,
focusOwner: "right-panel",
rightPanelOpen: false,
}),
).toBeNull();
});
});
@@ -1,96 +0,0 @@
import { isMacPlatform } from "./utils";
import type { NativeCloseFocusOwner } from "./nativeCloseFocus";
export const CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT = "t3:close-active-right-panel-surface";
interface NativeCloseShortcutInput {
readonly desktop: boolean;
readonly platform: string;
readonly event: {
readonly code?: string;
readonly key: string;
readonly metaKey: boolean;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
};
}
export function shouldDeferCloseShortcutToDesktopMenu({
desktop,
platform,
event,
}: NativeCloseShortcutInput): boolean {
return (
desktop &&
isMacPlatform(platform) &&
(event.key.toLowerCase() === "w" || event.code === "KeyW") &&
event.metaKey &&
!event.ctrlKey &&
!event.shiftKey &&
!event.altKey
);
}
export function shouldDeferCloseCommandToDesktopMenu({
command,
terminalFocused,
...shortcut
}: NativeCloseShortcutInput & {
readonly command: string;
readonly terminalFocused: boolean;
}): boolean {
const isNativeCloseCommand =
command === "rightPanel.closeActiveSurface" ||
(command === "terminal.close" && terminalFocused);
return isNativeCloseCommand && shouldDeferCloseShortcutToDesktopMenu(shortcut);
}
export function resolveRightPanelCloseTarget({
isOpen,
hasActiveSurface,
hasFocusedTerminal,
}: {
readonly isOpen: boolean;
readonly hasActiveSurface: boolean;
readonly hasFocusedTerminal: boolean;
}): "terminal" | "surface" | "panel" | null {
if (!isOpen) return null;
if (hasFocusedTerminal) return "terminal";
return hasActiveSurface ? "surface" : "panel";
}
export function resolveNativeCloseTarget({
focusOwner,
drawerTerminalOpen,
rightPanelOpen,
hasActiveRightPanelSurface,
activeRightPanelSurfaceIsTerminal,
}: {
readonly focusOwner: NativeCloseFocusOwner | null;
readonly drawerTerminalOpen: boolean;
readonly rightPanelOpen: boolean;
readonly hasActiveRightPanelSurface: boolean;
readonly activeRightPanelSurfaceIsTerminal: boolean;
}): "drawer-terminal" | "right-panel-terminal" | "right-panel-surface" | "right-panel" | null {
if (focusOwner === "drawer-terminal") {
return drawerTerminalOpen ? "drawer-terminal" : null;
}
if (focusOwner !== "right-panel" && focusOwner !== "right-panel-terminal") return null;
if (!rightPanelOpen) return null;
if (!hasActiveRightPanelSurface) return "right-panel";
if (focusOwner === "right-panel-terminal" && activeRightPanelSurfaceIsTerminal) {
return "right-panel-terminal";
}
return "right-panel-surface";
}
export function requestCloseActiveRightPanelSurface(
target: Pick<Window, "dispatchEvent"> = window,
): boolean {
const event = new Event(CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT, {
cancelable: true,
});
target.dispatchEvent(event);
return event.defaultPrevented;
}
-113
View File
@@ -1,113 +0,0 @@
import { afterEach, describe, expect, it } from "vite-plus/test";
import { isRightPanelFocused } from "./rightPanelFocus";
class MockHTMLElement {
isConnected = false;
rightPanelRegion = false;
inPreviewViewport = false;
previewTabId: string | null = null;
tagName = "div";
closest(selector: string): MockHTMLElement | null {
if (!this.isConnected) return null;
if (selector === "[data-preview-viewport]" && this.inPreviewViewport) return this;
if (
selector ===
"[data-right-panel-tabbar], [data-right-panel-content], [data-right-panel-control]" &&
this.rightPanelRegion
) {
return this;
}
return null;
}
getAttribute(name: string): string | null {
if (name === "data-preview-tab" || name === "data-preview-viewport") {
return this.previewTabId;
}
return null;
}
}
const originalDocument = globalThis.document;
const originalHTMLElement = globalThis.HTMLElement;
afterEach(() => {
if (originalDocument === undefined) {
delete (globalThis as { document?: Document }).document;
} else {
globalThis.document = originalDocument;
}
if (originalHTMLElement === undefined) {
delete (globalThis as { HTMLElement?: typeof HTMLElement }).HTMLElement;
} else {
globalThis.HTMLElement = originalHTMLElement;
}
});
describe("isRightPanelFocused", () => {
it("recognizes focus in the right-panel tab bar or active surface", () => {
const activeElement = new MockHTMLElement();
activeElement.isConnected = true;
activeElement.rightPanelRegion = true;
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: null })).toBe(true);
});
it("recognizes hosted preview focus while the right panel is open", () => {
const webview = new MockHTMLElement();
webview.isConnected = true;
webview.tagName = "webview";
webview.previewTabId = "preview-a";
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement: webview } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: "preview-a" })).toBe(
true,
);
const viewport = new MockHTMLElement();
viewport.isConnected = true;
viewport.inPreviewViewport = true;
viewport.previewTabId = "preview-a";
globalThis.document = { activeElement: viewport } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: "preview-a" })).toBe(
true,
);
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: "preview-b" })).toBe(
false,
);
});
it("ignores right-panel controls when the panel is closed", () => {
const activeElement = new MockHTMLElement();
activeElement.isConnected = true;
activeElement.rightPanelRegion = true;
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: false, activePreviewTabId: null })).toBe(false);
});
it("ignores detached elements and focus outside the right panel", () => {
const activeElement = new MockHTMLElement();
activeElement.rightPanelRegion = true;
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: null })).toBe(false);
activeElement.isConnected = true;
activeElement.rightPanelRegion = false;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: null })).toBe(false);
});
});
-30
View File
@@ -1,30 +0,0 @@
/**
* Returns true when keyboard focus belongs to the tabbed right-panel chrome
* or its active surface. This deliberately excludes other preview-panel
* shells so right-panel shortcuts do not affect standalone preview layouts.
*/
export function isRightPanelFocused({
rightPanelOpen,
activePreviewTabId,
}: {
readonly rightPanelOpen: boolean;
readonly activePreviewTabId: string | null;
}): boolean {
if (!rightPanelOpen) return false;
const activeElement = document.activeElement;
if (!(activeElement instanceof HTMLElement)) return false;
if (!activeElement.isConnected) return false;
const previewViewport = activeElement.closest<HTMLElement>("[data-preview-viewport]");
const focusedPreviewTabId =
activeElement.tagName.toLowerCase() === "webview"
? activeElement.getAttribute("data-preview-tab")
: (previewViewport?.getAttribute("data-preview-viewport") ?? null);
if (focusedPreviewTabId !== null) {
return focusedPreviewTabId === activePreviewTabId;
}
return (
activeElement.closest(
"[data-right-panel-tabbar], [data-right-panel-content], [data-right-panel-control]",
) !== null
);
}
-18
View File
@@ -1,18 +0,0 @@
import type { RightPanelSurface } from "~/rightPanelStore";
interface SurfaceTabAuxClickEvent {
readonly button: number;
preventDefault(): void;
stopPropagation(): void;
}
export function handleSurfaceTabAuxClick(
event: SurfaceTabAuxClickEvent,
surface: RightPanelSurface,
onCloseSurface: (surface: RightPanelSurface) => void,
): void {
if (event.button !== 1) return;
event.preventDefault();
event.stopPropagation();
onCloseSurface(surface);
}
@@ -41,12 +41,6 @@ it.effect("parses keybinding rules", () =>
});
assert.strictEqual(parsedRightPanelToggle.command, "rightPanel.toggle");
const parsedRightPanelClose = yield* decode(KeybindingRule, {
key: "mod+w",
command: "rightPanel.closeActiveSurface",
});
assert.strictEqual(parsedRightPanelClose.command, "rightPanel.closeActiveSurface");
const parsedClose = yield* decode(KeybindingRule, {
key: "mod+w",
command: "terminal.close",
-1
View File
@@ -55,7 +55,6 @@ const STATIC_KEYBINDING_COMMANDS = [
"terminal.new",
"terminal.close",
"rightPanel.toggle",
"rightPanel.closeActiveSurface",
"diff.toggle",
"preview.toggle",
"preview.refresh",
-5
View File
@@ -26,11 +26,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+shift+d", command: "terminal.splitVertical", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{
key: "mod+w",
command: "rightPanel.closeActiveSurface",
when: "rightPanelFocus && !terminalFocus",
},
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+shift+j", command: "preview.toggle" },
{ key: "mod+r", command: "preview.refresh", when: "previewFocus" },