"use client";
/* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */
/** 星港数字人空间:探索、会话、世界书和身份资料的响应式入口。 */
import Link from "next/link";
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,
} from "lucide-react";
import {
digital,
readStream,
type Card,
type Profile,
type Message,
type Settings,
type Conversation,
type Summary,
type Bootstrap,
} from "@/lib/digital";
import "./digital.css";
type Tab = "discover" | "chats" | "library" | "me";
/** 接收文本与视觉打字分离;减少动画设置下直接呈现完整文本。 */
function TypedText({ text, animate }: { text: string; animate: boolean }) {
const [shown, setShown] = useState(animate ? "" : text);
const latest = useRef(text);
useEffect(() => {
latest.current = text;
}, [text]);
useEffect(() => {
if (!animate) return;
const instant = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches;
const timer = setInterval(
() =>
setShown((current) => {
const target = latest.current;
if (instant || !target.startsWith(current)) return target;
const rest = Array.from(target.slice(current.length));
return (
current +
rest
.slice(0, Math.max(1, Math.min(10, Math.ceil(rest.length / 15))))
.join("")
);
}),
24,
);
return () => clearInterval(timer);
}, [animate]);
return <>{animate ? shown : text}>;
}
/** 内容完全作为文本渲染,角色对白不允许注入 HTML。 */
function MessageText({
message,
animate,
}: {
message: Message;
animate: boolean;
}) {
return (
{message.status === "generating" && (
)}
);
}
/** 前台无分组按钮、调试开关或实验配置。 */
export function DigitalHome({
initial,
initialSummaries,
}: {
initial: Bootstrap;
initialSummaries: Summary[];
}) {
const [tab, setTab] = useState("discover"),
[boot, setBoot] = useState(initial),
[summaries, setSummaries] = useState(initialSummaries);
const [query, setQuery] = useState(""),
[tag, setTag] = useState("全部"),
[onlyFavorites, setOnlyFavorites] = useState(false);
const [detail, setDetail] = useState(null),
[conversation, setConversation] = useState(null);
const [draft, setDraft] = useState(""),
[busy, setBusy] = useState(false),
[opening, setOpening] = useState(false),
[error, setError] = useState(""),
[notice, setNotice] = useState("");
const [showSettings, setShowSettings] = useState(false),
[settings, setSettings] = useState(null),
[profile, setProfile] = useState(initial.profile);
const [profileDraft, setProfileDraft] = useState(
initial.profile,
);
const favoritePending = useRef(false);
const [activeMessage, setActiveMessage] = useState(null),
[showJump, setShowJump] = useState(false),
[showMenu, setShowMenu] = useState(false);
const decisionReceived = useRef(0);
const stream = useRef(null),
streamingId = useRef(null),
viewport = useRef(null),
messagesElement = useRef(null),
textarea = useRef(null),
atBottom = useRef(true),
currentId = useRef(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 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("conversations")),
[],
);
const reloadBootstrap = useCallback(async () => {
const data = await digital("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,
decisionId: null,
},
}
: current,
),
remaining,
);
return () => clearTimeout(timer);
}, [decisionExpiresAt, decisionServerNow]);
useEffect(() => {
if (!notice) return;
const timer = setTimeout(() => setNotice(""), 3500);
return () => clearTimeout(timer);
}, [notice]);
useEffect(() => {
const el = messagesElement.current;
if (!el) return;
const observer = new ResizeObserver(() => {
if (atBottom.current)
viewport.current?.scrollTo({
top: viewport.current.scrollHeight,
behavior: "instant",
});
});
observer.observe(el);
return () => observer.disconnect();
}, [conversationId]);
useEffect(() => {
if (!conversationId) return;
const resize = () =>
document.documentElement.style.setProperty(
"--dh-viewport",
`${window.visualViewport?.height ?? window.innerHeight}px`,
);
resize();
window.visualViewport?.addEventListener("resize", resize);
return () => {
window.visualViewport?.removeEventListener("resize", resize);
document.documentElement.style.removeProperty("--dh-viewport");
};
}, [conversationId]);
useEffect(() => {
if (!conversationId) return;
try {
sessionStorage.setItem(`dh-draft:${conversationId}`, draft);
} catch {}
}, [draft, conversationId]);
useEffect(() => {
if (!detail && !showSettings) return;
const previous = document.activeElement as HTMLElement | null;
const dialog = document.querySelector(
'.dh-overlay [role="dialog"]',
);
const controls = () =>
Array.from(
dialog?.querySelectorAll(
'button:not([disabled]),input,textarea,select,[tabindex="0"]',
) ?? [],
);
const frame = requestAnimationFrame(() => controls()[0]?.focus());
const onKey = (event: globalThis.KeyboardEvent) => {
if (event.key === "Escape") {
setDetail(null);
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();
};
}, [detail, showSettings]);
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(
`conversations/${conversationId}`,
);
if (!cancelled && currentId.current === conversationId) {
setConversation(saved);
setBusy(saved.busy);
}
} catch {}
}, 2000);
return () => {
cancelled = true;
clearInterval(timer);
};
}, [busy, conversationId]);
async function openConversation(id: string) {
if (streamingId.current && streamingId.current !== id) {
setNotice("请先停止当前回复,再切换会话");
return;
}
const sequence = ++openSequence.current;
setOpening(true);
setError("");
try {
const c = await digital(`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;
try {
setDraft(sessionStorage.getItem(`dh-draft:${id}`) ?? "");
} catch {
setDraft("");
}
setTab("chats");
setDetail(null);
} 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,
uiDecisionId: boot?.decision.decisionId ?? undefined,
});
await openConversation(c.id);
await refreshSummaries();
} 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 {
await digital("profile", "PUT", next);
setProfile(next);
} catch (e) {
reportError(e);
} finally {
favoritePending.current = false;
}
}
async function send(mode: "send" | "regenerate" = "send") {
if (
!conversation ||
busy ||
streamingId.current ||
(mode === "send" && !draft.trim())
)
return;
const id = conversation.id,
content = draft.trim(),
requestId = crypto.randomUUID();
let assistantId = `pending-${requestId}`;
setBusy(true);
setError("");
setNotice("");
atBottom.current = true;
streamingId.current = id;
if (mode === "send") setDraft("");
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, ...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("/login");
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")
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);
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(`conversations/${id}`);
setConversation(saved);
setBusy(saved.busy);
} 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) {
if (
event.key === "Enter" &&
!event.shiftKey &&
!event.nativeEvent.isComposing &&
window.matchMedia("(min-width: 768px)").matches
) {
event.preventDefault();
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) {
if (!conversation || busy) return;
try {
const result = await digital<{ id: string }>(
`conversations/${conversation.id}/branch`,
"POST",
{ messageId: message.id },
);
await openConversation(result.id);
await refreshSummaries();
setNotice("已从这里开启新分支,原会话仍然保留");
} catch (e) {
reportError(e);
}
}
async function removeConversation() {
if (
!conversation ||
busy ||
!window.confirm("删除此会话和全部消息?此操作无法撤销。")
)
return;
try {
await digital(`conversations/${conversation.id}`, "DELETE");
setConversation(null);
currentId.current = null;
await refreshSummaries();
} catch (e) {
reportError(e);
}
}
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("对话设定已保存,下次回复生效");
} catch (e) {
reportError(e);
}
}
async function saveProfile(event: FormEvent) {
event.preventDefault();
if (!profile || !profileDraft) return;
const next = {
...profile,
userName: profileDraft.userName,
persona: profileDraft.persona,
};
try {
await digital("profile", "PUT", next);
setProfile(next);
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) {
if (conversation && busy) {
setNotice("请先停止当前回复,再离开会话");
return;
}
setConversation(null);
currentId.current = null;
setTab(value);
setError("");
}
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 modern = boot?.decision.variant === "B";
return (
{error && (
{error}
)}
{notice && (
{notice}
)}
{!boot ? (
正在开启你的星港…
) : conversation ? (
{
const v = viewport.current;
if (v) {
atBottom.current =
v.scrollHeight - v.scrollTop - v.clientHeight < 110;
setShowJump(!atBottom.current);
}
}}
>
✦
这里是你与 {currentCard?.name} 的私人故事
内容由 AI 生成,虚构世界中的角色可能会犯错。
{conversation.messages.map((m, index) => (
{m.role === "assistant" && (
)}
{m.role === "user"
? conversation.settings.userName
: currentCard?.name}
{m.pinned && }
{!m.content && m.status === "generating" && (
)}
{!busy && m.content && (
{m.role === "assistant" &&
index === conversation.messages.length - 1 &&
conversation.messages.some(
(v) => v.role === "user",
) && (
)}
)}
{!busy &&
!m.content &&
m.role === "assistant" &&
index === conversation.messages.length - 1 &&
conversation.messages.some(
(v) => v.role === "user",
) && (
)}
{m.status === "failed" && (
生成失败,可重新生成
)}
{m.status === "superseded" && (
此前回答
)}
{m.status === "stopped" && (
已停止
)}
))}
{showJump && (
)}
{busy
? "正在生成 · 点击方块随时停止"
: "Enter 发送 · Shift + Enter 换行"}
{draft.length > 3500
? `${draft.length}/4000`
: "一段对白,一个新的可能"}
) : (
YOUR PRIVATE UNIVERSE
{tab === "discover"
? "遇见,让故事开始"
: tab === "chats"
? "故事还在继续"
: tab === "library"
? "为想象力,留一盏灯"
: "你想以谁的身份相遇?"}
✦
{tab === "discover" && (
<>
今晚,有人等你开口
不止聊天。
走进另一个人的世界。
一封未寄出的信,一次雨夜的重逢。
挑选你心动的角色,写下只属于你们的下一章。
{cards.slice(0, 3).map((c) => (

))}
✧
{tags.map((t) => (
))}
{onlyFavorites ? "心动收藏" : "为你发现"}
{filtered.length} 位角色 · 全部成年
{filtered.map((c) => (
))}
{!filtered.length && (
暂时没有找到
换一个关键词,或者看看其他故事。
)}
>
)}
{tab === "chats" && (
<>
最近对话
{summaries.map((s) => {
const c = cards.find((c) => c.id === s.characterId);
return (
);
})}
{!summaries.length && (
第一句话,交给你
每个角色都准备好了一段开场,等你接下去。
)}
>
)}
{tab === "library" && (
<>
角色是灵魂,世界书是背景,预设决定叙事方式。在对话设定中组合它们,形成你自己的故事。
世界书
按关键词触发的故事背景
{books.map((b) => (
))}
叙事预设
切换文字的节奏与温度
{presets.map((b) => (
))}
>
)}
{tab === "me" && profile && profileDraft && (
)}
)}
{detail && (
{
if (e.target === e.currentTarget) setDetail(null);
}}
>
{detail.kind === "character" && (
)}
{detail.kind === "character"
? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色`
: detail.kind === "worldbook"
? "WORLD BOOK"
: "STORY PRESET"}
{detail.name}
{detail.tags.map((t) => (
{t}
))}
{detail.description}
{detail.greeting && (
{detail.greeting
.replaceAll("{{user}}", profile?.userName ?? "旅人")
.replaceAll("{{char}}", detail.name)}
)}
{detail.kind === "character" ? (
<>
{detail.alternateGreetings.map((g, i) => (
))}
>
) : (
进入任意对话,点击右上角「对话设定」即可使用。
)}
{detail.source}
)}
{showSettings && settings && (
)}
);
}