enhance admin leaderboard and previews
This commit is contained in:
1 parent
a5897caec4
commit
92f5cb8fe3
11 files changed
+937
-282
No files matched your search
@@ -136,8 +136,18 @@ export interface AdminUserAnalyticsResponse {
|
||||
export interface AdminLeaderboardReportResponse {
|
||||
report: string;
|
||||
generated_at: string;
|
||||
cached?: boolean;
|
||||
model_name?: string | null;
|
||||
}
|
||||
|
||||
export type AdminLeaderboardReportStreamEvent =
|
||||
| { event: "meta"; data: { cached?: boolean; model_name?: string | null } }
|
||||
| { event: "cached"; data: { report: string; generated_at?: string | null; model_name?: string | null } }
|
||||
| { event: "thinking"; data: { chunk: string } }
|
||||
| { event: "text"; data: { chunk: string } }
|
||||
| { event: "done"; data: { cached?: boolean; generated_at?: string | null; model_name?: string | null; report?: string } }
|
||||
| { event: "error"; data: { message: string } };
|
||||
|
||||
const base = () => `${getBackendBaseURL()}/api/admin/users`;
|
||||
|
||||
async function parse<T>(res: Response, what: string): Promise<T> {
|
||||
@@ -216,6 +226,7 @@ export async function getUserAnalytics(
|
||||
export async function generateUserLeaderboardReport(
|
||||
range: { since: string; until: string; days?: number },
|
||||
limit = 30,
|
||||
modelName?: string,
|
||||
): Promise<AdminLeaderboardReportResponse> {
|
||||
const params = new URLSearchParams({
|
||||
days: String(range.days ?? 30),
|
||||
@@ -223,6 +234,7 @@ export async function generateUserLeaderboardReport(
|
||||
until: range.until,
|
||||
limit: String(limit),
|
||||
});
|
||||
if (modelName) params.set("model_name", modelName);
|
||||
return parse(
|
||||
await apiFetch(`${base()}/leaderboard/report?${params}`, {
|
||||
method: "POST",
|
||||
@@ -231,6 +243,76 @@ export async function generateUserLeaderboardReport(
|
||||
);
|
||||
}
|
||||
|
||||
function parseSseFrame(frame: string): AdminLeaderboardReportStreamEvent | null {
|
||||
let event = "message";
|
||||
const dataLines: string[] = [];
|
||||
for (const rawLine of frame.split(/\r?\n/)) {
|
||||
const line = rawLine.trimEnd();
|
||||
if (!line || line.startsWith(":")) continue;
|
||||
if (line.startsWith("event:")) {
|
||||
event = line.slice("event:".length).trim();
|
||||
} else if (line.startsWith("data:")) {
|
||||
dataLines.push(line.slice("data:".length).trimStart());
|
||||
}
|
||||
}
|
||||
if (!dataLines.length) return null;
|
||||
const data = JSON.parse(dataLines.join("\n")) as AdminLeaderboardReportStreamEvent["data"];
|
||||
return { event, data } as AdminLeaderboardReportStreamEvent;
|
||||
}
|
||||
|
||||
export async function streamUserLeaderboardReport({
|
||||
range,
|
||||
limit = 30,
|
||||
modelName,
|
||||
signal,
|
||||
onEvent,
|
||||
}: {
|
||||
range: { since: string; until: string; days?: number };
|
||||
limit?: number;
|
||||
modelName?: string;
|
||||
signal?: AbortSignal;
|
||||
onEvent: (event: AdminLeaderboardReportStreamEvent) => void;
|
||||
}) {
|
||||
const params = new URLSearchParams({
|
||||
days: String(range.days ?? 30),
|
||||
since: range.since,
|
||||
until: range.until,
|
||||
limit: String(limit),
|
||||
});
|
||||
if (modelName) params.set("model_name", modelName);
|
||||
const response = await apiFetch(`${base()}/leaderboard/report/stream?${params}`, {
|
||||
method: "POST",
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
const err = (await response.json().catch(() => ({}))) as { detail?: string };
|
||||
throw new Error(err.detail ?? `Failed to stream leaderboard report (HTTP ${response.status})`);
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new Error("当前浏览器不支持流式报告读取");
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder("utf-8");
|
||||
let buffer = "";
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });
|
||||
const frames = buffer.split(/\r?\n\r?\n/);
|
||||
buffer = frames.pop() ?? "";
|
||||
for (const frame of frames) {
|
||||
const parsed = parseSseFrame(frame);
|
||||
if (parsed) onEvent(parsed);
|
||||
}
|
||||
if (done) break;
|
||||
}
|
||||
const tail = buffer.trim();
|
||||
if (tail) {
|
||||
const parsed = parseSseFrame(tail);
|
||||
if (parsed) onEvent(parsed);
|
||||
}
|
||||
}
|
||||
|
||||
export async function addAdminMemoryEntry(
|
||||
userId: string,
|
||||
content: string,
|
||||
|
||||
@@ -53,10 +53,12 @@ export function useGenerateUserLeaderboardReport() {
|
||||
mutationFn: ({
|
||||
range,
|
||||
limit,
|
||||
modelName,
|
||||
}: {
|
||||
range: { since: string; until: string; days?: number };
|
||||
limit?: number;
|
||||
}) => generateUserLeaderboardReport(range, limit ?? 30),
|
||||
modelName?: string;
|
||||
}) => generateUserLeaderboardReport(range, limit ?? 30, modelName),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ export function extractTitleFromMarkdown(markdown: string) {
|
||||
let title = markdown.split("\n")[0]!.trim();
|
||||
if (title.startsWith("# ")) {
|
||||
title = title.slice(2).trim();
|
||||
}
|
||||
return title;
|
||||
}
|
||||
return title;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -52,6 +52,36 @@ function decodeLinkPart(value: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** True for hrefs that point to an anchor within the current document (`#section`). */
|
||||
export function isInPageAnchor(href: string | undefined | null): href is string {
|
||||
return !!href && href.startsWith("#") && !href.startsWith("#reference-");
|
||||
}
|
||||
|
||||
function escapeAttrValue(value: string): string {
|
||||
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrolls to an in-page anchor by id without mutating `window.location.hash`.
|
||||
*
|
||||
* The app runs under a HashRouter, so letting an `<a href="#...">` click change
|
||||
* the hash would be interpreted as a route change and 404. We resolve the target
|
||||
* element ourselves and scroll to it instead. Scoped to the nearest
|
||||
* `[data-markdown-anchor-root]` so headings in other messages don't collide.
|
||||
*/
|
||||
export function scrollToInPageAnchor(anchor: HTMLElement, href: string | undefined | null): void {
|
||||
if (!isInPageAnchor(href)) return;
|
||||
const id = decodeLinkPart(href.slice(1)).trim();
|
||||
if (!id) return;
|
||||
const scope = anchor.closest<HTMLElement>("[data-markdown-anchor-root]");
|
||||
const selector = `[id="${escapeAttrValue(id)}"]`;
|
||||
const target =
|
||||
(scope?.querySelector<HTMLElement>(selector) ?? null) ??
|
||||
document.getElementById(id) ??
|
||||
document.querySelector<HTMLElement>(selector);
|
||||
target?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}
|
||||
|
||||
function normalizeLookupKey(value: string): string {
|
||||
return markdownSlug(decodeLinkPart(value).replace(/^#+/, ""));
|
||||
}
|
||||
@@ -68,6 +98,45 @@ function candidateTextFromHref(href: string): string {
|
||||
return decodeLinkPart(lastSegment).replace(/\.(md|markdown)$/i, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Injects a small runtime script into generated HTML so that clicking an
|
||||
* in-page anchor (`<a href="#section">`) scrolls within the iframe instead of
|
||||
* navigating it. The preview iframe loads from a sandboxed `blob:` URL, where a
|
||||
* fragment navigation blanks the frame; intercepting the click avoids that.
|
||||
*/
|
||||
export function injectInPageAnchorHandler(html: string): string {
|
||||
const script = `<script>(function(){
|
||||
function decode(v){try{return decodeURIComponent(v);}catch(e){return v;}}
|
||||
function bySelector(id){
|
||||
if(!document.querySelector)return null;
|
||||
var esc=window.CSS&&CSS.escape?CSS.escape(id):id.replace(/["\\\\]/g,"\\\\$&");
|
||||
try{return document.querySelector("#"+esc+",[name=\\""+esc+"\\"]");}catch(e){return null;}
|
||||
}
|
||||
document.addEventListener("click",function(e){
|
||||
var el=e.target;
|
||||
while(el&&el.tagName!=="A"){el=el.parentElement;}
|
||||
if(!el)return;
|
||||
var href=el.getAttribute("href");
|
||||
if(!href||href.charAt(0)!=="#"||href.length<2)return;
|
||||
e.preventDefault();
|
||||
var id=decode(href.slice(1));
|
||||
var raw=href.slice(1);
|
||||
var target=
|
||||
document.getElementById(id)||
|
||||
document.getElementById(raw)||
|
||||
document.getElementsByName(id)[0]||
|
||||
document.getElementsByName(raw)[0]||
|
||||
bySelector(id)||
|
||||
bySelector(raw);
|
||||
if(target){target.scrollIntoView({behavior:"smooth",block:"start"});}
|
||||
},true);
|
||||
})();</script>`;
|
||||
if (/<\/body>/i.test(html)) {
|
||||
return html.replace(/<\/body>/i, `${script}</body>`);
|
||||
}
|
||||
return html + script;
|
||||
}
|
||||
|
||||
export function createMarkdownAnchorResolver(markdown: string): MarkdownAnchorResolver {
|
||||
const headings: MarkdownHeadingAnchor[] = [];
|
||||
const idsByLookup = new Map<string, string>();
|
||||
|
||||
Reference in new issue
Block a user