Compare commits

...

8 Commits

Author SHA1 Message Date
zhanxi fb8be9c460 Merge pull request 'fix(chat): 修复尚未出字就停止后的继续重试' (#15) from feature/env-pipeline-split into master 2026-10-27 10:21:07 +00:00
湛兮 ae2b58e0b8 fix(chat): 恢复提前停止后的继续入口
- 以最近有效台词判断继续能力,停止前未出字时仍可重试
2026-10-27 18:20:49 +08:00
zhanxi 4638c72680 Merge pull request 'feat(chat): 新增继续按钮并修复回复滚动跟随' (#13) from feature/env-pipeline-split into master 2026-10-27 10:15:51 +00:00
湛兮 1f11112e04 feat(chat): 新增继续按钮并修复回复滚动跟随
- 继续生成保留输入草稿,不新增用户气泡,支持重复续写和停止

- 根据用户上翻意图控制跟随,修复结束后离底及思考点与光标同时出现
2026-10-27 18:15:31 +08:00
zhanxi cac56740cc Merge pull request 'fix(auth): 修复会话过期跳转内部地址' (#11) from feature/env-pipeline-split into master 2026-10-27 09:42:24 +00:00
湛兮 f75a9abecc fix(auth): 修复会话过期跳转内部地址
- logout 使用站内相对 Location,避免跳到 0.0.0.0 监听地址

- 校验站内返回路径并覆盖正式域名、本地地址及外部跳转变体
2026-10-27 17:42:06 +08:00
zhanxi afc474b0c4 Merge pull request 'fix(experiments): 发布多组决策消费支持' (#9) from feature/env-pipeline-split into master 2026-10-27 07:15:54 +00:00
湛兮 a963bec3f3 fix(experiments): 按决策返回值消费多组界面实验
- 用户端支持动态组别和未入组状态,不再固定使用B组判断新版界面
- 决策过期使用服务端返回的默认值,保留旧响应兼容
2026-10-27 15:15:21 +08:00
7 changed files with 190 additions and 38 deletions
+14
View File
@@ -136,3 +136,17 @@ pnpm start:prod
`src/components/conversation-row.tsx` 提供会话列表横滑删除、桌面删除入口与模态确认。灵感回复读取本人会话上下文,选择后只加入草稿,原草稿保留;回车发送覆盖 H5/Web,支持中文输入法、Shift+Enter 与手机换行按钮。
内部滚动区域统一隐藏原生轨道,保留触摸/键盘滚动,设定表单关闭横向溢出。风格控制提示使用只读 `GET /api/digital/conversations/:id/style-policy`,打开设定不会写入实验分组、决策或曝光。
实验决策支持 A~Z 动态组;未入组时组别为 null。界面消费 `decision.value`(`new` / `true` 为新版),组名仅用于归因。决策过期使用服务端的 `fallbackValue`,不将无实验用户伪装成 A 组;旧服务未返回value时保留既有兼容路径。
## 登录跳转回归
- `src/lib/auth-redirect.ts`:登出与会话过期后使用站内相对 `Location`,避免跳到 Next.js 内部监听地址 `0.0.0.0:3210`;仅允许站内返回路径。
- `tests/auth-redirect.test.mjs`:覆盖正式域名/本地地址的登录页跳转、站内参数和外部地址拦截。
- 执行:`node --experimental-strip-types --test tests/auth-redirect.test.mjs`(Node.js 22)。
聊天滚动将“跟随最新”与当前底部距离分开:停在底部时,流式回复、结束后操作栏及软键盘导致的尺寸变化均继续贴底;主动上翻才暂停跟随,点击“回到最新”重新启用。等待首段正文仅显示思考点,收到文字后才显示打字光标,结束时移除生成提示。
聊天输入区“继续”让 NPC 基于上一段内容继续说话,不发送或清空输入框草稿,也不插入用户气泡;可连续点击生成多段,生成时沿用停止按钮。角色尚无可接续内容时按钮不可用。
NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成的角色内容,输入草稿保持不变。
+6 -4
View File
@@ -1,15 +1,17 @@
import { NextRequest, NextResponse } from "next/server";
/** 清理会话后返回当前站点,保持反向代理域名与本地访问地址。 */
import { NextRequest } from "next/server";
import { logoutRedirect } from "@/lib/auth-redirect";
import { clearSessionToken } from "@/lib/session";
/** 客户端主动退出时仅清理 Cookie,由页面处理导航。 */
export async function POST() {
await clearSessionToken();
return Response.json({ success: true, data: null });
}
/** 会话过期或链接退出后跳转站内页面,不使用服务端监听地址。 */
export async function GET(request: NextRequest) {
await clearSessionToken();
const next = request.nextUrl.searchParams.get("next") || "/login";
return NextResponse.redirect(new URL(next, request.url));
return logoutRedirect(request.nextUrl.searchParams.get("next"));
}
+120 -32
View File
@@ -90,6 +90,14 @@ function MessageText({
message: Message;
animate: boolean;
}) {
if (message.status === "generating" && !message.content.trim())
return (
<span className="dh-thinking" role="status" aria-label="正在思考">
<i aria-hidden />
<i aria-hidden />
<i aria-hidden />
</span>
);
return (
<div className="dh-message-text">
<TypedText
@@ -166,13 +174,29 @@ export function DigitalHome({
viewport = useRef<HTMLDivElement>(null),
messagesElement = useRef<HTMLDivElement>(null),
textarea = useRef<HTMLTextAreaElement>(null),
// 跟随是用户意图,内容增高导致暂时离底不能自动退出跟随。
atBottom = useRef(true),
touchY = useRef<number | null>(null),
draggingScroll = useRef(false),
currentId = useRef<string | null>(null),
openSequence = useRef(0);
const cards = boot?.catalog.filter((c) => c.kind === "character") ?? [],
books = boot?.catalog.filter((c) => c.kind === "worldbook") ?? [],
presets = boot?.catalog.filter((c) => c.kind === "preset") ?? [];
const conversationId = conversation?.id;
// 尚未产生正文的失败/停止不算新台词,继续时接回上一段;真实用户消息仍是边界。
const lastReply = conversation?.messages.findLast(
(m) =>
!(
m.role === "assistant" &&
["stopped", "failed"].includes(m.status) &&
!m.content.trim()
),
);
const canContinue =
lastReply?.role === "assistant" &&
["complete", "stopped"].includes(lastReply.status) &&
!!lastReply.content.trim();
// 状态提示走只读接口,打开设定不应写入实验分组、决策或曝光。
useEffect(() => {
if (!showSettings || !conversationId) return;
@@ -248,6 +272,7 @@ export function DigitalHome({
decision: {
...current.decision,
variant: current.decision.fallbackVariant,
value: current.decision.fallbackValue,
decisionId: null,
},
}
@@ -263,17 +288,34 @@ export function DigitalHome({
return () => clearTimeout(timer);
}, [notice]);
useEffect(() => {
const el = messagesElement.current;
if (!el) return;
const observer = new ResizeObserver(() => {
if (atBottom.current)
viewport.current?.scrollTo({
top: viewport.current.scrollHeight,
behavior: "instant",
});
});
const el = messagesElement.current,
view = viewport.current;
if (!el || !view) return;
let frame = 0;
const follow = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
if (!atBottom.current) return;
view.scrollTo({ top: view.scrollHeight, behavior: "instant" });
setShowJump(false);
});
};
// 同时观察内容与可视区:视觉打字、结束后的操作栏、输入框和软键盘都会改变底部位置。
const observer = new ResizeObserver(follow);
observer.observe(el);
return () => observer.disconnect();
observer.observe(view);
const endDrag = () => {
draggingScroll.current = false;
};
window.addEventListener("pointerup", endDrag);
window.addEventListener("pointercancel", endDrag);
follow();
return () => {
observer.disconnect();
cancelAnimationFrame(frame);
window.removeEventListener("pointerup", endDrag);
window.removeEventListener("pointercancel", endDrag);
};
}, [conversationId]);
useEffect(() => {
if (!conversationId) return;
@@ -418,6 +460,7 @@ export function DigitalHome({
setActiveMessage(null);
setShowMenu(false);
atBottom.current = true;
setShowJump(false);
try {
setDraft(sessionStorage.getItem(`dh-draft:${id}`) ?? "");
} catch {
@@ -467,7 +510,7 @@ export function DigitalHome({
favoritePending.current = false;
}
}
async function send(mode: "send" | "regenerate" = "send") {
async function send(mode: "send" | "regenerate" | "continue" = "send") {
if (
!conversation ||
busy ||
@@ -477,13 +520,14 @@ export function DigitalHome({
return;
closeIdeas();
const id = conversation.id,
content = draft.trim(),
content = mode === "send" ? draft.trim() : "",
requestId = crypto.randomUUID();
let assistantId = `pending-${requestId}`;
setBusy(true);
setError("");
setNotice("");
atBottom.current = true;
setShowJump(false);
streamingId.current = id;
if (mode === "send") {
setDraft("");
@@ -993,7 +1037,12 @@ export function DigitalHome({
},
[],
);
const modern = boot?.decision.variant === "B";
// UI按消费者返回值决定,组名仅用于归因;C到Z同样可以返回新版UI。
// 缺少value时兼容尚未升级的服务响应。
const modern =
boot?.decision.value !== undefined
? boot.decision.value === "new" || boot.decision.value === true
: boot?.decision.variant === "B";
return (
<div
className={`dh-app ${modern ? "dh-modern" : "dh-classic"} ${conversation ? "dh-in-chat" : ""}`}
@@ -1122,12 +1171,45 @@ export function DigitalHome({
<div
className="dh-messages"
ref={viewport}
tabIndex={0}
aria-label="聊天消息"
onWheel={(event) => {
if (event.deltaY < 0 && event.currentTarget.scrollTop > 0)
atBottom.current = false;
}}
onTouchStart={(event) => {
touchY.current = event.touches[0]?.clientY ?? null;
}}
onTouchMove={(event) => {
const y = event.touches[0]?.clientY;
if (
y !== undefined &&
touchY.current !== null &&
y > touchY.current &&
event.currentTarget.scrollTop > 0
)
atBottom.current = false;
touchY.current = y ?? null;
}}
onTouchEnd={() => {
touchY.current = null;
}}
onPointerDown={(event) => {
draggingScroll.current =
event.pointerType === "mouse" &&
event.target === event.currentTarget;
}}
onKeyDown={(event) => {
if (["ArrowUp", "PageUp", "Home"].includes(event.key))
atBottom.current = false;
}}
onScroll={() => {
const v = viewport.current;
if (v) {
atBottom.current =
v.scrollHeight - v.scrollTop - v.clientHeight < 110;
setShowJump(!atBottom.current);
const gap = v.scrollHeight - v.scrollTop - v.clientHeight;
if (gap <= 2) atBottom.current = true;
else if (draggingScroll.current) atBottom.current = false;
setShowJump(!atBottom.current && gap > 80);
}
}}
>
@@ -1163,13 +1245,6 @@ export function DigitalHome({
m.id === activeMessage && m.status === "generating"
}
/>
{!m.content && m.status === "generating" && (
<span className="dh-thinking">
<i />
<i />
<i />
</span>
)}
</div>
{!busy && m.content && (
<div className="dh-message-actions">
@@ -1248,9 +1323,10 @@ export function DigitalHome({
className="dh-jump"
onClick={() => {
atBottom.current = true;
setShowJump(false);
viewport.current?.scrollTo({
top: viewport.current.scrollHeight,
behavior: "smooth",
behavior: "instant",
});
}}
>
@@ -1320,14 +1396,26 @@ export function DigitalHome({
</section>
)}
<div className="dh-compose-tools">
<button
type="button"
disabled={busy || ideasLoading}
onClick={generateIdeas}
>
<Sparkles size={14} />
{ideasLoading ? "灵感生成中…" : "灵感回复"}
</button>
<div className="dh-compose-actions">
<button
type="button"
disabled={busy || ideasLoading}
onClick={generateIdeas}
>
<Sparkles size={14} />
{ideasLoading ? "灵感生成中…" : "灵感回复"}
</button>
<button
type="button"
aria-label="让角色继续"
title="不发送输入框里的草稿,让角色接着说"
disabled={busy || ideasLoading || !canContinue}
onClick={() => send("continue")}
>
<ChevronRight size={14} />
继续
</button>
</div>
<button
type="button"
className="dh-mobile-linebreak"
+5
View File
@@ -762,6 +762,11 @@
align-items: center;
margin: 0 4px 8px;
}
.dh-compose-actions {
display: flex;
align-items: center;
gap: 14px;
}
.dh-app .dh-compose-tools button {
display: flex;
align-items: center;
+19
View File
@@ -0,0 +1,19 @@
/** 登出后的站内跳转,避免反向代理后的内部监听地址泄漏到浏览器。 */
/** 使用相对 Location 留在当前站点,并拒绝外部地址和 URL 控制字符。 */
export function logoutRedirect(next: string | null) {
let destination = "/login";
if (
next?.startsWith("/") &&
!/^\/[/\\]/.test(next) &&
!/[\\\u0000-\u0020\u007f]/.test(next)
) {
const local = new URL(next, "https://same-origin.invalid");
// 消除点路径后仍须禁止双斜杠,避免 /.//host 被规范化为外站地址。
if (local.origin === "https://same-origin.invalid" && !local.pathname.startsWith("//")) {
destination = local.pathname + local.search + local.hash;
}
}
// Route Handler 可直接返回相对 Location;不使用 request.url(生产中可能是 0.0.0.0)。
return new Response(null, { status: 307, headers: { Location: destination } });
}
+4 -2
View File
@@ -123,10 +123,12 @@ export type Bootstrap = {
catalog: Card[];
profile: Profile;
decision: {
variant: "A" | "B";
variant: string | null;
value?: unknown;
fallbackValue?: unknown;
decisionId: string | null;
expiresAt: number;
fallbackVariant: "A" | "B";
fallbackVariant: string | null;
};
serverNow: number;
};
+22
View File
@@ -0,0 +1,22 @@
/** 回归登录过期后的跳转:仅返回站内路径,不把服务监听地址发送给浏览器。 */
import test from 'node:test';
import assert from 'node:assert/strict';
import { logoutRedirect } from '../src/lib/auth-redirect.ts';
test('登录过期后跳回当前站点的登录页,不依赖服务内部地址', () => {
const response = logoutRedirect(null);
assert.equal(response.status, 307);
assert.equal(response.headers.get('location'), '/login');
assert.equal(new URL(response.headers.get('location'), 'https://mrzhan.top/api/auth/logout').href, 'https://mrzhan.top/login');
assert.equal(new URL(response.headers.get('location'), 'http://localhost:3210/api/auth/logout').href, 'http://localhost:3210/login');
});
test('保留站内路径和查询参数', () => {
assert.equal(logoutRedirect('/login?reason=expired').headers.get('location'), '/login?reason=expired');
});
test('拒绝外部链接、协议相对地址及反斜杠变体', () => {
for (const next of ['https://example.com', '//example.com', '/\\example.com', 'javascript:alert(1)', '\n//example.com', '/\n/example.com', '/.//example.com', '/%2e//example.com']) {
assert.equal(logoutRedirect(next).headers.get('location'), '/login', next);
}
});