feat: initialize TJWater WebGIS frontend
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createAgentApiClient } from "./client";
|
||||
|
||||
describe("Agent API client sessions", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("lists normalized sessions in newest-first order", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
sessions: [
|
||||
{ id: "old", title: "", created_at: 100, updated_at: 120 },
|
||||
{ id: "new", title: " 新会话 ", created_at: 200, updated_at: 210, run_status: "running" }
|
||||
]
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const sessions = await createAgentApiClient("http://agent.local").listSessions();
|
||||
|
||||
expect(sessions).toEqual([
|
||||
{
|
||||
id: "new",
|
||||
title: "新会话",
|
||||
createdAt: 200,
|
||||
updatedAt: 210,
|
||||
status: undefined,
|
||||
parentSessionId: undefined,
|
||||
isStreaming: undefined,
|
||||
runStatus: "running"
|
||||
},
|
||||
{
|
||||
id: "old",
|
||||
title: "新对话",
|
||||
createdAt: 100,
|
||||
updatedAt: 120,
|
||||
status: undefined,
|
||||
parentSessionId: undefined,
|
||||
isStreaming: undefined,
|
||||
runStatus: undefined
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns null when loading a missing session", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ message: "missing" }), { status: 404 })));
|
||||
|
||||
await expect(createAgentApiClient("http://agent.local").loadSession("missing")).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("falls back when a candidate is not the agent service", async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ message: "not found" }), { status: 404 }))
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
schema_version: "agent-ui-registry@1",
|
||||
chart_grammars: [],
|
||||
components: [],
|
||||
actions: []
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
await expect(createAgentApiClient(["http://not-agent.local", "http://agent.local"]).getUiRegistry()).resolves.toEqual({
|
||||
schema_version: "agent-ui-registry@1",
|
||||
chart_grammars: [],
|
||||
components: [],
|
||||
actions: []
|
||||
});
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://not-agent.local/api/v1/agent/chat/ui-registry",
|
||||
undefined
|
||||
);
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, "http://agent.local/api/v1/agent/chat/ui-registry", undefined);
|
||||
});
|
||||
|
||||
it("sends title update payloads using backend field names", async () => {
|
||||
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true }), { status: 200 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
await createAgentApiClient("http://agent.local").updateSessionTitle("session-1", " 标题 ", {
|
||||
isTitleManuallyEdited: true
|
||||
});
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://agent.local/api/v1/agent/chat/session/session-1/title",
|
||||
expect.objectContaining({
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({
|
||||
title: "标题",
|
||||
is_title_manually_edited: true
|
||||
})
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("streams session events from the backend SSE endpoint", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () =>
|
||||
new Response(
|
||||
[
|
||||
'event: state\ndata: {"session_id":"session-1","messages":[{"id":"u1","role":"user","parts":[{"type":"text","text":"检查压力"}]}],"is_streaming":true,"run_status":"running"}\n\n',
|
||||
'event: token\ndata: {"session_id":"session-1","content":"处理中"}\n\n',
|
||||
'event: done\ndata: {"session_id":"session-1","duration_ms":20}\n\n'
|
||||
].join(""),
|
||||
{ status: 200 }
|
||||
)
|
||||
)
|
||||
);
|
||||
const events: unknown[] = [];
|
||||
|
||||
await createAgentApiClient("http://agent.local").streamSession("session-1", {
|
||||
onEvent: (event) => events.push(event)
|
||||
});
|
||||
|
||||
expect(events).toEqual([
|
||||
{
|
||||
type: "state",
|
||||
sessionId: "session-1",
|
||||
messages: [{ id: "u1", role: "user", parts: [{ type: "text", text: "检查压力" }] }],
|
||||
isStreaming: true,
|
||||
runStatus: "running"
|
||||
},
|
||||
{
|
||||
type: "token",
|
||||
sessionId: "session-1",
|
||||
data: { session_id: "session-1", content: "处理中" }
|
||||
},
|
||||
{
|
||||
type: "done",
|
||||
sessionId: "session-1",
|
||||
data: { session_id: "session-1", duration_ms: 20 }
|
||||
}
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,581 @@
|
||||
import { env } from "@/shared/config/env";
|
||||
|
||||
export type AgentRunStatus = "running" | "completed" | "error" | "aborted";
|
||||
|
||||
export type AgentPermissionReply = "once" | "always" | "reject";
|
||||
|
||||
export type AgentModelOption = {
|
||||
id: string;
|
||||
label: string;
|
||||
description: string;
|
||||
icon: "bolt" | "sparkle";
|
||||
};
|
||||
|
||||
export type AgentModelsResponse = {
|
||||
defaultModel: string;
|
||||
models: AgentModelOption[];
|
||||
};
|
||||
|
||||
export type AgentChatSession = {
|
||||
id?: string;
|
||||
session_id: string;
|
||||
title?: string;
|
||||
status?: string;
|
||||
run_status?: AgentRunStatus;
|
||||
is_streaming?: boolean;
|
||||
messages?: unknown[];
|
||||
created_at?: number | string;
|
||||
updated_at?: number | string;
|
||||
is_title_manually_edited?: boolean;
|
||||
parent_session_id?: string;
|
||||
};
|
||||
|
||||
export type AgentChatSessionSummary = {
|
||||
id: string;
|
||||
title: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
status?: string;
|
||||
parentSessionId?: string;
|
||||
isStreaming?: boolean;
|
||||
runStatus?: AgentRunStatus;
|
||||
};
|
||||
|
||||
export type AgentLoadedChatSession = AgentChatSessionSummary & {
|
||||
sessionId: string;
|
||||
isTitleManuallyEdited: boolean;
|
||||
messages: unknown[];
|
||||
};
|
||||
|
||||
export type AgentSessionStreamDataEventType =
|
||||
| "token"
|
||||
| "progress"
|
||||
| "todo_update"
|
||||
| "permission_request"
|
||||
| "permission_response"
|
||||
| "question_request"
|
||||
| "question_response"
|
||||
| "tool_call"
|
||||
| "frontend_action"
|
||||
| "frontend_action_result"
|
||||
| "ui_envelope"
|
||||
| "session_title"
|
||||
| "done"
|
||||
| "error"
|
||||
| "auth_required";
|
||||
|
||||
export type AgentSessionStreamEvent =
|
||||
| {
|
||||
type: "state";
|
||||
sessionId: string;
|
||||
messages: unknown[];
|
||||
isStreaming: boolean;
|
||||
runStatus?: AgentRunStatus;
|
||||
}
|
||||
| {
|
||||
type: AgentSessionStreamDataEventType;
|
||||
sessionId?: string;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type AgentApiClient = {
|
||||
createSession: () => Promise<AgentChatSession>;
|
||||
listSessions: () => Promise<AgentChatSessionSummary[]>;
|
||||
loadSession: (sessionId: string) => Promise<AgentLoadedChatSession | null>;
|
||||
streamSession: (
|
||||
sessionId: string,
|
||||
options: {
|
||||
signal?: AbortSignal;
|
||||
onEvent: (event: AgentSessionStreamEvent) => void;
|
||||
}
|
||||
) => Promise<void>;
|
||||
updateSessionTitle: (
|
||||
sessionId: string,
|
||||
title: string,
|
||||
options?: { isTitleManuallyEdited?: boolean }
|
||||
) => Promise<void>;
|
||||
deleteSession: (sessionId: string) => Promise<void>;
|
||||
getModels: () => Promise<AgentModelsResponse>;
|
||||
getUiRegistry: () => Promise<unknown>;
|
||||
getFrontendActionRegistry: () => Promise<unknown>;
|
||||
submitFrontendActionResult: (sessionId: string, actionId: string, result: unknown) => Promise<void>;
|
||||
resolveRenderRef: (renderRef: string, sessionId: string) => Promise<unknown>;
|
||||
replyPermission: (
|
||||
requestId: string,
|
||||
options: { sessionId: string; reply: AgentPermissionReply; message?: string }
|
||||
) => Promise<void>;
|
||||
replyQuestion: (
|
||||
requestId: string,
|
||||
options: { sessionId: string; answers: string[][] }
|
||||
) => Promise<void>;
|
||||
rejectQuestion: (requestId: string, options: { sessionId: string }) => Promise<void>;
|
||||
abort: (sessionId: string) => Promise<void>;
|
||||
};
|
||||
|
||||
const AGENT_API_BASE_URLS = [env.TJWATER_AGENT_API_BASE_URL.replace(/\/$/, "")];
|
||||
|
||||
const CHAT_PATH = "/api/v1/agent/chat";
|
||||
|
||||
export function createAgentApiClient(baseUrls: string | string[] = AGENT_API_BASE_URLS): AgentApiClient {
|
||||
const candidates = (Array.isArray(baseUrls) ? baseUrls : [baseUrls]).map((item) => item.replace(/\/$/, ""));
|
||||
let activeBaseUrl = candidates[0] ?? "";
|
||||
|
||||
return {
|
||||
async createSession() {
|
||||
return requestJsonWithFallback<AgentChatSession>(candidates, activeBaseUrl, (nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
}, "/session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
},
|
||||
|
||||
async listSessions() {
|
||||
const payload = await requestJsonWithFallback<{ sessions?: unknown[] }>(
|
||||
candidates,
|
||||
activeBaseUrl,
|
||||
(nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
},
|
||||
"/sessions"
|
||||
);
|
||||
return (payload.sessions ?? []).map(toSessionSummary).filter(isPresent).sort(compareSessionSummaries);
|
||||
},
|
||||
|
||||
async getFrontendActionRegistry() {
|
||||
return requestJsonWithFallback<unknown>(candidates, activeBaseUrl, (nextBaseUrl) => { activeBaseUrl = nextBaseUrl; }, "/frontend-action-registry");
|
||||
},
|
||||
|
||||
async submitFrontendActionResult(sessionId, actionId, result) {
|
||||
await requestJsonWithFallback<unknown>(candidates, activeBaseUrl, (nextBaseUrl) => { activeBaseUrl = nextBaseUrl; }, `/frontend-actions/${encodeURIComponent(actionId)}/result`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "x-agent-session-id": sessionId },
|
||||
body: JSON.stringify(result)
|
||||
});
|
||||
},
|
||||
|
||||
async loadSession(sessionId) {
|
||||
const response = await fetchWithFallback(candidates, activeBaseUrl, (nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
}, `/session/${encodeURIComponent(sessionId)}`);
|
||||
const text = await response.text();
|
||||
const data = text ? JSON.parse(text) : null;
|
||||
|
||||
if (response.status === 404) {
|
||||
return null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(getResponseErrorMessage(data, response.status));
|
||||
}
|
||||
|
||||
return toLoadedSession(data);
|
||||
},
|
||||
|
||||
async streamSession(sessionId, options) {
|
||||
const response = await fetchWithFallback(
|
||||
candidates,
|
||||
activeBaseUrl,
|
||||
(nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
},
|
||||
`/session/${encodeURIComponent(sessionId)}/stream`,
|
||||
{ signal: options.signal }
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
const data = text ? JSON.parse(text) : null;
|
||||
throw new Error(getResponseErrorMessage(data, response.status));
|
||||
}
|
||||
|
||||
await readSessionSseStream(response, options.onEvent);
|
||||
},
|
||||
|
||||
async updateSessionTitle(sessionId, title, options) {
|
||||
const normalizedTitle = title.trim();
|
||||
if (!normalizedTitle) {
|
||||
return;
|
||||
}
|
||||
|
||||
await requestJsonWithFallback<unknown>(
|
||||
candidates,
|
||||
activeBaseUrl,
|
||||
(nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
},
|
||||
`/session/${encodeURIComponent(sessionId)}/title`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title: normalizedTitle,
|
||||
is_title_manually_edited: options?.isTitleManuallyEdited
|
||||
})
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
async deleteSession(sessionId) {
|
||||
await requestJsonWithFallback<unknown>(
|
||||
candidates,
|
||||
activeBaseUrl,
|
||||
(nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
},
|
||||
`/session/${encodeURIComponent(sessionId)}`,
|
||||
{ method: "DELETE" }
|
||||
);
|
||||
},
|
||||
|
||||
async getModels() {
|
||||
const payload = await requestJsonWithFallback<unknown>(candidates, activeBaseUrl, (nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
}, "/models");
|
||||
return toModelsResponse(payload);
|
||||
},
|
||||
|
||||
async getUiRegistry() {
|
||||
return requestJsonWithFallback<unknown>(candidates, activeBaseUrl, (nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
}, "/ui-registry");
|
||||
},
|
||||
|
||||
async resolveRenderRef(renderRef, sessionId) {
|
||||
const params = new URLSearchParams({ session_id: sessionId });
|
||||
return requestJsonWithFallback<unknown>(
|
||||
candidates,
|
||||
activeBaseUrl,
|
||||
(nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
},
|
||||
`/render-ref/${encodeURIComponent(renderRef)}?${params.toString()}`
|
||||
);
|
||||
},
|
||||
|
||||
async replyPermission(requestId, options) {
|
||||
await requestJsonWithFallback<unknown>(candidates, activeBaseUrl, (nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
}, `/permission/${encodeURIComponent(requestId)}/reply`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
session_id: options.sessionId,
|
||||
reply: options.reply,
|
||||
message: options.message
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
async replyQuestion(requestId, options) {
|
||||
await requestJsonWithFallback<unknown>(candidates, activeBaseUrl, (nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
}, `/question/${encodeURIComponent(requestId)}/reply`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
session_id: options.sessionId,
|
||||
answers: options.answers
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
async rejectQuestion(requestId, options) {
|
||||
await requestJsonWithFallback<unknown>(candidates, activeBaseUrl, (nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
}, `/question/${encodeURIComponent(requestId)}/reject`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
session_id: options.sessionId
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
async abort(sessionId) {
|
||||
await requestJsonWithFallback<unknown>(candidates, activeBaseUrl, (nextBaseUrl) => {
|
||||
activeBaseUrl = nextBaseUrl;
|
||||
}, "/abort", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ session_id: sessionId })
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function requestJsonWithFallback<T>(
|
||||
baseUrls: string[],
|
||||
activeBaseUrl: string,
|
||||
setActiveBaseUrl: (baseUrl: string) => void,
|
||||
path: string,
|
||||
init?: RequestInit
|
||||
) {
|
||||
const response = await fetchWithFallback(baseUrls, activeBaseUrl, setActiveBaseUrl, path, init);
|
||||
const text = await response.text();
|
||||
const data = text ? JSON.parse(text) : null;
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(getResponseErrorMessage(data, response.status));
|
||||
}
|
||||
|
||||
return data as T;
|
||||
}
|
||||
|
||||
async function fetchWithFallback(
|
||||
baseUrls: string[],
|
||||
activeBaseUrl: string,
|
||||
setActiveBaseUrl: (baseUrl: string) => void,
|
||||
path: string,
|
||||
init?: RequestInit
|
||||
) {
|
||||
const orderedBaseUrls = [activeBaseUrl, ...baseUrls.filter((item) => item !== activeBaseUrl)];
|
||||
let lastError: unknown;
|
||||
let lastResponse: Response | null = null;
|
||||
|
||||
for (const baseUrl of orderedBaseUrls) {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}${CHAT_PATH}${path}`, init);
|
||||
if (response.ok) {
|
||||
setActiveBaseUrl(baseUrl);
|
||||
return response;
|
||||
}
|
||||
|
||||
lastResponse = response;
|
||||
if (shouldFallbackOnHttpStatus(response.status) && baseUrl !== orderedBaseUrls[orderedBaseUrls.length - 1]) {
|
||||
await response.body?.cancel();
|
||||
continue;
|
||||
}
|
||||
return response;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
if (lastResponse) {
|
||||
return lastResponse;
|
||||
}
|
||||
|
||||
throw lastError instanceof Error ? lastError : new Error("Agent API unavailable");
|
||||
}
|
||||
|
||||
function shouldFallbackOnHttpStatus(status: number) {
|
||||
return status === 404 || status === 405 || status === 502 || status === 503 || status === 504;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function isPresent<T>(value: T | null | undefined): value is T {
|
||||
return value !== null && value !== undefined;
|
||||
}
|
||||
|
||||
function toModelsResponse(value: unknown): AgentModelsResponse {
|
||||
if (!isRecord(value)) {
|
||||
return { defaultModel: "", models: [] };
|
||||
}
|
||||
|
||||
const models = Array.isArray(value.models) ? value.models.map(toModelOption).filter(isPresent) : [];
|
||||
const defaultModel = typeof value.default_model === "string" ? value.default_model : models[0]?.id ?? "";
|
||||
return {
|
||||
defaultModel,
|
||||
models
|
||||
};
|
||||
}
|
||||
|
||||
function toModelOption(value: unknown): AgentModelOption | null {
|
||||
if (!isRecord(value) || typeof value.id !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const label = typeof value.label === "string" && value.label.trim() ? value.label : value.id;
|
||||
const description =
|
||||
typeof value.description === "string" && value.description.trim() ? value.description : label;
|
||||
const icon = value.icon === "bolt" || value.icon === "sparkle" ? value.icon : "sparkle";
|
||||
|
||||
return {
|
||||
id: value.id,
|
||||
label,
|
||||
description,
|
||||
icon
|
||||
};
|
||||
}
|
||||
|
||||
function getResponseErrorMessage(data: unknown, status: number) {
|
||||
return isRecord(data) && typeof data.message === "string"
|
||||
? data.message
|
||||
: `Agent API failed with HTTP ${status}`;
|
||||
}
|
||||
|
||||
function toMillis(value: unknown) {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = new Date(value).getTime();
|
||||
return Number.isFinite(parsed) ? parsed : Date.now();
|
||||
}
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
function normalizeTitle(value: unknown) {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : "新对话";
|
||||
}
|
||||
|
||||
function readRunStatus(value: unknown): AgentRunStatus | undefined {
|
||||
return value === "running" || value === "completed" || value === "error" || value === "aborted"
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function toSessionSummary(value: unknown): AgentChatSessionSummary | null {
|
||||
if (!isRecord(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const id = typeof value.id === "string" ? value.id : typeof value.session_id === "string" ? value.session_id : "";
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
title: normalizeTitle(value.title),
|
||||
createdAt: toMillis(value.created_at),
|
||||
updatedAt: toMillis(value.updated_at),
|
||||
status: typeof value.status === "string" ? value.status : undefined,
|
||||
parentSessionId: typeof value.parent_session_id === "string" ? value.parent_session_id : undefined,
|
||||
isStreaming: typeof value.is_streaming === "boolean" ? value.is_streaming : undefined,
|
||||
runStatus: readRunStatus(value.run_status)
|
||||
};
|
||||
}
|
||||
|
||||
function toLoadedSession(value: unknown): AgentLoadedChatSession {
|
||||
const summary = toSessionSummary(value);
|
||||
if (!summary || !isRecord(value)) {
|
||||
throw new Error("Invalid agent session payload");
|
||||
}
|
||||
|
||||
return {
|
||||
...summary,
|
||||
sessionId: typeof value.session_id === "string" ? value.session_id : summary.id,
|
||||
isTitleManuallyEdited:
|
||||
typeof value.is_title_manually_edited === "boolean" ? value.is_title_manually_edited : false,
|
||||
messages: Array.isArray(value.messages) ? value.messages : []
|
||||
};
|
||||
}
|
||||
|
||||
async function readSessionSseStream(
|
||||
response: Response,
|
||||
onEvent: (event: AgentSessionStreamEvent) => void
|
||||
) {
|
||||
if (!response.body) {
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
buffer += decoder.decode(value, { stream: !done });
|
||||
|
||||
let delimiterIndex = buffer.indexOf("\n\n");
|
||||
while (delimiterIndex !== -1) {
|
||||
const rawEvent = buffer.slice(0, delimiterIndex);
|
||||
buffer = buffer.slice(delimiterIndex + 2);
|
||||
emitSessionSseEvent(rawEvent, onEvent);
|
||||
delimiterIndex = buffer.indexOf("\n\n");
|
||||
}
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (buffer.trim()) {
|
||||
emitSessionSseEvent(buffer, onEvent);
|
||||
}
|
||||
}
|
||||
|
||||
function emitSessionSseEvent(
|
||||
rawEvent: string,
|
||||
onEvent: (event: AgentSessionStreamEvent) => void
|
||||
) {
|
||||
const lines = rawEvent.split(/\r?\n/);
|
||||
const eventType = lines
|
||||
.find((line) => line.startsWith("event:"))
|
||||
?.slice("event:".length)
|
||||
.trim();
|
||||
const dataText = lines
|
||||
.filter((line) => line.startsWith("data:"))
|
||||
.map((line) => line.slice("data:".length).trimStart())
|
||||
.join("\n");
|
||||
|
||||
if (!eventType || !dataText) {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = JSON.parse(dataText) as unknown;
|
||||
if (!isRecord(data)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventType === "state") {
|
||||
const sessionId = typeof data.session_id === "string" ? data.session_id : "";
|
||||
onEvent({
|
||||
type: "state",
|
||||
sessionId,
|
||||
messages: Array.isArray(data.messages) ? data.messages : [],
|
||||
isStreaming: data.is_streaming === true,
|
||||
runStatus: readRunStatus(data.run_status)
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isSessionStreamDataEventType(eventType)) {
|
||||
return;
|
||||
}
|
||||
|
||||
onEvent({
|
||||
type: eventType,
|
||||
sessionId: typeof data.session_id === "string" ? data.session_id : undefined,
|
||||
data
|
||||
});
|
||||
}
|
||||
|
||||
function isSessionStreamDataEventType(value: string): value is AgentSessionStreamDataEventType {
|
||||
return (
|
||||
value === "token" ||
|
||||
value === "progress" ||
|
||||
value === "todo_update" ||
|
||||
value === "permission_request" ||
|
||||
value === "permission_response" ||
|
||||
value === "question_request" ||
|
||||
value === "question_response" ||
|
||||
value === "tool_call" ||
|
||||
value === "frontend_action" ||
|
||||
value === "frontend_action_result" ||
|
||||
value === "ui_envelope" ||
|
||||
value === "session_title" ||
|
||||
value === "done" ||
|
||||
value === "error" ||
|
||||
value === "auth_required"
|
||||
);
|
||||
}
|
||||
|
||||
function compareSessionSummaries(left: AgentChatSessionSummary, right: AgentChatSessionSummary) {
|
||||
const createdAtDiff = right.createdAt - left.createdAt;
|
||||
if (createdAtDiff !== 0) {
|
||||
return createdAtDiff;
|
||||
}
|
||||
|
||||
const updatedAtDiff = right.updatedAt - left.updatedAt;
|
||||
if (updatedAtDiff !== 0) {
|
||||
return updatedAtDiff;
|
||||
}
|
||||
|
||||
return right.id.localeCompare(left.id);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { AgentApiClient } from "./client";
|
||||
import { fetchAgentBootstrap, fetchAgentSessions } from "./swr";
|
||||
|
||||
describe("Agent API SWR helpers", () => {
|
||||
it("loads bootstrap data with a normalized UI registry", async () => {
|
||||
const client = {
|
||||
getUiRegistry: vi.fn(async () => ({
|
||||
schema_version: "agent-ui-registry@1",
|
||||
chart_grammars: ["echarts-safe-subset"],
|
||||
components: [{ id: "HistoryPanel", supportedSurfaces: ["side_panel", "unknown"] }],
|
||||
actions: [{ id: "zoom_to_map", supportedSurfaces: ["map_overlay"] }]
|
||||
})),
|
||||
getModels: vi.fn(async () => ({
|
||||
defaultModel: "model-a",
|
||||
models: [{ id: "model-a", label: "Model A", description: "Default model", icon: "sparkle" }]
|
||||
}))
|
||||
} as Pick<AgentApiClient, "getUiRegistry" | "getModels"> as AgentApiClient;
|
||||
|
||||
await expect(fetchAgentBootstrap(client)).resolves.toEqual({
|
||||
defaultModel: "model-a",
|
||||
models: [{ id: "model-a", label: "Model A", description: "Default model", icon: "sparkle" }],
|
||||
registry: {
|
||||
schema_version: "agent-ui-registry@1",
|
||||
chart_grammars: ["echarts-safe-subset"],
|
||||
components: [{ id: "HistoryPanel", supportedSurfaces: ["side_panel"] }],
|
||||
actions: [{ id: "zoom_to_map", supportedSurfaces: ["map_overlay"] }]
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("loads session summaries through the shared client", async () => {
|
||||
const sessions = [
|
||||
{
|
||||
id: "session-1",
|
||||
title: "会话",
|
||||
createdAt: 1,
|
||||
updatedAt: 2
|
||||
}
|
||||
];
|
||||
const client = {
|
||||
listSessions: vi.fn(async () => sessions)
|
||||
} as Pick<AgentApiClient, "listSessions"> as AgentApiClient;
|
||||
|
||||
await expect(fetchAgentSessions(client)).resolves.toBe(sessions);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import type {
|
||||
AgentApiClient,
|
||||
AgentChatSessionSummary,
|
||||
AgentModelOption
|
||||
} from "./client";
|
||||
import { parseUiRegistry, type UIRegistry } from "../ui-envelope";
|
||||
import { parseFrontendActionRegistry, type FrontendActionRegistry } from "../frontend-action";
|
||||
|
||||
export const agentBootstrapKey = ["agent", "bootstrap"] as const;
|
||||
export const agentSessionsKey = ["agent", "sessions"] as const;
|
||||
|
||||
export type AgentBootstrapData = {
|
||||
registry: UIRegistry | null;
|
||||
frontendActionRegistry?: FrontendActionRegistry | null;
|
||||
models: AgentModelOption[];
|
||||
defaultModel: string;
|
||||
};
|
||||
|
||||
export async function fetchAgentBootstrap(client: AgentApiClient): Promise<AgentBootstrapData> {
|
||||
const [rawRegistry, rawFrontendActionRegistry, modelsResponse] = await Promise.all([
|
||||
client.getUiRegistry(),
|
||||
typeof client.getFrontendActionRegistry === "function" ? client.getFrontendActionRegistry() : Promise.resolve(undefined),
|
||||
client.getModels()
|
||||
]);
|
||||
|
||||
return {
|
||||
registry: parseUiRegistry(rawRegistry),
|
||||
...(rawFrontendActionRegistry === undefined ? {} : { frontendActionRegistry: parseFrontendActionRegistry(rawFrontendActionRegistry) }),
|
||||
models: modelsResponse.models,
|
||||
defaultModel: modelsResponse.defaultModel
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchAgentSessions(client: AgentApiClient): Promise<AgentChatSessionSummary[]> {
|
||||
return client.listSessions();
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { normalizeSafeChartData, parseChartSpec, pointToLabelValue } from "./chart-data";
|
||||
|
||||
describe("chart data normalization", () => {
|
||||
it("parses chart spec aliases", () => {
|
||||
expect(parseChartSpec({ title: "压力", chart_type: "bar", x_axis_name: "时间" })).toEqual({
|
||||
title: "压力",
|
||||
chartType: "bar",
|
||||
xAxisName: "时间",
|
||||
yAxisName: undefined
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes series with x_data and numeric strings", () => {
|
||||
expect(
|
||||
normalizeSafeChartData({
|
||||
x_data: ["00:00", "01:00"],
|
||||
series: [{ name: "压力", data: ["1.2", 1.4] }]
|
||||
})
|
||||
).toEqual({
|
||||
xData: ["00:00", "01:00"],
|
||||
series: [{ name: "压力", data: [1.2, 1.4], type: undefined }]
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes raw point arrays into a default series", () => {
|
||||
expect(
|
||||
normalizeSafeChartData({
|
||||
series: [
|
||||
["A", 12],
|
||||
["B", "13"]
|
||||
]
|
||||
})
|
||||
).toEqual({
|
||||
xData: ["A", "B"],
|
||||
series: [{ name: "数据", data: [12, 13], type: undefined }]
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes object points", () => {
|
||||
expect(pointToLabelValue({ time: "10:00", value: "2.4" }, "fallback")).toEqual({
|
||||
label: "10:00",
|
||||
value: 2.4
|
||||
});
|
||||
});
|
||||
|
||||
it("clips chart points to the safe limit", () => {
|
||||
const data = normalizeSafeChartData(
|
||||
{
|
||||
x_data: Array.from({ length: 30 }, (_, index) => String(index)),
|
||||
series: [{ name: "流量", data: Array.from({ length: 30 }, (_, index) => index) }]
|
||||
},
|
||||
5
|
||||
);
|
||||
|
||||
expect(data?.xData).toHaveLength(5);
|
||||
expect(data?.series[0].data).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
export type SafeChartSpec = {
|
||||
title?: string;
|
||||
chartType: "line" | "bar";
|
||||
xAxisName?: string;
|
||||
yAxisName?: string;
|
||||
};
|
||||
|
||||
export type SafeChartSeries = {
|
||||
name: string;
|
||||
data: number[];
|
||||
type?: "line" | "bar";
|
||||
};
|
||||
|
||||
export type SafeChartData = {
|
||||
xData: string[];
|
||||
series: SafeChartSeries[];
|
||||
};
|
||||
|
||||
type RawChartPoint = number | string | [unknown, unknown] | RawChartPointObject;
|
||||
|
||||
type RawChartPointObject = {
|
||||
x?: unknown;
|
||||
y?: unknown;
|
||||
time?: unknown;
|
||||
timestamp?: unknown;
|
||||
label?: unknown;
|
||||
name?: unknown;
|
||||
value?: unknown;
|
||||
};
|
||||
|
||||
type RawChartSeries = {
|
||||
name?: unknown;
|
||||
data?: unknown;
|
||||
points?: unknown;
|
||||
values?: unknown;
|
||||
type?: unknown;
|
||||
};
|
||||
|
||||
export function parseChartSpec(value: unknown): SafeChartSpec {
|
||||
if (!isRecord(value)) {
|
||||
return { chartType: "line" };
|
||||
}
|
||||
|
||||
return {
|
||||
title: stringValue(value.title),
|
||||
chartType: value.chart_type === "bar" || value.chartType === "bar" ? "bar" : "line",
|
||||
xAxisName: stringValue(value.x_axis_name ?? value.xAxisName),
|
||||
yAxisName: stringValue(value.y_axis_name ?? value.yAxisName)
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeSafeChartData(value: unknown, maxPoints = 24): SafeChartData | null {
|
||||
if (!isRecord(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const xData = normalizeXData(value.x_data ?? value.xData);
|
||||
const rawSeriesItems = normalizeRawSeriesItems(value.series);
|
||||
if (!rawSeriesItems.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedSeries = rawSeriesItems
|
||||
.map((rawItem, seriesIndex): SafeChartSeries | null => {
|
||||
const item =
|
||||
isRecord(rawItem) && !isRawChartPoint(rawItem) ? rawItem : ({ data: rawItem } satisfies RawChartSeries);
|
||||
const rawData = item.data ?? item.points ?? item.values;
|
||||
if (!Array.isArray(rawData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const labelsFromPoints: string[] = [];
|
||||
const data = rawData
|
||||
.slice(0, maxPoints)
|
||||
.map((point, index) => {
|
||||
const parsed = pointToLabelValue(point as RawChartPoint, xData[index] ?? `${index + 1}`);
|
||||
if (!parsed) {
|
||||
return null;
|
||||
}
|
||||
labelsFromPoints[index] = parsed.label;
|
||||
return parsed.value;
|
||||
})
|
||||
.filter((item): item is number => item !== null);
|
||||
|
||||
if (!data.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!xData.length && labelsFromPoints.length) {
|
||||
xData.push(...labelsFromPoints);
|
||||
}
|
||||
|
||||
return {
|
||||
name: stringValue(item.name) ?? `系列 ${seriesIndex + 1}`,
|
||||
data,
|
||||
type: item.type === "line" || item.type === "bar" ? item.type : undefined
|
||||
};
|
||||
})
|
||||
.filter((item): item is SafeChartSeries => Boolean(item));
|
||||
|
||||
const clippedXData = xData.slice(0, maxPoints);
|
||||
const clippedSeries = normalizedSeries.map((series) => ({
|
||||
...series,
|
||||
data: series.data.slice(0, clippedXData.length)
|
||||
}));
|
||||
|
||||
return clippedXData.length > 0 && clippedSeries.length > 0
|
||||
? {
|
||||
xData: clippedXData,
|
||||
series: clippedSeries
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
export function pointToLabelValue(point: RawChartPoint, fallbackLabel: string): { label: string; value: number } | null {
|
||||
const directValue = toFiniteNumber(point);
|
||||
if (directValue !== null) {
|
||||
return { label: fallbackLabel, value: directValue };
|
||||
}
|
||||
|
||||
if (Array.isArray(point)) {
|
||||
const value = toFiniteNumber(point[1]);
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
return { label: String(point[0] ?? fallbackLabel), value };
|
||||
}
|
||||
|
||||
if (isRecord(point)) {
|
||||
const value = toFiniteNumber(point.value ?? point.y);
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
const label = point.x ?? point.time ?? point.timestamp ?? point.label ?? point.name ?? fallbackLabel;
|
||||
return { label: String(label), value };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeXData(rawXData: unknown): string[] {
|
||||
return Array.isArray(rawXData) ? rawXData.map((item) => String(item ?? "")).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
function normalizeRawSeriesItems(rawSeries: unknown): unknown[] {
|
||||
if (!Array.isArray(rawSeries)) {
|
||||
return isRecord(rawSeries) ? [rawSeries] : [];
|
||||
}
|
||||
|
||||
return rawSeries.length > 0 && rawSeries.every(isRawChartPoint) ? [{ name: "数据", data: rawSeries }] : rawSeries;
|
||||
}
|
||||
|
||||
function isRawChartPoint(item: unknown): boolean {
|
||||
if (toFiniteNumber(item) !== null) {
|
||||
return true;
|
||||
}
|
||||
if (Array.isArray(item)) {
|
||||
return item.length >= 2 && toFiniteNumber(item[1]) !== null;
|
||||
}
|
||||
if (isRecord(item)) {
|
||||
return item.data === undefined && item.points === undefined && item.values === undefined && toFiniteNumber(item.value ?? item.y) !== null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function toFiniteNumber(value: unknown): number | null {
|
||||
if (typeof value === "number") {
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function stringValue(value: unknown) {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import type { PersonaState } from "@/shared/ai-elements/persona";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { MAP_MAJOR_PANEL_RADIUS_CLASS_NAME } from "@/features/map/core/components/map-control-styles";
|
||||
import { AgentPersona } from "./agent-persona";
|
||||
|
||||
type AgentCollapsedRailProps = {
|
||||
personaState?: PersonaState;
|
||||
onExpand: () => void;
|
||||
};
|
||||
|
||||
export function AgentCollapsedRail({ personaState, onExpand }: AgentCollapsedRailProps) {
|
||||
return (
|
||||
<aside
|
||||
aria-label="Agent 折叠栏"
|
||||
className={cn(
|
||||
"agent-rail-enter acrylic-panel pointer-events-auto w-[136px] border p-1.5",
|
||||
MAP_MAJOR_PANEL_RADIUS_CLASS_NAME
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="展开排水助手面板"
|
||||
title="展开排水助手面板"
|
||||
onClick={onExpand}
|
||||
className="agent-rail-item surface-control group flex h-14 w-full items-center justify-center gap-4 rounded-xl border px-3 transition-[background-color,transform] hover:bg-white active:scale-95"
|
||||
>
|
||||
<AgentPersona className="h-12 w-12" state={personaState} />
|
||||
<span className="agent-panel-primary-icon grid h-8 w-8 shrink-0 place-items-center rounded-lg !border-0 transition-transform group-hover:translate-x-0.5">
|
||||
<ChevronRight size={17} strokeWidth={2.25} aria-hidden="true" />
|
||||
</span>
|
||||
</button>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,296 @@
|
||||
"use client";
|
||||
|
||||
import { Check, Loader2, Pencil, RefreshCw, Trash2, X } from "lucide-react";
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
import { useState } from "react";
|
||||
import { Input } from "@/shared/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { AgentChatSessionSummary } from "../api/client";
|
||||
import {
|
||||
agentLayoutTransition,
|
||||
agentPanelItemVariants,
|
||||
agentPanelListVariants
|
||||
} from "./agent-motion";
|
||||
|
||||
type AgentHistoryPanelProps = {
|
||||
activeSessionId?: string | null;
|
||||
loading: boolean;
|
||||
loadingSessionId: string | null;
|
||||
sessions: AgentChatSessionSummary[];
|
||||
onRefresh?: () => Promise<void> | void;
|
||||
onSelectSession: (sessionId: string) => void;
|
||||
onRenameSession?: (sessionId: string, title: string) => Promise<void> | void;
|
||||
onDeleteSession?: (sessionId: string) => Promise<void> | void;
|
||||
};
|
||||
|
||||
export function AgentHistoryPanel({
|
||||
activeSessionId,
|
||||
loading,
|
||||
loadingSessionId,
|
||||
sessions,
|
||||
onRefresh,
|
||||
onSelectSession,
|
||||
onRenameSession,
|
||||
onDeleteSession
|
||||
}: AgentHistoryPanelProps) {
|
||||
const [editingSessionId, setEditingSessionId] = useState<string | null>(null);
|
||||
const [draftTitle, setDraftTitle] = useState("");
|
||||
const [savingSessionId, setSavingSessionId] = useState<string | null>(null);
|
||||
const [deletingSessionId, setDeletingSessionId] = useState<string | null>(null);
|
||||
const [confirmingDeleteSessionId, setConfirmingDeleteSessionId] = useState<string | null>(null);
|
||||
|
||||
const beginRename = (session: AgentChatSessionSummary) => {
|
||||
setEditingSessionId(session.id);
|
||||
setDraftTitle(session.title);
|
||||
};
|
||||
|
||||
const cancelRename = () => {
|
||||
setEditingSessionId(null);
|
||||
setDraftTitle("");
|
||||
};
|
||||
|
||||
const saveRename = (session: AgentChatSessionSummary) => {
|
||||
const normalizedTitle = draftTitle.trim();
|
||||
if (!normalizedTitle || normalizedTitle === session.title) {
|
||||
cancelRename();
|
||||
return;
|
||||
}
|
||||
|
||||
setSavingSessionId(session.id);
|
||||
void Promise.resolve(onRenameSession?.(session.id, normalizedTitle))
|
||||
.then(cancelRename)
|
||||
.finally(() => setSavingSessionId(null));
|
||||
};
|
||||
|
||||
const confirmDelete = (sessionId: string) => {
|
||||
setDeletingSessionId(sessionId);
|
||||
void Promise.resolve(onDeleteSession?.(sessionId))
|
||||
.then(() => setConfirmingDeleteSessionId(null))
|
||||
.finally(() => setDeletingSessionId(null));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="px-3 pb-3">
|
||||
<div className="agent-panel-control rounded-2xl p-2.5 shadow-sm">
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold text-slate-950">历史记录</p>
|
||||
<p className="mt-0.5 text-xs text-slate-500">{sessions.length ? `${sessions.length} 个会话` : "暂无历史会话"}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="刷新 Agent 历史记录"
|
||||
title="刷新 Agent 历史记录"
|
||||
className="grid h-8 w-8 shrink-0 place-items-center rounded-lg text-slate-500 transition hover:bg-white hover:text-slate-950 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={loading}
|
||||
onClick={() => void Promise.resolve(onRefresh?.())}
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<RefreshCw size={15} aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<motion.div className="max-h-56 space-y-1 overflow-y-auto pr-1" variants={agentPanelListVariants} animate="animate">
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{loading && sessions.length === 0 ? (
|
||||
<motion.div
|
||||
key="history-loading"
|
||||
className="flex items-center gap-2 rounded-xl bg-slate-50 px-3 py-3 text-xs font-semibold text-slate-500"
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelItemVariants}
|
||||
>
|
||||
<Loader2 size={14} className="animate-spin" aria-hidden="true" />
|
||||
正在加载
|
||||
</motion.div>
|
||||
) : sessions.length > 0 ? (
|
||||
sessions.map((session) => {
|
||||
const active = session.id === activeSessionId;
|
||||
const itemLoading = loadingSessionId === session.id;
|
||||
const editing = editingSessionId === session.id;
|
||||
const saving = savingSessionId === session.id;
|
||||
const deleting = deletingSessionId === session.id;
|
||||
const confirmingDelete = confirmingDeleteSessionId === session.id;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={session.id}
|
||||
layout
|
||||
className={cn(
|
||||
"grid w-full grid-cols-[1fr_auto] gap-2 rounded-xl px-3 py-2 text-left transition hover:bg-white",
|
||||
active ? "border border-blue-200 bg-blue-50/80" : "border border-transparent bg-slate-50/80"
|
||||
)}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelItemVariants}
|
||||
transition={agentLayoutTransition}
|
||||
>
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{confirmingDelete ? (
|
||||
<motion.div key="confirm-delete" className="min-w-0" initial="initial" animate="animate" exit="exit" variants={agentPanelItemVariants}>
|
||||
<span className="block truncate text-xs font-semibold text-red-700" title={session.title}>
|
||||
删除“{session.title}”?
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-xs text-slate-500">
|
||||
删除后无法从历史记录中恢复
|
||||
</span>
|
||||
</motion.div>
|
||||
) : editing ? (
|
||||
<motion.form
|
||||
key="rename"
|
||||
className="min-w-0"
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelItemVariants}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
saveRename(session);
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
autoFocus
|
||||
className="h-8 rounded-lg bg-white text-xs"
|
||||
value={draftTitle}
|
||||
disabled={saving}
|
||||
onChange={(event) => setDraftTitle(event.currentTarget.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") {
|
||||
cancelRename();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</motion.form>
|
||||
) : (
|
||||
<motion.button
|
||||
key="session-summary"
|
||||
type="button"
|
||||
className="min-w-0 text-left"
|
||||
disabled={itemLoading || deleting}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelItemVariants}
|
||||
onClick={() => onSelectSession(session.id)}
|
||||
>
|
||||
<span className="block truncate text-xs font-semibold text-slate-900" title={session.title}>
|
||||
{session.title}
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-xs text-slate-500">
|
||||
{formatSessionUpdatedAt(session.updatedAt)}
|
||||
</span>
|
||||
</motion.button>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<span className="flex items-center gap-1">
|
||||
{session.runStatus === "running" || session.isStreaming ? (
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-blue-500" />
|
||||
) : null}
|
||||
{itemLoading || saving || deleting ? (
|
||||
<Loader2 size={13} className="animate-spin text-blue-600" aria-hidden="true" />
|
||||
) : null}
|
||||
{active && !editing && !confirmingDelete ? (
|
||||
<span className="rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-700">
|
||||
当前
|
||||
</span>
|
||||
) : null}
|
||||
{confirmingDelete ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="h-7 rounded-lg bg-red-600 px-2 text-xs font-semibold text-white transition hover:bg-red-700 disabled:opacity-50"
|
||||
disabled={deleting}
|
||||
onClick={() => confirmDelete(session.id)}
|
||||
>
|
||||
确认
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="取消删除"
|
||||
title="取消删除"
|
||||
className="grid h-7 w-7 place-items-center rounded-lg text-slate-500 transition hover:bg-white disabled:opacity-50"
|
||||
disabled={deleting}
|
||||
onClick={() => setConfirmingDeleteSessionId(null)}
|
||||
>
|
||||
<X size={14} aria-hidden="true" />
|
||||
</button>
|
||||
</>
|
||||
) : editing ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="保存对话主题"
|
||||
title="保存对话主题"
|
||||
className="grid h-7 w-7 place-items-center rounded-lg text-blue-600 transition hover:bg-white disabled:opacity-50"
|
||||
disabled={saving}
|
||||
onClick={() => saveRename(session)}
|
||||
>
|
||||
<Check size={14} aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="取消重命名"
|
||||
title="取消重命名"
|
||||
className="grid h-7 w-7 place-items-center rounded-lg text-slate-500 transition hover:bg-white disabled:opacity-50"
|
||||
disabled={saving}
|
||||
onClick={cancelRename}
|
||||
>
|
||||
<X size={14} aria-hidden="true" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="重命名对话"
|
||||
title="重命名对话"
|
||||
className="grid h-7 w-7 place-items-center rounded-lg text-slate-500 transition hover:bg-white hover:text-slate-950 disabled:opacity-50"
|
||||
disabled={itemLoading || deleting || !onRenameSession}
|
||||
onClick={() => beginRename(session)}
|
||||
>
|
||||
<Pencil size={14} aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="删除对话"
|
||||
title="删除对话"
|
||||
className="grid h-7 w-7 place-items-center rounded-lg text-slate-500 transition hover:bg-red-50 hover:text-red-600 disabled:opacity-50"
|
||||
disabled={itemLoading || deleting || !onDeleteSession}
|
||||
onClick={() => {
|
||||
cancelRename();
|
||||
setConfirmingDeleteSessionId(session.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 size={14} aria-hidden="true" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</motion.div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<motion.div key="history-empty" className="rounded-xl bg-slate-50 px-3 py-3 text-xs text-slate-500" initial="initial" animate="animate" exit="exit" variants={agentPanelItemVariants}>
|
||||
暂无历史记录
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatSessionUpdatedAt(value: number) {
|
||||
return new Intl.DateTimeFormat("zh-CN", {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit"
|
||||
}).format(value);
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
HelpCircle,
|
||||
ListChecks,
|
||||
ListTree,
|
||||
LockKeyhole,
|
||||
ShieldCheck,
|
||||
XCircle,
|
||||
type LucideIcon
|
||||
} from "lucide-react";
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/shared/ui/button";
|
||||
import {
|
||||
agentEase,
|
||||
agentLayoutTransition,
|
||||
agentPanelItemVariants,
|
||||
agentPanelListVariants,
|
||||
agentPanelSectionVariants
|
||||
} from "./agent-motion";
|
||||
import type {
|
||||
AgentChatMessage,
|
||||
AgentChatProgress,
|
||||
AgentPermissionReply,
|
||||
AgentPermissionRequest,
|
||||
AgentQuestionInfo,
|
||||
AgentQuestionRequest,
|
||||
AgentTodoUpdate
|
||||
} from "../types";
|
||||
|
||||
type ProgressStatus = AgentChatProgress["status"];
|
||||
type TodoStatus = AgentTodoUpdate["todos"][number]["status"];
|
||||
type PermissionStatus = AgentPermissionRequest["status"];
|
||||
type QuestionStatus = AgentQuestionRequest["status"];
|
||||
|
||||
const STREAMING_PROGRESS_LIMIT = 3;
|
||||
|
||||
const progressStatusMeta: Record<ProgressStatus, { label: string; className: string; dotClassName: string }> = {
|
||||
running: {
|
||||
label: "进行中",
|
||||
className: "bg-blue-100 text-blue-700",
|
||||
dotClassName: "border-blue-500 bg-blue-100"
|
||||
},
|
||||
completed: {
|
||||
label: "完成",
|
||||
className: "bg-emerald-100 text-emerald-700",
|
||||
dotClassName: "border-emerald-500 bg-emerald-100"
|
||||
},
|
||||
error: {
|
||||
label: "失败",
|
||||
className: "bg-red-100 text-red-700",
|
||||
dotClassName: "border-red-500 bg-red-100"
|
||||
}
|
||||
};
|
||||
|
||||
const todoStatusMeta: Record<TodoStatus, { label: string; className: string; dotClassName: string }> = {
|
||||
completed: {
|
||||
label: "完成",
|
||||
className: "bg-emerald-100 text-emerald-700",
|
||||
dotClassName: "border-emerald-500 bg-emerald-500"
|
||||
},
|
||||
in_progress: {
|
||||
label: "进行中",
|
||||
className: "bg-blue-100 text-blue-700",
|
||||
dotClassName: "border-blue-500 bg-blue-100"
|
||||
},
|
||||
pending: {
|
||||
label: "待办",
|
||||
className: "bg-slate-100 text-slate-600",
|
||||
dotClassName: "border-slate-300 bg-white"
|
||||
},
|
||||
cancelled: {
|
||||
label: "取消",
|
||||
className: "bg-slate-200 text-slate-500",
|
||||
dotClassName: "border-slate-300 bg-slate-200"
|
||||
}
|
||||
};
|
||||
|
||||
const permissionStatusMeta: Record<PermissionStatus, { label: string; className: string }> = {
|
||||
approved_always: { label: "已始终允许", className: "bg-emerald-100 text-emerald-700" },
|
||||
approved_once: { label: "已允许一次", className: "bg-emerald-100 text-emerald-700" },
|
||||
rejected: { label: "已拒绝", className: "bg-red-100 text-red-700" },
|
||||
aborted: { label: "已中止", className: "bg-slate-200 text-slate-500" },
|
||||
error: { label: "失败", className: "bg-red-100 text-red-700" },
|
||||
submitting: { label: "提交中", className: "bg-blue-100 text-blue-700" },
|
||||
pending: { label: "待确认", className: "bg-orange-100 text-orange-700" }
|
||||
};
|
||||
|
||||
const questionStatusMeta: Record<QuestionStatus, { label: string; className: string }> = {
|
||||
answered: { label: "已回答", className: "bg-emerald-100 text-emerald-700" },
|
||||
rejected: { label: "已跳过", className: "bg-slate-200 text-slate-500" },
|
||||
error: { label: "失败", className: "bg-red-100 text-red-700" },
|
||||
submitting: { label: "提交中", className: "bg-blue-100 text-blue-700" },
|
||||
pending: { label: "待回答", className: "bg-blue-100 text-blue-700" }
|
||||
};
|
||||
|
||||
export function AgentMessageDetails({
|
||||
message,
|
||||
onReplyPermission,
|
||||
onReplyQuestion,
|
||||
onRejectQuestion
|
||||
}: {
|
||||
message: AgentChatMessage;
|
||||
onReplyPermission?: (permission: AgentPermissionRequest, reply: AgentPermissionReply) => Promise<void> | void;
|
||||
onReplyQuestion?: (request: AgentQuestionRequest, answers: string[][]) => Promise<void> | void;
|
||||
onRejectQuestion?: (request: AgentQuestionRequest) => Promise<void> | void;
|
||||
}) {
|
||||
const hasDetails = Boolean(
|
||||
message.todos?.todos.length ||
|
||||
message.permissions?.length ||
|
||||
message.questions?.length
|
||||
);
|
||||
|
||||
if (!hasDetails) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div className="space-y-2" variants={agentPanelListVariants} animate="animate">
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{message.todos ? (
|
||||
<motion.div key="todos" initial="initial" animate="animate" exit="exit" variants={agentPanelItemVariants}>
|
||||
<TodoCard todoUpdate={message.todos} />
|
||||
</motion.div>
|
||||
) : null}
|
||||
{message.permissions?.length ? (
|
||||
<motion.div key="permissions" initial="initial" animate="animate" exit="exit" variants={agentPanelItemVariants}>
|
||||
<PermissionList permissions={message.permissions} onReplyPermission={onReplyPermission} />
|
||||
</motion.div>
|
||||
) : null}
|
||||
{message.questions?.length ? (
|
||||
<motion.div key="questions" initial="initial" animate="animate" exit="exit" variants={agentPanelItemVariants}>
|
||||
<QuestionList
|
||||
questions={message.questions}
|
||||
onReplyQuestion={onReplyQuestion}
|
||||
onRejectQuestion={onRejectQuestion}
|
||||
/>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentMessageProgress({
|
||||
progress,
|
||||
running
|
||||
}: {
|
||||
progress?: AgentChatProgress[];
|
||||
running: boolean;
|
||||
}) {
|
||||
if (!progress?.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <ProgressList progress={progress} running={running} />;
|
||||
}
|
||||
|
||||
function AgentNestedBlock({
|
||||
icon: Icon,
|
||||
iconClassName,
|
||||
title,
|
||||
children,
|
||||
floating = false
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
iconClassName: string;
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
floating?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn(floating ? "px-0 py-1" : "agent-panel-nested rounded-xl p-2.5")}>
|
||||
<div className="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-600">
|
||||
<Icon size={14} className={iconClassName} aria-hidden="true" />
|
||||
{title}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AnimatedDetailItem({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<motion.div
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelItemVariants}
|
||||
transition={agentLayoutTransition}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProgressList({ progress, running }: { progress: AgentChatProgress[]; running: boolean }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const compact = running && !expanded;
|
||||
const visibleProgress = expanded
|
||||
? progress
|
||||
: running
|
||||
? progress.slice(-STREAMING_PROGRESS_LIMIT)
|
||||
: [];
|
||||
const listMode = expanded ? "expanded" : running ? "streaming" : "collapsed";
|
||||
|
||||
return (
|
||||
<div className="agent-panel-nested rounded-xl p-2.5">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 text-left text-xs font-semibold text-slate-600"
|
||||
aria-expanded={expanded}
|
||||
onClick={() => setExpanded((current) => !current)}
|
||||
>
|
||||
<ListTree size={16} className="shrink-0 text-blue-700" aria-hidden="true" />
|
||||
<span>执行进度</span>
|
||||
<span className="flex-1" />
|
||||
<span className="shrink-0 font-normal text-slate-400">
|
||||
{expanded
|
||||
? `全部 ${progress.length} 条`
|
||||
: running
|
||||
? `最近 ${Math.min(progress.length, STREAMING_PROGRESS_LIMIT)} 条`
|
||||
: `共 ${progress.length} 条`}
|
||||
</span>
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className={cn("shrink-0 text-slate-400 transition-transform", expanded && "rotate-180")}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
<AnimatePresence initial={false} mode="wait">
|
||||
{visibleProgress.length ? (
|
||||
<motion.ol
|
||||
key={listMode}
|
||||
aria-label={expanded ? "全部执行进度" : "最近执行进度"}
|
||||
className="mt-2 flex flex-col gap-1.5 overflow-hidden"
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: "auto", opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={agentLayoutTransition}
|
||||
>
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{visibleProgress.map((item) => (
|
||||
<motion.li
|
||||
key={item.id}
|
||||
className={cn(
|
||||
"grid grid-cols-[16px_minmax(0,1fr)_auto] items-start gap-2 text-xs",
|
||||
compact && "h-12 overflow-hidden"
|
||||
)}
|
||||
initial={{ opacity: 0, y: 4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -2 }}
|
||||
transition={{ duration: 0.16, ease: agentEase }}
|
||||
>
|
||||
<motion.span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"mt-0.5 h-3.5 w-3.5 rounded-full border transition-colors duration-150",
|
||||
progressStatusMeta[item.status].dotClassName
|
||||
)}
|
||||
animate={
|
||||
item.status === "running"
|
||||
? { opacity: [0.45, 1, 0.45], scale: 1 }
|
||||
: item.status === "error"
|
||||
? { opacity: [0.55, 1, 1], scale: [1, 1.28, 1] }
|
||||
: { opacity: 1, scale: 1 }
|
||||
}
|
||||
transition={
|
||||
item.status === "running"
|
||||
? { duration: 1.2, ease: "easeInOut", repeat: Infinity }
|
||||
: item.status === "error"
|
||||
? { duration: 0.28, ease: agentEase }
|
||||
: { duration: 0.14 }
|
||||
}
|
||||
/>
|
||||
<span className="min-w-0">
|
||||
<span
|
||||
className={cn(
|
||||
"block font-semibold text-slate-800",
|
||||
compact ? "truncate" : "break-words"
|
||||
)}
|
||||
title={item.title}
|
||||
>
|
||||
{item.title}
|
||||
</span>
|
||||
{item.detail ? (
|
||||
<span
|
||||
className={cn(
|
||||
"block leading-5 text-slate-500",
|
||||
compact ? "truncate" : "break-words"
|
||||
)}
|
||||
title={item.detail}
|
||||
>
|
||||
{item.detail}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<AnimatePresence initial={false} mode="wait">
|
||||
<motion.span
|
||||
key={item.status}
|
||||
data-progress-status={item.status}
|
||||
className={cn(
|
||||
"min-w-12 rounded-full px-2 py-0.5 text-center font-semibold",
|
||||
progressStatusMeta[item.status].className
|
||||
)}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={
|
||||
item.status === "error"
|
||||
? { opacity: [0, 1, 1], x: [0, -2, 2, -1, 0] }
|
||||
: { opacity: 1, x: 0 }
|
||||
}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={
|
||||
item.status === "error"
|
||||
? { duration: 0.24, ease: agentEase }
|
||||
: { duration: 0.14 }
|
||||
}
|
||||
>
|
||||
{progressStatusMeta[item.status].label}
|
||||
</motion.span>
|
||||
</AnimatePresence>
|
||||
</motion.li>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</motion.ol>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TodoCard({ todoUpdate }: { todoUpdate: AgentTodoUpdate }) {
|
||||
return (
|
||||
<AgentNestedBlock icon={ListChecks} iconClassName="text-emerald-600" title="计划">
|
||||
<motion.ol className="space-y-1.5" variants={agentPanelListVariants} animate="animate">
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{todoUpdate.todos.slice(0, 6).map((todo) => (
|
||||
<motion.li
|
||||
key={todo.id}
|
||||
className="grid grid-cols-[16px_1fr_auto] items-start gap-2 text-xs"
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelItemVariants}
|
||||
transition={agentLayoutTransition}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"mt-0.5 grid h-3.5 w-3.5 place-items-center rounded-full border",
|
||||
todoStatusMeta[todo.status].dotClassName
|
||||
)}
|
||||
>
|
||||
{todo.status === "completed" ? <CheckCircle2 size={10} className="text-white" aria-hidden="true" /> : null}
|
||||
</span>
|
||||
<span className="min-w-0 truncate text-slate-700" title={todo.content}>
|
||||
{todo.content}
|
||||
</span>
|
||||
<span className={cn("rounded-full px-2 py-0.5 font-semibold", todoStatusMeta[todo.status].className)}>
|
||||
{todoStatusMeta[todo.status].label}
|
||||
</span>
|
||||
</motion.li>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</motion.ol>
|
||||
</AgentNestedBlock>
|
||||
);
|
||||
}
|
||||
|
||||
function PermissionList({
|
||||
permissions,
|
||||
onReplyPermission
|
||||
}: {
|
||||
permissions: AgentPermissionRequest[];
|
||||
onReplyPermission?: (permission: AgentPermissionRequest, reply: AgentPermissionReply) => Promise<void> | void;
|
||||
}) {
|
||||
return (
|
||||
<AgentNestedBlock icon={LockKeyhole} iconClassName="text-orange-600" title="权限请求">
|
||||
<motion.div className="flex flex-col gap-1.5" variants={agentPanelListVariants} animate="animate">
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{permissions.slice(-4).map((permission) => (
|
||||
<AnimatedDetailItem key={permission.requestId}>
|
||||
<PermissionRequestCard
|
||||
permission={permission}
|
||||
onReplyPermission={onReplyPermission}
|
||||
/>
|
||||
</AnimatedDetailItem>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
</AgentNestedBlock>
|
||||
);
|
||||
}
|
||||
|
||||
function PermissionRequestCard({
|
||||
permission,
|
||||
onReplyPermission
|
||||
}: {
|
||||
permission: AgentPermissionRequest;
|
||||
onReplyPermission?: (permission: AgentPermissionRequest, reply: AgentPermissionReply) => Promise<void> | void;
|
||||
}) {
|
||||
const actionable = permission.status === "pending" || permission.status === "error";
|
||||
const submitting = permission.status === "submitting";
|
||||
const canApproveAlways = permission.always.length > 0;
|
||||
const disabled = !onReplyPermission || submitting;
|
||||
const target = permission.target ?? (permission.patterns.join(" ") || permission.permission);
|
||||
|
||||
const reply = (nextReply: AgentPermissionReply) => {
|
||||
if (!onReplyPermission || submitting) {
|
||||
return;
|
||||
}
|
||||
void Promise.resolve(onReplyPermission(permission, nextReply));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="surface-reading rounded-lg px-2.5 py-2 text-xs">
|
||||
<div className="grid grid-cols-[1fr_auto] gap-2">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-semibold text-slate-800" title={permission.target ?? permission.permission}>
|
||||
{getPermissionTitle(permission)}
|
||||
</p>
|
||||
<p className="mt-0.5 truncate font-mono text-xs text-slate-500" title={target}>
|
||||
{target}
|
||||
</p>
|
||||
{permission.error ? (
|
||||
<p className="mt-1 line-clamp-2 text-xs leading-4 text-red-600">{permission.error}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<span className={cn("self-start rounded-full px-2 py-0.5 font-semibold", permissionStatusMeta[permission.status].className)}>
|
||||
{permissionStatusMeta[permission.status].label}
|
||||
</span>
|
||||
</div>
|
||||
<AnimatePresence initial={false}>
|
||||
{actionable ? (
|
||||
<motion.div
|
||||
key="permission-actions"
|
||||
className="mt-2 flex flex-wrap items-center gap-1.5"
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelSectionVariants}
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
className="agent-panel-primary-action h-7 rounded-md px-2 text-xs"
|
||||
disabled={disabled}
|
||||
onClick={() => reply("once")}
|
||||
>
|
||||
<CheckCircle2 size={13} aria-hidden="true" />
|
||||
允许一次
|
||||
</Button>
|
||||
{canApproveAlways ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 rounded-md border-blue-200 bg-blue-50 px-2 text-xs text-blue-700 hover:bg-blue-100"
|
||||
disabled={disabled}
|
||||
onClick={() => reply("always")}
|
||||
>
|
||||
<ShieldCheck size={13} aria-hidden="true" />
|
||||
始终允许
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 rounded-md border-red-200 bg-red-50 px-2 text-xs text-red-700 hover:bg-red-100"
|
||||
disabled={disabled}
|
||||
onClick={() => reply("reject")}
|
||||
>
|
||||
<XCircle size={13} aria-hidden="true" />
|
||||
拒绝
|
||||
</Button>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QuestionList({
|
||||
questions,
|
||||
onReplyQuestion,
|
||||
onRejectQuestion
|
||||
}: {
|
||||
questions: AgentQuestionRequest[];
|
||||
onReplyQuestion?: (request: AgentQuestionRequest, answers: string[][]) => Promise<void> | void;
|
||||
onRejectQuestion?: (request: AgentQuestionRequest) => Promise<void> | void;
|
||||
}) {
|
||||
return (
|
||||
<AgentNestedBlock icon={HelpCircle} iconClassName="text-blue-600" title="补充信息" floating>
|
||||
<motion.div className="flex flex-col gap-1.5" variants={agentPanelListVariants} animate="animate">
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{questions.slice(-3).map((request) => (
|
||||
<AnimatedDetailItem key={request.requestId}>
|
||||
<QuestionRequestCard
|
||||
request={request}
|
||||
onReplyQuestion={onReplyQuestion}
|
||||
onRejectQuestion={onRejectQuestion}
|
||||
/>
|
||||
</AnimatedDetailItem>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
</AgentNestedBlock>
|
||||
);
|
||||
}
|
||||
|
||||
function QuestionRequestCard({
|
||||
request,
|
||||
onReplyQuestion,
|
||||
onRejectQuestion
|
||||
}: {
|
||||
request: AgentQuestionRequest;
|
||||
onReplyQuestion?: (request: AgentQuestionRequest, answers: string[][]) => Promise<void> | void;
|
||||
onRejectQuestion?: (request: AgentQuestionRequest) => Promise<void> | void;
|
||||
}) {
|
||||
const [draftAnswers, setDraftAnswers] = useState(() => createInitialQuestionAnswers(request));
|
||||
const actionable = request.status === "pending" || request.status === "error";
|
||||
const submitting = request.status === "submitting";
|
||||
const disabled = submitting || !onReplyQuestion;
|
||||
const answers = normalizeDraftAnswers(draftAnswers);
|
||||
const canSubmit = actionable && answers.length === request.questions.length && answers.every((answer) => answer.length > 0);
|
||||
|
||||
const submit = () => {
|
||||
if (!onReplyQuestion || !canSubmit) {
|
||||
return;
|
||||
}
|
||||
void Promise.resolve(onReplyQuestion(request, answers));
|
||||
};
|
||||
|
||||
const reject = () => {
|
||||
if (!onRejectQuestion || submitting) {
|
||||
return;
|
||||
}
|
||||
void Promise.resolve(onRejectQuestion(request));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="px-0 py-1 text-xs">
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<span className="min-w-0 truncate font-semibold text-slate-800">
|
||||
{request.questions[0]?.header || "问题"}
|
||||
</span>
|
||||
<span className={cn("rounded-full px-2 py-0.5 font-semibold", questionStatusMeta[request.status].className)}>
|
||||
{questionStatusMeta[request.status].label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{request.questions.map((question, questionIndex) => (
|
||||
<QuestionInput
|
||||
key={`${request.requestId}-${questionIndex}`}
|
||||
question={question}
|
||||
questionIndex={questionIndex}
|
||||
value={draftAnswers[questionIndex] ?? { selected: [], custom: "" }}
|
||||
disabled={!actionable || submitting}
|
||||
onChange={(nextValue) =>
|
||||
setDraftAnswers((current) => current.map((item, index) => (index === questionIndex ? nextValue : item)))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{request.error ? (
|
||||
<p className="mt-2 line-clamp-2 text-xs leading-4 text-red-600">{request.error}</p>
|
||||
) : null}
|
||||
{request.answers?.length ? (
|
||||
<p className="mt-2 truncate text-slate-500" title={request.answers.map((answer) => answer.join("、")).join(";")}>
|
||||
已答:{request.answers.map((answer) => answer.join("、")).join(";")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<AnimatePresence initial={false}>
|
||||
{actionable ? (
|
||||
<motion.div
|
||||
key="question-actions"
|
||||
className="mt-2 flex flex-wrap items-center gap-1.5"
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelSectionVariants}
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
className="agent-panel-primary-action h-7 rounded-md px-2 text-xs"
|
||||
disabled={disabled || !canSubmit}
|
||||
onClick={submit}
|
||||
>
|
||||
<CheckCircle2 size={13} aria-hidden="true" />
|
||||
提交回答
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 rounded-md border-slate-200 bg-white px-2 text-xs text-slate-600 hover:bg-slate-50"
|
||||
disabled={submitting || !onRejectQuestion}
|
||||
onClick={reject}
|
||||
>
|
||||
<XCircle size={13} aria-hidden="true" />
|
||||
跳过
|
||||
</Button>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type QuestionDraftAnswer = {
|
||||
selected: string[];
|
||||
custom: string;
|
||||
};
|
||||
|
||||
function QuestionInput({
|
||||
question,
|
||||
questionIndex,
|
||||
value,
|
||||
disabled,
|
||||
onChange
|
||||
}: {
|
||||
question: AgentQuestionInfo;
|
||||
questionIndex: number;
|
||||
value: QuestionDraftAnswer;
|
||||
disabled: boolean;
|
||||
onChange: (value: QuestionDraftAnswer) => void;
|
||||
}) {
|
||||
const name = `agent-question-${questionIndex}-${question.question}`;
|
||||
const showCustomInput = question.custom || question.options.length === 0;
|
||||
|
||||
const toggleOption = (label: string, checked: boolean) => {
|
||||
if (question.multiple) {
|
||||
onChange({
|
||||
...value,
|
||||
selected: checked ? [...value.selected, label] : value.selected.filter((item) => item !== label)
|
||||
});
|
||||
return;
|
||||
}
|
||||
onChange({
|
||||
...value,
|
||||
selected: checked ? [label] : []
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<p className="leading-5 text-slate-700">{question.question}</p>
|
||||
{question.options.length ? (
|
||||
<div className="space-y-1">
|
||||
{question.options.map((option) => {
|
||||
const checked = value.selected.includes(option.label);
|
||||
return (
|
||||
<label
|
||||
key={option.label}
|
||||
className="flex cursor-pointer items-start gap-2 rounded-md border border-slate-200/80 px-2 py-1.5 text-slate-600"
|
||||
>
|
||||
<input
|
||||
type={question.multiple ? "checkbox" : "radio"}
|
||||
name={name}
|
||||
className="mt-0.5 h-3.5 w-3.5 accent-blue-600"
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onChange={(event) => toggleOption(option.label, event.currentTarget.checked)}
|
||||
/>
|
||||
<span className="min-w-0">
|
||||
<span className="block font-semibold text-slate-700">{option.label}</span>
|
||||
{option.description ? (
|
||||
<span className="block leading-4 text-slate-500">{option.description}</span>
|
||||
) : null}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
{showCustomInput ? (
|
||||
<textarea
|
||||
className="min-h-16 w-full resize-none rounded-md border border-slate-200/80 bg-transparent px-2 py-1.5 text-xs leading-5 text-slate-700 outline-none transition focus:border-blue-300 focus:ring-2 focus:ring-blue-100 disabled:opacity-60"
|
||||
placeholder="输入回答"
|
||||
value={value.custom}
|
||||
disabled={disabled}
|
||||
onChange={(event) => onChange({ ...value, custom: event.currentTarget.value })}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function createInitialQuestionAnswers(request: AgentQuestionRequest): QuestionDraftAnswer[] {
|
||||
return request.questions.map((question, index) => ({
|
||||
selected: request.answers?.[index] ?? [],
|
||||
custom: ""
|
||||
}));
|
||||
}
|
||||
|
||||
function normalizeDraftAnswers(draftAnswers: QuestionDraftAnswer[]) {
|
||||
return draftAnswers.map((answer) => {
|
||||
const custom = answer.custom.trim();
|
||||
return custom ? [...answer.selected, custom] : answer.selected;
|
||||
});
|
||||
}
|
||||
|
||||
function getPermissionTitle(permission: AgentPermissionRequest) {
|
||||
if (permission.permission === "bash") return "执行终端命令";
|
||||
if (permission.permission === "edit") return "修改文件内容";
|
||||
if (permission.permission === "external_directory") return "访问工作区外目录";
|
||||
return permission.permission || "工具权限请求";
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import type { Variants } from "motion/react";
|
||||
|
||||
export const AGENT_MOTION_DURATION_MS = 180;
|
||||
|
||||
export const agentEase = [0.22, 1, 0.36, 1] as const;
|
||||
|
||||
export const agentPanelItemVariants: Variants = {
|
||||
initial: {
|
||||
opacity: 0,
|
||||
y: 6,
|
||||
scale: 0.985
|
||||
},
|
||||
animate: {
|
||||
opacity: 1,
|
||||
y: 0,
|
||||
scale: 1,
|
||||
transition: {
|
||||
duration: 0.18,
|
||||
ease: agentEase
|
||||
}
|
||||
},
|
||||
exit: {
|
||||
opacity: 0,
|
||||
y: -4,
|
||||
scale: 0.99,
|
||||
transition: {
|
||||
duration: 0.14,
|
||||
ease: [0.5, 0, 0.2, 1]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const agentPanelSectionVariants: Variants = {
|
||||
initial: {
|
||||
opacity: 0,
|
||||
height: 0,
|
||||
y: -4
|
||||
},
|
||||
animate: {
|
||||
opacity: 1,
|
||||
height: "auto",
|
||||
y: 0,
|
||||
transition: {
|
||||
duration: 0.18,
|
||||
ease: agentEase
|
||||
}
|
||||
},
|
||||
exit: {
|
||||
opacity: 0,
|
||||
height: 0,
|
||||
y: -4,
|
||||
transition: {
|
||||
duration: 0.14,
|
||||
ease: [0.5, 0, 0.2, 1]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const agentPanelListVariants: Variants = {
|
||||
animate: {
|
||||
transition: {
|
||||
staggerChildren: 0.025
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const agentLayoutTransition = {
|
||||
duration: 0.18,
|
||||
ease: agentEase
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ClipboardCheck,
|
||||
Crosshair,
|
||||
MapPinned,
|
||||
Radio,
|
||||
Route
|
||||
} from "lucide-react";
|
||||
import type { ReactNode } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type {
|
||||
AgentChatMessage
|
||||
} from "../types";
|
||||
|
||||
export function AgentOperationalBrief({
|
||||
messages,
|
||||
statusLabel,
|
||||
streaming,
|
||||
onSubmitCommand
|
||||
}: {
|
||||
messages: AgentChatMessage[];
|
||||
statusLabel: string;
|
||||
streaming: boolean;
|
||||
onSubmitCommand: (prompt: string) => void;
|
||||
}) {
|
||||
const brief = createOperationalBrief(messages, statusLabel, streaming);
|
||||
|
||||
return (
|
||||
<div className="agent-panel-control rounded-2xl p-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={cn("h-2 w-2 rounded-full", brief.statusDotClassName)} />
|
||||
<p className="truncate text-sm font-semibold text-slate-950">{brief.stateLabel}</p>
|
||||
</div>
|
||||
<p className="mt-1 truncate text-xs leading-5 text-slate-500" title={brief.task}>
|
||||
{brief.task}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<dl className="mt-3 grid grid-cols-3 gap-2">
|
||||
<AgentBriefMetric icon={<Radio size={13} aria-hidden="true" />} label="证据" value={brief.evidence} />
|
||||
<AgentBriefMetric icon={<Route size={13} aria-hidden="true" />} label="计划" value={brief.plan} />
|
||||
<AgentBriefMetric icon={<ClipboardCheck size={13} aria-hidden="true" />} label="确认" value={brief.confirmation} />
|
||||
</dl>
|
||||
|
||||
<div className="mt-3 grid grid-cols-2 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="agent-panel-primary-action flex h-9 items-center justify-center gap-1.5 rounded-xl px-3 text-xs font-semibold transition disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={streaming}
|
||||
onClick={() => onSubmitCommand(brief.primaryCommand)}
|
||||
>
|
||||
<MapPinned size={14} aria-hidden="true" />
|
||||
预览影响
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="surface-control flex h-9 items-center justify-center gap-1.5 rounded-xl border px-3 text-xs font-semibold text-slate-700 transition-colors hover:bg-blue-50 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={streaming}
|
||||
onClick={() => onSubmitCommand(brief.secondaryCommand)}
|
||||
>
|
||||
<Crosshair size={14} aria-hidden="true" />
|
||||
检查证据
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentBriefMetric({ icon, label, value }: { icon: ReactNode; label: string; value: string }) {
|
||||
return (
|
||||
<div className="surface-reading min-w-0 rounded-xl border px-2 py-2">
|
||||
<dt className="flex items-center gap-1.5 text-xs font-semibold text-slate-500">
|
||||
<span className="text-blue-600">{icon}</span>
|
||||
{label}
|
||||
</dt>
|
||||
<dd className="mt-1 truncate text-xs font-semibold text-slate-900" title={value}>
|
||||
{value}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function createOperationalBrief(messages: AgentChatMessage[], statusLabel: string, streaming: boolean) {
|
||||
const lastUserMessage = [...messages].reverse().find((message) => message.role === "user" && message.content.trim());
|
||||
const progressItems = messages.flatMap((message) => message.progress ?? []);
|
||||
const todoItems = messages.flatMap((message) => message.todos?.todos ?? []);
|
||||
const permissionItems = messages.flatMap((message) => message.permissions ?? []);
|
||||
const questionItems = messages.flatMap((message) => message.questions ?? []);
|
||||
const latestProgress = progressItems.at(-1);
|
||||
const activeTodo =
|
||||
[...todoItems].reverse().find((todo) => todo.status === "in_progress") ??
|
||||
[...todoItems].reverse().find((todo) => todo.status === "pending");
|
||||
const pendingConfirmations =
|
||||
permissionItems.filter((permission) => permission.status === "pending" || permission.status === "error").length +
|
||||
questionItems.filter((question) => question.status === "pending" || question.status === "error").length;
|
||||
const completedSteps = progressItems.filter((item) => item.status === "completed").length;
|
||||
const task = lastUserMessage?.content.trim() || "等待调度指令";
|
||||
const evidence = latestProgress?.detail || latestProgress?.title || statusLabel;
|
||||
const plan = activeTodo?.content || (completedSteps > 0 ? `${completedSteps} 项已完成` : "待生成");
|
||||
const confirmation = pendingConfirmations > 0 ? `${pendingConfirmations} 项待确认` : "无需确认";
|
||||
const stateLabel = pendingConfirmations > 0 ? "等待人工确认" : streaming ? "Agent 分析中" : "分析完成";
|
||||
const statusDotClassName = pendingConfirmations > 0 ? "bg-orange-500" : streaming ? "bg-blue-500" : "bg-emerald-500";
|
||||
const promptContext = lastUserMessage?.content.trim() || "当前排水管网运行态势";
|
||||
|
||||
return {
|
||||
task,
|
||||
evidence,
|
||||
plan,
|
||||
confirmation,
|
||||
stateLabel,
|
||||
statusDotClassName,
|
||||
primaryCommand: `请基于“${promptContext}”预览空间影响范围,并列出需要确认的操作。`,
|
||||
secondaryCommand: `请检查“${promptContext}”的证据链,按数据来源、风险和不确定性汇总。`
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Bot } from "lucide-react";
|
||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { PersonaState } from "@/shared/ai-elements/persona";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const LazyPersona = lazy(async () => {
|
||||
const module = await import("@/shared/ai-elements/persona");
|
||||
return { default: module.Persona };
|
||||
});
|
||||
|
||||
type AgentPersonaProps = {
|
||||
className?: string;
|
||||
state?: PersonaState;
|
||||
};
|
||||
|
||||
function useElementVisibility() {
|
||||
const containerRef = useRef<HTMLSpanElement>(null);
|
||||
const [visible, setVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
let intersectsViewport = false;
|
||||
const updateVisibility = () => {
|
||||
setVisible(intersectsViewport && document.visibilityState === "visible");
|
||||
};
|
||||
const observer = new IntersectionObserver(([entry]) => {
|
||||
intersectsViewport = Boolean(entry?.isIntersecting);
|
||||
updateVisibility();
|
||||
});
|
||||
|
||||
observer.observe(container);
|
||||
document.addEventListener("visibilitychange", updateVisibility);
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
document.removeEventListener("visibilitychange", updateVisibility);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { containerRef, visible };
|
||||
}
|
||||
|
||||
function PersonaFallback() {
|
||||
return (
|
||||
<span className="grid h-full w-full place-items-center rounded-full border border-slate-300/70 bg-slate-100 text-slate-500">
|
||||
<Bot className="h-2/5 w-2/5" aria-hidden="true" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentPersona({ className, state = "idle" }: AgentPersonaProps) {
|
||||
const { containerRef, visible } = useElementVisibility();
|
||||
const [failed, setFailed] = useState(false);
|
||||
const handleLoadError = useCallback(() => setFailed(true), []);
|
||||
|
||||
const shouldRenderAnimation = !failed && visible;
|
||||
|
||||
return (
|
||||
<span ref={containerRef} className={cn("relative block shrink-0", className)}>
|
||||
{shouldRenderAnimation ? (
|
||||
<Suspense fallback={<PersonaFallback />}>
|
||||
<LazyPersona
|
||||
className="h-full w-full scale-110"
|
||||
onLoadError={handleLoadError}
|
||||
state={state}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<PersonaFallback />
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
"use client";
|
||||
|
||||
import { Activity, BarChart3, Database, History, LineChart, MonitorCog } from "lucide-react";
|
||||
import { AnimatePresence, MotionConfig, motion } from "motion/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { normalizeSafeChartData, parseChartSpec, type SafeChartData, type SafeChartSeries, type SafeChartSpec } from "../chart-data";
|
||||
import type { AgentUiResult } from "../types";
|
||||
import type { UIEnvelope } from "../ui-envelope";
|
||||
import {
|
||||
agentLayoutTransition,
|
||||
agentPanelItemVariants,
|
||||
agentPanelListVariants
|
||||
} from "./agent-motion";
|
||||
|
||||
type AgentUiEnvelopeRendererProps = {
|
||||
results: AgentUiResult[];
|
||||
};
|
||||
|
||||
export function AgentUiEnvelopeRenderer({ results }: AgentUiEnvelopeRendererProps) {
|
||||
if (results.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<MotionConfig reducedMotion="user">
|
||||
<motion.div className="space-y-3" variants={agentPanelListVariants} animate="animate">
|
||||
<AnimatePresence initial={false} mode="popLayout">
|
||||
{results.map((result) => (
|
||||
<motion.div
|
||||
key={result.id}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={agentPanelItemVariants}
|
||||
transition={agentLayoutTransition}
|
||||
>
|
||||
<AgentUiResultCard result={result} />
|
||||
</motion.div>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
</MotionConfig>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentUiResultCard({ result }: { result: AgentUiResult }) {
|
||||
const { envelope } = result;
|
||||
|
||||
return (
|
||||
<div className="agent-panel-message w-full rounded-2xl p-3 text-slate-700 shadow-sm">
|
||||
<div className="mb-3 flex items-center justify-between gap-2">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-xl bg-blue-100 text-blue-700">
|
||||
{getEnvelopeIcon(envelope)}
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-semibold text-slate-950">{getEnvelopeTitle(envelope)}</p>
|
||||
<p className="text-xs text-slate-500">{getSurfaceLabel(envelope.surface)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className="shrink-0 rounded-full bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-600">
|
||||
agent-ui@1
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{envelope.kind === "chart" ? <SafeChartEnvelope envelope={envelope} /> : null}
|
||||
{envelope.kind === "registered_component" ? <RegisteredComponentEnvelope envelope={envelope} /> : null}
|
||||
{envelope.kind === "map_action" ? null : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SafeChartEnvelope({ envelope }: { envelope: Extract<UIEnvelope, { kind: "chart" }> }) {
|
||||
const spec = parseChartSpec(envelope.spec);
|
||||
const data = normalizeSafeChartData(envelope.data);
|
||||
|
||||
if (!data || data.series.length === 0 || data.xData.length === 0) {
|
||||
return <FallbackText text={envelope.fallbackText ?? "图表数据未通过前端安全子集校验。"} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="agent-panel-nested rounded-xl p-3">
|
||||
<div className="mb-3 flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-semibold text-slate-950" title={spec.title}>
|
||||
{spec.title ?? "Agent 图表"}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-slate-500">
|
||||
{spec.chartType === "bar" ? "柱状图" : "折线图"}
|
||||
{spec.yAxisName ? ` · ${spec.yAxisName}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap justify-end gap-1.5">
|
||||
{data.series.slice(0, 3).map((series, index) => (
|
||||
<span key={series.name} className="flex items-center gap-1 text-xs text-slate-600">
|
||||
<span className={cn("h-2 w-2 rounded-full", chartColorClass(index))} />
|
||||
{series.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<SafeChartSvg spec={spec} data={data} />
|
||||
{spec.xAxisName ? <p className="mt-2 text-center text-xs text-slate-500">{spec.xAxisName}</p> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SafeChartSvg({ spec, data }: { spec: SafeChartSpec; data: SafeChartData }) {
|
||||
const width = 360;
|
||||
const height = 190;
|
||||
const padding = { top: 16, right: 18, bottom: 32, left: 38 };
|
||||
const plotWidth = width - padding.left - padding.right;
|
||||
const plotHeight = height - padding.top - padding.bottom;
|
||||
const values = data.series.flatMap((series) => series.data);
|
||||
const min = Math.min(0, ...values);
|
||||
const max = Math.max(...values);
|
||||
const range = max - min || 1;
|
||||
const xFor = (index: number) =>
|
||||
padding.left + (data.xData.length === 1 ? plotWidth / 2 : (index / (data.xData.length - 1)) * plotWidth);
|
||||
const yFor = (value: number) => padding.top + plotHeight - ((value - min) / range) * plotHeight;
|
||||
const ticks = createTicks(min, max);
|
||||
|
||||
return (
|
||||
<svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label={spec.title ?? "Agent 图表"} className="h-48 w-full">
|
||||
<rect x="0" y="0" width={width} height={height} rx="12" className="fill-white/70" />
|
||||
{ticks.map((tick) => {
|
||||
const y = yFor(tick);
|
||||
return (
|
||||
<g key={tick}>
|
||||
<line x1={padding.left} x2={width - padding.right} y1={y} y2={y} className="stroke-slate-200" />
|
||||
<text x={padding.left - 8} y={y + 4} textAnchor="end" className="fill-slate-400 text-xs">
|
||||
{formatChartNumber(tick)}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
<line x1={padding.left} x2={padding.left} y1={padding.top} y2={height - padding.bottom} className="stroke-slate-300" />
|
||||
<line x1={padding.left} x2={width - padding.right} y1={height - padding.bottom} y2={height - padding.bottom} className="stroke-slate-300" />
|
||||
{data.xData.map((label, index) => (
|
||||
<text
|
||||
key={`${label}-${index}`}
|
||||
x={xFor(index)}
|
||||
y={height - 12}
|
||||
textAnchor="middle"
|
||||
className="fill-slate-500 text-xs"
|
||||
>
|
||||
{shortLabel(label)}
|
||||
</text>
|
||||
))}
|
||||
{data.series.slice(0, 4).map((series, seriesIndex) =>
|
||||
(series.type ?? spec.chartType) === "bar" ? (
|
||||
<BarSeries
|
||||
key={series.name}
|
||||
series={series}
|
||||
seriesIndex={seriesIndex}
|
||||
seriesCount={Math.min(data.series.length, 4)}
|
||||
xFor={xFor}
|
||||
yFor={yFor}
|
||||
baselineY={yFor(0)}
|
||||
/>
|
||||
) : (
|
||||
<LineSeries key={series.name} series={series} seriesIndex={seriesIndex} xFor={xFor} yFor={yFor} />
|
||||
)
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function LineSeries({
|
||||
series,
|
||||
seriesIndex,
|
||||
xFor,
|
||||
yFor
|
||||
}: {
|
||||
series: SafeChartSeries;
|
||||
seriesIndex: number;
|
||||
xFor: (index: number) => number;
|
||||
yFor: (value: number) => number;
|
||||
}) {
|
||||
const points = series.data.map((value, index) => `${xFor(index)},${yFor(value)}`).join(" ");
|
||||
const stroke = chartStroke(seriesIndex);
|
||||
|
||||
return (
|
||||
<g>
|
||||
<polyline
|
||||
points={points}
|
||||
fill="none"
|
||||
stroke={stroke}
|
||||
strokeWidth="2.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="agent-chart-line"
|
||||
/>
|
||||
{series.data.map((value, index) => (
|
||||
<circle
|
||||
key={`${series.name}-${index}`}
|
||||
cx={xFor(index)}
|
||||
cy={yFor(value)}
|
||||
r="2.8"
|
||||
fill={stroke}
|
||||
className="agent-chart-point"
|
||||
style={{ animationDelay: `${80 + index * 18}ms` }}
|
||||
/>
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function BarSeries({
|
||||
series,
|
||||
seriesIndex,
|
||||
seriesCount,
|
||||
xFor,
|
||||
yFor,
|
||||
baselineY
|
||||
}: {
|
||||
series: SafeChartSeries;
|
||||
seriesIndex: number;
|
||||
seriesCount: number;
|
||||
xFor: (index: number) => number;
|
||||
yFor: (value: number) => number;
|
||||
baselineY: number;
|
||||
}) {
|
||||
const fill = chartStroke(seriesIndex);
|
||||
const barWidth = Math.max(5, 22 / seriesCount);
|
||||
const offset = (seriesIndex - (seriesCount - 1) / 2) * (barWidth + 2);
|
||||
|
||||
return (
|
||||
<g>
|
||||
{series.data.map((value, index) => {
|
||||
const y = yFor(value);
|
||||
return (
|
||||
<rect
|
||||
key={`${series.name}-${index}`}
|
||||
x={xFor(index) - barWidth / 2 + offset}
|
||||
y={Math.min(y, baselineY)}
|
||||
width={barWidth}
|
||||
height={Math.max(1, Math.abs(baselineY - y))}
|
||||
rx="2"
|
||||
fill={fill}
|
||||
className="agent-chart-bar"
|
||||
style={{ animationDelay: `${seriesIndex * 28 + index * 16}ms` }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function RegisteredComponentEnvelope({
|
||||
envelope
|
||||
}: {
|
||||
envelope: Extract<UIEnvelope, { kind: "registered_component" }>;
|
||||
}) {
|
||||
if (envelope.component === "HistoryPanel") {
|
||||
return (
|
||||
<TrustedPanelShell icon={<History size={15} aria-hidden="true" />} title="历史数据面板">
|
||||
<PropRows props={envelope.props} labels={{ feature_id: "资产 ID", featureId: "资产 ID", metric: "指标", range: "时间范围" }} />
|
||||
</TrustedPanelShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (envelope.component === "ScadaPanel") {
|
||||
return (
|
||||
<TrustedPanelShell icon={<MonitorCog size={15} aria-hidden="true" />} title="SCADA 面板">
|
||||
<PropRows props={envelope.props} labels={{ device_id: "设备 ID", deviceId: "设备 ID", metric: "指标", range: "时间范围" }} />
|
||||
</TrustedPanelShell>
|
||||
);
|
||||
}
|
||||
|
||||
return <FallbackText text={envelope.fallbackText ?? "当前注册组件未接入渲染器。"} />;
|
||||
}
|
||||
|
||||
function TrustedPanelShell({
|
||||
icon,
|
||||
title,
|
||||
children
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="agent-panel-nested rounded-xl p-3">
|
||||
<div className="mb-3 flex items-center gap-2 text-sm font-semibold text-slate-950">
|
||||
<span className="grid h-7 w-7 place-items-center rounded-lg bg-emerald-100 text-emerald-700">{icon}</span>
|
||||
{title}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PropRows({ props, labels }: { props: unknown; labels: Record<string, string> }) {
|
||||
const rows = safePropRows(props, labels);
|
||||
|
||||
if (rows.length === 0) {
|
||||
return <p className="text-sm text-slate-600">已打开可信面板,暂无可展示参数。</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<dl className="grid grid-cols-2 gap-2">
|
||||
{rows.map((row) => (
|
||||
<div key={row.label} className="surface-reading min-w-0 rounded-lg px-2.5 py-2">
|
||||
<dt className="truncate text-xs text-slate-500">{row.label}</dt>
|
||||
<dd className="mt-1 truncate text-sm font-semibold text-slate-900" title={row.value}>
|
||||
{row.value}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
function FallbackText({ text }: { text: string }) {
|
||||
return (
|
||||
<div className="agent-panel-nested rounded-xl p-3 text-sm leading-6 text-slate-600">
|
||||
{text}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function safePropRows(props: unknown, labels: Record<string, string>) {
|
||||
if (!isRecord(props)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Object.entries(labels).flatMap(([key, label]) => {
|
||||
const value = props[key];
|
||||
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [{ label, value: String(value) }];
|
||||
});
|
||||
}
|
||||
|
||||
function getEnvelopeIcon(envelope: UIEnvelope) {
|
||||
if (envelope.kind === "chart") {
|
||||
return envelope.spec && isRecord(envelope.spec) && envelope.spec.chart_type === "bar" ? (
|
||||
<BarChart3 size={16} aria-hidden="true" />
|
||||
) : (
|
||||
<LineChart size={16} aria-hidden="true" />
|
||||
);
|
||||
}
|
||||
|
||||
if (envelope.kind === "registered_component") {
|
||||
return <Database size={16} aria-hidden="true" />;
|
||||
}
|
||||
|
||||
return <Activity size={16} aria-hidden="true" />;
|
||||
}
|
||||
|
||||
function getEnvelopeTitle(envelope: UIEnvelope) {
|
||||
if (envelope.kind === "chart") {
|
||||
const spec = parseChartSpec(envelope.spec);
|
||||
return spec.title ?? "Agent 图表";
|
||||
}
|
||||
|
||||
if (envelope.kind === "registered_component") {
|
||||
return envelope.component;
|
||||
}
|
||||
|
||||
return envelope.action;
|
||||
}
|
||||
|
||||
function getSurfaceLabel(surface: UIEnvelope["surface"]) {
|
||||
if (surface === "chat_inline") return "聊天内联展示";
|
||||
if (surface === "side_panel") return "侧栏展示";
|
||||
if (surface === "canvas") return "画布展示";
|
||||
return "地图叠加";
|
||||
}
|
||||
|
||||
function createTicks(min: number, max: number) {
|
||||
const range = max - min || 1;
|
||||
return [max, min + range * 0.5, min];
|
||||
}
|
||||
|
||||
function chartStroke(index: number) {
|
||||
return ["#2563eb", "#0aa6a6", "#ff7a45", "#0477bf"][index % 4] ?? "#2563eb";
|
||||
}
|
||||
|
||||
function chartColorClass(index: number) {
|
||||
return ["bg-blue-600", "bg-teal-600", "bg-orange-500", "bg-sky-700"][index % 4] ?? "bg-blue-600";
|
||||
}
|
||||
|
||||
function formatChartNumber(value: number) {
|
||||
if (Math.abs(value) >= 100) {
|
||||
return value.toFixed(0);
|
||||
}
|
||||
|
||||
if (Math.abs(value) >= 10) {
|
||||
return value.toFixed(1);
|
||||
}
|
||||
|
||||
return value.toFixed(2);
|
||||
}
|
||||
|
||||
function shortLabel(value: string) {
|
||||
return value.length > 8 ? `${value.slice(0, 7)}...` : value;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { MessageResponse } from "@/shared/ai-elements/message";
|
||||
|
||||
type StreamingTokenResponseProps = {
|
||||
content: string;
|
||||
streaming: boolean;
|
||||
streamDone?: boolean;
|
||||
className?: string;
|
||||
messageId?: string;
|
||||
};
|
||||
|
||||
export function StreamingTokenResponse({
|
||||
content,
|
||||
streaming,
|
||||
streamDone = !streaming,
|
||||
className,
|
||||
}: StreamingTokenResponseProps) {
|
||||
if (!content) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isAnimating = streaming && !streamDone;
|
||||
|
||||
return (
|
||||
<MessageResponse
|
||||
className={cn("agent-streaming-response", className)}
|
||||
isAnimating={isAnimating}
|
||||
mode="streaming"
|
||||
parseIncompleteMarkdown={true}
|
||||
>
|
||||
{content}
|
||||
</MessageResponse>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
parseFrontendActionRequest,
|
||||
readActionResults,
|
||||
storeActionResult,
|
||||
type FrontendActionRequest,
|
||||
type FrontendActionResult
|
||||
} from ".";
|
||||
|
||||
type ExecuteAction = (request: FrontendActionRequest, signal: AbortSignal) => Promise<unknown>;
|
||||
type SubmitResult = (sessionId: string, actionId: string, result: FrontendActionResult) => Promise<void>;
|
||||
const ERROR_CODE_PATTERN = /^[A-Z][A-Z0-9_]+$/;
|
||||
|
||||
export class FrontendActionExecutor {
|
||||
private readonly controllers = new Map<string, AbortController>();
|
||||
|
||||
constructor(private readonly execute: ExecuteAction, private readonly submit: SubmitResult) {}
|
||||
|
||||
async handle(value: unknown, activeSessionId: string | null): Promise<void> {
|
||||
const request = parseFrontendActionRequest(value);
|
||||
if (!request || request.sessionId !== activeSessionId) return;
|
||||
const saved = readActionResults(request.sessionId)[request.actionId];
|
||||
if (saved) {
|
||||
await this.submit(request.sessionId, request.actionId, saved);
|
||||
return;
|
||||
}
|
||||
if (this.controllers.has(request.actionId)) return;
|
||||
const result = await this.executeOnce(request);
|
||||
storeActionResult(request.sessionId, result);
|
||||
await this.submit(request.sessionId, request.actionId, result);
|
||||
}
|
||||
|
||||
cancelAll(): void {
|
||||
for (const controller of this.controllers.values()) controller.abort();
|
||||
this.controllers.clear();
|
||||
}
|
||||
|
||||
private async executeOnce(request: FrontendActionRequest): Promise<FrontendActionResult> {
|
||||
if (Date.now() >= request.expiresAt) return this.failure(request, "expired", "ACTION_EXPIRED", "frontend action expired before execution");
|
||||
const controller = new AbortController();
|
||||
this.controllers.set(request.actionId, controller);
|
||||
try {
|
||||
return { version: "frontend-action-result@1", actionId: request.actionId, status: "succeeded", output: await this.execute(request, controller.signal), completedAt: Date.now() };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "frontend action failed";
|
||||
const code = controller.signal.aborted ? "ACTION_CANCELLED" : ERROR_CODE_PATTERN.test(message) ? message : "ACTION_FAILED";
|
||||
return this.failure(request, controller.signal.aborted ? "cancelled" : "failed", code, message);
|
||||
} finally {
|
||||
this.controllers.delete(request.actionId);
|
||||
}
|
||||
}
|
||||
|
||||
private failure(request: FrontendActionRequest, status: "failed" | "cancelled" | "expired", code: string, message: string): FrontendActionResult {
|
||||
return { version: "frontend-action-result@1", actionId: request.actionId, status, error: { code, message }, completedAt: Date.now() };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { FrontendActionExecutor } from "./executor";
|
||||
import { parseFrontendActionRegistry, parseFrontendActionRequest, type FrontendActionResult } from ".";
|
||||
|
||||
const storage = new Map<string, string>();
|
||||
|
||||
beforeEach(() => {
|
||||
storage.clear();
|
||||
vi.stubGlobal("sessionStorage", {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => storage.set(key, value)
|
||||
});
|
||||
});
|
||||
|
||||
describe("SCADA frontend actions", () => {
|
||||
it("accepts only the two registered SCADA action names", () => {
|
||||
expect(parseFrontendActionRegistry({
|
||||
schema_version: "frontend-action-registry@1",
|
||||
actions: [
|
||||
{ id: "render_scada_analysis", version: "frontend-action@1" },
|
||||
{ id: "clear_scada_analysis", version: "frontend-action@1" },
|
||||
{ id: "zoom_to_map", version: "frontend-action@1" }
|
||||
]
|
||||
})?.actions.map((action) => action.id)).toEqual([
|
||||
"render_scada_analysis",
|
||||
"clear_scada_analysis"
|
||||
]);
|
||||
expect(parseFrontendActionRequest(createRequest("zoom_to_map"))).toBeNull();
|
||||
expect(parseFrontendActionRequest(createRequest("render_scada_analysis"))).not.toBeNull();
|
||||
});
|
||||
|
||||
it("submits the real browser output and replays the terminal receipt idempotently", async () => {
|
||||
const execute = vi.fn(async () => ({
|
||||
rendered_ids: ["MP01"],
|
||||
missing_ids: [],
|
||||
level_counts: { high: 1, medium: 0, low: 0, unrated: 0 },
|
||||
fitted: true
|
||||
}));
|
||||
const submit = vi.fn(async (
|
||||
_sessionId: string,
|
||||
_actionId: string,
|
||||
_result: FrontendActionResult
|
||||
) => undefined);
|
||||
const executor = new FrontendActionExecutor(execute, submit);
|
||||
const request = createRequest("render_scada_analysis");
|
||||
await executor.handle(request, "session-1");
|
||||
await executor.handle(request, "session-1");
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
expect(submit).toHaveBeenCalledTimes(2);
|
||||
expect(submit.mock.calls[0][2]).toMatchObject({
|
||||
status: "succeeded",
|
||||
output: { rendered_ids: ["MP01"], fitted: true }
|
||||
});
|
||||
expect(submit.mock.calls[1][2]).toEqual(submit.mock.calls[0][2]);
|
||||
});
|
||||
});
|
||||
|
||||
function createRequest(name: string) {
|
||||
return {
|
||||
version: "frontend-action@1",
|
||||
actionId: "action-1",
|
||||
toolCallId: "call-1",
|
||||
sessionId: "session-1",
|
||||
name,
|
||||
params: { items: [{ sensor_id: "MP01", level: "high" }] },
|
||||
issuedAt: Date.now(),
|
||||
expiresAt: Date.now() + 15_000
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export const FRONTEND_ACTION_NAMES = ["render_scada_analysis", "clear_scada_analysis"] as const;
|
||||
export type FrontendActionName = (typeof FRONTEND_ACTION_NAMES)[number];
|
||||
export type FrontendActionRegistry = { schema_version: "frontend-action-registry@1"; actions: Array<{ id: FrontendActionName; version: "frontend-action@1" }> };
|
||||
export type FrontendActionRequest = { version: "frontend-action@1"; actionId: string; toolCallId: string; sessionId: string; name: FrontendActionName; params: Record<string, unknown>; issuedAt: number; expiresAt: number };
|
||||
export type FrontendActionResult = { version: "frontend-action-result@1"; actionId: string; status: "succeeded" | "failed" | "cancelled" | "expired"; output?: unknown; error?: { code: string; message: string }; completedAt: number };
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
export function parseFrontendActionRegistry(value: unknown): FrontendActionRegistry | null { if (!isRecord(value) || value.schema_version !== "frontend-action-registry@1" || !Array.isArray(value.actions)) return null; const actions = value.actions.filter((item): item is { id: FrontendActionName; version: "frontend-action@1" } => isRecord(item) && FRONTEND_ACTION_NAMES.includes(item.id as FrontendActionName) && item.version === "frontend-action@1"); return { schema_version: "frontend-action-registry@1", actions }; }
|
||||
export function parseFrontendActionRequest(value: unknown): FrontendActionRequest | null { if (!isRecord(value) || value.version !== "frontend-action@1" || typeof value.actionId !== "string" || typeof value.toolCallId !== "string" || typeof value.sessionId !== "string" || !FRONTEND_ACTION_NAMES.includes(value.name as FrontendActionName) || !isRecord(value.params) || typeof value.issuedAt !== "number" || typeof value.expiresAt !== "number") return null; return value as FrontendActionRequest; }
|
||||
const storageKey = (sessionId: string) => `tjwater:frontend-actions:${sessionId}`;
|
||||
export function readActionResults(sessionId: string): Record<string, FrontendActionResult> { try { const value = JSON.parse(sessionStorage.getItem(storageKey(sessionId)) ?? "{}"); return isRecord(value) ? value as Record<string, FrontendActionResult> : {}; } catch { return {}; } }
|
||||
export function storeActionResult(sessionId: string, result: FrontendActionResult) { const values = { ...readActionResults(sessionId), [result.actionId]: result }; const bounded = Object.fromEntries(Object.entries(values).sort(([, a], [, b]) => b.completedAt - a.completedAt).slice(0, 100)); sessionStorage.setItem(storageKey(sessionId), JSON.stringify(bounded)); }
|
||||
@@ -0,0 +1,347 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
|
||||
import {
|
||||
splitSpeechTextIntoChunks,
|
||||
type AgentSpeakOptions,
|
||||
type AgentSpeechState
|
||||
} from "../speech";
|
||||
|
||||
interface BrowserSpeechRecognitionEvent extends Event {
|
||||
readonly resultIndex: number;
|
||||
readonly results: SpeechRecognitionResultList;
|
||||
}
|
||||
|
||||
interface BrowserSpeechRecognitionErrorEvent extends Event {
|
||||
readonly error: string;
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
interface BrowserSpeechRecognition extends EventTarget {
|
||||
lang: string;
|
||||
continuous: boolean;
|
||||
interimResults: boolean;
|
||||
onresult: ((event: BrowserSpeechRecognitionEvent) => void) | null;
|
||||
onerror: ((event: BrowserSpeechRecognitionErrorEvent) => void) | null;
|
||||
onend: (() => void) | null;
|
||||
start(): void;
|
||||
stop(): void;
|
||||
abort(): void;
|
||||
}
|
||||
|
||||
type BrowserSpeechRecognitionConstructor = new () => BrowserSpeechRecognition;
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
SpeechRecognition?: BrowserSpeechRecognitionConstructor;
|
||||
webkitSpeechRecognition?: BrowserSpeechRecognitionConstructor;
|
||||
}
|
||||
}
|
||||
|
||||
const subscribeToBrowserCapabilities = () => () => undefined;
|
||||
|
||||
function getSpeechSynthesisSupport() {
|
||||
return (
|
||||
typeof window.Audio !== "undefined" &&
|
||||
typeof window.URL !== "undefined" &&
|
||||
typeof window.fetch !== "undefined"
|
||||
);
|
||||
}
|
||||
|
||||
function getSpeechRecognitionSupport() {
|
||||
return "SpeechRecognition" in window || "webkitSpeechRecognition" in window;
|
||||
}
|
||||
|
||||
function getServerBrowserCapability() {
|
||||
return false;
|
||||
}
|
||||
|
||||
export function useAgentSpeechSynthesis() {
|
||||
const [speechState, setSpeechState] = useState<AgentSpeechState>("idle");
|
||||
const [speakingMessageId, setSpeakingMessageId] = useState<string | null>(null);
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
const currentAudioUrlRef = useRef<string | null>(null);
|
||||
const audioUrlsRef = useRef<Set<string>>(new Set());
|
||||
const fetchControllersRef = useRef<Set<AbortController>>(new Set());
|
||||
const chunkUrlCacheRef = useRef<Map<number, string>>(new Map());
|
||||
const chunkPromisesRef = useRef<Map<number, Promise<string>>>(new Map());
|
||||
const chunksRef = useRef<string[]>([]);
|
||||
const currentChunkIndexRef = useRef(0);
|
||||
const playbackTokenRef = useRef(0);
|
||||
const activeMessageIdRef = useRef<string | null>(null);
|
||||
const playChunkRef = useRef<(chunkIndex: number, playbackToken: number) => Promise<void>>(async () => undefined);
|
||||
|
||||
const isSupported = useSyncExternalStore(
|
||||
subscribeToBrowserCapabilities,
|
||||
getSpeechSynthesisSupport,
|
||||
getServerBrowserCapability
|
||||
);
|
||||
|
||||
const detachAudio = useCallback((revokeUrl: boolean) => {
|
||||
const audio = audioRef.current;
|
||||
audioRef.current = null;
|
||||
if (audio) {
|
||||
audio.pause();
|
||||
audio.onended = null;
|
||||
audio.onerror = null;
|
||||
audio.removeAttribute("src");
|
||||
audio.load();
|
||||
}
|
||||
|
||||
const currentUrl = currentAudioUrlRef.current;
|
||||
currentAudioUrlRef.current = null;
|
||||
if (revokeUrl && currentUrl) {
|
||||
URL.revokeObjectURL(currentUrl);
|
||||
audioUrlsRef.current.delete(currentUrl);
|
||||
chunkUrlCacheRef.current.delete(currentChunkIndexRef.current);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const releaseAudio = useCallback(() => {
|
||||
fetchControllersRef.current.forEach((controller) => controller.abort());
|
||||
fetchControllersRef.current.clear();
|
||||
chunkPromisesRef.current.clear();
|
||||
detachAudio(false);
|
||||
audioUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
audioUrlsRef.current.clear();
|
||||
chunkUrlCacheRef.current.clear();
|
||||
chunksRef.current = [];
|
||||
currentChunkIndexRef.current = 0;
|
||||
activeMessageIdRef.current = null;
|
||||
}, [detachAudio]);
|
||||
|
||||
const fetchChunkAudio = useCallback((chunkIndex: number, playbackToken: number) => {
|
||||
const cachedUrl = chunkUrlCacheRef.current.get(chunkIndex);
|
||||
if (cachedUrl) return Promise.resolve(cachedUrl);
|
||||
|
||||
const currentPromise = chunkPromisesRef.current.get(chunkIndex);
|
||||
if (currentPromise) return currentPromise;
|
||||
|
||||
const text = chunksRef.current[chunkIndex];
|
||||
if (!text) return Promise.reject(new Error("语音片段不存在"));
|
||||
|
||||
const controller = new AbortController();
|
||||
fetchControllersRef.current.add(controller);
|
||||
const promise = fetch("/api/tts/edge", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ text }),
|
||||
signal: controller.signal
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null) as { error?: string } | null;
|
||||
throw new Error(payload?.error ?? `语音生成失败 (${response.status})`);
|
||||
}
|
||||
const audioBlob = await response.blob();
|
||||
if (!audioBlob.size) throw new Error("语音服务返回了空音频");
|
||||
if (playbackToken !== playbackTokenRef.current) {
|
||||
throw new DOMException("语音播放已取消", "AbortError");
|
||||
}
|
||||
|
||||
const objectUrl = URL.createObjectURL(audioBlob);
|
||||
audioUrlsRef.current.add(objectUrl);
|
||||
chunkUrlCacheRef.current.set(chunkIndex, objectUrl);
|
||||
return objectUrl;
|
||||
})
|
||||
.finally(() => {
|
||||
fetchControllersRef.current.delete(controller);
|
||||
chunkPromisesRef.current.delete(chunkIndex);
|
||||
});
|
||||
|
||||
chunkPromisesRef.current.set(chunkIndex, promise);
|
||||
return promise;
|
||||
}, []);
|
||||
|
||||
const prefetchChunk = useCallback((chunkIndex: number, playbackToken: number) => {
|
||||
if (chunkIndex >= chunksRef.current.length) return;
|
||||
void fetchChunkAudio(chunkIndex, playbackToken).catch(() => undefined);
|
||||
}, [fetchChunkAudio]);
|
||||
|
||||
const playChunk = useCallback(async (chunkIndex: number, playbackToken: number) => {
|
||||
setSpeechState("loading");
|
||||
const objectUrl = await fetchChunkAudio(chunkIndex, playbackToken);
|
||||
if (playbackToken !== playbackTokenRef.current) return;
|
||||
|
||||
detachAudio(true);
|
||||
currentChunkIndexRef.current = chunkIndex;
|
||||
const audio = new Audio(objectUrl);
|
||||
audio.preload = "auto";
|
||||
audioRef.current = audio;
|
||||
currentAudioUrlRef.current = objectUrl;
|
||||
|
||||
audio.onended = () => {
|
||||
if (playbackToken !== playbackTokenRef.current) return;
|
||||
detachAudio(true);
|
||||
const nextChunkIndex = chunkIndex + 1;
|
||||
if (nextChunkIndex >= chunksRef.current.length) {
|
||||
releaseAudio();
|
||||
setSpeechState("idle");
|
||||
setSpeakingMessageId(null);
|
||||
return;
|
||||
}
|
||||
currentChunkIndexRef.current = nextChunkIndex;
|
||||
void playChunkRef.current(nextChunkIndex, playbackToken);
|
||||
};
|
||||
audio.onerror = () => {
|
||||
if (playbackToken !== playbackTokenRef.current) return;
|
||||
playbackTokenRef.current += 1;
|
||||
releaseAudio();
|
||||
setSpeechState("idle");
|
||||
setSpeakingMessageId(null);
|
||||
};
|
||||
|
||||
await audio.play();
|
||||
if (playbackToken !== playbackTokenRef.current) return;
|
||||
setSpeechState("playing");
|
||||
prefetchChunk(chunkIndex + 1, playbackToken);
|
||||
}, [detachAudio, fetchChunkAudio, prefetchChunk, releaseAudio]);
|
||||
|
||||
useEffect(() => {
|
||||
playChunkRef.current = playChunk;
|
||||
}, [playChunk]);
|
||||
|
||||
const speak = useCallback(async (messageId: string, text: string, options: AgentSpeakOptions = {}) => {
|
||||
const normalizedText = text.trim();
|
||||
if (!isSupported || !normalizedText) return;
|
||||
|
||||
const startOffset = Math.max(0, Math.min(options.startOffset ?? 0, normalizedText.length));
|
||||
const chunks = splitSpeechTextIntoChunks(normalizedText.slice(startOffset));
|
||||
if (!chunks.length) return;
|
||||
|
||||
const playbackToken = playbackTokenRef.current + 1;
|
||||
playbackTokenRef.current = playbackToken;
|
||||
releaseAudio();
|
||||
chunksRef.current = chunks;
|
||||
activeMessageIdRef.current = messageId;
|
||||
setSpeakingMessageId(messageId);
|
||||
setSpeechState("loading");
|
||||
|
||||
try {
|
||||
await playChunk(0, playbackToken);
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === "AbortError") return;
|
||||
releaseAudio();
|
||||
setSpeechState("idle");
|
||||
setSpeakingMessageId(null);
|
||||
}
|
||||
}, [isSupported, playChunk, releaseAudio]);
|
||||
|
||||
const pause = useCallback(() => {
|
||||
if (!audioRef.current || speechState !== "playing") return;
|
||||
audioRef.current.pause();
|
||||
setSpeechState("paused");
|
||||
}, [speechState]);
|
||||
|
||||
const resume = useCallback(() => {
|
||||
const audio = audioRef.current;
|
||||
if (!audio) return;
|
||||
setSpeakingMessageId(activeMessageIdRef.current);
|
||||
setSpeechState("playing");
|
||||
void audio.play().catch(() => {
|
||||
playbackTokenRef.current += 1;
|
||||
releaseAudio();
|
||||
setSpeechState("idle");
|
||||
setSpeakingMessageId(null);
|
||||
});
|
||||
}, [releaseAudio]);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
playbackTokenRef.current += 1;
|
||||
releaseAudio();
|
||||
setSpeechState("idle");
|
||||
setSpeakingMessageId(null);
|
||||
}, [releaseAudio]);
|
||||
|
||||
useEffect(() => () => {
|
||||
playbackTokenRef.current += 1;
|
||||
releaseAudio();
|
||||
}, [releaseAudio]);
|
||||
|
||||
return { speechState, speakingMessageId, speak, pause, resume, stop, isSupported };
|
||||
}
|
||||
|
||||
export function useAgentSpeechRecognition(onResult: (text: string) => void) {
|
||||
const [isListening, setIsListening] = useState(false);
|
||||
const recognitionRef = useRef<BrowserSpeechRecognition | null>(null);
|
||||
const onResultRef = useRef(onResult);
|
||||
const onErrorRef = useRef<(message: string) => void>(() => undefined);
|
||||
|
||||
useEffect(() => {
|
||||
onResultRef.current = onResult;
|
||||
}, [onResult]);
|
||||
|
||||
const isSupported = useSyncExternalStore(
|
||||
subscribeToBrowserCapabilities,
|
||||
getSpeechRecognitionSupport,
|
||||
getServerBrowserCapability
|
||||
);
|
||||
|
||||
const start = useCallback((onError?: (message: string) => void) => {
|
||||
if (!isSupported || recognitionRef.current) return;
|
||||
const Recognition = window.SpeechRecognition ?? window.webkitSpeechRecognition;
|
||||
if (!Recognition) return;
|
||||
|
||||
onErrorRef.current = onError ?? (() => undefined);
|
||||
|
||||
const recognition = new Recognition();
|
||||
recognition.lang = "zh-CN";
|
||||
recognition.continuous = true;
|
||||
recognition.interimResults = false;
|
||||
recognition.onresult = (event) => {
|
||||
for (let index = event.resultIndex; index < event.results.length; index += 1) {
|
||||
if (event.results[index].isFinal) {
|
||||
onResultRef.current(event.results[index][0].transcript);
|
||||
}
|
||||
}
|
||||
};
|
||||
recognition.onerror = (event) => {
|
||||
setIsListening(false);
|
||||
if (event.error !== "aborted") {
|
||||
onErrorRef.current(getSpeechRecognitionErrorMessage(event.error));
|
||||
}
|
||||
};
|
||||
recognition.onend = () => {
|
||||
if (recognitionRef.current === recognition) {
|
||||
recognitionRef.current = null;
|
||||
}
|
||||
setIsListening(false);
|
||||
};
|
||||
|
||||
recognitionRef.current = recognition;
|
||||
try {
|
||||
recognition.start();
|
||||
setIsListening(true);
|
||||
} catch {
|
||||
recognitionRef.current = null;
|
||||
setIsListening(false);
|
||||
onErrorRef.current("无法启动语音输入,请检查浏览器麦克风权限后重试");
|
||||
}
|
||||
}, [isSupported]);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
recognitionRef.current?.stop();
|
||||
recognitionRef.current = null;
|
||||
setIsListening(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => recognitionRef.current?.abort(), []);
|
||||
|
||||
return { isListening, start, stop, isSupported };
|
||||
}
|
||||
|
||||
function getSpeechRecognitionErrorMessage(error: string) {
|
||||
switch (error) {
|
||||
case "not-allowed":
|
||||
case "service-not-allowed":
|
||||
return "无法使用麦克风,请在浏览器地址栏允许麦克风权限后重试";
|
||||
case "audio-capture":
|
||||
return "未检测到可用麦克风,请检查设备连接";
|
||||
case "network":
|
||||
return "语音识别服务连接失败,请检查网络后重试";
|
||||
case "no-speech":
|
||||
return "未检测到语音,请靠近麦克风后重试";
|
||||
default:
|
||||
return "语音输入暂时不可用,请稍后重试";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
export { AgentCollapsedRail } from "./components/agent-collapsed-rail";
|
||||
export { AgentCommandPanel } from "./components/agent-command-panel";
|
||||
export { AgentPersona } from "./components/agent-persona";
|
||||
export { normalizeSafeChartData, parseChartSpec, pointToLabelValue } from "./chart-data";
|
||||
export {
|
||||
applyPermissionResponse,
|
||||
applyQuestionResponse,
|
||||
toTodoUpdate,
|
||||
upsertPermission,
|
||||
upsertProgress,
|
||||
upsertQuestion
|
||||
} from "./session-state";
|
||||
export type {
|
||||
AgentApprovalMode,
|
||||
AgentChatMessage,
|
||||
AgentChatProgress,
|
||||
AgentInteractionToolRef,
|
||||
AgentModelOption,
|
||||
AgentPermissionReply,
|
||||
AgentPermissionRequest,
|
||||
AgentPermissionStatus,
|
||||
AgentQuestionInfo,
|
||||
AgentQuestionOption,
|
||||
AgentQuestionRequest,
|
||||
AgentStreamRenderMessageState,
|
||||
AgentStreamRenderState,
|
||||
AgentTodoItem,
|
||||
AgentTodoUpdate,
|
||||
AgentUiResult
|
||||
} from "./types";
|
||||
export type {
|
||||
SafeChartData,
|
||||
SafeChartSeries,
|
||||
SafeChartSpec
|
||||
} from "./chart-data";
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyPermissionResponse,
|
||||
applyQuestionResponse,
|
||||
finalizeAssistantMessageAfterAbort,
|
||||
toTodoUpdate,
|
||||
upsertPermission,
|
||||
upsertProgress,
|
||||
upsertQuestion
|
||||
} from "./session-state";
|
||||
import type { AgentChatMessage } from "./types";
|
||||
|
||||
describe("agent session state", () => {
|
||||
it("upserts progress events by id", () => {
|
||||
const first = upsertProgress(undefined, {
|
||||
id: "tool-1",
|
||||
phase: "tool",
|
||||
status: "running",
|
||||
title: "调用工具",
|
||||
elapsed_ms: 20
|
||||
});
|
||||
const next = upsertProgress(first, {
|
||||
id: "tool-1",
|
||||
phase: "tool",
|
||||
status: "completed",
|
||||
title: "工具完成",
|
||||
duration_ms: 40
|
||||
});
|
||||
|
||||
expect(next).toHaveLength(1);
|
||||
expect(next[0]).toMatchObject({ id: "tool-1", status: "completed", title: "工具完成", durationMs: 40 });
|
||||
});
|
||||
|
||||
it("normalizes todo updates", () => {
|
||||
expect(
|
||||
toTodoUpdate({
|
||||
session_id: "session-1",
|
||||
todos: [{ id: "todo-1", content: "分析压力", status: "in_progress", priority: "high" }],
|
||||
created_at: 123
|
||||
})
|
||||
).toEqual({
|
||||
sessionId: "session-1",
|
||||
messageId: undefined,
|
||||
todos: [{ id: "todo-1", content: "分析压力", status: "in_progress", priority: "high" }],
|
||||
createdAt: 123
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks permission request and response", () => {
|
||||
const permissions = upsertPermission(undefined, {
|
||||
session_id: "session-1",
|
||||
request_id: "permission-1",
|
||||
permission: "bash",
|
||||
patterns: ["pnpm test"],
|
||||
always: [],
|
||||
created_at: 100
|
||||
});
|
||||
const next = applyPermissionResponse(permissions, {
|
||||
request_id: "permission-1",
|
||||
reply: "once"
|
||||
});
|
||||
|
||||
expect(next?.[0]).toMatchObject({
|
||||
requestId: "permission-1",
|
||||
status: "approved_once"
|
||||
});
|
||||
});
|
||||
|
||||
it("dedupes question requests by tool call id", () => {
|
||||
const questions = upsertQuestion(undefined, {
|
||||
session_id: "session-1",
|
||||
request_id: "call-1",
|
||||
tool: { messageID: "message-1", callID: "call-1" },
|
||||
questions: [{ header: "范围", question: "选择范围", options: [] }],
|
||||
created_at: 100
|
||||
});
|
||||
const next = upsertQuestion(questions, {
|
||||
session_id: "session-1",
|
||||
request_id: "question-1",
|
||||
tool: { messageID: "message-1", callID: "call-1" },
|
||||
questions: [{ header: "范围", question: "选择范围", options: [] }],
|
||||
created_at: 120
|
||||
});
|
||||
const answered = applyQuestionResponse(next, {
|
||||
request_id: "question-1",
|
||||
answers: [["东部"]]
|
||||
});
|
||||
|
||||
expect(next).toHaveLength(1);
|
||||
expect(answered?.[0]).toMatchObject({
|
||||
requestId: "question-1",
|
||||
status: "answered",
|
||||
answers: [["东部"]]
|
||||
});
|
||||
});
|
||||
|
||||
it("finalizes open assistant state after abort", () => {
|
||||
const message: AgentChatMessage = {
|
||||
id: "assistant-1",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
progress: [{ id: "run", phase: "run", status: "running", title: "处理中", startedAt: Date.now() }],
|
||||
permissions: [
|
||||
{
|
||||
requestId: "permission-1",
|
||||
sessionId: "session-1",
|
||||
permission: "bash",
|
||||
patterns: [],
|
||||
always: [],
|
||||
createdAt: 100,
|
||||
status: "pending"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const next = finalizeAssistantMessageAfterAbort(message);
|
||||
|
||||
expect(next.content).toBe("请求已中止。");
|
||||
expect(next.progress?.[0].status).toBe("completed");
|
||||
expect(next.permissions?.[0].status).toBe("aborted");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,362 @@
|
||||
import type {
|
||||
AgentChatMessage,
|
||||
AgentChatProgress,
|
||||
AgentInteractionToolRef,
|
||||
AgentPermissionRequest,
|
||||
AgentPermissionStatus,
|
||||
AgentQuestionInfo,
|
||||
AgentQuestionRequest,
|
||||
AgentTodoItem,
|
||||
AgentTodoUpdate
|
||||
} from "./types";
|
||||
|
||||
type RecordValue = Record<string, unknown>;
|
||||
|
||||
export function upsertProgress(progress: AgentChatProgress[] | undefined, data: unknown) {
|
||||
const payload = asRecord(data);
|
||||
const id = readString(payload.id) ?? `progress-${Date.now().toString(36)}`;
|
||||
const now = Date.now();
|
||||
const index = progress?.findIndex((item) => item.id === id) ?? -1;
|
||||
const existing = index >= 0 ? progress?.[index] : undefined;
|
||||
const status = readProgressStatus(payload.status);
|
||||
const startedAt = readNumber(payload.started_at) ?? readNumber(payload.startedAt) ?? existing?.startedAt;
|
||||
const endedAt = readNumber(payload.ended_at) ?? readNumber(payload.endedAt);
|
||||
const elapsedMs = readNumber(payload.elapsed_ms) ?? readNumber(payload.elapsedMs);
|
||||
const durationMs = readNumber(payload.duration_ms) ?? readNumber(payload.durationMs);
|
||||
const nextItem: AgentChatProgress = {
|
||||
id,
|
||||
phase: readString(payload.phase) ?? "progress",
|
||||
status,
|
||||
title: readString(payload.title) ?? "正在处理",
|
||||
detail: readString(payload.detail),
|
||||
startedAt,
|
||||
endedAt,
|
||||
elapsedMs: status === "running" ? elapsedMs : undefined,
|
||||
elapsedSnapshotAt: status === "running" && elapsedMs !== undefined ? now : undefined,
|
||||
durationMs: status === "running" ? undefined : durationMs
|
||||
};
|
||||
const next = [...(progress ?? [])];
|
||||
|
||||
if (index >= 0) {
|
||||
next[index] = nextItem;
|
||||
} else {
|
||||
next.push(nextItem);
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function completeRunningProgress(progress: AgentChatProgress[] | undefined) {
|
||||
return progress?.map((item) => {
|
||||
if (item.status !== "running") {
|
||||
return item;
|
||||
}
|
||||
|
||||
const endedAt = Date.now();
|
||||
return {
|
||||
...item,
|
||||
status: "completed" as const,
|
||||
endedAt,
|
||||
elapsedMs: undefined,
|
||||
elapsedSnapshotAt: undefined,
|
||||
durationMs:
|
||||
item.durationMs ??
|
||||
(item.startedAt !== undefined ? Math.max(0, endedAt - item.startedAt) : item.elapsedMs)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function toTodoUpdate(data: unknown): AgentTodoUpdate | null {
|
||||
const payload = asRecord(data);
|
||||
const sessionId = readString(payload.session_id) ?? readString(payload.sessionId);
|
||||
const rawTodos = Array.isArray(payload.todos) ? payload.todos : [];
|
||||
|
||||
if (!sessionId || rawTodos.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
messageId: readString(payload.message_id) ?? readString(payload.messageId),
|
||||
todos: rawTodos.map(toTodoItem).filter((item): item is AgentTodoItem => Boolean(item)),
|
||||
createdAt: readNumber(payload.created_at) ?? readNumber(payload.createdAt) ?? Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
export function cancelRunningTodos(todoUpdate: AgentTodoUpdate | undefined) {
|
||||
return todoUpdate
|
||||
? {
|
||||
...todoUpdate,
|
||||
todos: todoUpdate.todos.map((todo) =>
|
||||
todo.status === "pending" || todo.status === "in_progress"
|
||||
? {
|
||||
...todo,
|
||||
status: "cancelled" as const,
|
||||
updatedAt: Date.now()
|
||||
}
|
||||
: todo
|
||||
)
|
||||
}
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function upsertPermission(
|
||||
permissions: AgentPermissionRequest[] | undefined,
|
||||
data: unknown
|
||||
) {
|
||||
const payload = asRecord(data);
|
||||
const requestId = readString(payload.request_id) ?? readString(payload.requestId);
|
||||
const sessionId = readString(payload.session_id) ?? readString(payload.sessionId);
|
||||
|
||||
if (!requestId || !sessionId) {
|
||||
return permissions;
|
||||
}
|
||||
|
||||
const nextItem: AgentPermissionRequest = {
|
||||
requestId,
|
||||
sessionId,
|
||||
permission: readString(payload.permission) ?? "unknown",
|
||||
patterns: readStringArray(payload.patterns),
|
||||
target: readString(payload.target),
|
||||
always: readStringArray(payload.always),
|
||||
tool: toToolRef(payload.tool),
|
||||
createdAt: readNumber(payload.created_at) ?? readNumber(payload.createdAt) ?? Date.now(),
|
||||
status: "pending"
|
||||
};
|
||||
const next = [...(permissions ?? [])];
|
||||
const index = next.findIndex((permission) => permission.requestId === requestId);
|
||||
|
||||
if (index >= 0) {
|
||||
next[index] = {
|
||||
...next[index],
|
||||
...nextItem,
|
||||
status: next[index].status === "submitting" ? "submitting" : nextItem.status
|
||||
};
|
||||
} else {
|
||||
next.push(nextItem);
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function applyPermissionResponse(
|
||||
permissions: AgentPermissionRequest[] | undefined,
|
||||
data: unknown
|
||||
) {
|
||||
const payload = asRecord(data);
|
||||
const requestId = readString(payload.request_id) ?? readString(payload.requestId);
|
||||
if (!requestId) {
|
||||
return permissions;
|
||||
}
|
||||
|
||||
return permissions?.map((permission) =>
|
||||
permission.requestId === requestId
|
||||
? {
|
||||
...permission,
|
||||
status: toPermissionStatus(readString(payload.reply)),
|
||||
repliedAt: Date.now(),
|
||||
error: undefined
|
||||
}
|
||||
: permission
|
||||
);
|
||||
}
|
||||
|
||||
export function upsertQuestion(questions: AgentQuestionRequest[] | undefined, data: unknown) {
|
||||
const payload = asRecord(data);
|
||||
const requestId = readString(payload.request_id) ?? readString(payload.requestId);
|
||||
const sessionId = readString(payload.session_id) ?? readString(payload.sessionId);
|
||||
const rawQuestions = Array.isArray(payload.questions) ? payload.questions : [];
|
||||
|
||||
if (!requestId || !sessionId || rawQuestions.length === 0) {
|
||||
return questions;
|
||||
}
|
||||
|
||||
const nextItem: AgentQuestionRequest = {
|
||||
requestId,
|
||||
sessionId,
|
||||
questions: rawQuestions.map(toQuestionInfo).filter((item): item is AgentQuestionInfo => Boolean(item)),
|
||||
tool: toToolRef(payload.tool),
|
||||
createdAt: readNumber(payload.created_at) ?? readNumber(payload.createdAt) ?? Date.now(),
|
||||
status: "pending"
|
||||
};
|
||||
const next = [...(questions ?? [])];
|
||||
const index = next.findIndex((question) => isSameQuestion(question, nextItem));
|
||||
|
||||
if (index >= 0) {
|
||||
next[index] = {
|
||||
...next[index],
|
||||
...nextItem,
|
||||
status: next[index].status === "submitting" ? "submitting" : nextItem.status
|
||||
};
|
||||
} else {
|
||||
next.push(nextItem);
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function applyQuestionResponse(questions: AgentQuestionRequest[] | undefined, data: unknown) {
|
||||
const payload = asRecord(data);
|
||||
const requestId = readString(payload.request_id) ?? readString(payload.requestId);
|
||||
if (!requestId) {
|
||||
return questions;
|
||||
}
|
||||
|
||||
const answers = Array.isArray(payload.answers)
|
||||
? payload.answers.map((answer) => (Array.isArray(answer) ? answer.map(String) : []))
|
||||
: undefined;
|
||||
const rejected = payload.rejected === true;
|
||||
|
||||
return questions?.map((question) =>
|
||||
question.requestId === requestId
|
||||
? {
|
||||
...question,
|
||||
status: rejected ? ("rejected" as const) : ("answered" as const),
|
||||
answers: answers ?? question.answers,
|
||||
repliedAt: Date.now(),
|
||||
error: undefined
|
||||
}
|
||||
: question
|
||||
);
|
||||
}
|
||||
|
||||
export function finalizeAssistantMessageAfterAbort(message: AgentChatMessage): AgentChatMessage {
|
||||
const progress = completeRunningProgress(message.progress);
|
||||
const todos = cancelRunningTodos(message.todos);
|
||||
|
||||
return {
|
||||
...message,
|
||||
content: message.content || "请求已中止。",
|
||||
progress,
|
||||
todos,
|
||||
permissions: message.permissions?.map((permission) =>
|
||||
permission.status === "pending" || permission.status === "submitting" || permission.status === "error"
|
||||
? {
|
||||
...permission,
|
||||
status: "aborted" as const,
|
||||
repliedAt: Date.now(),
|
||||
error: undefined
|
||||
}
|
||||
: permission
|
||||
),
|
||||
questions: message.questions?.map((question) =>
|
||||
question.status === "pending" || question.status === "submitting" || question.status === "error"
|
||||
? {
|
||||
...question,
|
||||
status: "rejected" as const,
|
||||
repliedAt: Date.now(),
|
||||
error: undefined
|
||||
}
|
||||
: question
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
function toPermissionStatus(reply: string | undefined): AgentPermissionStatus {
|
||||
if (reply === "always") {
|
||||
return "approved_always";
|
||||
}
|
||||
if (reply === "once") {
|
||||
return "approved_once";
|
||||
}
|
||||
return "rejected";
|
||||
}
|
||||
|
||||
function isSameQuestion(left: AgentQuestionRequest, right: AgentQuestionRequest) {
|
||||
if (left.requestId === right.requestId) {
|
||||
return true;
|
||||
}
|
||||
return Boolean(left.tool?.callID && right.tool?.callID && left.tool.callID === right.tool.callID);
|
||||
}
|
||||
|
||||
function toQuestionInfo(value: unknown): AgentQuestionInfo | null {
|
||||
const payload = asRecord(value);
|
||||
const question = readString(payload.question);
|
||||
if (!question) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
header: readString(payload.header) ?? "",
|
||||
question,
|
||||
options: Array.isArray(payload.options)
|
||||
? payload.options
|
||||
.map((option) => {
|
||||
const item = asRecord(option);
|
||||
const label = readString(item.label);
|
||||
return label
|
||||
? {
|
||||
label,
|
||||
description: readString(item.description) ?? ""
|
||||
}
|
||||
: null;
|
||||
})
|
||||
.filter((item): item is { label: string; description: string } => Boolean(item))
|
||||
: [],
|
||||
multiple: typeof payload.multiple === "boolean" ? payload.multiple : undefined,
|
||||
custom: typeof payload.custom === "boolean" ? payload.custom : undefined
|
||||
};
|
||||
}
|
||||
|
||||
function toTodoItem(value: unknown): AgentTodoItem | null {
|
||||
const payload = asRecord(value);
|
||||
const id = readString(payload.id);
|
||||
const content = readString(payload.content);
|
||||
const status = readTodoStatus(payload.status);
|
||||
|
||||
if (!id || !content || !status) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
status,
|
||||
priority: readTodoPriority(payload.priority),
|
||||
createdAt: readNumber(payload.created_at) ?? readNumber(payload.createdAt),
|
||||
updatedAt: readNumber(payload.updated_at) ?? readNumber(payload.updatedAt)
|
||||
};
|
||||
}
|
||||
|
||||
function toToolRef(value: unknown): AgentInteractionToolRef | undefined {
|
||||
const payload = asRecord(value);
|
||||
const messageID = readString(payload.messageID);
|
||||
const callID = readString(payload.callID);
|
||||
return messageID && callID ? { messageID, callID } : undefined;
|
||||
}
|
||||
|
||||
function readProgressStatus(value: unknown): AgentChatProgress["status"] {
|
||||
return value === "completed" || value === "error" ? value : "running";
|
||||
}
|
||||
|
||||
function readTodoStatus(value: unknown): AgentTodoItem["status"] | undefined {
|
||||
if (value === "pending" || value === "in_progress" || value === "completed" || value === "cancelled") {
|
||||
return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readTodoPriority(value: unknown): AgentTodoItem["priority"] | undefined {
|
||||
if (value === "low" || value === "medium" || value === "high") {
|
||||
return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): RecordValue {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? (value as RecordValue)
|
||||
: {};
|
||||
}
|
||||
|
||||
function readString(value: unknown) {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function readNumber(value: unknown) {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function readStringArray(value: unknown) {
|
||||
return Array.isArray(value) ? value.map((item) => String(item).trim()).filter(Boolean) : [];
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
findSpeechSelectionStartOffset,
|
||||
splitSpeechTextIntoChunks,
|
||||
stripSpeechMarkdown
|
||||
} from "./speech";
|
||||
|
||||
describe("Agent 语音文本处理", () => {
|
||||
it("定位经过空白压缩的选择文本", () => {
|
||||
const text = "第一段内容。\n第二段 包含空格。";
|
||||
expect(findSpeechSelectionStartOffset(text, "第二段 包含空格")).toBe(text.indexOf("第二段"));
|
||||
expect(findSpeechSelectionStartOffset(text, "不存在")).toBeNull();
|
||||
});
|
||||
|
||||
it("按句子拆分长文本", () => {
|
||||
const chunks = splitSpeechTextIntoChunks(`${"甲".repeat(260)}。${"乙".repeat(260)}。`);
|
||||
expect(chunks).toHaveLength(2);
|
||||
expect(chunks.join("")).toContain("乙");
|
||||
});
|
||||
|
||||
it("移除会干扰朗读的 Markdown 标记", () => {
|
||||
expect(stripSpeechMarkdown("## 分析结果\n**水位** [详情](https://example.com)")).toBe("分析结果\n水位 详情");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
const compactWhitespace = (value: string) => value.replace(/\s+/g, " ").trim();
|
||||
const MAX_SPEECH_CHUNK_LENGTH = 520;
|
||||
const MIN_SPEECH_CHUNK_LENGTH = 180;
|
||||
const SPEECH_SENTENCE_PATTERN = /[^。!?!?;;\n]+(?:[。!?!?;;]+|(?=\n|$))/g;
|
||||
|
||||
export type AgentSpeechState = "idle" | "loading" | "playing" | "paused";
|
||||
|
||||
export type AgentSpeakOptions = {
|
||||
startOffset?: number;
|
||||
};
|
||||
|
||||
const normalizeWithOffsetMap = (value: string) => {
|
||||
let normalized = "";
|
||||
const offsetMap: number[] = [];
|
||||
let previousWasWhitespace = false;
|
||||
|
||||
Array.from(value).forEach((character, index) => {
|
||||
if (/\s/u.test(character)) {
|
||||
if (!previousWasWhitespace && normalized.length > 0) {
|
||||
normalized += " ";
|
||||
offsetMap.push(index);
|
||||
}
|
||||
previousWasWhitespace = true;
|
||||
return;
|
||||
}
|
||||
|
||||
normalized += character;
|
||||
offsetMap.push(index);
|
||||
previousWasWhitespace = false;
|
||||
});
|
||||
|
||||
return { normalized: normalized.trimEnd(), offsetMap };
|
||||
};
|
||||
|
||||
export function stripSpeechMarkdown(markdown: string) {
|
||||
return markdown
|
||||
.replace(/```[\s\S]*?```/g, "")
|
||||
.replace(/`([^`]+)`/g, "$1")
|
||||
.replace(/!\[.*?\]\(.*?\)/g, "")
|
||||
.replace(/\[([^\]]+)\]\(.*?\)/g, "$1")
|
||||
.replace(/#{1,6}\s+/g, "")
|
||||
.replace(/\*{1,3}(.+?)\*{1,3}/g, "$1")
|
||||
.replace(/~~(.+?)~~/g, "$1")
|
||||
.replace(/^>\s+/gm, "")
|
||||
.replace(/^[-*+]\s+/gm, "")
|
||||
.replace(/^\d+\.\s+/gm, "")
|
||||
.replace(/<[^>]+>/g, "")
|
||||
.replace(/\n{2,}/g, "\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function findSpeechSelectionStartOffset(text: string, selectedText: string): number | null {
|
||||
const needle = selectedText.trim();
|
||||
if (!needle) return null;
|
||||
|
||||
const exactIndex = text.indexOf(needle);
|
||||
if (exactIndex >= 0) return exactIndex;
|
||||
|
||||
const normalizedNeedle = compactWhitespace(needle);
|
||||
if (!normalizedNeedle) return null;
|
||||
|
||||
const haystack = normalizeWithOffsetMap(text);
|
||||
const normalizedIndex = haystack.normalized.indexOf(normalizedNeedle);
|
||||
if (normalizedIndex < 0) return null;
|
||||
|
||||
return haystack.offsetMap[normalizedIndex] ?? null;
|
||||
}
|
||||
|
||||
export function splitSpeechTextIntoChunks(text: string): string[] {
|
||||
const normalizedText = text.trim();
|
||||
if (!normalizedText) return [];
|
||||
|
||||
const segments = Array.from(normalizedText.matchAll(SPEECH_SENTENCE_PATTERN), (match) =>
|
||||
compactWhitespace(match[0])
|
||||
).filter(Boolean);
|
||||
const sourceSegments = segments.length > 0 ? segments : [normalizedText];
|
||||
const chunks: string[] = [];
|
||||
let currentChunk = "";
|
||||
|
||||
const flush = () => {
|
||||
if (!currentChunk) return;
|
||||
chunks.push(currentChunk);
|
||||
currentChunk = "";
|
||||
};
|
||||
|
||||
for (const segment of sourceSegments) {
|
||||
if (segment.length > MAX_SPEECH_CHUNK_LENGTH) {
|
||||
flush();
|
||||
for (let offset = 0; offset < segment.length; offset += MAX_SPEECH_CHUNK_LENGTH) {
|
||||
chunks.push(segment.slice(offset, offset + MAX_SPEECH_CHUNK_LENGTH));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const candidate = currentChunk ? `${currentChunk}${segment}` : segment;
|
||||
if (
|
||||
currentChunk &&
|
||||
candidate.length > MAX_SPEECH_CHUNK_LENGTH &&
|
||||
currentChunk.length >= MIN_SPEECH_CHUNK_LENGTH
|
||||
) {
|
||||
flush();
|
||||
currentChunk = segment;
|
||||
continue;
|
||||
}
|
||||
|
||||
currentChunk = candidate;
|
||||
}
|
||||
|
||||
flush();
|
||||
return chunks;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("StreamingTokenResponse", () => {
|
||||
it("renders the backend-smoothed stream without a second timer buffer", () => {
|
||||
const source = readFileSync(
|
||||
join(process.cwd(), "src/features/agent/components/streaming-token-response.tsx"),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
expect(source).not.toContain("setInterval");
|
||||
expect(source).not.toContain("useState");
|
||||
expect(source).not.toContain("streaming-token-response-state");
|
||||
expect(source).toContain("{content}");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("Streamdown fullscreen table", () => {
|
||||
it("disables inherited token animations only inside the fullscreen copy", () => {
|
||||
const styles = readFileSync(join(process.cwd(), "src/styles.css"), "utf8");
|
||||
|
||||
expect(styles).toMatch(
|
||||
/\[data-streamdown="table-fullscreen"\] \[data-sd-animate\] \{\s*animation: none;\s*filter: none;\s*opacity: 1;\s*transform: none;\s*\}/
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
export type AgentChatMessage = {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
progress?: AgentChatProgress[];
|
||||
permissions?: AgentPermissionRequest[];
|
||||
questions?: AgentQuestionRequest[];
|
||||
todos?: AgentTodoUpdate;
|
||||
};
|
||||
|
||||
export type AgentStreamRenderMessageState = {
|
||||
done: boolean;
|
||||
};
|
||||
|
||||
export type AgentStreamRenderState = Record<string, AgentStreamRenderMessageState>;
|
||||
|
||||
export type AgentChatProgress = {
|
||||
id: string;
|
||||
phase: string;
|
||||
status: "running" | "completed" | "error";
|
||||
title: string;
|
||||
detail?: string;
|
||||
startedAt?: number;
|
||||
endedAt?: number;
|
||||
elapsedMs?: number;
|
||||
elapsedSnapshotAt?: number;
|
||||
durationMs?: number;
|
||||
};
|
||||
|
||||
export type AgentPermissionStatus =
|
||||
| "pending"
|
||||
| "submitting"
|
||||
| "approved_once"
|
||||
| "approved_always"
|
||||
| "rejected"
|
||||
| "aborted"
|
||||
| "error";
|
||||
|
||||
export type AgentPermissionReply = "once" | "always" | "reject";
|
||||
|
||||
export type AgentApprovalMode = "request" | "always";
|
||||
|
||||
export type AgentModelOption = {
|
||||
id: string;
|
||||
label: string;
|
||||
description: string;
|
||||
icon: "bolt" | "sparkle";
|
||||
};
|
||||
|
||||
export type AgentPermissionRequest = {
|
||||
requestId: string;
|
||||
sessionId: string;
|
||||
permission: string;
|
||||
patterns: string[];
|
||||
target?: string;
|
||||
always: string[];
|
||||
tool?: AgentInteractionToolRef;
|
||||
createdAt: number;
|
||||
repliedAt?: number;
|
||||
status: AgentPermissionStatus;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type AgentQuestionOption = {
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
export type AgentQuestionInfo = {
|
||||
header: string;
|
||||
question: string;
|
||||
options: AgentQuestionOption[];
|
||||
multiple?: boolean;
|
||||
custom?: boolean;
|
||||
};
|
||||
|
||||
export type AgentQuestionRequest = {
|
||||
requestId: string;
|
||||
sessionId: string;
|
||||
questions: AgentQuestionInfo[];
|
||||
tool?: AgentInteractionToolRef;
|
||||
createdAt: number;
|
||||
repliedAt?: number;
|
||||
status: "pending" | "submitting" | "answered" | "rejected" | "error";
|
||||
answers?: string[][];
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type AgentTodoItem = {
|
||||
id: string;
|
||||
content: string;
|
||||
status: "pending" | "in_progress" | "completed" | "cancelled";
|
||||
priority?: "low" | "medium" | "high";
|
||||
createdAt?: number;
|
||||
updatedAt?: number;
|
||||
};
|
||||
|
||||
export type AgentTodoUpdate = {
|
||||
sessionId: string;
|
||||
messageId?: string;
|
||||
todos: AgentTodoItem[];
|
||||
createdAt: number;
|
||||
};
|
||||
|
||||
export type AgentInteractionToolRef = {
|
||||
messageID: string;
|
||||
callID: string;
|
||||
};
|
||||
|
||||
export type AgentUiResult = {
|
||||
id: string;
|
||||
sessionId: string;
|
||||
createdAt: number;
|
||||
envelope: import("./ui-envelope").UIEnvelope;
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
export type { UIEnvelope, UIEnvelopePayload, UIRegistry, UISurface } from "./types";
|
||||
export { toTrustedMapAction, type TrustedMapAction } from "./map-actions";
|
||||
export {
|
||||
isUiEnvelopeAllowed,
|
||||
parseUiEnvelope,
|
||||
parseUiEnvelopePayload,
|
||||
parseUiRegistry
|
||||
} from "./validator";
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { toTrustedMapAction } from "./map-actions";
|
||||
|
||||
describe("toTrustedMapAction", () => {
|
||||
it("rejects zoom_to_map actions without a valid center", () => {
|
||||
expect(toTrustedMapAction("zoom_to_map", { zoom: 14 })).toBeNull();
|
||||
expect(toTrustedMapAction("zoom_to_map", { center: ["east", 39.1] })).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects unsupported map actions", () => {
|
||||
expect(toTrustedMapAction("run_javascript", { code: "alert(1)" })).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects malformed or empty apply_layer_style params", () => {
|
||||
expect(
|
||||
toTrustedMapAction("apply_layer_style", {
|
||||
layer_group_id: 123,
|
||||
layer_id: [],
|
||||
visible: "true"
|
||||
})
|
||||
).toBeNull();
|
||||
expect(toTrustedMapAction("apply_layer_style", {})).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects out-of-range coordinates and zoom", () => {
|
||||
expect(toTrustedMapAction("zoom_to_map", { center: [181, 39.1] })).toBeNull();
|
||||
expect(toTrustedMapAction("zoom_to_map", { center: [117.2, -91] })).toBeNull();
|
||||
expect(toTrustedMapAction("zoom_to_map", { center: [117.2, 39.1], zoom: 25 })).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects empty and oversized locate requests", () => {
|
||||
expect(toTrustedMapAction("locate_features", { ids: [] })).toBeNull();
|
||||
expect(toTrustedMapAction("locate_features", { ids: Array.from({ length: 101 }, (_, index) => `P${index}`) })).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts valid zoom_to_map coordinates", () => {
|
||||
expect(toTrustedMapAction("zoom_to_map", { lng: 117.2, lat: 39.1, zoom: 13 })).toEqual({
|
||||
type: "zoom_to_map",
|
||||
center: [117.2, 39.1],
|
||||
zoom: 13,
|
||||
fallbackText: undefined
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts legacy zoom coordinate aliases and numeric strings", () => {
|
||||
expect(toTrustedMapAction("zoom_to_map", { coordinate: ["117.2", "39.1"], zoom: "13" })).toEqual({
|
||||
type: "zoom_to_map",
|
||||
center: [117.2, 39.1],
|
||||
zoom: 13,
|
||||
fallbackText: undefined
|
||||
});
|
||||
expect(toTrustedMapAction("zoom_to_map", { x: "117.2", y: "39.1" })).toMatchObject({
|
||||
type: "zoom_to_map",
|
||||
center: [117.2, 39.1]
|
||||
});
|
||||
});
|
||||
|
||||
it("converts EPSG:3857 zoom coordinates", () => {
|
||||
const action = toTrustedMapAction("zoom_to_map", { x: 13046644.321, y: 4736005.854, source_crs: "EPSG:3857" });
|
||||
|
||||
expect(action?.type).toBe("zoom_to_map");
|
||||
expect(action?.type === "zoom_to_map" ? action.center[0] : undefined).toBeCloseTo(117.2, 3);
|
||||
expect(action?.type === "zoom_to_map" ? action.center[1] : undefined).toBeCloseTo(39.1, 3);
|
||||
});
|
||||
|
||||
it("normalizes legacy locate tool actions", () => {
|
||||
expect(toTrustedMapAction("locate_pipes", { pipe_ids: "P1,P2" })).toEqual({
|
||||
type: "locate_features",
|
||||
featureIds: ["P1", "P2"],
|
||||
layer: "geo_pipes_mat",
|
||||
fallbackText: undefined
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes numeric locate ids", () => {
|
||||
expect(toTrustedMapAction("locate_junctions", { junction_id: 42 })).toMatchObject({
|
||||
type: "locate_features",
|
||||
featureIds: ["42"],
|
||||
layer: "geo_junctions_mat"
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts supply layer visibility and scada locate actions", () => {
|
||||
expect(toTrustedMapAction("apply_layer_style", { layer_id: "scada", visible: false })).toMatchObject({
|
||||
type: "apply_layer_style",
|
||||
layerId: "scada",
|
||||
visible: false
|
||||
});
|
||||
expect(toTrustedMapAction("locate_scada", { scada_id: "S-1" })).toMatchObject({
|
||||
type: "locate_features",
|
||||
featureIds: ["S-1"],
|
||||
layer: "geo_scada"
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
export type TrustedMapAction =
|
||||
| {
|
||||
type: "locate_features";
|
||||
featureIds: string[];
|
||||
layer?: string;
|
||||
fallbackText?: string;
|
||||
}
|
||||
| {
|
||||
type: "zoom_to_map";
|
||||
center: [number, number];
|
||||
zoom?: number;
|
||||
durationMs?: number;
|
||||
fallbackText?: string;
|
||||
}
|
||||
| {
|
||||
type: "apply_layer_style";
|
||||
layerGroupId?: string;
|
||||
layerId?: string;
|
||||
visible?: boolean;
|
||||
fallbackText?: string;
|
||||
}
|
||||
| {
|
||||
type: "render_junctions";
|
||||
renderRef: string;
|
||||
fallbackText?: string;
|
||||
};
|
||||
|
||||
export function toTrustedMapAction(action: string, params: unknown, fallbackText?: string): TrustedMapAction | null {
|
||||
if (!isRecord(params)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (action === "locate_features" || action in LEGACY_LOCATE_ACTION_LAYERS) {
|
||||
const featureIds = readLocateIds(params);
|
||||
if (featureIds.length === 0 || featureIds.length > 100 || featureIds.some((id) => id.length > 128)) return null;
|
||||
return {
|
||||
type: "locate_features",
|
||||
featureIds,
|
||||
layer:
|
||||
stringValue(params.layer ?? params.target_layer ?? params.targetLayer) ??
|
||||
LEGACY_LOCATE_ACTION_LAYERS[action],
|
||||
fallbackText
|
||||
};
|
||||
}
|
||||
|
||||
if (action === "zoom_to_map") {
|
||||
const center = parseCenter(params);
|
||||
if (!center) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const zoom = numberValue(params.zoom);
|
||||
const durationMs = numberValue(params.duration_ms ?? params.durationMs);
|
||||
if (center[0] < -180 || center[0] > 180 || center[1] < -90 || center[1] > 90 ||
|
||||
(zoom !== undefined && (zoom < 0 || zoom > 24))) return null;
|
||||
|
||||
return {
|
||||
type: "zoom_to_map",
|
||||
center,
|
||||
zoom,
|
||||
...(durationMs === undefined ? {} : { durationMs }),
|
||||
fallbackText
|
||||
};
|
||||
}
|
||||
|
||||
if (action === "apply_layer_style") {
|
||||
const layerGroupId = stringValue(params.layer_group_id ?? params.layerGroupId);
|
||||
const layerId = stringValue(params.layer_id ?? params.layerId);
|
||||
const visible = booleanValue(params.visible);
|
||||
if ((!layerGroupId && !layerId) || visible === undefined || (layerId && !ALLOWED_LAYER_IDS.has(layerId))) return null;
|
||||
return {
|
||||
type: "apply_layer_style",
|
||||
layerGroupId,
|
||||
layerId,
|
||||
visible,
|
||||
fallbackText
|
||||
};
|
||||
}
|
||||
|
||||
if (action === "render_junctions") {
|
||||
const renderRef = stringValue(params.render_ref ?? params.renderRef);
|
||||
if (!renderRef || !RESULT_REF_PATTERN.test(renderRef)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
type: "render_junctions",
|
||||
renderRef,
|
||||
fallbackText
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseCenter(params: Record<string, unknown>): [number, number] | null {
|
||||
const sourceCrs = params.source_crs ?? params.sourceCrs;
|
||||
|
||||
if (Array.isArray(params.center) && params.center.length >= 2) {
|
||||
const lng = numberValue(params.center[0]);
|
||||
const lat = numberValue(params.center[1]);
|
||||
return lng === undefined || lat === undefined ? null : normalizeCenter(lng, lat, sourceCrs);
|
||||
}
|
||||
|
||||
const rawCoordinate = params.coordinate ?? params.coordinates;
|
||||
if (Array.isArray(rawCoordinate) && rawCoordinate.length >= 2) {
|
||||
const lng = numberValue(rawCoordinate[0]);
|
||||
const lat = numberValue(rawCoordinate[1]);
|
||||
return lng === undefined || lat === undefined ? null : normalizeCenter(lng, lat, sourceCrs);
|
||||
}
|
||||
|
||||
const lng = numberValue(params.lng ?? params.lon ?? params.longitude ?? params.x);
|
||||
const lat = numberValue(params.lat ?? params.latitude ?? params.y);
|
||||
return lng === undefined || lat === undefined ? null : normalizeCenter(lng, lat, sourceCrs);
|
||||
}
|
||||
|
||||
function normalizeCenter(x: number, y: number, sourceCrs: unknown): [number, number] {
|
||||
if (sourceCrs === "EPSG:3857") {
|
||||
return webMercatorToLngLat(x, y);
|
||||
}
|
||||
|
||||
return [x, y];
|
||||
}
|
||||
|
||||
function webMercatorToLngLat(x: number, y: number): [number, number] {
|
||||
const lng = (x / WEB_MERCATOR_RADIUS) * (180 / Math.PI);
|
||||
const lat = (2 * Math.atan(Math.exp(y / WEB_MERCATOR_RADIUS)) - Math.PI / 2) * (180 / Math.PI);
|
||||
|
||||
return [lng, lat];
|
||||
}
|
||||
|
||||
function stringValue(value: unknown) {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function numberValue(value: unknown) {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown) {
|
||||
return typeof value === "boolean" ? value : undefined;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
const LEGACY_LOCATE_ACTION_LAYERS: Record<string, string> = {
|
||||
locate_junctions: "geo_junctions_mat",
|
||||
locate_pipes: "geo_pipes_mat",
|
||||
locate_valves: "geo_valves",
|
||||
locate_reservoirs: "geo_reservoirs",
|
||||
locate_scada: "geo_scada",
|
||||
locate_pumps: "geo_pumps",
|
||||
locate_tanks: "geo_tanks"
|
||||
};
|
||||
|
||||
const RESULT_REF_PATTERN = /^res-[A-Za-z0-9_-]{8,128}$/;
|
||||
const ALLOWED_LAYER_IDS = new Set(["junctions", "pipes", "valves", "reservoirs", "scada"]);
|
||||
const WEB_MERCATOR_RADIUS = 6378137;
|
||||
|
||||
const LOCATE_ID_PARAM_KEYS = [
|
||||
"feature_ids",
|
||||
"feature_id",
|
||||
"featureIds",
|
||||
"featureId",
|
||||
"ids",
|
||||
"id",
|
||||
"node_ids",
|
||||
"node_id",
|
||||
"junction_ids",
|
||||
"junction_id",
|
||||
"pipe_ids",
|
||||
"pipe_id",
|
||||
"valve_ids",
|
||||
"valve_id",
|
||||
"reservoir_ids",
|
||||
"reservoir_id",
|
||||
"scada_ids",
|
||||
"scada_id",
|
||||
"pump_ids",
|
||||
"pump_id",
|
||||
"tank_ids",
|
||||
"tank_id"
|
||||
] as const;
|
||||
|
||||
function readLocateIds(params: Record<string, unknown>) {
|
||||
for (const key of LOCATE_ID_PARAM_KEYS) {
|
||||
const value = params[key];
|
||||
const ids = normalizeIds(value);
|
||||
if (ids.length > 0) {
|
||||
return ids;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function normalizeIds(value: unknown) {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => String(item).trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
if (typeof value === "string" || typeof value === "number") {
|
||||
return String(value)
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
export type UISurface = "chat_inline" | "side_panel" | "canvas" | "map_overlay";
|
||||
|
||||
export type UIEnvelope =
|
||||
| {
|
||||
kind: "registered_component";
|
||||
schemaVersion: "agent-ui@1";
|
||||
component: string;
|
||||
surface: UISurface;
|
||||
props: unknown;
|
||||
data?: unknown;
|
||||
fallbackText?: string;
|
||||
}
|
||||
| {
|
||||
kind: "chart";
|
||||
schemaVersion: "agent-ui@1";
|
||||
grammar: "echarts-safe-subset";
|
||||
surface: "chat_inline" | "side_panel" | "canvas";
|
||||
spec: unknown;
|
||||
data: unknown;
|
||||
fallbackText?: string;
|
||||
}
|
||||
| {
|
||||
kind: "map_action";
|
||||
schemaVersion: "agent-ui@1";
|
||||
action: string;
|
||||
surface: "map_overlay";
|
||||
params: unknown;
|
||||
fallbackText?: string;
|
||||
};
|
||||
|
||||
export type UIEnvelopePayload = {
|
||||
session_id: string;
|
||||
envelope_id: string;
|
||||
created_at: number;
|
||||
envelope: UIEnvelope;
|
||||
};
|
||||
|
||||
export type UIRegistry = {
|
||||
schema_version: "agent-ui-registry@1";
|
||||
chart_grammars: string[];
|
||||
components: Array<{ id: string; supportedSurfaces: UISurface[] }>;
|
||||
actions: Array<{ id: string; supportedSurfaces: UISurface[] }>;
|
||||
};
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isUiEnvelopeAllowed, parseUiEnvelope, parseUiRegistry } from "./validator";
|
||||
import type { UIRegistry } from "./types";
|
||||
|
||||
const registry: UIRegistry = {
|
||||
schema_version: "agent-ui-registry@1",
|
||||
chart_grammars: ["echarts-safe-subset"],
|
||||
components: [{ id: "HistoryPanel", supportedSurfaces: ["side_panel", "canvas"] }],
|
||||
actions: [{ id: "zoom_to_map", supportedSurfaces: ["map_overlay"] }]
|
||||
};
|
||||
|
||||
describe("UIEnvelope validation", () => {
|
||||
it("fails closed when the backend registry is unavailable", () => {
|
||||
const envelope = parseUiEnvelope({
|
||||
kind: "chart",
|
||||
schemaVersion: "agent-ui@1",
|
||||
grammar: "echarts-safe-subset",
|
||||
surface: "chat_inline",
|
||||
spec: { chart_type: "line" },
|
||||
data: { x_data: ["a"], series: [{ name: "s", data: [1] }] }
|
||||
});
|
||||
expect(envelope).not.toBeNull();
|
||||
expect(envelope ? isUiEnvelopeAllowed(envelope, null) : true).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects registered components outside the frontend allowlist", () => {
|
||||
const envelope = parseUiEnvelope({
|
||||
kind: "registered_component",
|
||||
schemaVersion: "agent-ui@1",
|
||||
component: "UnsafePanel",
|
||||
surface: "side_panel",
|
||||
props: {}
|
||||
});
|
||||
|
||||
expect(envelope).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects registered components on unsupported surfaces", () => {
|
||||
const envelope = parseUiEnvelope({
|
||||
kind: "registered_component",
|
||||
schemaVersion: "agent-ui@1",
|
||||
component: "HistoryPanel",
|
||||
surface: "chat_inline",
|
||||
props: { feature_infos: [["J1", "junction"]], data_type: "realtime" }
|
||||
});
|
||||
|
||||
expect(envelope).not.toBeNull();
|
||||
expect(envelope ? isUiEnvelopeAllowed(envelope, registry) : false).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts only the echarts-safe-subset chart grammar", () => {
|
||||
expect(
|
||||
parseUiEnvelope({
|
||||
kind: "chart",
|
||||
schemaVersion: "agent-ui@1",
|
||||
grammar: "vega-lite",
|
||||
surface: "chat_inline",
|
||||
spec: { chart_type: "line" },
|
||||
data: { x_data: ["a"], series: [{ name: "s", data: [1] }] }
|
||||
})
|
||||
).toBeNull();
|
||||
|
||||
const envelope = parseUiEnvelope({
|
||||
kind: "chart",
|
||||
schemaVersion: "agent-ui@1",
|
||||
grammar: "echarts-safe-subset",
|
||||
surface: "chat_inline",
|
||||
spec: { chart_type: "line" },
|
||||
data: { x_data: ["a"], series: [{ name: "s", data: [1] }] }
|
||||
});
|
||||
|
||||
expect(envelope).not.toBeNull();
|
||||
expect(envelope ? isUiEnvelopeAllowed(envelope, registry) : false).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects unsupported chart types and mismatched data", () => {
|
||||
expect(parseUiEnvelope({
|
||||
kind: "chart",
|
||||
schemaVersion: "agent-ui@1",
|
||||
grammar: "echarts-safe-subset",
|
||||
surface: "chat_inline",
|
||||
spec: { chart_type: "pie" },
|
||||
data: { x_data: ["a"], series: [{ name: "s", data: [1] }] }
|
||||
})).toBeNull();
|
||||
expect(parseUiEnvelope({
|
||||
kind: "chart",
|
||||
schemaVersion: "agent-ui@1",
|
||||
grammar: "echarts-safe-subset",
|
||||
surface: "chat_inline",
|
||||
spec: { chart_type: "line" },
|
||||
data: { x_data: ["a", "b"], series: [{ name: "s", data: [1] }] }
|
||||
})).toBeNull();
|
||||
});
|
||||
|
||||
it("filters invalid registry surfaces before allowlist checks", () => {
|
||||
const parsed = parseUiRegistry({
|
||||
schema_version: "agent-ui-registry@1",
|
||||
chart_grammars: ["echarts-safe-subset"],
|
||||
components: [{ id: "HistoryPanel", supportedSurfaces: ["side_panel", "unsafe_surface"] }],
|
||||
actions: []
|
||||
});
|
||||
|
||||
expect(parsed?.components[0]?.supportedSurfaces).toEqual(["side_panel"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import { normalizeSafeChartData, parseChartSpec } from "../chart-data";
|
||||
import { toTrustedMapAction } from "./map-actions";
|
||||
import type { UIEnvelope, UIEnvelopePayload, UIRegistry, UISurface } from "./types";
|
||||
|
||||
const surfaces = new Set<UISurface>(["chat_inline", "side_panel", "canvas", "map_overlay"]);
|
||||
const MAX_ID_LENGTH = 128;
|
||||
const LOCAL_COMPONENT_SURFACES = new Map<string, UISurface[]>([
|
||||
["HistoryPanel", ["side_panel", "canvas"]]
|
||||
]);
|
||||
const LOCAL_ACTION_SURFACES = new Map<string, UISurface[]>([
|
||||
["locate_features", ["map_overlay"]],
|
||||
["zoom_to_map", ["map_overlay"]],
|
||||
["render_junctions", ["map_overlay"]],
|
||||
["apply_layer_style", ["map_overlay"]]
|
||||
]);
|
||||
|
||||
export function parseUiEnvelopePayload(value: unknown): UIEnvelopePayload | null {
|
||||
if (!isRecord(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const envelope = parseUiEnvelope(value.envelope);
|
||||
if (!envelope) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionId = boundedString(value.session_id, MAX_ID_LENGTH);
|
||||
const envelopeId = boundedString(value.envelope_id, MAX_ID_LENGTH);
|
||||
if (!sessionId || !envelopeId || !isFiniteTimestamp(value.created_at)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
session_id: sessionId,
|
||||
envelope_id: envelopeId,
|
||||
created_at: value.created_at,
|
||||
envelope
|
||||
};
|
||||
}
|
||||
|
||||
export function parseUiEnvelope(value: unknown): UIEnvelope | null {
|
||||
if (!isRecord(value) || value.schemaVersion !== "agent-ui@1") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value.kind === "registered_component") {
|
||||
if (typeof value.component !== "string" || !isSurface(value.surface) || !isValidComponentProps(value.component, value.props)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "registered_component",
|
||||
schemaVersion: "agent-ui@1",
|
||||
component: value.component,
|
||||
surface: value.surface,
|
||||
props: value.props,
|
||||
data: value.data,
|
||||
fallbackText: optionalString(value.fallbackText)
|
||||
};
|
||||
}
|
||||
|
||||
if (value.kind === "chart") {
|
||||
if (value.grammar !== "echarts-safe-subset" || !isChartSurface(value.surface) || !isValidChart(value.spec, value.data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "chart",
|
||||
schemaVersion: "agent-ui@1",
|
||||
grammar: "echarts-safe-subset",
|
||||
surface: value.surface,
|
||||
spec: value.spec,
|
||||
data: value.data,
|
||||
fallbackText: optionalString(value.fallbackText)
|
||||
};
|
||||
}
|
||||
|
||||
if (value.kind === "map_action") {
|
||||
if (typeof value.action !== "string" || value.surface !== "map_overlay" || !toTrustedMapAction(value.action, value.params)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "map_action",
|
||||
schemaVersion: "agent-ui@1",
|
||||
action: value.action,
|
||||
surface: "map_overlay",
|
||||
params: value.params,
|
||||
fallbackText: optionalString(value.fallbackText)
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isUiEnvelopeAllowed(envelope: UIEnvelope, registry: UIRegistry | null) {
|
||||
if (!registry) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (envelope.kind === "registered_component") {
|
||||
if (!LOCAL_COMPONENT_SURFACES.get(envelope.component)?.includes(envelope.surface)) return false;
|
||||
const manifest = registry.components.find((item) => item.id === envelope.component);
|
||||
return Boolean(manifest?.supportedSurfaces.includes(envelope.surface));
|
||||
}
|
||||
|
||||
if (envelope.kind === "chart") {
|
||||
return envelope.grammar === "echarts-safe-subset" && registry.chart_grammars.includes(envelope.grammar);
|
||||
}
|
||||
|
||||
if (!LOCAL_ACTION_SURFACES.get(envelope.action)?.includes(envelope.surface)) return false;
|
||||
const manifest = registry.actions.find((item) => item.id === envelope.action);
|
||||
return Boolean(manifest?.supportedSurfaces.includes(envelope.surface));
|
||||
}
|
||||
|
||||
export function parseUiRegistry(value: unknown): UIRegistry | null {
|
||||
if (!isRecord(value) || value.schema_version !== "agent-ui-registry@1") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
schema_version: "agent-ui-registry@1",
|
||||
chart_grammars: stringArray(value.chart_grammars),
|
||||
components: manifestArray(value.components),
|
||||
actions: manifestArray(value.actions)
|
||||
};
|
||||
}
|
||||
|
||||
function manifestArray(value: unknown) {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return value.flatMap((item) => {
|
||||
if (!isRecord(item) || typeof item.id !== "string") {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [{ id: item.id, supportedSurfaces: stringArray(item.supportedSurfaces).filter(isSurface) }];
|
||||
});
|
||||
}
|
||||
|
||||
function stringArray(value: unknown) {
|
||||
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
|
||||
}
|
||||
|
||||
function isChartSurface(value: unknown): value is "chat_inline" | "side_panel" | "canvas" {
|
||||
return value === "chat_inline" || value === "side_panel" || value === "canvas";
|
||||
}
|
||||
|
||||
function isSurface(value: unknown): value is UISurface {
|
||||
return typeof value === "string" && surfaces.has(value as UISurface);
|
||||
}
|
||||
|
||||
function optionalString(value: unknown) {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function boundedString(value: unknown, maxLength: number) {
|
||||
return typeof value === "string" && value.trim().length > 0 && value.length <= maxLength ? value.trim() : null;
|
||||
}
|
||||
|
||||
function isFiniteTimestamp(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
||||
}
|
||||
|
||||
function hasOnlyKeys(value: Record<string, unknown>, allowed: readonly string[]) {
|
||||
const keys = new Set(allowed);
|
||||
return Object.keys(value).every((key) => keys.has(key));
|
||||
}
|
||||
|
||||
function isValidComponentProps(component: string, props: unknown) {
|
||||
if (!isRecord(props)) return false;
|
||||
if (component === "HistoryPanel") {
|
||||
if (!hasOnlyKeys(props, ["reason", "feature_infos", "data_type", "start_time", "end_time"])) return false;
|
||||
const items = props.feature_infos;
|
||||
return Array.isArray(items) && items.length > 0 && items.length <= 100 &&
|
||||
items.every((item) => Array.isArray(item) && item.length === 2 && item.every((part) => boundedString(part, 128))) &&
|
||||
(props.data_type === "realtime" || props.data_type === "scheme" || props.data_type === "none");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isValidChart(spec: unknown, data: unknown) {
|
||||
if (!isRecord(spec) || !hasOnlyKeys(spec, ["title", "chart_type", "x_axis_name", "y_axis_name"])) return false;
|
||||
if (spec.chart_type !== undefined && spec.chart_type !== "line" && spec.chart_type !== "bar") return false;
|
||||
const parsedSpec = parseChartSpec(spec);
|
||||
const parsedData = normalizeSafeChartData(data, 100);
|
||||
return (parsedSpec.chartType === "line" || parsedSpec.chartType === "bar") && parsedData !== null &&
|
||||
parsedData.xData.length <= 100 && parsedData.series.length <= 8 &&
|
||||
parsedData.series.every((series) => series.data.length === parsedData.xData.length);
|
||||
}
|
||||
Reference in New Issue
Block a user