diff --git a/README.md b/README.md index 757a3b9..5dff522 100644 --- a/README.md +++ b/README.md @@ -195,3 +195,13 @@ NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成 路由与深链回归:`node --experimental-strip-types --test tests/*.test.mjs`;类型检查和构建按上面的项目命令执行。 `pnpm typecheck` 会先清理生产路由类型目录 `.next/types` 并执行 `next typegen`,再运行 TypeScript。这样 CI 在迁移页面目录或新增路由后不会复用上一版的路由声明;不清理整个构建产物目录。 + +## 聊天体验与会话管理 + +- `src/components/conversation-list.tsx` 提供服务端历史标题/消息搜索、置顶与重命名;`conversation-dialogs.tsx` 统一命名和分支确认的居中表单。 +- 前台删除可在 30 秒内撤销,后台可恢复历史删除。分支保存名称、父会话和消息锚点,可跳回原故事。 +- `use-chat-reading.ts` 按会话保存本标签页的消息锚点和偏移;上翻时新回复只提示,点击后才回到底部。 +- `src/lib/digital-stream.ts` 必须收到 SSE done 才确认结束,异常断流保留部分内容。发送前保存请求标识,重试复用同一标识;刷新先对照服务端记录,避免重复发送。 +- 发现页区分最近聊天、收藏和新角色;详情可展开备用开场全文。账号身份为新会话默认值,当前会话设定仅影响自己的后续回复,NSFW 是账号范围。 + +以上管理功能需要配套后端 `019_conversation_management.sql` 迁移及接口;不要只发布前台。 diff --git a/src/app/api/digital/[...path]/route.ts b/src/app/api/digital/[...path]/route.ts index 20a7ff0..2758ea2 100644 --- a/src/app/api/digital/[...path]/route.ts +++ b/src/app/api/digital/[...path]/route.ts @@ -33,7 +33,7 @@ async function proxy( const { path } = await context.params; const joined = path.join("/"); if ( - !/^(bootstrap|profile|exposure|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|suggestions|style-policy|messages\/[a-zA-Z0-9_-]+))?)?)$/.test( + !/^(bootstrap|profile|exposure|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|restore|suggestions|style-policy|messages\/[a-zA-Z0-9_-]+))?)?)$/.test( joined, ) ) @@ -55,6 +55,12 @@ async function proxy( return Response.json({ message: "请求来源不合法" }, { status: 403 }); } } + const search = + request.method === "GET" && joined === "conversations" + ? new URL(request.url).searchParams.get("q") + : null; + const query = + search === null ? "" : `?q=${encodeURIComponent(search.slice(0, 100))}`; const token = await getSessionToken(); if (!token) return Response.json({ message: "请先登录" }, { status: 401 }); const headers = new Headers({ @@ -63,7 +69,7 @@ async function proxy( }); try { const response = await fetch( - `${getBackendBaseUrl().replace(/\/$/, "")}/digital/${joined}`, + `${getBackendBaseUrl().replace(/\/$/, "")}/digital/${joined}${query}`, { method: request.method, headers, diff --git a/src/components/conversation-dialogs.tsx b/src/components/conversation-dialogs.tsx new file mode 100644 index 0000000..1496db6 --- /dev/null +++ b/src/components/conversation-dialogs.tsx @@ -0,0 +1,81 @@ +"use client"; +/** 会话命名和分支确认共用居中表单,失败时保留输入并允许重试。 */ +import { useEffect, useId, useRef, useState, type ReactNode } from "react"; + +/** 提交过程锁定重复操作,Escape 与取消均保留原会话。 */ +export function ConversationTitleDialog({ + heading, + initialTitle, + preview, + onCancel, + onSubmit, +}: { + heading: string; + initialTitle: string; + preview?: ReactNode; + onCancel: () => void; + onSubmit: (title: string) => Promise; +}) { + const ref = useRef(null), + lock = useRef(false), + id = useId(); + const [title, setTitle] = useState(initialTitle), + [busy, setBusy] = useState(false), + [error, setError] = useState(""); + useEffect(() => { + const dialog = ref.current; + dialog?.showModal(); + return () => dialog?.close(); + }, []); + return ( + { + e.preventDefault(); + if (!lock.current) onCancel(); + }} + > +
{ + e.preventDefault(); + if (lock.current || !title.trim()) return; + lock.current = true; + setBusy(true); + setError(""); + try { + await onSubmit(title.trim()); + } catch (e) { + setError(e instanceof Error ? e.message : "保存失败,请重试"); + } finally { + lock.current = false; + setBusy(false); + } + }} + > +

{heading}

+ {preview} + + {error &&

{error}

} +
+ + +
+
+
+ ); +} diff --git a/src/components/conversation-list.tsx b/src/components/conversation-list.tsx new file mode 100644 index 0000000..a00d2d2 --- /dev/null +++ b/src/components/conversation-list.tsx @@ -0,0 +1,153 @@ +"use client"; +/** 会话列表的服务端搜索、命名和置顶;删除仍通过独立确认流程处理。 */ +import { useEffect, useRef, useState } from "react"; +import { digital, type Card, type Summary } from "@/lib/digital"; +import { ConversationRow } from "./conversation-row"; +import { ConversationTitleDialog } from "./conversation-dialogs"; + +/** 搜索覆盖历史标题和消息;迟到查询不能覆盖新关键词或恢复全部列表。 */ +export function ConversationList({ + summaries, + cards, + disabled, + onDelete, + onRefresh, + onNotice, +}: { + summaries: Summary[]; + cards: Card[]; + disabled: boolean; + onDelete: (summary: Summary) => void; + onRefresh: () => Promise; + onNotice: (message: string) => void; +}) { + const [query, setQuery] = useState(""), + [results, setResults] = useState([]), + [resultQuery, setResultQuery] = useState(""), + [loading, setLoading] = useState(false), + [error, setError] = useState(""), + [swiped, setSwiped] = useState(null), + [renaming, setRenaming] = useState(null), + [pending, setPending] = useState(null); + const lock = useRef(false); + useEffect(() => { + if (!query.trim()) return; + const controller = new AbortController(); + const timer = setTimeout(() => { + setLoading(true); + setError(""); + digital( + `conversations?q=${encodeURIComponent(query.trim())}`, + "GET", + undefined, + controller.signal, + ) + .then((items) => { + if (!controller.signal.aborted) { + setResults(items); + setResultQuery(query.trim()); + } + }) + .catch((e) => { + if (!controller.signal.aborted) + setError(e instanceof Error ? e.message : "搜索失败"); + }) + .finally(() => { + if (!controller.signal.aborted) setLoading(false); + }); + }, 250); + return () => { + clearTimeout(timer); + controller.abort(); + }; + }, [query, summaries]); + async function save( + summary: Summary, + patch: { title?: string; pinned?: boolean }, + ) { + await digital(`conversations/${summary.id}`, "PATCH", patch); + setResults((items) => + items.map((item) => + item.id === summary.id ? { ...item, ...patch } : item, + ), + ); + await onRefresh(); + } + const items = [...(query.trim() ? resultQuery === query.trim() ? results : [] : summaries)].sort((a,b) => Number(!!b.pinned)-Number(!!a.pinned) || Date.parse(b.updatedAt)-Date.parse(a.updatedAt)); + return ( + <> + + {query.trim() && !error && (loading || resultQuery !== query.trim()) && ( +

正在搜索…

+ )} + {query.trim() && error &&

{error}

} +
+ {items.map((summary) => ( +
+ card.id === summary.characterId)} + revealed={swiped === summary.id} + disabled={disabled || pending === summary.id} + onReveal={setSwiped} + onDelete={() => onDelete(summary)} + /> +
+ + +
+
+ ))} +
+ {query.trim() && + resultQuery === query.trim() && + !loading && + !error && + !items.length &&

没有找到匹配的对话。

} + {renaming && ( + setRenaming(null)} + onSubmit={async (title) => { + await save(renaming, { title }); + setRenaming(null); + onNotice("对话名称已保存"); + }} + /> + )} + + ); +} diff --git a/src/components/conversation-row.tsx b/src/components/conversation-row.tsx index a79ed4e..6c0de1a 100644 --- a/src/components/conversation-row.tsx +++ b/src/components/conversation-row.tsx @@ -126,8 +126,13 @@ export function ConversationRow({ {/* eslint-disable-next-line @next/next/no-img-element */}
-

{summary.title}

-

{card?.description || "继续这段私人对话"}

+

+ {summary.pinned ? "置顶 · " : ""} + {summary.title} +

+

+ {summary.lastMessage || card?.description || "继续这段私人对话"} +

{new Date(summary.updatedAt).toLocaleDateString("zh-CN", { diff --git a/src/components/digital-home.tsx b/src/components/digital-home.tsx index 97ccceb..42639ac 100644 --- a/src/components/digital-home.tsx +++ b/src/components/digital-home.tsx @@ -10,6 +10,7 @@ import { expiredDigitalSessionPath, type DigitalTab, } from "@/lib/digital-routes"; +import { mergeConversationSnapshot } from "@/lib/digital-recovery"; import { useDigitalBack } from "./digital-route-history"; import { useCallback, @@ -57,7 +58,10 @@ import { type Summary, type Bootstrap, } from "@/lib/digital"; -import { ConversationRow, ConversationDeleteDialog } from "./conversation-row"; +import { ConversationDeleteDialog } from "./conversation-row"; +import { ConversationList } from "./conversation-list"; +import { ConversationTitleDialog } from "./conversation-dialogs"; +import { useChatReading } from "./use-chat-reading"; import { DigitalMessage } from "./digital-message"; import "./digital.css"; type Tab = DigitalTab; @@ -105,6 +109,22 @@ export function DigitalHome({ initialConversation ?? null, ); const [draftReady, setDraftReady] = useState(false); + const [branchTarget, setBranchTarget] = useState(null); + const [undo, setUndo] = useState<{ + id: string; + title: string; + until: number; + } | null>(null); + const [undoBusy, setUndoBusy] = useState(false); + const undoLock = useRef(false); + const [interrupted, setInterrupted] = useState(false); + const [canRetryRequest, setCanRetryRequest] = useState(false); + const undoKey = `dh-undo:${initial.account}`; + const pendingSend = useRef<{ + id: string; + requestId: string; + content: string; + } | null>(null); const [draft, setDraft] = useState(""), [busy, setBusy] = useState(initialConversation?.busy ?? false), [opening, setOpening] = useState(false), @@ -129,9 +149,6 @@ export function DigitalHome({ bookIds: string[]; }>({ bookIds: [] }); const selectionTrigger = useRef(null); - const [swipedConversation, setSwipedConversation] = useState( - null, - ); const [deleteTarget, setDeleteTarget] = useState(null), [deleting, setDeleting] = useState(false), [deleteError, setDeleteError] = useState(""); @@ -275,36 +292,36 @@ export function DigitalHome({ const timer = setTimeout(() => setNotice(""), 3500); return () => clearTimeout(timer); }, [notice]); + const unread = useChatReading( + conversationId, + viewport, + messagesElement, + atBottom, + draggingScroll, + setShowJump, + ); useEffect(() => { - const el = messagesElement.current, - view = viewport.current; - if (!el || !view) return; - let frame = 0; - const follow = () => { - cancelAnimationFrame(frame); - frame = requestAnimationFrame(() => { - if (!atBottom.current) return; - view.scrollTo({ top: view.scrollHeight, behavior: "instant" }); - setShowJump(false); - }); - }; - // 同时观察内容与可视区:视觉打字、结束后的操作栏、输入框和软键盘都会改变底部位置。 - const observer = new ResizeObserver(follow); - observer.observe(el); - observer.observe(view); - const endDrag = () => { - draggingScroll.current = false; - }; - window.addEventListener("pointerup", endDrag); - window.addEventListener("pointercancel", endDrag); - follow(); - return () => { - observer.disconnect(); - cancelAnimationFrame(frame); - window.removeEventListener("pointerup", endDrag); - window.removeEventListener("pointercancel", endDrag); - }; - }, [conversationId]); + const timer = setTimeout(() => { + try { + const stored = JSON.parse(sessionStorage.getItem(undoKey) ?? "null"); + if (stored?.until > Date.now()) setUndo(stored); + } catch {} + }, 0); + return () => clearTimeout(timer); + }, [undoKey]); + useEffect(() => { + if (!undo) return; + const timer = setTimeout( + () => { + setUndo(null); + try { + sessionStorage.removeItem(undoKey); + } catch {} + }, + Math.max(0, undo.until - Date.now()), + ); + return () => clearTimeout(timer); + }, [undo, undoKey]); useEffect(() => { if (!conversationId) return; const root = document.documentElement; @@ -351,12 +368,35 @@ export function DigitalHome({ if (!conversationId) return; const frame = requestAnimationFrame(() => { try { - setDraft(sessionStorage.getItem(`dh-draft:${conversationId}`) ?? ""); + const storedDraft = + sessionStorage.getItem(`dh-draft:${conversationId}`) ?? ""; + setDraft(storedDraft); + const pending = JSON.parse( + sessionStorage.getItem(`dh-pending:${conversationId}`) ?? "null", + ); + if ( + pending?.id === conversationId && + typeof pending.content === "string" && + /^[a-f0-9-]{36}$/.test(pending.requestId) + ) { + if ( + initialConversation?.messages.some( + (m) => m.requestId === pending.requestId, + ) + ) { + sessionStorage.removeItem(`dh-pending:${conversationId}`); + if (storedDraft === pending.content) setDraft(""); + } else { + pendingSend.current = pending; + setCanRetryRequest(true); + setInterrupted(true); + } + } } catch {} setDraftReady(true); }); return () => cancelAnimationFrame(frame); - }, [conversationId]); + }, [conversationId, initialConversation]); useEffect(() => { if (!conversationId || !draftReady) return; try { @@ -454,7 +494,9 @@ export function DigitalHome({ `conversations/${conversationId}`, ); if (!cancelled && currentId.current === conversationId) { - setConversation(saved); + setConversation((current) => + mergeConversationSnapshot(current, saved), + ); setBusy(saved.busy); } } catch {} @@ -471,7 +513,6 @@ export function DigitalHome({ } closeIdeas(); imeComposing.current = false; - setSwipedConversation(null); if (streamingId.current && streamingId.current !== id) { setNotice("请先停止当前回复,再切换会话"); return; @@ -541,18 +582,44 @@ export function DigitalHome({ favoritePending.current = false; } } - async function send(mode: "send" | "regenerate" | "continue" = "send") { + function clearPendingSend(id: string) { + pendingSend.current = null; + setCanRetryRequest(false); + try { + sessionStorage.removeItem(`dh-pending:${id}`); + } catch {} + } + async function send( + mode: "send" | "regenerate" | "continue" = "send", + retryContent?: string, + ) { if ( !conversation || busy || streamingId.current || - (mode === "send" && !draft.trim()) + (mode === "send" && !(retryContent ?? draft).trim()) ) return; closeIdeas(); const id = conversation.id, - content = mode === "send" ? draft.trim() : "", - requestId = crypto.randomUUID(); + content = mode === "send" ? (retryContent ?? draft).trim() : "", + requestId = + mode === "send" && + pendingSend.current?.id === id && + pendingSend.current.content === (retryContent ?? draft).trim() + ? pendingSend.current.requestId + : crypto.randomUUID(); + if (mode === "send") { + pendingSend.current = { id, requestId, content }; + setCanRetryRequest(true); + try { + sessionStorage.setItem( + `dh-pending:${id}`, + JSON.stringify(pendingSend.current), + ); + } catch {} + } + setInterrupted(false); let assistantId = `pending-${requestId}`; setBusy(true); setError(""); @@ -585,7 +652,19 @@ export function DigitalHome({ }, ]; setConversation((c) => - c && c.id === id ? { ...c, messages: [...c.messages, ...local] } : c, + c && c.id === id + ? { + ...c, + messages: [ + ...c.messages.filter( + (m) => + m.id !== `user-${requestId}` && + m.id !== `pending-${requestId}`, + ), + ...local, + ], + } + : c, ); setActiveMessage(assistantId); const controller = new AbortController(); @@ -641,7 +720,8 @@ export function DigitalHome({ } : c, ); - if (event === "done") + if (event === "done") { + clearPendingSend(id); setConversation((c) => c && c.id === id ? { @@ -654,11 +734,25 @@ export function DigitalHome({ } : c, ); + } if (event === "notice" || event === "error") setNotice(String(data.message ?? "")); }); } catch (e) { - if (!controller.signal.aborted) reportError(e); + if (!controller.signal.aborted) { + reportError(e); + setInterrupted(true); + } + setConversation((c) => + c?.id === id + ? { + ...c, + messages: c.messages.map((m) => + m.id === assistantId ? { ...m, status: "stopped" } : m, + ), + } + : c, + ); if (!accepted && mode === "send") setDraft(content); } finally { streamingId.current = null; @@ -669,8 +763,16 @@ export function DigitalHome({ if (currentId.current === id) try { const saved = await digital(`conversations/${id}`); - setConversation(saved); + setConversation((current) => + mergeConversationSnapshot(current, saved), + ); setBusy(saved.busy); + if ( + saved.messages.some( + (m) => m.requestId === pendingSend.current?.requestId, + ) + ) + clearPendingSend(id); } catch (e) { reportError(e); } @@ -723,17 +825,17 @@ export function DigitalHome({ reportError(e); } } - async function branch(message: Message) { + async function branch(message: Message, title: string) { if (!conversation || busy) return; try { const result = await digital<{ id: string }>( `conversations/${conversation.id}/branch`, "POST", - { messageId: message.id }, + { messageId: message.id, title }, ); router.push(chatPath(result.id)); } catch (e) { - reportError(e); + throw e; } } function requestDelete(target: Summary) { @@ -761,9 +863,11 @@ export function DigitalHome({ setDeleting(true); setDeleteError(""); try { - await digital(`conversations/${id}`, "DELETE"); + const removed = await digital<{ undoUntil: number }>( + `conversations/${id}`, + "DELETE", + ); setSummaries((current) => current.filter((s) => s.id !== id)); - setSwipedConversation(null); if (currentId.current === id) { closeIdeas(); currentId.current = null; @@ -773,8 +877,17 @@ export function DigitalHome({ try { sessionStorage.removeItem(`dh-draft:${id}`); } catch {} + const entry = { + id, + title: deleteTarget.title, + until: removed.undoUntil, + }; + try { + sessionStorage.setItem(undoKey, JSON.stringify(entry)); + } catch {} + setUndo(entry); setDeleteTarget(null); - setNotice("对话已删除"); + setNotice("对话已删除,可在 30 秒内撤销"); } catch (e) { setDeleteError(e instanceof Error ? e.message : "删除失败,请重试"); } finally { @@ -1230,7 +1343,7 @@ export function DigitalHome({ }} onScroll={() => { const v = viewport.current; - if (v) { + if (v?.isConnected && v.clientHeight > 0) { const gap = v.scrollHeight - v.scrollTop - v.clientHeight; if (gap <= 2) atBottom.current = true; else if (draggingScroll.current) atBottom.current = false; @@ -1239,6 +1352,69 @@ export function DigitalHome({ }} >
+ {conversation.parent && ( +

+ 分支自「{conversation.parent.title}」{" "} + {conversation.parent.available ? ( + + 回到原故事 + + ) : ( + "(原会话已删除或不可用)" + )} +

+ )} + {interrupted && ( +
+ 连接已中断,已显示的内容会保留 +

+ 先同步服务器结果,避免重复发送;已有部分回复可使用“继续”,需要替换回答时再重新生成。 +

+ + {canRetryRequest && ( + + )} +
+ )}
✦

这里是你与 {currentCard?.name} 的私人故事

@@ -1246,6 +1422,9 @@ export function DigitalHome({
{conversation.messages.map((m, index) => (
@@ -1291,7 +1470,7 @@ export function DigitalHome({ @@ -1334,7 +1513,9 @@ export function DigitalHome({ 此前回答 )} {m.status === "stopped" && ( - 已停止 + + 回复已中止 · 已保留现有内容 + )}
@@ -1354,7 +1535,7 @@ export function DigitalHome({ }} > - 回到最新 + {unread ? "有新回复 · 回到最新" : "回到最新"} )}
@@ -1522,6 +1703,45 @@ export function DigitalHome({ {tab === "discover" && ( <> + {summaries.length > 0 && ( +
+

继续最近聊天

+
+ {[...summaries] + .sort( + (a, b) => + Date.parse(b.updatedAt) - Date.parse(a.updatedAt), + ) + .slice(0, 3) + .map((item) => ( + + {item.title} + + {" "} + ·{" "} + {item.lastMessage?.slice(0, 36) || + "继续未完的故事"} + + + ))} +
+
+ )} + {!!profile?.favorites.length && ( +
+

收藏角色

+
+ {cards + .filter((card) => profile.favorites.includes(card.id)) + .slice(0, 4) + .map((card) => ( + + {card.name} + + ))} +
+
+ )}
今晚,有人等你开口 @@ -1672,19 +1892,14 @@ export function DigitalHome({ {summaries.length > 0 && (

向左滑动对话可删除

)} -
- {summaries.map((s) => ( - c.id === s.characterId)} - revealed={swipedConversation === s.id} - disabled={opening || deleting} - onReveal={setSwipedConversation} - onDelete={() => requestDelete(s)} - /> - ))} -
+ {!summaries.length && (
@@ -1786,7 +2001,8 @@ export function DigitalHome({ />

- 此资料可在新会话的「对话设定」中使用。每个会话的设定相互独立。 + 账号称呼与身份仅作为新会话的默认值;已有会话保留自己的设定。NSFW + 开关保存后影响所有会话的后续回复。

+

故事与背景

{detail.description}

{detail.greeting && ( -
- {detail.greeting - .replaceAll("{{user}}", profile?.userName ?? "旅人") - .replaceAll("{{char}}", detail.name)} -
+ <> +

开场预览

+
+ {detail.greeting + .replaceAll("{{user}}", profile?.userName ?? "旅人") + .replaceAll("{{char}}", detail.name)} +
+ )} {detail.kind === "character" ? ( <> @@ -1898,15 +2118,20 @@ export function DigitalHome({ 开启这段故事 {detail.alternateGreetings.map((g, i) => ( - +
+ 另一种相遇 {i + 1} · 预览 +

+ {g + .replaceAll("{{user}}", profile?.userName ?? "旅人") + .replaceAll("{{char}}", detail.name)} +

+ +
))} ) : ( @@ -1935,6 +2160,9 @@ export function DigitalHome({
MAKE IT YOUR STORY

对话设定

+

+ 只影响当前这段对话的后续回复,不修改账号身份、其他对话或已发送的消息。角色默认设定会作为未选择项目的基础。 +

+

+ 仅填入下方草稿,点击保存后才对当前会话生效。 +