Compare commits

...

4 Commits

Author SHA1 Message Date
zhanxi 87e7a3aeb3 merge(chat): 完善聊天恢复与会话管理体验 2026-10-28 11:21:26 +00:00
湛兮 15f672e10d feat(chat): 完善聊天恢复与会话管理体验
- 聊天:断流保留内容、同请求重试和阅读位置恢复
- 会话:搜索、命名、置顶、撤销删除和具名分支来源
- 发现与设定:最近聊天、开场预览及账号设置作用范围
- 组件与测试:拆分列表、弹窗和阅读逻辑,补充流解析回归
2026-10-28 19:19:38 +08:00
zhanxi 74d7caaca5 merge(navigation): 类型检查前重建 Next 路由声明 2026-10-28 09:11:25 +00:00
湛兮 76abb3ecfb fix(build): 类型检查前重建 Next 路由声明
- 清理过期的生产路由类型并执行 next typegen,避免 CI 引用迁移前页面
- 同步 README,使用过期类型夹具复现失败并验证检查可恢复
2026-10-28 17:10:42 +08:00
13 changed files with 956 additions and 129 deletions
+12
View File
@@ -193,3 +193,15 @@ NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成
未登录时保留具体资源地址,登录后回到原页;会话过期先清理 Cookie,避免登录页和失效会话之间循环。草稿按会话 ID 保存在当前标签页的 sessionStorage;退出聊天会取消该页流连接,已有消息仍由服务端持久化。对话设定、确认删除和选择项仍作为当前页面的临时弹窗。
路由与深链回归:`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` 迁移及接口;不要只发布前台。
+1 -1
View File
@@ -12,7 +12,7 @@
"start:develop": "APP_ENV=develop APP_ENV_LABEL=测试环境 ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3501/api ROLE_USER_SESSION_COOKIE=role_user_session_develop next start -p 3211",
"start:prod": "APP_ENV=production APP_ENV_LABEL=生产环境 ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3500/api ROLE_USER_SESSION_COOKIE=role_user_session next start -p 3210",
"lint": "eslint",
"typecheck": "tsc --noEmit --incremental false"
"typecheck": "node -e \"require('node:fs').rmSync('.next/types', { recursive: true, force: true })\" && next typegen && tsc --noEmit --incremental false"
},
"dependencies": {
"lucide-react": "^0.511.0",
+8 -2
View File
@@ -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,
+81
View File
@@ -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<void>;
}) {
const ref = useRef<HTMLDialogElement>(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 (
<dialog
ref={ref}
className="dh-delete-dialog dh-title-dialog"
aria-labelledby={id}
onCancel={(e) => {
e.preventDefault();
if (!lock.current) onCancel();
}}
>
<form
onSubmit={async (e) => {
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);
}
}}
>
<h2 id={id}>{heading}</h2>
{preview}
<label>
对话名称
<input
autoFocus
value={title}
maxLength={120}
required
onChange={(e) => setTitle(e.target.value)}
/>
</label>
{error && <p role="alert">{error}</p>}
<div className="dh-delete-actions">
<button type="button" disabled={busy} onClick={onCancel}>
取消
</button>
<button type="submit" disabled={busy || !title.trim()}>
{busy ? "正在保存…" : "确认"}
</button>
</div>
</form>
</dialog>
);
}
+153
View File
@@ -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<void>;
onNotice: (message: string) => void;
}) {
const [query, setQuery] = useState(""),
[results, setResults] = useState<Summary[]>([]),
[resultQuery, setResultQuery] = useState(""),
[loading, setLoading] = useState(false),
[error, setError] = useState(""),
[swiped, setSwiped] = useState<string | null>(null),
[renaming, setRenaming] = useState<Summary | null>(null),
[pending, setPending] = useState<string | null>(null);
const lock = useRef(false);
useEffect(() => {
if (!query.trim()) return;
const controller = new AbortController();
const timer = setTimeout(() => {
setLoading(true);
setError("");
digital<Summary[]>(
`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 (
<>
<label className="dh-conversation-search">
搜索对话或消息
<input
type="search"
value={query}
maxLength={100}
placeholder="输入对话名称或聊天内容…"
onChange={(e) => setQuery(e.target.value)}
/>
</label>
{query.trim() && !error && (loading || resultQuery !== query.trim()) && (
<p role="status">正在搜索…</p>
)}
{query.trim() && error && <p role="alert">{error}</p>}
<div className="dh-conversation-list">
{items.map((summary) => (
<div key={summary.id}>
<ConversationRow
summary={summary}
card={cards.find((card) => card.id === summary.characterId)}
revealed={swiped === summary.id}
disabled={disabled || pending === summary.id}
onReveal={setSwiped}
onDelete={() => onDelete(summary)}
/>
<div className="dh-conversation-tools">
<button
disabled={disabled || !!pending}
onClick={async () => {
if (lock.current) return;
lock.current = true;
setPending(summary.id);
try {
await save(summary, { pinned: !summary.pinned });
onNotice(summary.pinned ? "已取消置顶" : "对话已置顶");
} catch (e) {
onNotice(e instanceof Error ? e.message : "操作失败");
} finally {
setPending(null);
lock.current = false;
}
}}
>
{summary.pinned ? "取消置顶" : "置顶"}
</button>
<button
disabled={disabled || !!pending}
onClick={() => setRenaming(summary)}
>
重命名
</button>
</div>
</div>
))}
</div>
{query.trim() &&
resultQuery === query.trim() &&
!loading &&
!error &&
!items.length && <p className="dh-form-note">没有找到匹配的对话。</p>}
{renaming && (
<ConversationTitleDialog
heading="重命名对话"
initialTitle={renaming.title}
onCancel={() => setRenaming(null)}
onSubmit={async (title) => {
await save(renaming, { title });
setRenaming(null);
onNotice("对话名称已保存");
}}
/>
)}
</>
);
}
+7 -2
View File
@@ -126,8 +126,13 @@ export function ConversationRow({
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={card?.cover || "/icon.svg"} alt="" draggable={false} />
<div>
<h3>{summary.title}</h3>
<p>{card?.description || "继续这段私人对话"}</p>
<h3>
{summary.pinned ? "置顶 · " : ""}
{summary.title}
</h3>
<p>
{summary.lastMessage || card?.description || "继续这段私人对话"}
</p>
</div>
<small>
{new Date(summary.updatedAt).toLocaleDateString("zh-CN", {
+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}
+14
View File
@@ -2486,3 +2486,17 @@ html.dh-chat-active body {
min-height: 44px;
color: var(--dh-accent);
}
/* 会话管理与恢复操作沿用当前主题,移动端保持足够命中面积。 */
.dh-conversation-search { display: grid; gap: 8px; margin: 20px 0; color: var(--dh-muted); }
.dh-conversation-tools { display: flex; justify-content: flex-end; gap: 12px; margin: 4px 0 12px; }
.dh-conversation-tools button { min-height: 36px; padding: 4px 10px; color: var(--dh-muted); }
.dh-title-dialog label { display: grid; gap: 10px; margin-top: 20px; }
.dh-title-dialog input { width: 100%; font-size: 16px; }
.dh-title-dialog blockquote { max-height: 180px; overflow-y: auto; margin: 16px 0; padding: 12px; background: var(--dh-soft); white-space: pre-wrap; overflow-wrap: anywhere; }
.dh-undo { position: fixed; z-index: 120; bottom: max(90px, env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); width: min(460px, calc(100% - 28px)); padding: 14px 18px; border-radius: 14px; background: var(--dh-soft); border: 1px solid var(--dh-line); display: flex; align-items: center; gap: 12px; box-shadow: 0 12px 40px #0008; }
.dh-undo span { flex: 1; overflow-wrap: anywhere; }
.dh-undo button { flex: none; min-height: 44px; color: var(--dh-accent); }
.dh-branch-source, .dh-recovery { padding: 14px; margin-bottom: 16px !important; border: 1px solid var(--dh-line); border-radius: 12px; color: var(--dh-muted); }
.dh-branch-source a, .dh-recovery button { color: var(--dh-accent); min-height: 40px; padding: 6px; }
.dh-recent-stories { display: flex; flex-wrap: wrap; gap: 10px; margin: 14px 0 28px; }
.dh-recent-stories a { border: 1px solid var(--dh-line); border-radius: 12px; padding: 12px 16px; max-width: 100%; overflow-wrap: anywhere; }
+144
View File
@@ -0,0 +1,144 @@
"use client";
/** 会话阅读位置按标签页保存;上翻时新回复只提示,不改变用户正在阅读的位置。 */
import { useEffect, useRef, useState, type RefObject } from "react";
type Position = {
anchor?: string;
offset: number;
top: number;
bottom: boolean;
revision: string;
unread: boolean;
};
/** 保存消息锚点而非只保存像素,消息排版或窗口高度变化后仍尽量回到同一条。 */
export function useChatReading(
id: string | undefined,
viewportRef: RefObject<HTMLDivElement | null>,
contentRef: RefObject<HTMLDivElement | null>,
atBottomRef: RefObject<boolean>,
draggingRef: RefObject<boolean>,
onJump: (value: boolean) => void,
) {
const [unread, setUnread] = useState(false);
const unreadRef = useRef(false);
useEffect(() => {
const view = viewportRef.current,
body = contentRef.current;
if (!id || !view || !body) return;
let frame = 0,
saveFrame = 0,
restored = false,
previousRevision = "";
const elements = () =>
Array.from(body.querySelectorAll<HTMLElement>("[data-message-id]"));
const revision = () => {
const last = elements().at(-1);
return last
? `${last.dataset.messageId}:${last.dataset.messageLength}`
: "";
};
const mark = (value: boolean) => {
unreadRef.current = value;
setUnread(value);
};
let lastPosition: Position | undefined;
const save = () => {
if (!restored) return;
// App Router 隐藏或卸载页面后 DOM 尺寸可能归零,不能用它覆盖最后一次有效阅读位置。
if (view.isConnected && body.isConnected && view.clientHeight > 0) {
const top = view.getBoundingClientRect().top;
const anchor = elements().find(
(el) => el.getBoundingClientRect().bottom > top,
);
lastPosition = {
anchor: anchor?.dataset.messageId,
offset: (anchor?.getBoundingClientRect().top ?? top) - top,
top: view.scrollTop,
bottom: atBottomRef.current,
revision: revision(),
unread: unreadRef.current,
};
}
if (!lastPosition) return;
try {
sessionStorage.setItem(`dh-reading:${id}`, JSON.stringify(lastPosition));
} catch {}
};
let saved: Position | undefined;
try {
const value = JSON.parse(
sessionStorage.getItem(`dh-reading:${id}`) ?? "null",
);
if (value && Number.isFinite(value.top) && Number.isFinite(value.offset))
saved = value;
} catch {}
atBottomRef.current = saved?.bottom ?? true;
const follow = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
if (!restored) {
let hash = "";
try {
hash = decodeURIComponent(window.location.hash.slice(1));
} catch {}
const target = hash
? elements().find((el) => el.id === hash)
: !saved?.bottom && saved?.anchor
? elements().find((el) => el.dataset.messageId === saved?.anchor)
: undefined;
if (target) {
view.scrollTop +=
target.getBoundingClientRect().top -
view.getBoundingClientRect().top -
(hash ? 12 : (saved?.offset ?? 0));
atBottomRef.current = false;
} else
view.scrollTop = atBottomRef.current
? view.scrollHeight
: (saved?.top ?? 0);
previousRevision = saved?.revision ?? revision();
mark(!!saved?.unread);
restored = true;
}
const next = revision();
if (atBottomRef.current) {
view.scrollTo({ top: view.scrollHeight, behavior: "instant" });
onJump(false);
mark(false);
} else {
if (next !== previousRevision) mark(true);
onJump(view.scrollHeight - view.scrollTop - view.clientHeight > 80);
}
previousRevision = next;
save();
});
};
const scroll = () => {
if (!restored || !view.isConnected || view.clientHeight <= 0) return;
if (view.scrollHeight - view.scrollTop - view.clientHeight <= 2)
mark(false);
cancelAnimationFrame(saveFrame);
saveFrame = requestAnimationFrame(save);
};
const endDrag = () => {
draggingRef.current = false;
};
const observer = new ResizeObserver(follow);
observer.observe(body);
observer.observe(view);
view.addEventListener("scroll", scroll);
window.addEventListener("pointerup", endDrag);
window.addEventListener("pointercancel", endDrag);
follow();
return () => {
save();
observer.disconnect();
cancelAnimationFrame(frame);
cancelAnimationFrame(saveFrame);
view.removeEventListener("scroll", scroll);
window.removeEventListener("pointerup", endDrag);
window.removeEventListener("pointercancel", endDrag);
};
}, [id, viewportRef, contentRef, atBottomRef, draggingRef, onJump]);
return unread;
}
+25
View File
@@ -0,0 +1,25 @@
/** 服务端生成中快照可能尚未落入增量正文;同步时保留浏览器已经收到的部分回复。 */
import type { Conversation } from "./digital";
/** 已结束的服务端记录为最终依据;仅在仍生成时保留同一消息较长的本地正文。 */
export function mergeConversationSnapshot(
current: Conversation | null,
saved: Conversation,
): Conversation {
if (!current || current.id !== saved.id || !saved.busy) return saved;
const known = new Map(
current.messages.map((message) => [message.id, message]),
);
return {
...saved,
messages: saved.messages.map((message) => {
const local = known.get(message.id);
return message.role === "assistant" &&
message.status === "generating" &&
local &&
local.content.length > message.content.length
? { ...message, content: local.content }
: message;
}),
};
}
+48
View File
@@ -0,0 +1,48 @@
/** 独立 SSE 解码器,流关闭不代表回复成功,必须收到服务端 done 事件。 */
/** 网络分片可跨多个 SSE 事件,最后不完整事件不会被误解析。 */
export async function readDigitalStream(
response: Response,
onEvent: (event: string, data: Record<string, unknown>) => void,
) {
if (!response.ok) {
const p = await response.json();
throw new Error(p.error?.message ?? p.message ?? "发送失败");
}
if (!response.body) throw new Error("浏览器不支持流式连接");
const reader = response.body.getReader(),
decoder = new TextDecoder();
let buffer = "",
completed = false;
try {
for (;;) {
const { value, done } = await reader.read();
buffer += (
done ? decoder.decode() : decoder.decode(value, { stream: true })
).replaceAll("\r\n", "\n");
let end: number;
while ((end = buffer.indexOf("\n\n")) >= 0) {
const block = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = block
.split("\n")
.find((s) => s.startsWith("event:"))
?.slice(6)
.trim();
const data = block
.split("\n")
.filter((s) => s.startsWith("data:"))
.map((s) => s.slice(5).trim())
.join("\n");
if (event && data) {
if (event === "done") completed = true;
onEvent(event, JSON.parse(data));
}
}
if (done) break;
}
if (!completed)
throw new Error("连接在回复结束前中断,请同步聊天记录后继续");
} finally {
reader.releaseLock();
}
}
+13 -41
View File
@@ -33,6 +33,7 @@ export type Message = {
status: string;
pinned: boolean;
sequenceId?: number;
requestId?: string | null;
};
/** 不含实验配置的会话偏好。 */
export type Settings = {
@@ -50,6 +51,13 @@ export type Conversation = {
settings: Settings;
busy: boolean;
messages: Message[];
pinned?: boolean;
parent?: {
conversationId: string;
messageId: string;
title: string;
available: boolean;
} | null;
};
/** 通用请求保留服务端错误文本,401 自动返回登录。 */
export async function digital<T>(
@@ -77,47 +85,8 @@ export async function digital<T>(
throw new Error(data.error?.message ?? data.message ?? "请求失败");
return data.data as T;
}
/** 网络分片可跨多个 SSE 事件,最后不完整事件不会被误解析。 */
export async function readStream(
response: Response,
onEvent: (event: string, data: Record<string, unknown>) => void,
) {
if (!response.ok) {
const p = await response.json();
throw new Error(p.error?.message ?? p.message ?? "发送失败");
}
if (!response.body) throw new Error("浏览器不支持流式连接");
const reader = response.body.getReader(),
decoder = new TextDecoder();
let buffer = "";
try {
for (;;) {
const { value, done } = await reader.read();
buffer += (
done ? decoder.decode() : decoder.decode(value, { stream: true })
).replaceAll("\r\n", "\n");
let end: number;
while ((end = buffer.indexOf("\n\n")) >= 0) {
const block = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = block
.split("\n")
.find((s) => s.startsWith("event:"))
?.slice(6)
.trim();
const data = block
.split("\n")
.filter((s) => s.startsWith("data:"))
.map((s) => s.slice(5).trim())
.join("\n");
if (event && data) onEvent(event, JSON.parse(data));
}
if (done) break;
}
} finally {
reader.releaseLock();
}
}
/** 严格检查终止事件,避免断网被当作回复完成。 */
export { readDigitalStream as readStream } from "./digital-stream";
/** 会话列表摘要。 */
export type Summary = {
@@ -125,9 +94,12 @@ export type Summary = {
characterId: string;
title: string;
updatedAt: string;
pinned?: boolean;
lastMessage?: string | null;
};
/** 服务端首屏数据,仅包含可公开的内容摘要和当前账号决策。 */
export type Bootstrap = {
account: string;
catalog: Card[];
profile: Profile;
decision: {
+83
View File
@@ -0,0 +1,83 @@
/** SSE 的真正终止、网络中断与跨分片 Unicode 解码回归。 */
import test from "node:test";
import assert from "node:assert/strict";
import { readDigitalStream } from "../src/lib/digital-stream.ts";
test("只收到部分内容就断流时保留事件,并报告中断", async () => {
const events = [];
await assert.rejects(
readDigitalStream(
new Response('event: delta\ndata: {"text":"已有内容"}\n\n'),
(event, data) => events.push([event, data]),
),
/中断/,
);
assert.equal(events[0][1].text, "已有内容");
});
test("结束事件跨字节分片且包含中文时只解析一次", async () => {
const bytes = new TextEncoder().encode(
'event: delta\ndata: {"text":"中文"}\n\nevent: done\ndata: {"status":"complete"}\n\n',
);
const events = [];
await readDigitalStream(
new Response(
new ReadableStream({
start(controller) {
for (const byte of bytes) controller.enqueue(new Uint8Array([byte]));
controller.close();
},
}),
),
(event, data) => events.push([event, data]),
);
assert.deepEqual(events, [
["delta", { text: "中文" }],
["done", { status: "complete" }],
]);
});
test("空连接不能被当作完成,服务端拒绝保持原错误", async () => {
await assert.rejects(
readDigitalStream(new Response(""), () => {}),
/中断/,
);
await assert.rejects(
readDigitalStream(
new Response('{"message":"上一条仍在生成"}', { status: 409 }),
() => {},
),
/仍在生成/,
);
});
test("同步生成中快照不会清空已收到的部分回复,完成后以服务端记录为准", async () => {
const { mergeConversationSnapshot } = await import(
"../src/lib/digital-recovery.ts"
);
const local = {
id: "chat",
busy: true,
messages: [
{
id: "reply",
role: "assistant",
status: "generating",
content: "已经显示的正文",
},
],
};
const saved = { ...local, messages: [{ ...local.messages[0], content: "" }] };
assert.equal(
mergeConversationSnapshot(local, saved).messages[0].content,
"已经显示的正文",
);
assert.equal(
mergeConversationSnapshot(local, { ...saved, busy: false }).messages[0]
.content,
"",
);
assert.equal(
mergeConversationSnapshot({ ...local, id: "other" }, saved).messages[0]
.content,
"",
);
});