copy path and chat about file/folder

This commit is contained in:
2026-02-23 05:15:13 +00:00
parent bdefc52331
commit 9acef6cf6c
24 changed files with 1052 additions and 45 deletions
@@ -108,12 +108,31 @@ export function useEmbeddableChat(params: UseEmbeddableChatParams) {
};
// Auto-resize textarea
useEffect(() => {
const resizeTextarea = () => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
}, [input]);
};
useEffect(resizeTextarea, [input]);
// Re-measure when textarea width changes (e.g. panel animation)
useEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
let rafId = 0;
let prevWidth = textarea.clientWidth;
const observer = new ResizeObserver(() => {
const width = textarea.clientWidth;
if (width === prevWidth) return;
prevWidth = width;
cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(resizeTextarea);
});
observer.observe(textarea);
return () => { observer.disconnect(); cancelAnimationFrame(rafId); };
}, []);
// Auto-scroll to bottom on new messages
useEffect(() => {
@@ -53,6 +53,7 @@ export const FileGrid = ({ fileBrowserManager }: FileGridProps) => {
handleDelete,
handleRename,
handleChat,
handleCopyPath,
handleDownload,
setSelected,
handleCut,
@@ -170,6 +171,7 @@ export const FileGrid = ({ fileBrowserManager }: FileGridProps) => {
onDelete={handleDelete}
onRename={handleRename}
onChat={handleChat}
onCopyPath={handleCopyPath}
onDownload={handleDownload}
onSelect={handleSelect}
onCut={handleCut}
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react';
import { Folder, Trash2, Pencil, MoreVertical, MessageSquare, Scissors, Copy, Check, Play, Download, LayoutGrid, Volume2, ScanText, FileText, AudioLines, FolderArchive } from 'lucide-react';
import { Folder, Trash2, Pencil, MoreVertical, MessageSquare, Scissors, Copy, Check, Play, Download, LayoutGrid, Volume2, ScanText, FileText, AudioLines, FolderArchive, ClipboardCopy } from 'lucide-react';
import { getIcon } from 'material-file-icons';
import {
DropdownMenu,
@@ -37,6 +37,7 @@ export type FileItemProps = {
onDelete: (entry: DirEntry) => void;
onRename: (entry: DirEntry, newName: string) => void;
onChat: (entry: DirEntry) => void;
onCopyPath: (entry: DirEntry) => void;
onDownload: (entry: DirEntry) => void;
onSelect: (entry: DirEntry, ev: React.MouseEvent) => void;
onCut: () => void;
@@ -73,6 +74,7 @@ type MenuItemsProps = {
onDelete: (e: DirEntry) => void;
onStartRename: () => void;
onChat: (e: DirEntry) => void;
onCopyPath: (e: DirEntry) => void;
onDownload: (e: DirEntry) => void;
onReadAloud: (e: DirEntry) => void;
onOcr: (e: DirEntry) => void;
@@ -92,6 +94,7 @@ const DropdownMenuItems = ({
onDelete,
onStartRename,
onChat,
onCopyPath,
onDownload,
onReadAloud,
onOcr,
@@ -117,6 +120,10 @@ const DropdownMenuItems = ({
<MessageSquare className="mr-2 h-4 w-4" />
Chat...
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onCopyPath(entry)} className="cursor-pointer">
<ClipboardCopy className="mr-2 h-4 w-4" />
Copy path
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onDownload(entry)} className="cursor-pointer">
<Download className="mr-2 h-4 w-4" />
Download
@@ -205,6 +212,7 @@ const ContextMenuItems = ({
onDelete,
onStartRename,
onChat,
onCopyPath,
onDownload,
onReadAloud,
onOcr,
@@ -230,6 +238,10 @@ const ContextMenuItems = ({
<MessageSquare className="mr-2 h-4 w-4" />
Chat...
</ContextMenuItem>
<ContextMenuItem onClick={() => onCopyPath(entry)} className="cursor-pointer">
<ClipboardCopy className="mr-2 h-4 w-4" />
Copy path
</ContextMenuItem>
<ContextMenuItem onClick={() => onDownload(entry)} className="cursor-pointer">
<Download className="mr-2 h-4 w-4" />
Download
@@ -414,6 +426,7 @@ export const FileItem = ({
onDelete,
onRename,
onChat,
onCopyPath,
onDownload,
onSelect,
onCut,
@@ -499,6 +512,7 @@ export const FileItem = ({
onDelete,
onStartRename: () => setRenaming(true),
onChat,
onCopyPath,
onDownload,
onReadAloud,
onOcr,
@@ -1,4 +1,4 @@
import { Loader2, Folder, ClipboardPaste, FolderPlus, LayoutGrid, Download, Upload } from 'lucide-react';
import { Loader2, Folder, ClipboardPaste, FolderPlus, LayoutGrid, Download, Upload, ClipboardCopy, MessageSquare } from 'lucide-react';
import { getIcon } from 'material-file-icons';
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from '@/components/ui/context-menu';
import type { UseFileBrowserAppType } from '../useFileBrowserApp';
@@ -23,6 +23,8 @@ export const FileViewContainer = ({ fileBrowserManager }: FileViewContainerProps
handleBackgroundClick,
loading,
handlePaste,
handleCopyCurrentPath,
handleChatHere,
handleCreateDir,
handleCreateWorkspaceHere,
setShowVideoDownload,
@@ -96,6 +98,14 @@ export const FileViewContainer = ({ fileBrowserManager }: FileViewContainerProps
</div>
</ContextMenuTrigger>
<ContextMenuContent className="z-[600]">
<ContextMenuItem onClick={handleCopyCurrentPath} className="cursor-pointer">
<ClipboardCopy className="mr-2 h-4 w-4" />
Copy path
</ContextMenuItem>
<ContextMenuItem onClick={handleChatHere} className="cursor-pointer">
<MessageSquare className="mr-2 h-4 w-4" />
Chat about this
</ContextMenuItem>
<ContextMenuItem onClick={handlePaste} className="cursor-pointer">
<ClipboardPaste className="mr-2 h-4 w-4" />
Paste
@@ -23,6 +23,7 @@ export const useFileBrowserApp = (basePath: string, rootOverride?: string, initi
const currentPath = (scoped || isolated) ? localPath : globalPath;
const setCurrentPath = (scoped || isolated) ? setLocalPath : setGlobalPath;
const [entries, setEntries] = useState<DirEntry[]>([]);
const [rootDir, setRootDir] = useState('');
const [loading, setLoading] = useState(true);
const [viewMode, setViewMode] = useUserState<'grid' | 'list'>('files/viewMode', 'grid');
const [showHidden, setShowHidden] = useUserState<boolean>('files/showHidden', false);
@@ -66,6 +67,7 @@ export const useFileBrowserApp = (basePath: string, rootOverride?: string, initi
return;
}
setEntries(data.entries);
if (data.rootDir) setRootDir(data.rootDir);
} catch (err: any) {
console.error('[FileBrowser] refresh error:', err);
toast.error(err?.message || 'Failed to load directory');
@@ -332,16 +334,19 @@ export const useFileBrowserApp = (basePath: string, rootOverride?: string, initi
}
};
const absPath = (relPath: string) => {
const rel = relPath.replace(/^\/+/, '');
return rel ? `${rootDir}/${rel}` : rootDir;
};
const handleChat = (entry: DirEntry) => {
const path = entryPath(entry.name).replace(/^\//, '');
const isDir = entry.type === 'directory';
const tag = isDir ? 'folder' : 'file';
const cwdPath = isDir ? path : currentPath.replace(/^\//, '');
const message = isDir
? `[${tag}: ${path}] consider, for this session, this directory as your current working directory`
: `[${tag}: ${path}] Let's talk about this file`;
navigate('/chat/new', {
state: { initialMessage: message, cwd: { root: homeRoot, path: cwdPath } },
const path = entryPath(entry.name);
const type = entry.type === 'directory' ? 'folder' : 'file';
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
next.set('chatContext', path);
next.set('chatType', type);
return next;
});
};
@@ -373,6 +378,25 @@ export const useFileBrowserApp = (basePath: string, rootOverride?: string, initi
navigate(`/workspaces/new?name=${encodeURIComponent(entry.name)}&cwd=${encodeURIComponent(folderPath)}`);
};
const handleCopyPath = (entry: DirEntry) => {
navigator.clipboard.writeText(absPath(entryPath(entry.name)));
toast.success('Path copied');
};
const handleCopyCurrentPath = () => {
navigator.clipboard.writeText(absPath(currentPath));
toast.success('Path copied');
};
const handleChatHere = () => {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
next.set('chatContext', currentPath);
next.set('chatType', 'folder');
return next;
});
};
const handleCreateWorkspaceHere = () => {
const dirName = currentPath === '/' ? '' : currentPath.split('/').pop()!;
const params = new URLSearchParams({ cwd: currentPath });
@@ -663,6 +687,9 @@ export const useFileBrowserApp = (basePath: string, rootOverride?: string, initi
handleDelete,
handleDeleteSelected,
handleChat,
handleCopyPath,
handleCopyCurrentPath,
handleChatHere,
handleDownload,
handleDownloadSelected,
handleRunTask,
@@ -22,6 +22,8 @@ export type FileViewerContextValue = {
handleExtractAudio: () => void;
handleExtract: () => void;
handleDownload: () => void;
handleSaveResult: (() => void) | null;
saveResultLoading: boolean;
};
export const FileViewerContext = createContext<FileViewerContextValue | null>(null);
@@ -1,4 +1,4 @@
import { Download, Loader2, Music, Film, Image, FileType2, Volume2, ScanText, FileText, AudioLines, FolderArchive } from 'lucide-react';
import { Download, Loader2, Music, Film, Image, FileType2, Volume2, ScanText, FileText, AudioLines, FolderArchive, Save } from 'lucide-react';
import { getIcon } from 'material-file-icons';
import { getLang } from './file-types';
import { useFileViewer } from './FileViewerContext';
@@ -20,6 +20,8 @@ export const FileViewerHeader = () => {
handleExtractAudio,
handleExtract,
handleDownload,
handleSaveResult,
saveResultLoading,
} = useFileViewer();
const headerIcon =
@@ -94,6 +96,16 @@ export const FileViewerHeader = () => {
{extractLoading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FolderArchive className="h-3.5 w-3.5" />}
</button>
)}
{handleSaveResult && (
<button
onClick={handleSaveResult}
disabled={saveResultLoading}
className="p-1 rounded hover:bg-current/10 disabled:opacity-40 transition-colors cursor-pointer"
title="Save next to original"
>
{saveResultLoading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
</button>
)}
{!directContent && (
<button
onClick={handleDownload}
@@ -32,6 +32,7 @@ export const FileViewerProvider = ({
const [transcribeLoading, setTranscribeLoading] = useState(false);
const [extractAudioLoading, setExtractAudioLoading] = useState(false);
const [extractLoading, setExtractLoading] = useState(false);
const [saveResultLoading, setSaveResultLoading] = useState(false);
const files = useFilesAPI(root);
const fileType = getFileType(fileName);
@@ -111,6 +112,25 @@ export const FileViewerProvider = ({
}
};
const isCachedResult =
root === 'user-data' &&
(filePath.startsWith('ocr/') || filePath.startsWith('tts/') || filePath.startsWith('transcriptions/') || filePath.startsWith('audio/'));
const handleSaveResult = isCachedResult
? async () => {
setSaveResultLoading(true);
try {
const { savedPath } = await files.saveResult(filePath);
const savedName = savedPath.split('/').pop() ?? savedPath;
toast.success(`Saved as "${savedName}"`);
} catch {
toast.error('Failed to save file');
} finally {
setSaveResultLoading(false);
}
}
: null;
const handleExtract = async () => {
setExtractLoading(true);
try {
@@ -147,6 +167,8 @@ export const FileViewerProvider = ({
handleExtractAudio,
handleExtract,
handleDownload,
handleSaveResult,
saveResultLoading,
}}
>
{children}
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react';
import { useSearchParams } from 'react-router';
import { useUserState } from 'state/useUserState';
import { FileViewerProvider } from '../../apps/FileViewer';
import { EmbeddableChat } from '../../apps/Chat/EmbeddableChat';
export function ViewerProvider({ children }: { children: ReactNode }) {
const [searchParams, setSearchParams] = useSearchParams();
@@ -61,3 +62,31 @@ export function Ephemeral2Provider({ children }: { children: ReactNode }) {
</FileViewerProvider>
);
}
export const ChatEphemeralBody = () => {
const [searchParams] = useSearchParams();
const [homeRoot] = useUserState<string>('files/homeRoot', 'home');
const chatContext = searchParams.get('chatContext') ?? '';
const chatType = searchParams.get('chatType') as 'file' | 'folder' | null;
const hostRoot = homeRoot === '~' || homeRoot === 'officer.dev';
const sandboxed = !hostRoot;
const cwdPath = chatType === 'file'
? chatContext.substring(0, chatContext.lastIndexOf('/')) || '/'
: chatContext;
const tag = chatType === 'file' ? 'file' : 'folder';
const path = chatContext.replace(/^\//, '');
const message = chatType === 'file'
? `[${tag}: ${path}] Let's talk about this file`
: `[${tag}: ${path || '/'}] consider, for this session, this directory as your current working directory`;
return (
<EmbeddableChat
className="h-full"
cwd={{ root: homeRoot, path: cwdPath.replace(/^\//, '') || '/' }}
sandboxed={sandboxed}
defaultInput={message}
/>
);
};
@@ -16,6 +16,12 @@ export const viewerWithEphemeralLayout: LayoutNode = {
],
};
export const singleChatLayout: LayoutNode = {
type: 'panel',
id: 'files-chat',
appType: null,
};
export const viewerWithEphemeralSplitLayout: LayoutNode = {
type: 'group',
id: 'files-viewer-group',
@@ -1,18 +1,37 @@
import { useCallback, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useSearchParams } from 'react-router';
import type { EphemeralPanels } from '../../components/Workspace';
import { FileViewerHeader, FileViewerBody } from '../../apps/FileViewer';
import { singleViewerLayout, viewerWithEphemeralLayout, viewerWithEphemeralSplitLayout } from './layouts';
import { ViewerProvider, EphemeralProvider, Ephemeral2Provider } from './Providers';
import { singleViewerLayout, viewerWithEphemeralLayout, viewerWithEphemeralSplitLayout, singleChatLayout } from './layouts';
import { ViewerProvider, EphemeralProvider, Ephemeral2Provider, ChatEphemeralBody } from './Providers';
const EPHEMERAL_KEYS = ['view', 'ephemeral', 'ephemeralRoot', 'ephemeral2', 'ephemeral2Root', 'ephemeral2Auto', 'chatContext', 'chatType'];
export const useFileViewerPanels = (): EphemeralPanels | null => {
const [searchParams, setSearchParams] = useSearchParams();
const didClean = useRef(false);
// Clear stale ephemeral params on mount (page refresh)
useEffect(() => {
if (didClean.current) return;
didClean.current = true;
if (EPHEMERAL_KEYS.some((k) => searchParams.has(k))) {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
EPHEMERAL_KEYS.forEach((k) => next.delete(k));
return next;
});
}
}, []);
const viewPath = searchParams.get('view');
const ephemeralPath = searchParams.get('ephemeral');
const ephemeral2Path = searchParams.get('ephemeral2');
const chatContext = searchParams.get('chatContext');
const layout =
viewPath && ephemeralPath && ephemeral2Path
const layout = chatContext
? singleChatLayout
: viewPath && ephemeralPath && ephemeral2Path
? viewerWithEphemeralSplitLayout
: viewPath && ephemeralPath
? viewerWithEphemeralLayout
@@ -46,6 +65,17 @@ export const useFileViewerPanels = (): EphemeralPanels | null => {
[setSearchParams],
);
const onCloseChat = useCallback(
() =>
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
next.delete('chatContext');
next.delete('chatType');
return next;
}),
[setSearchParams],
);
const components = useMemo(
() => ({
'files-viewer': {
@@ -66,11 +96,15 @@ export const useFileViewerPanels = (): EphemeralPanels | null => {
component: FileViewerBody,
onClose: onCloseEphemeral2,
},
'files-chat': {
component: ChatEphemeralBody,
onClose: onCloseChat,
},
}),
[onCloseViewer, onCloseEphemeral, onCloseEphemeral2],
[onCloseViewer, onCloseEphemeral, onCloseEphemeral2, onCloseChat],
);
if (!viewPath) return null;
if (!viewPath && !chatContext) return null;
return { layout, components, defaultBaseSize: 40 };
};
@@ -63,6 +63,9 @@ export const useFilesAPI = (root: string = 'home') => {
extract: (path: string) =>
client.post<{ extractedPath: string }>(withRoot('/file-browser/extract'), { path }),
saveResult: (path: string) =>
client.post<{ savedPath: string }>('/file-browser/save-result', { path }),
getRawUrl: (path: string) => {
const token = getHeaders()['Authorization']?.replace('Bearer ', '') ?? '';
const rp = root !== 'home' ? `&root=${encodeURIComponent(root)}` : '';
@@ -134,6 +137,7 @@ export type DirEntry = {
type ListDirResponse = {
path: string;
rootDir: string;
entries: DirEntry[];
reset?: boolean;
};