diff --git a/README.md b/README.md index 14b3292..d2614f1 100644 --- a/README.md +++ b/README.md @@ -173,3 +173,23 @@ NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成 数据库与 SSE 继续使用原始 `content`,复制、导出、固定记忆、分支和重新生成仍以整条消息操作。后端公共格式规则由 `access-manage/src/modules/digital/digital.prompt.ts` 管理;管理端解析器与本仓保持同一实现和回归用例。 运行 `node --experimental-strip-types --test tests/*.test.mjs` 验证格式解析与登录跳转;格式用例覆盖中英文、旧括号、逐字累计流、不完整标记与 HTML 字面量。 + +## 数字人独立页面与返回行为 + +| 地址 | 页面 | +| --- | --- | +| `/discover` | 发现角色;`q`、`tag`、`favorites` 保存当前筛选 | +| `/characters/:id` | 角色详情与开场选择 | +| `/chats` | 我的对话列表 | +| `/chats/:id` | 指定会话;支持直接打开、刷新与草稿恢复 | +| `/library` | 世界书与对话风格书架 | +| `/library/:id` | 世界书或风格详情 | +| `/profile` | 数字人个人身份与内容偏好 | + +页面入口位于 `src/app/(digital)/`,共享布局追踪站内历史。`src/components/digital-page.tsx` 并行加载私有首屏,`src/lib/digital-routes.ts` 集中维护资源地址和登录回跳边界。原工作台 `/me` 保持兼容。 + +导航和详情使用真实链接,浏览器后退/前进还原实际上一页;页面内返回优先使用已有站内历史,从新标签页或外站直接打开时回到对应列表。搜索筛选替换当前历史条目,不为每次输入增加返回步骤。删除当前聊天后替换为列表地址,旧链接显示资源不存在。 + +未登录时保留具体资源地址,登录后回到原页;会话过期先清理 Cookie,避免登录页和失效会话之间循环。草稿按会话 ID 保存在当前标签页的 sessionStorage;退出聊天会取消该页流连接,已有消息仍由服务端持久化。对话设定、确认删除和选择项仍作为当前页面的临时弹窗。 + +路由与深链回归:`node --experimental-strip-types --test tests/*.test.mjs`;类型检查和构建按上面的项目命令执行。 diff --git a/src/app/(auth)/login/page.tsx b/src/app/(auth)/login/page.tsx index 4b0552e..b92b894 100644 --- a/src/app/(auth)/login/page.tsx +++ b/src/app/(auth)/login/page.tsx @@ -1,9 +1,18 @@ /** 星港登录页,使用独立用户账号,无公开注册。 */ import Link from "next/link"; +import { safeDigitalReturnTo } from "@/lib/digital-routes"; import { LoginForm } from "@/components/login-form"; import "@/components/digital-login.css"; /** 登录前展示独立品牌与简洁表单。 */ -export default function LoginPage() { +export default async function LoginPage({ + searchParams, +}: { + searchParams: Promise<{ next?: string | string[] }>; +}) { + const { next } = await searchParams; + const returnTo = safeDigitalReturnTo( + typeof next === "string" ? next : undefined, + ); return ( @@ -32,7 +41,7 @@ export default function LoginPage() { ✧ 欢迎回到星港 使用你的星港账号,继续未完的故事。 - + 账号由管理员开通 · 与后台账号独立 diff --git a/src/app/(digital)/characters/[id]/page.tsx b/src/app/(digital)/characters/[id]/page.tsx new file mode 100644 index 0000000..5b97b5b --- /dev/null +++ b/src/app/(digital)/characters/[id]/page.tsx @@ -0,0 +1,21 @@ +/** 角色详情深链入口,刷新后仍加载同一资源。 */ +import { DigitalPage } from "@/components/digital-page"; + +/** 独立详情页面名称。 */ +export const metadata = { title: "角色详情 · 星港" }; + +/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */ +export default async function Page({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + return ( + + ); +} diff --git a/src/app/(digital)/chats/[id]/page.tsx b/src/app/(digital)/chats/[id]/page.tsx new file mode 100644 index 0000000..a9ee339 --- /dev/null +++ b/src/app/(digital)/chats/[id]/page.tsx @@ -0,0 +1,21 @@ +/** 聊天深链入口,刷新后仍加载同一资源。 */ +import { DigitalPage } from "@/components/digital-page"; + +/** 独立详情页面名称。 */ +export const metadata = { title: "聊天 · 星港" }; + +/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */ +export default async function Page({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + return ( + + ); +} diff --git a/src/app/(digital)/chats/page.tsx b/src/app/(digital)/chats/page.tsx new file mode 100644 index 0000000..a984e68 --- /dev/null +++ b/src/app/(digital)/chats/page.tsx @@ -0,0 +1,10 @@ +/** 我的对话独立页面,浏览器历史与页面地址保持一致。 */ +import { DigitalPage } from "@/components/digital-page"; + +/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */ +export const metadata = { title: "我的对话 · 星港" }; + +/** 读取本页面的私有首屏数据。 */ +export default function Page() { + return ; +} diff --git a/src/app/(digital)/discover/page.tsx b/src/app/(digital)/discover/page.tsx new file mode 100644 index 0000000..17d892a --- /dev/null +++ b/src/app/(digital)/discover/page.tsx @@ -0,0 +1,31 @@ +/** 发现角色独立页面,浏览器历史与页面地址保持一致。 */ +import { DigitalPage } from "@/components/digital-page"; + +/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */ +export const metadata = { title: "发现角色 · 星港" }; + +/** 读取本页面的私有首屏数据。 */ +export default async function Page({ + searchParams, +}: { + searchParams: Promise>; +}) { + const search = await searchParams; + const first = (value: string | string[] | undefined) => + typeof value === "string" ? value : ""; + const filters = { + query: first(search.q).slice(0, 200), + tag: first(search.tag).slice(0, 80) || "全部", + favorites: first(search.favorites) === "1", + }; + const params = new URLSearchParams(); + if (filters.query) params.set("q", filters.query); + if (filters.tag !== "全部") params.set("tag", filters.tag); + if (filters.favorites) params.set("favorites", "1"); + return ( + + ); +} diff --git a/src/app/(digital)/error.tsx b/src/app/(digital)/error.tsx new file mode 100644 index 0000000..914a880 --- /dev/null +++ b/src/app/(digital)/error.tsx @@ -0,0 +1,16 @@ +"use client"; + +/** 私有页面请求失败时保留重试和返回入口,不把异常内容或服务地址展示给用户。 */ +import Link from "next/link"; + +/** 数据异常可就地重试,无需退出账号或返回站外页面。 */ +export default function DigitalError({ reset }: { reset: () => void }) { + return ( + + 页面暂时没有打开 + 请检查网络后重试。 + 重新加载 + 返回我的对话 + + ); +} diff --git a/src/app/(digital)/layout.tsx b/src/app/(digital)/layout.tsx new file mode 100644 index 0000000..b55fd68 --- /dev/null +++ b/src/app/(digital)/layout.tsx @@ -0,0 +1,20 @@ +/** 数字人独立页面共享样式和站内历史追踪;具体资源由各页面服务端读取。 */ +import { Suspense } from "react"; +import { DigitalRouteHistory } from "@/components/digital-route-history"; +import "@/components/digital.css"; + +/** 页面切换保留历史追踪器,不把页面内容作为标签状态缓存。 */ +export default function DigitalLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + <> + + + + {children} + > + ); +} diff --git a/src/app/(digital)/library/[id]/page.tsx b/src/app/(digital)/library/[id]/page.tsx new file mode 100644 index 0000000..acf3c0a --- /dev/null +++ b/src/app/(digital)/library/[id]/page.tsx @@ -0,0 +1,21 @@ +/** 内容详情深链入口,刷新后仍加载同一资源。 */ +import { DigitalPage } from "@/components/digital-page"; + +/** 独立详情页面名称。 */ +export const metadata = { title: "内容详情 · 星港" }; + +/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */ +export default async function Page({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + return ( + + ); +} diff --git a/src/app/(digital)/library/page.tsx b/src/app/(digital)/library/page.tsx new file mode 100644 index 0000000..2526b1d --- /dev/null +++ b/src/app/(digital)/library/page.tsx @@ -0,0 +1,10 @@ +/** 灵感书架独立页面,浏览器历史与页面地址保持一致。 */ +import { DigitalPage } from "@/components/digital-page"; + +/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */ +export const metadata = { title: "灵感书架 · 星港" }; + +/** 读取本页面的私有首屏数据。 */ +export default function Page() { + return ; +} diff --git a/src/app/(digital)/loading.tsx b/src/app/(digital)/loading.tsx new file mode 100644 index 0000000..0e1d2f0 --- /dev/null +++ b/src/app/(digital)/loading.tsx @@ -0,0 +1,8 @@ +/** 路由数据加载反馈,避免切换会话时暂时显示上一段聊天内容。 */ +export default function DigitalLoading() { + return ( + + 正在打开页面… + + ); +} diff --git a/src/app/(digital)/not-found.tsx b/src/app/(digital)/not-found.tsx new file mode 100644 index 0000000..3926d5a --- /dev/null +++ b/src/app/(digital)/not-found.tsx @@ -0,0 +1,14 @@ +/** 无效、下架或前台已删除的资源统一显示可恢复的导航入口。 */ +import Link from "next/link"; + +/** 不向其他账号泄露资源存在性或旧聊天内容。 */ +export default function DigitalNotFound() { + return ( + + 这个页面已经不在这里了 + 内容可能已下架,或这段对话已被删除。 + 查看我的对话 + 发现角色 + + ); +} diff --git a/src/app/(digital)/profile/page.tsx b/src/app/(digital)/profile/page.tsx new file mode 100644 index 0000000..afed2cc --- /dev/null +++ b/src/app/(digital)/profile/page.tsx @@ -0,0 +1,10 @@ +/** 我的身份独立页面,浏览器历史与页面地址保持一致。 */ +import { DigitalPage } from "@/components/digital-page"; + +/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */ +export const metadata = { title: "我的身份 · 星港" }; + +/** 读取本页面的私有首屏数据。 */ +export default function Page() { + return ; +} diff --git a/src/app/discover/page.tsx b/src/app/discover/page.tsx deleted file mode 100644 index 41b389c..0000000 --- a/src/app/discover/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -/** 数字人前台首屏,服务端并行读取私有数据,避免浏览器加载瀑布。 */ -import { requireBackendData } from "@/lib/backend"; -import type { Bootstrap, Summary } from "@/lib/digital"; -import { DigitalHome } from "@/components/digital-home"; -/** 私有入口,后端鉴权失败时由统一助手返回登录。 */ -export default async function DiscoverPage() { - const [initial, initialSummaries] = await Promise.all([ - requireBackendData("/digital/bootstrap"), - requireBackendData("/digital/conversations"), - ]); - return ; -} diff --git a/src/components/conversation-row.tsx b/src/components/conversation-row.tsx index 5170fc6..a79ed4e 100644 --- a/src/components/conversation-row.tsx +++ b/src/components/conversation-row.tsx @@ -1,6 +1,8 @@ "use client"; /** 会话列表的水平滑动操作与删除确认;纵向滑动继续交给页面滚动。 */ import { useEffect, useId, useRef, useState, type PointerEvent } from "react"; +import Link from "next/link"; +import { chatPath } from "@/lib/digital-routes"; import { LoaderCircle, Trash2 } from "lucide-react"; import type { Card, Summary } from "@/lib/digital"; @@ -11,7 +13,6 @@ export function ConversationRow({ revealed, disabled, onReveal, - onOpen, onDelete, }: { summary: Summary; @@ -19,7 +20,6 @@ export function ConversationRow({ revealed: boolean; disabled: boolean; onReveal: (id: string | null) => void; - onOpen: () => void; onDelete: () => void; }) { const [drag, setDrag] = useState(null); @@ -32,8 +32,16 @@ export function ConversationRow({ } | null>(null), suppressClick = useRef(false); const distance = 88; - function start(e: PointerEvent) { - if (disabled || e.button !== 0) return; + function start(e: PointerEvent) { + if ( + disabled || + e.button !== 0 || + e.metaKey || + e.ctrlKey || + e.shiftKey || + e.altKey + ) + return; suppressClick.current = false; gesture.current = { x: e.clientX, @@ -44,7 +52,7 @@ export function ConversationRow({ }; e.currentTarget.setPointerCapture(e.pointerId); } - function move(e: PointerEvent) { + function move(e: PointerEvent) { const g = gesture.current; if (!g) return; const dx = e.clientX - g.x, @@ -57,7 +65,7 @@ export function ConversationRow({ g.offset = Math.max(-distance, Math.min(0, g.base + dx)); setDrag(g.offset); } - function finish(e: PointerEvent, cancelled = false) { + function finish(e: PointerEvent, cancelled = false) { const g = gesture.current; if (!g) return; gesture.current = null; @@ -85,12 +93,13 @@ export function ConversationRow({ 删除 - finish(e)} @@ -102,15 +111,15 @@ export function ConversationRow({ } }} onClick={(e) => { - if (suppressClick.current && e.detail !== 0) { + if (disabled || (suppressClick.current && e.detail !== 0)) { + e.preventDefault(); suppressClick.current = false; return; } if (revealed) { + e.preventDefault(); onReveal(null); - return; } - onOpen(); }} > {/* 封面地址沿用服务端目录,不在小型服务器做图片转换。 */} @@ -126,7 +135,7 @@ export function ConversationRow({ day: "numeric", })} - + 删除这段对话? - 「{title}」将从你的对话列表中移除,你将无法继续查看。后台仍保留聊天记录。 + 「{title} + 」将从你的对话列表中移除,你将无法继续查看。后台仍保留聊天记录。 {error && ( diff --git a/src/components/digital-home.tsx b/src/components/digital-home.tsx index ade0646..97ccceb 100644 --- a/src/components/digital-home.tsx +++ b/src/components/digital-home.tsx @@ -2,6 +2,15 @@ /* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */ /** 星港数字人空间:探索、会话、世界书、身份资料和账号内容偏好。 */ import Link from "next/link"; +import { useRouter, useSearchParams } from "next/navigation"; +import { + chatPath, + contentPath, + digitalTabs, + expiredDigitalSessionPath, + type DigitalTab, +} from "@/lib/digital-routes"; +import { useDigitalBack } from "./digital-route-history"; import { useCallback, useEffect, @@ -51,25 +60,53 @@ import { import { ConversationRow, ConversationDeleteDialog } from "./conversation-row"; import { DigitalMessage } from "./digital-message"; import "./digital.css"; -type Tab = "discover" | "chats" | "library" | "me"; +type Tab = DigitalTab; /** 前台管理个人会话偏好;后台方案仅展示覆盖提示,不开放实验操作。 */ export function DigitalHome({ initial, initialSummaries, + initialTab, + initialConversation, + initialDetail, }: { initial: Bootstrap; initialSummaries: Summary[]; + initialTab: Tab; + initialConversation?: Conversation; + initialDetail?: Card; }) { - const [tab, setTab] = useState("discover"), - [boot, setBoot] = useState(initial), + const router = useRouter(); + const tab = initialTab; + const detail = initialDetail ?? null; + const goBack = useDigitalBack( + initialConversation ? "/chats" : digitalTabs[tab], + ); + const [boot, setBoot] = useState(initial), [summaries, setSummaries] = useState(initialSummaries); - const [query, setQuery] = useState(""), - [tag, setTag] = useState("全部"), - [onlyFavorites, setOnlyFavorites] = useState(false); - const [detail, setDetail] = useState(null), - [conversation, setConversation] = useState(null); + const searchParams = useSearchParams(); + const query = (searchParams.get("q") ?? "").slice(0, 200); + const tag = (searchParams.get("tag") ?? "全部").slice(0, 80); + const onlyFavorites = searchParams.get("favorites") === "1"; + function setFilters(next: { + query?: string; + tag?: string; + favorites?: boolean; + }) { + const params = new URLSearchParams(); + const values = { query, tag, favorites: onlyFavorites, ...next }; + if (values.query) params.set("q", values.query.slice(0, 200)); + if (values.tag !== "全部") params.set("tag", values.tag.slice(0, 80)); + if (values.favorites) params.set("favorites", "1"); + const path = `/discover${params.size ? `?${params}` : ""}`; + // 原生 replaceState 与 Next 同步查询参数,地址是筛选的唯一来源,返回时不会被旧组件状态覆盖。 + window.history.replaceState(window.history.state, "", path); + } + const [conversation, setConversation] = useState( + initialConversation ?? null, + ); + const [draftReady, setDraftReady] = useState(false); const [draft, setDraft] = useState(""), - [busy, setBusy] = useState(false), + [busy, setBusy] = useState(initialConversation?.busy ?? false), [opening, setOpening] = useState(false), [error, setError] = useState(""), [notice, setNotice] = useState(""); @@ -77,7 +114,9 @@ export function DigitalHome({ "loading" | "personal" | "managed" | "unknown" >("loading"); const [showSettings, setShowSettings] = useState(false), - [settings, setSettings] = useState(null), + [settings, setSettings] = useState( + initialConversation?.settings ?? null, + ), [profile, setProfile] = useState(initial.profile); const [profileDraft, setProfileDraft] = useState( initial.profile, @@ -117,7 +156,7 @@ export function DigitalHome({ atBottom = useRef(true), touchY = useRef(null), draggingScroll = useRef(false), - currentId = useRef(null), + currentId = useRef(initialConversation?.id ?? null), openSequence = useRef(0); const cards = boot?.catalog.filter((c) => c.kind === "character") ?? [], books = boot?.catalog.filter((c) => c.kind === "worldbook") ?? [], @@ -167,6 +206,16 @@ export function DigitalHome({ async () => setSummaries(await digital("conversations")), [], ); + useEffect(() => { + const controller = new AbortController(); + // 浏览器后退可能恢复 Next 缓存的页面快照,重新核对列表,避免遗漏刚创建或删除的会话。 + digital("conversations", "GET", undefined, controller.signal) + .then((items) => { + if (!controller.signal.aborted) setSummaries(items); + }) + .catch(() => {}); + return () => controller.abort(); + }, []); const reloadBootstrap = useCallback(async () => { const data = await digital("bootstrap"); decisionReceived.current = performance.now(); @@ -300,12 +349,22 @@ export function DigitalHome({ }, [conversationId]); useEffect(() => { if (!conversationId) return; + const frame = requestAnimationFrame(() => { + try { + setDraft(sessionStorage.getItem(`dh-draft:${conversationId}`) ?? ""); + } catch {} + setDraftReady(true); + }); + return () => cancelAnimationFrame(frame); + }, [conversationId]); + useEffect(() => { + if (!conversationId || !draftReady) return; try { sessionStorage.setItem(`dh-draft:${conversationId}`, draft); } catch {} - }, [draft, conversationId]); + }, [draft, conversationId, draftReady]); useEffect(() => { - if (!detail && !showSettings) return; + if (!showSettings) return; const previous = document.activeElement as HTMLElement | null; const dialog = document.querySelector( '.dh-overlay [role="dialog"]', @@ -326,7 +385,6 @@ export function DigitalHome({ setSelectionSheet(null); return; } - setDetail(null); setShowSettings(false); } if (event.key === "Tab") { @@ -348,7 +406,7 @@ export function DigitalHome({ document.removeEventListener("keydown", onKey); previous?.focus(); }; - }, [detail, showSettings]); + }, [showSettings]); /** 选择弹窗聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */ useEffect(() => { if (!selectionSheet) return; @@ -407,6 +465,10 @@ export function DigitalHome({ }; }, [busy, conversationId]); async function openConversation(id: string) { + if (id !== conversation?.id) { + router.push(chatPath(id)); + return; + } closeIdeas(); imeComposing.current = false; setSwipedConversation(null); @@ -433,8 +495,6 @@ export function DigitalHome({ } catch { setDraft(""); } - setTab("chats"); - setDetail(null); } catch (e) { reportError(e); } finally { @@ -451,8 +511,7 @@ export function DigitalHome({ greetingIndex: index, uiDecisionId: boot?.decision.decisionId ?? undefined, }); - await openConversation(c.id); - await refreshSummaries(); + router.push(chatPath(c.id)); } catch (e) { reportError(e); } finally { @@ -545,7 +604,11 @@ export function DigitalHome({ signal: controller.signal, }); if (response.status === 401) { - window.location.assign("/login"); + window.location.assign( + expiredDigitalSessionPath( + window.location.pathname + window.location.search, + ), + ); return; } accepted = response.ok; @@ -668,9 +731,7 @@ export function DigitalHome({ "POST", { messageId: message.id }, ); - await openConversation(result.id); - await refreshSummaries(); - setNotice("已从这里开启新分支,原会话仍然保留"); + router.push(chatPath(result.id)); } catch (e) { reportError(e); } @@ -705,9 +766,9 @@ export function DigitalHome({ setSwipedConversation(null); if (currentId.current === id) { closeIdeas(); - setConversation(null); currentId.current = null; setDraft(""); + router.replace("/chats"); } try { sessionStorage.removeItem(`dh-draft:${id}`); @@ -885,18 +946,9 @@ export function DigitalHome({ URL.revokeObjectURL(url); } function switchTab(value: Tab) { - closeIdeas(); - setSwipedConversation(null); - if (conversation && busy) { - setNotice("请先停止当前回复,再离开会话"); - return; - } - setConversation(null); - currentId.current = null; - if (value === "me" && tab !== "me" && profile) setProfileDraft(profile); - setTab(value); - setError(""); + router.push(digitalTabs[value]); } + const tags = [ "全部", ...new Set(cards.flatMap((c) => c.tags).slice(0, 30)), @@ -1005,12 +1057,14 @@ export function DigitalHome({ ))} ); - useEffect( - () => () => { + useEffect(() => { + // 缓存页面重新显示时重新绑定会话,离开后的旧流请求不能更新下一页。 + currentId.current = conversationId ?? null; + return () => { ideasRequest.current?.abort(); - }, - [], - ); + currentId.current = null; + }; + }, [conversationId]); // UI按消费者返回值决定,组名仅用于归因;C到Z同样可以返回新版UI。 // 缺少value时兼容尚未升级的服务响应。 const modern = @@ -1036,17 +1090,18 @@ export function DigitalHome({ { id: "me", label: "我的身份", icon: UserRound }, ] as const ).map((item) => ( - switchTab(item.id)} + aria-current={tab === item.id ? "page" : undefined} > {item.label} {item.id === "chats" && summaries.length > 0 && ( {summaries.length} )} - + ))} @@ -1086,12 +1141,8 @@ export function DigitalHome({ { - setConversation(null); - currentId.current = null; - }} + aria-label="返回上一页" + onClick={goBack} > @@ -1400,6 +1451,7 @@ export function DigitalHome({ - ) : ( + ) : detail ? null : ( @@ -1490,7 +1542,7 @@ export function DigitalHome({ cards.find( (c) => !profile?.favorites.includes(c.id), ) ?? cards[0]; - if (card) setDetail(card); + if (card) router.push(contentPath(card)); }} > @@ -1511,12 +1563,12 @@ export function DigitalHome({ aria-label="搜索角色" placeholder="搜索名字、性格或故事…" value={query} - onChange={(e) => setQuery(e.target.value)} + onChange={(e) => setFilters({ query: e.target.value })} /> {query && ( setQuery("")} + onClick={() => setFilters({ query: "" })} > @@ -1524,7 +1576,7 @@ export function DigitalHome({ setOnlyFavorites(!onlyFavorites)} + onClick={() => setFilters({ favorites: !onlyFavorites })} > setTag(t)} + onClick={() => setFilters({ tag: t })} > {t} @@ -1551,10 +1603,7 @@ export function DigitalHome({ {filtered.map((c) => ( - setDetail(c)} - > + - + 换一个关键词,或者看看其他故事。 { - setTag("全部"); - setQuery(""); - setOnlyFavorites(false); + setFilters({ + query: "", + tag: "全部", + favorites: false, + }); }} > 看看全部角色 @@ -1630,7 +1681,6 @@ export function DigitalHome({ revealed={swipedConversation === s.id} disabled={opening || deleting} onReveal={setSwipedConversation} - onOpen={() => openConversation(s.id)} onDelete={() => requestDelete(s)} /> ))} @@ -1661,17 +1711,17 @@ export function DigitalHome({ {books.map((b) => ( - setDetail(b)} + href={contentPath(b)} > {b.entriesCount} 条设定 {b.name} {b.description} 查看详情 → - + ))} @@ -1680,17 +1730,17 @@ export function DigitalHome({ {presets.map((b) => ( - setDetail(b)} + href={contentPath(b)} > 对话风格 {b.name} {b.description} 查看详情 → - + ))} > @@ -1741,7 +1791,9 @@ export function DigitalHome({ NSFW 成人内容 - 登录账号默认开启,可随时关闭;保存后用于后续回复。 + + 登录账号默认开启,可随时关闭;保存后用于后续回复。 + )} - - {detail && ( - { - if (e.target === e.currentTarget) setDetail(null); - }} - > - - setDetail(null)} - > - - - {detail.kind === "character" && ( - - - - )} - - + {detail && ( + + + + + 返回上一页 + + {detail.kind === "character" - ? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色` + ? "角色详情" : detail.kind === "worldbook" - ? "WORLD BOOK" - : "STORY PRESET"} + ? "世界书" + : "对话风格"} - {detail.name} - - {detail.tags.map((t) => ( - {t} - ))} - - {detail.description} - {detail.greeting && ( - - {detail.greeting - .replaceAll("{{user}}", profile?.userName ?? "旅人") - .replaceAll("{{char}}", detail.name)} - + + + {detail.kind === "character" && ( + + + )} - {detail.kind === "character" ? ( - <> - start(detail)} - > - {opening ? ( - - ) : ( - - )} - 开启这段故事 - - {detail.alternateGreetings.map((g, i) => ( - start(detail, i + 1)} - > - 另一种相遇 {i + 1} - {g.slice(0, 110)} - + + + {detail.kind === "character" + ? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色` + : detail.kind === "worldbook" + ? "WORLD BOOK" + : "STORY PRESET"} + + {detail.name} + + {detail.tags.map((t) => ( + {t} ))} - > - ) : ( - - 进入任意对话,点击右上角「对话设定」即可使用。 - - )} - {detail.source} - - - - )} + + {detail.description} + {detail.greeting && ( + + {detail.greeting + .replaceAll("{{user}}", profile?.userName ?? "旅人") + .replaceAll("{{char}}", detail.name)} + + )} + {detail.kind === "character" ? ( + <> + start(detail)} + > + {opening ? ( + + ) : ( + + )} + 开启这段故事 + + {detail.alternateGreetings.map((g, i) => ( + start(detail, i + 1)} + > + 另一种相遇 {i + 1} + {g.slice(0, 110)} + + ))} + > + ) : ( + + 进入任意对话,点击右上角「对话设定」即可使用。 + + )} + {detail.source} + + + + )} + {showSettings && settings && ( ("/digital/bootstrap", path), + requireBackendData("/digital/conversations", path), + conversationId + ? requireBackendData( + `/digital/conversations/${conversationId}`, + path, + ) + : undefined, + ]).catch((error) => { + if (error instanceof BackendError && error.status === 404) notFound(); + throw error; + }); + const detail = contentId + ? initial.catalog.find( + (card) => + card.id === contentId && + (tab === "discover" + ? card.kind === "character" + : card.kind !== "character"), + ) + : undefined; + if (contentId && !detail) notFound(); + return ( + + ); +} diff --git a/src/components/digital-route-history.tsx b/src/components/digital-route-history.tsx new file mode 100644 index 0000000..b48edc0 --- /dev/null +++ b/src/components/digital-route-history.tsx @@ -0,0 +1,54 @@ +"use client"; + +/** 记录当前浏览器条目的站内来源;返回优先沿真实历史,直接打开深链时回父页面。 */ +import type { Route } from "next"; +import { useEffect, useRef } from "react"; +import { usePathname, useRouter, useSearchParams } from "next/navigation"; +import { safeDigitalReturnTo } from "@/lib/digital-routes"; + +/** 共享布局持续存在,让不同路由的进入顺序成为浏览器真实历史。 */ +export function DigitalRouteHistory() { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const previous = useRef(null); + useEffect(() => { + const path = + window.location.pathname + window.location.search + window.location.hash; + const state = window.history.state ?? {}; + // 后退恢复的是已有条目,不能把它的来源覆盖成刚离开的页面。 + if (state.stellarNavigation?.path !== path) { + const existing = state.stellarNavigation; + // 筛选只替换当前 URL,不凭空增加一次返回步骤。 + const samePage = + typeof existing?.path === "string" && + new URL(existing.path, window.location.origin).pathname === pathname; + window.history.replaceState( + { + ...state, + stellarNavigation: { + path, + previous: samePage ? existing.previous : previous.current, + }, + }, + "", + path, + ); + } + previous.current = path; + }, [pathname, searchParams]); + return null; +} + +/** 页面内返回按钮与浏览器后退一致;外部打开或新标签页不返回站外。 */ +export function useDigitalBack(fallback: Route) { + const router = useRouter(); + return () => { + const previous = window.history.state?.stellarNavigation?.previous; + if ( + typeof previous === "string" && + safeDigitalReturnTo(previous) === previous + ) + router.back(); + else router.replace(fallback); + }; +} diff --git a/src/components/digital.css b/src/components/digital.css index ea5da52..5e93320 100644 --- a/src/components/digital.css +++ b/src/components/digital.css @@ -121,7 +121,7 @@ flex-direction: column; gap: 9px; } -.dh-sidebar nav button { +.dh-sidebar nav a { display: flex; align-items: center; gap: 14px; @@ -130,15 +130,15 @@ color: var(--dh-muted); text-align: left; } -.dh-sidebar nav button small { +.dh-sidebar nav a small { margin-left: auto; font-size: 11px; } -.dh-sidebar nav button.is-active { +.dh-sidebar nav a.is-active { color: var(--dh-accent); background: color-mix(in srgb, var(--dh-accent) 9%, transparent); } -.dh-sidebar nav button:hover { +.dh-sidebar nav a:hover { background: var(--dh-panel); } .dh-sidebar-bottom { @@ -1963,7 +1963,7 @@ gap: 2px; height: 100%; } - .dh-sidebar nav button { + .dh-sidebar nav a { padding: 7px 3px; display: flex; flex-direction: column; @@ -1973,7 +1973,7 @@ justify-content: center; position: relative; } - .dh-sidebar nav button small { + .dh-sidebar nav a small { position: absolute; top: 0; right: 18px; @@ -1982,10 +1982,10 @@ padding: 0 5px; border-radius: 9px; } - .dh-sidebar nav button.is-active { + .dh-sidebar nav a.is-active { background: none; } - .dh-sidebar nav button.is-active svg { + .dh-sidebar nav a.is-active svg { filter: drop-shadow( 0 0 8px color-mix(in srgb, var(--dh-accent) 45%, transparent) ); @@ -2422,3 +2422,67 @@ html.dh-chat-active body { display: none; } } + +/* 页面导航使用真实链接,视觉与触摸命中范围保持一致。 */ +.dh-sidebar nav a { + cursor: pointer; +} +.dh-conversation-open[aria-disabled="true"] { + opacity: 0.42; + cursor: not-allowed; +} +.dh-detail-page { + padding: 40px 32px; + min-height: 100dvh; +} +.dh-detail-page .dh-detail { + width: min(960px, 100%); + max-height: none; + overflow: visible; + margin: 0 auto; +} +.dh-detail-page .dh-detail-body h1 { + font-size: clamp(26px, 4vw, 38px); + line-height: 1.3; + overflow-wrap: anywhere; +} +.dh-route-message { + display: flex; + min-height: 100dvh; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 20px; + padding: 32px; + text-align: center; +} +.dh-route-message a, +.dh-route-message button { + padding: 12px 24px; + border: 1px solid var(--dh-line); + border-radius: 12px; +} +@media (max-width: 600px) { + .dh-detail-page { + padding: 16px 14px 100px; + } + .dh-detail-page .dh-detail { + max-height: none; + } +} +.dh-detail-nav { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + max-width: 960px; + margin: 0 auto 20px; + color: var(--dh-muted); +} +.dh-app .dh-detail-back { + display: flex; + align-items: center; + gap: 8px; + min-height: 44px; + color: var(--dh-accent); +} diff --git a/src/components/login-form.tsx b/src/components/login-form.tsx index 0a0e5bd..7bddc64 100644 --- a/src/components/login-form.tsx +++ b/src/components/login-form.tsx @@ -2,11 +2,12 @@ /** 独立星港用户账号登录,成功后进入数字人空间。 */ import { useRouter } from "next/navigation"; +import { safeDigitalReturnTo } from "@/lib/digital-routes"; import { Eye, EyeOff, LockKeyhole, Smartphone } from "lucide-react"; import { FormEvent, useState } from "react"; /** 独立用户的登录表单,不保存明文密码。 */ -export function LoginForm() { +export function LoginForm({ returnTo = "/discover" }: { returnTo?: string }) { const router = useRouter(); const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -31,7 +32,7 @@ export function LoginForm() { const payload = await response.json().catch(() => null); throw new Error(payload?.message || "登录失败,请检查账号和密码"); } - router.replace("/discover"); + router.replace(safeDigitalReturnTo(returnTo)); router.refresh(); } catch (error) { setError( diff --git a/src/lib/backend.ts b/src/lib/backend.ts index 7f02f90..7df9374 100644 --- a/src/lib/backend.ts +++ b/src/lib/backend.ts @@ -2,6 +2,7 @@ import "server-only"; import { redirect } from "next/navigation"; +import { expiredDigitalSessionPath } from "@/lib/digital-routes"; import { clearSessionToken, getSessionToken } from "@/lib/session"; import type { ApiEnvelope } from "@/lib/types"; @@ -77,12 +78,16 @@ export async function backendRequest( } /** 页面数据要求登录,失效时通过登出路由清理 Cookie。 */ -export async function requireBackendData(path: string) { +export async function requireBackendData(path: string, returnTo?: string) { try { return await backendRequest(path); } catch (error) { if (error instanceof BackendError && error.status === 401) { - redirect("/api/auth/logout?next=/login"); + redirect( + returnTo + ? expiredDigitalSessionPath(returnTo) + : "/api/auth/logout?next=/login", + ); } throw error; diff --git a/src/lib/digital-routes.ts b/src/lib/digital-routes.ts new file mode 100644 index 0000000..b883043 --- /dev/null +++ b/src/lib/digital-routes.ts @@ -0,0 +1,64 @@ +/** 数字人页面的固定地址与登录回跳校验,禁止把外部输入作为任意跳转目标。 */ + +import type { Route } from "next"; + +/** 顶部和底部导航共享同一份页面映射,保留旧工作台 /me 的兼容入口。 */ +export const digitalTabs = { + discover: "/discover", + chats: "/chats", + library: "/library", + me: "/profile", +} as const; + +/** 数字人导航项。 */ +export type DigitalTab = keyof typeof digitalTabs; + +/** 与后端资源 ID 的格式保持一致,非法深链直接显示不存在。 */ +export function validDigitalId(id: string) { + return /^[a-zA-Z0-9_-]{1,64}$/.test(id); +} + +/** 会话永久地址;导航和创建分支都使用同一个入口。 */ +export function chatPath(id: string): `/chats/${string}` { + return `/chats/${encodeURIComponent(id)}`; +} + +/** 角色与书架内容分别拥有可直接访问的详情页。 */ +export function contentPath(card: { + id: string; + kind: string; +}): `/characters/${string}` | `/library/${string}` { + return `/${card.kind === "character" ? "characters" : "library"}/${encodeURIComponent(card.id)}`; +} + +/** 只接受数字人业务页面,拒绝外站、接口、登录循环与畸形路径。 */ +export function safeDigitalReturnTo(value: string | null | undefined): Route { + if ( + !value || + !value.startsWith("/") || + /^\/[/\\]/.test(value) || + /[\\\u0000-\u0020\u007f]/.test(value) + ) + return "/discover"; + const url = new URL(value, "https://stellar.invalid"); + if ( + url.origin !== "https://stellar.invalid" || + !/^\/(?:discover|profile|chats(?:\/[a-zA-Z0-9_-]{1,64})?|library(?:\/[a-zA-Z0-9_-]{1,64})?|characters\/[a-zA-Z0-9_-]{1,64})$/.test( + url.pathname, + ) + ) + return "/discover"; + return (url.pathname + url.search + url.hash) as Route; +} + +/** 未登录时携带原始页面,登录成功后恢复具体会话而不是固定回首页。 */ +export function digitalLoginPath(returnTo: string): `/login?next=${string}` { + return `/login?next=${encodeURIComponent(safeDigitalReturnTo(returnTo))}`; +} + +/** 过期会话先清理 HttpOnly Cookie,避免代理把登录页重定向回失效会话。 */ +export function expiredDigitalSessionPath( + returnTo: string, +): `/api/auth/logout?next=${string}` { + return `/api/auth/logout?next=${encodeURIComponent(digitalLoginPath(returnTo))}`; +} diff --git a/src/lib/digital.ts b/src/lib/digital.ts index 49c17ff..4c240c8 100644 --- a/src/lib/digital.ts +++ b/src/lib/digital.ts @@ -1,4 +1,6 @@ /** 数字人客户端协议与事件解码,不包含模型凭据或实验操作。 */ +import { expiredDigitalSessionPath } from "./digital-routes"; + /** 前台可见内容摘要,提示词不会下发。 */ export type Card = { id: string; @@ -64,7 +66,11 @@ export async function digital( }); const data = await response.json(); if (response.status === 401) { - window.location.assign("/login"); + window.location.assign( + expiredDigitalSessionPath( + window.location.pathname + window.location.search, + ), + ); throw new Error("登录已过期"); } if (!response.ok || data.success === false) diff --git a/src/proxy.ts b/src/proxy.ts index 11a614a..b801251 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -1,8 +1,13 @@ /** 私有页面会话路由,默认登录后进入数字人空间。 */ import { NextRequest, NextResponse } from "next/server"; +import { digitalLoginPath, safeDigitalReturnTo } from "@/lib/digital-routes"; const protectedRoutes = [ "/discover", + "/chats", + "/characters", + "/library", + "/profile", "/dashboard", "/tasks", "/schedule", @@ -13,6 +18,7 @@ const protectedRoutes = [ const publicRoutes = ["/", "/login"]; const cookieName = process.env.ROLE_USER_SESSION_COOKIE || "role_user_session"; +/** 路由级登录保护;深链携带站内回跳目标,不丢失具体聊天地址。 */ export function proxy(request: NextRequest) { const path = request.nextUrl.pathname; const hasSession = Boolean(request.cookies.get(cookieName)?.value); @@ -22,16 +28,26 @@ export function proxy(request: NextRequest) { const isPublic = publicRoutes.includes(path); if (isProtected && !hasSession) { - return NextResponse.redirect(new URL("/login", request.url)); + return NextResponse.redirect( + new URL(digitalLoginPath(path + request.nextUrl.search), request.url), + ); } if (isPublic && hasSession) { - return NextResponse.redirect(new URL("/discover", request.url)); + return NextResponse.redirect( + new URL( + path === "/login" + ? safeDigitalReturnTo(request.nextUrl.searchParams.get("next")) + : "/discover", + request.url, + ), + ); } return NextResponse.next(); } +/** 只拦截业务页面,不影响 BFF、静态资源和安装文件。 */ export const config = { matcher: [ "/((?!api|_next/static|_next/image|manifest.webmanifest|sw.js|.*\\..*).*)", diff --git a/tests/digital-routes.test.mjs b/tests/digital-routes.test.mjs new file mode 100644 index 0000000..c2a3f0e --- /dev/null +++ b/tests/digital-routes.test.mjs @@ -0,0 +1,80 @@ +/** 页面地址和登录深链回归,不访问真实账号或后端。 */ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + digitalTabs, + validDigitalId, + chatPath, + contentPath, + safeDigitalReturnTo, + digitalLoginPath, + expiredDigitalSessionPath, +} from "../src/lib/digital-routes.ts"; +import { logoutRedirect } from "../src/lib/auth-redirect.ts"; + +test("主要页面与资源详情都有独立地址,身份页不覆盖旧工作台", () => { + assert.equal(new Set(Object.values(digitalTabs)).size, 4); + assert.equal(digitalTabs.me, "/profile"); + assert.equal(chatPath("chat-1"), "/chats/chat-1"); + assert.equal( + contentPath({ id: "role-1", kind: "character" }), + "/characters/role-1", + ); + assert.equal( + contentPath({ id: "book-1", kind: "worldbook" }), + "/library/book-1", + ); + assert.equal( + contentPath({ id: "style-1", kind: "preset" }), + "/library/style-1", + ); +}); + +test("深链格式遵循后端资源 ID 边界", () => { + for (const id of ["chat-1", "a_b", "a".repeat(64)]) + assert.equal(validDigitalId(id), true); + for (const id of ["", "a/b", "../other", "a?b", "a".repeat(65)]) + assert.equal(validDigitalId(id), false); +}); + +test("登录恢复完整会话地址和发现页筛选,不增加固定首页跳转", () => { + for (const path of [ + "/chats/chat-1", + "/characters/role-1", + "/library/book-1", + "/profile", + "/discover?q=hello&favorites=1", + ]) { + assert.equal(safeDigitalReturnTo(path), path); + const login = new URL(digitalLoginPath(path), "https://stellar.invalid"); + assert.equal(login.pathname, "/login"); + assert.equal(login.searchParams.get("next"), path); + const expired = new URL( + expiredDigitalSessionPath(path), + "https://stellar.invalid", + ); + assert.equal(expired.pathname, "/api/auth/logout"); + assert.equal( + logoutRedirect(expired.searchParams.get("next")).headers.get("location"), + digitalLoginPath(path), + ); + } +}); + +test("拒绝外站跳转、登录循环、接口及非法资源路径", () => { + for (const path of [ + undefined, + null, + "https://outside.invalid", + "//outside.invalid", + "/\\outside.invalid", + "/login", + "/api/auth/logout", + "/chats/one/other", + "/chats/a%2fb", + "/characters/", + "/.//outside.invalid", + "/\n/outside.invalid", + ]) + assert.equal(safeDigitalReturnTo(path), "/discover", String(path)); +});
使用你的星港账号,继续未完的故事。
请检查网络后重试。
内容可能已下架,或这段对话已被删除。
- 「{title}」将从你的对话列表中移除,你将无法继续查看。后台仍保留聊天记录。 + 「{title} + 」将从你的对话列表中移除,你将无法继续查看。后台仍保留聊天记录。
diff --git a/src/components/digital-home.tsx b/src/components/digital-home.tsx index ade0646..97ccceb 100644 --- a/src/components/digital-home.tsx +++ b/src/components/digital-home.tsx @@ -2,6 +2,15 @@ /* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */ /** 星港数字人空间:探索、会话、世界书、身份资料和账号内容偏好。 */ import Link from "next/link"; +import { useRouter, useSearchParams } from "next/navigation"; +import { + chatPath, + contentPath, + digitalTabs, + expiredDigitalSessionPath, + type DigitalTab, +} from "@/lib/digital-routes"; +import { useDigitalBack } from "./digital-route-history"; import { useCallback, useEffect, @@ -51,25 +60,53 @@ import { import { ConversationRow, ConversationDeleteDialog } from "./conversation-row"; import { DigitalMessage } from "./digital-message"; import "./digital.css"; -type Tab = "discover" | "chats" | "library" | "me"; +type Tab = DigitalTab; /** 前台管理个人会话偏好;后台方案仅展示覆盖提示,不开放实验操作。 */ export function DigitalHome({ initial, initialSummaries, + initialTab, + initialConversation, + initialDetail, }: { initial: Bootstrap; initialSummaries: Summary[]; + initialTab: Tab; + initialConversation?: Conversation; + initialDetail?: Card; }) { - const [tab, setTab] = useState("discover"), - [boot, setBoot] = useState(initial), + const router = useRouter(); + const tab = initialTab; + const detail = initialDetail ?? null; + const goBack = useDigitalBack( + initialConversation ? "/chats" : digitalTabs[tab], + ); + const [boot, setBoot] = useState(initial), [summaries, setSummaries] = useState(initialSummaries); - const [query, setQuery] = useState(""), - [tag, setTag] = useState("全部"), - [onlyFavorites, setOnlyFavorites] = useState(false); - const [detail, setDetail] = useState(null), - [conversation, setConversation] = useState(null); + const searchParams = useSearchParams(); + const query = (searchParams.get("q") ?? "").slice(0, 200); + const tag = (searchParams.get("tag") ?? "全部").slice(0, 80); + const onlyFavorites = searchParams.get("favorites") === "1"; + function setFilters(next: { + query?: string; + tag?: string; + favorites?: boolean; + }) { + const params = new URLSearchParams(); + const values = { query, tag, favorites: onlyFavorites, ...next }; + if (values.query) params.set("q", values.query.slice(0, 200)); + if (values.tag !== "全部") params.set("tag", values.tag.slice(0, 80)); + if (values.favorites) params.set("favorites", "1"); + const path = `/discover${params.size ? `?${params}` : ""}`; + // 原生 replaceState 与 Next 同步查询参数,地址是筛选的唯一来源,返回时不会被旧组件状态覆盖。 + window.history.replaceState(window.history.state, "", path); + } + const [conversation, setConversation] = useState( + initialConversation ?? null, + ); + const [draftReady, setDraftReady] = useState(false); const [draft, setDraft] = useState(""), - [busy, setBusy] = useState(false), + [busy, setBusy] = useState(initialConversation?.busy ?? false), [opening, setOpening] = useState(false), [error, setError] = useState(""), [notice, setNotice] = useState(""); @@ -77,7 +114,9 @@ export function DigitalHome({ "loading" | "personal" | "managed" | "unknown" >("loading"); const [showSettings, setShowSettings] = useState(false), - [settings, setSettings] = useState(null), + [settings, setSettings] = useState( + initialConversation?.settings ?? null, + ), [profile, setProfile] = useState(initial.profile); const [profileDraft, setProfileDraft] = useState( initial.profile, @@ -117,7 +156,7 @@ export function DigitalHome({ atBottom = useRef(true), touchY = useRef(null), draggingScroll = useRef(false), - currentId = useRef(null), + currentId = useRef(initialConversation?.id ?? null), openSequence = useRef(0); const cards = boot?.catalog.filter((c) => c.kind === "character") ?? [], books = boot?.catalog.filter((c) => c.kind === "worldbook") ?? [], @@ -167,6 +206,16 @@ export function DigitalHome({ async () => setSummaries(await digital("conversations")), [], ); + useEffect(() => { + const controller = new AbortController(); + // 浏览器后退可能恢复 Next 缓存的页面快照,重新核对列表,避免遗漏刚创建或删除的会话。 + digital("conversations", "GET", undefined, controller.signal) + .then((items) => { + if (!controller.signal.aborted) setSummaries(items); + }) + .catch(() => {}); + return () => controller.abort(); + }, []); const reloadBootstrap = useCallback(async () => { const data = await digital("bootstrap"); decisionReceived.current = performance.now(); @@ -300,12 +349,22 @@ export function DigitalHome({ }, [conversationId]); useEffect(() => { if (!conversationId) return; + const frame = requestAnimationFrame(() => { + try { + setDraft(sessionStorage.getItem(`dh-draft:${conversationId}`) ?? ""); + } catch {} + setDraftReady(true); + }); + return () => cancelAnimationFrame(frame); + }, [conversationId]); + useEffect(() => { + if (!conversationId || !draftReady) return; try { sessionStorage.setItem(`dh-draft:${conversationId}`, draft); } catch {} - }, [draft, conversationId]); + }, [draft, conversationId, draftReady]); useEffect(() => { - if (!detail && !showSettings) return; + if (!showSettings) return; const previous = document.activeElement as HTMLElement | null; const dialog = document.querySelector( '.dh-overlay [role="dialog"]', @@ -326,7 +385,6 @@ export function DigitalHome({ setSelectionSheet(null); return; } - setDetail(null); setShowSettings(false); } if (event.key === "Tab") { @@ -348,7 +406,7 @@ export function DigitalHome({ document.removeEventListener("keydown", onKey); previous?.focus(); }; - }, [detail, showSettings]); + }, [showSettings]); /** 选择弹窗聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */ useEffect(() => { if (!selectionSheet) return; @@ -407,6 +465,10 @@ export function DigitalHome({ }; }, [busy, conversationId]); async function openConversation(id: string) { + if (id !== conversation?.id) { + router.push(chatPath(id)); + return; + } closeIdeas(); imeComposing.current = false; setSwipedConversation(null); @@ -433,8 +495,6 @@ export function DigitalHome({ } catch { setDraft(""); } - setTab("chats"); - setDetail(null); } catch (e) { reportError(e); } finally { @@ -451,8 +511,7 @@ export function DigitalHome({ greetingIndex: index, uiDecisionId: boot?.decision.decisionId ?? undefined, }); - await openConversation(c.id); - await refreshSummaries(); + router.push(chatPath(c.id)); } catch (e) { reportError(e); } finally { @@ -545,7 +604,11 @@ export function DigitalHome({ signal: controller.signal, }); if (response.status === 401) { - window.location.assign("/login"); + window.location.assign( + expiredDigitalSessionPath( + window.location.pathname + window.location.search, + ), + ); return; } accepted = response.ok; @@ -668,9 +731,7 @@ export function DigitalHome({ "POST", { messageId: message.id }, ); - await openConversation(result.id); - await refreshSummaries(); - setNotice("已从这里开启新分支,原会话仍然保留"); + router.push(chatPath(result.id)); } catch (e) { reportError(e); } @@ -705,9 +766,9 @@ export function DigitalHome({ setSwipedConversation(null); if (currentId.current === id) { closeIdeas(); - setConversation(null); currentId.current = null; setDraft(""); + router.replace("/chats"); } try { sessionStorage.removeItem(`dh-draft:${id}`); @@ -885,18 +946,9 @@ export function DigitalHome({ URL.revokeObjectURL(url); } function switchTab(value: Tab) { - closeIdeas(); - setSwipedConversation(null); - if (conversation && busy) { - setNotice("请先停止当前回复,再离开会话"); - return; - } - setConversation(null); - currentId.current = null; - if (value === "me" && tab !== "me" && profile) setProfileDraft(profile); - setTab(value); - setError(""); + router.push(digitalTabs[value]); } + const tags = [ "全部", ...new Set(cards.flatMap((c) => c.tags).slice(0, 30)), @@ -1005,12 +1057,14 @@ export function DigitalHome({ ))} ); - useEffect( - () => () => { + useEffect(() => { + // 缓存页面重新显示时重新绑定会话,离开后的旧流请求不能更新下一页。 + currentId.current = conversationId ?? null; + return () => { ideasRequest.current?.abort(); - }, - [], - ); + currentId.current = null; + }; + }, [conversationId]); // UI按消费者返回值决定,组名仅用于归因;C到Z同样可以返回新版UI。 // 缺少value时兼容尚未升级的服务响应。 const modern = @@ -1036,17 +1090,18 @@ export function DigitalHome({ { id: "me", label: "我的身份", icon: UserRound }, ] as const ).map((item) => ( - switchTab(item.id)} + aria-current={tab === item.id ? "page" : undefined} > {item.label} {item.id === "chats" && summaries.length > 0 && ( {summaries.length} )} - + ))} @@ -1086,12 +1141,8 @@ export function DigitalHome({ { - setConversation(null); - currentId.current = null; - }} + aria-label="返回上一页" + onClick={goBack} > @@ -1400,6 +1451,7 @@ export function DigitalHome({ - ) : ( + ) : detail ? null : ( @@ -1490,7 +1542,7 @@ export function DigitalHome({ cards.find( (c) => !profile?.favorites.includes(c.id), ) ?? cards[0]; - if (card) setDetail(card); + if (card) router.push(contentPath(card)); }} > @@ -1511,12 +1563,12 @@ export function DigitalHome({ aria-label="搜索角色" placeholder="搜索名字、性格或故事…" value={query} - onChange={(e) => setQuery(e.target.value)} + onChange={(e) => setFilters({ query: e.target.value })} /> {query && ( setQuery("")} + onClick={() => setFilters({ query: "" })} > @@ -1524,7 +1576,7 @@ export function DigitalHome({ setOnlyFavorites(!onlyFavorites)} + onClick={() => setFilters({ favorites: !onlyFavorites })} > setTag(t)} + onClick={() => setFilters({ tag: t })} > {t} @@ -1551,10 +1603,7 @@ export function DigitalHome({ {filtered.map((c) => ( - setDetail(c)} - > + - + 换一个关键词,或者看看其他故事。 { - setTag("全部"); - setQuery(""); - setOnlyFavorites(false); + setFilters({ + query: "", + tag: "全部", + favorites: false, + }); }} > 看看全部角色 @@ -1630,7 +1681,6 @@ export function DigitalHome({ revealed={swipedConversation === s.id} disabled={opening || deleting} onReveal={setSwipedConversation} - onOpen={() => openConversation(s.id)} onDelete={() => requestDelete(s)} /> ))} @@ -1661,17 +1711,17 @@ export function DigitalHome({ {books.map((b) => ( - setDetail(b)} + href={contentPath(b)} > {b.entriesCount} 条设定 {b.name} {b.description} 查看详情 → - + ))} @@ -1680,17 +1730,17 @@ export function DigitalHome({ {presets.map((b) => ( - setDetail(b)} + href={contentPath(b)} > 对话风格 {b.name} {b.description} 查看详情 → - + ))} > @@ -1741,7 +1791,9 @@ export function DigitalHome({ NSFW 成人内容 - 登录账号默认开启,可随时关闭;保存后用于后续回复。 + + 登录账号默认开启,可随时关闭;保存后用于后续回复。 + )} - - {detail && ( - { - if (e.target === e.currentTarget) setDetail(null); - }} - > - - setDetail(null)} - > - - - {detail.kind === "character" && ( - - - - )} - - + {detail && ( + + + + + 返回上一页 + + {detail.kind === "character" - ? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色` + ? "角色详情" : detail.kind === "worldbook" - ? "WORLD BOOK" - : "STORY PRESET"} + ? "世界书" + : "对话风格"} - {detail.name} - - {detail.tags.map((t) => ( - {t} - ))} - - {detail.description} - {detail.greeting && ( - - {detail.greeting - .replaceAll("{{user}}", profile?.userName ?? "旅人") - .replaceAll("{{char}}", detail.name)} - + + + {detail.kind === "character" && ( + + + )} - {detail.kind === "character" ? ( - <> - start(detail)} - > - {opening ? ( - - ) : ( - - )} - 开启这段故事 - - {detail.alternateGreetings.map((g, i) => ( - start(detail, i + 1)} - > - 另一种相遇 {i + 1} - {g.slice(0, 110)} - + + + {detail.kind === "character" + ? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色` + : detail.kind === "worldbook" + ? "WORLD BOOK" + : "STORY PRESET"} + + {detail.name} + + {detail.tags.map((t) => ( + {t} ))} - > - ) : ( - - 进入任意对话,点击右上角「对话设定」即可使用。 - - )} - {detail.source} - - - - )} + + {detail.description} + {detail.greeting && ( + + {detail.greeting + .replaceAll("{{user}}", profile?.userName ?? "旅人") + .replaceAll("{{char}}", detail.name)} + + )} + {detail.kind === "character" ? ( + <> + start(detail)} + > + {opening ? ( + + ) : ( + + )} + 开启这段故事 + + {detail.alternateGreetings.map((g, i) => ( + start(detail, i + 1)} + > + 另一种相遇 {i + 1} + {g.slice(0, 110)} + + ))} + > + ) : ( + + 进入任意对话,点击右上角「对话设定」即可使用。 + + )} + {detail.source} + + + + )} + {showSettings && settings && ( ("/digital/bootstrap", path), + requireBackendData("/digital/conversations", path), + conversationId + ? requireBackendData( + `/digital/conversations/${conversationId}`, + path, + ) + : undefined, + ]).catch((error) => { + if (error instanceof BackendError && error.status === 404) notFound(); + throw error; + }); + const detail = contentId + ? initial.catalog.find( + (card) => + card.id === contentId && + (tab === "discover" + ? card.kind === "character" + : card.kind !== "character"), + ) + : undefined; + if (contentId && !detail) notFound(); + return ( + + ); +} diff --git a/src/components/digital-route-history.tsx b/src/components/digital-route-history.tsx new file mode 100644 index 0000000..b48edc0 --- /dev/null +++ b/src/components/digital-route-history.tsx @@ -0,0 +1,54 @@ +"use client"; + +/** 记录当前浏览器条目的站内来源;返回优先沿真实历史,直接打开深链时回父页面。 */ +import type { Route } from "next"; +import { useEffect, useRef } from "react"; +import { usePathname, useRouter, useSearchParams } from "next/navigation"; +import { safeDigitalReturnTo } from "@/lib/digital-routes"; + +/** 共享布局持续存在,让不同路由的进入顺序成为浏览器真实历史。 */ +export function DigitalRouteHistory() { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const previous = useRef(null); + useEffect(() => { + const path = + window.location.pathname + window.location.search + window.location.hash; + const state = window.history.state ?? {}; + // 后退恢复的是已有条目,不能把它的来源覆盖成刚离开的页面。 + if (state.stellarNavigation?.path !== path) { + const existing = state.stellarNavigation; + // 筛选只替换当前 URL,不凭空增加一次返回步骤。 + const samePage = + typeof existing?.path === "string" && + new URL(existing.path, window.location.origin).pathname === pathname; + window.history.replaceState( + { + ...state, + stellarNavigation: { + path, + previous: samePage ? existing.previous : previous.current, + }, + }, + "", + path, + ); + } + previous.current = path; + }, [pathname, searchParams]); + return null; +} + +/** 页面内返回按钮与浏览器后退一致;外部打开或新标签页不返回站外。 */ +export function useDigitalBack(fallback: Route) { + const router = useRouter(); + return () => { + const previous = window.history.state?.stellarNavigation?.previous; + if ( + typeof previous === "string" && + safeDigitalReturnTo(previous) === previous + ) + router.back(); + else router.replace(fallback); + }; +} diff --git a/src/components/digital.css b/src/components/digital.css index ea5da52..5e93320 100644 --- a/src/components/digital.css +++ b/src/components/digital.css @@ -121,7 +121,7 @@ flex-direction: column; gap: 9px; } -.dh-sidebar nav button { +.dh-sidebar nav a { display: flex; align-items: center; gap: 14px; @@ -130,15 +130,15 @@ color: var(--dh-muted); text-align: left; } -.dh-sidebar nav button small { +.dh-sidebar nav a small { margin-left: auto; font-size: 11px; } -.dh-sidebar nav button.is-active { +.dh-sidebar nav a.is-active { color: var(--dh-accent); background: color-mix(in srgb, var(--dh-accent) 9%, transparent); } -.dh-sidebar nav button:hover { +.dh-sidebar nav a:hover { background: var(--dh-panel); } .dh-sidebar-bottom { @@ -1963,7 +1963,7 @@ gap: 2px; height: 100%; } - .dh-sidebar nav button { + .dh-sidebar nav a { padding: 7px 3px; display: flex; flex-direction: column; @@ -1973,7 +1973,7 @@ justify-content: center; position: relative; } - .dh-sidebar nav button small { + .dh-sidebar nav a small { position: absolute; top: 0; right: 18px; @@ -1982,10 +1982,10 @@ padding: 0 5px; border-radius: 9px; } - .dh-sidebar nav button.is-active { + .dh-sidebar nav a.is-active { background: none; } - .dh-sidebar nav button.is-active svg { + .dh-sidebar nav a.is-active svg { filter: drop-shadow( 0 0 8px color-mix(in srgb, var(--dh-accent) 45%, transparent) ); @@ -2422,3 +2422,67 @@ html.dh-chat-active body { display: none; } } + +/* 页面导航使用真实链接,视觉与触摸命中范围保持一致。 */ +.dh-sidebar nav a { + cursor: pointer; +} +.dh-conversation-open[aria-disabled="true"] { + opacity: 0.42; + cursor: not-allowed; +} +.dh-detail-page { + padding: 40px 32px; + min-height: 100dvh; +} +.dh-detail-page .dh-detail { + width: min(960px, 100%); + max-height: none; + overflow: visible; + margin: 0 auto; +} +.dh-detail-page .dh-detail-body h1 { + font-size: clamp(26px, 4vw, 38px); + line-height: 1.3; + overflow-wrap: anywhere; +} +.dh-route-message { + display: flex; + min-height: 100dvh; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 20px; + padding: 32px; + text-align: center; +} +.dh-route-message a, +.dh-route-message button { + padding: 12px 24px; + border: 1px solid var(--dh-line); + border-radius: 12px; +} +@media (max-width: 600px) { + .dh-detail-page { + padding: 16px 14px 100px; + } + .dh-detail-page .dh-detail { + max-height: none; + } +} +.dh-detail-nav { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + max-width: 960px; + margin: 0 auto 20px; + color: var(--dh-muted); +} +.dh-app .dh-detail-back { + display: flex; + align-items: center; + gap: 8px; + min-height: 44px; + color: var(--dh-accent); +} diff --git a/src/components/login-form.tsx b/src/components/login-form.tsx index 0a0e5bd..7bddc64 100644 --- a/src/components/login-form.tsx +++ b/src/components/login-form.tsx @@ -2,11 +2,12 @@ /** 独立星港用户账号登录,成功后进入数字人空间。 */ import { useRouter } from "next/navigation"; +import { safeDigitalReturnTo } from "@/lib/digital-routes"; import { Eye, EyeOff, LockKeyhole, Smartphone } from "lucide-react"; import { FormEvent, useState } from "react"; /** 独立用户的登录表单,不保存明文密码。 */ -export function LoginForm() { +export function LoginForm({ returnTo = "/discover" }: { returnTo?: string }) { const router = useRouter(); const [error, setError] = useState(""); const [pending, setPending] = useState(false); @@ -31,7 +32,7 @@ export function LoginForm() { const payload = await response.json().catch(() => null); throw new Error(payload?.message || "登录失败,请检查账号和密码"); } - router.replace("/discover"); + router.replace(safeDigitalReturnTo(returnTo)); router.refresh(); } catch (error) { setError( diff --git a/src/lib/backend.ts b/src/lib/backend.ts index 7f02f90..7df9374 100644 --- a/src/lib/backend.ts +++ b/src/lib/backend.ts @@ -2,6 +2,7 @@ import "server-only"; import { redirect } from "next/navigation"; +import { expiredDigitalSessionPath } from "@/lib/digital-routes"; import { clearSessionToken, getSessionToken } from "@/lib/session"; import type { ApiEnvelope } from "@/lib/types"; @@ -77,12 +78,16 @@ export async function backendRequest( } /** 页面数据要求登录,失效时通过登出路由清理 Cookie。 */ -export async function requireBackendData(path: string) { +export async function requireBackendData(path: string, returnTo?: string) { try { return await backendRequest(path); } catch (error) { if (error instanceof BackendError && error.status === 401) { - redirect("/api/auth/logout?next=/login"); + redirect( + returnTo + ? expiredDigitalSessionPath(returnTo) + : "/api/auth/logout?next=/login", + ); } throw error; diff --git a/src/lib/digital-routes.ts b/src/lib/digital-routes.ts new file mode 100644 index 0000000..b883043 --- /dev/null +++ b/src/lib/digital-routes.ts @@ -0,0 +1,64 @@ +/** 数字人页面的固定地址与登录回跳校验,禁止把外部输入作为任意跳转目标。 */ + +import type { Route } from "next"; + +/** 顶部和底部导航共享同一份页面映射,保留旧工作台 /me 的兼容入口。 */ +export const digitalTabs = { + discover: "/discover", + chats: "/chats", + library: "/library", + me: "/profile", +} as const; + +/** 数字人导航项。 */ +export type DigitalTab = keyof typeof digitalTabs; + +/** 与后端资源 ID 的格式保持一致,非法深链直接显示不存在。 */ +export function validDigitalId(id: string) { + return /^[a-zA-Z0-9_-]{1,64}$/.test(id); +} + +/** 会话永久地址;导航和创建分支都使用同一个入口。 */ +export function chatPath(id: string): `/chats/${string}` { + return `/chats/${encodeURIComponent(id)}`; +} + +/** 角色与书架内容分别拥有可直接访问的详情页。 */ +export function contentPath(card: { + id: string; + kind: string; +}): `/characters/${string}` | `/library/${string}` { + return `/${card.kind === "character" ? "characters" : "library"}/${encodeURIComponent(card.id)}`; +} + +/** 只接受数字人业务页面,拒绝外站、接口、登录循环与畸形路径。 */ +export function safeDigitalReturnTo(value: string | null | undefined): Route { + if ( + !value || + !value.startsWith("/") || + /^\/[/\\]/.test(value) || + /[\\\u0000-\u0020\u007f]/.test(value) + ) + return "/discover"; + const url = new URL(value, "https://stellar.invalid"); + if ( + url.origin !== "https://stellar.invalid" || + !/^\/(?:discover|profile|chats(?:\/[a-zA-Z0-9_-]{1,64})?|library(?:\/[a-zA-Z0-9_-]{1,64})?|characters\/[a-zA-Z0-9_-]{1,64})$/.test( + url.pathname, + ) + ) + return "/discover"; + return (url.pathname + url.search + url.hash) as Route; +} + +/** 未登录时携带原始页面,登录成功后恢复具体会话而不是固定回首页。 */ +export function digitalLoginPath(returnTo: string): `/login?next=${string}` { + return `/login?next=${encodeURIComponent(safeDigitalReturnTo(returnTo))}`; +} + +/** 过期会话先清理 HttpOnly Cookie,避免代理把登录页重定向回失效会话。 */ +export function expiredDigitalSessionPath( + returnTo: string, +): `/api/auth/logout?next=${string}` { + return `/api/auth/logout?next=${encodeURIComponent(digitalLoginPath(returnTo))}`; +} diff --git a/src/lib/digital.ts b/src/lib/digital.ts index 49c17ff..4c240c8 100644 --- a/src/lib/digital.ts +++ b/src/lib/digital.ts @@ -1,4 +1,6 @@ /** 数字人客户端协议与事件解码,不包含模型凭据或实验操作。 */ +import { expiredDigitalSessionPath } from "./digital-routes"; + /** 前台可见内容摘要,提示词不会下发。 */ export type Card = { id: string; @@ -64,7 +66,11 @@ export async function digital( }); const data = await response.json(); if (response.status === 401) { - window.location.assign("/login"); + window.location.assign( + expiredDigitalSessionPath( + window.location.pathname + window.location.search, + ), + ); throw new Error("登录已过期"); } if (!response.ok || data.success === false) diff --git a/src/proxy.ts b/src/proxy.ts index 11a614a..b801251 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -1,8 +1,13 @@ /** 私有页面会话路由,默认登录后进入数字人空间。 */ import { NextRequest, NextResponse } from "next/server"; +import { digitalLoginPath, safeDigitalReturnTo } from "@/lib/digital-routes"; const protectedRoutes = [ "/discover", + "/chats", + "/characters", + "/library", + "/profile", "/dashboard", "/tasks", "/schedule", @@ -13,6 +18,7 @@ const protectedRoutes = [ const publicRoutes = ["/", "/login"]; const cookieName = process.env.ROLE_USER_SESSION_COOKIE || "role_user_session"; +/** 路由级登录保护;深链携带站内回跳目标,不丢失具体聊天地址。 */ export function proxy(request: NextRequest) { const path = request.nextUrl.pathname; const hasSession = Boolean(request.cookies.get(cookieName)?.value); @@ -22,16 +28,26 @@ export function proxy(request: NextRequest) { const isPublic = publicRoutes.includes(path); if (isProtected && !hasSession) { - return NextResponse.redirect(new URL("/login", request.url)); + return NextResponse.redirect( + new URL(digitalLoginPath(path + request.nextUrl.search), request.url), + ); } if (isPublic && hasSession) { - return NextResponse.redirect(new URL("/discover", request.url)); + return NextResponse.redirect( + new URL( + path === "/login" + ? safeDigitalReturnTo(request.nextUrl.searchParams.get("next")) + : "/discover", + request.url, + ), + ); } return NextResponse.next(); } +/** 只拦截业务页面,不影响 BFF、静态资源和安装文件。 */ export const config = { matcher: [ "/((?!api|_next/static|_next/image|manifest.webmanifest|sw.js|.*\\..*).*)", diff --git a/tests/digital-routes.test.mjs b/tests/digital-routes.test.mjs new file mode 100644 index 0000000..c2a3f0e --- /dev/null +++ b/tests/digital-routes.test.mjs @@ -0,0 +1,80 @@ +/** 页面地址和登录深链回归,不访问真实账号或后端。 */ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + digitalTabs, + validDigitalId, + chatPath, + contentPath, + safeDigitalReturnTo, + digitalLoginPath, + expiredDigitalSessionPath, +} from "../src/lib/digital-routes.ts"; +import { logoutRedirect } from "../src/lib/auth-redirect.ts"; + +test("主要页面与资源详情都有独立地址,身份页不覆盖旧工作台", () => { + assert.equal(new Set(Object.values(digitalTabs)).size, 4); + assert.equal(digitalTabs.me, "/profile"); + assert.equal(chatPath("chat-1"), "/chats/chat-1"); + assert.equal( + contentPath({ id: "role-1", kind: "character" }), + "/characters/role-1", + ); + assert.equal( + contentPath({ id: "book-1", kind: "worldbook" }), + "/library/book-1", + ); + assert.equal( + contentPath({ id: "style-1", kind: "preset" }), + "/library/style-1", + ); +}); + +test("深链格式遵循后端资源 ID 边界", () => { + for (const id of ["chat-1", "a_b", "a".repeat(64)]) + assert.equal(validDigitalId(id), true); + for (const id of ["", "a/b", "../other", "a?b", "a".repeat(65)]) + assert.equal(validDigitalId(id), false); +}); + +test("登录恢复完整会话地址和发现页筛选,不增加固定首页跳转", () => { + for (const path of [ + "/chats/chat-1", + "/characters/role-1", + "/library/book-1", + "/profile", + "/discover?q=hello&favorites=1", + ]) { + assert.equal(safeDigitalReturnTo(path), path); + const login = new URL(digitalLoginPath(path), "https://stellar.invalid"); + assert.equal(login.pathname, "/login"); + assert.equal(login.searchParams.get("next"), path); + const expired = new URL( + expiredDigitalSessionPath(path), + "https://stellar.invalid", + ); + assert.equal(expired.pathname, "/api/auth/logout"); + assert.equal( + logoutRedirect(expired.searchParams.get("next")).headers.get("location"), + digitalLoginPath(path), + ); + } +}); + +test("拒绝外站跳转、登录循环、接口及非法资源路径", () => { + for (const path of [ + undefined, + null, + "https://outside.invalid", + "//outside.invalid", + "/\\outside.invalid", + "/login", + "/api/auth/logout", + "/chats/one/other", + "/chats/a%2fb", + "/characters/", + "/.//outside.invalid", + "/\n/outside.invalid", + ]) + assert.equal(safeDigitalReturnTo(path), "/discover", String(path)); +});
{b.description}
{detail.description}
- {detail.greeting - .replaceAll("{{user}}", profile?.userName ?? "旅人") - .replaceAll("{{char}}", detail.name)} -
{g.slice(0, 110)}
- 进入任意对话,点击右上角「对话设定」即可使用。 -
+ {detail.greeting + .replaceAll("{{user}}", profile?.userName ?? "旅人") + .replaceAll("{{char}}", detail.name)} +
+ 进入任意对话,点击右上角「对话设定」即可使用。 +