Initial public release
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
import { ChatContainer } from '@/components/chat/ChatContainer';
|
||||
import { ChatErrorBoundary } from '@/components/chat/ChatErrorBoundary';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
|
||||
export const ChatView: React.FC = () => {
|
||||
const currentSessionId = useSessionStore((state) => state.currentSessionId);
|
||||
|
||||
return (
|
||||
<ChatErrorBoundary sessionId={currentSessionId || undefined}>
|
||||
<ChatContainer />
|
||||
</ChatErrorBoundary>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,491 @@
|
||||
import React from 'react';
|
||||
import { RiGitCommitLine, RiLoader4Line } from '@remixicon/react';
|
||||
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useGitStore, useGitStatus, useIsGitRepo, useGitFileCount } from '@/stores/useGitStore';
|
||||
import type { GitStatus } from '@/lib/api/types';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { RiArrowDownSLine } from '@remixicon/react';
|
||||
import { toast } from 'sonner';
|
||||
import { getLanguageFromExtension } from '@/lib/toolHelpers';
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
import { DiffViewToggle } from '@/components/chat/message/DiffViewToggle';
|
||||
import type { DiffViewMode } from '@/components/chat/message/types';
|
||||
|
||||
const LazyMonacoDiffViewer = React.lazy(() =>
|
||||
import('./MonacoDiffViewer').then((mod) => ({ default: mod.MonacoDiffViewer }))
|
||||
);
|
||||
|
||||
type FileEntry = GitStatus['files'][number] & {
|
||||
insertions: number;
|
||||
deletions: number;
|
||||
isNew: boolean;
|
||||
};
|
||||
|
||||
const isNewStatusFile = (file: GitStatus['files'][number]): boolean => {
|
||||
const { index, working_dir: workingDir } = file;
|
||||
|
||||
return index === 'A' || workingDir === 'A' || index === '?' || workingDir === '?';
|
||||
};
|
||||
|
||||
const formatDiffTotals = (insertions?: number, deletions?: number) => {
|
||||
const added = insertions ?? 0;
|
||||
const removed = deletions ?? 0;
|
||||
if (!added && !removed) return null;
|
||||
return (
|
||||
<span className="typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap">
|
||||
{added ? (
|
||||
<span style={{ color: 'var(--status-success)' }}>+{added}</span>
|
||||
) : null}
|
||||
{removed ? (
|
||||
<span style={{ color: 'var(--status-error)' }}>-{removed}</span>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
interface FileSelectorProps {
|
||||
changedFiles: FileEntry[];
|
||||
selectedFile: string | null;
|
||||
selectedFileEntry: FileEntry | null;
|
||||
onSelectFile: (path: string) => void;
|
||||
}
|
||||
|
||||
const FileSelector = React.memo<FileSelectorProps>(({
|
||||
changedFiles,
|
||||
selectedFile,
|
||||
selectedFileEntry,
|
||||
onSelectFile,
|
||||
}) => {
|
||||
if (changedFiles.length === 0) return null;
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring">
|
||||
{selectedFileEntry ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="truncate typography-meta">
|
||||
{selectedFileEntry.path}
|
||||
</span>
|
||||
{formatDiffTotals(selectedFileEntry.insertions, selectedFileEntry.deletions)}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Select file</span>
|
||||
)}
|
||||
<RiArrowDownSLine className="size-4 opacity-50" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="max-h-[70vh] min-w-[320px] overflow-y-auto">
|
||||
<DropdownMenuRadioGroup value={selectedFile ?? ''} onValueChange={onSelectFile}>
|
||||
{changedFiles.map((file) => (
|
||||
<DropdownMenuRadioItem key={file.path} value={file.path}>
|
||||
<div className="flex w-full items-center justify-between gap-3">
|
||||
<span className="truncate typography-meta">
|
||||
{file.path}
|
||||
</span>
|
||||
{formatDiffTotals(file.insertions, file.deletions)}
|
||||
</div>
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
});
|
||||
|
||||
interface DiffContentProps {
|
||||
fileDiff: { original: string; modified: string } | null;
|
||||
activeFilePath: string;
|
||||
isDiffLoading: boolean;
|
||||
diffError: string | null;
|
||||
onRetry: () => void;
|
||||
renderSideBySide: boolean;
|
||||
allowResponsive: boolean;
|
||||
}
|
||||
|
||||
const DiffContent = React.memo<DiffContentProps>(({
|
||||
fileDiff,
|
||||
activeFilePath,
|
||||
isDiffLoading,
|
||||
diffError,
|
||||
onRetry,
|
||||
renderSideBySide,
|
||||
allowResponsive,
|
||||
}) => {
|
||||
const language = React.useMemo(
|
||||
() => (activeFilePath ? getLanguageFromExtension(activeFilePath) || 'text' : 'text'),
|
||||
[activeFilePath]
|
||||
);
|
||||
|
||||
if (isDiffLoading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<RiLoader4Line size={16} className="animate-spin" />
|
||||
Loading diff…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (diffError) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 text-center">
|
||||
<p className="text-sm text-destructive">{diffError}</p>
|
||||
<Button size="sm" onClick={onRetry}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!fileDiff || (!fileDiff.original && !fileDiff.modified)) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
No changes detected for this file
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full">
|
||||
<React.Suspense
|
||||
fallback={(
|
||||
<div className="flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<RiLoader4Line size={16} className="animate-spin" />
|
||||
Loading diff viewer…
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
<LazyMonacoDiffViewer
|
||||
original={fileDiff.original}
|
||||
modified={fileDiff.modified}
|
||||
language={language}
|
||||
renderSideBySide={renderSideBySide}
|
||||
allowResponsive={allowResponsive}
|
||||
/>
|
||||
</React.Suspense>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
const useEffectiveDirectory = () => {
|
||||
const { currentSessionId, sessions, worktreeMetadata: worktreeMap } = useSessionStore();
|
||||
const { currentDirectory: fallbackDirectory } = useDirectoryStore();
|
||||
|
||||
const worktreeMetadata = currentSessionId ? worktreeMap.get(currentSessionId) ?? undefined : undefined;
|
||||
const currentSession = sessions.find((session) => session.id === currentSessionId);
|
||||
const sessionDirectory = (currentSession as Record<string, unknown>)?.directory as string | undefined;
|
||||
|
||||
return worktreeMetadata?.path ?? sessionDirectory ?? fallbackDirectory ?? undefined;
|
||||
};
|
||||
|
||||
export const DiffView: React.FC = () => {
|
||||
const { git } = useRuntimeAPIs();
|
||||
const effectiveDirectory = useEffectiveDirectory();
|
||||
|
||||
const isGitRepo = useIsGitRepo(effectiveDirectory ?? null);
|
||||
const status = useGitStatus(effectiveDirectory ?? null);
|
||||
const isLoadingStatus = useGitStore((state) => state.isLoadingStatus);
|
||||
const { setActiveDirectory, fetchStatus, setDiff } = useGitStore();
|
||||
|
||||
const [selectedFile, setSelectedFile] = React.useState<string | null>(null);
|
||||
const selectedFileRef = React.useRef<string | null>(null);
|
||||
|
||||
const [isDiffLoading, setIsDiffLoading] = React.useState(false);
|
||||
const [diffError, setDiffError] = React.useState<string | null>(null);
|
||||
const [fileDiff, setFileDiff] = React.useState<{ original: string; modified: string } | null>(null);
|
||||
|
||||
const pendingDiffFile = useUIStore((state) => state.pendingDiffFile);
|
||||
const setPendingDiffFile = useUIStore((state) => state.setPendingDiffFile);
|
||||
const diffLayoutPreference = useUIStore((state) => state.diffLayoutPreference);
|
||||
const diffFileLayout = useUIStore((state) => state.diffFileLayout);
|
||||
const setDiffFileLayout = useUIStore((state) => state.setDiffFileLayout);
|
||||
const lastStatusChange = useGitStore(React.useCallback((state) => {
|
||||
if (!effectiveDirectory) return 0;
|
||||
return state.directories.get(effectiveDirectory)?.lastStatusChange ?? 0;
|
||||
}, [effectiveDirectory]));
|
||||
|
||||
const getCachedDiffIfFresh = React.useCallback((directory: string | undefined, filePath: string) => {
|
||||
if (!directory) return null;
|
||||
const dirState = useGitStore.getState().directories.get(directory);
|
||||
if (!dirState) return null;
|
||||
const cached = dirState.diffCache.get(filePath);
|
||||
if (!cached) return null;
|
||||
|
||||
if (cached.fetchedAt < (dirState.lastStatusChange || 0)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
}, []);
|
||||
|
||||
const handleSelectFile = React.useCallback((value: string) => {
|
||||
selectedFileRef.current = value;
|
||||
setSelectedFile(value);
|
||||
setDiffError(null);
|
||||
|
||||
const cached = getCachedDiffIfFresh(effectiveDirectory, value);
|
||||
if (cached) {
|
||||
setFileDiff({ original: cached.original, modified: cached.modified });
|
||||
setIsDiffLoading(false);
|
||||
} else {
|
||||
setFileDiff(null);
|
||||
setIsDiffLoading(true);
|
||||
}
|
||||
}, [effectiveDirectory, getCachedDiffIfFresh]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (effectiveDirectory) {
|
||||
setActiveDirectory(effectiveDirectory);
|
||||
|
||||
const dirState = useGitStore.getState().directories.get(effectiveDirectory);
|
||||
if (!dirState?.status) {
|
||||
fetchStatus(effectiveDirectory, git);
|
||||
}
|
||||
}
|
||||
}, [effectiveDirectory, setActiveDirectory, fetchStatus, git]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!pendingDiffFile) return;
|
||||
|
||||
handleSelectFile(pendingDiffFile);
|
||||
|
||||
setPendingDiffFile(null);
|
||||
}, [pendingDiffFile, handleSelectFile, setPendingDiffFile]);
|
||||
|
||||
React.useEffect(() => {
|
||||
selectedFileRef.current = selectedFile;
|
||||
}, [selectedFile]);
|
||||
|
||||
const changedFiles: FileEntry[] = React.useMemo(() => {
|
||||
if (!status?.files) return [];
|
||||
const diffStats = status.diffStats ?? {};
|
||||
|
||||
return status.files
|
||||
.map((file) => ({
|
||||
...file,
|
||||
insertions: diffStats[file.path]?.insertions ?? 0,
|
||||
deletions: diffStats[file.path]?.deletions ?? 0,
|
||||
isNew: isNewStatusFile(file),
|
||||
}))
|
||||
.sort((a, b) => a.path.localeCompare(b.path));
|
||||
}, [status]);
|
||||
|
||||
const selectedFileEntry = React.useMemo(() => {
|
||||
if (!selectedFile) return null;
|
||||
return changedFiles.find((file) => file.path === selectedFile) ?? null;
|
||||
}, [changedFiles, selectedFile]);
|
||||
|
||||
const currentLayoutForSelectedFile = React.useMemo<'inline' | 'side-by-side' | null>(() => {
|
||||
if (!selectedFileEntry) return null;
|
||||
|
||||
const override = diffFileLayout[selectedFileEntry.path];
|
||||
if (override) return override;
|
||||
|
||||
if (diffLayoutPreference === 'inline' || diffLayoutPreference === 'side-by-side') {
|
||||
return diffLayoutPreference;
|
||||
}
|
||||
|
||||
return selectedFileEntry.isNew ? 'inline' : 'side-by-side';
|
||||
}, [selectedFileEntry, diffFileLayout, diffLayoutPreference]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!selectedFile && !pendingDiffFile && changedFiles.length > 0) {
|
||||
const nextPath = changedFiles[0].path;
|
||||
handleSelectFile(nextPath);
|
||||
}
|
||||
}, [changedFiles, selectedFile, pendingDiffFile, handleSelectFile]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (selectedFile && changedFiles.length > 0) {
|
||||
const stillExists = changedFiles.some((f) => f.path === selectedFile);
|
||||
if (!stillExists) {
|
||||
setSelectedFile(null);
|
||||
selectedFileRef.current = null;
|
||||
setFileDiff(null);
|
||||
setDiffError(null);
|
||||
}
|
||||
}
|
||||
}, [changedFiles, selectedFile]);
|
||||
|
||||
const loadDiff = React.useCallback(async () => {
|
||||
if (!effectiveDirectory || !selectedFileEntry) {
|
||||
setFileDiff(null);
|
||||
setDiffError(null);
|
||||
setIsDiffLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheKey = selectedFileEntry.path;
|
||||
|
||||
const cached = getCachedDiffIfFresh(effectiveDirectory, cacheKey);
|
||||
if (cached) {
|
||||
setFileDiff({ original: cached.original, modified: cached.modified });
|
||||
setDiffError(null);
|
||||
setIsDiffLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsDiffLoading(true);
|
||||
setDiffError(null);
|
||||
|
||||
try {
|
||||
const response = await git.getGitFileDiff(effectiveDirectory, {
|
||||
path: selectedFileEntry.path,
|
||||
});
|
||||
|
||||
const diff = {
|
||||
original: response.original ?? '',
|
||||
modified: response.modified ?? '',
|
||||
};
|
||||
setDiff(effectiveDirectory, cacheKey, diff);
|
||||
setFileDiff(diff);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to load diff';
|
||||
setDiffError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setIsDiffLoading(false);
|
||||
}
|
||||
}, [effectiveDirectory, git, selectedFileEntry, getCachedDiffIfFresh, setDiff, lastStatusChange]);
|
||||
|
||||
React.useEffect(() => {
|
||||
loadDiff();
|
||||
}, [loadDiff]);
|
||||
|
||||
const activeFilePath = selectedFileEntry?.path ?? '';
|
||||
|
||||
const renderContent = () => {
|
||||
if (!effectiveDirectory) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||
Select a session directory to view diffs
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoadingStatus && !status) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<RiLoader4Line size={16} className="animate-spin" />
|
||||
Loading repository status…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isGitRepo === false) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||
Not a git repository. Use the Git tab to initialize or change directories.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (changedFiles.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||
Working tree clean — no changes to display
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!selectedFileEntry) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||
Select a file to inspect its diff
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const effectiveLayout = currentLayoutForSelectedFile ?? 'side-by-side';
|
||||
const renderSideBySide = effectiveLayout === 'side-by-side';
|
||||
const hasFileOverride = !!diffFileLayout[selectedFileEntry.path];
|
||||
const allowResponsive =
|
||||
diffLayoutPreference === 'dynamic' && !hasFileOverride;
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 min-h-0 px-3 py-3">
|
||||
<DiffContent
|
||||
fileDiff={fileDiff}
|
||||
activeFilePath={activeFilePath}
|
||||
isDiffLoading={isDiffLoading}
|
||||
diffError={diffError}
|
||||
onRetry={loadDiff}
|
||||
renderSideBySide={renderSideBySide}
|
||||
allowResponsive={allowResponsive}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col overflow-hidden bg-background">
|
||||
<div className="flex items-center gap-3 px-3 py-2 bg-background">
|
||||
<div className="flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0">
|
||||
<RiGitCommitLine size={16} />
|
||||
<span className="typography-ui-label font-semibold text-foreground">
|
||||
{isLoadingStatus && !status
|
||||
? 'Loading changes…'
|
||||
: `${changedFiles.length} ${changedFiles.length === 1 ? 'file' : 'files'} changed`}
|
||||
</span>
|
||||
</div>
|
||||
<FileSelector
|
||||
changedFiles={changedFiles}
|
||||
selectedFile={selectedFile}
|
||||
selectedFileEntry={selectedFileEntry}
|
||||
onSelectFile={handleSelectFile}
|
||||
/>
|
||||
<div className="flex-1" />
|
||||
{selectedFileEntry && currentLayoutForSelectedFile && (
|
||||
<DiffViewToggle
|
||||
mode={currentLayoutForSelectedFile === 'side-by-side' ? 'side-by-side' : 'unified'}
|
||||
onModeChange={(mode: DiffViewMode) => {
|
||||
if (!selectedFileEntry) return;
|
||||
const nextLayout: 'inline' | 'side-by-side' =
|
||||
mode === 'side-by-side' ? 'side-by-side' : 'inline';
|
||||
setDiffFileLayout(selectedFileEntry.path, nextLayout);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{renderContent()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// eslint-disable-next-line react-refresh/only-export-components
|
||||
export const useDiffFileCount = (): number => {
|
||||
const { git } = useRuntimeAPIs();
|
||||
const { currentSessionId, sessions, worktreeMetadata: worktreeMap } = useSessionStore();
|
||||
const { currentDirectory: fallbackDirectory } = useDirectoryStore();
|
||||
|
||||
const worktreeMetadata = currentSessionId ? worktreeMap.get(currentSessionId) ?? undefined : undefined;
|
||||
const currentSession = sessions.find((session) => session.id === currentSessionId);
|
||||
const sessionDirectory = (currentSession as Record<string, unknown>)?.directory as string | undefined;
|
||||
const effectiveDirectory = worktreeMetadata?.path ?? sessionDirectory ?? fallbackDirectory ?? undefined;
|
||||
|
||||
const { setActiveDirectory, fetchStatus } = useGitStore();
|
||||
const fileCount = useGitFileCount(effectiveDirectory ?? null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (effectiveDirectory) {
|
||||
setActiveDirectory(effectiveDirectory);
|
||||
|
||||
const dirState = useGitStore.getState().directories.get(effectiveDirectory);
|
||||
if (!dirState?.status) {
|
||||
fetchStatus(effectiveDirectory, git);
|
||||
}
|
||||
}
|
||||
}, [effectiveDirectory, setActiveDirectory, fetchStatus, git]);
|
||||
|
||||
return fileCount;
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,151 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { DiffEditor, type DiffEditorProps, type MonacoDiffEditor } from '@monaco-editor/react';
|
||||
|
||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||
import { ensureMonacoThemeRegistered, getMonacoThemeIdForTheme } from '@/lib/theme/monacoThemeGenerator';
|
||||
|
||||
interface MonacoDiffViewerProps {
|
||||
original: string;
|
||||
modified: string;
|
||||
language: string;
|
||||
renderSideBySide: boolean;
|
||||
|
||||
allowResponsive?: boolean;
|
||||
readOnly?: boolean;
|
||||
showLineNumbers?: boolean;
|
||||
}
|
||||
|
||||
export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
|
||||
original,
|
||||
modified,
|
||||
language,
|
||||
renderSideBySide,
|
||||
allowResponsive = false,
|
||||
readOnly = true,
|
||||
showLineNumbers = true,
|
||||
}) => {
|
||||
const { currentTheme } = useThemeSystem();
|
||||
const diffEditorRef = useRef<MonacoDiffEditor | null>(null);
|
||||
|
||||
const themeId = useMemo(
|
||||
() => getMonacoThemeIdForTheme(currentTheme),
|
||||
[currentTheme],
|
||||
);
|
||||
|
||||
const handleBeforeMount = useCallback<NonNullable<DiffEditorProps['beforeMount']>>(
|
||||
(monacoInstance) => {
|
||||
ensureMonacoThemeRegistered(
|
||||
currentTheme,
|
||||
monacoInstance as Parameters<typeof ensureMonacoThemeRegistered>[1],
|
||||
);
|
||||
},
|
||||
[currentTheme],
|
||||
);
|
||||
|
||||
const options = useMemo(
|
||||
(): DiffEditorProps['options'] => ({
|
||||
readOnly,
|
||||
renderSideBySide,
|
||||
automaticLayout: true,
|
||||
minimap: { enabled: false },
|
||||
wordWrap: 'off',
|
||||
lineNumbers: showLineNumbers ? 'on' : 'off',
|
||||
renderIndicators: false,
|
||||
scrollBeyondLastLine: false,
|
||||
renderLineHighlight: 'none',
|
||||
selectionHighlight: false,
|
||||
occurrencesHighlight: 'off',
|
||||
roundedSelection: false,
|
||||
contextmenu: false,
|
||||
folding: false,
|
||||
glyphMargin: false,
|
||||
renderMarginRevertIcon: false,
|
||||
scrollbar: {
|
||||
vertical: 'visible',
|
||||
horizontal: 'visible',
|
||||
verticalScrollbarSize: 6,
|
||||
horizontalScrollbarSize: 6,
|
||||
useShadows: false,
|
||||
},
|
||||
hover: {
|
||||
enabled: false,
|
||||
},
|
||||
overviewRulerLanes: 1,
|
||||
|
||||
useInlineViewWhenSpaceIsLimited: allowResponsive,
|
||||
}),
|
||||
[allowResponsive, readOnly, renderSideBySide, showLineNumbers],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
const monaco = (window as typeof window & { monaco?: { editor: { setTheme: (id: string) => void } } }).monaco;
|
||||
if (!monaco?.editor?.setTheme) return;
|
||||
|
||||
ensureMonacoThemeRegistered(currentTheme);
|
||||
monaco.editor.setTheme(themeId);
|
||||
}, [currentTheme, themeId]);
|
||||
|
||||
useEffect(() => {
|
||||
const diffEditor = diffEditorRef.current;
|
||||
if (!diffEditor) return;
|
||||
|
||||
const originalEditor = diffEditor.getOriginalEditor();
|
||||
const modifiedEditor = diffEditor.getModifiedEditor();
|
||||
|
||||
const disablePopups = {
|
||||
hover: { enabled: false },
|
||||
quickSuggestions: false,
|
||||
parameterHints: { enabled: false },
|
||||
suggestOnTriggerCharacters: false,
|
||||
} as const;
|
||||
|
||||
originalEditor.updateOptions(disablePopups);
|
||||
modifiedEditor.updateOptions(disablePopups);
|
||||
}, [themeId, readOnly, renderSideBySide]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
const diffEditor = diffEditorRef.current;
|
||||
if (diffEditor) {
|
||||
try {
|
||||
diffEditor.dispose?.();
|
||||
} catch (error) {
|
||||
console.warn('Error disposing DiffEditor:', error);
|
||||
}
|
||||
}
|
||||
diffEditorRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<DiffEditor
|
||||
original={original}
|
||||
modified={modified}
|
||||
originalLanguage={language}
|
||||
modifiedLanguage={language}
|
||||
theme={themeId}
|
||||
options={options}
|
||||
beforeMount={handleBeforeMount}
|
||||
onMount={(diffEditor: MonacoDiffEditor) => {
|
||||
diffEditorRef.current = diffEditor;
|
||||
const original = diffEditor.getOriginalEditor();
|
||||
const modified = diffEditor.getModifiedEditor();
|
||||
const disablePopups = {
|
||||
hover: { enabled: false },
|
||||
quickSuggestions: false,
|
||||
parameterHints: { enabled: false },
|
||||
suggestOnTriggerCharacters: false,
|
||||
} as const;
|
||||
original.updateOptions(disablePopups);
|
||||
modified.updateOptions(disablePopups);
|
||||
}}
|
||||
loading={null}
|
||||
className="monaco-diff-wrapper"
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,784 @@
|
||||
import React from 'react';
|
||||
import { RiAlertLine, RiArrowDownLine, RiArrowGoBackLine, RiArrowLeftLine, RiArrowRightLine, RiArrowUpLine, RiCheckboxCircleLine, RiCircleLine, RiCloseLine, RiCommandLine, RiDeleteBinLine, RiRestartLine } from '@remixicon/react';
|
||||
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||
import { useTerminalStore } from '@/stores/useTerminalStore';
|
||||
import { type TerminalStreamEvent } from '@/lib/api/types';
|
||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||
import { useFontPreferences } from '@/hooks/useFontPreferences';
|
||||
import { CODE_FONT_OPTION_MAP, DEFAULT_MONO_FONT } from '@/lib/fontOptions';
|
||||
import { convertThemeToXterm } from '@/lib/terminalTheme';
|
||||
import { TerminalViewport, type TerminalController } from '@/components/terminal/TerminalViewport';
|
||||
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useDeviceInfo } from '@/lib/device';
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
|
||||
const TERMINAL_FONT_SIZE = 13;
|
||||
|
||||
type Modifier = 'ctrl' | 'cmd';
|
||||
type MobileKey =
|
||||
| 'esc'
|
||||
| 'tab'
|
||||
| 'enter'
|
||||
| 'arrow-up'
|
||||
| 'arrow-down'
|
||||
| 'arrow-left'
|
||||
| 'arrow-right';
|
||||
|
||||
const BASE_KEY_SEQUENCES: Record<MobileKey, string> = {
|
||||
esc: '\u001b',
|
||||
tab: '\t',
|
||||
enter: '\r',
|
||||
'arrow-up': '\u001b[A',
|
||||
'arrow-down': '\u001b[B',
|
||||
'arrow-left': '\u001b[D',
|
||||
'arrow-right': '\u001b[C',
|
||||
};
|
||||
|
||||
const MODIFIER_ARROW_SUFFIX: Record<Modifier, string> = {
|
||||
ctrl: '5',
|
||||
cmd: '3',
|
||||
};
|
||||
|
||||
const STREAM_OPTIONS = {
|
||||
retry: {
|
||||
maxRetries: 3,
|
||||
initialDelayMs: 500,
|
||||
maxDelayMs: 8000,
|
||||
},
|
||||
connectionTimeoutMs: 10_000,
|
||||
};
|
||||
|
||||
const getSequenceForKey = (key: MobileKey, modifier: Modifier | null): string | null => {
|
||||
if (modifier) {
|
||||
switch (key) {
|
||||
case 'arrow-up':
|
||||
return `\u001b[1;${MODIFIER_ARROW_SUFFIX[modifier]}A`;
|
||||
case 'arrow-down':
|
||||
return `\u001b[1;${MODIFIER_ARROW_SUFFIX[modifier]}B`;
|
||||
case 'arrow-right':
|
||||
return `\u001b[1;${MODIFIER_ARROW_SUFFIX[modifier]}C`;
|
||||
case 'arrow-left':
|
||||
return `\u001b[1;${MODIFIER_ARROW_SUFFIX[modifier]}D`;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return BASE_KEY_SEQUENCES[key] ?? null;
|
||||
};
|
||||
|
||||
export const TerminalView: React.FC = () => {
|
||||
const { terminal } = useRuntimeAPIs();
|
||||
const { currentTheme } = useThemeSystem();
|
||||
const { monoFont } = useFontPreferences();
|
||||
const { isMobile } = useDeviceInfo();
|
||||
|
||||
const { currentSessionId, sessions, worktreeMetadata: worktreeMap } = useSessionStore();
|
||||
const worktreeMetadata = currentSessionId ? worktreeMap.get(currentSessionId) ?? undefined : undefined;
|
||||
|
||||
const sessionDirectory = React.useMemo(() => {
|
||||
if (worktreeMetadata?.path) {
|
||||
return worktreeMetadata.path;
|
||||
}
|
||||
if (!currentSessionId) return null;
|
||||
const entry = sessions.find((session) => session.id === currentSessionId);
|
||||
const directory = typeof (entry as { directory?: string } | undefined)?.directory === 'string'
|
||||
? (entry as { directory?: string }).directory
|
||||
: null;
|
||||
return directory && directory.length > 0 ? directory : null;
|
||||
}, [currentSessionId, sessions, worktreeMetadata]);
|
||||
|
||||
const { currentDirectory: fallbackDirectory, homeDirectory } = useDirectoryStore();
|
||||
const effectiveDirectory = sessionDirectory || fallbackDirectory || null;
|
||||
|
||||
const displayDirectory = React.useMemo(() => {
|
||||
if (!effectiveDirectory) return '';
|
||||
if (!homeDirectory) return effectiveDirectory;
|
||||
if (effectiveDirectory === homeDirectory) return '~';
|
||||
if (effectiveDirectory.startsWith(homeDirectory + '/')) {
|
||||
return '~' + effectiveDirectory.slice(homeDirectory.length);
|
||||
}
|
||||
return effectiveDirectory;
|
||||
}, [effectiveDirectory, homeDirectory]);
|
||||
|
||||
const terminalStore = useTerminalStore();
|
||||
const terminalSessions = terminalStore.sessions;
|
||||
const setTerminalSession = terminalStore.setTerminalSession;
|
||||
const setConnecting = terminalStore.setConnecting;
|
||||
const appendToBuffer = terminalStore.appendToBuffer;
|
||||
const clearTerminalSession = terminalStore.clearTerminalSession;
|
||||
const removeTerminalSession = terminalStore.removeTerminalSession;
|
||||
const clearBuffer = terminalStore.clearBuffer;
|
||||
|
||||
const terminalState = React.useMemo(() => {
|
||||
if (!currentSessionId) return undefined;
|
||||
return terminalSessions.get(currentSessionId);
|
||||
}, [terminalSessions, currentSessionId]);
|
||||
const terminalSessionRef = terminalState?.terminalSessionId ?? null;
|
||||
const bufferChunks = terminalState?.bufferChunks ?? [];
|
||||
const bufferLength = terminalState?.bufferLength ?? 0;
|
||||
const isConnecting = terminalState?.isConnecting ?? false;
|
||||
const terminalSessionId = terminalSessionRef;
|
||||
|
||||
const [connectionError, setConnectionError] = React.useState<string | null>(null);
|
||||
const [activeModifier, setActiveModifier] = React.useState<Modifier | null>(null);
|
||||
|
||||
const streamCleanupRef = React.useRef<(() => void) | null>(null);
|
||||
const activeTerminalIdRef = React.useRef<string | null>(null);
|
||||
const sessionIdRef = React.useRef<string | null>(currentSessionId ?? null);
|
||||
const terminalIdRef = React.useRef<string | null>(terminalSessionId);
|
||||
const directoryRef = React.useRef<string | null>(effectiveDirectory);
|
||||
const terminalControllerRef = React.useRef<TerminalController | null>(null);
|
||||
|
||||
const activeMainTab = useUIStore((state) => state.activeMainTab);
|
||||
const isTerminalActive = activeMainTab === 'terminal';
|
||||
|
||||
React.useEffect(() => {
|
||||
sessionIdRef.current = currentSessionId ?? null;
|
||||
}, [currentSessionId]);
|
||||
|
||||
React.useEffect(() => {
|
||||
terminalIdRef.current = terminalSessionId;
|
||||
}, [terminalSessionId]);
|
||||
|
||||
React.useEffect(() => {
|
||||
directoryRef.current = effectiveDirectory;
|
||||
}, [effectiveDirectory]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isMobile && activeModifier !== null) {
|
||||
setActiveModifier(null);
|
||||
}
|
||||
}, [isMobile, activeModifier, setActiveModifier]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!terminalSessionId && activeModifier !== null) {
|
||||
setActiveModifier(null);
|
||||
}
|
||||
}, [terminalSessionId, activeModifier, setActiveModifier]);
|
||||
|
||||
const disconnectStream = React.useCallback(() => {
|
||||
streamCleanupRef.current?.();
|
||||
streamCleanupRef.current = null;
|
||||
activeTerminalIdRef.current = null;
|
||||
}, []);
|
||||
|
||||
React.useEffect(
|
||||
() => () => {
|
||||
disconnectStream();
|
||||
terminalIdRef.current = null;
|
||||
},
|
||||
[disconnectStream]
|
||||
);
|
||||
|
||||
const startStream = React.useCallback(
|
||||
(terminalId: string) => {
|
||||
if (activeTerminalIdRef.current === terminalId) {
|
||||
return;
|
||||
}
|
||||
|
||||
disconnectStream();
|
||||
|
||||
const subscription = terminal.connect(
|
||||
terminalId,
|
||||
{
|
||||
onEvent: (event: TerminalStreamEvent) => {
|
||||
const sessionId = sessionIdRef.current;
|
||||
if (!sessionId) return;
|
||||
|
||||
switch (event.type) {
|
||||
case 'connected': {
|
||||
setConnecting(sessionId, false);
|
||||
setConnectionError(null);
|
||||
terminalControllerRef.current?.focus();
|
||||
break;
|
||||
}
|
||||
case 'reconnecting': {
|
||||
const attempt = event.attempt ?? 0;
|
||||
const maxAttempts = event.maxAttempts ?? 3;
|
||||
setConnectionError(`Reconnecting (${attempt}/${maxAttempts})...`);
|
||||
break;
|
||||
}
|
||||
case 'data': {
|
||||
if (event.data) {
|
||||
appendToBuffer(sessionId, event.data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'exit': {
|
||||
const exitCode =
|
||||
typeof event.exitCode === 'number' ? event.exitCode : null;
|
||||
const signal = typeof event.signal === 'number' ? event.signal : null;
|
||||
appendToBuffer(
|
||||
sessionId,
|
||||
`\r\n[Process exited${
|
||||
exitCode !== null ? ` with code ${exitCode}` : ''
|
||||
}${signal !== null ? ` (signal ${signal})` : ''}]\r\n`
|
||||
);
|
||||
clearTerminalSession(sessionId);
|
||||
setConnecting(sessionId, false);
|
||||
setConnectionError('Terminal session ended');
|
||||
disconnectStream();
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
onError: (error, fatal) => {
|
||||
const sessionId = sessionIdRef.current;
|
||||
if (!sessionId) return;
|
||||
|
||||
const errorMsg = fatal
|
||||
? `Connection failed: ${error.message}`
|
||||
: error.message || 'Terminal stream connection error';
|
||||
|
||||
setConnectionError(errorMsg);
|
||||
|
||||
if (fatal) {
|
||||
setConnecting(sessionId, false);
|
||||
disconnectStream();
|
||||
removeTerminalSession(sessionId);
|
||||
}
|
||||
},
|
||||
},
|
||||
STREAM_OPTIONS
|
||||
);
|
||||
|
||||
streamCleanupRef.current = () => {
|
||||
subscription.close();
|
||||
activeTerminalIdRef.current = null;
|
||||
};
|
||||
activeTerminalIdRef.current = terminalId;
|
||||
},
|
||||
[appendToBuffer, clearTerminalSession, disconnectStream, removeTerminalSession, setConnecting, terminal, setConnectionError]
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
const sessionId = currentSessionId;
|
||||
|
||||
if (!sessionId || !effectiveDirectory) {
|
||||
setConnectionError(
|
||||
sessionId
|
||||
? 'No working directory available for terminal.'
|
||||
: 'Select a session to open the terminal.'
|
||||
);
|
||||
disconnectStream();
|
||||
return;
|
||||
}
|
||||
|
||||
const ensureSession = async () => {
|
||||
if (!sessionIdRef.current || sessionIdRef.current !== sessionId) return;
|
||||
const currentState = useTerminalStore.getState().sessions.get(sessionId);
|
||||
|
||||
if (
|
||||
currentState?.terminalSessionId &&
|
||||
currentState.directory &&
|
||||
currentState.directory !== effectiveDirectory
|
||||
) {
|
||||
disconnectStream();
|
||||
try {
|
||||
if (currentState.terminalSessionId) {
|
||||
await terminal.close(currentState.terminalSessionId);
|
||||
}
|
||||
} catch { /* ignored */ }
|
||||
removeTerminalSession(sessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
let terminalId = currentState?.terminalSessionId ?? null;
|
||||
|
||||
if (!terminalId) {
|
||||
setConnectionError(null);
|
||||
setConnecting(sessionId, true);
|
||||
try {
|
||||
const session = await terminal.createSession({
|
||||
cwd: effectiveDirectory,
|
||||
});
|
||||
if (cancelled) {
|
||||
try {
|
||||
await terminal.close(session.sessionId);
|
||||
} catch { /* ignored */ }
|
||||
return;
|
||||
}
|
||||
setTerminalSession(sessionId, session, effectiveDirectory);
|
||||
terminalId = session.sessionId;
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
setConnectionError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Failed to start terminal session'
|
||||
);
|
||||
setConnecting(sessionId, false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!terminalId || cancelled) return;
|
||||
|
||||
terminalIdRef.current = terminalId;
|
||||
startStream(terminalId);
|
||||
};
|
||||
|
||||
void ensureSession();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
terminalIdRef.current = null;
|
||||
disconnectStream();
|
||||
};
|
||||
}, [
|
||||
currentSessionId,
|
||||
effectiveDirectory,
|
||||
terminalSessionId,
|
||||
removeTerminalSession,
|
||||
setConnecting,
|
||||
setTerminalSession,
|
||||
startStream,
|
||||
disconnectStream,
|
||||
terminal,
|
||||
]);
|
||||
|
||||
const handleReconnect = React.useCallback(async () => {
|
||||
if (!currentSessionId) return;
|
||||
setConnectionError(null);
|
||||
disconnectStream();
|
||||
const terminalId = terminalSessionId;
|
||||
if (terminalId) {
|
||||
try {
|
||||
await terminal.close(terminalId);
|
||||
} catch { /* ignored */ }
|
||||
}
|
||||
removeTerminalSession(currentSessionId);
|
||||
}, [currentSessionId, disconnectStream, removeTerminalSession, terminal, terminalSessionId]);
|
||||
|
||||
const handleClear = React.useCallback(() => {
|
||||
if (!currentSessionId) return;
|
||||
clearBuffer(currentSessionId);
|
||||
terminalControllerRef.current?.clear();
|
||||
terminalControllerRef.current?.focus();
|
||||
|
||||
const terminalId = terminalIdRef.current;
|
||||
if (terminalId) {
|
||||
void terminal.sendInput(terminalId, '\u000c').catch((error) => {
|
||||
setConnectionError(error instanceof Error ? error.message : 'Failed to refresh prompt');
|
||||
});
|
||||
}
|
||||
}, [clearBuffer, currentSessionId, setConnectionError, terminal]);
|
||||
|
||||
const handleViewportInput = React.useCallback(
|
||||
(data: string) => {
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
|
||||
let payload = data;
|
||||
let modifierConsumed = false;
|
||||
|
||||
if (activeModifier && data.length > 0) {
|
||||
const firstChar = data[0];
|
||||
if (firstChar.length === 1 && /[a-zA-Z]/.test(firstChar)) {
|
||||
const upper = firstChar.toUpperCase();
|
||||
if (activeModifier === 'ctrl' || activeModifier === 'cmd') {
|
||||
payload = String.fromCharCode(upper.charCodeAt(0) & 0b11111);
|
||||
modifierConsumed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!modifierConsumed) {
|
||||
modifierConsumed = true;
|
||||
}
|
||||
}
|
||||
|
||||
const terminalId = terminalIdRef.current;
|
||||
if (!terminalId) return;
|
||||
|
||||
void terminal.sendInput(terminalId, payload).catch((error) => {
|
||||
setConnectionError(error instanceof Error ? error.message : 'Failed to send input');
|
||||
});
|
||||
|
||||
if (modifierConsumed) {
|
||||
setActiveModifier(null);
|
||||
terminalControllerRef.current?.focus();
|
||||
}
|
||||
},
|
||||
[activeModifier, setActiveModifier, terminal]
|
||||
);
|
||||
|
||||
const handleViewportResize = React.useCallback(
|
||||
(cols: number, rows: number) => {
|
||||
const terminalId = terminalIdRef.current;
|
||||
if (!terminalId) return;
|
||||
void terminal.resize({ sessionId: terminalId, cols, rows }).catch(() => {
|
||||
|
||||
});
|
||||
},
|
||||
[terminal]
|
||||
);
|
||||
|
||||
const handleModifierToggle = React.useCallback(
|
||||
(modifier: Modifier) => {
|
||||
setActiveModifier((current) => (current === modifier ? null : modifier));
|
||||
terminalControllerRef.current?.focus();
|
||||
},
|
||||
[setActiveModifier]
|
||||
);
|
||||
|
||||
const handleMobileKeyPress = React.useCallback(
|
||||
(key: MobileKey) => {
|
||||
const sequence = getSequenceForKey(key, activeModifier);
|
||||
if (!sequence) {
|
||||
return;
|
||||
}
|
||||
handleViewportInput(sequence);
|
||||
setActiveModifier(null);
|
||||
terminalControllerRef.current?.focus();
|
||||
},
|
||||
[activeModifier, handleViewportInput, setActiveModifier]
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isMobile || !activeModifier || !terminalSessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.repeat) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rawKey = event.key;
|
||||
if (!rawKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (rawKey === 'Control' || rawKey === 'Meta' || rawKey === 'Alt' || rawKey === 'Shift') {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedKey = rawKey.length === 1 ? rawKey.toLowerCase() : rawKey;
|
||||
const code = event.code ?? '';
|
||||
const upperFromCode =
|
||||
code.startsWith('Key') && code.length === 4
|
||||
? code.slice(3).toUpperCase()
|
||||
: null;
|
||||
const upperKey =
|
||||
rawKey.length === 1 && /[a-zA-Z]/.test(rawKey)
|
||||
? rawKey.toUpperCase()
|
||||
: upperFromCode;
|
||||
|
||||
const toMobileKey: Record<string, MobileKey> = {
|
||||
Tab: 'tab',
|
||||
Enter: 'enter',
|
||||
ArrowUp: 'arrow-up',
|
||||
ArrowDown: 'arrow-down',
|
||||
ArrowLeft: 'arrow-left',
|
||||
ArrowRight: 'arrow-right',
|
||||
Escape: 'esc',
|
||||
tab: 'tab',
|
||||
enter: 'enter',
|
||||
arrowup: 'arrow-up',
|
||||
arrowdown: 'arrow-down',
|
||||
arrowleft: 'arrow-left',
|
||||
arrowright: 'arrow-right',
|
||||
escape: 'esc',
|
||||
};
|
||||
|
||||
if (normalizedKey in toMobileKey) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleMobileKeyPress(toMobileKey[normalizedKey]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (activeModifier === 'ctrl' && upperKey && upperKey.length === 1) {
|
||||
if (upperKey >= 'A' && upperKey <= 'Z') {
|
||||
const controlCode = String.fromCharCode(upperKey.charCodeAt(0) & 0b11111);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleViewportInput(controlCode);
|
||||
setActiveModifier(null);
|
||||
terminalControllerRef.current?.focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [
|
||||
activeModifier,
|
||||
handleMobileKeyPress,
|
||||
handleViewportInput,
|
||||
isMobile,
|
||||
setActiveModifier,
|
||||
terminalSessionId,
|
||||
]);
|
||||
|
||||
const resolvedFontStack = React.useMemo(() => {
|
||||
const defaultStack = CODE_FONT_OPTION_MAP[DEFAULT_MONO_FONT].stack;
|
||||
if (typeof window === 'undefined') {
|
||||
const fallbackDefinition =
|
||||
CODE_FONT_OPTION_MAP[monoFont] ?? CODE_FONT_OPTION_MAP[DEFAULT_MONO_FONT];
|
||||
return fallbackDefinition.stack;
|
||||
}
|
||||
|
||||
const root = window.getComputedStyle(document.documentElement);
|
||||
const cssStack = root.getPropertyValue('--font-family-mono');
|
||||
if (cssStack && cssStack.trim().length > 0) {
|
||||
return cssStack.trim();
|
||||
}
|
||||
|
||||
const definition =
|
||||
CODE_FONT_OPTION_MAP[monoFont] ?? CODE_FONT_OPTION_MAP[DEFAULT_MONO_FONT];
|
||||
return definition.stack ?? defaultStack;
|
||||
}, [monoFont]);
|
||||
|
||||
const xtermTheme = React.useMemo(() => convertThemeToXterm(currentTheme), [currentTheme]);
|
||||
|
||||
const terminalSessionKey = React.useMemo(() => {
|
||||
const sessionPart = currentSessionId ?? 'none';
|
||||
const directoryPart = effectiveDirectory ?? 'no-dir';
|
||||
const terminalPart = terminalSessionId ?? 'pending';
|
||||
return `${sessionPart}::${directoryPart}::${terminalPart}`;
|
||||
}, [currentSessionId, effectiveDirectory, terminalSessionId]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isTerminalActive) {
|
||||
return;
|
||||
}
|
||||
const controller = terminalControllerRef.current;
|
||||
if (!controller) {
|
||||
return;
|
||||
}
|
||||
const fitOnce = () => {
|
||||
controller.fit();
|
||||
};
|
||||
if (typeof window !== 'undefined') {
|
||||
const rafId = window.requestAnimationFrame(() => {
|
||||
fitOnce();
|
||||
controller.focus();
|
||||
});
|
||||
const timeoutIds = [220, 400].map((delay) => window.setTimeout(fitOnce, delay));
|
||||
return () => {
|
||||
window.cancelAnimationFrame(rafId);
|
||||
timeoutIds.forEach((id) => window.clearTimeout(id));
|
||||
};
|
||||
}
|
||||
fitOnce();
|
||||
}, [isTerminalActive, terminalSessionKey, currentSessionId, terminalSessionId]);
|
||||
|
||||
const isReconnecting = connectionError?.includes('Reconnecting');
|
||||
|
||||
const statusIcon = connectionError
|
||||
? isReconnecting
|
||||
? <RiAlertLine size={20} className="text-amber-400" />
|
||||
: <RiCloseLine size={20} className="text-destructive" />
|
||||
: terminalSessionId && !isConnecting
|
||||
? <RiCheckboxCircleLine size={20} className="text-emerald-400" />
|
||||
: isConnecting
|
||||
? <RiCircleLine size={20} className="text-amber-400 animate-pulse" />
|
||||
: <RiCircleLine size={20} className="text-muted-foreground" />;
|
||||
|
||||
if (!currentSessionId) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground">
|
||||
Select a session to open the terminal
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!effectiveDirectory) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground">
|
||||
<p>No working directory available for this session.</p>
|
||||
<button
|
||||
onClick={handleReconnect}
|
||||
className="rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const quickKeysDisabled = !terminalSessionId || isConnecting;
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col overflow-hidden bg-background">
|
||||
<div className="px-3 py-2 text-xs bg-background">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-2 text-muted-foreground">
|
||||
<span className="truncate font-mono text-foreground/90">{displayDirectory}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{statusIcon}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
className="h-7 px-2 py-0"
|
||||
onClick={handleClear}
|
||||
disabled={!bufferLength}
|
||||
title="Clear output"
|
||||
type="button"
|
||||
>
|
||||
<RiDeleteBinLine size={16} />
|
||||
Clear
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
className="h-7 px-2 py-0"
|
||||
onClick={handleReconnect}
|
||||
title="Restart terminal session"
|
||||
type="button"
|
||||
>
|
||||
<RiRestartLine size={16} className={cn(isConnecting && 'animate-spin')} />
|
||||
Restart
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{isMobile ? (
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-6 px-2 text-xs"
|
||||
onClick={() => handleMobileKeyPress('esc')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
Esc
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-6 w-9 p-0"
|
||||
onClick={() => handleMobileKeyPress('tab')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
<RiArrowRightLine size={16} />
|
||||
<span className="sr-only">Tab</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={activeModifier === 'ctrl' ? 'default' : 'outline'}
|
||||
className="h-6 w-9 p-0"
|
||||
onClick={() => handleModifierToggle('ctrl')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
<span className="text-xs font-medium">Ctrl</span>
|
||||
<span className="sr-only">Control modifier</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={activeModifier === 'cmd' ? 'default' : 'outline'}
|
||||
className="h-6 w-9 p-0"
|
||||
onClick={() => handleModifierToggle('cmd')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
<RiCommandLine size={16} />
|
||||
<span className="sr-only">Command modifier</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-6 w-9 p-0"
|
||||
onClick={() => handleMobileKeyPress('arrow-up')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
<RiArrowUpLine size={16} />
|
||||
<span className="sr-only">Arrow up</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-6 w-9 p-0"
|
||||
onClick={() => handleMobileKeyPress('arrow-left')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
<RiArrowLeftLine size={16} />
|
||||
<span className="sr-only">Arrow left</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-6 w-9 p-0"
|
||||
onClick={() => handleMobileKeyPress('arrow-down')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
<RiArrowDownLine size={16} />
|
||||
<span className="sr-only">Arrow down</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-6 w-9 p-0"
|
||||
onClick={() => handleMobileKeyPress('arrow-right')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
<RiArrowRightLine size={16} />
|
||||
<span className="sr-only">Arrow right</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-6 w-9 p-0"
|
||||
onClick={() => handleMobileKeyPress('enter')}
|
||||
disabled={quickKeysDisabled}
|
||||
>
|
||||
<RiArrowGoBackLine size={16} />
|
||||
<span className="sr-only">Enter</span>
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="relative flex-1 overflow-hidden"
|
||||
style={{ backgroundColor: xtermTheme.background }}
|
||||
>
|
||||
<div className="h-full w-full box-border px-3 pt-3 pb-4">
|
||||
{isTerminalActive ? (
|
||||
<ScrollableOverlay outerClassName="h-full" className="h-full w-full" disableHorizontal>
|
||||
<TerminalViewport
|
||||
key={terminalSessionKey}
|
||||
ref={(controller) => {
|
||||
terminalControllerRef.current = controller;
|
||||
}}
|
||||
sessionKey={terminalSessionKey}
|
||||
chunks={bufferChunks}
|
||||
onInput={handleViewportInput}
|
||||
onResize={handleViewportResize}
|
||||
theme={xtermTheme}
|
||||
fontFamily={resolvedFontStack}
|
||||
fontSize={TERMINAL_FONT_SIZE}
|
||||
enableTouchScroll={isMobile}
|
||||
/>
|
||||
</ScrollableOverlay>
|
||||
) : null}
|
||||
</div>
|
||||
{connectionError && (
|
||||
<div className="absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground">
|
||||
{connectionError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
export { ChatView } from './ChatView';
|
||||
export { GitView } from './GitView';
|
||||
export { DiffView, useDiffFileCount } from './DiffView';
|
||||
export { TerminalView } from './TerminalView';
|
||||
Reference in New Issue
Block a user