Files
role-user/src/components/digital-home.tsx
T
湛兮 a580422100 feat(growth): 接入游客推荐与权益体验
- 登录:新增游客体验、登录承接和同源及请求体积校验
- 推荐与埋点:接入曝光回执、兴趣偏好和按账号隔离的重试队列
- 聊天体验:展示剩余额度、支持回答反馈及故事记忆管理
- 文档和测试:同步业务边界,覆盖队列幂等与代理登录校验
2026-10-28 21:17:45 +08:00

2549 lines
89 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
/* 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 { GrowthJourney } from "./growth-journey";
import { GrowthRecommendations } from "./growth-recommendations";
import { GrowthProfile } from "./growth-profile";
import { GrowthChat, ReplyFeedback } from "./growth-chat";
import { trackGrowth, flushGrowth, recommendationReceipt } from "@/lib/growth";
import { mergeConversationSnapshot } from "@/lib/digital-recovery";
import { useDigitalBack } from "./digital-route-history";
import {
useCallback,
useEffect,
useRef,
useState,
type FormEvent,
type KeyboardEvent,
} from "react";
import {
ArrowLeft,
ArrowUp,
BookOpen,
Check,
Copy,
GitBranch,
Heart,
LoaderCircle,
LogOut,
MessageCircle,
MoreHorizontal,
Pin,
Plus,
Search,
Settings2,
Sparkles,
Square,
Trash2,
UserRound,
WandSparkles,
X,
RefreshCw,
Download,
ChevronDown,
ChevronRight,
} from "lucide-react";
import {
digital,
readStream,
type Card,
type Profile,
type Message,
type Settings,
type Conversation,
type Summary,
type Bootstrap,
} from "@/lib/digital";
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;
/** 前台管理个人会话偏好;后台方案仅展示覆盖提示,不开放实验操作。 */
export function DigitalHome({
initial,
initialSummaries,
initialTab,
initialConversation,
initialDetail,
}: {
initial: Bootstrap;
initialSummaries: Summary[];
initialTab: Tab;
initialConversation?: Conversation;
initialDetail?: Card;
}) {
const router = useRouter();
const tab = initialTab;
const detail = initialDetail ?? null;
const goBack = useDigitalBack(
initialConversation ? "/chats" : digitalTabs[tab],
);
const [boot, setBoot] = useState<Bootstrap | null>(initial),
[summaries, setSummaries] = useState<Summary[]>(initialSummaries);
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<Conversation | null>(
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),
[error, setError] = useState(""),
[notice, setNotice] = useState("");
const [stylePolicy, setStylePolicy] = useState<
"loading" | "personal" | "managed" | "unknown"
>("loading");
const [showSettings, setShowSettings] = useState(false),
[settings, setSettings] = useState<Settings | null>(
initialConversation?.settings ?? null,
),
[profile, setProfile] = useState<Profile | null>(initial.profile);
const [profileDraft, setProfileDraft] = useState<Profile | null>(
initial.profile,
);
const [selectionSheet, setSelectionSheet] = useState<
"style" | "books" | null
>(null);
const [choiceDraft, setChoiceDraft] = useState<{
presetId?: string;
bookIds: string[];
}>({ bookIds: [] });
const selectionTrigger = useRef<HTMLElement | null>(null);
const [deleteTarget, setDeleteTarget] = useState<Summary | null>(null),
[deleting, setDeleting] = useState(false),
[deleteError, setDeleteError] = useState("");
const [ideasOpen, setIdeasOpen] = useState(false),
[ideasLoading, setIdeasLoading] = useState(false),
[ideas, setIdeas] = useState<string[]>([]),
[ideasError, setIdeasError] = useState("");
const ideasRequest = useRef<AbortController | null>(null),
imeComposing = useRef(false),
deleteLock = useRef(false);
const favoritePending = useRef(false);
const [activeMessage, setActiveMessage] = useState<string | null>(null),
[showJump, setShowJump] = useState(false),
[showMenu, setShowMenu] = useState(false);
const decisionReceived = useRef(0);
const stream = useRef<AbortController | null>(null),
streamingId = useRef<string | null>(null),
viewport = useRef<HTMLDivElement>(null),
messagesElement = useRef<HTMLDivElement>(null),
textarea = useRef<HTMLTextAreaElement>(null),
// 跟随是用户意图,内容增高导致暂时离底不能自动退出跟随。
atBottom = useRef(true),
touchY = useRef<number | null>(null),
draggingScroll = useRef(false),
currentId = useRef<string | null>(initialConversation?.id ?? null),
openSequence = useRef(0);
const cards = boot?.catalog.filter((c) => c.kind === "character") ?? [],
books = boot?.catalog.filter((c) => c.kind === "worldbook") ?? [],
presets = boot?.catalog.filter((c) => c.kind === "preset") ?? [];
const conversationId = conversation?.id;
// 尚未产生正文的失败/停止不算新台词,继续时接回上一段;真实用户消息仍是边界。
const lastReply = conversation?.messages.findLast(
(m) =>
!(
m.role === "assistant" &&
["stopped", "failed"].includes(m.status) &&
!m.content.trim()
),
);
const canContinue =
lastReply?.role === "assistant" &&
["complete", "stopped"].includes(lastReply.status) &&
!!lastReply.content.trim();
// 状态提示走只读接口,打开设定不应写入实验分组、决策或曝光。
useEffect(() => {
if (!showSettings || !conversationId) return;
const controller = new AbortController();
digital<{ managed: boolean }>(
`conversations/${conversationId}/style-policy`,
"GET",
undefined,
controller.signal,
)
.then((policy) => {
if (!controller.signal.aborted)
setStylePolicy(policy.managed ? "managed" : "personal");
})
.catch(() => {
if (!controller.signal.aborted) setStylePolicy("unknown");
});
return () => controller.abort();
}, [showSettings, conversationId]);
const decisionExpiresAt = boot?.decision.expiresAt,
decisionServerNow = boot?.serverNow;
const currentCard = cards.find((c) => c.id === conversation?.characterId);
const reportError = useCallback(
(e: unknown) =>
setError(e instanceof Error ? e.message : "请求失败,请重试"),
[],
);
const refreshSummaries = useCallback(
async () => setSummaries(await digital<Summary[]>("conversations")),
[],
);
useEffect(() => {
const controller = new AbortController();
// 浏览器后退可能恢复 Next 缓存的页面快照,重新核对列表,避免遗漏刚创建或删除的会话。
digital<Summary[]>("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>("bootstrap");
decisionReceived.current = performance.now();
setBoot(data);
setProfile(data.profile);
}, []);
useEffect(() => {
decisionReceived.current = performance.now();
}, [initial]);
useEffect(() => {
const timer = setInterval(() => {
if (!document.hidden && !streamingId.current)
reloadBootstrap().catch(() => {});
}, 45000);
const onVisible = () => {
if (!document.hidden && !streamingId.current)
reloadBootstrap().catch(() => {});
};
document.addEventListener("visibilitychange", onVisible);
return () => {
clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
stream.current?.abort();
};
}, [reloadBootstrap]);
useEffect(() => {
if (!decisionExpiresAt || !decisionServerNow) return;
const lifetime = Math.max(
0,
Math.min(60000, decisionExpiresAt - decisionServerNow),
);
const remaining = Math.max(
0,
lifetime - (performance.now() - decisionReceived.current),
);
const timer = setTimeout(
() =>
setBoot((current) =>
current
? {
...current,
decision: {
...current.decision,
variant: current.decision.fallbackVariant,
value: current.decision.fallbackValue,
decisionId: null,
},
}
: current,
),
remaining,
);
return () => clearTimeout(timer);
}, [decisionExpiresAt, decisionServerNow]);
useEffect(() => {
if (!notice) return;
const timer = setTimeout(() => setNotice(""), 3500);
return () => clearTimeout(timer);
}, [notice]);
const unread = useChatReading(
conversationId,
viewport,
messagesElement,
atBottom,
draggingScroll,
setShowJump,
);
useEffect(() => {
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;
const viewport = window.visualViewport;
const body = document.body;
const scrollY = window.scrollY;
const previousOverflow = body.style.overflow;
let frame = 0;
// 聊天只滚动消息区;Safari 键盘可能同时改变可视高度和偏移,必须一起同步。
body.style.overflow = "hidden";
root.classList.add("dh-chat-active");
const resize = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
// 用户手动捏合时保留浏览器缩放,不把缩放后的高度再次施加给布局。
if (viewport && Math.abs(viewport.scale - 1) > 0.01) return;
root.style.setProperty(
"--dh-viewport",
`${viewport?.height ?? window.innerHeight}px`,
);
root.style.setProperty(
"--dh-viewport-top",
`${viewport?.offsetTop ?? 0}px`,
);
});
};
resize();
viewport?.addEventListener("resize", resize);
viewport?.addEventListener("scroll", resize);
window.addEventListener("resize", resize);
return () => {
cancelAnimationFrame(frame);
viewport?.removeEventListener("resize", resize);
viewport?.removeEventListener("scroll", resize);
window.removeEventListener("resize", resize);
body.style.overflow = previousOverflow;
root.classList.remove("dh-chat-active");
root.style.removeProperty("--dh-viewport");
root.style.removeProperty("--dh-viewport-top");
window.scrollTo(0, scrollY);
};
}, [conversationId]);
useEffect(() => {
if (!conversationId) return;
const frame = requestAnimationFrame(() => {
try {
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, initialConversation]);
useEffect(() => {
if (!conversationId || !draftReady) return;
try {
sessionStorage.setItem(`dh-draft:${conversationId}`, draft);
} catch {}
}, [draft, conversationId, draftReady]);
useEffect(() => {
if (!showSettings) return;
const previous = document.activeElement as HTMLElement | null;
const dialog = document.querySelector<HTMLElement>(
'.dh-overlay [role="dialog"]',
);
const controls = () =>
Array.from(
(
document.querySelector<HTMLElement>(".dh-selection-sheet") ?? dialog
)?.querySelectorAll<HTMLElement>(
'button:not([disabled]),input,textarea,select,[tabindex="0"]',
) ?? [],
);
const frame = requestAnimationFrame(() => controls()[0]?.focus());
const onKey = (event: globalThis.KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
if (document.querySelector(".dh-selection-sheet")) {
setSelectionSheet(null);
return;
}
setShowSettings(false);
}
if (event.key === "Tab") {
const items = controls(),
first = items[0],
last = items.at(-1);
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last?.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first?.focus();
}
}
};
document.addEventListener("keydown", onKey);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener("keydown", onKey);
previous?.focus();
};
}, [showSettings]);
/** 选择弹窗聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */
useEffect(() => {
if (!selectionSheet) return;
const previous = selectionTrigger.current;
const media = window.matchMedia("(max-width: 600px)");
const resize = () => {
if (!media.matches) setSelectionSheet(null);
};
resize();
media.addEventListener("change", resize);
const frame = requestAnimationFrame(() => {
const panel = document.querySelector<HTMLElement>(".dh-selection-sheet");
(
panel?.querySelector<HTMLElement>("input:checked") ??
panel?.querySelector<HTMLElement>("input") ??
panel?.querySelector<HTMLElement>("button")
)?.focus();
});
return () => {
cancelAnimationFrame(frame);
media.removeEventListener("change", resize);
if (previous?.isConnected && previous.getClientRects().length)
previous.focus();
else
document
.querySelector<HTMLElement>(".dh-desktop-choices input:checked")
?.focus();
};
}, [selectionSheet]);
useEffect(() => {
const id = boot?.decision.decisionId;
if (!id || document.hidden) return;
const frame = requestAnimationFrame(() =>
digital("exposure", "POST", { decisionId: id }).catch(() => {}),
);
return () => cancelAnimationFrame(frame);
}, [boot?.decision.decisionId]);
useEffect(() => {
if (!busy || !conversationId || streamingId.current) return;
let cancelled = false;
const timer = setInterval(async () => {
if (document.hidden) return;
try {
const saved = await digital<Conversation>(
`conversations/${conversationId}`,
);
if (!cancelled && currentId.current === conversationId) {
setConversation((current) =>
mergeConversationSnapshot(current, saved),
);
setBusy(saved.busy);
}
} catch {}
}, 2000);
return () => {
cancelled = true;
clearInterval(timer);
};
}, [busy, conversationId]);
async function openConversation(id: string) {
if (id !== conversation?.id) {
router.push(chatPath(id));
return;
}
closeIdeas();
imeComposing.current = false;
if (streamingId.current && streamingId.current !== id) {
setNotice("请先停止当前回复,再切换会话");
return;
}
const sequence = ++openSequence.current;
setOpening(true);
setError("");
try {
const c = await digital<Conversation>(`conversations/${id}`);
if (sequence !== openSequence.current) return;
setConversation(c);
currentId.current = id;
setSettings(c.settings);
setBusy(c.busy);
setActiveMessage(null);
setShowMenu(false);
atBottom.current = true;
setShowJump(false);
try {
setDraft(sessionStorage.getItem(`dh-draft:${id}`) ?? "");
} catch {
setDraft("");
}
} catch (e) {
reportError(e);
} finally {
if (sequence === openSequence.current) setOpening(false);
}
}
async function start(card: Card, index = 0) {
if (opening) return;
setOpening(true);
setError("");
try {
const c = await digital<{ id: string }>("conversations", "POST", {
characterId: card.id,
greetingIndex: index,
recommendationReceiptId:
searchParams.get("recommendation") ===
recommendationReceipt(initial.account, card.id)
? recommendationReceipt(initial.account, card.id)
: undefined,
uiDecisionId: boot?.decision.decisionId ?? undefined,
});
router.push(chatPath(c.id));
} catch (e) {
reportError(e);
} finally {
setOpening(false);
}
}
async function favorite(card: Card) {
if (!profile || favoritePending.current) return;
favoritePending.current = true;
const next = {
...profile,
favorites: profile.favorites.includes(card.id)
? profile.favorites.filter((v) => v !== card.id)
: [...profile.favorites, card.id],
};
try {
// 收藏不写内容开关,避免旧页面状态覆盖管理员刚保存的账号偏好。
const saved = await digital<Profile>("profile", "PUT", {
favorites: next.favorites,
persona: next.persona,
userName: next.userName,
});
setProfile(saved);
} catch (e) {
reportError(e);
} finally {
favoritePending.current = false;
}
}
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" && !(retryContent ?? draft).trim())
)
return;
closeIdeas();
const id = conversation.id,
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("");
setNotice("");
atBottom.current = true;
setShowJump(false);
streamingId.current = id;
if (mode === "send") {
setDraft("");
if (textarea.current) textarea.current.style.height = "auto";
}
const local: Message[] = [
...(mode === "send"
? [
{
id: `user-${requestId}`,
role: "user" as const,
content,
status: "complete",
pinned: false,
},
]
: []),
{
id: assistantId,
role: "assistant",
content: "",
status: "generating",
pinned: false,
},
];
setConversation((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();
stream.current = controller;
let accepted = false;
try {
const response = await fetch(`/api/digital/conversations/${id}/stream`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
requestId,
content,
mode,
uiDecisionId: boot?.decision.decisionId ?? undefined,
}),
signal: controller.signal,
});
if (response.status === 401) {
window.location.assign(
expiredDigitalSessionPath(
window.location.pathname + window.location.search,
),
);
return;
}
accepted = response.ok;
await readStream(response, (event, data) => {
if (event === "start") {
const next = String(data.messageId);
setConversation((c) =>
c && c.id === id
? {
...c,
messages: c.messages.map((m) =>
m.id === assistantId ? { ...m, id: next } : m,
),
}
: c,
);
assistantId = next;
setActiveMessage(next);
}
if (event === "delta")
setConversation((c) =>
c && c.id === id
? {
...c,
messages: c.messages.map((m) =>
m.id === assistantId
? { ...m, content: m.content + String(data.text ?? "") }
: m,
),
}
: c,
);
if (event === "done") {
clearPendingSend(id);
setConversation((c) =>
c && c.id === id
? {
...c,
messages: c.messages.map((m) =>
m.id === assistantId
? { ...m, status: String(data.status) }
: m,
),
}
: c,
);
}
if (event === "notice" || event === "error")
setNotice(String(data.message ?? ""));
});
} catch (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;
stream.current = null;
setBusy(false);
// 从数据库收敛临时消息和最终状态;取消后服务端可能仍在提交,延后一帧刷新。
await new Promise((resolve) => setTimeout(resolve, 200));
if (currentId.current === id)
try {
const saved = await digital<Conversation>(`conversations/${id}`);
setConversation((current) =>
mergeConversationSnapshot(current, saved),
);
setBusy(saved.busy);
if (
saved.messages.some(
(m) => m.requestId === pendingSend.current?.requestId,
)
)
clearPendingSend(id);
} catch (e) {
reportError(e);
}
refreshSummaries().catch(() => {});
}
}
async function stop() {
if (!conversation) return;
try {
await digital(`conversations/${conversation.id}/stop`, "POST", {});
if (!stream.current) {
await openConversation(conversation.id);
}
} catch (e) {
reportError(e);
}
}
function onKey(event: KeyboardEvent<HTMLTextAreaElement>) {
if (
event.key === "Enter" &&
!event.shiftKey &&
!imeComposing.current &&
!event.nativeEvent.isComposing &&
event.nativeEvent.keyCode !== 229
) {
event.preventDefault();
if (!event.repeat) void send();
}
}
async function pin(message: Message) {
if (!conversation) return;
try {
await digital(
`conversations/${conversation.id}/messages/${message.id}`,
"PATCH",
{ pinned: !message.pinned },
);
setConversation((c) =>
c
? {
...c,
messages: c.messages.map((m) =>
m.id === message.id ? { ...m, pinned: !m.pinned } : m,
),
}
: c,
);
setNotice(message.pinned ? "已取消固定" : "已加入固定记忆");
} catch (e) {
reportError(e);
}
}
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, title },
);
router.push(chatPath(result.id));
} catch (e) {
throw e;
}
}
function requestDelete(target: Summary) {
if (target.id === conversation?.id && busy) {
setNotice("请先停止当前回复,再删除对话");
return;
}
setDeleteError("");
setDeleteTarget(target);
setShowMenu(false);
}
function removeConversation() {
if (conversation)
requestDelete({
id: conversation.id,
title: conversation.title,
characterId: conversation.characterId,
updatedAt: "",
});
}
async function confirmDelete() {
if (!deleteTarget || deleteLock.current) return;
const id = deleteTarget.id;
deleteLock.current = true;
setDeleting(true);
setDeleteError("");
try {
const removed = await digital<{ undoUntil: number }>(
`conversations/${id}`,
"DELETE",
);
setSummaries((current) => current.filter((s) => s.id !== id));
if (currentId.current === id) {
closeIdeas();
currentId.current = null;
setDraft("");
router.replace("/chats");
}
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("对话已删除,可在 30 秒内撤销");
} catch (e) {
setDeleteError(e instanceof Error ? e.message : "删除失败,请重试");
} finally {
deleteLock.current = false;
setDeleting(false);
}
}
/** 灵感建议只填入草稿,旧请求和已离开的会话不能覆盖当前输入。 */
function closeIdeas() {
ideasRequest.current?.abort();
ideasRequest.current = null;
setIdeasOpen(false);
setIdeasLoading(false);
setIdeasError("");
setIdeas([]);
}
async function generateIdeas() {
if (!conversation || busy || streamingId.current || ideasRequest.current)
return;
const id = conversation.id,
anchor = conversation.messages.at(-1)?.id ?? null,
controller = new AbortController();
ideasRequest.current = controller;
setIdeasOpen(true);
setIdeasLoading(true);
setIdeasError("");
setIdeas([]);
try {
const result = await digital<{
suggestions: string[];
anchorId: string | null;
}>(
`conversations/${id}/suggestions`,
"POST",
{ draft: draft.slice(0, 1000), requestId: crypto.randomUUID() },
controller.signal,
);
if (ideasRequest.current !== controller || currentId.current !== id)
return;
if (result.anchorId !== anchor) {
setIdeasError("对话已更新,请重新打开会话后再试");
return;
}
setIdeas(result.suggestions);
} catch (e) {
if (!controller.signal.aborted && currentId.current === id)
setIdeasError(e instanceof Error ? e.message : "灵感生成失败,请重试");
} finally {
if (ideasRequest.current === controller) {
ideasRequest.current = null;
setIdeasLoading(false);
}
}
}
function chooseIdea(value: string) {
const next = draft
? `${draft}${draft.endsWith("\n") ? "" : "\n"}${value}`
: value;
if (next.length > 4000) {
setIdeasError("草稿已接近字数上限,请先缩短内容");
return;
}
setDraft(next);
closeIdeas();
setNotice("已加入草稿,可修改后发送");
requestAnimationFrame(() => {
const input = textarea.current;
if (input) {
input.focus();
input.style.height = "auto";
input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
input.setSelectionRange(next.length, next.length);
}
});
}
function insertLineBreak() {
const input = textarea.current;
if (!input || draft.length >= 4000) return;
const start = input.selectionStart,
end = input.selectionEnd,
next = draft.slice(0, start) + "\n" + draft.slice(end);
setDraft(next);
requestAnimationFrame(() => {
input.focus();
input.setSelectionRange(start + 1, start + 1);
input.style.height = "auto";
input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
});
}
/** 选择弹窗仅编辑临时值;确认后回填设定,取消不改动已有选择。 */
function openSelection(kind: "style" | "books") {
if (!settings) return;
selectionTrigger.current = document.activeElement as HTMLElement;
setChoiceDraft({
presetId: settings.presetId,
bookIds: [...settings.bookIds],
});
setSelectionSheet(kind);
}
function confirmSelection() {
if (settings)
setSettings({
...settings,
...(selectionSheet === "style"
? { presetId: choiceDraft.presetId }
: { bookIds: choiceDraft.bookIds }),
});
setSelectionSheet(null);
}
async function saveSettings(event: FormEvent) {
event.preventDefault();
if (!conversation || !settings) return;
try {
await digital(`conversations/${conversation.id}`, "PATCH", { settings });
setConversation((c) => (c ? { ...c, settings } : c));
setShowSettings(false);
setNotice(
stylePolicy === "managed"
? "设定已保存;当前叙事风格仍由统一方案控制"
: "对话设定已保存,下次回复生效",
);
} catch (e) {
reportError(e);
}
}
async function saveProfile(event: FormEvent) {
event.preventDefault();
if (!profile || !profileDraft) return;
const next = {
...profile,
userName: profileDraft.userName,
persona: profileDraft.persona,
nsfwEnabled: profileDraft.nsfwEnabled ?? true,
};
try {
const saved = await digital<Profile>("profile", "PUT", next);
if (saved.nsfwEnabled !== next.nsfwEnabled)
throw new Error("内容偏好未保存,请稍后重试");
setProfile(saved);
setProfileDraft(saved);
setNotice("身份与内容偏好已保存");
} catch (e) {
reportError(e);
}
}
async function copy(text: string) {
try {
await navigator.clipboard.writeText(text);
setNotice("已复制");
} catch {
setNotice("当前浏览器无法访问剪贴板");
}
}
function exportChat() {
if (!conversation) return;
const text = conversation.messages
.map(
(m) =>
`${m.role === "user" ? "我" : (currentCard?.name ?? "角色")}:\n${m.content}`,
)
.join("\n\n");
const url = URL.createObjectURL(
new Blob([text], { type: "text/plain;charset=utf-8" }),
);
const a = document.createElement("a");
a.href = url;
a.download = `${conversation.title}.txt`;
a.click();
URL.revokeObjectURL(url);
}
function switchTab(value: Tab) {
router.push(digitalTabs[value]);
}
const tags = [
"全部",
...new Set(cards.flatMap((c) => c.tags).slice(0, 30)),
].slice(0, 12);
const filtered = cards.filter(
(c) =>
(!query ||
`${c.name} ${c.description} ${c.tags.join(" ")}`
.toLowerCase()
.includes(query.toLowerCase())) &&
(tag === "全部" || c.tags.includes(tag)) &&
(!onlyFavorites || profile?.favorites.includes(c.id)),
);
const styleChoices = (
value: string | undefined,
onChange: (value: string | undefined) => void,
inSheet = false,
) => (
<fieldset className="dh-style-picker">
<legend className={inSheet ? "dh-visually-hidden" : undefined}>
叙事风格
</legend>
<p className="dh-style-help" role="status">
{stylePolicy === "loading"
? "正在确认风格设置…"
: stylePolicy === "managed"
? "当前使用统一叙事风格。可以保存个人偏好,统一风格解除后采用。"
: stylePolicy === "unknown"
? "暂时无法确认当前风格,可以先保存个人偏好。"
: "为这段故事选一种氛围,也可以跟随角色默认风格。"}
</p>
<div className="dh-style-options">
{[
{
id: "",
name: "角色默认风格",
description: "沿用角色原有的语气与叙事节奏。",
},
...presets,
...(value && !presets.some((p) => p.id === value)
? [
{
id: value,
name: "当前会话风格",
description: "这个风格暂不可用,回复时会采用可用的默认风格。",
},
]
: []),
].map((p) => (
<label className="dh-style-option" key={p.id}>
<input
type="radio"
name={
inSheet
? "conversation-preset-sheet"
: "conversation-preset-inline"
}
value={p.id}
checked={(value ?? "") === p.id}
onChange={() => onChange(p.id || undefined)}
/>
<span className="dh-style-card">
<span className="dh-style-copy">
<strong>{p.name}</strong>
<small>{p.description || "以这套风格继续你们的故事。"}</small>
</span>
<span className="dh-style-check" aria-hidden="true">
<Check />
</span>
</span>
</label>
))}
</div>
</fieldset>
);
const bookChoices = (
value: string[],
onChange: (value: string[]) => void,
inSheet = false,
) => (
<fieldset className="dh-book-picker">
<legend className={inSheet ? "dh-visually-hidden" : undefined}>
加入世界书
</legend>
{books.map((b) => (
<label
className={`dh-checkbox ${value.includes(b.id) ? "is-selected" : ""}`}
key={b.id}
>
<input
type="checkbox"
checked={value.includes(b.id)}
onChange={(e) =>
onChange(
e.target.checked
? [...value, b.id]
: value.filter((v) => v !== b.id),
)
}
/>
<span>
{b.name}
<small>{b.description}</small>
</span>
</label>
))}
</fieldset>
);
useEffect(() => {
// 缓存页面重新显示时重新绑定会话,离开后的旧流请求不能更新下一页。
currentId.current = conversationId ?? null;
return () => {
ideasRequest.current?.abort();
currentId.current = null;
};
}, [conversationId]);
// UI按消费者返回值决定,组名仅用于归因;C到Z同样可以返回新版UI。
// 缺少value时兼容尚未升级的服务响应。
const modern =
boot?.decision.value !== undefined
? boot.decision.value === "new" || boot.decision.value === true
: boot?.decision.variant === "B";
return (
<div
className={`dh-app ${modern ? "dh-modern" : "dh-classic"} ${conversation ? "dh-in-chat" : ""}`}
>
<aside className="dh-sidebar">
<Link className="dh-brand" href="/discover">
<span className="dh-brand-mark">✦</span> 星港
<span className="dh-brand-en">STELLAR</span>
</Link>
<p className="dh-sidebar-caption">每一段相遇,都有下一章</p>
<nav aria-label="主要导航">
{(
[
{ id: "discover", label: "发现角色", icon: Sparkles },
{ id: "chats", label: "我的对话", icon: MessageCircle },
{ id: "library", label: "灵感书架", icon: BookOpen },
{ id: "me", label: "我的身份", icon: UserRound },
] as const
).map((item) => (
<Link
key={item.id}
href={digitalTabs[item.id]}
className={tab === item.id ? "is-active" : ""}
aria-current={tab === item.id ? "page" : undefined}
>
<item.icon size={19} />
<span>{item.label}</span>
{item.id === "chats" && summaries.length > 0 && (
<small>{summaries.length}</small>
)}
</Link>
))}
</nav>
<div className="dh-sidebar-bottom">
<span className="dh-avatar">
{profile?.userName?.slice(0, 1) || "旅"}
</span>
<div>
<strong>{profile?.userName || "旅人"}</strong>
<small>你的私人数字人空间</small>
</div>
<a aria-label="退出登录" href="/api/auth/logout?next=/login">
<LogOut size={17} />
</a>
</div>
</aside>
<main className="dh-main">
{error && (
<div className="dh-error" role="alert">
{error}
<button aria-label="关闭错误" onClick={() => setError("")}>
<X size={16} />
</button>
</div>
)}
{notice && (
<div className="dh-toast" role="status">
{notice}
</div>
)}
{!boot ? (
<div className="dh-loading">
<LoaderCircle className="dh-spin" />
<span>正在开启你的星港…</span>
</div>
) : conversation ? (
<section className="dh-chat">
<header className="dh-chat-header">
<button
className="dh-icon"
aria-label="返回上一页"
onClick={goBack}
>
<ArrowLeft size={21} />
</button>
{currentCard?.cover && <img src={currentCard.cover} alt="" />}
<div>
<h1>{currentCard?.name ?? conversation.title}</h1>
<small>
<i /> {busy ? "正在回应你" : "故事由你们续写"}
</small>
</div>
<button
className="dh-icon"
aria-label="对话设定"
onClick={() => {
setSettings(conversation.settings);
setStylePolicy("loading");
setShowSettings(true);
}}
>
<Settings2 size={20} />
</button>
<button
className="dh-icon"
aria-label="更多对话操作"
aria-expanded={showMenu}
onClick={() => setShowMenu(!showMenu)}
>
<MoreHorizontal size={21} />
</button>
{showMenu && (
<div className="dh-chat-menu">
<button onClick={exportChat}>
<Download size={16} />
导出对话
</button>
<button disabled={busy} onClick={removeConversation}>
<Trash2 size={16} />
删除会话
</button>
</div>
)}
</header>
<div
className="dh-chat-backdrop"
style={{
backgroundImage: currentCard?.cover
? `url("${currentCard.cover.replaceAll('"', "%22")}")`
: undefined,
}}
/>
<div
className="dh-messages"
ref={viewport}
tabIndex={0}
aria-label="聊天消息"
onWheel={(event) => {
if (event.deltaY < 0 && event.currentTarget.scrollTop > 0)
atBottom.current = false;
}}
onTouchStart={(event) => {
touchY.current = event.touches[0]?.clientY ?? null;
}}
onTouchMove={(event) => {
const y = event.touches[0]?.clientY;
if (
y !== undefined &&
touchY.current !== null &&
y > touchY.current &&
event.currentTarget.scrollTop > 0
)
atBottom.current = false;
touchY.current = y ?? null;
}}
onTouchEnd={() => {
touchY.current = null;
}}
onPointerDown={(event) => {
draggingScroll.current =
event.pointerType === "mouse" &&
event.target === event.currentTarget;
}}
onKeyDown={(event) => {
if (["ArrowUp", "PageUp", "Home"].includes(event.key))
atBottom.current = false;
}}
onScroll={() => {
const v = viewport.current;
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;
setShowJump(!atBottom.current && gap > 80);
}
}}
>
<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>
)}
<GrowthJourney account={initial.account} page="chat" />
<GrowthChat
account={initial.account}
conversation={conversation.id}
busy={busy}
onExpanded={() => {
atBottom.current = false;
}}
/>
<div className="dh-chat-intro">
<span>✦</span>
<p>这里是你与 {currentCard?.name} 的私人故事</p>
<small>内容由 AI 生成,虚构世界中的角色可能会犯错。</small>
</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}
>
{m.role === "assistant" && (
<img
className="dh-message-avatar"
src={currentCard?.cover || "/icon.svg"}
alt=""
/>
)}
<div className="dh-message-body">
<span className="dh-message-name">
{m.role === "user"
? conversation.settings.userName
: currentCard?.name}
{m.pinned && <Pin size={11} />}
</span>
<div className="dh-bubble">
<DigitalMessage
message={m}
animate={m.id === activeMessage}
/>
</div>
{!busy && m.content && (
<div className="dh-message-actions">
<button
aria-label="复制消息"
title="复制"
onClick={() => copy(m.content)}
>
<Copy size={13} />
</button>
<button
aria-label={
m.pinned ? "取消固定记忆" : "固定为记忆"
}
title="固定记忆"
className={m.pinned ? "is-active" : ""}
onClick={() => pin(m)}
>
<Pin size={13} />
</button>
<button
aria-label="从此处分支"
title="从此处创建分支"
onClick={() => setBranchTarget(m)}
>
<GitBranch size={13} />
</button>
{m.role === "assistant" &&
index === conversation.messages.length - 1 &&
conversation.messages.some(
(v) => v.role === "user",
) && (
<button
aria-label="重新生成"
title="换一个回答"
onClick={() => send("regenerate")}
>
<RefreshCw size={13} />
</button>
)}
</div>
)}
{!busy &&
!m.content &&
m.role === "assistant" &&
index === conversation.messages.length - 1 &&
conversation.messages.some(
(v) => v.role === "user",
) && (
<button
className="dh-text-button"
aria-label="重新生成"
onClick={() => send("regenerate")}
>
<RefreshCw size={13} /> 重新生成
</button>
)}
{!busy &&
m.role === "assistant" &&
!!m.requestId &&
m.status !== "generating" && (
<ReplyFeedback
account={initial.account}
conversation={conversation.id}
messageId={m.id}
/>
)}
{m.status === "failed" && (
<small className="dh-message-status">
生成失败,可重新生成
</small>
)}
{m.status === "superseded" && (
<small className="dh-message-status">此前回答</small>
)}
{m.status === "stopped" && (
<small className="dh-message-status">
回复已中止 · 已保留现有内容
</small>
)}
</div>
</article>
))}
</div>
</div>
{showJump && (
<button
className="dh-jump"
onClick={() => {
atBottom.current = true;
setShowJump(false);
viewport.current?.scrollTo({
top: viewport.current.scrollHeight,
behavior: "instant",
});
}}
>
<ChevronDown size={16} />
{unread ? "有新回复 · 回到最新" : "回到最新"}
</button>
)}
<div className="dh-composer-wrap">
{ideasOpen && (
<section
className="dh-reply-ideas"
aria-label="灵感回复"
aria-busy={ideasLoading}
>
<header>
<strong>
<Sparkles size={14} />
灵感回复
</strong>
<button
type="button"
className="dh-icon"
aria-label="关闭灵感回复"
onClick={closeIdeas}
>
<X size={16} />
</button>
</header>
<p className="dh-ideas-note">
{draft
? "选择后追加到现有草稿,不会自动发送。"
: "根据当前对话生成,选择后可编辑再发送。"}
</p>
{ideasLoading ? (
<p className="dh-ideas-loading" role="status">
<LoaderCircle size={16} className="dh-spin" />
正在寻找合适的接话方式…
</p>
) : ideasError ? (
<p className="dh-ideas-error" role="alert">
{ideasError}
</p>
) : (
<div className="dh-ideas-list">
{ideas.map((idea, i) => (
<button
type="button"
key={i}
onClick={() => chooseIdea(idea)}
>
<small>{i + 1}</small>
<span>{idea}</span>
</button>
))}
</div>
)}
{!ideasLoading && (
<button
type="button"
className="dh-ideas-refresh"
onClick={generateIdeas}
>
<RefreshCw size={13} />
{ideasError ? "重新生成" : "换一组"}
</button>
)}
</section>
)}
<div className="dh-compose-tools">
<div className="dh-compose-actions">
<button
type="button"
disabled={busy || ideasLoading}
onClick={generateIdeas}
>
<Sparkles size={14} />
{ideasLoading ? "灵感生成中…" : "灵感回复"}
</button>
<button
type="button"
aria-label="让角色继续"
title="不发送输入框里的草稿,让角色接着说"
disabled={busy || ideasLoading || !canContinue}
onClick={() => send("continue")}
>
<ChevronRight size={14} />
继续
</button>
</div>
<button
type="button"
className="dh-mobile-linebreak"
onClick={insertLineBreak}
>
换行
</button>
</div>
<div className="dh-composer">
<textarea
ref={textarea}
aria-label="消息"
disabled={!draftReady}
placeholder={`对 ${currentCard?.name ?? "角色"} 说点什么…`}
value={draft}
maxLength={4000}
rows={1}
onChange={(e) => {
setDraft(e.target.value);
e.target.style.height = "auto";
e.target.style.height = `${Math.min(e.target.scrollHeight, 160)}px`;
}}
enterKeyHint="send"
onCompositionStart={() => {
imeComposing.current = true;
}}
onCompositionEnd={() => {
imeComposing.current = false;
}}
onKeyDown={onKey}
/>
{busy ? (
<button
className="dh-send is-stop"
aria-label="停止生成"
onClick={stop}
>
<Square size={17} fill="currentColor" />
</button>
) : (
<button
className="dh-send"
aria-label="发送消息"
disabled={!draft.trim()}
onClick={() => send()}
>
<ArrowUp size={21} />
</button>
)}
</div>
<small className="dh-composer-hint">
{busy
? "正在生成 · 点击方块随时停止"
: "Enter 发送 · Shift + Enter 换行"}
<span>
{draft.length > 3500
? `${draft.length}/4000`
: "一段对白,一个新的可能"}
</span>
</small>
</div>
</section>
) : detail ? null : (
<div className="dh-page">
<header className="dh-page-header">
<div>
<p className="dh-eyebrow">YOUR PRIVATE UNIVERSE</p>
<h1>
{tab === "discover"
? "遇见,让故事开始"
: tab === "chats"
? "故事还在继续"
: tab === "library"
? "为想象力,留一盏灯"
: "你想以谁的身份相遇?"}
</h1>
</div>
<span className="dh-header-orbit" aria-hidden>
✦
</span>
</header>
<GrowthJourney
account={initial.account}
page={tab === "me" ? "profile" : tab}
/>
{tab === "discover" && (
<>
{!detail && (
<GrowthRecommendations
account={initial.account}
cards={cards}
/>
)}
{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>
<h2>
不止聊天。
<br />
走进另一个人的世界。
</h2>
<p>
一封未寄出的信,一次雨夜的重逢。
<br />
挑选你心动的角色,写下只属于你们的下一章。
</p>
<button
className="dh-primary"
onClick={() => {
const card =
cards.find(
(c) => !profile?.favorites.includes(c.id),
) ?? cards[0];
if (card) router.push(contentPath(card));
}}
>
<WandSparkles size={16} />
给我一次奇遇
</button>
</div>
<div className="dh-hero-art" aria-hidden>
{cards.slice(0, 3).map((c) => (
<img key={c.id} src={c.cover} alt="" />
))}
<span className="dh-orbit">✧</span>
</div>
</section>
<div className="dh-discovery-tools">
<label className="dh-search">
<Search size={18} />
<input
aria-label="搜索角色"
placeholder="搜索名字、性格或故事…"
value={query}
onChange={(e) => setFilters({ query: e.target.value })}
/>
{query && (
<button
aria-label="清空搜索"
onClick={() => setFilters({ query: "" })}
>
<X size={15} />
</button>
)}
</label>
<button
className={`dh-favorite-filter ${onlyFavorites ? "is-active" : ""}`}
onClick={() => setFilters({ favorites: !onlyFavorites })}
>
<Heart
size={17}
fill={onlyFavorites ? "currentColor" : "none"}
/>
我的收藏
</button>
</div>
<div className="dh-tags" aria-label="角色标签">
{tags.map((t) => (
<button
key={t}
className={tag === t ? "is-active" : ""}
onClick={() => setFilters({ tag: t })}
>
{t}
</button>
))}
</div>
<div className="dh-section-heading">
<h2>{onlyFavorites ? "心动收藏" : "为你发现"}</h2>
<span>{filtered.length} 位角色 · 全部成年</span>
</div>
<CatalogExposure
account={initial.account}
cardIds={filtered.map((c) => c.id).join(",")}
/>
<div className="dh-card-grid">
{filtered.map((c) => (
<article
className="dh-card"
data-growth-card={c.id}
key={c.id}
>
<Link className="dh-card-open" href={contentPath(c)}>
<img
src={c.cover || "/icon.svg"}
alt={c.name}
loading="lazy"
/>
<div className="dh-card-shade" />
<div className="dh-card-content">
<span className="dh-card-kicker">
{c.tags[0] ?? "初次相遇"} · {c.age}+
</span>
<h3>{c.name}</h3>
<p>{c.description}</p>
<div className="dh-card-tags">
{c.tags.slice(1, 3).map((t) => (
<span key={t}>{t}</span>
))}
</div>
</div>
</Link>
<button
className={`dh-card-favorite ${profile?.favorites.includes(c.id) ? "is-active" : ""}`}
aria-label={`收藏${c.name}`}
onClick={() => favorite(c)}
>
<Heart
size={17}
fill={
profile?.favorites.includes(c.id)
? "currentColor"
: "none"
}
/>
</button>
</article>
))}
</div>
{!filtered.length && (
<div className="dh-empty">
<Search />
<h3>暂时没有找到</h3>
<p>换一个关键词,或者看看其他故事。</p>
<button
onClick={() => {
setFilters({
query: "",
tag: "全部",
favorites: false,
});
}}
>
看看全部角色
</button>
</div>
)}
</>
)}
{tab === "chats" && (
<>
<div className="dh-section-heading">
<h2>最近对话</h2>
<button onClick={() => switchTab("discover")}>
<Plus size={16} />
开启新故事
</button>
</div>
{summaries.length > 0 && (
<p className="dh-swipe-hint">向左滑动对话可删除</p>
)}
<ConversationList
summaries={summaries}
cards={cards}
disabled={deleting}
onDelete={requestDelete}
onRefresh={refreshSummaries}
onNotice={setNotice}
/>
{!summaries.length && (
<div className="dh-empty">
<MessageCircle />
<h3>第一句话,交给你</h3>
<p>每个角色都准备好了一段开场,等你接下去。</p>
<button
className="dh-primary"
onClick={() => switchTab("discover")}
>
去发现角色
</button>
</div>
)}
</>
)}
{tab === "library" && (
<>
<p className="dh-page-lead">
角色是灵魂,世界书是背景,预设决定叙事方式。在对话设定中组合它们,形成你自己的故事。
</p>
<div className="dh-section-heading">
<h2>世界书</h2>
<span>按关键词触发的故事背景</span>
</div>
<div className="dh-library-grid">
{books.map((b) => (
<Link
key={b.id}
className="dh-library-card"
href={contentPath(b)}
>
<BookOpen size={24} />
<small>{b.entriesCount} 条设定</small>
<h3>{b.name}</h3>
<p>{b.description}</p>
<span>查看详情 →</span>
</Link>
))}
</div>
<div className="dh-section-heading">
<h2>叙事预设</h2>
<span>切换文字的节奏与温度</span>
</div>
<div className="dh-library-grid">
{presets.map((b) => (
<Link
key={b.id}
className="dh-library-card"
href={contentPath(b)}
>
<WandSparkles size={24} />
<small>对话风格</small>
<h3>{b.name}</h3>
<p>{b.description}</p>
<span>查看详情 →</span>
</Link>
))}
</div>
</>
)}
{tab === "me" && (
<GrowthProfile account={initial.account} cards={cards} />
)}
{tab === "me" && profile && profileDraft && (
<form className="dh-profile-form" onSubmit={saveProfile}>
<div className="dh-profile-banner">
<span className="dh-avatar">
{profile.userName.slice(0, 1)}
</span>
<div>
<h2>{profile.userName || "旅人"}</h2>
<p>角色会记住你选择的称呼与身份。</p>
</div>
</div>
<label>
你的称呼
<input
value={profileDraft.userName}
required
maxLength={60}
onChange={(e) =>
setProfileDraft({
...profileDraft,
userName: e.target.value,
})
}
/>
</label>
<label>
身份与背景
<textarea
rows={6}
value={profileDraft.persona}
maxLength={2000}
placeholder="例如:独自在星港旅行的摄影师,喜欢雨天和旧唱片。"
onChange={(e) =>
setProfileDraft({
...profileDraft,
persona: e.target.value,
})
}
/>
</label>
<p className="dh-form-note">
账号称呼与身份仅作为新会话的默认值;已有会话保留自己的设定。NSFW
开关保存后影响所有会话的后续回复。
</p>
<label className="dh-content-preference">
<span>
<strong>NSFW 成人内容</strong>
<small>
{initial.account.startsWith("guest:")
? "游客体验仅提供日常内容,登录后可管理账号偏好。"
: "登录账号默认开启,可随时关闭;保存后用于后续回复。"}
</small>
</span>
<input
type="checkbox"
role="switch"
disabled={initial.account.startsWith("guest:")}
checked={
initial.account.startsWith("guest:")
? false
: (profileDraft.nsfwEnabled ?? true)
}
onChange={(event) =>
setProfileDraft({
...profileDraft,
nsfwEnabled: event.target.checked,
})
}
/>
</label>
<button className="dh-primary" type="submit">
<Check size={16} />
保存身份与偏好
</button>
<div className="dh-profile-stats">
<div>
<strong>{summaries.length}</strong>
<span>段故事</span>
</div>
<div>
<strong>{profile.favorites.length}</strong>
<span>次心动</span>
</div>
<div>
<strong>{books.length}</strong>
<span>本世界书</span>
</div>
</div>
<a className="dh-logout" href="/api/auth/logout?next=/login">
<LogOut size={16} />
退出当前账号
</a>
</form>
)}
<footer className="dh-footer">
星港 STELLAR <span>✧</span> 虚构相遇,真实灵感
</footer>
</div>
)}
{detail && (
<div className="dh-detail-page">
<GrowthJourney account={initial.account} page="detail" />
{detail.kind === "character" && (
<CardOpenTracker
account={initial.account}
cardId={detail.id}
receipt={searchParams.get("recommendation")}
/>
)}
<header className="dh-detail-nav">
<button className="dh-detail-back" onClick={goBack}>
<ArrowLeft size={18} />
返回上一页
</button>
<span>
{detail.kind === "character"
? "角色详情"
: detail.kind === "worldbook"
? "世界书"
: "对话风格"}
</span>
</header>
<section
className="dh-detail"
role="region"
aria-label={detail.name}
>
{detail.kind === "character" && (
<div className="dh-detail-cover">
<img src={detail.cover || "/icon.svg"} alt={detail.name} />
</div>
)}
<div className="dh-detail-body">
<span className="dh-eyebrow">
{detail.kind === "character"
? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色`
: detail.kind === "worldbook"
? "WORLD BOOK"
: "STORY PRESET"}
</span>
<h1>{detail.name}</h1>
<div className="dh-card-tags">
{detail.tags.map((t) => (
<span key={t}>{t}</span>
))}
</div>
<h2>故事与背景</h2>
<p className="dh-detail-description">{detail.description}</p>
{detail.greeting && (
<>
<h2>开场预览</h2>
<blockquote>
{detail.greeting
.replaceAll("{{user}}", profile?.userName ?? "旅人")
.replaceAll("{{char}}", detail.name)}
</blockquote>
</>
)}
{detail.kind === "character" ? (
<>
<button
className="dh-primary"
disabled={opening}
onClick={() => start(detail)}
>
{opening ? (
<LoaderCircle className="dh-spin" size={17} />
) : (
<MessageCircle size={17} />
)}
开启这段故事
</button>
{detail.alternateGreetings.map((g, i) => (
<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>
))}
</>
) : (
<p className="dh-form-note">
进入任意对话,点击右上角「对话设定」即可使用。
</p>
)}
<small className="dh-source">{detail.source}</small>
</div>
</section>
</div>
)}
</main>
{showSettings && settings && (
<div className={`dh-overlay ${selectionSheet ? "dh-sheet-open" : ""}`}>
<form
className="dh-settings"
role="dialog"
aria-modal="true"
aria-label="对话设定"
aria-hidden={selectionSheet ? true : undefined}
inert={selectionSheet ? true : undefined}
onSubmit={saveSettings}
>
<header>
<div>
<span className="dh-eyebrow">MAKE IT YOUR STORY</span>
<h2>对话设定</h2>
<p className="dh-form-note">
只影响当前这段对话的后续回复,不修改账号身份、其他对话或已发送的消息。角色默认设定会作为未选择项目的基础。
</p>
</div>
<button
type="button"
className="dh-icon"
aria-label="关闭设定"
onClick={() => setShowSettings(false)}
>
<X />
</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
maxLength={60}
value={settings.userName}
onChange={(e) =>
setSettings({ ...settings, userName: e.target.value })
}
/>
</label>
<label>
本次身份
<textarea
rows={3}
maxLength={2000}
value={settings.persona}
onChange={(e) =>
setSettings({ ...settings, persona: e.target.value })
}
/>
</label>
<button
className="dh-text-button"
type="button"
onClick={() =>
setSettings({
...settings,
userName: profile?.userName ?? "旅人",
persona: profile?.persona ?? "",
})
}
>
使用我的身份资料
</button>
<label>
固定记忆
<textarea
rows={3}
maxLength={3000}
value={settings.memory}
placeholder="记录你们共同经历的重要事实…"
onChange={(e) =>
setSettings({ ...settings, memory: e.target.value })
}
/>
</label>
<div className="dh-mobile-choices">
<button
type="button"
className="dh-choice-trigger"
aria-label="选择叙事风格"
onClick={() => openSelection("style")}
>
<WandSparkles aria-hidden="true" />
<span>
<strong>叙事风格</strong>
<small>
{presets.find((p) => p.id === settings.presetId)?.name ??
(settings.presetId ? "当前会话风格" : "角色默认风格")}
</small>
</span>
<ChevronRight aria-hidden="true" />
</button>
<button
type="button"
className="dh-choice-trigger"
aria-label="选择世界书"
onClick={() => openSelection("books")}
>
<BookOpen aria-hidden="true" />
<span>
<strong>加入世界书</strong>
<small>
{settings.bookIds.length
? `已选 ${settings.bookIds.length} 本 · ${books
.filter((b) => settings.bookIds.includes(b.id))
.map((b) => b.name)
.join("、")}`
: "未加入世界书"}
</small>
</span>
<ChevronRight aria-hidden="true" />
</button>
</div>
<div className="dh-desktop-choices">
{styleChoices(settings.presetId, (value) =>
setSettings({ ...settings, presetId: value }),
)}
{bookChoices(settings.bookIds, (value) =>
setSettings({ ...settings, bookIds: value }),
)}
</div>
<p className="dh-form-note">
保存后用于接下来的回复。固定单条消息,可将它加入对话记忆。
</p>
</div>
<button className="dh-primary" type="submit">
保存设定
</button>
</form>
{selectionSheet && (
<div className="dh-selection-layer">
<button
type="button"
className="dh-selection-backdrop"
aria-label="取消选择"
tabIndex={-1}
onClick={() => setSelectionSheet(null)}
/>
<section
className="dh-selection-sheet"
role="dialog"
aria-modal="true"
aria-label={
selectionSheet === "style" ? "选择叙事风格" : "选择世界书"
}
>
<div className="dh-sheet-handle" aria-hidden="true" />
<header>
<div>
<h2>
{selectionSheet === "style" ? "叙事风格" : "加入世界书"}
</h2>
<p>
{selectionSheet === "style"
? "选择你喜欢的故事氛围"
: "可选择多本,丰富角色的故事背景"}
</p>
</div>
<button
type="button"
className="dh-icon"
aria-label="关闭选择抽屉"
onClick={() => setSelectionSheet(null)}
>
<X />
</button>
</header>
<div className="dh-selection-body">
{selectionSheet === "style"
? styleChoices(
choiceDraft.presetId,
(value) =>
setChoiceDraft({ ...choiceDraft, presetId: value }),
true,
)
: bookChoices(
choiceDraft.bookIds,
(value) =>
setChoiceDraft({ ...choiceDraft, bookIds: value }),
true,
)}
</div>
<footer>
<button
type="button"
className="dh-sheet-reset"
onClick={() =>
setChoiceDraft(
selectionSheet === "style"
? { ...choiceDraft, presetId: undefined }
: { ...choiceDraft, bookIds: [] },
)
}
>
{selectionSheet === "style" ? "恢复默认" : "清空选择"}
</button>
<button
type="button"
className="dh-primary"
onClick={confirmSelection}
>
确认选择
{selectionSheet === "books"
? `(${choiceDraft.bookIds.length})`
: ""}
</button>
</footer>
</section>
</div>
)}
</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}
busy={deleting}
error={deleteError}
onCancel={() => {
if (!deleting) setDeleteTarget(null);
}}
onConfirm={confirmDelete}
/>
)}
</div>
);
}
/** 独立详情路由打开也计入漏斗;推荐入口已上报的点击由回执事件去重链路承接。 */
function CardOpenTracker({
account,
cardId,
receipt,
}: {
account: string;
cardId: string;
receipt: string | null;
}) {
const seen = useRef("");
useEffect(() => {
if (seen.current === `${cardId}:${receipt}`) return;
seen.current = `${cardId}:${receipt}`;
const source =
receipt === recommendationReceipt(account, cardId) ? receipt : undefined;
if (source)
trackGrowth(account, "recommendation_exposure", undefined, source);
trackGrowth(account, "card_open", cardId, source ?? undefined);
void flushGrowth(account);
}, [account, cardId, receipt]);
return null;
}
/** 普通发现列表也只在可见时记曝光,筛选重渲染不会重复统计同一张卡。 */
function CatalogExposure({
account,
cardIds,
}: {
account: string;
cardIds: string;
}) {
const seen = useRef(new Set<string>());
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
const id = (entry.target as HTMLElement).dataset.growthCard;
if (entry.isIntersecting && id && !seen.current.has(id)) {
seen.current.add(id);
trackGrowth(account, "card_impression", id);
observer.unobserve(entry.target);
}
}
},
{ threshold: 0.5 },
);
document
.querySelectorAll("[data-growth-card]")
.forEach((e) => observer.observe(e));
return () => observer.disconnect();
}, [account, cardIds]);
return null;
}