diff --git a/src/components/digital-message.tsx b/src/components/digital-message.tsx
new file mode 100644
index 0000000..6b4dff5
--- /dev/null
+++ b/src/components/digital-message.tsx
@@ -0,0 +1,93 @@
+"use client";
+
+/** 角色对白与故事叙述的安全展示;流式与完成态共用排版,用户消息保持纯文本。 */
+import { memo, useEffect, useMemo, useRef, useState } from "react";
+import type { Message } from "@/lib/digital";
+import { parseDigitalMessage } from "@/lib/digital-message-format";
+
+/** 网络接收与视觉出字分离,结束后继续显示已收到的尾部,减少动画设置下直接显示。 */
+function useRevealedText(text: string, animate: boolean, generating: boolean) {
+ const [shown, setShown] = useState(animate ? "" : text);
+ const latest = useRef(text);
+ useEffect(() => {
+ latest.current = text;
+ }, [text]);
+ const revealing = animate && (generating || shown !== text);
+ useEffect(() => {
+ if (!revealing) 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);
+ }, [revealing]);
+ return animate ? shown : text;
+}
+
+/** 一条消息仍是一个操作单元;片段均渲染为文本节点,角色内容不能注入 HTML。 */
+export const DigitalMessage = memo(function DigitalMessage({
+ message,
+ animate,
+}: {
+ message: Message;
+ animate: boolean;
+}) {
+ const generating = message.status === "generating";
+ const text = useRevealedText(message.content, animate, generating);
+ const blocks = useMemo(
+ () =>
+ message.role === "assistant"
+ ? parseDigitalMessage(
+ text,
+ generating ||
+ ["stopped", "failed"].includes(message.status) ||
+ text !== message.content,
+ )
+ : [],
+ [generating, message.content, message.role, message.status, text],
+ );
+ if (generating && !message.content.trim())
+ return (
+
+
+
+
+
+ );
+ const cursor = generating ?
: null;
+ return (
+
+ {message.role === "assistant"
+ ? blocks.map((block, index) => (
+
+ {block.kind === "dialogue" ? (
+ {block.text}
+ ) : (
+ block.text
+ )}
+ {index === blocks.length - 1 ? cursor : null}
+
+ ))
+ : text}
+ {!blocks.length ? cursor : null}
+ {!message.content && !generating ? "这次没有生成内容。" : null}
+
+ );
+});
diff --git a/src/components/digital.css b/src/components/digital.css
index 58c8ba2..06cceb7 100644
--- a/src/components/digital.css
+++ b/src/components/digital.css
@@ -990,6 +990,53 @@
line-height: 1.9;
margin: 8px 0 20px !important;
}
+.dh-profile-form > .dh-content-preference {
+ flex-direction: row;
+ align-items: center;
+ justify-content: space-between;
+ gap: 18px;
+ padding: 16px 0;
+ border-top: 1px solid var(--dh-line);
+ border-bottom: 1px solid var(--dh-line);
+}
+.dh-content-preference span {
+ min-width: 0;
+}
+.dh-content-preference small {
+ display: block;
+ margin-top: 6px;
+ color: var(--dh-muted);
+ line-height: 1.7;
+}
+.dh-content-preference input[type="checkbox"] {
+ appearance: none;
+ flex: none;
+ width: 44px;
+ height: 26px;
+ padding: 3px;
+ border: 1px solid var(--dh-line);
+ border-radius: 20px;
+ background: var(--dh-panel);
+ cursor: pointer;
+}
+.dh-content-preference input::before {
+ display: block;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background: #fff;
+ content: "";
+}
+.dh-content-preference input:checked {
+ background: var(--dh-accent);
+}
+.dh-content-preference input:checked::before {
+ transform: translateX(18px);
+}
+.dh-content-preference input:focus-visible {
+ outline: 2px solid var(--dh-accent);
+ outline-offset: 3px;
+}
.dh-profile-stats {
display: flex;
border-top: 1px solid var(--dh-line);
@@ -1654,6 +1701,28 @@
font-size: 14px;
color: #e6dfe7;
}
+.dh-message-prose {
+ white-space: normal;
+}
+.dh-message-prose > p {
+ margin: 0;
+ white-space: pre-wrap;
+}
+.dh-message-prose > p + p {
+ margin-top: 12px;
+}
+.dh-prose-dialogue {
+ color: #fff5fc;
+}
+.dh-prose-dialogue strong {
+ font-weight: 600;
+}
+.dh-prose-narration {
+ color: #c2b6c4;
+}
+.dh-prose-narration.dh-prose-latin {
+ font-style: italic;
+}
.dh-message-user {
justify-content: flex-end;
}
diff --git a/src/lib/digital-message-format.ts b/src/lib/digital-message-format.ts
new file mode 100644
index 0000000..2e7d192
--- /dev/null
+++ b/src/lib/digital-message-format.ts
@@ -0,0 +1,151 @@
+/** 数字人消息的受限文本格式:对白、故事叙述与旧版括号;始终返回文本,不解释 HTML。 */
+
+/** 有序展示片段;原始 content 继续用于存储、复制、记忆和上下文。 */
+export type DigitalMessageBlock = {
+ kind: "dialogue" | "narration" | "plain";
+ text: string;
+};
+
+const quotePairs: Record
= {
+ '"': '"',
+ "“": "”",
+ "「": "」",
+ "『": "』",
+ "«": "»",
+ """: """,
+};
+
+/** 跳过转义字符;引号不跨行,括号按同类型嵌套匹配,避免误吞后续内容。 */
+function closingIndex(
+ text: string,
+ from: number,
+ open: string,
+ close: string,
+ nested = false,
+) {
+ let depth = 1;
+ for (let i = from; i < text.length; i++) {
+ if (text[i] === "\\") {
+ i++;
+ continue;
+ }
+ if (!nested && quotePairs[open] && text[i] === "\n") return -1;
+ if (nested && text.startsWith(open, i)) depth++;
+ if (text.startsWith(close, i)) {
+ depth--;
+ if (depth === 0) return i;
+ }
+ }
+ return -1;
+}
+
+/** 星号需要处于词边界,避免把乘法、文件名或普通单词里的星号视为排版。 */
+function markerBoundary(text: string, index: number) {
+ return (
+ index === 0 || /[\s。!?!?,,;;::))\]”"」』»]/u.test(text[index - 1])
+ );
+}
+
+/**
+ * 解析累计正文而非单个 SSE delta。未闭合标记仅在流式/中断展示时延续当前样式;
+ * 旧版括号外文本按对白处理,有引号的旧开场白将引号外文字作为叙述,其他纯文本保留。
+ * 与 role-admin/src/utils/digital-message-format.ts 保持同一实现和用例,独立构建时无需跨仓引用。
+ */
+export function parseDigitalMessage(
+ source: string,
+ streaming = false,
+): DigitalMessageBlock[] {
+ const blocks: DigitalMessageBlock[] = [];
+ for (const paragraph of source.replace(/\r\n?/g, "\n").split(/\n\s*\n/)) {
+ const parts: DigitalMessageBlock[] = [];
+ let legacyNarration = false;
+ const push = (kind: DigitalMessageBlock["kind"], text: string) => {
+ if (!text) return;
+ const last = parts[parts.length - 1];
+ if (last?.kind === kind) last.text += text;
+ else parts.push({ kind, text });
+ };
+ for (let i = 0; i < paragraph.length; ) {
+ const char = paragraph[i];
+ if (
+ char === "\\" &&
+ /[*"\\()()“”「」『』]/u.test(paragraph[i + 1] ?? "")
+ ) {
+ push("plain", paragraph[i + 1]);
+ i += 2;
+ continue;
+ }
+ const quoteEnd = quotePairs[char];
+ if (quoteEnd) {
+ const close = closingIndex(paragraph, i + 1, char, quoteEnd);
+ const lineEnd = paragraph.indexOf("\n", i + 1);
+ const end =
+ close >= 0 ? close + 1 : lineEnd >= 0 ? lineEnd : paragraph.length;
+ push("dialogue", paragraph.slice(i, end));
+ i = end;
+ continue;
+ }
+ if (
+ char === "*" &&
+ markerBoundary(paragraph, i) &&
+ !/\s/u.test(paragraph[i + 1] ?? "")
+ ) {
+ const marker = paragraph.startsWith("**", i) ? "**" : "*";
+ const close = closingIndex(
+ paragraph,
+ i + marker.length,
+ marker,
+ marker,
+ );
+ if (close >= 0 || streaming) {
+ push(
+ marker === "**" ? "dialogue" : "narration",
+ paragraph.slice(i + marker.length, close >= 0 ? close : undefined),
+ );
+ i = close >= 0 ? close + marker.length : paragraph.length;
+ continue;
+ }
+ // 格式不完整的历史正文原样保留,不猜测后面的哪些字符属于标记。
+ push("plain", paragraph.slice(i));
+ break;
+ }
+ if ((char === "(" || char === "(") && markerBoundary(paragraph, i)) {
+ const close = closingIndex(
+ paragraph,
+ i + 1,
+ char,
+ char === "(" ? ")" : ")",
+ true,
+ );
+ if (close >= 0 || streaming) {
+ legacyNarration = true;
+ push(
+ "narration",
+ paragraph.slice(i + 1, close >= 0 ? close : undefined),
+ );
+ i = close >= 0 ? close + 1 : paragraph.length;
+ continue;
+ }
+ push("plain", paragraph.slice(i));
+ break;
+ }
+ push("plain", char);
+ i++;
+ }
+ const hasDialogue = parts.some((part) => part.kind === "dialogue");
+ for (const part of parts) {
+ const kind =
+ part.kind !== "plain"
+ ? part.kind
+ : legacyNarration
+ ? "dialogue"
+ : hasDialogue
+ ? "narration"
+ : "plain";
+ for (const line of part.text.split(/\n+/)) {
+ if (line.trim()) blocks.push({ kind, text: line.trim() });
+ }
+ }
+ }
+ return blocks;
+}
diff --git a/src/lib/digital.ts b/src/lib/digital.ts
index 93a5859..49c17ff 100644
--- a/src/lib/digital.ts
+++ b/src/lib/digital.ts
@@ -20,6 +20,8 @@ export type Profile = {
favorites: string[];
persona: string;
userName: string;
+ /** 登录账号的成人内容偏好;旧服务未返回时沿用默认开启。 */
+ nsfwEnabled?: boolean;
};
/** 会话消息拥有持久化 id,避免流式刷新时重复插入。 */
export type Message = {
diff --git a/tests/digital-message-format.test.mjs b/tests/digital-message-format.test.mjs
new file mode 100644
index 0000000..546aca6
--- /dev/null
+++ b/tests/digital-message-format.test.mjs
@@ -0,0 +1,107 @@
+/** 对白、叙述、旧消息与累计流式文本的格式回归,不依赖浏览器或真实模型。 */
+import test from "node:test";
+import assert from "node:assert/strict";
+import { parseDigitalMessage as parse } from "../src/lib/digital-message-format.ts";
+
+test("标准消息按剧情顺序拆分叙述、对白与心理,隐藏星号并保留引号", () => {
+ assert.deepEqual(parse("*她合上书。*\n\n“你来了。”\n\n*她终于放松下来。*"), [
+ { kind: "narration", text: "她合上书。" },
+ { kind: "dialogue", text: "“你来了。”" },
+ { kind: "narration", text: "她终于放松下来。" },
+ ]);
+});
+
+test("旧消息的成对括号与括号外对白兼容,内层括号不会提前关闭叙述", () => {
+ assert.deepEqual(
+ parse(
+ "(她抱起书(封面有些旧),笑了笑)你来了。\n(她心里有些高兴)坐吧。",
+ ),
+ [
+ { kind: "narration", text: "她抱起书(封面有些旧),笑了笑" },
+ { kind: "dialogue", text: "你来了。" },
+ { kind: "narration", text: "她心里有些高兴" },
+ { kind: "dialogue", text: "坐吧。" },
+ ],
+ );
+});
+
+test("旧开场白的无标记叙述与引号对白分别展示,英文撇号不作为对白", () => {
+ assert.deepEqual(
+ parse('She picked up her book.\n"You’re early. Don\'t wait outside."'),
+ [
+ { kind: "narration", text: "She picked up her book." },
+ { kind: "dialogue", text: '"You’re early. Don\'t wait outside."' },
+ ],
+ );
+ for (const [open, close] of [
+ ["“", "”"],
+ ["「", "」"],
+ ["『", "』"],
+ ["«", "»"],
+ [""", """],
+ ]) {
+ assert.deepEqual(parse(`${open}你好${close}`), [
+ { kind: "dialogue", text: `${open}你好${close}` },
+ ]);
+ }
+});
+
+test("纯文本、普通备注、乘法与不完整的历史标记保留原文", () => {
+ for (const text of [
+ "普通文本",
+ "说明(选填)",
+ "3 * 4 = 12",
+ "file*name.txt",
+ "*未闭合",
+ "(未闭合",
+ ]) {
+ assert.deepEqual(parse(text), [{ kind: "plain", text }]);
+ }
+ assert.deepEqual(parse(" \n\r\n"), []);
+ assert.deepEqual(parse("第一段\r\n\r\n第二段"), [
+ { kind: "plain", text: "第一段" },
+ { kind: "plain", text: "第二段" },
+ ]);
+});
+
+test("显式叙述里的引号保持为故事文本,不再二次推断", () => {
+ assert.deepEqual(parse("*她想到“明天”这个词,轻轻笑了。*"), [
+ { kind: "narration", text: "她想到“明天”这个词,轻轻笑了。" },
+ ]);
+ assert.deepEqual(parse("**“你好。”**"), [
+ { kind: "dialogue", text: "“你好。”" },
+ ]);
+ assert.deepEqual(parse("\\*字面星号\\*"), [
+ { kind: "plain", text: "*字面星号*" },
+ ]);
+});
+
+test("累计流式输入的每个字符前缀都隐藏未闭合星号,完成态排版相同", () => {
+ const source = "*她推开门。*\n\n“你来了。”\n\n*她松了口气。*";
+ for (let end = 1; end <= source.length; end++) {
+ const blocks = parse(source.slice(0, end), true);
+ assert.equal(
+ blocks.some((block) => block.text.includes("*")),
+ false,
+ `前缀 ${end}`,
+ );
+ }
+ assert.deepEqual(parse(source, true), parse(source));
+ assert.deepEqual(parse("*她推开门", true), [
+ { kind: "narration", text: "她推开门" },
+ ]);
+ assert.deepEqual(parse("(她推开门", true), [
+ { kind: "narration", text: "她推开门" },
+ ]);
+ assert.deepEqual(parse("“你来了", true), [
+ { kind: "dialogue", text: "“你来了" },
+ ]);
+ assert.deepEqual(parse("**Hello", true), [
+ { kind: "dialogue", text: "Hello" },
+ ]);
+});
+
+test("HTML 与脚本内容只作为文本保留,格式解析不会生成任何标签", () => {
+ const text = "";
+ assert.deepEqual(parse(text), [{ kind: "plain", text }]);
+});