From 04fd86d97d6732342831e3cd6e91aa7d648b5381 Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Thu, 14 May 2026 20:20:27 +0800
Subject: [PATCH] 添加了清空缓存功能,释放用户上传的文件

---
 aigc-director/aigc-claw/frontend/components/AppShell.tsx |   59 +++++++++++++++++++++++++----
 aigc-director/aigc-claw/frontend/next.config.ts          |    4 ++
 aigc-director/aigc-claw/backend/api/routers/files.py     |   47 +++++++++++++++++++++++
 aigc-director/aigc-claw/frontend/lib/workflowApi.ts      |    9 ++++
 4 files changed, 111 insertions(+), 8 deletions(-)

diff --git a/aigc-director/aigc-claw/backend/api/routers/files.py b/aigc-director/aigc-claw/backend/api/routers/files.py
index 5cf28b9..28cb625 100644
--- a/aigc-director/aigc-claw/backend/api/routers/files.py
+++ b/aigc-director/aigc-claw/backend/api/routers/files.py
@@ -13,6 +13,27 @@
 router = APIRouter(tags=["Files"])
 
 
+def _path_size(path: str) -> int:
+    if os.path.isfile(path) or os.path.islink(path):
+        return os.path.getsize(path)
+    total = 0
+    for root, dirs, files in os.walk(path):
+        for name in files:
+            item = os.path.join(root, name)
+            try:
+                total += os.path.getsize(item)
+            except OSError:
+                continue
+        for name in dirs:
+            item = os.path.join(root, name)
+            if os.path.islink(item):
+                try:
+                    total += os.path.getsize(item)
+                except OSError:
+                    continue
+    return total
+
+
 @router.post("/api/upload_file")
 async def upload_file(file: UploadFile = File(...)):
     allowed_exts = [".docx", ".doc", ".txt", ".md", ".pdf"]
@@ -61,6 +82,32 @@
     }
 
 
+@router.delete("/api/cache/temp")
+async def clear_temp_cache():
+    os.makedirs(settings.TEMP_DIR, exist_ok=True)
+    deleted = 0
+    freed_bytes = 0
+    errors = []
+    for entry in os.scandir(settings.TEMP_DIR):
+        try:
+            freed_bytes += _path_size(entry.path)
+            if entry.is_dir(follow_symlinks=False):
+                shutil.rmtree(entry.path)
+            else:
+                os.remove(entry.path)
+            deleted += 1
+        except Exception as exc:
+            logger.warning("Failed to delete temp cache item: %s", entry.path, exc_info=True)
+            errors.append({"path": entry.name, "error": str(exc)})
+    return {
+        "status": "ok",
+        "deleted": deleted,
+        "freed_bytes": freed_bytes,
+        "freed_mb": round(freed_bytes / 1024 / 1024, 2),
+        "errors": errors,
+    }
+
+
 def merge_uploaded_file_into_idea(idea: str, file_path: Optional[str]) -> str:
     if not file_path:
         return idea
diff --git a/aigc-director/aigc-claw/frontend/components/AppShell.tsx b/aigc-director/aigc-claw/frontend/components/AppShell.tsx
index 658dfad..c578100 100644
--- a/aigc-director/aigc-claw/frontend/components/AppShell.tsx
+++ b/aigc-director/aigc-claw/frontend/components/AppShell.tsx
@@ -2,10 +2,10 @@
 
 import Link from 'next/link';
 import { usePathname, useRouter } from 'next/navigation';
-import { ChevronLeft, ChevronRight, Clapperboard, Clock, Hexagon, Home, Loader2, PanelLeftOpen, Repeat2, Settings, UserRound } from 'lucide-react';
+import { ChevronLeft, ChevronRight, Clapperboard, Clock, Hexagon, Home, Loader2, PanelLeftOpen, Repeat2, Settings, Trash2, UserRound } from 'lucide-react';
 import clsx from 'clsx';
 import { useEffect, useState } from 'react';
-import { fetchPipelineTasks, fetchSandboxTasks, fetchSessions, type PipelineTask, type SandboxTask } from '@/lib/workflowApi';
+import { clearTempCache, fetchPipelineTasks, fetchSandboxTasks, fetchSessions, type PipelineTask, type SandboxTask } from '@/lib/workflowApi';
 
 const NAV_ITEMS = [
   { href: '/', label: 'AIGC-Claw', icon: Home },
@@ -184,7 +184,23 @@
 
 export default function AppShell({ children }: { children: React.ReactNode }) {
   const pathname = usePathname();
+  const router = useRouter();
   const [open, setOpen] = useState(false);
+  const [settingsMenuOpen, setSettingsMenuOpen] = useState(false);
+  const [clearingCache, setClearingCache] = useState(false);
+
+  const handleClearCache = async () => {
+    setClearingCache(true);
+    try {
+      const result = await clearTempCache();
+      window.alert(`缓存已清空,删除 ${result.deleted} 项,释放 ${Number(result.freed_mb || 0).toFixed(2)} MB。`);
+      setSettingsMenuOpen(false);
+    } catch (error: any) {
+      window.alert(error?.message || '清空缓存失败');
+    } finally {
+      setClearingCache(false);
+    }
+  };
 
   return (
     <div className="min-h-screen bg-gray-50 text-gray-800">
@@ -223,23 +239,50 @@
             })}
           </nav>
           <RunningTaskList currentPath={pathname} />
-          <div className="border-t border-gray-100 p-3">
+          <div className="relative border-t border-gray-100 p-3">
             {(() => {
               const Icon = SETTINGS_ITEM.icon;
               const active = pathname.startsWith(SETTINGS_ITEM.href);
               return (
-                <Link
-                  href={SETTINGS_ITEM.href}
+                <>
+                  {settingsMenuOpen && (
+                    <div className="absolute bottom-[62px] left-3 right-3 rounded-xl border border-gray-200 bg-white p-2 shadow-lg">
+                      <button
+                        type="button"
+                        onClick={() => {
+                          setSettingsMenuOpen(false);
+                          router.push(SETTINGS_ITEM.href);
+                        }}
+                        className="flex h-10 w-full items-center gap-2 rounded-lg px-3 text-left text-sm font-medium text-gray-600 hover:bg-blue-50 hover:text-blue-600"
+                      >
+                        <Settings className="h-4 w-4" />
+                        修改配置
+                      </button>
+                      <button
+                        type="button"
+                        onClick={() => handleClearCache()}
+                        disabled={clearingCache}
+                        className="mt-1 flex h-10 w-full items-center gap-2 rounded-lg px-3 text-left text-sm font-medium text-gray-600 hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-60"
+                      >
+                        {clearingCache ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
+                        清空缓存
+                      </button>
+                    </div>
+                  )}
+                  <button
+                    type="button"
+                    onClick={() => setSettingsMenuOpen(value => !value)}
                   className={clsx(
-                    'flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors',
-                    active
+                    'flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors',
+                    active || settingsMenuOpen
                       ? 'bg-blue-50 text-blue-600'
                       : 'text-gray-500 hover:bg-gray-50 hover:text-gray-800'
                   )}
                 >
                   <Icon className="w-4 h-4 flex-shrink-0" />
                   <span className="truncate">{SETTINGS_ITEM.label}</span>
-                </Link>
+                  </button>
+                </>
               );
             })()}
           </div>
diff --git a/aigc-director/aigc-claw/frontend/lib/workflowApi.ts b/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
index 7811b17..8fead4c 100644
--- a/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
+++ b/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
@@ -167,6 +167,15 @@
   return data.tasks || [];
 }
 
+export async function clearTempCache(): Promise<{ status: string; deleted: number; freed_bytes?: number; freed_mb?: number; errors?: Array<{ path: string; error: string }> }> {
+  const resp = await fetch('/api/cache/temp', { method: 'DELETE' });
+  if (!resp.ok) {
+    const err = await resp.json().catch(() => ({ detail: '清空缓存失败' }));
+    throw new Error(err.detail || '清空缓存失败');
+  }
+  return resp.json();
+}
+
 export async function deletePipelineTask(taskId: string): Promise<void> {
   const resp = await fetch(`/api/tasks/${taskId}`, { method: 'DELETE' });
   if (!resp.ok) throw new Error('删除任务失败');
diff --git a/aigc-director/aigc-claw/frontend/next.config.ts b/aigc-director/aigc-claw/frontend/next.config.ts
index 7202a90..bfee8a8 100644
--- a/aigc-director/aigc-claw/frontend/next.config.ts
+++ b/aigc-director/aigc-claw/frontend/next.config.ts
@@ -36,6 +36,10 @@
         source: '/api/config',
         destination: 'http://127.0.0.1:8000/api/config',
       },
+      {
+        source: '/api/cache/:path*',
+        destination: 'http://127.0.0.1:8000/api/cache/:path*',
+      },
       // 一键 pipeline API
       {
         source: '/api/pipelines',

--
Gitblit v1.8.0