Compare commits
9 Commits
master
..
fbd946c9be
| Author | SHA1 | Date | |
|---|---|---|---|
| fbd946c9be | |||
| 0e04f54616 | |||
| e6a95b3d35 | |||
| e1aa51d8b2 | |||
| cb1314470a | |||
| f921204dc8 | |||
| c45fb9c941 | |||
| 6a40040573 | |||
| d3fe1b21ed |
@@ -195,28 +195,3 @@ NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成
|
|||||||
路由与深链回归:`node --experimental-strip-types --test tests/*.test.mjs`;类型检查和构建按上面的项目命令执行。
|
路由与深链回归:`node --experimental-strip-types --test tests/*.test.mjs`;类型检查和构建按上面的项目命令执行。
|
||||||
|
|
||||||
`pnpm typecheck` 会先清理生产路由类型目录 `.next/types` 并执行 `next typegen`,再运行 TypeScript。这样 CI 在迁移页面目录或新增路由后不会复用上一版的路由声明;不清理整个构建产物目录。
|
`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,40 +0,0 @@
|
|||||||
/** 游客令牌与复用凭据只保存在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,32 +1,21 @@
|
|||||||
/** 数字人登录 BFF,令牌仅写入 HttpOnly Cookie,不返回浏览器。 */
|
/** 数字人登录 BFF,令牌仅写入 HttpOnly Cookie,不返回浏览器。 */
|
||||||
import { readLoginInput } from "@/lib/auth-input";
|
import { setSessionToken } from "@/lib/session";
|
||||||
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 cookieStore = await cookies(),
|
const body = await request.json();
|
||||||
cookieName = getSessionCookieName();
|
|
||||||
const body = await readLoginInput(request);
|
|
||||||
const result = await backendRequest<LoginResponse>("/auth/digital/login", {
|
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,
|
||||||
@@ -37,12 +26,7 @@ export async function POST(request: Request) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const status =
|
const status = error instanceof BackendError ? error.status : 500;
|
||||||
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 });
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ async function proxy(
|
|||||||
const { path } = await context.params;
|
const { path } = await context.params;
|
||||||
const joined = path.join("/");
|
const joined = path.join("/");
|
||||||
if (
|
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(
|
!/^(bootstrap|profile|exposure|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|suggestions|style-policy|messages\/[a-zA-Z0-9_-]+))?)?)$/.test(
|
||||||
joined,
|
joined,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -55,12 +55,6 @@ async function proxy(
|
|||||||
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
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();
|
const token = await getSessionToken();
|
||||||
if (!token) return Response.json({ message: "请先登录" }, { status: 401 });
|
if (!token) return Response.json({ message: "请先登录" }, { status: 401 });
|
||||||
const headers = new Headers({
|
const headers = new Headers({
|
||||||
@@ -69,7 +63,7 @@ async function proxy(
|
|||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${getBackendBaseUrl().replace(/\/$/, "")}/digital/${joined}${query}`,
|
`${getBackendBaseUrl().replace(/\/$/, "")}/digital/${joined}`,
|
||||||
{
|
{
|
||||||
method: request.method,
|
method: request.method,
|
||||||
headers,
|
headers,
|
||||||
|
|||||||
@@ -1,81 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
"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("对话名称已保存");
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -126,13 +126,8 @@ export function ConversationRow({
|
|||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img src={card?.cover || "/icon.svg"} alt="" draggable={false} />
|
<img src={card?.cover || "/icon.svg"} alt="" draggable={false} />
|
||||||
<div>
|
<div>
|
||||||
<h3>
|
<h3>{summary.title}</h3>
|
||||||
{summary.pinned ? "置顶 · " : ""}
|
<p>{card?.description || "继续这段私人对话"}</p>
|
||||||
{summary.title}
|
|
||||||
</h3>
|
|
||||||
<p>
|
|
||||||
{summary.lastMessage || card?.description || "继续这段私人对话"}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
<small>
|
<small>
|
||||||
{new Date(summary.updatedAt).toLocaleDateString("zh-CN", {
|
{new Date(summary.updatedAt).toLocaleDateString("zh-CN", {
|
||||||
|
|||||||
+87
-490
@@ -10,12 +10,6 @@ import {
|
|||||||
expiredDigitalSessionPath,
|
expiredDigitalSessionPath,
|
||||||
type DigitalTab,
|
type DigitalTab,
|
||||||
} from "@/lib/digital-routes";
|
} from "@/lib/digital-routes";
|
||||||
import { GrowthJourney } from "./growth-journey";
|
|
||||||
import { GrowthRecommendations } from "./growth-recommendations";
|
|
||||||
import { GrowthProfile } from "./growth-profile";
|
|
||||||
import { GrowthChat, ReplyFeedback } from "./growth-chat";
|
|
||||||
import { trackGrowth, flushGrowth, recommendationReceipt } from "@/lib/growth";
|
|
||||||
import { mergeConversationSnapshot } from "@/lib/digital-recovery";
|
|
||||||
import { useDigitalBack } from "./digital-route-history";
|
import { useDigitalBack } from "./digital-route-history";
|
||||||
import {
|
import {
|
||||||
useCallback,
|
useCallback,
|
||||||
@@ -63,10 +57,7 @@ import {
|
|||||||
type Summary,
|
type Summary,
|
||||||
type Bootstrap,
|
type Bootstrap,
|
||||||
} from "@/lib/digital";
|
} from "@/lib/digital";
|
||||||
import { ConversationDeleteDialog } from "./conversation-row";
|
import { ConversationRow, ConversationDeleteDialog } from "./conversation-row";
|
||||||
import { ConversationList } from "./conversation-list";
|
|
||||||
import { ConversationTitleDialog } from "./conversation-dialogs";
|
|
||||||
import { useChatReading } from "./use-chat-reading";
|
|
||||||
import { DigitalMessage } from "./digital-message";
|
import { DigitalMessage } from "./digital-message";
|
||||||
import "./digital.css";
|
import "./digital.css";
|
||||||
type Tab = DigitalTab;
|
type Tab = DigitalTab;
|
||||||
@@ -114,22 +105,6 @@ export function DigitalHome({
|
|||||||
initialConversation ?? null,
|
initialConversation ?? null,
|
||||||
);
|
);
|
||||||
const [draftReady, setDraftReady] = useState(false);
|
const [draftReady, setDraftReady] = useState(false);
|
||||||
const [branchTarget, setBranchTarget] = useState<Message | null>(null);
|
|
||||||
const [undo, setUndo] = useState<{
|
|
||||||
id: string;
|
|
||||||
title: string;
|
|
||||||
until: number;
|
|
||||||
} | null>(null);
|
|
||||||
const [undoBusy, setUndoBusy] = useState(false);
|
|
||||||
const undoLock = useRef(false);
|
|
||||||
const [interrupted, setInterrupted] = useState(false);
|
|
||||||
const [canRetryRequest, setCanRetryRequest] = useState(false);
|
|
||||||
const undoKey = `dh-undo:${initial.account}`;
|
|
||||||
const pendingSend = useRef<{
|
|
||||||
id: string;
|
|
||||||
requestId: string;
|
|
||||||
content: string;
|
|
||||||
} | null>(null);
|
|
||||||
const [draft, setDraft] = useState(""),
|
const [draft, setDraft] = useState(""),
|
||||||
[busy, setBusy] = useState(initialConversation?.busy ?? false),
|
[busy, setBusy] = useState(initialConversation?.busy ?? false),
|
||||||
[opening, setOpening] = useState(false),
|
[opening, setOpening] = useState(false),
|
||||||
@@ -154,6 +129,9 @@ export function DigitalHome({
|
|||||||
bookIds: string[];
|
bookIds: string[];
|
||||||
}>({ bookIds: [] });
|
}>({ bookIds: [] });
|
||||||
const selectionTrigger = useRef<HTMLElement | null>(null);
|
const selectionTrigger = useRef<HTMLElement | null>(null);
|
||||||
|
const [swipedConversation, setSwipedConversation] = useState<string | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
const [deleteTarget, setDeleteTarget] = useState<Summary | null>(null),
|
const [deleteTarget, setDeleteTarget] = useState<Summary | null>(null),
|
||||||
[deleting, setDeleting] = useState(false),
|
[deleting, setDeleting] = useState(false),
|
||||||
[deleteError, setDeleteError] = useState("");
|
[deleteError, setDeleteError] = useState("");
|
||||||
@@ -297,36 +275,36 @@ export function DigitalHome({
|
|||||||
const timer = setTimeout(() => setNotice(""), 3500);
|
const timer = setTimeout(() => setNotice(""), 3500);
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, [notice]);
|
}, [notice]);
|
||||||
const unread = useChatReading(
|
|
||||||
conversationId,
|
|
||||||
viewport,
|
|
||||||
messagesElement,
|
|
||||||
atBottom,
|
|
||||||
draggingScroll,
|
|
||||||
setShowJump,
|
|
||||||
);
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setTimeout(() => {
|
const el = messagesElement.current,
|
||||||
try {
|
view = viewport.current;
|
||||||
const stored = JSON.parse(sessionStorage.getItem(undoKey) ?? "null");
|
if (!el || !view) return;
|
||||||
if (stored?.until > Date.now()) setUndo(stored);
|
let frame = 0;
|
||||||
} catch {}
|
const follow = () => {
|
||||||
}, 0);
|
cancelAnimationFrame(frame);
|
||||||
return () => clearTimeout(timer);
|
frame = requestAnimationFrame(() => {
|
||||||
}, [undoKey]);
|
if (!atBottom.current) return;
|
||||||
useEffect(() => {
|
view.scrollTo({ top: view.scrollHeight, behavior: "instant" });
|
||||||
if (!undo) return;
|
setShowJump(false);
|
||||||
const timer = setTimeout(
|
});
|
||||||
() => {
|
};
|
||||||
setUndo(null);
|
// 同时观察内容与可视区:视觉打字、结束后的操作栏、输入框和软键盘都会改变底部位置。
|
||||||
try {
|
const observer = new ResizeObserver(follow);
|
||||||
sessionStorage.removeItem(undoKey);
|
observer.observe(el);
|
||||||
} catch {}
|
observer.observe(view);
|
||||||
},
|
const endDrag = () => {
|
||||||
Math.max(0, undo.until - Date.now()),
|
draggingScroll.current = false;
|
||||||
);
|
};
|
||||||
return () => clearTimeout(timer);
|
window.addEventListener("pointerup", endDrag);
|
||||||
}, [undo, undoKey]);
|
window.addEventListener("pointercancel", endDrag);
|
||||||
|
follow();
|
||||||
|
return () => {
|
||||||
|
observer.disconnect();
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
window.removeEventListener("pointerup", endDrag);
|
||||||
|
window.removeEventListener("pointercancel", endDrag);
|
||||||
|
};
|
||||||
|
}, [conversationId]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!conversationId) return;
|
if (!conversationId) return;
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
@@ -373,35 +351,12 @@ export function DigitalHome({
|
|||||||
if (!conversationId) return;
|
if (!conversationId) return;
|
||||||
const frame = requestAnimationFrame(() => {
|
const frame = requestAnimationFrame(() => {
|
||||||
try {
|
try {
|
||||||
const storedDraft =
|
setDraft(sessionStorage.getItem(`dh-draft:${conversationId}`) ?? "");
|
||||||
sessionStorage.getItem(`dh-draft:${conversationId}`) ?? "";
|
|
||||||
setDraft(storedDraft);
|
|
||||||
const pending = JSON.parse(
|
|
||||||
sessionStorage.getItem(`dh-pending:${conversationId}`) ?? "null",
|
|
||||||
);
|
|
||||||
if (
|
|
||||||
pending?.id === conversationId &&
|
|
||||||
typeof pending.content === "string" &&
|
|
||||||
/^[a-f0-9-]{36}$/.test(pending.requestId)
|
|
||||||
) {
|
|
||||||
if (
|
|
||||||
initialConversation?.messages.some(
|
|
||||||
(m) => m.requestId === pending.requestId,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
sessionStorage.removeItem(`dh-pending:${conversationId}`);
|
|
||||||
if (storedDraft === pending.content) setDraft("");
|
|
||||||
} else {
|
|
||||||
pendingSend.current = pending;
|
|
||||||
setCanRetryRequest(true);
|
|
||||||
setInterrupted(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {}
|
} catch {}
|
||||||
setDraftReady(true);
|
setDraftReady(true);
|
||||||
});
|
});
|
||||||
return () => cancelAnimationFrame(frame);
|
return () => cancelAnimationFrame(frame);
|
||||||
}, [conversationId, initialConversation]);
|
}, [conversationId]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!conversationId || !draftReady) return;
|
if (!conversationId || !draftReady) return;
|
||||||
try {
|
try {
|
||||||
@@ -499,9 +454,7 @@ export function DigitalHome({
|
|||||||
`conversations/${conversationId}`,
|
`conversations/${conversationId}`,
|
||||||
);
|
);
|
||||||
if (!cancelled && currentId.current === conversationId) {
|
if (!cancelled && currentId.current === conversationId) {
|
||||||
setConversation((current) =>
|
setConversation(saved);
|
||||||
mergeConversationSnapshot(current, saved),
|
|
||||||
);
|
|
||||||
setBusy(saved.busy);
|
setBusy(saved.busy);
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
@@ -518,6 +471,7 @@ export function DigitalHome({
|
|||||||
}
|
}
|
||||||
closeIdeas();
|
closeIdeas();
|
||||||
imeComposing.current = false;
|
imeComposing.current = false;
|
||||||
|
setSwipedConversation(null);
|
||||||
if (streamingId.current && streamingId.current !== id) {
|
if (streamingId.current && streamingId.current !== id) {
|
||||||
setNotice("请先停止当前回复,再切换会话");
|
setNotice("请先停止当前回复,再切换会话");
|
||||||
return;
|
return;
|
||||||
@@ -555,11 +509,6 @@ export function DigitalHome({
|
|||||||
const c = await digital<{ id: string }>("conversations", "POST", {
|
const c = await digital<{ id: string }>("conversations", "POST", {
|
||||||
characterId: card.id,
|
characterId: card.id,
|
||||||
greetingIndex: index,
|
greetingIndex: index,
|
||||||
recommendationReceiptId:
|
|
||||||
searchParams.get("recommendation") ===
|
|
||||||
recommendationReceipt(initial.account, card.id)
|
|
||||||
? recommendationReceipt(initial.account, card.id)
|
|
||||||
: undefined,
|
|
||||||
uiDecisionId: boot?.decision.decisionId ?? undefined,
|
uiDecisionId: boot?.decision.decisionId ?? undefined,
|
||||||
});
|
});
|
||||||
router.push(chatPath(c.id));
|
router.push(chatPath(c.id));
|
||||||
@@ -592,44 +541,18 @@ export function DigitalHome({
|
|||||||
favoritePending.current = false;
|
favoritePending.current = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function clearPendingSend(id: string) {
|
async function send(mode: "send" | "regenerate" | "continue" = "send") {
|
||||||
pendingSend.current = null;
|
|
||||||
setCanRetryRequest(false);
|
|
||||||
try {
|
|
||||||
sessionStorage.removeItem(`dh-pending:${id}`);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
async function send(
|
|
||||||
mode: "send" | "regenerate" | "continue" = "send",
|
|
||||||
retryContent?: string,
|
|
||||||
) {
|
|
||||||
if (
|
if (
|
||||||
!conversation ||
|
!conversation ||
|
||||||
busy ||
|
busy ||
|
||||||
streamingId.current ||
|
streamingId.current ||
|
||||||
(mode === "send" && !(retryContent ?? draft).trim())
|
(mode === "send" && !draft.trim())
|
||||||
)
|
)
|
||||||
return;
|
return;
|
||||||
closeIdeas();
|
closeIdeas();
|
||||||
const id = conversation.id,
|
const id = conversation.id,
|
||||||
content = mode === "send" ? (retryContent ?? draft).trim() : "",
|
content = mode === "send" ? draft.trim() : "",
|
||||||
requestId =
|
requestId = crypto.randomUUID();
|
||||||
mode === "send" &&
|
|
||||||
pendingSend.current?.id === id &&
|
|
||||||
pendingSend.current.content === (retryContent ?? draft).trim()
|
|
||||||
? pendingSend.current.requestId
|
|
||||||
: crypto.randomUUID();
|
|
||||||
if (mode === "send") {
|
|
||||||
pendingSend.current = { id, requestId, content };
|
|
||||||
setCanRetryRequest(true);
|
|
||||||
try {
|
|
||||||
sessionStorage.setItem(
|
|
||||||
`dh-pending:${id}`,
|
|
||||||
JSON.stringify(pendingSend.current),
|
|
||||||
);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
setInterrupted(false);
|
|
||||||
let assistantId = `pending-${requestId}`;
|
let assistantId = `pending-${requestId}`;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError("");
|
setError("");
|
||||||
@@ -662,19 +585,7 @@ export function DigitalHome({
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
setConversation((c) =>
|
setConversation((c) =>
|
||||||
c && c.id === id
|
c && c.id === id ? { ...c, messages: [...c.messages, ...local] } : c,
|
||||||
? {
|
|
||||||
...c,
|
|
||||||
messages: [
|
|
||||||
...c.messages.filter(
|
|
||||||
(m) =>
|
|
||||||
m.id !== `user-${requestId}` &&
|
|
||||||
m.id !== `pending-${requestId}`,
|
|
||||||
),
|
|
||||||
...local,
|
|
||||||
],
|
|
||||||
}
|
|
||||||
: c,
|
|
||||||
);
|
);
|
||||||
setActiveMessage(assistantId);
|
setActiveMessage(assistantId);
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
@@ -730,8 +641,7 @@ export function DigitalHome({
|
|||||||
}
|
}
|
||||||
: c,
|
: c,
|
||||||
);
|
);
|
||||||
if (event === "done") {
|
if (event === "done")
|
||||||
clearPendingSend(id);
|
|
||||||
setConversation((c) =>
|
setConversation((c) =>
|
||||||
c && c.id === id
|
c && c.id === id
|
||||||
? {
|
? {
|
||||||
@@ -744,25 +654,11 @@ export function DigitalHome({
|
|||||||
}
|
}
|
||||||
: c,
|
: c,
|
||||||
);
|
);
|
||||||
}
|
|
||||||
if (event === "notice" || event === "error")
|
if (event === "notice" || event === "error")
|
||||||
setNotice(String(data.message ?? ""));
|
setNotice(String(data.message ?? ""));
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!controller.signal.aborted) {
|
if (!controller.signal.aborted) reportError(e);
|
||||||
reportError(e);
|
|
||||||
setInterrupted(true);
|
|
||||||
}
|
|
||||||
setConversation((c) =>
|
|
||||||
c?.id === id
|
|
||||||
? {
|
|
||||||
...c,
|
|
||||||
messages: c.messages.map((m) =>
|
|
||||||
m.id === assistantId ? { ...m, status: "stopped" } : m,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: c,
|
|
||||||
);
|
|
||||||
if (!accepted && mode === "send") setDraft(content);
|
if (!accepted && mode === "send") setDraft(content);
|
||||||
} finally {
|
} finally {
|
||||||
streamingId.current = null;
|
streamingId.current = null;
|
||||||
@@ -773,16 +669,8 @@ export function DigitalHome({
|
|||||||
if (currentId.current === id)
|
if (currentId.current === id)
|
||||||
try {
|
try {
|
||||||
const saved = await digital<Conversation>(`conversations/${id}`);
|
const saved = await digital<Conversation>(`conversations/${id}`);
|
||||||
setConversation((current) =>
|
setConversation(saved);
|
||||||
mergeConversationSnapshot(current, saved),
|
|
||||||
);
|
|
||||||
setBusy(saved.busy);
|
setBusy(saved.busy);
|
||||||
if (
|
|
||||||
saved.messages.some(
|
|
||||||
(m) => m.requestId === pendingSend.current?.requestId,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
clearPendingSend(id);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
reportError(e);
|
reportError(e);
|
||||||
}
|
}
|
||||||
@@ -835,17 +723,17 @@ export function DigitalHome({
|
|||||||
reportError(e);
|
reportError(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function branch(message: Message, title: string) {
|
async function branch(message: Message) {
|
||||||
if (!conversation || busy) return;
|
if (!conversation || busy) return;
|
||||||
try {
|
try {
|
||||||
const result = await digital<{ id: string }>(
|
const result = await digital<{ id: string }>(
|
||||||
`conversations/${conversation.id}/branch`,
|
`conversations/${conversation.id}/branch`,
|
||||||
"POST",
|
"POST",
|
||||||
{ messageId: message.id, title },
|
{ messageId: message.id },
|
||||||
);
|
);
|
||||||
router.push(chatPath(result.id));
|
router.push(chatPath(result.id));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw e;
|
reportError(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function requestDelete(target: Summary) {
|
function requestDelete(target: Summary) {
|
||||||
@@ -873,11 +761,9 @@ export function DigitalHome({
|
|||||||
setDeleting(true);
|
setDeleting(true);
|
||||||
setDeleteError("");
|
setDeleteError("");
|
||||||
try {
|
try {
|
||||||
const removed = await digital<{ undoUntil: number }>(
|
await digital(`conversations/${id}`, "DELETE");
|
||||||
`conversations/${id}`,
|
|
||||||
"DELETE",
|
|
||||||
);
|
|
||||||
setSummaries((current) => current.filter((s) => s.id !== id));
|
setSummaries((current) => current.filter((s) => s.id !== id));
|
||||||
|
setSwipedConversation(null);
|
||||||
if (currentId.current === id) {
|
if (currentId.current === id) {
|
||||||
closeIdeas();
|
closeIdeas();
|
||||||
currentId.current = null;
|
currentId.current = null;
|
||||||
@@ -887,17 +773,8 @@ export function DigitalHome({
|
|||||||
try {
|
try {
|
||||||
sessionStorage.removeItem(`dh-draft:${id}`);
|
sessionStorage.removeItem(`dh-draft:${id}`);
|
||||||
} catch {}
|
} catch {}
|
||||||
const entry = {
|
|
||||||
id,
|
|
||||||
title: deleteTarget.title,
|
|
||||||
until: removed.undoUntil,
|
|
||||||
};
|
|
||||||
try {
|
|
||||||
sessionStorage.setItem(undoKey, JSON.stringify(entry));
|
|
||||||
} catch {}
|
|
||||||
setUndo(entry);
|
|
||||||
setDeleteTarget(null);
|
setDeleteTarget(null);
|
||||||
setNotice("对话已删除,可在 30 秒内撤销");
|
setNotice("对话已删除");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setDeleteError(e instanceof Error ? e.message : "删除失败,请重试");
|
setDeleteError(e instanceof Error ? e.message : "删除失败,请重试");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -932,7 +809,7 @@ export function DigitalHome({
|
|||||||
}>(
|
}>(
|
||||||
`conversations/${id}/suggestions`,
|
`conversations/${id}/suggestions`,
|
||||||
"POST",
|
"POST",
|
||||||
{ draft: draft.slice(0, 1000), requestId: crypto.randomUUID() },
|
{ draft: draft.slice(0, 1000) },
|
||||||
controller.signal,
|
controller.signal,
|
||||||
);
|
);
|
||||||
if (ideasRequest.current !== controller || currentId.current !== id)
|
if (ideasRequest.current !== controller || currentId.current !== id)
|
||||||
@@ -1353,7 +1230,7 @@ export function DigitalHome({
|
|||||||
}}
|
}}
|
||||||
onScroll={() => {
|
onScroll={() => {
|
||||||
const v = viewport.current;
|
const v = viewport.current;
|
||||||
if (v?.isConnected && v.clientHeight > 0) {
|
if (v) {
|
||||||
const gap = v.scrollHeight - v.scrollTop - v.clientHeight;
|
const gap = v.scrollHeight - v.scrollTop - v.clientHeight;
|
||||||
if (gap <= 2) atBottom.current = true;
|
if (gap <= 2) atBottom.current = true;
|
||||||
else if (draggingScroll.current) atBottom.current = false;
|
else if (draggingScroll.current) atBottom.current = false;
|
||||||
@@ -1362,78 +1239,6 @@ export function DigitalHome({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div ref={messagesElement} className="dh-messages-inner">
|
<div ref={messagesElement} className="dh-messages-inner">
|
||||||
{conversation.parent && (
|
|
||||||
<p className="dh-branch-source">
|
|
||||||
分支自「{conversation.parent.title}」{" "}
|
|
||||||
{conversation.parent.available ? (
|
|
||||||
<Link
|
|
||||||
href={{
|
|
||||||
pathname: chatPath(
|
|
||||||
conversation.parent.conversationId,
|
|
||||||
),
|
|
||||||
hash: `message-${conversation.parent.messageId}`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
回到原故事
|
|
||||||
</Link>
|
|
||||||
) : (
|
|
||||||
"(原会话已删除或不可用)"
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{interrupted && (
|
|
||||||
<div className="dh-recovery" role="status">
|
|
||||||
<strong>连接已中断,已显示的内容会保留</strong>
|
|
||||||
<p>
|
|
||||||
先同步服务器结果,避免重复发送;已有部分回复可使用“继续”,需要替换回答时再重新生成。
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
disabled={busy}
|
|
||||||
onClick={async () => {
|
|
||||||
try {
|
|
||||||
const saved = await digital<Conversation>(
|
|
||||||
`conversations/${conversation.id}`,
|
|
||||||
);
|
|
||||||
setConversation((current) =>
|
|
||||||
mergeConversationSnapshot(current, saved),
|
|
||||||
);
|
|
||||||
setBusy(saved.busy);
|
|
||||||
if (
|
|
||||||
saved.messages.some(
|
|
||||||
(m) =>
|
|
||||||
m.requestId === pendingSend.current?.requestId,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
clearPendingSend(saved.id);
|
|
||||||
if (!saved.busy) setInterrupted(false);
|
|
||||||
} catch (e) {
|
|
||||||
reportError(e);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
同步聊天记录
|
|
||||||
</button>
|
|
||||||
{canRetryRequest && (
|
|
||||||
<button
|
|
||||||
disabled={busy}
|
|
||||||
onClick={() =>
|
|
||||||
send("send", pendingSend.current?.content)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
重试本次请求
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<GrowthJourney account={initial.account} page="chat" />
|
|
||||||
<GrowthChat
|
|
||||||
account={initial.account}
|
|
||||||
conversation={conversation.id}
|
|
||||||
busy={busy}
|
|
||||||
onExpanded={() => {
|
|
||||||
atBottom.current = false;
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div className="dh-chat-intro">
|
<div className="dh-chat-intro">
|
||||||
<span>✦</span>
|
<span>✦</span>
|
||||||
<p>这里是你与 {currentCard?.name} 的私人故事</p>
|
<p>这里是你与 {currentCard?.name} 的私人故事</p>
|
||||||
@@ -1441,9 +1246,6 @@ export function DigitalHome({
|
|||||||
</div>
|
</div>
|
||||||
{conversation.messages.map((m, index) => (
|
{conversation.messages.map((m, index) => (
|
||||||
<article
|
<article
|
||||||
id={`message-${m.id}`}
|
|
||||||
data-message-id={m.id}
|
|
||||||
data-message-length={m.content.length}
|
|
||||||
className={`dh-message dh-message-${m.role}`}
|
className={`dh-message dh-message-${m.role}`}
|
||||||
key={m.id}
|
key={m.id}
|
||||||
>
|
>
|
||||||
@@ -1489,7 +1291,7 @@ export function DigitalHome({
|
|||||||
<button
|
<button
|
||||||
aria-label="从此处分支"
|
aria-label="从此处分支"
|
||||||
title="从此处创建分支"
|
title="从此处创建分支"
|
||||||
onClick={() => setBranchTarget(m)}
|
onClick={() => branch(m)}
|
||||||
>
|
>
|
||||||
<GitBranch size={13} />
|
<GitBranch size={13} />
|
||||||
</button>
|
</button>
|
||||||
@@ -1523,16 +1325,6 @@ export function DigitalHome({
|
|||||||
<RefreshCw size={13} /> 重新生成
|
<RefreshCw size={13} /> 重新生成
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
{!busy &&
|
|
||||||
m.role === "assistant" &&
|
|
||||||
!!m.requestId &&
|
|
||||||
m.status !== "generating" && (
|
|
||||||
<ReplyFeedback
|
|
||||||
account={initial.account}
|
|
||||||
conversation={conversation.id}
|
|
||||||
messageId={m.id}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{m.status === "failed" && (
|
{m.status === "failed" && (
|
||||||
<small className="dh-message-status">
|
<small className="dh-message-status">
|
||||||
生成失败,可重新生成
|
生成失败,可重新生成
|
||||||
@@ -1542,9 +1334,7 @@ export function DigitalHome({
|
|||||||
<small className="dh-message-status">此前回答</small>
|
<small className="dh-message-status">此前回答</small>
|
||||||
)}
|
)}
|
||||||
{m.status === "stopped" && (
|
{m.status === "stopped" && (
|
||||||
<small className="dh-message-status">
|
<small className="dh-message-status">已停止</small>
|
||||||
回复已中止 · 已保留现有内容
|
|
||||||
</small>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
@@ -1564,7 +1354,7 @@ export function DigitalHome({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ChevronDown size={16} />
|
<ChevronDown size={16} />
|
||||||
{unread ? "有新回复 · 回到最新" : "回到最新"}
|
回到最新
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
<div className="dh-composer-wrap">
|
<div className="dh-composer-wrap">
|
||||||
@@ -1730,57 +1520,8 @@ export function DigitalHome({
|
|||||||
✦
|
✦
|
||||||
</span>
|
</span>
|
||||||
</header>
|
</header>
|
||||||
<GrowthJourney
|
|
||||||
account={initial.account}
|
|
||||||
page={tab === "me" ? "profile" : tab}
|
|
||||||
/>
|
|
||||||
{tab === "discover" && (
|
{tab === "discover" && (
|
||||||
<>
|
<>
|
||||||
{!detail && (
|
|
||||||
<GrowthRecommendations
|
|
||||||
account={initial.account}
|
|
||||||
cards={cards}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{summaries.length > 0 && (
|
|
||||||
<section aria-label="继续最近聊天">
|
|
||||||
<h2>继续最近聊天</h2>
|
|
||||||
<div className="dh-recent-stories">
|
|
||||||
{[...summaries]
|
|
||||||
.sort(
|
|
||||||
(a, b) =>
|
|
||||||
Date.parse(b.updatedAt) - Date.parse(a.updatedAt),
|
|
||||||
)
|
|
||||||
.slice(0, 3)
|
|
||||||
.map((item) => (
|
|
||||||
<Link key={item.id} href={chatPath(item.id)}>
|
|
||||||
{item.title}
|
|
||||||
<small>
|
|
||||||
{" "}
|
|
||||||
·{" "}
|
|
||||||
{item.lastMessage?.slice(0, 36) ||
|
|
||||||
"继续未完的故事"}
|
|
||||||
</small>
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
)}
|
|
||||||
{!!profile?.favorites.length && (
|
|
||||||
<section aria-label="收藏角色">
|
|
||||||
<h2>收藏角色</h2>
|
|
||||||
<div className="dh-recent-stories">
|
|
||||||
{cards
|
|
||||||
.filter((card) => profile.favorites.includes(card.id))
|
|
||||||
.slice(0, 4)
|
|
||||||
.map((card) => (
|
|
||||||
<Link key={card.id} href={contentPath(card)}>
|
|
||||||
{card.name}
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
)}
|
|
||||||
<section className="dh-hero">
|
<section className="dh-hero">
|
||||||
<div>
|
<div>
|
||||||
<span className="dh-pill">今晚,有人等你开口</span>
|
<span className="dh-pill">今晚,有人等你开口</span>
|
||||||
@@ -1859,17 +1600,9 @@ export function DigitalHome({
|
|||||||
<h2>{onlyFavorites ? "心动收藏" : "为你发现"}</h2>
|
<h2>{onlyFavorites ? "心动收藏" : "为你发现"}</h2>
|
||||||
<span>{filtered.length} 位角色 · 全部成年</span>
|
<span>{filtered.length} 位角色 · 全部成年</span>
|
||||||
</div>
|
</div>
|
||||||
<CatalogExposure
|
|
||||||
account={initial.account}
|
|
||||||
cardIds={filtered.map((c) => c.id).join(",")}
|
|
||||||
/>
|
|
||||||
<div className="dh-card-grid">
|
<div className="dh-card-grid">
|
||||||
{filtered.map((c) => (
|
{filtered.map((c) => (
|
||||||
<article
|
<article className="dh-card" key={c.id}>
|
||||||
className="dh-card"
|
|
||||||
data-growth-card={c.id}
|
|
||||||
key={c.id}
|
|
||||||
>
|
|
||||||
<Link className="dh-card-open" href={contentPath(c)}>
|
<Link className="dh-card-open" href={contentPath(c)}>
|
||||||
<img
|
<img
|
||||||
src={c.cover || "/icon.svg"}
|
src={c.cover || "/icon.svg"}
|
||||||
@@ -1939,14 +1672,19 @@ export function DigitalHome({
|
|||||||
{summaries.length > 0 && (
|
{summaries.length > 0 && (
|
||||||
<p className="dh-swipe-hint">向左滑动对话可删除</p>
|
<p className="dh-swipe-hint">向左滑动对话可删除</p>
|
||||||
)}
|
)}
|
||||||
<ConversationList
|
<div className="dh-conversation-list">
|
||||||
summaries={summaries}
|
{summaries.map((s) => (
|
||||||
cards={cards}
|
<ConversationRow
|
||||||
disabled={deleting}
|
key={s.id}
|
||||||
onDelete={requestDelete}
|
summary={s}
|
||||||
onRefresh={refreshSummaries}
|
card={cards.find((c) => c.id === s.characterId)}
|
||||||
onNotice={setNotice}
|
revealed={swipedConversation === s.id}
|
||||||
/>
|
disabled={opening || deleting}
|
||||||
|
onReveal={setSwipedConversation}
|
||||||
|
onDelete={() => requestDelete(s)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
{!summaries.length && (
|
{!summaries.length && (
|
||||||
<div className="dh-empty">
|
<div className="dh-empty">
|
||||||
<MessageCircle />
|
<MessageCircle />
|
||||||
@@ -2007,9 +1745,6 @@ export function DigitalHome({
|
|||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{tab === "me" && (
|
|
||||||
<GrowthProfile account={initial.account} cards={cards} />
|
|
||||||
)}
|
|
||||||
{tab === "me" && profile && profileDraft && (
|
{tab === "me" && profile && profileDraft && (
|
||||||
<form className="dh-profile-form" onSubmit={saveProfile}>
|
<form className="dh-profile-form" onSubmit={saveProfile}>
|
||||||
<div className="dh-profile-banner">
|
<div className="dh-profile-banner">
|
||||||
@@ -2051,27 +1786,19 @@ export function DigitalHome({
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<p className="dh-form-note">
|
<p className="dh-form-note">
|
||||||
账号称呼与身份仅作为新会话的默认值;已有会话保留自己的设定。NSFW
|
此资料可在新会话的「对话设定」中使用。每个会话的设定相互独立。
|
||||||
开关保存后影响所有会话的后续回复。
|
|
||||||
</p>
|
</p>
|
||||||
<label className="dh-content-preference">
|
<label className="dh-content-preference">
|
||||||
<span>
|
<span>
|
||||||
<strong>NSFW 成人内容</strong>
|
<strong>NSFW 成人内容</strong>
|
||||||
<small>
|
<small>
|
||||||
{initial.account.startsWith("guest:")
|
登录账号默认开启,可随时关闭;保存后用于后续回复。
|
||||||
? "游客体验仅提供日常内容,登录后可管理账号偏好。"
|
|
||||||
: "登录账号默认开启,可随时关闭;保存后用于后续回复。"}
|
|
||||||
</small>
|
</small>
|
||||||
</span>
|
</span>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
role="switch"
|
role="switch"
|
||||||
disabled={initial.account.startsWith("guest:")}
|
checked={profileDraft.nsfwEnabled ?? true}
|
||||||
checked={
|
|
||||||
initial.account.startsWith("guest:")
|
|
||||||
? false
|
|
||||||
: (profileDraft.nsfwEnabled ?? true)
|
|
||||||
}
|
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
setProfileDraft({
|
setProfileDraft({
|
||||||
...profileDraft,
|
...profileDraft,
|
||||||
@@ -2111,14 +1838,6 @@ export function DigitalHome({
|
|||||||
)}
|
)}
|
||||||
{detail && (
|
{detail && (
|
||||||
<div className="dh-detail-page">
|
<div className="dh-detail-page">
|
||||||
<GrowthJourney account={initial.account} page="detail" />
|
|
||||||
{detail.kind === "character" && (
|
|
||||||
<CardOpenTracker
|
|
||||||
account={initial.account}
|
|
||||||
cardId={detail.id}
|
|
||||||
receipt={searchParams.get("recommendation")}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<header className="dh-detail-nav">
|
<header className="dh-detail-nav">
|
||||||
<button className="dh-detail-back" onClick={goBack}>
|
<button className="dh-detail-back" onClick={goBack}>
|
||||||
<ArrowLeft size={18} />
|
<ArrowLeft size={18} />
|
||||||
@@ -2156,17 +1875,13 @@ export function DigitalHome({
|
|||||||
<span key={t}>{t}</span>
|
<span key={t}>{t}</span>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<h2>故事与背景</h2>
|
|
||||||
<p className="dh-detail-description">{detail.description}</p>
|
<p className="dh-detail-description">{detail.description}</p>
|
||||||
{detail.greeting && (
|
{detail.greeting && (
|
||||||
<>
|
<blockquote>
|
||||||
<h2>开场预览</h2>
|
{detail.greeting
|
||||||
<blockquote>
|
.replaceAll("{{user}}", profile?.userName ?? "旅人")
|
||||||
{detail.greeting
|
.replaceAll("{{char}}", detail.name)}
|
||||||
.replaceAll("{{user}}", profile?.userName ?? "旅人")
|
</blockquote>
|
||||||
.replaceAll("{{char}}", detail.name)}
|
|
||||||
</blockquote>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
{detail.kind === "character" ? (
|
{detail.kind === "character" ? (
|
||||||
<>
|
<>
|
||||||
@@ -2183,20 +1898,15 @@ export function DigitalHome({
|
|||||||
开启这段故事
|
开启这段故事
|
||||||
</button>
|
</button>
|
||||||
{detail.alternateGreetings.map((g, i) => (
|
{detail.alternateGreetings.map((g, i) => (
|
||||||
<details className="dh-alt-greeting" key={i}>
|
<button
|
||||||
<summary>另一种相遇 {i + 1} · 预览</summary>
|
className="dh-alt-greeting"
|
||||||
<p>
|
key={i}
|
||||||
{g
|
disabled={opening}
|
||||||
.replaceAll("{{user}}", profile?.userName ?? "旅人")
|
onClick={() => start(detail, i + 1)}
|
||||||
.replaceAll("{{char}}", detail.name)}
|
>
|
||||||
</p>
|
<small>另一种相遇 {i + 1}</small>
|
||||||
<button
|
<p>{g.slice(0, 110)}</p>
|
||||||
disabled={opening}
|
</button>
|
||||||
onClick={() => start(detail, i + 1)}
|
|
||||||
>
|
|
||||||
使用这个开场
|
|
||||||
</button>
|
|
||||||
</details>
|
|
||||||
))}
|
))}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
@@ -2225,9 +1935,6 @@ export function DigitalHome({
|
|||||||
<div>
|
<div>
|
||||||
<span className="dh-eyebrow">MAKE IT YOUR STORY</span>
|
<span className="dh-eyebrow">MAKE IT YOUR STORY</span>
|
||||||
<h2>对话设定</h2>
|
<h2>对话设定</h2>
|
||||||
<p className="dh-form-note">
|
|
||||||
只影响当前这段对话的后续回复,不修改账号身份、其他对话或已发送的消息。角色默认设定会作为未选择项目的基础。
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -2239,21 +1946,6 @@ export function DigitalHome({
|
|||||||
</button>
|
</button>
|
||||||
</header>
|
</header>
|
||||||
<div className="dh-settings-body">
|
<div className="dh-settings-body">
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() =>
|
|
||||||
setSettings({
|
|
||||||
...settings,
|
|
||||||
userName: profile?.userName ?? "旅人",
|
|
||||||
persona: profile?.persona ?? "",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
将账号身份填入本次设定
|
|
||||||
</button>
|
|
||||||
<p className="dh-form-note">
|
|
||||||
仅填入下方草稿,点击保存后才对当前会话生效。
|
|
||||||
</p>
|
|
||||||
<label>
|
<label>
|
||||||
你的称呼
|
你的称呼
|
||||||
<input
|
<input
|
||||||
@@ -2437,47 +2129,6 @@ export function DigitalHome({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{undo && (
|
|
||||||
<div className="dh-undo" role="status">
|
|
||||||
<span>已删除「{undo.title}」 · 30 秒内可撤销</span>
|
|
||||||
<button
|
|
||||||
disabled={undoBusy}
|
|
||||||
onClick={async () => {
|
|
||||||
if (undoLock.current) return;
|
|
||||||
undoLock.current = true;
|
|
||||||
setUndoBusy(true);
|
|
||||||
try {
|
|
||||||
await digital(`conversations/${undo.id}/restore`, "POST", {});
|
|
||||||
setUndo(null);
|
|
||||||
sessionStorage.removeItem(undoKey);
|
|
||||||
await refreshSummaries();
|
|
||||||
setNotice("对话已恢复");
|
|
||||||
} catch (e) {
|
|
||||||
reportError(e);
|
|
||||||
} finally {
|
|
||||||
undoLock.current = false;
|
|
||||||
setUndoBusy(false);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{undoBusy ? "恢复中…" : "撤销删除"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{branchTarget && (
|
|
||||||
<ConversationTitleDialog
|
|
||||||
heading="从这里开启分支"
|
|
||||||
initialTitle={`${conversation?.title.slice(0, 100) ?? "故事"} · 分支`}
|
|
||||||
preview={
|
|
||||||
<>
|
|
||||||
<p>原故事会保留,新分支复制到下方这条消息为止。</p>
|
|
||||||
<blockquote>{branchTarget.content.slice(0, 240)}</blockquote>
|
|
||||||
</>
|
|
||||||
}
|
|
||||||
onCancel={() => setBranchTarget(null)}
|
|
||||||
onSubmit={(title) => branch(branchTarget, title)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{deleteTarget && (
|
{deleteTarget && (
|
||||||
<ConversationDeleteDialog
|
<ConversationDeleteDialog
|
||||||
title={deleteTarget.title}
|
title={deleteTarget.title}
|
||||||
@@ -2492,57 +2143,3 @@ export function DigitalHome({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 独立详情路由打开也计入漏斗;推荐入口已上报的点击由回执事件去重链路承接。 */
|
|
||||||
function CardOpenTracker({
|
|
||||||
account,
|
|
||||||
cardId,
|
|
||||||
receipt,
|
|
||||||
}: {
|
|
||||||
account: string;
|
|
||||||
cardId: string;
|
|
||||||
receipt: string | null;
|
|
||||||
}) {
|
|
||||||
const seen = useRef("");
|
|
||||||
useEffect(() => {
|
|
||||||
if (seen.current === `${cardId}:${receipt}`) return;
|
|
||||||
seen.current = `${cardId}:${receipt}`;
|
|
||||||
const source =
|
|
||||||
receipt === recommendationReceipt(account, cardId) ? receipt : undefined;
|
|
||||||
if (source)
|
|
||||||
trackGrowth(account, "recommendation_exposure", undefined, source);
|
|
||||||
trackGrowth(account, "card_open", cardId, source ?? undefined);
|
|
||||||
void flushGrowth(account);
|
|
||||||
}, [account, cardId, receipt]);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
/** 普通发现列表也只在可见时记曝光,筛选重渲染不会重复统计同一张卡。 */
|
|
||||||
function CatalogExposure({
|
|
||||||
account,
|
|
||||||
cardIds,
|
|
||||||
}: {
|
|
||||||
account: string;
|
|
||||||
cardIds: string;
|
|
||||||
}) {
|
|
||||||
const seen = useRef(new Set<string>());
|
|
||||||
useEffect(() => {
|
|
||||||
const observer = new IntersectionObserver(
|
|
||||||
(entries) => {
|
|
||||||
for (const entry of entries) {
|
|
||||||
const id = (entry.target as HTMLElement).dataset.growthCard;
|
|
||||||
if (entry.isIntersecting && id && !seen.current.has(id)) {
|
|
||||||
seen.current.add(id);
|
|
||||||
trackGrowth(account, "card_impression", id);
|
|
||||||
observer.unobserve(entry.target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ threshold: 0.5 },
|
|
||||||
);
|
|
||||||
document
|
|
||||||
.querySelectorAll("[data-growth-card]")
|
|
||||||
.forEach((e) => observer.observe(e));
|
|
||||||
return () => observer.disconnect();
|
|
||||||
}, [account, cardIds]);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2486,20 +2486,3 @@ html.dh-chat-active body {
|
|||||||
min-height: 44px;
|
min-height: 44px;
|
||||||
color: var(--dh-accent);
|
color: var(--dh-accent);
|
||||||
}
|
}
|
||||||
/* 会话管理与恢复操作沿用当前主题,移动端保持足够命中面积。 */
|
|
||||||
.dh-conversation-search { display: grid; gap: 8px; margin: 20px 0; color: var(--dh-muted); }
|
|
||||||
.dh-conversation-tools { display: flex; justify-content: flex-end; gap: 12px; margin: 4px 0 12px; }
|
|
||||||
.dh-conversation-tools button { min-height: 36px; padding: 4px 10px; color: var(--dh-muted); }
|
|
||||||
.dh-title-dialog label { display: grid; gap: 10px; margin-top: 20px; }
|
|
||||||
.dh-title-dialog input { width: 100%; font-size: 16px; }
|
|
||||||
.dh-title-dialog blockquote { max-height: 180px; overflow-y: auto; margin: 16px 0; padding: 12px; background: var(--dh-soft); white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
||||||
.dh-undo { position: fixed; z-index: 120; bottom: max(90px, env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); width: min(460px, calc(100% - 28px)); padding: 14px 18px; border-radius: 14px; background: var(--dh-soft); border: 1px solid var(--dh-line); display: flex; align-items: center; gap: 12px; box-shadow: 0 12px 40px #0008; }
|
|
||||||
.dh-undo span { flex: 1; overflow-wrap: anywhere; }
|
|
||||||
.dh-undo button { flex: none; min-height: 44px; color: var(--dh-accent); }
|
|
||||||
.dh-branch-source, .dh-recovery { padding: 14px; margin-bottom: 16px !important; border: 1px solid var(--dh-line); border-radius: 12px; color: var(--dh-muted); }
|
|
||||||
.dh-branch-source a, .dh-recovery button { color: var(--dh-accent); min-height: 40px; padding: 6px; }
|
|
||||||
.dh-recent-stories { display: flex; flex-wrap: wrap; gap: 10px; margin: 14px 0 28px; }
|
|
||||||
.dh-recent-stories a { border: 1px solid var(--dh-line); border-radius: 12px; padding: 12px 16px; max-width: 100%; overflow-wrap: anywhere; }
|
|
||||||
|
|
||||||
/* 增长入口沿用原有暗色界面,表单保持移动端16px,原生details减少聊天常驻操作。 */
|
|
||||||
.dh-growth-recommendations,.dh-growth-profile{margin:24px 0}.dh-growth-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.dh-growth-grid article{min-width:0;border:1px solid var(--line,#333);border-radius:16px;overflow:hidden}.dh-growth-grid a{display:flex;flex-direction:column;gap:8px;padding:12px;color:inherit;text-decoration:none}.dh-growth-grid img{width:100%;height:160px;object-fit:cover;border-radius:10px}.dh-growth-grid small{color:#aaa}.dh-growth-grid button,.dh-growth-feedback button,.dh-growth-chat button,.dh-growth-profile button{padding:9px 12px;border-radius:10px;background:#292129;color:#f3b0dc;border:1px solid #554050}.dh-growth-banner,.dh-growth-chat{padding:14px;margin:12px 0;border:1px solid #493442;border-radius:14px;background:#201a1e}.dh-growth-banner p,.dh-growth-chat p{line-height:1.7}.dh-growth-chat summary{cursor:pointer}.dh-growth-chat textarea,.dh-growth-profile input,.dh-growth-feedback select{font-size:16px}.dh-growth-chat textarea{display:block;width:100%;min-height:70px;background:#191919;color:#eee;padding:10px;border:1px solid #444;border-radius:10px}.dh-growth-memory{margin:12px 0}.dh-growth-profile fieldset{display:flex;flex-wrap:wrap;gap:12px;margin:18px 0;border:1px solid #444;border-radius:12px}.dh-growth-profile label{display:inline-flex;gap:6px;align-items:center}.dh-growth-feedback{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}.dh-growth-feedback button{font-size:12px}.dh-growth-feedback [aria-pressed=true]{border-color:#efa5d3}.dh-growth-feedback select{background:#222;color:#eee;padding:8px}.dh-growth-profile small{line-height:1.7;color:#aaa}
|
|
||||||
|
|||||||
@@ -1,255 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
"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;
|
|
||||||
}
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,139 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -91,31 +91,6 @@ export function LoginForm({ returnTo = "/discover" }: { returnTo?: string }) {
|
|||||||
<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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,144 +0,0 @@
|
|||||||
"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;
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
/** 登录入口在解析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>;
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
/** 同源写入校验使用代理保留的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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
/** 服务端生成中快照可能尚未落入增量正文;同步时保留浏览器已经收到的部分回复。 */
|
|
||||||
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;
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
/** 独立 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+41
-13
@@ -33,7 +33,6 @@ export type Message = {
|
|||||||
status: string;
|
status: string;
|
||||||
pinned: boolean;
|
pinned: boolean;
|
||||||
sequenceId?: number;
|
sequenceId?: number;
|
||||||
requestId?: string | null;
|
|
||||||
};
|
};
|
||||||
/** 不含实验配置的会话偏好。 */
|
/** 不含实验配置的会话偏好。 */
|
||||||
export type Settings = {
|
export type Settings = {
|
||||||
@@ -51,13 +50,6 @@ export type Conversation = {
|
|||||||
settings: Settings;
|
settings: Settings;
|
||||||
busy: boolean;
|
busy: boolean;
|
||||||
messages: Message[];
|
messages: Message[];
|
||||||
pinned?: boolean;
|
|
||||||
parent?: {
|
|
||||||
conversationId: string;
|
|
||||||
messageId: string;
|
|
||||||
title: string;
|
|
||||||
available: boolean;
|
|
||||||
} | null;
|
|
||||||
};
|
};
|
||||||
/** 通用请求保留服务端错误文本,401 自动返回登录。 */
|
/** 通用请求保留服务端错误文本,401 自动返回登录。 */
|
||||||
export async function digital<T>(
|
export async function digital<T>(
|
||||||
@@ -85,8 +77,47 @@ export async function digital<T>(
|
|||||||
throw new Error(data.error?.message ?? data.message ?? "请求失败");
|
throw new Error(data.error?.message ?? data.message ?? "请求失败");
|
||||||
return data.data as T;
|
return data.data as T;
|
||||||
}
|
}
|
||||||
/** 严格检查终止事件,避免断网被当作回复完成。 */
|
/** 网络分片可跨多个 SSE 事件,最后不完整事件不会被误解析。 */
|
||||||
export { readDigitalStream as readStream } from "./digital-stream";
|
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 = {
|
export type Summary = {
|
||||||
@@ -94,12 +125,9 @@ export type Summary = {
|
|||||||
characterId: string;
|
characterId: string;
|
||||||
title: string;
|
title: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
pinned?: boolean;
|
|
||||||
lastMessage?: string | null;
|
|
||||||
};
|
};
|
||||||
/** 服务端首屏数据,仅包含可公开的内容摘要和当前账号决策。 */
|
/** 服务端首屏数据,仅包含可公开的内容摘要和当前账号决策。 */
|
||||||
export type Bootstrap = {
|
export type Bootstrap = {
|
||||||
account: string;
|
|
||||||
catalog: Card[];
|
catalog: Card[];
|
||||||
profile: Profile;
|
profile: Profile;
|
||||||
decision: {
|
decision: {
|
||||||
|
|||||||
@@ -1,94 +0,0 @@
|
|||||||
/** 无依赖的前台增长队列与推荐回执,便于验证重试幂等和账号隔离。 */
|
|
||||||
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 {}
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
/** 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}`);
|
|
||||||
}
|
|
||||||
+2
-5
@@ -1,4 +1,3 @@
|
|||||||
/** 会话令牌仅保存在HttpOnly Cookie,游客标记供登录路由承接身份。 */
|
|
||||||
import "server-only";
|
import "server-only";
|
||||||
|
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
@@ -23,12 +22,10 @@ export async function setSessionToken(token: string) {
|
|||||||
secure: getAppEnv() === "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() {
|
||||||
const store = await cookies();
|
(await cookies()).delete(getSessionCookieName());
|
||||||
store.delete(getSessionCookieName());
|
|
||||||
store.delete(`${getSessionCookieName()}_guest`);
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-2
@@ -33,8 +33,7 @@ export function proxy(request: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const guest = Boolean(request.cookies.get(`${cookieName}_guest`)?.value);
|
if (isPublic && hasSession) {
|
||||||
if (isPublic && hasSession && !(path === "/login" && guest)) {
|
|
||||||
return NextResponse.redirect(
|
return NextResponse.redirect(
|
||||||
new URL(
|
new URL(
|
||||||
path === "/login"
|
path === "/login"
|
||||||
|
|||||||
@@ -1,83 +0,0 @@
|
|||||||
/** 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,
|
|
||||||
"",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
/** 事件队列使用可控浏览器存储与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);
|
|
||||||
});
|
|
||||||
Reference in New Issue
Block a user