Commit d9ae969b by 黄南光

智能化P5: 登录/画像/会话前端与用户反馈修复

前端:
- AppShell 统一渲染侧边栏+顶栏+未登录拦截,修复 profile/admin 页各自
  再渲染 Sidebar 导致的两个侧边栏;登录页脱离外壳全屏白底
- 未登录访问受保护页由 AppShell 客户端重定向到 /login;对外 API 直连
  后端不经前端路由,不受影响
- 用户信息移到全局顶栏右上角,独立成条避免与页面头部按钮重叠;
  Copilot 面板头部不再重复渲染用户菜单与新建会话按钮
- 会话侧栏默认展开;删除按钮 hover 浮出,二次确认
- 新增 Toast,fetchFiles 与问答请求失败时弹出可见提示,不再静默
- 登录/会话/画像 API 封装于 lib/auth,请求统一带 credentials
- /api 代理用 getSetCookie 逐条透传 Set-Cookie,避免多条 cookie 被
  Headers 合并成非法头导致登录态无法下发

后端:
- 删除会话改为先沉淀再软删除:按产品要求,删除时把本会话学到的稳定
  事实更新进长期记忆,未达最小轮数门槛的短会话自动跳过
1 parent e9560853
"use client";
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { KeyRound, Loader2, Plus, Search, UserRound } from "lucide-react";
import ConfirmDialog from "@/components/ConfirmDialog";
import { apiJson, fetchMe } from "@/lib/auth";
import { cn } from "@/lib/utils";
interface AdminUser {
id: string;
username: string;
displayName: string;
phone: string | null;
email: string | null;
role: string;
status: string;
storeName: string | null;
positionName: string | null;
lastLoginAt: string | null;
}
export default function AdminUsersPage() {
const router = useRouter();
const [users, setUsers] = useState<AdminUser[]>([]);
const [total, setTotal] = useState(0);
const [keyword, setKeyword] = useState("");
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [resetTarget, setResetTarget] = useState<AdminUser | null>(null);
const [notice, setNotice] = useState("");
const load = useCallback(
async (search = "") => {
setLoading(true);
try {
const data = await apiJson<{ total: number; items: AdminUser[] }>(
`/admin/users?keyword=${encodeURIComponent(search)}&limit=100`
);
setUsers(data.items);
setTotal(data.total);
} catch {
router.push("/login");
} finally {
setLoading(false);
}
},
[router]
);
useEffect(() => {
(async () => {
const me = await fetchMe().catch(() => null);
if (!me) {
router.push("/login");
return;
}
if (me.role !== "admin") {
router.push("/");
return;
}
await load();
})();
}, [router, load]);
const handleReset = async () => {
if (!resetTarget) return;
setBusy(true);
try {
const data = await apiJson<{ initialPassword: string }>(
`/admin/users/${resetTarget.id}/reset-password`,
{ method: "POST" }
);
setNotice(`已将 ${resetTarget.displayName} 的密码重置为 ${data.initialPassword}`);
setResetTarget(null);
setTimeout(() => setNotice(""), 4000);
} finally {
setBusy(false);
}
};
return (
<div className="flex-1 overflow-y-auto bg-slate-100">
<div className="max-w-5xl mx-auto px-8 py-8">
<header className="mb-5 flex items-end justify-between">
<div>
<h1 className="text-lg font-bold text-slate-800">用户管理</h1>
<p className="text-xs text-slate-500 mt-1">共 {total} 名用户</p>
</div>
<div className="relative">
<Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && load(keyword)}
placeholder="搜索姓名 / 账号 / 手机号"
className="w-64 pl-8 pr-3 py-2 text-xs bg-white border border-slate-200 rounded-lg outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 transition"
/>
</div>
</header>
{notice && (
<div className="mb-4 text-xs text-emerald-700 bg-emerald-50 border border-emerald-100 rounded-lg px-3 py-2.5">
{notice}
</div>
)}
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
{loading ? (
<div className="flex items-center justify-center py-16 text-slate-400 text-xs gap-2">
<Loader2 className="w-4 h-4 animate-spin" />
加载中…
</div>
) : (
<table className="w-full text-xs">
<thead className="bg-slate-50 border-b border-slate-200">
<tr className="text-left text-slate-500">
<th className="px-4 py-2.5 font-semibold">姓名</th>
<th className="px-4 py-2.5 font-semibold">账号</th>
<th className="px-4 py-2.5 font-semibold">岗位</th>
<th className="px-4 py-2.5 font-semibold">角色</th>
<th className="px-4 py-2.5 font-semibold">状态</th>
<th className="px-4 py-2.5 font-semibold text-right">操作</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id} className="border-b border-slate-100 last:border-0 hover:bg-slate-50/60">
<td className="px-4 py-2.5">
<div className="flex items-center gap-2">
<div className="w-6 h-6 bg-slate-100 rounded-lg flex items-center justify-center text-slate-500">
<UserRound className="w-3 h-3" />
</div>
<span className="font-medium text-slate-800">{user.displayName}</span>
</div>
</td>
<td className="px-4 py-2.5 text-slate-500">{user.username}</td>
<td className="px-4 py-2.5 text-slate-500">{user.positionName || "—"}</td>
<td className="px-4 py-2.5">
<span
className={cn(
"px-2 py-0.5 rounded-md text-[10px] font-semibold",
user.role === "admin"
? "bg-blue-50 text-blue-700"
: "bg-slate-100 text-slate-500"
)}
>
{user.role === "admin" ? "管理员" : "普通用户"}
</span>
</td>
<td className="px-4 py-2.5">
<span
className={cn(
"px-2 py-0.5 rounded-md text-[10px] font-semibold",
user.status === "active"
? "bg-emerald-50 text-emerald-700"
: "bg-slate-100 text-slate-400"
)}
>
{user.status === "active" ? "启用" : "停用"}
</span>
</td>
<td className="px-4 py-2.5 text-right">
<button
onClick={() => setResetTarget(user)}
className="inline-flex items-center gap-1 px-2.5 py-1 text-[11px] font-semibold text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50 transition"
>
<KeyRound className="w-3 h-3" />
重置密码
</button>
</td>
</tr>
))}
{users.length === 0 && (
<tr>
<td colSpan={6} className="px-4 py-12 text-center text-slate-400">
没有匹配的用户
</td>
</tr>
)}
</tbody>
</table>
)}
</div>
</div>
<ConfirmDialog
open={!!resetTarget}
title="重置密码?"
description={`将把 ${resetTarget?.displayName || ""} 的密码重置为初始密码,该用户需用新密码重新登录。`}
confirmText="重置"
loading={busy}
onConfirm={handleReset}
onCancel={() => setResetTarget(null)}
/>
</div>
);
}
...@@ -52,8 +52,17 @@ async function proxy(req: NextRequest) { ...@@ -52,8 +52,17 @@ async function proxy(req: NextRequest) {
upstream.headers.forEach((value, key) => { upstream.headers.forEach((value, key) => {
const k = key.toLowerCase(); const k = key.toLowerCase();
if (k === "content-length" || k === "transfer-encoding" || k === "connection") return; if (k === "content-length" || k === "transfer-encoding" || k === "connection") return;
// Set-Cookie 不能走 forEach:多条 cookie 会被 Headers 合并成一条非法头,
// 导致浏览器整条丢弃(登录态就是靠它下发的)。下面用 getSetCookie 单独逐条 append。
if (k === "set-cookie") return;
respHeaders.set(key, value); respHeaders.set(key, value);
}); });
// 登录/登出的 httpOnly cookie 经此透传
const setCookies = upstream.headers.getSetCookie?.() ?? [];
for (const cookie of setCookies) {
respHeaders.append("set-cookie", cookie);
}
// 保障 SSE 等流式响应实时下发 // 保障 SSE 等流式响应实时下发
respHeaders.set("cache-control", "no-cache, no-transform"); respHeaders.set("cache-control", "no-cache, no-transform");
respHeaders.set("x-accel-buffering", "no"); respHeaders.set("x-accel-buffering", "no");
......
import type { Metadata } from "next"; import type { Metadata } from "next";
import "./globals.css"; import "./globals.css";
import Sidebar from "@/components/Sidebar"; import AppShell from "@/components/AppShell";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Wiki App", title: "Wiki App",
...@@ -17,11 +17,9 @@ export default function RootLayout({ ...@@ -17,11 +17,9 @@ export default function RootLayout({
lang="zh-CN" lang="zh-CN"
className="h-full antialiased font-sans" className="h-full antialiased font-sans"
> >
<body className="min-h-full flex h-screen bg-[#F8FAFC] text-slate-900 font-sans overflow-hidden"> <body className="min-h-full h-screen bg-[#F8FAFC] text-slate-900 font-sans overflow-hidden">
<Sidebar /> {/* 侧边栏、顶栏用户信息、未登录拦截统一由 AppShell 承担 */}
<main className="flex-1 flex flex-col min-w-0 bg-white overflow-hidden"> <AppShell>{children}</AppShell>
{children}
</main>
</body> </body>
</html> </html>
); );
......
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { BookOpen, Loader2, LogIn } from "lucide-react";
import { login } from "@/lib/auth";
export default function LoginPage() {
const router = useRouter();
const [account, setAccount] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
if (!account.trim() || !password) {
setError("请输入账号和密码");
return;
}
setLoading(true);
setError("");
try {
await login(account.trim(), password);
router.push("/");
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : "登录失败");
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen w-full flex items-center justify-center bg-white px-4">
<div className="w-full max-w-sm">
{/* 复用侧边栏的 Logo 样式,保持品牌一致 */}
<div className="flex flex-col items-center mb-8">
<div className="w-14 h-14 bg-blue-600 rounded-xl flex items-center justify-center text-white shadow-lg shadow-blue-500/20 mb-4">
<BookOpen className="w-7 h-7 fill-current" />
</div>
<h1 className="text-xl font-bold text-slate-800">企业知识库</h1>
<p className="text-xs text-slate-400 mt-1.5">登录后即可使用 Wiki 智能问答</p>
</div>
<form
onSubmit={handleSubmit}
className="bg-white rounded-xl shadow-xl border border-slate-100 p-6 space-y-4"
>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
账号 / 手机号
</label>
<input
type="text"
value={account}
onChange={(e) => setAccount(e.target.value)}
autoComplete="username"
placeholder="请输入手机号"
className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-lg outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20"
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">密码</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
placeholder="请输入密码"
className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-lg outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20"
/>
</div>
{error && (
<div className="text-xs text-red-600 bg-red-50 border border-red-100 rounded-lg px-3 py-2">
{error}
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white text-sm font-semibold py-2.5 rounded-lg transition flex items-center justify-center gap-2"
>
{loading ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
登录中…
</>
) : (
<>
<LogIn className="w-4 h-4" />
登录
</>
)}
</button>
<p className="text-[11px] text-slate-400 text-center pt-1">
初始密码为 123456,登录后可在右上角修改
</p>
</form>
</div>
</div>
);
}
"use client";
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Brain, Loader2, RefreshCw, Trash2, UserRound } from "lucide-react";
import ConfirmDialog from "@/components/ConfirmDialog";
import {
clearMemory,
fetchMe,
fetchProfile,
regenerateProfile,
type CurrentUser,
type ProfilePayload,
} from "@/lib/auth";
import { cn } from "@/lib/utils";
type TabKey = "profile" | "memory";
export default function ProfilePage() {
const router = useRouter();
const [user, setUser] = useState<CurrentUser | null>(null);
const [data, setData] = useState<ProfilePayload | null>(null);
const [tab, setTab] = useState<TabKey>("profile");
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [confirmClear, setConfirmClear] = useState(false);
const load = useCallback(async () => {
const me = await fetchMe();
if (!me) {
router.push("/login");
return;
}
setUser(me);
setData(await fetchProfile());
setLoading(false);
}, [router]);
useEffect(() => {
load().catch(() => setLoading(false));
}, [load]);
const handleRegenerate = async () => {
setBusy(true);
try {
await regenerateProfile();
setData(await fetchProfile());
} finally {
setBusy(false);
}
};
const handleClearMemory = async () => {
setBusy(true);
try {
await clearMemory();
setData(await fetchProfile());
setConfirmClear(false);
} finally {
setBusy(false);
}
};
const content = tab === "profile" ? data?.profileMd : data?.agentMd;
return (
<div className="flex-1 overflow-y-auto bg-slate-100">
<div className="max-w-3xl mx-auto px-8 py-8">
<header className="mb-6">
<h1 className="text-lg font-bold text-slate-800">我的画像</h1>
<p className="text-xs text-slate-500 mt-1">
画像与长期记忆由系统自动生成与沉淀,此处仅供查看,不可编辑。
</p>
</header>
{user && (
<div className="bg-white rounded-xl border border-slate-200 px-5 py-4 mb-5 flex items-center gap-4">
<div className="w-11 h-11 bg-blue-600 rounded-xl flex items-center justify-center text-white shrink-0">
<UserRound className="w-5 h-5" />
</div>
<div className="min-w-0">
<div className="text-sm font-bold text-slate-800">{user.displayName}</div>
<div className="text-xs text-slate-500 mt-0.5">
{[user.positionName, user.storeName, user.username]
.filter(Boolean)
.join(" · ")}
</div>
</div>
</div>
)}
<div className="flex items-center gap-1 mb-4">
{(
[
{ key: "profile", label: "岗位画像", icon: UserRound },
{ key: "memory", label: "长期记忆", icon: Brain },
] as const
).map(({ key, label, icon: Icon }) => (
<button
key={key}
onClick={() => setTab(key)}
className={cn(
"flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold rounded-lg transition",
tab === key
? "bg-blue-50 text-blue-700"
: "text-slate-500 hover:bg-slate-200/60"
)}
>
<Icon className="w-3.5 h-3.5" />
{label}
</button>
))}
<div className="ml-auto flex items-center gap-2">
{tab === "profile" && (
<button
onClick={handleRegenerate}
disabled={busy}
className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition disabled:opacity-60"
>
{busy ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
<RefreshCw className="w-3 h-3" />
)}
重新生成
</button>
)}
{tab === "memory" && (
<button
onClick={() => setConfirmClear(true)}
disabled={busy}
className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-red-600 bg-white border border-red-200 rounded-lg hover:bg-red-50 transition disabled:opacity-60"
>
<Trash2 className="w-3 h-3" />
清空记忆
</button>
)}
</div>
</div>
<div className="bg-white rounded-xl border border-slate-200 p-6 min-h-[320px]">
{loading ? (
<div className="flex items-center justify-center py-16 text-slate-400 text-xs gap-2">
<Loader2 className="w-4 h-4 animate-spin" />
加载中…
</div>
) : content ? (
<article className="prose prose-sm prose-slate max-w-none">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
</article>
) : (
<div className="text-center py-16">
<Brain className="w-10 h-10 mx-auto text-slate-300 mb-3" />
<p className="text-xs text-slate-400 leading-relaxed">
{tab === "profile"
? "岗位画像尚未生成,稍后刷新即可看到"
: "还没有沉淀出长期记忆,多使用几次问答后会自动生成"}
</p>
</div>
)}
</div>
{tab === "memory" && data && (
<p className="text-[11px] text-slate-400 mt-3">
已沉淀 {data.memoryStats.entries} 条 · {data.memoryStats.chars}/
{data.memoryStats.maxChars} 字符
</p>
)}
</div>
<ConfirmDialog
open={confirmClear}
title="清空长期记忆?"
description="将清除系统对你的所有理解(关注范围、表达偏好等),会话记录不受影响。此操作不可撤销。"
confirmText="清空"
loading={busy}
onConfirm={handleClearMemory}
onCancel={() => setConfirmClear(false)}
/>
</div>
);
}
"use client";
import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import Sidebar from "@/components/Sidebar";
import UserMenu from "@/components/UserMenu";
import { fetchMe, type CurrentUser } from "@/lib/auth";
/** 登录页自成一屏,不套侧边栏与顶栏。 */
const BARE_PATHS = new Set(["/login"]);
/**
* 应用外壳:统一渲染侧边栏 + 顶栏用户信息,并做未登录拦截。
*
* 侧边栏从这里唯一渲染,各业务页不再自行渲染,避免出现两个侧边栏。
* 对外 API(后端直连)不经过前端路由,不受此拦截影响。
*/
export default function AppShell({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const isBare = BARE_PATHS.has(pathname);
// undefined = 鉴权中;null = 未登录;对象 = 已登录
const [user, setUser] = useState<CurrentUser | null | undefined>(undefined);
useEffect(() => {
if (isBare) return;
let cancelled = false;
fetchMe()
.then((me) => {
if (cancelled) return;
setUser(me);
if (!me) router.replace("/login"); // 未登录一律拦回登录页
})
.catch(() => {
if (!cancelled) setUser(null);
});
return () => {
cancelled = true;
};
}, [pathname, isBare, router]);
// 登录页:整屏交给页面自身
if (isBare) {
return <>{children}</>;
}
// 鉴权中或未登录:不渲染受保护内容,避免闪现
if (!user) {
return (
<div className="h-screen w-full flex items-center justify-center bg-[#F8FAFC]" />
);
}
return (
<div className="flex h-screen w-full">
<Sidebar />
<main className="flex-1 flex flex-col min-w-0 bg-white overflow-hidden">
{/* 顶栏:用户信息固定在右上角,独立成条避免与各页面头部按钮重叠 */}
<div className="h-11 shrink-0 flex items-center justify-end px-4 border-b border-slate-100 bg-white z-40">
<UserMenu user={user} variant="light" />
</div>
<div className="flex-1 min-h-0 flex flex-col overflow-hidden">{children}</div>
</main>
</div>
);
}
"use client";
import { useState } from "react";
import { KeyRound, Loader2 } from "lucide-react";
import { changePassword } from "@/lib/auth";
interface ChangePasswordDialogProps {
open: boolean;
onClose: () => void;
}
export default function ChangePasswordDialog({ open, onClose }: ChangePasswordDialogProps) {
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const [done, setDone] = useState(false);
const [loading, setLoading] = useState(false);
if (!open) return null;
const reset = () => {
setOldPassword("");
setNewPassword("");
setConfirmPassword("");
setError("");
setDone(false);
};
const handleClose = () => {
reset();
onClose();
};
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
if (newPassword !== confirmPassword) {
setError("两次输入的新密码不一致");
return;
}
if (newPassword.length < 6) {
setError("新密码长度不能少于 6 位");
return;
}
setLoading(true);
setError("");
try {
await changePassword(oldPassword, newPassword);
setDone(true);
setTimeout(handleClose, 1200);
} catch (err) {
setError(err instanceof Error ? err.message : "修改失败");
} finally {
setLoading(false);
}
};
const inputClass =
"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20";
return (
<div
className="fixed inset-0 z-[60] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm"
onClick={handleClose}
>
<form
onSubmit={handleSubmit}
onClick={(e) => e.stopPropagation()}
className="w-[360px] bg-white rounded-2xl shadow-2xl p-5 space-y-3.5"
>
<div className="flex items-center gap-2.5 pb-1">
<div className="w-9 h-9 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center">
<KeyRound className="w-4.5 h-4.5" />
</div>
<h3 className="text-sm font-bold text-slate-800">修改密码</h3>
</div>
{done ? (
<p className="text-xs text-emerald-600 bg-emerald-50 border border-emerald-100 rounded-lg px-3 py-2.5">
密码修改成功
</p>
) : (
<>
<input
type="password"
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
placeholder="当前密码"
autoComplete="current-password"
className={inputClass}
/>
<input
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="新密码(至少 6 位)"
autoComplete="new-password"
className={inputClass}
/>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="确认新密码"
autoComplete="new-password"
className={inputClass}
/>
{error && (
<div className="text-xs text-red-600 bg-red-50 border border-red-100 rounded-lg px-3 py-2">
{error}
</div>
)}
<div className="flex justify-end gap-2 pt-1">
<button
type="button"
onClick={handleClose}
className="px-3.5 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-100 rounded-lg transition"
>
取消
</button>
<button
type="submit"
disabled={loading}
className="px-3.5 py-1.5 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-60 rounded-lg transition flex items-center gap-1.5"
>
{loading && <Loader2 className="w-3 h-3 animate-spin" />}
确定
</button>
</div>
</>
)}
</form>
</div>
);
}
"use client";
import { AlertTriangle, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
interface ConfirmDialogProps {
open: boolean;
title: string;
description: string;
confirmText?: string;
danger?: boolean;
loading?: boolean;
onConfirm: () => void;
onCancel: () => void;
}
/** 通用二次确认弹窗。删除会话、清空长期记忆等不可逆操作复用。 */
export default function ConfirmDialog({
open,
title,
description,
confirmText = "确定",
danger = true,
loading = false,
onConfirm,
onCancel,
}: ConfirmDialogProps) {
if (!open) return null;
return (
<div
className="fixed inset-0 z-[60] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm"
onClick={onCancel}
>
<div
className="w-[360px] bg-white rounded-2xl shadow-2xl p-5"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-start gap-3">
<div
className={cn(
"w-9 h-9 rounded-xl flex items-center justify-center shrink-0",
danger ? "bg-red-50 text-red-600" : "bg-blue-50 text-blue-600"
)}
>
<AlertTriangle className="w-4.5 h-4.5" />
</div>
<div className="flex-1 min-w-0">
<h3 className="text-sm font-bold text-slate-800">{title}</h3>
<p className="text-xs text-slate-500 mt-1.5 leading-relaxed">{description}</p>
</div>
</div>
<div className="flex justify-end gap-2 mt-5">
<button
onClick={onCancel}
disabled={loading}
className="px-3.5 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-100 rounded-lg transition"
>
取消
</button>
<button
onClick={onConfirm}
disabled={loading}
className={cn(
"px-3.5 py-1.5 text-xs font-semibold text-white rounded-lg transition flex items-center gap-1.5",
danger ? "bg-red-600 hover:bg-red-700" : "bg-blue-600 hover:bg-blue-700",
loading && "opacity-60"
)}
>
{loading && <Loader2 className="w-3 h-3 animate-spin" />}
{confirmText}
</button>
</div>
</div>
</div>
);
}
"use client";
import { useState } from "react";
import { MessageSquare, SquarePen, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import type { SessionItem } from "@/lib/auth";
interface SessionSidebarProps {
sessions: SessionItem[];
currentId: string | null;
loading?: boolean;
onSelect: (id: string) => void;
onCreate: () => void;
onDelete: (session: SessionItem) => void;
}
/** 相对时间展示,避免侧栏出现冗长的绝对时间戳。 */
function relativeTime(iso: string | null): string {
if (!iso) return "";
const then = new Date(iso).getTime();
if (Number.isNaN(then)) return "";
const diff = Date.now() - then;
const minute = 60_000;
const hour = 60 * minute;
const day = 24 * hour;
if (diff < minute) return "刚刚";
if (diff < hour) return `${Math.floor(diff / minute)} 分钟前`;
if (diff < day) return `${Math.floor(diff / hour)} 小时前`;
if (diff < 2 * day) return "昨天";
if (diff < 7 * day) return `${Math.floor(diff / day)} 天前`;
return new Date(iso).toLocaleDateString("zh-CN", { month: "numeric", day: "numeric" });
}
export default function SessionSidebar({
sessions,
currentId,
loading = false,
onSelect,
onCreate,
onDelete,
}: SessionSidebarProps) {
const [hoveredId, setHoveredId] = useState<string | null>(null);
return (
<aside className="w-[220px] shrink-0 bg-slate-50/80 border-r border-slate-200 flex flex-col">
<div className="p-3 border-b border-slate-200">
<button
onClick={onCreate}
className="w-full flex items-center justify-center gap-1.5 bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold py-2 rounded-lg transition"
>
<SquarePen className="w-3.5 h-3.5" />
新建会话
</button>
</div>
<div className="flex-1 overflow-y-auto scrollbar-thin p-2 space-y-0.5">
{loading && (
<div className="text-[11px] text-slate-400 text-center py-4">加载中…</div>
)}
{!loading && sessions.length === 0 && (
<div className="text-center py-8 px-3">
<MessageSquare className="w-8 h-8 mx-auto text-slate-300 mb-2" />
<p className="text-[11px] text-slate-400 leading-relaxed">
还没有会话
<br />
点上方按钮开始提问
</p>
</div>
)}
{sessions.map((session) => {
const active = session.id === currentId;
return (
<div
key={session.id}
onMouseEnter={() => setHoveredId(session.id)}
onMouseLeave={() => setHoveredId(null)}
onClick={() => onSelect(session.id)}
className={cn(
"group relative px-2.5 py-2 rounded-lg cursor-pointer transition",
active ? "bg-blue-50 text-blue-700" : "hover:bg-slate-200/60 text-slate-700"
)}
>
<div className="flex items-center gap-1.5 pr-5">
<MessageSquare
className={cn("w-3.5 h-3.5 shrink-0", active ? "text-blue-600" : "text-slate-400")}
/>
<span className="text-xs font-medium truncate">{session.title}</span>
</div>
<div className="flex items-center gap-2 mt-0.5 pl-5">
<span className="text-[10px] text-slate-400">{relativeTime(session.updatedAt)}</span>
{session.totalTurns > 0 && (
<span className="text-[10px] text-slate-400">{session.totalTurns} 轮</span>
)}
</div>
{/* 删除图标平时隐藏,hover 才浮出,避免误触 */}
{hoveredId === session.id && (
<button
onClick={(e) => {
e.stopPropagation();
onDelete(session);
}}
title="删除会话"
className="absolute right-1.5 top-1/2 -translate-y-1/2 p-1 rounded-md text-slate-400 hover:text-red-600 hover:bg-white transition"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
)}
</div>
);
})}
</div>
</aside>
);
}
"use client"; "use client";
import { useEffect, useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { BookOpen, Database, FileText } from "lucide-react"; import { BookOpen, Database, FileText, Settings, UserRound } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { fetchMe } from "@/lib/auth";
interface NavItem {
href: string;
label: string;
icon: typeof BookOpen;
/** 仅管理员可见 */
adminOnly?: boolean;
}
const NAV_ITEMS: NavItem[] = [
{ href: "/", label: "Wiki 原始文件", icon: FileText },
{ href: "/wiki-repo", label: "Wiki 知识库", icon: BookOpen },
{ href: "/rag", label: "RAG 工作台", icon: Database },
{ href: "/profile", label: "我的画像", icon: UserRound },
{ href: "/admin/users", label: "系统管理", icon: Settings, adminOnly: true },
];
export default function Sidebar() { export default function Sidebar() {
const pathname = usePathname(); const pathname = usePathname();
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
fetchMe()
.then((user) => setIsAdmin(user?.role === "admin"))
.catch(() => setIsAdmin(false));
}, []);
const visible = NAV_ITEMS.filter((item) => !item.adminOnly || isAdmin);
return ( return (
<aside className="w-16 flex flex-col items-center py-6 bg-slate-900 text-slate-400 shrink-0"> <aside className="w-16 flex flex-col items-center py-6 bg-slate-900 text-slate-400 shrink-0">
...@@ -14,45 +41,25 @@ export default function Sidebar() { ...@@ -14,45 +41,25 @@ export default function Sidebar() {
<BookOpen className="w-6 h-6 fill-current" /> <BookOpen className="w-6 h-6 fill-current" />
</div> </div>
<nav className="flex-1 flex flex-col gap-6"> <nav className="flex-1 flex flex-col gap-6">
{visible.map(({ href, label, icon: Icon }) => {
const active = pathname === href || (href !== "/" && pathname.startsWith(href));
return (
<Link <Link
href="/" key={href}
className={cn( href={href}
"p-2 rounded-lg transition relative group",
pathname === "/" ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200"
)}
title="Wiki 原始文件"
>
<FileText className="w-5 h-5" />
<span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50">
Wiki 原始文件
</span>
</Link>
<Link
href="/wiki-repo"
className={cn(
"p-2 rounded-lg transition relative group",
pathname === "/wiki-repo" ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200"
)}
title="Wiki 知识库"
>
<BookOpen className="w-5 h-5" />
<span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50">
Wiki 知识库
</span>
</Link>
<Link
href="/rag"
className={cn( className={cn(
"p-2 rounded-lg transition relative group", "p-2 rounded-lg transition relative group",
pathname === "/rag" ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200" active ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200"
)} )}
title="RAG 工作台" title={label}
> >
<Database className="w-5 h-5" /> <Icon className="w-5 h-5" />
<span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50"> <span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50">
RAG 工作台 {label}
</span> </span>
</Link> </Link>
);
})}
</nav> </nav>
</aside> </aside>
); );
......
"use client";
import { useEffect } from "react";
import { AlertCircle, CheckCircle2, Info, X } from "lucide-react";
import { cn } from "@/lib/utils";
export type ToastType = "error" | "success" | "info";
export interface ToastState {
message: string;
type: ToastType;
}
const ICONS = {
error: AlertCircle,
success: CheckCircle2,
info: Info,
} as const;
const STYLES = {
error: "bg-red-50 border-red-200 text-red-700",
success: "bg-emerald-50 border-emerald-200 text-emerald-700",
info: "bg-blue-50 border-blue-200 text-blue-700",
} as const;
/** 右上角轻量提示。错误默认停留久一些,方便用户看清。 */
export default function Toast({
toast,
onClose,
}: {
toast: ToastState | null;
onClose: () => void;
}) {
useEffect(() => {
if (!toast) return;
const timeout = toast.type === "error" ? 6000 : 3000;
const timer = setTimeout(onClose, timeout);
return () => clearTimeout(timer);
}, [toast, onClose]);
if (!toast) return null;
const Icon = ICONS[toast.type];
return (
<div className="fixed top-4 left-1/2 -translate-x-1/2 z-[80] animate-in fade-in slide-in-from-top-4 duration-200">
<div
className={cn(
"flex items-center gap-2.5 pl-3.5 pr-2.5 py-2.5 rounded-xl border shadow-lg max-w-md",
STYLES[toast.type]
)}
>
<Icon className="w-4 h-4 shrink-0" />
<span className="text-xs font-medium">{toast.message}</span>
<button
onClick={onClose}
className="p-0.5 rounded-md hover:bg-black/5 transition shrink-0"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
</div>
);
}
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { KeyRound, LogOut, UserRound } from "lucide-react";
import ChangePasswordDialog from "@/components/ChangePasswordDialog";
import { logout, type CurrentUser } from "@/lib/auth";
import { cn } from "@/lib/utils";
interface UserMenuProps {
user: CurrentUser;
/** 深色背景(如渐变头部)下需要反色的浅色样式 */
variant?: "light" | "dark";
}
export default function UserMenu({ user, variant = "dark" }: UserMenuProps) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const onClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
setOpen(false);
}
};
document.addEventListener("mousedown", onClickOutside);
return () => document.removeEventListener("mousedown", onClickOutside);
}, []);
const handleLogout = async () => {
await logout();
router.push("/login");
router.refresh();
};
return (
<>
<div className="relative" ref={ref}>
<button
onClick={() => setOpen((v) => !v)}
className={cn(
"flex items-center gap-2 px-2 py-1.5 rounded-lg transition",
variant === "dark"
? "hover:bg-white/10 text-blue-100 hover:text-white"
: "hover:bg-slate-100 text-slate-600"
)}
>
<div
className={cn(
"w-6 h-6 rounded-lg flex items-center justify-center shrink-0",
variant === "dark" ? "bg-white/20" : "bg-blue-600 text-white"
)}
>
<UserRound className="w-3.5 h-3.5" />
</div>
<div className="text-left leading-tight hidden sm:block">
<div className="text-[11px] font-semibold">{user.displayName}</div>
{user.positionName && (
<div className="text-[10px] opacity-70">{user.positionName}</div>
)}
</div>
</button>
{open && (
<div className="absolute right-0 top-full mt-1.5 w-44 bg-white rounded-xl shadow-xl border border-slate-100 py-1 z-50">
<div className="px-3 py-2 border-b border-slate-100">
<div className="text-xs font-semibold text-slate-800">{user.displayName}</div>
<div className="text-[10px] text-slate-400 mt-0.5">{user.username}</div>
{user.storeName && (
<div className="text-[10px] text-slate-400">{user.storeName}</div>
)}
</div>
<button
onClick={() => {
setShowPassword(true);
setOpen(false);
}}
className="w-full flex items-center gap-2 px-3 py-2 text-xs text-slate-600 hover:bg-slate-50 transition"
>
<KeyRound className="w-3.5 h-3.5" />
修改密码
</button>
<button
onClick={handleLogout}
className="w-full flex items-center gap-2 px-3 py-2 text-xs text-red-600 hover:bg-red-50 transition"
>
<LogOut className="w-3.5 h-3.5" />
退出登录
</button>
</div>
)}
</div>
<ChangePasswordDialog open={showPassword} onClose={() => setShowPassword(false)} />
</>
);
}
/**
* 登录态与受保护接口的请求封装。
*
* token 由后端种在 httpOnly cookie 中,前端读不到也不需要读,
* 所有请求带上 `credentials: "include"` 即可自动携带。
*/
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";
export interface CurrentUser {
id: string;
username: string;
displayName: string;
phone: string | null;
role: string;
positionId: string | null;
positionName: string | null;
storeName: string | null;
}
export class UnauthorizedError extends Error {
constructor() {
super("未登录或登录已失效");
this.name = "UnauthorizedError";
}
}
/** 带凭据的 fetch。遇到 401 统一抛 UnauthorizedError,由调用方决定是否跳登录页。 */
export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
const response = await fetch(`${API_BASE}${path}`, {
...init,
credentials: "include",
headers: {
...(init.body ? { "Content-Type": "application/json" } : {}),
...(init.headers || {}),
},
});
if (response.status === 401) {
throw new UnauthorizedError();
}
return response;
}
/** 请求 JSON 接口,非 2xx 时抛出后端返回的 detail 文案。 */
export async function apiJson<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
const response = await apiFetch(path, init);
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const detail = (data as { detail?: string }).detail || `请求失败(${response.status})`;
throw new Error(detail);
}
return data as T;
}
export async function login(account: string, password: string): Promise<CurrentUser> {
const data = await apiJson<{ user: CurrentUser }>("/auth/login", {
method: "POST",
body: JSON.stringify({ account, password }),
});
return data.user;
}
export async function logout(): Promise<void> {
await apiFetch("/auth/logout", { method: "POST" }).catch(() => undefined);
}
/** 获取当前用户;未登录返回 null(不抛异常,便于页面做重定向判断)。 */
export async function fetchMe(): Promise<CurrentUser | null> {
try {
const data = await apiJson<{ user: CurrentUser }>("/auth/me");
return data.user;
} catch (error) {
if (error instanceof UnauthorizedError) return null;
throw error;
}
}
export async function changePassword(oldPassword: string, newPassword: string): Promise<void> {
await apiJson("/auth/change-password", {
method: "POST",
body: JSON.stringify({ oldPassword, newPassword }),
});
}
// ============================== 会话 ==============================
export interface SessionItem {
id: string;
title: string;
totalTurns: number;
status: string;
updatedAt: string | null;
createdAt: string | null;
}
export interface SessionMessage {
seq: number;
role: "user" | "assistant";
content: string;
reasoning: ReasoningStep[] | null;
createdAt: string | null;
}
/** 落库的思考步骤。工具返回正文不入库,只有 meta 里的成功标志与字节数。 */
export interface ReasoningStep {
id: string;
type: "thought" | "call" | "response";
name?: string | null;
content?: string;
meta?: { ok: boolean; bytes: number };
}
export async function listSessions(limit = 20, offset = 0) {
return apiJson<{ total: number; items: SessionItem[] }>(
`/sessions?limit=${limit}&offset=${offset}`
);
}
/** 新建会话。传 previousSessionId 可让后端对上一个会话触发收尾沉淀。 */
export async function createSession(previousSessionId?: string | null) {
return apiJson<{ id: string }>("/sessions", {
method: "POST",
body: JSON.stringify({ previousSessionId: previousSessionId || null }),
});
}
export async function fetchSessionMessages(sessionId: string) {
return apiJson<{ id: string; title: string; messages: SessionMessage[] }>(
`/sessions/${sessionId}/messages`
);
}
export async function deleteSession(sessionId: string) {
return apiJson(`/sessions/${sessionId}`, { method: "DELETE" });
}
export async function renameSession(sessionId: string, title: string) {
return apiJson(`/sessions/${sessionId}`, {
method: "PATCH",
body: JSON.stringify({ title }),
});
}
// ============================== 画像 ==============================
export interface ProfilePayload {
profileMd: string;
agentMd: string;
profileGenerated: boolean;
profileVersion: number;
memoryStats: { chars: number; entries: number; maxChars: number };
}
export async function fetchProfile() {
return apiJson<ProfilePayload>("/profile");
}
export async function regenerateProfile() {
return apiJson("/profile/regenerate", { method: "POST" });
}
export async function clearMemory() {
return apiJson("/profile/memory", { method: "DELETE" });
}
...@@ -13,6 +13,7 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Query, status ...@@ -13,6 +13,7 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from config import SESSION_LIST_PAGE_SIZE from config import SESSION_LIST_PAGE_SIZE
from src.database.models import WikiUser from src.database.models import WikiUser
from src.services.identity.tokens import get_current_user from src.services.identity.tokens import get_current_user
from src.services.memory.reflector import reflect_on_session_end
from src.services.memory.sessions import ( from src.services.memory.sessions import (
create_session, create_session,
get_owned_session, get_owned_session,
...@@ -106,14 +107,24 @@ async def delete_session( ...@@ -106,14 +107,24 @@ async def delete_session(
session_id: str, session_id: str,
user: WikiUser = Depends(get_current_user), user: WikiUser = Depends(get_current_user),
): ):
"""软删除会话。 """删除会话:先把本会话的价值沉淀进长期记忆,再软删除。
刻意**不触发**长期沉淀:删除是用户的主动否定,不应把被丢弃的内容 按产品要求,删除会话前会触发一次收尾沉淀,让「越用越聪明」不因删除而漏水
固化进长期记忆。已被此前定时任务沉淀过的内容也不回滚——记忆是关于用户的 (未达最小轮数门槛的短会话会在 reflector 内部跳过,不产生多余 LLM 调用)。
抽象结论,已蒸馏无法反向撤销,且它不属于某一次具体会话。 沉淀在删除前完成,因为软删除后该会话会被 reflector 的候选筛选排除。
""" """
if not await soft_delete_session(session_id, user.id): # 归属校验:先确认会话属于当前用户,避免对他人会话做任何操作
record = await get_owned_session(session_id, user.id)
if record is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在") raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
logger.info("[Session] 删除会话: user=%s session=%s", user.username, session_id) # 删除前沉淀:把这段会话学到的稳定事实并入 agent.md
try:
await reflect_on_session_end(user.id, session_id)
except Exception as exc:
# 沉淀失败不应阻断删除本身
logger.warning("[Session] 删除前沉淀失败(不影响删除): session=%s err=%s", session_id, exc)
await soft_delete_session(session_id, user.id)
logger.info("[Session] 删除会话(已沉淀): user=%s session=%s", user.username, session_id)
return {"success": True} return {"success": True}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!