Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ebf4308ec7 | |||
| a580422100 | |||
| 87e7a3aeb3 | |||
| 15f672e10d | |||
| 74d7caaca5 | |||
| 76abb3ecfb | |||
| a1fdc882e2 | |||
| 4132b80ee0 | |||
| da4f45525b | |||
| caa54c9b34 | |||
| 5fed13b6fb | |||
| ebb8a50eb6 | |||
| 16e989859c | |||
| cb5e004eb9 | |||
| fb46c0fdb5 | |||
| 3530219123 | |||
| fb8be9c460 | |||
| ae2b58e0b8 | |||
| 4638c72680 | |||
| 1f11112e04 | |||
| cac56740cc | |||
| f75a9abecc | |||
| afc474b0c4 | |||
| a963bec3f3 | |||
| 81079c7364 | |||
| 4079397625 | |||
| 9b2f7fc7cf | |||
| 981eab9dcf | |||
| d0442f5bb9 | |||
| a8ef8222c8 | |||
| 374ab1c606 | |||
| 5adb6eaec3 | |||
| 0f0aebe3a4 | |||
| b1c5610f23 | |||
| 1d045b7770 | |||
| a07ba77c5a | |||
| c4ea05ee0b | |||
| 781a735559 | |||
| b7433acba4 | |||
| 6b0dd6ea67 | |||
| 8415291772 | |||
| f8386d7b02 | |||
| 5fe2e2c75c | |||
| 3e1789e124 | |||
| 3efb2182b2 |
@@ -0,0 +1,21 @@
|
|||||||
|
# role-user Agent Skills
|
||||||
|
|
||||||
|
本目录存放 `role-user` 的项目级 Agent skill。规则参考 SeaCloud 项目的 agent skill 组织方式,并按当前员工端 Next.js、TypeScript、移动端工作台场景保留最小必要规范。
|
||||||
|
|
||||||
|
## 使用入口
|
||||||
|
|
||||||
|
1. 进入仓库后先读 `AGENTS.md` 和 `RTK.md`。
|
||||||
|
2. 创建或修改代码文件时,使用 `header-comment-sync` 保持中文文件头、导出声明和复杂逻辑注释同步。
|
||||||
|
3. 提交或推送代码时,使用 `chinese-commit-message` 生成英文 type 前缀加中文摘要的 commit message。
|
||||||
|
4. 所有 skill 的触达文件补齐规则只处理本次任务相关文件,不要求为了单次任务全仓扫描。
|
||||||
|
|
||||||
|
## 当前项目事实
|
||||||
|
|
||||||
|
- 应用类型:员工端 C 端移动优先工作台。
|
||||||
|
- 技术栈:Next.js App Router、React、TypeScript。
|
||||||
|
- 关键边界:BFF Route Handlers 负责会话与后端转发,前端不持久化 JWT 或明文密码。
|
||||||
|
|
||||||
|
## Skill 索引
|
||||||
|
|
||||||
|
- `header-comment-sync`:中文文件头、导出声明、复杂逻辑和风险边界注释。
|
||||||
|
- `chinese-commit-message`:中文提交信息格式。
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
---
|
||||||
|
name: chinese-commit-message
|
||||||
|
description: 在本仓库执行 git commit、整理提交说明或准备推送时使用,保持提交信息使用英文类型前缀加中文描述。
|
||||||
|
---
|
||||||
|
|
||||||
|
# 中文提交信息
|
||||||
|
|
||||||
|
## 何时使用
|
||||||
|
|
||||||
|
- 用户要求提交、推送或整理 commit message。
|
||||||
|
- 你准备执行 `git commit`。
|
||||||
|
- 需要总结当前 diff 的提交说明。
|
||||||
|
|
||||||
|
## 核心要求
|
||||||
|
|
||||||
|
1. 提交信息必须使用英文 type 加中文摘要,例如 `feat: 补齐员工端 agent skill 规范`。
|
||||||
|
2. 常用 type 优先使用 `feat`、`fix`、`refactor`、`docs`、`chore`。
|
||||||
|
3. 不强制 scope;只有模块边界非常清楚时才使用 `feat(auth): ...`。
|
||||||
|
4. 标题部分使用简洁中文,直接说明改动,不写“修改一下”“更新代码”这类空泛描述。
|
||||||
|
5. 非 trivial 改动建议补中文正文,用扁平 bullet 按文件或内容块说明关键动作。
|
||||||
|
6. 正文与标题之间空一行;正文每条 bullet 对应一个独立文件或明确内容块。
|
||||||
|
7. 如果用户指定提交信息,优先尊重用户原意,只做必要格式整理。
|
||||||
|
|
||||||
|
## 触达文件补齐
|
||||||
|
|
||||||
|
- 不要求为了提交信息单独全仓扫描。
|
||||||
|
- 提交前如果 diff 中的触达文件明显违反对应 skill 的触达补齐要求,应先修正当前相关链路,再整理 commit message。
|
||||||
|
- commit 正文应概括本次触达补齐,例如“补齐触达文件注释”“同步 README 目录说明”。
|
||||||
|
|
||||||
|
## 推荐结构
|
||||||
|
|
||||||
|
```text
|
||||||
|
feat: 补齐员工端 agent skill 规范
|
||||||
|
|
||||||
|
- .agents/README.md: 新增项目级 skill 索引和使用入口
|
||||||
|
- .agents/skills: 补充中文提交与注释同步规则
|
||||||
|
- AGENTS.md: 增加本地 skill 入口
|
||||||
|
```
|
||||||
|
|
||||||
|
## 不推荐写法
|
||||||
|
|
||||||
|
- `新增规则`
|
||||||
|
- `feat: add skills`
|
||||||
|
- `fix bug`
|
||||||
|
- `update`
|
||||||
|
- 复杂改动只有标题没有正文。
|
||||||
|
- 正文写成长段流水账或嵌套列表。
|
||||||
|
|
||||||
|
## 落地检查
|
||||||
|
|
||||||
|
- type 是否合理。
|
||||||
|
- 中文摘要是否覆盖主改动。
|
||||||
|
- 是否需要正文。
|
||||||
|
- 正文是否按文件或内容块归纳。
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
---
|
||||||
|
name: header-comment-sync
|
||||||
|
description: 在本仓库创建或修改 ts、tsx、js、jsx、mjs、cjs、vue、astro 文件时使用,保持中文文件头、导出声明、复杂逻辑和风险边界注释准确。
|
||||||
|
---
|
||||||
|
|
||||||
|
# 注释规范与同步
|
||||||
|
|
||||||
|
## 目标
|
||||||
|
|
||||||
|
让下一次进入文件的维护者能快速理解当前职责、关键约束和风险边界。注释解释“为什么”和“边界”,不复述代码表面行为。
|
||||||
|
|
||||||
|
## 适用场景
|
||||||
|
|
||||||
|
- 新增或修改页面、组件、Hook、store、service、utils、类型、配置或脚本文件。
|
||||||
|
- 修改 BFF Route Handler、鉴权、Cookie、权限、后端协议转换、缓存或错误兜底逻辑。
|
||||||
|
- 发现旧注释与当前代码行为不一致。
|
||||||
|
|
||||||
|
## 核心原则
|
||||||
|
|
||||||
|
- 注释使用中文,描述当前事实。
|
||||||
|
- 简单局部变量不强行注释。
|
||||||
|
- 文件头说明文件当前职责,1 到 2 行即可。
|
||||||
|
- 导出的函数、组件、Hook、类型、配置对象、service method 应有用途说明。
|
||||||
|
- 复杂兼容逻辑、后端协议、竞态锁、缓存、权限映射和会话安全边界需要短注释。
|
||||||
|
- TODO/FIXME 必须说明触发条件、剩余动作和可删除条件。
|
||||||
|
|
||||||
|
## 文件头规则
|
||||||
|
|
||||||
|
- 每个适用文件都要有准确文件头。
|
||||||
|
- 如果文件必须以 `"use client"` 或 `"use server"` 开头,文件头注释放在指令之后、导入之前。
|
||||||
|
- Vue 文件不为了补头注释重排模板结构;在 `<script>` 或 `<script setup>` 顶部补当前职责说明。
|
||||||
|
- 文件头不要写“本文件用于...”这类空话,直接说明业务角色。
|
||||||
|
|
||||||
|
```ts
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 员工端任务详情页,负责加载任务、发起流转动作并展示备注时间线。
|
||||||
|
*/
|
||||||
|
```
|
||||||
|
|
||||||
|
## JSDoc 与局部注释
|
||||||
|
|
||||||
|
- 导出的函数、类、组件、Hook、类型、常量和配置对象优先使用 JSDoc。
|
||||||
|
- 非导出但复杂的解析、格式化、请求构造、状态派生、回调工厂也要补。
|
||||||
|
- 只在局部逻辑确实有约束时使用行内注释,例如竞态锁、兼容字段、后端协议和临时迁移。
|
||||||
|
- 不要在每一行、每个 JSX 片段、每个短生命周期变量上堆注释。
|
||||||
|
|
||||||
|
## 触达文件补齐
|
||||||
|
|
||||||
|
- 不要求为了注释规范单独全仓扫描。
|
||||||
|
- 只要本次任务修改了适用文件,就顺手补齐明显缺失或过时的文件头、导出声明、共享类型、复杂回调和协议注释。
|
||||||
|
- 大文件可按触达区域优先,但同文件内裸露的顶层导出和共享类型应一起补。
|
||||||
|
- 如果一次补齐整个大文件会明显超出需求范围,至少补齐当前需求链路和顶层声明,并在交付说明里说明剩余范围。
|
||||||
|
|
||||||
|
## 不推荐的写法
|
||||||
|
|
||||||
|
- 注释只写“处理数据”“点击事件”这种无信息内容。
|
||||||
|
- 注释描述旧方案,和当前代码矛盾。
|
||||||
|
- 为每个 JSX 片段、简单赋值、短生命周期变量写注释。
|
||||||
|
- 用英文口号、emoji 或情绪化标记替代项目内中文说明。
|
||||||
|
|
||||||
|
## 落地检查
|
||||||
|
|
||||||
|
- 修改后的文件头是否准确。
|
||||||
|
- 新增/修改的导出声明是否有必要说明。
|
||||||
|
- 复杂逻辑是否解释了约束而不是复述代码。
|
||||||
|
- 旧注释是否仍然可信。
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3501/api
|
||||||
|
ROLE_USER_SESSION_COOKIE=role_user_session_develop
|
||||||
|
APP_ENV=develop
|
||||||
|
APP_ENV_LABEL=测试环境
|
||||||
|
PORT=3211
|
||||||
|
HOSTNAME=0.0.0.0
|
||||||
@@ -1,2 +1,6 @@
|
|||||||
ACCESS_MANAGE_API_BASE_URL=http://localhost:3500/api
|
ACCESS_MANAGE_API_BASE_URL=http://localhost:3500/api
|
||||||
ROLE_USER_SESSION_COOKIE=role_user_session
|
ROLE_USER_SESSION_COOKIE=role_user_session_local
|
||||||
|
APP_ENV=local
|
||||||
|
APP_ENV_LABEL=本地环境
|
||||||
|
PORT=3210
|
||||||
|
HOSTNAME=0.0.0.0
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3501/api
|
ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3501/api
|
||||||
ROLE_USER_SESSION_COOKIE=role_user_session_test
|
ROLE_USER_SESSION_COOKIE=role_user_session_develop
|
||||||
APP_ENV=test
|
APP_ENV=develop
|
||||||
APP_ENV_LABEL=测试环境
|
APP_ENV_LABEL=测试环境
|
||||||
PORT=3211
|
PORT=3211
|
||||||
HOSTNAME=0.0.0.0
|
HOSTNAME=0.0.0.0
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
@RTK.md
|
||||||
|
|
||||||
|
# role-user Agent 入口
|
||||||
|
|
||||||
|
## 必用 Skill
|
||||||
|
|
||||||
|
- 创建或修改 `ts`、`tsx`、`js`、`jsx`、`mjs`、`cjs`、`vue`、`astro` 文件时,使用 `./.agents/skills/header-comment-sync/SKILL.md`。
|
||||||
|
- 执行 `git commit`、整理提交说明或准备推送时,使用 `./.agents/skills/chinese-commit-message/SKILL.md`。
|
||||||
|
|
||||||
|
## 本地规则
|
||||||
|
|
||||||
|
- 先读 `RTK.md`,再按任务读取 `.agents/README.md` 中匹配的 skill。
|
||||||
|
- skill 的触达文件补齐只处理本次修改相关文件,不为单次任务全仓扫描。
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
def isProductionDeploy() {
|
|
||||||
return params.DEPLOY_ENV == "production"
|
|
||||||
}
|
|
||||||
|
|
||||||
def isTestDeploy() {
|
|
||||||
def branch = env.BRANCH_NAME ?: ""
|
|
||||||
return params.DEPLOY_ENV == "test" && !params.SKIP_DEPLOY && branch == env.TEST_BRANCH
|
|
||||||
}
|
|
||||||
|
|
||||||
@NonCPS
|
|
||||||
boolean isUserTriggeredBuild() {
|
|
||||||
return currentBuild.rawBuild.getCauses().any { cause ->
|
|
||||||
cause.class.name == "hudson.model.Cause\$UserIdCause"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pipeline {
|
|
||||||
agent any
|
|
||||||
|
|
||||||
options {
|
|
||||||
timestamps()
|
|
||||||
disableConcurrentBuilds()
|
|
||||||
buildDiscarder(logRotator(numToKeepStr: "30", artifactNumToKeepStr: "10"))
|
|
||||||
}
|
|
||||||
|
|
||||||
parameters {
|
|
||||||
choice(
|
|
||||||
name: "DEPLOY_ENV",
|
|
||||||
choices: ["test", "production"],
|
|
||||||
description: "test: develop 合并后自动部署测试环境;production: 仅允许手动输入 Tag 部署"
|
|
||||||
)
|
|
||||||
string(name: "RELEASE_TAG", defaultValue: "", description: "生产部署必填,必须是 Gitea 中已存在的 Tag")
|
|
||||||
booleanParam(name: "SKIP_DEPLOY", defaultValue: false, description: "只构建检查,不执行部署")
|
|
||||||
}
|
|
||||||
|
|
||||||
environment {
|
|
||||||
PROJECT_NAME = "role-user"
|
|
||||||
TEST_BRANCH = "develop"
|
|
||||||
DEPLOY_BASE_DIR = "/srv/www"
|
|
||||||
}
|
|
||||||
|
|
||||||
stages {
|
|
||||||
stage("Validate deploy policy") {
|
|
||||||
steps {
|
|
||||||
script {
|
|
||||||
if (isProductionDeploy()) {
|
|
||||||
if (!isUserTriggeredBuild()) {
|
|
||||||
error("生产环境禁止自动触发,只能在 Jenkins 手动 Build With Parameters。")
|
|
||||||
}
|
|
||||||
if (!params.RELEASE_TAG?.trim()) {
|
|
||||||
error("生产环境部署必须填写 RELEASE_TAG,且只能从项目 Tag 部署。")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (params.DEPLOY_ENV == "test" && env.BRANCH_NAME && env.BRANCH_NAME != env.TEST_BRANCH) {
|
|
||||||
echo "当前分支 ${env.BRANCH_NAME} 不是 ${env.TEST_BRANCH},本次只构建检查,不自动部署测试环境。"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage("Checkout production tag") {
|
|
||||||
when {
|
|
||||||
expression { isProductionDeploy() }
|
|
||||||
}
|
|
||||||
steps {
|
|
||||||
sh '''
|
|
||||||
set -euo pipefail
|
|
||||||
git fetch --tags --force origin '+refs/tags/*:refs/tags/*'
|
|
||||||
tag_commit="$(git rev-parse -q --verify "refs/tags/${RELEASE_TAG}^{commit}")"
|
|
||||||
if [ -z "${tag_commit}" ]; then
|
|
||||||
echo "Tag not found: ${RELEASE_TAG}" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
git checkout -f "${tag_commit}"
|
|
||||||
git log -1 --oneline
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage("Install") {
|
|
||||||
steps {
|
|
||||||
sh '''
|
|
||||||
corepack enable || true
|
|
||||||
pnpm install --frozen-lockfile
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage("Verify") {
|
|
||||||
steps {
|
|
||||||
sh '''
|
|
||||||
pnpm typecheck
|
|
||||||
pnpm lint
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage("Build") {
|
|
||||||
steps {
|
|
||||||
script {
|
|
||||||
sh isProductionDeploy() ? "pnpm build:prod" : "pnpm build:test"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage("Package standalone") {
|
|
||||||
steps {
|
|
||||||
sh '''
|
|
||||||
set -euo pipefail
|
|
||||||
rm -rf .deploy/role-user
|
|
||||||
mkdir -p .deploy/role-user/.next
|
|
||||||
cp -R .next/standalone/. .deploy/role-user/
|
|
||||||
cp -R .next/static .deploy/role-user/.next/static
|
|
||||||
cp -R public .deploy/role-user/public
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage("Deploy test") {
|
|
||||||
when {
|
|
||||||
expression { isTestDeploy() }
|
|
||||||
}
|
|
||||||
steps {
|
|
||||||
sh "bash deploy/jenkins/deploy-standalone.sh test .deploy/role-user"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage("Deploy production") {
|
|
||||||
when {
|
|
||||||
expression { isProductionDeploy() && !params.SKIP_DEPLOY }
|
|
||||||
}
|
|
||||||
steps {
|
|
||||||
sh "bash deploy/jenkins/deploy-standalone.sh production .deploy/role-user"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
# role-user
|
# role-user
|
||||||
|
|
||||||
员工端 C 端工作台,基于 `access-manage` 后端和 `role-admin` 管理后台建设。
|
星港 H5/Web 数字人空间,基于现有 `access-manage` 后端和 `role-admin` 管理后台改造。
|
||||||
|
|
||||||
当前已搭建 React + Next.js App Router + TypeScript 前端骨架,采用移动优先、PWA 友好的工作台形态。
|
采用 React + Next.js App Router + TypeScript,移动优先并适配桌面,保留原工作台兼容路由。
|
||||||
|
|
||||||
## 启动
|
## 启动
|
||||||
|
|
||||||
@@ -15,7 +15,8 @@ pnpm dev
|
|||||||
默认访问:
|
默认访问:
|
||||||
|
|
||||||
- 登录页:http://localhost:3210/login
|
- 登录页:http://localhost:3210/login
|
||||||
- 工作台:http://localhost:3210/dashboard
|
- 数字人空间:http://localhost:3210/discover
|
||||||
|
- 原工作台兼容入口:http://localhost:3210/dashboard
|
||||||
- 任务:http://localhost:3210/tasks
|
- 任务:http://localhost:3210/tasks
|
||||||
- 排班:http://localhost:3210/schedule
|
- 排班:http://localhost:3210/schedule
|
||||||
- 公告:http://localhost:3210/announcements
|
- 公告:http://localhost:3210/announcements
|
||||||
@@ -26,10 +27,22 @@ pnpm dev
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
ACCESS_MANAGE_API_BASE_URL=http://localhost:3500/api
|
ACCESS_MANAGE_API_BASE_URL=http://localhost:3500/api
|
||||||
ROLE_USER_SESSION_COOKIE=role_user_session
|
ROLE_USER_SESSION_COOKIE=role_user_session_local
|
||||||
|
APP_ENV=local
|
||||||
|
APP_ENV_LABEL=本地环境
|
||||||
|
PORT=3210
|
||||||
|
HOSTNAME=0.0.0.0
|
||||||
```
|
```
|
||||||
|
|
||||||
`ACCESS_MANAGE_API_BASE_URL` 指向 `access-manage` 服务端 API 根路径。员工登录会调用后端 `POST /api/auth/employee/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` 区分:
|
||||||
|
|
||||||
|
- `local`: 本地环境,默认使用 `.env.example` 复制出的 `.env.local`。
|
||||||
|
- `develop`: 测试环境,参考 `.env.develop.example`;`.env.test.example` 保留为兼容入口。
|
||||||
|
- `production`: 生产环境,参考 `.env.production.example`。
|
||||||
|
|
||||||
|
`APP_ENV_LABEL` 可覆盖页面右上角显示文案;未配置时会按 `APP_ENV` 自动显示“本地环境”“测试环境”或“生产环境”。Cookie 只在 `APP_ENV=production` 时设置 `Secure`,避免测试环境 HTTP 访问时登录后被浏览器丢弃 Cookie。
|
||||||
|
|
||||||
## 可用命令
|
## 可用命令
|
||||||
|
|
||||||
@@ -38,6 +51,10 @@ pnpm dev
|
|||||||
pnpm typecheck
|
pnpm typecheck
|
||||||
pnpm lint
|
pnpm lint
|
||||||
pnpm build
|
pnpm build
|
||||||
|
pnpm build:develop
|
||||||
|
pnpm build:prod
|
||||||
|
pnpm start:develop
|
||||||
|
pnpm start:prod
|
||||||
```
|
```
|
||||||
|
|
||||||
## 当前实现范围
|
## 当前实现范围
|
||||||
@@ -83,8 +100,12 @@ pnpm build
|
|||||||
|
|
||||||
## 文档
|
## 文档
|
||||||
|
|
||||||
|
- `.agents/README.md`: 本项目 Agent skill 索引和使用入口。
|
||||||
|
- `.agents/skills/chinese-commit-message/SKILL.md`: 中文提交信息规范。
|
||||||
|
- `.agents/skills/header-comment-sync/SKILL.md`: 中文文件头和注释同步规范。
|
||||||
- `docs/C_EMPLOYEE_APP_REQUIREMENTS.md`: C 端员工工作台需求文档。
|
- `docs/C_EMPLOYEE_APP_REQUIREMENTS.md`: C 端员工工作台需求文档。
|
||||||
- `docs/FULLSTACK_BACKEND_GAP_ANALYSIS.md`: C 端员工工作台三端缺口与改动范围分析。
|
- `docs/FULLSTACK_BACKEND_GAP_ANALYSIS.md`: C 端员工工作台三端缺口与改动范围分析。
|
||||||
|
- `AGENTS.md`: Codex/Agent 入口规则,转到 `RTK.md` 并登记本地 skill。
|
||||||
- `RTK.md`: 本项目 Codex/Agent 协作规则。
|
- `RTK.md`: 本项目 Codex/Agent 协作规则。
|
||||||
|
|
||||||
## 关联项目
|
## 关联项目
|
||||||
@@ -98,3 +119,104 @@ pnpm build
|
|||||||
- 不把密码、JWT 或权限 token 持久化到前端存储。
|
- 不把密码、JWT 或权限 token 持久化到前端存储。
|
||||||
- 员工端修改密码已通过 BFF 接入后端 `PATCH /api/auth/me/password`。
|
- 员工端修改密码已通过 BFF 接入后端 `PATCH /api/auth/me/password`。
|
||||||
- 公告、任务、排班已按正式后端接口接入列表、筛选、详情和员工端操作;后端临时不可用时页面保留业务空态。
|
- 公告、任务、排班已按正式后端接口接入列表、筛选、详情和员工端操作;后端临时不可用时页面保留业务空态。
|
||||||
|
|
||||||
|
## 数字人空间
|
||||||
|
|
||||||
|
- `/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` 仅在业务后端配置,前端不读取、不保存。
|
||||||
|
|
||||||
|
标签页图标采用 `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 字面量。
|
||||||
|
|
||||||
|
## 数字人独立页面与返回行为
|
||||||
|
|
||||||
|
| 地址 | 页面 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/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 在迁移页面目录或新增路由后不会复用上一版的路由声明;不清理整个构建产物目录。
|
||||||
|
|
||||||
|
## 聊天体验与会话管理
|
||||||
|
|
||||||
|
- `src/components/conversation-list.tsx` 提供服务端历史标题/消息搜索、置顶与重命名;`conversation-dialogs.tsx` 统一命名和分支确认的居中表单。
|
||||||
|
- 前台删除可在 30 秒内撤销,后台可恢复历史删除。分支保存名称、父会话和消息锚点,可跳回原故事。
|
||||||
|
- `use-chat-reading.ts` 按会话保存本标签页的消息锚点和偏移;上翻时新回复只提示,点击后才回到底部。
|
||||||
|
- `src/lib/digital-stream.ts` 必须收到 SSE done 才确认结束,异常断流保留部分内容。发送前保存请求标识,重试复用同一标识;刷新先对照服务端记录,避免重复发送。
|
||||||
|
- 发现页区分最近聊天、收藏和新角色;详情可展开备用开场全文。账号身份为新会话默认值,当前会话设定仅影响自己的后续回复,NSFW 是账号范围。
|
||||||
|
|
||||||
|
以上管理功能需要配套后端 `019_conversation_management.sql` 迁移及接口;不要只发布前台。
|
||||||
|
|
||||||
|
## C端增长体验
|
||||||
|
|
||||||
|
需配套后端 `020_digital_growth.sql`,不能只发布前台。登录页提供游客体验,凭据仅存HttpOnly Cookie;游客可登录独立账号承接原故事和已用额度。`src/app/api/auth/guest/route.ts` 为游客BFF,同源校验位于 `src/lib/auth-origin.ts`,代理下使用公网Host校验;`src/lib/auth-input.ts` 在JSON解析前限制公开登录请求为8KB。
|
||||||
|
|
||||||
|
- `growth-journey.tsx`:读取站内运营卡片后上报本次访问,实际可见时才确认曝光,不向外部渠道发消息。
|
||||||
|
- `growth-recommendations.tsx`:展示服务端推荐及原因、支持跳过,推荐回执随独立详情路由承接,避免普通入口误用旧推荐来源。
|
||||||
|
- `growth-profile.tsx`:选择最多12个兴趣、查看真实剩余额度,明确开启或关闭自动记忆。会员权益由后台授予,前台没有虚构购买或支付成功状态。
|
||||||
|
- `growth-chat.tsx`:故事内查看/更正/移除记忆、手动添加背景,提供回答点赞与原因反馈;评价按具体回复保存。
|
||||||
|
- `growth-analytics.ts`:事件队列按账号隔离,最多200条,单批20条,保留UUID重试,过期事件不补报;仅上报事件和资源ID,不采集正文、密码或设备指纹。
|
||||||
|
- `growth.ts`:个人权益协议、反馈合并读取与推荐来源工具,避免每条消息各发一条评价查询。
|
||||||
|
|
||||||
|
自动记忆是用户明确事实提取和历史原文摘录,不是额外调用模型生成的智能总结。删除的同一来源不会被后台任务重新加入。每日次数与字符预算分别展示和计算,字符数不是供应商Token账单;空失败释放次数,部分回复计次,灵感也消耗一次。推荐实验与现有UI实验独立;前端不自行决定分组、发放权益或计算扣减结果。
|
||||||
|
|
||||||
|
验证新增 `tests/growth-analytics.test.mjs`,覆盖账号切换、UUID重试、批次上限、请求期间新事件保留及反向代理同源校验。真机、真实数据库并发和支付验收不能被这些测试替代。
|
||||||
|
|||||||
@@ -1,71 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
deploy_env="${1:?Usage: deploy-standalone.sh test|production [artifact_dir]}"
|
|
||||||
artifact_dir="${2:-.deploy/role-user}"
|
|
||||||
|
|
||||||
case "${deploy_env}" in
|
|
||||||
test)
|
|
||||||
env_file=".env.test"
|
|
||||||
;;
|
|
||||||
production)
|
|
||||||
env_file=".env.production"
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
echo "Unknown deploy environment: ${deploy_env}" >&2
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
if [[ ! -f "${artifact_dir}/server.js" ]]; then
|
|
||||||
echo "Standalone server.js not found in ${artifact_dir}" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
project_name="${PROJECT_NAME:-role-user}"
|
|
||||||
base_dir="${DEPLOY_BASE_DIR:-/srv/www}"
|
|
||||||
target_dir="${DEPLOY_TARGET_DIR:-${base_dir}/${deploy_env}/${project_name}}"
|
|
||||||
deploy_remote="${DEPLOY_REMOTE:-}"
|
|
||||||
release_id="${BUILD_NUMBER:-manual}-$(git rev-parse --short=12 HEAD 2>/dev/null || date +%Y%m%d%H%M%S)"
|
|
||||||
|
|
||||||
remote_shell() {
|
|
||||||
if [[ -n "${deploy_remote}" ]]; then
|
|
||||||
ssh "${deploy_remote}" "$@"
|
|
||||||
else
|
|
||||||
bash -lc "$*"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
remote_copy() {
|
|
||||||
local source_dir="$1"
|
|
||||||
local dest_dir="$2"
|
|
||||||
|
|
||||||
if [[ -n "${deploy_remote}" ]]; then
|
|
||||||
rsync -az --delete "${source_dir}/" "${deploy_remote}:${dest_dir}/"
|
|
||||||
else
|
|
||||||
mkdir -p "${dest_dir}"
|
|
||||||
rsync -az --delete "${source_dir}/" "${dest_dir}/"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
release_dir="${target_dir}/releases/${release_id}"
|
|
||||||
shared_dir="${target_dir}/shared"
|
|
||||||
|
|
||||||
remote_shell "mkdir -p '${release_dir}' '${shared_dir}' '${target_dir}/logs'"
|
|
||||||
remote_copy "${artifact_dir}" "${release_dir}"
|
|
||||||
remote_shell "
|
|
||||||
set -euo pipefail
|
|
||||||
if [ -f '${shared_dir}/${env_file}' ]; then
|
|
||||||
ln -sfn '../../shared/${env_file}' '${release_dir}/${env_file}'
|
|
||||||
else
|
|
||||||
echo 'Missing ${shared_dir}/${env_file}; create it before starting the service.' >&2
|
|
||||||
fi
|
|
||||||
ln -sfn '${release_dir}' '${target_dir}/current'
|
|
||||||
"
|
|
||||||
|
|
||||||
if [[ -n "${DEPLOY_POST_DEPLOY_CMD:-}" ]]; then
|
|
||||||
remote_shell "cd '${target_dir}/current' && ${DEPLOY_POST_DEPLOY_CMD}"
|
|
||||||
else
|
|
||||||
echo "Deployed ${project_name} ${deploy_env} to ${target_dir}/current"
|
|
||||||
echo "Start with: set -a; source ${target_dir}/shared/${env_file}; set +a; node ${target_dir}/current/server.js"
|
|
||||||
fi
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
# 环境拆分与流水线规则
|
|
||||||
|
|
||||||
`role-user` 是 Next.js standalone 服务。测试环境和生产环境通过独立部署目录、独立运行时环境变量和独立后端 API 地址拆分。
|
|
||||||
|
|
||||||
## 环境约定
|
|
||||||
|
|
||||||
| 环境 | 触发方式 | 代码依据 | 构建命令 | 默认部署目录 | 默认端口 | 后端 API |
|
|
||||||
| --- | --- | --- | --- | --- | --- | --- |
|
|
||||||
| 测试环境 | `develop` 合并后自动触发 Jenkins | `develop` 最新提交 | `pnpm build:test` | `/srv/www/test/role-user/current` | `3211` | `http://127.0.0.1:3501/api` |
|
|
||||||
| 生产环境 | Jenkins 手动触发 | Gitea 项目 Tag | `pnpm build:prod` | `/srv/www/production/role-user/current` | `3210` | `http://127.0.0.1:3500/api` |
|
|
||||||
|
|
||||||
生产环境禁止因代码合并自动部署。生产部署时必须在 Jenkins 参数中选择 `DEPLOY_ENV=production` 并填写已存在的 `RELEASE_TAG`。
|
|
||||||
|
|
||||||
## Jenkins 参数
|
|
||||||
|
|
||||||
| 参数 | 说明 |
|
|
||||||
| --- | --- |
|
|
||||||
| `DEPLOY_ENV` | `test` 或 `production`。默认 `test`。 |
|
|
||||||
| `RELEASE_TAG` | 生产环境必填,必须是 Gitea 仓库中已存在的 Tag。 |
|
|
||||||
| `SKIP_DEPLOY` | 为 `true` 时只执行安装、检查、构建,不部署。 |
|
|
||||||
|
|
||||||
`Jenkinsfile` 会强制校验:
|
|
||||||
|
|
||||||
- 测试环境只在 `develop` 分支自动部署。
|
|
||||||
- 生产环境必须手动触发。
|
|
||||||
- 生产环境必须填写 `RELEASE_TAG`。
|
|
||||||
- 生产环境构建会先 checkout 到该 Tag 对应的提交,再部署。
|
|
||||||
|
|
||||||
## 运行时环境变量
|
|
||||||
|
|
||||||
真实环境变量必须留在服务器,不提交到仓库。
|
|
||||||
|
|
||||||
部署脚本默认读取:
|
|
||||||
|
|
||||||
```text
|
|
||||||
/srv/www/test/role-user/shared/.env.test
|
|
||||||
/srv/www/production/role-user/shared/.env.production
|
|
||||||
```
|
|
||||||
|
|
||||||
示例文件:
|
|
||||||
|
|
||||||
```text
|
|
||||||
.env.test.example
|
|
||||||
.env.production.example
|
|
||||||
```
|
|
||||||
|
|
||||||
`ACCESS_MANAGE_API_BASE_URL` 是服务端 BFF 使用的运行时变量,不加 `NEXT_PUBLIC_`,不会暴露到浏览器 bundle。Cookie 名测试和生产应分开,避免同域下会话互相覆盖。
|
|
||||||
|
|
||||||
## standalone 产物
|
|
||||||
|
|
||||||
`next.config.ts` 已启用 `output: "standalone"`。Jenkins 构建后会打包:
|
|
||||||
|
|
||||||
```text
|
|
||||||
.next/standalone
|
|
||||||
.next/static
|
|
||||||
public
|
|
||||||
```
|
|
||||||
|
|
||||||
部署脚本会发布到:
|
|
||||||
|
|
||||||
```text
|
|
||||||
${DEPLOY_BASE_DIR}/${DEPLOY_ENV}/role-user/releases/<build>-<commit>
|
|
||||||
```
|
|
||||||
|
|
||||||
并更新:
|
|
||||||
|
|
||||||
```text
|
|
||||||
${DEPLOY_BASE_DIR}/${DEPLOY_ENV}/role-user/current
|
|
||||||
```
|
|
||||||
|
|
||||||
如果 Jenkins 不在目标服务器上运行,可以配置:
|
|
||||||
|
|
||||||
```text
|
|
||||||
DEPLOY_REMOTE=user@server
|
|
||||||
```
|
|
||||||
|
|
||||||
## 生产发布流程
|
|
||||||
|
|
||||||
1. 在需要发布的提交上创建 Tag。
|
|
||||||
2. 推送 Tag 到 Gitea。
|
|
||||||
3. Jenkins 手动 Build With Parameters。
|
|
||||||
4. 选择 `DEPLOY_ENV=production`。
|
|
||||||
5. 填写 `RELEASE_TAG`。
|
|
||||||
6. 执行构建部署。
|
|
||||||
|
|
||||||
示例:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git tag -a v2026.06.05-1 -m "role-user production release 2026-06-05"
|
|
||||||
git push origin v2026.06.05-1
|
|
||||||
```
|
|
||||||
@@ -3,13 +3,16 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev -p 3210",
|
"dev": "APP_ENV=local APP_ENV_LABEL=本地环境 ACCESS_MANAGE_API_BASE_URL=http://localhost:3500/api ROLE_USER_SESSION_COOKIE=role_user_session_local next dev -p 3210",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"build:test": "next build",
|
"build: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 build",
|
||||||
"build:prod": "next build",
|
"build:test": "pnpm build:develop",
|
||||||
|
"build: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 build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
|
"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",
|
||||||
"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",
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
packages:
|
||||||
|
- '.'
|
||||||
|
|
||||||
|
allowBuilds:
|
||||||
|
sharp: true
|
||||||
|
unrs-resolver: true
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
{
|
||||||
|
"note": "角色设定由星港项目原创,封面沿用用户授权参考的现有 SeaChat公开角色资源,私人体验。",
|
||||||
|
"female": [
|
||||||
|
{
|
||||||
|
"index": 0,
|
||||||
|
"id": "ee061032-332b-4f65-b312-b4a488d49ef0",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/dc9c91be-cc40-4426-9733-918d630a6644",
|
||||||
|
"title": "Dahlia-Single mother"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 1,
|
||||||
|
"id": "8683dd96-b3ca-41bb-aa4d-3888fb246db8",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/6a2ade59-d048-45fc-8488-9c6e9da2c54c",
|
||||||
|
"title": "Morgan"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 2,
|
||||||
|
"id": "9a2afe98-884b-45d4-a88f-5b785437b4c2",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/dd157230-e605-4c1b-b091-d4fc59f735be",
|
||||||
|
"title": "Sillia (Arrogant Elf Princess)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 3,
|
||||||
|
"id": "c7147e4c-cb1c-40ca-9791-2ff5c84c3afc",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/aff51642-cbc7-46f0-b483-3a42f6de910f",
|
||||||
|
"title": "Kiara │ Betrayed Childhood Friend"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 4,
|
||||||
|
"id": "c3989993-1cc5-4ed1-9c8a-675f85cc0a1e",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/4608cfea-0df0-4b72-b7f0-54efbfea18d2",
|
||||||
|
"title": "Dragon Princess Kirin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 5,
|
||||||
|
"id": "36cd7214-eb33-4bcd-b6b2-29e0c45df6dd",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/d67b8d7c-e25e-4aa4-b456-41139177e091",
|
||||||
|
"title": "Natalia \"Still Your Sitter\""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 6,
|
||||||
|
"id": "2880d71c-4988-497b-874f-0c25569f0bdb",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/6085d595-46f0-4fbe-845a-b23652e007d0",
|
||||||
|
"title": "Roxanne"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 7,
|
||||||
|
"id": "b9a62845-014e-4faa-a96e-f428f1120ec8",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/f3432df4-52fc-423e-a0bf-3c31593766d3",
|
||||||
|
"title": "Selina Ellison"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 8,
|
||||||
|
"id": "9dfbcdd7-d132-41a9-a399-81b4d77d9df5",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/9c6758c6-9aeb-42bc-9c21-de6e65fa68f8",
|
||||||
|
"title": "Orelia"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 9,
|
||||||
|
"id": "35f2df7b-f7f1-4a7b-b048-323bd316e445",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/0b5b615b-2efb-4cec-aa80-369a8bb3bed8",
|
||||||
|
"title": "You are a Rich Girl's Bodyguard"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 10,
|
||||||
|
"id": "0084a3eb-203a-4064-8982-4aeecfc05e42",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/568add55-df11-4105-943f-e2edb8be7909",
|
||||||
|
"title": "Grace"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 11,
|
||||||
|
"id": "3424d41f-56c5-4a61-bbd0-ff45d4480822",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/abbf0b7c-9dc8-4e56-8c19-bc0d72f5c795",
|
||||||
|
"title": "The Colonel's Doomed Empire"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 12,
|
||||||
|
"id": "5f9b6411-b487-4f7d-9951-1eba794d4565",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/5638a2cc-0d8c-42d0-b5d0-2b482a605ea8",
|
||||||
|
"title": "Ursula & Fiona"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 13,
|
||||||
|
"id": "9be1233a-30bf-409a-b66e-3d0752b960a5",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/b7480b45-edb5-4a54-8f42-fcad1f854f65",
|
||||||
|
"title": "Ena"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 14,
|
||||||
|
"id": "9aa3b4a8-c065-41a9-b3c7-7eff8dd63101",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/b30edd5d-0b67-402b-bdb1-b4ce4eddb905",
|
||||||
|
"title": "🦝🗑 Luna | The Hungry Raccoon Girl"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 15,
|
||||||
|
"id": "9910bceb-dec2-4cf5-926c-6efd83def7a9",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/78306f70-aa69-4d21-8837-3a7d149be75f",
|
||||||
|
"title": "Lilith \"Sorry... You're Mine Now\""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 16,
|
||||||
|
"id": "fbbd76b0-40f9-43e0-9e93-fdd6528eb1a3",
|
||||||
|
"source": "https://resource.seachat.ai/by-id/d6e9bc09-3d31-4899-84e1-ef6d4de1be78",
|
||||||
|
"title": "Mitsuri Kanroji"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"male": [
|
||||||
|
{
|
||||||
|
"id": "c85f0f30-6883-4d48-b858-dd8734677e83",
|
||||||
|
"name": "Simon Riley AKA Ghost"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "7f61d36c-78b7-406b-8147-69df810eb978",
|
||||||
|
"name": "Alistair | Vampire hunter"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "6bda6248-1cf0-4a5b-9403-8b72019d0bae",
|
||||||
|
"name": "Riot Sorel | Before the Curtains Close"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 125 KiB |
|
After Width: | Height: | Size: 266 KiB |
|
After Width: | Height: | Size: 868 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 149 KiB |
|
After Width: | Height: | Size: 272 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 283 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 2.8 MiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 183 KiB |
|
After Width: | Height: | Size: 585 KiB |
|
After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 318 KiB |
|
After Width: | Height: | Size: 5.3 KiB |
@@ -1,13 +1 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="stellar" x1="12" y1="13" x2="49" y2="49" gradientUnits="userSpaceOnUse"><stop stop-color="#F4D5A3"/><stop offset="1" stop-color="#F5A8D9"/></linearGradient></defs><rect x="2" y="2" width="60" height="60" rx="18" fill="#211628"/><path d="M24 14h16c9 0 15 6 15 15v4c0 9-6 15-15 15H27L14 54l3-13c-4-3-6-7-6-12 0-9 5-15 13-15Z" fill="url(#stellar)"/><path d="M33 20c2.2 6.5 4.5 8.8 11 11-6.5 2.2-8.8 4.5-11 11-2.2-6.5-4.5-8.8-11-11 6.5-2.2 8.8-4.5 11-11Z" fill="#211628"/><circle cx="51" cy="13" r="5" fill="#F7B7DD" stroke="#211628" stroke-width="3"/></svg>
|
||||||
<rect width="512" height="512" rx="96" fill="#ffffff"/>
|
|
||||||
<rect x="32" y="32" width="448" height="448" rx="72" fill="#f4f4f6"/>
|
|
||||||
<path d="M346 90 238 238l5 9 44 58c26-22 18-56 34-58 16-1 56 2 79-49 23-51-30-94-54-108Z" fill="#ffffff"/>
|
|
||||||
<path d="M164 86c31-2 59 12 75 36l70 86c17 22 44 35 74 33 29-2 54-18 68-42l-90 163c-1 3-3 5-5 8l-1 1c-14 22-38 38-66 40-28 2-54-10-71-30l-73-89c-17-24-45-39-76-37-29 2-54 18-68 42l92-166c13-25 39-43 70-45Z" fill="#131313"/>
|
|
||||||
<path d="M346 90 238 238l5 9 44 58c26-22 18-56 34-58 16-1 56 2 79-49 23-51-30-94-54-108Z" fill="url(#shine)"/>
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="shine" x1="441" x2="201" y1="58" y2="236" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#ffffff"/>
|
|
||||||
<stop offset="1" stop-color="#000000"/>
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 868 B After Width: | Height: | Size: 640 B |
|
After Width: | Height: | Size: 6.1 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="stellar" x1="12" y1="13" x2="49" y2="49" gradientUnits="userSpaceOnUse"><stop stop-color="#F4D5A3"/><stop offset="1" stop-color="#F5A8D9"/></linearGradient></defs><rect x="2" y="2" width="60" height="60" rx="18" fill="#211628"/><path d="M24 14h16c9 0 15 6 15 15v4c0 9-6 15-15 15H27L14 54l3-13c-4-3-6-7-6-12 0-9 5-15 13-15Z" fill="url(#stellar)"/><path d="M33 20c2.2 6.5 4.5 8.8 11 11-6.5 2.2-8.8 4.5-11 11-2.2-6.5-4.5-8.8-11-11 6.5-2.2 8.8-4.5 11-11Z" fill="#211628"/><circle cx="51" cy="13" r="5" fill="#F7B7DD" stroke="#211628" stroke-width="3"/></svg>
|
||||||
|
After Width: | Height: | Size: 640 B |
@@ -1,38 +1,48 @@
|
|||||||
|
/** 星港登录页,使用独立用户账号,无公开注册。 */
|
||||||
|
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";
|
||||||
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="login-page">
|
<main className="stellar-login">
|
||||||
<section className="login-hero">
|
<section className="stellar-login-story">
|
||||||
<div className="login-brand-line">
|
<Link href="/" className="stellar-login-brand">
|
||||||
<span className="brand-mark" aria-hidden />
|
✦{" "}
|
||||||
<span>Role User</span>
|
<span>
|
||||||
</div>
|
星港 <small>STELLAR</small>
|
||||||
<p className="hero-kicker">Employee Console</p>
|
</span>
|
||||||
<h1>门店工作,清晰处理</h1>
|
</Link>
|
||||||
<p>排班、任务、公告和账号安全集中在同一个移动端工作区。</p>
|
<div>
|
||||||
<div className="login-preview" aria-hidden>
|
<p>YOUR PRIVATE UNIVERSE</p>
|
||||||
<div className="login-preview__top">
|
<h1>
|
||||||
<span />
|
每一段相遇,
|
||||||
<span />
|
<br />
|
||||||
</div>
|
都有下一章。
|
||||||
<div className="login-preview__body">
|
</h1>
|
||||||
<strong>08:30</strong>
|
<span>
|
||||||
<span>早班 · 正常</span>
|
与你心动的角色对话,
|
||||||
</div>
|
<br />
|
||||||
<div className="login-preview__grid">
|
在世界的另一端,写下属于你的故事。
|
||||||
<span />
|
</span>
|
||||||
<span />
|
|
||||||
<span />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<small>虚构相遇,真实灵感。</small>
|
||||||
</section>
|
</section>
|
||||||
<section className="login-panel" aria-label="员工登录">
|
<section className="stellar-login-panel">
|
||||||
<div className="login-panel__header">
|
<span className="stellar-login-star">✧</span>
|
||||||
<h2>员工登录</h2>
|
<h2>欢迎回到星港</h2>
|
||||||
<p>使用手机号和临时密码进入工作台。</p>
|
<p>使用你的星港账号,继续未完的故事。</p>
|
||||||
</div>
|
<LoginForm returnTo={returnTo} />
|
||||||
<LoginForm />
|
<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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/** 我的对话独立页面,浏览器历史与页面地址保持一致。 */
|
||||||
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
|
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
||||||
|
export const metadata = { title: "我的对话 · 星港" };
|
||||||
|
|
||||||
|
/** 读取本页面的私有首屏数据。 */
|
||||||
|
export default function Page() {
|
||||||
|
return <DigitalPage tab="chats" path="/chats" />;
|
||||||
|
}
|
||||||
@@ -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}` : ""}`}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/** 灵感书架独立页面,浏览器历史与页面地址保持一致。 */
|
||||||
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
|
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
||||||
|
export const metadata = { title: "灵感书架 · 星港" };
|
||||||
|
|
||||||
|
/** 读取本页面的私有首屏数据。 */
|
||||||
|
export default function Page() {
|
||||||
|
return <DigitalPage tab="library" path="/library" />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/** 路由数据加载反馈,避免切换会话时暂时显示上一段聊天内容。 */
|
||||||
|
export default function DigitalLoading() {
|
||||||
|
return (
|
||||||
|
<main className="dh-app dh-loading" role="status" aria-live="polite">
|
||||||
|
正在打开页面…
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/** 我的身份独立页面,浏览器历史与页面地址保持一致。 */
|
||||||
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
|
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
||||||
|
export const metadata = { title: "我的身份 · 星港" };
|
||||||
|
|
||||||
|
/** 读取本页面的私有首屏数据。 */
|
||||||
|
export default function Page() {
|
||||||
|
return <DigitalPage tab="me" path="/profile" />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/** 游客令牌与复用凭据只保存在HttpOnly Cookie,体验额度由后端控制。 */
|
||||||
|
import { sameOriginRequest } from "@/lib/auth-origin";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { backendRequest, backendErrorResponse } from "@/lib/backend";
|
||||||
|
import {
|
||||||
|
getSessionCookieName,
|
||||||
|
setSessionToken,
|
||||||
|
getSessionToken,
|
||||||
|
} from "@/lib/session";
|
||||||
|
import { getAppEnv } from "@/lib/environment";
|
||||||
|
/** 同源创建体验,已有登录身份不能被游客入口覆盖。 */
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
if (!sameOriginRequest(request))
|
||||||
|
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
||||||
|
const store = await cookies(),
|
||||||
|
name = getSessionCookieName();
|
||||||
|
if ((await getSessionToken()) && !store.has(`${name}_guest`))
|
||||||
|
return Response.json({ message: "当前已经登录" }, { status: 409 });
|
||||||
|
try {
|
||||||
|
const result = await backendRequest<{ token: string }>(
|
||||||
|
"/digital-guest/session",
|
||||||
|
{ method: "POST", token: store.get(`${name}_guest_token`)?.value ?? "" },
|
||||||
|
);
|
||||||
|
await setSessionToken(result.token);
|
||||||
|
for (const [suffix, value] of [
|
||||||
|
["_guest", "1"],
|
||||||
|
["_guest_token", result.token],
|
||||||
|
])
|
||||||
|
store.set(name + suffix, value, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: getAppEnv() === "production",
|
||||||
|
sameSite: "lax",
|
||||||
|
path: "/",
|
||||||
|
maxAge: 7 * 86400,
|
||||||
|
});
|
||||||
|
return Response.json({ success: true });
|
||||||
|
} catch (e) {
|
||||||
|
return backendErrorResponse(e, "体验暂不可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,31 +1,48 @@
|
|||||||
import { setSessionToken } from "@/lib/session";
|
/** 数字人登录 BFF,令牌仅写入 HttpOnly Cookie,不返回浏览器。 */
|
||||||
|
import { readLoginInput } from "@/lib/auth-input";
|
||||||
|
import { sameOriginRequest } from "@/lib/auth-origin";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { getSessionCookieName, setSessionToken } from "@/lib/session";
|
||||||
import { BackendError, backendRequest } from "@/lib/backend";
|
import { BackendError, backendRequest } from "@/lib/backend";
|
||||||
import type { LoginResponse } from "@/lib/types";
|
import type { LoginResponse } from "@/lib/types";
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
if (!sameOriginRequest(request))
|
||||||
|
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const cookieStore = await cookies(),
|
||||||
const result = await backendRequest<LoginResponse>("/auth/employee/login", {
|
cookieName = getSessionCookieName();
|
||||||
|
const body = await readLoginInput(request);
|
||||||
|
const result = await backendRequest<LoginResponse>("/auth/digital/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
username: body.username,
|
username: body.username,
|
||||||
password: body.password
|
password: body.password,
|
||||||
|
guestToken: cookieStore.has(`${cookieName}_guest`)
|
||||||
|
? cookieStore.get(`${cookieName}_guest_token`)?.value
|
||||||
|
: undefined,
|
||||||
}),
|
}),
|
||||||
token: ""
|
token: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
await setSessionToken(result.token);
|
await setSessionToken(result.token);
|
||||||
|
cookieStore.delete(`${cookieName}_guest`);
|
||||||
|
|
||||||
return Response.json({
|
return Response.json({
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
user: result.user,
|
user: result.user,
|
||||||
tokenType: result.tokenType,
|
tokenType: result.tokenType,
|
||||||
expiresIn: result.expiresIn
|
expiresIn: result.expiresIn,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const status = error instanceof BackendError ? error.status : 500;
|
const status =
|
||||||
|
error instanceof BackendError
|
||||||
|
? error.status
|
||||||
|
: error instanceof SyntaxError || error instanceof RangeError
|
||||||
|
? 400
|
||||||
|
: 500;
|
||||||
const message = error instanceof Error ? error.message : "登录失败";
|
const message = error instanceof Error ? error.message : "登录失败";
|
||||||
|
|
||||||
return Response.json({ success: false, data: null, message }, { status });
|
return Response.json({ success: false, data: null, message }, { status });
|
||||||
|
|||||||
@@ -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";
|
import { clearSessionToken } from "@/lib/session";
|
||||||
|
|
||||||
|
/** 客户端主动退出时仅清理 Cookie,由页面处理导航。 */
|
||||||
export async function POST() {
|
export async function POST() {
|
||||||
await clearSessionToken();
|
await clearSessionToken();
|
||||||
return Response.json({ success: true, data: null });
|
return Response.json({ success: true, data: null });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 会话过期或链接退出后跳转站内页面,不使用服务端监听地址。 */
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
await clearSessionToken();
|
await clearSessionToken();
|
||||||
const next = request.nextUrl.searchParams.get("next") || "/login";
|
return logoutRedirect(request.nextUrl.searchParams.get("next"));
|
||||||
|
|
||||||
return NextResponse.redirect(new URL(next, request.url));
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
/** 数字人 BFF:HttpOnly 会话只在服务端转发,白名单阻止前台访问实验管理。 */
|
||||||
|
import { getBackendBaseUrl } from "@/lib/backend";
|
||||||
|
import { getSessionToken } from "@/lib/session";
|
||||||
|
|
||||||
|
/** 限制 BFF 接收体积,后端校验之前也不会无界缓存请求。 */
|
||||||
|
async function readBody(request: Request) {
|
||||||
|
if (!request.body) return undefined;
|
||||||
|
const reader = request.body.getReader(),
|
||||||
|
decoder = new TextDecoder();
|
||||||
|
let bytes = 0,
|
||||||
|
body = "";
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
bytes += value.byteLength;
|
||||||
|
if (bytes > 65536) {
|
||||||
|
await reader.cancel();
|
||||||
|
throw new RangeError("请求内容过长");
|
||||||
|
}
|
||||||
|
body += decoder.decode(value, { stream: true });
|
||||||
|
}
|
||||||
|
return body + decoder.decode();
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** 私有会话不缓存;取消下游请求会中断上游 SSE。 */
|
||||||
|
async function proxy(
|
||||||
|
request: Request,
|
||||||
|
context: { params: Promise<{ path: string[] }> },
|
||||||
|
) {
|
||||||
|
const { path } = await context.params;
|
||||||
|
const joined = path.join("/");
|
||||||
|
if (
|
||||||
|
!/^(bootstrap|profile|exposure|growth(?:\/(?:preferences|recommendations|events|inbox\/[a-zA-Z0-9_-]+))?|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|restore|suggestions|feedback|memories(?:\/[a-zA-Z0-9_-]+)?|style-policy|messages\/[a-zA-Z0-9_-]+))?)?)$/.test(
|
||||||
|
joined,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return Response.json({ message: "接口不存在" }, { status: 404 });
|
||||||
|
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 {
|
||||||
|
if (!origin || new URL(origin).host !== request.headers.get("host"))
|
||||||
|
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
||||||
|
} catch {
|
||||||
|
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const search =
|
||||||
|
request.method === "GET" && joined === "conversations"
|
||||||
|
? new URL(request.url).searchParams.get("q")
|
||||||
|
: null;
|
||||||
|
const query =
|
||||||
|
search === null ? "" : `?q=${encodeURIComponent(search.slice(0, 100))}`;
|
||||||
|
const token = await getSessionToken();
|
||||||
|
if (!token) return Response.json({ message: "请先登录" }, { status: 401 });
|
||||||
|
const headers = new Headers({
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${getBackendBaseUrl().replace(/\/$/, "")}/digital/${joined}${query}`,
|
||||||
|
{
|
||||||
|
method: request.method,
|
||||||
|
headers,
|
||||||
|
body: request.method === "GET" ? undefined : await readBody(request),
|
||||||
|
cache: "no-store",
|
||||||
|
signal: request.signal,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return new Response(response.body, {
|
||||||
|
status: response.status,
|
||||||
|
headers: {
|
||||||
|
"Content-Type":
|
||||||
|
response.headers.get("content-type") ?? "application/json",
|
||||||
|
"Cache-Control": "no-store, no-transform",
|
||||||
|
"X-Accel-Buffering": "no",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof RangeError)
|
||||||
|
return Response.json({ message: error.message }, { status: 413 });
|
||||||
|
return Response.json(
|
||||||
|
{ message: "连接暂时不可用,请稍后重试" },
|
||||||
|
{ status: 502 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** 转发前台读取。 */
|
||||||
|
export const GET = proxy;
|
||||||
|
/** 转发创建与生成。 */
|
||||||
|
export const POST = proxy;
|
||||||
|
/** 转发用户资料保存。 */
|
||||||
|
export const PUT = proxy;
|
||||||
|
/** 转发会话偏好和固定记忆。 */
|
||||||
|
export const PATCH = proxy;
|
||||||
|
/** 转发用户自己的会话删除。 */
|
||||||
|
export const DELETE = proxy;
|
||||||
@@ -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%;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,39 +1,53 @@
|
|||||||
|
/** 站点元信息与视口配置,保留系统缩放以支持可访问性。 */
|
||||||
import type { Metadata, Viewport } from "next";
|
import type { Metadata, Viewport } from "next";
|
||||||
import { connection } from "next/server";
|
import { connection } from "next/server";
|
||||||
|
|
||||||
|
import { getAppEnvLabel } from "@/lib/environment";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
|
/** 星港品牌与安装元数据。 */
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "员工工作台",
|
title: "星港 · 数字人空间",
|
||||||
description: "门店员工日常任务、排班、公告和个人中心",
|
description: "与有故事的人相遇,让每一段对话继续生长",
|
||||||
manifest: "/manifest.webmanifest",
|
manifest: "/manifest.webmanifest",
|
||||||
icons: {
|
icons: {
|
||||||
icon: "/icon.svg",
|
icon: [
|
||||||
apple: "/icon.svg"
|
{ url: "/stellar-icon-v2.svg", type: "image/svg+xml" },
|
||||||
|
{ url: "/favicon.ico?v=stellar-2", sizes: "any" },
|
||||||
|
],
|
||||||
|
apple: "/stellar-icon-180-v2.png",
|
||||||
},
|
},
|
||||||
appleWebApp: {
|
appleWebApp: {
|
||||||
capable: true,
|
capable: true,
|
||||||
title: "员工工作台",
|
title: "星港 · 数字人空间",
|
||||||
statusBarStyle: "default"
|
statusBarStyle: "default",
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 允许缩放并覆盖安全区,由页面布局补齐系统边距。 */
|
||||||
export const viewport: Viewport = {
|
export const viewport: Viewport = {
|
||||||
width: "device-width",
|
width: "device-width",
|
||||||
initialScale: 1,
|
initialScale: 1,
|
||||||
maximumScale: 1,
|
viewportFit: "cover",
|
||||||
themeColor: "#ffffff"
|
|
||||||
|
themeColor: "#101010",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
/** 全站根布局,私有数字人页面自行负责业务鉴权。 */
|
||||||
|
export default async function RootLayout({
|
||||||
|
children,
|
||||||
|
}: Readonly<{ children: React.ReactNode }>) {
|
||||||
await connection();
|
await connection();
|
||||||
|
|
||||||
const environmentLabel = process.env.APP_ENV_LABEL || "生产环境";
|
const environmentLabel = getAppEnvLabel();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html lang="zh-CN">
|
<html lang="zh-CN">
|
||||||
<body>
|
<body>
|
||||||
<div className="environment-badge" aria-label={`当前环境:${environmentLabel}`}>
|
<div
|
||||||
|
className="environment-badge"
|
||||||
|
aria-label={`当前环境:${environmentLabel}`}
|
||||||
|
>
|
||||||
{environmentLabel}
|
{environmentLabel}
|
||||||
</div>
|
</div>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -1,21 +1,24 @@
|
|||||||
|
/** 数字人空间 PWA 元数据,保留原有安装机制。 */
|
||||||
import type { MetadataRoute } from "next";
|
import type { MetadataRoute } from "next";
|
||||||
|
|
||||||
export default function manifest(): MetadataRoute.Manifest {
|
export default function manifest(): MetadataRoute.Manifest {
|
||||||
return {
|
return {
|
||||||
name: "role-user 员工工作台",
|
name: "星港 · 数字人空间",
|
||||||
short_name: "员工工作台",
|
short_name: "星港",
|
||||||
description: "门店员工任务、公告、排班和个人中心",
|
description: "你的私人数字人空间",
|
||||||
start_url: "/dashboard",
|
start_url: "/discover",
|
||||||
scope: "/",
|
scope: "/",
|
||||||
display: "standalone",
|
display: "standalone",
|
||||||
background_color: "#f4f4f6",
|
background_color: "#141218",
|
||||||
theme_color: "#ffffff",
|
theme_color: "#141218",
|
||||||
icons: [
|
icons: [
|
||||||
|
{ src: "/stellar-icon-192-v2.png", sizes: "192x192", type: "image/png" },
|
||||||
|
{ src: "/stellar-icon-512-v2.png", sizes: "512x512", type: "image/png" },
|
||||||
{
|
{
|
||||||
src: "/icon.svg",
|
src: "/stellar-icon-v2.svg",
|
||||||
sizes: "any",
|
sizes: "any",
|
||||||
type: "image/svg+xml"
|
type: "image/svg+xml",
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
/** 默认入口进入数字人空间,登录由目标页统一校验。 */
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
/** 私有站点首页。 */
|
||||||
export default function HomePage() {
|
export default function HomePage() {
|
||||||
redirect("/dashboard");
|
redirect("/discover");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话命名和分支确认共用居中表单,失败时保留输入并允许重试。 */
|
||||||
|
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||||
|
|
||||||
|
/** 提交过程锁定重复操作,Escape 与取消均保留原会话。 */
|
||||||
|
export function ConversationTitleDialog({
|
||||||
|
heading,
|
||||||
|
initialTitle,
|
||||||
|
preview,
|
||||||
|
onCancel,
|
||||||
|
onSubmit,
|
||||||
|
}: {
|
||||||
|
heading: string;
|
||||||
|
initialTitle: string;
|
||||||
|
preview?: ReactNode;
|
||||||
|
onCancel: () => void;
|
||||||
|
onSubmit: (title: string) => Promise<void>;
|
||||||
|
}) {
|
||||||
|
const ref = useRef<HTMLDialogElement>(null),
|
||||||
|
lock = useRef(false),
|
||||||
|
id = useId();
|
||||||
|
const [title, setTitle] = useState(initialTitle),
|
||||||
|
[busy, setBusy] = useState(false),
|
||||||
|
[error, setError] = useState("");
|
||||||
|
useEffect(() => {
|
||||||
|
const dialog = ref.current;
|
||||||
|
dialog?.showModal();
|
||||||
|
return () => dialog?.close();
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<dialog
|
||||||
|
ref={ref}
|
||||||
|
className="dh-delete-dialog dh-title-dialog"
|
||||||
|
aria-labelledby={id}
|
||||||
|
onCancel={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!lock.current) onCancel();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (lock.current || !title.trim()) return;
|
||||||
|
lock.current = true;
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await onSubmit(title.trim());
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "保存失败,请重试");
|
||||||
|
} finally {
|
||||||
|
lock.current = false;
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h2 id={id}>{heading}</h2>
|
||||||
|
{preview}
|
||||||
|
<label>
|
||||||
|
对话名称
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
value={title}
|
||||||
|
maxLength={120}
|
||||||
|
required
|
||||||
|
onChange={(e) => setTitle(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
<div className="dh-delete-actions">
|
||||||
|
<button type="button" disabled={busy} onClick={onCancel}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button type="submit" disabled={busy || !title.trim()}>
|
||||||
|
{busy ? "正在保存…" : "确认"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话列表的服务端搜索、命名和置顶;删除仍通过独立确认流程处理。 */
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { digital, type Card, type Summary } from "@/lib/digital";
|
||||||
|
import { ConversationRow } from "./conversation-row";
|
||||||
|
import { ConversationTitleDialog } from "./conversation-dialogs";
|
||||||
|
|
||||||
|
/** 搜索覆盖历史标题和消息;迟到查询不能覆盖新关键词或恢复全部列表。 */
|
||||||
|
export function ConversationList({
|
||||||
|
summaries,
|
||||||
|
cards,
|
||||||
|
disabled,
|
||||||
|
onDelete,
|
||||||
|
onRefresh,
|
||||||
|
onNotice,
|
||||||
|
}: {
|
||||||
|
summaries: Summary[];
|
||||||
|
cards: Card[];
|
||||||
|
disabled: boolean;
|
||||||
|
onDelete: (summary: Summary) => void;
|
||||||
|
onRefresh: () => Promise<void>;
|
||||||
|
onNotice: (message: string) => void;
|
||||||
|
}) {
|
||||||
|
const [query, setQuery] = useState(""),
|
||||||
|
[results, setResults] = useState<Summary[]>([]),
|
||||||
|
[resultQuery, setResultQuery] = useState(""),
|
||||||
|
[loading, setLoading] = useState(false),
|
||||||
|
[error, setError] = useState(""),
|
||||||
|
[swiped, setSwiped] = useState<string | null>(null),
|
||||||
|
[renaming, setRenaming] = useState<Summary | null>(null),
|
||||||
|
[pending, setPending] = useState<string | null>(null);
|
||||||
|
const lock = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!query.trim()) return;
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
digital<Summary[]>(
|
||||||
|
`conversations?q=${encodeURIComponent(query.trim())}`,
|
||||||
|
"GET",
|
||||||
|
undefined,
|
||||||
|
controller.signal,
|
||||||
|
)
|
||||||
|
.then((items) => {
|
||||||
|
if (!controller.signal.aborted) {
|
||||||
|
setResults(items);
|
||||||
|
setResultQuery(query.trim());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
if (!controller.signal.aborted)
|
||||||
|
setError(e instanceof Error ? e.message : "搜索失败");
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!controller.signal.aborted) setLoading(false);
|
||||||
|
});
|
||||||
|
}, 250);
|
||||||
|
return () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
controller.abort();
|
||||||
|
};
|
||||||
|
}, [query, summaries]);
|
||||||
|
async function save(
|
||||||
|
summary: Summary,
|
||||||
|
patch: { title?: string; pinned?: boolean },
|
||||||
|
) {
|
||||||
|
await digital(`conversations/${summary.id}`, "PATCH", patch);
|
||||||
|
setResults((items) =>
|
||||||
|
items.map((item) =>
|
||||||
|
item.id === summary.id ? { ...item, ...patch } : item,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await onRefresh();
|
||||||
|
}
|
||||||
|
const items = [...(query.trim() ? resultQuery === query.trim() ? results : [] : summaries)].sort((a,b) => Number(!!b.pinned)-Number(!!a.pinned) || Date.parse(b.updatedAt)-Date.parse(a.updatedAt));
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<label className="dh-conversation-search">
|
||||||
|
搜索对话或消息
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
value={query}
|
||||||
|
maxLength={100}
|
||||||
|
placeholder="输入对话名称或聊天内容…"
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{query.trim() && !error && (loading || resultQuery !== query.trim()) && (
|
||||||
|
<p role="status">正在搜索…</p>
|
||||||
|
)}
|
||||||
|
{query.trim() && error && <p role="alert">{error}</p>}
|
||||||
|
<div className="dh-conversation-list">
|
||||||
|
{items.map((summary) => (
|
||||||
|
<div key={summary.id}>
|
||||||
|
<ConversationRow
|
||||||
|
summary={summary}
|
||||||
|
card={cards.find((card) => card.id === summary.characterId)}
|
||||||
|
revealed={swiped === summary.id}
|
||||||
|
disabled={disabled || pending === summary.id}
|
||||||
|
onReveal={setSwiped}
|
||||||
|
onDelete={() => onDelete(summary)}
|
||||||
|
/>
|
||||||
|
<div className="dh-conversation-tools">
|
||||||
|
<button
|
||||||
|
disabled={disabled || !!pending}
|
||||||
|
onClick={async () => {
|
||||||
|
if (lock.current) return;
|
||||||
|
lock.current = true;
|
||||||
|
setPending(summary.id);
|
||||||
|
try {
|
||||||
|
await save(summary, { pinned: !summary.pinned });
|
||||||
|
onNotice(summary.pinned ? "已取消置顶" : "对话已置顶");
|
||||||
|
} catch (e) {
|
||||||
|
onNotice(e instanceof Error ? e.message : "操作失败");
|
||||||
|
} finally {
|
||||||
|
setPending(null);
|
||||||
|
lock.current = false;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{summary.pinned ? "取消置顶" : "置顶"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
disabled={disabled || !!pending}
|
||||||
|
onClick={() => setRenaming(summary)}
|
||||||
|
>
|
||||||
|
重命名
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{query.trim() &&
|
||||||
|
resultQuery === query.trim() &&
|
||||||
|
!loading &&
|
||||||
|
!error &&
|
||||||
|
!items.length && <p className="dh-form-note">没有找到匹配的对话。</p>}
|
||||||
|
{renaming && (
|
||||||
|
<ConversationTitleDialog
|
||||||
|
heading="重命名对话"
|
||||||
|
initialTitle={renaming.title}
|
||||||
|
onCancel={() => setRenaming(null)}
|
||||||
|
onSubmit={async (title) => {
|
||||||
|
await save(renaming, { title });
|
||||||
|
setRenaming(null);
|
||||||
|
onNotice("对话名称已保存");
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话列表的水平滑动操作与删除确认;纵向滑动继续交给页面滚动。 */
|
||||||
|
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 type { Card, Summary } from "@/lib/digital";
|
||||||
|
|
||||||
|
/** 一次只展开一条会话;拖动不会触发进入会话,桌面和键盘保留显式删除入口。 */
|
||||||
|
export function ConversationRow({
|
||||||
|
summary,
|
||||||
|
card,
|
||||||
|
revealed,
|
||||||
|
disabled,
|
||||||
|
onReveal,
|
||||||
|
onDelete,
|
||||||
|
}: {
|
||||||
|
summary: Summary;
|
||||||
|
card?: Card;
|
||||||
|
revealed: boolean;
|
||||||
|
disabled: boolean;
|
||||||
|
onReveal: (id: string | null) => 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<HTMLAnchorElement>) {
|
||||||
|
if (
|
||||||
|
disabled ||
|
||||||
|
e.button !== 0 ||
|
||||||
|
e.metaKey ||
|
||||||
|
e.ctrlKey ||
|
||||||
|
e.shiftKey ||
|
||||||
|
e.altKey
|
||||||
|
)
|
||||||
|
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<HTMLAnchorElement>) {
|
||||||
|
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<HTMLAnchorElement>, 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>
|
||||||
|
<Link
|
||||||
|
href={chatPath(summary.id)}
|
||||||
|
className={`dh-conversation-open ${drag !== null ? "is-dragging" : ""}`}
|
||||||
|
style={{
|
||||||
|
transform: `translateX(${drag ?? (revealed ? -distance : 0)}px)`,
|
||||||
|
}}
|
||||||
|
aria-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 (disabled || (suppressClick.current && e.detail !== 0)) {
|
||||||
|
e.preventDefault();
|
||||||
|
suppressClick.current = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (revealed) {
|
||||||
|
e.preventDefault();
|
||||||
|
onReveal(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 封面地址沿用服务端目录,不在小型服务器做图片转换。 */}
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src={card?.cover || "/icon.svg"} alt="" draggable={false} />
|
||||||
|
<div>
|
||||||
|
<h3>
|
||||||
|
{summary.pinned ? "置顶 · " : ""}
|
||||||
|
{summary.title}
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
{summary.lastMessage || card?.description || "继续这段私人对话"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<small>
|
||||||
|
{new Date(summary.updatedAt).toLocaleDateString("zh-CN", {
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
})}
|
||||||
|
</small>
|
||||||
|
</Link>
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
/* 登录页与数字人前台共享深色金色基调。 */
|
||||||
|
.stellar-login {
|
||||||
|
min-height: 100dvh;
|
||||||
|
background: #141218;
|
||||||
|
color: #f4eef4;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1.1fr 1fr;
|
||||||
|
font-family: Inter, "PingFang SC", sans-serif;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
.stellar-login-story {
|
||||||
|
padding: 45px 60px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: space-between;
|
||||||
|
background:
|
||||||
|
radial-gradient(ellipse at 60% 50%, #8e635644, transparent 65%),
|
||||||
|
linear-gradient(135deg, #281d29, #19141c);
|
||||||
|
border-right: 1px solid #ffffff0b;
|
||||||
|
}
|
||||||
|
.stellar-login-brand {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
color: #e0b888;
|
||||||
|
text-decoration: none;
|
||||||
|
font-size: 38px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.stellar-login-brand span {
|
||||||
|
font-size: 26px;
|
||||||
|
color: #f4eef4;
|
||||||
|
}
|
||||||
|
.stellar-login-brand small {
|
||||||
|
font-size: 9px;
|
||||||
|
letter-spacing: 3px;
|
||||||
|
display: block;
|
||||||
|
color: #b09da9;
|
||||||
|
}
|
||||||
|
.stellar-login-story > div > p {
|
||||||
|
font-size: 10px;
|
||||||
|
letter-spacing: 4px;
|
||||||
|
color: #e0b888;
|
||||||
|
}
|
||||||
|
.stellar-login-story h1 {
|
||||||
|
font-size: 44px;
|
||||||
|
line-height: 1.5;
|
||||||
|
font-weight: 400;
|
||||||
|
letter-spacing: -1px;
|
||||||
|
margin: 22px 0;
|
||||||
|
}
|
||||||
|
.stellar-login-story > div > span {
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 2;
|
||||||
|
color: #b5a6b7;
|
||||||
|
}
|
||||||
|
.stellar-login-story > small {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #9b879e;
|
||||||
|
}
|
||||||
|
.stellar-login-panel {
|
||||||
|
max-width: 470px;
|
||||||
|
width: 100%;
|
||||||
|
padding: 70px 40px;
|
||||||
|
margin: auto;
|
||||||
|
}
|
||||||
|
.stellar-login-panel h2 {
|
||||||
|
font-size: 26px;
|
||||||
|
font-weight: 500;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
.stellar-login-panel > p {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #aa9aaf;
|
||||||
|
margin-bottom: 32px;
|
||||||
|
}
|
||||||
|
.stellar-login-star {
|
||||||
|
font-size: 45px;
|
||||||
|
color: #e0b888;
|
||||||
|
}
|
||||||
|
.stellar-login-panel > .login-form {
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
.stellar-login-panel .login-form label {
|
||||||
|
color: #c5b7c9;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.stellar-login-panel .input-wrap {
|
||||||
|
background: #211c25;
|
||||||
|
border: 1px solid #ffffff18;
|
||||||
|
border-radius: 10px;
|
||||||
|
color: #ac9bb2;
|
||||||
|
}
|
||||||
|
.stellar-login-panel .input-wrap:focus-within {
|
||||||
|
border-color: #e0b88888;
|
||||||
|
}
|
||||||
|
.stellar-login-panel input {
|
||||||
|
color: #f4eef4;
|
||||||
|
font-size: 16px;
|
||||||
|
background: none;
|
||||||
|
}
|
||||||
|
.stellar-login-panel input::placeholder {
|
||||||
|
color: #796d80;
|
||||||
|
}
|
||||||
|
.stellar-login-panel .primary-button {
|
||||||
|
background: #e0b888;
|
||||||
|
color: #2b1d11;
|
||||||
|
border-radius: 10px;
|
||||||
|
min-height: 46px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.stellar-login-panel > small {
|
||||||
|
display: block;
|
||||||
|
text-align: center;
|
||||||
|
color: #776a7d;
|
||||||
|
font-size: 10px;
|
||||||
|
margin-top: 28px;
|
||||||
|
}
|
||||||
|
.stellar-login-panel .form-error {
|
||||||
|
color: #ffa6a6;
|
||||||
|
}
|
||||||
|
.stellar-login-panel .icon-button {
|
||||||
|
color: #b3a1b9;
|
||||||
|
}
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
.stellar-login {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
min-height: 100dvh;
|
||||||
|
}
|
||||||
|
.stellar-login-story {
|
||||||
|
padding: 30px 25px 22px;
|
||||||
|
border: 0;
|
||||||
|
background: radial-gradient(ellipse at 80% 50%, #8e635638, transparent 70%);
|
||||||
|
}
|
||||||
|
.stellar-login-brand {
|
||||||
|
font-size: 25px;
|
||||||
|
}
|
||||||
|
.stellar-login-brand span {
|
||||||
|
font-size: 21px;
|
||||||
|
}
|
||||||
|
.stellar-login-brand small {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.stellar-login-story > div {
|
||||||
|
padding-top: 30px;
|
||||||
|
}
|
||||||
|
.stellar-login-story h1 {
|
||||||
|
font-size: 29px;
|
||||||
|
line-height: 1.5;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
.stellar-login-story > div > p {
|
||||||
|
font-size: 8px;
|
||||||
|
letter-spacing: 3px;
|
||||||
|
}
|
||||||
|
.stellar-login-story > div > span {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.stellar-login-story > small {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.stellar-login-panel {
|
||||||
|
padding: 12px 25px 45px;
|
||||||
|
max-width: 470px;
|
||||||
|
}
|
||||||
|
.stellar-login-star {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.stellar-login-panel h2 {
|
||||||
|
font-size: 21px;
|
||||||
|
margin: 10px 0;
|
||||||
|
}
|
||||||
|
.stellar-login-panel > p {
|
||||||
|
font-size: 11px;
|
||||||
|
margin-bottom: 25px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body:has(.stellar-login) .environment-badge {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话内记忆管理和回答质量反馈,所有写入仍由后端校验消息归属与版本。 */
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { digital } from "@/lib/digital";
|
||||||
|
import {
|
||||||
|
feedbackFor,
|
||||||
|
invalidateFeedback,
|
||||||
|
type GrowthState,
|
||||||
|
} from "@/lib/growth";
|
||||||
|
type Memory = { id: string; kind: string; content: string; version: number };
|
||||||
|
/** 延迟读取记忆列表,删除保留服务端源键,后台任务不能将它重新创建。 */
|
||||||
|
export function GrowthChat({
|
||||||
|
account,
|
||||||
|
conversation,
|
||||||
|
busy,
|
||||||
|
onExpanded,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
conversation: string;
|
||||||
|
busy: boolean;
|
||||||
|
onExpanded: () => void;
|
||||||
|
}) {
|
||||||
|
const [memories, setMemories] = useState<Memory[]>([]),
|
||||||
|
[draft, setDraft] = useState(""),
|
||||||
|
[error, setError] = useState(""),
|
||||||
|
[pending, setPending] = useState(false),
|
||||||
|
[rights, setRights] = useState<GrowthState["entitlement"] | null>(null),
|
||||||
|
[open, setOpen] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
const c = new AbortController();
|
||||||
|
digital<GrowthState>("growth", "GET", undefined, c.signal)
|
||||||
|
.then((r) => setRights(r.entitlement))
|
||||||
|
.catch(() => {});
|
||||||
|
return () => c.abort();
|
||||||
|
}, [account, busy]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const c = new AbortController();
|
||||||
|
digital<Memory[]>(
|
||||||
|
`conversations/${conversation}/memories`,
|
||||||
|
"GET",
|
||||||
|
undefined,
|
||||||
|
c.signal,
|
||||||
|
)
|
||||||
|
.then(setMemories)
|
||||||
|
.catch((e) => {
|
||||||
|
if (!c.signal.aborted) setError(e.message);
|
||||||
|
});
|
||||||
|
return () => c.abort();
|
||||||
|
}, [conversation, open]);
|
||||||
|
async function mutate(path: string, method: "POST" | "PATCH", body: unknown) {
|
||||||
|
if (pending) return;
|
||||||
|
setPending(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await digital(path, method, body);
|
||||||
|
setMemories(
|
||||||
|
await digital<Memory[]>(`conversations/${conversation}/memories`),
|
||||||
|
);
|
||||||
|
setDraft("");
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "操作失败");
|
||||||
|
} finally {
|
||||||
|
setPending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<details
|
||||||
|
className="dh-growth-chat"
|
||||||
|
onToggle={(e) => {
|
||||||
|
setOpen(e.currentTarget.open);
|
||||||
|
if (e.currentTarget.open) onExpanded();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<summary>
|
||||||
|
故事记忆与权益 {rights ? `· 剩余 ${rights.remaining} 次` : ""}
|
||||||
|
</summary>
|
||||||
|
{account.startsWith("guest:") && (
|
||||||
|
<p>
|
||||||
|
<Link href="/login?next=%2Fchats">登录并保留这段体验故事</Link>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="dh-form-note">
|
||||||
|
记忆仅用于当前故事。自动事实需要在“我的”中开启;这里可以更正为手动记忆,或移除不想继续使用的内容。
|
||||||
|
</p>
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
{memories.map((m) => (
|
||||||
|
<MemoryRow
|
||||||
|
key={`${m.id}:${m.version}`}
|
||||||
|
memory={m}
|
||||||
|
disabled={busy || pending}
|
||||||
|
onSave={(content) =>
|
||||||
|
mutate(`conversations/${conversation}/memories/${m.id}`, "PATCH", {
|
||||||
|
version: m.version,
|
||||||
|
content,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
onDelete={() =>
|
||||||
|
mutate(`conversations/${conversation}/memories/${m.id}`, "PATCH", {
|
||||||
|
version: m.version,
|
||||||
|
deleted: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<label>
|
||||||
|
添加重要背景
|
||||||
|
<textarea
|
||||||
|
value={draft}
|
||||||
|
maxLength={600}
|
||||||
|
onChange={(e) => setDraft(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
disabled={busy || pending || !draft.trim()}
|
||||||
|
onClick={() =>
|
||||||
|
mutate(`conversations/${conversation}/memories`, "POST", {
|
||||||
|
content: draft,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
记住这件事
|
||||||
|
</button>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function MemoryRow({
|
||||||
|
memory,
|
||||||
|
disabled,
|
||||||
|
onSave,
|
||||||
|
onDelete,
|
||||||
|
}: {
|
||||||
|
memory: Memory;
|
||||||
|
disabled: boolean;
|
||||||
|
onSave: (value: string) => void;
|
||||||
|
onDelete: () => void;
|
||||||
|
}) {
|
||||||
|
const [text, setText] = useState(memory.content);
|
||||||
|
return (
|
||||||
|
<div className="dh-growth-memory">
|
||||||
|
<small>
|
||||||
|
{memory.kind === "summary"
|
||||||
|
? "历史摘录"
|
||||||
|
: memory.kind === "fact"
|
||||||
|
? "明确记忆"
|
||||||
|
: "手动背景"}
|
||||||
|
</small>
|
||||||
|
<textarea
|
||||||
|
aria-label="记忆内容"
|
||||||
|
value={text}
|
||||||
|
maxLength={600}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
disabled={disabled || !text.trim() || text === memory.content}
|
||||||
|
onClick={() => onSave(text)}
|
||||||
|
>
|
||||||
|
保存更正
|
||||||
|
</button>
|
||||||
|
<button disabled={disabled} onClick={onDelete}>
|
||||||
|
不再使用
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
/** 点踩原因与指定回复绑定,不采集新的聊天正文。 */
|
||||||
|
export function ReplyFeedback({
|
||||||
|
account,
|
||||||
|
conversation,
|
||||||
|
messageId,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
conversation: string;
|
||||||
|
messageId: string;
|
||||||
|
}) {
|
||||||
|
const [rating, setRating] = useState<"up" | "down" | "">(""),
|
||||||
|
[reason, setReason] = useState(""),
|
||||||
|
[choosing, setChoosing] = useState(false),
|
||||||
|
[busy, setBusy] = useState(false),
|
||||||
|
[error, setError] = useState("");
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
feedbackFor(account, conversation)
|
||||||
|
.then((items) => {
|
||||||
|
const r = items.find((i) => i.messageId === messageId);
|
||||||
|
if (alive && r) {
|
||||||
|
setRating(r.rating);
|
||||||
|
setReason(r.reason);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [account, conversation, messageId]);
|
||||||
|
async function save(value: "up" | "down", why = "") {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await digital(`conversations/${conversation}/feedback`, "POST", {
|
||||||
|
messageId,
|
||||||
|
rating: value,
|
||||||
|
reason: why,
|
||||||
|
});
|
||||||
|
invalidateFeedback(account, conversation);
|
||||||
|
setRating(value);
|
||||||
|
setReason(why);
|
||||||
|
setChoosing(false);
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "反馈失败");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="dh-growth-feedback">
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
aria-pressed={rating === "up"}
|
||||||
|
onClick={() => void save("up")}
|
||||||
|
>
|
||||||
|
{rating === "up" ? "已赞同" : "喜欢这个回答"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
aria-pressed={rating === "down"}
|
||||||
|
onClick={() => setChoosing(!choosing)}
|
||||||
|
>
|
||||||
|
{rating === "down" ? "已反馈" : "不太满意"}
|
||||||
|
</button>
|
||||||
|
{choosing && (
|
||||||
|
<label>
|
||||||
|
原因
|
||||||
|
<select value={reason} onChange={(e) => setReason(e.target.value)}>
|
||||||
|
<option value="">选择原因</option>
|
||||||
|
<option value="forgot">忘记设定</option>
|
||||||
|
<option value="repetition">重复内容</option>
|
||||||
|
<option value="slow">回复太慢</option>
|
||||||
|
<option value="off_topic">偏离故事</option>
|
||||||
|
<option value="other">其他</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
disabled={busy || !reason}
|
||||||
|
onClick={() => void save("down", reason)}
|
||||||
|
>
|
||||||
|
提交反馈
|
||||||
|
</button>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
{error && <small role="alert">{error}</small>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"use client";
|
||||||
|
/** 站内运营卡片与漏斗入口,先读取回访分群再上报本次访问,避免把沉默用户立即改为活跃。 */
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { digital } from "@/lib/digital";
|
||||||
|
import { trackGrowth, flushGrowth, type GrowthState } from "@/lib/growth";
|
||||||
|
/** 不向外部渠道发通知;仅实际可见的站内卡片确认曝光。 */
|
||||||
|
export function GrowthJourney({
|
||||||
|
account,
|
||||||
|
page,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
page: string;
|
||||||
|
}) {
|
||||||
|
const [cards, setCards] = useState<GrowthState["inbox"]>([]),
|
||||||
|
box = useRef<HTMLDivElement>(null),
|
||||||
|
visited = useRef("");
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
const controller = new AbortController();
|
||||||
|
digital<GrowthState>("growth", "GET", undefined, controller.signal)
|
||||||
|
.then((s) => {
|
||||||
|
if (alive) setCards(s.inbox);
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
.finally(() => {
|
||||||
|
if (alive && visited.current !== `${account}:${page}`) {
|
||||||
|
visited.current = `${account}:${page}`;
|
||||||
|
trackGrowth(account, "page_view", page);
|
||||||
|
void flushGrowth(account);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const timer = setInterval(() => void flushGrowth(account), 5000),
|
||||||
|
hide = () => void flushGrowth(account);
|
||||||
|
window.addEventListener("pagehide", hide);
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
controller.abort();
|
||||||
|
clearInterval(timer);
|
||||||
|
window.removeEventListener("pagehide", hide);
|
||||||
|
void flushGrowth(account);
|
||||||
|
};
|
||||||
|
}, [account, page]);
|
||||||
|
useEffect(() => {
|
||||||
|
const element = box.current;
|
||||||
|
if (!element || !cards.length) return;
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
if (entries.some((e) => e.isIntersecting)) {
|
||||||
|
for (const card of cards)
|
||||||
|
void digital(`growth/inbox/${card.id}`, "POST", {
|
||||||
|
action: "exposure",
|
||||||
|
}).catch(() => {});
|
||||||
|
observer.disconnect();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ threshold: 0.5 },
|
||||||
|
);
|
||||||
|
observer.observe(element);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [cards]);
|
||||||
|
return cards.length ? (
|
||||||
|
<aside ref={box} className="dh-growth-banner">
|
||||||
|
{cards.map((c) => (
|
||||||
|
<div key={c.id}>
|
||||||
|
<strong>{c.title}</strong>
|
||||||
|
<p>{c.content}</p>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
await digital(`growth/inbox/${c.id}`, "POST", {
|
||||||
|
action: "exposure",
|
||||||
|
})
|
||||||
|
.then(() =>
|
||||||
|
digital(`growth/inbox/${c.id}`, "POST", { action: "click" }),
|
||||||
|
)
|
||||||
|
.catch(() => {});
|
||||||
|
setCards([]);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
知道了,继续探索
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</aside>
|
||||||
|
) : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"use client";
|
||||||
|
/** 个人权益和主动兴趣选择,自动记忆须用户开启,关闭后不再提取和检索自动内容。 */
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { digital, type Card } from "@/lib/digital";
|
||||||
|
import type { GrowthState } from "@/lib/growth";
|
||||||
|
/** 所有额度和偏好读取服务端真实状态,不展示虚构购买按钮。 */
|
||||||
|
export function GrowthProfile({
|
||||||
|
account,
|
||||||
|
cards,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
cards: Card[];
|
||||||
|
}) {
|
||||||
|
const [state, setState] = useState<GrowthState | null>(null),
|
||||||
|
[error, setError] = useState(""),
|
||||||
|
[notice, setNotice] = useState(""),
|
||||||
|
[busy, setBusy] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
const c = new AbortController();
|
||||||
|
digital<GrowthState>("growth", "GET", undefined, c.signal)
|
||||||
|
.then(setState)
|
||||||
|
.catch((e) => {
|
||||||
|
if (!c.signal.aborted) setError(e.message);
|
||||||
|
});
|
||||||
|
return () => c.abort();
|
||||||
|
}, [account]);
|
||||||
|
const tags = [...new Set(cards.flatMap((c) => c.tags))].slice(0, 30);
|
||||||
|
return (
|
||||||
|
<section className="dh-growth-profile">
|
||||||
|
<h2>我的体验与偏好</h2>
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
{state && (
|
||||||
|
<>
|
||||||
|
<p>
|
||||||
|
{state.entitlement.tier === "guest"
|
||||||
|
? "游客体验"
|
||||||
|
: state.entitlement.tier === "member"
|
||||||
|
? "会员权益"
|
||||||
|
: "免费权益"}{" "}
|
||||||
|
· 剩余 {state.entitlement.remaining} / {state.entitlement.limit} 次
|
||||||
|
· 生成中预占 {state.entitlement.reserved} 次
|
||||||
|
</p>
|
||||||
|
<small>
|
||||||
|
每次聊天或灵感生成消耗一次;空失败会释放,部分回复会保留并计次。
|
||||||
|
{state.entitlement.tier === "guest"
|
||||||
|
? "游客次数为本次身份的总额度,登录时承接使用记录。"
|
||||||
|
: "每日额度按服务器自然日重置。会员权益由后台运营授予。"}
|
||||||
|
</small>
|
||||||
|
{state.entitlement.tier === "guest" && (
|
||||||
|
<p>
|
||||||
|
<Link href="/login?next=%2Fprofile">登录并保留体验故事</Link>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<fieldset>
|
||||||
|
<legend>我感兴趣的题材(最多12项)</legend>
|
||||||
|
{tags.map((tag) => (
|
||||||
|
<label key={tag}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={state.interests.includes(tag)}
|
||||||
|
disabled={
|
||||||
|
busy ||
|
||||||
|
(!state.interests.includes(tag) &&
|
||||||
|
state.interests.length >= 12)
|
||||||
|
}
|
||||||
|
onChange={(e) =>
|
||||||
|
setState({
|
||||||
|
...state,
|
||||||
|
interests: e.target.checked
|
||||||
|
? [...state.interests, tag]
|
||||||
|
: state.interests.filter((t) => t !== tag),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{tag}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</fieldset>
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={state.autoMemory}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setState({ ...state, autoMemory: e.target.checked })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
允许为我的故事提取记忆
|
||||||
|
</label>
|
||||||
|
<p className="dh-form-note">
|
||||||
|
仅提取你明确说“请记住”的事实,并定期生成历史原文摘录;你可以在故事内查看、更正或移除。关闭后不再使用自动记忆,手动添加的记忆继续生效。
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
onClick={async () => {
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
setNotice("");
|
||||||
|
try {
|
||||||
|
await digital("growth/preferences", "PUT", {
|
||||||
|
interests: state.interests,
|
||||||
|
autoMemory: state.autoMemory,
|
||||||
|
});
|
||||||
|
setNotice("偏好已保存,下次推荐与回复时生效");
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "保存失败");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{busy ? "保存中…" : "保存推荐与记忆偏好"}
|
||||||
|
</button>
|
||||||
|
{notice && <p role="status">{notice}</p>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"use client";
|
||||||
|
/** 服务端推荐结果与真实可见曝光,默认排序、实验组和归因都由服务端决定。 */
|
||||||
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { digital, type Card } from "@/lib/digital";
|
||||||
|
import { contentPath } from "@/lib/digital-routes";
|
||||||
|
import { trackGrowth, flushGrowth, rememberRecommendation } from "@/lib/growth";
|
||||||
|
type Recommendation = {
|
||||||
|
receiptId: string;
|
||||||
|
items: { id: string; reason: string }[];
|
||||||
|
};
|
||||||
|
/** 兴趣偏好来自用户主动选择,跳过不会被误计为开聊。 */
|
||||||
|
export function GrowthRecommendations({
|
||||||
|
account,
|
||||||
|
cards,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
cards: Card[];
|
||||||
|
}) {
|
||||||
|
const [result, setResult] = useState<Recommendation | null>(null),
|
||||||
|
[error, setError] = useState(""),
|
||||||
|
root = useRef<HTMLElement>(null),
|
||||||
|
seen = useRef(new Set<string>());
|
||||||
|
useEffect(() => {
|
||||||
|
const c = new AbortController();
|
||||||
|
digital<Recommendation>(
|
||||||
|
"growth/recommendations",
|
||||||
|
"GET",
|
||||||
|
undefined,
|
||||||
|
c.signal,
|
||||||
|
)
|
||||||
|
.then(setResult)
|
||||||
|
.catch((e) => {
|
||||||
|
if (!c.signal.aborted)
|
||||||
|
setError(e instanceof Error ? e.message : "推荐加载失败");
|
||||||
|
});
|
||||||
|
return () => c.abort();
|
||||||
|
}, [account]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!result || !root.current) return;
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isIntersecting) continue;
|
||||||
|
const id = (entry.target as HTMLElement).dataset.cardId;
|
||||||
|
if (!id) continue;
|
||||||
|
const key = `${result.receiptId}:${id}`;
|
||||||
|
if (seen.current.has(key)) continue;
|
||||||
|
seen.current.add(key);
|
||||||
|
trackGrowth(
|
||||||
|
account,
|
||||||
|
"recommendation_exposure",
|
||||||
|
undefined,
|
||||||
|
result.receiptId,
|
||||||
|
);
|
||||||
|
trackGrowth(account, "card_impression", id, result.receiptId);
|
||||||
|
void flushGrowth(account);
|
||||||
|
observer.unobserve(entry.target);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ threshold: 0.5 },
|
||||||
|
);
|
||||||
|
root.current
|
||||||
|
.querySelectorAll("[data-card-id]")
|
||||||
|
.forEach((e) => observer.observe(e));
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [account, result]);
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
ref={root}
|
||||||
|
className="dh-growth-recommendations"
|
||||||
|
aria-label="为你推荐"
|
||||||
|
>
|
||||||
|
<h2>为你推荐</h2>
|
||||||
|
<p>
|
||||||
|
<Link href="/profile">选择兴趣,让推荐更懂你</Link>
|
||||||
|
</p>
|
||||||
|
{error ? (
|
||||||
|
<p role="status">{error}</p>
|
||||||
|
) : !result ? (
|
||||||
|
<p>正在寻找适合你的故事…</p>
|
||||||
|
) : (
|
||||||
|
<div className="dh-growth-grid">
|
||||||
|
{result.items.map((item) => {
|
||||||
|
const card = cards.find((c) => c.id === item.id);
|
||||||
|
return card ? (
|
||||||
|
<article key={item.id} data-card-id={item.id}>
|
||||||
|
<Link
|
||||||
|
href={{
|
||||||
|
pathname: contentPath(card),
|
||||||
|
query: { recommendation: result.receiptId },
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
trackGrowth(
|
||||||
|
account,
|
||||||
|
"recommendation_exposure",
|
||||||
|
undefined,
|
||||||
|
result.receiptId,
|
||||||
|
);
|
||||||
|
rememberRecommendation(account, card.id, result.receiptId);
|
||||||
|
void flushGrowth(account);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Image
|
||||||
|
src={card.cover || "/icon.svg"}
|
||||||
|
alt=""
|
||||||
|
width={240}
|
||||||
|
height={160}
|
||||||
|
unoptimized
|
||||||
|
/>
|
||||||
|
<strong>{card.name}</strong>
|
||||||
|
<small>{item.reason}</small>
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
trackGrowth(
|
||||||
|
account,
|
||||||
|
"card_skip",
|
||||||
|
card.id,
|
||||||
|
result.receiptId,
|
||||||
|
);
|
||||||
|
void flushGrowth(account);
|
||||||
|
setResult({
|
||||||
|
...result,
|
||||||
|
items: result.items.filter((i) => i.id !== card.id),
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
暂不感兴趣
|
||||||
|
</button>
|
||||||
|
</article>
|
||||||
|
) : null;
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,10 +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);
|
||||||
@@ -16,38 +19,45 @@ export function LoginForm() {
|
|||||||
setPending(true);
|
setPending(true);
|
||||||
|
|
||||||
const formData = new FormData(event.currentTarget);
|
const formData = new FormData(event.currentTarget);
|
||||||
const response = await fetch("/api/auth/login", {
|
try {
|
||||||
method: "POST",
|
const response = await fetch("/api/auth/login", {
|
||||||
headers: { "Content-Type": "application/json" },
|
method: "POST",
|
||||||
body: JSON.stringify({
|
headers: { "Content-Type": "application/json" },
|
||||||
username: String(formData.get("username") || "").trim(),
|
body: JSON.stringify({
|
||||||
password: String(formData.get("password") || "")
|
username: String(formData.get("username") || "").trim(),
|
||||||
})
|
password: String(formData.get("password") || ""),
|
||||||
});
|
}),
|
||||||
|
});
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const payload = (await response.json().catch(() => null)) as { message?: string } | null;
|
const payload = await response.json().catch(() => null);
|
||||||
setError(payload?.message || "登录失败,请检查手机号和密码");
|
throw new Error(payload?.message || "登录失败,请检查账号和密码");
|
||||||
|
}
|
||||||
|
router.replace(safeDigitalReturnTo(returnTo));
|
||||||
|
router.refresh();
|
||||||
|
} catch (error) {
|
||||||
|
setError(
|
||||||
|
error instanceof TypeError
|
||||||
|
? "网络连接失败,请稍后重试"
|
||||||
|
: error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "登录失败,请重试",
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
setPending(false);
|
setPending(false);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
router.replace("/dashboard");
|
|
||||||
router.refresh();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form className="login-form" onSubmit={handleSubmit}>
|
<form className="login-form" onSubmit={handleSubmit}>
|
||||||
<label>
|
<label>
|
||||||
<span>手机号</span>
|
<span>登录账号</span>
|
||||||
<div className="input-wrap">
|
<div className="input-wrap">
|
||||||
<Smartphone aria-hidden size={18} />
|
<Smartphone aria-hidden size={18} />
|
||||||
<input
|
<input
|
||||||
autoComplete="username"
|
autoComplete="username"
|
||||||
defaultValue="13211111111"
|
inputMode="text"
|
||||||
inputMode="tel"
|
|
||||||
name="username"
|
name="username"
|
||||||
placeholder="请输入员工手机号"
|
placeholder="请输入账号"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -58,7 +68,6 @@ export function LoginForm() {
|
|||||||
<LockKeyhole aria-hidden size={18} />
|
<LockKeyhole aria-hidden size={18} />
|
||||||
<input
|
<input
|
||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
defaultValue="pw111111"
|
|
||||||
name="password"
|
name="password"
|
||||||
placeholder="请输入登录密码"
|
placeholder="请输入登录密码"
|
||||||
required
|
required
|
||||||
@@ -70,7 +79,11 @@ export function LoginForm() {
|
|||||||
onClick={() => setPasswordVisible((visible) => !visible)}
|
onClick={() => setPasswordVisible((visible) => !visible)}
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
{passwordVisible ? <EyeOff aria-hidden size={18} /> : <Eye aria-hidden size={18} />}
|
{passwordVisible ? (
|
||||||
|
<EyeOff aria-hidden size={18} />
|
||||||
|
) : (
|
||||||
|
<Eye aria-hidden size={18} />
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</label>
|
</label>
|
||||||
@@ -78,6 +91,31 @@ export function LoginForm() {
|
|||||||
<button className="primary-button" disabled={pending} type="submit">
|
<button className="primary-button" disabled={pending} type="submit">
|
||||||
{pending ? "登录中..." : "登录"}
|
{pending ? "登录中..." : "登录"}
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={pending}
|
||||||
|
className="secondary-button"
|
||||||
|
onClick={async () => {
|
||||||
|
setPending(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/auth/guest", { method: "POST" });
|
||||||
|
if (!response.ok) {
|
||||||
|
const b = await response.json();
|
||||||
|
throw new Error(b.message ?? "体验暂不可用");
|
||||||
|
}
|
||||||
|
router.replace(safeDigitalReturnTo(returnTo));
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "体验暂不可用");
|
||||||
|
} finally {
|
||||||
|
setPending(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
先体验,再登录承接故事
|
||||||
|
</button>
|
||||||
|
<small>游客可体验有限轮次,登录后保留原故事。账号仍由管理员开通。</small>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话阅读位置按标签页保存;上翻时新回复只提示,不改变用户正在阅读的位置。 */
|
||||||
|
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||||
|
|
||||||
|
type Position = {
|
||||||
|
anchor?: string;
|
||||||
|
offset: number;
|
||||||
|
top: number;
|
||||||
|
bottom: boolean;
|
||||||
|
revision: string;
|
||||||
|
unread: boolean;
|
||||||
|
};
|
||||||
|
/** 保存消息锚点而非只保存像素,消息排版或窗口高度变化后仍尽量回到同一条。 */
|
||||||
|
export function useChatReading(
|
||||||
|
id: string | undefined,
|
||||||
|
viewportRef: RefObject<HTMLDivElement | null>,
|
||||||
|
contentRef: RefObject<HTMLDivElement | null>,
|
||||||
|
atBottomRef: RefObject<boolean>,
|
||||||
|
draggingRef: RefObject<boolean>,
|
||||||
|
onJump: (value: boolean) => void,
|
||||||
|
) {
|
||||||
|
const [unread, setUnread] = useState(false);
|
||||||
|
const unreadRef = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
const view = viewportRef.current,
|
||||||
|
body = contentRef.current;
|
||||||
|
if (!id || !view || !body) return;
|
||||||
|
let frame = 0,
|
||||||
|
saveFrame = 0,
|
||||||
|
restored = false,
|
||||||
|
previousRevision = "";
|
||||||
|
const elements = () =>
|
||||||
|
Array.from(body.querySelectorAll<HTMLElement>("[data-message-id]"));
|
||||||
|
const revision = () => {
|
||||||
|
const last = elements().at(-1);
|
||||||
|
return last
|
||||||
|
? `${last.dataset.messageId}:${last.dataset.messageLength}`
|
||||||
|
: "";
|
||||||
|
};
|
||||||
|
const mark = (value: boolean) => {
|
||||||
|
unreadRef.current = value;
|
||||||
|
setUnread(value);
|
||||||
|
};
|
||||||
|
let lastPosition: Position | undefined;
|
||||||
|
const save = () => {
|
||||||
|
if (!restored) return;
|
||||||
|
// App Router 隐藏或卸载页面后 DOM 尺寸可能归零,不能用它覆盖最后一次有效阅读位置。
|
||||||
|
if (view.isConnected && body.isConnected && view.clientHeight > 0) {
|
||||||
|
const top = view.getBoundingClientRect().top;
|
||||||
|
const anchor = elements().find(
|
||||||
|
(el) => el.getBoundingClientRect().bottom > top,
|
||||||
|
);
|
||||||
|
lastPosition = {
|
||||||
|
anchor: anchor?.dataset.messageId,
|
||||||
|
offset: (anchor?.getBoundingClientRect().top ?? top) - top,
|
||||||
|
top: view.scrollTop,
|
||||||
|
bottom: atBottomRef.current,
|
||||||
|
revision: revision(),
|
||||||
|
unread: unreadRef.current,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!lastPosition) return;
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(`dh-reading:${id}`, JSON.stringify(lastPosition));
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
|
let saved: Position | undefined;
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(
|
||||||
|
sessionStorage.getItem(`dh-reading:${id}`) ?? "null",
|
||||||
|
);
|
||||||
|
if (value && Number.isFinite(value.top) && Number.isFinite(value.offset))
|
||||||
|
saved = value;
|
||||||
|
} catch {}
|
||||||
|
atBottomRef.current = saved?.bottom ?? true;
|
||||||
|
const follow = () => {
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
frame = requestAnimationFrame(() => {
|
||||||
|
if (!restored) {
|
||||||
|
let hash = "";
|
||||||
|
try {
|
||||||
|
hash = decodeURIComponent(window.location.hash.slice(1));
|
||||||
|
} catch {}
|
||||||
|
const target = hash
|
||||||
|
? elements().find((el) => el.id === hash)
|
||||||
|
: !saved?.bottom && saved?.anchor
|
||||||
|
? elements().find((el) => el.dataset.messageId === saved?.anchor)
|
||||||
|
: undefined;
|
||||||
|
if (target) {
|
||||||
|
view.scrollTop +=
|
||||||
|
target.getBoundingClientRect().top -
|
||||||
|
view.getBoundingClientRect().top -
|
||||||
|
(hash ? 12 : (saved?.offset ?? 0));
|
||||||
|
atBottomRef.current = false;
|
||||||
|
} else
|
||||||
|
view.scrollTop = atBottomRef.current
|
||||||
|
? view.scrollHeight
|
||||||
|
: (saved?.top ?? 0);
|
||||||
|
previousRevision = saved?.revision ?? revision();
|
||||||
|
mark(!!saved?.unread);
|
||||||
|
restored = true;
|
||||||
|
}
|
||||||
|
const next = revision();
|
||||||
|
if (atBottomRef.current) {
|
||||||
|
view.scrollTo({ top: view.scrollHeight, behavior: "instant" });
|
||||||
|
onJump(false);
|
||||||
|
mark(false);
|
||||||
|
} else {
|
||||||
|
if (next !== previousRevision) mark(true);
|
||||||
|
onJump(view.scrollHeight - view.scrollTop - view.clientHeight > 80);
|
||||||
|
}
|
||||||
|
previousRevision = next;
|
||||||
|
save();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const scroll = () => {
|
||||||
|
if (!restored || !view.isConnected || view.clientHeight <= 0) return;
|
||||||
|
if (view.scrollHeight - view.scrollTop - view.clientHeight <= 2)
|
||||||
|
mark(false);
|
||||||
|
cancelAnimationFrame(saveFrame);
|
||||||
|
saveFrame = requestAnimationFrame(save);
|
||||||
|
};
|
||||||
|
const endDrag = () => {
|
||||||
|
draggingRef.current = false;
|
||||||
|
};
|
||||||
|
const observer = new ResizeObserver(follow);
|
||||||
|
observer.observe(body);
|
||||||
|
observer.observe(view);
|
||||||
|
view.addEventListener("scroll", scroll);
|
||||||
|
window.addEventListener("pointerup", endDrag);
|
||||||
|
window.addEventListener("pointercancel", endDrag);
|
||||||
|
follow();
|
||||||
|
return () => {
|
||||||
|
save();
|
||||||
|
observer.disconnect();
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
cancelAnimationFrame(saveFrame);
|
||||||
|
view.removeEventListener("scroll", scroll);
|
||||||
|
window.removeEventListener("pointerup", endDrag);
|
||||||
|
window.removeEventListener("pointercancel", endDrag);
|
||||||
|
};
|
||||||
|
}, [id, viewportRef, contentRef, atBottomRef, draggingRef, onJump]);
|
||||||
|
return unread;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/** 登录入口在解析JSON之前限制字节数,防止公开入口先无界缓存再交给后端校验。 */
|
||||||
|
export async function readLoginInput(
|
||||||
|
request: Request,
|
||||||
|
): Promise<Record<string, unknown>> {
|
||||||
|
if (!request.body) throw new SyntaxError("登录内容不合法");
|
||||||
|
const reader = request.body.getReader(),
|
||||||
|
decoder = new TextDecoder();
|
||||||
|
let bytes = 0,
|
||||||
|
text = "";
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
bytes += value.byteLength;
|
||||||
|
if (bytes > 8192) {
|
||||||
|
await reader.cancel();
|
||||||
|
throw new RangeError("登录内容过长");
|
||||||
|
}
|
||||||
|
text += decoder.decode(value, { stream: true });
|
||||||
|
}
|
||||||
|
text += decoder.decode();
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
const body: unknown = JSON.parse(text);
|
||||||
|
if (!body || typeof body !== "object" || Array.isArray(body))
|
||||||
|
throw new SyntaxError("登录内容不合法");
|
||||||
|
return body as Record<string, unknown>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
/** 同源写入校验使用代理保留的Host,避免服务端监听地址与公网域名不一致导致登录失败。 */
|
||||||
|
export function sameOriginRequest(request: Request) {
|
||||||
|
try {
|
||||||
|
const origin = request.headers.get("origin");
|
||||||
|
if (!origin) return false;
|
||||||
|
const parsed = new URL(origin);
|
||||||
|
return (
|
||||||
|
["https:", "http:"].includes(parsed.protocol) &&
|
||||||
|
parsed.origin === origin &&
|
||||||
|
parsed.host === request.headers.get("host")
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 } });
|
||||||
|
}
|
||||||
@@ -1,33 +1,48 @@
|
|||||||
|
/** 服务端后端访问与会话错误转换,统一保留业务错误文案。 */
|
||||||
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";
|
||||||
|
|
||||||
|
/** 保留后端状态以便 BFF 清理失效会话。 */
|
||||||
export class BackendError extends Error {
|
export class BackendError extends Error {
|
||||||
constructor(
|
constructor(
|
||||||
message: string,
|
message: string,
|
||||||
public status: number
|
public status: number,
|
||||||
) {
|
) {
|
||||||
super(message);
|
super(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 后端根地址仅由服务端环境配置决定。 */
|
||||||
export function getBackendBaseUrl() {
|
export function getBackendBaseUrl() {
|
||||||
return process.env.ACCESS_MANAGE_API_BASE_URL || "http://localhost:3500/api";
|
return process.env.ACCESS_MANAGE_API_BASE_URL || "http://localhost:3500/api";
|
||||||
}
|
}
|
||||||
|
|
||||||
function toUrl(path: string) {
|
function toUrl(path: string) {
|
||||||
return new URL(path.replace(/^\//, ""), `${getBackendBaseUrl().replace(/\/$/, "")}/`);
|
return new URL(
|
||||||
|
path.replace(/^\//, ""),
|
||||||
|
`${getBackendBaseUrl().replace(/\/$/, "")}/`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function parseBackendResponse<T>(response: Response): Promise<T> {
|
async function parseBackendResponse<T>(response: Response): Promise<T> {
|
||||||
const contentType = response.headers.get("content-type") || "";
|
const contentType = response.headers.get("content-type") || "";
|
||||||
const payload = contentType.includes("application/json") ? await response.json() : null;
|
const payload = contentType.includes("application/json")
|
||||||
|
? await response.json()
|
||||||
|
: null;
|
||||||
|
|
||||||
if (!response.ok || payload?.success === false) {
|
if (!response.ok || payload?.success === false) {
|
||||||
throw new BackendError(payload?.message || response.statusText || "请求失败", response.status);
|
throw new BackendError(
|
||||||
|
payload?.error?.message ||
|
||||||
|
payload?.message ||
|
||||||
|
response.statusText ||
|
||||||
|
"请求失败",
|
||||||
|
response.status,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload && typeof payload === "object" && "data" in payload) {
|
if (payload && typeof payload === "object" && "data" in payload) {
|
||||||
@@ -37,9 +52,10 @@ async function parseBackendResponse<T>(response: Response): Promise<T> {
|
|||||||
return payload as T;
|
return payload as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 为服务端请求附加 HttpOnly 会话并禁止缓存私有数据。 */
|
||||||
export async function backendRequest<T>(
|
export async function backendRequest<T>(
|
||||||
path: string,
|
path: string,
|
||||||
init: RequestInit & { token?: string; allowUnauthorized?: boolean } = {}
|
init: RequestInit & { token?: string; allowUnauthorized?: boolean } = {},
|
||||||
) {
|
) {
|
||||||
const token = init.token ?? (await getSessionToken());
|
const token = init.token ?? (await getSessionToken());
|
||||||
const headers = new Headers(init.headers);
|
const headers = new Headers(init.headers);
|
||||||
@@ -55,25 +71,34 @@ export async function backendRequest<T>(
|
|||||||
const response = await fetch(toUrl(path), {
|
const response = await fetch(toUrl(path), {
|
||||||
...init,
|
...init,
|
||||||
headers,
|
headers,
|
||||||
cache: "no-store"
|
cache: "no-store",
|
||||||
});
|
});
|
||||||
|
|
||||||
return parseBackendResponse<T>(response);
|
return parseBackendResponse<T>(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function requireBackendData<T>(path: string) {
|
/** 页面数据要求登录,失效时通过登出路由清理 Cookie。 */
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function proxyBackendJson<T>(path: string, init: RequestInit = {}) {
|
/** 包装普通 JSON 业务接口,流式对话使用专用 BFF。 */
|
||||||
|
export async function proxyBackendJson<T>(
|
||||||
|
path: string,
|
||||||
|
init: RequestInit = {},
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
const data = await backendRequest<T>(path, init);
|
const data = await backendRequest<T>(path, init);
|
||||||
return Response.json({ success: true, data } satisfies ApiEnvelope<T>);
|
return Response.json({ success: true, data } satisfies ApiEnvelope<T>);
|
||||||
@@ -82,7 +107,11 @@ export async function proxyBackendJson<T>(path: string, init: RequestInit = {})
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function backendErrorResponse(error: unknown, fallbackMessage = "请求失败") {
|
/** 对浏览器返回统一错误,401 时同步清理 Cookie。 */
|
||||||
|
export async function backendErrorResponse(
|
||||||
|
error: unknown,
|
||||||
|
fallbackMessage = "请求失败",
|
||||||
|
) {
|
||||||
const status = error instanceof BackendError ? error.status : 500;
|
const status = error instanceof BackendError ? error.status : 500;
|
||||||
const message = error instanceof Error ? error.message : fallbackMessage;
|
const message = error instanceof Error ? error.message : fallbackMessage;
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/** 服务端生成中快照可能尚未落入增量正文;同步时保留浏览器已经收到的部分回复。 */
|
||||||
|
import type { Conversation } from "./digital";
|
||||||
|
|
||||||
|
/** 已结束的服务端记录为最终依据;仅在仍生成时保留同一消息较长的本地正文。 */
|
||||||
|
export function mergeConversationSnapshot(
|
||||||
|
current: Conversation | null,
|
||||||
|
saved: Conversation,
|
||||||
|
): Conversation {
|
||||||
|
if (!current || current.id !== saved.id || !saved.busy) return saved;
|
||||||
|
const known = new Map(
|
||||||
|
current.messages.map((message) => [message.id, message]),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
...saved,
|
||||||
|
messages: saved.messages.map((message) => {
|
||||||
|
const local = known.get(message.id);
|
||||||
|
return message.role === "assistant" &&
|
||||||
|
message.status === "generating" &&
|
||||||
|
local &&
|
||||||
|
local.content.length > message.content.length
|
||||||
|
? { ...message, content: local.content }
|
||||||
|
: message;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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))}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/** 独立 SSE 解码器,流关闭不代表回复成功,必须收到服务端 done 事件。 */
|
||||||
|
/** 网络分片可跨多个 SSE 事件,最后不完整事件不会被误解析。 */
|
||||||
|
export async function readDigitalStream(
|
||||||
|
response: Response,
|
||||||
|
onEvent: (event: string, data: Record<string, unknown>) => void,
|
||||||
|
) {
|
||||||
|
if (!response.ok) {
|
||||||
|
const p = await response.json();
|
||||||
|
throw new Error(p.error?.message ?? p.message ?? "发送失败");
|
||||||
|
}
|
||||||
|
if (!response.body) throw new Error("浏览器不支持流式连接");
|
||||||
|
const reader = response.body.getReader(),
|
||||||
|
decoder = new TextDecoder();
|
||||||
|
let buffer = "",
|
||||||
|
completed = false;
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
buffer += (
|
||||||
|
done ? decoder.decode() : decoder.decode(value, { stream: true })
|
||||||
|
).replaceAll("\r\n", "\n");
|
||||||
|
let end: number;
|
||||||
|
while ((end = buffer.indexOf("\n\n")) >= 0) {
|
||||||
|
const block = buffer.slice(0, end);
|
||||||
|
buffer = buffer.slice(end + 2);
|
||||||
|
const event = block
|
||||||
|
.split("\n")
|
||||||
|
.find((s) => s.startsWith("event:"))
|
||||||
|
?.slice(6)
|
||||||
|
.trim();
|
||||||
|
const data = block
|
||||||
|
.split("\n")
|
||||||
|
.filter((s) => s.startsWith("data:"))
|
||||||
|
.map((s) => s.slice(5).trim())
|
||||||
|
.join("\n");
|
||||||
|
if (event && data) {
|
||||||
|
if (event === "done") completed = true;
|
||||||
|
onEvent(event, JSON.parse(data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done) break;
|
||||||
|
}
|
||||||
|
if (!completed)
|
||||||
|
throw new Error("连接在回复结束前中断,请同步聊天记录后继续");
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
/** 数字人客户端协议与事件解码,不包含模型凭据或实验操作。 */
|
||||||
|
import { expiredDigitalSessionPath } from "./digital-routes";
|
||||||
|
|
||||||
|
/** 前台可见内容摘要,提示词不会下发。 */
|
||||||
|
export type Card = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
kind: "character" | "worldbook" | "preset";
|
||||||
|
version: number;
|
||||||
|
description: string;
|
||||||
|
greeting: string;
|
||||||
|
alternateGreetings: string[];
|
||||||
|
gender: string;
|
||||||
|
age: number;
|
||||||
|
cover: string;
|
||||||
|
tags: string[];
|
||||||
|
source: string;
|
||||||
|
entriesCount: number;
|
||||||
|
};
|
||||||
|
/** 用户自己的身份资料。 */
|
||||||
|
export type Profile = {
|
||||||
|
favorites: string[];
|
||||||
|
persona: string;
|
||||||
|
userName: string;
|
||||||
|
/** 登录账号的成人内容偏好;旧服务未返回时沿用默认开启。 */
|
||||||
|
nsfwEnabled?: boolean;
|
||||||
|
};
|
||||||
|
/** 会话消息拥有持久化 id,避免流式刷新时重复插入。 */
|
||||||
|
export type Message = {
|
||||||
|
id: string;
|
||||||
|
role: "user" | "assistant";
|
||||||
|
content: string;
|
||||||
|
status: string;
|
||||||
|
pinned: boolean;
|
||||||
|
sequenceId?: number;
|
||||||
|
requestId?: string | null;
|
||||||
|
};
|
||||||
|
/** 不含实验配置的会话偏好。 */
|
||||||
|
export type Settings = {
|
||||||
|
persona: string;
|
||||||
|
userName: string;
|
||||||
|
memory: string;
|
||||||
|
presetId?: string;
|
||||||
|
bookIds: string[];
|
||||||
|
};
|
||||||
|
/** 对话详情。 */
|
||||||
|
export type Conversation = {
|
||||||
|
id: string;
|
||||||
|
characterId: string;
|
||||||
|
title: string;
|
||||||
|
settings: Settings;
|
||||||
|
busy: boolean;
|
||||||
|
messages: Message[];
|
||||||
|
pinned?: boolean;
|
||||||
|
parent?: {
|
||||||
|
conversationId: string;
|
||||||
|
messageId: string;
|
||||||
|
title: string;
|
||||||
|
available: boolean;
|
||||||
|
} | null;
|
||||||
|
};
|
||||||
|
/** 通用请求保留服务端错误文本,401 自动返回登录。 */
|
||||||
|
export async function digital<T>(
|
||||||
|
path: string,
|
||||||
|
method = "GET",
|
||||||
|
body?: unknown,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
): Promise<T> {
|
||||||
|
const response = await fetch(`/api/digital/${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
if (response.status === 401) {
|
||||||
|
window.location.assign(
|
||||||
|
expiredDigitalSessionPath(
|
||||||
|
window.location.pathname + window.location.search,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
throw new Error("登录已过期");
|
||||||
|
}
|
||||||
|
if (!response.ok || data.success === false)
|
||||||
|
throw new Error(data.error?.message ?? data.message ?? "请求失败");
|
||||||
|
return data.data as T;
|
||||||
|
}
|
||||||
|
/** 严格检查终止事件,避免断网被当作回复完成。 */
|
||||||
|
export { readDigitalStream as readStream } from "./digital-stream";
|
||||||
|
|
||||||
|
/** 会话列表摘要。 */
|
||||||
|
export type Summary = {
|
||||||
|
id: string;
|
||||||
|
characterId: string;
|
||||||
|
title: string;
|
||||||
|
updatedAt: string;
|
||||||
|
pinned?: boolean;
|
||||||
|
lastMessage?: string | null;
|
||||||
|
};
|
||||||
|
/** 服务端首屏数据,仅包含可公开的内容摘要和当前账号决策。 */
|
||||||
|
export type Bootstrap = {
|
||||||
|
account: string;
|
||||||
|
catalog: Card[];
|
||||||
|
profile: Profile;
|
||||||
|
decision: {
|
||||||
|
variant: string | null;
|
||||||
|
value?: unknown;
|
||||||
|
fallbackValue?: unknown;
|
||||||
|
decisionId: string | null;
|
||||||
|
expiresAt: number;
|
||||||
|
fallbackVariant: string | null;
|
||||||
|
};
|
||||||
|
serverNow: number;
|
||||||
|
};
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
export type AppEnv = "local" | "develop" | "production";
|
||||||
|
|
||||||
|
export function getAppEnv(): AppEnv {
|
||||||
|
const appEnv = process.env.APP_ENV;
|
||||||
|
|
||||||
|
if (appEnv === "production") {
|
||||||
|
return "production";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (appEnv === "develop" || appEnv === "test") {
|
||||||
|
return "develop";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (appEnv === "local") {
|
||||||
|
return "local";
|
||||||
|
}
|
||||||
|
|
||||||
|
return process.env.NODE_ENV === "production" ? "production" : "local";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAppEnvLabel() {
|
||||||
|
if (process.env.APP_ENV_LABEL) {
|
||||||
|
return process.env.APP_ENV_LABEL;
|
||||||
|
}
|
||||||
|
|
||||||
|
const labels: Record<AppEnv, string> = {
|
||||||
|
local: "本地环境",
|
||||||
|
develop: "测试环境",
|
||||||
|
production: "生产环境"
|
||||||
|
};
|
||||||
|
|
||||||
|
return labels[getAppEnv()];
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
/** 无依赖的前台增长队列与推荐回执,便于验证重试幂等和账号隔离。 */
|
||||||
|
type EventName =
|
||||||
|
| "page_view"
|
||||||
|
| "card_impression"
|
||||||
|
| "card_open"
|
||||||
|
| "card_skip"
|
||||||
|
| "recommendation_exposure";
|
||||||
|
type Event = {
|
||||||
|
id: string;
|
||||||
|
event: EventName;
|
||||||
|
entity?: string;
|
||||||
|
receiptId?: string;
|
||||||
|
queuedAt: number;
|
||||||
|
};
|
||||||
|
const flushing = new Set<string>();
|
||||||
|
/** 队列按账号隔离;失败保留同一UUID重试,服务端以UUID幂等写入。 */
|
||||||
|
export function trackGrowth(
|
||||||
|
account: string,
|
||||||
|
event: EventName,
|
||||||
|
entity?: string,
|
||||||
|
receiptId?: string,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const key = `dh-events:${account}`,
|
||||||
|
queue = JSON.parse(sessionStorage.getItem(key) ?? "[]") as Event[];
|
||||||
|
queue.push({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
event,
|
||||||
|
entity,
|
||||||
|
receiptId,
|
||||||
|
queuedAt: Date.now(),
|
||||||
|
});
|
||||||
|
sessionStorage.setItem(key, JSON.stringify(queue.slice(-200)));
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
/** 单批20条,过期回执不再补报;400/404代表无效事件,其他失败保留待重试。 */
|
||||||
|
export async function flushGrowth(account: string) {
|
||||||
|
if (flushing.has(account)) return;
|
||||||
|
flushing.add(account);
|
||||||
|
try {
|
||||||
|
const key = `dh-events:${account}`,
|
||||||
|
queue = (
|
||||||
|
JSON.parse(sessionStorage.getItem(key) ?? "[]") as Event[]
|
||||||
|
).filter((e) => Date.now() - e.queuedAt < 23 * 3600000),
|
||||||
|
batch = queue.slice(0, 20);
|
||||||
|
if (!batch.length) return;
|
||||||
|
const response = await fetch("/api/digital/growth/events", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
account,
|
||||||
|
events: batch.map(({ queuedAt, ...event }) => {
|
||||||
|
return { ...event, occurredAt: queuedAt };
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
keepalive: true,
|
||||||
|
});
|
||||||
|
if (response.ok || response.status === 400 || response.status === 404) {
|
||||||
|
const sent = new Set(batch.map((e) => e.id)),
|
||||||
|
current = JSON.parse(sessionStorage.getItem(key) ?? "[]") as Event[];
|
||||||
|
sessionStorage.setItem(
|
||||||
|
key,
|
||||||
|
JSON.stringify(current.filter((e) => !sent.has(e.id))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
} finally {
|
||||||
|
flushing.delete(account);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** 推荐来源有24小时有效期,只用于服务端再次验证的归因回执。 */
|
||||||
|
export function recommendationReceipt(account: string, card: string) {
|
||||||
|
try {
|
||||||
|
const r = JSON.parse(
|
||||||
|
sessionStorage.getItem(`dh-recommendation:${account}:${card}`) ?? "null",
|
||||||
|
);
|
||||||
|
return r && r.until > Date.now() ? (r.id as string) : undefined;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** 推荐打开后跨独立路由承接回执;跳过后立即移除该项。 */
|
||||||
|
export function rememberRecommendation(
|
||||||
|
account: string,
|
||||||
|
card: string,
|
||||||
|
id: string,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(
|
||||||
|
`dh-recommendation:${account}:${card}`,
|
||||||
|
JSON.stringify({ id, until: Date.now() + 23 * 3600000 }),
|
||||||
|
);
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/** C端增长事件队列只包含事件名、内容ID与回执;不采集正文、密码、设备指纹。 */
|
||||||
|
import { digital } from "./digital";
|
||||||
|
export {
|
||||||
|
trackGrowth,
|
||||||
|
flushGrowth,
|
||||||
|
recommendationReceipt,
|
||||||
|
rememberRecommendation,
|
||||||
|
} from "./growth-analytics";
|
||||||
|
/** 前台权益与运营卡片不包含后台策略和全站预算。 */
|
||||||
|
export type GrowthState = {
|
||||||
|
entitlement: {
|
||||||
|
tier: "guest" | "free" | "member";
|
||||||
|
limit: number;
|
||||||
|
remaining: number;
|
||||||
|
used: number;
|
||||||
|
reserved: number;
|
||||||
|
memberUntil: string | null;
|
||||||
|
};
|
||||||
|
interests: string[];
|
||||||
|
autoMemory: boolean;
|
||||||
|
segment: string;
|
||||||
|
inbox: { id: string; title: string; content: string }[];
|
||||||
|
};
|
||||||
|
/** 已保存评价按会话合并加载,避免每条消息各请求一次。 */
|
||||||
|
const feedbackCache = new Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
until: number;
|
||||||
|
value: Promise<
|
||||||
|
{ messageId: string; rating: "up" | "down"; reason: string }[]
|
||||||
|
>;
|
||||||
|
}
|
||||||
|
>();
|
||||||
|
export function feedbackFor(account: string, conversation: string) {
|
||||||
|
const key = `${account}:${conversation}`,
|
||||||
|
hit = feedbackCache.get(key);
|
||||||
|
if (hit && hit.until > Date.now()) return hit.value;
|
||||||
|
if (feedbackCache.size >= 100)
|
||||||
|
feedbackCache.delete(feedbackCache.keys().next().value!);
|
||||||
|
const value = digital<
|
||||||
|
{ messageId: string; rating: "up" | "down"; reason: string }[]
|
||||||
|
>(`conversations/${conversation}/feedback`);
|
||||||
|
feedbackCache.set(key, { until: Date.now() + 30000, value });
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本人提交评价后失效会话缓存,下次进入从后端还原最新选择。 */
|
||||||
|
export function invalidateFeedback(account: string, conversation: string) {
|
||||||
|
feedbackCache.delete(`${account}:${conversation}`);
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
|
/** 会话令牌仅保存在HttpOnly Cookie,游客标记供登录路由承接身份。 */
|
||||||
import "server-only";
|
import "server-only";
|
||||||
|
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
|
|
||||||
|
import { getAppEnv } from "@/lib/environment";
|
||||||
|
|
||||||
const DEFAULT_COOKIE_NAME = "role_user_session";
|
const DEFAULT_COOKIE_NAME = "role_user_session";
|
||||||
|
|
||||||
export function getSessionCookieName() {
|
export function getSessionCookieName() {
|
||||||
@@ -17,13 +20,15 @@ export async function setSessionToken(token: string) {
|
|||||||
|
|
||||||
cookieStore.set(getSessionCookieName(), token, {
|
cookieStore.set(getSessionCookieName(), token, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: process.env.NODE_ENV === "production",
|
secure: getAppEnv() === "production",
|
||||||
sameSite: "lax",
|
sameSite: "lax",
|
||||||
path: "/",
|
path: "/",
|
||||||
maxAge: 60 * 60 * 8
|
maxAge: 60 * 60 * 8,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function clearSessionToken() {
|
export async function clearSessionToken() {
|
||||||
(await cookies()).delete(getSessionCookieName());
|
const store = await cookies();
|
||||||
|
store.delete(getSessionCookieName());
|
||||||
|
store.delete(`${getSessionCookieName()}_guest`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -1,26 +1,56 @@
|
|||||||
|
/** 私有页面会话路由,默认登录后进入数字人空间。 */
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { digitalLoginPath, safeDigitalReturnTo } from "@/lib/digital-routes";
|
||||||
|
|
||||||
const protectedRoutes = ["/dashboard", "/tasks", "/schedule", "/announcements", "/store", "/me"];
|
const protectedRoutes = [
|
||||||
|
"/discover",
|
||||||
|
"/chats",
|
||||||
|
"/characters",
|
||||||
|
"/library",
|
||||||
|
"/profile",
|
||||||
|
"/dashboard",
|
||||||
|
"/tasks",
|
||||||
|
"/schedule",
|
||||||
|
"/announcements",
|
||||||
|
"/store",
|
||||||
|
"/me",
|
||||||
|
];
|
||||||
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);
|
||||||
const isProtected = protectedRoutes.some((route) => path === route || path.startsWith(`${route}/`));
|
const isProtected = protectedRoutes.some(
|
||||||
|
(route) => path === route || path.startsWith(`${route}/`),
|
||||||
|
);
|
||||||
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) {
|
const guest = Boolean(request.cookies.get(`${cookieName}_guest`)?.value);
|
||||||
return NextResponse.redirect(new URL("/dashboard", request.url));
|
if (isPublic && hasSession && !(path === "/login" && guest)) {
|
||||||
|
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: ["/((?!api|_next/static|_next/image|manifest.webmanifest|sw.js|.*\\..*).*)"]
|
matcher: [
|
||||||
|
"/((?!api|_next/static|_next/image|manifest.webmanifest|sw.js|.*\\..*).*)",
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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 }]);
|
||||||
|
});
|
||||||
@@ -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));
|
||||||
|
});
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
/** SSE 的真正终止、网络中断与跨分片 Unicode 解码回归。 */
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readDigitalStream } from "../src/lib/digital-stream.ts";
|
||||||
|
|
||||||
|
test("只收到部分内容就断流时保留事件,并报告中断", async () => {
|
||||||
|
const events = [];
|
||||||
|
await assert.rejects(
|
||||||
|
readDigitalStream(
|
||||||
|
new Response('event: delta\ndata: {"text":"已有内容"}\n\n'),
|
||||||
|
(event, data) => events.push([event, data]),
|
||||||
|
),
|
||||||
|
/中断/,
|
||||||
|
);
|
||||||
|
assert.equal(events[0][1].text, "已有内容");
|
||||||
|
});
|
||||||
|
test("结束事件跨字节分片且包含中文时只解析一次", async () => {
|
||||||
|
const bytes = new TextEncoder().encode(
|
||||||
|
'event: delta\ndata: {"text":"中文"}\n\nevent: done\ndata: {"status":"complete"}\n\n',
|
||||||
|
);
|
||||||
|
const events = [];
|
||||||
|
await readDigitalStream(
|
||||||
|
new Response(
|
||||||
|
new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
for (const byte of bytes) controller.enqueue(new Uint8Array([byte]));
|
||||||
|
controller.close();
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(event, data) => events.push([event, data]),
|
||||||
|
);
|
||||||
|
assert.deepEqual(events, [
|
||||||
|
["delta", { text: "中文" }],
|
||||||
|
["done", { status: "complete" }],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
test("空连接不能被当作完成,服务端拒绝保持原错误", async () => {
|
||||||
|
await assert.rejects(
|
||||||
|
readDigitalStream(new Response(""), () => {}),
|
||||||
|
/中断/,
|
||||||
|
);
|
||||||
|
await assert.rejects(
|
||||||
|
readDigitalStream(
|
||||||
|
new Response('{"message":"上一条仍在生成"}', { status: 409 }),
|
||||||
|
() => {},
|
||||||
|
),
|
||||||
|
/仍在生成/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("同步生成中快照不会清空已收到的部分回复,完成后以服务端记录为准", async () => {
|
||||||
|
const { mergeConversationSnapshot } = await import(
|
||||||
|
"../src/lib/digital-recovery.ts"
|
||||||
|
);
|
||||||
|
const local = {
|
||||||
|
id: "chat",
|
||||||
|
busy: true,
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
id: "reply",
|
||||||
|
role: "assistant",
|
||||||
|
status: "generating",
|
||||||
|
content: "已经显示的正文",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const saved = { ...local, messages: [{ ...local.messages[0], content: "" }] };
|
||||||
|
assert.equal(
|
||||||
|
mergeConversationSnapshot(local, saved).messages[0].content,
|
||||||
|
"已经显示的正文",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
mergeConversationSnapshot(local, { ...saved, busy: false }).messages[0]
|
||||||
|
.content,
|
||||||
|
"",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
mergeConversationSnapshot({ ...local, id: "other" }, saved).messages[0]
|
||||||
|
.content,
|
||||||
|
"",
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
/** 事件队列使用可控浏览器存储与HTTP夹具,验证批次边界、重试和账号切换。 */
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import {
|
||||||
|
trackGrowth,
|
||||||
|
flushGrowth,
|
||||||
|
rememberRecommendation,
|
||||||
|
recommendationReceipt,
|
||||||
|
} from "../src/lib/growth-analytics.ts";
|
||||||
|
function storage(t) {
|
||||||
|
const values = new Map();
|
||||||
|
if (!("sessionStorage" in globalThis))
|
||||||
|
Object.defineProperty(globalThis, "sessionStorage", {
|
||||||
|
value: undefined,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
t.mock.property(globalThis, "sessionStorage", {
|
||||||
|
getItem: (key) => values.get(key) ?? null,
|
||||||
|
setItem: (key, value) => values.set(key, value),
|
||||||
|
});
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
test("账号队列隔离,并将账号绑定到上报批次供服务端核验", async (t) => {
|
||||||
|
storage(t);
|
||||||
|
const sent = [];
|
||||||
|
t.mock.method(globalThis, "fetch", async (_url, init) => {
|
||||||
|
sent.push(JSON.parse(init.body));
|
||||||
|
return new Response("{}");
|
||||||
|
});
|
||||||
|
trackGrowth("user:1", "page_view", "discover");
|
||||||
|
trackGrowth("user:2", "card_open", "role");
|
||||||
|
await flushGrowth("user:1");
|
||||||
|
assert.equal(sent[0].account, "user:1");
|
||||||
|
assert.equal(sent[0].events.length, 1);
|
||||||
|
assert.equal(sent[0].events[0].event, "page_view");
|
||||||
|
await flushGrowth("user:2");
|
||||||
|
assert.equal(sent[1].account, "user:2");
|
||||||
|
});
|
||||||
|
test("失败重试保留同一个事件UUID,不重新记一次曝光", async (t) => {
|
||||||
|
storage(t);
|
||||||
|
const sent = [];
|
||||||
|
t.mock.method(globalThis, "fetch", async (_url, init) => {
|
||||||
|
sent.push(JSON.parse(init.body));
|
||||||
|
return new Response("{}", { status: sent.length === 1 ? 503 : 200 });
|
||||||
|
});
|
||||||
|
trackGrowth("user:retry", "card_impression", "role");
|
||||||
|
await flushGrowth("user:retry");
|
||||||
|
await flushGrowth("user:retry");
|
||||||
|
assert.equal(sent.length, 2);
|
||||||
|
assert.equal(sent[0].events[0].id, sent[1].events[0].id);
|
||||||
|
await flushGrowth("user:retry");
|
||||||
|
assert.equal(sent.length, 2);
|
||||||
|
});
|
||||||
|
test("一批最多20条,成功响应不丢失请求期间新入队的事件", async (t) => {
|
||||||
|
const values = storage(t);
|
||||||
|
const sent = [];
|
||||||
|
t.mock.method(globalThis, "fetch", async (_url, init) => {
|
||||||
|
sent.push(JSON.parse(init.body));
|
||||||
|
trackGrowth("user:batch", "card_open", "new");
|
||||||
|
return new Response("{}");
|
||||||
|
});
|
||||||
|
for (let i = 0; i < 25; i++)
|
||||||
|
trackGrowth("user:batch", "card_impression", `role-${i}`);
|
||||||
|
await flushGrowth("user:batch");
|
||||||
|
assert.equal(sent[0].events.length, 20);
|
||||||
|
const left = JSON.parse(values.get("dh-events:user:batch"));
|
||||||
|
assert.equal(left.length, 6);
|
||||||
|
assert.equal(left.at(-1).entity, "new");
|
||||||
|
});
|
||||||
|
test("无效批次停止重试,未授权与暂时失败不直接丢弃", async (t) => {
|
||||||
|
const values = storage(t);
|
||||||
|
let code = 401;
|
||||||
|
t.mock.method(
|
||||||
|
globalThis,
|
||||||
|
"fetch",
|
||||||
|
async () => new Response("{}", { status: code }),
|
||||||
|
);
|
||||||
|
trackGrowth("user:invalid", "page_view", "discover");
|
||||||
|
await flushGrowth("user:invalid");
|
||||||
|
assert.equal(JSON.parse(values.get("dh-events:user:invalid")).length, 1);
|
||||||
|
code = 400;
|
||||||
|
await flushGrowth("user:invalid");
|
||||||
|
assert.equal(JSON.parse(values.get("dh-events:user:invalid")).length, 0);
|
||||||
|
});
|
||||||
|
test("推荐回执按账号角色隔离,过期后不再用于新故事归因", (t) => {
|
||||||
|
const values = storage(t);
|
||||||
|
rememberRecommendation("u", "card", "receipt");
|
||||||
|
assert.equal(recommendationReceipt("u", "card"), "receipt");
|
||||||
|
assert.equal(recommendationReceipt("other", "card"), undefined);
|
||||||
|
values.set(
|
||||||
|
"dh-recommendation:u:card",
|
||||||
|
JSON.stringify({ id: "expired", until: Date.now() - 100 }),
|
||||||
|
);
|
||||||
|
assert.equal(recommendationReceipt("u", "card"), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
import { sameOriginRequest } from "../src/lib/auth-origin.ts";
|
||||||
|
test("代理下公网Host可登录,跨站Origin和缺失Origin被拒绝", () => {
|
||||||
|
const make = (origin, host = "mrzhan.top") =>
|
||||||
|
new Request("http://127.0.0.1:3210/api/auth/login", {
|
||||||
|
headers: { host, ...(origin ? { origin } : {}) },
|
||||||
|
});
|
||||||
|
assert.equal(sameOriginRequest(make("https://mrzhan.top")), true);
|
||||||
|
for (const origin of [
|
||||||
|
"https://evil.test",
|
||||||
|
"null",
|
||||||
|
"https://mrzhan.top/path",
|
||||||
|
"https://mrzhan.top.evil.test",
|
||||||
|
undefined,
|
||||||
|
])
|
||||||
|
assert.equal(sameOriginRequest(make(origin)), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
import { readLoginInput } from "../src/lib/auth-input.ts";
|
||||||
|
test("登录公开入口限制真实字节数,不先无界解析JSON", async () => {
|
||||||
|
const request = (body) =>
|
||||||
|
new Request("http://localhost/api/auth/login", { method: "POST", body });
|
||||||
|
assert.deepEqual(
|
||||||
|
await readLoginInput(request('{"username":"user","password":"fixture"}')),
|
||||||
|
{ username: "user", password: "fixture" },
|
||||||
|
);
|
||||||
|
await assert.rejects(
|
||||||
|
readLoginInput(request(JSON.stringify({ username: "a".repeat(9000) }))),
|
||||||
|
RangeError,
|
||||||
|
);
|
||||||
|
for (const body of ["null", "[]", "invalid"])
|
||||||
|
await assert.rejects(readLoginInput(request(body)), SyntaxError);
|
||||||
|
});
|
||||||