"use client"; import { useEffect, useMemo, useReducer, useRef, useState } from "react"; import { ChevronDown, ChevronRight, FileArchive, FileText, Folder, FolderOpen, FolderTree, Search, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { useAddItem, useDeleteItem, useItem, useItems, useUpdateItem, } from "@/hooks/use-file-memory"; import { useI18n } from "@/i18n/i18n-context"; import { buildFileTree, flattenVisible } from "@/lib/file-tree"; import { cn } from "@/lib/utils"; import { ApiClientError } from "@/services/api-client"; import type { FileMemoryItem, FileMemoryScope, ListItemsResponse, } from "@/types/file-memory"; import { FileDetailsPanel } from "./file-details-panel"; import { downloadFileMemoryBinary, fileMemoryBinaryAcceptForPath, fileMemoryBinaryErrorKey, fileMemoryBinaryMediaType, isFileMemoryBinary, readFileMemoryBinary, } from "./file-binary-content"; import { FileEditor, MAX_FILE_CONTENT_BYTES, normalizeFileMemoryPath, validateFileMemoryContent, } from "./file-editor"; import { FileMutationDialogs, type FileMutationDialog, } from "./file-mutation-dialogs"; import { FileWorkspaceToolbar } from "./file-workspace-toolbar"; export interface WorkspaceEditorState { selectedPath: string | null; content: string; loadedItemId: string | null; loadedVersionId: string | null; dirty: boolean; conflict: string | null; } export const initialWorkspaceEditorState: WorkspaceEditorState = { selectedPath: null, content: "", loadedItemId: null, loadedVersionId: null, dirty: false, conflict: null, }; type WorkspaceEditorAction = | { type: "select"; path: string | null } | { type: "load"; path: string; content: string; itemId: string; versionId: string; } | { type: "edit"; content: string } | { type: "save-success"; itemId: string; versionId: string; content?: string; } | { type: "rename-success"; path: string; itemId: string; versionId: string; content?: string; } | { type: "save-conflict"; message: string }; export function workspaceEditorReducer( state: WorkspaceEditorState, action: WorkspaceEditorAction, ): WorkspaceEditorState { switch (action.type) { case "select": return { ...initialWorkspaceEditorState, selectedPath: action.path, }; case "load": if (state.selectedPath !== action.path) return state; return { selectedPath: action.path, content: action.content, loadedItemId: action.itemId, loadedVersionId: action.versionId, dirty: false, conflict: null, }; case "edit": return { ...state, content: action.content, dirty: true, conflict: null }; case "save-success": return { ...state, content: action.content ?? state.content, loadedItemId: action.itemId, loadedVersionId: action.versionId, dirty: false, conflict: null, }; case "rename-success": return { selectedPath: action.path, content: action.content ?? state.content, loadedItemId: action.itemId, loadedVersionId: action.versionId, dirty: false, conflict: null, }; case "save-conflict": return { ...state, dirty: true, conflict: action.message }; } } export function isFileMemoryReadOnly( pages: Array> | undefined, ): boolean { return pages?.some((page) => page.readOnly === true) ?? false; } export function shouldApplyFileSelection( editor: WorkspaceEditorState, nextPath: string | null, confirmDiscard: () => boolean, ): boolean { return !editor.dirty || nextPath === editor.selectedPath || confirmDiscard(); } export function isFileMemoryVersionConflict(error: unknown): boolean { if (error instanceof ApiClientError && error.code === "LOCK_CONFLICT") { return true; } return error instanceof Error && error.message.includes("LOCK_CONFLICT"); } export function buildFileUpdateRequest( current: Pick, content: string, ) { return { itemId: current.itemId, content, precondition: { expectedVersionId: current.latestVersionId }, view: "full" as const, }; } export function isFileMutationPending( mode: FileMutationDialog, pending: { create: boolean; rename: boolean; delete: boolean }, ): boolean { if (mode === "create" || mode === "upload") return pending.create; if (mode === "rename") return pending.rename; if (mode === "delete") return pending.delete; return false; } export function MemoryFilesBrowser({ memoryStoreName, scope, enabled = true, initialPath, className, }: { memoryStoreName: string; scope: FileMemoryScope; enabled?: boolean; initialPath?: string | null; className?: string; }) { const { t } = useI18n(); const [editor, dispatch] = useReducer( workspaceEditorReducer, initialWorkspaceEditorState, ); const editorRef = useRef(editor); editorRef.current = editor; const tRef = useRef(t); tRef.current = t; const [collapsed, setCollapsed] = useState>(new Set()); const [filter, setFilter] = useState(""); const [dialog, setDialog] = useState(null); useEffect(() => { if (initialPath) { const path = normalizeFileMemoryPath(initialPath); if ( shouldApplyFileSelection(editorRef.current, path, () => window.confirm(tRef.current("memory.files.discardChanges")), ) ) { dispatch({ type: "select", path }); } } }, [initialPath]); const listQuery = useItems(memoryStoreName, scope, { depth: 0, view: "basic", limit: 100, enabled, }); const fileQuery = useItem( memoryStoreName, scope, editor.selectedPath ? { path: editor.selectedPath } : null, ); const addMutation = useAddItem(); const updateMutation = useUpdateItem(); const deleteMutation = useDeleteItem(); const pages = listQuery.data?.pages; const memories = useMemo(() => { const byPath = new Map(); for (const page of pages ?? []) { for (const file of page.items) { if (file.type !== "memoryfile") continue; byPath.set(normalizeFileMemoryPath(file.path), { ...file, path: normalizeFileMemoryPath(file.path), }); } } return Array.from(byPath.values()).sort((a, b) => a.path.localeCompare(b.path), ); }, [pages]); const visibleMemories = useMemo(() => { const query = filter.trim().toLocaleLowerCase(); return query ? memories.filter((file) => file.path.toLocaleLowerCase().includes(query)) : memories; }, [filter, memories]); const filesByPath = useMemo( () => new Map(memories.map((file) => [file.path, file])), [memories], ); const rows = useMemo( () => flattenVisible( buildFileTree( visibleMemories.map((file) => ({ rel: file.path.replace(/^\/+/, ""), size: file.contentSizeBytes, })), ), collapsed, ), [visibleMemories, collapsed], ); const readOnly = isFileMemoryReadOnly(pages); const selectedFile = editor.selectedPath ? (fileQuery.data ?? filesByPath.get(editor.selectedPath)) : undefined; const binarySelection = isFileMemoryBinary(selectedFile); useEffect(() => { const file = fileQuery.data; if ( !file || editor.dirty || !editor.selectedPath || editor.loadedItemId !== null ) { return; } dispatch({ type: "load", path: normalizeFileMemoryPath(file.path), content: file.content ?? "", itemId: file.itemId, versionId: file.latestVersionId, }); }, [ editor.dirty, editor.loadedItemId, editor.selectedPath, fileQuery.data, fileQuery.data?.content, fileQuery.data?.contentSha256, fileQuery.data?.itemId, fileQuery.data?.latestVersionId, fileQuery.data?.path, ]); function selectFile(path: string | null) { if ( !shouldApplyFileSelection(editor, path, () => window.confirm(t("memory.files.discardChanges")), ) ) { return; } dispatch({ type: "select", path }); } function toggleDirectory(path: string) { setCollapsed((previous) => { const next = new Set(previous); if (next.has(path)) next.delete(path); else next.add(path); return next; }); } async function save() { if (binarySelection) return; const validationError = validateFileMemoryContent(editor.content); if (validationError) { toast.error( t("memory.files.contentTooLarge", { limit: MAX_FILE_CONTENT_BYTES.toLocaleString("en-US"), }), ); return; } try { if (!editor.loadedItemId || !editor.loadedVersionId) { throw new Error("FILE_VERSION_NOT_LOADED"); } const updated = await updateMutation.mutateAsync({ memoryStoreName, scope, ...buildFileUpdateRequest( { itemId: editor.loadedItemId, latestVersionId: editor.loadedVersionId, }, editor.content, ), }); dispatch({ type: "save-success", itemId: updated.itemId, versionId: updated.latestVersionId, content: editor.content, }); toast.success(t("memory.files.saveSuccess")); } catch (error) { const message = error instanceof Error ? error.message : String(error); if (isFileMemoryVersionConflict(error)) { dispatch({ type: "save-conflict", message }); toast.error(t("memory.files.versionConflict")); return; } toast.error(message || t("memory.files.saveFailed")); } } async function create(path: string, content: string) { const created = await addMutation.mutateAsync({ memoryStoreName, scope, path, content, view: "full", }); dispatch({ type: "select", path: normalizeFileMemoryPath(created.path) }); toast.success(t("memory.files.createSuccess")); } async function upload(path: string, file: File) { const binary = await readFileMemoryBinary(file, path); const created = await addMutation.mutateAsync({ memoryStoreName, scope, path, ...binary, view: "full", }); dispatch({ type: "select", path: normalizeFileMemoryPath(created.path) }); toast.success(t("memory.files.uploadSuccess")); } async function replaceBinary(file: File) { if ( !editor.selectedPath || !editor.loadedItemId || !editor.loadedVersionId || !binarySelection ) { return; } try { const binary = await readFileMemoryBinary(file, editor.selectedPath); const updated = await updateMutation.mutateAsync({ memoryStoreName, scope, itemId: editor.loadedItemId, ...binary, precondition: { expectedVersionId: editor.loadedVersionId }, view: "full", }); dispatch({ type: "save-success", itemId: updated.itemId, versionId: updated.latestVersionId, content: "", }); toast.success(t("memory.files.replaceSuccess")); } catch (error) { const message = error instanceof Error ? error.message : String(error); if (isFileMemoryVersionConflict(error)) { dispatch({ type: "save-conflict", message }); toast.error(t("memory.files.versionConflict")); return; } const binaryErrorKey = fileMemoryBinaryErrorKey(error); toast.error( binaryErrorKey ? t(binaryErrorKey, { limit: MAX_FILE_CONTENT_BYTES.toLocaleString("en-US"), }) : message || t("memory.files.replaceFailed"), ); } } function downloadBinary() { if (!fileQuery.data || !downloadFileMemoryBinary(fileQuery.data)) { toast.error(t("memory.files.downloadUnavailable")); } } async function rename(toPath: string) { if ( !editor.selectedPath || !editor.loadedItemId || !editor.loadedVersionId ) { return; } const normalizedPath = normalizeFileMemoryPath(toPath); if ( binarySelection && fileMemoryBinaryMediaType(normalizedPath) !== selectedFile?.mediaType ) { throw new Error("BINARY_FORMAT_MISMATCH"); } const renamed = await updateMutation.mutateAsync({ memoryStoreName, scope, itemId: editor.loadedItemId, path: normalizedPath, precondition: { expectedVersionId: editor.loadedVersionId }, view: "full", }); // The requested path is authoritative for the local selection. Some // service versions return the pre-rename path in the update response. dispatch({ type: "rename-success", path: normalizedPath, itemId: renamed.itemId, versionId: renamed.latestVersionId, content: renamed.content, }); toast.success(t("memory.files.renameSuccess")); } async function remove() { if (!editor.loadedItemId || !editor.loadedVersionId) return; await deleteMutation.mutateAsync({ memoryStoreName, scope, itemId: editor.loadedItemId, precondition: { expectedVersionId: editor.loadedVersionId }, }); dispatch({ type: "select", path: null }); toast.success(t("memory.files.deleteSuccess")); } async function refresh() { await listQuery.refetch(); if (editor.selectedPath) await fileQuery.refetch(); } const mutationPending = isFileMutationPending(dialog, { create: addMutation.isPending, rename: updateMutation.isPending, delete: deleteMutation.isPending, }); return (
setDialog("create")} onUpload={() => setDialog("upload")} onRename={() => setDialog("rename")} onDelete={() => setDialog("delete")} onRefresh={() => void refresh()} onSave={() => void save()} /> {readOnly ? (
{t("memory.files.readOnlyGuidance")}
) : null}
dispatch({ type: "edit", content })} onDownload={downloadBinary} onReplace={(file) => void replaceBinary(file)} />
setDialog(null)} onCreate={create} onUpload={upload} onRename={rename} onDelete={remove} />
); } export const MemoryFilesIcon = FolderTree;