Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat:用户空间配额管理2

wangxindadae18c744e
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index 807c6e2dfd..1f599cb018 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -8,7 +8,8 @@ import { useState, useCallback, useEffect, useRef, Component, ReactNode, useMemo
import { ChatPanel } from './components/ChatPanel';
import { SessionSidebar } from './components/SessionSidebar';
import { SkillPanel } from './components/SkillPanel';
-import { AgentPanel } from './components/AgentPanel/index';
+import { WorkspacePanel } from './components/WorkspacePanel/index';
+import { ApprovalsPanel } from './components/ApprovalsPanel';
import { TeamPanel } from './components/TeamPanel';
import { SessionsPanel } from './components/SessionsPanel';
import CronPanel from './components/CronPanel';
@@ -73,7 +74,7 @@ import {
type MainNavKey,
} from './features/mainNavigationState';
import { ConversationSidebar, type NewConversationOptions } from './multi-session/sidebar/ConversationSidebar';
-import { DeleteDialog } from './multi-session/dialogs/Dialogs';
+import { DeleteDialog, NoticeDialog } from './multi-session/dialogs/Dialogs';
import {
NEW_CONVERSATION_ID,
createConversationTitle,
@@ -83,7 +84,7 @@ import {
resetNewConversationRuntime,
} from './multi-session/state/newConversationLifecycle';
import { toDisplaySessionTitle } from './utils/documentMessage';
-import { createConversationSession } from './multi-session/state/createConversationSession';
+import { createConversationSession, isWorkspaceQuotaError } from './multi-session/state/createConversationSession';
import { useTranslation } from 'react-i18next';
import {
normalizeA2UIEnabled,
@@ -341,7 +342,10 @@ function AppContent() {
const enterpriseMode = isEnterprise();
const cronJobPullSyncEnabled = enterpriseMode && getWebTransport() === 'http';
useCronJobSync(cronJobPullSyncEnabled);
- const enterpriseBlockedNav = new Set<MainNavKey>(ENTERPRISE_HIDDEN_NAV_ITEMS);
+ const enterpriseBlockedNav = useMemo(
+ () => new Set<MainNavKey>(enterpriseMode ? ENTERPRISE_HIDDEN_NAV_ITEMS : (['approvals'] as const)),
+ [enterpriseMode],
+ );
const [activeNav, setActiveNav] = useState<MainNavKey>(() => {
let stored: string | null = null;
try {
@@ -350,7 +354,7 @@ function AppContent() {
// Storage may be unavailable in private/locked-down browser contexts.
}
return parseStoredMainNav(stored, {
- blocked: enterpriseMode ? ENTERPRISE_HIDDEN_NAV_ITEMS : [],
+ blocked: enterpriseMode ? ENTERPRISE_HIDDEN_NAV_ITEMS : ['approvals'],
updaterEnabled: FEATURE_APP_UPDATER_UI,
});
});
@@ -380,6 +384,7 @@ function AppContent() {
const [deleteTarget, setDeleteTarget] = useState<Session | null>(null);
const [dialogBusy, setDialogBusy] = useState(false);
const [dialogError, setDialogError] = useState<string | null>(null);
+ const [createErrorNotice, setCreateErrorNotice] = useState<{ title: string; message?: string } | null>(null);
const [composerFocusNonce, setComposerFocusNonce] = useState(0);
const [missingSessionId, setMissingSessionId] = useState<string | null>(null);
const startupUpdateCheckRef = useRef(false);
@@ -430,7 +435,7 @@ function AppContent() {
useEffect(() => {
const handler = (e: Event) => {
const nav = (e as CustomEvent<MainNavKey>).detail;
- if (!nav || (enterpriseMode && enterpriseBlockedNav.has(nav))) return;
+ if (!nav || enterpriseBlockedNav.has(nav)) return;
setActiveNav(nav);
if (nav === 'skills') setHasVisitedSkills(true);
if (nav === 'channels') setHasVisitedChannels(true);
@@ -1905,7 +1910,13 @@ function AppContent() {
useChatStore.getState().setThinking(NEW_CONVERSATION_ID, false);
useChatStore.getState().setInputValue(NEW_CONVERSATION_ID, content);
console.error('Failed to create conversation:', error);
- window.alert(t('multiSession.errors.create'));
+ const quotaHit = isWorkspaceQuotaError(error);
+ setCreateErrorNotice(quotaHit
+ ? {
+ title: t('multiSession.errors.quotaExceededTitle'),
+ message: t('multiSession.errors.quotaExceeded'),
+ }
+ : { title: t('multiSession.errors.create') });
} finally {
creatingSessionRef.current = false;
}
@@ -2365,7 +2376,7 @@ function AppContent() {
}, [deleteTarget, enterNewConversation, request, t]);
const handleNavigate = useCallback((nav: MainNavKey) => {
- if (enterpriseMode && enterpriseBlockedNav.has(nav)) return;
+ if (enterpriseBlockedNav.has(nav)) return;
setActiveNav(nav);
if (modelSetupGuideStep === 1 && nav === 'configpanel') {
setModelSetupGuideStep(2);
@@ -2373,7 +2384,7 @@ function AppContent() {
if (nav === 'skills') setHasVisitedSkills(true);
if (nav === 'channels') setHasVisitedChannels(true);
if (nav === 'personalContext') setHasVisitedPersonalContext(true);
- }, [enterpriseMode, modelSetupGuideStep]);
+ }, [enterpriseBlockedNav, modelSetupGuideStep]);
const skipModelSetupGuide = useCallback(() => {
setModelSetupGuideStep(null);
@@ -2498,7 +2509,7 @@ function AppContent() {
isConnected={isConnected}
onNewSession={handleNewSession}
showNewSession={false}
- hiddenNavItems={enterpriseMode ? ['sessions', 'history', ...ENTERPRISE_HIDDEN_NAV_ITEMS] : ['sessions', 'history']}
+ hiddenNavItems={enterpriseMode ? ['sessions', 'history', ...ENTERPRISE_HIDDEN_NAV_ITEMS] : ['sessions', 'history', 'approvals']}
onMorePanelOpenChange={setSidebarMorePanelOpen}
/>
@@ -2632,7 +2643,12 @@ function AppContent() {
)}
{activeNav === 'agents' && (
<div className="app-section">
- <AgentPanel sessionId={sessionId} />
+ <WorkspacePanel sessionId={sessionId} />
+ </div>
+ )}
+ {activeNav === 'approvals' && (
+ <div className="app-section">
+ <ApprovalsPanel />
</div>
)}
{activeNav === 'teams' && (
@@ -2770,6 +2786,14 @@ function AppContent() {
/>
)}
+ {createErrorNotice && (
+ <NoticeDialog
+ title={createErrorNotice.title}
+ message={createErrorNotice.message}
+ onClose={() => setCreateErrorNotice(null)}
+ />
+ )}
+
{/* 连接状态提示 */}
{!isConnected && (
<div className="app-toast-wrapper app-toast-wrapper--top">
diff --git a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
index 216da1a148..b7b5508372 100644
--- a/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/EnterpriseEntry.tsx
@@ -189,7 +189,19 @@ function errorText(error: unknown): string {
return error instanceof Error && error.message ? error.message : '加载企业用户上下文失败';
}
-function EntryStatus({ phase, error, onLogout }: { phase: EntryPhase; error: string; onLogout: () => void }) {
+function EntryStatus({
+ phase,
+ error,
+ managerAccess,
+ onSwitchToManager,
+ onLogout,
+}: {
+ phase: EntryPhase;
+ error: string;
+ managerAccess: boolean;
+ onSwitchToManager: () => void;
+ onLogout: () => void;
+}) {
const empty = phase === 'empty';
const failed = phase === 'error';
const loginRequired = phase === 'login-required';
@@ -222,9 +234,16 @@ function EntryStatus({ phase, error, onLogout }: { phase: EntryPhase; error: str
: '正在校验账号权限并选择一个可用 Agent。'}
</p>
{(empty || failed) && (
- <button type="button" className="enterprise-entry__button" onClick={onLogout}>
- 返回登录页
- </button>
+ <div className="enterprise-entry__actions">
+ {managerAccess && (
+ <button type="button" className="enterprise-entry__button" onClick={onSwitchToManager}>
+ 进入管理面
+ </button>
+ )}
+ <button type="button" className="enterprise-entry__button" onClick={onLogout}>
+ 返回登录页
+ </button>
+ </div>
)}
</div>
</div>
@@ -244,11 +263,16 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
const [error, setError] = useState('');
const [contextError, setContextError] = useState('');
const [contextSwitching, setContextSwitching] = useState(false);
+ const [managerAccess, setManagerAccess] = useState(false);
const logout = useCallback(() => {
if (provider) void provider.logout();
}, [provider]);
+ const switchToManager = useCallback(() => {
+ window.location.href = '/manager';
+ }, []);
+
useEffect(() => {
if (!enterprise || !provider) return;
console.info(provider.startupMessage);
@@ -263,7 +287,17 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
const preferred = parseRuntimeScope(window.location.search);
const preferredClusterId =
parsePreferredClusterId(window.location.search) || readKnownCluster();
- const [user, contexts] = await Promise.all([provider.getCurrentUser(), provider.listAgentContexts()]);
+ const user = await provider.getCurrentUser();
+ if (cancelled) return;
+ let canManage = false;
+ try {
+ canManage = provider.getManagerAccess ? await provider.getManagerAccess() : false;
+ } catch {
+ canManage = false;
+ }
+ if (cancelled) return;
+ setManagerAccess(canManage);
+ const contexts = await provider.listAgentContexts();
if (cancelled) return;
let selected: EnterpriseAgentContext | null = null;
@@ -347,6 +381,7 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
if (!context) return null;
return {
...context,
+ managerAccess,
contextError,
contextSwitching,
onContextChange: key => {
@@ -407,11 +442,22 @@ export function EnterpriseEntry({ children }: { children: ReactNode }) {
}
})();
},
+ onSwitchToManager: switchToManager,
onLogout: logout,
};
- }, [context, contextError, contextSwitching, logout, provider, t]);
+ }, [context, contextError, contextSwitching, logout, managerAccess, provider, switchToManager, t]);
if (!enterprise) return <>{children}</>;
- if (phase !== 'ready' || !contextValue) return <EntryStatus phase={phase} error={error} onLogout={logout} />;
+ if (phase !== 'ready' || !contextValue) {
+ return (
+ <EntryStatus
+ phase={phase}
+ error={error}
+ managerAccess={managerAccess}
+ onSwitchToManager={switchToManager}
+ onLogout={logout}
+ />
+ );
+ }
return <EnterpriseContext.Provider value={contextValue}>{children}</EnterpriseContext.Provider>;
}
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
index cc76138ab0..cd6ff998e6 100644
--- a/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
+++ b/jiuwenswarm/channels/web/frontend/src/auth/manager/ManagerAuthProvider.ts
@@ -57,6 +57,17 @@ export const managerAuthProvider: EnterpriseAuthProvider = {
if (result.code !== 200) throw new EnterpriseAuthError(result.code, result.message || '加载 Agent 上下文失败');
return result.data?.contexts ?? [];
},
+ async getManagerAccess() {
+ try {
+ const result = await requestJson<
+ ManagerResponse<{ manager_access?: boolean; is_platform_admin?: boolean }>
+ >('/manager-api/v1/authz/me');
+ if (result.code !== 200) return false;
+ return Boolean(result.data?.manager_access || result.data?.is_platform_admin);
+ } catch {
+ return false;
+ }
+ },
async setActiveCluster(jiuwenclawId: string) {
const result = await requestJson<ManagerResponse<{ jiuwenclaw_id: string }>>(
resolveApiUrl('/manager-api/v1/user-console/active-cluster'),
diff --git a/jiuwenswarm/channels/web/frontend/src/auth/types.ts b/jiuwenswarm/channels/web/frontend/src/auth/types.ts
index 4765abeaba..e77ed985ec 100644
--- a/jiuwenswarm/channels/web/frontend/src/auth/types.ts
+++ b/jiuwenswarm/channels/web/frontend/src/auth/types.ts
@@ -8,6 +8,8 @@ export interface EnterpriseAuthProvider {
redirectToLogin(): boolean;
getCurrentUser(): Promise<EnterpriseUser>;
listAgentContexts(): Promise<EnterpriseAgentContext[]>;
+ /** 是否可进入管理面(有管理面角色/权限);普通用户为 false。模拟登录可省略。 */
+ getManagerAccess?(): Promise<boolean>;
/** 写入 Manager 用户面反代 Cookie ``jiuwenclaw_id``;模拟登录可省略。 */
setActiveCluster?(jiuwenclawId: string): Promise<void>;
logout(): Promise<void>;
diff --git a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx
deleted file mode 100644
index 670c756b6f..0000000000
--- a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx
+++ /dev/null
@@ -1,519 +0,0 @@
-import { useEffect, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { FileViewer } from './FileViewer';
-import { containsIgnoredDirectory } from '../../features/fileTreeFilters';
-import { isHistoryPreviewFile } from '../../features/historyFilePreview';
-
-interface AgentPanelProps {
- sessionId: string;
-}
-
-interface FileInfo {
- name: string;
- path: string;
- isMarkdown: boolean;
-}
-
-const ROOT_FOLDER_KEY = '__root__';
-const AGENT_ROOT_PREFIX = 'agent/';
-
-interface DirectoryNode {
- key: string;
- label: string;
- isSkillFolder: boolean;
- childDirectoryKeys: string[];
- files: FileInfo[];
-}
-
-interface TreeData {
- directoryMap: Map<string, DirectoryNode>;
- rootChildDirectoryKeys: string[];
- rootFiles: FileInfo[];
- rootEntries: Array<
- | { kind: 'directory'; key: string; label: string }
- | { kind: 'file'; file: FileInfo }
- >;
- directoryCount: number;
- totalFileCount: number;
- previewableFileCount: number;
-}
-
-const compareByName = (a: string, b: string) => a.localeCompare(b, 'zh-Hans-CN');
-
-const getFolderDisplayName = (folderKey: string, t: (key: string) => string) => {
- if (folderKey === ROOT_FOLDER_KEY) return t('agent.root');
- const segments = folderKey.split('/').filter(Boolean);
- return segments[segments.length - 1] || folderKey;
-};
-
-const isSkillFolder = (folderKey: string) =>
- folderKey === 'skills' ||
- folderKey.startsWith('skills/') ||
- folderKey === 'workspace/skills' ||
- folderKey.startsWith('workspace/skills/');
-
-const normalizeFolderKey = (folderKey: string) => (folderKey ? folderKey : ROOT_FOLDER_KEY);
-
-const isPreviewableFile = (fileName: string) => {
- const lowerName = fileName.toLowerCase();
- return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json') || isHistoryPreviewFile(fileName);
-};
-
-const getParentFolderKey = (folderKey: string) => {
- if (folderKey === ROOT_FOLDER_KEY) return null;
- const separatorIndex = folderKey.lastIndexOf('/');
- if (separatorIndex === -1) return ROOT_FOLDER_KEY;
- return folderKey.substring(0, separatorIndex);
-};
-
-const getFolderKeyByFilePath = (filePath: string) => {
- if (!filePath.startsWith(AGENT_ROOT_PREFIX)) {
- return ROOT_FOLDER_KEY;
- }
- const relativePath = filePath.slice(AGENT_ROOT_PREFIX.length);
- const separatorIndex = relativePath.lastIndexOf('/');
- if (separatorIndex === -1) {
- return ROOT_FOLDER_KEY;
- }
- return relativePath.substring(0, separatorIndex) || ROOT_FOLDER_KEY;
-};
-
-const filterFolderData = (data: Record<string, FileInfo[]>) =>
- Object.fromEntries(
- Object.entries(data)
- .filter(([rawFolderKey]) => !containsIgnoredDirectory(rawFolderKey))
- .map(([rawFolderKey, files]) => [
- rawFolderKey,
- files.filter((file) => !containsIgnoredDirectory(file.path)),
- ]),
- );
-
-const buildTreeData = (data: Record<string, FileInfo[]>, t: (key: string) => string): TreeData => {
- const directoryKeys = new Set<string>([ROOT_FOLDER_KEY]);
- const sourceFolderKeys = Object.keys(data);
-
- sourceFolderKeys.forEach((rawFolderKey) => {
- const folderKey = normalizeFolderKey(rawFolderKey);
- if (folderKey === ROOT_FOLDER_KEY) {
- directoryKeys.add(ROOT_FOLDER_KEY);
- return;
- }
-
- const parts = folderKey.split('/').filter(Boolean);
- let current = '';
- parts.forEach((part) => {
- current = current ? `${current}/${part}` : part;
- directoryKeys.add(current);
- });
- });
-
- const directoryMap = new Map<string, DirectoryNode>();
- directoryKeys.forEach((folderKey) => {
- directoryMap.set(folderKey, {
- key: folderKey,
- label: getFolderDisplayName(folderKey, t),
- isSkillFolder: isSkillFolder(folderKey),
- childDirectoryKeys: [],
- files: [],
- });
- });
-
- directoryKeys.forEach((folderKey) => {
- if (folderKey === ROOT_FOLDER_KEY) return;
- const parentKey = getParentFolderKey(folderKey);
- if (!parentKey) return;
- const parent = directoryMap.get(parentKey);
- if (parent) {
- parent.childDirectoryKeys.push(folderKey);
- }
- });
-
- sourceFolderKeys.forEach((rawFolderKey) => {
- const folderKey = normalizeFolderKey(rawFolderKey);
- const node = directoryMap.get(folderKey);
- if (!node) return;
- node.files = (data[rawFolderKey] || [])
- .slice()
- .sort((a, b) => compareByName(a.name, b.name));
- });
-
- directoryMap.forEach((node) => {
- node.childDirectoryKeys.sort((a, b) => compareByName(getFolderDisplayName(a, t), getFolderDisplayName(b, t)));
- });
-
- const rootNode = directoryMap.get(ROOT_FOLDER_KEY);
- const rootChildDirectoryKeys = rootNode ? rootNode.childDirectoryKeys : [];
- const rootFiles = rootNode ? rootNode.files : [];
- const rootEntries = [
- ...rootChildDirectoryKeys.map((key) => ({
- kind: 'directory' as const,
- key,
- label: getFolderDisplayName(key, t),
- })),
- ...rootFiles.map((file) => ({
- kind: 'file' as const,
- file,
- })),
- ].sort((a, b) => {
- const aName = a.kind === 'directory' ? a.label : a.file.name;
- const bName = b.kind === 'directory' ? b.label : b.file.name;
- return compareByName(aName, bName);
- });
- const allFiles = sourceFolderKeys.flatMap((folderKey) => data[folderKey] || []);
-
- return {
- directoryMap,
- rootChildDirectoryKeys,
- rootFiles,
- rootEntries,
- directoryCount: Math.max(directoryMap.size - 1, 0),
- totalFileCount: allFiles.length,
- previewableFileCount: allFiles.filter((file) => isPreviewableFile(file.name)).length,
- };
-};
-
-export function AgentPanel({ sessionId: _sessionId }: AgentPanelProps) {
- const { t } = useTranslation();
- const [folderData, setFolderData] = useState<Record<string, FileInfo[]>>({});
- const [loading, setLoading] = useState(true);
- const [refreshing, setRefreshing] = useState(false);
- const [loadError, setLoadError] = useState<string | null>(null);
- const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null);
- const [expandedKeys, setExpandedKeys] = useState<Set<string>>(
- () => new Set<string>([ROOT_FOLDER_KEY]),
- );
- const [hasRebuiltOnce, setHasRebuiltOnce] = useState(false);
-
- const loadFolderData = async (options?: { rebuildBeforeFetch?: boolean }) => {
- const shouldRebuild = Boolean(options?.rebuildBeforeFetch);
- try {
- if (shouldRebuild) {
- const rebuildResponse = await fetch('/file-api/rebuild-agent-data', {
- method: 'POST',
- });
- if (!rebuildResponse.ok) {
- const rebuildError = await rebuildResponse.text();
- throw new Error(`REBUILD_FAILED:${rebuildError.substring(0, 160)}`);
- }
- }
-
- const res = await fetch('/file-api/file-content?path=agent/jiuwenclaw_workspace/agent-data.json');
- if (!res.ok) {
- throw new Error('FETCH_FAILED');
- }
- const rawData = await res.text();
- const parsedData = JSON.parse(rawData) as Record<string, FileInfo[]>;
- const data = filterFolderData(parsedData);
- setFolderData(data);
- setLoadError(null);
-
- const nextTreeData = buildTreeData(data, t);
- setSelectedFile((prev) => {
- if (!prev) {
- return null;
- }
- const stillExists = Object.values(data).some((files) =>
- files.some((file) => file.path === prev.path),
- );
- return stillExists ? prev : null;
- });
- setExpandedKeys((prev) => {
- const next = new Set<string>([ROOT_FOLDER_KEY]);
- prev.forEach((key) => {
- if (nextTreeData.directoryMap.has(key)) {
- next.add(key);
- }
- });
- return next;
- });
- } catch (err) {
- console.error('Failed to load agent files:', err);
- setFolderData({});
- if (err instanceof Error && err.message.startsWith('REBUILD_FAILED:')) {
- setLoadError(t('agent.errors.refreshFailed'));
- } else {
- setLoadError(t('agent.errors.loadFailed'));
- }
- } finally {
- setLoading(false);
- setRefreshing(false);
- }
- };
-
- useEffect(() => {
- // 首次进入时自动 rebuild,确保 agent-data.json 与实际安装的技能同步
- // 后续进入直接读取,避免每次都触发重建
- if (!hasRebuiltOnce) {
- setHasRebuiltOnce(true);
- void loadFolderData({ rebuildBeforeFetch: true });
- } else {
- void loadFolderData();
- }
- }, [hasRebuiltOnce]);
-
- const handleRefresh = () => {
- setRefreshing(true);
- void loadFolderData({ rebuildBeforeFetch: true });
- };
-
- const treeData = useMemo(() => buildTreeData(folderData, t), [folderData, t]);
-
- const expandFolderAndAncestors = (folderKey: string) => {
- setExpandedKeys((prev) => {
- const next = new Set(prev);
- let current: string | null = folderKey;
- while (current) {
- next.add(current);
- current = getParentFolderKey(current);
- }
- return next;
- });
- };
-
- const toggleFolder = (folderKey: string) => {
- setExpandedKeys((prev) => {
- const next = new Set(prev);
- if (next.has(folderKey)) {
- next.delete(folderKey);
- } else {
- next.add(folderKey);
- }
- return next;
- });
- };
-
- const handleFileClick = (file: FileInfo) => {
- if (!isPreviewableFile(file.name)) {
- return;
- }
- const folderKey = getFolderKeyByFilePath(file.path);
- expandFolderAndAncestors(folderKey);
- setSelectedFile(file);
- };
-
- if (loading) {
- return (
- <div className="flex-1 min-h-0">
- <div className="card w-full h-full flex items-center justify-center">
- <div className="w-8 h-8 rounded-full border-4 border-border border-t-accent animate-spin" />
- </div>
- </div>
- );
- }
-
- const renderTree = (folderKey: string, depth: number): JSX.Element | null => {
- const node = treeData.directoryMap.get(folderKey);
- if (!node) {
- return null;
- }
- const isExpanded = expandedKeys.has(folderKey);
- const hasChildren = node.childDirectoryKeys.length > 0 || node.files.length > 0;
-
- return (
- <div key={`dir-${folderKey}`}>
- <button
- type="button"
- onClick={() => toggleFolder(folderKey)}
- className="w-full min-h-10 flex items-center gap-2 rounded-lg px-2 py-2 text-left text-[15px] text-text-muted hover:bg-secondary/40 hover:text-text "
- style={{ paddingLeft: `${depth * 14 + 8}px` }}
- title={node.label}
- >
- <span className="w-4 h-4 flex items-center justify-center text-text-muted/80">
- {hasChildren ? (
- <svg
- className={`w-3 h-3 ${isExpanded ? 'rotate-90' : ''}`}
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- >
- <path strokeLinecap="round" strokeLinejoin="round" d="M9 6l6 6-6 6" />
- </svg>
- ) : null}
- </span>
- <svg className="w-4 h-4 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
- <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h4.5l1.5 2.25h10.5v8.25A2.25 2.25 0 0118 19.5H6A2.25 2.25 0 013.75 17.25V6.75z" />
- </svg>
- <span className="flex-1 min-w-0 truncate">{node.label}</span>
- {node.isSkillFolder ? (
- <span className="text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border border-[var(--color-border-accent)] bg-accent-subtle text-accent">
- skills
- </span>
- ) : null}
- </button>
-
- {isExpanded ? (
- <div>
- {node.childDirectoryKeys.map((childKey) => renderTree(childKey, depth + 1))}
- {node.files.map((file) => {
- const selectable = isPreviewableFile(file.name);
- const selected = selectedFile?.path === file.path;
- return (
- <button
- key={file.path}
- type="button"
- className={`w-full min-h-10 flex items-center gap-2 rounded-lg px-2 py-2 text-left text-[15px] ${
- selected
- ? 'bg-accent-subtle text-text border border-[var(--color-border-accent)]'
- : selectable
- ? 'text-text-muted hover:bg-secondary/40 hover:text-text border border-transparent'
- : 'text-text-muted/60 border border-transparent cursor-not-allowed'
- }`}
- style={{ paddingLeft: `${(depth + 1) * 14 + 8}px` }}
- onClick={() => handleFileClick(file)}
- disabled={!selectable}
- title={file.name}
- >
- <span className="w-4 h-4 flex items-center justify-center" />
- <svg className="w-4 h-4 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
- {file.isMarkdown ? (
- <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 3.75h7.5l4.5 4.5v12a1.5 1.5 0 01-1.5 1.5h-10.5a1.5 1.5 0 01-1.5-1.5v-15a1.5 1.5 0 011.5-1.5zM9 14.25V9.75l3 3 3-3v4.5" />
- ) : (
- <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 3.75h7.5l4.5 4.5v12a1.5 1.5 0 01-1.5 1.5h-10.5a1.5 1.5 0 01-1.5-1.5v-15a1.5 1.5 0 011.5-1.5zM14.25 3.75v4.5h4.5" />
- )}
- </svg>
- <span className="flex-1 min-w-0 truncate">{file.name}</span>
- {!selectable ? (
- <span className="text-[10px] px-1.5 py-0.5 rounded border border-border bg-secondary/40">
- {t('agent.notPreviewable')}
- </span>
- ) : null}
- </button>
- );
- })}
- </div>
- ) : null}
- </div>
- );
- };
-
- return (
- <div className="flex-1 min-h-0">
- <div className="card w-full h-full flex flex-col">
- <div className="flex items-center justify-between mb-3">
- <div>
- <h2 className="text-lg font-semibold">{t('agent.title')}</h2>
- <p className="text-sm text-text-muted mt-1">{t('agent.subtitle')}</p>
- </div>
- <div className="flex items-center gap-2">
- <div className="flex items-center gap-2 text-xs text-text-muted">
- <span className="mono px-2.5 py-1 rounded-full border border-border bg-secondary/60">
- {t('agent.directoryCount', { count: treeData.directoryCount })}
- </span>
- <span className="mono px-2.5 py-1 rounded-full border border-border bg-secondary/60">
- {t('agent.fileCount', { count: treeData.totalFileCount })}
- </span>
- <span className="mono px-2.5 py-1 rounded-full border border-border bg-secondary/60">
- {t('agent.previewableCount', { count: treeData.previewableFileCount })}
- </span>
- </div>
- </div>
- </div>
-
- {loadError ? (
- <div className="mb-4 rounded-md border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">
- {loadError}
- </div>
- ) : null}
-
- <div className="flex-1 min-h-0 grid grid-cols-[minmax(0,3fr)_minmax(0,7fr)] gap-4">
- <div className="rounded-xl border border-border bg-card/70 backdrop-blur-sm overflow-hidden shadow-sm flex flex-col min-h-0">
- <div className="px-4 py-3 bg-secondary/30 border-b border-border">
- <div className="flex items-start justify-between gap-4">
- <div>
- <h3 className="text-sm font-medium text-text">{t('agent.workspace')}</h3>
- <p className="text-xs text-text-muted mt-1 mono">
- {t('agent.workspaceMeta', { directories: treeData.directoryCount, files: treeData.totalFileCount })}
- </p>
- </div>
- <button
- type="button"
- onClick={handleRefresh}
- disabled={refreshing}
- className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
- title={t('agent.refresh')}
- >
- {refreshing ? t('common.refreshing') : t('common.refresh')}
- </button>
- </div>
- </div>
- <div className="flex-1 overflow-auto p-2">
- {treeData.rootChildDirectoryKeys.length === 0 && treeData.rootFiles.length === 0 ? (
- <div className="h-full flex items-center justify-center text-sm text-text-muted">{t('agent.empty')}</div>
- ) : (
- <div className="space-y-0.5">
- {treeData.rootEntries.map((entry) => {
- if (entry.kind === 'directory') {
- return renderTree(entry.key, 0);
- }
- const file = entry.file;
- const selectable = isPreviewableFile(file.name);
- const selected = selectedFile?.path === file.path;
- return (
- <button
- key={file.path}
- type="button"
- className={`w-full min-h-10 flex items-center gap-2 rounded-lg px-2 py-2 text-left text-[15px] ${
- selected
- ? 'bg-accent-subtle text-text border border-[var(--color-border-accent)]'
- : selectable
- ? 'text-text-muted hover:bg-secondary/40 hover:text-text border border-transparent'
- : 'text-text-muted/60 border border-transparent cursor-not-allowed'
- }`}
- style={{ paddingLeft: '8px' }}
- onClick={() => handleFileClick(file)}
- disabled={!selectable}
- >
- <svg className="w-4 h-4 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
- {file.isMarkdown ? (
- <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 3.75h7.5l4.5 4.5v12a1.5 1.5 0 01-1.5 1.5h-10.5a1.5 1.5 0 01-1.5-1.5v-15a1.5 1.5 0 011.5-1.5zM9 14.25V9.75l3 3 3-3v4.5" />
- ) : (
- <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 3.75h7.5l4.5 4.5v12a1.5 1.5 0 01-1.5 1.5h-10.5a1.5 1.5 0 01-1.5-1.5v-15a1.5 1.5 0 011.5-1.5zM14.25 3.75v4.5h4.5" />
- )}
- </svg>
- <span className="flex-1 min-w-0 truncate">{file.name}</span>
- {!selectable ? (
- <span className="text-[10px] px-1.5 py-0.5 rounded border border-border bg-secondary/40">
- {t('agent.notPreviewable')}
- </span>
- ) : null}
- </button>
- );
- })}
- </div>
- )}
- </div>
- </div>
-
- <div className="rounded-xl border border-border bg-card/70 backdrop-blur-sm overflow-hidden shadow-sm flex flex-col min-h-0">
- {selectedFile ? (
- <FileViewer filePath={selectedFile.path} fileName={selectedFile.name} />
- ) : (
- <>
- <div className="px-4 py-3 bg-secondary/30 border-b border-border">
- <div className="flex items-center gap-3">
- <span className="h-9 w-9 rounded-lg border border-border bg-card flex items-center justify-center text-text-muted flex-shrink-0">
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.6} className="h-7 w-7">
- <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
- </svg>
- </span>
- <div>
- <h4 className="text-sm font-medium text-text">{t('agent.contentPreview')}</h4>
- <p className="text-xs text-text-muted mt-1">{t('agent.selectMarkdown')}</p>
- </div>
- </div>
- </div>
- <div className="flex-1 min-h-0 flex items-center justify-center">
- <div className="text-center text-text-muted">
- <div className="mb-2 text-sm">{t('agent.selectMarkdownContent')}</div>
- <div className="text-xs mono">{t('agent.markdownOnly')}</div>
- </div>
- </div>
- </>
- )}
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ApprovalsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ApprovalsPanel/index.tsx
new file mode 100644
index 0000000000..deca965cd1
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ApprovalsPanel/index.tsx
@@ -0,0 +1,823 @@
+/**
+ * 用户面「我的申请」面板(通用审批单列表)。
+ * 布局与视觉对齐定时任务列表:页头、统计 pill、搜索筛选、表格操作链。
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Search } from 'lucide-react';
+import {
+ cancelMyApproval,
+ listApproverCandidates,
+ listMyApprovals,
+ type ApprovalApprover,
+ type ApprovalOrderItem,
+ type ApprovalStatus,
+} from '../../features/approvals/approvalsApi';
+import {
+ createWorkspaceExpandRequest,
+ fetchWorkspaceUsage,
+ formatBytes,
+} from '../../features/workspace/workspaceApi';
+import { isEnterprise } from '../../edition';
+import { hasManagerSessionCredentials } from '../../auth/manager/authSession';
+import { BoldRingIcon, RunningIcon } from '../CronPanel/StatusBadge';
+import { Pagination } from '../common/Pagination';
+import { TableColumnFilter } from '../common/TableColumnFilter';
+import { ApproverPicker } from '../common/ApproverPicker';
+import { copyHistoryText } from '../A2AIngressPanel/copyHistoryText';
+
+const WORKSPACE_QUOTA_EXPAND = 'workspace_quota_expand';
+const GIB = 1024 ** 3;
+const PAGE_SIZE_OPTIONS = [10, 20, 50];
+const DEFAULT_PAGE_SIZE = 20;
+const STATUS_FILTERS: ApprovalStatus[] = ['pending', 'approved', 'rejected', 'cancelled'];
+
+function businessLabel(businessType: string, t: (key: string) => string): string {
+ const key = `approvals.business.${businessType}`;
+ const translated = t(key);
+ return translated === key ? businessType : translated;
+}
+
+function requestedQuotaText(item: ApprovalOrderItem): string {
+ if (item.business_type !== WORKSPACE_QUOTA_EXPAND) return '—';
+ const requested = Number(item.apply_data?.requested_limit_bytes);
+ if (Number.isFinite(requested) && requested > 0) return formatBytes(requested);
+ return '—';
+}
+
+function currentApprovers(item: ApprovalOrderItem): ApprovalApprover[] {
+ if (item.status === 'pending' && item.current_approvers?.length) {
+ return item.current_approvers.filter((approver) => (approver.user_id || '').trim());
+ }
+ const fallbackId = (item.approver_id || '').trim();
+ if (!fallbackId) return [];
+ return [{ user_id: fallbackId, display_name: fallbackId }];
+}
+
+function CurrentApproversCell({ item }: { item: ApprovalOrderItem }) {
+ const approvers = currentApprovers(item);
+ if (!approvers.length) return <span className="text-text-muted">—</span>;
+ return (
+ <div className="flex w-[8.5rem] max-w-[8.5rem] flex-col gap-1">
+ {approvers.map((approver) => {
+ const id = (approver.user_id || '').trim();
+ const name = (approver.display_name || '').trim() || id;
+ const label = `${name}(${id})`;
+ return (
+ <div
+ key={id}
+ className="break-all text-sm text-text"
+ title={label}
+ >
+ {label}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function buildApprovalDetailLink(orderNum: string): string {
+ const origin = typeof window !== 'undefined' ? window.location.origin : '';
+ return `${origin}/manager/approvals/${encodeURIComponent(orderNum)}`;
+}
+
+function canResubmit(item: ApprovalOrderItem): boolean {
+ return (
+ item.business_type === WORKSPACE_QUOTA_EXPAND &&
+ (item.status === 'rejected' || item.status === 'cancelled')
+ );
+}
+
+function bytesToGiBInput(bytes: number): string {
+ if (!Number.isFinite(bytes) || bytes <= 0) return '';
+ const gib = bytes / GIB;
+ return Number.isInteger(gib) ? String(gib) : gib.toFixed(1);
+}
+
+function StatusBadge({ status }: { status: string }) {
+ const { t } = useTranslation();
+ const label = t(`approvals.status.${status}`, { defaultValue: status });
+ if (status === 'pending') {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-sm text-cron-running">
+ <RunningIcon />
+ {label}
+ </span>
+ );
+ }
+ if (status === 'approved') {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-sm text-ok">
+ <BoldRingIcon />
+ {label}
+ </span>
+ );
+ }
+ if (status === 'rejected') {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-sm text-danger">
+ <BoldRingIcon />
+ {label}
+ </span>
+ );
+ }
+ return (
+ <span className="inline-flex items-center gap-1.5 text-sm text-text-muted">
+ <BoldRingIcon />
+ {label}
+ </span>
+ );
+}
+
+function StatPill({
+ icon,
+ label,
+ count,
+ active = false,
+ onClick,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ count: number;
+ active?: boolean;
+ onClick?: () => void;
+}) {
+ const className = [
+ 'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs transition-colors',
+ active
+ ? 'border-accent bg-accent/10 text-text-strong'
+ : 'border-border bg-card text-text',
+ onClick ? 'cursor-pointer hover:border-accent/60 hover:bg-secondary/50' : '',
+ ]
+ .filter(Boolean)
+ .join(' ');
+
+ if (!onClick) {
+ return (
+ <span className={className}>
+ {icon}
+ {label} {count}
+ </span>
+ );
+ }
+
+ return (
+ <button
+ type="button"
+ className={className}
+ aria-pressed={active}
+ onClick={onClick}
+ >
+ {icon}
+ {label} {count}
+ </button>
+ );
+}
+
+function Th({ children, first }: { children: React.ReactNode; first?: boolean }) {
+ return (
+ <th className="py-3 font-medium">
+ <span className={`inline-block ${first ? 'px-4' : 'border-l border-border pl-4 pr-4'}`}>{children}</span>
+ </th>
+ );
+}
+
+export function ApprovalsPanel() {
+ const { t } = useTranslation();
+ const enabled = isEnterprise() && hasManagerSessionCredentials();
+ const [items, setItems] = useState<ApprovalOrderItem[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [busyOrder, setBusyOrder] = useState<string | null>(null);
+ const [search, setSearch] = useState('');
+ const [debouncedSearch, setDebouncedSearch] = useState('');
+ const searchDebounceRef = useRef<number | null>(null);
+ const [statusFilter, setStatusFilter] = useState('');
+ const [businessTypeFilter, setBusinessTypeFilter] = useState('');
+ const [page, setPage] = useState(1);
+ const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
+ const [copyHint, setCopyHint] = useState<string | null>(null);
+
+ const [resubmitItem, setResubmitItem] = useState<ApprovalOrderItem | null>(null);
+ const [resubmitLimitGiB, setResubmitLimitGiB] = useState('');
+ const [resubmitReason, setResubmitReason] = useState('');
+ const [resubmitApproverId, setResubmitApproverId] = useState('');
+ const [resubmitApprovers, setResubmitApprovers] = useState<ApprovalApprover[]>([]);
+ const [resubmitApproversLoading, setResubmitApproversLoading] = useState(false);
+ const [resubmitBusy, setResubmitBusy] = useState(false);
+ const [resubmitError, setResubmitError] = useState<string | null>(null);
+ const [currentLimitBytes, setCurrentLimitBytes] = useState(0);
+ const [usedBytes, setUsedBytes] = useState<number | undefined>(undefined);
+
+ const statusFilterOptions = useMemo(
+ () => [
+ { value: '', label: t('common.all') },
+ ...STATUS_FILTERS.map((status) => ({
+ value: status,
+ label: t(`approvals.status.${status}`),
+ })),
+ ],
+ [t],
+ );
+
+ const businessTypeFilterOptions = useMemo(() => {
+ const types = [...new Set(items.map((item) => item.business_type).filter(Boolean))].sort();
+ return [
+ { value: '', label: t('common.all') },
+ ...types.map((value) => ({ value, label: businessLabel(value, t) })),
+ ];
+ }, [items, t]);
+
+ const load = useCallback(async () => {
+ if (!enabled) {
+ setItems([]);
+ return;
+ }
+ setLoading(true);
+ setError(null);
+ try {
+ const next = await listMyApprovals({
+ search: debouncedSearch.trim() || undefined,
+ });
+ setItems(next);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : t('approvals.loadFailed'));
+ setItems([]);
+ } finally {
+ setLoading(false);
+ }
+ }, [debouncedSearch, enabled, t]);
+
+ useEffect(() => {
+ if (searchDebounceRef.current != null) {
+ window.clearTimeout(searchDebounceRef.current);
+ }
+ searchDebounceRef.current = window.setTimeout(() => {
+ setDebouncedSearch(search);
+ searchDebounceRef.current = null;
+ }, 300);
+ return () => {
+ if (searchDebounceRef.current != null) {
+ window.clearTimeout(searchDebounceRef.current);
+ searchDebounceRef.current = null;
+ }
+ };
+ }, [search]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const counts = useMemo(() => {
+ const next = { pending: 0, approved: 0, rejected: 0, cancelled: 0 };
+ for (const item of items) {
+ if (item.status in next) next[item.status as ApprovalStatus] += 1;
+ }
+ return next;
+ }, [items]);
+
+ const filteredItems = useMemo(() => {
+ return items.filter((item) => {
+ if (statusFilter && item.status !== statusFilter) return false;
+ if (businessTypeFilter && item.business_type !== businessTypeFilter) return false;
+ return true;
+ });
+ }, [businessTypeFilter, items, statusFilter]);
+
+ const totalPages = useMemo(
+ () => Math.max(1, Math.ceil(filteredItems.length / pageSize)),
+ [filteredItems.length, pageSize],
+ );
+
+ useEffect(() => {
+ setPage(1);
+ }, [search, statusFilter, businessTypeFilter, pageSize]);
+
+ useEffect(() => {
+ if (!copyHint) return;
+ const timer = window.setTimeout(() => setCopyHint(null), 2500);
+ return () => window.clearTimeout(timer);
+ }, [copyHint]);
+
+ useEffect(() => {
+ if (page > totalPages) setPage(totalPages);
+ }, [page, totalPages]);
+
+ const pagedItems = useMemo(() => {
+ const start = (page - 1) * pageSize;
+ return filteredItems.slice(start, start + pageSize);
+ }, [filteredItems, page, pageSize]);
+
+ const onCancel = useCallback(
+ async (orderNum: string) => {
+ setBusyOrder(orderNum);
+ setError(null);
+ try {
+ await cancelMyApproval(orderNum);
+ await load();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : t('approvals.cancelFailed'));
+ } finally {
+ setBusyOrder(null);
+ }
+ },
+ [load, t],
+ );
+
+ const copyApprovalLink = useCallback(
+ async (orderNum: string) => {
+ const link = buildApprovalDetailLink(orderNum);
+ try {
+ await copyHistoryText(link);
+ setError(null);
+ setCopyHint(t('approvals.copyLinkSuccess'));
+ } catch {
+ setError(t('approvals.copyLinkFailed'));
+ }
+ },
+ [t],
+ );
+
+ const copyOrderNum = useCallback(
+ async (orderNum: string) => {
+ try {
+ await copyHistoryText(orderNum);
+ setError(null);
+ setCopyHint(t('approvals.copyOrderNumSuccess'));
+ } catch {
+ setError(t('approvals.copyOrderNumFailed'));
+ }
+ },
+ [t],
+ );
+
+ const openResubmit = useCallback(async (item: ApprovalOrderItem) => {
+ const requested = Number(item.apply_data?.requested_limit_bytes);
+ const snapshotCurrent = Number(item.apply_data?.current_limit_bytes);
+ setResubmitItem(item);
+ setResubmitLimitGiB(bytesToGiBInput(requested));
+ setResubmitReason(item.reason || '');
+ setResubmitApproverId('');
+ setResubmitError(null);
+ setCurrentLimitBytes(Number.isFinite(snapshotCurrent) ? snapshotCurrent : 0);
+ setUsedBytes(
+ Number.isFinite(Number(item.apply_data?.used_bytes))
+ ? Number(item.apply_data?.used_bytes)
+ : undefined,
+ );
+ setResubmitApproversLoading(true);
+ try {
+ const [usageSettled, candidates] = await Promise.all([
+ fetchWorkspaceUsage().catch(() => null),
+ listApproverCandidates(),
+ ]);
+ if (usageSettled) {
+ if (usageSettled.limit_bytes > 0) setCurrentLimitBytes(usageSettled.limit_bytes);
+ setUsedBytes(usageSettled.used_bytes);
+ }
+ setResubmitApprovers(candidates);
+ const preferred = String(item.approver_id || '').trim();
+ if (preferred && candidates.some((c) => c.user_id === preferred)) {
+ setResubmitApproverId(preferred);
+ } else if (candidates.length === 1) {
+ setResubmitApproverId(candidates[0]?.user_id || '');
+ }
+ } catch {
+ setResubmitApprovers([]);
+ setResubmitError(t('agent.quota.expandApproverLoadFailed'));
+ } finally {
+ setResubmitApproversLoading(false);
+ }
+ }, [t]);
+
+ const closeResubmit = useCallback(() => {
+ if (resubmitBusy) return;
+ setResubmitItem(null);
+ setResubmitError(null);
+ }, [resubmitBusy]);
+
+ const submitResubmit = useCallback(async () => {
+ if (!resubmitItem) return;
+ const gib = Number(resubmitLimitGiB);
+ if (!Number.isFinite(gib) || gib <= 0) {
+ setResubmitError(t('agent.quota.expandInvalidLimit'));
+ return;
+ }
+ const reason = resubmitReason.trim();
+ if (!reason) {
+ setResubmitError(t('agent.quota.expandReasonRequired'));
+ return;
+ }
+ const approverId = resubmitApproverId.trim();
+ if (!approverId) {
+ setResubmitError(t('agent.quota.expandApproverRequired'));
+ return;
+ }
+ const requested = Math.round(gib * GIB);
+ if (currentLimitBytes > 0 && requested <= currentLimitBytes) {
+ setResubmitError(t('agent.quota.expandMustIncrease'));
+ return;
+ }
+ const jiuwenclawId = String(resubmitItem.cluster_id || '').trim();
+ const groupId = String(resubmitItem.group_id || '').trim();
+ const botId = String(resubmitItem.bot_id || '').trim();
+ if (!jiuwenclawId || !botId) {
+ setResubmitError(t('agent.quota.expandContextRequired'));
+ return;
+ }
+
+ setResubmitBusy(true);
+ setResubmitError(null);
+ try {
+ await createWorkspaceExpandRequest({
+ jiuwenclawId,
+ groupId,
+ botId,
+ requestedLimitBytes: requested,
+ reason,
+ usedBytes,
+ approverId,
+ });
+ setResubmitItem(null);
+ await load();
+ } catch (err) {
+ setResubmitError(err instanceof Error ? err.message : t('approvals.resubmitFailed'));
+ } finally {
+ setResubmitBusy(false);
+ }
+ }, [
+ currentLimitBytes,
+ load,
+ resubmitApproverId,
+ resubmitItem,
+ resubmitLimitGiB,
+ resubmitReason,
+ t,
+ usedBytes,
+ ]);
+ return (
+ <div className="flex-1 min-h-0 relative overflow-y-auto w-full" data-testid="approvals-panel">
+ {error ? (
+ <div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 z-20">
+ <div className="bg-danger px-4 py-2 text-sm text-text-inverse rounded-lg shadow-lg animate-rise">{error}</div>
+ </div>
+ ) : null}
+ {copyHint ? (
+ <div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 z-20">
+ <div className="rounded-lg bg-ok px-4 py-2 text-sm text-text-inverse shadow-lg animate-rise">
+ {copyHint}
+ </div>
+ </div>
+ ) : null}
+
+ <div className="mx-auto w-[90%] max-w-[1600px] py-8">
+ <div className="mb-5 flex items-start justify-between gap-3">
+ <div>
+ <h1 className="text-xl font-semibold text-text-strong">{t('approvals.myTitle')}</h1>
+ <p className="mt-1 text-sm text-text-muted">{t('approvals.mySubtitle')}</p>
+ </div>
+ <button
+ type="button"
+ className="flex items-center gap-2 rounded-full bg-cron-action px-6 py-1.5 text-sm font-bold text-cron-action-foreground hover:bg-cron-action-hover disabled:opacity-60"
+ onClick={() => {
+ void load();
+ }}
+ disabled={!enabled || loading}
+ >
+ {t('common.refresh')}
+ </button>
+ </div>
+
+ {!enabled ? (
+ <div className="rounded-lg border border-border bg-secondary/30 px-4 py-8 text-center text-sm text-text-muted">
+ {t('approvals.unavailable')}
+ </div>
+ ) : null}
+
+ {enabled && items.length > 0 ? (
+ <div className="mb-4 flex flex-wrap items-center gap-3">
+ <button
+ type="button"
+ className={`text-sm font-bold transition-colors ${
+ statusFilter === ''
+ ? 'text-accent'
+ : 'text-text-strong hover:text-accent'
+ }`}
+ aria-pressed={statusFilter === ''}
+ onClick={() => setStatusFilter('')}
+ >
+ {t('approvals.stats.total', { count: items.length })}
+ </button>
+ <StatPill
+ icon={
+ <span className="text-cron-running">
+ <RunningIcon size={15} />
+ </span>
+ }
+ label={t('approvals.status.pending')}
+ count={counts.pending}
+ active={statusFilter === 'pending'}
+ onClick={() =>
+ setStatusFilter((current) => (current === 'pending' ? '' : 'pending'))
+ }
+ />
+ <StatPill
+ icon={
+ <span className="text-ok">
+ <BoldRingIcon />
+ </span>
+ }
+ label={t('approvals.status.approved')}
+ count={counts.approved}
+ active={statusFilter === 'approved'}
+ onClick={() =>
+ setStatusFilter((current) => (current === 'approved' ? '' : 'approved'))
+ }
+ />
+ <StatPill
+ icon={
+ <span className="text-danger">
+ <BoldRingIcon />
+ </span>
+ }
+ label={t('approvals.status.rejected')}
+ count={counts.rejected}
+ active={statusFilter === 'rejected'}
+ onClick={() =>
+ setStatusFilter((current) => (current === 'rejected' ? '' : 'rejected'))
+ }
+ />
+ <StatPill
+ icon={
+ <span className="text-text-muted">
+ <BoldRingIcon />
+ </span>
+ }
+ label={t('approvals.status.cancelled')}
+ count={counts.cancelled}
+ active={statusFilter === 'cancelled'}
+ onClick={() =>
+ setStatusFilter((current) => (current === 'cancelled' ? '' : 'cancelled'))
+ }
+ />
+ </div>
+ ) : null}
+
+ {enabled && !(loading && items.length === 0) ? (
+ <div className="mb-4">
+ <div className="relative">
+ <Search size={14} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
+ <input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t('approvals.search.placeholder') ?? undefined}
+ className="w-full rounded-md border border-border bg-card py-1.5 pl-9 pr-3 text-sm text-text outline-none focus:border-accent"
+ />
+ </div>
+ </div>
+ ) : null}
+
+ {enabled && loading && items.length === 0 ? (
+ <div className="rounded-lg border border-border bg-secondary/30 px-3 py-4 flex items-center justify-center text-sm text-text-muted">
+ {t('common.loading')}
+ </div>
+ ) : null}
+
+ {enabled && !loading && items.length === 0 ? (
+ <div className="flex min-h-[50vh] flex-col items-center justify-center gap-2 text-text-muted">
+ <p className="text-sm">{t('approvals.empty')}</p>
+ </div>
+ ) : null}
+
+ {enabled && items.length > 0 && filteredItems.length === 0 ? (
+ <div className="flex min-h-[30vh] flex-col items-center justify-center gap-2 text-text-muted">
+ <p className="text-sm">{t('approvals.search.noResults')}</p>
+ </div>
+ ) : null}
+
+ {enabled && filteredItems.length > 0 ? (
+ <div className="overflow-x-auto rounded-lg border border-border">
+ <table className="w-full min-w-[1100px] border-collapse text-sm">
+ <thead>
+ <tr className="border-b border-border bg-bg-muted text-left text-text">
+ <Th first>
+ <TableColumnFilter
+ label={t('approvals.table.type')}
+ value={businessTypeFilter}
+ options={businessTypeFilterOptions}
+ onChange={setBusinessTypeFilter}
+ />
+ </Th>
+ <Th>{t('approvals.table.orderNum')}</Th>
+ <Th>{t('approvals.table.title')}</Th>
+ <Th>{t('approvals.table.requestedQuota')}</Th>
+ <Th>{t('approvals.table.approver')}</Th>
+ <Th>
+ <TableColumnFilter
+ label={t('approvals.table.status')}
+ value={statusFilter}
+ options={statusFilterOptions}
+ onChange={setStatusFilter}
+ />
+ </Th>
+ <Th>{t('approvals.table.createdAt')}</Th>
+ <Th>{t('approvals.table.reason')}</Th>
+ <Th>{t('approvals.table.actions')}</Th>
+ </tr>
+ </thead>
+ <tbody>
+ {pagedItems.map((item) => {
+ const typeLabel = businessLabel(item.business_type, t);
+ const title = item.title || typeLabel;
+ const quota = requestedQuotaText(item);
+ const reason = item.reason?.trim() || '—';
+ return (
+ <tr key={item.order_num} className="border-b border-border last:border-0 align-top">
+ <td className="px-4 py-3 text-text">
+ <span
+ className="inline-flex max-w-[160px] truncate rounded-full border border-border bg-card px-2 py-0.5 text-xs text-text-muted"
+ title={typeLabel}
+ >
+ {typeLabel}
+ </span>
+ </td>
+ <td className="px-4 py-3 text-text">
+ <button
+ type="button"
+ className="block w-[12rem] max-w-[12rem] whitespace-nowrap text-left font-mono text-xs text-text-muted hover:text-text-strong"
+ title={t('approvals.copyOrderNum')}
+ onClick={() => {
+ void copyOrderNum(item.order_num);
+ }}
+ >
+ {item.order_num}
+ </button>
+ </td>
+ <td className="px-4 py-3 text-text">
+ <div className="max-w-[220px] truncate font-medium" title={title}>
+ {title}
+ </div>
+ </td>
+ <td className="px-4 py-3 text-text whitespace-nowrap" title={quota}>
+ {quota}
+ </td>
+ <td className="px-4 py-3 text-text">
+ <CurrentApproversCell item={item} />
+ </td>
+ <td className="px-4 py-3">
+ <StatusBadge status={item.status} />
+ </td>
+ <td className="px-4 py-3 text-text whitespace-nowrap">
+ {item.created_at ? new Date(item.created_at).toLocaleString() : '—'}
+ </td>
+ <td className="px-4 py-3 text-text">
+ <div className="min-w-[12rem] max-w-[24rem] space-y-1">
+ <div className="line-clamp-3" title={reason}>
+ {reason}
+ </div>
+ {item.status === 'rejected' && item.latest_reject_comment ? (
+ <div className="line-clamp-2 text-xs text-danger" title={item.latest_reject_comment}>
+ {t('approvals.rejectComment')}: {item.latest_reject_comment}
+ </div>
+ ) : null}
+ </div>
+ </td>
+ <td className="relative px-4 py-3">
+ <div className="flex flex-wrap items-center gap-3">
+ {item.status === 'pending' ? (
+ <>
+ <button
+ type="button"
+ className="text-sm text-cron-action-link hover:opacity-80"
+ onClick={() => {
+ void copyApprovalLink(item.order_num);
+ }}
+ >
+ {t('approvals.copyLink')}
+ </button>
+ <button
+ type="button"
+ className="text-sm text-cron-action-link hover:opacity-80 disabled:opacity-50"
+ disabled={busyOrder === item.order_num}
+ onClick={() => {
+ void onCancel(item.order_num);
+ }}
+ >
+ {busyOrder === item.order_num ? t('common.loading') : t('approvals.cancel')}
+ </button>
+ </>
+ ) : null}
+ {canResubmit(item) ? (
+ <button
+ type="button"
+ className="text-sm text-cron-action-link hover:opacity-80"
+ onClick={() => {
+ void openResubmit(item);
+ }}
+ >
+ {t('approvals.resubmit')}
+ </button>
+ ) : null}
+ {item.status !== 'pending' && !canResubmit(item) ? (
+ <span className="text-sm text-text-muted/50">—</span>
+ ) : null}
+ </div>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ ) : null}
+
+ {enabled && filteredItems.length > 0 ? (
+ <Pagination
+ page={page}
+ totalPages={totalPages}
+ total={filteredItems.length}
+ pageSize={pageSize}
+ pageSizeOptions={PAGE_SIZE_OPTIONS}
+ onPageChange={setPage}
+ onPageSizeChange={setPageSize}
+ className="mt-3"
+ />
+ ) : null}
+ </div>
+
+ {resubmitItem ? (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/60"
+ onClick={closeResubmit}
+ >
+ <div
+ className="relative w-[440px] max-w-[92vw] rounded-lg bg-card p-6 shadow-xl animate-rise"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <h3 className="text-base font-semibold text-text-strong mb-2">{t('approvals.resubmitTitle')}</h3>
+ <p className="text-sm text-text-muted mb-3">{t('approvals.resubmitHint')}</p>
+ {resubmitItem.latest_reject_comment ? (
+ <div className="mb-3 rounded-md border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">
+ {t('approvals.rejectComment')}: {resubmitItem.latest_reject_comment}
+ </div>
+ ) : null}
+ {currentLimitBytes > 0 ? (
+ <p className="text-xs text-text-muted mb-3">
+ {t('approvals.currentQuota')}: {formatBytes(currentLimitBytes)}
+ </p>
+ ) : null}
+ <label className="block text-sm text-text mb-1">{t('agent.quota.expandLimitLabel')}</label>
+ <input
+ type="number"
+ min="0.1"
+ step="0.1"
+ className="w-full mb-3 rounded-md border border-border bg-background px-3 py-2 text-sm"
+ value={resubmitLimitGiB}
+ onChange={(e) => setResubmitLimitGiB(e.target.value)}
+ disabled={resubmitBusy}
+ />
+ <label className="block text-sm text-text mb-1">{t('agent.quota.expandReasonLabel')}</label>
+ <textarea
+ className="w-full mb-3 rounded-md border border-border bg-background px-3 py-2 text-sm min-h-[88px]"
+ value={resubmitReason}
+ onChange={(e) => setResubmitReason(e.target.value)}
+ disabled={resubmitBusy}
+ maxLength={1024}
+ />
+ <label className="block text-sm text-text mb-1">{t('agent.quota.expandApproverLabel')}</label>
+ <ApproverPicker
+ value={resubmitApproverId}
+ options={resubmitApprovers}
+ onChange={setResubmitApproverId}
+ disabled={resubmitBusy}
+ loading={resubmitApproversLoading}
+ />
+ {resubmitError ? <div className="mb-3 text-sm text-danger">{resubmitError}</div> : null}
+ <div className="flex justify-end gap-3">
+ <button
+ type="button"
+ className="rounded-full border border-border bg-card px-10 py-1.5 text-sm font-bold text-text hover:bg-bg-hover"
+ onClick={closeResubmit}
+ disabled={resubmitBusy}
+ >
+ {t('common.cancel')}
+ </button>
+ <button
+ type="button"
+ className="rounded-full bg-cron-action px-10 py-1.5 text-sm font-bold text-cron-action-foreground hover:bg-cron-action-hover disabled:opacity-60"
+ disabled={resubmitBusy}
+ onClick={() => {
+ void submitResubmit();
+ }}
+ >
+ {resubmitBusy ? t('common.loading') : t('approvals.resubmitSubmit')}
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
index eda9e14a0d..7451d46f18 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
@@ -33,6 +33,7 @@ import { isTeamLeaderMember } from '../../utils/teamMemberAvatar';
import { TeamMemberAvatar } from '../TeamMemberAvatar';
import welcomeBanner from '../../assets/home-banner.svg';
import './ChatPanel.css';
+import { WorkspaceQuotaBanner } from '../WorkspacePanel/WorkspaceQuotaBanner';
import { CodeChangesCard } from '../../features/code-mode/CodeChangesCard';
import { useCodeTurnDiffHistory } from '../../features/code-mode/useCodeTurnDiffHistory';
import type { CodeReviewTarget } from '../../features/code-mode/types';
@@ -1155,6 +1156,7 @@ export function ChatPanel({
</div>
</div>
)}
+ <WorkspaceQuotaBanner />
{hasHarnessProgress && (
<div className="sticky top-0 z-10 px-3 pt-2 bg-bg/95 backdrop-blur-sm">
<HarnessProgressBar />
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx
index c09c9387f3..974f0f0802 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx
@@ -19,7 +19,7 @@ import { getProjectDisplayName } from '../../stores/workspaceStore';
import type { AgentMode } from '../../types';
// 会话输入框工具栏那一套 .chat-mode-select pill 下拉组件(模式/模型选择器)的 CSS,
// 抽屉里的模式/模型选择器直接复用同一套 class,跟会话界面视觉/交互完全一致。
-// 这份 CSS 是普通全局样式(非 CSS Module),AgentPanel/FileViewer.tsx 已有同样 import 先例。
+// 这份 CSS 是普通全局样式(非 CSS Module),WorkspacePanel/FileViewer.tsx 已有同样 import 先例。
import '../ChatPanel/ChatPanel.css';
export { isDefaultLikeProject } from './cronProjectDisplay';
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css
index 5b48308814..1fdda41c0a 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionSidebar.css
@@ -537,5 +537,7 @@
}
.enterprise-context-popover__status { margin-top: 10px; color: var(--color-text-secondary); font-size: 11px; }
.enterprise-context-popover__error { margin-top: 10px; color: var(--color-feedback-danger); font-size: 11px; line-height: 1.45; }
-.enterprise-context-popover__logout { width: 100%; margin-top: 12px; padding: 8px 10px; border: 1px solid var(--color-border-default); border-radius: 7px; background: transparent; color: var(--color-feedback-danger); cursor: pointer; font-size: 12px; text-align: center; }
+.enterprise-context-popover__switch { width: 100%; margin-top: 12px; padding: 8px 10px; border: 1px solid var(--color-border-default); border-radius: 7px; background: transparent; color: var(--color-text-primary); cursor: pointer; font-size: 12px; text-align: center; }
+.enterprise-context-popover__switch:hover { background: color-mix(in srgb, var(--color-action-primary) 8%, transparent); border-color: var(--color-action-primary); color: var(--color-action-primary); }
+.enterprise-context-popover__logout { width: 100%; margin-top: 8px; padding: 8px 10px; border: 1px solid var(--color-border-default); border-radius: 7px; background: transparent; color: var(--color-feedback-danger); cursor: pointer; font-size: 12px; text-align: center; }
.enterprise-context-popover__logout:hover { background: color-mix(in srgb, var(--color-feedback-danger) 8%, transparent); border-color: var(--color-feedback-danger); }
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
index 4b48483a82..994884f539 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
@@ -18,7 +18,6 @@ import AdvancedConfigIcon from '../../assets/sidebar/advanced-config-new.svg?rea
import UpdateIcon from '../../assets/sidebar/advanced-config.svg?react';
import WorkIcon from '../../assets/工作.svg?react';
import SkillDesignIcon from '../../assets/技能.svg?react';
-import AgentDesignIcon from '../../assets/智能体.svg?react';
import MoreDesignIcon from '../../assets/更多.svg?react';
import { webRequest } from '../../services/webClient';
import {
@@ -81,11 +80,31 @@ const personalContextNavIcon = (
</svg>
);
+const workspaceNavIcon = (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5}>
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M2.25 12.75V12A2.25 2.25 0 014.5 9.75h15A2.25 2.25 0 0121.75 12v.75m-8.69-6.44l-2.12-2.12a1.5 1.5 0 00-1.061-.44H4.5A2.25 2.25 0 002.25 6v12a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9a2.25 2.25 0 00-2.25-2.25h-5.379a1.5 1.5 0 01-1.06-.44z"
+ />
+ </svg>
+);
+
+const approvalsNavIcon = (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5}>
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
+ />
+ </svg>
+);
+
const mainNavItems: NavItem[] = [
{ key: 'chat', labelKey: 'nav.work', icon: <WorkIcon aria-hidden /> },
{ key: 'skills', labelKey: 'nav.skills', icon: <SkillDesignIcon aria-hidden /> },
{ key: 'channels', labelKey: 'nav.channels', icon: <ChannelIcon aria-hidden /> },
- { key: 'agents', labelKey: 'nav.agent', icon: <AgentDesignIcon aria-hidden /> },
+ { key: 'agents', labelKey: 'nav.workspace', icon: workspaceNavIcon },
{ key: 'teams', labelKey: 'nav.teams', icon: teamNavIcon },
{ key: 'personalContext', labelKey: 'nav.personalContext', icon: personalContextNavIcon },
];
@@ -359,6 +378,19 @@ export function SessionSidebar({
<div className="icon-rail-spacer" />
+ {enterprise && !hiddenNavItems.includes('approvals') && (
+ <button
+ type="button"
+ className={`icon-rail-nav-item${activeNav === 'approvals' ? ' icon-rail-nav-item--active' : ''}`}
+ onClick={() => handleNavClick('approvals')}
+ aria-label={t('nav.approvals')}
+ title={t('nav.approvals')}
+ >
+ <span className="icon-rail-nav-item__icon">{approvalsNavIcon}</span>
+ <span className="icon-rail-nav-item__label">{t('nav.approvals')}</span>
+ </button>
+ )}
+
{enterprise && (
<button
ref={contextButtonRef}
@@ -493,6 +525,15 @@ export function SessionSidebar({
<div className="enterprise-context-popover__status">{t('sessionSidebar.enterpriseContext.switching')}</div>
)}
{enterprise.contextError && <div className="enterprise-context-popover__error">{enterprise.contextError}</div>}
+ {enterprise.managerAccess && (
+ <button
+ type="button"
+ className="enterprise-context-popover__switch"
+ onClick={enterprise.onSwitchToManager}
+ >
+ {t('sessionSidebar.enterpriseContext.switchToManager')}
+ </button>
+ )}
<button type="button" className="enterprise-context-popover__logout" onClick={enterprise.onLogout}>
{t('sessionSidebar.enterpriseContext.logout')}
</button>
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx
index 27fb6c2173..06386bd514 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CircleAlert } from 'lucide-react';
-import { FileViewer } from '../AgentPanel/FileViewer';
+import { FileViewer } from '../WorkspacePanel/FileViewer';
import { containsIgnoredDirectory } from '../../features/fileTreeFilters';
import { isHistoryPreviewFile } from '../../features/historyFilePreview';
import { webRequest } from '../../services/webClient';
diff --git a/jiuwenswarm/channels/web/frontend/src/components/TeamPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/TeamPanel/index.tsx
index 28b187f3a5..becfa0fd62 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/TeamPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/TeamPanel/index.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { PointerEvent as ReactPointerEvent } from 'react';
import { useTranslation } from 'react-i18next';
-import { FileViewer } from '../AgentPanel/FileViewer';
+import { FileViewer } from '../WorkspacePanel/FileViewer';
import { webRequest } from '../../services/webClient';
import { containsIgnoredDirectory } from '../../features/fileTreeFilters';
import { isHistoryPreviewFile } from '../../features/historyFilePreview';
diff --git a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx b/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/FileViewer.tsx
similarity index 100%
rename from jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx
rename to jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/FileViewer.tsx
diff --git a/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/WorkspaceQuotaBanner.tsx b/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/WorkspaceQuotaBanner.tsx
new file mode 100644
index 0000000000..7cbe822c14
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/WorkspaceQuotaBanner.tsx
@@ -0,0 +1,70 @@
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { fetchWorkspaceUsage } from '../../features/workspace/workspaceApi';
+import type { WorkspaceUsageData } from '../../features/workspace/workspaceTypes';
+
+const POLL_MS = 60_000;
+
+interface WorkspaceQuotaBannerProps {
+ /** 隐藏横幅(例如当前已在工作空间页) */
+ hidden?: boolean;
+}
+
+export function WorkspaceQuotaBanner({ hidden }: WorkspaceQuotaBannerProps) {
+ const { t } = useTranslation();
+ const [usage, setUsage] = useState<WorkspaceUsageData | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ const load = async () => {
+ try {
+ const next = await fetchWorkspaceUsage();
+ if (!cancelled) setUsage(next);
+ } catch {
+ if (!cancelled) setUsage(null);
+ }
+ };
+ void load();
+ const timer = window.setInterval(() => {
+ void load();
+ }, POLL_MS);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ };
+ }, []);
+
+ if (hidden || !usage || usage.status === 'ok' || usage.unlimited || usage.limit_bytes === -1) {
+ return null;
+ }
+
+ const goAgents = () => {
+ window.dispatchEvent(new CustomEvent<string>('jiuwen:nav', { detail: 'agents' }));
+ };
+
+ if (usage.status === 'block') {
+ return (
+ <div className="mx-3 mt-2 rounded-lg border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="font-medium">{t('agent.quota.chatBlockTitle')}</div>
+ <div className="text-xs mt-0.5 opacity-90">{t('agent.quota.chatBlockBody')}</div>
+ </div>
+ <button type="button" className="btn !px-3 !py-1.5 flex-shrink-0" onClick={goAgents}>
+ {t('agent.quota.openWorkspace')}
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="mx-3 mt-2 rounded-lg border border-warn/40 bg-warn/10 px-3 py-2 text-sm text-warn flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="font-medium">{t('agent.quota.chatWarnTitle')}</div>
+ <div className="text-xs mt-0.5 opacity-90">{t('agent.quota.chatWarnBody')}</div>
+ </div>
+ <button type="button" className="btn !px-3 !py-1.5 flex-shrink-0" onClick={goAgents}>
+ {t('agent.quota.openWorkspace')}
+ </button>
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/WorkspaceUsageBar.tsx b/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/WorkspaceUsageBar.tsx
new file mode 100644
index 0000000000..67dfbcd5e5
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/WorkspaceUsageBar.tsx
@@ -0,0 +1,105 @@
+import { useTranslation } from 'react-i18next';
+import { isEnterprise } from '../../edition';
+import {
+ formatBytes,
+ formatPercent,
+} from '../../features/workspace/workspaceApi';
+import type { WorkspaceUsageData } from '../../features/workspace/workspaceTypes';
+
+interface WorkspaceUsageBarProps {
+ usage: WorkspaceUsageData | null;
+ loading?: boolean;
+ onRequestExpand?: () => void;
+ onRefresh?: () => void;
+}
+
+function isUnlimited(usage: WorkspaceUsageData | null | undefined): boolean {
+ if (!usage) return false;
+ if (usage.unlimited === true) return true;
+ return usage.limit_bytes === -1;
+}
+
+function barColor(status: string | undefined): string {
+ if (status === 'block') return 'bg-danger';
+ if (status === 'warn') return 'bg-warn';
+ return 'bg-accent';
+}
+
+function statusLabel(
+ status: string | undefined,
+ t: (key: string) => string,
+): string {
+ if (status === 'block') return t('agent.quota.block');
+ if (status === 'warn') return t('agent.quota.warn');
+ return t('agent.quota.ok');
+}
+
+export function WorkspaceUsageBar({
+ usage,
+ loading,
+ onRequestExpand,
+ onRefresh,
+}: WorkspaceUsageBarProps) {
+ const { t } = useTranslation();
+ const unlimited = isUnlimited(usage);
+ const percent = usage && !unlimited ? Math.min(100, Math.max(0, usage.percent)) : 0;
+ // 扩容仅企业版;个人版不展示入口
+ const showExpand = Boolean(onRequestExpand) && isEnterprise();
+ // 有限额即可申请扩容(含用量正常);仅无用量数据或无限制配额时禁用
+ const expandDisabled = !usage || unlimited;
+
+ let summary: string;
+ if (loading && !usage) {
+ summary = t('common.loading');
+ } else if (!usage) {
+ summary = t('agent.quota.unavailable');
+ } else if (unlimited) {
+ summary = `${formatBytes(usage.used_bytes)} / ${t('agent.quota.unlimited')} · ${statusLabel(usage.status, t)}`;
+ } else {
+ summary = `${formatBytes(usage.used_bytes)} / ${formatBytes(usage.limit_bytes)} · ${formatPercent(usage.percent)} · ${statusLabel(usage.status, t)}`;
+ }
+
+ return (
+ <div className="rounded-xl border border-border bg-card/70 px-4 py-3 flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-text">{t('agent.quota.title')}</div>
+ <div className="text-xs text-text-muted mt-0.5 mono">{summary}</div>
+ </div>
+ <div className="flex items-center gap-2 flex-shrink-0">
+ {onRefresh ? (
+ <button
+ type="button"
+ className="btn !px-3 !py-1.5"
+ onClick={onRefresh}
+ disabled={loading}
+ >
+ {loading ? t('common.refreshing') : t('common.refresh')}
+ </button>
+ ) : null}
+ {showExpand ? (
+ <button
+ type="button"
+ className="btn primary !px-3 !py-1.5"
+ onClick={onRequestExpand}
+ disabled={expandDisabled}
+ title={
+ unlimited
+ ? t('agent.quota.expandUnlimitedHint')
+ : t('agent.quota.expandHint')
+ }
+ >
+ {t('agent.quota.requestExpand')}
+ </button>
+ ) : null}
+ </div>
+ </div>
+ <div className="h-2 rounded-full bg-secondary overflow-hidden">
+ <div
+ className={`h-full rounded-full transition-all ${barColor(unlimited ? 'ok' : usage?.status)}`}
+ style={{ width: unlimited ? '0%' : `${percent}%` }}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/index.tsx
new file mode 100644
index 0000000000..c97748bfda
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/WorkspacePanel/index.tsx
@@ -0,0 +1,773 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation, Trans } from 'react-i18next';
+import ReactMarkdown from 'react-markdown';
+import {
+ createWorkspaceExpandRequest,
+ deleteWorkspaceEntries,
+ downloadWorkspaceEntry,
+ fetchWorkspaceTree,
+ fetchWorkspaceUsage,
+ formatBytes,
+ previewWorkspaceFile,
+} from '../../features/workspace/workspaceApi';
+import {
+ listApproverCandidates,
+ type ApprovalApprover,
+} from '../../features/approvals/approvalsApi';
+import type {
+ WorkspaceEntry,
+ WorkspaceUsageData,
+} from '../../features/workspace/workspaceTypes';
+import { useEnterpriseContext } from '../../services/enterpriseContext';
+import { getRuntimeScope } from '../../services/runtimeScope';
+import { isEnterprise } from '../../edition';
+import { WorkspaceUsageBar } from './WorkspaceUsageBar';
+import { ConfirmDialog } from '../common/ConfirmDialog';
+import { ApproverPicker } from '../common/ApproverPicker';
+
+interface WorkspacePanelProps {
+ sessionId: string;
+}
+
+const ROOT_KEY = '';
+
+/** 可清理 zone 的根路径(相对租户根);筛选时保留其祖先目录以便导航。 */
+const DELETABLE_ZONE_ROOTS = [
+ 'agent/jiuwenclaw_workspace/projects',
+ 'agent/jiuwenclaw_workspace/todo',
+ 'agent/jiuwenclaw_workspace/prompt_attachment',
+ 'agent/jiuwenclaw_workspace/received_files',
+] as const;
+
+/** 打开「仅可删除」时预展开并拉取的路径(含中间祖先)。 */
+const DELETABLE_FILTER_EXPAND_PATHS = [
+ 'agent',
+ 'agent/jiuwenclaw_workspace',
+ ...DELETABLE_ZONE_ROOTS,
+] as const;
+
+type ChildrenCache = Record<string, WorkspaceEntry[]>;
+
+function parentPath(relativePath: string): string {
+ const idx = relativePath.lastIndexOf('/');
+ return idx === -1 ? ROOT_KEY : relativePath.slice(0, idx);
+}
+
+function formatTime(ms: number | undefined): string {
+ if (!ms || !Number.isFinite(ms)) return '—';
+ try {
+ return new Date(ms).toLocaleString();
+ } catch {
+ return '—';
+ }
+}
+
+function zoneLabel(zone: string, t: (key: string) => string): string {
+ const key = `agent.zones.${zone}`;
+ const translated = t(key);
+ return translated === key ? zone : translated;
+}
+
+/** 条目本身可删,或目录是通往可删 zone 的祖先 / 落在可删 zone 内。 */
+function keepUnderDeletableFilter(entry: WorkspaceEntry): boolean {
+ if (entry.deletable) return true;
+ if (!entry.is_dir) return false;
+ const path = entry.relative_path.replace(/\/+$/, '');
+ if (!path) return false;
+ return DELETABLE_ZONE_ROOTS.some(
+ (zoneRoot) => zoneRoot === path || zoneRoot.startsWith(`${path}/`),
+ );
+}
+
+export function WorkspacePanel({ sessionId: _sessionId }: WorkspacePanelProps) {
+ const { t } = useTranslation();
+ const enterprise = useEnterpriseContext();
+ const [usage, setUsage] = useState<WorkspaceUsageData | null>(null);
+ const [usageLoading, setUsageLoading] = useState(true);
+ const [childrenCache, setChildrenCache] = useState<ChildrenCache>({});
+ const childrenCacheRef = useRef<ChildrenCache>({});
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set([ROOT_KEY]));
+ const [loadingDirs, setLoadingDirs] = useState<Set<string>>(() => new Set());
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [selected, setSelected] = useState<WorkspaceEntry | null>(null);
+ const [deletableOnly, setDeletableOnly] = useState(false);
+ const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
+ const [actionBusy, setActionBusy] = useState(false);
+ const [actionError, setActionError] = useState<string | null>(null);
+ const [previewContent, setPreviewContent] = useState<string | null>(null);
+ const [previewTruncated, setPreviewTruncated] = useState(false);
+ const [previewLoading, setPreviewLoading] = useState(false);
+ const [previewBinary, setPreviewBinary] = useState(false);
+ const [expandSuccessOpen, setExpandSuccessOpen] = useState(false);
+ const [expandOpen, setExpandOpen] = useState(false);
+ const [expandLimitGiB, setExpandLimitGiB] = useState('');
+ const [expandReason, setExpandReason] = useState('');
+ const [expandApproverId, setExpandApproverId] = useState('');
+ const [expandApprovers, setExpandApprovers] = useState<ApprovalApprover[]>([]);
+ const [expandApproversLoading, setExpandApproversLoading] = useState(false);
+ const [expandBusy, setExpandBusy] = useState(false);
+ const [expandError, setExpandError] = useState<string | null>(null);
+
+ useEffect(() => {
+ childrenCacheRef.current = childrenCache;
+ }, [childrenCache]);
+
+ const loadUsage = useCallback(async () => {
+ setUsageLoading(true);
+ try {
+ const next = await fetchWorkspaceUsage();
+ setUsage(next);
+ } catch (err) {
+ console.error('[WorkspacePanel] usage failed', err);
+ setUsage(null);
+ } finally {
+ setUsageLoading(false);
+ }
+ }, []);
+
+ const loadDir = useCallback(async (relativePath: string, force = false) => {
+ if (!force && childrenCacheRef.current[relativePath] !== undefined) {
+ return;
+ }
+ setLoadingDirs((prev) => new Set(prev).add(relativePath));
+ try {
+ const data = await fetchWorkspaceTree(relativePath);
+ setChildrenCache((prev) => ({ ...prev, [relativePath]: data.entries }));
+ setLoadError(null);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : t('agent.errors.loadFailed');
+ // 「仅可删除」会预拉 projects/todo/prompt_attachment/received_files 等 zone;
+ // 尚未创建的目录后端返回 path not found,应按空目录处理,避免整页报错。
+ if (/path not found/i.test(message)) {
+ setChildrenCache((prev) => ({ ...prev, [relativePath]: [] }));
+ return;
+ }
+ console.error('[WorkspacePanel] tree failed', err);
+ setLoadError(message);
+ } finally {
+ setLoadingDirs((prev) => {
+ const next = new Set(prev);
+ next.delete(relativePath);
+ return next;
+ });
+ }
+ }, [t]);
+
+ useEffect(() => {
+ void loadUsage();
+ void loadDir(ROOT_KEY, true);
+ }, [loadDir, loadUsage]);
+
+ const refreshAll = useCallback(async () => {
+ setActionError(null);
+ const openPaths = Array.from(expanded);
+ await loadUsage();
+ await Promise.all(openPaths.map((path) => loadDir(path, true)));
+ if (selected) {
+ const parent = selected.is_dir ? selected.relative_path : parentPath(selected.relative_path);
+ try {
+ const entries = (await fetchWorkspaceTree(parent)).entries;
+ setChildrenCache((prev) => ({ ...prev, [parent]: entries }));
+ setSelected(entries.find((e) => e.relative_path === selected.relative_path) || null);
+ } catch {
+ setSelected(null);
+ }
+ }
+ }, [expanded, loadDir, loadUsage, selected]);
+ const visibleEntries = useCallback(
+ (path: string): WorkspaceEntry[] => {
+ let entries = childrenCache[path] || [];
+ if (deletableOnly) {
+ entries = entries.filter((e) => keepUnderDeletableFilter(e));
+ }
+ return [...entries].sort((a, b) => {
+ if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
+ return a.name.localeCompare(b.name, 'zh-Hans-CN');
+ });
+ },
+ [childrenCache, deletableOnly],
+ );
+
+ useEffect(() => {
+ if (!deletableOnly) return;
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ for (const path of DELETABLE_FILTER_EXPAND_PATHS) {
+ next.add(path);
+ }
+ return next;
+ });
+ for (const path of DELETABLE_FILTER_EXPAND_PATHS) {
+ void loadDir(path);
+ }
+ }, [deletableOnly, loadDir]);
+
+ const toggleDir = (entry: WorkspaceEntry) => {
+ const key = entry.relative_path;
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ void loadDir(key);
+ }
+ return next;
+ });
+ };
+
+ const selectEntry = (entry: WorkspaceEntry) => {
+ setSelected(entry);
+ setActionError(null);
+ if (entry.is_dir) {
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ next.add(entry.relative_path);
+ return next;
+ });
+ void loadDir(entry.relative_path);
+ }
+ };
+
+ useEffect(() => {
+ if (!selected || selected.is_dir) {
+ setPreviewContent(null);
+ setPreviewTruncated(false);
+ setPreviewBinary(false);
+ setPreviewLoading(false);
+ return;
+ }
+ let cancelled = false;
+ setPreviewLoading(true);
+ setPreviewContent(null);
+ setPreviewBinary(false);
+ void previewWorkspaceFile(selected.relative_path)
+ .then((data) => {
+ if (cancelled) return;
+ setPreviewTruncated(data.truncated);
+ if (data.content == null) {
+ setPreviewBinary(true);
+ setPreviewContent(null);
+ } else {
+ setPreviewBinary(false);
+ setPreviewContent(data.content);
+ }
+ })
+ .catch((err) => {
+ if (cancelled) return;
+ setPreviewBinary(false);
+ setPreviewContent(null);
+ setActionError(err instanceof Error ? err.message : t('fileViewer.unknownError'));
+ })
+ .finally(() => {
+ if (!cancelled) setPreviewLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [selected, t]);
+
+ const requestDelete = () => {
+ if (!selected?.deletable || actionBusy) return;
+ setDeleteConfirmOpen(true);
+ };
+
+ const confirmDelete = async () => {
+ if (!selected?.deletable) {
+ setDeleteConfirmOpen(false);
+ return;
+ }
+ setActionBusy(true);
+ setActionError(null);
+ try {
+ const result = await deleteWorkspaceEntries([selected.relative_path]);
+ const item = result.results[0];
+ if (item && !item.ok) {
+ setActionError(item.error || t('agent.errors.deleteFailed'));
+ return;
+ }
+ const parent = parentPath(selected.relative_path);
+ setSelected(null);
+ setDeleteConfirmOpen(false);
+ await loadDir(parent, true);
+ await loadUsage();
+ } catch (err) {
+ setActionError(err instanceof Error ? err.message : t('agent.errors.deleteFailed'));
+ } finally {
+ setActionBusy(false);
+ }
+ };
+
+ const handleDownload = async () => {
+ if (!selected) return;
+ setActionBusy(true);
+ setActionError(null);
+ try {
+ await downloadWorkspaceEntry(selected.relative_path);
+ } catch (err) {
+ setActionError(err instanceof Error ? err.message : t('agent.errors.downloadFailed'));
+ } finally {
+ setActionBusy(false);
+ }
+ };
+
+ const isMarkdown =
+ selected &&
+ !selected.is_dir &&
+ (selected.name.toLowerCase().endsWith('.md') ||
+ selected.name.toLowerCase().endsWith('.mdx'));
+
+ const rootEntries = useMemo(() => visibleEntries(ROOT_KEY), [visibleEntries]);
+
+ const renderTree = (path: string, depth: number): JSX.Element[] => {
+ const entries = visibleEntries(path);
+ const loading = loadingDirs.has(path);
+ if (loading && entries.length === 0) {
+ return [
+ <div
+ key={`loading-${path}`}
+ className="px-2 py-2 text-xs text-text-muted"
+ style={{ paddingLeft: `${depth * 14 + 8}px` }}
+ >
+ {t('common.loading')}
+ </div>,
+ ];
+ }
+ return entries.map((entry) => {
+ const isExpanded = expanded.has(entry.relative_path);
+ const selectedRow = selected?.relative_path === entry.relative_path;
+ return (
+ <div key={entry.relative_path}>
+ <div
+ className={`w-full min-h-10 flex items-center gap-1 rounded-lg px-1 py-1 text-left text-[14px] border ${
+ selectedRow
+ ? 'bg-accent-subtle text-text border-[var(--color-border-accent)]'
+ : 'text-text-muted hover:bg-secondary/40 hover:text-text border-transparent'
+ }`}
+ style={{ paddingLeft: `${depth * 14 + 4}px` }}
+ >
+ {entry.is_dir ? (
+ <button
+ type="button"
+ className="w-5 h-5 flex items-center justify-center flex-shrink-0"
+ onClick={() => toggleDir(entry)}
+ aria-label={isExpanded ? 'collapse' : 'expand'}
+ >
+ <svg
+ className={`w-3 h-3 ${isExpanded ? 'rotate-90' : ''}`}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <path strokeLinecap="round" strokeLinejoin="round" d="M9 6l6 6-6 6" />
+ </svg>
+ </button>
+ ) : (
+ <span className="w-5 h-5 flex-shrink-0" />
+ )}
+ <button
+ type="button"
+ className="flex-1 min-w-0 flex items-center gap-2 py-1.5 pr-2 text-left"
+ onClick={() => selectEntry(entry)}
+ title={entry.relative_path}
+ >
+ <svg className="w-4 h-4 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
+ {entry.is_dir ? (
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h4.5l1.5 2.25h10.5v8.25A2.25 2.25 0 0118 19.5H6A2.25 2.25 0 013.75 17.25V6.75z" />
+ ) : (
+ <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 3.75h7.5l4.5 4.5v12a1.5 1.5 0 01-1.5 1.5h-10.5a1.5 1.5 0 01-1.5-1.5v-15a1.5 1.5 0 011.5-1.5zM14.25 3.75v4.5h4.5" />
+ )}
+ </svg>
+ <span className="flex-1 min-w-0 truncate">{entry.name}</span>
+ {entry.deletable ? (
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-border bg-secondary/40">
+ {t('agent.deletable')}
+ </span>
+ ) : null}
+ </button>
+ </div>
+ {entry.is_dir && isExpanded ? renderTree(entry.relative_path, depth + 1) : null}
+ </div>
+ );
+ });
+ };
+
+ const openExpandDialog = useCallback(() => {
+ const currentGiB =
+ usage && usage.limit_bytes > 0 ? (usage.limit_bytes / (1024 ** 3)).toFixed(1) : '';
+ setExpandLimitGiB(currentGiB);
+ setExpandReason('');
+ setExpandApproverId('');
+ setExpandError(null);
+ setExpandOpen(true);
+ setExpandApproversLoading(true);
+ void listApproverCandidates()
+ .then((items) => {
+ setExpandApprovers(items);
+ if (items.length === 1) {
+ setExpandApproverId(items[0]?.user_id || '');
+ }
+ })
+ .catch(() => {
+ setExpandApprovers([]);
+ setExpandError(t('agent.quota.expandApproverLoadFailed'));
+ })
+ .finally(() => setExpandApproversLoading(false));
+ }, [t, usage]);
+
+ const submitExpand = useCallback(async () => {
+ const gib = Number(expandLimitGiB);
+ if (!Number.isFinite(gib) || gib <= 0) {
+ setExpandError(t('agent.quota.expandInvalidLimit'));
+ return;
+ }
+ const reason = expandReason.trim();
+ if (!reason) {
+ setExpandError(t('agent.quota.expandReasonRequired'));
+ return;
+ }
+ const approverId = expandApproverId.trim();
+ if (!approverId) {
+ setExpandError(t('agent.quota.expandApproverRequired'));
+ return;
+ }
+ const requested = Math.round(gib * 1024 ** 3);
+ if (usage && usage.limit_bytes > 0 && requested <= usage.limit_bytes) {
+ setExpandError(t('agent.quota.expandMustIncrease'));
+ return;
+ }
+ const scope = getRuntimeScope();
+ const jiuwenclawId = enterprise?.selected.jiuwenclaw_id?.trim() || '';
+ const groupId = enterprise?.selected.group_id ?? scope.groupId ?? '';
+ const botId = enterprise?.selected.bot_id ?? scope.botId ?? '';
+ if (!jiuwenclawId || !botId) {
+ setExpandError(t('agent.quota.expandContextRequired'));
+ return;
+ }
+ setExpandBusy(true);
+ setExpandError(null);
+ try {
+ await createWorkspaceExpandRequest({
+ jiuwenclawId,
+ groupId,
+ botId,
+ requestedLimitBytes: requested,
+ reason,
+ usedBytes: usage?.used_bytes,
+ approverId,
+ });
+ setExpandOpen(false);
+ setExpandSuccessOpen(true);
+ } catch (err) {
+ setExpandError(err instanceof Error ? err.message : t('agent.quota.expandFailed'));
+ } finally {
+ setExpandBusy(false);
+ }
+ }, [enterprise, expandApproverId, expandLimitGiB, expandReason, t, usage]);
+
+ const goToApprovals = useCallback(() => {
+ setExpandSuccessOpen(false);
+ window.dispatchEvent(new CustomEvent<string>('jiuwen:nav', { detail: 'approvals' }));
+ }, []);
+
+ return (
+ <>
+ {expandOpen ? (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/60"
+ onClick={() => {
+ if (!expandBusy) setExpandOpen(false);
+ }}
+ >
+ <div
+ className="relative w-[420px] rounded-lg bg-card p-6 shadow-xl animate-rise"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <h3 className="text-base font-semibold text-text-strong mb-4">
+ {t('agent.quota.expandTitle')}
+ </h3>
+ <p className="text-sm text-text-muted mb-4">{t('agent.quota.expandDialogHint')}</p>
+ <label className="block text-sm text-text mb-1">{t('agent.quota.expandLimitLabel')}</label>
+ <input
+ type="number"
+ min="0.1"
+ step="0.1"
+ className="w-full mb-3 rounded-md border border-border bg-background px-3 py-2 text-sm"
+ value={expandLimitGiB}
+ onChange={(e) => setExpandLimitGiB(e.target.value)}
+ disabled={expandBusy}
+ />
+ <label className="block text-sm text-text mb-1">{t('agent.quota.expandReasonLabel')}</label>
+ <textarea
+ className="w-full mb-3 rounded-md border border-border bg-background px-3 py-2 text-sm min-h-[88px]"
+ value={expandReason}
+ onChange={(e) => setExpandReason(e.target.value)}
+ disabled={expandBusy}
+ maxLength={1024}
+ />
+ <label className="block text-sm text-text mb-1">{t('agent.quota.expandApproverLabel')}</label>
+ <ApproverPicker
+ value={expandApproverId}
+ options={expandApprovers}
+ onChange={setExpandApproverId}
+ disabled={expandBusy}
+ loading={expandApproversLoading}
+ />
+ {expandError ? (
+ <div className="mb-3 text-sm text-danger">{expandError}</div>
+ ) : null}
+ <div className="flex justify-end gap-3">
+ <button
+ type="button"
+ className="px-6 py-1.5 rounded-full border border-border text-sm font-medium text-text hover:bg-secondary/50"
+ disabled={expandBusy}
+ onClick={() => setExpandOpen(false)}
+ >
+ {t('common.cancel')}
+ </button>
+ <button
+ type="button"
+ className="rounded-full bg-accent px-6 py-1.5 text-sm font-medium text-accent-foreground hover:bg-accent-hover disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={expandBusy}
+ onClick={() => {
+ void submitExpand();
+ }}
+ >
+ {expandBusy ? t('common.loading') : t('agent.quota.expandSubmit')}
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : null}
+ {expandSuccessOpen ? (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/60"
+ onClick={() => setExpandSuccessOpen(false)}
+ >
+ <div
+ className="relative w-[420px] rounded-lg bg-card p-6 shadow-xl animate-rise"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="expand-success-title"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <h3 id="expand-success-title" className="text-base font-semibold text-text-strong mb-3">
+ {t('agent.quota.expandSubmittedTitle')}
+ </h3>
+ <p className="mb-6 text-sm text-text leading-relaxed">
+ <Trans
+ i18nKey="agent.quota.expandSubmittedBody"
+ components={{
+ approvals: (
+ <button
+ type="button"
+ className="font-medium text-accent underline underline-offset-2 hover:text-accent-hover"
+ onClick={goToApprovals}
+ />
+ ),
+ }}
+ />
+ </p>
+ <div className="flex justify-end gap-3">
+ <button
+ type="button"
+ className="px-6 py-1.5 rounded-full border border-border text-sm font-medium text-text hover:bg-secondary/50"
+ onClick={() => setExpandSuccessOpen(false)}
+ >
+ {t('common.ok')}
+ </button>
+ <button
+ type="button"
+ className="rounded-full bg-accent px-6 py-1.5 text-sm font-medium text-accent-foreground hover:bg-accent-hover"
+ onClick={goToApprovals}
+ >
+ {t('agent.quota.expandViewApprovals')}
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : null}
+ {deleteConfirmOpen && selected ? (
+ <ConfirmDialog
+ title={t('agent.deleteConfirmTitle')}
+ message={t('agent.confirmDelete', { name: selected.name })}
+ confirmLabel={t('agent.delete')}
+ onConfirm={() => {
+ void confirmDelete();
+ }}
+ onCancel={() => {
+ if (!actionBusy) setDeleteConfirmOpen(false);
+ }}
+ loading={actionBusy}
+ />
+ ) : null}
+ <div className="flex-1 min-h-0">
+ <div className="card w-full h-full flex flex-col gap-3">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <div>
+ <h2 className="text-lg font-semibold">{t('agent.title')}</h2>
+ <p className="text-sm text-text-muted mt-1">{t('agent.subtitle')}</p>
+ </div>
+ </div>
+
+ <WorkspaceUsageBar
+ usage={usage}
+ loading={usageLoading}
+ onRefresh={() => {
+ void refreshAll();
+ }}
+ onRequestExpand={isEnterprise() ? openExpandDialog : undefined}
+ />
+
+ {loadError ? (
+ <div className="rounded-md border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">
+ {loadError}
+ </div>
+ ) : null}
+
+ <div className="flex-1 min-h-0 grid grid-cols-[minmax(0,3fr)_minmax(0,7fr)] gap-4">
+ <div className="rounded-xl border border-border bg-card/70 overflow-hidden flex flex-col min-h-0">
+ <div className="px-4 py-3 bg-secondary/30 border-b border-border space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-sm font-medium text-text">{t('agent.workspace')}</h3>
+ <button
+ type="button"
+ className="btn !px-3 !py-1.5"
+ onClick={() => {
+ void refreshAll();
+ }}
+ disabled={usageLoading}
+ >
+ {t('common.refresh')}
+ </button>
+ </div>
+ <div className="flex items-center gap-3 text-xs text-text-muted flex-wrap">
+ <label className="inline-flex items-center gap-1.5 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={deletableOnly}
+ onChange={(e) => setDeletableOnly(e.target.checked)}
+ />
+ {t('agent.filterDeletable')}
+ </label>
+ </div>
+ </div>
+ <div className="flex-1 overflow-auto p-2">
+ {rootEntries.length === 0 && !loadingDirs.has(ROOT_KEY) ? (
+ <div className="h-full flex items-center justify-center text-sm text-text-muted">
+ {deletableOnly ? t('agent.emptyDeletable') : t('agent.empty')}
+ </div>
+ ) : (
+ <div className="space-y-0.5">{renderTree(ROOT_KEY, 0)}</div>
+ )}
+ </div>
+ </div>
+
+ <div className="rounded-xl border border-border bg-card/70 overflow-hidden flex flex-col min-h-0">
+ {selected ? (
+ <>
+ <div className="px-4 py-3 bg-secondary/30 border-b border-border space-y-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <h4 className="text-sm font-medium text-text truncate">{selected.name}</h4>
+ <p className="text-xs text-text-muted mono truncate mt-1" title={selected.relative_path}>
+ {selected.relative_path}
+ </p>
+ </div>
+ <div className="flex items-center gap-2 flex-shrink-0">
+ <button
+ type="button"
+ className="btn !px-3 !py-1.5 disabled:opacity-50"
+ disabled={actionBusy}
+ onClick={() => {
+ void handleDownload();
+ }}
+ >
+ {t('agent.download')}
+ </button>
+ <button
+ type="button"
+ className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
+ disabled={actionBusy || !selected.deletable}
+ title={
+ selected.deletable
+ ? t('agent.delete')
+ : t('agent.notDeletableReason')
+ }
+ onClick={requestDelete}
+ >
+ {t('agent.delete')}
+ </button>
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-2 text-xs text-text-muted">
+ <div>{t('agent.meta.zone')}: <span className="text-text">{zoneLabel(String(selected.zone), t)}</span></div>
+ <div>{t('agent.meta.size')}: <span className="text-text mono">{formatBytes(selected.size_bytes)}</span></div>
+ <div>{t('agent.meta.mtime')}: <span className="text-text">{formatTime(selected.mtime_ms)}</span></div>
+ <div>
+ {t('agent.meta.deletable')}:{' '}
+ <span className="text-text">
+ {selected.deletable ? t('common.yes') : t('common.no')}
+ </span>
+ </div>
+ </div>
+ {actionError ? (
+ <div className="rounded-md border border-danger/30 bg-danger/10 px-2.5 py-1.5 text-xs text-danger">
+ {actionError}
+ </div>
+ ) : null}
+ </div>
+ <div className="flex-1 min-h-0 overflow-auto p-4">
+ {selected.is_dir ? (
+ <div className="h-full flex items-center justify-center text-sm text-text-muted">
+ {t('agent.dirSelectedHint')}
+ </div>
+ ) : previewLoading ? (
+ <div className="h-full flex items-center justify-center">
+ <div className="w-7 h-7 rounded-full border-4 border-border border-t-accent animate-spin" />
+ </div>
+ ) : previewBinary ? (
+ <div className="h-full flex items-center justify-center text-sm text-text-muted">
+ {t('agent.binaryPreview')}
+ </div>
+ ) : previewContent != null ? (
+ <div className="space-y-2">
+ {previewTruncated ? (
+ <div className="text-xs text-warn">{t('agent.previewTruncated')}</div>
+ ) : null}
+ {isMarkdown ? (
+ <article className="chat-text max-w-none">
+ <ReactMarkdown>{previewContent || ' '}</ReactMarkdown>
+ </article>
+ ) : (
+ <pre className="text-sm text-text mono whitespace-pre-wrap break-words rounded-lg border border-border bg-card p-3">
+ {previewContent}
+ </pre>
+ )}
+ </div>
+ ) : (
+ <div className="h-full flex items-center justify-center text-sm text-text-muted">
+ {t('agent.previewEmpty')}
+ </div>
+ )}
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="px-4 py-3 bg-secondary/30 border-b border-border">
+ <h4 className="text-sm font-medium text-text">{t('agent.contentPreview')}</h4>
+ <p className="text-xs text-text-muted mt-1">{t('agent.selectEntry')}</p>
+ </div>
+ <div className="flex-1 min-h-0 flex items-center justify-center text-sm text-text-muted">
+ {t('agent.selectEntryHint')}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/common/ApproverPicker.tsx b/jiuwenswarm/channels/web/frontend/src/components/common/ApproverPicker.tsx
new file mode 100644
index 0000000000..b68ee51365
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/common/ApproverPicker.tsx
@@ -0,0 +1,158 @@
+import { useEffect, useId, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ChevronDown, Search } from 'lucide-react';
+import type { ApprovalApprover } from '../../features/approvals/approvalsApi';
+
+function matchesQuery(item: ApprovalApprover, query: string): boolean {
+ const q = query.trim().toLowerCase();
+ if (!q) return true;
+ const userId = (item.user_id || '').toLowerCase();
+ const displayName = (item.display_name || '').toLowerCase();
+ return userId.includes(q) || displayName.includes(q);
+}
+
+function formatSelected(item: ApprovalApprover | undefined): string {
+ if (!item) return '';
+ const name = (item.display_name || '').trim();
+ const id = (item.user_id || '').trim();
+ if (name && id && name !== id) return `${name} (${id})`;
+ return name || id;
+}
+
+interface ApproverPickerProps {
+ value: string;
+ options: ApprovalApprover[];
+ onChange: (userId: string) => void;
+ disabled?: boolean;
+ loading?: boolean;
+ className?: string;
+}
+
+/** 审批人可搜索下拉:展示 display_name + user_id,支持按二者搜索。 */
+export function ApproverPicker({
+ value,
+ options,
+ onChange,
+ disabled = false,
+ loading = false,
+ className = '',
+}: ApproverPickerProps) {
+ const { t } = useTranslation();
+ const listId = useId();
+ const rootRef = useRef<HTMLDivElement>(null);
+ const searchRef = useRef<HTMLInputElement>(null);
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState('');
+
+ const selected = useMemo(
+ () => options.find((item) => item.user_id === value),
+ [options, value],
+ );
+ const filtered = useMemo(
+ () => options.filter((item) => matchesQuery(item, query)),
+ [options, query],
+ );
+
+ useEffect(() => {
+ if (!open) {
+ setQuery('');
+ return;
+ }
+ const timer = window.setTimeout(() => searchRef.current?.focus(), 0);
+ return () => window.clearTimeout(timer);
+ }, [open]);
+
+ useEffect(() => {
+ if (!open) return;
+ const onPointerDown = (event: MouseEvent) => {
+ if (rootRef.current && !rootRef.current.contains(event.target as Node)) {
+ setOpen(false);
+ }
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') setOpen(false);
+ };
+ document.addEventListener('mousedown', onPointerDown);
+ document.addEventListener('keydown', onKeyDown);
+ return () => {
+ document.removeEventListener('mousedown', onPointerDown);
+ document.removeEventListener('keydown', onKeyDown);
+ };
+ }, [open]);
+
+ const emptyHint = loading
+ ? t('common.loading')
+ : options.length === 0
+ ? t('agent.quota.expandApproverEmpty')
+ : t('agent.quota.expandApproverPlaceholder');
+
+ return (
+ <div className={`relative mb-3 ${className}`} ref={rootRef}>
+ <button
+ type="button"
+ className="flex w-full items-center justify-between gap-2 rounded-md border border-border bg-background px-3 py-2 text-left text-sm disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={disabled || loading || options.length === 0}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-controls={listId}
+ onClick={() => setOpen((current) => !current)}
+ >
+ <span className={selected ? 'truncate text-text' : 'truncate text-text-muted'}>
+ {selected ? formatSelected(selected) : emptyHint}
+ </span>
+ <ChevronDown className={`h-4 w-4 shrink-0 text-text-muted transition-transform ${open ? 'rotate-180' : ''}`} />
+ </button>
+
+ {open && !disabled && options.length > 0 ? (
+ <div
+ className="absolute left-0 right-0 top-[calc(100%+4px)] z-50 overflow-hidden rounded-md border border-border bg-card shadow-lg"
+ role="listbox"
+ id={listId}
+ >
+ <div className="flex items-center gap-2 border-b border-border px-3 py-2">
+ <Search className="h-3.5 w-3.5 shrink-0 text-text-muted" aria-hidden />
+ <input
+ ref={searchRef}
+ type="text"
+ className="w-full bg-transparent text-sm text-text outline-none placeholder:text-text-muted"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t('agent.quota.expandApproverSearch')}
+ aria-label={t('agent.quota.expandApproverSearch')}
+ />
+ </div>
+ <div className="max-h-52 overflow-y-auto py-1">
+ {filtered.length === 0 ? (
+ <div className="px-3 py-2 text-sm text-text-muted">
+ {t('agent.quota.expandApproverNoMatch')}
+ </div>
+ ) : (
+ filtered.map((item) => {
+ const active = item.user_id === value;
+ const name = (item.display_name || '').trim() || item.user_id;
+ return (
+ <button
+ key={item.user_id}
+ type="button"
+ role="option"
+ aria-selected={active}
+ className={`flex w-full flex-col items-start gap-0.5 px-3 py-2 text-left hover:bg-secondary/60 ${
+ active ? 'bg-secondary/40' : ''
+ }`}
+ onClick={() => {
+ onChange(item.user_id);
+ setOpen(false);
+ }}
+ >
+ <span className="text-sm font-medium text-text-strong break-all">{name}</span>
+ <span className="font-mono text-xs text-text-muted break-all">{item.user_id}</span>
+ </button>
+ );
+ })
+ )}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/common/TableColumnFilter.tsx b/jiuwenswarm/channels/web/frontend/src/components/common/TableColumnFilter.tsx
new file mode 100644
index 0000000000..a53477df1e
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/common/TableColumnFilter.tsx
@@ -0,0 +1,93 @@
+/**
+ * 表头列筛选:标签 + 漏斗图标,点击弹出单选菜单。
+ * value 为空串表示「全部 / 未筛选」。
+ * 供列表表格在 thead 内复用(对齐管理面 TableColumnFilter 交互)。
+ */
+
+import { useCallback, useRef, useState, type ReactNode } from 'react';
+import { useClickOutside } from '../CronPanel/useClickOutside';
+
+export type TableColumnFilterOption = {
+ value: string;
+ label: ReactNode;
+};
+
+export type TableColumnFilterProps = {
+ label: string;
+ value: string;
+ options: TableColumnFilterOption[];
+ onChange: (value: string) => void;
+ /** 仅展示筛选图标,不展示 label 文本(仍用于 aria-label) */
+ iconOnly?: boolean;
+ /** 下拉对齐:默认 left */
+ menuAlign?: 'left' | 'right';
+ className?: string;
+};
+
+export function TableColumnFilter({
+ label,
+ value,
+ options,
+ onChange,
+ iconOnly = false,
+ menuAlign = 'left',
+ className = '',
+}: TableColumnFilterProps) {
+ const [open, setOpen] = useState(false);
+ const hostRef = useRef<HTMLDivElement>(null);
+ const active = value !== '';
+ const dismiss = useCallback(() => setOpen(false), []);
+ useClickOutside(hostRef, open, dismiss);
+
+ return (
+ <div
+ ref={hostRef}
+ className={`relative inline-flex max-w-full items-center gap-1 ${open ? 'z-[2]' : ''} ${className}`}
+ data-testid="table-column-filter"
+ >
+ {!iconOnly ? <span className="truncate font-medium">{label}</span> : null}
+ <button
+ type="button"
+ aria-label={label}
+ aria-expanded={open}
+ className={`inline-flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-md border-0 bg-transparent transition-colors ${
+ active ? 'text-accent' : 'text-text-muted'
+ } ${open ? 'bg-bg-hover text-text' : 'hover:bg-bg-hover hover:text-text'}`}
+ onClick={() => setOpen((prev) => !prev)}
+ >
+ <svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3 4.5h18M7 9.75h10M10.5 15h3" />
+ </svg>
+ </button>
+ {open ? (
+ <div
+ role="menu"
+ className={`absolute top-[calc(100%+6px)] z-30 min-w-[148px] rounded-lg border border-border bg-card py-1.5 shadow-lg ${
+ menuAlign === 'right' ? 'right-0' : 'left-0'
+ }`}
+ >
+ {options.map((opt) => {
+ const selected = value === opt.value;
+ return (
+ <button
+ key={opt.value || '__all__'}
+ type="button"
+ role="menuitemradio"
+ aria-checked={selected}
+ className={`block w-full px-3 py-1.5 text-left text-sm hover:bg-bg-hover ${
+ selected ? 'bg-accent-subtle font-medium text-accent' : 'text-text'
+ }`}
+ onClick={() => {
+ onChange(opt.value);
+ setOpen(false);
+ }}
+ >
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/edition.ts b/jiuwenswarm/channels/web/frontend/src/edition.ts
index 43551f3182..1619f9b15e 100644
--- a/jiuwenswarm/channels/web/frontend/src/edition.ts
+++ b/jiuwenswarm/channels/web/frontend/src/edition.ts
@@ -11,7 +11,6 @@ export const isEnterprise = (): boolean => readEdition() === "enterprise";
export const ENTERPRISE_HIDDEN_NAV_ITEMS = [
"channels",
- "agents",
"teams",
"personalContext",
"extensions",
diff --git a/jiuwenswarm/channels/web/frontend/src/features/approvals/approvalsApi.ts b/jiuwenswarm/channels/web/frontend/src/features/approvals/approvalsApi.ts
new file mode 100644
index 0000000000..07e603cfb0
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/approvals/approvalsApi.ts
@@ -0,0 +1,111 @@
+/**
+ * 用户面通用审批 API(Manager ``/user-console/approvals/*``)。
+ * 扩容提交仍走 workspace/expand-requests;列表与撤回对本模块通用。
+ */
+
+import { managerAuthenticatedFetch } from '../../auth/manager/authSession';
+
+export type ApprovalStatus = 'pending' | 'approved' | 'rejected' | 'cancelled';
+
+export interface ApprovalApprover {
+ user_id: string;
+ display_name: string;
+}
+
+export interface ApprovalOrderItem {
+ order_num: string;
+ cluster_id?: string;
+ business_type: string;
+ title: string;
+ status: ApprovalStatus | string;
+ reason: string;
+ group_id?: string;
+ bot_id?: string;
+ applicant_id?: string;
+ approver_id?: string | null;
+ apply_data?: Record<string, unknown>;
+ result_data?: Record<string, unknown> | null;
+ latest_reject_comment?: string;
+ current_approvers: ApprovalApprover[];
+ created_at: string;
+ updated_at?: string;
+}
+
+interface ManagerEnvelope<T> {
+ code: number;
+ message?: string;
+ data: T;
+}
+
+async function managerJson<T>(path: string, init: RequestInit = {}): Promise<T> {
+ const response = await managerAuthenticatedFetch(path, {
+ ...init,
+ headers: {
+ Accept: 'application/json',
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
+ ...Object.fromEntries(new Headers(init.headers).entries()),
+ },
+ });
+ let body: unknown = null;
+ try {
+ body = await response.json();
+ } catch {
+ // keep null
+ }
+ if (!response.ok) {
+ const detail =
+ body && typeof body === 'object'
+ ? String(
+ (body as Record<string, unknown>).detail ||
+ (body as Record<string, unknown>).message ||
+ '',
+ )
+ : '';
+ throw new Error(detail || `HTTP ${response.status}`);
+ }
+ const envelope = body as ManagerEnvelope<T>;
+ if (!envelope || envelope.code !== 200) {
+ throw new Error(envelope?.message || 'manager request failed');
+ }
+ return envelope.data;
+}
+
+export async function listMyApprovals(options?: {
+ businessType?: string;
+ status?: string;
+ /** 匹配单号、标题、申请说明 */
+ search?: string;
+}): Promise<ApprovalOrderItem[]> {
+ const params = new URLSearchParams();
+ if (options?.businessType) params.set('business_type', options.businessType);
+ if (options?.status) params.set('status', options.status);
+ const search = options?.search?.trim();
+ if (search) params.set('search', search);
+ const query = params.toString() ? `?${params.toString()}` : '';
+ const payload = await managerJson<{ items?: ApprovalOrderItem[] }>(
+ `/manager-api/v1/user-console/approvals/mine${query}`,
+ );
+ return Array.isArray(payload?.items) ? payload.items : [];
+}
+
+/** 扩容申请可选审批人(持有 approval:act)。 */
+export async function listApproverCandidates(): Promise<ApprovalApprover[]> {
+ const payload = await managerJson<{ items?: ApprovalApprover[] }>(
+ '/manager-api/v1/user-console/approvals/candidates',
+ );
+ return Array.isArray(payload?.items) ? payload.items : [];
+}
+
+export async function cancelMyApproval(orderNum: string): Promise<{
+ order_num: string;
+ status: string;
+}> {
+ const payload = await managerJson<{ order_num?: string; status?: string }>(
+ `/manager-api/v1/user-console/approvals/${encodeURIComponent(orderNum)}/cancel`,
+ { method: 'POST', body: '{}' },
+ );
+ return {
+ order_num: String(payload?.order_num || orderNum),
+ status: String(payload?.status || 'cancelled'),
+ };
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/mainNavigationState.ts b/jiuwenswarm/channels/web/frontend/src/features/mainNavigationState.ts
index d834c0388b..f88b89e0eb 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/mainNavigationState.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/mainNavigationState.ts
@@ -12,7 +12,8 @@ export type MainNavKey =
| 'configpanel'
| 'browserpanel'
| 'updatepanel'
- | 'a2aingress';
+ | 'a2aingress'
+ | 'approvals';
export const MAIN_NAV_STORAGE_KEY = 'jiuwenswarm.active-main-nav';
@@ -31,6 +32,7 @@ const MAIN_NAV_KEYS = new Set<MainNavKey>([
'browserpanel',
'updatepanel',
'a2aingress',
+ 'approvals',
]);
export function parseStoredMainNav(raw: string | null, options: { blocked?: readonly MainNavKey[]; updaterEnabled?: boolean } = {}): MainNavKey {
diff --git a/jiuwenswarm/channels/web/frontend/src/features/workspace/workspaceApi.ts b/jiuwenswarm/channels/web/frontend/src/features/workspace/workspaceApi.ts
new file mode 100644
index 0000000000..7f336e4c52
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/workspace/workspaceApi.ts
@@ -0,0 +1,273 @@
+/**
+ * 工作空间管理 API(Gateway ``/api/v1/workspace/*``)。
+ * 列表/用量/删除/预览走 webRequest;下载为手写文件流。
+ */
+
+import { isEnterprise } from '../../edition';
+import {
+ getManagerAccessToken,
+ hasManagerSessionCredentials,
+ managerAuthenticatedFetch,
+} from '../../auth/manager/authSession';
+import { webRequest } from '../../services/webClient';
+import { buildRuntimeIdentityHeaders } from '../../services/runtimeScope';
+import { getGatewayHttpBase } from '../../utils/env';
+import { unwrapHttpUnary } from '../../services/webHttpClient';
+import type {
+ WorkspaceDeleteData,
+ WorkspaceExpandCreateResult,
+ WorkspacePreviewData,
+ WorkspaceTreeData,
+ WorkspaceUsageData,
+} from './workspaceTypes';
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+}
+
+function asEntryList(raw: unknown): WorkspaceTreeData {
+ if (!isRecord(raw)) {
+ return { relative_path: '', entries: [] };
+ }
+ const entriesRaw = Array.isArray(raw.entries) ? raw.entries : [];
+ const entries: WorkspaceTreeData['entries'] = [];
+ for (const item of entriesRaw) {
+ if (!isRecord(item)) continue;
+ if (typeof item.name !== 'string' || typeof item.relative_path !== 'string') continue;
+ entries.push({
+ name: item.name,
+ relative_path: item.relative_path,
+ is_dir: Boolean(item.is_dir),
+ size_bytes: typeof item.size_bytes === 'number' ? item.size_bytes : null,
+ mtime_ms: typeof item.mtime_ms === 'number' ? item.mtime_ms : 0,
+ ctime_ms: typeof item.ctime_ms === 'number' ? item.ctime_ms : 0,
+ zone: typeof item.zone === 'string' ? item.zone : 'other',
+ deletable: Boolean(item.deletable),
+ mime_hint: typeof item.mime_hint === 'string' ? item.mime_hint : null,
+ });
+ }
+ return {
+ relative_path: typeof raw.relative_path === 'string' ? raw.relative_path : '',
+ entries,
+ };
+}
+
+export async function fetchWorkspaceTree(relativePath = ''): Promise<WorkspaceTreeData> {
+ const params: Record<string, unknown> = {};
+ if (relativePath) {
+ params.relative_path = relativePath;
+ }
+ const payload = await webRequest<unknown>('workspace.tree', params, { timeoutMs: 60000 });
+ return asEntryList(payload);
+}
+
+export async function fetchWorkspaceUsage(): Promise<WorkspaceUsageData> {
+ const payload = await webRequest<WorkspaceUsageData>('workspace.usage', {}, { timeoutMs: 60000 });
+ return {
+ used_bytes: Number(payload?.used_bytes ?? 0),
+ limit_bytes: Number(payload?.limit_bytes ?? 0),
+ percent: Number(payload?.percent ?? 0),
+ status: (payload?.status as WorkspaceUsageData['status']) || 'ok',
+ user_id: payload?.user_id,
+ group_id: payload?.group_id,
+ bot_id: payload?.bot_id,
+ source_policy_id: payload?.source_policy_id,
+ };
+}
+
+export async function deleteWorkspaceEntries(
+ relativePaths: string[],
+): Promise<WorkspaceDeleteData> {
+ const payload = await webRequest<WorkspaceDeleteData>(
+ 'workspace.entries.delete',
+ { relative_paths: relativePaths },
+ { timeoutMs: 120000 },
+ );
+ return {
+ results: Array.isArray(payload?.results) ? payload.results : [],
+ };
+}
+
+export async function previewWorkspaceFile(
+ relativePath: string,
+ maxBytes?: number,
+): Promise<WorkspacePreviewData> {
+ const params: Record<string, unknown> = { relative_path: relativePath };
+ if (maxBytes != null) {
+ params.max_bytes = maxBytes;
+ }
+ const payload = await webRequest<WorkspacePreviewData>('workspace.preview', params, {
+ timeoutMs: 60000,
+ });
+ return {
+ relative_path: String(payload?.relative_path || relativePath),
+ truncated: Boolean(payload?.truncated),
+ content: payload?.content == null ? null : String(payload.content),
+ };
+}
+
+interface ManagerEnvelope<T> {
+ code: number;
+ message?: string;
+ data: T;
+}
+
+async function managerJson<T>(path: string, init: RequestInit = {}): Promise<T> {
+ const response = await managerAuthenticatedFetch(path, {
+ ...init,
+ headers: {
+ Accept: 'application/json',
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
+ ...Object.fromEntries(new Headers(init.headers).entries()),
+ },
+ });
+ let body: unknown = null;
+ try {
+ body = await response.json();
+ } catch {
+ // keep null
+ }
+ if (!response.ok) {
+ const detail =
+ body && typeof body === 'object'
+ ? String((body as Record<string, unknown>).detail || (body as Record<string, unknown>).message || '')
+ : '';
+ throw new Error(detail || `HTTP ${response.status}`);
+ }
+ const envelope = body as ManagerEnvelope<T>;
+ if (!envelope || envelope.code !== 200) {
+ throw new Error(envelope?.message || 'manager request failed');
+ }
+ return envelope.data;
+}
+
+export async function createWorkspaceExpandRequest(input: {
+ jiuwenclawId: string;
+ groupId: string;
+ botId: string;
+ requestedLimitBytes: number;
+ reason: string;
+ usedBytes?: number;
+ approverId: string;
+}): Promise<WorkspaceExpandCreateResult> {
+ const payload = await managerJson<WorkspaceExpandCreateResult>(
+ '/manager-api/v1/user-console/workspace/expand-requests',
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ jiuwenclaw_id: input.jiuwenclawId,
+ group_id: input.groupId,
+ bot_id: input.botId,
+ requested_limit_bytes: input.requestedLimitBytes,
+ reason: input.reason,
+ used_bytes: input.usedBytes,
+ approver_id: input.approverId,
+ }),
+ },
+ );
+ return {
+ order_num: String(payload?.order_num || ''),
+ status: String(payload?.status || 'pending'),
+ };
+}
+
+function nextRequestId(): string {
+ return `req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
+}
+
+function parseFilenameFromDisposition(header: string | null): string | null {
+ if (!header) return null;
+ const star = /filename\*=UTF-8''([^;]+)/i.exec(header);
+ if (star?.[1]) {
+ try {
+ return decodeURIComponent(star[1].trim());
+ } catch {
+ return star[1].trim();
+ }
+ }
+ const plain = /filename="([^"]+)"/i.exec(header) || /filename=([^;]+)/i.exec(header);
+ return plain?.[1]?.trim() || null;
+}
+
+async function authenticatedFetch(input: RequestInfo | URL, init: RequestInit): Promise<Response> {
+ if (isEnterprise() && hasManagerSessionCredentials()) {
+ const headers = new Headers(init.headers);
+ const authorization = headers.get('Authorization');
+ const managerAccessToken = getManagerAccessToken();
+ if (
+ authorization &&
+ authorization !== (managerAccessToken ? `Bearer ${managerAccessToken}` : null)
+ ) {
+ return fetch(input, init);
+ }
+ return managerAuthenticatedFetch(input, init);
+ }
+ return fetch(input, init);
+}
+
+/** 触发浏览器下载;失败时抛出带 message 的 Error。 */
+export async function downloadWorkspaceEntry(relativePath: string): Promise<void> {
+ const requestId = nextRequestId();
+ const base = getGatewayHttpBase().replace(/\/+$/, '');
+ const url = `${base}/workspace/download?relative_path=${encodeURIComponent(relativePath)}`;
+ const response = await authenticatedFetch(url, {
+ method: 'GET',
+ headers: {
+ ...buildRuntimeIdentityHeaders(requestId, {}),
+ Accept: '*/*',
+ },
+ });
+
+ const contentType = (response.headers.get('content-type') || '').toLowerCase();
+ if (!response.ok || contentType.includes('application/json')) {
+ const text = await response.text();
+ let message = `download failed (${response.status})`;
+ try {
+ const unwrapped = unwrapHttpUnary(JSON.parse(text) as unknown, response.status);
+ if (!unwrapped.ok) {
+ message = unwrapped.message;
+ }
+ } catch {
+ if (text.trim()) message = text.slice(0, 200);
+ }
+ throw new Error(message);
+ }
+
+ const blob = await response.blob();
+ const filename =
+ parseFilenameFromDisposition(response.headers.get('content-disposition')) ||
+ relativePath.split('/').pop() ||
+ 'download.bin';
+ const objectUrl = URL.createObjectURL(blob);
+ try {
+ const anchor = document.createElement('a');
+ anchor.href = objectUrl;
+ anchor.download = filename;
+ anchor.rel = 'noopener';
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+ } finally {
+ URL.revokeObjectURL(objectUrl);
+ }
+}
+
+export function formatBytes(bytes: number | null | undefined): string {
+ const n = Number(bytes);
+ if (!Number.isFinite(n) || n < 0) return '—';
+ if (n < 1024) return `${Math.round(n)} B`;
+ const units = ['KB', 'MB', 'GB', 'TB'];
+ let value = n / 1024;
+ let unit = 0;
+ while (value >= 1024 && unit < units.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ const digits = value >= 100 ? 0 : value >= 10 ? 1 : 2;
+ return `${value.toFixed(digits)} ${units[unit]}`;
+}
+
+export function formatPercent(percent: number): string {
+ if (!Number.isFinite(percent)) return '0%';
+ return `${Math.min(999, Math.max(0, percent)).toFixed(percent >= 10 ? 0 : 1)}%`;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/workspace/workspaceTypes.ts b/jiuwenswarm/channels/web/frontend/src/features/workspace/workspaceTypes.ts
new file mode 100644
index 0000000000..b490f33e13
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/workspace/workspaceTypes.ts
@@ -0,0 +1,65 @@
+/** 工作空间管理(§2)类型。 */
+
+export type WorkspaceZone =
+ | 'session_workspace'
+ | 'session_todo'
+ | 'session_meta'
+ | 'skills'
+ | 'role_md'
+ | 'memory'
+ | 'runtime'
+ | 'artifact'
+ | 'other';
+
+export type WorkspaceQuotaStatus = 'ok' | 'warn' | 'block';
+
+export interface WorkspaceEntry {
+ name: string;
+ relative_path: string;
+ is_dir: boolean;
+ size_bytes: number | null;
+ mtime_ms: number;
+ ctime_ms: number;
+ zone: WorkspaceZone | string;
+ deletable: boolean;
+ mime_hint: string | null;
+}
+
+export interface WorkspaceTreeData {
+ relative_path: string;
+ entries: WorkspaceEntry[];
+}
+
+export interface WorkspaceUsageData {
+ user_id?: string;
+ group_id?: string;
+ bot_id?: string;
+ used_bytes: number;
+ limit_bytes: number;
+ percent: number;
+ status: WorkspaceQuotaStatus;
+ source_policy_id?: string;
+ /** limit_bytes === -1 时为 true;前端优先读此字段 */
+ unlimited?: boolean;
+}
+
+export interface WorkspaceDeleteResult {
+ relative_path: string;
+ ok: boolean;
+ error: string | null;
+}
+
+export interface WorkspaceDeleteData {
+ results: WorkspaceDeleteResult[];
+}
+
+export interface WorkspacePreviewData {
+ relative_path: string;
+ truncated: boolean;
+ content: string | null;
+}
+
+export interface WorkspaceExpandCreateResult {
+ order_num: string;
+ status: string;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index 01bded9408..96915ae099 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -6,6 +6,7 @@
import { useEffect, useRef, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { isWorkspaceQuotaError } from '../multi-session/state/createConversationSession';
import {
ConnectionAckPayload,
WebConnectOptions,
@@ -3556,8 +3557,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
if (!sessionId) return;
if (shouldDropDuplicatedEvent('chat.error', payload)) return;
useChatStore.getState().setThinking(sessionId, false);
- const errorMsg =
+ const rawError =
typeof payload.error === 'string' ? payload.error : t('network.unknownError');
+ const errorMsg = isWorkspaceQuotaError(payload)
+ ? t('multiSession.errors.quotaExceeded')
+ : rawError;
// 忽略 "invalid page_idx or session history not found" 错误,因为这是新会话的正常情况
if (errorMsg.includes('invalid page_idx or session history not found')) {
useChatStore.getState().setLoadingHistory(sessionId, false);
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index e6010139be..f02da49305 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -11,6 +11,8 @@
"saveSuccess": "Saved successfully",
"error": "Error",
"ok": "OK",
+ "yes": "Yes",
+ "no": "No",
"and": "and",
"modify": "Modify",
"delete": "Delete",
@@ -22,6 +24,64 @@
"pageSize": "Per page",
"jumpTo": "Go to",
"go": "Go"
+ },
+ "all": "All"
+ },
+ "approvals": {
+ "myTitle": "My requests",
+ "mySubtitle": "View and manage approval requests you submitted",
+ "unavailable": "Requests are unavailable in the current environment",
+ "empty": "No requests yet",
+ "loadFailed": "Failed to load requests",
+ "cancelFailed": "Failed to cancel request",
+ "cancel": "Cancel",
+ "resubmit": "Edit and resubmit",
+ "resubmitTitle": "Resubmit request",
+ "resubmitHint": "Update the request and resubmit. This revises the same request.",
+ "resubmitSubmit": "Resubmit",
+ "resubmitFailed": "Failed to resubmit",
+ "rejectComment": "Rejection comment",
+ "currentQuota": "Current quota",
+ "approvers": "Approvers",
+ "copyLink": "Copy approval link",
+ "copyLinkSuccess": "Approval link copied",
+ "copyLinkFailed": "Failed to copy approval link",
+ "copyOrderNum": "Click to copy order number",
+ "copyOrderNumSuccess": "Order number copied",
+ "copyOrderNumFailed": "Failed to copy order number",
+ "stats": {
+ "total": "Total {{count}}"
+ },
+ "search": {
+ "placeholder": "Search by order number, title, or reason",
+ "noResults": "No matching requests"
+ },
+ "filter": {
+ "reset": "Clear filters"
+ },
+ "table": {
+ "title": "Title",
+ "orderNum": "Order No.",
+ "type": "Type",
+ "summary": "Summary",
+ "requestedQuota": "Requested quota",
+ "approver": "Current approver",
+ "reason": "Reason",
+ "status": "Status",
+ "createdAt": "Submitted",
+ "actions": "Actions"
+ },
+ "status": {
+ "pending": "Pending",
+ "approved": "Approved",
+ "rejected": "Rejected",
+ "cancelled": "Cancelled"
+ },
+ "business": {
+ "workspace_quota_expand": "Workspace expansion"
+ },
+ "summary": {
+ "quotaExpand": "Requested quota {{size}}"
}
},
"a2ui": {
@@ -35,6 +95,7 @@
"chat": "Chat",
"work": "Work",
"agent": "Agent",
+ "workspace": "Space",
"teams": "Teams",
"sessions": "Sessions",
"cron": "Scheduled Tasks",
@@ -50,7 +111,8 @@
"logs": "Logs",
"update": "Updates",
"a2aIngress": "A2A Control Center",
- "personalContext": "Personal\nContext"
+ "personalContext": "Personal\nContext",
+ "approvals": "Requests"
},
"team": {
"members": "Team Members",
@@ -562,6 +624,7 @@
"apply": "Apply",
"switching": "Switching...",
"logout": "Sign out",
+ "switchToManager": "Go to Manager",
"customRequired": "Please fill in bot_id, group_id, user_id, and jiuwenclaw_id",
"noMatch": "No matches",
"pleaseSelect": "Please select"
@@ -2194,8 +2257,8 @@
}
},
"agent": {
- "title": "Agent Management",
- "subtitle": "View agent workspace files and memory content",
+ "title": "Workspace",
+ "subtitle": "View usage, clean deletable files, and preview or download workspace content",
"root": "Root",
"workspace": "Workspace",
"workspaceMeta": "{{directories}} directories, {{files}} files",
@@ -2204,14 +2267,86 @@
"previewableCount": "{{count}} previewable",
"refresh": "Refresh List",
"empty": "No files",
+ "emptyDeletable": "Nothing deletable (cleanup zones are empty)",
"notPreviewable": "Not previewable",
- "contentPreview": "Content Preview",
- "selectMarkdown": "Select a previewable file on the left to view",
- "selectMarkdownContent": "Select a previewable file on the left to view its content",
+ "contentPreview": "Details & preview",
+ "selectMarkdown": "Select a file on the left to view",
+ "selectMarkdownContent": "Select a file on the left to view its content",
"markdownOnly": "Only Markdown/JSON (.md/.mdx/.json) preview is supported",
+ "selectEntry": "Select a file or folder on the left to view metadata",
+ "selectEntryHint": "Click an entry to see path, zone, and size. Files can be previewed or downloaded.",
+ "dirSelectedHint": "Folder selected. Download as zip, or delete the subtree when allowed.",
+ "binaryPreview": "Binary files have no text preview. Use Download.",
+ "previewTruncated": "Preview truncated. Download for the full file.",
+ "previewEmpty": "No preview content",
+ "deletable": "Deletable",
+ "filterDeletable": "Deletable only",
+ "download": "Download",
+ "delete": "Delete",
+ "notDeletableReason": "Protected zone — cannot delete",
+ "confirmDelete": "Delete \"{{name}}\"? This cannot be undone.",
+ "deleteConfirmTitle": "Confirm delete",
+ "quota": {
+ "title": "Workspace usage",
+ "ok": "OK",
+ "warn": "Near limit",
+ "block": "Full",
+ "unlimited": "Unlimited",
+ "unavailable": "Usage unavailable",
+ "requestExpand": "Request expansion",
+ "expandHint": "Submit an expansion request to the admin plane",
+ "expandIdleHint": "Expansion is not needed while usage is healthy",
+ "expandUnlimitedHint": "Quota is unlimited; expansion is not applicable",
+ "expandSoon": "Expansion requests will connect to admin approval soon. Clean deletable files first, or ask an admin to raise the quota.",
+ "expandTitle": "Request workspace expansion",
+ "expandDialogHint": "Enter the target quota (GiB) and a reason. The new limit takes effect after approval.",
+ "expandLimitLabel": "Target quota (GiB)",
+ "expandReasonLabel": "Reason",
+ "expandApproverLabel": "Approver",
+ "expandApproverPlaceholder": "Select an approver",
+ "expandApproverSearch": "Search by user ID or display name",
+ "expandApproverNoMatch": "No matching approvers",
+ "expandApproverRequired": "Please select an approver",
+ "expandApproverEmpty": "No approvers available. Ask an admin to grant approval permission.",
+ "expandApproverLoadFailed": "Failed to load approvers",
+ "expandSubmit": "Submit request",
+ "expandInvalidLimit": "Enter a valid target quota in GiB",
+ "expandReasonRequired": "Please provide a reason",
+ "expandMustIncrease": "Target quota must be greater than the current limit",
+ "expandFailed": "Failed to submit expansion request",
+ "expandSubmittedTitle": "Request submitted",
+ "expandSubmittedBody": "Your expansion request was submitted. The new quota takes effect after approval. Track progress under <approvals>My Requests</approvals>.",
+ "expandViewApprovals": "View My Requests",
+ "expandSubmitted": "Expansion request submitted. The new quota takes effect after approval — track progress under My Requests in the sidebar.",
+ "expandContextRequired": "Select an Agent context (cluster and bot) before requesting expansion",
+ "openWorkspace": "Open workspace",
+ "chatWarnTitle": "Workspace nearly full",
+ "chatWarnBody": "Over 80% of quota used. Clean session artifacts or request expansion.",
+ "chatBlockTitle": "Workspace full — writes blocked",
+ "chatBlockBody": "Quota exhausted. Clean deletable files or request expansion before sending messages."
+ },
+ "meta": {
+ "zone": "Zone",
+ "size": "Size",
+ "mtime": "Modified",
+ "deletable": "Deletable"
+ },
+ "zones": {
+ "session_workspace": "Session artifacts",
+ "session_todo": "Session todos",
+ "session_meta": "Session metadata",
+ "skills": "Skills",
+ "role_md": "Role files",
+ "memory": "Memory",
+ "runtime": "Runtime",
+ "artifact": "Attachments",
+ "other": "Other"
+ },
"errors": {
"refreshFailed": "Refresh failed: unable to rebuild the agent file index. Check the generator script logs.",
- "loadFailed": "Unable to read the agent file list. Check whether agent/jiuwenclaw_workspace/agent-data.json has been generated."
+ "loadFailed": "Unable to list the workspace. Ensure the Agent is ready.",
+ "deleteFailed": "Delete failed",
+ "downloadFailed": "Download failed"
}
},
"fileViewer": {
@@ -2650,7 +2785,13 @@
"runtime": { "processing": "Processing" },
"deleteDialog": { "title": "Delete", "description": "Delete “<name>{{title}}</name>”? This action cannot be undone." },
"notFound": { "title": "Conversation not found or deleted", "newConversation": "New conversation" },
- "errors": { "delete": "Failed to delete conversation", "create": "Failed to create conversation", "send": "Failed to send message" }
+ "errors": {
+ "delete": "Failed to delete conversation",
+ "create": "Failed to create conversation",
+ "quotaExceededTitle": "Workspace is full",
+ "quotaExceeded": "A new conversation cannot be created. Clean deletable files in Space, or request more quota, then try again.",
+ "send": "Failed to send message"
+ }
},
"mermaid": {
"image": "Image",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 1095a0912f..575ad54dbd 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -11,6 +11,8 @@
"saveSuccess": "保存成功",
"error": "错误",
"ok": "确定",
+ "yes": "是",
+ "no": "否",
"and": "和",
"modify": "修改",
"delete": "删除",
@@ -22,6 +24,64 @@
"pageSize": "每页",
"jumpTo": "跳至",
"go": "确定"
+ },
+ "all": "全部"
+ },
+ "approvals": {
+ "myTitle": "我的申请",
+ "mySubtitle": "查看并管理本人提交的审批单",
+ "unavailable": "当前环境无法查看申请记录",
+ "empty": "暂无申请记录",
+ "loadFailed": "加载申请列表失败",
+ "cancelFailed": "撤回申请失败",
+ "cancel": "撤回",
+ "resubmit": "编辑并重新提交",
+ "resubmitTitle": "重新提交申请",
+ "resubmitHint": "修改后重新提交,将更新同一张申请单。",
+ "resubmitSubmit": "重新提交",
+ "resubmitFailed": "重新提交失败",
+ "rejectComment": "驳回意见",
+ "currentQuota": "当前配额",
+ "approvers": "当前审批人",
+ "copyLink": "复制审批链接",
+ "copyLinkSuccess": "审批链接已复制",
+ "copyLinkFailed": "复制审批链接失败",
+ "copyOrderNum": "点击复制单号",
+ "copyOrderNumSuccess": "单号已复制",
+ "copyOrderNumFailed": "复制单号失败",
+ "stats": {
+ "total": "申请总数 {{count}}"
+ },
+ "search": {
+ "placeholder": "搜索单号、标题或申请说明",
+ "noResults": "没有符合条件的申请"
+ },
+ "filter": {
+ "reset": "清除筛选"
+ },
+ "table": {
+ "title": "标题",
+ "orderNum": "单号",
+ "type": "类型",
+ "summary": "摘要",
+ "requestedQuota": "申请配额",
+ "approver": "当前审批人",
+ "reason": "申请说明",
+ "status": "状态",
+ "createdAt": "提交时间",
+ "actions": "操作"
+ },
+ "status": {
+ "pending": "审批中",
+ "approved": "已通过",
+ "rejected": "已驳回",
+ "cancelled": "已撤回"
+ },
+ "business": {
+ "workspace_quota_expand": "工作区扩容"
+ },
+ "summary": {
+ "quotaExpand": "申请配额 {{size}}"
}
},
"a2ui": {
@@ -35,6 +95,7 @@
"chat": "对话",
"work": "工作",
"agent": "智能体",
+ "workspace": "空间",
"teams": "团队",
"sessions": "会话",
"cron": "定时任务",
@@ -50,7 +111,8 @@
"logs": "日志",
"update": "更新",
"a2aIngress": "A2A 调度中心",
- "personalContext": "个人\n上下文"
+ "personalContext": "个人\n上下文",
+ "approvals": "申请"
},
"team": {
"members": "团队成员",
@@ -563,6 +625,7 @@
"apply": "应用",
"switching": "正在切换...",
"logout": "注销登录",
+ "switchToManager": "进入管理面",
"customRequired": "请填写 bot_id、group_id、user_id、jiuwenclaw_id",
"noMatch": "没有匹配项",
"pleaseSelect": "请选择"
@@ -2181,24 +2244,96 @@
}
},
"agent": {
- "title": "智能体管理",
- "subtitle": "查看智能体工作区文件与记忆内容",
+ "title": "工作空间管理",
+ "subtitle": "查看用量、清理可删文件,并预览或下载工作空间内容",
"root": "根目录",
- "workspace": "工作区",
+ "workspace": "工作空间",
"workspaceMeta": "{{directories}} 个目录,{{files}} 个文件",
"directoryCount": "{{count}} 个目录",
"fileCount": "{{count}} 个文件",
"previewableCount": "{{count}} 个可预览",
"refresh": "刷新列表",
"empty": "暂无文件",
+ "emptyDeletable": "暂无可删除内容(清理区为空)",
"notPreviewable": "不可预览",
- "contentPreview": "内容预览",
- "selectMarkdown": "选择左侧可预览文件查看",
- "selectMarkdownContent": "请选择左侧可预览文件查看内容",
+ "contentPreview": "详情与预览",
+ "selectMarkdown": "选择左侧文件查看",
+ "selectMarkdownContent": "请选择左侧文件查看内容",
"markdownOnly": "仅支持 Markdown/JSON(.md/.mdx/.json)预览",
+ "selectEntry": "选择左侧文件或目录查看元信息",
+ "selectEntryHint": "点击左侧条目查看路径、zone、大小等信息;文件可预览与下载",
+ "dirSelectedHint": "已选中目录。可下载为 zip,或在可删时删除整棵子树。",
+ "binaryPreview": "二进制文件不展示正文,请使用下载。",
+ "previewTruncated": "内容已截断,完整文件请下载。",
+ "previewEmpty": "暂无预览内容",
+ "deletable": "可删",
+ "filterDeletable": "仅可删除",
+ "download": "下载",
+ "delete": "删除",
+ "notDeletableReason": "该 zone 受保护,不可删除",
+ "confirmDelete": "确认删除「{{name}}」?此操作不可恢复。",
+ "deleteConfirmTitle": "删除确认",
+ "quota": {
+ "title": "工作空间用量",
+ "ok": "正常",
+ "warn": "接近上限",
+ "block": "已满额",
+ "unlimited": "无限制",
+ "unavailable": "暂无法读取用量",
+ "requestExpand": "申请扩容",
+ "expandHint": "向管理面提交扩容申请",
+ "expandIdleHint": "用量正常时无需扩容",
+ "expandUnlimitedHint": "当前为无限制配额,无需扩容",
+ "expandSoon": "扩容申请将对接管理面审批(即将上线)。当前请先清理可删文件,或联系管理员调整配额。",
+ "expandTitle": "申请工作区扩容",
+ "expandDialogHint": "请填写目标配额(GiB)与申请说明。审批通过后配额才会生效。",
+ "expandLimitLabel": "目标配额(GiB)",
+ "expandReasonLabel": "申请说明",
+ "expandApproverLabel": "审批人",
+ "expandApproverPlaceholder": "请选择审批人",
+ "expandApproverSearch": "搜索用户 ID 或显示名",
+ "expandApproverNoMatch": "没有匹配的审批人",
+ "expandApproverRequired": "请选择审批人",
+ "expandApproverEmpty": "暂无可选审批人,请联系管理员配置审批权限",
+ "expandApproverLoadFailed": "加载审批人列表失败",
+ "expandSubmit": "提交申请",
+ "expandInvalidLimit": "请输入有效的目标配额(GiB)",
+ "expandReasonRequired": "请填写申请说明",
+ "expandMustIncrease": "目标配额必须大于当前生效配额",
+ "expandFailed": "提交扩容申请失败",
+ "expandSubmittedTitle": "申请已提交",
+ "expandSubmittedBody": "扩容申请已提交,审批通过后配额将自动生效。可在<approvals>我的申请</approvals>查看进度。",
+ "expandViewApprovals": "查看我的申请",
+ "expandSubmitted": "扩容申请已提交。审批通过后配额将自动生效,可在侧栏「我的申请」查看进度。",
+ "expandContextRequired": "请先选择 Agent 上下文(集群与 Bot)后再申请扩容",
+ "openWorkspace": "打开工作空间",
+ "chatWarnTitle": "工作空间即将用尽",
+ "chatWarnBody": "已超过 80% 配额,建议清理会话产物或申请扩容。",
+ "chatBlockTitle": "工作空间已满,无法继续写入",
+ "chatBlockBody": "已用尽配额。请清理可删文件或申请扩容后再发送消息。"
+ },
+ "meta": {
+ "zone": "分区",
+ "size": "大小",
+ "mtime": "修改时间",
+ "deletable": "可删除"
+ },
+ "zones": {
+ "session_workspace": "会话产物",
+ "session_todo": "会话待办",
+ "session_meta": "会话元数据",
+ "skills": "技能",
+ "role_md": "角色文件",
+ "memory": "记忆",
+ "runtime": "运行时",
+ "artifact": "附件",
+ "other": "其他"
+ },
"errors": {
"refreshFailed": "刷新失败:无法重建 agent 文件索引,请检查生成脚本日志。",
- "loadFailed": "无法读取 agent 文件列表,请检查 agent/jiuwenclaw_workspace/agent-data.json 是否已生成。"
+ "loadFailed": "无法读取工作空间目录,请确认 Agent 已就绪。",
+ "deleteFailed": "删除失败",
+ "downloadFailed": "下载失败"
}
},
"fileViewer": {
@@ -2640,7 +2775,13 @@
"runtime": { "processing": "处理中" },
"deleteDialog": { "title": "删除", "description": "确定删除“<name>{{title}}</name>”吗?此操作不可撤销。" },
"notFound": { "title": "对话不存在或已删除", "newConversation": "新建对话" },
- "errors": { "delete": "删除对话失败", "create": "创建对话失败", "send": "发送消息失败" }
+ "errors": {
+ "delete": "删除对话失败",
+ "create": "创建对话失败",
+ "quotaExceededTitle": "工作空间已满",
+ "quotaExceeded": "无法创建新对话。请先到「空间」清理可删除文件,或申请扩容后再试。",
+ "send": "发送消息失败"
+ }
},
"mermaid": {
"image": "图片",
diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/dialogs/Dialogs.tsx b/jiuwenswarm/channels/web/frontend/src/multi-session/dialogs/Dialogs.tsx
index 2a6f93c684..26f2fc534f 100644
--- a/jiuwenswarm/channels/web/frontend/src/multi-session/dialogs/Dialogs.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/dialogs/Dialogs.tsx
@@ -41,6 +41,27 @@ function DialogActions({ busy, danger = false, confirmLabel, onCancel, onConfirm
);
}
+interface NoticeDialogProps {
+ title: string;
+ message?: string;
+ confirmLabel?: string;
+ onClose: () => void;
+}
+
+export function NoticeDialog({ title, message, confirmLabel, onClose }: NoticeDialogProps) {
+ const { t } = useTranslation();
+ return (
+ <DialogShell title={title} onCancel={onClose}>
+ {message ? <p>{message}</p> : null}
+ <div className="conversation-dialog__actions">
+ <button type="button" className="is-primary" onClick={onClose}>
+ {confirmLabel || t('common.ok')}
+ </button>
+ </div>
+ </DialogShell>
+ );
+}
+
export function DeleteDialog({
title,
dialogTitle,
diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/state/createConversationSession.ts b/jiuwenswarm/channels/web/frontend/src/multi-session/state/createConversationSession.ts
index 81259258c4..7ea8584a78 100644
--- a/jiuwenswarm/channels/web/frontend/src/multi-session/state/createConversationSession.ts
+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/state/createConversationSession.ts
@@ -47,6 +47,17 @@ function errorCode(error: unknown): string | undefined {
return typeof code === 'string' ? code : undefined;
}
+export function isWorkspaceQuotaError(error: unknown): boolean {
+ if (typeof error === 'string') {
+ return error.includes('WORKSPACE_QUOTA_EXCEEDED');
+ }
+ if (!error || typeof error !== 'object') return false;
+ const record = error as { code?: unknown; message?: unknown; error?: unknown };
+ return [record.code, record.message, record.error].some(
+ (value) => typeof value === 'string' && value.includes('WORKSPACE_QUOTA_EXCEEDED'),
+ );
+}
+
export function isRequestTimeoutError(error: unknown): boolean {
return errorCode(error) === 'REQUEST_TIMEOUT';
}
diff --git a/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx b/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
index 12504a8bc3..32a6ff28d2 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/services/enterpriseContext.tsx
@@ -21,6 +21,8 @@ export type EnterpriseContextSnapshot = {
};
export type EnterpriseContextValue = EnterpriseContextSnapshot & {
+ /** 有管理面资格时展示「进入管理面」;普通用户为 false。 */
+ managerAccess: boolean;
contextError: string;
contextSwitching: boolean;
onContextChange: (key: string) => void;
@@ -30,6 +32,7 @@ export type EnterpriseContextValue = EnterpriseContextSnapshot & {
userId: string;
jiuwenclawId: string;
}) => void;
+ onSwitchToManager: () => void;
onLogout: () => void;
};
diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
index 5dd6d038f6..53261c788a 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
@@ -139,6 +139,10 @@ const ROUTES: Record<string, RouteRow> = {
'project.remove': { verb: 'DELETE', path: '/projects/{project_id}', kind: 'unary' },
'project.restore': { verb: 'POST', path: '/projects/actions/restore', kind: 'unary' },
'project.pinned_sessions': { verb: 'GET', path: '/projects/pinned-sessions', kind: 'unary' },
+ 'workspace.tree': { verb: 'GET', path: '/workspace/tree', kind: 'unary' },
+ 'workspace.usage': { verb: 'GET', path: '/workspace/usage', kind: 'unary' },
+ 'workspace.entries.delete': { verb: 'DELETE', path: '/workspace/entries', kind: 'unary' },
+ 'workspace.preview': { verb: 'GET', path: '/workspace/preview', kind: 'unary' },
};
const PATH_PLACEHOLDER = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
index b383363b5b..12e176e0b1 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
@@ -36,6 +36,8 @@ INSTANCE_PURGE_TABLES: tuple[str, ...] = (
"agent_template",
"instance_agent_resource",
"log_masking_rule",
+ "workspace_quota_policy",
+ "workspace_quota_usage",
"logging_config",
"task_memory_config",
"audit_log_config",
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/quota/__init__.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/quota/__init__.py
new file mode 100644
index 0000000000..ab59c6e7ea
--- /dev/null
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/quota/__init__.py
@@ -0,0 +1,6 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
+"""配额业务包(workspace-quota 等)。"""
+
+from .workspace_quota_policy import WorkspaceQuotaPolicyService
+
+__all__ = ("WorkspaceQuotaPolicyService",)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/quota/workspace_quota_policy.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/quota/workspace_quota_policy.py
new file mode 100644
index 0000000000..ac72bad9c5
--- /dev/null
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/quota/workspace_quota_policy.py
@@ -0,0 +1,182 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
+
+"""工作区配额策略:Manager 按 policy_id upsert / 删除 Gateway 副本。"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from jiuwenswarm.gateway.config.enterprise.expressions import validate_match_expr
+from jiuwenswarm.gateway.config.enterprise.tables.quota_models import (
+ WORKSPACE_QUOTA_POLICY_TABLE_DEF,
+)
+
+from ...infrastructure.repository_access import require_enterprise_repository
+from ...infrastructure.utils import parse_iso_datetime, utc_now
+from ...schemas.quota_schemas import PolicyUpsertRequest
+
+_TABLE = WORKSPACE_QUOTA_POLICY_TABLE_DEF.table_name
+_PAGE = 500
+
+
+def _canonical_match_expr(value: Any) -> Any:
+ """与 Manager 入库形态对齐:全匹配为 ``[]``,单条为字符串,多条 OR 为字符串列表。"""
+ if value is None:
+ return []
+ if isinstance(value, list):
+ parts: list[str] = []
+ for item in value:
+ if item is None:
+ continue
+ text = str(item).strip()
+ if text:
+ parts.append(text)
+ if not parts:
+ return []
+ if len(parts) == 1:
+ return _canonical_string(parts[0])
+ return parts
+ if isinstance(value, str):
+ return _canonical_string(value.strip())
+ text = str(value).strip()
+ return _canonical_string(text) if text else []
+
+
+def _canonical_string(text: str) -> Any:
+ if not text:
+ return []
+ if text.startswith("["):
+ try:
+ parsed = json.loads(text)
+ except json.JSONDecodeError:
+ parsed = None
+ else:
+ if isinstance(parsed, list):
+ return _canonical_match_expr(parsed)
+ return text
+
+
+def _match_key(expr: Any) -> str:
+ return json.dumps(_canonical_match_expr(expr), ensure_ascii=False, separators=(",", ":"))
+
+
+def _is_full_match(expr: Any) -> bool:
+ canon = _canonical_match_expr(expr)
+ if canon == []:
+ return True
+ if not isinstance(canon, str):
+ return False
+ return not any(marker in canon for marker in ("==", "!=", " in "))
+
+
+def _validated_expr(value: Any) -> Any:
+ canon = _canonical_match_expr(value)
+ validate_match_expr(canon)
+ return canon
+
+
+class WorkspaceQuotaPolicyService:
+ async def upsert(self, body: dict[str, Any]) -> None:
+ if not isinstance(body, dict):
+ raise ValueError("workspace quota policy upsert requires an object")
+ req = PolicyUpsertRequest.model_validate(body)
+ expr = _validated_expr(req.match_expr)
+ pid = req.policy_id.strip()
+ enabled = bool(req.enabled)
+ priority = int(req.priority)
+ repo = require_enterprise_repository(_TABLE)
+ existing = await repo.get(policy_id=pid)
+ if enabled:
+ await self._assert_unique(repo, expr, priority, exclude_policy_id=pid)
+ now = utc_now()
+ source = req.source
+ source_order_num = req.source_order_num
+ if existing is None:
+ await repo.create(
+ {
+ "policy_id": pid,
+ "policy_name": req.policy_name,
+ "policy_desc": req.policy_desc,
+ "match_expr": expr,
+ "priority": priority,
+ "limit_bytes": int(req.limit_bytes),
+ "soft_percent": int(req.soft_percent),
+ "hard_percent": int(req.hard_percent),
+ "source": source,
+ "source_order_num": source_order_num,
+ "enabled": enabled,
+ "data": None,
+ "created_at": now,
+ "created_by": None,
+ "updated_at": now,
+ "updated_by": None,
+ }
+ )
+ return
+ created_at = parse_iso_datetime(existing.get("created_at")) or now
+ updated = await repo.update(
+ {"policy_id": pid},
+ {
+ "policy_name": req.policy_name,
+ "policy_desc": req.policy_desc,
+ "match_expr": expr,
+ "priority": priority,
+ "limit_bytes": int(req.limit_bytes),
+ "soft_percent": int(req.soft_percent),
+ "hard_percent": int(req.hard_percent),
+ "source": source,
+ "source_order_num": source_order_num,
+ "enabled": enabled,
+ "updated_at": now,
+ "created_at": created_at,
+ },
+ )
+ if updated is None:
+ raise ValueError(f"failed to upsert workspace quota policy id={pid!r}")
+
+ async def delete(self, policy_id: str) -> None:
+ pid = str(policy_id or "").strip()
+ if not pid:
+ raise ValueError("policy_id is required")
+ repo = require_enterprise_repository(_TABLE)
+ existing = await repo.get(policy_id=pid)
+ if existing is None:
+ return
+ await repo.delete(policy_id=pid)
+
+ async def _assert_unique(
+ self,
+ repo: Any,
+ match_expr: Any,
+ priority: int,
+ *,
+ exclude_policy_id: str,
+ ) -> None:
+ rows = await _list_all(repo)
+ key = _match_key(match_expr)
+ full = _is_full_match(match_expr)
+ for row in rows:
+ if not bool(row.get("enabled", True)):
+ continue
+ pid = str(row.get("policy_id") or "")
+ if pid == exclude_policy_id:
+ continue
+ # 与 Manager 对齐:负数域(审批 -1)可多条并存;非负 priority 仍唯一
+ if int(priority) >= 0 and int(row.get("priority") or 0) == int(priority):
+ raise ValueError("priority already used by an enabled policy")
+ if _match_key(row.get("match_expr")) == key:
+ raise ValueError("match_expr already used by an enabled policy")
+ if full and _is_full_match(row.get("match_expr")):
+ raise ValueError("full-match policy already exists")
+
+
+async def _list_all(repo: Any) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ offset = 0
+ while True:
+ batch = await repo.list(limit=_PAGE, offset=offset)
+ rows.extend(batch)
+ if len(batch) < _PAGE:
+ return rows
+ offset += _PAGE
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py
index 1c4f76f678..bdfc26ec7c 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py
@@ -17,6 +17,7 @@ from ..infrastructure.config import get_settings
from ..routers.application_config_routers import application_config_router
from ..routers.instance_resource_routers import instance_resource_router
from ..routers.instance_routers import instance_router
+from ..routers.quota_routers import quota_router
from ..routers.template_routers import templates_router
logger = logging.getLogger(__name__)
@@ -70,6 +71,7 @@ def create_app() -> FastAPI:
v1.include_router(instance_router, tags=["Instances"])
v1.include_router(instance_resource_router, tags=["Instance Resources"])
v1.include_router(application_config_router, tags=["Application Config"])
+ v1.include_router(quota_router, tags=["Quota"])
app.include_router(v1)
return app
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/__init__.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/__init__.py
index 9009aabb04..f3378dd7da 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/__init__.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/__init__.py
@@ -3,11 +3,13 @@
from .application_config_routers import application_config_router
from .instance_resource_routers import instance_resource_router
from .instance_routers import instance_router
+from .quota_routers import quota_router
from .template_routers import templates_router
__all__ = [
"application_config_router",
"instance_resource_router",
"instance_router",
+ "quota_router",
"templates_router",
]
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/quota_routers.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/quota_routers.py
new file mode 100644
index 0000000000..c89580ba07
--- /dev/null
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/quota_routers.py
@@ -0,0 +1,49 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""配额同步 API(工作区配额策略投影)。"""
+
+from __future__ import annotations
+
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, HTTPException
+
+from ..core.quota import WorkspaceQuotaPolicyService
+from ..schemas.common_schemas import ResponseModel
+from ..schemas.quota_schemas import PolicyUpsertRequest
+from ..schemas.sync_schemas import make_sync_body
+from .deps import (
+ SyncContext,
+ VerifySyncEnvelopeOnly,
+ sync_write_data,
+ verify_sync,
+)
+
+quota_router = APIRouter()
+
+PolicySyncBody = make_sync_body("PolicySyncBody", PolicyUpsertRequest)
+
+
+@quota_router.put("/workspace-quota/policies", response_model=ResponseModel)
+async def upsert_workspace_quota_policy(
+ sync: Annotated[SyncContext, Depends(verify_sync(PolicySyncBody))],
+):
+ """工作区配额策略投影。管理面不直接调用。"""
+ try:
+ await WorkspaceQuotaPolicyService().upsert(sync.business)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return ResponseModel(code=200, message="success", data=sync_write_data(sync, None))
+
+
+@quota_router.delete(
+ "/workspace-quota/policies/{policy_id}", response_model=ResponseModel
+)
+async def delete_workspace_quota_policy(
+ policy_id: str,
+ sync: VerifySyncEnvelopeOnly,
+):
+ try:
+ await WorkspaceQuotaPolicyService().delete(policy_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return ResponseModel(code=200, message="success", data=sync_write_data(sync, None))
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/quota_schemas.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/quota_schemas.py
new file mode 100644
index 0000000000..246a8b3d02
--- /dev/null
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/quota_schemas.py
@@ -0,0 +1,59 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
+
+"""配额 API 请求 Schema。"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+
+class PolicyUpsertRequest(BaseModel):
+ """工作区配额策略按 policy_id 全量 upsert。未传的可选字段使用缺省。
+
+ 不含 cluster_id:一套 Gateway 对应一个集群。
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ policy_id: str = Field(min_length=1, max_length=64)
+ policy_name: str = Field(min_length=1, max_length=128)
+ policy_desc: str | None = Field(default=None, max_length=512)
+ match_expr: Any = None
+ priority: int
+ # -1=无限制;0=零配额;>0=正常限额
+ limit_bytes: int = Field(ge=-1)
+ soft_percent: int = Field(ge=0, le=100, default=80)
+ hard_percent: int = Field(ge=0, le=100, default=100)
+ source: str = Field(default="manual", max_length=32)
+ source_order_num: str | None = Field(default=None, max_length=64)
+ enabled: bool
+
+ @model_validator(mode="after")
+ def _percents(self) -> PolicyUpsertRequest:
+ if self.hard_percent <= self.soft_percent:
+ raise ValueError("hard_percent must be greater than soft_percent")
+ return self
+
+ @model_validator(mode="after")
+ def _normalize_name_desc(self) -> PolicyUpsertRequest:
+ name = self.policy_name.strip()
+ if not name:
+ raise ValueError("policy_name is required")
+ self.policy_name = name
+ desc = (self.policy_desc or "").strip()
+ self.policy_desc = desc or None
+ return self
+
+ @model_validator(mode="after")
+ def _normalize_source(self) -> PolicyUpsertRequest:
+ raw = (self.source or "").strip().lower() or "manual"
+ if raw not in {"manual", "approval"}:
+ raise ValueError("source must be manual or approval")
+ self.source = raw
+ order = (self.source_order_num or "").strip() or None
+ if self.source != "approval":
+ order = None
+ self.source_order_num = order
+ return self
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/safe_text.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/safe_text.py
index b77e5f7ee5..bb32ad7eb3 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/safe_text.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/safe_text.py
@@ -30,6 +30,7 @@ SAFE_TEXT_FIELD_NAMES: frozenset[str] = frozenset(
{
"template_name",
"policy_name",
+ "policy_desc",
"description",
"namespace",
"pod_name",