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 });
|
||||
|
||||
@@ -764,7 +764,9 @@ button:disabled { cursor: default; opacity: .45; }
|
||||
font-weight: 500;
|
||||
letter-spacing: .02em;
|
||||
}
|
||||
.session-main small { color: var(--color-ink-tertiary); line-height: 1.3; font-size: var(--type-overline); }
|
||||
.session-main small, .session-subtitle { color: var(--color-ink-tertiary); line-height: 1.3; font-size: var(--type-overline); }
|
||||
.sidebar-group-label { margin: var(--space-2) 0 var(--space-1); color: var(--color-ink-tertiary); font-size: var(--type-overline); font-weight: 500; letter-spacing: .02em; }
|
||||
.session-list-sentinel { height: 1px; }
|
||||
.session-menu-trigger { width: 44px; height: 44px; display: grid; place-items: center; justify-self: center; padding: 0; border: 0; border-radius: 0; background: transparent; color: inherit; cursor: pointer; opacity: .64; transition: background-color 120ms ease-out, color 120ms ease-out, opacity 120ms ease-out, transform 120ms ease-out; }
|
||||
.session-menu-trigger > svg { width: 18px; height: 18px; }
|
||||
.session-row:hover .session-menu-trigger, .session-row:focus-within .session-menu-trigger, .session-menu-trigger[aria-expanded="true"] { opacity: 1; }
|
||||
|
||||
+19
-24
@@ -77,6 +77,7 @@ import { useConversationScrollAnchor } from "@/hooks/use-conversation-scroll-anc
|
||||
import { useProfileOnboarding } from "@/hooks/use-profile-onboarding";
|
||||
import { useRectificationSurface } from "@/hooks/use-rectification-surface";
|
||||
import { useSessionManagement } from "@/hooks/use-session-management";
|
||||
import { sortSessions } from "@/lib/session-groups";
|
||||
import { showChatNotice as setComposerNotice } from "@/lib/chat-notice";
|
||||
import { chatReplyAnnouncement, type ChatReplyPhase } from "@/lib/chat-reply-announcement";
|
||||
import {
|
||||
@@ -196,9 +197,7 @@ import {
|
||||
placeQuestion,
|
||||
readProfile,
|
||||
selectedBirthPlace,
|
||||
sessionChartLabel,
|
||||
sessionSidebarTitle,
|
||||
upsertSelfChart,
|
||||
sessionChartLabel, sessionSidebarSubtitle, sessionSidebarTitle, upsertSelfChart,
|
||||
} from "@/lib/home-profile";
|
||||
import {
|
||||
activeChartStorageKey,
|
||||
@@ -272,6 +271,7 @@ export default function Home() {
|
||||
const [signingOut, setSigningOut] = useState(false);
|
||||
const [sessions, setSessions] = useState<ChatSession[]>([]);
|
||||
const [showArchivedSessions, setShowArchivedSessions] = useState(false);
|
||||
const [sessionsCursor, setSessionsCursor] = useState<string | null>(null);
|
||||
const [sessionMenuId, setSessionMenuId] = useState<string | null>(null);
|
||||
const [pendingSessionDeletion, setPendingSessionDeletion] = useState<ChatSession | null>(null);
|
||||
const [modelCatalog, setModelCatalog] = useState<PublicLanguageModelCatalog | null>(null);
|
||||
@@ -379,13 +379,11 @@ export default function Home() {
|
||||
const activeRectificationSession = activeSession?.sessionType === "birth_time_rectification";
|
||||
const rectificationSurfaceOpen = activeRectificationSession
|
||||
&& activeSession.id === rectificationSessionId;
|
||||
const visibleSessions = sessions
|
||||
.filter((session) => showArchivedSessions ? Boolean(session.archivedAt) : !session.archivedAt)
|
||||
.filter((session) => session.sessionType === "birth_time_rectification"
|
||||
|| session.messages.length > 0
|
||||
|| !session.messagesHydrated
|
||||
|| session.id === activeSessionId)
|
||||
.sort((left, right) => Number(right.pinned) - Number(left.pinned));
|
||||
const visibleSessions = sortSessions(sessions.filter((session) => (showArchivedSessions ? session.archivedAt : !session.archivedAt)
|
||||
&& (session.sessionType === "birth_time_rectification"
|
||||
|| session.messages.length > 0
|
||||
|| !session.messagesHydrated
|
||||
|| session.id === activeSessionId)));
|
||||
const activeError = requestError && requestError.sessionId === activeSession?.id ? requestError.message : "";
|
||||
const isLoading = pendingSessionId === activeSession?.id;
|
||||
const productEntrypointsDisabled = !hydrated
|
||||
@@ -442,8 +440,7 @@ export default function Home() {
|
||||
toggleArchivedSession,
|
||||
shareSession,
|
||||
startNewChat,
|
||||
selectSession,
|
||||
selectSessionModel,
|
||||
selectSession, selectSessionModel, loadMoreSessions, toggleArchivedView,
|
||||
} = useSessionManagement({
|
||||
account, accountId, activeChartId, activeSession, activeSessionId, activeSessionIdRef,
|
||||
applySessionPopStateRef, cancellationPending, chartLibrary, creatingSession, modelCatalog,
|
||||
@@ -451,7 +448,8 @@ export default function Home() {
|
||||
rectificationSessionId, sessionDetailInFlight, sessionSelectionSource, sessions, sessionsRef,
|
||||
setActiveChartId, setActiveSessionId, setBirthTimeConsultationConsent, setCreatingSession,
|
||||
setDraft, setDraftEntrypoint, setDraftTheme, setRectificationError, setRequestError,
|
||||
setSessionDetailLoadingId, setSessionFullPrompt, setSessions, uiPreview, visibleSessions,
|
||||
setSessionDetailLoadingId, setSessionFullPrompt, setSessions, sessionsCursor, setSessionsCursor,
|
||||
showArchivedSessions, setShowArchivedSessions, uiPreview, visibleSessions,
|
||||
openRectificationSession: (exactSessionId) => rectificationSessionOpenerRef.current(exactSessionId),
|
||||
});
|
||||
|
||||
@@ -932,7 +930,8 @@ export default function Home() {
|
||||
]);
|
||||
const nextModelCatalog = modelCatalogResult.catalog;
|
||||
const nextProfile = readProfile(nextAccount.profile);
|
||||
const parsedSessions = readSessions(sessionsPayload, nextModelCatalog);
|
||||
const parsedSessions = readSessions(sessionsPayload.sessions, nextModelCatalog);
|
||||
setSessionsCursor(sessionsPayload.nextCursor);
|
||||
let nextSessions = parsedSessions.sessions;
|
||||
if (nextSessions.length === 0) {
|
||||
if (controller.signal.aborted) return;
|
||||
@@ -1590,10 +1589,9 @@ export default function Home() {
|
||||
};
|
||||
|
||||
const sidebarSessions = visibleSessions.map((session) => ({
|
||||
id: session.id,
|
||||
title: sessionSidebarTitle(session, chartLibrary),
|
||||
pinned: session.pinned,
|
||||
archived: Boolean(session.archivedAt),
|
||||
id: session.id, title: sessionSidebarTitle(session, chartLibrary),
|
||||
subtitle: sessionSidebarSubtitle(session, chartLibrary),
|
||||
pinned: session.pinned, archived: Boolean(session.archivedAt), updatedAt: session.updatedAt,
|
||||
}));
|
||||
const sidebarCharts = (chartLibrary.length > 0
|
||||
? chartLibrary
|
||||
@@ -1744,14 +1742,11 @@ export default function Home() {
|
||||
newChatDisabled={!hydrated || !modelCatalog || creatingSession || Boolean(pendingSessionId) || cancellationPending}
|
||||
creatingSession={creatingSession}
|
||||
sessionControls={{
|
||||
archivedCount: sessions.filter((session) => session.archivedAt).length,
|
||||
showingArchived: showArchivedSessions,
|
||||
archivedCount: sessions.filter((session) => session.archivedAt).length, showingArchived: showArchivedSessions,
|
||||
hasMore: Boolean(sessionsCursor), onLoadMore: loadMoreSessions,
|
||||
menuSessionId: sessionMenuId,
|
||||
disabled: Boolean(pendingSessionId) || cancellationPending,
|
||||
onToggleArchivedView: () => {
|
||||
setShowArchivedSessions((current) => !current);
|
||||
setSessionMenuId(null);
|
||||
},
|
||||
onToggleArchivedView: () => { void toggleArchivedView(); setSessionMenuId(null); },
|
||||
onMenuSessionChange: setSessionMenuId,
|
||||
onTogglePinned: togglePinnedSession,
|
||||
onRename: (sessionId) => {
|
||||
|
||||
Reference in New Issue
Block a user