Compare commits

...
Author SHA1 Message Date
Cursor Agent fc52f7f4cf Fix: move command palette open check before workspace command dispatch
Workspace commands (via isWorkspaceCommandId) and standalone terminal
commands were dispatched before the useCommandPaletteStore.getState().open
guard, causing shortcuts like Mod+W, Mod+[, Mod+] to fire while the
command palette dialog was open. Move the palette check to run immediately
after resolving the shortcut command, consistent with the guard pattern
in ChatView.tsx.
2026-04-15 00:53:04 +00:00
Julius Marminge 5c8504d602 Add composable workspace pane controls
- add workspace pane focus, split, resize, and zoom commands
- wire chat composer focus repair across workspace activation
- enable dragging threads into workspace surfaces
2026-04-14 17:47:30 -07:00
Julius Marminge d3d096c6f7 Refactor chat into composable workspace shell
- Add workspace document storage and store tests
- Route terminal and command-palette actions through workspace surfaces
- Update chat layout, sidebar, and thread terminal handling
2026-04-13 19:41:56 -07:00
28 changed files with 5526 additions and 503 deletions

No files matched your search

+15
View File
@@ -188,6 +188,21 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const),
);
assert.equal(defaultsByCommand.get("workspace.pane.splitRight"), "mod+d");
assert.equal(defaultsByCommand.get("workspace.pane.splitDown"), "mod+shift+d");
assert.equal(defaultsByCommand.get("workspace.pane.close"), "mod+w");
assert.equal(defaultsByCommand.get("workspace.focus.previous"), "mod+[");
assert.equal(defaultsByCommand.get("workspace.focus.next"), "mod+]");
assert.equal(defaultsByCommand.get("workspace.focus.left"), "mod+alt+arrowleft");
assert.equal(defaultsByCommand.get("workspace.focus.right"), "mod+alt+arrowright");
assert.equal(defaultsByCommand.get("workspace.focus.up"), "mod+alt+arrowup");
assert.equal(defaultsByCommand.get("workspace.focus.down"), "mod+alt+arrowdown");
assert.equal(defaultsByCommand.get("workspace.pane.toggleZoom"), "mod+shift+enter");
assert.equal(defaultsByCommand.get("workspace.pane.resizeLeft"), "mod+ctrl+arrowleft");
assert.equal(defaultsByCommand.get("workspace.pane.resizeRight"), "mod+ctrl+arrowright");
assert.equal(defaultsByCommand.get("workspace.pane.resizeUp"), "mod+ctrl+arrowup");
assert.equal(defaultsByCommand.get("workspace.pane.resizeDown"), "mod+ctrl+arrowdown");
assert.equal(defaultsByCommand.get("workspace.pane.equalize"), "mod+ctrl+=");
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
+16 -1
View File
@@ -60,7 +60,22 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+d", command: "workspace.pane.splitRight", when: "!terminalFocus" },
{ key: "mod+shift+d", command: "workspace.pane.splitDown", when: "!terminalFocus" },
{ key: "mod+w", command: "workspace.pane.close", when: "!terminalFocus" },
{ key: "mod+[", command: "workspace.focus.previous" },
{ key: "mod+]", command: "workspace.focus.next" },
{ key: "mod+alt+arrowup", command: "workspace.focus.up" },
{ key: "mod+alt+arrowdown", command: "workspace.focus.down" },
{ key: "mod+alt+arrowleft", command: "workspace.focus.left" },
{ key: "mod+alt+arrowright", command: "workspace.focus.right" },
{ key: "mod+shift+enter", command: "workspace.pane.toggleZoom" },
{ key: "mod+ctrl+arrowup", command: "workspace.pane.resizeUp" },
{ key: "mod+ctrl+arrowdown", command: "workspace.pane.resizeDown" },
{ key: "mod+ctrl+arrowleft", command: "workspace.pane.resizeLeft" },
{ key: "mod+ctrl+arrowright", command: "workspace.pane.resizeRight" },
{ key: "mod+ctrl+=", command: "workspace.pane.equalize" },
{ key: "mod+alt+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
@@ -77,4 +77,54 @@ describe("clientPersistenceStorage", () => {
],
});
});
it("reads and writes workspace documents as JSON blobs", async () => {
const testWindow = getTestWindow();
const {
WORKSPACE_DOCUMENT_STORAGE_KEY,
readBrowserWorkspaceDocument,
writeBrowserWorkspaceDocument,
} = await import("./clientPersistenceStorage");
const workspaceDocument = {
version: 1 as const,
layoutEngine: "split" as const,
rootNodeId: "node-1",
nodesById: {
"node-1": {
id: "node-1",
kind: "window" as const,
windowId: "window-1",
},
},
windowsById: {
"window-1": {
id: "window-1",
tabIds: ["surface-1"],
activeTabId: "surface-1",
},
},
surfacesById: {
"surface-1": {
id: "surface-1",
kind: "thread" as const,
input: {
scope: "server" as const,
threadRef: {
environmentId: testEnvironmentId,
threadId: "thread-1",
},
},
},
},
focusedWindowId: "window-1",
mobileActiveWindowId: "window-1",
};
writeBrowserWorkspaceDocument(workspaceDocument);
expect(readBrowserWorkspaceDocument<typeof workspaceDocument>()).toEqual(workspaceDocument);
expect(JSON.parse(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)!)).toEqual(
workspaceDocument,
);
});
});
+37
View File
@@ -11,6 +11,7 @@ import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorag
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
export const WORKSPACE_DOCUMENT_STORAGE_KEY = "t3code:workspace-document:v1";
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
environmentId: EnvironmentId,
@@ -34,6 +35,34 @@ function hasWindow(): boolean {
return typeof window !== "undefined";
}
function readBrowserJsonDocument<T>(storageKey: string): T | null {
if (!hasWindow()) {
return null;
}
try {
const raw = window.localStorage.getItem(storageKey);
if (!raw) {
return null;
}
return JSON.parse(raw) as T;
} catch {
return null;
}
}
function writeBrowserJsonDocument<T>(storageKey: string, document: T): void {
if (!hasWindow()) {
return;
}
try {
window.localStorage.setItem(storageKey, JSON.stringify(document));
} catch {
// Ignore quota/storage errors to avoid breaking the app.
}
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
@@ -192,3 +221,11 @@ export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentId
}),
});
}
export function readBrowserWorkspaceDocument<T>(): T | null {
return readBrowserJsonDocument<T>(WORKSPACE_DOCUMENT_STORAGE_KEY);
}
export function writeBrowserWorkspaceDocument<T>(document: T): void {
writeBrowserJsonDocument(WORKSPACE_DOCUMENT_STORAGE_KEY, document);
}
+16 -2
View File
@@ -1,13 +1,27 @@
import { create } from "zustand";
export interface CommandPaletteWorkspaceTarget {
disposition: "split-right" | "split-down";
}
interface CommandPaletteStore {
open: boolean;
workspaceTarget: CommandPaletteWorkspaceTarget | null;
setOpen: (open: boolean) => void;
toggleOpen: () => void;
openWorkspaceTarget: (target: CommandPaletteWorkspaceTarget) => void;
clearWorkspaceTarget: () => void;
}
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
open: false,
setOpen: (open) => set({ open }),
toggleOpen: () => set((state) => ({ open: !state.open })),
workspaceTarget: null,
setOpen: (open) => set({ open, ...(open ? {} : { workspaceTarget: null }) }),
toggleOpen: () =>
set((state) => ({
open: !state.open,
...(!state.open ? {} : { workspaceTarget: null }),
})),
openWorkspaceTarget: (target) => set({ open: true, workspaceTarget: target }),
clearWorkspaceTarget: () => set({ workspaceTarget: null }),
}));
+101 -380
View File
@@ -19,17 +19,12 @@ import {
RuntimeMode,
TerminalOpenInput,
} from "@t3tools/contracts";
import {
parseScopedThreadKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
import { scopedThreadKey, scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { Debouncer } from "@tanstack/react-pacer";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import { useGitStatus } from "~/lib/gitStatusState";
@@ -66,11 +61,7 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import {
selectProjectsAcrossEnvironments,
selectThreadsAcrossEnvironments,
useStore,
} from "../store";
import { selectProjectsAcrossEnvironments, useStore } from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
@@ -89,13 +80,16 @@ import {
type TurnDiffSummary,
} from "../types";
import { useTheme } from "../hooks/useTheme";
import {
isWorkspaceCommandId,
useWorkspaceCommandExecutor,
} from "../hooks/useWorkspaceCommandExecutor";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon } from "lucide-react";
import { cn, randomUUID } from "~/lib/utils";
import { toastManager } from "./ui/toast";
@@ -127,7 +121,6 @@ import {
appendTerminalContextsToPrompt,
formatTerminalContextLabel,
type TerminalContextDraft,
type TerminalContextSelection,
} from "../lib/terminalContext";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
@@ -141,7 +134,6 @@ import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./Branch
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
collectUserMessageBlobPreviewUrls,
@@ -171,6 +163,7 @@ import {
} from "~/rpc/serverState";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { retainThreadDetailSubscription } from "../environments/runtime/service";
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -312,6 +305,8 @@ const SCRIPT_TERMINAL_ROWS = 30;
type ChatViewProps =
| {
activationFocusRequestId?: number;
bindSharedComposerHandle?: boolean;
environmentId: EnvironmentId;
threadId: ThreadId;
onDiffPanelOpen?: () => void;
@@ -320,6 +315,8 @@ type ChatViewProps =
draftId?: never;
}
| {
activationFocusRequestId?: number;
bindSharedComposerHandle?: boolean;
environmentId: EnvironmentId;
threadId: ThreadId;
onDiffPanelOpen?: () => void;
@@ -328,14 +325,6 @@ type ChatViewProps =
draftId: DraftId;
};
interface TerminalLaunchContext {
threadId: ThreadId;
cwd: string;
worktreePath: string | null;
}
type PersistentTerminalLaunchContext = Pick<TerminalLaunchContext, "cwd" | "worktreePath">;
function useLocalDispatchState(input: {
activeThread: Thread | undefined;
activeLatestTurn: Thread["latestTurn"] | null;
@@ -403,181 +392,10 @@ function useLocalDispatchState(input: {
};
}
interface PersistentThreadTerminalDrawerProps {
threadRef: { environmentId: EnvironmentId; threadId: ThreadId };
threadId: ThreadId;
visible: boolean;
launchContext: PersistentTerminalLaunchContext | null;
focusRequestId: number;
splitShortcutLabel: string | undefined;
newShortcutLabel: string | undefined;
closeShortcutLabel: string | undefined;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
}
const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDrawer({
threadRef,
threadId,
visible,
launchContext,
focusRequestId,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onAddTerminalContext,
}: PersistentThreadTerminalDrawerProps) {
const serverThread = useStore(useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]));
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
const projectRef = serverThread
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
: draftThread
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
: null;
const project = useStore(useMemo(() => createProjectSelectorByRef(projectRef), [projectRef]));
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadKey, threadRef),
);
const storeSetTerminalHeight = useTerminalStateStore((state) => state.setTerminalHeight);
const storeSplitTerminal = useTerminalStateStore((state) => state.splitTerminal);
const storeNewTerminal = useTerminalStateStore((state) => state.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((state) => state.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal);
const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const effectiveWorktreePath = useMemo(() => {
if (launchContext !== null) {
return launchContext.worktreePath;
}
return worktreePath;
}, [launchContext, worktreePath]);
const cwd = useMemo(
() =>
launchContext?.cwd ??
(project
? projectScriptCwd({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: null),
[effectiveWorktreePath, launchContext?.cwd, project],
);
const runtimeEnv = useMemo(
() =>
project
? projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: {},
[effectiveWorktreePath, project],
);
const bumpFocusRequestId = useCallback(() => {
if (!visible) {
return;
}
setLocalFocusRequestId((value) => value + 1);
}, [visible]);
const setTerminalHeight = useCallback(
(height: number) => {
storeSetTerminalHeight(threadRef, height);
},
[storeSetTerminalHeight, threadRef],
);
const splitTerminal = useCallback(() => {
storeSplitTerminal(threadRef, `terminal-${randomUUID()}`);
bumpFocusRequestId();
}, [bumpFocusRequestId, storeSplitTerminal, threadRef]);
const createNewTerminal = useCallback(() => {
storeNewTerminal(threadRef, `terminal-${randomUUID()}`);
bumpFocusRequestId();
}, [bumpFocusRequestId, storeNewTerminal, threadRef]);
const activateTerminal = useCallback(
(terminalId: string) => {
storeSetActiveTerminal(threadRef, terminalId);
bumpFocusRequestId();
},
[bumpFocusRequestId, storeSetActiveTerminal, threadRef],
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readEnvironmentApi(threadRef.environmentId);
if (!api) return;
const isFinalTerminal = terminalState.terminalIds.length <= 1;
const fallbackExitWrite = () =>
api.terminal.write({ threadId, terminalId, data: "exit\n" }).catch(() => undefined);
if ("close" in api.terminal && typeof api.terminal.close === "function") {
void (async () => {
if (isFinalTerminal) {
await api.terminal.clear({ threadId, terminalId }).catch(() => undefined);
}
await api.terminal.close({
threadId,
terminalId,
deleteHistory: true,
});
})().catch(() => fallbackExitWrite());
} else {
void fallbackExitWrite();
}
storeCloseTerminal(threadRef, terminalId);
bumpFocusRequestId();
},
[bumpFocusRequestId, storeCloseTerminal, terminalState.terminalIds.length, threadId, threadRef],
);
const handleAddTerminalContext = useCallback(
(selection: TerminalContextSelection) => {
if (!visible) {
return;
}
onAddTerminalContext(selection);
},
[onAddTerminalContext, visible],
);
if (!project || !terminalState.terminalOpen || !cwd) {
return null;
}
return (
<div className={visible ? undefined : "hidden"}>
<ThreadTerminalDrawer
threadRef={threadRef}
threadId={threadId}
cwd={cwd}
worktreePath={effectiveWorktreePath}
runtimeEnv={runtimeEnv}
visible={visible}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={visible ? splitShortcutLabel : undefined}
newShortcutLabel={visible ? newShortcutLabel : undefined}
closeShortcutLabel={visible ? closeShortcutLabel : undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={setTerminalHeight}
onAddTerminalContext={handleAddTerminalContext}
/>
</div>
);
});
export default function ChatView(props: ChatViewProps) {
const {
activationFocusRequestId,
bindSharedComposerHandle = true,
environmentId,
threadId,
routeKind,
@@ -654,7 +472,8 @@ export default function ChatView(props: ChatViewProps) {
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const localComposerRef = useRef<ChatComposerHandle | null>(null);
const composerRef = useComposerHandleContext() ?? localComposerRef;
const sharedComposerRef = useComposerHandleContext();
const composerRef = localComposerRef;
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
@@ -681,11 +500,9 @@ export default function ChatView(props: ChatViewProps) {
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
const planSidebarOpenOnNextThreadRef = useRef(false);
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [nowTick, setNowTick] = useState(() => Date.now());
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [terminalLaunchContext, setTerminalLaunchContext] = useState<TerminalLaunchContext | null>(
null,
);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -704,51 +521,40 @@ export default function ChatView(props: ChatViewProps) {
const sendInFlightRef = useRef(false);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
useLayoutEffect(() => {
if (!sharedComposerRef) {
return;
}
const localComposerHandle = localComposerRef.current;
if (bindSharedComposerHandle) {
sharedComposerRef.current = localComposerHandle;
return () => {
if (sharedComposerRef.current === localComposerHandle) {
sharedComposerRef.current = null;
}
};
}
if (sharedComposerRef.current === localComposerHandle) {
sharedComposerRef.current = null;
}
});
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef),
);
const openTerminalThreadKeys = useTerminalStateStore(
useShallow((state) =>
Object.entries(state.terminalStateByThreadKey).flatMap(([nextThreadKey, nextTerminalState]) =>
nextTerminalState.terminalOpen ? [nextThreadKey] : [],
),
),
);
const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen);
const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal);
const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
const serverThreadKeys = useStore(
useShallow((state) =>
selectThreadsAcrossEnvironments(state).map((thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
),
),
);
const storeSetTerminalLaunchContext = useTerminalStateStore((s) => s.setTerminalLaunchContext);
const storeServerTerminalLaunchContext = useTerminalStateStore(
(s) => s.terminalLaunchContextByThreadKey[scopedThreadKey(routeThreadRef)] ?? null,
);
const storeClearTerminalLaunchContext = useTerminalStateStore(
(s) => s.clearTerminalLaunchContext,
);
const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);
const draftThreadKeys = useMemo(
() =>
Object.values(draftThreadsByThreadKey).map((draftThread) =>
scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)),
),
[draftThreadsByThreadKey],
);
const [mountedTerminalThreadKeys, setMountedTerminalThreadKeys] = useState<string[]>([]);
const mountedTerminalThreadRefs = useMemo(
() =>
mountedTerminalThreadKeys.flatMap((mountedThreadKey) => {
const mountedThreadRef = parseScopedThreadKey(mountedThreadKey);
return mountedThreadRef ? [{ key: mountedThreadKey, threadRef: mountedThreadRef }] : [];
}),
[mountedTerminalThreadKeys],
);
const fallbackDraftProjectRef = draftThread
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
@@ -789,10 +595,16 @@ export default function ChatView(props: ChatViewProps) {
[activeThread],
);
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
const existingOpenTerminalThreadKeys = useMemo(() => {
const existingThreadKeys = new Set<string>([...serverThreadKeys, ...draftThreadKeys]);
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
const terminalSurfaceOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
const ensureTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.ensureTerminalSurfaceForThread,
);
const toggleTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.toggleTerminalSurfaceForThread,
);
const closeTerminalSurfacesForThread = useWorkspaceStore(
(state) => state.closeTerminalSurfacesForThread,
);
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
@@ -807,21 +619,6 @@ export default function ChatView(props: ChatViewProps) {
return threadIds;
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
);
useEffect(() => {
setMountedTerminalThreadKeys((currentThreadIds) => {
const nextThreadIds = reconcileMountedTerminalThreadIds({
currentThreadIds,
openThreadIds: existingOpenTerminalThreadKeys,
activeThreadId: activeThreadKey,
activeThreadTerminalOpen: Boolean(activeThreadKey && terminalState.terminalOpen),
maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
});
return currentThreadIds.length === nextThreadIds.length &&
currentThreadIds.every((nextThreadId, index) => nextThreadId === nextThreadIds[index])
? currentThreadIds
: nextThreadIds;
});
}, [activeThreadKey, existingOpenTerminalThreadKeys, terminalState.terminalOpen]);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProjectRef = activeThread
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
@@ -1403,6 +1200,7 @@ export default function ChatView(props: ChatViewProps) {
const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd });
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const { executeWorkspaceCommand } = useWorkspaceCommandExecutor();
const activeProviderStatus = useMemo(
() => providerStatuses.find((status) => status.provider === selectedProvider) ?? null,
[selectedProvider, providerStatuses],
@@ -1410,46 +1208,21 @@ export default function ChatView(props: ChatViewProps) {
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
const activeTerminalLaunchContext =
terminalLaunchContext?.threadId === activeThreadId
? terminalLaunchContext
: (storeServerTerminalLaunchContext ?? null);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
terminalFocus: true,
terminalOpen: Boolean(terminalState.terminalOpen),
},
}),
[terminalState.terminalOpen],
);
const nonTerminalShortcutLabelOptions = useMemo(
() => ({
context: {
terminalFocus: false,
terminalOpen: Boolean(terminalState.terminalOpen),
terminalOpen: terminalSurfaceOpen,
},
}),
[terminalState.terminalOpen],
[terminalSurfaceOpen],
);
const terminalToggleShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.toggle"),
[keybindings],
);
const splitTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const newTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const closeTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const diffPanelShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "diff.toggle", nonTerminalShortcutLabelOptions),
[keybindings, nonTerminalShortcutLabelOptions],
@@ -1543,32 +1316,22 @@ export default function ChatView(props: ChatViewProps) {
focusComposer();
});
}, [focusComposer]);
const addTerminalContextToDraft = useCallback((selection: TerminalContextSelection) => {
composerRef.current?.addTerminalContext(selection);
}, []);
const setTerminalOpen = useCallback(
(open: boolean) => {
if (!activeThreadRef) return;
storeSetTerminalOpen(activeThreadRef, open);
},
[activeThreadRef, storeSetTerminalOpen],
);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadRef) return;
setTerminalOpen(!terminalState.terminalOpen);
}, [activeThreadRef, setTerminalOpen, terminalState.terminalOpen]);
toggleTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, toggleTerminalSurfaceForThread]);
const splitTerminal = useCallback(() => {
if (!activeThreadRef || hasReachedSplitLimit) return;
const terminalId = `terminal-${randomUUID()}`;
storeSplitTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadRef, hasReachedSplitLimit, storeSplitTerminal]);
ensureTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, ensureTerminalSurfaceForThread, hasReachedSplitLimit, storeSplitTerminal]);
const createNewTerminal = useCallback(() => {
if (!activeThreadRef) return;
const terminalId = `terminal-${randomUUID()}`;
storeNewTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadRef, storeNewTerminal]);
ensureTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, ensureTerminalSurfaceForThread, storeNewTerminal]);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readEnvironmentApi(environmentId);
@@ -1596,12 +1359,15 @@ export default function ChatView(props: ChatViewProps) {
}
if (activeThreadRef) {
storeCloseTerminal(activeThreadRef, terminalId);
if (isFinalTerminal) {
closeTerminalSurfacesForThread(activeThreadRef);
}
}
setTerminalFocusRequestId((value) => value + 1);
},
[
activeThreadId,
activeThreadRef,
closeTerminalSurfacesForThread,
environmentId,
storeCloseTerminal,
terminalState.terminalIds.length,
@@ -1639,21 +1405,19 @@ export default function ChatView(props: ChatViewProps) {
: baseTerminalId;
const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
setTerminalLaunchContext({
threadId: activeThreadId,
cwd: targetCwd,
worktreePath: targetWorktreePath,
});
setTerminalOpen(true);
if (!activeThreadRef) {
return;
}
storeSetTerminalLaunchContext(activeThreadRef, {
cwd: targetCwd,
worktreePath: targetWorktreePath,
});
ensureTerminalSurfaceForThread(activeThreadRef);
if (shouldCreateNewTerminal) {
storeNewTerminal(activeThreadRef, targetTerminalId);
} else {
storeSetActiveTerminal(activeThreadRef, targetTerminalId);
}
setTerminalFocusRequestId((value) => value + 1);
const runtimeEnv = projectScriptRuntimeEnv({
project: {
@@ -1699,10 +1463,11 @@ export default function ChatView(props: ChatViewProps) {
activeThread,
activeThreadId,
activeThreadRef,
ensureTerminalSurfaceForThread,
gitCwd,
setTerminalOpen,
setThreadError,
storeNewTerminal,
storeSetTerminalLaunchContext,
storeSetActiveTerminal,
setLastInvokedScriptByProjectId,
environmentId,
@@ -1994,14 +1759,21 @@ export default function ChatView(props: ChatViewProps) {
}, [activeThread?.id]);
useEffect(() => {
if (!activeThread?.id || terminalState.terminalOpen) return;
if (!activeThread?.id || terminalSurfaceOpen) return;
const frame = window.requestAnimationFrame(() => {
focusComposer();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [activeThread?.id, focusComposer, terminalState.terminalOpen]);
}, [activeThread?.id, focusComposer, terminalSurfaceOpen]);
useLayoutEffect(() => {
if (activationFocusRequestId === undefined) {
return;
}
focusComposer();
}, [activationFocusRequestId, focusComposer]);
useEffect(() => {
if (!activeThread?.id) return;
@@ -2086,48 +1858,11 @@ export default function ChatView(props: ChatViewProps) {
useEffect(() => {
if (!activeThreadId) {
setTerminalLaunchContext(null);
storeClearTerminalLaunchContext(routeThreadRef);
return;
}
setTerminalLaunchContext((current) => {
if (!current) return current;
if (current.threadId === activeThreadId) return current;
return null;
});
}, [activeThreadId, routeThreadRef, storeClearTerminalLaunchContext]);
useEffect(() => {
if (!activeThreadId || !activeProjectCwd) {
return;
}
setTerminalLaunchContext((current) => {
if (!current || current.threadId !== activeThreadId) {
return current;
}
const settledCwd = projectScriptCwd({
project: { cwd: activeProjectCwd },
worktreePath: activeThreadWorktreePath,
});
if (
settledCwd === current.cwd &&
(activeThreadWorktreePath ?? null) === current.worktreePath
) {
if (activeThreadRef) {
storeClearTerminalLaunchContext(activeThreadRef);
}
return null;
}
return current;
});
}, [
activeProjectCwd,
activeThreadId,
activeThreadRef,
activeThreadWorktreePath,
storeClearTerminalLaunchContext,
]);
useEffect(() => {
if (!activeThreadId || !activeProjectCwd || !storeServerTerminalLaunchContext) {
return;
@@ -2154,28 +1889,21 @@ export default function ChatView(props: ChatViewProps) {
]);
useEffect(() => {
if (terminalState.terminalOpen) {
if (terminalSurfaceOpen) {
return;
}
if (activeThreadRef) {
storeClearTerminalLaunchContext(activeThreadRef);
}
setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current));
}, [
activeThreadId,
activeThreadRef,
storeClearTerminalLaunchContext,
terminalState.terminalOpen,
]);
}, [activeThreadRef, storeClearTerminalLaunchContext, terminalSurfaceOpen]);
useEffect(() => {
if (!activeThreadKey) return;
const previous = terminalOpenByThreadRef.current[activeThreadKey] ?? false;
const current = Boolean(terminalState.terminalOpen);
const current = terminalSurfaceOpen;
if (!previous && current) {
terminalOpenByThreadRef.current[activeThreadKey] = current;
setTerminalFocusRequestId((value) => value + 1);
return;
} else if (previous && !current) {
terminalOpenByThreadRef.current[activeThreadKey] = current;
@@ -2188,7 +1916,7 @@ export default function ChatView(props: ChatViewProps) {
}
terminalOpenByThreadRef.current[activeThreadKey] = current;
}, [activeThreadKey, focusComposer, terminalState.terminalOpen]);
}, [activeThreadKey, focusComposer, terminalSurfaceOpen]);
useEffect(() => {
const handler = (event: globalThis.KeyboardEvent) => {
@@ -2197,7 +1925,7 @@ export default function ChatView(props: ChatViewProps) {
}
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(terminalState.terminalOpen),
terminalOpen: terminalSurfaceOpen,
};
const command = resolveShortcutCommand(event, keybindings, {
@@ -2205,6 +1933,13 @@ export default function ChatView(props: ChatViewProps) {
});
if (!command) return;
if (isWorkspaceCommandId(command)) {
event.preventDefault();
event.stopPropagation();
void executeWorkspaceCommand(command);
return;
}
if (command === "terminal.toggle") {
event.preventDefault();
event.stopPropagation();
@@ -2215,8 +1950,8 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
if (!terminalSurfaceOpen && activeThreadRef) {
ensureTerminalSurfaceForThread(activeThreadRef);
}
splitTerminal();
return;
@@ -2225,7 +1960,7 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) return;
if (!terminalSurfaceOpen) return;
closeTerminal(terminalState.activeTerminalId);
return;
}
@@ -2233,8 +1968,8 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.new") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
if (!terminalSurfaceOpen && activeThreadRef) {
ensureTerminalSurfaceForThread(activeThreadRef);
}
createNewTerminal();
return;
@@ -2259,16 +1994,18 @@ export default function ChatView(props: ChatViewProps) {
return () => window.removeEventListener("keydown", handler);
}, [
activeProject,
terminalState.terminalOpen,
terminalState.activeTerminalId,
activeThreadRef,
activeThreadId,
closeTerminal,
createNewTerminal,
setTerminalOpen,
executeWorkspaceCommand,
ensureTerminalSurfaceForThread,
runProjectScript,
splitTerminal,
keybindings,
onToggleDiff,
terminalSurfaceOpen,
toggleTerminalVisibility,
]);
@@ -3171,7 +2908,7 @@ export default function ChatView(props: ChatViewProps) {
}
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
<div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
{/* Top bar */}
<header
className={cn(
@@ -3200,7 +2937,7 @@ export default function ChatView(props: ChatViewProps) {
keybindings={keybindings}
availableEditors={availableEditors}
terminalAvailable={activeProject !== undefined}
terminalOpen={terminalState.terminalOpen}
terminalOpen={terminalSurfaceOpen}
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
diffToggleShortcutLabel={diffPanelShortcutLabel}
gitCwd={gitCwd}
@@ -3271,6 +3008,7 @@ export default function ChatView(props: ChatViewProps) {
<div className={cn("px-3 pt-1.5 sm:px-5 sm:pt-2", isGitRepo ? "pb-1" : "pb-3 sm:pb-4")}>
<ChatComposer
ref={composerRef}
{...(activationFocusRequestId === undefined ? {} : { activationFocusRequestId })}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
@@ -3403,23 +3141,6 @@ export default function ChatView(props: ChatViewProps) {
</div>
{/* end horizontal flex container */}
{mountedTerminalThreadRefs.map(({ key: mountedThreadKey, threadRef: mountedThreadRef }) => (
<PersistentThreadTerminalDrawer
key={mountedThreadKey}
threadRef={mountedThreadRef}
threadId={mountedThreadRef.threadId}
visible={mountedThreadKey === activeThreadKey && terminalState.terminalOpen}
launchContext={
mountedThreadKey === activeThreadKey ? (activeTerminalLaunchContext ?? null) : null
}
focusRequestId={mountedThreadKey === activeThreadKey ? terminalFocusRequestId : 0}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onAddTerminalContext={addTerminalContextToDraft}
/>
))}
{expandedImage && (
<ExpandedImageDialog preview={expandedImage} onClose={closeExpandedImage} />
)}
+409 -14
View File
@@ -6,10 +6,15 @@ import { useNavigate, useParams } from "@tanstack/react-router";
import {
ArrowDownIcon,
ArrowLeftIcon,
ArrowRightIcon,
ArrowUpIcon,
Columns2Icon,
MessageSquareIcon,
Rows2Icon,
SettingsIcon,
SquarePenIcon,
TerminalSquareIcon,
XIcon,
} from "lucide-react";
import {
useDeferredValue,
@@ -23,6 +28,10 @@ import {
import { useShallow } from "zustand/react/shallow";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import {
WORKSPACE_COMMAND_METADATA,
useWorkspaceCommandExecutor,
} from "../hooks/useWorkspaceCommandExecutor";
import { useSettings } from "../hooks/useSettings";
import {
startNewThreadInProjectFromContext,
@@ -36,8 +45,9 @@ import {
selectSidebarThreadsAcrossEnvironments,
useStore,
} from "../store";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
import { serverThreadSurfaceInput } from "../workspace/types";
import {
ADDON_ICON_CLASS,
buildProjectActionItems,
@@ -80,11 +90,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
select: (params) => resolveThreadRouteTarget(params),
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const terminalOpen = useTerminalStateStore((state) =>
routeThreadRef
? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
const terminalOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
@@ -108,8 +114,8 @@ export function CommandPalette({ children }: { children: ReactNode }) {
return (
<ComposerHandleContext.Provider value={composerHandleRef}>
{children}
<CommandDialog open={open} onOpenChange={setOpen}>
{children}
<CommandPaletteDialog />
</CommandDialog>
</ComposerHandleContext.Provider>
@@ -136,6 +142,8 @@ function CommandPaletteDialog() {
function OpenCommandPaletteDialog() {
const navigate = useNavigate();
const setOpen = useCommandPaletteStore((store) => store.setOpen);
const workspaceTarget = useCommandPaletteStore((store) => store.workspaceTarget);
const clearWorkspaceTarget = useCommandPaletteStore((store) => store.clearWorkspaceTarget);
const composerHandleRef = useComposerHandleContext();
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
@@ -149,6 +157,13 @@ function OpenCommandPaletteDialog() {
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
const currentView = viewStack.at(-1) ?? null;
const paletteMode = getCommandPaletteMode({ currentView });
const { canOpenTerminalSurface, canSplitFocusedPane, executeWorkspaceCommand } =
useWorkspaceCommandExecutor();
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const workspaceWindowCount = useWorkspaceStore(
(state) => Object.keys(state.document.windowsById).length,
);
const canUseSpatialWorkspaceCommands = workspaceWindowCount > 1;
const projectTitleById = useMemo(
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
@@ -258,6 +273,40 @@ function OpenCommandPaletteDialog() {
[activeThreadId, navigate, projectTitleById, settings.sidebarThreadSortOrder, threads],
);
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
const workspaceTargetThreadItems = useMemo(() => {
if (!workspaceTarget) {
return [];
}
return buildThreadActionItems({
threads,
...(activeThreadId ? { activeThreadId } : {}),
projectTitleById,
sortOrder: settings.sidebarThreadSortOrder,
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
runThread: async (thread) => {
openThreadSurface(
serverThreadSurfaceInput(scopeThreadRef(thread.environmentId, thread.id)),
workspaceTarget.disposition,
);
},
});
}, [
activeThreadId,
openThreadSurface,
projectTitleById,
settings.sidebarThreadSortOrder,
threads,
workspaceTarget,
]);
useEffect(() => {
if (!workspaceTarget) {
return;
}
setViewStack([]);
setQuery("");
}, [workspaceTarget]);
function pushView(item: CommandPaletteSubmenuItem): void {
setViewStack((previousViews) => [
@@ -276,6 +325,15 @@ function OpenCommandPaletteDialog() {
setQuery("");
}
function leaveSubmenu(): void {
if (currentView) {
popView();
return;
}
clearWorkspaceTarget();
setQuery("");
}
function handleQueryChange(nextQuery: string): void {
setQuery(nextQuery);
if (nextQuery === "" && currentView?.initialQuery) {
@@ -325,6 +383,301 @@ function OpenCommandPaletteDialog() {
});
}
if (canOpenTerminalSurface) {
actionItems.push({
kind: "action",
value: "action:workspace-terminal-split-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitRight"].title,
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.terminal.splitRight",
run: async () => {
await executeWorkspaceCommand("workspace.terminal.splitRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-terminal-split-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitDown"].title,
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.terminal.splitDown",
run: async () => {
await executeWorkspaceCommand("workspace.terminal.splitDown");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-terminal-tab",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.newTab"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.newTab"].title,
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.terminal.newTab",
run: async () => {
await executeWorkspaceCommand("workspace.terminal.newTab");
},
});
}
if (canSplitFocusedPane) {
actionItems.push({
kind: "action",
value: "action:workspace-pane-split-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.splitRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.splitRight"].title,
icon: <Columns2Icon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.splitRight",
run: async () => {
await executeWorkspaceCommand("workspace.pane.splitRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-split-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.splitDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.splitDown"].title,
icon: <Rows2Icon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.splitDown",
run: async () => {
await executeWorkspaceCommand("workspace.pane.splitDown");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-close",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.close"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.close"].title,
icon: <XIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.close",
run: async () => {
await executeWorkspaceCommand("workspace.pane.close");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-toggle-zoom",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.toggleZoom"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.toggleZoom"].title,
icon: <Columns2Icon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.toggleZoom",
run: async () => {
await executeWorkspaceCommand("workspace.pane.toggleZoom");
},
});
}
if (canUseSpatialWorkspaceCommands) {
actionItems.push({
kind: "action",
value: "action:workspace-focus-previous",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.previous"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.focus.previous"].title,
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.focus.previous",
run: async () => {
await executeWorkspaceCommand("workspace.focus.previous");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-focus-next",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.next"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.focus.next"].title,
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.focus.next",
run: async () => {
await executeWorkspaceCommand("workspace.focus.next");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-focus-left",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.left"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.focus.left"].title,
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.focus.left",
run: async () => {
await executeWorkspaceCommand("workspace.focus.left");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-focus-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.right"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.focus.right"].title,
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.focus.right",
run: async () => {
await executeWorkspaceCommand("workspace.focus.right");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-focus-up",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.up"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.focus.up"].title,
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.focus.up",
run: async () => {
await executeWorkspaceCommand("workspace.focus.up");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-focus-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.focus.down"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.focus.down"].title,
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.focus.down",
run: async () => {
await executeWorkspaceCommand("workspace.focus.down");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-resize-left",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeLeft"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeLeft"].title,
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.resizeLeft",
run: async () => {
await executeWorkspaceCommand("workspace.pane.resizeLeft");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-resize-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeRight"].title,
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.resizeRight",
run: async () => {
await executeWorkspaceCommand("workspace.pane.resizeRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-resize-up",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeUp"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeUp"].title,
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.resizeUp",
run: async () => {
await executeWorkspaceCommand("workspace.pane.resizeUp");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-resize-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.resizeDown"].title,
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.resizeDown",
run: async () => {
await executeWorkspaceCommand("workspace.pane.resizeDown");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-equalize",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.equalize"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.equalize"].title,
icon: <Rows2Icon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.equalize",
run: async () => {
await executeWorkspaceCommand("workspace.pane.equalize");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-move-left",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveLeft"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveLeft"].title,
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.moveLeft",
run: async () => {
await executeWorkspaceCommand("workspace.pane.moveLeft");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-move-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveRight"].title,
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.moveRight",
run: async () => {
await executeWorkspaceCommand("workspace.pane.moveRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-move-up",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveUp"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveUp"].title,
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.moveUp",
run: async () => {
await executeWorkspaceCommand("workspace.pane.moveUp");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-move-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveDown"].title,
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.moveDown",
run: async () => {
await executeWorkspaceCommand("workspace.pane.moveDown");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-tab-move-left",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveLeft"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveLeft"].title,
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.tab.moveLeft",
run: async () => {
await executeWorkspaceCommand("workspace.tab.moveLeft");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-tab-move-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveRight"].title,
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.tab.moveRight",
run: async () => {
await executeWorkspaceCommand("workspace.tab.moveRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-tab-move-up",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveUp"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveUp"].title,
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.tab.moveUp",
run: async () => {
await executeWorkspaceCommand("workspace.tab.moveUp");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-tab-move-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveDown"].title,
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.tab.moveDown",
run: async () => {
await executeWorkspaceCommand("workspace.tab.moveDown");
},
});
}
actionItems.push({
kind: "action",
value: "action:settings",
@@ -337,23 +690,65 @@ function OpenCommandPaletteDialog() {
});
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
const activeGroups = currentView ? currentView.groups : rootGroups;
const workspaceTargetGroups = useMemo(() => {
if (!workspaceTarget) {
return [];
}
const items: CommandPaletteActionItem[] = [];
if (canOpenTerminalSurface) {
const targetCommand =
workspaceTarget.disposition === "split-right"
? "workspace.terminal.splitRight"
: "workspace.terminal.splitDown";
items.push({
kind: "action",
value: `action:workspace-target:${targetCommand}`,
searchTerms: WORKSPACE_COMMAND_METADATA[targetCommand].searchTerms,
title: WORKSPACE_COMMAND_METADATA[targetCommand].title,
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: targetCommand,
run: async () => {
await executeWorkspaceCommand(targetCommand);
},
});
}
return [
...(items.length > 0 ? [{ value: "actions", label: "Actions", items }] : []),
...(workspaceTargetThreadItems.length > 0
? [{ value: "threads", label: "Threads", items: workspaceTargetThreadItems }]
: []),
];
}, [
canOpenTerminalSurface,
executeWorkspaceCommand,
workspaceTarget,
workspaceTargetThreadItems,
]);
const activeGroups = currentView
? currentView.groups
: workspaceTarget
? workspaceTargetGroups
: rootGroups;
const displayedGroups = filterCommandPaletteGroups({
activeGroups,
query: deferredQuery,
isInSubmenu: currentView !== null,
isInSubmenu: currentView !== null || workspaceTarget !== null,
projectSearchItems: projectSearchItems,
threadSearchItems: allThreadItems,
});
const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
const isSubmenu = paletteMode === "submenu";
const isSubmenu = paletteMode === "submenu" || workspaceTarget !== null;
const inputPlaceholder = workspaceTarget
? "Open in split..."
: getCommandPaletteInputPlaceholder(paletteMode);
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
if (event.key === "Backspace" && query === "" && isSubmenu) {
event.preventDefault();
popView();
leaveSubmenu();
}
}
@@ -387,7 +782,7 @@ function OpenCommandPaletteDialog() {
}}
>
<Command
key={viewStack.length}
key={`${viewStack.length}-${workspaceTarget?.disposition ?? "root"}`}
aria-label="Command palette"
autoHighlight="always"
mode="none"
@@ -408,7 +803,7 @@ function OpenCommandPaletteDialog() {
type="button"
className="flex cursor-pointer items-center"
aria-label="Back"
onClick={popView}
onClick={leaveSubmenu}
>
<ArrowLeftIcon />
</button>
@@ -890,6 +890,7 @@ export interface ComposerPromptEditorHandle {
focus: () => void;
focusAt: (cursor: number) => void;
focusAtEnd: () => void;
isFocused: () => boolean;
readSnapshot: () => {
value: string;
cursor: number;
@@ -1383,7 +1384,6 @@ function ComposerSurroundSelectionPlugin(props: {
const onCompositionEnd = () => {
tryApplyDeadKeyBacktickSurround({ finalAttempt: true });
};
let activeRootElement: HTMLElement | null = null;
const unregisterRootListener = editor.registerRootListener((rootElement, prevRootElement) => {
prevRootElement?.removeEventListener("keydown", onKeyDown);
@@ -1493,7 +1493,7 @@ function ComposerPromptEditorInner({
if (shouldRewriteEditorState) {
$setComposerEditorPrompt(value, terminalContexts, skillMetadataRef.current);
}
if (shouldRewriteEditorState || isFocused) {
if (isFocused) {
$setSelectionAtComposerOffset(normalizedCursor);
}
});
@@ -1508,22 +1508,19 @@ function ComposerPromptEditorInner({
if (!rootElement) return;
const boundedCursor = clampCollapsedComposerCursor(snapshotRef.current.value, nextCursor);
rootElement.focus();
isApplyingControlledUpdateRef.current = true;
editor.update(() => {
$setSelectionAtComposerOffset(boundedCursor);
});
queueMicrotask(() => {
isApplyingControlledUpdateRef.current = false;
});
snapshotRef.current = {
value: snapshotRef.current.value,
cursor: boundedCursor,
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
terminalContextIds: snapshotRef.current.terminalContextIds,
};
onChangeRef.current(
snapshotRef.current.value,
boundedCursor,
snapshotRef.current.expandedCursor,
false,
snapshotRef.current.terminalContextIds,
);
},
[editor],
);
@@ -1577,9 +1574,13 @@ function ComposerPromptEditorInner({
),
);
},
isFocused: () => {
const rootElement = editor.getRootElement();
return Boolean(rootElement && document.activeElement === rootElement);
},
readSnapshot,
}),
[focusAt, readSnapshot],
[editor, focusAt, readSnapshot],
);
const handleEditorChange = useCallback((editorState: EditorState) => {
+74 -17
View File
@@ -141,15 +141,18 @@ import {
import { sortThreads } from "../lib/threadSort";
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { CommandDialogTrigger } from "./ui/command";
import { readEnvironmentApi } from "../environmentApi";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import { useServerKeybindings } from "../rpc/serverState";
import { deriveLogicalProjectKey } from "../logicalProject";
import { useCommandPaletteStore } from "../commandPaletteStore";
import {
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
import { serverThreadSurfaceInput } from "../workspace/types";
import { useWorkspaceDragStore } from "../workspace/dragStore";
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
import type { Project, SidebarThreadSummary } from "../types";
const THREAD_PREVIEW_LIMIT = 6;
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
@@ -570,6 +573,24 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
},
[],
);
const handleDragStart = useCallback(
(event: React.DragEvent<HTMLElement>) => {
if (renamingThreadKey === threadKey) {
event.preventDefault();
return;
}
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", thread.id);
useWorkspaceDragStore.getState().setItem({
kind: "thread",
input: serverThreadSurfaceInput(threadRef),
});
},
[renamingThreadKey, thread.id, threadKey, threadRef],
);
const handleDragEnd = useCallback(() => {
useWorkspaceDragStore.getState().clearItem();
}, []);
const handleConfirmArchiveClick = useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
@@ -616,7 +637,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
isActive,
isSelected,
})} relative isolate`}
draggable={renamingThreadKey !== threadKey}
onClick={handleRowClick}
onDragEnd={handleDragEnd}
onDragStart={handleDragStart}
onKeyDown={handleRowKeyDown}
onContextMenu={handleRowContextMenu}
>
@@ -1008,6 +1032,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const removeFromSelection = useThreadSelectionStore((state) => state.removeFromSelection);
const setSelectionAnchor = useThreadSelectionStore((state) => state.setAnchor);
const selectedThreadCount = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
const openThreadInNewTab = useWorkspaceStore((state) => state.openThreadInNewTab);
const openThreadInSplit = useWorkspaceStore((state) => state.openThreadInSplit);
const clearComposerDraftForThread = useComposerDraftStore((state) => state.clearDraftThread);
const getDraftThreadByProjectRef = useComposerDraftStore(
(state) => state.getDraftThreadByProjectRef,
@@ -1636,6 +1662,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const threadWorkspacePath = thread.worktreePath ?? project.cwd ?? null;
const clicked = await api.contextMenu.show(
[
{ id: "open-new-tab", label: "Open in new tab" },
{ id: "open-split-right", label: "Open in split right" },
{ id: "open-split-down", label: "Open in split down" },
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy Path" },
@@ -1645,6 +1674,33 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
position,
);
if (clicked === "open-new-tab") {
openThreadInNewTab(serverThreadSurfaceInput(threadRef));
void router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(threadRef),
});
return;
}
if (clicked === "open-split-right") {
openThreadInSplit(serverThreadSurfaceInput(threadRef), "x");
void router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(threadRef),
});
return;
}
if (clicked === "open-split-down") {
openThreadInSplit(serverThreadSurfaceInput(threadRef), "y");
void router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(threadRef),
});
return;
}
if (clicked === "rename") {
setRenamingThreadKey(threadKey);
setRenamingTitle(thread.title);
@@ -1692,7 +1748,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyThreadIdToClipboard,
deleteThread,
markThreadUnread,
openThreadInNewTab,
openThreadInSplit,
project.cwd,
router,
],
);
@@ -2062,6 +2121,7 @@ interface SidebarProjectsContentProps {
routeThreadKey: string | null;
newThreadShortcutLabel: string | null;
commandPaletteShortcutLabel: string | null;
onOpenCommandPalette: () => void;
threadJumpLabelByKey: ReadonlyMap<string, string>;
attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void;
expandThreadListForProject: (projectKey: string) => void;
@@ -2114,6 +2174,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
routeThreadKey,
newThreadShortcutLabel,
commandPaletteShortcutLabel,
onOpenCommandPalette,
threadJumpLabelByKey,
attachThreadListAutoAnimateRef,
expandThreadListForProject,
@@ -2163,14 +2224,12 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
<SidebarGroup className="px-2 pt-2 pb-1">
<SidebarMenu>
<SidebarMenuItem>
<CommandDialogTrigger
render={
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground focus-visible:ring-0"
data-testid="command-palette-trigger"
/>
}
<SidebarMenuButton
type="button"
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground focus-visible:ring-0"
data-testid="command-palette-trigger"
onClick={onOpenCommandPalette}
>
<SearchIcon className="size-3.5" />
<span className="flex-1 truncate text-left text-xs">Search</span>
@@ -2179,7 +2238,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
{commandPaletteShortcutLabel}
</Kbd>
) : null}
</CommandDialogTrigger>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
@@ -2390,7 +2449,9 @@ export default function Sidebar() {
select: (params) => resolveThreadRouteRef(params),
});
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
const routeThreadTerminalOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
const keybindings = useServerKeybindings();
const setCommandPaletteOpen = useCommandPaletteStore((state) => state.setOpen);
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
@@ -2552,14 +2613,9 @@ export default function Sidebar() {
const getCurrentSidebarShortcutContext = useCallback(
() => ({
terminalFocus: isTerminalFocused(),
terminalOpen: routeThreadRef
? selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadKey,
routeThreadRef,
).terminalOpen
: false,
terminalOpen: routeThreadTerminalOpen,
}),
[routeThreadRef],
[routeThreadTerminalOpen],
);
const newThreadShortcutLabelOptions = useMemo(
() => ({
@@ -3241,6 +3297,7 @@ export default function Sidebar() {
routeThreadKey={routeThreadKey}
newThreadShortcutLabel={newThreadShortcutLabel}
commandPaletteShortcutLabel={commandPaletteShortcutLabel}
onOpenCommandPalette={() => setCommandPaletteOpen(true)}
threadJumpLabelByKey={visibleThreadJumpLabelByKey}
attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef}
expandThreadListForProject={expandThreadListForProject}
@@ -783,6 +783,7 @@ interface ThreadTerminalDrawerProps {
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
showResizeHandle?: boolean;
}
interface TerminalActionButtonProps {
@@ -836,6 +837,7 @@ export default function ThreadTerminalDrawer({
onCloseTerminal,
onHeightChange,
onAddTerminalContext,
showResizeHandle = true,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
@@ -1072,16 +1074,20 @@ export default function ThreadTerminalDrawer({
return (
<aside
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
className={`thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden bg-background ${
showResizeHandle ? "border-t border-border/80" : ""
}`}
style={{ height: `${drawerHeight}px` }}
>
<div
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
/>
{showResizeHandle ? (
<div
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
/>
) : null}
{!hasTerminalSidebar && (
<div className="pointer-events-none absolute right-2 top-2 z-20">
+28 -1
View File
@@ -339,6 +339,7 @@ export interface ChatComposerHandle {
// --------------------------------------------------------------------------
export interface ChatComposerProps {
activationFocusRequestId?: number;
composerDraftTarget: ScopedThreadRef | DraftId;
environmentId: EnvironmentId;
routeKind: "server" | "draft";
@@ -447,6 +448,7 @@ export interface ChatComposerProps {
export const ChatComposer = memo(
forwardRef<ChatComposerHandle, ChatComposerProps>(function ChatComposer(props, ref) {
const {
activationFocusRequestId,
composerDraftTarget,
environmentId,
routeKind,
@@ -653,6 +655,7 @@ export const ChatComposer = memo(
// Refs
// ------------------------------------------------------------------
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const pendingActivationFocusRepairRef = useRef(false);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerFormHeightRef = useRef(0);
const composerSelectLockRef = useRef(false);
@@ -661,6 +664,13 @@ export const ChatComposer = memo(
const activeComposerMenuItemRef = useRef<ComposerCommandItem | null>(null);
const dragDepthRef = useRef(0);
useEffect(() => {
if (activationFocusRequestId === undefined) {
return;
}
pendingActivationFocusRepairRef.current = true;
}, [activationFocusRequestId]);
// ------------------------------------------------------------------
// Derived: composer send state
// ------------------------------------------------------------------
@@ -1227,8 +1237,11 @@ export const ChatComposer = memo(
);
return;
}
const previousPrompt = promptRef.current;
promptRef.current = nextPrompt;
setPrompt(nextPrompt);
if (previousPrompt !== nextPrompt) {
setPrompt(nextPrompt);
}
if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) {
setComposerDraftTerminalContexts(
composerDraftTarget,
@@ -1239,6 +1252,20 @@ export const ChatComposer = memo(
setComposerTrigger(
cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
);
if (pendingActivationFocusRepairRef.current) {
const repairCursor = nextCursor;
window.requestAnimationFrame(() => {
const composerEditor = composerEditorRef.current;
if (!composerEditor) {
pendingActivationFocusRepairRef.current = false;
return;
}
if (!composerEditor.isFocused()) {
composerEditor.focusAt(repairCursor);
}
pendingActivationFocusRepairRef.current = false;
});
}
},
[
activePendingProgress?.activeQuestion,
+3 -3
View File
@@ -122,7 +122,7 @@ export const ChatHeader = memo(function ChatHeader({
className="shrink-0"
pressed={terminalOpen}
onPressedChange={onToggleTerminal}
aria-label="Toggle terminal drawer"
aria-label="Toggle terminal split"
variant="outline"
size="xs"
disabled={!terminalAvailable}
@@ -135,8 +135,8 @@ export const ChatHeader = memo(function ChatHeader({
{!terminalAvailable
? "Terminal is unavailable until this thread has an active project."
: terminalToggleShortcutLabel
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
: "Toggle terminal drawer"}
? `Toggle terminal split (${terminalToggleShortcutLabel})`
: "Toggle terminal split"}
</TooltipPopup>
</Tooltip>
<Tooltip>
@@ -0,0 +1,100 @@
import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useEffect, useMemo, useRef, useState } from "react";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../../storeSelectors";
import { useStore } from "../../store";
import { useTerminalStateStore } from "../../terminalStateStore";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { TerminalViewport } from "../ThreadTerminalDrawer";
import { useWorkspaceStore } from "../../workspace/store";
export function ThreadTerminalSurface(props: {
surfaceId: string;
terminalId: string;
threadRef: ScopedThreadRef;
activationFocusRequestId?: number;
}) {
const { activationFocusRequestId, surfaceId, terminalId, threadRef } = props;
const thread = useStore(useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]));
const projectRef = thread ? scopeProjectRef(thread.environmentId, thread.projectId) : null;
const project = useStore(useMemo(() => createProjectSelectorByRef(projectRef), [projectRef]));
const closeTerminal = useTerminalStateStore((state) => state.closeTerminal);
const terminalLaunchContext = useTerminalStateStore(
(state) => state.terminalLaunchContextByThreadKey[scopedThreadKey(threadRef)] ?? null,
);
const [containerHeight, setContainerHeight] = useState(320);
const [focusRequestId, setFocusRequestId] = useState(1);
const closeSurface = useWorkspaceStore((state) => state.closeSurface);
const containerRef = useRef<HTMLDivElement | null>(null);
const worktreePath = terminalLaunchContext?.worktreePath ?? thread?.worktreePath ?? null;
const cwd = useMemo(
() =>
terminalLaunchContext?.cwd ??
(project
? projectScriptCwd({
project: { cwd: project.cwd },
worktreePath,
})
: null),
[project, terminalLaunchContext?.cwd, worktreePath],
);
const runtimeEnv = useMemo(
() =>
project
? projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath,
})
: {},
[project, worktreePath],
);
useEffect(() => {
const element = containerRef.current;
if (!element) {
return;
}
const observer = new ResizeObserver((entries) => {
const nextHeight = Math.max(180, Math.floor(entries[0]?.contentRect.height ?? 0));
setContainerHeight((current) => (current === nextHeight ? current : nextHeight));
});
observer.observe(element);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (activationFocusRequestId === undefined) {
return;
}
setFocusRequestId((current) => current + 1);
}, [activationFocusRequestId]);
if (!thread || !project || !cwd) {
return <div ref={containerRef} className="min-h-0 flex-1 bg-background" />;
}
return (
<div ref={containerRef} className="min-h-0 flex-1 overflow-hidden bg-background">
<TerminalViewport
threadRef={threadRef}
threadId={thread.id}
terminalId={terminalId}
terminalLabel={thread.title}
cwd={cwd}
worktreePath={worktreePath}
runtimeEnv={runtimeEnv}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={0}
drawerHeight={containerHeight}
onAddTerminalContext={() => undefined}
onSessionExited={() => {
closeTerminal(threadRef, terminalId);
closeSurface(surfaceId);
}}
/>
</div>
);
}
@@ -0,0 +1,130 @@
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import { useEffect, useMemo, useRef } from "react";
import { useComposerDraftStore } from "../../composerDraftStore";
import { resolveThreadRouteTarget } from "../../threadRoutes";
import { useFocusedWorkspaceRouteTarget, useWorkspaceStore } from "../../workspace/store";
import type { ThreadSurfaceInput } from "../../workspace/types";
function sameRouteTarget(
left: ReturnType<typeof resolveThreadRouteTarget>,
right: ReturnType<typeof resolveThreadRouteTarget>,
): boolean {
if (!left && !right) {
return true;
}
if (!left || !right || left.kind !== right.kind) {
return false;
}
if (left.kind === "server" && right.kind === "server") {
return (
left.threadRef.environmentId === right.threadRef.environmentId &&
left.threadRef.threadId === right.threadRef.threadId
);
}
if (left.kind === "draft" && right.kind === "draft") {
return left.draftId === right.draftId;
}
return false;
}
export function WorkspaceRouteSync() {
const navigate = useNavigate();
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const currentRouteTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const focusedRouteTarget = useFocusedWorkspaceRouteTarget();
const pathname = useLocation({
select: (location) => location.pathname,
});
const previousPathnameRef = useRef(pathname);
const draftSession = useComposerDraftStore((store) =>
currentRouteTarget?.kind === "draft" ? store.getDraftSession(currentRouteTarget.draftId) : null,
);
const currentRouteSurfaceInput = useMemo<ThreadSurfaceInput | null>(() => {
if (!currentRouteTarget) {
return null;
}
if (currentRouteTarget.kind === "server") {
return {
scope: "server",
threadRef: currentRouteTarget.threadRef,
};
}
if (!draftSession) {
return null;
}
return {
scope: "draft",
draftId: currentRouteTarget.draftId,
environmentId: draftSession.environmentId,
threadId: draftSession.threadId,
};
}, [currentRouteTarget, draftSession]);
useEffect(() => {
const pathnameChanged = previousPathnameRef.current !== pathname;
previousPathnameRef.current = pathname;
if (currentRouteTarget) {
if (!currentRouteSurfaceInput) {
return;
}
if (!focusedRouteTarget || pathnameChanged) {
openThreadSurface(currentRouteSurfaceInput, "focus-or-tab");
return;
}
if (sameRouteTarget(currentRouteTarget, focusedRouteTarget)) {
return;
}
void navigateToRouteTarget(navigate, focusedRouteTarget);
return;
}
if (!focusedRouteTarget) {
return;
}
void navigateToRouteTarget(navigate, focusedRouteTarget);
}, [
currentRouteSurfaceInput,
currentRouteTarget,
focusedRouteTarget,
navigate,
openThreadSurface,
pathname,
]);
return null;
}
function navigateToRouteTarget(
navigate: ReturnType<typeof useNavigate>,
target: NonNullable<ReturnType<typeof resolveThreadRouteTarget>>,
) {
if (target.kind === "server") {
return navigate({
to: "/$environmentId/$threadId",
params: {
environmentId: target.threadRef.environmentId,
threadId: target.threadRef.threadId,
},
replace: true,
search: {},
});
}
return navigate({
to: "/draft/$draftId",
params: {
draftId: target.draftId,
},
replace: true,
search: {},
});
}
@@ -0,0 +1,984 @@
import { useParams } from "@tanstack/react-router";
import { Columns2Icon, Rows2Icon, TerminalSquareIcon, XIcon } from "lucide-react";
import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createThreadSelectorByRef } from "../../storeSelectors";
import { useStore } from "../../store";
import { cn } from "../../lib/utils";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { SidebarInset } from "../ui/sidebar";
import ChatView from "../ChatView";
import { useComposerDraftStore } from "../../composerDraftStore";
import { resolveThreadRouteTarget } from "../../threadRoutes";
import { ThreadTerminalSurface } from "./ThreadTerminalSurface";
import { useWorkspaceDragStore } from "../../workspace/dragStore";
import {
useWorkspaceFocusedWindowId,
useWorkspaceMobileActiveWindowId,
useWorkspaceNode,
useWorkspaceRootNodeId,
useWorkspaceStore,
useWorkspaceSurface,
useWorkspaceWindow,
useWorkspaceWindowIds,
useWorkspaceZoomedWindowId,
} from "../../workspace/store";
import {
normalizeWorkspaceSplitSizes,
type WorkspaceNode,
type WorkspaceDropPlacement,
type WorkspacePlacementTarget,
type WorkspaceSurfaceInstance,
} from "../../workspace/types";
const WORKSPACE_MIN_PANE_SIZE_PX = 220;
const WORKSPACE_DROP_EDGE_THRESHOLD = 0.22;
const INTERACTIVE_PANE_TARGET_SELECTOR = [
"button",
"a[href]",
"input",
"textarea",
"select",
"summary",
"[contenteditable='true']",
"[contenteditable='']",
"[role='button']",
"[role='link']",
"[role='menuitem']",
"[draggable='true']",
"[data-pane-autofocus-prevent='true']",
].join(", ");
function isWorkspaceDropTarget(
value: WorkspaceDropPlacement | string | null,
target: WorkspaceDropPlacement | string,
): boolean {
return value === target;
}
function resolveWorkspaceDropPlacementFromPoint(
rect: DOMRect,
clientX: number,
clientY: number,
): WorkspaceDropPlacement {
if (rect.width <= 0 || rect.height <= 0) {
return "center";
}
const normalizedX = (clientX - rect.left) / rect.width;
const normalizedY = (clientY - rect.top) / rect.height;
const distanceLeft = normalizedX;
const distanceRight = 1 - normalizedX;
const distanceTop = normalizedY;
const distanceBottom = 1 - normalizedY;
const minEdgeDistance = Math.min(distanceLeft, distanceRight, distanceTop, distanceBottom);
if (minEdgeDistance > WORKSPACE_DROP_EDGE_THRESHOLD) {
return "center";
}
if (minEdgeDistance === distanceLeft) {
return "left";
}
if (minEdgeDistance === distanceRight) {
return "right";
}
if (minEdgeDistance === distanceTop) {
return "top";
}
return "bottom";
}
function workspaceDropPreviewClass(target: WorkspaceDropPlacement | string | null): string {
switch (target) {
case "left":
return "left-2 top-2 bottom-2 w-1/2";
case "right":
return "right-2 top-2 bottom-2 w-1/2";
case "top":
return "left-2 right-2 top-2 h-1/2";
case "bottom":
return "left-2 right-2 bottom-2 h-1/2";
case "center":
return "inset-2";
default:
return "hidden";
}
}
function shouldSuppressPaneActivationAutoFocus(target: EventTarget | null): boolean {
if (!(target instanceof Element)) {
return false;
}
if (target.closest("[data-pane-autofocus-allow='true']")) {
return false;
}
return target.closest(INTERACTIVE_PANE_TARGET_SELECTOR) !== null;
}
function applyWorkspaceDrop(params: {
clearDragItem: () => void;
dragItem:
| {
kind: "surface";
surfaceId: string;
}
| {
kind: "thread";
input: Parameters<ReturnType<typeof useWorkspaceStore.getState>["placeThreadSurface"]>[0];
};
placeSurface: ReturnType<typeof useWorkspaceStore.getState>["placeSurface"];
placeThreadSurface: ReturnType<typeof useWorkspaceStore.getState>["placeThreadSurface"];
target: WorkspacePlacementTarget;
}) {
if (params.dragItem.kind === "surface") {
params.placeSurface(params.dragItem.surfaceId, params.target);
} else {
params.placeThreadSurface(params.dragItem.input, params.target);
}
params.clearDragItem();
}
function WorkspaceEmptyState() {
return (
<div className="flex min-h-0 flex-1 items-center justify-center px-6">
<div className="w-full max-w-lg rounded-xl border border-border/55 bg-card/20 px-8 py-12 shadow-sm/5">
<p className="text-xl text-foreground">Pick a thread to continue</p>
<p className="mt-2 text-sm text-muted-foreground/78">
Select an existing thread or create a new one to get started.
</p>
</div>
</div>
);
}
export function WorkspaceShell() {
const rootNodeId = useWorkspaceRootNodeId();
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
{rootNodeId ? <WorkspaceLayoutRoot /> : <WorkspaceRouteFallback />}
</div>
</SidebarInset>
);
}
function WorkspaceRouteFallback() {
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const draftSession = useComposerDraftStore((store) =>
routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
);
useEffect(() => {
if (!routeTarget) {
return;
}
if (routeTarget.kind === "server") {
openThreadSurface(
{
scope: "server",
threadRef: routeTarget.threadRef,
},
"focus-or-tab",
);
return;
}
if (!draftSession) {
return;
}
openThreadSurface(
{
scope: "draft",
draftId: routeTarget.draftId,
environmentId: draftSession.environmentId,
threadId: draftSession.threadId,
},
"focus-or-tab",
);
}, [draftSession, openThreadSurface, routeTarget]);
if (!routeTarget) {
return <WorkspaceEmptyState />;
}
if (routeTarget.kind === "server") {
return (
<ChatView
environmentId={routeTarget.threadRef.environmentId}
threadId={routeTarget.threadRef.threadId}
routeKind="server"
/>
);
}
if (!draftSession) {
return <WorkspaceEmptyState />;
}
return (
<ChatView
draftId={routeTarget.draftId}
environmentId={draftSession.environmentId}
threadId={draftSession.threadId}
routeKind="draft"
/>
);
}
function WorkspaceLayoutRoot() {
const rootNodeId = useWorkspaceRootNodeId();
const focusedWindowId = useWorkspaceFocusedWindowId();
const mobileActiveWindowId = useWorkspaceMobileActiveWindowId();
const windowIds = useWorkspaceWindowIds();
const zoomedWindowId = useWorkspaceZoomedWindowId();
const setMobileActiveWindow = useWorkspaceStore((state) => state.setMobileActiveWindow);
const isDesktopViewport = useMediaQuery("md");
const activeWindowId =
zoomedWindowId ?? mobileActiveWindowId ?? focusedWindowId ?? windowIds[0] ?? null;
return (
<div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
{windowIds.length > 1 ? (
<div className="flex items-center gap-2 border-b border-border px-3 py-2 md:hidden">
{windowIds.map((windowId, index) => {
const isActive = (mobileActiveWindowId ?? focusedWindowId ?? windowIds[0]) === windowId;
return (
<button
key={windowId}
type="button"
className={cn(
"rounded-md border px-2 py-1 text-xs",
isActive
? "border-border bg-accent text-foreground"
: "border-border/60 text-muted-foreground",
)}
onClick={() => setMobileActiveWindow(windowId)}
>
Window {index + 1}
</button>
);
})}
</div>
) : null}
<div className="min-h-0 min-w-0 flex-1 overflow-hidden">
{isDesktopViewport ? (
zoomedWindowId ? (
<WorkspaceWindowView windowId={zoomedWindowId} />
) : (
<WorkspaceNodeView nodeId={rootNodeId} />
)
) : (
<MobileWorkspaceWindow windowId={activeWindowId} />
)}
</div>
</div>
);
}
const MobileWorkspaceWindow = memo(function MobileWorkspaceWindow(props: {
windowId: string | null;
}) {
const window = useWorkspaceWindow(props.windowId);
if (!props.windowId) {
return <WorkspaceEmptyState />;
}
if (!window) {
return <WorkspaceEmptyState />;
}
return <WorkspaceWindowView windowId={window.id} />;
});
const WorkspaceNodeView = memo(function WorkspaceNodeView(props: { nodeId: string | null }) {
const node = useWorkspaceNode(props.nodeId);
if (!props.nodeId) {
return null;
}
if (!node) {
return null;
}
if (node.kind === "window") {
return <WorkspaceWindowView windowId={node.windowId} />;
}
return <WorkspaceSplitNodeView node={node} />;
});
const WorkspaceSplitNodeView = memo(function WorkspaceSplitNodeView(props: {
node: Extract<WorkspaceNode, { kind: "split" }>;
}) {
const setSplitNodeSizes = useWorkspaceStore((state) => state.setSplitNodeSizes);
const containerRef = useRef<HTMLDivElement | null>(null);
const resizeStateRef = useRef<{
handle: HTMLButtonElement;
handleIndex: number;
pendingSizes: number[];
pointerId: number;
rafId: number | null;
startCoordinate: number;
startSizes: number[];
totalPx: number;
} | null>(null);
const sizes = useMemo(
() => normalizeWorkspaceSplitSizes(props.node.sizes, props.node.childIds.length),
[props.node.childIds.length, props.node.sizes],
);
const stopResize = useCallback(
(pointerId: number) => {
const resizeState = resizeStateRef.current;
if (!resizeState) {
return;
}
if (resizeState.rafId !== null) {
window.cancelAnimationFrame(resizeState.rafId);
setSplitNodeSizes(props.node.id, resizeState.pendingSizes);
}
resizeStateRef.current = null;
if (resizeState.handle.hasPointerCapture(pointerId)) {
resizeState.handle.releasePointerCapture(pointerId);
}
document.body.style.removeProperty("cursor");
document.body.style.removeProperty("user-select");
},
[props.node.id, setSplitNodeSizes],
);
useEffect(() => {
return () => {
const resizeState = resizeStateRef.current;
if (resizeState && resizeState.rafId !== null) {
window.cancelAnimationFrame(resizeState.rafId);
}
document.body.style.removeProperty("cursor");
document.body.style.removeProperty("user-select");
};
}, []);
const handleResizePointerDown = useCallback(
(handleIndex: number, event: React.PointerEvent<HTMLButtonElement>) => {
if (event.button !== 0) {
return;
}
const container = containerRef.current;
if (!container) {
return;
}
const rect = container.getBoundingClientRect();
const totalPx = props.node.axis === "x" ? rect.width : rect.height;
if (totalPx <= 0) {
return;
}
event.preventDefault();
event.stopPropagation();
resizeStateRef.current = {
handle: event.currentTarget,
handleIndex,
pendingSizes: sizes,
pointerId: event.pointerId,
rafId: null,
startCoordinate: props.node.axis === "x" ? event.clientX : event.clientY,
startSizes: sizes,
totalPx,
};
event.currentTarget.setPointerCapture(event.pointerId);
document.body.style.cursor = props.node.axis === "x" ? "col-resize" : "row-resize";
document.body.style.userSelect = "none";
},
[props.node.axis, sizes],
);
const handleResizePointerMove = useCallback(
(event: React.PointerEvent<HTMLButtonElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) {
return;
}
event.preventDefault();
const deltaPx =
(props.node.axis === "x" ? event.clientX : event.clientY) - resizeState.startCoordinate;
const deltaFraction = deltaPx / resizeState.totalPx;
const pairTotal =
resizeState.startSizes[resizeState.handleIndex]! +
resizeState.startSizes[resizeState.handleIndex + 1]!;
const requestedMinFraction = WORKSPACE_MIN_PANE_SIZE_PX / resizeState.totalPx;
const minFraction = Math.min(requestedMinFraction, Math.max(pairTotal / 2 - 0.001, 0));
const nextBefore = Math.min(
pairTotal - minFraction,
Math.max(minFraction, resizeState.startSizes[resizeState.handleIndex]! + deltaFraction),
);
const nextAfter = pairTotal - nextBefore;
const nextSizes = [...resizeState.startSizes];
nextSizes[resizeState.handleIndex] = nextBefore;
nextSizes[resizeState.handleIndex + 1] = nextAfter;
resizeState.pendingSizes = nextSizes;
if (resizeState.rafId !== null) {
return;
}
resizeState.rafId = window.requestAnimationFrame(() => {
const activeResizeState = resizeStateRef.current;
if (!activeResizeState) {
return;
}
activeResizeState.rafId = null;
setSplitNodeSizes(props.node.id, activeResizeState.pendingSizes);
});
},
[props.node.axis, props.node.id, setSplitNodeSizes],
);
const endResizeInteraction = useCallback(
(event: React.PointerEvent<HTMLButtonElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) {
return;
}
event.preventDefault();
stopResize(event.pointerId);
},
[stopResize],
);
return (
<div
ref={containerRef}
className={cn(
"flex h-full min-h-0 min-w-0 flex-1 overflow-hidden",
props.node.axis === "x" ? "flex-row" : "flex-col",
)}
>
{props.node.childIds.map((childId, index) => (
<Fragment key={childId}>
<div
className="h-full min-h-0 min-w-0 overflow-hidden"
style={{
flexBasis: 0,
flexGrow: sizes[index] ?? 1,
flexShrink: 1,
}}
>
<WorkspaceNodeView nodeId={childId} />
</div>
{index < props.node.childIds.length - 1 ? (
<button
type="button"
className={cn(
"relative z-10 shrink-0 bg-border/80 transition hover:bg-foreground/40",
props.node.axis === "x"
? "h-full w-1 cursor-col-resize touch-none"
: "h-1 w-full cursor-row-resize touch-none",
)}
aria-label={
props.node.axis === "x" ? "Resize panes horizontally" : "Resize panes vertically"
}
title={props.node.axis === "x" ? "Drag to resize panes" : "Drag to resize panes"}
onPointerCancel={endResizeInteraction}
onPointerDown={(event) => handleResizePointerDown(index, event)}
onPointerMove={handleResizePointerMove}
onPointerUp={endResizeInteraction}
>
<span
className={cn(
"pointer-events-none absolute rounded-full bg-background/90",
props.node.axis === "x"
? "top-1/2 left-1/2 h-10 w-px -translate-x-1/2 -translate-y-1/2"
: "top-1/2 left-1/2 h-px w-10 -translate-x-1/2 -translate-y-1/2",
)}
/>
</button>
) : null}
</Fragment>
))}
</div>
);
});
const WorkspaceWindowView = memo(function WorkspaceWindowView(props: { windowId: string }) {
const dragItem = useWorkspaceDragStore((state) => state.item);
const clearDragItem = useWorkspaceDragStore((state) => state.clearItem);
const focusWindow = useWorkspaceStore((state) => state.focusWindow);
const focusTab = useWorkspaceStore((state) => state.focusTab);
const closeSurface = useWorkspaceStore((state) => state.closeSurface);
const placeSurface = useWorkspaceStore((state) => state.placeSurface);
const placeThreadSurface = useWorkspaceStore((state) => state.placeThreadSurface);
const splitWindowSurface = useWorkspaceStore((state) => state.splitWindowSurface);
const window = useWorkspaceWindow(props.windowId);
const activeSurface = useWorkspaceSurface(window?.activeTabId ?? null);
const focusedWindowId = useWorkspaceFocusedWindowId();
const [isWindowDragActive, setIsWindowDragActive] = useState(false);
const [threadActivationFocusRequestId, setThreadActivationFocusRequestId] = useState(0);
const [terminalActivationFocusRequestId, setTerminalActivationFocusRequestId] = useState(0);
const [hoveredDropTarget, setHoveredDropTarget] = useState<
WorkspaceDropPlacement | string | null
>(null);
const shouldAutoFocusOnActivationRef = useRef(true);
const wasFocusedRef = useRef(focusedWindowId === props.windowId);
const windowElementRef = useRef<HTMLElement | null>(null);
const pendingFocusWindowFrameRef = useRef<number | null>(null);
const resetHoveredDropTarget = useCallback(() => {
setHoveredDropTarget(null);
}, []);
useEffect(() => {
if (!dragItem) {
setIsWindowDragActive(false);
setHoveredDropTarget(null);
}
}, [dragItem]);
useEffect(() => {
return () => {
if (pendingFocusWindowFrameRef.current !== null) {
globalThis.cancelAnimationFrame(pendingFocusWindowFrameRef.current);
}
};
}, []);
useEffect(() => {
const isFocused = focusedWindowId === props.windowId;
const wasFocused = wasFocusedRef.current;
wasFocusedRef.current = isFocused;
if (!isFocused || wasFocused || !activeSurface) {
return;
}
const shouldAutoFocus = shouldAutoFocusOnActivationRef.current;
shouldAutoFocusOnActivationRef.current = true;
if (!shouldAutoFocus) {
return;
}
const activeElement = document.activeElement;
const windowElement = windowElementRef.current;
if (
activeElement instanceof HTMLElement &&
windowElement &&
!windowElement.contains(activeElement)
) {
activeElement.blur();
}
if (activeSurface.kind === "thread") {
setThreadActivationFocusRequestId((current) => current + 1);
return;
}
setTerminalActivationFocusRequestId((current) => current + 1);
}, [activeSurface, focusedWindowId, props.windowId]);
const handleWindowDragOver = useCallback(
(event: React.DragEvent<HTMLElement>) => {
if (!dragItem) {
return;
}
event.preventDefault();
event.dataTransfer.dropEffect = "move";
setIsWindowDragActive(true);
setHoveredDropTarget(
resolveWorkspaceDropPlacementFromPoint(
event.currentTarget.getBoundingClientRect(),
event.clientX,
event.clientY,
),
);
},
[dragItem],
);
const handleWindowDragLeave = useCallback((event: React.DragEvent<HTMLElement>) => {
const relatedTarget = event.relatedTarget;
if (relatedTarget instanceof Node && event.currentTarget.contains(relatedTarget)) {
return;
}
setIsWindowDragActive(false);
setHoveredDropTarget(null);
}, []);
const handleDropTarget = useCallback(
(target: WorkspacePlacementTarget) => (event: React.DragEvent<HTMLElement>) => {
if (!dragItem) {
return;
}
event.preventDefault();
event.stopPropagation();
applyWorkspaceDrop({
clearDragItem,
dragItem,
placeSurface,
placeThreadSurface,
target,
});
setIsWindowDragActive(false);
setHoveredDropTarget(null);
},
[clearDragItem, dragItem, placeSurface, placeThreadSurface],
);
const handleDragOverTarget = useCallback(
(hoverTarget: WorkspaceDropPlacement | string) => (event: React.DragEvent<HTMLElement>) => {
if (!dragItem) {
return;
}
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = "move";
setHoveredDropTarget(hoverTarget);
},
[dragItem],
);
const handleWindowDrop = useCallback(
(event: React.DragEvent<HTMLElement>) => {
if (!dragItem) {
return;
}
event.preventDefault();
event.stopPropagation();
const targetPlacement = resolveWorkspaceDropPlacementFromPoint(
event.currentTarget.getBoundingClientRect(),
event.clientX,
event.clientY,
);
applyWorkspaceDrop({
clearDragItem,
dragItem,
placeSurface,
placeThreadSurface,
target: {
kind: "window",
windowId: props.windowId,
placement: targetPlacement,
},
});
setIsWindowDragActive(false);
setHoveredDropTarget(null);
},
[clearDragItem, dragItem, placeSurface, placeThreadSurface, props.windowId],
);
const handleTabDragStart = useCallback(
(surfaceId: string) => (event: React.DragEvent<HTMLElement>) => {
event.stopPropagation();
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", surfaceId);
useWorkspaceDragStore.getState().setItem({
kind: "surface",
surfaceId,
});
focusWindow(props.windowId);
focusTab(props.windowId, surfaceId);
},
[focusTab, focusWindow, props.windowId],
);
const handleTabDragEnd = useCallback(() => {
useWorkspaceDragStore.getState().clearItem();
setHoveredDropTarget(null);
}, []);
if (!window) {
return null;
}
return (
<section
ref={windowElementRef}
className={cn(
"relative flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden border border-border/70 bg-background",
focusedWindowId === props.windowId ? "ring-1 ring-border/80" : "",
)}
onPointerDownCapture={(event) => {
if (event.button !== 0) {
shouldAutoFocusOnActivationRef.current = true;
return;
}
const shouldSuppressAutoFocus = shouldSuppressPaneActivationAutoFocus(event.target);
shouldAutoFocusOnActivationRef.current = !shouldSuppressAutoFocus;
if (pendingFocusWindowFrameRef.current !== null) {
globalThis.cancelAnimationFrame(pendingFocusWindowFrameRef.current);
pendingFocusWindowFrameRef.current = null;
}
if (!shouldSuppressAutoFocus) {
focusWindow(props.windowId);
return;
}
pendingFocusWindowFrameRef.current = globalThis.requestAnimationFrame(() => {
pendingFocusWindowFrameRef.current = null;
focusWindow(props.windowId);
});
}}
>
<div className="flex min-w-0 items-center gap-1 border-b border-border/70 bg-muted/20 px-2 py-1.5">
<div
className={cn(
"flex min-w-0 flex-1 items-center gap-1 overflow-x-auto rounded-md transition",
isWorkspaceDropTarget(hoveredDropTarget, "tab-strip") ? "bg-accent/60" : "",
)}
onDragLeave={resetHoveredDropTarget}
onDragOver={handleDragOverTarget("tab-strip")}
onDrop={handleDropTarget({
kind: "window",
windowId: props.windowId,
placement: "center",
})}
>
{window.tabIds.map((surfaceId) => {
return (
<WorkspaceTabView
key={surfaceId}
closeSurface={closeSurface}
focusTab={focusTab}
handleDragOverTarget={handleDragOverTarget}
handleDropTarget={handleDropTarget}
handleTabDragEnd={handleTabDragEnd}
handleTabDragStart={handleTabDragStart}
hoveredDropTarget={hoveredDropTarget}
resetHoveredDropTarget={resetHoveredDropTarget}
surfaceId={surfaceId}
windowId={props.windowId}
isActive={window.activeTabId === surfaceId}
/>
);
})}
</div>
<div className="hidden items-center gap-1 md:flex">
<button
type="button"
className="rounded-sm p-1 text-muted-foreground transition hover:bg-accent hover:text-foreground"
onClick={() => splitWindowSurface(props.windowId, "x")}
aria-label="Split active tab right"
title="Split active tab right"
>
<Columns2Icon className="size-3.5" />
</button>
<button
type="button"
className="rounded-sm p-1 text-muted-foreground transition hover:bg-accent hover:text-foreground"
onClick={() => splitWindowSurface(props.windowId, "y")}
aria-label="Split active tab down"
title="Split active tab down"
>
<Rows2Icon className="size-3.5" />
</button>
</div>
</div>
<div
className={cn(
"h-0.5 shrink-0 transition-colors",
focusedWindowId === props.windowId ? "bg-primary" : "bg-transparent",
)}
/>
<div
className="relative flex h-full min-h-0 min-w-0 flex-1 overflow-hidden"
onDragLeave={handleWindowDragLeave}
onDrop={handleWindowDrop}
onDragOver={handleWindowDragOver}
>
{activeSurface ? (
<WorkspaceSurfaceView
activationFocusRequestId={
activeSurface.kind === "thread"
? threadActivationFocusRequestId
: terminalActivationFocusRequestId
}
surface={activeSurface}
bindSharedComposerHandle={focusedWindowId === props.windowId}
/>
) : null}
{dragItem && isWindowDragActive ? (
<>
<div className="pointer-events-none absolute inset-0 z-10 bg-background/10" />
<div
className={cn(
"pointer-events-none absolute z-20 rounded-lg border-2 border-primary/70 bg-primary/10 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.08)] transition-all",
workspaceDropPreviewClass(hoveredDropTarget),
)}
/>
</>
) : null}
</div>
</section>
);
});
const WorkspaceTabView = memo(function WorkspaceTabView(props: {
closeSurface: (surfaceId: string) => void;
focusTab: (windowId: string, surfaceId: string) => void;
handleDragOverTarget: (
hoverTarget: WorkspaceDropPlacement | string,
) => (event: React.DragEvent<HTMLElement>) => void;
handleDropTarget: (
target: WorkspacePlacementTarget,
) => (event: React.DragEvent<HTMLElement>) => void;
handleTabDragEnd: () => void;
handleTabDragStart: (surfaceId: string) => (event: React.DragEvent<HTMLElement>) => void;
hoveredDropTarget: WorkspaceDropPlacement | string | null;
isActive: boolean;
resetHoveredDropTarget: () => void;
surfaceId: string;
windowId: string;
}) {
const surface = useWorkspaceSurface(props.surfaceId);
if (!surface) {
return null;
}
return (
<div
className={cn(
"group flex max-w-[18rem] min-w-0 items-center gap-1 rounded-md border px-2 py-1 text-xs",
props.isActive
? "border-border bg-background text-foreground"
: "border-transparent text-muted-foreground hover:bg-accent/50",
isWorkspaceDropTarget(props.hoveredDropTarget, props.surfaceId)
? "ring-1 ring-primary/50"
: "",
)}
onDragLeave={props.resetHoveredDropTarget}
onDragOver={props.handleDragOverTarget(props.surfaceId)}
onDrop={props.handleDropTarget({
kind: "tab",
windowId: props.windowId,
surfaceId: props.surfaceId,
})}
>
<button
type="button"
className="min-w-0 flex-1 truncate text-left"
data-pane-autofocus-allow="true"
draggable
onClick={() => props.focusTab(props.windowId, props.surfaceId)}
onDragEnd={props.handleTabDragEnd}
onDragStart={props.handleTabDragStart(props.surfaceId)}
>
<WorkspaceSurfaceTitle surface={surface} />
</button>
<button
type="button"
draggable={false}
className="rounded-sm p-0.5 text-muted-foreground opacity-0 transition group-hover:opacity-100 hover:bg-accent hover:text-foreground"
onClick={() => props.closeSurface(props.surfaceId)}
aria-label="Close tab"
>
<XIcon className="size-3" />
</button>
</div>
);
});
const WorkspaceSurfaceView = memo(function WorkspaceSurfaceView(props: {
activationFocusRequestId?: number;
bindSharedComposerHandle?: boolean;
surface: WorkspaceSurfaceInstance;
}) {
if (props.surface.kind === "thread") {
if (props.surface.input.scope === "server") {
return (
<ChatView
{...(props.activationFocusRequestId === undefined
? {}
: { activationFocusRequestId: props.activationFocusRequestId })}
environmentId={props.surface.input.threadRef.environmentId}
threadId={props.surface.input.threadRef.threadId}
routeKind="server"
{...(props.bindSharedComposerHandle === undefined
? {}
: { bindSharedComposerHandle: props.bindSharedComposerHandle })}
/>
);
}
return (
<ChatView
{...(props.activationFocusRequestId === undefined
? {}
: { activationFocusRequestId: props.activationFocusRequestId })}
draftId={props.surface.input.draftId}
environmentId={props.surface.input.environmentId}
threadId={props.surface.input.threadId}
routeKind="draft"
{...(props.bindSharedComposerHandle === undefined
? {}
: { bindSharedComposerHandle: props.bindSharedComposerHandle })}
/>
);
}
return (
<ThreadTerminalSurface
surfaceId={props.surface.id}
terminalId={props.surface.input.terminalId}
threadRef={props.surface.input.threadRef}
{...(props.activationFocusRequestId === undefined
? {}
: { activationFocusRequestId: props.activationFocusRequestId })}
/>
);
});
function WorkspaceSurfaceTitle(props: { surface: WorkspaceSurfaceInstance }) {
if (props.surface.kind === "terminal") {
return <TerminalSurfaceTitle threadRef={props.surface.input.threadRef} />;
}
return <ThreadSurfaceTitle surface={props.surface} />;
}
function ThreadSurfaceTitle(props: {
surface: Extract<WorkspaceSurfaceInstance, { kind: "thread" }>;
}) {
const thread = useStore(
useMemo(
() =>
createThreadSelectorByRef(
props.surface.input.scope === "server" ? props.surface.input.threadRef : null,
),
[props.surface.input],
),
);
if (props.surface.input.scope === "server") {
return <>{thread?.title ?? props.surface.input.threadRef.threadId}</>;
}
return <>{thread?.title ?? props.surface.input.threadId ?? "Draft thread"}</>;
}
function TerminalSurfaceTitle(props: {
threadRef: Extract<WorkspaceSurfaceInstance, { kind: "terminal" }>["input"]["threadRef"];
}) {
const thread = useStore(
useMemo(() => createThreadSelectorByRef(props.threadRef), [props.threadRef]),
);
const label = thread?.title ?? props.threadRef.threadId;
return (
<span className="inline-flex items-center gap-1">
<TerminalSquareIcon className="size-3 shrink-0" />
<span className="truncate">{label}</span>
</span>
);
}
+3
View File
@@ -2158,6 +2158,9 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
}
set((state) => {
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
if (existing.prompt === prompt) {
return state;
}
const nextDraft: ComposerThreadDraftState = {
...existing,
prompt,
@@ -0,0 +1,333 @@
import type { KeybindingCommand, ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useMemo } from "react";
import { useCommandPaletteStore } from "../commandPaletteStore";
import {
useFocusedWorkspaceSurface,
useWorkspaceDocument,
useWorkspaceStore,
} from "../workspace/store";
import type { WorkspaceSurfaceInstance } from "../workspace/types";
export const WORKSPACE_COMMAND_IDS = [
"workspace.terminal.splitRight",
"workspace.terminal.splitDown",
"workspace.terminal.newTab",
"workspace.pane.splitRight",
"workspace.pane.splitDown",
"workspace.focus.previous",
"workspace.focus.next",
"workspace.focus.left",
"workspace.focus.right",
"workspace.focus.up",
"workspace.focus.down",
"workspace.pane.close",
"workspace.pane.toggleZoom",
"workspace.pane.resizeLeft",
"workspace.pane.resizeRight",
"workspace.pane.resizeUp",
"workspace.pane.resizeDown",
"workspace.pane.equalize",
"workspace.pane.moveLeft",
"workspace.pane.moveRight",
"workspace.pane.moveUp",
"workspace.pane.moveDown",
"workspace.tab.moveLeft",
"workspace.tab.moveRight",
"workspace.tab.moveUp",
"workspace.tab.moveDown",
] as const satisfies readonly KeybindingCommand[];
export type WorkspaceCommandId = (typeof WORKSPACE_COMMAND_IDS)[number];
export const WORKSPACE_COMMAND_METADATA: Record<
WorkspaceCommandId,
{
searchTerms: readonly string[];
title: string;
}
> = {
"workspace.terminal.splitRight": {
title: "Open terminal in split right",
searchTerms: ["terminal", "split", "right", "pane", "workspace"],
},
"workspace.terminal.splitDown": {
title: "Open terminal in split down",
searchTerms: ["terminal", "split", "down", "bottom", "pane", "workspace"],
},
"workspace.terminal.newTab": {
title: "Open terminal as tab",
searchTerms: ["terminal", "tab", "pane", "workspace"],
},
"workspace.pane.splitRight": {
title: "Open in split right",
searchTerms: ["split", "pane", "right", "open", "workspace"],
},
"workspace.pane.splitDown": {
title: "Open in split down",
searchTerms: ["split", "pane", "down", "open", "workspace"],
},
"workspace.focus.left": {
title: "Focus pane left",
searchTerms: ["focus", "pane", "left", "workspace"],
},
"workspace.focus.previous": {
title: "Focus previous pane",
searchTerms: ["focus", "previous", "pane", "workspace"],
},
"workspace.focus.next": {
title: "Focus next pane",
searchTerms: ["focus", "next", "pane", "workspace"],
},
"workspace.focus.right": {
title: "Focus pane right",
searchTerms: ["focus", "pane", "right", "workspace"],
},
"workspace.focus.up": {
title: "Focus pane up",
searchTerms: ["focus", "pane", "up", "workspace"],
},
"workspace.focus.down": {
title: "Focus pane down",
searchTerms: ["focus", "pane", "down", "workspace"],
},
"workspace.pane.close": {
title: "Close current pane",
searchTerms: ["close", "pane", "window", "workspace"],
},
"workspace.pane.toggleZoom": {
title: "Toggle pane zoom",
searchTerms: ["zoom", "maximize", "pane", "workspace"],
},
"workspace.pane.resizeLeft": {
title: "Resize pane left",
searchTerms: ["resize", "pane", "left", "workspace"],
},
"workspace.pane.resizeRight": {
title: "Resize pane right",
searchTerms: ["resize", "pane", "right", "workspace"],
},
"workspace.pane.resizeUp": {
title: "Resize pane up",
searchTerms: ["resize", "pane", "up", "workspace"],
},
"workspace.pane.resizeDown": {
title: "Resize pane down",
searchTerms: ["resize", "pane", "down", "workspace"],
},
"workspace.pane.equalize": {
title: "Equalize splits",
searchTerms: ["equalize", "reset", "split", "pane", "workspace"],
},
"workspace.pane.moveLeft": {
title: "Move pane left",
searchTerms: ["move", "pane", "left", "workspace"],
},
"workspace.pane.moveRight": {
title: "Move pane right",
searchTerms: ["move", "pane", "right", "workspace"],
},
"workspace.pane.moveUp": {
title: "Move pane up",
searchTerms: ["move", "pane", "up", "workspace"],
},
"workspace.pane.moveDown": {
title: "Move pane down",
searchTerms: ["move", "pane", "down", "workspace"],
},
"workspace.tab.moveLeft": {
title: "Move tab left",
searchTerms: ["move", "tab", "left", "workspace"],
},
"workspace.tab.moveRight": {
title: "Move tab right",
searchTerms: ["move", "tab", "right", "workspace"],
},
"workspace.tab.moveUp": {
title: "Move tab up",
searchTerms: ["move", "tab", "up", "workspace"],
},
"workspace.tab.moveDown": {
title: "Move tab down",
searchTerms: ["move", "tab", "down", "workspace"],
},
};
function threadRefForWorkspaceSurface(
surface: WorkspaceSurfaceInstance | null | undefined,
): ScopedThreadRef | null {
if (!surface) {
return null;
}
if (surface.kind === "terminal") {
return surface.input.threadRef;
}
if (surface.input.scope === "server") {
return surface.input.threadRef;
}
return null;
}
export function isWorkspaceCommandId(
command: string | null | undefined,
): command is WorkspaceCommandId {
return WORKSPACE_COMMAND_IDS.includes(command as WorkspaceCommandId);
}
export function useWorkspaceCommandExecutor() {
const document = useWorkspaceDocument();
const focusedSurface = useFocusedWorkspaceSurface();
const openWorkspaceTarget = useCommandPaletteStore((state) => state.openWorkspaceTarget);
const closeFocusedWindow = useWorkspaceStore((state) => state.closeFocusedWindow);
const equalizeSplits = useWorkspaceStore((state) => state.equalizeSplits);
const focusWindowByStep = useWorkspaceStore((state) => state.focusWindowByStep);
const focusAdjacentWindow = useWorkspaceStore((state) => state.focusAdjacentWindow);
const moveActiveTabToAdjacentWindow = useWorkspaceStore(
(state) => state.moveActiveTabToAdjacentWindow,
);
const moveFocusedWindow = useWorkspaceStore((state) => state.moveFocusedWindow);
const openTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.openTerminalSurfaceForThread,
);
const resizeFocusedWindow = useWorkspaceStore((state) => state.resizeFocusedWindow);
const toggleFocusedWindowZoom = useWorkspaceStore((state) => state.toggleFocusedWindowZoom);
const focusedWindowId = useMemo(() => {
if (document.focusedWindowId && document.windowsById[document.focusedWindowId]) {
return document.focusedWindowId;
}
return Object.keys(document.windowsById)[0] ?? null;
}, [document]);
const focusedThreadRef = useMemo(
() => threadRefForWorkspaceSurface(focusedSurface),
[focusedSurface],
);
const executeWorkspaceCommand = useCallback(
async (command: WorkspaceCommandId): Promise<boolean> => {
switch (command) {
case "workspace.terminal.splitRight":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "split-right");
return true;
case "workspace.terminal.splitDown":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "split-down");
return true;
case "workspace.terminal.newTab":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "new-tab");
return true;
case "workspace.pane.splitRight":
if (!focusedWindowId) {
return false;
}
openWorkspaceTarget({ disposition: "split-right" });
return true;
case "workspace.pane.splitDown":
if (!focusedWindowId) {
return false;
}
openWorkspaceTarget({ disposition: "split-down" });
return true;
case "workspace.focus.left":
focusAdjacentWindow("left");
return true;
case "workspace.focus.previous":
focusWindowByStep(-1);
return true;
case "workspace.focus.next":
focusWindowByStep(1);
return true;
case "workspace.focus.right":
focusAdjacentWindow("right");
return true;
case "workspace.focus.up":
focusAdjacentWindow("up");
return true;
case "workspace.focus.down":
focusAdjacentWindow("down");
return true;
case "workspace.pane.close":
closeFocusedWindow();
return true;
case "workspace.pane.toggleZoom":
toggleFocusedWindowZoom();
return true;
case "workspace.pane.resizeLeft":
resizeFocusedWindow("left");
return true;
case "workspace.pane.resizeRight":
resizeFocusedWindow("right");
return true;
case "workspace.pane.resizeUp":
resizeFocusedWindow("up");
return true;
case "workspace.pane.resizeDown":
resizeFocusedWindow("down");
return true;
case "workspace.pane.equalize":
equalizeSplits();
return true;
case "workspace.pane.moveLeft":
moveFocusedWindow("left");
return true;
case "workspace.pane.moveRight":
moveFocusedWindow("right");
return true;
case "workspace.pane.moveUp":
moveFocusedWindow("up");
return true;
case "workspace.pane.moveDown":
moveFocusedWindow("down");
return true;
case "workspace.tab.moveLeft":
moveActiveTabToAdjacentWindow("left");
return true;
case "workspace.tab.moveRight":
moveActiveTabToAdjacentWindow("right");
return true;
case "workspace.tab.moveUp":
moveActiveTabToAdjacentWindow("up");
return true;
case "workspace.tab.moveDown":
moveActiveTabToAdjacentWindow("down");
return true;
}
},
[
closeFocusedWindow,
equalizeSplits,
focusAdjacentWindow,
focusWindowByStep,
focusedThreadRef,
focusedWindowId,
moveActiveTabToAdjacentWindow,
moveFocusedWindow,
openTerminalSurfaceForThread,
openWorkspaceTarget,
resizeFocusedWindow,
toggleFocusedWindowZoom,
],
);
return {
canOpenTerminalSurface: focusedThreadRef !== null,
canSplitFocusedPane: focusedWindowId !== null,
executeWorkspaceCommand,
focusedSurface,
focusedThreadRef,
focusedWindowId,
};
}
+62 -3
View File
@@ -98,6 +98,42 @@ const DEFAULT_BINDINGS = compile([
},
{
shortcut: modShortcut("d"),
command: "workspace.pane.splitRight",
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
{
shortcut: modShortcut("d", { shiftKey: true }),
command: "workspace.pane.splitDown",
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
{
shortcut: modShortcut("w"),
command: "workspace.pane.close",
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
{ shortcut: modShortcut("["), command: "workspace.focus.previous" },
{ shortcut: modShortcut("]"), command: "workspace.focus.next" },
{ shortcut: modShortcut("arrowup", { altKey: true }), command: "workspace.focus.up" },
{ shortcut: modShortcut("arrowdown", { altKey: true }), command: "workspace.focus.down" },
{ shortcut: modShortcut("arrowleft", { altKey: true }), command: "workspace.focus.left" },
{ shortcut: modShortcut("arrowright", { altKey: true }), command: "workspace.focus.right" },
{ shortcut: modShortcut("enter", { shiftKey: true }), command: "workspace.pane.toggleZoom" },
{ shortcut: modShortcut("arrowup", { ctrlKey: true }), command: "workspace.pane.resizeUp" },
{
shortcut: modShortcut("arrowdown", { ctrlKey: true }),
command: "workspace.pane.resizeDown",
},
{
shortcut: modShortcut("arrowleft", { ctrlKey: true }),
command: "workspace.pane.resizeLeft",
},
{
shortcut: modShortcut("arrowright", { ctrlKey: true }),
command: "workspace.pane.resizeRight",
},
{ shortcut: modShortcut("=", { ctrlKey: true }), command: "workspace.pane.equalize" },
{
shortcut: modShortcut("d", { altKey: true }),
command: "diff.toggle",
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
@@ -253,7 +289,30 @@ describe("shortcutLabelForCommand", () => {
it("returns effective labels for non-terminal commands", () => {
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "workspace.pane.splitRight", "MacIntel"),
"⌘D",
);
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "workspace.focus.previous", "Linux"),
"Ctrl+[",
);
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "workspace.pane.resizeLeft", "MacIntel"),
"⌃⌘Left",
);
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "workspace.pane.equalize", "MacIntel"),
"⌃⌘=",
);
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "workspace.pane.close", "MacIntel"),
"⌘W",
);
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"),
"Ctrl+Alt+D",
);
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "commandPalette.toggle", "MacIntel"),
"⌘K",
@@ -410,13 +469,13 @@ describe("chat/editor shortcuts", () => {
it("matches diff.toggle shortcut outside terminal focus", () => {
assert.isTrue(
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
isDiffToggleShortcut(event({ key: "d", metaKey: true, altKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: false },
}),
);
assert.isFalse(
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
isDiffToggleShortcut(event({ key: "d", metaKey: true, altKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: true },
}),
+1 -1
View File
@@ -3,5 +3,5 @@ export function isTerminalFocused(): boolean {
if (!(activeElement instanceof HTMLElement)) return false;
if (!activeElement.isConnected) return false;
if (activeElement.classList.contains("xterm-helper-textarea")) return true;
return activeElement.closest(".thread-terminal-drawer .xterm") !== null;
return activeElement.closest(".xterm") !== null;
}
@@ -1,7 +1,6 @@
import { createFileRoute, retainSearchParams, useNavigate } from "@tanstack/react-router";
import { Suspense, lazy, type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import ChatView from "../components/ChatView";
import { threadHasStarted } from "../components/ChatView.logic";
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
import {
@@ -21,7 +20,8 @@ import { selectEnvironmentState, selectThreadExistsByRef, useStore } from "../st
import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteRef, buildThreadRouteParams } from "../threadRoutes";
import { Sheet, SheetPopup } from "../components/ui/sheet";
import { Sidebar, SidebarInset, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
import { useWorkspaceStore } from "../workspace/store";
const DiffPanel = lazy(() => import("../components/DiffPanel"));
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
@@ -164,6 +164,7 @@ const DiffPanelInlineSidebar = (props: {
function ChatThreadRouteView() {
const navigate = useNavigate();
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const threadRef = Route.useParams({
select: (params) => resolveThreadRouteRef(params),
});
@@ -248,6 +249,20 @@ function ChatThreadRouteView() {
}
}, [bootstrapComplete, environmentHasAnyThreads, navigate, routeThreadExists, threadRef]);
useEffect(() => {
if (!threadRef || !bootstrapComplete || !routeThreadExists) {
return;
}
openThreadSurface(
{
scope: "server",
threadRef,
},
"focus-or-tab",
);
}, [bootstrapComplete, openThreadSurface, routeThreadExists, threadRef]);
useEffect(() => {
if (!threadRef || !serverThreadStarted || !draftThread?.promotedTo) {
return;
@@ -263,40 +278,19 @@ function ChatThreadRouteView() {
if (!shouldUseDiffSheet) {
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView
environmentId={threadRef.environmentId}
threadId={threadRef.threadId}
onDiffPanelOpen={markDiffOpened}
reserveTitleBarControlInset={!diffOpen}
routeKind="server"
/>
</SidebarInset>
<DiffPanelInlineSidebar
diffOpen={diffOpen}
onCloseDiff={closeDiff}
onOpenDiff={openDiff}
renderDiffContent={shouldRenderDiffContent}
/>
</>
<DiffPanelInlineSidebar
diffOpen={diffOpen}
onCloseDiff={closeDiff}
onOpenDiff={openDiff}
renderDiffContent={shouldRenderDiffContent}
/>
);
}
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView
environmentId={threadRef.environmentId}
threadId={threadRef.threadId}
onDiffPanelOpen={markDiffOpened}
routeKind="server"
/>
</SidebarInset>
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
{shouldRenderDiffContent ? <LazyDiffPanel mode="sheet" /> : null}
</DiffPanelSheet>
</>
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
{shouldRenderDiffContent ? <LazyDiffPanel mode="sheet" /> : null}
</DiffPanelSheet>
);
}
+20 -21
View File
@@ -1,15 +1,15 @@
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useMemo } from "react";
import ChatView from "../components/ChatView";
import { threadHasStarted } from "../components/ChatView.logic";
import { useComposerDraftStore, DraftId } from "../composerDraftStore";
import { SidebarInset } from "../components/ui/sidebar";
import { createThreadSelectorAcrossEnvironments } from "../storeSelectors";
import { useStore } from "../store";
import { buildThreadRouteParams } from "../threadRoutes";
import { useWorkspaceStore } from "../workspace/store";
function DraftChatThreadRouteView() {
const navigate = useNavigate();
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const { draftId: rawDraftId } = Route.useParams();
const draftId = DraftId.make(rawDraftId);
const draftSession = useComposerDraftStore((store) => store.getDraftSession(draftId));
@@ -53,32 +53,31 @@ function DraftChatThreadRouteView() {
void navigate({ to: "/", replace: true });
}, [canonicalThreadRef, draftSession, navigate]);
if (canonicalThreadRef) {
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView
environmentId={canonicalThreadRef.environmentId}
threadId={canonicalThreadRef.threadId}
routeKind="server"
/>
</SidebarInset>
useEffect(() => {
if (!draftSession || canonicalThreadRef) {
return;
}
openThreadSurface(
{
scope: "draft",
draftId,
environmentId: draftSession.environmentId,
threadId: draftSession.threadId,
},
"focus-or-tab",
);
}, [canonicalThreadRef, draftId, draftSession, openThreadSurface]);
if (canonicalThreadRef) {
return null;
}
if (!draftSession) {
return null;
}
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView
draftId={draftId}
environmentId={draftSession.environmentId}
threadId={draftSession.threadId}
routeKind="draft"
/>
</SidebarInset>
);
return null;
}
export const Route = createFileRoute("/_chat/draft/$draftId")({
+1 -3
View File
@@ -1,9 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { NoActiveThreadState } from "../components/NoActiveThreadState";
function ChatIndexRouteView() {
return <NoActiveThreadState />;
return null;
}
export const Route = createFileRoute("/_chat/")({
+46 -7
View File
@@ -2,6 +2,11 @@ import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
import { useEffect } from "react";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { WorkspaceShell } from "../components/workspace/WorkspaceShell";
import {
isWorkspaceCommandId,
useWorkspaceCommandExecutor,
} from "../hooks/useWorkspaceCommandExecutor";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import {
startNewLocalThreadFromContext,
@@ -9,8 +14,9 @@ import {
} from "../lib/chatThreadActions";
import { isTerminalFocused } from "../lib/terminalFocus";
import { resolveShortcutCommand } from "../keybindings";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { useWorkspaceThreadTerminalOpen } from "../workspace/store";
import { useFocusedWorkspaceSurface, useWorkspaceStore } from "../workspace/store";
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
import { useSettings } from "~/hooks/useSettings";
import { useServerKeybindings } from "~/rpc/serverState";
@@ -20,12 +26,11 @@ function ChatRouteGlobalShortcuts() {
const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
useHandleNewThread();
const { executeWorkspaceCommand } = useWorkspaceCommandExecutor();
const focusedWorkspaceSurface = useFocusedWorkspaceSurface();
const closeFocusedWindow = useWorkspaceStore((state) => state.closeFocusedWindow);
const keybindings = useServerKeybindings();
const terminalOpen = useTerminalStateStore((state) =>
routeThreadRef
? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
const terminalOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
const appSettings = useSettings();
useEffect(() => {
@@ -37,11 +42,41 @@ function ChatRouteGlobalShortcuts() {
terminalOpen,
},
});
if (useCommandPaletteStore.getState().open) {
return;
}
const isFocusedStandaloneTerminal = focusedWorkspaceSurface?.kind === "terminal";
if (command && isWorkspaceCommandId(command)) {
event.preventDefault();
event.stopPropagation();
void executeWorkspaceCommand(command);
return;
}
if (isFocusedStandaloneTerminal) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
void executeWorkspaceCommand("workspace.terminal.splitRight");
return;
}
if (command === "terminal.new") {
event.preventDefault();
event.stopPropagation();
void executeWorkspaceCommand("workspace.terminal.newTab");
return;
}
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
closeFocusedWindow();
return;
}
}
if (event.key === "Escape" && selectedThreadKeysSize > 0) {
event.preventDefault();
clearSelection();
@@ -86,9 +121,12 @@ function ChatRouteGlobalShortcuts() {
activeDraftThread,
activeThread,
clearSelection,
closeFocusedWindow,
handleNewThread,
keybindings,
defaultProjectRef,
executeWorkspaceCommand,
focusedWorkspaceSurface,
selectedThreadKeysSize,
terminalOpen,
appSettings.defaultThreadEnvMode,
@@ -101,6 +139,7 @@ function ChatRouteLayout() {
return (
<>
<ChatRouteGlobalShortcuts />
<WorkspaceShell />
<Outlet />
</>
);
+25
View File
@@ -0,0 +1,25 @@
import { create } from "zustand";
import type { ThreadSurfaceInput } from "./types";
export type WorkspaceDragItem =
| {
kind: "surface";
surfaceId: string;
}
| {
kind: "thread";
input: ThreadSurfaceInput;
};
interface WorkspaceDragStoreState {
item: WorkspaceDragItem | null;
clearItem: () => void;
setItem: (item: WorkspaceDragItem) => void;
}
export const useWorkspaceDragStore = create<WorkspaceDragStoreState>()((set) => ({
item: null,
clearItem: () => set({ item: null }),
setItem: (item) => set({ item }),
}));
+746
View File
@@ -0,0 +1,746 @@
import { scopeThreadRef } from "@t3tools/client-runtime";
import { afterEach, describe, expect, it, vi } from "vitest";
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => {
store.clear();
},
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
};
}
function getTestWindow(): Window & typeof globalThis {
const localStorage = createLocalStorageStub();
const testWindow = {
localStorage,
setTimeout: globalThis.setTimeout.bind(globalThis),
clearTimeout: globalThis.clearTimeout.bind(globalThis),
} as Window & typeof globalThis;
vi.stubGlobal("window", testWindow);
vi.stubGlobal("localStorage", localStorage);
return testWindow;
}
afterEach(() => {
vi.useRealTimers();
vi.resetModules();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("workspace store", () => {
it("focuses an existing thread surface instead of duplicating it by default", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const initialDocument = useWorkspaceStore.getState().document;
const windowId = Object.keys(initialDocument.windowsById)[0]!;
const initialSurfaceId = initialDocument.windowsById[windowId]!.activeTabId;
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(nextDocument.windowsById[windowId]!.tabIds).toEqual([initialSurfaceId]);
expect(nextDocument.windowsById[windowId]!.activeTabId).toBe(initialSurfaceId);
});
it("does not rewrite workspace state when refocusing the already active surface", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const initialDocument = useWorkspaceStore.getState().document;
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
expect(useWorkspaceStore.getState().document).toBe(initialDocument);
});
it("collapses the split tree when closing the last tab in a window", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const splitDocument = useWorkspaceStore.getState().document;
expect(Object.keys(splitDocument.windowsById)).toHaveLength(2);
expect(splitDocument.rootNodeId).not.toBeNull();
expect(splitDocument.nodesById[splitDocument.rootNodeId!]?.kind).toBe("split");
const closingWindowId = splitDocument.focusedWindowId!;
const closingSurfaceId = splitDocument.windowsById[closingWindowId]!.activeTabId!;
useWorkspaceStore.getState().closeSurface(closingSurfaceId);
const collapsedDocument = useWorkspaceStore.getState().document;
expect(Object.keys(collapsedDocument.windowsById)).toHaveLength(1);
expect(collapsedDocument.rootNodeId).not.toBeNull();
expect(collapsedDocument.nodesById[collapsedDocument.rootNodeId!]?.kind).toBe("window");
});
it("creates one terminal surface per thread and toggles it off cleanly", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
useWorkspaceStore.getState().ensureTerminalSurfaceForThread(threadRef);
let document = useWorkspaceStore.getState().document;
expect(
Object.values(document.surfacesById).filter((surface) => surface.kind === "terminal"),
).toHaveLength(1);
useWorkspaceStore.getState().ensureTerminalSurfaceForThread(threadRef);
document = useWorkspaceStore.getState().document;
expect(
Object.values(document.surfacesById).filter((surface) => surface.kind === "terminal"),
).toHaveLength(1);
useWorkspaceStore.getState().toggleTerminalSurfaceForThread(threadRef);
document = useWorkspaceStore.getState().document;
expect(
Object.values(document.surfacesById).filter((surface) => surface.kind === "terminal"),
).toHaveLength(0);
});
it("opens a terminal surface as a tab in the focused window", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const initialDocument = useWorkspaceStore.getState().document;
const windowId = initialDocument.focusedWindowId!;
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "new-tab");
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(nextDocument.windowsById[windowId]!.tabIds).toHaveLength(2);
const activeSurfaceId = nextDocument.windowsById[windowId]!.activeTabId!;
expect(nextDocument.surfacesById[activeSurfaceId]?.kind).toBe("terminal");
});
it("opens an additional terminal tab when explicitly requested", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "new-tab");
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "new-tab");
const nextDocument = useWorkspaceStore.getState().document;
const windowId = nextDocument.focusedWindowId!;
const terminalSurfaces = Object.values(nextDocument.surfacesById).filter(
(surface) => surface.kind === "terminal",
);
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(terminalSurfaces).toHaveLength(2);
expect(new Set(terminalSurfaces.map((surface) => surface.input.terminalId)).size).toBe(2);
expect(nextDocument.windowsById[windowId]!.tabIds).toHaveLength(3);
});
it("opens a terminal surface in a split when requested", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "split-right");
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(2);
const activeWindowId = nextDocument.focusedWindowId!;
const activeSurfaceId = nextDocument.windowsById[activeWindowId]!.activeTabId!;
expect(nextDocument.surfacesById[activeSurfaceId]?.kind).toBe("terminal");
});
it("creates a new terminal split even when one already exists for the thread", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "split-right");
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "split-right");
const nextDocument = useWorkspaceStore.getState().document;
const terminalSurfaces = Object.values(nextDocument.surfacesById).filter(
(surface) => surface.kind === "terminal",
);
expect(Object.keys(nextDocument.windowsById)).toHaveLength(3);
expect(terminalSurfaces).toHaveLength(2);
expect(new Set(terminalSurfaces.map((surface) => surface.input.terminalId)).size).toBe(2);
});
it("splits terminal panes into a new terminal session instead of duplicating the same one", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "new-tab");
const terminalWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().splitWindowSurface(terminalWindowId, "x");
const nextDocument = useWorkspaceStore.getState().document;
const terminalSurfaces = Object.values(nextDocument.surfacesById).filter(
(surface) => surface.kind === "terminal",
);
expect(terminalSurfaces).toHaveLength(2);
expect(new Set(terminalSurfaces.map((surface) => surface.input.terminalId)).size).toBe(2);
});
it("splits the active surface in the selected window", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const initialDocument = useWorkspaceStore.getState().document;
const sourceWindowId = initialDocument.focusedWindowId!;
const sourceSurfaceId = initialDocument.windowsById[sourceWindowId]!.activeTabId!;
useWorkspaceStore.getState().splitWindowSurface(sourceWindowId, "x");
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(2);
const newWindowId = nextDocument.focusedWindowId!;
expect(newWindowId).not.toBe(sourceWindowId);
const newSurfaceId = nextDocument.windowsById[newWindowId]!.activeTabId!;
expect(newSurfaceId).not.toBe(sourceSurfaceId);
expect(nextDocument.surfacesById[newSurfaceId]?.kind).toBe("thread");
expect(nextDocument.nodesById[nextDocument.rootNodeId!]?.kind).toBe("split");
});
it("rebalances same-axis auto splits evenly when adding a third pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
const nextDocument = useWorkspaceStore.getState().document;
const rootNode = nextDocument.nodesById[nextDocument.rootNodeId!];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(rootNode.childIds).toHaveLength(3);
expect(rootNode.sizingMode).toBe("auto");
expect(rootNode.sizes).toEqual([1 / 3, 1 / 3, 1 / 3]);
});
it("persists resized split proportions on the workspace node", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const splitNodeId = useWorkspaceStore.getState().document.rootNodeId!;
useWorkspaceStore.getState().setSplitNodeSizes(splitNodeId, [1, 3]);
const nextDocument = useWorkspaceStore.getState().document;
const splitNode = nextDocument.nodesById[splitNodeId];
expect(splitNode?.kind).toBe("split");
if (splitNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(splitNode.sizes).toEqual([0.25, 0.75]);
expect(splitNode.sizingMode).toBe("manual");
});
it("keeps manual same-axis splits local when adding another pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const rootNodeId = useWorkspaceStore.getState().document.rootNodeId!;
useWorkspaceStore.getState().setSplitNodeSizes(rootNodeId, [0.7, 0.3]);
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
const nextDocument = useWorkspaceStore.getState().document;
const rootNode = nextDocument.nodesById[rootNodeId];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(rootNode.childIds).toHaveLength(2);
expect(rootNode.sizingMode).toBe("manual");
expect(rootNode.sizes).toEqual([0.7, 0.3]);
const nestedNode = nextDocument.nodesById[rootNode.childIds[1]!];
expect(nestedNode?.kind).toBe("split");
if (nestedNode?.kind !== "split") {
throw new Error("Expected nested split node");
}
expect(nestedNode.axis).toBe("x");
expect(nestedNode.sizingMode).toBe("auto");
expect(nestedNode.childIds).toHaveLength(2);
});
it("rebalances auto split groups after closing a pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
let document = useWorkspaceStore.getState().document;
const rootNode = document.nodesById[document.rootNodeId!];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
const middleNode = rootNode.childIds[1] ? document.nodesById[rootNode.childIds[1]!] : null;
const middleWindowId = middleNode?.kind === "window" ? middleNode.windowId : null;
if (!middleWindowId) {
throw new Error("Expected middle window node");
}
const middleSurfaceId = document.windowsById[middleWindowId]!.activeTabId!;
useWorkspaceStore.getState().closeSurface(middleSurfaceId);
document = useWorkspaceStore.getState().document;
const nextRootNode = document.nodesById[document.rootNodeId!];
expect(nextRootNode?.kind).toBe("split");
if (nextRootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(nextRootNode.childIds).toHaveLength(2);
expect(nextRootNode.sizingMode).toBe("auto");
expect(nextRootNode.sizes).toEqual([0.5, 0.5]);
});
it("preserves remaining proportions after closing a pane in a manual split group", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
const rootNodeId = useWorkspaceStore.getState().document.rootNodeId!;
useWorkspaceStore.getState().setSplitNodeSizes(rootNodeId, [0.2, 0.3, 0.5]);
let document = useWorkspaceStore.getState().document;
const rootNode = document.nodesById[rootNodeId];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
const middleNode = rootNode.childIds[1] ? document.nodesById[rootNode.childIds[1]!] : null;
const middleWindowId = middleNode?.kind === "window" ? middleNode.windowId : null;
if (!middleWindowId) {
throw new Error("Expected middle window node");
}
const middleSurfaceId = document.windowsById[middleWindowId]!.activeTabId!;
useWorkspaceStore.getState().closeSurface(middleSurfaceId);
document = useWorkspaceStore.getState().document;
const nextRootNode = document.nodesById[document.rootNodeId!];
expect(nextRootNode?.kind).toBe("split");
if (nextRootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(nextRootNode.childIds).toHaveLength(2);
expect(nextRootNode.sizingMode).toBe("manual");
expect(nextRootNode.sizes[0]).toBeCloseTo(2 / 7);
expect(nextRootNode.sizes[1]).toBeCloseTo(5 / 7);
});
it("focuses the adjacent pane in the requested direction", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const rightWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().focusAdjacentWindow("left");
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.focusedWindowId).not.toBe(rightWindowId);
expect(nextDocument.focusedWindowId).toBe(nextDocument.mobileActiveWindowId);
});
it("cycles focus between panes in previous and next order", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
const leftWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const rightWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().focusWindowByStep(-1);
expect(useWorkspaceStore.getState().document.focusedWindowId).toBe(leftWindowId);
useWorkspaceStore.getState().focusWindowByStep(1);
expect(useWorkspaceStore.getState().document.focusedWindowId).toBe(rightWindowId);
});
it("resizes the focused pane toward an adjacent pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const beforeDocument = useWorkspaceStore.getState().document;
const rootNode = beforeDocument.nodesById[beforeDocument.rootNodeId!];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
const beforeSizes = [...rootNode.sizes];
useWorkspaceStore.getState().resizeFocusedWindow("left");
const nextDocument = useWorkspaceStore.getState().document;
const nextRootNode = nextDocument.nodesById[nextDocument.rootNodeId!];
expect(nextRootNode?.kind).toBe("split");
if (nextRootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(nextRootNode.sizingMode).toBe("manual");
expect(nextRootNode.sizes[1]).toBeGreaterThan(beforeSizes[1] ?? 0);
expect(nextRootNode.sizes[0]).toBeLessThan(beforeSizes[0] ?? 0);
});
it("equalizes splits back to auto sizing", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const splitNodeId = useWorkspaceStore.getState().document.rootNodeId!;
useWorkspaceStore.getState().setSplitNodeSizes(splitNodeId, [1, 3]);
useWorkspaceStore.getState().equalizeSplits();
const nextDocument = useWorkspaceStore.getState().document;
const rootNode = nextDocument.nodesById[splitNodeId];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(rootNode.sizingMode).toBe("auto");
expect(rootNode.sizes).toEqual([0.5, 0.5]);
});
it("toggles zoom for the focused pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
const focusedWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().toggleFocusedWindowZoom();
expect(useWorkspaceStore.getState().zoomedWindowId).toBe(focusedWindowId);
useWorkspaceStore.getState().toggleFocusedWindowZoom();
expect(useWorkspaceStore.getState().zoomedWindowId).toBeNull();
});
it("closes the focused pane and keeps the remaining pane active", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const closingWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().closeFocusedWindow();
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.windowsById[closingWindowId]).toBeUndefined();
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(nextDocument.nodesById[nextDocument.rootNodeId!]?.kind).toBe("window");
});
it("moves the active tab into the adjacent pane and collapses the source pane if empty", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().focusAdjacentWindow("left");
const sourceWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().moveActiveTabToAdjacentWindow("right");
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.windowsById[sourceWindowId]).toBeUndefined();
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
const remainingWindowId = nextDocument.focusedWindowId!;
expect(nextDocument.windowsById[remainingWindowId]!.tabIds).toHaveLength(2);
expect(nextDocument.nodesById[nextDocument.rootNodeId!]?.kind).toBe("window");
});
it("moves a specific surface before another tab when placing it on a tab target", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInNewTab(serverThreadSurfaceInput(threadB));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
let document = useWorkspaceStore.getState().document;
const rightWindowId = document.focusedWindowId!;
useWorkspaceStore.getState().focusAdjacentWindow("left");
document = useWorkspaceStore.getState().document;
const leftWindowId = document.focusedWindowId!;
const sourceSurfaceId = document.windowsById[leftWindowId]!.activeTabId!;
const targetSurfaceId = document.windowsById[rightWindowId]!.activeTabId!;
useWorkspaceStore.getState().placeSurface(sourceSurfaceId, {
kind: "tab",
windowId: rightWindowId,
surfaceId: targetSurfaceId,
});
const nextDocument = useWorkspaceStore.getState().document;
const remainingSurfaceId = document.windowsById[leftWindowId]!.tabIds.find(
(surfaceId) => surfaceId !== sourceSurfaceId,
);
expect(nextDocument.windowsById[leftWindowId]!.tabIds).toEqual([remainingSurfaceId]);
expect(nextDocument.windowsById[rightWindowId]!.tabIds).toEqual([
sourceSurfaceId,
targetSurfaceId,
]);
expect(nextDocument.windowsById[rightWindowId]!.activeTabId).toBe(sourceSurfaceId);
});
it("reuses an existing thread surface when placing a thread onto a target window", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const beforeDocument = useWorkspaceStore.getState().document;
const targetWindowId = beforeDocument.focusedWindowId!;
useWorkspaceStore.getState().placeThreadSurface(serverThreadSurfaceInput(threadA), {
kind: "window",
windowId: targetWindowId,
placement: "center",
});
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.surfacesById)).toHaveLength(2);
expect(nextDocument.windowsById[targetWindowId]!.tabIds).toHaveLength(2);
});
it("splits a window by moving a non-active tab to an edge target", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInNewTab(serverThreadSurfaceInput(threadB));
const beforeDocument = useWorkspaceStore.getState().document;
const windowId = beforeDocument.focusedWindowId!;
const sourceSurfaceId = beforeDocument.windowsById[windowId]!.tabIds[0]!;
useWorkspaceStore.getState().placeSurface(sourceSurfaceId, {
kind: "window",
windowId,
placement: "left",
});
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(2);
expect(nextDocument.nodesById[nextDocument.rootNodeId!]?.kind).toBe("split");
});
it("moves the focused pane by swapping positions with the adjacent pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const beforeDocument = useWorkspaceStore.getState().document;
const rootNode = beforeDocument.nodesById[beforeDocument.rootNodeId!];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
const leftNodeId = rootNode.childIds[0]!;
const rightNodeId = rootNode.childIds[1]!;
const rightWindowId = beforeDocument.focusedWindowId!;
useWorkspaceStore.getState().moveFocusedWindow("left");
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.focusedWindowId).toBe(rightWindowId);
expect(nextDocument.nodesById[leftNodeId]).toMatchObject({
kind: "window",
windowId: rightWindowId,
});
expect(nextDocument.nodesById[rightNodeId]).not.toMatchObject({
kind: "window",
windowId: rightWindowId,
});
});
it("clears the workspace tree when closing the last focused pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().closeFocusedWindow();
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.rootNodeId).toBeNull();
expect(nextDocument.focusedWindowId).toBeNull();
expect(Object.keys(nextDocument.windowsById)).toHaveLength(0);
expect(Object.keys(nextDocument.surfacesById)).toHaveLength(0);
});
it("persists workspace documents after the debounce interval", async () => {
vi.useFakeTimers();
const testWindow = getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { WORKSPACE_DOCUMENT_STORAGE_KEY } = await import("../clientPersistenceStorage");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
expect(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)).toBeNull();
await vi.advanceTimersByTimeAsync(150);
const persisted = JSON.parse(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)!);
expect(persisted.layoutEngine).toBe("split");
expect(persisted.focusedWindowId).not.toBeNull();
});
});
File diff suppressed because it is too large. Load diff
+261
View File
@@ -0,0 +1,261 @@
import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import type { DraftId } from "../composerDraftStore";
import type { ThreadRouteTarget } from "../threadRoutes";
export type WorkspaceAxis = "x" | "y";
export type WorkspaceDirection = "left" | "right" | "up" | "down";
export type WorkspaceDropPlacement = "center" | "left" | "right" | "top" | "bottom";
export type WorkspaceLayoutEngine = "split";
export type WorkspaceSurfaceKind = "thread" | "terminal";
export type WorkspaceSplitSizingMode = "auto" | "manual";
export type ThreadSurfaceInput =
| {
scope: "server";
threadRef: ScopedThreadRef;
}
| {
scope: "draft";
draftId: DraftId;
environmentId: EnvironmentId;
threadId: ThreadId;
};
export interface TerminalSurfaceInput {
scope: "thread";
threadRef: ScopedThreadRef;
terminalId: string;
}
export type WorkspaceSurfaceInstance =
| {
id: string;
kind: "thread";
input: ThreadSurfaceInput;
}
| {
id: string;
kind: "terminal";
input: TerminalSurfaceInput;
};
export interface WorkspaceWindow {
id: string;
tabIds: string[];
activeTabId: string | null;
}
export type WorkspacePlacementTarget =
| {
kind: "window";
windowId: string;
placement: WorkspaceDropPlacement;
}
| {
kind: "tab";
windowId: string;
surfaceId: string;
};
export type WorkspaceNode =
| {
id: string;
kind: "window";
windowId: string;
}
| {
id: string;
kind: "split";
axis: WorkspaceAxis;
childIds: string[];
sizes: number[];
sizingMode: WorkspaceSplitSizingMode;
};
export interface WorkspaceDocument {
version: 1;
layoutEngine: WorkspaceLayoutEngine;
rootNodeId: string | null;
nodesById: Record<string, WorkspaceNode>;
windowsById: Record<string, WorkspaceWindow>;
surfacesById: Record<string, WorkspaceSurfaceInstance>;
focusedWindowId: string | null;
mobileActiveWindowId: string | null;
}
export function createEmptyWorkspaceDocument(): WorkspaceDocument {
return {
version: 1,
layoutEngine: "split",
rootNodeId: null,
nodesById: {},
windowsById: {},
surfacesById: {},
focusedWindowId: null,
mobileActiveWindowId: null,
};
}
export function normalizeWorkspaceSplitSizes(
sizes: number[] | null | undefined,
childCount: number,
): number[] {
if (childCount <= 0) {
return [];
}
const fallback = Array.from({ length: childCount }, () => 1 / childCount);
if (!sizes || sizes.length !== childCount) {
return fallback;
}
const finiteSizes = sizes.map((size) => (Number.isFinite(size) && size > 0 ? size : 0));
const total = finiteSizes.reduce((sum, size) => sum + size, 0);
if (total <= 0) {
return fallback;
}
return finiteSizes.map((size) => size / total);
}
export function isWorkspaceDocument(value: unknown): value is WorkspaceDocument {
if (!value || typeof value !== "object") {
return false;
}
const candidate = value as Partial<WorkspaceDocument>;
return candidate.version === 1 && candidate.layoutEngine === "split";
}
export function sameThreadSurfaceInput(
left: ThreadSurfaceInput | null | undefined,
right: ThreadSurfaceInput | null | undefined,
): boolean {
if (!left || !right || left.scope !== right.scope) {
return false;
}
if (left.scope === "server" && right.scope === "server") {
return (
left.threadRef.environmentId === right.threadRef.environmentId &&
left.threadRef.threadId === right.threadRef.threadId
);
}
if (left.scope !== "draft" || right.scope !== "draft") {
return false;
}
return (
left.draftId === right.draftId &&
left.environmentId === right.environmentId &&
left.threadId === right.threadId
);
}
export function sameTerminalSurfaceInput(
left: TerminalSurfaceInput | null | undefined,
right: TerminalSurfaceInput | null | undefined,
): boolean {
if (!left || !right) {
return false;
}
return (
left.scope === right.scope &&
left.threadRef.environmentId === right.threadRef.environmentId &&
left.threadRef.threadId === right.threadRef.threadId &&
left.terminalId === right.terminalId
);
}
export function sameWorkspaceSurface(
left: WorkspaceSurfaceInstance | null | undefined,
right: WorkspaceSurfaceInstance | null | undefined,
): boolean {
if (!left || !right || left.kind !== right.kind) {
return false;
}
if (left.kind === "thread" && right.kind === "thread") {
return sameThreadSurfaceInput(left.input, right.input);
}
if (left.kind === "terminal" && right.kind === "terminal") {
return sameTerminalSurfaceInput(left.input, right.input);
}
return false;
}
export function routeTargetForSurface(
surface: WorkspaceSurfaceInstance | null | undefined,
): ThreadRouteTarget | null {
if (!surface) {
return null;
}
if (surface.kind === "thread") {
if (surface.input.scope === "server") {
return {
kind: "server",
threadRef: surface.input.threadRef,
};
}
return {
kind: "draft",
draftId: surface.input.draftId,
};
}
return {
kind: "server",
threadRef: surface.input.threadRef,
};
}
export function normalizeThreadSurfaceInput(input: ThreadSurfaceInput): ThreadSurfaceInput {
if (input.scope === "server") {
return input;
}
return {
scope: "draft",
draftId: input.draftId,
environmentId: input.environmentId,
threadId: input.threadId,
};
}
export function serverThreadSurfaceInput(threadRef: ScopedThreadRef): ThreadSurfaceInput {
return {
scope: "server",
threadRef,
};
}
export function draftThreadSurfaceInput(input: {
draftId: DraftId;
environmentId: EnvironmentId;
threadId: ThreadId;
}): ThreadSurfaceInput {
return {
scope: "draft",
draftId: input.draftId,
environmentId: input.environmentId,
threadId: input.threadId,
};
}
export function terminalSurfaceInput(
threadRef: ScopedThreadRef,
terminalId: string,
): TerminalSurfaceInput {
return {
scope: "thread",
threadRef,
terminalId,
};
}
+26
View File
@@ -32,6 +32,32 @@ const STATIC_KEYBINDING_COMMANDS = [
"terminal.split",
"terminal.new",
"terminal.close",
"workspace.terminal.splitRight",
"workspace.terminal.splitDown",
"workspace.terminal.newTab",
"workspace.pane.splitRight",
"workspace.pane.splitDown",
"workspace.focus.previous",
"workspace.focus.next",
"workspace.focus.left",
"workspace.focus.right",
"workspace.focus.up",
"workspace.focus.down",
"workspace.pane.close",
"workspace.pane.toggleZoom",
"workspace.pane.resizeLeft",
"workspace.pane.resizeRight",
"workspace.pane.resizeUp",
"workspace.pane.resizeDown",
"workspace.pane.equalize",
"workspace.pane.moveLeft",
"workspace.pane.moveRight",
"workspace.pane.moveUp",
"workspace.pane.moveDown",
"workspace.tab.moveLeft",
"workspace.tab.moveRight",
"workspace.tab.moveUp",
"workspace.tab.moveDown",
"diff.toggle",
"commandPalette.toggle",
"chat.new",