Compare commits

..
Author SHA1 Message Date
Yash Singh 327ada5ecc Remove remote download-and-reveal flow
- حذف desktop IPC and shell support for temporary file downloads
- Simplify asset URL handling to treat workspace files uniformly
- Update markdown file links to use platform-specific reveal labels
2026-07-25 19:08:21 -05:00
Yash Singh daee2c3098 support remote environments 2026-07-24 12:11:50 -05:00
Yash Singh c877be3931 Merge remote-tracking branch 'origin/main' into t3code/show-in-finder 2026-07-21 22:02:21 -05:00
Yash Singh 708f9da5e1 feat: show in finder btn for file pills 2026-07-21 22:02:05 -05:00
Theo BrowneandClaude Fable 5 6f34ad3e87 fix(claude): handle all SDK stream messages; stop spurious work-log warning rows (#4244)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 19:58:39 -07:00
Theo BrowneandClaude Fable 5 62cf461759 fix: better defaults — Claude 1M context, Codex gpt-5.6, worktrees from origin main (#4240)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 17:13:44 -07:00
Theo BrowneandClaude Fable 5 23c18fda7a fix(web): keep composer editable while disconnected (#4241)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 14:29:23 -07:00
Theo BrowneandClaude Fable 5 c0bb237345 fix(web): always show environment chip for remote projects (#4217)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-20 18:27:57 -07:00
54 changed files with 827 additions and 1431 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) =>
@@ -58,6 +58,8 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree";
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
function pendingTaskDraftKey(messageId: string): string {
return `pending-task:${messageId}`;
}
@@ -348,7 +350,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
// Keep the user's explicit choice separate from the resolved display value:
// only the explicit flag is ever written back to the draft, so the resolved
// value keeps tracking the server setting when the config loads late.
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
const startFromOrigin =
draftStartFromOrigin ??
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
true;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
@@ -368,6 +377,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions.find((option) => option.isDefault)?.selection ??
modelOptions[0]?.selection ??
null;
const selectedModelKey = selectedModel
@@ -475,13 +485,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const branchState = useBranches(branchTarget);
const branchesLoading = branchState.isPending;
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
const availableBranches = useMemo(
() =>
pipe(
branchState.data?.refs ?? [],
allBranchRefs,
Arr.filter((branch) => !branch.isRemote),
),
[branchState.data?.refs],
[allBranchRefs],
);
const filteredBranches = useMemo(() => {
@@ -543,11 +554,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
@@ -560,11 +571,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
);
const setStartFromOrigin = useCallback(
@@ -597,14 +608,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
// availableBranches filters out — search the unfiltered refs for it.
const preferredBranch =
allBranchRefs.find((branch) => branch.isDefault) ??
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -696,7 +709,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode: mode,
branch: workspaceSelection?.branch ?? null,
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
// The draft only carries the flag when the user touched it; fall
// back to the resolved default (server settings) so queued tasks
// drain with the same origin mode the composer displayed.
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
? { startFromOrigin: true }
: {}),
},
createdAt: metadata.createdAt,
};
@@ -707,6 +725,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedProject,
selectedProjectDraftKey,
startFromOrigin,
],
);
+3
View File
@@ -15,6 +15,7 @@ export type ModelOption = {
readonly providerKey: string;
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -78,6 +79,7 @@ export function buildModelOptions(
providerKey: provider.instanceId,
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -107,6 +109,7 @@ export function buildModelOptions(
providerKey: fallbackModelSelection.instanceId,
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
capabilities: null,
selection: fallbackModelSelection,
});
@@ -92,11 +92,67 @@ it.effect("launches the default browser through the platform command", () => {
);
});
it.effect("reveals a file in Finder on macOS", () => {
let spawned: ChildProcess.StandardCommand | undefined;
let didUnref = false;
const target = "/tmp/project with spaces/src/odd '✨' file.ts";
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.revealInFileManager(target);
assert.ok(spawned);
assert.equal(spawned.command, "open");
assert.deepEqual(spawned.args, ["-R", target]);
assert.equal(spawned.options.detached, true);
assert.equal(didUnref, true);
}).pipe(
Effect.provide(
testLayer({
platform: "darwin",
onSpawn: (command) => {
spawned = command;
},
onUnref: () => {
didUnref = true;
},
}),
),
);
});
it.effect("reveals a file in Explorer on Windows", () => {
let spawned: ChildProcess.StandardCommand | undefined;
const target = `C:/project with spaces/src/odd '✨' file.ts`;
const windowsTarget = String.raw`C:\project with spaces\src\odd '✨' file.ts`;
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.revealInFileManager(target);
assert.ok(spawned);
assert.equal(spawned.command, "explorer");
assert.deepEqual(spawned.args, ["/select,", windowsTarget]);
assert.equal(spawned.options.detached, true);
}).pipe(
Effect.provide(
testLayer({
platform: "win32",
onSpawn: (command) => {
spawned = command;
},
}),
),
);
});
it.effect("launches an installed editor with platform-safe arguments", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const binDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-editors-",
});
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
let spawned: ChildProcess.StandardCommand | undefined;
@@ -134,7 +190,9 @@ it.effect("discovers editors through the service API", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const binDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-editors-",
});
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
@@ -159,7 +217,10 @@ it.effect("rejects unknown editors through the service API", () =>
Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const error = yield* launcher
.launchEditor({ editor: "missing-editor" as never, cwd: "/tmp/workspace" })
.launchEditor({
editor: "missing-editor" as never,
cwd: "/tmp/workspace",
})
.pipe(Effect.flip);
assert.instanceOf(error, ExternalLauncher.ExternalLauncherUnknownEditorError);
assert.equal(error.editor, "missing-editor");
+64 -2
View File
@@ -313,6 +313,8 @@ export class ExternalLauncher extends Context.Service<
* Launches the editor as a detached process so server startup is not blocked.
*/
readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
/** Reveal a workspace path in the host platform's file manager. */
readonly revealInFileManager: (target: string) => Effect.Effect<void, ExternalLauncherError>;
}
>()("t3/process/externalLauncher") {}
@@ -332,7 +334,9 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
});
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
return yield* new ExternalLauncherUnknownEditorError({
editor: input.editor,
});
}
if (editorDef.commands) {
@@ -349,7 +353,9 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
}
if (editorDef.id !== "file-manager") {
return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
return yield* new ExternalLauncherUnsupportedEditorError({
editor: input.editor,
});
}
return {
@@ -430,6 +436,57 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu
);
});
const resolveFileManagerRevealLaunch = Effect.fn("externalLauncher.resolveFileManagerRevealLaunch")(
function* (target: string): Effect.fn.Return<ProcessLaunch, never, Path.Path> {
const platform = yield* HostProcessPlatform;
const path = yield* Path.Path;
switch (platform) {
case "darwin":
return {
command: "open",
args: ["-R", target],
options: DETACHED_IGNORE_STDIO_OPTIONS,
};
case "win32": {
const windowsTarget = target.replaceAll("/", "\\");
return {
command: "explorer",
args: ["/select,", windowsTarget],
options: DETACHED_IGNORE_STDIO_OPTIONS,
};
}
default:
return {
command: "xdg-open",
args: [path.dirname(target)],
options: DETACHED_IGNORE_STDIO_OPTIONS,
};
}
},
);
const revealInFileManager = Effect.fn("externalLauncher.revealInFileManager")(function* (
target: string,
): Effect.fn.Return<
void,
ExternalLauncherError,
ChildProcessSpawner.ChildProcessSpawner | Path.Path
> {
const launch = yield* resolveFileManagerRevealLaunch(target);
return yield* launchAndUnref(
launch,
(cause) =>
new ExternalLauncherEditorSpawnError({
editor: "file-manager",
target,
command: launch.command,
args: launch.args,
cause,
}),
);
});
export const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
@@ -457,6 +514,11 @@ export const make = Effect.gen(function* () {
),
),
),
revealInFileManager: (target) =>
revealInFileManager(target).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(Path.Path, path),
),
});
});
@@ -1711,6 +1711,133 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("consumes undeclared and UX-internal system subtypes without warning rows", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => runtimeEvents.push(event)),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
// Undeclared wire-only roster snapshot + every typed UX-internal
// subtype and top-level type consumed silently: none may surface as
// unknown-subtype warnings.
for (const message of [
{
type: "system",
subtype: "background_tasks_changed",
tasks: [{ task_id: "t1", task_type: "local_agent", description: "Say hi" }],
session_id: "session",
uuid: "roster",
},
{
type: "system",
subtype: "task_updated",
task_id: "t1",
patch: { status: "running" },
session_id: "session",
uuid: "tu",
},
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
{ type: "system", subtype: "elicitation_complete", session_id: "session", uuid: "ec" },
{ type: "prompt_suggestion", suggestion: "try this", session_id: "session", uuid: "ps" },
{
type: "system",
subtype: "notification",
key: "context",
text: "low priority note",
priority: "low",
session_id: "session",
uuid: "notif",
},
]) {
harness.query.emit(message as unknown as SDKMessage);
}
// High-priority notifications DO surface as a warning row.
harness.query.emit({
type: "system",
subtype: "notification",
key: "limit",
text: "context window nearly full",
priority: "high",
session_id: "session",
uuid: "notif-high",
} as unknown as SDKMessage);
// session_state_changed maps to the matching session states.
for (const [state, uuid] of [
["running", "ssc-run"],
["requires_action", "ssc-req"],
["idle", "ssc-idle"],
]) {
harness.query.emit({
type: "system",
subtype: "session_state_changed",
state,
session_id: "session",
uuid,
} as unknown as SDKMessage);
}
// api_retry maps to a session heartbeat, not a warning row.
harness.query.emit({
type: "system",
subtype: "api_retry",
attempt: 3,
max_retries: 10,
retry_delay_ms: 1000,
error_status: 502,
error: { type: "api_error" },
session_id: "session",
uuid: "retry",
} as unknown as SDKMessage);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
// Exactly one warning: the high-priority notification. Nothing else.
assert.deepEqual(
warnings.map((event) => event.payload.message),
["context window nearly full"],
);
const sessionStates = runtimeEvents
.filter((event) => event.type === "session.state.changed")
.map((event) =>
event.type === "session.state.changed"
? `${event.payload.state}:${event.payload.reason ?? ""}`
: "",
)
.filter(
(entry) => entry.startsWith("running:session_state") || entry.includes("session_state"),
);
assert.deepEqual(sessionStates, [
"running:session_state:running",
"waiting:session_state:requires_action",
"ready:session_state:idle",
]);
const heartbeat = runtimeEvents.find(
(event) =>
event.type === "session.state.changed" &&
typeof event.payload.reason === "string" &&
event.payload.reason.startsWith("api_retry:"),
);
assert.equal(heartbeat?.type, "session.state.changed");
runtimeEventsFiber.interruptUnsafe();
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("emits thread token usage updates from Claude task progress", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -3045,7 +3172,7 @@ describe("ClaudeAdapterLive", () => {
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3143,10 +3270,11 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "contextWindow", value: "200k" }],
),
attachments: [],
});
@@ -77,6 +77,7 @@ import {
isClaudeUltracodeEffort,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeContextWindow,
resolveClaudeEffort,
} from "./ClaudeProvider.ts";
import {
@@ -341,24 +342,18 @@ function selectedClaudeContextWindow(
switch (modelSelection?.model) {
case "claude-opus-4-8":
case "claude-opus-4-7":
// Always 1M at the API; these models expose no contextWindow option.
return 1_000_000;
}
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
if (optionValue === "1m") {
return 1_000_000;
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return 1_000_000;
case "200k":
return 200_000;
default:
return undefined;
}
if (optionValue === "200k") {
return 200_000;
}
const caps = getClaudeModelCapabilities(modelSelection?.model);
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
);
if (hasContextWindowOption) {
return 200_000;
}
return undefined;
}
function finiteNonNegativeInteger(value: unknown): number | undefined {
@@ -2590,6 +2585,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
};
// Undeclared-but-real subtypes (absent from the SDK's union, so they can't
// be switch cases): consumed intentionally without emitting, otherwise
// they fall through to the unknown-subtype warning and surface as spurious
// error rows in client work logs. `background_tasks_changed` is a roster
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
// authoritative per-agent data and the typed background_tasks control
// request is the reconciliation source.
if ((message.subtype as string) === "background_tasks_changed") {
return;
}
switch (message.subtype) {
case "init":
yield* offerRuntimeEvent({
@@ -2702,6 +2708,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
// Task state patch (status/backgrounded/end_time). No runtime mapping
// yet — the terminal task_notification reports the outcome — but it
// must not surface as an unknown-subtype warning row.
case "task_updated":
return;
case "task_notification":
yield* emitThreadTokenUsage(
context,
@@ -2746,6 +2757,52 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
case "thinking_tokens":
return;
case "api_retry":
// Transport-level retry heartbeat. Surfacing each attempt as a
// warning row spammed the work log (10 rows during a 502 storm);
// the terminal result/error path reports the actual failure. Keep
// the session visibly alive instead.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state: "running",
reason: `api_retry:${message.attempt}/${message.max_retries}`,
},
});
return;
case "session_state_changed":
// Authoritative turn-over signal from the CLI.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state:
message.state === "running"
? "running"
: message.state === "requires_action"
? "waiting"
: "ready",
reason: `session_state:${message.state}`,
},
});
return;
case "notification":
// User-facing CLI notification (e.g. context-limit warnings). Only
// high-priority ones warrant a work-log row.
if (message.priority === "high" || message.priority === "immediate") {
yield* emitRuntimeWarning(context, message.text, message);
}
return;
// Inner protocol/UX details with no T3 surface today — consumed
// deliberately so they don't masquerade as unknown-subtype warnings.
case "model_refusal_fallback":
case "local_command_output":
case "plugin_install":
case "commands_changed":
case "memory_recall":
case "elicitation_complete":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
@@ -2765,13 +2822,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
message,
);
return;
default:
default: {
// Exhaustiveness guard: every subtype in the SDK's typed union is
// handled above, so `message` narrows to never here — a new SDK
// release adding a subtype fails this typecheck instead of silently
// warning at runtime. The runtime fallback still catches undeclared
// wire-only subtypes (like background_tasks_changed used to be).
message satisfies never;
const unknownMessage = message as never as { subtype: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
message,
);
return;
}
}
});
@@ -2879,13 +2944,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
case "rate_limit_event":
yield* handleSdkTelemetryMessage(context, message);
return;
default:
// Composer prompt suggestions have no T3 surface; consumed deliberately.
case "prompt_suggestion":
return;
default: {
// Exhaustiveness guard (see handleSystemMessage): new SDK top-level
// message types fail typecheck here instead of warning at runtime.
message satisfies never;
const unknownMessage = message as never as { type: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
message,
);
return;
}
}
});
@@ -76,8 +76,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -162,8 +162,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -214,6 +214,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -243,6 +244,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -369,8 +371,22 @@ export function isClaudeUltracodeEffort(effort: string | null | undefined): bool
return effort === "ultracode";
}
export function resolveClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): string | undefined {
const caps = getClaudeModelCapabilities(modelSelection?.model);
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
});
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
const value = getProviderOptionCurrentValue(descriptor);
return typeof value === "string" ? value : undefined;
}
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
@@ -102,3 +102,45 @@ it("uses standard routing when the catalog has no default service tier", () => {
},
]);
});
it("marks the most preferred available model as default", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(
models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
[
{ slug: "gpt-5.6-terra", isDefault: true },
{ slug: "gpt-5.4", isDefault: undefined },
],
);
});
it("prefers sol over terra when both are available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol");
});
it("keeps Codex's own default when no preferred model is available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
it("ignores custom models that shadow a preferred slug", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
@@ -22,7 +22,7 @@ import type {
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
import { ServerSettingsError } from "@t3tools/contracts";
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -189,10 +189,36 @@ function parseCodexModelListResponse(
slug: model.model,
name: toDisplayName(model),
isCustom: false,
...(model.isDefault ? { isDefault: true } : {}),
capabilities: mapCodexModelCapabilities(model),
}));
}
/**
* Prefer our own default-model ranking when one of the preferred slugs is in
* the live catalog; otherwise keep whatever Codex itself flagged as default.
*/
export function applyPreferredCodexDefaultModel(
models: ReadonlyArray<ServerProviderModel>,
): ReadonlyArray<ServerProviderModel> {
const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
models.some((model) => model.slug === slug && !model.isCustom),
);
if (!preferredSlug) {
return models;
}
return models.map((model) => {
if (model.slug === preferredSlug) {
return model.isDefault ? model : { ...model, isDefault: true };
}
if (!model.isDefault) {
return model;
}
const { isDefault: _isDefault, ...rest } = model;
return rest;
});
}
function appendCustomCodexModels(
models: ReadonlyArray<ServerProviderModel>,
customModels: ReadonlyArray<string>,
@@ -376,7 +402,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
return {
account: accountResponse,
version,
models: appendCustomCodexModels(models, input.customModels ?? []),
models: applyPreferredCodexDefaultModel(
appendCustomCodexModels(models, input.customModels ?? []),
),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
});
+27
View File
@@ -4798,6 +4798,33 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc shell.revealInFileManager", () =>
Effect.gen(function* () {
let revealedPath: string | null = null;
yield* buildAppUnderTest({
layers: {
externalLauncher: {
revealInFileManager: (path) =>
Effect.sync(() => {
revealedPath = path;
}),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.shellRevealInFileManager]({
path: "/tmp/project/src/index.ts",
}),
),
);
assert.equal(revealedPath, "/tmp/project/src/index.ts");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc git methods", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
@@ -596,6 +596,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("marks the origin default ref as default when no local copy exists", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
yield* git(cwd, ["branch", "-D", initialBranch]);
const driver = yield* GitVcsDriver.GitVcsDriver;
const refs = yield* driver.listRefs({ cwd });
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
assert.equal(remoteDefault?.isRemote, true);
assert.equal(remoteDefault?.isDefault, true);
}),
);
it.effect("creates, checks out, renames, and lists refs", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+14 -2
View File
@@ -2217,7 +2217,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
name: refName.name,
current: false,
isRemote: true,
isDefault: false,
// origin/HEAD's target is the repo default even when no local
// copy of the default branch exists.
isDefault:
defaultBranch !== null &&
parsedRemoteRef?.remoteName === "origin" &&
parsedRemoteRef.branchName === defaultBranch,
worktreePath: null,
};
if (parsedRemoteRef) {
@@ -2232,9 +2237,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
})
: [];
const allBranches = input.includeMatchingRemoteRefs
const combinedBranches = input.includeMatchingRemoteRefs
? [...localBranches, ...remoteBranches]
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
// Keep current/default refs on the first page even when the default
// only exists as origin/<default> (remote refs sort after all locals).
const allBranches = combinedBranches.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
return aPriority - bPriority;
});
const branchesForKind =
input.refKind === "local"
? allBranches.filter((ref) => !ref.isRemote)
+7
View File
@@ -315,6 +315,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
[WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
[WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
[WS_METHODS.shellRevealInFileManager, AuthOrchestrationOperateScope],
[WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope],
[WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope],
[WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],
@@ -1675,6 +1676,12 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.shellRevealInFileManager]: (input) =>
observeRpcEffect(
WS_METHODS.shellRevealInFileManager,
externalLauncher.revealInFileManager(input.path),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.filesystemBrowse]: (input) =>
observeRpcEffect(
WS_METHODS.filesystemBrowse,
@@ -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();
}
}
});
@@ -12,6 +12,7 @@ import {
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
const localEnvironmentId = EnvironmentId.make("environment-local");
@@ -119,6 +120,44 @@ describe("resolveEnvironmentOptionLabel", () => {
});
});
describe("shouldShowEnvironmentIndicator", () => {
it("shows the indicator whenever multiple environments are pickable", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: true,
}),
).toBe(true);
});
it("shows a sole remote environment so the user knows where the project runs", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: false },
canPickEnvironment: false,
}),
).toBe(true);
});
it("hides a sole primary (this-device) environment", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: false,
}),
).toBe(false);
});
it("hides the indicator when the active environment is unknown", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: null,
canPickEnvironment: false,
}),
).toBe(false);
});
});
describe("resolveEffectiveEnvMode", () => {
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
expect(
@@ -42,6 +42,17 @@ export function resolveEnvironmentOptionLabel(input: {
return runtimeLabel ?? savedLabel ?? input.environmentId;
}
// A remote (non-primary) environment is always surfaced, even when it is the
// only environment available: with a single connected machine there is nothing
// to pick, but the user still needs to see where the project runs.
export function shouldShowEnvironmentIndicator(input: {
activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
canPickEnvironment: boolean;
}): boolean {
if (input.canPickEnvironment) return true;
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
}
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
+14 -4
View File
@@ -20,6 +20,7 @@ import {
resolveEnvModeLabel,
resolveEffectiveEnvMode,
resolveLockedWorkspaceLabel,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
@@ -60,6 +61,7 @@ interface MobileRunContextSelectorProps {
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[] | undefined;
showEnvironmentPicker: boolean;
showEnvironmentIndicator: boolean;
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
@@ -72,6 +74,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
environmentId,
availableEnvironments,
showEnvironmentPicker,
showEnvironmentIndicator,
onEnvironmentChange,
effectiveEnvMode,
activeWorktreePath,
@@ -94,7 +97,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
: resolveCurrentWorkspaceLabel(activeWorktreePath);
const isLocked = envLocked || envModeLocked;
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
const icon = showEnvironmentPicker ? (
const icon = showEnvironmentIndicator ? (
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
<span className="inline-flex shrink-0 items-center gap-0.5">
@@ -108,7 +111,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<>
{icon}
<span className="min-w-0 truncate">
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
</span>
</>
);
@@ -234,6 +237,12 @@ export const BranchToolbar = memo(function BranchToolbar({
const showEnvironmentPicker = Boolean(
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
);
const activeEnvironmentOption =
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
activeEnvironment: activeEnvironmentOption,
canPickEnvironment: showEnvironmentPicker,
});
const isMobile = useIsMobile();
if (!hasActiveThread || !activeProject) return null;
@@ -247,6 +256,7 @@ export const BranchToolbar = memo(function BranchToolbar({
environmentId={environmentId}
availableEnvironments={availableEnvironments}
showEnvironmentPicker={showEnvironmentPicker}
showEnvironmentIndicator={showEnvironmentIndicator}
onEnvironmentChange={onEnvironmentChange}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
@@ -254,13 +264,13 @@ export const BranchToolbar = memo(function BranchToolbar({
/>
) : (
<div className="flex min-w-0 shrink-0 items-center gap-1">
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
{showEnvironmentIndicator && availableEnvironments && (
<>
<BranchToolbarEnvironmentSelector
envLocked={envLocked}
environmentId={environmentId}
availableEnvironments={availableEnvironments}
onEnvironmentChange={onEnvironmentChange}
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
</>
@@ -422,17 +422,32 @@ export function BranchToolbarBranchSelector({
});
};
// Default the worktree base to the repo default branch (origin/HEAD), only
// falling back to the checked-out branch when no default is known.
const defaultBranchName = useMemo(
() => refs.find((refName) => refName.isDefault)?.name ?? null,
[refs],
);
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
? null
: (defaultBranchName ?? currentGitBranch);
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
activeWorktreePath ||
activeThreadBranch ||
!currentGitBranch
!worktreeBaseBranchCandidate
) {
return;
}
setThreadBranch(currentGitBranch, null);
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
setThreadBranch(worktreeBaseBranchCandidate, null);
}, [
activeThreadBranch,
activeWorktreePath,
effectiveEnvMode,
setThreadBranch,
worktreeBaseBranchCandidate,
]);
// ---------------------------------------------------------------------------
// Combobox / list plumbing
@@ -17,7 +17,9 @@ interface BranchToolbarEnvironmentSelectorProps {
envLocked: boolean;
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[];
onEnvironmentChange: (environmentId: EnvironmentId) => void;
// Absent when there is only one environment to show: the indicator still
// renders (as a static label) so remote projects are always identifiable.
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
}
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
@@ -39,7 +41,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
[availableEnvironments],
);
if (envLocked) {
if (envLocked || onEnvironmentChange === undefined) {
return (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeEnvironment?.isPrimary ? (
+95 -4
View File
@@ -9,7 +9,11 @@ import {
Minimize2Icon,
WrapTextIcon,
} from "lucide-react";
import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts";
import type {
ExecutionEnvironmentPlatformOs,
ScopedThreadRef,
ServerProviderSkill,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -74,6 +78,7 @@ import { serverEnvironment } from "../state/server";
import { assetEnvironment } from "../state/assets";
import { usePreparedConnection } from "../state/session";
import { previewEnvironment } from "../state/preview";
import { shellEnvironment } from "../state/shell";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
@@ -743,6 +748,8 @@ interface MarkdownFileLinkProps {
theme: "light" | "dark";
threadRef?: ScopedThreadRef | undefined;
onOpen: (targetPath: string) => Promise<AtomCommandResult<unknown, unknown>>;
onShowInFinder: (targetPath: string) => Promise<AtomCommandResult<unknown, unknown>>;
fileManagerLabel: string;
onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
className?: string | undefined;
}
@@ -751,6 +758,12 @@ const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)
const MARKDOWN_FILE_LINK_CLASS_NAME =
"chat-markdown-file-link cursor-pointer transition-colors hover:bg-accent/70";
function fileManagerLabelForPlatform(platform: ExecutionEnvironmentPlatformOs | undefined): string {
if (platform === "darwin") return "Show in Finder";
if (platform === "windows") return "Show in File Explorer";
return "Show in Files";
}
function pathParentSegments(path: string): string[] {
const normalized = path.replaceAll("\\", "/");
const segments = normalized.split("/").filter((segment) => segment.length > 0);
@@ -1022,6 +1035,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
theme,
threadRef,
onOpen,
onShowInFinder,
fileManagerLabel,
onOpenInBrowser,
className,
}: MarkdownFileLinkProps) {
@@ -1068,6 +1083,38 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath, line);
}, [handleOpenInEditor, line, threadRef, workspaceRelativePath]);
const handleShowInFinder = useCallback(() => {
void (async () => {
try {
const result = await onShowInFinder(iconPath);
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
reportMarkdownActionFailure(
{ operation: "show-file-in-finder", target: iconPath },
result.cause,
);
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: `Unable to ${fileManagerLabel.toLowerCase()}`,
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
} catch (cause) {
reportMarkdownActionFailure({ operation: "show-file-in-finder", target: iconPath }, cause);
toastManager.add(
stackedThreadToast({
type: "error",
title: `Unable to ${fileManagerLabel.toLowerCase()}`,
description: cause instanceof Error ? cause.message : "An error occurred.",
}),
);
}
})();
}, [fileManagerLabel, iconPath, onShowInFinder]);
const handleOpenInBrowser = useCallback(() => {
if (!onOpenInBrowser) {
return;
@@ -1162,6 +1209,10 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
: []),
{ id: "copy-relative", label: "Copy relative path" },
{ id: "copy-full", label: "Copy full path" },
{
id: "show-in-finder",
label: fileManagerLabel,
},
] as const,
{ x: event.clientX, y: event.clientY },
);
@@ -1180,6 +1231,10 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
}
if (clicked === "copy-full") {
handleCopy(targetPath, "Full path");
return;
}
if (clicked === "show-in-finder") {
handleShowInFinder();
}
} catch (cause) {
reportMarkdownActionFailure(
@@ -1188,7 +1243,16 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
);
}
},
[displayPath, handleCopy, handleOpenInBrowser, handleOpenInEditor, onOpenInBrowser, targetPath],
[
displayPath,
handleCopy,
handleOpenInBrowser,
handleOpenInEditor,
handleShowInFinder,
fileManagerLabel,
onOpenInBrowser,
targetPath,
],
);
return (
@@ -1242,6 +1306,8 @@ function areMarkdownFileLinkPropsEqual(
previous.theme === next.theme &&
previous.threadRef === next.threadRef &&
previous.onOpen === next.onOpen &&
previous.onShowInFinder === next.onShowInFinder &&
previous.fileManagerLabel === next.fileManagerLabel &&
previous.onOpenInBrowser === next.onOpenInBrowser &&
previous.className === next.className
);
@@ -1264,13 +1330,34 @@ function ChatMarkdown({
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const revealInFileManager = useAtomCommand(shellEnvironment.revealInFileManager, {
reportFailure: false,
});
const preparedConnection = usePreparedConnection(threadRef?.environmentId ?? null);
const environmentId = useActiveEnvironmentId();
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
const fileEnvironmentId = threadRef?.environmentId ?? environmentId;
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(fileEnvironmentId));
const openInPreferredEditor = useOpenInPreferredEditor(
environmentId,
fileEnvironmentId,
serverConfig?.availableEditors ?? [],
);
const showFileInFinder = useCallback(
(targetPath: string) => {
if (fileEnvironmentId === null) {
return Promise.resolve(
AsyncResult.failure<void, Error>(
Cause.fail(new Error("Cannot show the file because no environment is selected.")),
),
);
}
return revealInFileManager({
environmentId: fileEnvironmentId,
input: { path: targetPath },
});
},
[fileEnvironmentId, revealInFileManager],
);
const fileManagerLabel = fileManagerLabelForPlatform(serverConfig?.environment.platform.os);
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const markdownFileLinkMetaByHref = useMemo(() => {
const metaByHref = new Map<
@@ -1492,6 +1579,8 @@ function ChatMarkdown({
theme={resolvedTheme}
threadRef={threadRef}
onOpen={openInPreferredEditor}
onShowInFinder={showFileInFinder}
fileManagerLabel={fileManagerLabel}
onOpenInBrowser={
threadRef &&
isPreviewSupportedInRuntime() &&
@@ -1547,7 +1636,9 @@ function ChatMarkdown({
openInPreferredEditor,
openExternalLinkInPreview,
openMarkdownFileInPreview,
fileManagerLabel,
resolvedTheme,
showFileInFinder,
skills,
text,
threadRef,
+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}
+8 -12
View File
@@ -1159,6 +1159,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isSendBusy ||
isConnecting ||
projectSelectionRequired ||
environmentUnavailable !== null ||
!composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
@@ -1697,7 +1698,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
if (!isMobileViewport) return false;
if (isSendBusy || isConnecting || phase === "running") return false;
if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") {
return false;
}
if (activePendingProgress) {
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
}
@@ -1706,6 +1709,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activePendingProgress,
activePendingResolvedAnswers,
composerSendState.hasSendableContent,
environmentUnavailable,
isConnecting,
isMobileViewport,
isSendBusy,
@@ -1892,8 +1896,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
projectSelectionRequired
) {
return false;
}
@@ -2101,8 +2104,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isComposerApprovalState,
pendingUserInputs.length,
projectSelectionRequired,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
isComposerModelPickerOpen,
readComposerSnapshot,
@@ -2144,7 +2145,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className={cn(
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
onFocusCapture={(event) => {
@@ -2502,12 +2503,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
}
disabled={
isConnecting ||
isComposerApprovalState ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
}
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
/>
{showMobilePendingAnswerActions ? (
<div
@@ -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);
}
+4
View File
@@ -75,6 +75,7 @@ export interface AppModelOption {
shortName?: string;
subProvider?: string;
isCustom: boolean;
isDefault?: boolean;
}
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
@@ -85,6 +86,7 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
};
if (model.shortName) option.shortName = model.shortName;
if (model.subProvider) option.subProvider = model.subProvider;
if (model.isDefault) option.isDefault = true;
return option;
}
@@ -247,7 +249,9 @@ export function resolveAppModelSelectionForInstance(
const options = getAppModelOptionsForInstance(settings, entry);
return (
resolveSelectableModel(entry.driverKind, selectedModel, options) ??
options.find((option) => option.isDefault)?.slug ??
options[0]?.slug ??
entry.models.find((model) => model.isDefault)?.slug ??
entry.models[0]?.slug ??
null
);
+1
View File
@@ -92,6 +92,7 @@ export function getDefaultServerModel(
): string {
const models = getProviderModels(providers, provider);
return (
models.find((model) => model.isDefault && !model.isCustom)?.slug ??
models.find((model) => !model.isCustom)?.slug ??
models[0]?.slug ??
DEFAULT_MODEL_BY_PROVIDER[provider] ??
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
DEFAULT_MODEL,
EnvironmentId,
ProjectId,
CommandId,
@@ -139,7 +140,7 @@ describe("add project shared logic", () => {
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
instanceId: "codex",
model: "gpt-5.4",
model: DEFAULT_MODEL,
},
});
});
@@ -12,5 +12,9 @@ export function createShellEnvironmentAtoms<R, E>(
label: "environment-data:shell:open-in-editor",
tag: WS_METHODS.shellOpenInEditor,
}),
revealInFileManager: createEnvironmentRpcCommand(runtime, {
label: "environment-data:shell:reveal-in-file-manager",
tag: WS_METHODS.shellRevealInFileManager,
}),
};
}
+5
View File
@@ -50,6 +50,11 @@ export const LaunchEditorInput = Schema.Struct({
});
export type LaunchEditorInput = typeof LaunchEditorInput.Type;
export const RevealPathInput = Schema.Struct({
path: TrimmedNonEmptyString,
});
export type RevealPathInput = typeof RevealPathInput.Type;
export class ExternalLauncherUnknownEditorError extends Schema.TaggedErrorClass<ExternalLauncherUnknownEditorError>()(
"ExternalLauncherUnknownEditorError",
{
@@ -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",
+12 -2
View File
@@ -133,8 +133,18 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
export const DEFAULT_MODEL = "gpt-5.4";
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
export const DEFAULT_MODEL = "gpt-5.6-sol";
/**
* Codex default-model preference, most preferred first. The provider snapshot
* marks the first of these present in the live `model/list` response as
* default; when none are available, Codex's own `isDefault` flag wins.
*/
export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
"gpt-5.6-sol",
"gpt-5.6-terra",
];
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
+8 -1
View File
@@ -2,7 +2,7 @@ import * as Schema from "effect/Schema";
import * as Rpc from "effect/unstable/rpc/Rpc";
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
import { ExternalLauncherError, LaunchEditorInput } from "./editor.ts";
import { ExternalLauncherError, LaunchEditorInput, RevealPathInput } from "./editor.ts";
import {
AuthAccessStreamError,
AuthAccessStreamEvent,
@@ -156,6 +156,7 @@ export const WS_METHODS = {
// Shell methods
shellOpenInEditor: "shell.openInEditor",
shellRevealInFileManager: "shell.revealInFileManager",
// Filesystem methods
filesystemBrowse: "filesystem.browse",
@@ -390,6 +391,11 @@ export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),
});
export const WsShellRevealInFileManagerRpc = Rpc.make(WS_METHODS.shellRevealInFileManager, {
payload: RevealPathInput,
error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),
});
export const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {
payload: FilesystemBrowseInput,
success: FilesystemBrowseResult,
@@ -712,6 +718,7 @@ export const WsRpcGroup = RpcGroup.make(
WsProjectsSearchEntriesRpc,
WsProjectsWriteFileRpc,
WsShellOpenInEditorRpc,
WsShellRevealInFileManagerRpc,
WsFilesystemBrowseRpc,
WsAssetsCreateUrlRpc,
WsSubscribeVcsStatusRpc,
+1
View File
@@ -64,6 +64,7 @@ export const ServerProviderModel = Schema.Struct({
shortName: Schema.optional(TrimmedNonEmptyString),
subProvider: Schema.optional(TrimmedNonEmptyString),
isCustom: Schema.Boolean,
isDefault: Schema.optional(Schema.Boolean),
capabilities: Schema.NullOr(ModelCapabilities),
});
export type ServerProviderModel = typeof ServerProviderModel.Type;
+4 -4
View File
@@ -88,14 +88,14 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
});
describe("ServerSettings worktree defaults", () => {
it("defaults start-from-origin off for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(false);
it("defaults start-from-origin on for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
});
it("accepts start-from-origin updates", () => {
expect(
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
).toBe(true);
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
).toBe(false);
});
});
+1 -1
View File
@@ -382,7 +382,7 @@ export const ServerSettings = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.withDecodingDefault(Effect.succeed(true)),
),
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
textGenerationModelSelection: ModelSelection.pipe(
-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" },