Merge branch 'master' into dhk-1
解决 8 处冲突: - app.py:同时挂载 public_embed + html_page_favorites 两个 router - .env:保留 dhk-1 的 CORS 配置(含 5174、ALLOW_ALL=0) - message-list.tsx:并入双方新增(onSetupWriting* 解构 + contentClassName/fitMessageRowsToContent 类型) - WorkspaceRoutes.tsx:采用 master 的路由结构(含 chats_iframe/IframeChatPage),补回 dhk-1 的 BusinessChainEditorPage 导入与 roundtable/chains 路由 - LoginPage.tsx:合并两套登录(master 的 token 换登录 + dhk-1 的 online-ticket),并集依赖数组 - ScheduledTasksPage.tsx:采用 master 的 HTML 定时任务表单(isHtmlTask 分支) - AIWritingForm.tsx:保留 dhk-1 的 useWritingForm 重构,补回 master 的笔记来源 useState;WritingFormContext.materialSource 扩展支持 'notebook' - useAIWritingStream.ts:保留 dhk-1 重构(仅 reducer/helpers,useAIWriting 已移至 AIWritingContext),不并入 master 在此文件的旧实现 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
d49406d2f1
102 files changed
+6816
-6016
No files matched your search
@@ -2,26 +2,28 @@
|
||||
|
||||
import { Client as LangGraphClient } from "@langchain/langgraph-sdk/client";
|
||||
|
||||
import { getAuthorizationHeaderValue } from "../auth";
|
||||
import { getLangGraphBaseURL } from "../config";
|
||||
|
||||
import { sanitizeRunStreamOptions } from "./stream-mode";
|
||||
import { getAuthorizationHeaderValue } from "../auth";
|
||||
import { getLangGraphBaseURL } from "../config";
|
||||
|
||||
import { withCsrfHeaders } from "./csrf";
|
||||
import { sanitizeRunStreamOptions } from "./stream-mode";
|
||||
|
||||
function createCompatibleClient(isMock?: boolean): LangGraphClient {
|
||||
const client = new LangGraphClient({
|
||||
apiUrl: getLangGraphBaseURL(isMock),
|
||||
onRequest(_url, init) {
|
||||
const headers = new Headers(init.headers ?? {});
|
||||
const authHeader = getAuthorizationHeaderValue();
|
||||
if (authHeader && !headers.has("Authorization")) {
|
||||
headers.set("Authorization", authHeader);
|
||||
}
|
||||
return {
|
||||
...init,
|
||||
headers,
|
||||
};
|
||||
},
|
||||
});
|
||||
apiUrl: getLangGraphBaseURL(isMock),
|
||||
onRequest(_url, init) {
|
||||
const headers = withCsrfHeaders(init.headers);
|
||||
const authHeader = getAuthorizationHeaderValue();
|
||||
if (authHeader && !headers.has("Authorization")) {
|
||||
headers.set("Authorization", authHeader);
|
||||
}
|
||||
return {
|
||||
...init,
|
||||
credentials: init.credentials ?? "include",
|
||||
headers,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const originalRunStream = client.runs.stream.bind(client.runs);
|
||||
client.runs.stream = ((threadId, assistantId, payload) =>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Client as LangGraphClient } from "@langchain/langgraph-sdk/client";
|
||||
import { getAuthorizationHeaderValue } from "../auth";
|
||||
import { getCanvasLangGraphBaseURL } from "../config";
|
||||
|
||||
import { withCsrfHeaders } from "./csrf";
|
||||
import { sanitizeRunStreamOptions } from "./stream-mode";
|
||||
|
||||
/**
|
||||
@@ -19,12 +20,16 @@ function createCanvasClient(): LangGraphClient {
|
||||
const client = new LangGraphClient({
|
||||
apiUrl: getCanvasLangGraphBaseURL(),
|
||||
onRequest(_url, init) {
|
||||
const headers = new Headers(init.headers ?? {});
|
||||
const headers = withCsrfHeaders(init.headers);
|
||||
const authHeader = getAuthorizationHeaderValue();
|
||||
if (authHeader && !headers.has("Authorization")) {
|
||||
headers.set("Authorization", authHeader);
|
||||
}
|
||||
return { ...init, headers };
|
||||
return {
|
||||
...init,
|
||||
credentials: init.credentials ?? "include",
|
||||
headers,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
const CSRF_COOKIE_NAME = "csrf_token";
|
||||
const CSRF_HEADER_NAME = "X-CSRF-Token";
|
||||
|
||||
function readCookie(name: string): string | undefined {
|
||||
if (typeof document === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const cookies = document.cookie.split(";");
|
||||
for (const cookie of cookies) {
|
||||
const [rawName, ...rest] = cookie.trim().split("=");
|
||||
if (rawName !== name) {
|
||||
continue;
|
||||
}
|
||||
const rawValue = rest.join("=");
|
||||
if (!rawValue) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(rawValue);
|
||||
} catch {
|
||||
return rawValue;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getCsrfToken(): string | undefined {
|
||||
const token = readCookie(CSRF_COOKIE_NAME)?.trim();
|
||||
return token ? token : undefined;
|
||||
}
|
||||
|
||||
export function withCsrfHeaders(headers?: HeadersInit): Headers {
|
||||
const next = new Headers(headers ?? {});
|
||||
const csrfToken = getCsrfToken();
|
||||
if (csrfToken && !next.has(CSRF_HEADER_NAME)) {
|
||||
next.set(CSRF_HEADER_NAME, csrfToken);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { getAuthorizationHeaderValue } from "@/core/auth";
|
||||
|
||||
function withAuthHeaders(headers?: HeadersInit): Headers {
|
||||
const next = new Headers(headers ?? {});
|
||||
const authHeader = getAuthorizationHeaderValue();
|
||||
if (authHeader && !next.has("Authorization")) {
|
||||
next.set("Authorization", authHeader);
|
||||
}
|
||||
return next;
|
||||
import { getAuthorizationHeaderValue } from "@/core/auth";
|
||||
import { withCsrfHeaders } from "./csrf";
|
||||
|
||||
function withAuthHeaders(headers?: HeadersInit): Headers {
|
||||
const next = withCsrfHeaders(headers);
|
||||
const authHeader = getAuthorizationHeaderValue();
|
||||
if (authHeader && !next.has("Authorization")) {
|
||||
next.set("Authorization", authHeader);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
|
||||
return fetch(input, {
|
||||
...init,
|
||||
headers: withAuthHeaders(init?.headers),
|
||||
});
|
||||
}
|
||||
export function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
|
||||
return fetch(input, {
|
||||
...init,
|
||||
credentials: init?.credentials ?? "include",
|
||||
headers: withAuthHeaders(init?.headers),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -17,24 +17,70 @@ export async function listAllUsers(): Promise<UserListItem[]> {
|
||||
return res.json() as Promise<UserListItem[]>;
|
||||
}
|
||||
|
||||
// Normalize a FastAPI error body into a human-readable string. `detail` may be
|
||||
// a plain string, an object like AuthErrorResponse ({ code, message }), or an
|
||||
// array of validation errors — anything but a string would otherwise render as
|
||||
// the dreaded "[object Object]".
|
||||
function extractErrorMessage(body: unknown, fallback = "Login failed."): string {
|
||||
const detail = (body as { detail?: unknown } | null)?.detail ?? body;
|
||||
if (typeof detail === "string") return detail;
|
||||
if (Array.isArray(detail)) {
|
||||
const msg = detail
|
||||
.map((d) => (d && typeof d === "object" ? (d as { msg?: string }).msg : String(d)))
|
||||
.filter(Boolean)
|
||||
.join("; ");
|
||||
return msg || fallback;
|
||||
}
|
||||
if (detail && typeof detail === "object") {
|
||||
const obj = detail as { message?: string; msg?: string };
|
||||
return obj.message ?? obj.msg ?? fallback;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export async function loginByUsername(
|
||||
username: string,
|
||||
password?: string | null,
|
||||
): Promise<LoginByUsernameResponse> {
|
||||
// When the username-login password gate is enabled server-side, the shared
|
||||
// secret must be passed as ?password=. Omitted when no password is provided
|
||||
// so the passwordless flow keeps working unchanged.
|
||||
const base = `${getBackendBaseURL()}/api/v1/auth/login/username`;
|
||||
const url =
|
||||
password != null && password !== ""
|
||||
? `${base}?password=${encodeURIComponent(password)}`
|
||||
: base;
|
||||
const response = await apiFetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ username }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => null);
|
||||
throw new Error(extractErrorMessage(error));
|
||||
}
|
||||
return response.json() as Promise<LoginByUsernameResponse>;
|
||||
}
|
||||
|
||||
export async function loginByToken(
|
||||
token: string,
|
||||
): Promise<LoginByUsernameResponse> {
|
||||
// Token-exchange login: the gateway resolves the upstream token to a username
|
||||
// and signs the matching local account in.
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/v1/auth/login/username`,
|
||||
`${getBackendBaseURL()}/api/v1/auth/login/token?token=${encodeURIComponent(token)}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ username }),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const error = await response
|
||||
.json()
|
||||
.catch(() => ({ detail: "Login failed." }));
|
||||
throw new Error(error.detail ?? "Login failed.");
|
||||
const error = await response.json().catch(() => null);
|
||||
throw new Error(extractErrorMessage(error));
|
||||
}
|
||||
return response.json() as Promise<LoginByUsernameResponse>;
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ export function getLangGraphBaseURL(isMock?: boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 笔记本外部系统(Studio)API 基础地址,通过 VITE_NOTEBOOK_API_BASE_URL 配置。 */
|
||||
/** 笔记本外部系统后端 API 地址,通过 VITE_AIPI_BACKENP_URL 配置。 */
|
||||
export function getNotebookApiBaseURL(): string {
|
||||
if (env.NEXT_PUBLIC_NOTEBOOK_API_BASE_URL) {
|
||||
return env.NEXT_PUBLIC_NOTEBOOK_API_BASE_URL.replace(/\/+$/, "");
|
||||
|
||||
@@ -41,6 +41,7 @@ export const enUS: Translations = {
|
||||
code: "Code",
|
||||
preview: "Preview",
|
||||
cancel: "Cancel",
|
||||
confirm: "Confirm",
|
||||
save: "Save",
|
||||
install: "Install",
|
||||
create: "Create",
|
||||
@@ -80,6 +81,7 @@ export const enUS: Translations = {
|
||||
// Input Box
|
||||
inputBox: {
|
||||
placeholder: "How can I assist you today?",
|
||||
editQuestion: "Edit question",
|
||||
createSkillPrompt:
|
||||
"We're going to build a new skill step by step with `skill-creator`. To start, what do you want this skill to do?",
|
||||
addAttachments: "Add attachments",
|
||||
|
||||
@@ -42,6 +42,7 @@ export interface Translations {
|
||||
code: string;
|
||||
preview: string;
|
||||
cancel: string;
|
||||
confirm: string;
|
||||
save: string;
|
||||
install: string;
|
||||
create: string;
|
||||
@@ -77,6 +78,7 @@ export interface Translations {
|
||||
// Input Box
|
||||
inputBox: {
|
||||
placeholder: string;
|
||||
editQuestion: string;
|
||||
createSkillPrompt: string;
|
||||
addAttachments: string;
|
||||
mode: string;
|
||||
|
||||
@@ -41,6 +41,7 @@ export const zhCN: Translations = {
|
||||
code: "代码",
|
||||
preview: "预览",
|
||||
cancel: "取消",
|
||||
confirm: "确定",
|
||||
save: "保存",
|
||||
install: "安装",
|
||||
create: "创建",
|
||||
@@ -80,6 +81,7 @@ export const zhCN: Translations = {
|
||||
// Input Box
|
||||
inputBox: {
|
||||
placeholder: "今天我能为你做些什么?",
|
||||
editQuestion: "编辑问题",
|
||||
createSkillPrompt:
|
||||
"我们一起用 skill-creator 技能来创建一个技能吧。先问问我希望这个技能能做什么。",
|
||||
addAttachments: "添加附件",
|
||||
|
||||
@@ -482,10 +482,10 @@ export function parseUploadedFiles(content: string): FileInMessage[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Check if the backend reported no new files were uploaded in this message
|
||||
if (uploadedFilesContent?.includes("(empty)")) {
|
||||
return [];
|
||||
}
|
||||
// NOTE: do NOT bail on "(empty)" here. The backend writes "(empty)" only for
|
||||
// the "uploaded in this message" section; files uploaded in previous messages
|
||||
// are still listed below it. Bailing dropped those valid entries. The file
|
||||
// regex below naturally skips the "(empty)" line, so parsing stays correct.
|
||||
|
||||
// Parse file list
|
||||
// Format: - filename (size)\n Path: /path/to/file
|
||||
|
||||
@@ -7,6 +7,8 @@ const CITE_RE = /\[\[cite:(\d+)\]\]/g;
|
||||
|
||||
export function rehypeCitations(sources: Array<{ id: number; title: string }>) {
|
||||
const sourceMap = new Map(sources.map((s) => [s.id, s.title]));
|
||||
const citeCounter = new Map<number, number>();
|
||||
let citeIndex = 0;
|
||||
|
||||
return (tree: Root) => {
|
||||
visit(tree, "text", (node, index, parent) => {
|
||||
@@ -14,8 +16,6 @@ export function rehypeCitations(sources: Array<{ id: number; title: string }>) {
|
||||
CITE_RE.lastIndex = 0;
|
||||
|
||||
const newNodes: ElementContent[] = [];
|
||||
const citeCounter = new Map<number, number>();
|
||||
let citeIndex = 0;
|
||||
let last = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
|
||||
@@ -2,12 +2,15 @@ import { apiFetch } from "@/core/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
import type {
|
||||
HtmlPageFavorite,
|
||||
PublishedScheduledTask,
|
||||
ScheduledTask,
|
||||
ScheduledTaskDeliveryProfile,
|
||||
ScheduledTaskExecutionContext,
|
||||
ScheduledTaskResultFileContent,
|
||||
ScheduledTaskRun,
|
||||
ScheduledTaskRunFileUpdateResponse,
|
||||
ScheduledTaskRunHtml,
|
||||
ScheduledTaskRunMessagesResponse,
|
||||
ScheduledTaskSubscription,
|
||||
SchedulerThread,
|
||||
@@ -52,6 +55,7 @@ export async function createScheduledTask(data: {
|
||||
timezone?: string | null;
|
||||
execution_agent_name?: string | null;
|
||||
require_markdown?: boolean;
|
||||
execution_context?: ScheduledTaskExecutionContext | null;
|
||||
}) {
|
||||
return parseResponse<ScheduledTask>(
|
||||
await apiFetch(baseUrl(), {
|
||||
@@ -212,6 +216,7 @@ export async function updateScheduledTask(
|
||||
enabled: boolean;
|
||||
execution_agent_name: string | null;
|
||||
require_markdown: boolean;
|
||||
execution_context: ScheduledTaskExecutionContext | null;
|
||||
}>,
|
||||
) {
|
||||
return parseResponse<ScheduledTask>(
|
||||
@@ -368,3 +373,47 @@ export async function adminTriggerScheduledTask(taskId: string) {
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// --- HTML page tasks ---
|
||||
|
||||
/** Fetch the generated HTML document for an ``html_page`` run. */
|
||||
export async function getScheduledTaskRunHtml(runId: string) {
|
||||
return parseResponse<ScheduledTaskRunHtml>(
|
||||
await apiFetch(`${baseUrl()}/runs/${encodeURIComponent(runId)}/html`),
|
||||
);
|
||||
}
|
||||
|
||||
const favoritesUrl = () => `${getBackendBaseURL()}/api/html-page-favorites`;
|
||||
|
||||
export async function listHtmlPageFavorites() {
|
||||
return parseResponse<HtmlPageFavorite[]>(await apiFetch(favoritesUrl()));
|
||||
}
|
||||
|
||||
export async function getHtmlPageFavorite(favoriteId: string) {
|
||||
return parseResponse<HtmlPageFavorite>(
|
||||
await apiFetch(`${favoritesUrl()}/${encodeURIComponent(favoriteId)}`),
|
||||
);
|
||||
}
|
||||
|
||||
export async function createHtmlPageFavorite(data: {
|
||||
page_id: string;
|
||||
title?: string | null;
|
||||
description?: string | null;
|
||||
tags?: string[];
|
||||
}) {
|
||||
return parseResponse<HtmlPageFavorite>(
|
||||
await apiFetch(favoritesUrl(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteHtmlPageFavorite(favoriteId: string) {
|
||||
return parseResponse<{ success: boolean }>(
|
||||
await apiFetch(`${favoritesUrl()}/${encodeURIComponent(favoriteId)}`, {
|
||||
method: "DELETE",
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -10,14 +10,18 @@ import {
|
||||
adminListScheduledTaskRuns,
|
||||
adminTriggerScheduledTask,
|
||||
adminUpdateScheduledTask,
|
||||
createHtmlPageFavorite,
|
||||
createScheduledTask,
|
||||
deleteHtmlPageFavorite,
|
||||
deleteScheduledTask,
|
||||
deleteScheduledTaskRun,
|
||||
getSchedulerThread,
|
||||
getScheduledTaskDeliveryProfile,
|
||||
getScheduledTaskRun,
|
||||
getScheduledTaskRunHtml,
|
||||
getScheduledTaskRunMessages,
|
||||
listAllScheduledTasks,
|
||||
listHtmlPageFavorites,
|
||||
listPublishedScheduledTasks,
|
||||
listScheduledTaskRuns,
|
||||
listScheduledTasks,
|
||||
@@ -112,6 +116,42 @@ export function useScheduledTaskRunMessages(
|
||||
});
|
||||
}
|
||||
|
||||
/** Generated HTML for an ``html_page`` run; polls while the run is in flight. */
|
||||
export function useScheduledTaskRunHtml(
|
||||
runId?: string | null,
|
||||
options: { enabled?: boolean; live?: boolean } = {},
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["scheduled-tasks", "runs", runId, "html"],
|
||||
queryFn: () => getScheduledTaskRunHtml(runId!),
|
||||
enabled: !!runId && (options.enabled ?? true),
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
refetchInterval: options.live ? 5000 : false,
|
||||
});
|
||||
}
|
||||
|
||||
/** The current user's bookmarked HTML pages. */
|
||||
export function useHtmlPageFavorites(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: ["html-page-favorites"],
|
||||
queryFn: listHtmlPageFavorites,
|
||||
enabled,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
/** Create / delete HTML page favorites. */
|
||||
export function useHtmlPageFavoriteActions() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () =>
|
||||
queryClient.invalidateQueries({ queryKey: ["html-page-favorites"] });
|
||||
return {
|
||||
create: useMutation({ mutationFn: createHtmlPageFavorite, onSuccess: invalidate }),
|
||||
remove: useMutation({ mutationFn: deleteHtmlPageFavorite, onSuccess: invalidate }),
|
||||
};
|
||||
}
|
||||
|
||||
export function useScheduledTaskDeliveryProfile() {
|
||||
return useQuery({
|
||||
queryKey: ["scheduled-tasks", "delivery-profile"],
|
||||
|
||||
@@ -11,6 +11,26 @@ export type ScheduledTaskSubscription = {
|
||||
updated_at?: string | null;
|
||||
};
|
||||
|
||||
/** Task kinds. A bare/absent kind is the regular agent task. */
|
||||
export type ScheduledTaskKind = "agent" | "html_page";
|
||||
|
||||
/** Config for an ``html_page`` task, persisted inside ``execution_context``.
|
||||
* Data gathering is delegated to the agent's own search skills, so there is no
|
||||
* explicit search query / data source — the page prompt drives everything. */
|
||||
export type HtmlPageConfig = {
|
||||
page_prompt?: string | null;
|
||||
negative_prompt?: string | null;
|
||||
reference_favorite_id?: string | null;
|
||||
model_name?: string | null;
|
||||
};
|
||||
|
||||
export type ScheduledTaskExecutionContext = {
|
||||
require_markdown?: boolean;
|
||||
task_kind?: ScheduledTaskKind;
|
||||
html_config?: HtmlPageConfig;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type ScheduledTask = {
|
||||
task_id: string;
|
||||
name: string;
|
||||
@@ -21,11 +41,11 @@ export type ScheduledTask = {
|
||||
timezone: string;
|
||||
enabled: boolean;
|
||||
/**
|
||||
* Free-form execution context persisted with the task. ``require_markdown``
|
||||
* lives here (rather than a dedicated column) so the feature needs no schema
|
||||
* migration.
|
||||
* Free-form execution context persisted with the task. ``require_markdown``,
|
||||
* ``task_kind`` and ``html_config`` live here (rather than dedicated columns)
|
||||
* so the feature needs no schema migration.
|
||||
*/
|
||||
execution_context?: { require_markdown?: boolean; [key: string]: unknown } | null;
|
||||
execution_context?: ScheduledTaskExecutionContext | null;
|
||||
next_run_at?: string | null;
|
||||
last_run_at?: string | null;
|
||||
last_status?: string | null;
|
||||
@@ -70,7 +90,7 @@ export type ScheduledTaskResultFile = {
|
||||
path?: string | null;
|
||||
mime_type?: string | null;
|
||||
size?: number | null;
|
||||
kind?: "markdown" | "attachment" | "artifact" | null;
|
||||
kind?: "markdown" | "attachment" | "artifact" | "html" | null;
|
||||
};
|
||||
|
||||
export type ScheduledTaskResultFileContent = {
|
||||
@@ -86,9 +106,42 @@ export type ScheduledTaskResultFileContent = {
|
||||
export type ScheduledTaskRunResult = {
|
||||
title: string;
|
||||
content: string;
|
||||
format: "markdown" | "text" | "json" | "mixed";
|
||||
format: "markdown" | "text" | "json" | "mixed" | "html";
|
||||
files: ScheduledTaskResultFile[];
|
||||
created_at: string;
|
||||
/** Present for ``html_page`` runs: the full generated HTML document. */
|
||||
html?: string | null;
|
||||
style_summary?: string | null;
|
||||
layout_summary?: string | null;
|
||||
};
|
||||
|
||||
/** Response of the run/latest HTML preview endpoints. */
|
||||
export type ScheduledTaskRunHtml = {
|
||||
run_id: string;
|
||||
task_id?: string | null;
|
||||
title?: string | null;
|
||||
html?: string | null;
|
||||
style_summary?: string | null;
|
||||
layout_summary?: string | null;
|
||||
page_id?: string | null;
|
||||
created_at?: string | null;
|
||||
};
|
||||
|
||||
/** A user-bookmarked generated HTML page. */
|
||||
export type HtmlPageFavorite = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
page_id: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
tags?: string[];
|
||||
html_snapshot?: string;
|
||||
style_summary?: string | null;
|
||||
layout_summary?: string | null;
|
||||
content_structure_summary?: string | null;
|
||||
reuse_prompt?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
};
|
||||
|
||||
export type ScheduledTaskRun = {
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
export { useLocalSettings, useThreadSettings } from "./hooks";
|
||||
export { isThreadRagModeLocked, lockThreadRagMode } from "./local";
|
||||
export {
|
||||
getLastAgentId,
|
||||
isThreadRagModeLocked,
|
||||
lockThreadRagMode,
|
||||
saveLastAgentId,
|
||||
} from "./local";
|
||||
export type { LocalSettings } from "./local";
|
||||
@@ -21,6 +21,7 @@ export const DEFAULT_LOCAL_SETTINGS: LocalSettings = {
|
||||
export const LOCAL_SETTINGS_KEY = "deerflow.local-settings";
|
||||
export const THREAD_MODEL_KEY_PREFIX = "deerflow.thread-model.";
|
||||
export const THREAD_RAG_MODE_KEY_PREFIX = "deerflow.thread-rag-mode.";
|
||||
export const LAST_AGENT_ID_KEY = "deerflow.last-agent-id";
|
||||
|
||||
function isBrowser(): boolean {
|
||||
return typeof window !== "undefined";
|
||||
@@ -148,6 +149,29 @@ export function applyThreadModelOverride(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The id of the agent the user last started a conversation with. New-chat
|
||||
* landing screens pre-select this agent so the user doesn't have to re-pick it
|
||||
* every time. Returns ``null`` when nothing was stored yet.
|
||||
*/
|
||||
export function getLastAgentId(): string | null {
|
||||
if (!isBrowser()) {
|
||||
return null;
|
||||
}
|
||||
return localStorage.getItem(LAST_AGENT_ID_KEY) || null;
|
||||
}
|
||||
|
||||
export function saveLastAgentId(agentId: string | null | undefined) {
|
||||
if (!isBrowser()) {
|
||||
return;
|
||||
}
|
||||
if (!agentId) {
|
||||
localStorage.removeItem(LAST_AGENT_ID_KEY);
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(LAST_AGENT_ID_KEY, agentId);
|
||||
}
|
||||
|
||||
export function getLocalSettings(): LocalSettings {
|
||||
if (!isBrowser()) {
|
||||
return DEFAULT_LOCAL_SETTINGS;
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { SkillDisplayConfig } from "@/core/skills/type";
|
||||
import type {
|
||||
SkillDisplayConfig,
|
||||
SkillDisplayResultSetConfig,
|
||||
} from "@/core/skills/type";
|
||||
|
||||
const DEFAULT_CITATION_MAX_ITEMS = 100;
|
||||
const DEFAULT_LIST_MAX_ITEMS = 20;
|
||||
@@ -15,6 +18,10 @@ export interface DisplaySourceItem {
|
||||
url?: string;
|
||||
content?: string;
|
||||
score?: number;
|
||||
displayMode?: SkillDisplayConfig["mode"];
|
||||
resultSetKey?: string;
|
||||
resultSetLabel?: string | null;
|
||||
tableColumns?: SkillDisplayConfig["tableColumns"];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
@@ -38,6 +45,7 @@ export const emptyDisplayConfig = (): SkillDisplayConfig => ({
|
||||
maxItems: DEFAULT_CITATION_MAX_ITEMS,
|
||||
customInstruction: "",
|
||||
tableColumns: [],
|
||||
resultSets: [],
|
||||
});
|
||||
|
||||
const candidateFields: Record<string, string[]> = {
|
||||
@@ -53,7 +61,7 @@ const candidateFields: Record<string, string[]> = {
|
||||
idField: ["recUuid", "rec_uuid", "uuid", "docId", "taskId", "recordId", "id"],
|
||||
};
|
||||
|
||||
function getByPath(value: unknown, path: string): unknown {
|
||||
function getByPath(value: unknown, path: string | null | undefined): unknown {
|
||||
if (!path) return value;
|
||||
return path.split(".").reduce<unknown>((acc, key) => {
|
||||
if (acc && typeof acc === "object") {
|
||||
@@ -63,19 +71,55 @@ function getByPath(value: unknown, path: string): unknown {
|
||||
}, value);
|
||||
}
|
||||
|
||||
function findFirstArray(
|
||||
value: unknown,
|
||||
path = "",
|
||||
): { path: string; items: Record<string, unknown>[] } | null {
|
||||
if (Array.isArray(value) && value.every((item) => item && typeof item === "object")) {
|
||||
return { path, items: value as Record<string, unknown>[] };
|
||||
export type ResultArrayCandidate = {
|
||||
key: string;
|
||||
label: string;
|
||||
path: string;
|
||||
items: Record<string, unknown>[];
|
||||
};
|
||||
|
||||
export function findResultArrayCandidates(samplePayload: unknown): ResultArrayCandidate[] {
|
||||
const candidates: ResultArrayCandidate[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
function visit(value: unknown, path = "", depth = 0) {
|
||||
if (depth > 8 || candidates.length >= 20) return;
|
||||
if (Array.isArray(value)) {
|
||||
const objectItems = value.filter(
|
||||
(item): item is Record<string, unknown> =>
|
||||
!!item && typeof item === "object" && !Array.isArray(item),
|
||||
);
|
||||
if (
|
||||
(value.length === 0 || objectItems.length > 0) &&
|
||||
objectItems.length === value.length &&
|
||||
!seen.has(path)
|
||||
) {
|
||||
seen.add(path);
|
||||
candidates.push({
|
||||
key: buildResultSetKey(path || "root"),
|
||||
label: buildResultSetLabel(path || "根数组", objectItems.length),
|
||||
path,
|
||||
items: objectItems,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
visit(child, path ? `${path}.${key}` : key, depth + 1);
|
||||
}
|
||||
}
|
||||
if (!value || typeof value !== "object") return null;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const found = findFirstArray(child, path ? `${path}.${key}` : key);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
|
||||
visit(samplePayload);
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function buildResultSetKey(path: string): string {
|
||||
return path.replace(/[^a-zA-Z0-9_]+/g, "_").replace(/^_+|_+$/g, "") || "root";
|
||||
}
|
||||
|
||||
function buildResultSetLabel(path: string, count: number): string {
|
||||
return `${path}(${count} 条)`;
|
||||
}
|
||||
|
||||
function pickField(sample: Record<string, unknown>, candidates: string[]): string | null {
|
||||
@@ -93,13 +137,31 @@ function pickField(sample: Record<string, unknown>, candidates: string[]): strin
|
||||
}
|
||||
|
||||
export function inferDisplayConfig(samplePayload: unknown, skillName?: string): SkillDisplayConfig {
|
||||
const found = findFirstArray(samplePayload) ?? { path: "results", items: [] };
|
||||
const sample = found.items[0] ?? {};
|
||||
const candidates = findResultArrayCandidates(samplePayload);
|
||||
const found = candidates[0] ?? {
|
||||
key: "results",
|
||||
label: "results(0 条)",
|
||||
path: "results",
|
||||
items: [],
|
||||
};
|
||||
const inferred = buildConfigFromCandidate(found, skillName);
|
||||
inferred.resultSets =
|
||||
candidates.length > 1
|
||||
? candidates.map((candidate) => buildResultSetConfigFromCandidate(candidate, skillName))
|
||||
: [];
|
||||
return inferred;
|
||||
}
|
||||
|
||||
function buildConfigFromCandidate(
|
||||
candidate: ResultArrayCandidate,
|
||||
skillName?: string,
|
||||
): SkillDisplayConfig {
|
||||
const sample = candidate.items[0] ?? {};
|
||||
const inferred = emptyDisplayConfig();
|
||||
inferred.enabled = true;
|
||||
inferred.mode = skillName === "knowledge-search-v2" ? "citation" : "list";
|
||||
inferred.resultPath = found.path || "results";
|
||||
inferred.maxItems = inferMaxItems(found.items.length, inferred.mode);
|
||||
inferred.resultPath = candidate.path || "results";
|
||||
inferred.maxItems = inferMaxItems(candidate.items.length, inferred.mode);
|
||||
|
||||
for (const [target, candidates] of Object.entries(candidateFields)) {
|
||||
(inferred as unknown as Record<string, string | null>)[target] = pickField(sample, candidates);
|
||||
@@ -123,6 +185,65 @@ export function inferDisplayConfig(samplePayload: unknown, skillName?: string):
|
||||
return inferred;
|
||||
}
|
||||
|
||||
function buildResultSetConfigFromCandidate(
|
||||
candidate: ResultArrayCandidate,
|
||||
skillName?: string,
|
||||
): SkillDisplayResultSetConfig {
|
||||
const config = buildConfigFromCandidate(candidate, skillName);
|
||||
return {
|
||||
key: candidate.key,
|
||||
label: candidate.label,
|
||||
enabled: true,
|
||||
mode: config.mode,
|
||||
resultPath: config.resultPath,
|
||||
titleField: config.titleField,
|
||||
summaryField: config.summaryField,
|
||||
contentField: config.contentField,
|
||||
sourceField: config.sourceField,
|
||||
authorField: config.authorField,
|
||||
typeField: config.typeField,
|
||||
timeField: config.timeField,
|
||||
scoreField: config.scoreField,
|
||||
urlField: config.urlField,
|
||||
idField: config.idField,
|
||||
linkStrategy: config.linkStrategy,
|
||||
linkTemplate: config.linkTemplate,
|
||||
citationToken: config.citationToken,
|
||||
maxItems: config.maxItems,
|
||||
customInstruction: config.customInstruction,
|
||||
tableColumns: config.tableColumns,
|
||||
};
|
||||
}
|
||||
|
||||
export function displayConfigFromResultSet(
|
||||
base: SkillDisplayConfig,
|
||||
resultSet: SkillDisplayResultSetConfig,
|
||||
): SkillDisplayConfig {
|
||||
return {
|
||||
...base,
|
||||
enabled: resultSet.enabled,
|
||||
mode: resultSet.mode,
|
||||
resultPath: resultSet.resultPath,
|
||||
titleField: resultSet.titleField,
|
||||
summaryField: resultSet.summaryField,
|
||||
contentField: resultSet.contentField,
|
||||
sourceField: resultSet.sourceField,
|
||||
authorField: resultSet.authorField,
|
||||
typeField: resultSet.typeField,
|
||||
timeField: resultSet.timeField,
|
||||
scoreField: resultSet.scoreField,
|
||||
urlField: resultSet.urlField,
|
||||
idField: resultSet.idField,
|
||||
linkStrategy: resultSet.linkStrategy,
|
||||
linkTemplate: resultSet.linkTemplate,
|
||||
citationToken: resultSet.citationToken,
|
||||
maxItems: resultSet.maxItems,
|
||||
customInstruction: resultSet.customInstruction,
|
||||
tableColumns: resultSet.tableColumns,
|
||||
resultSets: [],
|
||||
};
|
||||
}
|
||||
|
||||
function buildDefaultTableColumns(
|
||||
sample: Record<string, unknown>,
|
||||
config: SkillDisplayConfig,
|
||||
@@ -161,13 +282,13 @@ function stringify(value: unknown, fallback = ""): string {
|
||||
|
||||
function renderTemplate(template: string, item: Record<string, unknown>): string {
|
||||
return template.replace(/\{([^}]+)\}/g, (_match, key: string) =>
|
||||
encodeURIComponent(stringify(item[key])),
|
||||
encodeURIComponent(stringify(getByPath(item, key.trim()))),
|
||||
);
|
||||
}
|
||||
|
||||
function resolveLink(item: Record<string, unknown>, config: SkillDisplayConfig): string | undefined {
|
||||
const url = config.urlField ? stringify(item[config.urlField]) : "";
|
||||
const id = config.idField ? stringify(item[config.idField]) : "";
|
||||
const url = config.urlField ? stringify(getByPath(item, config.urlField)) : "";
|
||||
const id = config.idField ? stringify(getByPath(item, config.idField)) : "";
|
||||
if (config.linkStrategy === "url") return url || undefined;
|
||||
if (config.linkStrategy === "id") {
|
||||
return id && config.linkTemplate ? renderTemplate(config.linkTemplate, item) : undefined;
|
||||
@@ -176,6 +297,30 @@ function resolveLink(item: Record<string, unknown>, config: SkillDisplayConfig):
|
||||
}
|
||||
|
||||
export function normalizeDisplaySources(payload: unknown, config: SkillDisplayConfig): DisplaySourceItem[] {
|
||||
const configuredResultSets = config.resultSets ?? [];
|
||||
const resultSets = configuredResultSets.filter(
|
||||
(resultSet) => resultSet.enabled && resultSet.mode !== "none",
|
||||
);
|
||||
if (configuredResultSets.length > 0) {
|
||||
return resultSets.flatMap((resultSet) =>
|
||||
normalizeDisplaySourcesForConfig(
|
||||
payload,
|
||||
displayConfigFromResultSet(config, resultSet),
|
||||
resultSet,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!config.enabled || config.mode === "none") {
|
||||
return [];
|
||||
}
|
||||
return normalizeDisplaySourcesForConfig(payload, config);
|
||||
}
|
||||
|
||||
function normalizeDisplaySourcesForConfig(
|
||||
payload: unknown,
|
||||
config: SkillDisplayConfig,
|
||||
resultSet?: SkillDisplayResultSetConfig,
|
||||
): DisplaySourceItem[] {
|
||||
const rawItems = getByPath(payload, config.resultPath);
|
||||
if (!Array.isArray(rawItems)) return [];
|
||||
const maxItems = resolveMaxItems(config, rawItems.length);
|
||||
@@ -183,19 +328,23 @@ export function normalizeDisplaySources(payload: unknown, config: SkillDisplayCo
|
||||
.filter((item): item is Record<string, unknown> => !!item && typeof item === "object")
|
||||
.slice(0, maxItems)
|
||||
.map((item, index) => ({
|
||||
id: config.idField ? stringify(item[config.idField]) : undefined,
|
||||
title: config.titleField ? stringify(item[config.titleField], `结果 ${index + 1}`) : `结果 ${index + 1}`,
|
||||
type: config.typeField ? stringify(item[config.typeField], "result") : "result",
|
||||
snippet: config.summaryField ? stringify(item[config.summaryField]) : "",
|
||||
content: config.contentField ? stringify(item[config.contentField]) : undefined,
|
||||
source: config.sourceField ? stringify(item[config.sourceField]) : undefined,
|
||||
author: config.authorField ? stringify(item[config.authorField]) : undefined,
|
||||
time: config.timeField ? stringify(item[config.timeField]) : undefined,
|
||||
id: config.idField ? stringify(getByPath(item, config.idField)) : undefined,
|
||||
title: config.titleField ? stringify(getByPath(item, config.titleField), `结果 ${index + 1}`) : `结果 ${index + 1}`,
|
||||
type: config.typeField ? stringify(getByPath(item, config.typeField), "result") : "result",
|
||||
snippet: config.summaryField ? stringify(getByPath(item, config.summaryField)) : "",
|
||||
content: config.contentField ? stringify(getByPath(item, config.contentField)) : undefined,
|
||||
source: config.sourceField ? stringify(getByPath(item, config.sourceField)) : undefined,
|
||||
author: config.authorField ? stringify(getByPath(item, config.authorField)) : undefined,
|
||||
time: config.timeField ? stringify(getByPath(item, config.timeField)) : undefined,
|
||||
score:
|
||||
config.scoreField && typeof item[config.scoreField] === "number"
|
||||
? (item[config.scoreField] as number)
|
||||
config.scoreField && typeof getByPath(item, config.scoreField) === "number"
|
||||
? (getByPath(item, config.scoreField) as number)
|
||||
: undefined,
|
||||
url: resolveLink(item, config),
|
||||
displayMode: config.mode,
|
||||
resultSetKey: resultSet?.key,
|
||||
resultSetLabel: resultSet?.label,
|
||||
tableColumns: config.tableColumns,
|
||||
raw: item,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -202,8 +202,8 @@ export function collectRuntimeDisplaySources(
|
||||
normalized.map((item) => ({
|
||||
...item,
|
||||
skillName: match?.skillName ?? toolCall.name,
|
||||
mode: effectiveMode,
|
||||
tableColumns: match?.display.tableColumns,
|
||||
mode: item.displayMode ?? effectiveMode,
|
||||
tableColumns: item.tableColumns ?? match?.display.tableColumns,
|
||||
})),
|
||||
seenCitationKeys,
|
||||
() => ++citationIndex,
|
||||
@@ -242,8 +242,8 @@ export function collectRuntimeDisplaySources(
|
||||
normalized.map((item) => ({
|
||||
...item,
|
||||
skillName: match?.skillName ?? toolName,
|
||||
mode: effectiveMode,
|
||||
tableColumns: match?.display.tableColumns,
|
||||
mode: item.displayMode ?? effectiveMode,
|
||||
tableColumns: item.tableColumns ?? match?.display.tableColumns,
|
||||
})),
|
||||
seenCitationKeys,
|
||||
() => ++citationIndex,
|
||||
|
||||
@@ -202,6 +202,24 @@ export async function installSkillUpload(
|
||||
return response.json() as Promise<InstallSkillResponse>;
|
||||
}
|
||||
|
||||
export async function duplicateSkill(
|
||||
sourceName: string,
|
||||
newName: string,
|
||||
): Promise<InstallSkillResponse> {
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/skills/custom/${encodeURIComponent(sourceName)}/duplicate`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ new_name: newName }),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await parseDetailedError(response, "Failed to duplicate skill");
|
||||
}
|
||||
return response.json() as Promise<InstallSkillResponse>;
|
||||
}
|
||||
|
||||
export interface ReconcileCustomSkillsResponse {
|
||||
adopted: string[];
|
||||
already_registered: string[];
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
|
||||
import {
|
||||
deleteCustomSkill,
|
||||
duplicateSkill,
|
||||
enableSkill,
|
||||
getSkill,
|
||||
getSkillContent,
|
||||
@@ -192,6 +193,22 @@ export function useSetSkillPinned() {
|
||||
});
|
||||
}
|
||||
|
||||
export function useDuplicateSkill() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
sourceName,
|
||||
newName,
|
||||
}: {
|
||||
sourceName: string;
|
||||
newName: string;
|
||||
}) => duplicateSkill(sourceName, newName),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["skills"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteCustomSkill() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
|
||||
@@ -12,7 +12,9 @@ export interface SkillDisplayTableColumn {
|
||||
width?: string | null;
|
||||
}
|
||||
|
||||
export interface SkillDisplayConfig {
|
||||
export interface SkillDisplayResultSetConfig {
|
||||
key: string;
|
||||
label?: string | null;
|
||||
enabled: boolean;
|
||||
mode: SkillDisplayMode;
|
||||
resultPath: string;
|
||||
@@ -34,6 +36,10 @@ export interface SkillDisplayConfig {
|
||||
tableColumns?: SkillDisplayTableColumn[];
|
||||
}
|
||||
|
||||
export interface SkillDisplayConfig extends Omit<SkillDisplayResultSetConfig, "key" | "label"> {
|
||||
resultSets?: SkillDisplayResultSetConfig[];
|
||||
}
|
||||
|
||||
export interface Skill {
|
||||
name: string;
|
||||
description: string;
|
||||
|
||||
@@ -7,7 +7,7 @@ function base(): string {
|
||||
|
||||
export async function fetchStudioToken(email: string): Promise<string> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
|
||||
const res = await fetch(
|
||||
`${apiBase}/api/getTokenByEmail?email=${encodeURIComponent(email)}`,
|
||||
@@ -22,7 +22,7 @@ export async function fetchStudioToken(email: string): Promise<string> {
|
||||
|
||||
export async function fetchStudioNotebooks(token: string): Promise<StudioNotebook[]> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
@@ -36,7 +36,7 @@ export async function createSearchSpace(
|
||||
token: string,
|
||||
): Promise<void> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces`, {
|
||||
method: "POST",
|
||||
@@ -46,7 +46,47 @@ export async function createSearchSpace(
|
||||
},
|
||||
body: JSON.stringify({ name, description: "", citations_enabled: true }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`创建失败:${res.status}`);
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => null);
|
||||
throw new Error(body?.detail || `创建失败:${res.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function uploadSourceText(
|
||||
notebookId: number,
|
||||
content: string,
|
||||
title: string,
|
||||
token: string,
|
||||
): Promise<void> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
const res = await fetch(`${apiBase}/api/v1/documents/textupload`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ search_space_id: notebookId, content, title: title || "粘贴的文字" }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`上传失败:${res.status}`);
|
||||
}
|
||||
|
||||
export async function deleteSearchSpace(id: number, token: string): Promise<void> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!res.ok) throw new Error(`删除失败:${res.status}`);
|
||||
}
|
||||
|
||||
export async function renameSearchSpace(id: number, name: string, token: string): Promise<void> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`重命名失败:${res.status}`);
|
||||
}
|
||||
|
||||
export interface ChunkRead {
|
||||
@@ -69,7 +109,7 @@ export async function fetchDocumentByChunk(
|
||||
token: string,
|
||||
): Promise<DocumentWithChunks> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
|
||||
const res = await fetch(`${apiBase}/api/v1/documents/by-chunk/${chunkId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
@@ -78,12 +118,34 @@ export async function fetchDocumentByChunk(
|
||||
return res.json() as Promise<DocumentWithChunks>;
|
||||
}
|
||||
|
||||
export async function uploadSourceFiles(
|
||||
notebookId: number,
|
||||
files: File[],
|
||||
token: string,
|
||||
): Promise<void> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("search_space_id", String(notebookId));
|
||||
for (const file of files) {
|
||||
formData.append("files", file);
|
||||
}
|
||||
|
||||
const res = await fetch(`${apiBase}/api/v1/documents/fileupload`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: formData,
|
||||
});
|
||||
if (!res.ok) throw new Error(`上传失败:${res.status}`);
|
||||
}
|
||||
|
||||
export async function fetchNotebookSources(
|
||||
notebookId: number,
|
||||
token: string,
|
||||
): Promise<SourceItem[]> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
|
||||
const res = await fetch(
|
||||
`${apiBase}/api/v1/source/search-space/${notebookId}?limit=100`,
|
||||
|
||||
@@ -12,6 +12,7 @@ export function useStudioNotebooks(): {
|
||||
notebooks: StudioNotebook[];
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
token: string | undefined;
|
||||
} {
|
||||
const email = getStoredAuth()?.email ?? "";
|
||||
|
||||
@@ -35,6 +36,7 @@ export function useStudioNotebooks(): {
|
||||
notebooks: (notebooksQuery.data ?? []).filter((nb) => nb.is_owner),
|
||||
isLoading: tokenQuery.isLoading || notebooksQuery.isLoading,
|
||||
isError: tokenQuery.isError || notebooksQuery.isError,
|
||||
token: tokenQuery.data,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,10 +91,15 @@ export function useNotebookChat(
|
||||
|
||||
const send = async (text: string, selectedSourceIds: number[]) => {
|
||||
if (thread.isLoading || !token) return;
|
||||
// API 需要 document.id,而不是 source.id
|
||||
const toDocIds = (ids: number[]) =>
|
||||
ids
|
||||
.map((id) => sources.find((s) => s.id === id)?.document?.id)
|
||||
.filter((id): id is number => id !== undefined);
|
||||
const sourceIds =
|
||||
selectedSourceIds.length > 0
|
||||
? selectedSourceIds
|
||||
: sources.map((s) => s.id).filter(Boolean);
|
||||
? toDocIds(selectedSourceIds)
|
||||
: sources.map((s) => s.document?.id).filter((id): id is number => id !== undefined);
|
||||
|
||||
await thread.submit(
|
||||
{ messages: [{ type: "human", content: text }] },
|
||||
|
||||
@@ -350,9 +350,12 @@ export function useThreadStream({
|
||||
// agent thread URL — otherwise fall back to the global new chat.
|
||||
const hash = typeof window !== "undefined" ? window.location.hash : "";
|
||||
const agentMatch = hash.match(/#\/page\/workspace\/agents\/([^/]+)\//);
|
||||
const target = agentMatch
|
||||
? `/page/workspace/agents/${agentMatch[1]}/chats/new`
|
||||
: "/page/workspace/chats/new";
|
||||
const iframeMatch = hash.match(/#\/page\/workspace\/chats_iframe\//);
|
||||
const target = agentMatch
|
||||
? `/page/workspace/agents/${agentMatch[1]}/chats/new`
|
||||
: iframeMatch
|
||||
? "/page/workspace/chats_iframe/new"
|
||||
: "/page/workspace/chats/new";
|
||||
// First navigate to a safe URL so the post-reload page lands on a
|
||||
// valid route. Then full-reload so TanStack Query cache, context
|
||||
// providers and any other state captured under the previous user's
|
||||
|
||||
@@ -65,3 +65,15 @@ export function textOfMessage(message: Message) {
|
||||
export function titleOfThread(thread: AgentThread) {
|
||||
return thread.values?.title ?? "Untitled";
|
||||
}
|
||||
|
||||
export function sanitizeThreadTitleForDisplay(title: string | null | undefined) {
|
||||
if (!title) return "Untitled";
|
||||
|
||||
const cleaned = title
|
||||
.replace(/<\/?[^>\n]+>/g, " ")
|
||||
.replace(/<[^>\n]*$/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
|
||||
return cleaned || "Untitled";
|
||||
}
|
||||
Reference in new issue
Block a user