"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,
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 { ConversationRow, ConversationDeleteDialog } from "./conversation-row";
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;
}) {
if (message.status === "generating" && !message.content.trim())
return (
);
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 [stylePolicy, setStylePolicy] = useState<
"loading" | "personal" | "managed" | "unknown"
>("loading");
const [showSettings, setShowSettings] = useState(false),
[settings, setSettings] = useState(null),
[profile, setProfile] = useState(initial.profile);
const [profileDraft, setProfileDraft] = useState(
initial.profile,
);
const [selectionSheet, setSelectionSheet] = useState<
"style" | "books" | null
>(null);
const [choiceDraft, setChoiceDraft] = useState<{
presetId?: string;
bookIds: string[];
}>({ bookIds: [] });
const selectionTrigger = useRef(null);
const [swipedConversation, setSwipedConversation] = useState(
null,
);
const [deleteTarget, setDeleteTarget] = useState(null),
[deleting, setDeleting] = useState(false),
[deleteError, setDeleteError] = useState("");
const [ideasOpen, setIdeasOpen] = useState(false),
[ideasLoading, setIdeasLoading] = useState(false),
[ideas, setIdeas] = useState([]),
[ideasError, setIdeasError] = useState("");
const ideasRequest = useRef(null),
imeComposing = useRef(false),
deleteLock = useRef(false);
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),
touchY = useRef(null),
draggingScroll = useRef(false),
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 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("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,
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]);
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]);
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(
(
document.querySelector(".dh-selection-sheet") ?? 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") {
event.preventDefault();
if (document.querySelector(".dh-selection-sheet")) {
setSelectionSheet(null);
return;
}
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(() => {
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(".dh-selection-sheet");
(
panel?.querySelector("input:checked") ??
panel?.querySelector("input") ??
panel?.querySelector("button")
)?.focus();
});
return () => {
cancelAnimationFrame(frame);
media.removeEventListener("change", resize);
if (previous?.isConnected && previous.getClientRects().length)
previous.focus();
else
document
.querySelector(".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(
`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) {
closeIdeas();
imeComposing.current = false;
setSwipedConversation(null);
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;
setShowJump(false);
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" | "continue" = "send") {
if (
!conversation ||
busy ||
streamingId.current ||
(mode === "send" && !draft.trim())
)
return;
closeIdeas();
const id = conversation.id,
content = mode === "send" ? draft.trim() : "",
requestId = crypto.randomUUID();
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, ...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 &&
!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) {
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);
}
}
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 {
await digital(`conversations/${id}`, "DELETE");
setSummaries((current) => current.filter((s) => s.id !== id));
setSwipedConversation(null);
if (currentId.current === id) {
closeIdeas();
setConversation(null);
currentId.current = null;
setDraft("");
}
try {
sessionStorage.removeItem(`dh-draft:${id}`);
} catch {}
setDeleteTarget(null);
setNotice("对话已删除");
} 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) },
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,
};
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) {
closeIdeas();
setSwipedConversation(null);
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 styleChoices = (
value: string | undefined,
onChange: (value: string | undefined) => void,
inSheet = false,
) => (
);
const bookChoices = (
value: string[],
onChange: (value: string[]) => void,
inSheet = false,
) => (
);
useEffect(
() => () => {
ideasRequest.current?.abort();
},
[],
);
// UI按消费者返回值决定,组名仅用于归因;C到Z同样可以返回新版UI。
// 缺少value时兼容尚未升级的服务响应。
const modern =
boot?.decision.value !== undefined
? boot.decision.value === "new" || boot.decision.value === true
: boot?.decision.variant === "B";
return (
{error && (
{error}
)}
{notice && (
{notice}
)}
{!boot ? (
正在开启你的星港…
) : conversation ? (
{
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) {
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);
}
}}
>
✦
这里是你与 {currentCard?.name} 的私人故事
内容由 AI 生成,虚构世界中的角色可能会犯错。
{conversation.messages.map((m, index) => (
{m.role === "assistant" && (
)}
{m.role === "user"
? conversation.settings.userName
: currentCard?.name}
{m.pinned && }
{!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 && (
)}
{ideasOpen && (
{draft
? "选择后追加到现有草稿,不会自动发送。"
: "根据当前对话生成,选择后可编辑再发送。"}
{ideasLoading ? (
正在寻找合适的接话方式…
) : ideasError ? (
{ideasError}
) : (
{ideas.map((idea, i) => (
))}
)}
{!ideasLoading && (
)}
)}
{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.length > 0 && (
向左滑动对话可删除
)}
{summaries.map((s) => (
c.id === s.characterId)}
revealed={swipedConversation === s.id}
disabled={opening || deleting}
onReveal={setSwipedConversation}
onOpen={() => openConversation(s.id)}
onDelete={() => requestDelete(s)}
/>
))}
{!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 && (
{selectionSheet && (
)}
)}
{deleteTarget && (
{
if (!deleting) setDeleteTarget(null);
}}
onConfirm={confirmDelete}
/>
)}
);
}