Compare commits

...
Author SHA1 Message Date
Cursor Agent dc4ee0b932 Remove dead code and fix sidebar split/tab navigation conflict
- Remove unused `nowTick` state variable from ChatView
- Remove unused `terminalFocusRequestId` state variable from ChatView
- Delete unused `WorkspaceRouteSync` component
- Remove redundant router.navigate() calls from sidebar split/tab context menu handlers that conflicted with route-level openThreadSurface("focus-or-tab")
2026-04-14 02:49:37 +00: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
19 changed files with 3597 additions and 486 deletions

No files matched your search

@@ -77,4 +77,54 @@ describe("clientPersistenceStorage", () => {
],
});
});
it("reads and writes workspace documents as JSON blobs", async () => {
const testWindow = getTestWindow();
const {
WORKSPACE_DOCUMENT_STORAGE_KEY,
readBrowserWorkspaceDocument,
writeBrowserWorkspaceDocument,
} = await import("./clientPersistenceStorage");
const workspaceDocument = {
version: 1 as const,
layoutEngine: "split" as const,
rootNodeId: "node-1",
nodesById: {
"node-1": {
id: "node-1",
kind: "window" as const,
windowId: "window-1",
},
},
windowsById: {
"window-1": {
id: "window-1",
tabIds: ["surface-1"],
activeTabId: "surface-1",
},
},
surfacesById: {
"surface-1": {
id: "surface-1",
kind: "thread" as const,
input: {
scope: "server" as const,
threadRef: {
environmentId: testEnvironmentId,
threadId: "thread-1",
},
},
},
},
focusedWindowId: "window-1",
mobileActiveWindowId: "window-1",
};
writeBrowserWorkspaceDocument(workspaceDocument);
expect(readBrowserWorkspaceDocument<typeof workspaceDocument>()).toEqual(workspaceDocument);
expect(JSON.parse(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)!)).toEqual(
workspaceDocument,
);
});
});
+37
View File
@@ -11,6 +11,7 @@ import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorag
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
export const WORKSPACE_DOCUMENT_STORAGE_KEY = "t3code:workspace-document:v1";
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
environmentId: EnvironmentId,
@@ -34,6 +35,34 @@ function hasWindow(): boolean {
return typeof window !== "undefined";
}
function readBrowserJsonDocument<T>(storageKey: string): T | null {
if (!hasWindow()) {
return null;
}
try {
const raw = window.localStorage.getItem(storageKey);
if (!raw) {
return null;
}
return JSON.parse(raw) as T;
} catch {
return null;
}
}
function writeBrowserJsonDocument<T>(storageKey: string, document: T): void {
if (!hasWindow()) {
return;
}
try {
window.localStorage.setItem(storageKey, JSON.stringify(document));
} catch {
// Ignore quota/storage errors to avoid breaking the app.
}
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
@@ -192,3 +221,11 @@ export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentId
}),
});
}
export function readBrowserWorkspaceDocument<T>(): T | null {
return readBrowserJsonDocument<T>(WORKSPACE_DOCUMENT_STORAGE_KEY);
}
export function writeBrowserWorkspaceDocument<T>(document: T): void {
writeBrowserJsonDocument(WORKSPACE_DOCUMENT_STORAGE_KEY, document);
}
+16 -2
View File
@@ -1,13 +1,27 @@
import { create } from "zustand";
export interface CommandPaletteWorkspaceTarget {
disposition: "split-right" | "split-down";
}
interface CommandPaletteStore {
open: boolean;
workspaceTarget: CommandPaletteWorkspaceTarget | null;
setOpen: (open: boolean) => void;
toggleOpen: () => void;
openWorkspaceTarget: (target: CommandPaletteWorkspaceTarget) => void;
clearWorkspaceTarget: () => void;
}
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
open: false,
setOpen: (open) => set({ open }),
toggleOpen: () => set((state) => ({ open: !state.open })),
workspaceTarget: null,
setOpen: (open) => set({ open, ...(open ? {} : { workspaceTarget: null }) }),
toggleOpen: () =>
set((state) => ({
open: !state.open,
...(!state.open ? {} : { workspaceTarget: null }),
})),
openWorkspaceTarget: (target) => set({ open: true, workspaceTarget: target }),
clearWorkspaceTarget: () => set({ workspaceTarget: null }),
}));
+70 -380
View File
@@ -19,12 +19,7 @@ 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";
@@ -66,11 +61,7 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import {
selectProjectsAcrossEnvironments,
selectThreadsAcrossEnvironments,
useStore,
} from "../store";
import { selectProjectsAcrossEnvironments, useStore } from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
@@ -89,13 +80,16 @@ import {
type TurnDiffSummary,
} from "../types";
import { useTheme } from "../hooks/useTheme";
import {
isWorkspaceCommandId,
useWorkspaceCommandExecutor,
} from "../hooks/useWorkspaceCommandExecutor";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon } from "lucide-react";
import { cn, randomUUID } from "~/lib/utils";
import { toastManager } from "./ui/toast";
@@ -127,7 +121,6 @@ import {
appendTerminalContextsToPrompt,
formatTerminalContextLabel,
type TerminalContextDraft,
type TerminalContextSelection,
} from "../lib/terminalContext";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
@@ -141,7 +134,6 @@ import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./Branch
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
collectUserMessageBlobPreviewUrls,
@@ -171,6 +163,7 @@ import {
} from "~/rpc/serverState";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { retainThreadDetailSubscription } from "../environments/runtime/service";
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -312,6 +305,7 @@ const SCRIPT_TERMINAL_ROWS = 30;
type ChatViewProps =
| {
bindSharedComposerHandle?: boolean;
environmentId: EnvironmentId;
threadId: ThreadId;
onDiffPanelOpen?: () => void;
@@ -320,6 +314,7 @@ type ChatViewProps =
draftId?: never;
}
| {
bindSharedComposerHandle?: boolean;
environmentId: EnvironmentId;
threadId: ThreadId;
onDiffPanelOpen?: () => void;
@@ -328,14 +323,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 +390,9 @@ 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 {
bindSharedComposerHandle = true,
environmentId,
threadId,
routeKind,
@@ -654,7 +469,10 @@ 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 = bindSharedComposerHandle
? (sharedComposerRef ?? localComposerRef)
: localComposerRef;
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
@@ -680,12 +498,8 @@ export default function ChatView(props: ChatViewProps) {
// When set, the thread-change reset effect will open the sidebar instead of closing it.
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
const planSidebarOpenOnNextThreadRef = useRef(false);
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [terminalLaunchContext, setTerminalLaunchContext] = useState<TerminalLaunchContext | null>(
null,
);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -707,48 +521,17 @@ export default function ChatView(props: ChatViewProps) {
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef),
);
const openTerminalThreadKeys = useTerminalStateStore(
useShallow((state) =>
Object.entries(state.terminalStateByThreadKey).flatMap(([nextThreadKey, nextTerminalState]) =>
nextTerminalState.terminalOpen ? [nextThreadKey] : [],
),
),
);
const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen);
const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal);
const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
const serverThreadKeys = useStore(
useShallow((state) =>
selectThreadsAcrossEnvironments(state).map((thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
),
),
);
const storeSetTerminalLaunchContext = useTerminalStateStore((s) => s.setTerminalLaunchContext);
const storeServerTerminalLaunchContext = useTerminalStateStore(
(s) => s.terminalLaunchContextByThreadKey[scopedThreadKey(routeThreadRef)] ?? null,
);
const storeClearTerminalLaunchContext = useTerminalStateStore(
(s) => s.clearTerminalLaunchContext,
);
const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);
const draftThreadKeys = useMemo(
() =>
Object.values(draftThreadsByThreadKey).map((draftThread) =>
scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)),
),
[draftThreadsByThreadKey],
);
const [mountedTerminalThreadKeys, setMountedTerminalThreadKeys] = useState<string[]>([]);
const mountedTerminalThreadRefs = useMemo(
() =>
mountedTerminalThreadKeys.flatMap((mountedThreadKey) => {
const mountedThreadRef = parseScopedThreadKey(mountedThreadKey);
return mountedThreadRef ? [{ key: mountedThreadKey, threadRef: mountedThreadRef }] : [];
}),
[mountedTerminalThreadKeys],
);
const fallbackDraftProjectRef = draftThread
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
@@ -789,10 +572,16 @@ export default function ChatView(props: ChatViewProps) {
[activeThread],
);
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
const existingOpenTerminalThreadKeys = useMemo(() => {
const existingThreadKeys = new Set<string>([...serverThreadKeys, ...draftThreadKeys]);
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
const terminalSurfaceOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
const ensureTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.ensureTerminalSurfaceForThread,
);
const toggleTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.toggleTerminalSurfaceForThread,
);
const closeTerminalSurfacesForThread = useWorkspaceStore(
(state) => state.closeTerminalSurfacesForThread,
);
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
@@ -807,21 +596,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 +1177,7 @@ export default function ChatView(props: ChatViewProps) {
const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd });
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const { executeWorkspaceCommand } = useWorkspaceCommandExecutor();
const activeProviderStatus = useMemo(
() => providerStatuses.find((status) => status.provider === selectedProvider) ?? null,
[selectedProvider, providerStatuses],
@@ -1410,46 +1185,21 @@ export default function ChatView(props: ChatViewProps) {
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
const activeTerminalLaunchContext =
terminalLaunchContext?.threadId === activeThreadId
? terminalLaunchContext
: (storeServerTerminalLaunchContext ?? null);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
terminalFocus: true,
terminalOpen: Boolean(terminalState.terminalOpen),
},
}),
[terminalState.terminalOpen],
);
const nonTerminalShortcutLabelOptions = useMemo(
() => ({
context: {
terminalFocus: false,
terminalOpen: Boolean(terminalState.terminalOpen),
terminalOpen: terminalSurfaceOpen,
},
}),
[terminalState.terminalOpen],
[terminalSurfaceOpen],
);
const terminalToggleShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.toggle"),
[keybindings],
);
const splitTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const newTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const closeTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions),
[keybindings, terminalShortcutLabelOptions],
);
const diffPanelShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "diff.toggle", nonTerminalShortcutLabelOptions),
[keybindings, nonTerminalShortcutLabelOptions],
@@ -1543,32 +1293,22 @@ export default function ChatView(props: ChatViewProps) {
focusComposer();
});
}, [focusComposer]);
const addTerminalContextToDraft = useCallback((selection: TerminalContextSelection) => {
composerRef.current?.addTerminalContext(selection);
}, []);
const setTerminalOpen = useCallback(
(open: boolean) => {
if (!activeThreadRef) return;
storeSetTerminalOpen(activeThreadRef, open);
},
[activeThreadRef, storeSetTerminalOpen],
);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadRef) return;
setTerminalOpen(!terminalState.terminalOpen);
}, [activeThreadRef, setTerminalOpen, terminalState.terminalOpen]);
toggleTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, toggleTerminalSurfaceForThread]);
const splitTerminal = useCallback(() => {
if (!activeThreadRef || hasReachedSplitLimit) return;
const terminalId = `terminal-${randomUUID()}`;
storeSplitTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadRef, hasReachedSplitLimit, storeSplitTerminal]);
ensureTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, ensureTerminalSurfaceForThread, hasReachedSplitLimit, storeSplitTerminal]);
const createNewTerminal = useCallback(() => {
if (!activeThreadRef) return;
const terminalId = `terminal-${randomUUID()}`;
storeNewTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadRef, storeNewTerminal]);
ensureTerminalSurfaceForThread(activeThreadRef);
}, [activeThreadRef, ensureTerminalSurfaceForThread, storeNewTerminal]);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readEnvironmentApi(environmentId);
@@ -1596,12 +1336,15 @@ export default function ChatView(props: ChatViewProps) {
}
if (activeThreadRef) {
storeCloseTerminal(activeThreadRef, terminalId);
if (isFinalTerminal) {
closeTerminalSurfacesForThread(activeThreadRef);
}
}
setTerminalFocusRequestId((value) => value + 1);
},
[
activeThreadId,
activeThreadRef,
closeTerminalSurfacesForThread,
environmentId,
storeCloseTerminal,
terminalState.terminalIds.length,
@@ -1639,21 +1382,19 @@ export default function ChatView(props: ChatViewProps) {
: baseTerminalId;
const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
setTerminalLaunchContext({
threadId: activeThreadId,
cwd: targetCwd,
worktreePath: targetWorktreePath,
});
setTerminalOpen(true);
if (!activeThreadRef) {
return;
}
storeSetTerminalLaunchContext(activeThreadRef, {
cwd: targetCwd,
worktreePath: targetWorktreePath,
});
ensureTerminalSurfaceForThread(activeThreadRef);
if (shouldCreateNewTerminal) {
storeNewTerminal(activeThreadRef, targetTerminalId);
} else {
storeSetActiveTerminal(activeThreadRef, targetTerminalId);
}
setTerminalFocusRequestId((value) => value + 1);
const runtimeEnv = projectScriptRuntimeEnv({
project: {
@@ -1699,10 +1440,11 @@ export default function ChatView(props: ChatViewProps) {
activeThread,
activeThreadId,
activeThreadRef,
ensureTerminalSurfaceForThread,
gitCwd,
setTerminalOpen,
setThreadError,
storeNewTerminal,
storeSetTerminalLaunchContext,
storeSetActiveTerminal,
setLastInvokedScriptByProjectId,
environmentId,
@@ -1994,14 +1736,14 @@ export default function ChatView(props: ChatViewProps) {
}, [activeThread?.id]);
useEffect(() => {
if (!activeThread?.id || terminalState.terminalOpen) return;
if (!activeThread?.id || terminalSurfaceOpen) return;
const frame = window.requestAnimationFrame(() => {
focusComposer();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [activeThread?.id, focusComposer, terminalState.terminalOpen]);
}, [activeThread?.id, focusComposer, terminalSurfaceOpen]);
useEffect(() => {
if (!activeThread?.id) return;
@@ -2086,48 +1828,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 +1859,21 @@ export default function ChatView(props: ChatViewProps) {
]);
useEffect(() => {
if (terminalState.terminalOpen) {
if (terminalSurfaceOpen) {
return;
}
if (activeThreadRef) {
storeClearTerminalLaunchContext(activeThreadRef);
}
setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current));
}, [
activeThreadId,
activeThreadRef,
storeClearTerminalLaunchContext,
terminalState.terminalOpen,
]);
}, [activeThreadRef, storeClearTerminalLaunchContext, terminalSurfaceOpen]);
useEffect(() => {
if (!activeThreadKey) return;
const previous = terminalOpenByThreadRef.current[activeThreadKey] ?? false;
const current = Boolean(terminalState.terminalOpen);
const current = terminalSurfaceOpen;
if (!previous && current) {
terminalOpenByThreadRef.current[activeThreadKey] = current;
setTerminalFocusRequestId((value) => value + 1);
return;
} else if (previous && !current) {
terminalOpenByThreadRef.current[activeThreadKey] = current;
@@ -2188,7 +1886,7 @@ export default function ChatView(props: ChatViewProps) {
}
terminalOpenByThreadRef.current[activeThreadKey] = current;
}, [activeThreadKey, focusComposer, terminalState.terminalOpen]);
}, [activeThreadKey, focusComposer, terminalSurfaceOpen]);
useEffect(() => {
const handler = (event: globalThis.KeyboardEvent) => {
@@ -2197,7 +1895,7 @@ export default function ChatView(props: ChatViewProps) {
}
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(terminalState.terminalOpen),
terminalOpen: terminalSurfaceOpen,
};
const command = resolveShortcutCommand(event, keybindings, {
@@ -2205,6 +1903,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 +1920,8 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
if (!terminalSurfaceOpen && activeThreadRef) {
ensureTerminalSurfaceForThread(activeThreadRef);
}
splitTerminal();
return;
@@ -2225,7 +1930,7 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) return;
if (!terminalSurfaceOpen) return;
closeTerminal(terminalState.activeTerminalId);
return;
}
@@ -2233,8 +1938,8 @@ export default function ChatView(props: ChatViewProps) {
if (command === "terminal.new") {
event.preventDefault();
event.stopPropagation();
if (!terminalState.terminalOpen) {
setTerminalOpen(true);
if (!terminalSurfaceOpen && activeThreadRef) {
ensureTerminalSurfaceForThread(activeThreadRef);
}
createNewTerminal();
return;
@@ -2259,16 +1964,18 @@ export default function ChatView(props: ChatViewProps) {
return () => window.removeEventListener("keydown", handler);
}, [
activeProject,
terminalState.terminalOpen,
terminalState.activeTerminalId,
activeThreadRef,
activeThreadId,
closeTerminal,
createNewTerminal,
setTerminalOpen,
executeWorkspaceCommand,
ensureTerminalSurfaceForThread,
runProjectScript,
splitTerminal,
keybindings,
onToggleDiff,
terminalSurfaceOpen,
toggleTerminalVisibility,
]);
@@ -3171,7 +2878,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 +2907,7 @@ export default function ChatView(props: ChatViewProps) {
keybindings={keybindings}
availableEditors={availableEditors}
terminalAvailable={activeProject !== undefined}
terminalOpen={terminalState.terminalOpen}
terminalOpen={terminalSurfaceOpen}
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
diffToggleShortcutLabel={diffPanelShortcutLabel}
gitCwd={gitCwd}
@@ -3403,23 +3110,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} />
)}
+321 -14
View File
@@ -6,10 +6,15 @@ import { useNavigate, useParams } from "@tanstack/react-router";
import {
ArrowDownIcon,
ArrowLeftIcon,
ArrowRightIcon,
ArrowUpIcon,
Columns2Icon,
MessageSquareIcon,
Rows2Icon,
SettingsIcon,
SquarePenIcon,
TerminalSquareIcon,
XIcon,
} from "lucide-react";
import {
useDeferredValue,
@@ -23,6 +28,10 @@ import {
import { useShallow } from "zustand/react/shallow";
import { useCommandPaletteStore } from "../commandPaletteStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import {
WORKSPACE_COMMAND_METADATA,
useWorkspaceCommandExecutor,
} from "../hooks/useWorkspaceCommandExecutor";
import { useSettings } from "../hooks/useSettings";
import {
startNewThreadInProjectFromContext,
@@ -36,8 +45,9 @@ import {
selectSidebarThreadsAcrossEnvironments,
useStore,
} from "../store";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
import { serverThreadSurfaceInput } from "../workspace/types";
import {
ADDON_ICON_CLASS,
buildProjectActionItems,
@@ -80,11 +90,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
select: (params) => resolveThreadRouteTarget(params),
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const terminalOpen = useTerminalStateStore((state) =>
routeThreadRef
? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
const terminalOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
@@ -108,8 +114,8 @@ export function CommandPalette({ children }: { children: ReactNode }) {
return (
<ComposerHandleContext.Provider value={composerHandleRef}>
{children}
<CommandDialog open={open} onOpenChange={setOpen}>
{children}
<CommandPaletteDialog />
</CommandDialog>
</ComposerHandleContext.Provider>
@@ -136,6 +142,8 @@ function CommandPaletteDialog() {
function OpenCommandPaletteDialog() {
const navigate = useNavigate();
const setOpen = useCommandPaletteStore((store) => store.setOpen);
const workspaceTarget = useCommandPaletteStore((store) => store.workspaceTarget);
const clearWorkspaceTarget = useCommandPaletteStore((store) => store.clearWorkspaceTarget);
const composerHandleRef = useComposerHandleContext();
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
@@ -149,6 +157,13 @@ function OpenCommandPaletteDialog() {
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
const currentView = viewStack.at(-1) ?? null;
const paletteMode = getCommandPaletteMode({ currentView });
const { canOpenTerminalSurface, canSplitFocusedPane, executeWorkspaceCommand } =
useWorkspaceCommandExecutor();
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const workspaceWindowCount = useWorkspaceStore(
(state) => Object.keys(state.document.windowsById).length,
);
const canUseSpatialWorkspaceCommands = workspaceWindowCount > 1;
const projectTitleById = useMemo(
() => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
@@ -258,6 +273,40 @@ function OpenCommandPaletteDialog() {
[activeThreadId, navigate, projectTitleById, settings.sidebarThreadSortOrder, threads],
);
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
const workspaceTargetThreadItems = useMemo(() => {
if (!workspaceTarget) {
return [];
}
return buildThreadActionItems({
threads,
...(activeThreadId ? { activeThreadId } : {}),
projectTitleById,
sortOrder: settings.sidebarThreadSortOrder,
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
runThread: async (thread) => {
openThreadSurface(
serverThreadSurfaceInput(scopeThreadRef(thread.environmentId, thread.id)),
workspaceTarget.disposition,
);
},
});
}, [
activeThreadId,
openThreadSurface,
projectTitleById,
settings.sidebarThreadSortOrder,
threads,
workspaceTarget,
]);
useEffect(() => {
if (!workspaceTarget) {
return;
}
setViewStack([]);
setQuery("");
}, [workspaceTarget]);
function pushView(item: CommandPaletteSubmenuItem): void {
setViewStack((previousViews) => [
@@ -276,6 +325,15 @@ function OpenCommandPaletteDialog() {
setQuery("");
}
function leaveSubmenu(): void {
if (currentView) {
popView();
return;
}
clearWorkspaceTarget();
setQuery("");
}
function handleQueryChange(nextQuery: string): void {
setQuery(nextQuery);
if (nextQuery === "" && currentView?.initialQuery) {
@@ -325,6 +383,213 @@ function OpenCommandPaletteDialog() {
});
}
if (canOpenTerminalSurface) {
actionItems.push({
kind: "action",
value: "action:workspace-terminal-split-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitRight"].title,
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.terminal.splitRight",
run: async () => {
await executeWorkspaceCommand("workspace.terminal.splitRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-terminal-split-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.splitDown"].title,
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.terminal.splitDown",
run: async () => {
await executeWorkspaceCommand("workspace.terminal.splitDown");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-terminal-tab",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.terminal.newTab"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.terminal.newTab"].title,
icon: <TerminalSquareIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.terminal.newTab",
run: async () => {
await executeWorkspaceCommand("workspace.terminal.newTab");
},
});
}
if (canSplitFocusedPane) {
actionItems.push({
kind: "action",
value: "action:workspace-pane-split-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.splitRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.splitRight"].title,
icon: <Columns2Icon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.splitRight",
run: async () => {
await executeWorkspaceCommand("workspace.pane.splitRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-split-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.splitDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.splitDown"].title,
icon: <Rows2Icon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.splitDown",
run: async () => {
await executeWorkspaceCommand("workspace.pane.splitDown");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-close",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.close"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.close"].title,
icon: <XIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.close",
run: async () => {
await executeWorkspaceCommand("workspace.pane.close");
},
});
}
if (canUseSpatialWorkspaceCommands) {
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-move-left",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveLeft"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveLeft"].title,
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.moveLeft",
run: async () => {
await executeWorkspaceCommand("workspace.pane.moveLeft");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-move-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveRight"].title,
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.moveRight",
run: async () => {
await executeWorkspaceCommand("workspace.pane.moveRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-move-up",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveUp"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveUp"].title,
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.moveUp",
run: async () => {
await executeWorkspaceCommand("workspace.pane.moveUp");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-pane-move-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.pane.moveDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.pane.moveDown"].title,
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.pane.moveDown",
run: async () => {
await executeWorkspaceCommand("workspace.pane.moveDown");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-tab-move-left",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveLeft"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveLeft"].title,
icon: <ArrowLeftIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.tab.moveLeft",
run: async () => {
await executeWorkspaceCommand("workspace.tab.moveLeft");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-tab-move-right",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveRight"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveRight"].title,
icon: <ArrowRightIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.tab.moveRight",
run: async () => {
await executeWorkspaceCommand("workspace.tab.moveRight");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-tab-move-up",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveUp"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveUp"].title,
icon: <ArrowUpIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.tab.moveUp",
run: async () => {
await executeWorkspaceCommand("workspace.tab.moveUp");
},
});
actionItems.push({
kind: "action",
value: "action:workspace-tab-move-down",
searchTerms: WORKSPACE_COMMAND_METADATA["workspace.tab.moveDown"].searchTerms,
title: WORKSPACE_COMMAND_METADATA["workspace.tab.moveDown"].title,
icon: <ArrowDownIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "workspace.tab.moveDown",
run: async () => {
await executeWorkspaceCommand("workspace.tab.moveDown");
},
});
}
actionItems.push({
kind: "action",
value: "action:settings",
@@ -337,23 +602,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 +694,7 @@ function OpenCommandPaletteDialog() {
}}
>
<Command
key={viewStack.length}
key={`${viewStack.length}-${workspaceTarget?.disposition ?? "root"}`}
aria-label="Command palette"
autoHighlight="always"
mode="none"
@@ -408,7 +715,7 @@ function OpenCommandPaletteDialog() {
type="button"
className="flex cursor-pointer items-center"
aria-label="Back"
onClick={popView}
onClick={leaveSubmenu}
>
<ArrowLeftIcon />
</button>
+39 -17
View File
@@ -141,15 +141,17 @@ import {
import { sortThreads } from "../lib/threadSort";
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { CommandDialogTrigger } from "./ui/command";
import { readEnvironmentApi } from "../environmentApi";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import { useServerKeybindings } from "../rpc/serverState";
import { deriveLogicalProjectKey } from "../logicalProject";
import { useCommandPaletteStore } from "../commandPaletteStore";
import {
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
import { serverThreadSurfaceInput } from "../workspace/types";
import { useWorkspaceStore, useWorkspaceThreadTerminalOpen } from "../workspace/store";
import type { Project, SidebarThreadSummary } from "../types";
const THREAD_PREVIEW_LIMIT = 6;
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
@@ -1008,6 +1010,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const removeFromSelection = useThreadSelectionStore((state) => state.removeFromSelection);
const setSelectionAnchor = useThreadSelectionStore((state) => state.setAnchor);
const selectedThreadCount = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
const openThreadInNewTab = useWorkspaceStore((state) => state.openThreadInNewTab);
const openThreadInSplit = useWorkspaceStore((state) => state.openThreadInSplit);
const clearComposerDraftForThread = useComposerDraftStore((state) => state.clearDraftThread);
const getDraftThreadByProjectRef = useComposerDraftStore(
(state) => state.getDraftThreadByProjectRef,
@@ -1636,6 +1640,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const threadWorkspacePath = thread.worktreePath ?? project.cwd ?? null;
const clicked = await api.contextMenu.show(
[
{ id: "open-new-tab", label: "Open in new tab" },
{ id: "open-split-right", label: "Open in split right" },
{ id: "open-split-down", label: "Open in split down" },
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy Path" },
@@ -1645,6 +1652,21 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
position,
);
if (clicked === "open-new-tab") {
openThreadInNewTab(serverThreadSurfaceInput(threadRef));
return;
}
if (clicked === "open-split-right") {
openThreadInSplit(serverThreadSurfaceInput(threadRef), "x");
return;
}
if (clicked === "open-split-down") {
openThreadInSplit(serverThreadSurfaceInput(threadRef), "y");
return;
}
if (clicked === "rename") {
setRenamingThreadKey(threadKey);
setRenamingTitle(thread.title);
@@ -1692,6 +1714,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyThreadIdToClipboard,
deleteThread,
markThreadUnread,
openThreadInNewTab,
openThreadInSplit,
project.cwd,
],
);
@@ -2062,6 +2086,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 +2139,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
routeThreadKey,
newThreadShortcutLabel,
commandPaletteShortcutLabel,
onOpenCommandPalette,
threadJumpLabelByKey,
attachThreadListAutoAnimateRef,
expandThreadListForProject,
@@ -2163,14 +2189,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 +2203,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
{commandPaletteShortcutLabel}
</Kbd>
) : null}
</CommandDialogTrigger>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
@@ -2390,7 +2414,9 @@ export default function Sidebar() {
select: (params) => resolveThreadRouteRef(params),
});
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
const routeThreadTerminalOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
const keybindings = useServerKeybindings();
const setCommandPaletteOpen = useCommandPaletteStore((state) => state.setOpen);
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
@@ -2552,14 +2578,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 +3262,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">
+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,182 @@
import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useComposerDraftStore } from "../../composerDraftStore";
import { randomUUID } from "../../lib/utils";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../../storeSelectors";
import { selectThreadTerminalState, useTerminalStateStore } from "../../terminalStateStore";
import ThreadTerminalDrawer from "../ThreadTerminalDrawer";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { readEnvironmentApi } from "../../environmentApi";
import { useStore } from "../../store";
import type { TerminalContextSelection } from "../../lib/terminalContext";
import { useWorkspaceStore } from "../../workspace/store";
export function ThreadTerminalSurface(props: { threadRef: ScopedThreadRef }) {
const { threadRef } = props;
const thread = useStore(useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]));
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
const projectRef = thread
? scopeProjectRef(thread.environmentId, thread.projectId)
: draftThread
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
: null;
const project = useStore(useMemo(() => createProjectSelectorByRef(projectRef), [projectRef]));
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadKey, threadRef),
);
const storeSetActiveTerminal = useTerminalStateStore((state) => state.setActiveTerminal);
const storeNewTerminal = useTerminalStateStore((state) => state.newTerminal);
const storeSplitTerminal = useTerminalStateStore((state) => state.splitTerminal);
const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal);
const storeSetTerminalHeight = useTerminalStateStore((state) => state.setTerminalHeight);
const terminalLaunchContext = useTerminalStateStore(
(state) => state.terminalLaunchContextByThreadKey[scopedThreadKey(threadRef)] ?? null,
);
const addTerminalContext = useComposerDraftStore((state) => state.addTerminalContext);
const closeTerminalSurfacesForThread = useWorkspaceStore(
(state) => state.closeTerminalSurfacesForThread,
);
const [containerHeight, setContainerHeight] = useState(320);
const [focusRequestId, setFocusRequestId] = useState(1);
const containerRef = useRef<HTMLDivElement | null>(null);
const worktreePath = thread?.worktreePath ?? draftThread?.worktreePath ?? null;
const effectiveWorktreePath = terminalLaunchContext?.worktreePath ?? worktreePath;
const cwd = useMemo(
() =>
terminalLaunchContext?.cwd ??
(project
? projectScriptCwd({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: null),
[effectiveWorktreePath, project, terminalLaunchContext?.cwd],
);
const runtimeEnv = useMemo(
() =>
project
? projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: {},
[effectiveWorktreePath, project],
);
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(() => {
setFocusRequestId((current) => current + 1);
}, [terminalState.activeTerminalId]);
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: threadRef.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: threadRef.threadId, terminalId })
.catch(() => undefined);
}
await api.terminal.close({
threadId: threadRef.threadId,
terminalId,
deleteHistory: true,
});
})().catch(() => fallbackExitWrite());
} else {
void fallbackExitWrite();
}
storeCloseTerminal(threadRef, terminalId);
if (isFinalTerminal) {
closeTerminalSurfacesForThread(threadRef);
}
setFocusRequestId((current) => current + 1);
},
[
closeTerminalSurfacesForThread,
storeCloseTerminal,
terminalState.terminalIds.length,
threadRef,
],
);
const handleAddTerminalContext = useCallback(
(selection: TerminalContextSelection) => {
addTerminalContext(threadRef, {
...selection,
id: randomUUID(),
threadId: threadRef.threadId,
createdAt: new Date().toISOString(),
});
},
[addTerminalContext, threadRef],
);
if (!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">
<ThreadTerminalDrawer
threadRef={threadRef}
threadId={threadRef.threadId}
cwd={cwd}
worktreePath={effectiveWorktreePath}
runtimeEnv={runtimeEnv}
visible
height={containerHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={focusRequestId}
onSplitTerminal={() => {
storeSplitTerminal(threadRef, `terminal-${randomUUID()}`);
setFocusRequestId((current) => current + 1);
}}
onNewTerminal={() => {
storeNewTerminal(threadRef, `terminal-${randomUUID()}`);
setFocusRequestId((current) => current + 1);
}}
onActiveTerminalChange={(terminalId) => {
storeSetActiveTerminal(threadRef, terminalId);
setFocusRequestId((current) => current + 1);
}}
onCloseTerminal={closeTerminal}
onHeightChange={(height) => {
storeSetTerminalHeight(threadRef, height);
}}
onAddTerminalContext={handleAddTerminalContext}
showResizeHandle={false}
/>
</div>
);
}
@@ -0,0 +1,556 @@
import { useParams } from "@tanstack/react-router";
import { Rows2Icon, Columns2Icon, TerminalSquareIcon, XIcon } from "lucide-react";
import { Fragment, memo, useCallback, useEffect, useMemo, useRef } from "react";
import { createThreadSelectorByRef } from "../../storeSelectors";
import { useStore } from "../../store";
import { cn } from "../../lib/utils";
import { SidebarInset } from "../ui/sidebar";
import ChatView from "../ChatView";
import { useComposerDraftStore } from "../../composerDraftStore";
import { resolveThreadRouteTarget } from "../../threadRoutes";
import { ThreadTerminalSurface } from "./ThreadTerminalSurface";
import { useWorkspaceDocument, useWorkspaceStore } from "../../workspace/store";
import {
normalizeWorkspaceSplitSizes,
type WorkspaceNode,
type WorkspaceSurfaceInstance,
} from "../../workspace/types";
const WORKSPACE_MIN_PANE_SIZE_PX = 220;
function WorkspaceEmptyState() {
return (
<div className="flex min-h-0 flex-1 items-center justify-center px-6">
<div className="w-full max-w-lg rounded-xl border border-border/55 bg-card/20 px-8 py-12 shadow-sm/5">
<p className="text-xl text-foreground">Pick a thread to continue</p>
<p className="mt-2 text-sm text-muted-foreground/78">
Select an existing thread or create a new one to get started.
</p>
</div>
</div>
);
}
export function WorkspaceShell() {
const document = useWorkspaceDocument();
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
{document.rootNodeId ? <WorkspaceLayoutRoot /> : <WorkspaceRouteFallback />}
</div>
</SidebarInset>
);
}
function WorkspaceRouteFallback() {
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const draftSession = useComposerDraftStore((store) =>
routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
);
useEffect(() => {
if (!routeTarget) {
return;
}
if (routeTarget.kind === "server") {
openThreadSurface(
{
scope: "server",
threadRef: routeTarget.threadRef,
},
"focus-or-tab",
);
return;
}
if (!draftSession) {
return;
}
openThreadSurface(
{
scope: "draft",
draftId: routeTarget.draftId,
environmentId: draftSession.environmentId,
threadId: draftSession.threadId,
},
"focus-or-tab",
);
}, [draftSession, openThreadSurface, routeTarget]);
if (!routeTarget) {
return <WorkspaceEmptyState />;
}
if (routeTarget.kind === "server") {
return (
<ChatView
environmentId={routeTarget.threadRef.environmentId}
threadId={routeTarget.threadRef.threadId}
routeKind="server"
/>
);
}
if (!draftSession) {
return <WorkspaceEmptyState />;
}
return (
<ChatView
draftId={routeTarget.draftId}
environmentId={draftSession.environmentId}
threadId={draftSession.threadId}
routeKind="draft"
/>
);
}
function WorkspaceLayoutRoot() {
const document = useWorkspaceDocument();
const focusedWindowId = useWorkspaceStore((state) => state.document.focusedWindowId);
const mobileActiveWindowId = useWorkspaceStore((state) => state.document.mobileActiveWindowId);
const setMobileActiveWindow = useWorkspaceStore((state) => state.setMobileActiveWindow);
const windowIds = useMemo(
() => Object.keys(document.windowsById).filter((windowId) => document.windowsById[windowId]),
[document.windowsById],
);
return (
<div className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
{windowIds.length > 1 ? (
<div className="flex items-center gap-2 border-b border-border px-3 py-2 md:hidden">
{windowIds.map((windowId, index) => {
const isActive = (mobileActiveWindowId ?? focusedWindowId ?? windowIds[0]) === windowId;
return (
<button
key={windowId}
type="button"
className={cn(
"rounded-md border px-2 py-1 text-xs",
isActive
? "border-border bg-accent text-foreground"
: "border-border/60 text-muted-foreground",
)}
onClick={() => setMobileActiveWindow(windowId)}
>
Window {index + 1}
</button>
);
})}
</div>
) : null}
<div className="min-h-0 min-w-0 flex-1 overflow-hidden md:flex">
<div className="hidden h-full min-h-0 min-w-0 flex-1 overflow-hidden md:flex">
<WorkspaceNodeView nodeId={document.rootNodeId} />
</div>
<div className="flex h-full min-h-0 min-w-0 flex-1 overflow-hidden md:hidden">
<MobileWorkspaceWindow
windowId={mobileActiveWindowId ?? focusedWindowId ?? windowIds[0] ?? null}
/>
</div>
</div>
</div>
);
}
function MobileWorkspaceWindow(props: { windowId: string | null }) {
const document = useWorkspaceDocument();
if (!props.windowId) {
return <WorkspaceEmptyState />;
}
const window = document.windowsById[props.windowId];
if (!window) {
return <WorkspaceEmptyState />;
}
return <WorkspaceWindowView windowId={window.id} />;
}
function WorkspaceNodeView(props: { nodeId: string | null }) {
const document = useWorkspaceDocument();
if (!props.nodeId) {
return null;
}
const node = document.nodesById[props.nodeId];
if (!node) {
return null;
}
if (node.kind === "window") {
return <WorkspaceWindowView windowId={node.windowId} />;
}
return <WorkspaceSplitNodeView node={node} />;
}
function WorkspaceSplitNodeView(props: { node: Extract<WorkspaceNode, { kind: "split" }> }) {
const setSplitNodeSizes = useWorkspaceStore((state) => state.setSplitNodeSizes);
const containerRef = useRef<HTMLDivElement | null>(null);
const resizeStateRef = useRef<{
handle: HTMLButtonElement;
handleIndex: number;
pendingSizes: number[];
pointerId: number;
rafId: number | null;
startCoordinate: number;
startSizes: number[];
totalPx: number;
} | null>(null);
const sizes = useMemo(
() => normalizeWorkspaceSplitSizes(props.node.sizes, props.node.childIds.length),
[props.node.childIds.length, props.node.sizes],
);
const stopResize = useCallback(
(pointerId: number) => {
const resizeState = resizeStateRef.current;
if (!resizeState) {
return;
}
if (resizeState.rafId !== null) {
window.cancelAnimationFrame(resizeState.rafId);
setSplitNodeSizes(props.node.id, resizeState.pendingSizes);
}
resizeStateRef.current = null;
if (resizeState.handle.hasPointerCapture(pointerId)) {
resizeState.handle.releasePointerCapture(pointerId);
}
document.body.style.removeProperty("cursor");
document.body.style.removeProperty("user-select");
},
[props.node.id, setSplitNodeSizes],
);
useEffect(() => {
return () => {
const resizeState = resizeStateRef.current;
if (resizeState && resizeState.rafId !== null) {
window.cancelAnimationFrame(resizeState.rafId);
}
document.body.style.removeProperty("cursor");
document.body.style.removeProperty("user-select");
};
}, []);
const handleResizePointerDown = useCallback(
(handleIndex: number, event: React.PointerEvent<HTMLButtonElement>) => {
if (event.button !== 0) {
return;
}
const container = containerRef.current;
if (!container) {
return;
}
const rect = container.getBoundingClientRect();
const totalPx = props.node.axis === "x" ? rect.width : rect.height;
if (totalPx <= 0) {
return;
}
event.preventDefault();
event.stopPropagation();
resizeStateRef.current = {
handle: event.currentTarget,
handleIndex,
pendingSizes: sizes,
pointerId: event.pointerId,
rafId: null,
startCoordinate: props.node.axis === "x" ? event.clientX : event.clientY,
startSizes: sizes,
totalPx,
};
event.currentTarget.setPointerCapture(event.pointerId);
document.body.style.cursor = props.node.axis === "x" ? "col-resize" : "row-resize";
document.body.style.userSelect = "none";
},
[props.node.axis, sizes],
);
const handleResizePointerMove = useCallback(
(event: React.PointerEvent<HTMLButtonElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) {
return;
}
event.preventDefault();
const deltaPx =
(props.node.axis === "x" ? event.clientX : event.clientY) - resizeState.startCoordinate;
const deltaFraction = deltaPx / resizeState.totalPx;
const pairTotal =
resizeState.startSizes[resizeState.handleIndex]! +
resizeState.startSizes[resizeState.handleIndex + 1]!;
const requestedMinFraction = WORKSPACE_MIN_PANE_SIZE_PX / resizeState.totalPx;
const minFraction = Math.min(requestedMinFraction, Math.max(pairTotal / 2 - 0.001, 0));
const nextBefore = Math.min(
pairTotal - minFraction,
Math.max(minFraction, resizeState.startSizes[resizeState.handleIndex]! + deltaFraction),
);
const nextAfter = pairTotal - nextBefore;
const nextSizes = [...resizeState.startSizes];
nextSizes[resizeState.handleIndex] = nextBefore;
nextSizes[resizeState.handleIndex + 1] = nextAfter;
resizeState.pendingSizes = nextSizes;
if (resizeState.rafId !== null) {
return;
}
resizeState.rafId = window.requestAnimationFrame(() => {
const activeResizeState = resizeStateRef.current;
if (!activeResizeState) {
return;
}
activeResizeState.rafId = null;
setSplitNodeSizes(props.node.id, activeResizeState.pendingSizes);
});
},
[props.node.axis, props.node.id, setSplitNodeSizes],
);
const endResizeInteraction = useCallback(
(event: React.PointerEvent<HTMLButtonElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) {
return;
}
event.preventDefault();
stopResize(event.pointerId);
},
[stopResize],
);
return (
<div
ref={containerRef}
className={cn(
"flex h-full min-h-0 min-w-0 flex-1 overflow-hidden",
props.node.axis === "x" ? "flex-row" : "flex-col",
)}
>
{props.node.childIds.map((childId, index) => (
<Fragment key={childId}>
<div
className="h-full min-h-0 min-w-0 overflow-hidden"
style={{
flexBasis: 0,
flexGrow: sizes[index] ?? 1,
flexShrink: 1,
}}
>
<WorkspaceNodeView nodeId={childId} />
</div>
{index < props.node.childIds.length - 1 ? (
<button
type="button"
className={cn(
"relative z-10 shrink-0 bg-border/80 transition hover:bg-foreground/40",
props.node.axis === "x"
? "h-full w-1 cursor-col-resize touch-none"
: "h-1 w-full cursor-row-resize touch-none",
)}
aria-label={
props.node.axis === "x" ? "Resize panes horizontally" : "Resize panes vertically"
}
title={props.node.axis === "x" ? "Drag to resize panes" : "Drag to resize panes"}
onPointerCancel={endResizeInteraction}
onPointerDown={(event) => handleResizePointerDown(index, event)}
onPointerMove={handleResizePointerMove}
onPointerUp={endResizeInteraction}
>
<span
className={cn(
"pointer-events-none absolute rounded-full bg-background/90",
props.node.axis === "x"
? "top-1/2 left-1/2 h-10 w-px -translate-x-1/2 -translate-y-1/2"
: "top-1/2 left-1/2 h-px w-10 -translate-x-1/2 -translate-y-1/2",
)}
/>
</button>
) : null}
</Fragment>
))}
</div>
);
}
const WorkspaceWindowView = memo(function WorkspaceWindowView(props: { windowId: string }) {
const document = useWorkspaceDocument();
const focusWindow = useWorkspaceStore((state) => state.focusWindow);
const focusTab = useWorkspaceStore((state) => state.focusTab);
const closeSurface = useWorkspaceStore((state) => state.closeSurface);
const splitWindowSurface = useWorkspaceStore((state) => state.splitWindowSurface);
const window = document.windowsById[props.windowId];
const focusedWindowId = document.focusedWindowId;
if (!window) {
return null;
}
const activeSurface = window.activeTabId ? document.surfacesById[window.activeTabId] : null;
return (
<section
className={cn(
"flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden border border-border/70 bg-background",
focusedWindowId === props.windowId ? "ring-1 ring-border/80" : "",
)}
onMouseDown={() => focusWindow(props.windowId)}
>
<div className="flex min-w-0 items-center gap-1 border-b border-border/70 bg-muted/20 px-2 py-1.5">
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto">
{window.tabIds.map((surfaceId) => {
const surface = document.surfacesById[surfaceId];
if (!surface) {
return null;
}
const isActive = window.activeTabId === surfaceId;
return (
<div
key={surfaceId}
className={cn(
"group flex max-w-[18rem] min-w-0 items-center gap-1 rounded-md border px-2 py-1 text-xs",
isActive
? "border-border bg-background text-foreground"
: "border-transparent text-muted-foreground hover:bg-accent/50",
)}
>
<button
type="button"
className="min-w-0 flex-1 truncate text-left"
onClick={() => focusTab(props.windowId, surfaceId)}
>
<WorkspaceSurfaceTitle surface={surface} />
</button>
<button
type="button"
className="rounded-sm p-0.5 text-muted-foreground opacity-0 transition group-hover:opacity-100 hover:bg-accent hover:text-foreground"
onClick={() => closeSurface(surfaceId)}
aria-label="Close tab"
>
<XIcon className="size-3" />
</button>
</div>
);
})}
</div>
<div className="hidden items-center gap-1 md:flex">
<button
type="button"
className="rounded-sm p-1 text-muted-foreground transition hover:bg-accent hover:text-foreground"
onClick={() => splitWindowSurface(props.windowId, "x")}
aria-label="Split active tab right"
title="Split active tab right"
>
<Columns2Icon className="size-3.5" />
</button>
<button
type="button"
className="rounded-sm p-1 text-muted-foreground transition hover:bg-accent hover:text-foreground"
onClick={() => splitWindowSurface(props.windowId, "y")}
aria-label="Split active tab down"
title="Split active tab down"
>
<Rows2Icon className="size-3.5" />
</button>
</div>
</div>
<div className="flex h-full min-h-0 min-w-0 flex-1 overflow-hidden">
{activeSurface ? (
<WorkspaceSurfaceView
surface={activeSurface}
bindSharedComposerHandle={focusedWindowId === props.windowId}
/>
) : null}
</div>
</section>
);
});
function WorkspaceSurfaceView(props: {
bindSharedComposerHandle?: boolean;
surface: WorkspaceSurfaceInstance;
}) {
if (props.surface.kind === "thread") {
if (props.surface.input.scope === "server") {
return (
<ChatView
environmentId={props.surface.input.threadRef.environmentId}
threadId={props.surface.input.threadRef.threadId}
routeKind="server"
{...(props.bindSharedComposerHandle === undefined
? {}
: { bindSharedComposerHandle: props.bindSharedComposerHandle })}
/>
);
}
return (
<ChatView
draftId={props.surface.input.draftId}
environmentId={props.surface.input.environmentId}
threadId={props.surface.input.threadId}
routeKind="draft"
{...(props.bindSharedComposerHandle === undefined
? {}
: { bindSharedComposerHandle: props.bindSharedComposerHandle })}
/>
);
}
return <ThreadTerminalSurface threadRef={props.surface.input.threadRef} />;
}
function WorkspaceSurfaceTitle(props: { surface: WorkspaceSurfaceInstance }) {
if (props.surface.kind === "terminal") {
return <TerminalSurfaceTitle threadRef={props.surface.input.threadRef} />;
}
return <ThreadSurfaceTitle surface={props.surface} />;
}
function ThreadSurfaceTitle(props: {
surface: Extract<WorkspaceSurfaceInstance, { kind: "thread" }>;
}) {
const thread = useStore(
useMemo(
() =>
createThreadSelectorByRef(
props.surface.input.scope === "server" ? props.surface.input.threadRef : null,
),
[props.surface.input],
),
);
if (props.surface.input.scope === "server") {
return <>{thread?.title ?? props.surface.input.threadRef.threadId}</>;
}
return <>{thread?.title ?? props.surface.input.threadId ?? "Draft thread"}</>;
}
function TerminalSurfaceTitle(props: {
threadRef: Extract<WorkspaceSurfaceInstance, { kind: "terminal" }>["input"]["threadRef"];
}) {
const thread = useStore(
useMemo(() => createThreadSelectorByRef(props.threadRef), [props.threadRef]),
);
const label = thread?.title ?? props.threadRef.threadId;
return (
<span className="inline-flex items-center gap-1">
<TerminalSquareIcon className="size-3 shrink-0" />
<span className="truncate">{label}</span>
</span>
);
}
@@ -0,0 +1,261 @@
import type { KeybindingCommand, ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useMemo } from "react";
import { useCommandPaletteStore } from "../commandPaletteStore";
import {
useFocusedWorkspaceSurface,
useWorkspaceDocument,
useWorkspaceStore,
} from "../workspace/store";
import type { WorkspaceSurfaceInstance } from "../workspace/types";
export const WORKSPACE_COMMAND_IDS = [
"workspace.terminal.splitRight",
"workspace.terminal.splitDown",
"workspace.terminal.newTab",
"workspace.pane.splitRight",
"workspace.pane.splitDown",
"workspace.focus.left",
"workspace.focus.right",
"workspace.focus.up",
"workspace.focus.down",
"workspace.pane.close",
"workspace.pane.moveLeft",
"workspace.pane.moveRight",
"workspace.pane.moveUp",
"workspace.pane.moveDown",
"workspace.tab.moveLeft",
"workspace.tab.moveRight",
"workspace.tab.moveUp",
"workspace.tab.moveDown",
] as const satisfies readonly KeybindingCommand[];
export type WorkspaceCommandId = (typeof WORKSPACE_COMMAND_IDS)[number];
export const WORKSPACE_COMMAND_METADATA: Record<
WorkspaceCommandId,
{
searchTerms: readonly string[];
title: string;
}
> = {
"workspace.terminal.splitRight": {
title: "Open terminal in split right",
searchTerms: ["terminal", "split", "right", "pane", "workspace"],
},
"workspace.terminal.splitDown": {
title: "Open terminal in split down",
searchTerms: ["terminal", "split", "down", "bottom", "pane", "workspace"],
},
"workspace.terminal.newTab": {
title: "Open terminal as tab",
searchTerms: ["terminal", "tab", "pane", "workspace"],
},
"workspace.pane.splitRight": {
title: "Open in split right",
searchTerms: ["split", "pane", "right", "open", "workspace"],
},
"workspace.pane.splitDown": {
title: "Open in split down",
searchTerms: ["split", "pane", "down", "open", "workspace"],
},
"workspace.focus.left": {
title: "Focus pane left",
searchTerms: ["focus", "pane", "left", "workspace"],
},
"workspace.focus.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.moveLeft": {
title: "Move pane left",
searchTerms: ["move", "pane", "left", "workspace"],
},
"workspace.pane.moveRight": {
title: "Move pane right",
searchTerms: ["move", "pane", "right", "workspace"],
},
"workspace.pane.moveUp": {
title: "Move pane up",
searchTerms: ["move", "pane", "up", "workspace"],
},
"workspace.pane.moveDown": {
title: "Move pane down",
searchTerms: ["move", "pane", "down", "workspace"],
},
"workspace.tab.moveLeft": {
title: "Move tab left",
searchTerms: ["move", "tab", "left", "workspace"],
},
"workspace.tab.moveRight": {
title: "Move tab right",
searchTerms: ["move", "tab", "right", "workspace"],
},
"workspace.tab.moveUp": {
title: "Move tab up",
searchTerms: ["move", "tab", "up", "workspace"],
},
"workspace.tab.moveDown": {
title: "Move tab down",
searchTerms: ["move", "tab", "down", "workspace"],
},
};
function threadRefForWorkspaceSurface(
surface: WorkspaceSurfaceInstance | null | undefined,
): ScopedThreadRef | null {
if (!surface) {
return null;
}
if (surface.kind === "terminal") {
return surface.input.threadRef;
}
if (surface.input.scope === "server") {
return surface.input.threadRef;
}
return null;
}
export function isWorkspaceCommandId(
command: string | null | undefined,
): command is WorkspaceCommandId {
return WORKSPACE_COMMAND_IDS.includes(command as WorkspaceCommandId);
}
export function useWorkspaceCommandExecutor() {
const document = useWorkspaceDocument();
const focusedSurface = useFocusedWorkspaceSurface();
const openWorkspaceTarget = useCommandPaletteStore((state) => state.openWorkspaceTarget);
const closeFocusedWindow = useWorkspaceStore((state) => state.closeFocusedWindow);
const focusAdjacentWindow = useWorkspaceStore((state) => state.focusAdjacentWindow);
const moveActiveTabToAdjacentWindow = useWorkspaceStore(
(state) => state.moveActiveTabToAdjacentWindow,
);
const moveFocusedWindow = useWorkspaceStore((state) => state.moveFocusedWindow);
const openTerminalSurfaceForThread = useWorkspaceStore(
(state) => state.openTerminalSurfaceForThread,
);
const focusedWindowId = useMemo(() => {
if (document.focusedWindowId && document.windowsById[document.focusedWindowId]) {
return document.focusedWindowId;
}
return Object.keys(document.windowsById)[0] ?? null;
}, [document]);
const focusedThreadRef = useMemo(
() => threadRefForWorkspaceSurface(focusedSurface),
[focusedSurface],
);
const executeWorkspaceCommand = useCallback(
async (command: WorkspaceCommandId): Promise<boolean> => {
switch (command) {
case "workspace.terminal.splitRight":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "split-right");
return true;
case "workspace.terminal.splitDown":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "split-down");
return true;
case "workspace.terminal.newTab":
if (!focusedThreadRef) {
return false;
}
openTerminalSurfaceForThread(focusedThreadRef, "new-tab");
return true;
case "workspace.pane.splitRight":
if (!focusedWindowId) {
return false;
}
openWorkspaceTarget({ disposition: "split-right" });
return true;
case "workspace.pane.splitDown":
if (!focusedWindowId) {
return false;
}
openWorkspaceTarget({ disposition: "split-down" });
return true;
case "workspace.focus.left":
focusAdjacentWindow("left");
return true;
case "workspace.focus.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.moveLeft":
moveFocusedWindow("left");
return true;
case "workspace.pane.moveRight":
moveFocusedWindow("right");
return true;
case "workspace.pane.moveUp":
moveFocusedWindow("up");
return true;
case "workspace.pane.moveDown":
moveFocusedWindow("down");
return true;
case "workspace.tab.moveLeft":
moveActiveTabToAdjacentWindow("left");
return true;
case "workspace.tab.moveRight":
moveActiveTabToAdjacentWindow("right");
return true;
case "workspace.tab.moveUp":
moveActiveTabToAdjacentWindow("up");
return true;
case "workspace.tab.moveDown":
moveActiveTabToAdjacentWindow("down");
return true;
}
},
[
closeFocusedWindow,
focusAdjacentWindow,
focusedThreadRef,
focusedWindowId,
moveActiveTabToAdjacentWindow,
moveFocusedWindow,
openTerminalSurfaceForThread,
openWorkspaceTarget,
],
);
return {
canOpenTerminalSurface: focusedThreadRef !== null,
canSplitFocusedPane: focusedWindowId !== null,
executeWorkspaceCommand,
focusedSurface,
focusedThreadRef,
focusedWindowId,
};
}
@@ -1,7 +1,6 @@
import { createFileRoute, retainSearchParams, useNavigate } from "@tanstack/react-router";
import { Suspense, lazy, type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import ChatView from "../components/ChatView";
import { threadHasStarted } from "../components/ChatView.logic";
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
import {
@@ -21,7 +20,8 @@ import { selectEnvironmentState, selectThreadExistsByRef, useStore } from "../st
import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteRef, buildThreadRouteParams } from "../threadRoutes";
import { Sheet, SheetPopup } from "../components/ui/sheet";
import { Sidebar, SidebarInset, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
import { useWorkspaceStore } from "../workspace/store";
const DiffPanel = lazy(() => import("../components/DiffPanel"));
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
@@ -164,6 +164,7 @@ const DiffPanelInlineSidebar = (props: {
function ChatThreadRouteView() {
const navigate = useNavigate();
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const threadRef = Route.useParams({
select: (params) => resolveThreadRouteRef(params),
});
@@ -248,6 +249,20 @@ function ChatThreadRouteView() {
}
}, [bootstrapComplete, environmentHasAnyThreads, navigate, routeThreadExists, threadRef]);
useEffect(() => {
if (!threadRef || !bootstrapComplete || !routeThreadExists) {
return;
}
openThreadSurface(
{
scope: "server",
threadRef,
},
"focus-or-tab",
);
}, [bootstrapComplete, openThreadSurface, routeThreadExists, threadRef]);
useEffect(() => {
if (!threadRef || !serverThreadStarted || !draftThread?.promotedTo) {
return;
@@ -263,40 +278,19 @@ function ChatThreadRouteView() {
if (!shouldUseDiffSheet) {
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView
environmentId={threadRef.environmentId}
threadId={threadRef.threadId}
onDiffPanelOpen={markDiffOpened}
reserveTitleBarControlInset={!diffOpen}
routeKind="server"
/>
</SidebarInset>
<DiffPanelInlineSidebar
diffOpen={diffOpen}
onCloseDiff={closeDiff}
onOpenDiff={openDiff}
renderDiffContent={shouldRenderDiffContent}
/>
</>
<DiffPanelInlineSidebar
diffOpen={diffOpen}
onCloseDiff={closeDiff}
onOpenDiff={openDiff}
renderDiffContent={shouldRenderDiffContent}
/>
);
}
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView
environmentId={threadRef.environmentId}
threadId={threadRef.threadId}
onDiffPanelOpen={markDiffOpened}
routeKind="server"
/>
</SidebarInset>
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
{shouldRenderDiffContent ? <LazyDiffPanel mode="sheet" /> : null}
</DiffPanelSheet>
</>
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
{shouldRenderDiffContent ? <LazyDiffPanel mode="sheet" /> : null}
</DiffPanelSheet>
);
}
+20 -21
View File
@@ -1,15 +1,15 @@
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useMemo } from "react";
import ChatView from "../components/ChatView";
import { threadHasStarted } from "../components/ChatView.logic";
import { useComposerDraftStore, DraftId } from "../composerDraftStore";
import { SidebarInset } from "../components/ui/sidebar";
import { createThreadSelectorAcrossEnvironments } from "../storeSelectors";
import { useStore } from "../store";
import { buildThreadRouteParams } from "../threadRoutes";
import { useWorkspaceStore } from "../workspace/store";
function DraftChatThreadRouteView() {
const navigate = useNavigate();
const openThreadSurface = useWorkspaceStore((state) => state.openThreadSurface);
const { draftId: rawDraftId } = Route.useParams();
const draftId = DraftId.make(rawDraftId);
const draftSession = useComposerDraftStore((store) => store.getDraftSession(draftId));
@@ -53,32 +53,31 @@ function DraftChatThreadRouteView() {
void navigate({ to: "/", replace: true });
}, [canonicalThreadRef, draftSession, navigate]);
if (canonicalThreadRef) {
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView
environmentId={canonicalThreadRef.environmentId}
threadId={canonicalThreadRef.threadId}
routeKind="server"
/>
</SidebarInset>
useEffect(() => {
if (!draftSession || canonicalThreadRef) {
return;
}
openThreadSurface(
{
scope: "draft",
draftId,
environmentId: draftSession.environmentId,
threadId: draftSession.threadId,
},
"focus-or-tab",
);
}, [canonicalThreadRef, draftId, draftSession, openThreadSurface]);
if (canonicalThreadRef) {
return null;
}
if (!draftSession) {
return null;
}
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView
draftId={draftId}
environmentId={draftSession.environmentId}
threadId={draftSession.threadId}
routeKind="draft"
/>
</SidebarInset>
);
return null;
}
export const Route = createFileRoute("/_chat/draft/$draftId")({
+1 -3
View File
@@ -1,9 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { NoActiveThreadState } from "../components/NoActiveThreadState";
function ChatIndexRouteView() {
return <NoActiveThreadState />;
return null;
}
export const Route = createFileRoute("/_chat/")({
+16 -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,8 @@ import {
} from "../lib/chatThreadActions";
import { isTerminalFocused } from "../lib/terminalFocus";
import { resolveShortcutCommand } from "../keybindings";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { useWorkspaceThreadTerminalOpen } from "../workspace/store";
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
import { useSettings } from "~/hooks/useSettings";
import { useServerKeybindings } from "~/rpc/serverState";
@@ -20,12 +25,9 @@ function ChatRouteGlobalShortcuts() {
const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
useHandleNewThread();
const { executeWorkspaceCommand } = useWorkspaceCommandExecutor();
const keybindings = useServerKeybindings();
const terminalOpen = useTerminalStateStore((state) =>
routeThreadRef
? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
const terminalOpen = useWorkspaceThreadTerminalOpen(routeThreadRef);
const appSettings = useSettings();
useEffect(() => {
@@ -37,6 +39,12 @@ function ChatRouteGlobalShortcuts() {
terminalOpen,
},
});
if (command && isWorkspaceCommandId(command)) {
event.preventDefault();
event.stopPropagation();
void executeWorkspaceCommand(command);
return;
}
if (useCommandPaletteStore.getState().open) {
return;
@@ -89,6 +97,7 @@ function ChatRouteGlobalShortcuts() {
handleNewThread,
keybindings,
defaultProjectRef,
executeWorkspaceCommand,
selectedThreadKeysSize,
terminalOpen,
appSettings.defaultThreadEnvMode,
@@ -101,6 +110,7 @@ function ChatRouteLayout() {
return (
<>
<ChatRouteGlobalShortcuts />
<WorkspaceShell />
<Outlet />
</>
);
+498
View File
@@ -0,0 +1,498 @@
import { scopeThreadRef } from "@t3tools/client-runtime";
import { afterEach, describe, expect, it, vi } from "vitest";
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => {
store.clear();
},
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
};
}
function getTestWindow(): Window & typeof globalThis {
const localStorage = createLocalStorageStub();
const testWindow = {
localStorage,
setTimeout: globalThis.setTimeout.bind(globalThis),
clearTimeout: globalThis.clearTimeout.bind(globalThis),
} as Window & typeof globalThis;
vi.stubGlobal("window", testWindow);
vi.stubGlobal("localStorage", localStorage);
return testWindow;
}
afterEach(() => {
vi.useRealTimers();
vi.resetModules();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("workspace store", () => {
it("focuses an existing thread surface instead of duplicating it by default", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const initialDocument = useWorkspaceStore.getState().document;
const windowId = Object.keys(initialDocument.windowsById)[0]!;
const initialSurfaceId = initialDocument.windowsById[windowId]!.activeTabId;
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(nextDocument.windowsById[windowId]!.tabIds).toEqual([initialSurfaceId]);
expect(nextDocument.windowsById[windowId]!.activeTabId).toBe(initialSurfaceId);
});
it("does not rewrite workspace state when refocusing the already active surface", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const initialDocument = useWorkspaceStore.getState().document;
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
expect(useWorkspaceStore.getState().document).toBe(initialDocument);
});
it("collapses the split tree when closing the last tab in a window", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const splitDocument = useWorkspaceStore.getState().document;
expect(Object.keys(splitDocument.windowsById)).toHaveLength(2);
expect(splitDocument.rootNodeId).not.toBeNull();
expect(splitDocument.nodesById[splitDocument.rootNodeId!]?.kind).toBe("split");
const closingWindowId = splitDocument.focusedWindowId!;
const closingSurfaceId = splitDocument.windowsById[closingWindowId]!.activeTabId!;
useWorkspaceStore.getState().closeSurface(closingSurfaceId);
const collapsedDocument = useWorkspaceStore.getState().document;
expect(Object.keys(collapsedDocument.windowsById)).toHaveLength(1);
expect(collapsedDocument.rootNodeId).not.toBeNull();
expect(collapsedDocument.nodesById[collapsedDocument.rootNodeId!]?.kind).toBe("window");
});
it("creates one terminal surface per thread and toggles it off cleanly", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
useWorkspaceStore.getState().ensureTerminalSurfaceForThread(threadRef);
let document = useWorkspaceStore.getState().document;
expect(
Object.values(document.surfacesById).filter((surface) => surface.kind === "terminal"),
).toHaveLength(1);
useWorkspaceStore.getState().ensureTerminalSurfaceForThread(threadRef);
document = useWorkspaceStore.getState().document;
expect(
Object.values(document.surfacesById).filter((surface) => surface.kind === "terminal"),
).toHaveLength(1);
useWorkspaceStore.getState().toggleTerminalSurfaceForThread(threadRef);
document = useWorkspaceStore.getState().document;
expect(
Object.values(document.surfacesById).filter((surface) => surface.kind === "terminal"),
).toHaveLength(0);
});
it("opens a terminal surface as a tab in the focused window", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const initialDocument = useWorkspaceStore.getState().document;
const windowId = initialDocument.focusedWindowId!;
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "new-tab");
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(nextDocument.windowsById[windowId]!.tabIds).toHaveLength(2);
const activeSurfaceId = nextDocument.windowsById[windowId]!.activeTabId!;
expect(nextDocument.surfacesById[activeSurfaceId]?.kind).toBe("terminal");
});
it("opens a terminal surface in a split when requested", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
useWorkspaceStore.getState().openTerminalSurfaceForThread(threadRef, "split-right");
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(2);
const activeWindowId = nextDocument.focusedWindowId!;
const activeSurfaceId = nextDocument.windowsById[activeWindowId]!.activeTabId!;
expect(nextDocument.surfacesById[activeSurfaceId]?.kind).toBe("terminal");
});
it("splits the active surface in the selected window", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
const initialDocument = useWorkspaceStore.getState().document;
const sourceWindowId = initialDocument.focusedWindowId!;
const sourceSurfaceId = initialDocument.windowsById[sourceWindowId]!.activeTabId!;
useWorkspaceStore.getState().splitWindowSurface(sourceWindowId, "x");
const nextDocument = useWorkspaceStore.getState().document;
expect(Object.keys(nextDocument.windowsById)).toHaveLength(2);
const newWindowId = nextDocument.focusedWindowId!;
expect(newWindowId).not.toBe(sourceWindowId);
const newSurfaceId = nextDocument.windowsById[newWindowId]!.activeTabId!;
expect(newSurfaceId).not.toBe(sourceSurfaceId);
expect(nextDocument.surfacesById[newSurfaceId]?.kind).toBe("thread");
expect(nextDocument.nodesById[nextDocument.rootNodeId!]?.kind).toBe("split");
});
it("rebalances same-axis auto splits evenly when adding a third pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
const nextDocument = useWorkspaceStore.getState().document;
const rootNode = nextDocument.nodesById[nextDocument.rootNodeId!];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(rootNode.childIds).toHaveLength(3);
expect(rootNode.sizingMode).toBe("auto");
expect(rootNode.sizes).toEqual([1 / 3, 1 / 3, 1 / 3]);
});
it("persists resized split proportions on the workspace node", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const splitNodeId = useWorkspaceStore.getState().document.rootNodeId!;
useWorkspaceStore.getState().setSplitNodeSizes(splitNodeId, [1, 3]);
const nextDocument = useWorkspaceStore.getState().document;
const splitNode = nextDocument.nodesById[splitNodeId];
expect(splitNode?.kind).toBe("split");
if (splitNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(splitNode.sizes).toEqual([0.25, 0.75]);
expect(splitNode.sizingMode).toBe("manual");
});
it("keeps manual same-axis splits local when adding another pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const rootNodeId = useWorkspaceStore.getState().document.rootNodeId!;
useWorkspaceStore.getState().setSplitNodeSizes(rootNodeId, [0.7, 0.3]);
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
const nextDocument = useWorkspaceStore.getState().document;
const rootNode = nextDocument.nodesById[rootNodeId];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(rootNode.childIds).toHaveLength(2);
expect(rootNode.sizingMode).toBe("manual");
expect(rootNode.sizes).toEqual([0.7, 0.3]);
const nestedNode = nextDocument.nodesById[rootNode.childIds[1]!];
expect(nestedNode?.kind).toBe("split");
if (nestedNode?.kind !== "split") {
throw new Error("Expected nested split node");
}
expect(nestedNode.axis).toBe("x");
expect(nestedNode.sizingMode).toBe("auto");
expect(nestedNode.childIds).toHaveLength(2);
});
it("rebalances auto split groups after closing a pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
let document = useWorkspaceStore.getState().document;
const rootNode = document.nodesById[document.rootNodeId!];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
const middleNode = rootNode.childIds[1] ? document.nodesById[rootNode.childIds[1]!] : null;
const middleWindowId = middleNode?.kind === "window" ? middleNode.windowId : null;
if (!middleWindowId) {
throw new Error("Expected middle window node");
}
const middleSurfaceId = document.windowsById[middleWindowId]!.activeTabId!;
useWorkspaceStore.getState().closeSurface(middleSurfaceId);
document = useWorkspaceStore.getState().document;
const nextRootNode = document.nodesById[document.rootNodeId!];
expect(nextRootNode?.kind).toBe("split");
if (nextRootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(nextRootNode.childIds).toHaveLength(2);
expect(nextRootNode.sizingMode).toBe("auto");
expect(nextRootNode.sizes).toEqual([0.5, 0.5]);
});
it("preserves remaining proportions after closing a pane in a manual split group", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
const threadC = scopeThreadRef("environment-c" as never, "thread-c" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadC), "x");
const rootNodeId = useWorkspaceStore.getState().document.rootNodeId!;
useWorkspaceStore.getState().setSplitNodeSizes(rootNodeId, [0.2, 0.3, 0.5]);
let document = useWorkspaceStore.getState().document;
const rootNode = document.nodesById[rootNodeId];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
const middleNode = rootNode.childIds[1] ? document.nodesById[rootNode.childIds[1]!] : null;
const middleWindowId = middleNode?.kind === "window" ? middleNode.windowId : null;
if (!middleWindowId) {
throw new Error("Expected middle window node");
}
const middleSurfaceId = document.windowsById[middleWindowId]!.activeTabId!;
useWorkspaceStore.getState().closeSurface(middleSurfaceId);
document = useWorkspaceStore.getState().document;
const nextRootNode = document.nodesById[document.rootNodeId!];
expect(nextRootNode?.kind).toBe("split");
if (nextRootNode?.kind !== "split") {
throw new Error("Expected split node");
}
expect(nextRootNode.childIds).toHaveLength(2);
expect(nextRootNode.sizingMode).toBe("manual");
expect(nextRootNode.sizes[0]).toBeCloseTo(2 / 7);
expect(nextRootNode.sizes[1]).toBeCloseTo(5 / 7);
});
it("focuses the adjacent pane in the requested direction", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const rightWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().focusAdjacentWindow("left");
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.focusedWindowId).not.toBe(rightWindowId);
expect(nextDocument.focusedWindowId).toBe(nextDocument.mobileActiveWindowId);
});
it("closes the focused pane and keeps the remaining pane active", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const closingWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().closeFocusedWindow();
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.windowsById[closingWindowId]).toBeUndefined();
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
expect(nextDocument.nodesById[nextDocument.rootNodeId!]?.kind).toBe("window");
});
it("moves the active tab into the adjacent pane and collapses the source pane if empty", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
useWorkspaceStore.getState().focusAdjacentWindow("left");
const sourceWindowId = useWorkspaceStore.getState().document.focusedWindowId!;
useWorkspaceStore.getState().moveActiveTabToAdjacentWindow("right");
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.windowsById[sourceWindowId]).toBeUndefined();
expect(Object.keys(nextDocument.windowsById)).toHaveLength(1);
const remainingWindowId = nextDocument.focusedWindowId!;
expect(nextDocument.windowsById[remainingWindowId]!.tabIds).toHaveLength(2);
expect(nextDocument.nodesById[nextDocument.rootNodeId!]?.kind).toBe("window");
});
it("moves the focused pane by swapping positions with the adjacent pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
const threadB = scopeThreadRef("environment-b" as never, "thread-b" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().openThreadInSplit(serverThreadSurfaceInput(threadB), "x");
const beforeDocument = useWorkspaceStore.getState().document;
const rootNode = beforeDocument.nodesById[beforeDocument.rootNodeId!];
expect(rootNode?.kind).toBe("split");
if (rootNode?.kind !== "split") {
throw new Error("Expected split node");
}
const leftNodeId = rootNode.childIds[0]!;
const rightNodeId = rootNode.childIds[1]!;
const rightWindowId = beforeDocument.focusedWindowId!;
useWorkspaceStore.getState().moveFocusedWindow("left");
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.focusedWindowId).toBe(rightWindowId);
expect(nextDocument.nodesById[leftNodeId]).toMatchObject({
kind: "window",
windowId: rightWindowId,
});
expect(nextDocument.nodesById[rightNodeId]).not.toMatchObject({
kind: "window",
windowId: rightWindowId,
});
});
it("clears the workspace tree when closing the last focused pane", async () => {
getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { serverThreadSurfaceInput } = await import("./types");
const threadA = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadA));
useWorkspaceStore.getState().closeFocusedWindow();
const nextDocument = useWorkspaceStore.getState().document;
expect(nextDocument.rootNodeId).toBeNull();
expect(nextDocument.focusedWindowId).toBeNull();
expect(Object.keys(nextDocument.windowsById)).toHaveLength(0);
expect(Object.keys(nextDocument.surfacesById)).toHaveLength(0);
});
it("persists workspace documents after the debounce interval", async () => {
vi.useFakeTimers();
const testWindow = getTestWindow();
const { useWorkspaceStore } = await import("./store");
const { WORKSPACE_DOCUMENT_STORAGE_KEY } = await import("../clientPersistenceStorage");
const { serverThreadSurfaceInput } = await import("./types");
const threadRef = scopeThreadRef("environment-a" as never, "thread-a" as never);
useWorkspaceStore.getState().resetWorkspace();
useWorkspaceStore.getState().openThreadSurface(serverThreadSurfaceInput(threadRef));
expect(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)).toBeNull();
await vi.advanceTimersByTimeAsync(150);
const persisted = JSON.parse(testWindow.localStorage.getItem(WORKSPACE_DOCUMENT_STORAGE_KEY)!);
expect(persisted.layoutEngine).toBe("split");
expect(persisted.focusedWindowId).not.toBeNull();
});
});
File diff suppressed because it is too large. Load diff
+242
View File
@@ -0,0 +1,242 @@
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 WorkspaceLayoutEngine = "split";
export type WorkspaceSurfaceKind = "thread" | "terminal";
export type WorkspaceSplitSizingMode = "auto" | "manual";
export type ThreadSurfaceInput =
| {
scope: "server";
threadRef: ScopedThreadRef;
}
| {
scope: "draft";
draftId: DraftId;
environmentId: EnvironmentId;
threadId: ThreadId;
};
export interface TerminalSurfaceInput {
scope: "thread";
threadRef: ScopedThreadRef;
}
export type WorkspaceSurfaceInstance =
| {
id: string;
kind: "thread";
input: ThreadSurfaceInput;
}
| {
id: string;
kind: "terminal";
input: TerminalSurfaceInput;
};
export interface WorkspaceWindow {
id: string;
tabIds: string[];
activeTabId: string | null;
}
export type WorkspaceNode =
| {
id: string;
kind: "window";
windowId: string;
}
| {
id: string;
kind: "split";
axis: WorkspaceAxis;
childIds: string[];
sizes: number[];
sizingMode: WorkspaceSplitSizingMode;
};
export interface WorkspaceDocument {
version: 1;
layoutEngine: WorkspaceLayoutEngine;
rootNodeId: string | null;
nodesById: Record<string, WorkspaceNode>;
windowsById: Record<string, WorkspaceWindow>;
surfacesById: Record<string, WorkspaceSurfaceInstance>;
focusedWindowId: string | null;
mobileActiveWindowId: string | null;
}
export function createEmptyWorkspaceDocument(): WorkspaceDocument {
return {
version: 1,
layoutEngine: "split",
rootNodeId: null,
nodesById: {},
windowsById: {},
surfacesById: {},
focusedWindowId: null,
mobileActiveWindowId: null,
};
}
export function normalizeWorkspaceSplitSizes(
sizes: number[] | null | undefined,
childCount: number,
): number[] {
if (childCount <= 0) {
return [];
}
const fallback = Array.from({ length: childCount }, () => 1 / childCount);
if (!sizes || sizes.length !== childCount) {
return fallback;
}
const finiteSizes = sizes.map((size) => (Number.isFinite(size) && size > 0 ? size : 0));
const total = finiteSizes.reduce((sum, size) => sum + size, 0);
if (total <= 0) {
return fallback;
}
return finiteSizes.map((size) => size / total);
}
export function isWorkspaceDocument(value: unknown): value is WorkspaceDocument {
if (!value || typeof value !== "object") {
return false;
}
const candidate = value as Partial<WorkspaceDocument>;
return candidate.version === 1 && candidate.layoutEngine === "split";
}
export function sameThreadSurfaceInput(
left: ThreadSurfaceInput | null | undefined,
right: ThreadSurfaceInput | null | undefined,
): boolean {
if (!left || !right || left.scope !== right.scope) {
return false;
}
if (left.scope === "server" && right.scope === "server") {
return (
left.threadRef.environmentId === right.threadRef.environmentId &&
left.threadRef.threadId === right.threadRef.threadId
);
}
if (left.scope !== "draft" || right.scope !== "draft") {
return false;
}
return (
left.draftId === right.draftId &&
left.environmentId === right.environmentId &&
left.threadId === right.threadId
);
}
export function sameTerminalSurfaceInput(
left: TerminalSurfaceInput | null | undefined,
right: TerminalSurfaceInput | null | undefined,
): boolean {
if (!left || !right) {
return false;
}
return (
left.scope === right.scope &&
left.threadRef.environmentId === right.threadRef.environmentId &&
left.threadRef.threadId === right.threadRef.threadId
);
}
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): TerminalSurfaceInput {
return {
scope: "thread",
threadRef,
};
}
+18
View File
@@ -32,6 +32,24 @@ const STATIC_KEYBINDING_COMMANDS = [
"terminal.split",
"terminal.new",
"terminal.close",
"workspace.terminal.splitRight",
"workspace.terminal.splitDown",
"workspace.terminal.newTab",
"workspace.pane.splitRight",
"workspace.pane.splitDown",
"workspace.focus.left",
"workspace.focus.right",
"workspace.focus.up",
"workspace.focus.down",
"workspace.pane.close",
"workspace.pane.moveLeft",
"workspace.pane.moveRight",
"workspace.pane.moveUp",
"workspace.pane.moveDown",
"workspace.tab.moveLeft",
"workspace.tab.moveRight",
"workspace.tab.moveUp",
"workspace.tab.moveDown",
"diff.toggle",
"commandPalette.toggle",
"chat.new",