fix(web): summarize session titles, sort by activity, and paginate history (BUG-553)
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -73,6 +73,7 @@ import {
|
||||
type GeneralDailyPanchangaContext,
|
||||
} from "@/lib/general-daily-panchanga";
|
||||
import { consultationHistoryFromStoredMessages } from "@/lib/consultation-session-history";
|
||||
import { generateSessionTitle, shouldGenerateSessionTitle } from "@/lib/session-title-agent";
|
||||
import { z } from "zod";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -278,7 +279,7 @@ export async function POST(request: Request) {
|
||||
|
||||
const { data: chatSession, error: chatSessionError } = await supabase
|
||||
.from("chat_sessions")
|
||||
.select("id,model_id,model_config_version,session_type,messages")
|
||||
.select("id,model_id,model_config_version,session_type,messages,title,theme,chart_profile_role")
|
||||
.eq("id", parsed.data.sessionId)
|
||||
.eq("user_id", user.id)
|
||||
.maybeSingle();
|
||||
@@ -637,6 +638,34 @@ export async function POST(request: Request) {
|
||||
// its settle-and-log entry point here so the request-level catch below can
|
||||
// still emit it.
|
||||
const agenticFailure: { report?: (error: unknown) => Promise<void> } = {};
|
||||
const expectedTitle = typeof chatSession.title === "string" ? chatSession.title : "";
|
||||
const titleSideEvent = shouldGenerateSessionTitle({
|
||||
title: expectedTitle,
|
||||
sessionType: chatSession.session_type,
|
||||
}, storedHistory)
|
||||
? generateSessionTitle({
|
||||
model: selectedModel,
|
||||
question: parsed.data.question,
|
||||
theme: consultationTheme,
|
||||
chartRole: chatSession.chart_profile_role === "other" ? "other" : "self",
|
||||
signal: request.signal,
|
||||
}).then(async (title) => {
|
||||
if (!title) return null;
|
||||
try {
|
||||
const { error } = await supabase.from("chat_sessions").update({ title })
|
||||
.eq("id", sessionId)
|
||||
.eq("user_id", userId)
|
||||
.eq("title", expectedTitle);
|
||||
if (error) console.warn("session title persist failed", error);
|
||||
} catch (error) {
|
||||
console.warn("session title persist failed", error);
|
||||
}
|
||||
return { type: "session.title" as const, title };
|
||||
}).catch((error) => {
|
||||
console.warn("session title failed", error);
|
||||
return null;
|
||||
})
|
||||
: Promise.resolve(null);
|
||||
|
||||
async function runAgenticConsultation(
|
||||
consultationMode: ConsultationBirthTimeMode,
|
||||
@@ -837,6 +866,7 @@ export async function POST(request: Request) {
|
||||
return streamAgentResponse({
|
||||
runId: requestId,
|
||||
requestId,
|
||||
sideEvent: titleSideEvent,
|
||||
state,
|
||||
stream: result.fullStream,
|
||||
requireTool: false,
|
||||
@@ -939,6 +969,7 @@ export async function POST(request: Request) {
|
||||
return streamAgentResponse({
|
||||
runId: requestId,
|
||||
requestId,
|
||||
sideEvent: titleSideEvent,
|
||||
state,
|
||||
stream: result.fullStream,
|
||||
requireTool: true,
|
||||
@@ -1054,6 +1085,7 @@ export async function POST(request: Request) {
|
||||
return streamAgentResponse({
|
||||
runId: requestId,
|
||||
requestId,
|
||||
sideEvent: titleSideEvent,
|
||||
state,
|
||||
stream: result.fullStream,
|
||||
requireTool: true,
|
||||
|
||||
@@ -101,11 +101,19 @@ export async function GET(request: Request) {
|
||||
statusData = settledData;
|
||||
}
|
||||
|
||||
const { data: sessionRow } = await supabase
|
||||
.from("chat_sessions")
|
||||
.select("title")
|
||||
.eq("id", statusData.session_id)
|
||||
.eq("user_id", user.id)
|
||||
.maybeSingle();
|
||||
|
||||
return NextResponse.json({
|
||||
requestId: statusData.request_id,
|
||||
sessionId: statusData.session_id,
|
||||
status: statusData.status,
|
||||
responseMessage: statusData.response_message,
|
||||
updatedAt: statusData.updated_at,
|
||||
...(typeof sessionRow?.title === "string" ? { title: sessionRow.title } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,14 +3,13 @@ import { createServerSupabaseClient } from "@/lib/supabase/server";
|
||||
import { isSupabaseConfigurationError } from "@/lib/supabase/config";
|
||||
import {
|
||||
ChatSessionBodyTooLargeError,
|
||||
chatSessionMetadataPatchSchema,
|
||||
chatSessionModelPatchSchema,
|
||||
chatSessionWriteSchema,
|
||||
extractChatSessionMetadataPatch,
|
||||
readChatSessionJson,
|
||||
} from "@/lib/chat-session-write-contract";
|
||||
import { logIgnoredSessionMessages } from "@/lib/chat-session-observability";
|
||||
import { consumeUserRequestRateLimit } from "@/lib/request-rate-limit";
|
||||
import { metadataUpdateValues } from "@/lib/session-metadata-update";
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
@@ -25,12 +24,6 @@ function ignoredMessageCount(payload: { messages: unknown }) {
|
||||
return Array.isArray(payload.messages) ? payload.messages.length : 0;
|
||||
}
|
||||
|
||||
function metadataUpdateValues(payload: unknown): Record<string, unknown> | null {
|
||||
const parsed = chatSessionMetadataPatchSchema.safeParse(extractChatSessionMetadataPatch(payload));
|
||||
if (!parsed.success) return null;
|
||||
return { ...parsed.data, updated_at: new Date().toISOString() };
|
||||
}
|
||||
|
||||
export async function GET(_request: Request, context: RouteContext) {
|
||||
try {
|
||||
const { id } = await context.params;
|
||||
@@ -86,7 +79,7 @@ export async function PATCH(request: Request, context: RouteContext) {
|
||||
values = metadataUpdateValues(fullWrite.data);
|
||||
}
|
||||
if (!values && modelPatch.success) {
|
||||
values = { ...modelPatch.data, updated_at: new Date().toISOString() };
|
||||
values = { ...modelPatch.data };
|
||||
}
|
||||
if (!values && payloadHasMessages(payload)) {
|
||||
return NextResponse.json({ ok: true });
|
||||
|
||||
@@ -3,21 +3,74 @@ import { chatSessionCreateSchema, ChatSessionBodyTooLargeError, readChatSessionJ
|
||||
import { consumeUserRequestRateLimit } from "@/lib/request-rate-limit";
|
||||
import { isSupabaseConfigurationError } from "@/lib/supabase/config";
|
||||
import { createServerSupabaseClient } from "@/lib/supabase/server";
|
||||
import {
|
||||
clampSessionLimit,
|
||||
isArchivedSessionQuery,
|
||||
nextSessionCursor,
|
||||
parseSessionCursor,
|
||||
sessionCursorFilter,
|
||||
} from "@/lib/session-cursor";
|
||||
|
||||
const SESSION_LIST_COLUMNS = "id,title,theme,model_id,session_type,rectification_case_id,chart_profile_id,chart_profile_name,chart_profile_role,updated_at,pinned,archived_at";
|
||||
|
||||
export async function GET() {
|
||||
function applyArchiveFilter<Query extends {
|
||||
is: (column: string, value: null) => Query;
|
||||
not: (column: string, operator: string, value: null) => Query;
|
||||
}>(query: Query, archived: boolean): Query {
|
||||
return archived ? query.not("archived_at", "is", null) : query.is("archived_at", null);
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url);
|
||||
const limit = clampSessionLimit(url.searchParams.get("limit"));
|
||||
const archived = isArchivedSessionQuery(url.searchParams.get("archived"));
|
||||
const beforeRaw = url.searchParams.get("before");
|
||||
const cursor = parseSessionCursor(beforeRaw);
|
||||
if (beforeRaw && !cursor) {
|
||||
return NextResponse.json({ error: "聊天记录请求无效" }, { status: 400 });
|
||||
}
|
||||
const supabase = await createServerSupabaseClient();
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser();
|
||||
if (authError || !user) return NextResponse.json({ error: "请先登录" }, { status: 401 });
|
||||
const { data, error } = await supabase
|
||||
.from("chat_sessions")
|
||||
.select(SESSION_LIST_COLUMNS)
|
||||
.eq("user_id", user.id)
|
||||
.order("updated_at", { ascending: false });
|
||||
if (error) return NextResponse.json({ error: "聊天记录暂时无法读取" }, { status: 500 });
|
||||
return NextResponse.json({ sessions: data ?? [] });
|
||||
|
||||
let pageQuery = applyArchiveFilter(
|
||||
supabase
|
||||
.from("chat_sessions")
|
||||
.select(SESSION_LIST_COLUMNS)
|
||||
.eq("user_id", user.id)
|
||||
.eq("pinned", false),
|
||||
archived,
|
||||
)
|
||||
.order("updated_at", { ascending: false })
|
||||
.order("id", { ascending: false })
|
||||
.limit(limit + 1);
|
||||
if (cursor) {
|
||||
pageQuery = pageQuery.or(sessionCursorFilter(cursor));
|
||||
}
|
||||
const { data: pageRows, error: pageError } = await pageQuery;
|
||||
if (pageError) return NextResponse.json({ error: "聊天记录暂时无法读取" }, { status: 500 });
|
||||
|
||||
let pinnedRows: typeof pageRows = [];
|
||||
if (!cursor) {
|
||||
const { data: pinnedData, error: pinnedError } = await applyArchiveFilter(
|
||||
supabase
|
||||
.from("chat_sessions")
|
||||
.select(SESSION_LIST_COLUMNS)
|
||||
.eq("user_id", user.id)
|
||||
.eq("pinned", true),
|
||||
archived,
|
||||
)
|
||||
.order("updated_at", { ascending: false })
|
||||
.order("id", { ascending: false });
|
||||
if (pinnedError) return NextResponse.json({ error: "聊天记录暂时无法读取" }, { status: 500 });
|
||||
pinnedRows = pinnedData ?? [];
|
||||
}
|
||||
|
||||
const nextCursor = nextSessionCursor(pageRows ?? [], limit);
|
||||
const page = (pageRows ?? []).slice(0, limit);
|
||||
const sessions = cursor ? page : [...(pinnedRows ?? []), ...page];
|
||||
return NextResponse.json({ sessions, nextCursor });
|
||||
} catch (error) {
|
||||
if (isSupabaseConfigurationError(error)) {
|
||||
return NextResponse.json({ error: "数据库尚未配置", code: "DATABASE_NOT_CONFIGURED" }, { status: 503 });
|
||||
|
||||
Reference in New Issue
Block a user