This commit is contained in:
xuhd committed 2026-05-19 16:05:11 +08:00
commit 64492bec43
46 files changed
+3298 -313

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
/** A conversation thread owned by some user (admin view). */
export interface AdminThread {
thread_id: string;
display_name: string;
status: string;
created_at: string;
updated_at: string;
}
/**
* One conversation message, as serialized from the LangGraph checkpoint —
* a LangChain message dump: ``type`` is "human" | "ai" | "tool" | "system",
* ``content`` is a string or a content-block list.
*/
export interface AdminMessage {
type?: string;
content?: unknown;
id?: string | null;
name?: string | null;
}
/** One memory bucket: the global file or a per-agent file. */
export interface AdminMemoryBucket {
name: string;
data: Record<string, unknown>;
}
export interface AdminMemoryResponse {
user_id: string;
buckets: AdminMemoryBucket[];
}
const base = () => `${getBackendBaseURL()}/api/admin/users`;
async function parse<T>(res: Response, what: string): Promise<T> {
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `${what} (HTTP ${res.status})`);
}
return res.json() as Promise<T>;
}
export async function listUserThreads(userId: string): Promise<AdminThread[]> {
return parse(
await apiFetch(`${base()}/${encodeURIComponent(userId)}/threads?limit=200`),
"Failed to load threads",
);
}
export async function listUserThreadMessages(
userId: string,
threadId: string,
): Promise<AdminMessage[]> {
return parse(
await apiFetch(
`${base()}/${encodeURIComponent(userId)}/threads/${encodeURIComponent(threadId)}/messages`,
),
"Failed to load messages",
);
}
export async function getUserMemory(
userId: string,
): Promise<AdminMemoryResponse> {
return parse(
await apiFetch(`${base()}/${encodeURIComponent(userId)}/memory`),
"Failed to load memory",
);
}
+33
View File
@@ -0,0 +1,33 @@
import { useQuery } from "@tanstack/react-query";
import { getUserMemory, listUserThreadMessages, listUserThreads } from "./api";
/** Threads owned by a given user. Disabled until a user is picked. */
export function useUserThreads(userId: string | null) {
return useQuery({
queryKey: ["admin-activity", "threads", userId],
queryFn: () => listUserThreads(userId!),
enabled: !!userId,
});
}
/** Messages of a given thread. Disabled until a thread is picked. */
export function useUserThreadMessages(
userId: string | null,
threadId: string | null,
) {
return useQuery({
queryKey: ["admin-activity", "messages", userId, threadId],
queryFn: () => listUserThreadMessages(userId!, threadId!),
enabled: !!userId && !!threadId,
});
}
/** All memory buckets of a given user. Disabled until a user is picked. */
export function useUserMemory(userId: string | null) {
return useQuery({
queryKey: ["admin-activity", "memory", userId],
queryFn: () => getUserMemory(userId!),
enabled: !!userId,
});
}
+2 -2
View File
@@ -17,13 +17,13 @@ export class AgentNameCheckError extends Error {
export interface ListAgentsParams {
search?: string;
tagId?: string | null;
tagIds?: string[];
}
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
const qs = new URLSearchParams();
if (params.search) qs.set("search", params.search);
if (params.tagId) qs.set("tag_id", params.tagId);
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
const query = qs.toString();
const res = await apiFetch(
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
+4 -4
View File
@@ -14,12 +14,12 @@ import {
} from "./api";
import type { CreateAgentRequest, UpdateAgentRequest } from "./types";
export function useAgents(params: { search?: string; tagId?: string | null } = {}) {
export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
const search = params.search ?? "";
const tagId = params.tagId ?? null;
const tagIds = params.tagIds ?? [];
const { data, isLoading, error } = useQuery({
queryKey: ["agents", search, tagId],
queryFn: () => listAgents({ search, tagId }),
queryKey: ["agents", search, [...tagIds].sort()],
queryFn: () => listAgents({ search, tagIds }),
placeholderData: keepPreviousData,
});
return { agents: data ?? [], isLoading, error };
+6 -2
View File
@@ -43,12 +43,14 @@ export async function downloadArtifactFile({
filepath,
threadId,
isMock,
publicShareCode,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
publicShareCode?: string;
}): Promise<void> {
const url = urlOfArtifact({ filepath, threadId, isMock, download: true });
const url = urlOfArtifact({ filepath, threadId, isMock, publicShareCode, download: true });
const res = await apiFetch(url);
if (!res.ok) {
throw new Error(await errorMessageFromResponse(res));
@@ -73,12 +75,14 @@ export async function openArtifactInNewTab({
filepath,
threadId,
isMock,
publicShareCode,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
publicShareCode?: string;
}): Promise<void> {
const url = urlOfArtifact({ filepath, threadId, isMock, download: false });
const url = urlOfArtifact({ filepath, threadId, isMock, publicShareCode, download: false });
const res = await apiFetch(url);
if (!res.ok) {
throw new Error(await errorMessageFromResponse(res));
+28 -28
View File
@@ -1,8 +1,8 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo } from "react";
import { useThread } from "@/components/workspace/messages/context";
import { useThread } from "@/components/workspace/messages/context";
import { loadArtifactContent, loadArtifactContentFromToolCall } from "./loader";
import { updateArtifactContent } from "./api";
@@ -60,32 +60,32 @@ function applyPendingTextEdit({
}
return null;
}
export function useArtifactContent({
filepath,
threadId,
enabled,
}: {
filepath: string;
threadId: string;
enabled?: boolean;
}) {
const isWriteFile = useMemo(() => {
return filepath.startsWith("write-file:");
}, [filepath]);
const { thread, isMock } = useThread();
const content = useMemo(() => {
if (isWriteFile) {
return loadArtifactContentFromToolCall({ url: filepath, thread });
}
return null;
}, [filepath, isWriteFile, thread]);
export function useArtifactContent({
filepath,
threadId,
enabled,
}: {
filepath: string;
threadId: string;
enabled?: boolean;
}) {
const isWriteFile = useMemo(() => {
return filepath.startsWith("write-file:");
}, [filepath]);
const { thread, isMock, publicShareCode } = useThread();
const content = useMemo(() => {
if (isWriteFile) {
return loadArtifactContentFromToolCall({ url: filepath, thread });
}
return null;
}, [filepath, isWriteFile, thread]);
const { data, isLoading, error } = useQuery({
queryKey: ["artifact", filepath, threadId, isMock],
queryFn: () => {
return loadArtifactContent({ filepath, threadId, isMock });
},
queryKey: ["artifact", filepath, threadId, isMock, publicShareCode],
queryFn: () => {
return loadArtifactContent({ filepath, threadId, isMock, publicShareCode });
},
enabled,
refetchInterval: thread.isLoading ? 1000 : false,
// Cache artifact content for 5 minutes to avoid repeated fetches (especially for .skill ZIP extraction)
+3 -1
View File
@@ -9,16 +9,18 @@ export async function loadArtifactContent({
filepath,
threadId,
isMock,
publicShareCode,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
publicShareCode?: string;
}) {
let enhancedFilepath = filepath;
if (filepath.endsWith(".skill")) {
enhancedFilepath = filepath + "/SKILL.md";
}
const url = urlOfArtifact({ filepath: enhancedFilepath, threadId, isMock });
const url = urlOfArtifact({ filepath: enhancedFilepath, threadId, isMock, publicShareCode });
const response = await apiFetch(url);
const text = await response.text();
return { content: text, url };
+10
View File
@@ -6,12 +6,22 @@ export function urlOfArtifact({
threadId,
download = false,
isMock = false,
publicShareCode,
}: {
filepath: string;
threadId: string;
download?: boolean;
isMock?: boolean;
publicShareCode?: string;
}) {
// A public read-only share has no auth-gated thread route — its referenced
// files are served by the unauthenticated public-share endpoint instead.
if (publicShareCode) {
const normalized = filepath.startsWith("/") ? filepath : `/${filepath}`;
return `${getBackendBaseURL()}/api/public/shares/${encodeURIComponent(
publicShareCode,
)}/files${normalized}`;
}
if (isMock) {
return `${getBackendBaseURL()}/mock/api/threads/${threadId}/artifacts${filepath}${download ? "?download=true" : ""}`;
}
+2 -2
View File
@@ -31,13 +31,13 @@ export async function getSchedulerThread() {
export interface ListScheduledTasksParams {
search?: string;
tagId?: string | null;
tagIds?: string[];
}
export async function listScheduledTasks(params: ListScheduledTasksParams = {}) {
const qs = new URLSearchParams();
if (params.search) qs.set("search", params.search);
if (params.tagId) qs.set("tag_id", params.tagId);
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
const query = qs.toString();
return parseResponse<ScheduledTask[]>(
await apiFetch(`${baseUrl()}${query ? `?${query}` : ""}`),
@@ -42,13 +42,13 @@ export function useSchedulerThread() {
}
export function useScheduledTasks(
params: { search?: string; tagId?: string | null } = {},
params: { search?: string; tagIds?: string[] } = {},
) {
const search = params.search ?? "";
const tagId = params.tagId ?? null;
const tagIds = params.tagIds ?? [];
return useQuery({
queryKey: ["scheduled-tasks", "list", search, tagId],
queryFn: () => listScheduledTasks({ search, tagId }),
queryKey: ["scheduled-tasks", "list", search, [...tagIds].sort()],
queryFn: () => listScheduledTasks({ search, tagIds }),
refetchOnWindowFocus: false,
placeholderData: keepPreviousData,
});
+2 -2
View File
@@ -5,13 +5,13 @@ import type { Skill, SkillState } from "./type";
export interface ListSkillsParams {
search?: string;
tagId?: string | null;
tagIds?: string[];
}
export async function loadSkills(params: ListSkillsParams = {}) {
const qs = new URLSearchParams();
if (params.search) qs.set("search", params.search);
if (params.tagId) qs.set("tag_id", params.tagId);
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
const query = qs.toString();
const skills = await apiFetch(
`${getBackendBaseURL()}/api/skills${query ? `?${query}` : ""}`,
+4 -4
View File
@@ -21,12 +21,12 @@ import type { SkillState } from "./type";
import { loadSkills } from ".";
export function useSkills(params: { search?: string; tagId?: string | null } = {}) {
export function useSkills(params: { search?: string; tagIds?: string[] } = {}) {
const search = params.search ?? "";
const tagId = params.tagId ?? null;
const tagIds = params.tagIds ?? [];
const { data, isLoading, error } = useQuery({
queryKey: ["skills", search, tagId],
queryFn: () => loadSkills({ search, tagId }),
queryKey: ["skills", search, [...tagIds].sort()],
queryFn: () => loadSkills({ search, tagIds }),
placeholderData: keepPreviousData,
});
return { skills: data ?? [], isLoading, error };
+151
View File
@@ -0,0 +1,151 @@
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
/** Coarse failure buckets, mirrored from the backend classifier. */
export const TOOL_ERROR_CATEGORIES = [
"rate_limited",
"ip_blocked",
"auth_error",
"timeout",
"network_error",
"not_found",
"empty_result",
"tool_error",
] as const;
export type ToolErrorCategory = (typeof TOOL_ERROR_CATEGORIES)[number];
/** Human-readable Chinese labels for each failure bucket. */
export const TOOL_ERROR_CATEGORY_LABELS: Record<string, string> = {
rate_limited: "限流 / 频率超限",
ip_blocked: "IP 被封 / 拒绝访问",
auth_error: "鉴权失败",
timeout: "超时",
network_error: "网络错误",
not_found: "资源不存在",
empty_result: "检索为空",
tool_error: "工具内部错误",
};
export interface ToolMetric {
id: string;
created_at?: string | null;
user_id?: string | null;
user_name?: string | null;
thread_id?: string | null;
run_id?: string | null;
agent_name?: string | null;
tool_name?: string | null;
/** The Agent Skill this call targets (skill tool calls only). */
skill_name?: string | null;
duration_ms: number;
status: "success" | "error" | string;
error_category?: string | null;
error_message?: string | null;
}
export interface ToolMetricsListResponse {
items: ToolMetric[];
total: number;
limit: number;
offset: number;
}
/** Per-skill aggregate — was the skill invoked, and how often did it succeed. */
export interface SkillStat {
skill_name: string;
total: number;
success: number;
error: number;
}
export interface ToolMetricsSummary {
total: number;
error_total: number;
by_category: Record<string, number>;
by_skill: SkillStat[];
}
export interface ToolMetricsFilters {
user_id?: string;
user_name?: string;
tool_name?: string;
/** Coarse call kind: "skill" keeps only Agent-Skill invocations; omit for all. */
kind?: "skill" | "all";
/** Filter to one specific Agent Skill by name. */
skill_name?: string;
status?: "success" | "error";
error_category?: string;
since?: string;
until?: string;
}
export interface ToolMetricsListQuery extends ToolMetricsFilters {
limit?: number;
offset?: number;
}
function buildQuery(filters: ToolMetricsListQuery): string {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(filters)) {
if (value === undefined || value === null || value === "") continue;
params.set(key, String(value));
}
const qs = params.toString();
return qs ? `?${qs}` : "";
}
export async function loadToolMetrics(
query: ToolMetricsListQuery,
): Promise<ToolMetricsListResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/admin/tool-metrics${buildQuery(query)}`,
);
if (!response.ok) {
const detail = await response.json().catch(() => ({ detail: response.statusText }));
throw new Error(detail.detail ?? "Failed to load tool metrics");
}
return (await response.json()) as ToolMetricsListResponse;
}
export async function loadToolMetricsSummary(
filters: ToolMetricsFilters,
): Promise<ToolMetricsSummary> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/admin/tool-metrics/summary${buildQuery(filters)}`,
);
if (!response.ok) {
const detail = await response.json().catch(() => ({ detail: response.statusText }));
throw new Error(detail.detail ?? "Failed to load tool metrics summary");
}
return (await response.json()) as ToolMetricsSummary;
}
export async function downloadToolMetricsExcel(
filters: ToolMetricsFilters,
): Promise<void> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/admin/tool-metrics/export${buildQuery(filters)}`,
);
if (!response.ok) {
const detail = await response.json().catch(() => ({ detail: response.statusText }));
throw new Error(detail.detail ?? "Failed to export tool metrics");
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const filename = (() => {
const header = response.headers.get("content-disposition") ?? "";
const utf8 = /filename\*=UTF-8''([^;]+)/i.exec(header);
if (utf8?.[1]) return decodeURIComponent(utf8[1]);
const plain = /filename="?([^";]+)"?/i.exec(header);
return plain?.[1] ?? `tool_call_metrics.xlsx`;
})();
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.rel = "noopener";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
@@ -0,0 +1,26 @@
import { useQuery } from "@tanstack/react-query";
import {
loadToolMetrics,
loadToolMetricsSummary,
type ToolMetricsFilters,
type ToolMetricsListQuery,
} from "./api";
export function useToolMetrics(query: ToolMetricsListQuery) {
return useQuery({
queryKey: ["toolMetrics", query],
queryFn: () => loadToolMetrics(query),
refetchOnWindowFocus: false,
placeholderData: (previous) => previous,
});
}
export function useToolMetricsSummary(filters: ToolMetricsFilters) {
return useQuery({
queryKey: ["toolMetricsSummary", filters],
queryFn: () => loadToolMetricsSummary(filters),
refetchOnWindowFocus: false,
placeholderData: (previous) => previous,
});
}