Update local frontend and backend changes

This commit is contained in:
吉鑫升 committed 2026-05-13 17:17:42 +08:00
1 parent faca2c9a2d
commit a27206c543
35 files changed
+1756 -334

No files matched your search

+2 -2
View File
@@ -74,7 +74,7 @@ export async function checkAgentName(
);
} catch {
throw new AgentNameCheckError(
"Could not reach the DeerFlow backend.",
"Could not reach the CM Assistant backend.",
"backend_unreachable",
);
}
@@ -83,7 +83,7 @@ export async function checkAgentName(
const err = (await res.json().catch(() => ({}))) as { detail?: string };
if (BACKEND_UNAVAILABLE_STATUSES.has(res.status)) {
throw new AgentNameCheckError(
"Could not reach the DeerFlow backend.",
"Could not reach the CM Assistant backend.",
"backend_unreachable",
);
}
+39 -16
View File
@@ -61,11 +61,11 @@ export const enUS: Translations = {
welcome: {
greeting: "Hello, again!",
description:
"Welcome to 🦌 DeerFlow, an open source super agent. With built-in and custom skills, DeerFlow helps you search on the web, analyze data, and generate artifacts like slides, web pages and do almost anything.",
"Welcome to CM Assistant. With built-in and custom skills, CM Assistant helps you search on the web, analyze data, and generate artifacts like slides, web pages and do almost anything.",
createYourOwnSkill: "Create Your Own Skill",
createYourOwnSkillDescription:
"Create your own skill to release the power of DeerFlow. With customized skills,\nDeerFlow can help you search on the web, analyze data, and generate\n artifacts like slides, web pages and do almost anything.",
"Create your own skill to release the power of CM Assistant. With customized skills,\nCM Assistant can help you search on the web, analyze data, and generate\n artifacts like slides, web pages and do almost anything.",
},
// Clipboard
@@ -208,13 +208,13 @@ export const enUS: Translations = {
save: "Save agent",
saving: "Saving agent...",
saveRequested:
"Save requested. DeerFlow is generating and saving an initial version now.",
"Save requested. CM Assistant is generating and saving an initial version now.",
saveHint:
"You can save this agent at any time from the top-right menu, even if this is only a first draft.",
saveCommandMessage:
"Please save this custom agent now based on everything we have discussed so far. Treat this as my explicit confirmation to save. If some details are still missing, make reasonable assumptions, generate a concise first SOUL.md in English, and call setup_agent immediately without asking me for more confirmation.",
agentCreatedPendingRefresh:
"The agent was created, but DeerFlow could not load it yet. Please refresh this page in a moment.",
"The agent was created, but CM Assistant could not load it yet. Please refresh this page in a moment.",
more: "More actions",
agentCreated: "Agent created!",
startChatting: "Start chatting",
@@ -229,13 +229,13 @@ export const enUS: Translations = {
// Workspace
workspace: {
officialWebsite: "DeerFlow's official website",
githubTooltip: "DeerFlow on Github",
officialWebsite: "CM Assistant's official website",
githubTooltip: "CM Assistant on Github",
settingsAndMore: "Settings and more",
visitGithub: "DeerFlow on GitHub",
visitGithub: "CM Assistant on GitHub",
reportIssue: "Report a issue",
contactUs: "Contact us",
about: "About DeerFlow",
about: "About CM Assistant",
},
// Conversation
@@ -251,7 +251,7 @@ export const enUS: Translations = {
// Page titles (document title)
pages: {
appName: "DeerFlow",
appName: "CM Assistant",
brandSubtitle: "Smart CM Platform",
chats: "Chats",
newChat: "New chat",
@@ -278,7 +278,7 @@ export const enUS: Translations = {
writeFile: "Write file",
clickToViewContent: "Click to view file content",
writeTodos: "Update to-do list",
skillInstallTooltip: "Install skill and make it available to DeerFlow",
skillInstallTooltip: "Install skill and make it available to CM Assistant",
},
// Subtasks
@@ -315,7 +315,7 @@ export const enUS: Translations = {
actions: "Actions",
keyboardShortcuts: "Keyboard Shortcuts",
keyboardShortcutsDescription:
"Navigate DeerFlow faster with keyboard shortcuts.",
"Navigate CM Assistant faster with keyboard shortcuts.",
openCommandPalette: "Open Command Palette",
toggleSidebar: "Toggle Sidebar",
},
@@ -323,7 +323,7 @@ export const enUS: Translations = {
// Settings
settings: {
title: "Settings",
description: "Adjust how DeerFlow looks and behaves for you.",
description: "Adjust how CM Assistant looks and behaves for you.",
sections: {
appearance: "Appearance",
memory: "Memory",
@@ -335,7 +335,7 @@ export const enUS: Translations = {
memory: {
title: "Memory",
description:
"DeerFlow automatically learns from your conversations in the background. These memories help DeerFlow understand you better and deliver a more personalized experience.",
"CM Assistant automatically learns from your conversations in the background. These memories help CM Assistant understand you better and deliver a more personalized experience.",
empty: "No memory data to display.",
rawJson: "Raw JSON",
exportButton: "Export memory",
@@ -433,20 +433,43 @@ export const enUS: Translations = {
description:
"Manage the configuration and enabled status of the agent skills.",
createSkill: "Create skill",
installSkill: "Install skill",
emptyTitle: "No agent skill yet",
emptyDescription:
"Put your agent skill folders under the `/skills/custom` folder under the root folder of DeerFlow.",
"Put your agent skill folders under the `/skills/custom` folder under the root folder of CM Assistant.",
emptyButton: "Create Your First Skill",
installDialog: {
title: "Install skill",
dropHint: "Drop a .zip or .skill archive here, or",
chooseFile: "Choose file",
validating: "Validating archive…",
installing: "Installing…",
replace: "Replace existing",
install: "Install",
cancel: "Cancel",
nameLabel: "Name",
descriptionLabel: "Description",
licenseLabel: "License",
toolsLabel: "Allowed tools",
warningsLabel: "Warnings",
conflictCustom:
"A custom skill named '{name}' is already installed. Use 'Replace existing' to overwrite (its enabled state will be kept).",
conflictPublic:
"A built-in public skill named '{name}' already exists and cannot be overwritten.",
installSuccess: "Skill '{name}' installed.",
installSuccessReplaced: "Skill '{name}' replaced.",
rejectInvalidExt: "Only .zip or .skill files are accepted.",
},
},
notification: {
title: "Notification",
description:
"DeerFlow only sends a completion notification when the window is not active. This is especially useful for long-running tasks so you can switch to other work and get notified when done.",
"CM Assistant only sends a completion notification when the window is not active. This is especially useful for long-running tasks so you can switch to other work and get notified when done.",
requestPermission: "Request notification permission",
deniedHint:
"Notification permission was denied. You can enable it in your browser's site settings to receive completion alerts.",
testButton: "Send test notification",
testTitle: "DeerFlow",
testTitle: "CM Assistant",
testBody: "This is a test notification.",
notSupported: "Your browser does not support notifications.",
disableNotification: "Disable notification",
@@ -354,9 +354,30 @@ export interface Translations {
title: string;
description: string;
createSkill: string;
installSkill: string;
emptyTitle: string;
emptyDescription: string;
emptyButton: string;
installDialog: {
title: string;
dropHint: string;
chooseFile: string;
validating: string;
installing: string;
replace: string;
install: string;
cancel: string;
nameLabel: string;
descriptionLabel: string;
licenseLabel: string;
toolsLabel: string;
warningsLabel: string;
conflictCustom: string;
conflictPublic: string;
installSuccess: string;
installSuccessReplaced: string;
rejectInvalidExt: string;
};
};
notification: {
title: string;
+38 -16
View File
@@ -61,11 +61,11 @@ export const zhCN: Translations = {
welcome: {
greeting: "你好,欢迎回来!",
description:
"欢迎使用 CM业务中心-问答管理",
"欢迎使用 CM 助手",
createYourOwnSkill: "创建你自己的 Agent SKill",
createYourOwnSkillDescription:
"创建你的 Agent Skill 来释放 CM业务中心-问答管理的潜力。通过自定义技能,CM业务中心-问答管理\n可以帮你搜索网络、分析数据,还能为你生成幻灯片、\n网页等作品,几乎可以做任何事情。",
"创建你的 Agent Skill 来释放 CM 助手的潜力。通过自定义技能,CM 助手\n可以帮你搜索网络、分析数据,还能为你生成幻灯片、\n网页等作品,几乎可以做任何事情。",
},
// Clipboard
@@ -196,13 +196,13 @@ export const zhCN: Translations = {
save: "保存智能体",
saving: "正在保存智能体...",
saveRequested:
"已提交保存请求,CM业务中心-问答管理 正在根据当前对话生成并保存初版智能体。",
"已提交保存请求,CM 助手 正在根据当前对话生成并保存初版智能体。",
saveHint:
"你可以在右上角的菜单里随时保存这个智能体,就算目前还只是初稿也可以。",
saveCommandMessage:
"请现在根据我们目前已经讨论的全部内容保存这个自定义智能体。这就是我明确的保存确认。如果仍有少量细节缺失,请根据上下文做出合理假设,生成一份简洁的英文初始 SOUL.md,并直接调用 setup_agent,不要再向我索要额外确认。",
agentCreatedPendingRefresh:
"智能体已创建,但 CM业务中心-问答管理 暂时还无法读取到它。请稍后刷新当前页面。",
"智能体已创建,但 CM 助手 暂时还无法读取到它。请稍后刷新当前页面。",
more: "更多操作",
agentCreated: "智能体已创建!",
startChatting: "开始对话",
@@ -217,13 +217,13 @@ export const zhCN: Translations = {
// Workspace
workspace: {
officialWebsite: "访问 CM业务中心-问答管理 官方网站",
githubTooltip: "访问 CM业务中心-问答管理 的 Github 仓库",
officialWebsite: "访问 CM 助手 官方网站",
githubTooltip: "访问 CM 助手 的 Github 仓库",
settingsAndMore: "设置和更多",
visitGithub: "在 Github 上查看 CM业务中心-问答管理",
visitGithub: "在 Github 上查看 CM 助手",
reportIssue: "报告问题",
contactUs: "联系我们",
about: "关于 CM业务中心-问答管理",
about: "关于 CM 助手",
},
// Conversation
@@ -239,7 +239,7 @@ export const zhCN: Translations = {
// Page titles (document title)
pages: {
appName: "CM业务中心-问答管理",
appName: "CM 助手",
brandSubtitle: "Smart CM Platform",
chats: "对话",
newChat: "新对话",
@@ -265,7 +265,7 @@ export const zhCN: Translations = {
writeFile: "写入文件",
clickToViewContent: "点击查看文件内容",
writeTodos: "更新 To-do 列表",
skillInstallTooltip: "安装技能并使其可在 CM业务中心-问答管理 中使用",
skillInstallTooltip: "安装技能并使其可在 CM 助手 中使用",
},
uploads: {
@@ -300,7 +300,7 @@ export const zhCN: Translations = {
noResults: "未找到结果。",
actions: "操作",
keyboardShortcuts: "键盘快捷键",
keyboardShortcutsDescription: "使用键盘快捷键更快地操作 CM业务中心-问答管理。",
keyboardShortcutsDescription: "使用键盘快捷键更快地操作 CM 助手。",
openCommandPalette: "打开命令面板",
toggleSidebar: "切换侧边栏",
},
@@ -308,7 +308,7 @@ export const zhCN: Translations = {
// Settings
settings: {
title: "设置",
description: "根据你的偏好调整 CM业务中心-问答管理 的界面和行为。",
description: "根据你的偏好调整 CM 助手 的界面和行为。",
sections: {
appearance: "外观",
memory: "记忆",
@@ -320,7 +320,7 @@ export const zhCN: Translations = {
memory: {
title: "记忆",
description:
"CM业务中心-问答管理 会在后台不断从你的对话中自动学习。这些记忆能帮助 CM业务中心-问答管理 更好地理解你,并提供更个性化的体验。",
"CM 助手 会在后台不断从你的对话中自动学习。这些记忆能帮助 CM 助手 更好地理解你,并提供更个性化的体验。",
empty: "暂无可展示的记忆数据。",
rawJson: "原始 JSON",
exportButton: "导出记忆",
@@ -414,20 +414,42 @@ export const zhCN: Translations = {
title: "技能",
description: "管理 Agent Skill 配置和启用状态。",
createSkill: "新建技能",
installSkill: "安装技能",
emptyTitle: "还没有技能",
emptyDescription:
"将你的 Agent Skill 文件夹放在 CM业务中心-问答管理 根目录下的 `/skills/custom` 文件夹中。",
"将你的 Agent Skill 文件夹放在 CM 助手 根目录下的 `/skills/custom` 文件夹中。",
emptyButton: "创建你的第一个技能",
installDialog: {
title: "安装技能",
dropHint: "拖拽 .zip 或 .skill 文件到此处,或者",
chooseFile: "选择文件",
validating: "正在校验文件…",
installing: "安装中…",
replace: "覆盖已有",
install: "安装",
cancel: "取消",
nameLabel: "名称",
descriptionLabel: "描述",
licenseLabel: "许可证",
toolsLabel: "允许的工具",
warningsLabel: "警告",
conflictCustom:
"已存在同名自定义技能 “{name}”。点击「覆盖已有」可替换(原启用状态保留)。",
conflictPublic: "存在同名内置技能 “{name}”,无法覆盖。",
installSuccess: "技能 “{name}” 已安装。",
installSuccessReplaced: "技能 “{name}” 已替换。",
rejectInvalidExt: "只接受 .zip 或 .skill 文件。",
},
},
notification: {
title: "通知",
description:
"CM业务中心-问答管理 只会在窗口不活跃时发送完成通知,特别适合长时间任务:你可以先去做别的事,完成后会收到提醒。",
"CM 助手 只会在窗口不活跃时发送完成通知,特别适合长时间任务:你可以先去做别的事,完成后会收到提醒。",
requestPermission: "请求通知权限",
deniedHint:
"通知权限已被拒绝。可在浏览器的网站设置中重新开启,以接收完成提醒。",
testButton: "发送测试通知",
testTitle: "CM业务中心-问答管理",
testTitle: "CM 助手",
testBody: "这是一条测试通知。",
notSupported: "当前浏览器不支持通知功能。",
disableNotification: "关闭通知",
@@ -7,6 +7,7 @@ import type {
ScheduledTaskDeliveryProfile,
ScheduledTaskResultFileContent,
ScheduledTaskRun,
ScheduledTaskRunFileUpdateResponse,
ScheduledTaskSubscription,
SchedulerThread,
} from "./types";
@@ -81,6 +82,20 @@ export async function getScheduledTaskRunFileContent(runId: string, fileIndex: n
);
}
export async function updateScheduledTaskRunFile(
runId: string,
fileIndex: number,
content: string,
) {
return parseResponse<ScheduledTaskRunFileUpdateResponse>(
await apiFetch(`${baseUrl()}/runs/${encodeURIComponent(runId)}/files/${fileIndex}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }),
}),
);
}
function filenameFromContentDisposition(header: string | null): string | null {
if (!header) return null;
const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header);
@@ -0,0 +1,274 @@
/**
* Convert markdown text to a Word (.docx) Blob in the browser.
*
* Implementation notes:
* - Uses the `docx` npm package to construct an OOXML document client-side.
* - Parser is intentionally lightweight: it covers the markdown features that
* scheduled-task agent reports actually emit — ATX headings, paragraphs,
* ordered/unordered lists, fenced code blocks, blockquotes, horizontal
* rules, and inline `**bold**` / `*italic*` / `` `code` `` runs.
* - We deliberately do NOT reach for a full markdown AST library (remark/
* unified) to keep the bundle small. Edge cases (tables, footnotes, html)
* degrade to plain text rather than failing loudly.
*/
import {
AlignmentType,
Document,
HeadingLevel,
Packer,
Paragraph,
TextRun,
type IRunOptions,
} from "docx";
const HEADING_LEVELS = [
HeadingLevel.HEADING_1,
HeadingLevel.HEADING_2,
HeadingLevel.HEADING_3,
HeadingLevel.HEADING_4,
HeadingLevel.HEADING_5,
HeadingLevel.HEADING_6,
];
type InlineSegment = { text: string; bold?: boolean; italic?: boolean; code?: boolean };
/**
* Tokenise a single line of markdown into formatted segments.
*
* Recognised inline syntax:
* `code`, **bold**, __bold__, *italic*, _italic_
* Order matters: code spans win over emphasis so backticks don't get parsed
* as italic delimiters.
*/
function parseInlineSegments(text: string): InlineSegment[] {
const tokens: InlineSegment[] = [];
const pattern = /(`+)([^`]+)\1|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*]+)\*|_([^_]+)_/g;
let cursor = 0;
let match: RegExpExecArray | null;
while ((match = pattern.exec(text)) !== null) {
if (match.index > cursor) {
tokens.push({ text: text.slice(cursor, match.index) });
}
if (match[2] !== undefined) {
tokens.push({ text: match[2], code: true });
} else if (match[3] !== undefined) {
tokens.push({ text: match[3], bold: true });
} else if (match[4] !== undefined) {
tokens.push({ text: match[4], bold: true });
} else if (match[5] !== undefined) {
tokens.push({ text: match[5], italic: true });
} else if (match[6] !== undefined) {
tokens.push({ text: match[6], italic: true });
}
cursor = pattern.lastIndex;
}
if (cursor < text.length) {
tokens.push({ text: text.slice(cursor) });
}
return tokens.length > 0 ? tokens : [{ text }];
}
function segmentsToRuns(segments: InlineSegment[], extra?: Partial<IRunOptions>): TextRun[] {
return segments.map((seg) => {
const opts: IRunOptions = {
text: seg.text,
bold: seg.bold,
italics: seg.italic,
...extra,
};
if (seg.code) {
opts.font = { name: "Consolas" };
}
return new TextRun(opts);
});
}
function makeParagraphFromInline(text: string): Paragraph {
return new Paragraph({
children: segmentsToRuns(parseInlineSegments(text)),
});
}
function makeHeadingParagraph(level: number, text: string): Paragraph {
return new Paragraph({
heading: HEADING_LEVELS[Math.min(level, HEADING_LEVELS.length) - 1],
children: segmentsToRuns(parseInlineSegments(text)),
});
}
function makeListItem(text: string, ordered: boolean, level: number): Paragraph {
return new Paragraph({
children: segmentsToRuns(parseInlineSegments(text)),
numbering: ordered
? { reference: "ordered-list", level: Math.min(level, 8) }
: undefined,
bullet: ordered ? undefined : { level: Math.min(level, 8) },
});
}
function makeCodeParagraph(line: string): Paragraph {
return new Paragraph({
children: [
new TextRun({
text: line || " ",
font: { name: "Consolas" },
}),
],
});
}
function makeQuoteParagraph(text: string): Paragraph {
return new Paragraph({
children: segmentsToRuns(parseInlineSegments(text), { italics: true }),
indent: { left: 720 },
});
}
function makeHorizontalRule(): Paragraph {
return new Paragraph({
alignment: AlignmentType.CENTER,
children: [new TextRun({ text: "────────" })],
});
}
/**
* Convert markdown text into an array of docx Paragraph objects.
*
* Block grammar handled (line-by-line):
* - ATX heading: `^(#{1,6})\s+(.*)$`
* - Fenced code: lines between ``` ``` are emitted verbatim
* - Blockquote: `^>\s?(.*)$`
* - Ordered list: `^\s*(\d+)\.\s+(.*)$`
* - Unordered list: `^\s*[-*+]\s+(.*)$`
* - Horizontal rule: `^(---|\*\*\*|___)\s*$`
* - Blank line: paragraph break
* - Anything else: paragraph (with inline formatting)
*/
function markdownToParagraphs(markdown: string): Paragraph[] {
const lines = markdown.replace(/\r\n/g, "\n").split("\n");
const paragraphs: Paragraph[] = [];
let inFence = false;
let paragraphBuffer: string[] = [];
const flushParagraph = () => {
if (paragraphBuffer.length === 0) return;
paragraphs.push(makeParagraphFromInline(paragraphBuffer.join(" ")));
paragraphBuffer = [];
};
for (const rawLine of lines) {
const line = rawLine.replace(/\t/g, " ");
if (line.trim().startsWith("```")) {
flushParagraph();
inFence = !inFence;
continue;
}
if (inFence) {
paragraphs.push(makeCodeParagraph(line));
continue;
}
if (!line.trim()) {
flushParagraph();
continue;
}
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
if (heading) {
flushParagraph();
paragraphs.push(makeHeadingParagraph(heading[1].length, heading[2].trim()));
continue;
}
if (/^(?:---|\*\*\*|___)\s*$/.test(line)) {
flushParagraph();
paragraphs.push(makeHorizontalRule());
continue;
}
const blockquote = /^>\s?(.*)$/.exec(line);
if (blockquote) {
flushParagraph();
paragraphs.push(makeQuoteParagraph(blockquote[1]));
continue;
}
const orderedItem = /^(\s*)(\d+)\.\s+(.*)$/.exec(line);
if (orderedItem) {
flushParagraph();
const indent = Math.floor(orderedItem[1].length / 2);
paragraphs.push(makeListItem(orderedItem[3], true, indent));
continue;
}
const unorderedItem = /^(\s*)[-*+]\s+(.*)$/.exec(line);
if (unorderedItem) {
flushParagraph();
const indent = Math.floor(unorderedItem[1].length / 2);
paragraphs.push(makeListItem(unorderedItem[2], false, indent));
continue;
}
paragraphBuffer.push(line.trim());
}
flushParagraph();
return paragraphs;
}
/**
* Convert a markdown string into a .docx Blob suitable for download.
*/
export async function markdownToDocxBlob(markdown: string, title?: string): Promise<Blob> {
const children: Paragraph[] = [];
if (title?.trim()) {
children.push(
new Paragraph({
heading: HeadingLevel.TITLE,
children: [new TextRun({ text: title.trim(), bold: true })],
}),
);
}
children.push(...markdownToParagraphs(markdown));
const doc = new Document({
numbering: {
config: [
{
reference: "ordered-list",
levels: [
{ level: 0, format: "decimal", text: "%1.", alignment: AlignmentType.START },
{ level: 1, format: "decimal", text: "%2.", alignment: AlignmentType.START },
{ level: 2, format: "decimal", text: "%3.", alignment: AlignmentType.START },
],
},
],
},
sections: [{ children }],
});
return Packer.toBlob(doc);
}
/**
* Trigger a browser download of the markdown source converted to .docx.
*/
export async function downloadMarkdownAsDocx(
markdown: string,
fileName: string,
title?: string,
): Promise<void> {
const blob = await markdownToDocxBlob(markdown, title);
const safeName = fileName.replace(/\.(md|markdown)$/i, "") || "document";
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `${safeName}.docx`;
anchor.rel = "noopener";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
@@ -89,4 +89,13 @@ export type ScheduledTaskRun = {
result?: ScheduledTaskRunResult | null;
created_at?: string | null;
updated_at?: string | null;
can_edit?: boolean;
};
export type ScheduledTaskRunFileUpdateResponse = {
index: number;
name: string;
size: number;
mime_type?: string | null;
kind?: string | null;
};
+49
View File
@@ -34,6 +34,18 @@ export interface InstallSkillResponse {
success: boolean;
skill_name: string;
message: string;
overwritten?: boolean;
}
export interface ValidateSkillUploadResponse {
ok: boolean;
skill_name: string;
description: string;
license: string | null;
allowed_tools: string[];
conflict: boolean;
conflict_kind: "public" | "custom" | null;
warnings: string[];
}
export async function installSkill(
@@ -61,3 +73,40 @@ export async function installSkill(
return response.json();
}
async function parseDetailedError(response: Response, fallback: string): Promise<Error> {
const data = await response.json().catch(() => ({}));
const detail = (data as { detail?: unknown }).detail;
const message = typeof detail === "string" && detail ? detail : `${fallback} (HTTP ${response.status})`;
return new Error(message);
}
export async function validateSkillUpload(file: File): Promise<ValidateSkillUploadResponse> {
const form = new FormData();
form.append("file", file, file.name);
const response = await apiFetch(`${getBackendBaseURL()}/api/skills/validate`, {
method: "POST",
body: form,
});
if (!response.ok) {
throw await parseDetailedError(response, "Validation failed");
}
return response.json() as Promise<ValidateSkillUploadResponse>;
}
export async function installSkillUpload(
file: File,
options: { overwrite?: boolean } = {},
): Promise<InstallSkillResponse> {
const form = new FormData();
form.append("file", file, file.name);
const query = options.overwrite ? "?overwrite=true" : "";
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/install-upload${query}`,
{ method: "POST", body: form },
);
if (!response.ok) {
throw await parseDetailedError(response, "Install failed");
}
return response.json() as Promise<InstallSkillResponse>;
}
+18 -1
View File
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { enableSkill } from "./api";
import { enableSkill, installSkillUpload, validateSkillUpload } from "./api";
import { loadSkills } from ".";
@@ -29,3 +29,20 @@ export function useEnableSkill() {
},
});
}
export function useValidateSkillUpload() {
return useMutation({
mutationFn: (file: File) => validateSkillUpload(file),
});
}
export function useInstallSkillUpload() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ file, overwrite }: { file: File; overwrite?: boolean }) =>
installSkillUpload(file, { overwrite }),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
},
});
}