Compare commits

..

28 Commits

Author SHA1 Message Date
zhanxi e6a95b3d35 merge(master): 同步移动键盘优化与会话软删除到测试分支 2026-10-28 08:12:14 +00:00
zhanxi da4f45525b merge(chat): 修复键盘布局和输入缩放并优化删除弹窗 2026-10-28 08:10:12 +00:00
湛兮 caa54c9b34 fix(mobile): 修复键盘视口与输入缩放并优化删除交互
- 同步 Safari 可视高度和偏移,限制聊天页面滚动并保留手动缩放
- 统一移动输入字号并限制消息输入框高度
- 分离滑动删除按钮,将确认和选择弹窗改为居中样式
2026-10-28 16:08:15 +08:00
zhanxi e1aa51d8b2 merge(master): 同步对白与叙述排版发布到测试分支 2026-10-27 14:27:08 +00:00
zhanxi 5fed13b6fb merge(chat): 区分角色对白与故事叙述 2026-10-27 14:21:14 +00:00
湛兮 ebb8a50eb6 feat(chat): 区分角色对白与故事叙述
- digital-message.tsx: 统一流式与完成态展示,保留用户纯文本和停止后的尾部
- digital-message-format.ts: 解析星号叙述、中英文对白及旧版括号格式
- digital-home.tsx、digital.css: 接入独立消息组件并区分对白与叙述样式
- tests、README.md: 补齐累计流式、旧消息和文本安全回归及中文说明
2026-10-27 22:19:05 +08:00
zhanxi 16e989859c merge(nsfw): 发布登录账号成人内容偏好
合入已验证的 NSFW 账号偏好改动,游客登录限制保持不变。
2026-10-27 12:39:16 +00:00
湛兮 cb5e004eb9 feat(nsfw): 新增账号成人内容偏好并默认开启
- src/lib/digital.ts: 补充账号 NSFW 偏好协议,兼容未返回偏好的旧响应
- src/components/digital-home.tsx: 我的页支持保存开关,收藏更新保留服务端偏好
- src/components/digital.css: 增加开关样式与键盘焦点提示
- README.md: 说明默认值、游客限制与前后端配套发布要求
2026-10-27 20:18:16 +08:00
zhanxi cb1314470a Merge pull request 'chore: 同步独立用户与聊天管理到测试分支' (#18) from master into develop 2026-10-27 11:02:57 +00:00
zhanxi fb46c0fdb5 Merge pull request 'feat(users): 独立 C 端账号并提供聊天记录管理' (#17) from feature/env-pipeline-split into master 2026-10-27 10:56:51 +00:00
湛兮 3530219123 feat(users): 使用独立账号并简化选择样式
- login: 改为独立 C 端账号文案与身份类型
- digital: 世界书和风格改用平面选择列表,保留键盘焦点
- README: 同步独立登录与历史迁移说明
2026-10-27 18:56:24 +08:00
zhanxi f921204dc8 Merge pull request 'chore: 同步继续功能与阅读体验发布到测试分支' (#16) from master into develop 2026-10-27 10:22:19 +00:00
zhanxi fb8be9c460 Merge pull request 'fix(chat): 修复尚未出字就停止后的继续重试' (#15) from feature/env-pipeline-split into master 2026-10-27 10:21:07 +00:00
湛兮 ae2b58e0b8 fix(chat): 恢复提前停止后的继续入口
- 以最近有效台词判断继续能力,停止前未出字时仍可重试
2026-10-27 18:20:49 +08:00
zhanxi c45fb9c941 Merge pull request 'chore: 同步继续功能与阅读体验发布到测试分支' (#14) from master into develop 2026-10-27 10:16:49 +00:00
zhanxi 4638c72680 Merge pull request 'feat(chat): 新增继续按钮并修复回复滚动跟随' (#13) from feature/env-pipeline-split into master 2026-10-27 10:15:51 +00:00
湛兮 1f11112e04 feat(chat): 新增继续按钮并修复回复滚动跟随
- 继续生成保留输入草稿,不新增用户气泡,支持重复续写和停止

- 根据用户上翻意图控制跟随,修复结束后离底及思考点与光标同时出现
2026-10-27 18:15:31 +08:00
zhanxi 6a40040573 Merge pull request 'chore: 同步新老 UI 接入与登录修复到测试分支' (#12) from master into develop 2026-10-27 09:42:54 +00:00
zhanxi cac56740cc Merge pull request 'fix(auth): 修复会话过期跳转内部地址' (#11) from feature/env-pipeline-split into master 2026-10-27 09:42:24 +00:00
湛兮 f75a9abecc fix(auth): 修复会话过期跳转内部地址
- logout 使用站内相对 Location,避免跳到 0.0.0.0 监听地址

- 校验站内返回路径并覆盖正式域名、本地地址及外部跳转变体
2026-10-27 17:42:06 +08:00
zhanxi d3fe1b21ed Merge pull request 'chore: 同步多组实验发布到测试分支' (#10) from master into develop 2026-10-27 07:16:32 +00:00
zhanxi afc474b0c4 Merge pull request 'fix(experiments): 发布多组决策消费支持' (#9) from feature/env-pipeline-split into master 2026-10-27 07:15:54 +00:00
湛兮 a963bec3f3 fix(experiments): 按决策返回值消费多组界面实验
- 用户端支持动态组别和未入组状态,不再固定使用B组判断新版界面
- 决策过期使用服务端返回的默认值,保留旧响应兼容
2026-10-27 15:15:21 +08:00
zhanxi 81079c7364 fix(ui): 隐藏内部滚动轨道并修正风格状态提示
已完成三端构建、规则与真实浏览器链路验收,统一按同一版本发布。
2026-10-27 05:08:33 +00:00
湛兮 4079397625 fix(ui): 隐藏内部滚动轨道并整合叙事风格提示
- 滚动区域:隐藏原生横竖轨道,保留触摸滚动,约束表单和文本域横向溢出

- Grok业务改动:纳入个人风格与统一方案的提示和不可用预设说明

- 状态查询:通过会话只读接口显示控制状态,取消离开页面后的请求
2026-10-27 12:54:51 +08:00
zhanxi 9b2f7fc7cf feat(chat): 滑动删除灵感回复与H5回车发送
已完成类型检查、构建、规则与真实浏览器验收,沿用既有流水线发布。
2026-10-27 04:38:05 +00:00
湛兮 981eab9dcf fix(ui): 保持滑动会话卡片的主题背景与边框 2026-10-27 12:30:54 +08:00
湛兮 d0442f5bb9 feat(chat): 支持滑动删除灵感回复与H5回车发送
- 会话列表:水平滑动展开删除、桌面快捷入口、模态确认及失败重试

- 灵感回复:按上下文生成建议,仅加入草稿,保留原输入并取消过期请求

- 输入交互:移除回车发送的屏宽限制,保护中文输入法,支持Shift换行与手机换行按钮
2026-10-27 12:29:48 +08:00
16 changed files with 1624 additions and 221 deletions
+43 -2
View File
@@ -34,7 +34,7 @@ PORT=3210
HOSTNAME=0.0.0.0
```
`ACCESS_MANAGE_API_BASE_URL` 指向 `access-manage` 服务端 API 根路径。数字人登录调用后端 `POST /api/auth/digital/login`,接受现有超级管理员或员工账号,登录成功后只把 JWT 写入 Next.js 服务端 HttpOnly Cookie,不写入 `localStorage`。
`ACCESS_MANAGE_API_BASE_URL` 指向 `access-manage` 服务端 API 根路径。数字人登录调用后端 `POST /api/auth/digital/login`,仅接受后台开通的独立 C 端账号,登录成功后只把 JWT 写入 Next.js 服务端 HttpOnly Cookie,不写入 `localStorage`。
环境标识按 `APP_ENV` 区分:
@@ -122,9 +122,11 @@ pnpm start:prod
## 数字人空间
- `/discover` 为默认入口,复用原登录账户和 HttpOnly Cookie。
- `/discover` 为默认入口,使用独立 C 端账号和 HttpOnly Cookie。
- `src/components/digital-home.tsx`、`digital.css`:深色双 UI、移动/桌面适配、探索、流式对话、停止、重生成、分支、固定记忆、世界书与用户身份。
- `src/lib/digital.ts`:前台协议、请求和 SSE 解码。
- `src/components/digital-message.tsx`:对白与故事叙述分段展示、视觉出字和纯文本用户消息。
- `src/lib/digital-message-format.ts`:受限格式解析;与管理端同名工具同步规则,不执行 HTML。
- `src/app/api/digital/[...path]/route.ts`:白名单 BFF,只转发前台接口,禁止访问后台实验管理,写入校验同源。
- 实验控制仅在 role-admin。前台没有切换实验或分组入口。
- `DEEPSEEK_API_KEY` 仅在业务后端配置,前端不读取、不保存。
@@ -132,3 +134,42 @@ pnpm start:prod
标签页图标采用 `public/stellar-icon-v2.svg`,同时提供多尺寸 `favicon.ico`、180/192/512 PNG,覆盖浏览器、Apple 主屏幕和 PWA。版本化资源路径用于刷新旧图标缓存。
通用实验消费者可经 `GET /api/digital/decisions/:key` 读取本人类型决策的 `data.value`,沿用 HttpOnly 会话与不缓存策略。类型、测试方案和用户分组全部在后台管理;新类型需要应用真实使用返回值并完成后台接入验收后才可启动。
`src/components/conversation-row.tsx` 提供会话列表横滑删除、桌面删除入口与模态确认。灵感回复读取本人会话上下文,选择后只加入草稿,原草稿保留;回车发送覆盖 H5/Web,支持中文输入法、Shift+Enter 与手机换行按钮。
内部滚动区域统一隐藏原生轨道,保留触摸/键盘滚动,设定表单关闭横向溢出。风格控制提示使用只读 `GET /api/digital/conversations/:id/style-policy`,打开设定不会写入实验分组、决策或曝光。
实验决策支持 A~Z 动态组;未入组时组别为 null。界面消费 `decision.value`(`new` / `true` 为新版),组名仅用于归因。决策过期使用服务端的 `fallbackValue`,不将无实验用户伪装成 A 组;旧服务未返回value时保留既有兼容路径。
## 登录跳转回归
- `src/lib/auth-redirect.ts`:登出与会话过期后使用站内相对 `Location`,避免跳到 Next.js 内部监听地址 `0.0.0.0:3210`;仅允许站内返回路径。
- `tests/auth-redirect.test.mjs`:覆盖正式域名/本地地址的登录页跳转、站内参数和外部地址拦截。
- 执行:`node --experimental-strip-types --test tests/auth-redirect.test.mjs`(Node.js 22)。
聊天滚动将“跟随最新”与当前底部距离分开:停在底部时,流式回复、结束后操作栏及软键盘导致的尺寸变化均继续贴底;主动上翻才暂停跟随,点击“回到最新”重新启用。等待首段正文仅显示思考点,收到文字后才显示打字光标,结束时移除生成提示。
聊天输入区“继续”让 NPC 基于上一段内容继续说话,不发送或清空输入框草稿,也不插入用户气泡;可连续点击生成多段,生成时沿用停止按钮。角色尚无可接续内容时按钮不可用。
NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成的角色内容,输入草稿保持不变。
### 独立 C 端登录
前台通过 `/api/auth/digital/login` 使用独立 C 端账号,由后台「用户管理」开通;不再使用管理员/员工身份。已有数字人业务账号由迁移复制密码哈希并保留会话,之后两套账号密码和状态独立。登录令牌保存在 HttpOnly Cookie,密码重置/账号停用会撤销旧登录状态。
对话设置的世界书与叙事风格使用平面列表;选中只保留轻底色和一个勾选标记,键盘焦点仍显示明确轮廓。
### NSFW 账号偏好
「我的」提供 NSFW 成人内容开关,登录账号未保存偏好时默认开启,已保存的关闭选择继续保留。保存后对已有及新会话的后续回复生效,包括发送、继续、重生成与回复灵感;游客仍须先登录。偏好由 `access-manage` 保存在本人资料中,前台不使用本地存储伪造保存结果。前后端需配套发布。
### 对白与叙述排版
角色消息使用 `*动作、神态、心理或环境叙述*` 与 `“实际对白”`,切换时空一行。对白加粗,叙述使用较柔和颜色,英文叙述增加斜体,中文保持正体。开场白、流式回复和历史记录共用同一个渲染组件,用户消息保持纯文本。
历史括号叙述兼容嵌套括号,同一段中括号外文字作为对白;有引号的旧开场白将引号外文字作为叙述。没有明确边界的普通文本保留原样。不完整历史标记默认原样显示,生成中及停止/失败的尾部允许未闭合标记,避免星号闪现。所有片段均为文本节点,不解释 HTML。
数据库与 SSE 继续使用原始 `content`,复制、导出、固定记忆、分支和重新生成仍以整条消息操作。后端公共格式规则由 `access-manage/src/modules/digital/digital.prompt.ts` 管理;管理端解析器与本仓保持同一实现和回归用例。
运行 `node --experimental-strip-types --test tests/*.test.mjs` 验证格式解析与登录跳转;格式用例覆盖中英文、旧括号、逐字累计流、不完整标记与 HTML 字面量。
+3 -3
View File
@@ -1,4 +1,4 @@
/** 星港登录页,沿用既有账号,无公开注册。 */
/** 星港登录页,使用独立用户账号,无公开注册。 */
import Link from "next/link";
import { LoginForm } from "@/components/login-form";
import "@/components/digital-login.css";
@@ -31,9 +31,9 @@ export default function LoginPage() {
<section className="stellar-login-panel">
<span className="stellar-login-star">✧</span>
<h2>欢迎回到星港</h2>
<p>使用你的现有账号,继续未完的故事。</p>
<p>使用你的星港账号,继续未完的故事。</p>
<LoginForm />
<small>私人数字人空间 · 不开放公开注册</small>
<small>账号由管理员开通 · 与后台账号独立</small>
</section>
</main>
);
+6 -4
View File
@@ -1,15 +1,17 @@
import { NextRequest, NextResponse } from "next/server";
/** 清理会话后返回当前站点,保持反向代理域名与本地访问地址。 */
import { NextRequest } from "next/server";
import { logoutRedirect } from "@/lib/auth-redirect";
import { clearSessionToken } from "@/lib/session";
/** 客户端主动退出时仅清理 Cookie,由页面处理导航。 */
export async function POST() {
await clearSessionToken();
return Response.json({ success: true, data: null });
}
/** 会话过期或链接退出后跳转站内页面,不使用服务端监听地址。 */
export async function GET(request: NextRequest) {
await clearSessionToken();
const next = request.nextUrl.searchParams.get("next") || "/login";
return NextResponse.redirect(new URL(next, request.url));
return logoutRedirect(request.nextUrl.searchParams.get("next"));
}
+9 -3
View File
@@ -33,13 +33,19 @@ async function proxy(
const { path } = await context.params;
const joined = path.join("/");
if (
!/^(bootstrap|profile|exposure|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|messages\/[a-zA-Z0-9_-]+))?)?)$/.test(
!/^(bootstrap|profile|exposure|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|suggestions|style-policy|messages\/[a-zA-Z0-9_-]+))?)?)$/.test(
joined,
)
)
return Response.json({ message: "接口不存在" }, { status: 404 });
if (joined.startsWith("decisions/") && request.method !== "GET")
return Response.json({ message: "仅支持读取决策" }, {status:405,headers:{Allow:"GET"}});
if (
(joined.startsWith("decisions/") || joined.endsWith("/style-policy")) &&
request.method !== "GET"
)
return Response.json(
{ message: "仅支持读取决策" },
{ status: 405, headers: { Allow: "GET" } },
);
if (request.method !== "GET") {
const origin = request.headers.get("origin");
try {
+13
View File
@@ -1123,3 +1123,16 @@ textarea:focus-visible {
width: calc(100% - 32px);
}
}
/* 移动表单保持可读字号,避免 Safari 聚焦后自动放大且不复原。 */
@media (pointer: coarse) {
body input:not([type="checkbox"]):not([type="radio"]),
body textarea,
body select {
font-size: max(16px, 1em);
}
}
html {
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
+209
View File
@@ -0,0 +1,209 @@
"use client";
/** 会话列表的水平滑动操作与删除确认;纵向滑动继续交给页面滚动。 */
import { useEffect, useId, useRef, useState, type PointerEvent } from "react";
import { LoaderCircle, Trash2 } from "lucide-react";
import type { Card, Summary } from "@/lib/digital";
/** 一次只展开一条会话;拖动不会触发进入会话,桌面和键盘保留显式删除入口。 */
export function ConversationRow({
summary,
card,
revealed,
disabled,
onReveal,
onOpen,
onDelete,
}: {
summary: Summary;
card?: Card;
revealed: boolean;
disabled: boolean;
onReveal: (id: string | null) => void;
onOpen: () => void;
onDelete: () => void;
}) {
const [drag, setDrag] = useState<number | null>(null);
const gesture = useRef<{
x: number;
y: number;
base: number;
offset: number;
axis: "pending" | "x" | "y";
} | null>(null),
suppressClick = useRef(false);
const distance = 88;
function start(e: PointerEvent<HTMLButtonElement>) {
if (disabled || e.button !== 0) return;
suppressClick.current = false;
gesture.current = {
x: e.clientX,
y: e.clientY,
base: revealed ? -distance : 0,
offset: revealed ? -distance : 0,
axis: "pending",
};
e.currentTarget.setPointerCapture(e.pointerId);
}
function move(e: PointerEvent<HTMLButtonElement>) {
const g = gesture.current;
if (!g) return;
const dx = e.clientX - g.x,
dy = e.clientY - g.y;
if (g.axis === "pending" && Math.max(Math.abs(dx), Math.abs(dy)) > 8) {
g.axis = Math.abs(dx) > Math.abs(dy) * 1.2 ? "x" : "y";
if (g.axis === "x") onReveal(summary.id);
}
if (g.axis !== "x") return;
g.offset = Math.max(-distance, Math.min(0, g.base + dx));
setDrag(g.offset);
}
function finish(e: PointerEvent<HTMLButtonElement>, cancelled = false) {
const g = gesture.current;
if (!g) return;
gesture.current = null;
if (g.axis === "x") {
suppressClick.current = true;
onReveal(
(cancelled ? g.base : g.offset) < -distance / 2 ? summary.id : null,
);
}
setDrag(null);
if (e.currentTarget.hasPointerCapture(e.pointerId))
e.currentTarget.releasePointerCapture(e.pointerId);
}
const exposed = revealed || (drag !== null && drag < 0);
return (
<article className={`dh-conversation-row ${exposed ? "is-revealed" : ""}`}>
<button
className="dh-row-delete-swipe"
aria-label={`删除对话:${summary.title}`}
tabIndex={exposed ? 0 : -1}
aria-hidden={!exposed}
disabled={disabled}
onClick={onDelete}
>
<Trash2 size={18} />
<span>删除</span>
</button>
<button
className={`dh-conversation-open ${drag !== null ? "is-dragging" : ""}`}
style={{
transform: `translateX(${drag ?? (revealed ? -distance : 0)}px)`,
}}
disabled={disabled}
onPointerDown={start}
onPointerMove={move}
onPointerUp={(e) => finish(e)}
onPointerCancel={(e) => finish(e, true)}
onLostPointerCapture={() => {
if (gesture.current) {
gesture.current = null;
setDrag(null);
}
}}
onClick={(e) => {
if (suppressClick.current && e.detail !== 0) {
suppressClick.current = false;
return;
}
if (revealed) {
onReveal(null);
return;
}
onOpen();
}}
>
{/* 封面地址沿用服务端目录,不在小型服务器做图片转换。 */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={card?.cover || "/icon.svg"} alt="" draggable={false} />
<div>
<h3>{summary.title}</h3>
<p>{card?.description || "继续这段私人对话"}</p>
</div>
<small>
{new Date(summary.updatedAt).toLocaleDateString("zh-CN", {
month: "short",
day: "numeric",
})}
</small>
</button>
<button
className="dh-row-delete-desktop"
aria-label={`删除对话:${summary.title}`}
disabled={disabled}
onClick={onDelete}
>
<Trash2 size={17} />
</button>
</article>
);
}
/** 原生模态对话框负责焦点约束,删除成功前保留原会话,失败可在原处重试。 */
export function ConversationDeleteDialog({
title,
busy,
error,
onCancel,
onConfirm,
}: {
title: string;
busy: boolean;
error: string;
onCancel: () => void;
onConfirm: () => void;
}) {
const ref = useRef<HTMLDialogElement>(null),
id = useId();
useEffect(() => {
const dialog = ref.current;
dialog?.showModal();
return () => dialog?.close();
}, []);
return (
<dialog
ref={ref}
className="dh-delete-dialog"
role="alertdialog"
aria-labelledby={id}
aria-describedby={`${id}-description`}
onCancel={(e) => {
e.preventDefault();
if (!busy) onCancel();
}}
>
<span className="dh-delete-symbol">
<Trash2 size={24} />
</span>
<h2 id={id}>删除这段对话?</h2>
<p id={`${id}-description`}>
「{title}」将从你的对话列表中移除,你将无法继续查看。后台仍保留聊天记录。
</p>
{error && (
<p className="dh-delete-error" role="alert">
{error}
</p>
)}
<div className="dh-delete-actions">
<button type="button" autoFocus disabled={busy} onClick={onCancel}>
取消
</button>
<button
type="button"
className="is-danger"
disabled={busy}
onClick={onConfirm}
>
{busy ? (
<>
<LoaderCircle size={16} className="dh-spin" />
正在删除
</>
) : (
"删除对话"
)}
</button>
</div>
</dialog>
);
}
+485 -145
View File
@@ -1,6 +1,6 @@
"use client";
/* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */
/** 星港数字人空间:探索、会话、世界书和身份资料的响应式入口。 */
/** 星港数字人空间:探索、会话、世界书、身份资料和账号内容偏好。 */
import Link from "next/link";
import {
useCallback,
@@ -48,63 +48,11 @@ import {
type Summary,
type Bootstrap,
} from "@/lib/digital";
import { ConversationRow, ConversationDeleteDialog } from "./conversation-row";
import { DigitalMessage } from "./digital-message";
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 (
<div className="dh-message-text">
<TypedText
text={
message.content ||
(message.status === "generating" ? "" : "这次没有生成内容。")
}
animate={animate}
/>
{message.status === "generating" && (
<span className="dh-caret" aria-hidden />
)}
</div>
);
}
/** 前台无分组按钮、调试开关或实验配置。 */
/** 前台管理个人会话偏好;后台方案仅展示覆盖提示,不开放实验操作。 */
export function DigitalHome({
initial,
initialSummaries,
@@ -125,6 +73,9 @@ export function DigitalHome({
[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>(null),
[profile, setProfile] = useState<Profile | null>(initial.profile);
@@ -139,6 +90,19 @@ export function DigitalHome({
bookIds: string[];
}>({ bookIds: [] });
const selectionTrigger = useRef<HTMLElement | null>(null);
const [swipedConversation, setSwipedConversation] = useState<string | null>(
null,
);
const [deleteTarget, setDeleteTarget] = useState<Summary | null>(null),
[deleting, setDeleting] = useState(false),
[deleteError, setDeleteError] = useState("");
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),
@@ -149,13 +113,48 @@ export function DigitalHome({
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>(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);
@@ -212,6 +211,7 @@ export function DigitalHome({
decision: {
...current.decision,
variant: current.decision.fallbackVariant,
value: current.decision.fallbackValue,
decisionId: null,
},
}
@@ -227,30 +227,75 @@ export function DigitalHome({
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",
});
});
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);
return () => observer.disconnect();
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`,
);
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();
window.visualViewport?.addEventListener("resize", resize);
viewport?.addEventListener("resize", resize);
viewport?.addEventListener("scroll", resize);
window.addEventListener("resize", resize);
return () => {
window.visualViewport?.removeEventListener("resize", resize);
document.documentElement.style.removeProperty("--dh-viewport");
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(() => {
@@ -304,7 +349,7 @@ export function DigitalHome({
previous?.focus();
};
}, [detail, showSettings]);
/** 抽屉聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */
/** 选择弹窗聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */
useEffect(() => {
if (!selectionSheet) return;
const previous = selectionTrigger.current;
@@ -362,6 +407,9 @@ export function DigitalHome({
};
}, [busy, conversationId]);
async function openConversation(id: string) {
closeIdeas();
imeComposing.current = false;
setSwipedConversation(null);
if (streamingId.current && streamingId.current !== id) {
setNotice("请先停止当前回复,再切换会话");
return;
@@ -379,6 +427,7 @@ export function DigitalHome({
setActiveMessage(null);
setShowMenu(false);
atBottom.current = true;
setShowJump(false);
try {
setDraft(sessionStorage.getItem(`dh-draft:${id}`) ?? "");
} catch {
@@ -420,15 +469,20 @@ export function DigitalHome({
: [...profile.favorites, card.id],
};
try {
await digital("profile", "PUT", next);
setProfile(next);
// 收藏不写内容开关,避免旧页面状态覆盖管理员刚保存的账号偏好。
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;
}
}
async function send(mode: "send" | "regenerate" = "send") {
async function send(mode: "send" | "regenerate" | "continue" = "send") {
if (
!conversation ||
busy ||
@@ -436,16 +490,21 @@ export function DigitalHome({
(mode === "send" && !draft.trim())
)
return;
closeIdeas();
const id = conversation.id,
content = draft.trim(),
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 (mode === "send") {
setDraft("");
if (textarea.current) textarea.current.style.height = "auto";
}
const local: Message[] = [
...(mode === "send"
? [
@@ -570,11 +629,12 @@ export function DigitalHome({
if (
event.key === "Enter" &&
!event.shiftKey &&
!imeComposing.current &&
!event.nativeEvent.isComposing &&
window.matchMedia("(min-width: 768px)").matches
event.nativeEvent.keyCode !== 229
) {
event.preventDefault();
void send();
if (!event.repeat) void send();
}
}
async function pin(message: Message) {
@@ -615,23 +675,135 @@ export function DigitalHome({
reportError(e);
}
}
async function removeConversation() {
if (
!conversation ||
busy ||
!window.confirm("删除此会话和全部消息?此操作无法撤销。")
)
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/${conversation.id}`, "DELETE");
setConversation(null);
currentId.current = null;
await refreshSummaries();
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) {
reportError(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;
@@ -658,7 +830,11 @@ export function DigitalHome({
await digital(`conversations/${conversation.id}`, "PATCH", { settings });
setConversation((c) => (c ? { ...c, settings } : c));
setShowSettings(false);
setNotice("对话设定已保存,下次回复生效");
setNotice(
stylePolicy === "managed"
? "设定已保存;当前叙事风格仍由统一方案控制"
: "对话设定已保存,下次回复生效",
);
} catch (e) {
reportError(e);
}
@@ -670,11 +846,15 @@ export function DigitalHome({
...profile,
userName: profileDraft.userName,
persona: profileDraft.persona,
nsfwEnabled: profileDraft.nsfwEnabled ?? true,
};
try {
await digital("profile", "PUT", next);
setProfile(next);
setNotice("身份资料已保存");
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);
}
@@ -705,12 +885,15 @@ export function DigitalHome({
URL.revokeObjectURL(url);
}
function switchTab(value: Tab) {
closeIdeas();
setSwipedConversation(null);
if (conversation && busy) {
setNotice("请先停止当前回复,再离开会话");
return;
}
setConversation(null);
currentId.current = null;
if (value === "me" && tab !== "me" && profile) setProfileDraft(profile);
setTab(value);
setError("");
}
@@ -736,7 +919,15 @@ export function DigitalHome({
<legend className={inSheet ? "dh-visually-hidden" : undefined}>
叙事风格
</legend>
<p className="dh-style-help">为这段故事选一种氛围</p>
<p className="dh-style-help" role="status">
{stylePolicy === "loading"
? "正在确认风格设置…"
: stylePolicy === "managed"
? "当前使用统一叙事风格。可以保存个人偏好,统一风格解除后采用。"
: stylePolicy === "unknown"
? "暂时无法确认当前风格,可以先保存个人偏好。"
: "为这段故事选一种氛围,也可以跟随角色默认风格。"}
</p>
<div className="dh-style-options">
{[
{
@@ -750,8 +941,7 @@ export function DigitalHome({
{
id: value,
name: "当前会话风格",
description:
"此风格暂不在可选列表中,可以保留或选择其他风格。",
description: "这个风格暂不可用,回复时会采用可用的默认风格。",
},
]
: []),
@@ -769,9 +959,6 @@ export function DigitalHome({
onChange={() => onChange(p.id || undefined)}
/>
<span className="dh-style-card">
<span className="dh-style-symbol" aria-hidden="true">
{p.id ? <WandSparkles /> : <Sparkles />}
</span>
<span className="dh-style-copy">
<strong>{p.name}</strong>
<small>{p.description || "以这套风格继续你们的故事。"}</small>
@@ -818,7 +1005,18 @@ export function DigitalHome({
))}
</fieldset>
);
const modern = boot?.decision.variant === "B";
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 (
<div
className={`dh-app ${modern ? "dh-modern" : "dh-classic"} ${conversation ? "dh-in-chat" : ""}`}
@@ -909,6 +1107,7 @@ export function DigitalHome({
aria-label="对话设定"
onClick={() => {
setSettings(conversation.settings);
setStylePolicy("loading");
setShowSettings(true);
}}
>
@@ -946,12 +1145,45 @@ export function DigitalHome({
<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) {
atBottom.current =
v.scrollHeight - v.scrollTop - v.clientHeight < 110;
setShowJump(!atBottom.current);
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);
}
}}
>
@@ -981,19 +1213,10 @@ export function DigitalHome({
{m.pinned && <Pin size={11} />}
</span>
<div className="dh-bubble">
<MessageText
<DigitalMessage
message={m}
animate={
m.id === activeMessage && m.status === "generating"
}
animate={m.id === activeMessage}
/>
{!m.content && m.status === "generating" && (
<span className="dh-thinking">
<i />
<i />
<i />
</span>
)}
</div>
{!busy && m.content && (
<div className="dh-message-actions">
@@ -1072,9 +1295,10 @@ export function DigitalHome({
className="dh-jump"
onClick={() => {
atBottom.current = true;
setShowJump(false);
viewport.current?.scrollTo({
top: viewport.current.scrollHeight,
behavior: "smooth",
behavior: "instant",
});
}}
>
@@ -1083,6 +1307,95 @@ export function DigitalHome({
</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}
@@ -1096,6 +1409,13 @@ export function DigitalHome({
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 ? (
@@ -1298,30 +1618,22 @@ export function DigitalHome({
开启新故事
</button>
</div>
{summaries.length > 0 && (
<p className="dh-swipe-hint">向左滑动对话可删除</p>
)}
<div className="dh-conversation-list">
{summaries.map((s) => {
const c = cards.find((c) => c.id === s.characterId);
return (
<button
key={s.id}
onClick={() => openConversation(s.id)}
disabled={opening}
>
<img src={c?.cover || "/icon.svg"} alt="" />
<div>
<h3>{s.title}</h3>
<p>{c?.description || "继续这段私人对话"}</p>
</div>
<small>
{new Date(s.updatedAt).toLocaleDateString("zh-CN", {
month: "short",
day: "numeric",
})}
</small>
<MessageCircle size={18} />
</button>
);
})}
{summaries.map((s) => (
<ConversationRow
key={s.id}
summary={s}
card={cards.find((c) => c.id === s.characterId)}
revealed={swipedConversation === s.id}
disabled={opening || deleting}
onReveal={setSwipedConversation}
onOpen={() => openConversation(s.id)}
onDelete={() => requestDelete(s)}
/>
))}
</div>
{!summaries.length && (
<div className="dh-empty">
@@ -1426,9 +1738,26 @@ export function DigitalHome({
<p className="dh-form-note">
此资料可在新会话的「对话设定」中使用。每个会话的设定相互独立。
</p>
<label className="dh-content-preference">
<span>
<strong>NSFW 成人内容</strong>
<small>登录账号默认开启,可随时关闭;保存后用于后续回复。</small>
</span>
<input
type="checkbox"
role="switch"
checked={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>
@@ -1658,7 +1987,7 @@ export function DigitalHome({
)}
</div>
<p className="dh-form-note">
保存后从下一次回复生效。可以固定单条消息,将它加入对话记忆。
保存后用于接下来的回复。固定单条消息,可将它加入对话记忆。
</p>
</div>
<button className="dh-primary" type="submit">
@@ -1748,6 +2077,17 @@ export function DigitalHome({
)}
</div>
)}
{deleteTarget && (
<ConversationDeleteDialog
title={deleteTarget.title}
busy={deleting}
error={deleteError}
onCancel={() => {
if (!deleting) setDeleteTarget(null);
}}
onConfirm={confirmDelete}
/>
)}
</div>
);
}
+93
View File
@@ -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 (
<span className="dh-thinking" role="status" aria-label="正在思考">
<i aria-hidden />
<i aria-hidden />
<i aria-hidden />
</span>
);
const cursor = generating ? <span className="dh-caret" aria-hidden /> : null;
return (
<div
className={`dh-message-text${message.role === "assistant" ? " dh-message-prose" : ""}`}
>
{message.role === "assistant"
? blocks.map((block, index) => (
<p
key={index}
className={`dh-prose-${block.kind}${/[A-Za-z]/.test(block.text) && !/[\u3400-\u9fff]/.test(block.text) ? " dh-prose-latin" : ""}`}
>
{block.kind === "dialogue" ? (
<strong>{block.text}</strong>
) : (
block.text
)}
{index === blocks.length - 1 ? cursor : null}
</p>
))
: text}
{!blocks.length ? cursor : null}
{!message.content && !generating ? "这次没有生成内容。" : null}
</div>
);
});
+454 -59
View File
@@ -588,7 +588,7 @@
flex-direction: column;
gap: 12px;
}
.dh-conversation-list > button {
.dh-conversation-list .dh-conversation-open {
border: 1px solid var(--dh-line);
background: var(--dh-panel);
border-radius: 14px;
@@ -598,7 +598,7 @@
gap: 16px;
text-align: left;
}
.dh-conversation-list > button:hover {
.dh-conversation-list .dh-conversation-open:hover {
border-color: #ffffff25;
}
.dh-conversation-list img {
@@ -620,7 +620,7 @@
text-overflow: ellipsis;
margin-top: 5px;
}
.dh-conversation-list > button > div {
.dh-conversation-list .dh-conversation-open > div {
min-width: 0;
flex: 1;
}
@@ -633,6 +633,277 @@
color: var(--dh-accent);
flex: none;
}
/* 横滑只移动会话卡片,删除在明确确认后才执行。 */
.dh-conversation-row {
position: relative;
overflow: visible;
border-radius: 14px;
background: transparent;
}
.dh-conversation-list .dh-conversation-open {
position: relative;
z-index: 1;
width: 100%;
touch-action: pan-y;
transition: transform 180ms ease;
user-select: none;
}
.dh-conversation-list .dh-conversation-open.is-dragging {
transition: none;
}
.dh-app .dh-row-delete-swipe {
position: absolute;
inset: 0 0 0 auto;
display: flex;
flex-direction: column;
gap: 5px;
align-items: center;
justify-content: center;
width: 76px;
color: #fff;
background: #a3374c;
border-radius: 14px;
box-shadow: 0 4px 16px #0003;
visibility: hidden;
}
.dh-conversation-row.is-revealed .dh-row-delete-swipe {
visibility: visible;
}
.dh-conversation-list .dh-row-delete-swipe svg {
color: #fff;
}
.dh-row-delete-swipe span {
font-size: 12px;
}
.dh-row-delete-desktop {
position: absolute;
z-index: 2;
top: 50%;
right: 12px;
display: grid;
place-items: center;
width: 34px;
height: 34px;
transform: translateY(-50%);
border-radius: 9px;
}
.dh-conversation-list .dh-row-delete-desktop svg {
color: var(--dh-muted);
}
.dh-app .dh-row-delete-desktop:hover {
background: #f8717120;
}
.dh-conversation-row.is-revealed .dh-row-delete-desktop {
display: none;
}
.dh-swipe-hint {
display: none;
}
.dh-delete-dialog {
width: min(420px, calc(100% - 32px));
max-height: calc(100dvh - 48px);
margin: auto;
overflow-y: auto;
overscroll-behavior: contain;
box-shadow: 0 24px 80px #0008;
padding: 26px;
color: var(--dh-text);
background: var(--dh-panel);
border: 1px solid #ffffff1c;
border-radius: 20px;
}
.dh-delete-dialog::backdrop {
background: #000b;
backdrop-filter: blur(6px);
}
.dh-delete-symbol {
display: grid;
place-items: center;
width: 46px;
height: 46px;
margin-bottom: 18px;
color: #fda4af;
background: #fb718519;
border-radius: 14px;
}
.dh-delete-dialog h2 {
font-size: 21px;
font-weight: 600;
}
.dh-delete-dialog p {
margin-top: 12px;
color: var(--dh-muted);
font-size: 13px;
line-height: 1.8;
overflow-wrap: anywhere;
}
.dh-delete-actions {
display: flex;
gap: 12px;
margin-top: 24px;
}
.dh-app .dh-delete-actions button {
display: flex;
flex: 1;
gap: 7px;
align-items: center;
justify-content: center;
min-height: 44px;
font-size: 13px;
background: var(--dh-soft);
border: 1px solid var(--dh-line);
border-radius: 11px;
}
.dh-app .dh-delete-actions .is-danger {
color: #fff;
background: #a3374c;
border-color: #a3374c;
}
.dh-delete-dialog .dh-delete-error {
color: #fda4af;
}
.dh-compose-tools {
display: flex;
justify-content: space-between;
align-items: center;
margin: 0 4px 8px;
}
.dh-compose-actions {
display: flex;
align-items: center;
gap: 14px;
}
.dh-app .dh-compose-tools button {
display: flex;
align-items: center;
gap: 6px;
min-height: 32px;
padding: 0 4px;
color: var(--dh-accent);
font-size: 11px;
}
.dh-app .dh-compose-tools .dh-mobile-linebreak {
display: none;
}
.dh-reply-ideas {
margin: 0 0 12px;
padding: 13px;
background: var(--dh-panel);
border: 1px solid var(--dh-line);
border-radius: 15px;
}
.dh-reply-ideas header {
display: flex;
align-items: center;
justify-content: space-between;
}
.dh-reply-ideas strong {
display: flex;
gap: 7px;
align-items: center;
color: var(--dh-accent);
font-size: 12px;
font-weight: 500;
}
.dh-reply-ideas header .dh-icon {
width: 28px;
height: 28px;
}
.dh-ideas-note {
margin: 2px 0 10px !important;
color: var(--dh-muted);
font-size: 10px;
}
.dh-ideas-list {
display: flex;
flex-direction: column;
gap: 7px;
max-height: 30dvh;
overflow-y: auto;
overscroll-behavior: contain;
}
.dh-app .dh-ideas-list button {
display: flex;
gap: 10px;
align-items: flex-start;
padding: 10px;
text-align: left;
font-size: 12px;
line-height: 1.7;
background: var(--dh-soft);
border: 1px solid transparent;
border-radius: 9px;
}
.dh-app .dh-ideas-list button:hover {
border-color: var(--dh-accent);
}
.dh-ideas-list small {
flex: none;
color: var(--dh-accent);
font-size: 10px;
}
.dh-ideas-loading {
display: flex;
gap: 8px;
align-items: center;
min-height: 58px;
color: var(--dh-muted);
font-size: 12px;
}
.dh-ideas-error {
padding: 12px 0;
color: #fda4af;
font-size: 12px;
}
.dh-app .dh-ideas-refresh {
display: flex;
gap: 6px;
align-items: center;
min-height: 32px;
margin-top: 7px;
color: var(--dh-accent);
font-size: 11px;
}
.dh-spin {
animation: dh-spin 1s linear infinite;
}
@keyframes dh-spin {
to {
transform: rotate(360deg);
}
}
@media (width>600px) {
.dh-conversation-list .dh-conversation-open {
padding-right: 56px !important;
}
}
@media (width<=600px) {
.dh-row-delete-desktop {
display: none;
}
.dh-swipe-hint {
display: block;
margin: -10px 0 14px !important;
color: var(--dh-muted);
font-size: 10px;
}
.dh-delete-dialog {
width: min(380px, calc(100% - 40px));
margin: auto;
padding: 24px;
border-radius: 22px;
}
.dh-app .dh-compose-tools .dh-mobile-linebreak {
display: flex;
}
.dh-reply-ideas {
padding: 10px;
}
.dh-ideas-list {
max-height: 28dvh;
}
}
.dh-page-lead {
max-width: 650px;
color: var(--dh-muted);
@@ -707,6 +978,11 @@
color: #d4cbd5;
font-size: 12px;
}
.dh-settings > label small {
color: var(--dh-muted);
font-size: 11px;
line-height: 1.7;
}
.dh-profile-form textarea,
.dh-settings textarea {
resize: vertical;
@@ -718,6 +994,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);
@@ -907,8 +1230,8 @@
}
.dh-style-options {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
grid-template-columns: minmax(0, 1fr);
gap: 0;
}
.dh-style-option {
position: relative;
@@ -916,10 +1239,6 @@
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
.dh-style-option:first-child,
.dh-style-option:last-child:nth-child(even) {
grid-column: 1 / -1;
}
.dh-style-option > input {
position: absolute;
width: 1px;
@@ -933,41 +1252,26 @@
display: flex;
align-items: flex-start;
gap: 10px;
height: 100%;
min-height: 88px;
padding: 15px 13px;
border: 1px solid #ffffff17;
border-radius: 13px;
background: color-mix(in srgb, var(--dh-soft) 60%, var(--dh-panel));
min-height: 72px;
padding: 14px 10px;
border: 0;
border-bottom: 1px solid var(--dh-line);
border-radius: 0;
background: transparent;
transition:
border-color 160ms,
background 160ms;
}
.dh-style-option:hover .dh-style-card {
border-color: color-mix(in srgb, var(--dh-accent) 55%, transparent);
background: #ffffff04;
}
.dh-style-option > input:checked + .dh-style-card {
border-color: var(--dh-accent);
background: color-mix(in srgb, var(--dh-accent) 9%, var(--dh-panel));
background: color-mix(in srgb, var(--dh-accent) 7%, transparent);
}
.dh-style-option > input:focus-visible + .dh-style-card {
outline: 2px solid var(--dh-accent);
outline-offset: 3px;
}
.dh-style-symbol {
display: grid;
flex: none;
place-items: center;
width: 29px;
height: 29px;
color: var(--dh-accent);
background: color-mix(in srgb, var(--dh-accent) 10%, transparent);
border-radius: 9px;
}
.dh-style-symbol svg {
width: 15px;
height: 15px;
}
.dh-style-copy {
flex: 1;
min-width: 0;
@@ -994,8 +1298,7 @@
height: 17px;
margin-top: 2px;
color: transparent;
border: 1px solid #ffffff30;
border-radius: 50%;
border: 0;
}
.dh-style-check svg {
width: 11px;
@@ -1003,9 +1306,8 @@
stroke-width: 3;
}
.dh-style-option > input:checked + .dh-style-card .dh-style-check {
color: var(--dh-accent-ink);
background: var(--dh-accent);
border-color: var(--dh-accent);
color: var(--dh-accent);
background: transparent;
}
@media (width <= 600px) {
.dh-style-options {
@@ -1015,7 +1317,7 @@
min-height: 76px;
}
}
/* H5 选择项以底部抽屉编辑草稿,确认后才回填到对话设定。 */
/* H5 选择项在居中弹窗编辑草稿,确认后才回填到对话设定。 */
.dh-mobile-choices {
display: none;
}
@@ -1030,8 +1332,9 @@
inset: 0;
z-index: 2;
display: flex;
align-items: flex-end;
align-items: center;
justify-content: center;
padding: 20px;
overscroll-behavior: contain;
}
.dh-selection-backdrop {
@@ -1045,15 +1348,14 @@
position: relative;
display: flex;
flex-direction: column;
width: 100%;
width: min(520px, 100%);
max-height: 86dvh;
min-height: 0;
overflow: hidden;
background: var(--dh-panel);
border: 1px solid #ffffff1c;
border-bottom: 0;
border-radius: 24px 24px 0 0;
box-shadow: 0 -16px 60px #0005;
border-radius: 22px;
box-shadow: 0 24px 80px #0008;
animation: dh-sheet-enter 180ms ease-out;
}
.dh-sheet-handle {
@@ -1095,18 +1397,18 @@
border: 0;
}
.dh-selection-sheet .dh-checkbox {
min-height: 74px;
padding: 14px;
margin: 0 0 10px;
border: 1px solid #ffffff17;
border-radius: 13px;
min-height: 70px;
padding: 14px 10px;
margin: 0;
border: 0;
border-bottom: 1px solid var(--dh-line);
border-radius: 0;
cursor: pointer;
}
.dh-selection-sheet .dh-checkbox.is-selected {
background: color-mix(in srgb, var(--dh-accent) 9%, var(--dh-panel));
border-color: var(--dh-accent);
background: color-mix(in srgb, var(--dh-accent) 7%, transparent);
}
.dh-selection-sheet .dh-checkbox:focus-within {
.dh-selection-sheet .dh-checkbox:has(input:focus-visible) {
outline: 2px solid var(--dh-accent);
outline-offset: 2px;
}
@@ -1144,10 +1446,12 @@
}
@keyframes dh-sheet-enter {
from {
transform: translateY(100%);
opacity: 0;
transform: translateY(8px) scale(0.98);
}
to {
transform: translateY(0);
opacity: 1;
transform: translateY(0) scale(1);
}
}
@media (width > 600px) {
@@ -1339,8 +1643,7 @@
overflow-y: auto;
overflow-x: hidden;
overscroll-behavior: contain;
scrollbar-width: thin;
scrollbar-color: #ffffff20 transparent;
scrollbar-width: none;
}
.dh-messages-inner {
max-width: 840px;
@@ -1404,6 +1707,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;
}
@@ -1514,7 +1839,7 @@
width: 100%;
resize: none;
min-height: 36px;
max-height: 160px;
max-height: min(160px, calc(var(--dh-viewport, 100dvh) * 0.28));
border: 0;
background: none;
padding: 7px 0;
@@ -1824,7 +2149,7 @@
.dh-library-card h3 {
margin-top: 16px;
}
.dh-conversation-list > button {
.dh-conversation-list .dh-conversation-open {
gap: 12px;
padding: 13px;
}
@@ -1838,7 +2163,7 @@
.dh-conversation-list p {
font-size: 11px;
}
.dh-conversation-list > button > svg {
.dh-conversation-list .dh-conversation-open > svg {
display: none;
}
.dh-profile-banner {
@@ -1909,7 +2234,7 @@
}
.dh-chat {
position: fixed;
inset: 0;
inset: var(--dh-viewport-top, 0px) 0 auto;
width: 100%;
height: var(--dh-viewport, 100dvh);
z-index: 20;
@@ -2027,3 +2352,73 @@
body:has(.dh-app) .environment-badge {
display: none;
}
/* 内部区域保留手势和键盘滚动,不显示系统轨道,也不允许设定表单横向漂移。 */
.dh-app,
.dh-app * {
scrollbar-width: none !important;
}
.dh-app::-webkit-scrollbar,
.dh-app *::-webkit-scrollbar {
display: none !important;
width: 0 !important;
height: 0 !important;
}
.dh-settings-body,
.dh-selection-body,
.dh-detail-body,
.dh-ideas-list {
min-width: 0;
max-width: 100%;
overflow-x: hidden;
}
.dh-settings-body {
width: 100%;
}
.dh-settings-body > label,
.dh-settings fieldset,
.dh-selection-sheet fieldset {
min-width: 0;
max-width: 100%;
}
.dh-app textarea {
width: 100%;
max-width: 100%;
overflow-x: hidden;
overflow-wrap: anywhere;
}
/* 世界书与风格统一使用平面列表,选中只保留轻底色和一个勾选标记。 */
.dh-settings .dh-book-picker {
border: 0;
padding: 0;
}
.dh-checkbox input {
flex: none;
width: 16px;
height: 16px;
}
/* 聊天独立占据可视区域,防止焦点滚动带动整个文档。 */
html.dh-chat-active,
html.dh-chat-active body {
overflow: hidden;
overscroll-behavior: none;
}
.dh-composer-wrap {
flex-shrink: 0;
}
@media (pointer: coarse) {
/* iOS 会自动放大不足 16px 的表单;覆盖各页面局部小字号,同时保留手动缩放。 */
.dh-app input:not([type="checkbox"]):not([type="radio"]),
.dh-app textarea,
.dh-app select {
font-size: 16px;
}
.dh-conversation-list .dh-conversation-open {
overflow: hidden;
}
.dh-conversation-list .dh-row-delete-desktop {
display: none;
}
}
+2 -2
View File
@@ -1,11 +1,11 @@
"use client";
/** 复用原有账号登录,成功后进入数字人空间。 */
/** 独立星港用户账号登录,成功后进入数字人空间。 */
import { useRouter } from "next/navigation";
import { Eye, EyeOff, LockKeyhole, Smartphone } from "lucide-react";
import { FormEvent, useState } from "react";
/** 现有账号的登录表单,不保存明文密码。 */
/** 独立用户的登录表单,不保存明文密码。 */
export function LoginForm() {
const router = useRouter();
const [error, setError] = useState("");
+19
View File
@@ -0,0 +1,19 @@
/** 登出后的站内跳转,避免反向代理后的内部监听地址泄漏到浏览器。 */
/** 使用相对 Location 留在当前站点,并拒绝外部地址和 URL 控制字符。 */
export function logoutRedirect(next: string | null) {
let destination = "/login";
if (
next?.startsWith("/") &&
!/^\/[/\\]/.test(next) &&
!/[\\\u0000-\u0020\u007f]/.test(next)
) {
const local = new URL(next, "https://same-origin.invalid");
// 消除点路径后仍须禁止双斜杠,避免 /.//host 被规范化为外站地址。
if (local.origin === "https://same-origin.invalid" && !local.pathname.startsWith("//")) {
destination = local.pathname + local.search + local.hash;
}
}
// Route Handler 可直接返回相对 Location;不使用 request.url(生产中可能是 0.0.0.0)。
return new Response(null, { status: 307, headers: { Location: destination } });
}
+151
View File
@@ -0,0 +1,151 @@
/** 数字人消息的受限文本格式:对白、故事叙述与旧版括号;始终返回文本,不解释 HTML。 */
/** 有序展示片段;原始 content 继续用于存储、复制、记忆和上下文。 */
export type DigitalMessageBlock = {
kind: "dialogue" | "narration" | "plain";
text: string;
};
const quotePairs: Record<string, string> = {
'"': '"',
"“": "”",
"「": "」",
"『": "』",
"«": "»",
""": """,
};
/** 跳过转义字符;引号不跨行,括号按同类型嵌套匹配,避免误吞后续内容。 */
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;
}
+6 -2
View File
@@ -20,6 +20,8 @@ export type Profile = {
favorites: string[];
persona: string;
userName: string;
/** 登录账号的成人内容偏好;旧服务未返回时沿用默认开启。 */
nsfwEnabled?: boolean;
};
/** 会话消息拥有持久化 id,避免流式刷新时重复插入。 */
export type Message = {
@@ -123,10 +125,12 @@ export type Bootstrap = {
catalog: Card[];
profile: Profile;
decision: {
variant: "A" | "B";
variant: string | null;
value?: unknown;
fallbackValue?: unknown;
decisionId: string | null;
expiresAt: number;
fallbackVariant: "A" | "B";
fallbackVariant: string | null;
};
serverNow: number;
};
+2 -1
View File
@@ -1,4 +1,5 @@
export type AccountType = "SUPER_ADMIN" | "EMPLOYEE";
/** 前台身份与业务协议,数字人账号使用独立 DIGITAL_USER 类型。 */
export type AccountType = "SUPER_ADMIN" | "EMPLOYEE" | "DIGITAL_USER";
export type Role = {
id: number;
+22
View File
@@ -0,0 +1,22 @@
/** 回归登录过期后的跳转:仅返回站内路径,不把服务监听地址发送给浏览器。 */
import test from 'node:test';
import assert from 'node:assert/strict';
import { logoutRedirect } from '../src/lib/auth-redirect.ts';
test('登录过期后跳回当前站点的登录页,不依赖服务内部地址', () => {
const response = logoutRedirect(null);
assert.equal(response.status, 307);
assert.equal(response.headers.get('location'), '/login');
assert.equal(new URL(response.headers.get('location'), 'https://mrzhan.top/api/auth/logout').href, 'https://mrzhan.top/login');
assert.equal(new URL(response.headers.get('location'), 'http://localhost:3210/api/auth/logout').href, 'http://localhost:3210/login');
});
test('保留站内路径和查询参数', () => {
assert.equal(logoutRedirect('/login?reason=expired').headers.get('location'), '/login?reason=expired');
});
test('拒绝外部链接、协议相对地址及反斜杠变体', () => {
for (const next of ['https://example.com', '//example.com', '/\\example.com', 'javascript:alert(1)', '\n//example.com', '/\n/example.com', '/.//example.com', '/%2e//example.com']) {
assert.equal(logoutRedirect(next).headers.get('location'), '/login', next);
}
});
+107
View File
@@ -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 = "<script>globalThis.injected = true</script>";
assert.deepEqual(parse(text), [{ kind: "plain", text }]);
});