feat(desktop): align docked workspace with web client

This commit is contained in:
2026-07-25 21:52:19 +08:00
parent b2afa4edf8
commit 4b3f0d9167
5 changed files with 426 additions and 807 deletions

View File

@@ -1,325 +1,63 @@
import { useEffect, useRef, useState } from 'react'
import { Alert, Avatar, Button, Empty, Input, Message, Modal, Select, Spin, Tag, Typography } from '@arco-design/web-react'
import { useEffect, useMemo, useState } from 'react'
import { Alert, Avatar, Button, Dropdown, Empty, Form, Input, Menu, Modal, Select, Spin, Switch, Tag, Typography } from '@arco-design/web-react'
import {
IconApps, IconCheckCircle, IconClockCircle,
IconFile, IconFolder, IconPlus, IconRefresh, IconRobot, IconSearch, IconSettings,
IconApps, IconCheckCircle, IconCheckCircleFill, IconClockCircle, IconDown, IconEmail, IconFile,
IconFolder, IconLeft, IconList, IconMoon, IconPlus, IconRight, IconRobot,
IconSun, IconUser,
} from '@arco-design/web-react/icon'
import {
ApiError, checkServerConnection, createAISession, createCron, createProject, createTask, fetchAISessions, fetchExperts,
fetchProjects, fetchWorkspace, login, updateTask, uploadSource,
type AISession, type ApiSession, type Expert, type Project, type Workspace,
ApiError, createProject, fetchProjectWorkspace, fetchProjects, getCurrentUser,
listAIExperts, login, setApiBaseUrl, updateCurrentUser, updateTask,
type ApiSession, type CurrentUser, type Expert, type Project, type Workspace, type WorkspaceTask,
} from './api'
const { Text, Title } = Typography
type View = 'home' | 'tasks' | 'notes' | 'ai' | 'more'
type Action = 'project' | 'task' | 'cron' | null
type ConnectionStatus = 'checking' | 'online' | 'offline'
const SESSION_KEY = 'senlin-app-session'
type View = 'overview' | 'tasks' | 'inbox' | 'documents' | 'ai' | 'cron'
type SavedSession = ApiSession & { user?: CurrentUser }
type TaskWithProject = WorkspaceTask & { projectName: string }
const navItems: Array<{ id: View; label: string; icon: React.ReactNode }> = [
{ id: 'home', label: '项目', icon: <IconApps /> },
{ id: 'tasks', label: '计划', icon: <IconCheckCircle /> },
{ id: 'notes', label: '资料', icon: <IconFile /> },
{ id: 'overview', label: '概况', icon: <IconApps /> },
{ id: 'tasks', label: '计划', icon: <IconList /> },
{ id: 'inbox', label: '收集箱', icon: <IconEmail /> },
{ id: 'documents', label: '资料', icon: <IconFile /> },
{ id: 'ai', label: 'AI', icon: <IconRobot /> },
{ id: 'more', label: '更多', icon: <IconSettings /> },
{ id: 'cron', label: '周期计划', icon: <IconClockCircle /> },
]
export function App() {
const [session, setSession] = useState<ApiSession | null>(() => readStoredSession())
const stored = useMemo(readStoredSession, [])
const [session, setSession] = useState<ApiSession | null>(stored)
const [user, setUser] = useState<CurrentUser | null>(stored?.user ?? null)
const [projects, setProjects] = useState<Project[]>([])
const [workspaces, setWorkspaces] = useState<Record<string, Workspace>>({})
const [projectId, setProjectId] = useState('')
const [workspace, setWorkspace] = useState<Workspace | null>(null)
const [experts, setExperts] = useState<Expert[]>([])
const [aiSessions, setAISessions] = useState<AISession[]>([])
const [view, setView] = useState<View>('home')
const [loading, setLoading] = useState(Boolean(session))
const [view, setView] = useState<View>('overview')
const [dark, setDark] = useState(false)
const [loading, setLoading] = useState(Boolean(stored))
const [error, setError] = useState('')
const [action, setAction] = useState<Action>(null)
const refreshGeneration = useRef(0)
const [taskEditor, setTaskEditor] = useState<TaskWithProject | null>(null)
const [projectModalOpen, setProjectModalOpen] = useState(false)
const [profileModalOpen, setProfileModalOpen] = useState(false)
const [experts, setExperts] = useState<Expert[]>([])
useEffect(() => {
if (!session) return
let cancelled = false
setLoading(true)
void fetchProjects(session)
.then((items) => {
if (cancelled) return
setProjects(items)
setProjectId((current) => items.some((item) => item.id === current) ? current : items[0]?.id ?? '')
})
.catch((requestError) => !cancelled && setError(errorMessage(requestError)))
.finally(() => !cancelled && setLoading(false))
return () => { cancelled = true }
if (!user) void getCurrentUser(session).then(setUser).catch((requestError) => setError(errorMessage(requestError)))
void loadWorkspaces(session)
}, [session])
useEffect(() => {
if (!session || !projectId) return
void refreshProject(session, projectId)
}, [projectId, session])
async function refreshProject(activeSession = session, activeProject = projectId) {
if (!activeSession || !activeProject) return
const generation = ++refreshGeneration.current
async function loadWorkspaces(activeSession = session) {
if (!activeSession) return
setLoading(true)
setError('')
try {
const [nextWorkspace, nextExperts, nextSessions] = await Promise.all([
fetchWorkspace(activeSession, activeProject),
experts.length ? Promise.resolve(experts) : fetchExperts(activeSession),
fetchAISessions(activeSession, activeProject),
])
if (generation !== refreshGeneration.current) return
setWorkspace(nextWorkspace)
setExperts(nextExperts)
setAISessions(nextSessions)
} catch (requestError) {
if (generation === refreshGeneration.current) setError(errorMessage(requestError))
} finally {
if (generation === refreshGeneration.current) setLoading(false)
}
}
if (!session) return <Login onLogin={(next) => { localStorage.setItem('senlin-mini-session', JSON.stringify(next)); setSession(next) }} />
const activeProject = projects.find((project) => project.id === projectId) ?? projects[0]
const content = !workspace || !activeProject
? <Empty description="还没有项目,点击右上角新建" />
: renderView(view, {
session, workspace, experts, aiSessions,
refresh: () => refreshProject(),
openAction: setAction,
})
return (
<div className="mini-shell">
<header className="mini-header" data-tauri-drag-region>
<div className="mini-brand" data-tauri-drag-region>
<img src="/senlinai-icon.svg" alt="" />
<span>AI</span>
<Tag size="small" color="arcoblue">App 1.0</Tag>
</div>
</header>
<div className="project-switcher">
<Select
value={projectId || undefined}
placeholder="选择项目"
onChange={setProjectId}
triggerElement={() => (
<button className="project-trigger">
<Avatar size={26} style={{ background: activeProject?.background || '#165DFF' }}>{projectMark(activeProject)}</Avatar>
<span>{activeProject?.name || '选择项目'}</span>
<small>{activeProject?.identifier || ''}</small>
</button>
)}
>
{projects.map((project) => <Select.Option key={project.id} value={project.id}>{project.name}</Select.Option>)}
</Select>
<Button aria-label="刷新" type="text" shape="circle" icon={<IconRefresh />} loading={loading} onClick={() => void refreshProject()} />
<Button aria-label="新建项目" type="text" shape="circle" icon={<IconPlus />} onClick={() => setAction('project')} />
</div>
<nav className="mini-nav" aria-label="主要导航">
{navItems.map((item) => (
<button className={view === item.id ? 'active' : ''} key={item.id} onClick={() => setView(item.id)}>
{item.icon}<span>{item.label}</span>
</button>
))}
</nav>
{error ? <Alert className="mini-alert" type="error" content={error} closable onClose={() => setError('')} /> : null}
<main className="mini-content"><Spin loading={loading} block>{content}</Spin></main>
<footer className="mini-footer">
<span><i /> </span>
<button onClick={() => { localStorage.removeItem('senlin-mini-session'); setSession(null); setWorkspace(null) }}>退</button>
</footer>
<ActionModal
action={action}
workspace={workspace}
onClose={() => setAction(null)}
onProject={async (name) => {
const project = await createProject(session, name)
const next = await fetchProjects(session)
setProjects(next)
setProjectId(project.id)
}}
onTask={async (title, tag) => {
if (!projectId) return
await createTask(session, projectId, title, tag)
await refreshProject()
}}
onCron={async (title, schedule) => {
if (!projectId) return
await createCron(session, projectId, title, schedule)
await refreshProject()
}}
/>
</div>
)
}
function renderView(view: View, props: ViewProps) {
if (view === 'tasks') return <TasksView {...props} />
if (view === 'notes') return <NotesView {...props} />
if (view === 'ai') return <AIView {...props} />
if (view === 'more') return <MoreView {...props} />
return <HomeView {...props} />
}
type ViewProps = {
session: ApiSession
workspace: Workspace
experts: Expert[]
aiSessions: AISession[]
refresh: () => void | Promise<void>
openAction: (action: Action) => void
}
function HomeView({ workspace, openAction }: ViewProps) {
const pending = workspace.tasks.filter((task) => !task.completed)
return (
<section className="mini-page home-view">
<div className="page-intro">
<Text type="secondary"></Text>
<Title heading={4}>{workspace.project.name}</Title>
<p>{workspace.project.description || '把计划、资料与 AI 会话放进同一个项目上下文。'}</p>
</div>
<div className="metric-grid">
<Metric value={pending.length} label="待办计划" color="blue" />
<Metric value={workspace.documents.length} label="笔记资料" color="green" />
<Metric value={workspace.aiSessions.length} label="AI 会话" color="purple" />
<Metric value={workspace.cronPlans.length} label="计划任务" color="orange" />
</div>
<div className="section-title"><strong></strong></div>
<div className="quick-actions">
<button onClick={() => openAction('task')}><IconPlus /><span><b></b><small></small></span></button>
<button onClick={() => openAction('cron')}><IconClockCircle /><span><b></b><small></small></span></button>
</div>
<div className="section-title"><strong></strong><Tag color="arcoblue">{pending.length}</Tag></div>
<div className="compact-list">
{pending.slice(0, 4).map((task) => <div key={task.id}><IconCheckCircle /><span><b>{task.title}</b><small>{task.tag || '未分类'}</small></span></div>)}
{!pending.length && <Empty description="当前没有未完成计划" />}
</div>
</section>
)
}
function Metric({ value, label, color }: { value: number; label: string; color: string }) {
return <div className={`metric ${color}`}><strong>{value}</strong><span>{label}</span></div>
}
function TasksView({ session, workspace, refresh, openAction }: ViewProps) {
const [tag, setTag] = useState('全部')
const tags = workspace.tags.filter((item) => item.name !== '全部' && item.name !== 'all')
const tasks = tag === '全部' ? workspace.tasks : workspace.tasks.filter((task) => task.tag === tag)
return (
<section className="mini-page">
<div className="page-title"><div><Title heading={5}></Title><Text type="secondary"></Text></div><Button type="primary" size="small" icon={<IconPlus />} onClick={() => openAction('task')}></Button></div>
<div className="filter-strip">
{['全部', ...tags.map((item) => item.name)].map((item) => <button className={tag === item ? 'active' : ''} key={item} onClick={() => setTag(item)}>{item}</button>)}
</div>
<div className="sticky-list">
{tasks.map((task) => (
<article className={task.completed ? 'task-note completed' : 'task-note'} key={task.id}>
<button className="task-check" aria-label={task.completed ? '恢复计划' : '完成计划'} onClick={async () => { await updateTask(session, workspace.project.id, task); await refresh() }}><IconCheckCircle /></button>
<div><strong>{task.title}</strong><p>{task.summary || '暂无说明'}</p><span>{task.tag || '未分类'} · {task.createdAt}</span></div>
</article>
))}
{!tasks.length && <Empty description="当前筛选下没有计划" />}
</div>
</section>
)
}
function NotesView({ session, workspace, refresh }: ViewProps) {
const fileInput = useRef<HTMLInputElement>(null)
return (
<section className="mini-page">
<div className="page-title"><div><Title heading={5}></Title><Text type="secondary"></Text></div><Button type="primary" size="small" icon={<IconPlus />} onClick={() => fileInput.current?.click()}></Button></div>
<input className="hidden-file" ref={fileInput} type="file" onChange={async (event) => { const file = event.target.files?.[0]; if (!file) return; await uploadSource(session, workspace.project.id, file); await refresh(); event.target.value = '' }} />
<div className="note-grid">
{workspace.documents.map((document, index) => <article className={`source-note tone-${index % 4}`} key={document.id}><IconFile /><strong>{document.name}</strong><p>{document.extension || document.mimeType || document.kind}</p><span>{document.kind || '资料'} · {document.updatedAt}</span></article>)}
{!workspace.documents.length && <Empty description="还没有笔记或资料" />}
</div>
</section>
)
}
function AIView({ session, workspace, experts, aiSessions, refresh }: ViewProps) {
const [query, setQuery] = useState('')
const [category, setCategory] = useState('全部')
const [expertId, setExpertId] = useState('')
const [prompt, setPrompt] = useState('')
const [sending, setSending] = useState(false)
const categories = [...new Set(experts.map((expert) => expert.categoryName))]
const visible = experts.filter((expert) => (category === '全部' || expert.categoryName === category) && `${expert.name}${expert.description}`.toLowerCase().includes(query.toLowerCase()))
const selected = experts.find((expert) => expert.id === expertId)
return (
<section className="mini-page ai-view">
<div className="page-title"><div><Title heading={5}>AI </Title><Text type="secondary"></Text></div><Tag color="purple">{experts.length} </Tag></div>
<Input prefix={<IconSearch />} value={query} onChange={setQuery} allowClear placeholder="搜索专家" />
<div className="filter-strip">
{['全部', ...categories].map((item) => <button className={category === item ? 'active' : ''} key={item} onClick={() => setCategory(item)}>{item}</button>)}
</div>
<div className="expert-strip">
{visible.slice(0, 30).map((expert) => <button className={expertId === expert.id ? 'active' : ''} key={expert.id} onClick={() => setExpertId(expert.id)}><i style={{ background: expert.color }}>{expert.emoji}</i><span><b>{expert.name}</b><small>{expert.categoryName}</small></span></button>)}
</div>
<div className="mini-composer">
<div className="selected-expert">{selected ? <><i style={{ background: selected.color }}>{selected.emoji}</i><span><b>{selected.name}</b><small>{selected.description}</small></span></> : <Text type="secondary"></Text>}</div>
<Input.TextArea value={prompt} onChange={setPrompt} autoSize={{ minRows: 3, maxRows: 6 }} placeholder={selected ? `${selected.name}发送消息` : '请先选择专家'} />
<Button type="primary" long loading={sending} disabled={!selected || !prompt.trim()} onClick={async () => { if (!selected) return; setSending(true); try { await createAISession(session, workspace.project.id, selected.id, prompt.trim()); setPrompt(''); await refresh() } finally { setSending(false) } }}></Button>
</div>
<div className="section-title"><strong></strong></div>
<div className="session-list">{aiSessions.slice(0, 5).map((item) => <div key={item.id}><i style={{ background: item.expert?.color }}>{item.expert?.emoji || '🤖'}</i><span><b>{item.title}</b><small>{item.expert?.name || '森林AI'}</small></span></div>)}</div>
</section>
)
}
function MoreView({ workspace, openAction }: ViewProps) {
return (
<section className="mini-page">
<div className="page-title"><div><Title heading={5}></Title><Text type="secondary"></Text></div><Button size="small" icon={<IconPlus />} onClick={() => openAction('cron')}></Button></div>
<div className="settings-card"><strong></strong>{workspace.cronPlans.map((plan) => <div key={plan.id}><IconClockCircle /><span><b>{plan.title}</b><small>{plan.schedule} · {plan.enabled ? '已启用' : '已停用'}</small></span></div>)}{!workspace.cronPlans.length && <Text type="secondary"></Text>}</div>
<div className="settings-card"><strong></strong><p>Web </p></div>
<div className="settings-card version-card"><img src="/senlinai-icon.svg" alt="" /><span><b>AI App</b><small>v1.0 · </small></span></div>
</section>
)
}
function Login({ onLogin }: { onLogin: (session: ApiSession) => void }) {
const [server, setServer] = useState('http://localhost:9150')
const [email, setEmail] = useState('demo@senlin.ai')
const [password, setPassword] = useState('password123')
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [connection, setConnection] = useState<ConnectionStatus>('checking')
useEffect(() => {
const controller = new AbortController()
const timer = window.setTimeout(() => void checkConnection(controller.signal), 300)
return () => {
controller.abort()
window.clearTimeout(timer)
}
}, [server])
async function checkConnection(signal?: AbortSignal) {
setConnection('checking')
try {
const online = await checkServerConnection(server, signal)
if (!signal?.aborted) setConnection(online ? 'online' : 'offline')
} catch (requestError) {
if (!(requestError instanceof DOMException && requestError.name === 'AbortError')) setConnection('offline')
}
}
async function submitLogin() {
if (loading) return
setLoading(true)
setError('')
try {
onLogin(await login(server, email.trim(), password))
const nextProjects = await fetchProjects(activeSession)
const items = await Promise.all(nextProjects.map(async (project) => [project.id, await fetchProjectWorkspace(activeSession, project.id)] as const))
setProjects(nextProjects)
setWorkspaces(Object.fromEntries(items))
setProjectId((current) => current && nextProjects.some((project) => project.id === current) ? current : '')
} catch (requestError) {
setError(errorMessage(requestError))
} finally {
@@ -327,72 +65,159 @@ function Login({ onLogin }: { onLogin: (session: ApiSession) => void }) {
}
}
async function loadAI() {
if (!session || experts.length) return
try { setExperts(await listAIExperts(session)) } catch (requestError) { setError(errorMessage(requestError)) }
}
const visibleWorkspaces = projectId ? [workspaces[projectId]].filter(Boolean) : Object.values(workspaces)
const activeProject = projectId ? projects.find((project) => project.id === projectId) : undefined
const tasks = visibleWorkspaces.flatMap((workspace) => workspace.tasks.map((task) => ({ ...task, projectName: workspace.project.name })))
const title = activeProject?.name ?? '全部项目'
function cycleProject(direction: number) {
const index = projects.findIndex((project) => project.id === projectId)
const next = projectId ? (index + direction + projects.length) % projects.length : direction > 0 ? 0 : projects.length - 1
setProjectId(projects[next]?.id ?? '')
}
function logout() {
localStorage.removeItem(SESSION_KEY)
localStorage.removeItem('senlin-mini-session')
setSession(null); setUser(null); setProjects([]); setWorkspaces({}); setProjectId(''); setView('overview')
}
if (!session) return <Login onLogin={(next) => { setSession(next); setUser(next.user); persistSession(next) }} />
return (
<div className="mini-login">
<form className="login-note" onSubmit={(event) => { event.preventDefault(); void submitLogin() }}>
<img src="/senlinai-icon.svg" alt="" />
<Title heading={3}>AI App</Title>
<Text type="secondary"></Text>
<label><Input value={server} onChange={setServer} /></label>
<div className={`mini-connection ${connection}`} role="status">
<i />
<strong>{connection === 'checking' ? '正在检查' : connection === 'online' ? '连接正常' : '连接异常'}</strong>
<button type="button" onClick={() => void checkConnection()}>{connection === 'checking' ? '检查中' : '重新检查'}</button>
<div className={`app-shell ${dark ? 'theme-dark' : ''}`}>
<header className="app-header">
<div className="app-brand" data-tauri-drag-region><img src="/senlinai-icon.svg" alt="" /><span>AI</span></div>
<div className="header-actions">
<Button type="text" shape="circle" aria-label={dark ? '切换浅色模式' : '切换深色模式'} icon={dark ? <IconSun /> : <IconMoon />} onClick={() => setDark((value) => !value)} />
<ProfileMenu user={user} onProfile={() => setProfileModalOpen(true)} onLogout={() => logout()} />
</div>
<label><Input value={email} onChange={setEmail} /></label>
<label><Input.Password value={password} onChange={setPassword} /></label>
{error ? <Alert type="error" content={error} /> : null}
<Button type="primary" htmlType="submit" long loading={loading}></Button>
<small>v1.0 </small>
</form>
</header>
<section className="project-strip" aria-label="项目列表">
<button className={!projectId ? 'project-pill active' : 'project-pill'} onClick={() => setProjectId('')}><IconApps /><span></span></button>
<div className="project-scroller">
{projects.map((project) => <button key={project.id} className={projectId === project.id ? 'project-pill active' : 'project-pill'} onClick={() => setProjectId(project.id)}><i style={{ background: project.background || '#165DFF' }}>{projectLabel(project)}</i><span>{project.name}</span></button>)}
</div>
<Button type="text" size="mini" shape="circle" aria-label="上一个项目" icon={<IconLeft />} onClick={() => cycleProject(-1)} />
<Button type="text" size="mini" shape="circle" aria-label="下一个项目" icon={<IconRight />} onClick={() => cycleProject(1)} />
<Button type="primary" size="mini" shape="circle" aria-label="新建项目" icon={<IconPlus />} onClick={() => setProjectModalOpen(true)} />
</section>
{error ? <Alert className="app-alert" type="error" content={error} closable onClose={() => setError('')} /> : null}
<main className="app-main"><Spin loading={loading} block>{visibleWorkspaces.length ? <Content view={view} title={title} workspaces={visibleWorkspaces} tasks={tasks} onEditTask={setTaskEditor} onLoadAI={loadAI} experts={experts} /> : <Empty description="还没有项目,点击右上方加号创建一个项目" />}</Spin></main>
<aside className="channel-rail" aria-label="项目子菜单">
{navItems.map((item) => <button key={item.id} title={item.label} className={view === item.id ? 'active' : ''} onClick={() => { setView(item.id); if (item.id === 'ai') void loadAI() }}>{item.icon}<span>{item.label}</span></button>)}
</aside>
<TaskEditor task={taskEditor} tags={visibleWorkspaces.flatMap((workspace) => workspace.tags.map((tag) => tag.name))} onClose={() => setTaskEditor(null)} onSave={async (draft) => {
if (!taskEditor) return
await updateTask(session, taskEditor.projectId, taskEditor.id, { title: draft.title, description: draft.summary, tag: draft.tag, completed: draft.completed })
await loadWorkspaces()
setTaskEditor(null)
}} />
<ProjectModal visible={projectModalOpen} onClose={() => setProjectModalOpen(false)} onSave={async (name) => {
const project = await createProject(session, { name, identifier: slugify(name) || `project-${Date.now().toString(36)}`, icon: 'folder', background: '#165DFF', description: '' })
setProjectModalOpen(false)
await loadWorkspaces()
setProjectId(project.id)
}} />
<ProfileModal user={user} visible={profileModalOpen} onClose={() => setProfileModalOpen(false)} onSave={async (input) => {
const nextUser = await updateCurrentUser(session, input)
setUser(nextUser)
persistSession({ ...session, user: nextUser })
setProfileModalOpen(false)
}} />
</div>
)
}
function ActionModal({ action, workspace, onClose, onProject, onTask, onCron }: {
action: Action
workspace: Workspace | null
onClose: () => void
onProject: (name: string) => Promise<void>
onTask: (title: string, tag: string) => Promise<void>
onCron: (title: string, schedule: string) => Promise<void>
}) {
const [title, setTitle] = useState('')
const [tag, setTag] = useState('')
const [schedule, setSchedule] = useState('0 9 * * 1-5')
const [loading, setLoading] = useState(false)
useEffect(() => { if (action) { setTitle(''); setTag(''); setSchedule('0 9 * * 1-5') } }, [action])
const labels = action === 'project' ? ['新建项目', '项目名称'] : action === 'task' ? ['新建计划', '计划标题'] : ['新建计划任务', '任务名称']
return (
<Modal className="mini-modal" visible={Boolean(action)} title={labels[0]} onCancel={onClose} footer={null} unmountOnExit>
<div className="mini-form">
<label>{labels[1]}<Input autoFocus value={title} onChange={setTitle} /></label>
{action === 'task' ? <label><Select value={tag || undefined} placeholder="可选" onChange={setTag}>{workspace?.tags.filter((item) => item.name !== 'all' && item.name !== '全部').map((item) => <Select.Option key={item.id} value={item.name}>{item.name}</Select.Option>)}</Select></label> : null}
{action === 'cron' ? <label>Cron <Input value={schedule} onChange={setSchedule} /></label> : null}
<Button type="primary" long loading={loading} disabled={!title.trim()} onClick={async () => { setLoading(true); try { if (action === 'project') await onProject(title.trim()); if (action === 'task') await onTask(title.trim(), tag); if (action === 'cron') await onCron(title.trim(), schedule.trim()); onClose() } catch (requestError) { Message.error(errorMessage(requestError)) } finally { setLoading(false) } }}></Button>
</div>
</Modal>
)
function Content({ view, title, workspaces, tasks, onEditTask, onLoadAI, experts }: { view: View; title: string; workspaces: Workspace[]; tasks: TaskWithProject[]; onEditTask: (task: TaskWithProject) => void; onLoadAI: () => void; experts: Expert[] }) {
if (view === 'tasks' || view === 'overview') return <TaskBoard title={view === 'overview' ? '待办任务' : '工作计划'} subtitle={title} tasks={tasks} onEditTask={onEditTask} />
if (view === 'inbox') return <InboxPanel title={title} workspaces={workspaces} />
if (view === 'documents') return <DocumentPanel title={title} workspaces={workspaces} />
if (view === 'ai') return <AIPanel title={title} workspaces={workspaces} experts={experts} onLoad={onLoadAI} />
return <CronPanel title={title} workspaces={workspaces} />
}
function readStoredSession(): ApiSession | null {
try {
const value = JSON.parse(localStorage.getItem('senlin-mini-session') || 'null') as ApiSession | null
return value?.baseUrl && value?.token ? value : null
} catch {
return null
}
function TaskBoard({ title, subtitle, tasks, onEditTask }: { title: string; subtitle: string; tasks: TaskWithProject[]; onEditTask: (task: TaskWithProject) => void }) {
const [tag, setTag] = useState('全部')
const tags = [...new Set(tasks.map((task) => task.tag).filter(Boolean))]
const visible = tag === '全部' ? tasks : tasks.filter((task) => task.tag === tag)
const pending = visible.filter((task) => !task.completed)
const completed = visible.filter((task) => task.completed)
return <section className="content-page task-page">
<div className="content-heading"><div><Text type="secondary">{subtitle}</Text><Title heading={4}>{title}</Title></div><Tag color="arcoblue">{pending.length} </Tag></div>
<div className="tag-filter"><button className={tag === '全部' ? 'active' : ''} onClick={() => setTag('全部')}></button>{tags.map((item) => <button key={item} className={tag === item ? 'active' : ''} onClick={() => setTag(item)}>{item}</button>)}</div>
<section className="task-section"><div className="section-label"><strong></strong><span>{pending.length}</span></div><div className="task-list">{pending.map((task) => <TaskRow key={task.id} task={task} onClick={() => onEditTask(task)} />)}{!pending.length && <Empty description="当前没有待办任务" />}</div></section>
<section className="task-section completed-section"><div className="section-label"><strong></strong><span>{completed.length}</span></div><div className="task-list">{completed.map((task) => <TaskRow key={task.id} task={task} onClick={() => onEditTask(task)} />)}{!completed.length && <Empty description="尚未完成任何任务" />}</div></section>
</section>
}
function projectMark(project?: Project) {
if (!project) return <IconFolder />
if (project.icon && !['folder', 'project'].includes(project.icon)) return project.icon
const chars = Array.from(project.name.trim())
const chinese = chars.some((char) => /[\u3400-\u9fff]/.test(char))
return chars.slice(0, chinese ? 2 : 4).join('').toUpperCase()
function TaskRow({ task, onClick }: { task: TaskWithProject; onClick: () => void }) {
return <button className={`task-row ${task.completed ? 'done' : ''}`} onClick={onClick}><span className="task-check">{task.completed ? <IconCheckCircleFill /> : <IconCheckCircle />}</span><span className="task-copy"><strong>{task.title}</strong><small>{task.summary || '暂无任务说明'}</small></span><span className="task-meta"><Tag color={task.completed ? 'green' : 'arcoblue'}>{task.tag || task.projectName}</Tag><small>{formatDate(task.completedAt || task.createdAt)}</small></span></button>
}
function errorMessage(error: unknown) {
if (error instanceof ApiError || error instanceof Error) return error.message
return '操作失败,请稍后重试'
function InboxPanel({ title, workspaces }: { title: string; workspaces: Workspace[] }) {
const items = workspaces.flatMap((workspace) => workspace.inbox.map((item) => ({ ...item, projectName: workspace.project.name })))
return <Panel title="收集箱" subtitle={title}>{items.map((item) => <article className="detail-row" key={item.id}><IconEmail /><div><strong>{item.title}</strong><p>{item.summary || item.source}</p></div><Tag>{item.projectName}</Tag></article>)}{!items.length && <Empty description="收集箱为空" />}</Panel>
}
function DocumentPanel({ title, workspaces }: { title: string; workspaces: Workspace[] }) {
const documents = workspaces.flatMap((workspace) => workspace.documents.map((item) => ({ ...item, projectName: workspace.project.name })))
return <Panel title="笔记资料" subtitle={title}>{documents.map((item) => <article className="detail-row" key={item.id}><IconFile /><div><strong>{item.name}</strong><p>{item.extension || item.mimeType || item.kind} · {formatDate(item.updatedAt)}</p></div><Tag>{item.projectName}</Tag></article>)}{!documents.length && <Empty description="暂无笔记或资料" />}</Panel>
}
function AIPanel({ title, workspaces, experts, onLoad }: { title: string; workspaces: Workspace[]; experts: Expert[]; onLoad: () => void }) {
useEffect(() => { onLoad() }, [onLoad])
const sessions = workspaces.flatMap((workspace) => workspace.aiSessions.map((item) => ({ ...item, projectName: workspace.project.name })))
return <Panel title="AI 会话" subtitle={title}><div className="expert-chips">{experts.slice(0, 6).map((expert) => <span key={expert.id}><i style={{ background: expert.color }}>{expert.emoji}</i>{expert.name}</span>)}</div>{sessions.map((item) => <article className="detail-row" key={item.id}><IconRobot /><div><strong>{item.title}</strong><p>{item.summary || 'AI 会话'}</p></div><Tag>{item.projectName}</Tag></article>)}{!sessions.length && <Empty description="暂无 AI 会话" />}</Panel>
}
function CronPanel({ title, workspaces }: { title: string; workspaces: Workspace[] }) {
const plans = workspaces.flatMap((workspace) => workspace.cronPlans.map((item) => ({ ...item, projectName: workspace.project.name })))
return <Panel title="周期计划" subtitle={title}>{plans.map((item) => <article className="detail-row" key={item.id}><IconClockCircle /><div><strong>{item.title}</strong><p>{item.schedule} · {item.enabled ? '已启用' : '已停用'}</p></div><Tag>{item.projectName}</Tag></article>)}{!plans.length && <Empty description="暂无周期计划" />}</Panel>
}
function Panel({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) { return <section className="content-page"><div className="content-heading"><div><Text type="secondary">{subtitle}</Text><Title heading={4}>{title}</Title></div></div><div className="detail-list">{children}</div></section> }
function ProfileMenu({ user, onProfile, onLogout }: { user: CurrentUser | null; onProfile: () => void; onLogout: () => void }) {
const menu = <Menu><Menu.Item key="profile" onClick={onProfile}></Menu.Item><Menu.Item key="logout" onClick={onLogout}>退</Menu.Item></Menu>
return <Dropdown droplist={menu} position="br" trigger="click"><button className="profile-trigger"><Avatar size={28}>{user?.displayName.slice(0, 1) || <IconUser />}</Avatar><span>{user?.displayName || '用户'}</span><IconDown /></button></Dropdown>
}
function TaskEditor({ task, tags, onClose, onSave }: { task: TaskWithProject | null; tags: string[]; onClose: () => void; onSave: (draft: { title: string; summary: string; tag: string; completed: boolean }) => Promise<void> }) {
const [title, setTitle] = useState(''); const [summary, setSummary] = useState(''); const [tag, setTag] = useState(''); const [completed, setCompleted] = useState(false); const [saving, setSaving] = useState(false)
useEffect(() => { if (task) { setTitle(task.title); setSummary(task.summary); setTag(task.tag); setCompleted(task.completed) } }, [task])
return <Modal title="编辑任务" visible={Boolean(task)} onCancel={onClose} confirmLoading={saving} onOk={async () => { if (!title.trim()) return; setSaving(true); try { await onSave({ title: title.trim(), summary: summary.trim(), tag, completed }) } finally { setSaving(false) } }}><Form layout="vertical"><Form.Item label="标题" required><Input value={title} onChange={setTitle} /></Form.Item><Form.Item label="说明"><Input.TextArea value={summary} onChange={setSummary} autoSize={{ minRows: 3, maxRows: 6 }} /></Form.Item><Form.Item label="标签"><Select value={tag || undefined} allowClear onChange={(value) => setTag(value ?? '')}>{[...new Set(tags.filter(Boolean))].map((item) => <Select.Option key={item} value={item}>{item}</Select.Option>)}</Select></Form.Item><Form.Item label="完成状态"><Switch checked={completed} checkedText="已完成" uncheckedText="待办" onChange={setCompleted} /></Form.Item></Form></Modal>
}
function ProjectModal({ visible, onClose, onSave }: { visible: boolean; onClose: () => void; onSave: (name: string) => Promise<void> }) {
const [name, setName] = useState(''); const [saving, setSaving] = useState(false)
return <Modal title="新建项目" visible={visible} onCancel={onClose} confirmLoading={saving} onOk={async () => { if (!name.trim()) return; setSaving(true); try { await onSave(name.trim()); setName('') } finally { setSaving(false) } }}><Input autoFocus placeholder="项目名称" value={name} onChange={setName} /></Modal>
}
function ProfileModal({ user, visible, onClose, onSave }: { user: CurrentUser | null; visible: boolean; onClose: () => void; onSave: (input: { displayName: string; currentPassword?: string; newPassword?: string }) => Promise<void> }) {
const [displayName, setDisplayName] = useState(user?.displayName ?? ''); const [currentPassword, setCurrentPassword] = useState(''); const [newPassword, setNewPassword] = useState(''); const [saving, setSaving] = useState(false)
useEffect(() => setDisplayName(user?.displayName ?? ''), [user])
return <Modal title="修改资料" visible={visible} onCancel={onClose} confirmLoading={saving} onOk={async () => { setSaving(true); try { await onSave({ displayName, currentPassword: currentPassword || undefined, newPassword: newPassword || undefined }); setCurrentPassword(''); setNewPassword('') } finally { setSaving(false) } }}><Form layout="vertical"><Form.Item label="名称" required><Input value={displayName} onChange={setDisplayName} /></Form.Item><Form.Item label="邮箱"><Input disabled value={user?.email} /></Form.Item><Form.Item label="当前密码"><Input.Password value={currentPassword} onChange={setCurrentPassword} placeholder="修改密码时必填" /></Form.Item><Form.Item label="新密码"><Input.Password value={newPassword} onChange={setNewPassword} placeholder="不修改可留空" /></Form.Item></Form></Modal>
}
function Login({ onLogin }: { onLogin: (session: ApiSession & { user: CurrentUser }) => void }) {
const [server, setServer] = useState('http://localhost:9150'); const [email, setEmail] = useState('demo@senlin.ai'); const [password, setPassword] = useState('password123'); const [loading, setLoading] = useState(false); const [error, setError] = useState('')
return <div className="login-page"><form className="login-card" onSubmit={(event) => { event.preventDefault(); void submit() }}><img src="/senlinai-icon.svg" alt="" /><Title heading={3}>AI App</Title><Text type="secondary"></Text><label><Input value={server} onChange={setServer} /></label><label><Input value={email} onChange={setEmail} /></label><label><Input.Password value={password} onChange={setPassword} /></label>{error && <Alert type="error" content={error} />}<Button type="primary" htmlType="submit" long loading={loading}></Button></form></div>
async function submit() { setLoading(true); setError(''); try { onLogin(await login(server, email.trim(), password)) } catch (requestError) { setError(errorMessage(requestError)) } finally { setLoading(false) } }
}
function readStoredSession(): SavedSession | null { try { const value = JSON.parse(localStorage.getItem(SESSION_KEY) || localStorage.getItem('senlin-mini-session') || 'null') as SavedSession | null; if (!value?.baseUrl || !value.token) return null; setApiBaseUrl(value.baseUrl); return value } catch { return null } }
function persistSession(session: SavedSession) { localStorage.setItem(SESSION_KEY, JSON.stringify(session)) }
function projectLabel(project: Project) { if (project.icon && !['folder', 'project'].includes(project.icon)) return Array.from(project.icon).slice(0, 2).join(''); return Array.from(project.name.trim()).slice(0, 2).join('').toUpperCase() || <IconFolder /> }
function formatDate(value: string) { const date = new Date(value); return Number.isNaN(date.getTime()) ? value : `${date.getMonth() + 1}/${date.getDate()}` }
function slugify(value: string) { return value.toLowerCase().trim().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').replace(/^-|-$/g, '') }
function errorMessage(error: unknown) { return error instanceof ApiError || error instanceof Error ? error.message : '操作失败,请稍后重试' }