Compare commits

...
Author SHA1 Message Date
Julius Marminge b5281f994e Add composable chat and workspace layout modes
- Move thread terminal into an inline chat drawer
- Add split/paper workspace layout switching and scrolling
- Update route sync, command palette, and tests for new state
2026-04-15 17:40:23 -07: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
29 changed files with 6538 additions and 502 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,53 @@ 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",
surfaceId: "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 }),
}));
+169 -379
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 { 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";
@@ -126,8 +120,8 @@ import {
import {
appendTerminalContextsToPrompt,
formatTerminalContextLabel,
type TerminalContextDraft,
type TerminalContextSelection,
type TerminalContextDraft,
} from "../lib/terminalContext";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
@@ -140,8 +134,8 @@ import { NoActiveThreadState } from "./NoActiveThreadState";
import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
collectUserMessageBlobPreviewUrls,
@@ -155,7 +149,6 @@ import {
cloneComposerImageForRetry,
deriveLockedProvider,
readFileAsDataUrl,
reconcileMountedTerminalThreadIds,
resolveSendEnvMode,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
@@ -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[]>([]);
@@ -683,9 +502,6 @@ export default function ChatView(props: ChatViewProps) {
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [terminalLaunchContext, setTerminalLaunchContext] = useState<TerminalLaunchContext | null>(
null,
);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -704,51 +520,44 @@ 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 storeEnsureTerminal = useTerminalStateStore((s) => s.ensureTerminal);
const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen);
const storeSetTerminalHeight = useTerminalStateStore((s) => s.setTerminalHeight);
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 addTerminalContext = useComposerDraftStore((state) => state.addTerminalContext);
const fallbackDraftProjectRef = draftThread
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
@@ -789,10 +598,6 @@ 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 activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
@@ -807,21 +612,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 +1193,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,26 +1201,13 @@ 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: terminalState.terminalOpen,
},
}),
[terminalState.terminalOpen],
@@ -1438,18 +1216,6 @@ export default function ChatView(props: ChatViewProps) {
() => 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,31 +1309,39 @@ 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 terminalDrawerOpen = terminalState.terminalOpen;
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadRef) return;
setTerminalOpen(!terminalState.terminalOpen);
}, [activeThreadRef, setTerminalOpen, terminalState.terminalOpen]);
const nextOpen = !terminalDrawerOpen;
if (nextOpen) {
const terminalId =
terminalState.activeTerminalId ||
terminalState.terminalIds[0] ||
DEFAULT_THREAD_TERMINAL_ID;
storeEnsureTerminal(activeThreadRef, terminalId, { open: true, active: true });
setTerminalFocusRequestId((current) => current + 1);
return;
}
storeSetTerminalOpen(activeThreadRef, false);
}, [
activeThreadRef,
storeEnsureTerminal,
storeSetTerminalOpen,
terminalDrawerOpen,
terminalState.activeTerminalId,
terminalState.terminalIds,
]);
const splitTerminal = useCallback(() => {
if (!activeThreadRef || hasReachedSplitLimit) return;
const terminalId = `terminal-${randomUUID()}`;
storeSplitTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
setTerminalFocusRequestId((current) => current + 1);
}, [activeThreadRef, hasReachedSplitLimit, storeSplitTerminal]);
const createNewTerminal = useCallback(() => {
if (!activeThreadRef) return;
const terminalId = `terminal-${randomUUID()}`;
storeNewTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
setTerminalFocusRequestId((current) => current + 1);
}, [activeThreadRef, storeNewTerminal]);
const closeTerminal = useCallback(
(terminalId: string) => {
@@ -1597,7 +1371,6 @@ export default function ChatView(props: ChatViewProps) {
if (activeThreadRef) {
storeCloseTerminal(activeThreadRef, terminalId);
}
setTerminalFocusRequestId((value) => value + 1);
},
[
activeThreadId,
@@ -1607,6 +1380,17 @@ export default function ChatView(props: ChatViewProps) {
terminalState.terminalIds.length,
],
);
const handleAddTerminalContext = useCallback(
(selection: TerminalContextSelection) => {
addTerminalContext(routeThreadRef, {
...selection,
id: randomUUID(),
threadId: routeThreadRef.threadId,
createdAt: new Date().toISOString(),
});
},
[addTerminalContext, routeThreadRef],
);
const runProjectScript = useCallback(
async (
script: ProjectScript,
@@ -1639,21 +1423,20 @@ 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,
});
if (shouldCreateNewTerminal) {
storeNewTerminal(activeThreadRef, targetTerminalId);
} else {
storeSetActiveTerminal(activeThreadRef, targetTerminalId);
storeEnsureTerminal(activeThreadRef, targetTerminalId, { open: true, active: true });
}
setTerminalFocusRequestId((value) => value + 1);
storeSetTerminalOpen(activeThreadRef, true);
setTerminalFocusRequestId((current) => current + 1);
const runtimeEnv = projectScriptRuntimeEnv({
project: {
@@ -1700,10 +1483,11 @@ export default function ChatView(props: ChatViewProps) {
activeThreadId,
activeThreadRef,
gitCwd,
setTerminalOpen,
setThreadError,
storeEnsureTerminal,
storeNewTerminal,
storeSetActiveTerminal,
storeSetTerminalLaunchContext,
storeSetTerminalOpen,
setLastInvokedScriptByProjectId,
environmentId,
terminalState.activeTerminalId,
@@ -1711,6 +1495,26 @@ export default function ChatView(props: ChatViewProps) {
terminalState.terminalIds,
],
);
const terminalDrawerWorktreePath =
storeServerTerminalLaunchContext?.worktreePath ?? activeThread?.worktreePath ?? null;
const terminalDrawerCwd =
storeServerTerminalLaunchContext?.cwd ??
(activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
worktreePath: terminalDrawerWorktreePath,
})
: null);
const terminalDrawerRuntimeEnv = useMemo(
() =>
activeProject
? projectScriptRuntimeEnv({
project: { cwd: activeProject.cwd },
worktreePath: terminalDrawerWorktreePath,
})
: {},
[activeProject, terminalDrawerWorktreePath],
);
const persistProjectScripts = useCallback(
async (input: {
@@ -1994,14 +1798,21 @@ export default function ChatView(props: ChatViewProps) {
}, [activeThread?.id]);
useEffect(() => {
if (!activeThread?.id || terminalState.terminalOpen) return;
if (!activeThread?.id || terminalDrawerOpen) return;
const frame = window.requestAnimationFrame(() => {
focusComposer();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [activeThread?.id, focusComposer, terminalState.terminalOpen]);
}, [activeThread?.id, focusComposer, terminalDrawerOpen]);
useLayoutEffect(() => {
if (activationFocusRequestId === undefined) {
return;
}
focusComposer();
}, [activationFocusRequestId, focusComposer]);
useEffect(() => {
if (!activeThread?.id) return;
@@ -2086,48 +1897,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 +1928,21 @@ export default function ChatView(props: ChatViewProps) {
]);
useEffect(() => {
if (terminalState.terminalOpen) {
if (terminalDrawerOpen) {
return;
}
if (activeThreadRef) {
storeClearTerminalLaunchContext(activeThreadRef);
}
setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current));
}, [
activeThreadId,
activeThreadRef,
storeClearTerminalLaunchContext,
terminalState.terminalOpen,
]);
}, [activeThreadRef, storeClearTerminalLaunchContext, terminalDrawerOpen]);
useEffect(() => {
if (!activeThreadKey) return;
const previous = terminalOpenByThreadRef.current[activeThreadKey] ?? false;
const current = Boolean(terminalState.terminalOpen);
const current = terminalDrawerOpen;
if (!previous && current) {
terminalOpenByThreadRef.current[activeThreadKey] = current;
setTerminalFocusRequestId((value) => value + 1);
return;
} else if (previous && !current) {
terminalOpenByThreadRef.current[activeThreadKey] = current;
@@ -2188,7 +1955,7 @@ export default function ChatView(props: ChatViewProps) {
}
terminalOpenByThreadRef.current[activeThreadKey] = current;
}, [activeThreadKey, focusComposer, terminalState.terminalOpen]);
}, [activeThreadKey, focusComposer, terminalDrawerOpen]);
useEffect(() => {
const handler = (event: globalThis.KeyboardEvent) => {
@@ -2197,7 +1964,7 @@ export default function ChatView(props: ChatViewProps) {
}
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(terminalState.terminalOpen),
terminalOpen: terminalDrawerOpen,
};
const command = resolveShortcutCommand(event, keybindings, {
@@ -2205,6 +1972,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 +1989,8 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
if (!terminalDrawerOpen && activeThreadRef) {
storeSetTerminalOpen(activeThreadRef, true);
}
splitTerminal();
return;
@@ -2225,7 +1999,7 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) return;
if (!terminalDrawerOpen) return;
closeTerminal(terminalState.activeTerminalId);
return;
}
@@ -2233,8 +2007,8 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.new") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
if (!terminalDrawerOpen && activeThreadRef) {
storeSetTerminalOpen(activeThreadRef, true);
}
createNewTerminal();
return;
@@ -2259,16 +2033,18 @@ export default function ChatView(props: ChatViewProps) {
return () => window.removeEventListener("keydown", handler);
}, [
activeProject,
terminalState.terminalOpen,
terminalState.activeTerminalId,
activeThreadRef,
activeThreadId,
closeTerminal,
createNewTerminal,
setTerminalOpen,
executeWorkspaceCommand,
runProjectScript,
splitTerminal,
keybindings,
onToggleDiff,
storeSetTerminalOpen,
terminalDrawerOpen,
toggleTerminalVisibility,
]);
@@ -3171,7 +2947,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 +2976,7 @@ export default function ChatView(props: ChatViewProps) {
keybindings={keybindings}
availableEditors={availableEditors}
terminalAvailable={activeProject !== undefined}
terminalOpen={terminalState.terminalOpen}
terminalOpen={terminalDrawerOpen}
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
diffToggleShortcutLabel={diffPanelShortcutLabel}
gitCwd={gitCwd}
@@ -3271,6 +3047,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}
@@ -3336,6 +3113,36 @@ export default function ChatView(props: ChatViewProps) {
/>
</div>
{terminalDrawerOpen && activeThreadId && activeProject && terminalDrawerCwd ? (
<div className="min-h-0 px-3 pb-3 sm:px-5">
<ThreadTerminalDrawer
threadRef={routeThreadRef}
threadId={activeThreadId}
cwd={terminalDrawerCwd}
worktreePath={terminalDrawerWorktreePath}
runtimeEnv={terminalDrawerRuntimeEnv}
visible={terminalDrawerOpen}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
onActiveTerminalChange={(terminalId) => {
storeSetActiveTerminal(routeThreadRef, terminalId);
setTerminalFocusRequestId((current) => current + 1);
}}
onCloseTerminal={closeTerminal}
onHeightChange={(height) => {
storeSetTerminalHeight(routeThreadRef, height);
}}
onAddTerminalContext={handleAddTerminalContext}
/>
</div>
) : null}
{isGitRepo && (
<BranchToolbar
environmentId={activeThread.environmentId}
@@ -3403,23 +3210,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} />
)}
+355 -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,10 @@ import {
selectSidebarThreadsAcrossEnvironments,
useStore,
} from "../store";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { useThreadTerminalOpen } from "../terminalStateStore";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
import { useWorkspaceStore } from "../workspace/store";
import { serverThreadSurfaceInput } from "../workspace/types";
import {
ADDON_ICON_CLASS,
buildProjectActionItems,
@@ -80,11 +91,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 = useThreadTerminalOpen(routeThreadRef);
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
@@ -108,8 +115,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 +143,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 +158,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 +274,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 +326,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 +384,246 @@ 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");
},
});
}
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:settings",
@@ -337,23 +636,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 +728,7 @@ function OpenCommandPaletteDialog() {
}}
>
<Command
key={viewStack.length}
key={`${viewStack.length}-${workspaceTarget?.disposition ?? "root"}`}
aria-label="Command palette"
autoHighlight="always"
mode="none"
@@ -408,7 +749,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) => {
+100 -18
View File
@@ -68,7 +68,11 @@ import {
selectThreadByRef,
useStore,
} from "../store";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import {
selectThreadTerminalState,
useTerminalStateStore,
useThreadTerminalOpen,
} from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
import {
resolveShortcutCommand,
@@ -141,15 +145,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, type WorkspaceLayoutEngine } from "../workspace/types";
import { useWorkspaceDragStore } from "../workspace/dragStore";
import { useWorkspaceLayoutEngine, useWorkspaceStore } from "../workspace/store";
import type { Project, SidebarThreadSummary } from "../types";
const THREAD_PREVIEW_LIMIT = 6;
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
@@ -570,6 +577,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 +641,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 +1036,7 @@ 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 openThreadInSplit = useWorkspaceStore((state) => state.openThreadInSplit);
const clearComposerDraftForThread = useComposerDraftStore((state) => state.clearDraftThread);
const getDraftThreadByProjectRef = useComposerDraftStore(
(state) => state.getDraftThreadByProjectRef,
@@ -1636,6 +1665,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const threadWorkspacePath = thread.worktreePath ?? project.cwd ?? null;
const clicked = await api.contextMenu.show(
[
{ 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 +1676,24 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
position,
);
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 +1741,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyThreadIdToClipboard,
deleteThread,
markThreadUnread,
openThreadInSplit,
project.cwd,
router,
],
);
@@ -2001,6 +2052,8 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
const SidebarChromeFooter = memo(function SidebarChromeFooter() {
const navigate = useNavigate();
const layoutEngine = useWorkspaceLayoutEngine();
const setLayoutEngine = useWorkspaceStore((state) => state.setLayoutEngine);
const handleSettingsClick = useCallback(() => {
void navigate({ to: "/settings" });
}, [navigate]);
@@ -2020,10 +2073,41 @@ const SidebarChromeFooter = memo(function SidebarChromeFooter() {
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
<div className="mt-2 flex items-center gap-1 px-2">
<span className="text-[11px] text-muted-foreground/70">Layout</span>
<WorkspaceLayoutToggle
layoutEngine={layoutEngine}
onSelect={(engine) => setLayoutEngine(engine)}
/>
</div>
</SidebarFooter>
);
});
const WorkspaceLayoutToggle = memo(function WorkspaceLayoutToggle(props: {
layoutEngine: WorkspaceLayoutEngine;
onSelect: (engine: WorkspaceLayoutEngine) => void;
}) {
return (
<div className="ml-auto flex items-center gap-1">
{(["split", "paper"] as const).map((engine) => (
<button
key={engine}
type="button"
className={
props.layoutEngine === engine
? "rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground"
: "rounded-md border border-border/60 px-2 py-1 text-[11px] text-muted-foreground transition hover:bg-accent hover:text-foreground"
}
onClick={() => props.onSelect(engine)}
>
{engine === "split" ? "Split" : "Paper"}
</button>
))}
</div>
);
});
interface SidebarProjectsContentProps {
showArm64IntelBuildWarning: boolean;
arm64IntelBuildWarningDescription: string | null;
@@ -2062,6 +2146,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 +2199,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
routeThreadKey,
newThreadShortcutLabel,
commandPaletteShortcutLabel,
onOpenCommandPalette,
threadJumpLabelByKey,
attachThreadListAutoAnimateRef,
expandThreadListForProject,
@@ -2163,14 +2249,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 +2263,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
{commandPaletteShortcutLabel}
</Kbd>
) : null}
</CommandDialogTrigger>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
@@ -2390,7 +2474,9 @@ export default function Sidebar() {
select: (params) => resolveThreadRouteRef(params),
});
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
const routeThreadTerminalOpen = useThreadTerminalOpen(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 +2638,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 +3322,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-replace");
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: {},
});
}
File diff suppressed because it is too large. Load diff
+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,286 @@
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.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",
] 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.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"],
},
};
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 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.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;
}
},
[
closeFocusedWindow,
equalizeSplits,
focusAdjacentWindow,
focusWindowByStep,
focusedThreadRef,
focusedWindowId,
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-replace",
);
}, [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-replace",
);
}, [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/")({
+45 -6
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 { useThreadTerminalOpen } from "../terminalStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
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 = useThreadTerminalOpen(routeThreadRef);
const appSettings = useSettings();
useEffect(() => {
@@ -37,6 +42,36 @@ function ChatRouteGlobalShortcuts() {
terminalOpen,
},
});
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.splitDown");
return;
}
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
closeFocusedWindow();
return;
}
}
if (useCommandPaletteStore.getState().open) {
return;
@@ -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 />
</>
);
+6
View File
@@ -519,6 +519,12 @@ export function selectThreadTerminalState(
return terminalStateByThreadKey[terminalThreadKey(threadRef)] ?? getDefaultThreadTerminalState();
}
export function useThreadTerminalOpen(threadRef: ScopedThreadRef | null | undefined): boolean {
return useTerminalStateStore(
(state) => selectThreadTerminalState(state.terminalStateByThreadKey, threadRef).terminalOpen,
);
}
function updateTerminalStateByThreadKey(
terminalStateByThreadKey: Record<string, ThreadTerminalState>,
threadRef: ScopedThreadRef,
+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 }),
}));
+844
View File
@@ -0,0 +1,844 @@
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]!.surfaceId;
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(nextDocument.windowsById[windowId]!.surfaceId).toBe(initialSurfaceId);
expect(Object.keys(nextDocument.surfacesById)).toHaveLength(1);
});
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("normalizes legacy persisted tab-based workspace documents on load", async () => {
const testWindow = getTestWindow();
const { WORKSPACE_DOCUMENT_STORAGE_KEY } = await import("../clientPersistenceStorage");
testWindow.localStorage.setItem(
WORKSPACE_DOCUMENT_STORAGE_KEY,
JSON.stringify({
version: 1,
layoutEngine: "split",
rootNodeId: "node-1",
nodesById: {
"node-1": {
id: "node-1",
kind: "window",
windowId: "window-1",
},
},
windowsById: {
"window-1": {
id: "window-1",
tabIds: ["surface-1"],
activeTabId: "surface-1",
},
},
surfacesById: {
"surface-1": {
id: "surface-1",
kind: "thread",
input: {
scope: "server",
threadRef: {
environmentId: "environment-a",
threadId: "thread-a",
},
},
},
},
focusedWindowId: "window-1",
mobileActiveWindowId: "window-1",
}),
);
const { useWorkspaceStore } = await import("./store");
expect(useWorkspaceStore.getState().document.windowsById["window-1"]).toEqual({
id: "window-1",
surfaceId: "surface-1",
});
});
it("collapses the split tree when closing the last pane 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]!.surfaceId!;
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("replaces the focused pane with a terminal surface 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 = initialDocument.focusedWindowId!;
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef);
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(nextDocument.windowsById[windowId]!.surfaceId).not.toBe(
initialDocument.windowsById[windowId]!.surfaceId,
);
expect(nextDocument.surfacesById[nextDocument.windowsById[windowId]!.surfaceId!]?.kind).toBe(
"terminal",
);
});
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]!.surfaceId!;
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);
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]!.surfaceId!;
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]!.surfaceId!;
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]!.surfaceId!;
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]!.surfaceId!;
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("swaps an existing thread surface onto the target pane when placed in the center", 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().placeThreadSurface(serverThreadSurfaceInput(threadA), {
kind: "window",
windowId: rightWindowId,
placement: "center",
});
const nextDocument = useWorkspaceStore.getState().document;
const leftSurfaceId = nextDocument.windowsById[leftWindowId]!.surfaceId!;
const rightSurfaceId = nextDocument.windowsById[rightWindowId]!.surfaceId!;
expect(Object.keys(nextDocument.surfacesById)).toHaveLength(2);
expect(nextDocument.surfacesById[rightSurfaceId]?.kind).toBe("thread");
expect(nextDocument.surfacesById[rightSurfaceId]?.input).toEqual(
serverThreadSurfaceInput(threadA),
);
expect(nextDocument.surfacesById[leftSurfaceId]?.input).toEqual(
serverThreadSurfaceInput(threadB),
);
});
it("replaces the target pane with a new thread surface when placed in the center", 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 targetWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().placeThreadSurface(serverThreadSurfaceInput(threadB), {
kind: "window",
windowId: targetWindowId,
placement: "center",
});
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(Object.keys(nextDocument.surfacesById)).toHaveLength(1);
expect(
nextDocument.surfacesById[nextDocument.windowsById[targetWindowId]!.surfaceId!]?.input,
).toEqual(serverThreadSurfaceInput(threadB));
});
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("converts an existing split workspace into paper columns", 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().setLayoutEngine("paper");
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.layoutEngine).toBe("paper");
const rootNode = nextDocument.nodesById[nextDocument.rootNodeId!];
expect(rootNode?.kind).toBe("paper-root");
if (rootNode?.kind !== "paper-root") {
throw new Error("Expected paper root");
}
expect(rootNode.childIds).toHaveLength(2);
expect(rootNode.widths).toEqual([1, 1]);
for (const columnId of rootNode.childIds) {
const column = nextDocument.nodesById[columnId];
expect(column?.kind).toBe("paper-column");
if (column?.kind !== "paper-column") {
throw new Error("Expected paper column");
}
expect(column.childIds).toHaveLength(1);
}
});
it("stacks split-down panes inside a paper column and split-right creates a new column", 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().setLayoutEngine("paper");
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "y");
useWorkspaceStore.getState().focusAdjacentWindow("up");
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
const nextDocument = useWorkspaceStore.getState().document;
const rootNode = nextDocument.nodesById[nextDocument.rootNodeId!];
expect(rootNode?.kind).toBe("paper-root");
if (rootNode?.kind !== "paper-root") {
throw new Error("Expected paper root");
}
expect(rootNode.childIds).toHaveLength(2);
const firstColumn = nextDocument.nodesById[rootNode.childIds[0]!];
const secondColumn = nextDocument.nodesById[rootNode.childIds[1]!];
expect(firstColumn?.kind).toBe("paper-column");
expect(secondColumn?.kind).toBe("paper-column");
if (firstColumn?.kind !== "paper-column" || secondColumn?.kind !== "paper-column") {
throw new Error("Expected paper columns");
}
expect(firstColumn.childIds).toHaveLength(2);
expect(secondColumn.childIds).toHaveLength(1);
});
it("resizes paper columns by adjusting neighboring widths", 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().setLayoutEngine("paper");
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const beforeDocument = useWorkspaceStore.getState().document;
const beforeRoot = beforeDocument.nodesById[beforeDocument.rootNodeId!];
expect(beforeRoot?.kind).toBe("paper-root");
if (beforeRoot?.kind !== "paper-root") {
throw new Error("Expected paper root");
}
useWorkspaceStore.getState().resizeFocusedWindow("left");
const nextDocument = useWorkspaceStore.getState().document;
const nextRoot = nextDocument.nodesById[nextDocument.rootNodeId!];
expect(nextRoot?.kind).toBe("paper-root");
if (nextRoot?.kind !== "paper-root") {
throw new Error("Expected paper root");
}
expect(nextRoot.sizingMode).toBe("manual");
expect(nextRoot.widths[1]).toBeGreaterThan(beforeRoot.widths[1] ?? 0);
expect(nextRoot.widths[0]).toBeLessThan(beforeRoot.widths[0] ?? 0);
});
it("removes an empty paper column when its last pane closes", 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().setLayoutEngine("paper");
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().closeFocusedWindow();
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.layoutEngine).toBe("paper");
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
const rootNode = nextDocument.nodesById[nextDocument.rootNodeId!];
expect(rootNode?.kind).toBe("paper-root");
if (rootNode?.kind !== "paper-root") {
throw new Error("Expected paper root");
}
expect(rootNode.childIds).toHaveLength(1);
});
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
+288
View File
@@ -0,0 +1,288 @@
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" | "paper";
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;
surfaceId: string | null;
}
export interface WorkspacePlacementTarget {
kind: "window";
windowId: string;
placement: WorkspaceDropPlacement;
}
export type WorkspaceNode =
| {
id: string;
kind: "window";
windowId: string;
}
| {
id: string;
kind: "split";
axis: WorkspaceAxis;
childIds: string[];
sizes: number[];
sizingMode: WorkspaceSplitSizingMode;
}
| {
id: string;
kind: "paper-root";
childIds: string[];
widths: number[];
sizingMode: WorkspaceSplitSizingMode;
}
| {
id: string;
kind: "paper-column";
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(
layoutEngine: WorkspaceLayoutEngine = "split",
): WorkspaceDocument {
return {
version: 1,
layoutEngine,
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 normalizeWorkspacePaperColumnWidths(
widths: number[] | null | undefined,
childCount: number,
): number[] {
if (childCount <= 0) {
return [];
}
if (!widths || widths.length !== childCount) {
return Array.from({ length: childCount }, () => 1);
}
return widths.map((width) => (Number.isFinite(width) && width > 0 ? width : 1));
}
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" || candidate.layoutEngine === "paper")
);
}
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,
};
}
+21
View File
@@ -32,6 +32,27 @@ const STATIC_KEYBINDING_COMMANDS = [
"terminal.split",
"terminal.new",
"terminal.close",
"workspace.terminal.splitRight",
"workspace.terminal.splitDown",
"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",
"diff.toggle",
"commandPalette.toggle",
"chat.new",