Compare commits

...

12 Commits

Author SHA1 Message Date
zhanxi 74d7caaca5 merge(navigation): 类型检查前重建 Next 路由声明 2026-10-28 09:11:25 +00:00
湛兮 76abb3ecfb fix(build): 类型检查前重建 Next 路由声明
- 清理过期的生产路由类型并执行 next typegen,避免 CI 引用迁移前页面
- 同步 README,使用过期类型夹具复现失败并验证检查可恢复
2026-10-28 17:10:42 +08:00
zhanxi a1fdc882e2 merge(navigation): 为数字人前台拆分独立页面路由 2026-10-28 09:08:34 +00:00
湛兮 4132b80ee0 feat(navigation): 为数字人前台拆分独立页面路由
- 新增对话列表、聊天、角色详情、书架详情及个人资料独立路由
- 导航使用真实链接,补齐历史返回、登录深链与会话草稿恢复
- 搜索筛选由 URL 驱动,修复浏览器返回时丢失筛选的问题
- 补齐路由校验回归、页面加载与异常入口,并同步 README
2026-10-28 17:07:34 +08: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 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 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
31 changed files with 1428 additions and 349 deletions
+47 -2
View File
@@ -34,7 +34,7 @@ PORT=3210
HOSTNAME=0.0.0.0 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` 区分: 环境标识按 `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/components/digital-home.tsx`、`digital.css`:深色双 UI、移动/桌面适配、探索、流式对话、停止、重生成、分支、固定记忆、世界书与用户身份。
- `src/lib/digital.ts`:前台协议、请求和 SSE 解码。 - `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,只转发前台接口,禁止访问后台实验管理,写入校验同源。 - `src/app/api/digital/[...path]/route.ts`:白名单 BFF,只转发前台接口,禁止访问后台实验管理,写入校验同源。
- 实验控制仅在 role-admin。前台没有切换实验或分组入口。 - 实验控制仅在 role-admin。前台没有切换实验或分组入口。
- `DEEPSEEK_API_KEY` 仅在业务后端配置,前端不读取、不保存。 - `DEEPSEEK_API_KEY` 仅在业务后端配置,前端不读取、不保存。
@@ -150,3 +152,46 @@ pnpm start:prod
聊天输入区“继续”让 NPC 基于上一段内容继续说话,不发送或清空输入框草稿,也不插入用户气泡;可连续点击生成多段,生成时沿用停止按钮。角色尚无可接续内容时按钮不可用。 聊天输入区“继续”让 NPC 基于上一段内容继续说话,不发送或清空输入框草稿,也不插入用户气泡;可连续点击生成多段,生成时沿用停止按钮。角色尚无可接续内容时按钮不可用。
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 字面量。
## 数字人独立页面与返回行为
| 地址 | 页面 |
| --- | --- |
| `/discover` | 发现角色;`q`、`tag`、`favorites` 保存当前筛选 |
| `/characters/:id` | 角色详情与开场选择 |
| `/chats` | 我的对话列表 |
| `/chats/:id` | 指定会话;支持直接打开、刷新与草稿恢复 |
| `/library` | 世界书与对话风格书架 |
| `/library/:id` | 世界书或风格详情 |
| `/profile` | 数字人个人身份与内容偏好 |
页面入口位于 `src/app/(digital)/`,共享布局追踪站内历史。`src/components/digital-page.tsx` 并行加载私有首屏,`src/lib/digital-routes.ts` 集中维护资源地址和登录回跳边界。原工作台 `/me` 保持兼容。
导航和详情使用真实链接,浏览器后退/前进还原实际上一页;页面内返回优先使用已有站内历史,从新标签页或外站直接打开时回到对应列表。搜索筛选替换当前历史条目,不为每次输入增加返回步骤。删除当前聊天后替换为列表地址,旧链接显示资源不存在。
未登录时保留具体资源地址,登录后回到原页;会话过期先清理 Cookie,避免登录页和失效会话之间循环。草稿按会话 ID 保存在当前标签页的 sessionStorage;退出聊天会取消该页流连接,已有消息仍由服务端持久化。对话设定、确认删除和选择项仍作为当前页面的临时弹窗。
路由与深链回归:`node --experimental-strip-types --test tests/*.test.mjs`;类型检查和构建按上面的项目命令执行。
`pnpm typecheck` 会先清理生产路由类型目录 `.next/types` 并执行 `next typegen`,再运行 TypeScript。这样 CI 在迁移页面目录或新增路由后不会复用上一版的路由声明;不清理整个构建产物目录。
+1 -1
View File
@@ -12,7 +12,7 @@
"start:develop": "APP_ENV=develop APP_ENV_LABEL=测试环境 ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3501/api ROLE_USER_SESSION_COOKIE=role_user_session_develop next start -p 3211", "start:develop": "APP_ENV=develop APP_ENV_LABEL=测试环境 ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3501/api ROLE_USER_SESSION_COOKIE=role_user_session_develop next start -p 3211",
"start:prod": "APP_ENV=production APP_ENV_LABEL=生产环境 ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3500/api ROLE_USER_SESSION_COOKIE=role_user_session next start -p 3210", "start:prod": "APP_ENV=production APP_ENV_LABEL=生产环境 ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3500/api ROLE_USER_SESSION_COOKIE=role_user_session next start -p 3210",
"lint": "eslint", "lint": "eslint",
"typecheck": "tsc --noEmit --incremental false" "typecheck": "node -e \"require('node:fs').rmSync('.next/types', { recursive: true, force: true })\" && next typegen && tsc --noEmit --incremental false"
}, },
"dependencies": { "dependencies": {
"lucide-react": "^0.511.0", "lucide-react": "^0.511.0",
+14 -5
View File
@@ -1,9 +1,18 @@
/** 星港登录页,沿用既有账号,无公开注册。 */ /** 星港登录页,使用独立用户账号,无公开注册。 */
import Link from "next/link"; import Link from "next/link";
import { safeDigitalReturnTo } from "@/lib/digital-routes";
import { LoginForm } from "@/components/login-form"; import { LoginForm } from "@/components/login-form";
import "@/components/digital-login.css"; import "@/components/digital-login.css";
/** 登录前展示独立品牌与简洁表单。 */ /** 登录前展示独立品牌与简洁表单。 */
export default function LoginPage() { export default async function LoginPage({
searchParams,
}: {
searchParams: Promise<{ next?: string | string[] }>;
}) {
const { next } = await searchParams;
const returnTo = safeDigitalReturnTo(
typeof next === "string" ? next : undefined,
);
return ( return (
<main className="stellar-login"> <main className="stellar-login">
<section className="stellar-login-story"> <section className="stellar-login-story">
@@ -31,9 +40,9 @@ export default function LoginPage() {
<section className="stellar-login-panel"> <section className="stellar-login-panel">
<span className="stellar-login-star">✧</span> <span className="stellar-login-star">✧</span>
<h2>欢迎回到星港</h2> <h2>欢迎回到星港</h2>
<p>使用你的现有账号,继续未完的故事。</p> <p>使用你的星港账号,继续未完的故事。</p>
<LoginForm /> <LoginForm returnTo={returnTo} />
<small>私人数字人空间 · 不开放公开注册</small> <small>账号由管理员开通 · 与后台账号独立</small>
</section> </section>
</main> </main>
); );
@@ -0,0 +1,21 @@
/** 角色详情深链入口,刷新后仍加载同一资源。 */
import { DigitalPage } from "@/components/digital-page";
/** 独立详情页面名称。 */
export const metadata = { title: "角色详情 · 星港" };
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
export default async function Page({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return (
<DigitalPage
tab="discover"
path={`/characters/${encodeURIComponent(id)}`}
contentId={id}
/>
);
}
+21
View File
@@ -0,0 +1,21 @@
/** 聊天深链入口,刷新后仍加载同一资源。 */
import { DigitalPage } from "@/components/digital-page";
/** 独立详情页面名称。 */
export const metadata = { title: "聊天 · 星港" };
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
export default async function Page({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return (
<DigitalPage
tab="chats"
path={`/chats/${encodeURIComponent(id)}`}
conversationId={id}
/>
);
}
+10
View File
@@ -0,0 +1,10 @@
/** 我的对话独立页面,浏览器历史与页面地址保持一致。 */
import { DigitalPage } from "@/components/digital-page";
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
export const metadata = { title: "我的对话 · 星港" };
/** 读取本页面的私有首屏数据。 */
export default function Page() {
return <DigitalPage tab="chats" path="/chats" />;
}
+31
View File
@@ -0,0 +1,31 @@
/** 发现角色独立页面,浏览器历史与页面地址保持一致。 */
import { DigitalPage } from "@/components/digital-page";
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
export const metadata = { title: "发现角色 · 星港" };
/** 读取本页面的私有首屏数据。 */
export default async function Page({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const search = await searchParams;
const first = (value: string | string[] | undefined) =>
typeof value === "string" ? value : "";
const filters = {
query: first(search.q).slice(0, 200),
tag: first(search.tag).slice(0, 80) || "全部",
favorites: first(search.favorites) === "1",
};
const params = new URLSearchParams();
if (filters.query) params.set("q", filters.query);
if (filters.tag !== "全部") params.set("tag", filters.tag);
if (filters.favorites) params.set("favorites", "1");
return (
<DigitalPage
tab="discover"
path={`/discover${params.size ? `?${params}` : ""}`}
/>
);
}
+16
View File
@@ -0,0 +1,16 @@
"use client";
/** 私有页面请求失败时保留重试和返回入口,不把异常内容或服务地址展示给用户。 */
import Link from "next/link";
/** 数据异常可就地重试,无需退出账号或返回站外页面。 */
export default function DigitalError({ reset }: { reset: () => void }) {
return (
<main className="dh-app dh-route-message">
<h1>页面暂时没有打开</h1>
<p>请检查网络后重试。</p>
<button onClick={reset}>重新加载</button>
<Link href="/chats">返回我的对话</Link>
</main>
);
}
+20
View File
@@ -0,0 +1,20 @@
/** 数字人独立页面共享样式和站内历史追踪;具体资源由各页面服务端读取。 */
import { Suspense } from "react";
import { DigitalRouteHistory } from "@/components/digital-route-history";
import "@/components/digital.css";
/** 页面切换保留历史追踪器,不把页面内容作为标签状态缓存。 */
export default function DigitalLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<>
<Suspense fallback={null}>
<DigitalRouteHistory />
</Suspense>
{children}
</>
);
}
+21
View File
@@ -0,0 +1,21 @@
/** 内容详情深链入口,刷新后仍加载同一资源。 */
import { DigitalPage } from "@/components/digital-page";
/** 独立详情页面名称。 */
export const metadata = { title: "内容详情 · 星港" };
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
export default async function Page({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return (
<DigitalPage
tab="library"
path={`/library/${encodeURIComponent(id)}`}
contentId={id}
/>
);
}
+10
View File
@@ -0,0 +1,10 @@
/** 灵感书架独立页面,浏览器历史与页面地址保持一致。 */
import { DigitalPage } from "@/components/digital-page";
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
export const metadata = { title: "灵感书架 · 星港" };
/** 读取本页面的私有首屏数据。 */
export default function Page() {
return <DigitalPage tab="library" path="/library" />;
}
+8
View File
@@ -0,0 +1,8 @@
/** 路由数据加载反馈,避免切换会话时暂时显示上一段聊天内容。 */
export default function DigitalLoading() {
return (
<main className="dh-app dh-loading" role="status" aria-live="polite">
正在打开页面…
</main>
);
}
+14
View File
@@ -0,0 +1,14 @@
/** 无效、下架或前台已删除的资源统一显示可恢复的导航入口。 */
import Link from "next/link";
/** 不向其他账号泄露资源存在性或旧聊天内容。 */
export default function DigitalNotFound() {
return (
<main className="dh-app dh-route-message">
<h1>这个页面已经不在这里了</h1>
<p>内容可能已下架,或这段对话已被删除。</p>
<Link href="/chats">查看我的对话</Link>
<Link href="/discover">发现角色</Link>
</main>
);
}
+10
View File
@@ -0,0 +1,10 @@
/** 我的身份独立页面,浏览器历史与页面地址保持一致。 */
import { DigitalPage } from "@/components/digital-page";
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
export const metadata = { title: "我的身份 · 星港" };
/** 读取本页面的私有首屏数据。 */
export default function Page() {
return <DigitalPage tab="me" path="/profile" />;
}
-12
View File
@@ -1,12 +0,0 @@
/** 数字人前台首屏,服务端并行读取私有数据,避免浏览器加载瀑布。 */
import { requireBackendData } from "@/lib/backend";
import type { Bootstrap, Summary } from "@/lib/digital";
import { DigitalHome } from "@/components/digital-home";
/** 私有入口,后端鉴权失败时由统一助手返回登录。 */
export default async function DiscoverPage() {
const [initial, initialSummaries] = await Promise.all([
requireBackendData<Bootstrap>("/digital/bootstrap"),
requireBackendData<Summary[]>("/digital/conversations"),
]);
return <DigitalHome initial={initial} initialSummaries={initialSummaries} />;
}
+13
View File
@@ -1123,3 +1123,16 @@ textarea:focus-visible {
width: calc(100% - 32px); 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%;
}
+24 -14
View File
@@ -1,6 +1,8 @@
"use client"; "use client";
/** 会话列表的水平滑动操作与删除确认;纵向滑动继续交给页面滚动。 */ /** 会话列表的水平滑动操作与删除确认;纵向滑动继续交给页面滚动。 */
import { useEffect, useId, useRef, useState, type PointerEvent } from "react"; import { useEffect, useId, useRef, useState, type PointerEvent } from "react";
import Link from "next/link";
import { chatPath } from "@/lib/digital-routes";
import { LoaderCircle, Trash2 } from "lucide-react"; import { LoaderCircle, Trash2 } from "lucide-react";
import type { Card, Summary } from "@/lib/digital"; import type { Card, Summary } from "@/lib/digital";
@@ -11,7 +13,6 @@ export function ConversationRow({
revealed, revealed,
disabled, disabled,
onReveal, onReveal,
onOpen,
onDelete, onDelete,
}: { }: {
summary: Summary; summary: Summary;
@@ -19,7 +20,6 @@ export function ConversationRow({
revealed: boolean; revealed: boolean;
disabled: boolean; disabled: boolean;
onReveal: (id: string | null) => void; onReveal: (id: string | null) => void;
onOpen: () => void;
onDelete: () => void; onDelete: () => void;
}) { }) {
const [drag, setDrag] = useState<number | null>(null); const [drag, setDrag] = useState<number | null>(null);
@@ -32,8 +32,16 @@ export function ConversationRow({
} | null>(null), } | null>(null),
suppressClick = useRef(false); suppressClick = useRef(false);
const distance = 88; const distance = 88;
function start(e: PointerEvent<HTMLButtonElement>) { function start(e: PointerEvent<HTMLAnchorElement>) {
if (disabled || e.button !== 0) return; if (
disabled ||
e.button !== 0 ||
e.metaKey ||
e.ctrlKey ||
e.shiftKey ||
e.altKey
)
return;
suppressClick.current = false; suppressClick.current = false;
gesture.current = { gesture.current = {
x: e.clientX, x: e.clientX,
@@ -44,7 +52,7 @@ export function ConversationRow({
}; };
e.currentTarget.setPointerCapture(e.pointerId); e.currentTarget.setPointerCapture(e.pointerId);
} }
function move(e: PointerEvent<HTMLButtonElement>) { function move(e: PointerEvent<HTMLAnchorElement>) {
const g = gesture.current; const g = gesture.current;
if (!g) return; if (!g) return;
const dx = e.clientX - g.x, const dx = e.clientX - g.x,
@@ -57,7 +65,7 @@ export function ConversationRow({
g.offset = Math.max(-distance, Math.min(0, g.base + dx)); g.offset = Math.max(-distance, Math.min(0, g.base + dx));
setDrag(g.offset); setDrag(g.offset);
} }
function finish(e: PointerEvent<HTMLButtonElement>, cancelled = false) { function finish(e: PointerEvent<HTMLAnchorElement>, cancelled = false) {
const g = gesture.current; const g = gesture.current;
if (!g) return; if (!g) return;
gesture.current = null; gesture.current = null;
@@ -85,12 +93,13 @@ export function ConversationRow({
<Trash2 size={18} /> <Trash2 size={18} />
<span>删除</span> <span>删除</span>
</button> </button>
<button <Link
href={chatPath(summary.id)}
className={`dh-conversation-open ${drag !== null ? "is-dragging" : ""}`} className={`dh-conversation-open ${drag !== null ? "is-dragging" : ""}`}
style={{ style={{
transform: `translateX(${drag ?? (revealed ? -distance : 0)}px)`, transform: `translateX(${drag ?? (revealed ? -distance : 0)}px)`,
}} }}
disabled={disabled} aria-disabled={disabled}
onPointerDown={start} onPointerDown={start}
onPointerMove={move} onPointerMove={move}
onPointerUp={(e) => finish(e)} onPointerUp={(e) => finish(e)}
@@ -102,15 +111,15 @@ export function ConversationRow({
} }
}} }}
onClick={(e) => { onClick={(e) => {
if (suppressClick.current && e.detail !== 0) { if (disabled || (suppressClick.current && e.detail !== 0)) {
e.preventDefault();
suppressClick.current = false; suppressClick.current = false;
return; return;
} }
if (revealed) { if (revealed) {
e.preventDefault();
onReveal(null); onReveal(null);
return;
} }
onOpen();
}} }}
> >
{/* 封面地址沿用服务端目录,不在小型服务器做图片转换。 */} {/* 封面地址沿用服务端目录,不在小型服务器做图片转换。 */}
@@ -126,7 +135,7 @@ export function ConversationRow({
day: "numeric", day: "numeric",
})} })}
</small> </small>
</button> </Link>
<button <button
className="dh-row-delete-desktop" className="dh-row-delete-desktop"
aria-label={`删除对话:${summary.title}`} aria-label={`删除对话:${summary.title}`}
@@ -177,7 +186,8 @@ export function ConversationDeleteDialog({
</span> </span>
<h2 id={id}>删除这段对话?</h2> <h2 id={id}>删除这段对话?</h2>
<p id={`${id}-description`}> <p id={`${id}-description`}>
「{title}」的对话记录将被永久删除,无法恢复。 「{title}
」将从你的对话列表中移除,你将无法继续查看。后台仍保留聊天记录。
</p> </p>
{error && ( {error && (
<p className="dh-delete-error" role="alert"> <p className="dh-delete-error" role="alert">
@@ -185,7 +195,7 @@ export function ConversationDeleteDialog({
</p> </p>
)} )}
<div className="dh-delete-actions"> <div className="dh-delete-actions">
<button type="button" disabled={busy} onClick={onCancel}> <button type="button" autoFocus disabled={busy} onClick={onCancel}>
取消 取消
</button> </button>
<button <button
+275 -234
View File
@@ -1,7 +1,16 @@
"use client"; "use client";
/* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */ /* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */
/** 星港数字人空间:探索、会话、世界书和身份资料的响应式入口。 */ /** 星港数字人空间:探索、会话、世界书、身份资料和账号内容偏好。 */
import Link from "next/link"; import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import {
chatPath,
contentPath,
digitalTabs,
expiredDigitalSessionPath,
type DigitalTab,
} from "@/lib/digital-routes";
import { useDigitalBack } from "./digital-route-history";
import { import {
useCallback, useCallback,
useEffect, useEffect,
@@ -49,88 +58,55 @@ import {
type Bootstrap, type Bootstrap,
} from "@/lib/digital"; } from "@/lib/digital";
import { ConversationRow, ConversationDeleteDialog } from "./conversation-row"; import { ConversationRow, ConversationDeleteDialog } from "./conversation-row";
import { DigitalMessage } from "./digital-message";
import "./digital.css"; import "./digital.css";
type Tab = "discover" | "chats" | "library" | "me"; type Tab = DigitalTab;
/** 接收文本与视觉打字分离;减少动画设置下直接呈现完整文本。 */
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 (
<span className="dh-thinking" role="status" aria-label="正在思考">
<i aria-hidden />
<i aria-hidden />
<i aria-hidden />
</span>
);
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({ export function DigitalHome({
initial, initial,
initialSummaries, initialSummaries,
initialTab,
initialConversation,
initialDetail,
}: { }: {
initial: Bootstrap; initial: Bootstrap;
initialSummaries: Summary[]; initialSummaries: Summary[];
initialTab: Tab;
initialConversation?: Conversation;
initialDetail?: Card;
}) { }) {
const [tab, setTab] = useState<Tab>("discover"), const router = useRouter();
[boot, setBoot] = useState<Bootstrap | null>(initial), const tab = initialTab;
const detail = initialDetail ?? null;
const goBack = useDigitalBack(
initialConversation ? "/chats" : digitalTabs[tab],
);
const [boot, setBoot] = useState<Bootstrap | null>(initial),
[summaries, setSummaries] = useState<Summary[]>(initialSummaries); [summaries, setSummaries] = useState<Summary[]>(initialSummaries);
const [query, setQuery] = useState(""), const searchParams = useSearchParams();
[tag, setTag] = useState("全部"), const query = (searchParams.get("q") ?? "").slice(0, 200);
[onlyFavorites, setOnlyFavorites] = useState(false); const tag = (searchParams.get("tag") ?? "全部").slice(0, 80);
const [detail, setDetail] = useState<Card | null>(null), const onlyFavorites = searchParams.get("favorites") === "1";
[conversation, setConversation] = useState<Conversation | null>(null); function setFilters(next: {
query?: string;
tag?: string;
favorites?: boolean;
}) {
const params = new URLSearchParams();
const values = { query, tag, favorites: onlyFavorites, ...next };
if (values.query) params.set("q", values.query.slice(0, 200));
if (values.tag !== "全部") params.set("tag", values.tag.slice(0, 80));
if (values.favorites) params.set("favorites", "1");
const path = `/discover${params.size ? `?${params}` : ""}`;
// 原生 replaceState 与 Next 同步查询参数,地址是筛选的唯一来源,返回时不会被旧组件状态覆盖。
window.history.replaceState(window.history.state, "", path);
}
const [conversation, setConversation] = useState<Conversation | null>(
initialConversation ?? null,
);
const [draftReady, setDraftReady] = useState(false);
const [draft, setDraft] = useState(""), const [draft, setDraft] = useState(""),
[busy, setBusy] = useState(false), [busy, setBusy] = useState(initialConversation?.busy ?? false),
[opening, setOpening] = useState(false), [opening, setOpening] = useState(false),
[error, setError] = useState(""), [error, setError] = useState(""),
[notice, setNotice] = useState(""); [notice, setNotice] = useState("");
@@ -138,7 +114,9 @@ export function DigitalHome({
"loading" | "personal" | "managed" | "unknown" "loading" | "personal" | "managed" | "unknown"
>("loading"); >("loading");
const [showSettings, setShowSettings] = useState(false), const [showSettings, setShowSettings] = useState(false),
[settings, setSettings] = useState<Settings | null>(null), [settings, setSettings] = useState<Settings | null>(
initialConversation?.settings ?? null,
),
[profile, setProfile] = useState<Profile | null>(initial.profile); [profile, setProfile] = useState<Profile | null>(initial.profile);
const [profileDraft, setProfileDraft] = useState<Profile | null>( const [profileDraft, setProfileDraft] = useState<Profile | null>(
initial.profile, initial.profile,
@@ -178,7 +156,7 @@ export function DigitalHome({
atBottom = useRef(true), atBottom = useRef(true),
touchY = useRef<number | null>(null), touchY = useRef<number | null>(null),
draggingScroll = useRef(false), draggingScroll = useRef(false),
currentId = useRef<string | null>(null), currentId = useRef<string | null>(initialConversation?.id ?? null),
openSequence = useRef(0); openSequence = useRef(0);
const cards = boot?.catalog.filter((c) => c.kind === "character") ?? [], const cards = boot?.catalog.filter((c) => c.kind === "character") ?? [],
books = boot?.catalog.filter((c) => c.kind === "worldbook") ?? [], books = boot?.catalog.filter((c) => c.kind === "worldbook") ?? [],
@@ -228,6 +206,16 @@ export function DigitalHome({
async () => setSummaries(await digital<Summary[]>("conversations")), async () => setSummaries(await digital<Summary[]>("conversations")),
[], [],
); );
useEffect(() => {
const controller = new AbortController();
// 浏览器后退可能恢复 Next 缓存的页面快照,重新核对列表,避免遗漏刚创建或删除的会话。
digital<Summary[]>("conversations", "GET", undefined, controller.signal)
.then((items) => {
if (!controller.signal.aborted) setSummaries(items);
})
.catch(() => {});
return () => controller.abort();
}, []);
const reloadBootstrap = useCallback(async () => { const reloadBootstrap = useCallback(async () => {
const data = await digital<Bootstrap>("bootstrap"); const data = await digital<Bootstrap>("bootstrap");
decisionReceived.current = performance.now(); decisionReceived.current = performance.now();
@@ -319,26 +307,64 @@ export function DigitalHome({
}, [conversationId]); }, [conversationId]);
useEffect(() => { useEffect(() => {
if (!conversationId) return; if (!conversationId) return;
const resize = () => const root = document.documentElement;
document.documentElement.style.setProperty( const viewport = window.visualViewport;
"--dh-viewport", const body = document.body;
`${window.visualViewport?.height ?? window.innerHeight}px`, 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(); resize();
window.visualViewport?.addEventListener("resize", resize); viewport?.addEventListener("resize", resize);
viewport?.addEventListener("scroll", resize);
window.addEventListener("resize", resize);
return () => { return () => {
window.visualViewport?.removeEventListener("resize", resize); cancelAnimationFrame(frame);
document.documentElement.style.removeProperty("--dh-viewport"); 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]); }, [conversationId]);
useEffect(() => { useEffect(() => {
if (!conversationId) return; if (!conversationId) return;
const frame = requestAnimationFrame(() => {
try {
setDraft(sessionStorage.getItem(`dh-draft:${conversationId}`) ?? "");
} catch {}
setDraftReady(true);
});
return () => cancelAnimationFrame(frame);
}, [conversationId]);
useEffect(() => {
if (!conversationId || !draftReady) return;
try { try {
sessionStorage.setItem(`dh-draft:${conversationId}`, draft); sessionStorage.setItem(`dh-draft:${conversationId}`, draft);
} catch {} } catch {}
}, [draft, conversationId]); }, [draft, conversationId, draftReady]);
useEffect(() => { useEffect(() => {
if (!detail && !showSettings) return; if (!showSettings) return;
const previous = document.activeElement as HTMLElement | null; const previous = document.activeElement as HTMLElement | null;
const dialog = document.querySelector<HTMLElement>( const dialog = document.querySelector<HTMLElement>(
'.dh-overlay [role="dialog"]', '.dh-overlay [role="dialog"]',
@@ -359,7 +385,6 @@ export function DigitalHome({
setSelectionSheet(null); setSelectionSheet(null);
return; return;
} }
setDetail(null);
setShowSettings(false); setShowSettings(false);
} }
if (event.key === "Tab") { if (event.key === "Tab") {
@@ -381,8 +406,8 @@ export function DigitalHome({
document.removeEventListener("keydown", onKey); document.removeEventListener("keydown", onKey);
previous?.focus(); previous?.focus();
}; };
}, [detail, showSettings]); }, [showSettings]);
/** 抽屉聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */ /** 选择弹窗聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */
useEffect(() => { useEffect(() => {
if (!selectionSheet) return; if (!selectionSheet) return;
const previous = selectionTrigger.current; const previous = selectionTrigger.current;
@@ -440,6 +465,10 @@ export function DigitalHome({
}; };
}, [busy, conversationId]); }, [busy, conversationId]);
async function openConversation(id: string) { async function openConversation(id: string) {
if (id !== conversation?.id) {
router.push(chatPath(id));
return;
}
closeIdeas(); closeIdeas();
imeComposing.current = false; imeComposing.current = false;
setSwipedConversation(null); setSwipedConversation(null);
@@ -466,8 +495,6 @@ export function DigitalHome({
} catch { } catch {
setDraft(""); setDraft("");
} }
setTab("chats");
setDetail(null);
} catch (e) { } catch (e) {
reportError(e); reportError(e);
} finally { } finally {
@@ -484,8 +511,7 @@ export function DigitalHome({
greetingIndex: index, greetingIndex: index,
uiDecisionId: boot?.decision.decisionId ?? undefined, uiDecisionId: boot?.decision.decisionId ?? undefined,
}); });
await openConversation(c.id); router.push(chatPath(c.id));
await refreshSummaries();
} catch (e) { } catch (e) {
reportError(e); reportError(e);
} finally { } finally {
@@ -502,8 +528,13 @@ export function DigitalHome({
: [...profile.favorites, card.id], : [...profile.favorites, card.id],
}; };
try { 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) { } catch (e) {
reportError(e); reportError(e);
} finally { } finally {
@@ -573,7 +604,11 @@ export function DigitalHome({
signal: controller.signal, signal: controller.signal,
}); });
if (response.status === 401) { if (response.status === 401) {
window.location.assign("/login"); window.location.assign(
expiredDigitalSessionPath(
window.location.pathname + window.location.search,
),
);
return; return;
} }
accepted = response.ok; accepted = response.ok;
@@ -696,9 +731,7 @@ export function DigitalHome({
"POST", "POST",
{ messageId: message.id }, { messageId: message.id },
); );
await openConversation(result.id); router.push(chatPath(result.id));
await refreshSummaries();
setNotice("已从这里开启新分支,原会话仍然保留");
} catch (e) { } catch (e) {
reportError(e); reportError(e);
} }
@@ -733,9 +766,9 @@ export function DigitalHome({
setSwipedConversation(null); setSwipedConversation(null);
if (currentId.current === id) { if (currentId.current === id) {
closeIdeas(); closeIdeas();
setConversation(null);
currentId.current = null; currentId.current = null;
setDraft(""); setDraft("");
router.replace("/chats");
} }
try { try {
sessionStorage.removeItem(`dh-draft:${id}`); sessionStorage.removeItem(`dh-draft:${id}`);
@@ -831,7 +864,7 @@ export function DigitalHome({
input.style.height = `${Math.min(input.scrollHeight, 160)}px`; input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
}); });
} }
/** 抽屉仅编辑临时值;确认后回填设定,取消不改动已有选择。 */ /** 选择弹窗仅编辑临时值;确认后回填设定,取消不改动已有选择。 */
function openSelection(kind: "style" | "books") { function openSelection(kind: "style" | "books") {
if (!settings) return; if (!settings) return;
selectionTrigger.current = document.activeElement as HTMLElement; selectionTrigger.current = document.activeElement as HTMLElement;
@@ -874,11 +907,15 @@ export function DigitalHome({
...profile, ...profile,
userName: profileDraft.userName, userName: profileDraft.userName,
persona: profileDraft.persona, persona: profileDraft.persona,
nsfwEnabled: profileDraft.nsfwEnabled ?? true,
}; };
try { try {
await digital("profile", "PUT", next); const saved = await digital<Profile>("profile", "PUT", next);
setProfile(next); if (saved.nsfwEnabled !== next.nsfwEnabled)
setNotice("身份资料已保存"); throw new Error("内容偏好未保存,请稍后重试");
setProfile(saved);
setProfileDraft(saved);
setNotice("身份与内容偏好已保存");
} catch (e) { } catch (e) {
reportError(e); reportError(e);
} }
@@ -909,17 +946,9 @@ export function DigitalHome({
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
} }
function switchTab(value: Tab) { function switchTab(value: Tab) {
closeIdeas(); router.push(digitalTabs[value]);
setSwipedConversation(null);
if (conversation && busy) {
setNotice("请先停止当前回复,再离开会话");
return;
}
setConversation(null);
currentId.current = null;
setTab(value);
setError("");
} }
const tags = [ const tags = [
"全部", "全部",
...new Set(cards.flatMap((c) => c.tags).slice(0, 30)), ...new Set(cards.flatMap((c) => c.tags).slice(0, 30)),
@@ -982,9 +1011,6 @@ export function DigitalHome({
onChange={() => onChange(p.id || undefined)} onChange={() => onChange(p.id || undefined)}
/> />
<span className="dh-style-card"> <span className="dh-style-card">
<span className="dh-style-symbol" aria-hidden="true">
{p.id ? <WandSparkles /> : <Sparkles />}
</span>
<span className="dh-style-copy"> <span className="dh-style-copy">
<strong>{p.name}</strong> <strong>{p.name}</strong>
<small>{p.description || "以这套风格继续你们的故事。"}</small> <small>{p.description || "以这套风格继续你们的故事。"}</small>
@@ -1031,12 +1057,14 @@ export function DigitalHome({
))} ))}
</fieldset> </fieldset>
); );
useEffect( useEffect(() => {
() => () => { // 缓存页面重新显示时重新绑定会话,离开后的旧流请求不能更新下一页。
currentId.current = conversationId ?? null;
return () => {
ideasRequest.current?.abort(); ideasRequest.current?.abort();
}, currentId.current = null;
[], };
); }, [conversationId]);
// UI按消费者返回值决定,组名仅用于归因;C到Z同样可以返回新版UI。 // UI按消费者返回值决定,组名仅用于归因;C到Z同样可以返回新版UI。
// 缺少value时兼容尚未升级的服务响应。 // 缺少value时兼容尚未升级的服务响应。
const modern = const modern =
@@ -1062,17 +1090,18 @@ export function DigitalHome({
{ id: "me", label: "我的身份", icon: UserRound }, { id: "me", label: "我的身份", icon: UserRound },
] as const ] as const
).map((item) => ( ).map((item) => (
<button <Link
key={item.id} key={item.id}
href={digitalTabs[item.id]}
className={tab === item.id ? "is-active" : ""} className={tab === item.id ? "is-active" : ""}
onClick={() => switchTab(item.id)} aria-current={tab === item.id ? "page" : undefined}
> >
<item.icon size={19} /> <item.icon size={19} />
<span>{item.label}</span> <span>{item.label}</span>
{item.id === "chats" && summaries.length > 0 && ( {item.id === "chats" && summaries.length > 0 && (
<small>{summaries.length}</small> <small>{summaries.length}</small>
)} )}
</button> </Link>
))} ))}
</nav> </nav>
<div className="dh-sidebar-bottom"> <div className="dh-sidebar-bottom">
@@ -1112,12 +1141,8 @@ export function DigitalHome({
<header className="dh-chat-header"> <header className="dh-chat-header">
<button <button
className="dh-icon" className="dh-icon"
aria-label="返回对话列表" aria-label="返回上一页"
disabled={busy} onClick={goBack}
onClick={() => {
setConversation(null);
currentId.current = null;
}}
> >
<ArrowLeft size={21} /> <ArrowLeft size={21} />
</button> </button>
@@ -1239,11 +1264,9 @@ export function DigitalHome({
{m.pinned && <Pin size={11} />} {m.pinned && <Pin size={11} />}
</span> </span>
<div className="dh-bubble"> <div className="dh-bubble">
<MessageText <DigitalMessage
message={m} message={m}
animate={ animate={m.id === activeMessage}
m.id === activeMessage && m.status === "generating"
}
/> />
</div> </div>
{!busy && m.content && ( {!busy && m.content && (
@@ -1428,6 +1451,7 @@ export function DigitalHome({
<textarea <textarea
ref={textarea} ref={textarea}
aria-label="消息" aria-label="消息"
disabled={!draftReady}
placeholder={`对 ${currentCard?.name ?? "角色"} 说点什么…`} placeholder={`对 ${currentCard?.name ?? "角色"} 说点什么…`}
value={draft} value={draft}
maxLength={4000} maxLength={4000}
@@ -1477,7 +1501,7 @@ export function DigitalHome({
</small> </small>
</div> </div>
</section> </section>
) : ( ) : detail ? null : (
<div className="dh-page"> <div className="dh-page">
<header className="dh-page-header"> <header className="dh-page-header">
<div> <div>
@@ -1518,7 +1542,7 @@ export function DigitalHome({
cards.find( cards.find(
(c) => !profile?.favorites.includes(c.id), (c) => !profile?.favorites.includes(c.id),
) ?? cards[0]; ) ?? cards[0];
if (card) setDetail(card); if (card) router.push(contentPath(card));
}} }}
> >
<WandSparkles size={16} /> <WandSparkles size={16} />
@@ -1539,12 +1563,12 @@ export function DigitalHome({
aria-label="搜索角色" aria-label="搜索角色"
placeholder="搜索名字、性格或故事…" placeholder="搜索名字、性格或故事…"
value={query} value={query}
onChange={(e) => setQuery(e.target.value)} onChange={(e) => setFilters({ query: e.target.value })}
/> />
{query && ( {query && (
<button <button
aria-label="清空搜索" aria-label="清空搜索"
onClick={() => setQuery("")} onClick={() => setFilters({ query: "" })}
> >
<X size={15} /> <X size={15} />
</button> </button>
@@ -1552,7 +1576,7 @@ export function DigitalHome({
</label> </label>
<button <button
className={`dh-favorite-filter ${onlyFavorites ? "is-active" : ""}`} className={`dh-favorite-filter ${onlyFavorites ? "is-active" : ""}`}
onClick={() => setOnlyFavorites(!onlyFavorites)} onClick={() => setFilters({ favorites: !onlyFavorites })}
> >
<Heart <Heart
size={17} size={17}
@@ -1566,7 +1590,7 @@ export function DigitalHome({
<button <button
key={t} key={t}
className={tag === t ? "is-active" : ""} className={tag === t ? "is-active" : ""}
onClick={() => setTag(t)} onClick={() => setFilters({ tag: t })}
> >
{t} {t}
</button> </button>
@@ -1579,10 +1603,7 @@ export function DigitalHome({
<div className="dh-card-grid"> <div className="dh-card-grid">
{filtered.map((c) => ( {filtered.map((c) => (
<article className="dh-card" key={c.id}> <article className="dh-card" key={c.id}>
<button <Link className="dh-card-open" href={contentPath(c)}>
className="dh-card-open"
onClick={() => setDetail(c)}
>
<img <img
src={c.cover || "/icon.svg"} src={c.cover || "/icon.svg"}
alt={c.name} alt={c.name}
@@ -1601,7 +1622,7 @@ export function DigitalHome({
))} ))}
</div> </div>
</div> </div>
</button> </Link>
<button <button
className={`dh-card-favorite ${profile?.favorites.includes(c.id) ? "is-active" : ""}`} className={`dh-card-favorite ${profile?.favorites.includes(c.id) ? "is-active" : ""}`}
aria-label={`收藏${c.name}`} aria-label={`收藏${c.name}`}
@@ -1626,9 +1647,11 @@ export function DigitalHome({
<p>换一个关键词,或者看看其他故事。</p> <p>换一个关键词,或者看看其他故事。</p>
<button <button
onClick={() => { onClick={() => {
setTag("全部"); setFilters({
setQuery(""); query: "",
setOnlyFavorites(false); tag: "全部",
favorites: false,
});
}} }}
> >
看看全部角色 看看全部角色
@@ -1658,7 +1681,6 @@ export function DigitalHome({
revealed={swipedConversation === s.id} revealed={swipedConversation === s.id}
disabled={opening || deleting} disabled={opening || deleting}
onReveal={setSwipedConversation} onReveal={setSwipedConversation}
onOpen={() => openConversation(s.id)}
onDelete={() => requestDelete(s)} onDelete={() => requestDelete(s)}
/> />
))} ))}
@@ -1689,17 +1711,17 @@ export function DigitalHome({
</div> </div>
<div className="dh-library-grid"> <div className="dh-library-grid">
{books.map((b) => ( {books.map((b) => (
<button <Link
key={b.id} key={b.id}
className="dh-library-card" className="dh-library-card"
onClick={() => setDetail(b)} href={contentPath(b)}
> >
<BookOpen size={24} /> <BookOpen size={24} />
<small>{b.entriesCount} 条设定</small> <small>{b.entriesCount} 条设定</small>
<h3>{b.name}</h3> <h3>{b.name}</h3>
<p>{b.description}</p> <p>{b.description}</p>
<span>查看详情 →</span> <span>查看详情 →</span>
</button> </Link>
))} ))}
</div> </div>
<div className="dh-section-heading"> <div className="dh-section-heading">
@@ -1708,17 +1730,17 @@ export function DigitalHome({
</div> </div>
<div className="dh-library-grid"> <div className="dh-library-grid">
{presets.map((b) => ( {presets.map((b) => (
<button <Link
key={b.id} key={b.id}
className="dh-library-card" className="dh-library-card"
onClick={() => setDetail(b)} href={contentPath(b)}
> >
<WandSparkles size={24} /> <WandSparkles size={24} />
<small>对话风格</small> <small>对话风格</small>
<h3>{b.name}</h3> <h3>{b.name}</h3>
<p>{b.description}</p> <p>{b.description}</p>
<span>查看详情 →</span> <span>查看详情 →</span>
</button> </Link>
))} ))}
</div> </div>
</> </>
@@ -1766,9 +1788,28 @@ export function DigitalHome({
<p className="dh-form-note"> <p className="dh-form-note">
此资料可在新会话的「对话设定」中使用。每个会话的设定相互独立。 此资料可在新会话的「对话设定」中使用。每个会话的设定相互独立。
</p> </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"> <button className="dh-primary" type="submit">
<Check size={16} /> <Check size={16} />
保存身份 保存身份与偏好
</button> </button>
<div className="dh-profile-stats"> <div className="dh-profile-stats">
<div> <div>
@@ -1795,90 +1836,90 @@ export function DigitalHome({
</footer> </footer>
</div> </div>
)} )}
</main> {detail && (
{detail && ( <div className="dh-detail-page">
<div <header className="dh-detail-nav">
className="dh-overlay" <button className="dh-detail-back" onClick={goBack}>
onClick={(e) => { <ArrowLeft size={18} />
if (e.target === e.currentTarget) setDetail(null); 返回上一页
}} </button>
> <span>
<section
className="dh-detail"
role="dialog"
aria-modal="true"
aria-label={detail.name}
>
<button
className="dh-close"
aria-label="关闭详情"
onClick={() => setDetail(null)}
>
<X />
</button>
{detail.kind === "character" && (
<div className="dh-detail-cover">
<img src={detail.cover || "/icon.svg"} alt={detail.name} />
</div>
)}
<div className="dh-detail-body">
<span className="dh-eyebrow">
{detail.kind === "character" {detail.kind === "character"
? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色` ? "角色详情"
: detail.kind === "worldbook" : detail.kind === "worldbook"
? "WORLD BOOK" ? "世界书"
: "STORY PRESET"} : "对话风格"}
</span> </span>
<h2>{detail.name}</h2> </header>
<div className="dh-card-tags"> <section
{detail.tags.map((t) => ( className="dh-detail"
<span key={t}>{t}</span> role="region"
))} aria-label={detail.name}
</div> >
<p className="dh-detail-description">{detail.description}</p> {detail.kind === "character" && (
{detail.greeting && ( <div className="dh-detail-cover">
<blockquote> <img src={detail.cover || "/icon.svg"} alt={detail.name} />
{detail.greeting </div>
.replaceAll("{{user}}", profile?.userName ?? "旅人")
.replaceAll("{{char}}", detail.name)}
</blockquote>
)} )}
{detail.kind === "character" ? ( <div className="dh-detail-body">
<> <span className="dh-eyebrow">
<button {detail.kind === "character"
className="dh-primary" ? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色`
disabled={opening} : detail.kind === "worldbook"
onClick={() => start(detail)} ? "WORLD BOOK"
> : "STORY PRESET"}
{opening ? ( </span>
<LoaderCircle className="dh-spin" size={17} /> <h1>{detail.name}</h1>
) : ( <div className="dh-card-tags">
<MessageCircle size={17} /> {detail.tags.map((t) => (
)} <span key={t}>{t}</span>
开启这段故事
</button>
{detail.alternateGreetings.map((g, i) => (
<button
className="dh-alt-greeting"
key={i}
disabled={opening}
onClick={() => start(detail, i + 1)}
>
<small>另一种相遇 {i + 1}</small>
<p>{g.slice(0, 110)}</p>
</button>
))} ))}
</> </div>
) : ( <p className="dh-detail-description">{detail.description}</p>
<p className="dh-form-note"> {detail.greeting && (
进入任意对话,点击右上角「对话设定」即可使用。 <blockquote>
</p> {detail.greeting
)} .replaceAll("{{user}}", profile?.userName ?? "旅人")
<small className="dh-source">{detail.source}</small> .replaceAll("{{char}}", detail.name)}
</div> </blockquote>
</section> )}
</div> {detail.kind === "character" ? (
)} <>
<button
className="dh-primary"
disabled={opening}
onClick={() => start(detail)}
>
{opening ? (
<LoaderCircle className="dh-spin" size={17} />
) : (
<MessageCircle size={17} />
)}
开启这段故事
</button>
{detail.alternateGreetings.map((g, i) => (
<button
className="dh-alt-greeting"
key={i}
disabled={opening}
onClick={() => start(detail, i + 1)}
>
<small>另一种相遇 {i + 1}</small>
<p>{g.slice(0, 110)}</p>
</button>
))}
</>
) : (
<p className="dh-form-note">
进入任意对话,点击右上角「对话设定」即可使用。
</p>
)}
<small className="dh-source">{detail.source}</small>
</div>
</section>
</div>
)}
</main>
{showSettings && settings && ( {showSettings && settings && (
<div className={`dh-overlay ${selectionSheet ? "dh-sheet-open" : ""}`}> <div className={`dh-overlay ${selectionSheet ? "dh-sheet-open" : ""}`}>
<form <form
+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>
);
});
+58
View File
@@ -0,0 +1,58 @@
/** 独立数字人页面的数据入口:并行加载私有首屏,深链读取会话并统一处理失效资源。 */
import { notFound } from "next/navigation";
import { BackendError, requireBackendData } from "@/lib/backend";
import { validDigitalId, type DigitalTab } from "@/lib/digital-routes";
import type { Bootstrap, Conversation, Summary } from "@/lib/digital";
import { DigitalHome } from "./digital-home";
/** 每个地址生成独立页面;刷新、分享或浏览器后退均能从服务端还原同一资源。 */
export async function DigitalPage({
tab,
path,
conversationId,
contentId,
}: {
tab: DigitalTab;
path: string;
conversationId?: string;
contentId?: string;
}) {
if (
(conversationId && !validDigitalId(conversationId)) ||
(contentId && !validDigitalId(contentId))
)
notFound();
const [initial, initialSummaries, initialConversation] = await Promise.all([
requireBackendData<Bootstrap>("/digital/bootstrap", path),
requireBackendData<Summary[]>("/digital/conversations", path),
conversationId
? requireBackendData<Conversation>(
`/digital/conversations/${conversationId}`,
path,
)
: undefined,
]).catch((error) => {
if (error instanceof BackendError && error.status === 404) notFound();
throw error;
});
const detail = contentId
? initial.catalog.find(
(card) =>
card.id === contentId &&
(tab === "discover"
? card.kind === "character"
: card.kind !== "character"),
)
: undefined;
if (contentId && !detail) notFound();
return (
<DigitalHome
key={path}
initial={initial}
initialSummaries={initialSummaries}
initialTab={tab}
initialConversation={initialConversation}
initialDetail={detail}
/>
);
}
+54
View File
@@ -0,0 +1,54 @@
"use client";
/** 记录当前浏览器条目的站内来源;返回优先沿真实历史,直接打开深链时回父页面。 */
import type { Route } from "next";
import { useEffect, useRef } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { safeDigitalReturnTo } from "@/lib/digital-routes";
/** 共享布局持续存在,让不同路由的进入顺序成为浏览器真实历史。 */
export function DigitalRouteHistory() {
const pathname = usePathname();
const searchParams = useSearchParams();
const previous = useRef<string | null>(null);
useEffect(() => {
const path =
window.location.pathname + window.location.search + window.location.hash;
const state = window.history.state ?? {};
// 后退恢复的是已有条目,不能把它的来源覆盖成刚离开的页面。
if (state.stellarNavigation?.path !== path) {
const existing = state.stellarNavigation;
// 筛选只替换当前 URL,不凭空增加一次返回步骤。
const samePage =
typeof existing?.path === "string" &&
new URL(existing.path, window.location.origin).pathname === pathname;
window.history.replaceState(
{
...state,
stellarNavigation: {
path,
previous: samePage ? existing.previous : previous.current,
},
},
"",
path,
);
}
previous.current = path;
}, [pathname, searchParams]);
return null;
}
/** 页面内返回按钮与浏览器后退一致;外部打开或新标签页不返回站外。 */
export function useDigitalBack(fallback: Route) {
const router = useRouter();
return () => {
const previous = window.history.state?.stellarNavigation?.previous;
if (
typeof previous === "string" &&
safeDigitalReturnTo(previous) === previous
)
router.back();
else router.replace(fallback);
};
}
+224 -71
View File
@@ -121,7 +121,7 @@
flex-direction: column; flex-direction: column;
gap: 9px; gap: 9px;
} }
.dh-sidebar nav button { .dh-sidebar nav a {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 14px; gap: 14px;
@@ -130,15 +130,15 @@
color: var(--dh-muted); color: var(--dh-muted);
text-align: left; text-align: left;
} }
.dh-sidebar nav button small { .dh-sidebar nav a small {
margin-left: auto; margin-left: auto;
font-size: 11px; font-size: 11px;
} }
.dh-sidebar nav button.is-active { .dh-sidebar nav a.is-active {
color: var(--dh-accent); color: var(--dh-accent);
background: color-mix(in srgb, var(--dh-accent) 9%, transparent); background: color-mix(in srgb, var(--dh-accent) 9%, transparent);
} }
.dh-sidebar nav button:hover { .dh-sidebar nav a:hover {
background: var(--dh-panel); background: var(--dh-panel);
} }
.dh-sidebar-bottom { .dh-sidebar-bottom {
@@ -636,9 +636,9 @@
/* 横滑只移动会话卡片,删除在明确确认后才执行。 */ /* 横滑只移动会话卡片,删除在明确确认后才执行。 */
.dh-conversation-row { .dh-conversation-row {
position: relative; position: relative;
overflow: hidden; overflow: visible;
border-radius: 14px; border-radius: 14px;
background: #9a394b; background: transparent;
} }
.dh-conversation-list .dh-conversation-open { .dh-conversation-list .dh-conversation-open {
position: relative; position: relative;
@@ -659,9 +659,11 @@
gap: 5px; gap: 5px;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 88px; width: 76px;
color: #fff; color: #fff;
background: #9a394b; background: #a3374c;
border-radius: 14px;
box-shadow: 0 4px 16px #0003;
visibility: hidden; visibility: hidden;
} }
.dh-conversation-row.is-revealed .dh-row-delete-swipe { .dh-conversation-row.is-revealed .dh-row-delete-swipe {
@@ -699,7 +701,11 @@
} }
.dh-delete-dialog { .dh-delete-dialog {
width: min(420px, calc(100% - 32px)); width: min(420px, calc(100% - 32px));
max-height: 90dvh; max-height: calc(100dvh - 48px);
margin: auto;
overflow-y: auto;
overscroll-behavior: contain;
box-shadow: 0 24px 80px #0008;
padding: 26px; padding: 26px;
color: var(--dh-text); color: var(--dh-text);
background: var(--dh-panel); background: var(--dh-panel);
@@ -882,12 +888,10 @@
font-size: 10px; font-size: 10px;
} }
.dh-delete-dialog { .dh-delete-dialog {
width: 100%; width: min(380px, calc(100% - 40px));
max-width: 100%; margin: auto;
margin: auto 0 0; padding: 24px;
padding: 24px 22px calc(22px + env(safe-area-inset-bottom)); border-radius: 22px;
border-radius: 22px 22px 0 0;
border-bottom: 0;
} }
.dh-app .dh-compose-tools .dh-mobile-linebreak { .dh-app .dh-compose-tools .dh-mobile-linebreak {
display: flex; display: flex;
@@ -990,6 +994,53 @@
line-height: 1.9; line-height: 1.9;
margin: 8px 0 20px !important; 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 { .dh-profile-stats {
display: flex; display: flex;
border-top: 1px solid var(--dh-line); border-top: 1px solid var(--dh-line);
@@ -1179,8 +1230,8 @@
} }
.dh-style-options { .dh-style-options {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: minmax(0, 1fr);
gap: 10px; gap: 0;
} }
.dh-style-option { .dh-style-option {
position: relative; position: relative;
@@ -1188,10 +1239,6 @@
cursor: pointer; cursor: pointer;
-webkit-tap-highlight-color: transparent; -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 { .dh-style-option > input {
position: absolute; position: absolute;
width: 1px; width: 1px;
@@ -1205,41 +1252,26 @@
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
gap: 10px; gap: 10px;
height: 100%; min-height: 72px;
min-height: 88px; padding: 14px 10px;
padding: 15px 13px; border: 0;
border: 1px solid #ffffff17; border-bottom: 1px solid var(--dh-line);
border-radius: 13px; border-radius: 0;
background: color-mix(in srgb, var(--dh-soft) 60%, var(--dh-panel)); background: transparent;
transition: transition:
border-color 160ms, border-color 160ms,
background 160ms; background 160ms;
} }
.dh-style-option:hover .dh-style-card { .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 { .dh-style-option > input:checked + .dh-style-card {
border-color: var(--dh-accent); background: color-mix(in srgb, var(--dh-accent) 7%, transparent);
background: color-mix(in srgb, var(--dh-accent) 9%, var(--dh-panel));
} }
.dh-style-option > input:focus-visible + .dh-style-card { .dh-style-option > input:focus-visible + .dh-style-card {
outline: 2px solid var(--dh-accent); outline: 2px solid var(--dh-accent);
outline-offset: 3px; 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 { .dh-style-copy {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
@@ -1266,8 +1298,7 @@
height: 17px; height: 17px;
margin-top: 2px; margin-top: 2px;
color: transparent; color: transparent;
border: 1px solid #ffffff30; border: 0;
border-radius: 50%;
} }
.dh-style-check svg { .dh-style-check svg {
width: 11px; width: 11px;
@@ -1275,9 +1306,8 @@
stroke-width: 3; stroke-width: 3;
} }
.dh-style-option > input:checked + .dh-style-card .dh-style-check { .dh-style-option > input:checked + .dh-style-card .dh-style-check {
color: var(--dh-accent-ink); color: var(--dh-accent);
background: var(--dh-accent); background: transparent;
border-color: var(--dh-accent);
} }
@media (width <= 600px) { @media (width <= 600px) {
.dh-style-options { .dh-style-options {
@@ -1287,7 +1317,7 @@
min-height: 76px; min-height: 76px;
} }
} }
/* H5 选择项以底部抽屉编辑草稿,确认后才回填到对话设定。 */ /* H5 选择项在居中弹窗编辑草稿,确认后才回填到对话设定。 */
.dh-mobile-choices { .dh-mobile-choices {
display: none; display: none;
} }
@@ -1302,8 +1332,9 @@
inset: 0; inset: 0;
z-index: 2; z-index: 2;
display: flex; display: flex;
align-items: flex-end; align-items: center;
justify-content: center; justify-content: center;
padding: 20px;
overscroll-behavior: contain; overscroll-behavior: contain;
} }
.dh-selection-backdrop { .dh-selection-backdrop {
@@ -1317,15 +1348,14 @@
position: relative; position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: 100%; width: min(520px, 100%);
max-height: 86dvh; max-height: 86dvh;
min-height: 0; min-height: 0;
overflow: hidden; overflow: hidden;
background: var(--dh-panel); background: var(--dh-panel);
border: 1px solid #ffffff1c; border: 1px solid #ffffff1c;
border-bottom: 0; border-radius: 22px;
border-radius: 24px 24px 0 0; box-shadow: 0 24px 80px #0008;
box-shadow: 0 -16px 60px #0005;
animation: dh-sheet-enter 180ms ease-out; animation: dh-sheet-enter 180ms ease-out;
} }
.dh-sheet-handle { .dh-sheet-handle {
@@ -1367,18 +1397,18 @@
border: 0; border: 0;
} }
.dh-selection-sheet .dh-checkbox { .dh-selection-sheet .dh-checkbox {
min-height: 74px; min-height: 70px;
padding: 14px; padding: 14px 10px;
margin: 0 0 10px; margin: 0;
border: 1px solid #ffffff17; border: 0;
border-radius: 13px; border-bottom: 1px solid var(--dh-line);
border-radius: 0;
cursor: pointer; cursor: pointer;
} }
.dh-selection-sheet .dh-checkbox.is-selected { .dh-selection-sheet .dh-checkbox.is-selected {
background: color-mix(in srgb, var(--dh-accent) 9%, var(--dh-panel)); background: color-mix(in srgb, var(--dh-accent) 7%, transparent);
border-color: var(--dh-accent);
} }
.dh-selection-sheet .dh-checkbox:focus-within { .dh-selection-sheet .dh-checkbox:has(input:focus-visible) {
outline: 2px solid var(--dh-accent); outline: 2px solid var(--dh-accent);
outline-offset: 2px; outline-offset: 2px;
} }
@@ -1416,10 +1446,12 @@
} }
@keyframes dh-sheet-enter { @keyframes dh-sheet-enter {
from { from {
transform: translateY(100%); opacity: 0;
transform: translateY(8px) scale(0.98);
} }
to { to {
transform: translateY(0); opacity: 1;
transform: translateY(0) scale(1);
} }
} }
@media (width > 600px) { @media (width > 600px) {
@@ -1675,6 +1707,28 @@
font-size: 14px; font-size: 14px;
color: #e6dfe7; 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 { .dh-message-user {
justify-content: flex-end; justify-content: flex-end;
} }
@@ -1785,7 +1839,7 @@
width: 100%; width: 100%;
resize: none; resize: none;
min-height: 36px; min-height: 36px;
max-height: 160px; max-height: min(160px, calc(var(--dh-viewport, 100dvh) * 0.28));
border: 0; border: 0;
background: none; background: none;
padding: 7px 0; padding: 7px 0;
@@ -1909,7 +1963,7 @@
gap: 2px; gap: 2px;
height: 100%; height: 100%;
} }
.dh-sidebar nav button { .dh-sidebar nav a {
padding: 7px 3px; padding: 7px 3px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -1919,7 +1973,7 @@
justify-content: center; justify-content: center;
position: relative; position: relative;
} }
.dh-sidebar nav button small { .dh-sidebar nav a small {
position: absolute; position: absolute;
top: 0; top: 0;
right: 18px; right: 18px;
@@ -1928,10 +1982,10 @@
padding: 0 5px; padding: 0 5px;
border-radius: 9px; border-radius: 9px;
} }
.dh-sidebar nav button.is-active { .dh-sidebar nav a.is-active {
background: none; background: none;
} }
.dh-sidebar nav button.is-active svg { .dh-sidebar nav a.is-active svg {
filter: drop-shadow( filter: drop-shadow(
0 0 8px color-mix(in srgb, var(--dh-accent) 45%, transparent) 0 0 8px color-mix(in srgb, var(--dh-accent) 45%, transparent)
); );
@@ -2180,7 +2234,7 @@
} }
.dh-chat { .dh-chat {
position: fixed; position: fixed;
inset: 0; inset: var(--dh-viewport-top, 0px) 0 auto;
width: 100%; width: 100%;
height: var(--dh-viewport, 100dvh); height: var(--dh-viewport, 100dvh);
z-index: 20; z-index: 20;
@@ -2333,3 +2387,102 @@ body:has(.dh-app) .environment-badge {
overflow-x: hidden; overflow-x: hidden;
overflow-wrap: anywhere; 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;
}
}
/* 页面导航使用真实链接,视觉与触摸命中范围保持一致。 */
.dh-sidebar nav a {
cursor: pointer;
}
.dh-conversation-open[aria-disabled="true"] {
opacity: 0.42;
cursor: not-allowed;
}
.dh-detail-page {
padding: 40px 32px;
min-height: 100dvh;
}
.dh-detail-page .dh-detail {
width: min(960px, 100%);
max-height: none;
overflow: visible;
margin: 0 auto;
}
.dh-detail-page .dh-detail-body h1 {
font-size: clamp(26px, 4vw, 38px);
line-height: 1.3;
overflow-wrap: anywhere;
}
.dh-route-message {
display: flex;
min-height: 100dvh;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 20px;
padding: 32px;
text-align: center;
}
.dh-route-message a,
.dh-route-message button {
padding: 12px 24px;
border: 1px solid var(--dh-line);
border-radius: 12px;
}
@media (max-width: 600px) {
.dh-detail-page {
padding: 16px 14px 100px;
}
.dh-detail-page .dh-detail {
max-height: none;
}
}
.dh-detail-nav {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
max-width: 960px;
margin: 0 auto 20px;
color: var(--dh-muted);
}
.dh-app .dh-detail-back {
display: flex;
align-items: center;
gap: 8px;
min-height: 44px;
color: var(--dh-accent);
}
+5 -4
View File
@@ -1,12 +1,13 @@
"use client"; "use client";
/** 复用原有账号登录,成功后进入数字人空间。 */ /** 独立星港用户账号登录,成功后进入数字人空间。 */
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { safeDigitalReturnTo } from "@/lib/digital-routes";
import { Eye, EyeOff, LockKeyhole, Smartphone } from "lucide-react"; import { Eye, EyeOff, LockKeyhole, Smartphone } from "lucide-react";
import { FormEvent, useState } from "react"; import { FormEvent, useState } from "react";
/** 现有账号的登录表单,不保存明文密码。 */ /** 独立用户的登录表单,不保存明文密码。 */
export function LoginForm() { export function LoginForm({ returnTo = "/discover" }: { returnTo?: string }) {
const router = useRouter(); const router = useRouter();
const [error, setError] = useState(""); const [error, setError] = useState("");
const [pending, setPending] = useState(false); const [pending, setPending] = useState(false);
@@ -31,7 +32,7 @@ export function LoginForm() {
const payload = await response.json().catch(() => null); const payload = await response.json().catch(() => null);
throw new Error(payload?.message || "登录失败,请检查账号和密码"); throw new Error(payload?.message || "登录失败,请检查账号和密码");
} }
router.replace("/discover"); router.replace(safeDigitalReturnTo(returnTo));
router.refresh(); router.refresh();
} catch (error) { } catch (error) {
setError( setError(
+7 -2
View File
@@ -2,6 +2,7 @@
import "server-only"; import "server-only";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { expiredDigitalSessionPath } from "@/lib/digital-routes";
import { clearSessionToken, getSessionToken } from "@/lib/session"; import { clearSessionToken, getSessionToken } from "@/lib/session";
import type { ApiEnvelope } from "@/lib/types"; import type { ApiEnvelope } from "@/lib/types";
@@ -77,12 +78,16 @@ export async function backendRequest<T>(
} }
/** 页面数据要求登录,失效时通过登出路由清理 Cookie。 */ /** 页面数据要求登录,失效时通过登出路由清理 Cookie。 */
export async function requireBackendData<T>(path: string) { export async function requireBackendData<T>(path: string, returnTo?: string) {
try { try {
return await backendRequest<T>(path); return await backendRequest<T>(path);
} catch (error) { } catch (error) {
if (error instanceof BackendError && error.status === 401) { if (error instanceof BackendError && error.status === 401) {
redirect("/api/auth/logout?next=/login"); redirect(
returnTo
? expiredDigitalSessionPath(returnTo)
: "/api/auth/logout?next=/login",
);
} }
throw error; throw error;
+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;
}
+64
View File
@@ -0,0 +1,64 @@
/** 数字人页面的固定地址与登录回跳校验,禁止把外部输入作为任意跳转目标。 */
import type { Route } from "next";
/** 顶部和底部导航共享同一份页面映射,保留旧工作台 /me 的兼容入口。 */
export const digitalTabs = {
discover: "/discover",
chats: "/chats",
library: "/library",
me: "/profile",
} as const;
/** 数字人导航项。 */
export type DigitalTab = keyof typeof digitalTabs;
/** 与后端资源 ID 的格式保持一致,非法深链直接显示不存在。 */
export function validDigitalId(id: string) {
return /^[a-zA-Z0-9_-]{1,64}$/.test(id);
}
/** 会话永久地址;导航和创建分支都使用同一个入口。 */
export function chatPath(id: string): `/chats/${string}` {
return `/chats/${encodeURIComponent(id)}`;
}
/** 角色与书架内容分别拥有可直接访问的详情页。 */
export function contentPath(card: {
id: string;
kind: string;
}): `/characters/${string}` | `/library/${string}` {
return `/${card.kind === "character" ? "characters" : "library"}/${encodeURIComponent(card.id)}`;
}
/** 只接受数字人业务页面,拒绝外站、接口、登录循环与畸形路径。 */
export function safeDigitalReturnTo(value: string | null | undefined): Route {
if (
!value ||
!value.startsWith("/") ||
/^\/[/\\]/.test(value) ||
/[\\\u0000-\u0020\u007f]/.test(value)
)
return "/discover";
const url = new URL(value, "https://stellar.invalid");
if (
url.origin !== "https://stellar.invalid" ||
!/^\/(?:discover|profile|chats(?:\/[a-zA-Z0-9_-]{1,64})?|library(?:\/[a-zA-Z0-9_-]{1,64})?|characters\/[a-zA-Z0-9_-]{1,64})$/.test(
url.pathname,
)
)
return "/discover";
return (url.pathname + url.search + url.hash) as Route;
}
/** 未登录时携带原始页面,登录成功后恢复具体会话而不是固定回首页。 */
export function digitalLoginPath(returnTo: string): `/login?next=${string}` {
return `/login?next=${encodeURIComponent(safeDigitalReturnTo(returnTo))}`;
}
/** 过期会话先清理 HttpOnly Cookie,避免代理把登录页重定向回失效会话。 */
export function expiredDigitalSessionPath(
returnTo: string,
): `/api/auth/logout?next=${string}` {
return `/api/auth/logout?next=${encodeURIComponent(digitalLoginPath(returnTo))}`;
}
+9 -1
View File
@@ -1,4 +1,6 @@
/** 数字人客户端协议与事件解码,不包含模型凭据或实验操作。 */ /** 数字人客户端协议与事件解码,不包含模型凭据或实验操作。 */
import { expiredDigitalSessionPath } from "./digital-routes";
/** 前台可见内容摘要,提示词不会下发。 */ /** 前台可见内容摘要,提示词不会下发。 */
export type Card = { export type Card = {
id: string; id: string;
@@ -20,6 +22,8 @@ export type Profile = {
favorites: string[]; favorites: string[];
persona: string; persona: string;
userName: string; userName: string;
/** 登录账号的成人内容偏好;旧服务未返回时沿用默认开启。 */
nsfwEnabled?: boolean;
}; };
/** 会话消息拥有持久化 id,避免流式刷新时重复插入。 */ /** 会话消息拥有持久化 id,避免流式刷新时重复插入。 */
export type Message = { export type Message = {
@@ -62,7 +66,11 @@ export async function digital<T>(
}); });
const data = await response.json(); const data = await response.json();
if (response.status === 401) { if (response.status === 401) {
window.location.assign("/login"); window.location.assign(
expiredDigitalSessionPath(
window.location.pathname + window.location.search,
),
);
throw new Error("登录已过期"); throw new Error("登录已过期");
} }
if (!response.ok || data.success === false) if (!response.ok || data.success === false)
+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 = { export type Role = {
id: number; id: number;
+18 -2
View File
@@ -1,8 +1,13 @@
/** 私有页面会话路由,默认登录后进入数字人空间。 */ /** 私有页面会话路由,默认登录后进入数字人空间。 */
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { digitalLoginPath, safeDigitalReturnTo } from "@/lib/digital-routes";
const protectedRoutes = [ const protectedRoutes = [
"/discover", "/discover",
"/chats",
"/characters",
"/library",
"/profile",
"/dashboard", "/dashboard",
"/tasks", "/tasks",
"/schedule", "/schedule",
@@ -13,6 +18,7 @@ const protectedRoutes = [
const publicRoutes = ["/", "/login"]; const publicRoutes = ["/", "/login"];
const cookieName = process.env.ROLE_USER_SESSION_COOKIE || "role_user_session"; const cookieName = process.env.ROLE_USER_SESSION_COOKIE || "role_user_session";
/** 路由级登录保护;深链携带站内回跳目标,不丢失具体聊天地址。 */
export function proxy(request: NextRequest) { export function proxy(request: NextRequest) {
const path = request.nextUrl.pathname; const path = request.nextUrl.pathname;
const hasSession = Boolean(request.cookies.get(cookieName)?.value); const hasSession = Boolean(request.cookies.get(cookieName)?.value);
@@ -22,16 +28,26 @@ export function proxy(request: NextRequest) {
const isPublic = publicRoutes.includes(path); const isPublic = publicRoutes.includes(path);
if (isProtected && !hasSession) { if (isProtected && !hasSession) {
return NextResponse.redirect(new URL("/login", request.url)); return NextResponse.redirect(
new URL(digitalLoginPath(path + request.nextUrl.search), request.url),
);
} }
if (isPublic && hasSession) { if (isPublic && hasSession) {
return NextResponse.redirect(new URL("/discover", request.url)); return NextResponse.redirect(
new URL(
path === "/login"
? safeDigitalReturnTo(request.nextUrl.searchParams.get("next"))
: "/discover",
request.url,
),
);
} }
return NextResponse.next(); return NextResponse.next();
} }
/** 只拦截业务页面,不影响 BFF、静态资源和安装文件。 */
export const config = { export const config = {
matcher: [ matcher: [
"/((?!api|_next/static|_next/image|manifest.webmanifest|sw.js|.*\\..*).*)", "/((?!api|_next/static|_next/image|manifest.webmanifest|sw.js|.*\\..*).*)",
+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 }]);
});
+80
View File
@@ -0,0 +1,80 @@
/** 页面地址和登录深链回归,不访问真实账号或后端。 */
import test from "node:test";
import assert from "node:assert/strict";
import {
digitalTabs,
validDigitalId,
chatPath,
contentPath,
safeDigitalReturnTo,
digitalLoginPath,
expiredDigitalSessionPath,
} from "../src/lib/digital-routes.ts";
import { logoutRedirect } from "../src/lib/auth-redirect.ts";
test("主要页面与资源详情都有独立地址,身份页不覆盖旧工作台", () => {
assert.equal(new Set(Object.values(digitalTabs)).size, 4);
assert.equal(digitalTabs.me, "/profile");
assert.equal(chatPath("chat-1"), "/chats/chat-1");
assert.equal(
contentPath({ id: "role-1", kind: "character" }),
"/characters/role-1",
);
assert.equal(
contentPath({ id: "book-1", kind: "worldbook" }),
"/library/book-1",
);
assert.equal(
contentPath({ id: "style-1", kind: "preset" }),
"/library/style-1",
);
});
test("深链格式遵循后端资源 ID 边界", () => {
for (const id of ["chat-1", "a_b", "a".repeat(64)])
assert.equal(validDigitalId(id), true);
for (const id of ["", "a/b", "../other", "a?b", "a".repeat(65)])
assert.equal(validDigitalId(id), false);
});
test("登录恢复完整会话地址和发现页筛选,不增加固定首页跳转", () => {
for (const path of [
"/chats/chat-1",
"/characters/role-1",
"/library/book-1",
"/profile",
"/discover?q=hello&favorites=1",
]) {
assert.equal(safeDigitalReturnTo(path), path);
const login = new URL(digitalLoginPath(path), "https://stellar.invalid");
assert.equal(login.pathname, "/login");
assert.equal(login.searchParams.get("next"), path);
const expired = new URL(
expiredDigitalSessionPath(path),
"https://stellar.invalid",
);
assert.equal(expired.pathname, "/api/auth/logout");
assert.equal(
logoutRedirect(expired.searchParams.get("next")).headers.get("location"),
digitalLoginPath(path),
);
}
});
test("拒绝外站跳转、登录循环、接口及非法资源路径", () => {
for (const path of [
undefined,
null,
"https://outside.invalid",
"//outside.invalid",
"/\\outside.invalid",
"/login",
"/api/auth/logout",
"/chats/one/other",
"/chats/a%2fb",
"/characters/",
"/.//outside.invalid",
"/\n/outside.invalid",
])
assert.equal(safeDigitalReturnTo(path), "/discover", String(path));
});