feat(chat): 完善聊天恢复与会话管理体验

- 聊天:断流保留内容、同请求重试和阅读位置恢复
- 会话:搜索、命名、置顶、撤销删除和具名分支来源
- 发现与设定:最近聊天、开场预览及账号设置作用范围
- 组件与测试:拆分列表、弹窗和阅读逻辑,补充流解析回归
This commit is contained in:
湛兮
2026-10-28 19:19:38 +08:00
parent 76abb3ecfb
commit 15f672e10d
12 changed files with 953 additions and 128 deletions
+367 -83
View File
@@ -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<Message | null>(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<HTMLElement | null>(null);
const [swipedConversation, setSwipedConversation] = useState<string | null>(
null,
);
const [deleteTarget, setDeleteTarget] = useState<Summary | null>(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<Conversation>(`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({
}}
>
<div ref={messagesElement} className="dh-messages-inner">
{conversation.parent && (
<p className="dh-branch-source">
分支自「{conversation.parent.title}」{" "}
{conversation.parent.available ? (
<Link
href={{
pathname: chatPath(
conversation.parent.conversationId,
),
hash: `message-${conversation.parent.messageId}`,
}}
>
回到原故事
</Link>
) : (
"(原会话已删除或不可用)"
)}
</p>
)}
{interrupted && (
<div className="dh-recovery" role="status">
<strong>连接已中断,已显示的内容会保留</strong>
<p>
先同步服务器结果,避免重复发送;已有部分回复可使用“继续”,需要替换回答时再重新生成。
</p>
<button
disabled={busy}
onClick={async () => {
try {
const saved = await digital<Conversation>(
`conversations/${conversation.id}`,
);
setConversation((current) =>
mergeConversationSnapshot(current, saved),
);
setBusy(saved.busy);
if (
saved.messages.some(
(m) =>
m.requestId === pendingSend.current?.requestId,
)
)
clearPendingSend(saved.id);
if (!saved.busy) setInterrupted(false);
} catch (e) {
reportError(e);
}
}}
>
同步聊天记录
</button>
{canRetryRequest && (
<button
disabled={busy}
onClick={() =>
send("send", pendingSend.current?.content)
}
>
重试本次请求
</button>
)}
</div>
)}
<div className="dh-chat-intro">
<span>✦</span>
<p>这里是你与 {currentCard?.name} 的私人故事</p>
@@ -1246,6 +1422,9 @@ export function DigitalHome({
</div>
{conversation.messages.map((m, index) => (
<article
id={`message-${m.id}`}
data-message-id={m.id}
data-message-length={m.content.length}
className={`dh-message dh-message-${m.role}`}
key={m.id}
>
@@ -1291,7 +1470,7 @@ export function DigitalHome({
<button
aria-label="从此处分支"
title="从此处创建分支"
onClick={() => branch(m)}
onClick={() => setBranchTarget(m)}
>
<GitBranch size={13} />
</button>
@@ -1334,7 +1513,9 @@ export function DigitalHome({
<small className="dh-message-status">此前回答</small>
)}
{m.status === "stopped" && (
<small className="dh-message-status">已停止</small>
<small className="dh-message-status">
回复已中止 · 已保留现有内容
</small>
)}
</div>
</article>
@@ -1354,7 +1535,7 @@ export function DigitalHome({
}}
>
<ChevronDown size={16} />
回到最新
{unread ? "有新回复 · 回到最新" : "回到最新"}
</button>
)}
<div className="dh-composer-wrap">
@@ -1522,6 +1703,45 @@ export function DigitalHome({
</header>
{tab === "discover" && (
<>
{summaries.length > 0 && (
<section aria-label="继续最近聊天">
<h2>继续最近聊天</h2>
<div className="dh-recent-stories">
{[...summaries]
.sort(
(a, b) =>
Date.parse(b.updatedAt) - Date.parse(a.updatedAt),
)
.slice(0, 3)
.map((item) => (
<Link key={item.id} href={chatPath(item.id)}>
{item.title}
<small>
{" "}
·{" "}
{item.lastMessage?.slice(0, 36) ||
"继续未完的故事"}
</small>
</Link>
))}
</div>
</section>
)}
{!!profile?.favorites.length && (
<section aria-label="收藏角色">
<h2>收藏角色</h2>
<div className="dh-recent-stories">
{cards
.filter((card) => profile.favorites.includes(card.id))
.slice(0, 4)
.map((card) => (
<Link key={card.id} href={contentPath(card)}>
{card.name}
</Link>
))}
</div>
</section>
)}
<section className="dh-hero">
<div>
<span className="dh-pill">今晚,有人等你开口</span>
@@ -1672,19 +1892,14 @@ export function DigitalHome({
{summaries.length > 0 && (
<p className="dh-swipe-hint">向左滑动对话可删除</p>
)}
<div className="dh-conversation-list">
{summaries.map((s) => (
<ConversationRow
key={s.id}
summary={s}
card={cards.find((c) => c.id === s.characterId)}
revealed={swipedConversation === s.id}
disabled={opening || deleting}
onReveal={setSwipedConversation}
onDelete={() => requestDelete(s)}
/>
))}
</div>
<ConversationList
summaries={summaries}
cards={cards}
disabled={deleting}
onDelete={requestDelete}
onRefresh={refreshSummaries}
onNotice={setNotice}
/>
{!summaries.length && (
<div className="dh-empty">
<MessageCircle />
@@ -1786,7 +2001,8 @@ export function DigitalHome({
/>
</label>
<p className="dh-form-note">
此资料可在新会话的「对话设定」中使用。每个会话的设定相互独立。
账号称呼与身份仅作为新会话的默认值;已有会话保留自己的设定。NSFW
开关保存后影响所有会话的后续回复。
</p>
<label className="dh-content-preference">
<span>
@@ -1875,13 +2091,17 @@ export function DigitalHome({
<span key={t}>{t}</span>
))}
</div>
<h2>故事与背景</h2>
<p className="dh-detail-description">{detail.description}</p>
{detail.greeting && (
<blockquote>
{detail.greeting
.replaceAll("{{user}}", profile?.userName ?? "旅人")
.replaceAll("{{char}}", detail.name)}
</blockquote>
<>
<h2>开场预览</h2>
<blockquote>
{detail.greeting
.replaceAll("{{user}}", profile?.userName ?? "旅人")
.replaceAll("{{char}}", detail.name)}
</blockquote>
</>
)}
{detail.kind === "character" ? (
<>
@@ -1898,15 +2118,20 @@ export function DigitalHome({
开启这段故事
</button>
{detail.alternateGreetings.map((g, i) => (
<button
className="dh-alt-greeting"
key={i}
disabled={opening}
onClick={() => start(detail, i + 1)}
>
<small>另一种相遇 {i + 1}</small>
<p>{g.slice(0, 110)}</p>
</button>
<details className="dh-alt-greeting" key={i}>
<summary>另一种相遇 {i + 1} · 预览</summary>
<p>
{g
.replaceAll("{{user}}", profile?.userName ?? "旅人")
.replaceAll("{{char}}", detail.name)}
</p>
<button
disabled={opening}
onClick={() => start(detail, i + 1)}
>
使用这个开场
</button>
</details>
))}
</>
) : (
@@ -1935,6 +2160,9 @@ export function DigitalHome({
<div>
<span className="dh-eyebrow">MAKE IT YOUR STORY</span>
<h2>对话设定</h2>
<p className="dh-form-note">
只影响当前这段对话的后续回复,不修改账号身份、其他对话或已发送的消息。角色默认设定会作为未选择项目的基础。
</p>
</div>
<button
type="button"
@@ -1946,6 +2174,21 @@ export function DigitalHome({
</button>
</header>
<div className="dh-settings-body">
<button
type="button"
onClick={() =>
setSettings({
...settings,
userName: profile?.userName ?? "旅人",
persona: profile?.persona ?? "",
})
}
>
将账号身份填入本次设定
</button>
<p className="dh-form-note">
仅填入下方草稿,点击保存后才对当前会话生效。
</p>
<label>
你的称呼
<input
@@ -2129,6 +2372,47 @@ export function DigitalHome({
)}
</div>
)}
{undo && (
<div className="dh-undo" role="status">
<span>已删除「{undo.title}」 · 30 秒内可撤销</span>
<button
disabled={undoBusy}
onClick={async () => {
if (undoLock.current) return;
undoLock.current = true;
setUndoBusy(true);
try {
await digital(`conversations/${undo.id}/restore`, "POST", {});
setUndo(null);
sessionStorage.removeItem(undoKey);
await refreshSummaries();
setNotice("对话已恢复");
} catch (e) {
reportError(e);
} finally {
undoLock.current = false;
setUndoBusy(false);
}
}}
>
{undoBusy ? "恢复中…" : "撤销删除"}
</button>
</div>
)}
{branchTarget && (
<ConversationTitleDialog
heading="从这里开启分支"
initialTitle={`${conversation?.title.slice(0, 100) ?? "故事"} · 分支`}
preview={
<>
<p>原故事会保留,新分支复制到下方这条消息为止。</p>
<blockquote>{branchTarget.content.slice(0, 240)}</blockquote>
</>
}
onCancel={() => setBranchTarget(null)}
onSubmit={(title) => branch(branchTarget, title)}
/>
)}
{deleteTarget && (
<ConversationDeleteDialog
title={deleteTarget.title}