feat(growth): 接入游客推荐与权益体验
- 登录:新增游客体验、登录承接和同源及请求体积校验 - 推荐与埋点:接入曝光回执、兴趣偏好和按账号隔离的重试队列 - 聊天体验:展示剩余额度、支持回答反馈及故事记忆管理 - 文档和测试:同步业务边界,覆盖队列幂等与代理登录校验
This commit is contained in:
@@ -10,6 +10,11 @@ import {
|
||||
expiredDigitalSessionPath,
|
||||
type DigitalTab,
|
||||
} 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 {
|
||||
@@ -550,6 +555,11 @@ export function DigitalHome({
|
||||
const c = await digital<{ id: string }>("conversations", "POST", {
|
||||
characterId: card.id,
|
||||
greetingIndex: index,
|
||||
recommendationReceiptId:
|
||||
searchParams.get("recommendation") ===
|
||||
recommendationReceipt(initial.account, card.id)
|
||||
? recommendationReceipt(initial.account, card.id)
|
||||
: undefined,
|
||||
uiDecisionId: boot?.decision.decisionId ?? undefined,
|
||||
});
|
||||
router.push(chatPath(c.id));
|
||||
@@ -922,7 +932,7 @@ export function DigitalHome({
|
||||
}>(
|
||||
`conversations/${id}/suggestions`,
|
||||
"POST",
|
||||
{ draft: draft.slice(0, 1000) },
|
||||
{ draft: draft.slice(0, 1000), requestId: crypto.randomUUID() },
|
||||
controller.signal,
|
||||
);
|
||||
if (ideasRequest.current !== controller || currentId.current !== id)
|
||||
@@ -1415,6 +1425,15 @@ export function DigitalHome({
|
||||
)}
|
||||
</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">
|
||||
<span>✦</span>
|
||||
<p>这里是你与 {currentCard?.name} 的私人故事</p>
|
||||
@@ -1504,6 +1523,16 @@ export function DigitalHome({
|
||||
<RefreshCw size={13} /> 重新生成
|
||||
</button>
|
||||
)}
|
||||
{!busy &&
|
||||
m.role === "assistant" &&
|
||||
!!m.requestId &&
|
||||
m.status !== "generating" && (
|
||||
<ReplyFeedback
|
||||
account={initial.account}
|
||||
conversation={conversation.id}
|
||||
messageId={m.id}
|
||||
/>
|
||||
)}
|
||||
{m.status === "failed" && (
|
||||
<small className="dh-message-status">
|
||||
生成失败,可重新生成
|
||||
@@ -1701,8 +1730,18 @@ export function DigitalHome({
|
||||
✦
|
||||
</span>
|
||||
</header>
|
||||
<GrowthJourney
|
||||
account={initial.account}
|
||||
page={tab === "me" ? "profile" : tab}
|
||||
/>
|
||||
{tab === "discover" && (
|
||||
<>
|
||||
{!detail && (
|
||||
<GrowthRecommendations
|
||||
account={initial.account}
|
||||
cards={cards}
|
||||
/>
|
||||
)}
|
||||
{summaries.length > 0 && (
|
||||
<section aria-label="继续最近聊天">
|
||||
<h2>继续最近聊天</h2>
|
||||
@@ -1820,9 +1859,17 @@ export function DigitalHome({
|
||||
<h2>{onlyFavorites ? "心动收藏" : "为你发现"}</h2>
|
||||
<span>{filtered.length} 位角色 · 全部成年</span>
|
||||
</div>
|
||||
<CatalogExposure
|
||||
account={initial.account}
|
||||
cardIds={filtered.map((c) => c.id).join(",")}
|
||||
/>
|
||||
<div className="dh-card-grid">
|
||||
{filtered.map((c) => (
|
||||
<article className="dh-card" key={c.id}>
|
||||
<article
|
||||
className="dh-card"
|
||||
data-growth-card={c.id}
|
||||
key={c.id}
|
||||
>
|
||||
<Link className="dh-card-open" href={contentPath(c)}>
|
||||
<img
|
||||
src={c.cover || "/icon.svg"}
|
||||
@@ -1960,6 +2007,9 @@ export function DigitalHome({
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{tab === "me" && (
|
||||
<GrowthProfile account={initial.account} cards={cards} />
|
||||
)}
|
||||
{tab === "me" && profile && profileDraft && (
|
||||
<form className="dh-profile-form" onSubmit={saveProfile}>
|
||||
<div className="dh-profile-banner">
|
||||
@@ -2008,13 +2058,20 @@ export function DigitalHome({
|
||||
<span>
|
||||
<strong>NSFW 成人内容</strong>
|
||||
<small>
|
||||
登录账号默认开启,可随时关闭;保存后用于后续回复。
|
||||
{initial.account.startsWith("guest:")
|
||||
? "游客体验仅提供日常内容,登录后可管理账号偏好。"
|
||||
: "登录账号默认开启,可随时关闭;保存后用于后续回复。"}
|
||||
</small>
|
||||
</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
checked={profileDraft.nsfwEnabled ?? true}
|
||||
disabled={initial.account.startsWith("guest:")}
|
||||
checked={
|
||||
initial.account.startsWith("guest:")
|
||||
? false
|
||||
: (profileDraft.nsfwEnabled ?? true)
|
||||
}
|
||||
onChange={(event) =>
|
||||
setProfileDraft({
|
||||
...profileDraft,
|
||||
@@ -2054,6 +2111,14 @@ export function DigitalHome({
|
||||
)}
|
||||
{detail && (
|
||||
<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">
|
||||
<button className="dh-detail-back" onClick={goBack}>
|
||||
<ArrowLeft size={18} />
|
||||
@@ -2427,3 +2492,57 @@ export function DigitalHome({
|
||||
</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;
|
||||
}
|
||||
|
||||
@@ -2500,3 +2500,6 @@ html.dh-chat-active body {
|
||||
.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}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
"use client";
|
||||
/** 会话内记忆管理和回答质量反馈,所有写入仍由后端校验消息归属与版本。 */
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { digital } from "@/lib/digital";
|
||||
import {
|
||||
feedbackFor,
|
||||
invalidateFeedback,
|
||||
type GrowthState,
|
||||
} from "@/lib/growth";
|
||||
type Memory = { id: string; kind: string; content: string; version: number };
|
||||
/** 延迟读取记忆列表,删除保留服务端源键,后台任务不能将它重新创建。 */
|
||||
export function GrowthChat({
|
||||
account,
|
||||
conversation,
|
||||
busy,
|
||||
onExpanded,
|
||||
}: {
|
||||
account: string;
|
||||
conversation: string;
|
||||
busy: boolean;
|
||||
onExpanded: () => void;
|
||||
}) {
|
||||
const [memories, setMemories] = useState<Memory[]>([]),
|
||||
[draft, setDraft] = useState(""),
|
||||
[error, setError] = useState(""),
|
||||
[pending, setPending] = useState(false),
|
||||
[rights, setRights] = useState<GrowthState["entitlement"] | null>(null),
|
||||
[open, setOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
const c = new AbortController();
|
||||
digital<GrowthState>("growth", "GET", undefined, c.signal)
|
||||
.then((r) => setRights(r.entitlement))
|
||||
.catch(() => {});
|
||||
return () => c.abort();
|
||||
}, [account, busy]);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const c = new AbortController();
|
||||
digital<Memory[]>(
|
||||
`conversations/${conversation}/memories`,
|
||||
"GET",
|
||||
undefined,
|
||||
c.signal,
|
||||
)
|
||||
.then(setMemories)
|
||||
.catch((e) => {
|
||||
if (!c.signal.aborted) setError(e.message);
|
||||
});
|
||||
return () => c.abort();
|
||||
}, [conversation, open]);
|
||||
async function mutate(path: string, method: "POST" | "PATCH", body: unknown) {
|
||||
if (pending) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
await digital(path, method, body);
|
||||
setMemories(
|
||||
await digital<Memory[]>(`conversations/${conversation}/memories`),
|
||||
);
|
||||
setDraft("");
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "操作失败");
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<details
|
||||
className="dh-growth-chat"
|
||||
onToggle={(e) => {
|
||||
setOpen(e.currentTarget.open);
|
||||
if (e.currentTarget.open) onExpanded();
|
||||
}}
|
||||
>
|
||||
<summary>
|
||||
故事记忆与权益 {rights ? `· 剩余 ${rights.remaining} 次` : ""}
|
||||
</summary>
|
||||
{account.startsWith("guest:") && (
|
||||
<p>
|
||||
<Link href="/login?next=%2Fchats">登录并保留这段体验故事</Link>
|
||||
</p>
|
||||
)}
|
||||
<p className="dh-form-note">
|
||||
记忆仅用于当前故事。自动事实需要在“我的”中开启;这里可以更正为手动记忆,或移除不想继续使用的内容。
|
||||
</p>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{memories.map((m) => (
|
||||
<MemoryRow
|
||||
key={`${m.id}:${m.version}`}
|
||||
memory={m}
|
||||
disabled={busy || pending}
|
||||
onSave={(content) =>
|
||||
mutate(`conversations/${conversation}/memories/${m.id}`, "PATCH", {
|
||||
version: m.version,
|
||||
content,
|
||||
})
|
||||
}
|
||||
onDelete={() =>
|
||||
mutate(`conversations/${conversation}/memories/${m.id}`, "PATCH", {
|
||||
version: m.version,
|
||||
deleted: true,
|
||||
})
|
||||
}
|
||||
/>
|
||||
))}
|
||||
<label>
|
||||
添加重要背景
|
||||
<textarea
|
||||
value={draft}
|
||||
maxLength={600}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
disabled={busy || pending || !draft.trim()}
|
||||
onClick={() =>
|
||||
mutate(`conversations/${conversation}/memories`, "POST", {
|
||||
content: draft,
|
||||
})
|
||||
}
|
||||
>
|
||||
记住这件事
|
||||
</button>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
function MemoryRow({
|
||||
memory,
|
||||
disabled,
|
||||
onSave,
|
||||
onDelete,
|
||||
}: {
|
||||
memory: Memory;
|
||||
disabled: boolean;
|
||||
onSave: (value: string) => void;
|
||||
onDelete: () => void;
|
||||
}) {
|
||||
const [text, setText] = useState(memory.content);
|
||||
return (
|
||||
<div className="dh-growth-memory">
|
||||
<small>
|
||||
{memory.kind === "summary"
|
||||
? "历史摘录"
|
||||
: memory.kind === "fact"
|
||||
? "明确记忆"
|
||||
: "手动背景"}
|
||||
</small>
|
||||
<textarea
|
||||
aria-label="记忆内容"
|
||||
value={text}
|
||||
maxLength={600}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
disabled={disabled || !text.trim() || text === memory.content}
|
||||
onClick={() => onSave(text)}
|
||||
>
|
||||
保存更正
|
||||
</button>
|
||||
<button disabled={disabled} onClick={onDelete}>
|
||||
不再使用
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
/** 点踩原因与指定回复绑定,不采集新的聊天正文。 */
|
||||
export function ReplyFeedback({
|
||||
account,
|
||||
conversation,
|
||||
messageId,
|
||||
}: {
|
||||
account: string;
|
||||
conversation: string;
|
||||
messageId: string;
|
||||
}) {
|
||||
const [rating, setRating] = useState<"up" | "down" | "">(""),
|
||||
[reason, setReason] = useState(""),
|
||||
[choosing, setChoosing] = useState(false),
|
||||
[busy, setBusy] = useState(false),
|
||||
[error, setError] = useState("");
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
feedbackFor(account, conversation)
|
||||
.then((items) => {
|
||||
const r = items.find((i) => i.messageId === messageId);
|
||||
if (alive && r) {
|
||||
setRating(r.rating);
|
||||
setReason(r.reason);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [account, conversation, messageId]);
|
||||
async function save(value: "up" | "down", why = "") {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await digital(`conversations/${conversation}/feedback`, "POST", {
|
||||
messageId,
|
||||
rating: value,
|
||||
reason: why,
|
||||
});
|
||||
invalidateFeedback(account, conversation);
|
||||
setRating(value);
|
||||
setReason(why);
|
||||
setChoosing(false);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "反馈失败");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="dh-growth-feedback">
|
||||
<button
|
||||
disabled={busy}
|
||||
aria-pressed={rating === "up"}
|
||||
onClick={() => void save("up")}
|
||||
>
|
||||
{rating === "up" ? "已赞同" : "喜欢这个回答"}
|
||||
</button>
|
||||
<button
|
||||
disabled={busy}
|
||||
aria-pressed={rating === "down"}
|
||||
onClick={() => setChoosing(!choosing)}
|
||||
>
|
||||
{rating === "down" ? "已反馈" : "不太满意"}
|
||||
</button>
|
||||
{choosing && (
|
||||
<label>
|
||||
原因
|
||||
<select value={reason} onChange={(e) => setReason(e.target.value)}>
|
||||
<option value="">选择原因</option>
|
||||
<option value="forgot">忘记设定</option>
|
||||
<option value="repetition">重复内容</option>
|
||||
<option value="slow">回复太慢</option>
|
||||
<option value="off_topic">偏离故事</option>
|
||||
<option value="other">其他</option>
|
||||
</select>
|
||||
<button
|
||||
disabled={busy || !reason}
|
||||
onClick={() => void save("down", reason)}
|
||||
>
|
||||
提交反馈
|
||||
</button>
|
||||
</label>
|
||||
)}
|
||||
{error && <small role="alert">{error}</small>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client";
|
||||
/** 站内运营卡片与漏斗入口,先读取回访分群再上报本次访问,避免把沉默用户立即改为活跃。 */
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { digital } from "@/lib/digital";
|
||||
import { trackGrowth, flushGrowth, type GrowthState } from "@/lib/growth";
|
||||
/** 不向外部渠道发通知;仅实际可见的站内卡片确认曝光。 */
|
||||
export function GrowthJourney({
|
||||
account,
|
||||
page,
|
||||
}: {
|
||||
account: string;
|
||||
page: string;
|
||||
}) {
|
||||
const [cards, setCards] = useState<GrowthState["inbox"]>([]),
|
||||
box = useRef<HTMLDivElement>(null),
|
||||
visited = useRef("");
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const controller = new AbortController();
|
||||
digital<GrowthState>("growth", "GET", undefined, controller.signal)
|
||||
.then((s) => {
|
||||
if (alive) setCards(s.inbox);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
if (alive && visited.current !== `${account}:${page}`) {
|
||||
visited.current = `${account}:${page}`;
|
||||
trackGrowth(account, "page_view", page);
|
||||
void flushGrowth(account);
|
||||
}
|
||||
});
|
||||
const timer = setInterval(() => void flushGrowth(account), 5000),
|
||||
hide = () => void flushGrowth(account);
|
||||
window.addEventListener("pagehide", hide);
|
||||
return () => {
|
||||
alive = false;
|
||||
controller.abort();
|
||||
clearInterval(timer);
|
||||
window.removeEventListener("pagehide", hide);
|
||||
void flushGrowth(account);
|
||||
};
|
||||
}, [account, page]);
|
||||
useEffect(() => {
|
||||
const element = box.current;
|
||||
if (!element || !cards.length) return;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((e) => e.isIntersecting)) {
|
||||
for (const card of cards)
|
||||
void digital(`growth/inbox/${card.id}`, "POST", {
|
||||
action: "exposure",
|
||||
}).catch(() => {});
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ threshold: 0.5 },
|
||||
);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, [cards]);
|
||||
return cards.length ? (
|
||||
<aside ref={box} className="dh-growth-banner">
|
||||
{cards.map((c) => (
|
||||
<div key={c.id}>
|
||||
<strong>{c.title}</strong>
|
||||
<p>{c.content}</p>
|
||||
<button
|
||||
onClick={async () => {
|
||||
await digital(`growth/inbox/${c.id}`, "POST", {
|
||||
action: "exposure",
|
||||
})
|
||||
.then(() =>
|
||||
digital(`growth/inbox/${c.id}`, "POST", { action: "click" }),
|
||||
)
|
||||
.catch(() => {});
|
||||
setCards([]);
|
||||
}}
|
||||
>
|
||||
知道了,继续探索
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
) : null;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
"use client";
|
||||
/** 个人权益和主动兴趣选择,自动记忆须用户开启,关闭后不再提取和检索自动内容。 */
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { digital, type Card } from "@/lib/digital";
|
||||
import type { GrowthState } from "@/lib/growth";
|
||||
/** 所有额度和偏好读取服务端真实状态,不展示虚构购买按钮。 */
|
||||
export function GrowthProfile({
|
||||
account,
|
||||
cards,
|
||||
}: {
|
||||
account: string;
|
||||
cards: Card[];
|
||||
}) {
|
||||
const [state, setState] = useState<GrowthState | null>(null),
|
||||
[error, setError] = useState(""),
|
||||
[notice, setNotice] = useState(""),
|
||||
[busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
const c = new AbortController();
|
||||
digital<GrowthState>("growth", "GET", undefined, c.signal)
|
||||
.then(setState)
|
||||
.catch((e) => {
|
||||
if (!c.signal.aborted) setError(e.message);
|
||||
});
|
||||
return () => c.abort();
|
||||
}, [account]);
|
||||
const tags = [...new Set(cards.flatMap((c) => c.tags))].slice(0, 30);
|
||||
return (
|
||||
<section className="dh-growth-profile">
|
||||
<h2>我的体验与偏好</h2>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{state && (
|
||||
<>
|
||||
<p>
|
||||
{state.entitlement.tier === "guest"
|
||||
? "游客体验"
|
||||
: state.entitlement.tier === "member"
|
||||
? "会员权益"
|
||||
: "免费权益"}{" "}
|
||||
· 剩余 {state.entitlement.remaining} / {state.entitlement.limit} 次
|
||||
· 生成中预占 {state.entitlement.reserved} 次
|
||||
</p>
|
||||
<small>
|
||||
每次聊天或灵感生成消耗一次;空失败会释放,部分回复会保留并计次。
|
||||
{state.entitlement.tier === "guest"
|
||||
? "游客次数为本次身份的总额度,登录时承接使用记录。"
|
||||
: "每日额度按服务器自然日重置。会员权益由后台运营授予。"}
|
||||
</small>
|
||||
{state.entitlement.tier === "guest" && (
|
||||
<p>
|
||||
<Link href="/login?next=%2Fprofile">登录并保留体验故事</Link>
|
||||
</p>
|
||||
)}
|
||||
<fieldset>
|
||||
<legend>我感兴趣的题材(最多12项)</legend>
|
||||
{tags.map((tag) => (
|
||||
<label key={tag}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={state.interests.includes(tag)}
|
||||
disabled={
|
||||
busy ||
|
||||
(!state.interests.includes(tag) &&
|
||||
state.interests.length >= 12)
|
||||
}
|
||||
onChange={(e) =>
|
||||
setState({
|
||||
...state,
|
||||
interests: e.target.checked
|
||||
? [...state.interests, tag]
|
||||
: state.interests.filter((t) => t !== tag),
|
||||
})
|
||||
}
|
||||
/>
|
||||
{tag}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={state.autoMemory}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setState({ ...state, autoMemory: e.target.checked })
|
||||
}
|
||||
/>
|
||||
允许为我的故事提取记忆
|
||||
</label>
|
||||
<p className="dh-form-note">
|
||||
仅提取你明确说“请记住”的事实,并定期生成历史原文摘录;你可以在故事内查看、更正或移除。关闭后不再使用自动记忆,手动添加的记忆继续生效。
|
||||
</p>
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setNotice("");
|
||||
try {
|
||||
await digital("growth/preferences", "PUT", {
|
||||
interests: state.interests,
|
||||
autoMemory: state.autoMemory,
|
||||
});
|
||||
setNotice("偏好已保存,下次推荐与回复时生效");
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "保存失败");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{busy ? "保存中…" : "保存推荐与记忆偏好"}
|
||||
</button>
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
"use client";
|
||||
/** 服务端推荐结果与真实可见曝光,默认排序、实验组和归因都由服务端决定。 */
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { digital, type Card } from "@/lib/digital";
|
||||
import { contentPath } from "@/lib/digital-routes";
|
||||
import { trackGrowth, flushGrowth, rememberRecommendation } from "@/lib/growth";
|
||||
type Recommendation = {
|
||||
receiptId: string;
|
||||
items: { id: string; reason: string }[];
|
||||
};
|
||||
/** 兴趣偏好来自用户主动选择,跳过不会被误计为开聊。 */
|
||||
export function GrowthRecommendations({
|
||||
account,
|
||||
cards,
|
||||
}: {
|
||||
account: string;
|
||||
cards: Card[];
|
||||
}) {
|
||||
const [result, setResult] = useState<Recommendation | null>(null),
|
||||
[error, setError] = useState(""),
|
||||
root = useRef<HTMLElement>(null),
|
||||
seen = useRef(new Set<string>());
|
||||
useEffect(() => {
|
||||
const c = new AbortController();
|
||||
digital<Recommendation>(
|
||||
"growth/recommendations",
|
||||
"GET",
|
||||
undefined,
|
||||
c.signal,
|
||||
)
|
||||
.then(setResult)
|
||||
.catch((e) => {
|
||||
if (!c.signal.aborted)
|
||||
setError(e instanceof Error ? e.message : "推荐加载失败");
|
||||
});
|
||||
return () => c.abort();
|
||||
}, [account]);
|
||||
useEffect(() => {
|
||||
if (!result || !root.current) return;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isIntersecting) continue;
|
||||
const id = (entry.target as HTMLElement).dataset.cardId;
|
||||
if (!id) continue;
|
||||
const key = `${result.receiptId}:${id}`;
|
||||
if (seen.current.has(key)) continue;
|
||||
seen.current.add(key);
|
||||
trackGrowth(
|
||||
account,
|
||||
"recommendation_exposure",
|
||||
undefined,
|
||||
result.receiptId,
|
||||
);
|
||||
trackGrowth(account, "card_impression", id, result.receiptId);
|
||||
void flushGrowth(account);
|
||||
observer.unobserve(entry.target);
|
||||
}
|
||||
},
|
||||
{ threshold: 0.5 },
|
||||
);
|
||||
root.current
|
||||
.querySelectorAll("[data-card-id]")
|
||||
.forEach((e) => observer.observe(e));
|
||||
return () => observer.disconnect();
|
||||
}, [account, result]);
|
||||
return (
|
||||
<section
|
||||
ref={root}
|
||||
className="dh-growth-recommendations"
|
||||
aria-label="为你推荐"
|
||||
>
|
||||
<h2>为你推荐</h2>
|
||||
<p>
|
||||
<Link href="/profile">选择兴趣,让推荐更懂你</Link>
|
||||
</p>
|
||||
{error ? (
|
||||
<p role="status">{error}</p>
|
||||
) : !result ? (
|
||||
<p>正在寻找适合你的故事…</p>
|
||||
) : (
|
||||
<div className="dh-growth-grid">
|
||||
{result.items.map((item) => {
|
||||
const card = cards.find((c) => c.id === item.id);
|
||||
return card ? (
|
||||
<article key={item.id} data-card-id={item.id}>
|
||||
<Link
|
||||
href={{
|
||||
pathname: contentPath(card),
|
||||
query: { recommendation: result.receiptId },
|
||||
}}
|
||||
onClick={() => {
|
||||
trackGrowth(
|
||||
account,
|
||||
"recommendation_exposure",
|
||||
undefined,
|
||||
result.receiptId,
|
||||
);
|
||||
rememberRecommendation(account, card.id, result.receiptId);
|
||||
void flushGrowth(account);
|
||||
}}
|
||||
>
|
||||
<Image
|
||||
src={card.cover || "/icon.svg"}
|
||||
alt=""
|
||||
width={240}
|
||||
height={160}
|
||||
unoptimized
|
||||
/>
|
||||
<strong>{card.name}</strong>
|
||||
<small>{item.reason}</small>
|
||||
</Link>
|
||||
<button
|
||||
onClick={() => {
|
||||
trackGrowth(
|
||||
account,
|
||||
"card_skip",
|
||||
card.id,
|
||||
result.receiptId,
|
||||
);
|
||||
void flushGrowth(account);
|
||||
setResult({
|
||||
...result,
|
||||
items: result.items.filter((i) => i.id !== card.id),
|
||||
});
|
||||
}}
|
||||
>
|
||||
暂不感兴趣
|
||||
</button>
|
||||
</article>
|
||||
) : null;
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -91,6 +91,31 @@ export function LoginForm({ returnTo = "/discover" }: { returnTo?: string }) {
|
||||
<button className="primary-button" disabled={pending} type="submit">
|
||||
{pending ? "登录中..." : "登录"}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user