feat(digital): 打造星港响应式数字人对话空间

新增角色探索、收藏、世界书和身份资料;接入流式打字、停止重生成、固定记忆、会话分支与导出;适配手机和桌面并保持实验只由后台控制。
This commit is contained in:
湛兮
2026-10-27 10:25:40 +08:00
parent 6b0dd6ea67
commit b7433acba4
37 changed files with 3914 additions and 106 deletions
+32 -8
View File
@@ -1,3 +1,4 @@
/** 服务端后端访问与会话错误转换,统一保留业务错误文案。 */
import "server-only";
import { redirect } from "next/navigation";
@@ -5,29 +6,42 @@ import { redirect } from "next/navigation";
import { clearSessionToken, getSessionToken } from "@/lib/session";
import type { ApiEnvelope } from "@/lib/types";
/** 保留后端状态以便 BFF 清理失效会话。 */
export class BackendError extends Error {
constructor(
message: string,
public status: number
public status: number,
) {
super(message);
}
}
/** 后端根地址仅由服务端环境配置决定。 */
export function getBackendBaseUrl() {
return process.env.ACCESS_MANAGE_API_BASE_URL || "http://localhost:3500/api";
}
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> {
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) {
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) {
@@ -37,9 +51,10 @@ async function parseBackendResponse<T>(response: Response): Promise<T> {
return payload as T;
}
/** 为服务端请求附加 HttpOnly 会话并禁止缓存私有数据。 */
export async function backendRequest<T>(
path: string,
init: RequestInit & { token?: string; allowUnauthorized?: boolean } = {}
init: RequestInit & { token?: string; allowUnauthorized?: boolean } = {},
) {
const token = init.token ?? (await getSessionToken());
const headers = new Headers(init.headers);
@@ -55,12 +70,13 @@ export async function backendRequest<T>(
const response = await fetch(toUrl(path), {
...init,
headers,
cache: "no-store"
cache: "no-store",
});
return parseBackendResponse<T>(response);
}
/** 页面数据要求登录,失效时通过登出路由清理 Cookie。 */
export async function requireBackendData<T>(path: string) {
try {
return await backendRequest<T>(path);
@@ -73,7 +89,11 @@ export async function requireBackendData<T>(path: string) {
}
}
export async function proxyBackendJson<T>(path: string, init: RequestInit = {}) {
/** 包装普通 JSON 业务接口,流式对话使用专用 BFF。 */
export async function proxyBackendJson<T>(
path: string,
init: RequestInit = {},
) {
try {
const data = await backendRequest<T>(path, init);
return Response.json({ success: true, data } satisfies ApiEnvelope<T>);
@@ -82,7 +102,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 message = error instanceof Error ? error.message : fallbackMessage;
+132
View File
@@ -0,0 +1,132 @@
/** 数字人客户端协议与事件解码,不包含模型凭据或实验操作。 */
/** 前台可见内容摘要,提示词不会下发。 */
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;
};
/** 会话消息拥有持久化 id,避免流式刷新时重复插入。 */
export type Message = {
id: string;
role: "user" | "assistant";
content: string;
status: string;
pinned: boolean;
sequenceId?: number;
};
/** 不含实验配置的会话偏好。 */
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[];
};
/** 通用请求保留服务端错误文本,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("/login");
throw new Error("登录已过期");
}
if (!response.ok || data.success === false)
throw new Error(data.error?.message ?? data.message ?? "请求失败");
return data.data as T;
}
/** 网络分片可跨多个 SSE 事件,最后不完整事件不会被误解析。 */
export async function readStream(
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 = "";
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) onEvent(event, JSON.parse(data));
}
if (done) break;
}
} finally {
reader.releaseLock();
}
}
/** 会话列表摘要。 */
export type Summary = {
id: string;
characterId: string;
title: string;
updatedAt: string;
};
/** 服务端首屏数据,仅包含可公开的内容摘要和当前账号决策。 */
export type Bootstrap = {
catalog: Card[];
profile: Profile;
decision: {
variant: "A" | "B";
decisionId: string | null;
expiresAt: number;
fallbackVariant: "A" | "B";
};
serverNow: number;
};