diff --git a/README.md b/README.md index 00c8ca5..327a4ac 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # 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/dashboard +- 数字人空间:http://localhost:3210/discover +- 原工作台兼容入口:http://localhost:3210/dashboard - 任务:http://localhost:3210/tasks - 排班:http://localhost:3210/schedule - 公告:http://localhost:3210/announcements @@ -33,7 +34,7 @@ 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`,接受现有超级管理员或员工账号,登录成功后只把 JWT 写入 Next.js 服务端 HttpOnly Cookie,不写入 `localStorage`。 环境标识按 `APP_ENV` 区分: @@ -118,3 +119,12 @@ pnpm start:prod - 不把密码、JWT 或权限 token 持久化到前端存储。 - 员工端修改密码已通过 BFF 接入后端 `PATCH /api/auth/me/password`。 - 公告、任务、排班已按正式后端接口接入列表、筛选、详情和员工端操作;后端临时不可用时页面保留业务空态。 + +## 数字人空间 + +- `/discover` 为默认入口,复用原登录账户和 HttpOnly Cookie。 +- `src/components/digital-home.tsx`、`digital.css`:深色双 UI、移动/桌面适配、探索、流式对话、停止、重生成、分支、固定记忆、世界书与用户身份。 +- `src/lib/digital.ts`:前台协议、请求和 SSE 解码。 +- `src/app/api/digital/[...path]/route.ts`:白名单 BFF,只转发前台接口,禁止访问后台实验管理,写入校验同源。 +- 实验控制仅在 role-admin。前台没有切换实验或分组入口。 +- `DEEPSEEK_API_KEY` 仅在业务后端配置,前端不读取、不保存。 diff --git a/public/digital/cover-provenance.json b/public/digital/cover-provenance.json new file mode 100644 index 0000000..87ee637 --- /dev/null +++ b/public/digital/cover-provenance.json @@ -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" + } + ] +} \ No newline at end of file diff --git a/public/digital/covers/female-00.jpg b/public/digital/covers/female-00.jpg new file mode 100644 index 0000000..370cdbf Binary files /dev/null and b/public/digital/covers/female-00.jpg differ diff --git a/public/digital/covers/female-01.jpg b/public/digital/covers/female-01.jpg new file mode 100644 index 0000000..051ccd0 Binary files /dev/null and b/public/digital/covers/female-01.jpg differ diff --git a/public/digital/covers/female-02.jpg b/public/digital/covers/female-02.jpg new file mode 100644 index 0000000..d611f3e Binary files /dev/null and b/public/digital/covers/female-02.jpg differ diff --git a/public/digital/covers/female-03.jpg b/public/digital/covers/female-03.jpg new file mode 100644 index 0000000..8b38c8c Binary files /dev/null and b/public/digital/covers/female-03.jpg differ diff --git a/public/digital/covers/female-04.jpg b/public/digital/covers/female-04.jpg new file mode 100644 index 0000000..28b74c5 Binary files /dev/null and b/public/digital/covers/female-04.jpg differ diff --git a/public/digital/covers/female-05.jpg b/public/digital/covers/female-05.jpg new file mode 100644 index 0000000..28708af Binary files /dev/null and b/public/digital/covers/female-05.jpg differ diff --git a/public/digital/covers/female-06.jpg b/public/digital/covers/female-06.jpg new file mode 100644 index 0000000..a99b78e Binary files /dev/null and b/public/digital/covers/female-06.jpg differ diff --git a/public/digital/covers/female-07.jpg b/public/digital/covers/female-07.jpg new file mode 100644 index 0000000..790de14 Binary files /dev/null and b/public/digital/covers/female-07.jpg differ diff --git a/public/digital/covers/female-08.jpg b/public/digital/covers/female-08.jpg new file mode 100644 index 0000000..23201ab Binary files /dev/null and b/public/digital/covers/female-08.jpg differ diff --git a/public/digital/covers/female-09.jpg b/public/digital/covers/female-09.jpg new file mode 100644 index 0000000..97c3c81 Binary files /dev/null and b/public/digital/covers/female-09.jpg differ diff --git a/public/digital/covers/female-10.jpg b/public/digital/covers/female-10.jpg new file mode 100644 index 0000000..1485bb7 Binary files /dev/null and b/public/digital/covers/female-10.jpg differ diff --git a/public/digital/covers/female-11.jpg b/public/digital/covers/female-11.jpg new file mode 100644 index 0000000..e339d24 Binary files /dev/null and b/public/digital/covers/female-11.jpg differ diff --git a/public/digital/covers/female-12.jpg b/public/digital/covers/female-12.jpg new file mode 100644 index 0000000..99437af Binary files /dev/null and b/public/digital/covers/female-12.jpg differ diff --git a/public/digital/covers/female-13.jpg b/public/digital/covers/female-13.jpg new file mode 100644 index 0000000..e38572a Binary files /dev/null and b/public/digital/covers/female-13.jpg differ diff --git a/public/digital/covers/female-14.jpg b/public/digital/covers/female-14.jpg new file mode 100644 index 0000000..efa6a0c Binary files /dev/null and b/public/digital/covers/female-14.jpg differ diff --git a/public/digital/covers/female-15.jpg b/public/digital/covers/female-15.jpg new file mode 100644 index 0000000..b69b570 Binary files /dev/null and b/public/digital/covers/female-15.jpg differ diff --git a/public/digital/covers/female-16.jpg b/public/digital/covers/female-16.jpg new file mode 100644 index 0000000..ca01457 Binary files /dev/null and b/public/digital/covers/female-16.jpg differ diff --git a/public/digital/covers/male-00.jpg b/public/digital/covers/male-00.jpg new file mode 100644 index 0000000..fece01d Binary files /dev/null and b/public/digital/covers/male-00.jpg differ diff --git a/public/digital/covers/male-01.jpg b/public/digital/covers/male-01.jpg new file mode 100644 index 0000000..35d5676 Binary files /dev/null and b/public/digital/covers/male-01.jpg differ diff --git a/public/digital/covers/male-02.jpg b/public/digital/covers/male-02.jpg new file mode 100644 index 0000000..c69cf16 Binary files /dev/null and b/public/digital/covers/male-02.jpg differ diff --git a/public/icon.svg b/public/icon.svg index bde4fbb..713b642 100644 --- a/public/icon.svg +++ b/public/icon.svg @@ -1,13 +1 @@ - - - - - - - - - - - - - + \ No newline at end of file diff --git a/src/app/(auth)/login/page.tsx b/src/app/(auth)/login/page.tsx index 86c4a66..32bf924 100644 --- a/src/app/(auth)/login/page.tsx +++ b/src/app/(auth)/login/page.tsx @@ -1,38 +1,39 @@ +/** 星港登录页,沿用既有账号,无公开注册。 */ +import Link from "next/link"; import { LoginForm } from "@/components/login-form"; - +import "@/components/digital-login.css"; +/** 登录前展示独立品牌与简洁表单。 */ export default function LoginPage() { return ( -
-
-
- - Role User -
-

Employee Console

-

门店工作,清晰处理

-

排班、任务、公告和账号安全集中在同一个移动端工作区。

-
-
- - -
-
- 08:30 - 早班 · 正常 -
-
- - - -
+
+
+ + ✦{" "} + + 星港 STELLAR + + +
+

YOUR PRIVATE UNIVERSE

+

+ 每一段相遇, +
+ 都有下一章。 +

+ + 与你心动的角色对话, +
+ 在世界的另一端,写下属于你的故事。 +
+ 虚构相遇,真实灵感。
-
-
-

员工登录

-

使用手机号和临时密码进入工作台。

-
+
+ ✧ +

欢迎回到星港

+

使用你的现有账号,继续未完的故事。

+ 私人数字人空间 · 不开放公开注册
); diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts index 3f4f6ee..62617f2 100644 --- a/src/app/api/auth/login/route.ts +++ b/src/app/api/auth/login/route.ts @@ -1,3 +1,4 @@ +/** 数字人登录 BFF,令牌仅写入 HttpOnly Cookie,不返回浏览器。 */ import { setSessionToken } from "@/lib/session"; import { BackendError, backendRequest } from "@/lib/backend"; import type { LoginResponse } from "@/lib/types"; @@ -5,13 +6,13 @@ import type { LoginResponse } from "@/lib/types"; export async function POST(request: Request) { try { const body = await request.json(); - const result = await backendRequest("/auth/employee/login", { + const result = await backendRequest("/auth/digital/login", { method: "POST", body: JSON.stringify({ username: body.username, - password: body.password + password: body.password, }), - token: "" + token: "", }); await setSessionToken(result.token); @@ -21,8 +22,8 @@ export async function POST(request: Request) { data: { user: result.user, tokenType: result.tokenType, - expiresIn: result.expiresIn - } + expiresIn: result.expiresIn, + }, }); } catch (error) { const status = error instanceof BackendError ? error.status : 500; diff --git a/src/app/api/digital/[...path]/route.ts b/src/app/api/digital/[...path]/route.ts new file mode 100644 index 0000000..348a79f --- /dev/null +++ b/src/app/api/digital/[...path]/route.ts @@ -0,0 +1,94 @@ +/** 数字人 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|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|messages\/[a-zA-Z0-9_-]+))?)?)$/.test( + joined, + ) + ) + return Response.json({ message: "接口不存在" }, { status: 404 }); + 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 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}`, + { + 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; diff --git a/src/app/discover/page.tsx b/src/app/discover/page.tsx new file mode 100644 index 0000000..41b389c --- /dev/null +++ b/src/app/discover/page.tsx @@ -0,0 +1,12 @@ +/** 数字人前台首屏,服务端并行读取私有数据,避免浏览器加载瀑布。 */ +import { requireBackendData } from "@/lib/backend"; +import type { Bootstrap, Summary } from "@/lib/digital"; +import { DigitalHome } from "@/components/digital-home"; +/** 私有入口,后端鉴权失败时由统一助手返回登录。 */ +export default async function DiscoverPage() { + const [initial, initialSummaries] = await Promise.all([ + requireBackendData("/digital/bootstrap"), + requireBackendData("/digital/conversations"), + ]); + return ; +} diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 7792a07..6f50005 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,32 +1,39 @@ +/** 站点元信息与视口配置,保留系统缩放以支持可访问性。 */ import type { Metadata, Viewport } from "next"; import { connection } from "next/server"; import { getAppEnvLabel } from "@/lib/environment"; import "./globals.css"; +/** 星港品牌与安装元数据。 */ export const metadata: Metadata = { - title: "员工工作台", - description: "门店员工日常任务、排班、公告和个人中心", + title: "星港 · 数字人空间", + description: "与有故事的人相遇,让每一段对话继续生长", manifest: "/manifest.webmanifest", icons: { icon: "/icon.svg", - apple: "/icon.svg" + apple: "/icon.svg", }, appleWebApp: { capable: true, - title: "员工工作台", - statusBarStyle: "default" - } + title: "星港 · 数字人空间", + statusBarStyle: "default", + }, }; +/** 允许缩放并覆盖安全区,由页面布局补齐系统边距。 */ export const viewport: Viewport = { width: "device-width", initialScale: 1, - maximumScale: 1, - themeColor: "#ffffff" + viewportFit: "cover", + + themeColor: "#101010", }; -export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { +/** 全站根布局,私有数字人页面自行负责业务鉴权。 */ +export default async function RootLayout({ + children, +}: Readonly<{ children: React.ReactNode }>) { await connection(); const environmentLabel = getAppEnvLabel(); @@ -34,7 +41,10 @@ export default async function RootLayout({ children }: Readonly<{ children: Reac return ( -
+
{environmentLabel}
{children} diff --git a/src/app/manifest.ts b/src/app/manifest.ts index 3f882b1..3b55cc0 100644 --- a/src/app/manifest.ts +++ b/src/app/manifest.ts @@ -1,21 +1,22 @@ +/** 数字人空间 PWA 元数据,保留原有安装机制。 */ import type { MetadataRoute } from "next"; export default function manifest(): MetadataRoute.Manifest { return { - name: "role-user 员工工作台", - short_name: "员工工作台", - description: "门店员工任务、公告、排班和个人中心", - start_url: "/dashboard", + name: "星港 · 数字人空间", + short_name: "星港", + description: "你的私人数字人空间", + start_url: "/discover", scope: "/", display: "standalone", - background_color: "#f4f4f6", - theme_color: "#ffffff", + background_color: "#141218", + theme_color: "#141218", icons: [ { src: "/icon.svg", sizes: "any", - type: "image/svg+xml" - } - ] + type: "image/svg+xml", + }, + ], }; } diff --git a/src/app/page.tsx b/src/app/page.tsx index 9ef1235..c2d286d 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,5 +1,6 @@ +/** 默认入口进入数字人空间,登录由目标页统一校验。 */ import { redirect } from "next/navigation"; - +/** 私有站点首页。 */ export default function HomePage() { - redirect("/dashboard"); + redirect("/discover"); } diff --git a/src/components/digital-home.tsx b/src/components/digital-home.tsx new file mode 100644 index 0000000..d7554d3 --- /dev/null +++ b/src/components/digital-home.tsx @@ -0,0 +1,1508 @@ +"use client"; +/* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */ +/** 星港数字人空间:探索、会话、世界书和身份资料的响应式入口。 */ +import Link from "next/link"; +import { + useCallback, + useEffect, + useRef, + useState, + type FormEvent, + type KeyboardEvent, +} from "react"; +import { + ArrowLeft, + ArrowUp, + BookOpen, + Check, + Copy, + GitBranch, + Heart, + LoaderCircle, + LogOut, + MessageCircle, + MoreHorizontal, + Pin, + Plus, + Search, + Settings2, + Sparkles, + Square, + Trash2, + UserRound, + WandSparkles, + X, + RefreshCw, + Download, + ChevronDown, +} from "lucide-react"; +import { + digital, + readStream, + type Card, + type Profile, + type Message, + type Settings, + type Conversation, + type Summary, + type Bootstrap, +} from "@/lib/digital"; +import "./digital.css"; +type Tab = "discover" | "chats" | "library" | "me"; +/** 接收文本与视觉打字分离;减少动画设置下直接呈现完整文本。 */ +function TypedText({ text, animate }: { text: string; animate: boolean }) { + const [shown, setShown] = useState(animate ? "" : text); + const latest = useRef(text); + useEffect(() => { + latest.current = text; + }, [text]); + useEffect(() => { + if (!animate) return; + const instant = window.matchMedia( + "(prefers-reduced-motion: reduce)", + ).matches; + const timer = setInterval( + () => + setShown((current) => { + const target = latest.current; + if (instant || !target.startsWith(current)) return target; + const rest = Array.from(target.slice(current.length)); + return ( + current + + rest + .slice(0, Math.max(1, Math.min(10, Math.ceil(rest.length / 15)))) + .join("") + ); + }), + 24, + ); + return () => clearInterval(timer); + }, [animate]); + return <>{animate ? shown : text}; +} +/** 内容完全作为文本渲染,角色对白不允许注入 HTML。 */ +function MessageText({ + message, + animate, +}: { + message: Message; + animate: boolean; +}) { + return ( +
+ + {message.status === "generating" && ( + + )} +
+ ); +} +/** 前台无分组按钮、调试开关或实验配置。 */ +export function DigitalHome({ + initial, + initialSummaries, +}: { + initial: Bootstrap; + initialSummaries: Summary[]; +}) { + const [tab, setTab] = useState("discover"), + [boot, setBoot] = useState(initial), + [summaries, setSummaries] = useState(initialSummaries); + const [query, setQuery] = useState(""), + [tag, setTag] = useState("全部"), + [onlyFavorites, setOnlyFavorites] = useState(false); + const [detail, setDetail] = useState(null), + [conversation, setConversation] = useState(null); + const [draft, setDraft] = useState(""), + [busy, setBusy] = useState(false), + [opening, setOpening] = useState(false), + [error, setError] = useState(""), + [notice, setNotice] = useState(""); + const [showSettings, setShowSettings] = useState(false), + [settings, setSettings] = useState(null), + [profile, setProfile] = useState(initial.profile); + const [profileDraft, setProfileDraft] = useState( + initial.profile, + ); + const favoritePending = useRef(false); + const [activeMessage, setActiveMessage] = useState(null), + [showJump, setShowJump] = useState(false), + [showMenu, setShowMenu] = useState(false); + const decisionReceived = useRef(0); + const stream = useRef(null), + streamingId = useRef(null), + viewport = useRef(null), + messagesElement = useRef(null), + textarea = useRef(null), + atBottom = useRef(true), + currentId = useRef(null), + openSequence = useRef(0); + const cards = boot?.catalog.filter((c) => c.kind === "character") ?? [], + books = boot?.catalog.filter((c) => c.kind === "worldbook") ?? [], + presets = boot?.catalog.filter((c) => c.kind === "preset") ?? []; + const conversationId = conversation?.id; + const decisionExpiresAt = boot?.decision.expiresAt, + decisionServerNow = boot?.serverNow; + const currentCard = cards.find((c) => c.id === conversation?.characterId); + const reportError = useCallback( + (e: unknown) => + setError(e instanceof Error ? e.message : "请求失败,请重试"), + [], + ); + const refreshSummaries = useCallback( + async () => setSummaries(await digital("conversations")), + [], + ); + const reloadBootstrap = useCallback(async () => { + const data = await digital("bootstrap"); + decisionReceived.current = performance.now(); + setBoot(data); + setProfile(data.profile); + }, []); + useEffect(() => { + decisionReceived.current = performance.now(); + }, [initial]); + useEffect(() => { + const timer = setInterval(() => { + if (!document.hidden && !streamingId.current) + reloadBootstrap().catch(() => {}); + }, 45000); + const onVisible = () => { + if (!document.hidden && !streamingId.current) + reloadBootstrap().catch(() => {}); + }; + document.addEventListener("visibilitychange", onVisible); + return () => { + clearInterval(timer); + document.removeEventListener("visibilitychange", onVisible); + stream.current?.abort(); + }; + }, [reloadBootstrap]); + useEffect(() => { + if (!decisionExpiresAt || !decisionServerNow) return; + const lifetime = Math.max( + 0, + Math.min(60000, decisionExpiresAt - decisionServerNow), + ); + const remaining = Math.max( + 0, + lifetime - (performance.now() - decisionReceived.current), + ); + const timer = setTimeout( + () => + setBoot((current) => + current + ? { + ...current, + decision: { + ...current.decision, + variant: current.decision.fallbackVariant, + decisionId: null, + }, + } + : current, + ), + remaining, + ); + return () => clearTimeout(timer); + }, [decisionExpiresAt, decisionServerNow]); + useEffect(() => { + if (!notice) return; + const timer = setTimeout(() => setNotice(""), 3500); + return () => clearTimeout(timer); + }, [notice]); + useEffect(() => { + const el = messagesElement.current; + if (!el) return; + const observer = new ResizeObserver(() => { + if (atBottom.current) + viewport.current?.scrollTo({ + top: viewport.current.scrollHeight, + behavior: "instant", + }); + }); + observer.observe(el); + return () => observer.disconnect(); + }, [conversationId]); + useEffect(() => { + if (!conversationId) return; + const resize = () => + document.documentElement.style.setProperty( + "--dh-viewport", + `${window.visualViewport?.height ?? window.innerHeight}px`, + ); + resize(); + window.visualViewport?.addEventListener("resize", resize); + return () => { + window.visualViewport?.removeEventListener("resize", resize); + document.documentElement.style.removeProperty("--dh-viewport"); + }; + }, [conversationId]); + useEffect(() => { + if (!conversationId) return; + try { + sessionStorage.setItem(`dh-draft:${conversationId}`, draft); + } catch {} + }, [draft, conversationId]); + useEffect(() => { + if (!detail && !showSettings) return; + const previous = document.activeElement as HTMLElement | null; + const dialog = document.querySelector( + '.dh-overlay [role="dialog"]', + ); + const controls = () => + Array.from( + dialog?.querySelectorAll( + 'button:not([disabled]),input,textarea,select,[tabindex="0"]', + ) ?? [], + ); + const frame = requestAnimationFrame(() => controls()[0]?.focus()); + const onKey = (event: globalThis.KeyboardEvent) => { + if (event.key === "Escape") { + setDetail(null); + setShowSettings(false); + } + if (event.key === "Tab") { + const items = controls(), + first = items[0], + last = items.at(-1); + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last?.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first?.focus(); + } + } + }; + document.addEventListener("keydown", onKey); + return () => { + cancelAnimationFrame(frame); + document.removeEventListener("keydown", onKey); + previous?.focus(); + }; + }, [detail, showSettings]); + useEffect(() => { + const id = boot?.decision.decisionId; + if (!id || document.hidden) return; + const frame = requestAnimationFrame(() => + digital("exposure", "POST", { decisionId: id }).catch(() => {}), + ); + return () => cancelAnimationFrame(frame); + }, [boot?.decision.decisionId]); + useEffect(() => { + if (!busy || !conversationId || streamingId.current) return; + let cancelled = false; + const timer = setInterval(async () => { + if (document.hidden) return; + try { + const saved = await digital( + `conversations/${conversationId}`, + ); + if (!cancelled && currentId.current === conversationId) { + setConversation(saved); + setBusy(saved.busy); + } + } catch {} + }, 2000); + return () => { + cancelled = true; + clearInterval(timer); + }; + }, [busy, conversationId]); + async function openConversation(id: string) { + if (streamingId.current && streamingId.current !== id) { + setNotice("请先停止当前回复,再切换会话"); + return; + } + const sequence = ++openSequence.current; + setOpening(true); + setError(""); + try { + const c = await digital(`conversations/${id}`); + if (sequence !== openSequence.current) return; + setConversation(c); + currentId.current = id; + setSettings(c.settings); + setBusy(c.busy); + setActiveMessage(null); + setShowMenu(false); + atBottom.current = true; + try { + setDraft(sessionStorage.getItem(`dh-draft:${id}`) ?? ""); + } catch { + setDraft(""); + } + setTab("chats"); + setDetail(null); + } catch (e) { + reportError(e); + } finally { + if (sequence === openSequence.current) setOpening(false); + } + } + async function start(card: Card, index = 0) { + if (opening) return; + setOpening(true); + setError(""); + try { + const c = await digital<{ id: string }>("conversations", "POST", { + characterId: card.id, + greetingIndex: index, + uiDecisionId: boot?.decision.decisionId ?? undefined, + }); + await openConversation(c.id); + await refreshSummaries(); + } catch (e) { + reportError(e); + } finally { + setOpening(false); + } + } + async function favorite(card: Card) { + if (!profile || favoritePending.current) return; + favoritePending.current = true; + const next = { + ...profile, + favorites: profile.favorites.includes(card.id) + ? profile.favorites.filter((v) => v !== card.id) + : [...profile.favorites, card.id], + }; + try { + await digital("profile", "PUT", next); + setProfile(next); + } catch (e) { + reportError(e); + } finally { + favoritePending.current = false; + } + } + async function send(mode: "send" | "regenerate" = "send") { + if ( + !conversation || + busy || + streamingId.current || + (mode === "send" && !draft.trim()) + ) + return; + const id = conversation.id, + content = draft.trim(), + requestId = crypto.randomUUID(); + let assistantId = `pending-${requestId}`; + setBusy(true); + setError(""); + setNotice(""); + atBottom.current = true; + streamingId.current = id; + if (mode === "send") setDraft(""); + const local: Message[] = [ + ...(mode === "send" + ? [ + { + id: `user-${requestId}`, + role: "user" as const, + content, + status: "complete", + pinned: false, + }, + ] + : []), + { + id: assistantId, + role: "assistant", + content: "", + status: "generating", + pinned: false, + }, + ]; + setConversation((c) => + c && c.id === id ? { ...c, messages: [...c.messages, ...local] } : c, + ); + setActiveMessage(assistantId); + const controller = new AbortController(); + stream.current = controller; + let accepted = false; + try { + const response = await fetch(`/api/digital/conversations/${id}/stream`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + requestId, + content, + mode, + uiDecisionId: boot?.decision.decisionId ?? undefined, + }), + signal: controller.signal, + }); + if (response.status === 401) { + window.location.assign("/login"); + return; + } + accepted = response.ok; + await readStream(response, (event, data) => { + if (event === "start") { + const next = String(data.messageId); + setConversation((c) => + c && c.id === id + ? { + ...c, + messages: c.messages.map((m) => + m.id === assistantId ? { ...m, id: next } : m, + ), + } + : c, + ); + assistantId = next; + setActiveMessage(next); + } + if (event === "delta") + setConversation((c) => + c && c.id === id + ? { + ...c, + messages: c.messages.map((m) => + m.id === assistantId + ? { ...m, content: m.content + String(data.text ?? "") } + : m, + ), + } + : c, + ); + if (event === "done") + setConversation((c) => + c && c.id === id + ? { + ...c, + messages: c.messages.map((m) => + m.id === assistantId + ? { ...m, status: String(data.status) } + : m, + ), + } + : c, + ); + if (event === "notice" || event === "error") + setNotice(String(data.message ?? "")); + }); + } catch (e) { + if (!controller.signal.aborted) reportError(e); + if (!accepted && mode === "send") setDraft(content); + } finally { + streamingId.current = null; + stream.current = null; + setBusy(false); + // 从数据库收敛临时消息和最终状态;取消后服务端可能仍在提交,延后一帧刷新。 + await new Promise((resolve) => setTimeout(resolve, 200)); + if (currentId.current === id) + try { + const saved = await digital(`conversations/${id}`); + setConversation(saved); + setBusy(saved.busy); + } catch (e) { + reportError(e); + } + refreshSummaries().catch(() => {}); + } + } + async function stop() { + if (!conversation) return; + try { + await digital(`conversations/${conversation.id}/stop`, "POST", {}); + if (!stream.current) { + await openConversation(conversation.id); + } + } catch (e) { + reportError(e); + } + } + function onKey(event: KeyboardEvent) { + if ( + event.key === "Enter" && + !event.shiftKey && + !event.nativeEvent.isComposing && + window.matchMedia("(min-width: 768px)").matches + ) { + event.preventDefault(); + void send(); + } + } + async function pin(message: Message) { + if (!conversation) return; + try { + await digital( + `conversations/${conversation.id}/messages/${message.id}`, + "PATCH", + { pinned: !message.pinned }, + ); + setConversation((c) => + c + ? { + ...c, + messages: c.messages.map((m) => + m.id === message.id ? { ...m, pinned: !m.pinned } : m, + ), + } + : c, + ); + setNotice(message.pinned ? "已取消固定" : "已加入固定记忆"); + } catch (e) { + reportError(e); + } + } + async function branch(message: Message) { + if (!conversation || busy) return; + try { + const result = await digital<{ id: string }>( + `conversations/${conversation.id}/branch`, + "POST", + { messageId: message.id }, + ); + await openConversation(result.id); + await refreshSummaries(); + setNotice("已从这里开启新分支,原会话仍然保留"); + } catch (e) { + reportError(e); + } + } + async function removeConversation() { + if ( + !conversation || + busy || + !window.confirm("删除此会话和全部消息?此操作无法撤销。") + ) + return; + try { + await digital(`conversations/${conversation.id}`, "DELETE"); + setConversation(null); + currentId.current = null; + await refreshSummaries(); + } catch (e) { + reportError(e); + } + } + async function saveSettings(event: FormEvent) { + event.preventDefault(); + if (!conversation || !settings) return; + try { + await digital(`conversations/${conversation.id}`, "PATCH", { settings }); + setConversation((c) => (c ? { ...c, settings } : c)); + setShowSettings(false); + setNotice("对话设定已保存,下次回复生效"); + } catch (e) { + reportError(e); + } + } + async function saveProfile(event: FormEvent) { + event.preventDefault(); + if (!profile || !profileDraft) return; + const next = { + ...profile, + userName: profileDraft.userName, + persona: profileDraft.persona, + }; + try { + await digital("profile", "PUT", next); + setProfile(next); + setNotice("身份资料已保存"); + } catch (e) { + reportError(e); + } + } + async function copy(text: string) { + try { + await navigator.clipboard.writeText(text); + setNotice("已复制"); + } catch { + setNotice("当前浏览器无法访问剪贴板"); + } + } + function exportChat() { + if (!conversation) return; + const text = conversation.messages + .map( + (m) => + `${m.role === "user" ? "我" : (currentCard?.name ?? "角色")}:\n${m.content}`, + ) + .join("\n\n"); + const url = URL.createObjectURL( + new Blob([text], { type: "text/plain;charset=utf-8" }), + ); + const a = document.createElement("a"); + a.href = url; + a.download = `${conversation.title}.txt`; + a.click(); + URL.revokeObjectURL(url); + } + function switchTab(value: Tab) { + if (conversation && busy) { + setNotice("请先停止当前回复,再离开会话"); + return; + } + setConversation(null); + currentId.current = null; + setTab(value); + setError(""); + } + const tags = [ + "全部", + ...new Set(cards.flatMap((c) => c.tags).slice(0, 30)), + ].slice(0, 12); + const filtered = cards.filter( + (c) => + (!query || + `${c.name} ${c.description} ${c.tags.join(" ")}` + .toLowerCase() + .includes(query.toLowerCase())) && + (tag === "全部" || c.tags.includes(tag)) && + (!onlyFavorites || profile?.favorites.includes(c.id)), + ); + const modern = boot?.decision.variant === "B"; + return ( +
+ +
+ {error && ( +
+ {error} + +
+ )} + {notice && ( +
+ {notice} +
+ )} + {!boot ? ( +
+ + 正在开启你的星港… +
+ ) : conversation ? ( +
+
+ + {currentCard?.cover && } +
+

{currentCard?.name ?? conversation.title}

+ + {busy ? "正在回应你" : "故事由你们续写"} + +
+ + + {showMenu && ( +
+ + +
+ )} +
+
+
{ + const v = viewport.current; + if (v) { + atBottom.current = + v.scrollHeight - v.scrollTop - v.clientHeight < 110; + setShowJump(!atBottom.current); + } + }} + > +
+
+ ✦ +

这里是你与 {currentCard?.name} 的私人故事

+ 内容由 AI 生成,虚构世界中的角色可能会犯错。 +
+ {conversation.messages.map((m, index) => ( +
+ {m.role === "assistant" && ( + + )} +
+ + {m.role === "user" + ? conversation.settings.userName + : currentCard?.name} + {m.pinned && } + +
+ + {!m.content && m.status === "generating" && ( + + + + + + )} +
+ {!busy && m.content && ( +
+ + + + {m.role === "assistant" && + index === conversation.messages.length - 1 && + conversation.messages.some( + (v) => v.role === "user", + ) && ( + + )} +
+ )} + {!busy && + !m.content && + m.role === "assistant" && + index === conversation.messages.length - 1 && + conversation.messages.some( + (v) => v.role === "user", + ) && ( + + )} + {m.status === "failed" && ( + + 生成失败,可重新生成 + + )} + {m.status === "superseded" && ( + 此前回答 + )} + {m.status === "stopped" && ( + 已停止 + )} +
+
+ ))} +
+
+ {showJump && ( + + )} +
+
+