79 lines
2.6 KiB
TypeScript
79 lines
2.6 KiB
TypeScript
import type { FeedbackMessage } from "./feedback-contract";
|
|
|
|
export const CANVAS_FEEDBACK_CONTEXT_EVENT = "canvas-feedback-context";
|
|
export type FeedbackChatCapture = { chatId: string | null; messages: FeedbackMessage[] };
|
|
export type FeedbackCaptureEvent = CustomEvent<{
|
|
projectId: string;
|
|
receive: (value: FeedbackChatCapture) => void;
|
|
}>;
|
|
|
|
export function captureFeedbackChat(projectId: string): FeedbackChatCapture {
|
|
let result: FeedbackChatCapture = { chatId: null, messages: [] };
|
|
window.dispatchEvent(
|
|
new CustomEvent(CANVAS_FEEDBACK_CONTEXT_EVENT, {
|
|
detail: {
|
|
projectId,
|
|
receive: (value: FeedbackChatCapture) => {
|
|
result = value;
|
|
},
|
|
},
|
|
}),
|
|
);
|
|
return result;
|
|
}
|
|
|
|
export function feedbackMessages(messages: readonly unknown[]): FeedbackMessage[] {
|
|
let remaining = 48000;
|
|
return messages
|
|
.slice(-12)
|
|
.reverse()
|
|
.flatMap((value: any) => {
|
|
if (!value || !["user", "assistant"].includes(value.role) || typeof value.id !== "string")
|
|
return [];
|
|
const parts = Array.isArray(value.parts) ? value.parts : [];
|
|
let state: any = null;
|
|
for (const part of parts) {
|
|
if (part.type !== "data-imageGenerationStatus") continue;
|
|
try {
|
|
state = typeof part.data === "string" ? JSON.parse(part.data) : part.data;
|
|
} catch {
|
|
/* Keep public message text when a stream part is incomplete. */
|
|
}
|
|
}
|
|
const fullText = parts
|
|
.filter((part: any) => part.type === "text")
|
|
.map((part: any) => String(part.text || ""))
|
|
.join("\n");
|
|
const text = fullText.slice(0, Math.min(16000, remaining));
|
|
remaining -= text.length;
|
|
return [
|
|
{
|
|
id: value.id.slice(0, 180),
|
|
role: value.role,
|
|
text,
|
|
...(value.createdAt
|
|
? {
|
|
createdAt: String(
|
|
value.createdAt instanceof Date ? value.createdAt.toISOString() : value.createdAt,
|
|
).slice(0, 64),
|
|
}
|
|
: {}),
|
|
...(state?.requestId ? { requestId: String(state.requestId).slice(0, 180) } : {}),
|
|
...(state?.userMessageId
|
|
? { userMessageId: String(state.userMessageId).slice(0, 180) }
|
|
: {}),
|
|
...(state?.phase ? { status: String(state.phase).slice(0, 64) } : {}),
|
|
...(state?.failure?.message
|
|
? {
|
|
error: [state.failure.message, state.failure.recommendation]
|
|
.filter(Boolean)
|
|
.join("\n")
|
|
.slice(0, 2000),
|
|
}
|
|
: {}),
|
|
},
|
|
];
|
|
})
|
|
.reverse();
|
|
}
|