Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-server into xuhd
This commit is contained in:
commit
070cd07199
372 files changed
+86240
-4969
No files matched your search
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { Client as LangGraphClient } from "@langchain/langgraph-sdk/client";
|
||||
|
||||
import { getAuthorizationHeaderValue } from "../auth";
|
||||
import { getCanvasLangGraphBaseURL } from "../config";
|
||||
|
||||
import { sanitizeRunStreamOptions } from "./stream-mode";
|
||||
|
||||
/**
|
||||
* Dedicated LangGraph client for the Canvas page.
|
||||
*
|
||||
* Keeping this separate from getAPIClient() means:
|
||||
* - Canvas API calls can be pointed at a different server via VITE_CANVAS_LANGGRAPH_BASE_URL
|
||||
* - Canvas-specific HTTP-level logic (headers, retries, middleware) lives here
|
||||
* - Changes here never touch the main page's API path
|
||||
*/
|
||||
function createCanvasClient(): LangGraphClient {
|
||||
const client = new LangGraphClient({
|
||||
apiUrl: getCanvasLangGraphBaseURL(),
|
||||
onRequest(_url, init) {
|
||||
const headers = new Headers(init.headers ?? {});
|
||||
const authHeader = getAuthorizationHeaderValue();
|
||||
if (authHeader && !headers.has("Authorization")) {
|
||||
headers.set("Authorization", authHeader);
|
||||
}
|
||||
return { ...init, headers };
|
||||
},
|
||||
});
|
||||
|
||||
const originalRunStream = client.runs.stream.bind(client.runs);
|
||||
client.runs.stream = ((threadId, assistantId, payload) =>
|
||||
originalRunStream(
|
||||
threadId,
|
||||
assistantId,
|
||||
sanitizeRunStreamOptions(payload),
|
||||
)) as typeof client.runs.stream;
|
||||
|
||||
const originalJoinStream = client.runs.joinStream.bind(client.runs);
|
||||
client.runs.joinStream = ((threadId, runId, options) =>
|
||||
originalJoinStream(
|
||||
threadId,
|
||||
runId,
|
||||
sanitizeRunStreamOptions(options),
|
||||
)) as typeof client.runs.joinStream;
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
let _canvasClient: LangGraphClient | null = null;
|
||||
|
||||
export function getCanvasAPIClient(): LangGraphClient {
|
||||
if (!_canvasClient) {
|
||||
_canvasClient = createCanvasClient();
|
||||
}
|
||||
return _canvasClient;
|
||||
}
|
||||
@@ -1,5 +1,18 @@
|
||||
import { env } from "@/env";
|
||||
|
||||
/**
|
||||
* 内网知识库「查看原文」详情页地址前缀。
|
||||
* 素材的 recUuid 直接拼接在其后即为完整原文链接。
|
||||
*/
|
||||
export const INTRANET_SOURCE_URL_BASE =
|
||||
"https://chlib.b.uat.4.cn/knowlibrary/#/knowledge/mid_detail?recUuid=";
|
||||
|
||||
/** 由 recUuid 构造内网原文详情页地址;recUuid 为空时返回空串。 */
|
||||
export function buildIntranetSourceUrl(recUuid?: string | null): string {
|
||||
if (!recUuid) return "";
|
||||
return `${INTRANET_SOURCE_URL_BASE}${encodeURIComponent(recUuid)}`;
|
||||
}
|
||||
|
||||
function getBaseOrigin() {
|
||||
if (typeof window !== "undefined") {
|
||||
return window.location.origin;
|
||||
@@ -18,6 +31,23 @@ export function getBackendBaseURL() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Canvas page has its own LangGraph base URL so canvas-specific modifications
|
||||
* (different server, different route prefix, etc.) can be made independently
|
||||
* without touching the main page's API path.
|
||||
* Falls back to the main LangGraph URL when VITE_CANVAS_LANGGRAPH_BASE_URL is unset.
|
||||
*/
|
||||
export function getCanvasLangGraphBaseURL(): string {
|
||||
if (env.NEXT_PUBLIC_CANVAS_LANGGRAPH_BASE_URL) {
|
||||
return new URL(
|
||||
env.NEXT_PUBLIC_CANVAS_LANGGRAPH_BASE_URL,
|
||||
getBaseOrigin(),
|
||||
).toString();
|
||||
}
|
||||
// Fall back to the main LangGraph URL (same server, different assistantId)
|
||||
return getLangGraphBaseURL();
|
||||
}
|
||||
|
||||
export function getLangGraphBaseURL(isMock?: boolean) {
|
||||
if (env.NEXT_PUBLIC_LANGGRAPH_BASE_URL) {
|
||||
return new URL(
|
||||
|
||||
@@ -250,6 +250,35 @@ export const enUS: Translations = {
|
||||
searchChats: "Search chats",
|
||||
},
|
||||
|
||||
// Conversation sharing
|
||||
threadShare: {
|
||||
importChats: "Import chat",
|
||||
shareTitle: "Share conversation",
|
||||
shareDescription:
|
||||
'Share this conversation with others. They enter the code under "Import chat" to copy it into their own account and keep chatting.',
|
||||
generating: "Generating code...",
|
||||
shareCodeLabel: "Share code",
|
||||
copyCode: "Copy",
|
||||
codeCopied: "Share code copied",
|
||||
shareHint:
|
||||
"Anyone who has the code can copy this conversation — share it carefully.",
|
||||
revoke: "Revoke share",
|
||||
revokeConfirm: "Revoking makes the code unusable immediately. Continue?",
|
||||
revokeSuccess: "Share revoked",
|
||||
importTitle: "Import a conversation",
|
||||
importDescription:
|
||||
"Enter a share code to copy the shared conversation into your account.",
|
||||
codeInputPlaceholder: "Paste a share code",
|
||||
preview: "Preview",
|
||||
previewConversation: "Conversation: {title}",
|
||||
previewFrom: "From user {user}",
|
||||
doImport: "Import",
|
||||
importing: "Importing...",
|
||||
importSuccess: "Conversation imported",
|
||||
alreadyImported: "You have already imported this conversation",
|
||||
emptyCode: "Enter a share code first",
|
||||
},
|
||||
|
||||
// Page titles (document title)
|
||||
pages: {
|
||||
appName: "CM Assistant",
|
||||
|
||||
@@ -194,6 +194,32 @@ export interface Translations {
|
||||
searchChats: string;
|
||||
};
|
||||
|
||||
// Conversation sharing
|
||||
threadShare: {
|
||||
importChats: string;
|
||||
shareTitle: string;
|
||||
shareDescription: string;
|
||||
generating: string;
|
||||
shareCodeLabel: string;
|
||||
copyCode: string;
|
||||
codeCopied: string;
|
||||
shareHint: string;
|
||||
revoke: string;
|
||||
revokeConfirm: string;
|
||||
revokeSuccess: string;
|
||||
importTitle: string;
|
||||
importDescription: string;
|
||||
codeInputPlaceholder: string;
|
||||
preview: string;
|
||||
previewConversation: string;
|
||||
previewFrom: string;
|
||||
doImport: string;
|
||||
importing: string;
|
||||
importSuccess: string;
|
||||
alreadyImported: string;
|
||||
emptyCode: string;
|
||||
};
|
||||
|
||||
// Page titles (document title)
|
||||
pages: {
|
||||
appName: string;
|
||||
|
||||
@@ -238,6 +238,33 @@ export const zhCN: Translations = {
|
||||
searchChats: "搜索对话",
|
||||
},
|
||||
|
||||
// Conversation sharing
|
||||
threadShare: {
|
||||
importChats: "导入对话",
|
||||
shareTitle: "分享对话",
|
||||
shareDescription:
|
||||
"把这个对话分享给他人。对方在「导入对话」里填入分享码,即可把它复制一份到自己账号并继续聊天。",
|
||||
generating: "生成分享码中...",
|
||||
shareCodeLabel: "分享码",
|
||||
copyCode: "复制",
|
||||
codeCopied: "分享码已复制",
|
||||
shareHint: "知道分享码的人都能复制这个对话,请谨慎分享。",
|
||||
revoke: "撤销分享",
|
||||
revokeConfirm: "撤销后该分享码立即失效,确定撤销?",
|
||||
revokeSuccess: "已撤销分享",
|
||||
importTitle: "导入对话",
|
||||
importDescription: "填入对方给你的分享码,把 TA 分享的那个对话复制到你的账号。",
|
||||
codeInputPlaceholder: "粘贴分享码",
|
||||
preview: "预览",
|
||||
previewConversation: "对话:{title}",
|
||||
previewFrom: "来自用户 {user}",
|
||||
doImport: "导入",
|
||||
importing: "导入中...",
|
||||
importSuccess: "对话已导入",
|
||||
alreadyImported: "你已经导入过这个对话了",
|
||||
emptyCode: "请先填入分享码",
|
||||
},
|
||||
|
||||
// Page titles (document title)
|
||||
pages: {
|
||||
appName: "CM 助手",
|
||||
|
||||
@@ -14,20 +14,20 @@ interface AssistantMessageGroup extends GenericMessageGroup<"assistant"> {}
|
||||
|
||||
interface AssistantPresentFilesGroup extends GenericMessageGroup<"assistant:present-files"> {}
|
||||
|
||||
interface AssistantClarificationGroup extends GenericMessageGroup<"assistant:clarification"> {}
|
||||
|
||||
interface AssistantSetupAgentApprovalGroup extends GenericMessageGroup<"assistant:setup-agent-approval"> {}
|
||||
|
||||
interface AssistantSubagentGroup extends GenericMessageGroup<"assistant:subagent"> {}
|
||||
interface AssistantClarificationGroup extends GenericMessageGroup<"assistant:clarification"> {}
|
||||
|
||||
interface AssistantSetupAgentApprovalGroup extends GenericMessageGroup<"assistant:setup-agent-approval"> {}
|
||||
|
||||
interface AssistantSubagentGroup extends GenericMessageGroup<"assistant:subagent"> {}
|
||||
|
||||
type MessageGroup =
|
||||
| HumanMessageGroup
|
||||
| AssistantProcessingGroup
|
||||
| AssistantMessageGroup
|
||||
| AssistantPresentFilesGroup
|
||||
| AssistantClarificationGroup
|
||||
| AssistantSetupAgentApprovalGroup
|
||||
| AssistantSubagentGroup;
|
||||
| AssistantPresentFilesGroup
|
||||
| AssistantClarificationGroup
|
||||
| AssistantSetupAgentApprovalGroup
|
||||
| AssistantSubagentGroup;
|
||||
|
||||
export function groupMessages<T>(
|
||||
messages: Message[],
|
||||
@@ -44,11 +44,11 @@ export function groupMessages<T>(
|
||||
function lastOpenGroup() {
|
||||
const last = groups[groups.length - 1];
|
||||
if (
|
||||
last &&
|
||||
last.type !== "human" &&
|
||||
last.type !== "assistant" &&
|
||||
last.type !== "assistant:clarification" &&
|
||||
last.type !== "assistant:setup-agent-approval"
|
||||
last &&
|
||||
last.type !== "human" &&
|
||||
last.type !== "assistant" &&
|
||||
last.type !== "assistant:clarification" &&
|
||||
last.type !== "assistant:setup-agent-approval"
|
||||
) {
|
||||
return last;
|
||||
}
|
||||
@@ -70,23 +70,23 @@ export function groupMessages<T>(
|
||||
}
|
||||
|
||||
if (message.type === "tool") {
|
||||
if (isClarificationToolMessage(message)) {
|
||||
if (isClarificationToolMessage(message)) {
|
||||
// Add to the preceding processing group to preserve tool-call association,
|
||||
// then also open a standalone clarification group for prominent display.
|
||||
lastOpenGroup()?.messages.push(message);
|
||||
groups.push({
|
||||
id: message.id,
|
||||
type: "assistant:clarification",
|
||||
messages: [message],
|
||||
});
|
||||
} else if (isSetupAgentApprovalToolMessage(message)) {
|
||||
lastOpenGroup()?.messages.push(message);
|
||||
groups.push({
|
||||
id: message.id,
|
||||
type: "assistant:setup-agent-approval",
|
||||
messages: [message],
|
||||
});
|
||||
} else {
|
||||
messages: [message],
|
||||
});
|
||||
} else if (isSetupAgentApprovalToolMessage(message)) {
|
||||
lastOpenGroup()?.messages.push(message);
|
||||
groups.push({
|
||||
id: message.id,
|
||||
type: "assistant:setup-agent-approval",
|
||||
messages: [message],
|
||||
});
|
||||
} else {
|
||||
const open = lastOpenGroup();
|
||||
if (open) {
|
||||
open.messages.push(message);
|
||||
@@ -297,19 +297,19 @@ export function hasPresentFiles(message: Message) {
|
||||
);
|
||||
}
|
||||
|
||||
export function isClarificationToolMessage(message: Message) {
|
||||
return message.type === "tool" && message.name === "ask_clarification";
|
||||
}
|
||||
|
||||
export function isSetupAgentApprovalToolMessage(message: Message) {
|
||||
return (
|
||||
message.type === "tool" &&
|
||||
message.name === "setup_agent" &&
|
||||
typeof message.additional_kwargs?.setup_agent_approval === "object" &&
|
||||
message.additional_kwargs.setup_agent_approval !== null
|
||||
);
|
||||
}
|
||||
|
||||
export function isClarificationToolMessage(message: Message) {
|
||||
return message.type === "tool" && message.name === "ask_clarification";
|
||||
}
|
||||
|
||||
export function isSetupAgentApprovalToolMessage(message: Message) {
|
||||
return (
|
||||
message.type === "tool" &&
|
||||
message.name === "setup_agent" &&
|
||||
typeof message.additional_kwargs?.setup_agent_approval === "object" &&
|
||||
message.additional_kwargs.setup_agent_approval !== null
|
||||
);
|
||||
}
|
||||
|
||||
export function extractPresentFilesFromMessage(message: Message) {
|
||||
if (message.type !== "ai" || !hasPresentFiles(message)) {
|
||||
return [];
|
||||
@@ -372,6 +372,13 @@ export function stripUploadedFilesTag(content: string): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Strip injected <artifact ...>...</artifact> blocks from human message display. */
|
||||
export function stripArtifactTag(content: string): string {
|
||||
return content
|
||||
.replace(/<artifact[^>]*>[\s\S]*?<\/artifact>/g, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function parseUploadedFiles(content: string): FileInMessage[] {
|
||||
// Match <uploaded_files>...</uploaded_files> tag
|
||||
const uploadedFilesRegex = /<uploaded_files>([\s\S]*?)<\/uploaded_files>/;
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
ScheduledTaskResultFileContent,
|
||||
ScheduledTaskRun,
|
||||
ScheduledTaskRunFileUpdateResponse,
|
||||
ScheduledTaskRunMessagesResponse,
|
||||
ScheduledTaskSubscription,
|
||||
SchedulerThread,
|
||||
} from "./types";
|
||||
@@ -79,6 +80,13 @@ export async function deleteScheduledTaskRun(runId: string) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Agent messages for a run's underlying agent run — used to inspect a stuck/running run. */
|
||||
export async function getScheduledTaskRunMessages(runId: string) {
|
||||
return parseResponse<ScheduledTaskRunMessagesResponse>(
|
||||
await apiFetch(`${baseUrl()}/runs/${encodeURIComponent(runId)}/messages`),
|
||||
);
|
||||
}
|
||||
|
||||
export function scheduledTaskRunDownloadUrl(runId: string) {
|
||||
return `${baseUrl()}/runs/${encodeURIComponent(runId)}/download`;
|
||||
}
|
||||
@@ -296,3 +304,61 @@ export async function unsubscribeScheduledTask(taskId: string) {
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// --- Admin (cross-user management) ---
|
||||
|
||||
/** List every scheduled task across all users. Admin-only endpoint. */
|
||||
export async function listAllScheduledTasks(search?: string) {
|
||||
const qs = new URLSearchParams();
|
||||
if (search) qs.set("search", search);
|
||||
const query = qs.toString();
|
||||
return parseResponse<ScheduledTask[]>(
|
||||
await apiFetch(`${baseUrl()}/admin/all${query ? `?${query}` : ""}`),
|
||||
);
|
||||
}
|
||||
|
||||
/** List runs for any task regardless of owner. Admin-only endpoint. */
|
||||
export async function adminListScheduledTaskRuns(taskId: string) {
|
||||
return parseResponse<ScheduledTaskRun[]>(
|
||||
await apiFetch(`${baseUrl()}/admin/${encodeURIComponent(taskId)}/runs`),
|
||||
);
|
||||
}
|
||||
|
||||
/** Update any task regardless of owner. Admin-only endpoint. */
|
||||
export async function adminUpdateScheduledTask(
|
||||
taskId: string,
|
||||
data: Partial<{
|
||||
name: string;
|
||||
prompt: string;
|
||||
schedule: string;
|
||||
timezone: string;
|
||||
enabled: boolean;
|
||||
execution_agent_name: string | null;
|
||||
}>,
|
||||
) {
|
||||
return parseResponse<ScheduledTask>(
|
||||
await apiFetch(`${baseUrl()}/admin/${encodeURIComponent(taskId)}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Delete any task regardless of owner. Admin-only endpoint. */
|
||||
export async function adminDeleteScheduledTask(taskId: string) {
|
||||
return parseResponse<{ success: boolean }>(
|
||||
await apiFetch(`${baseUrl()}/admin/${encodeURIComponent(taskId)}`, {
|
||||
method: "DELETE",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Trigger an immediate run of any task regardless of owner. Admin-only. */
|
||||
export async function adminTriggerScheduledTask(taskId: string) {
|
||||
return parseResponse<{ success: boolean; task: ScheduledTask }>(
|
||||
await apiFetch(`${baseUrl()}/admin/${encodeURIComponent(taskId)}/trigger`, {
|
||||
method: "POST",
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -6,12 +6,18 @@ import {
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import {
|
||||
adminDeleteScheduledTask,
|
||||
adminListScheduledTaskRuns,
|
||||
adminTriggerScheduledTask,
|
||||
adminUpdateScheduledTask,
|
||||
createScheduledTask,
|
||||
deleteScheduledTask,
|
||||
deleteScheduledTaskRun,
|
||||
getSchedulerThread,
|
||||
getScheduledTaskDeliveryProfile,
|
||||
getScheduledTaskRun,
|
||||
getScheduledTaskRunMessages,
|
||||
listAllScheduledTasks,
|
||||
listPublishedScheduledTasks,
|
||||
listScheduledTaskRuns,
|
||||
listScheduledTasks,
|
||||
@@ -57,12 +63,34 @@ export function useScheduledTaskRuns(taskId?: string | null) {
|
||||
});
|
||||
}
|
||||
|
||||
/** A run still in flight — used to drive live polling of the run/messages. */
|
||||
function runIsLive(status?: string | null): boolean {
|
||||
return status === "running" || status === "pending";
|
||||
}
|
||||
|
||||
export function useScheduledTaskRun(runId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ["scheduled-tasks", "runs", runId],
|
||||
queryFn: () => getScheduledTaskRun(runId!),
|
||||
enabled: !!runId,
|
||||
refetchOnWindowFocus: false,
|
||||
// Keep refreshing while the run is still executing so the detail page
|
||||
// reflects status / result changes without a manual reload.
|
||||
refetchInterval: (query) => (runIsLive(query.state.data?.status) ? 5000 : false),
|
||||
});
|
||||
}
|
||||
|
||||
/** Agent messages for a run; polls every 4s while the run is still executing. */
|
||||
export function useScheduledTaskRunMessages(
|
||||
runId?: string | null,
|
||||
options: { live?: boolean } = {},
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["scheduled-tasks", "runs", runId, "messages"],
|
||||
queryFn: () => getScheduledTaskRunMessages(runId!),
|
||||
enabled: !!runId,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchInterval: options.live ? 4000 : false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -74,6 +102,64 @@ export function useScheduledTaskDeliveryProfile() {
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin: every scheduled task across all users. */
|
||||
export function useAllScheduledTasks(
|
||||
params: { search?: string; enabled?: boolean } = {},
|
||||
) {
|
||||
const search = params.search ?? "";
|
||||
return useQuery({
|
||||
queryKey: ["scheduled-tasks", "admin", "list", search],
|
||||
queryFn: () => listAllScheduledTasks(search),
|
||||
enabled: params.enabled ?? true,
|
||||
refetchOnWindowFocus: false,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin: runs for any task regardless of owner. */
|
||||
export function useAdminScheduledTaskRuns(taskId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ["scheduled-tasks", "admin", taskId, "runs"],
|
||||
queryFn: () => adminListScheduledTaskRuns(taskId!),
|
||||
enabled: !!taskId,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin mutations: edit / delete / trigger any task. */
|
||||
export function useAdminScheduledTaskActions() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () =>
|
||||
queryClient.invalidateQueries({ queryKey: ["scheduled-tasks"] });
|
||||
|
||||
return {
|
||||
update: useMutation({
|
||||
mutationFn: ({
|
||||
taskId,
|
||||
data,
|
||||
}: {
|
||||
taskId: string;
|
||||
data: Parameters<typeof adminUpdateScheduledTask>[1];
|
||||
}) => adminUpdateScheduledTask(taskId, data),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
remove: useMutation({
|
||||
mutationFn: adminDeleteScheduledTask,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
// The DELETE /runs/{id} route is admin-aware, so the same call deletes
|
||||
// any user's run when the caller is an admin.
|
||||
removeRun: useMutation({
|
||||
mutationFn: deleteScheduledTaskRun,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
trigger: useMutation({
|
||||
mutationFn: adminTriggerScheduledTask,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function usePublishedScheduledTasks(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: ["scheduled-tasks", "published"],
|
||||
|
||||
@@ -94,6 +94,7 @@ export type ScheduledTaskRun = {
|
||||
status: "pending" | "running" | "succeeded" | "failed" | string;
|
||||
error?: string | null;
|
||||
result?: ScheduledTaskRunResult | null;
|
||||
retry_count?: number | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
can_edit?: boolean;
|
||||
@@ -106,3 +107,19 @@ export type ScheduledTaskRunFileUpdateResponse = {
|
||||
mime_type?: string | null;
|
||||
kind?: string | null;
|
||||
};
|
||||
|
||||
/** One agent message produced by a scheduled run's underlying agent run. */
|
||||
export type ScheduledTaskRunMessage = {
|
||||
seq: number;
|
||||
event_type: string;
|
||||
category: string;
|
||||
// string for human input; object (LangChain message dump) for ai/tool.
|
||||
content: unknown;
|
||||
metadata?: Record<string, unknown> | null;
|
||||
created_at?: string | null;
|
||||
};
|
||||
|
||||
export type ScheduledTaskRunMessagesResponse = {
|
||||
messages: ScheduledTaskRunMessage[];
|
||||
has_more: boolean;
|
||||
};
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { Message } from "@langchain/langgraph-sdk";
|
||||
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
/**
|
||||
* Share modes:
|
||||
* - `import` — recipient (a logged-in user) copies the conversation into
|
||||
* their own account and can keep chatting in the copy.
|
||||
* - `view` — a public, read-only static page anyone can open without
|
||||
* logging in; viewers cannot send new messages.
|
||||
*/
|
||||
export type ThreadShareMode = "import" | "view";
|
||||
|
||||
export interface ThreadShare {
|
||||
share_code: string;
|
||||
owner_user_id: string;
|
||||
thread_id: string;
|
||||
revoked: boolean;
|
||||
mode: ThreadShareMode;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
/** Read-only conversation snapshot returned by the public view-share endpoint. */
|
||||
export interface PublicShareSnapshot {
|
||||
share_code: string;
|
||||
title: string;
|
||||
mode: string;
|
||||
messages: Message[];
|
||||
artifacts: string[];
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
export interface SharePreview {
|
||||
share_code: string;
|
||||
shared_by: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
imported: number;
|
||||
skipped: number;
|
||||
}
|
||||
|
||||
const baseUrl = () => `${getBackendBaseURL()}/api/thread-shares`;
|
||||
|
||||
async function parseError(response: Response, fallback: string): Promise<Error> {
|
||||
const data = (await response.json().catch(() => ({}))) as { detail?: unknown };
|
||||
const detail = data.detail;
|
||||
const message =
|
||||
typeof detail === "string" && detail
|
||||
? detail
|
||||
: `${fallback} (HTTP ${response.status})`;
|
||||
return new Error(message);
|
||||
}
|
||||
|
||||
/** Create (or reuse) a share code for one conversation in the given mode. */
|
||||
export async function createShare(
|
||||
threadId: string,
|
||||
mode: ThreadShareMode = "import",
|
||||
): Promise<ThreadShare> {
|
||||
const response = await apiFetch(baseUrl(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ thread_id: threadId, mode }),
|
||||
});
|
||||
if (!response.ok) throw await parseError(response, "创建分享失败");
|
||||
return response.json() as Promise<ThreadShare>;
|
||||
}
|
||||
|
||||
/** List the current user's own share links. */
|
||||
export async function listShares(): Promise<ThreadShare[]> {
|
||||
const response = await apiFetch(baseUrl());
|
||||
if (!response.ok) throw await parseError(response, "加载分享列表失败");
|
||||
const json = (await response.json()) as { shares: ThreadShare[] };
|
||||
return json.shares;
|
||||
}
|
||||
|
||||
/** Revoke a share link so it can no longer be previewed or imported. */
|
||||
export async function revokeShare(shareCode: string): Promise<void> {
|
||||
const response = await apiFetch(`${baseUrl()}/${encodeURIComponent(shareCode)}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!response.ok) throw await parseError(response, "撤销分享失败");
|
||||
}
|
||||
|
||||
/** Preview a share link before importing it. */
|
||||
export async function previewShare(shareCode: string): Promise<SharePreview> {
|
||||
const response = await apiFetch(
|
||||
`${baseUrl()}/${encodeURIComponent(shareCode)}/preview`,
|
||||
);
|
||||
if (!response.ok) throw await parseError(response, "无法读取该分享");
|
||||
return response.json() as Promise<SharePreview>;
|
||||
}
|
||||
|
||||
/** Import every conversation behind a share link into the current account. */
|
||||
export async function importShare(shareCode: string): Promise<ImportResult> {
|
||||
const response = await apiFetch(
|
||||
`${baseUrl()}/${encodeURIComponent(shareCode)}/import`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
if (!response.ok) throw await parseError(response, "导入失败");
|
||||
return response.json() as Promise<ImportResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the public read-only snapshot of a `view`-mode share.
|
||||
*
|
||||
* Uses a plain `fetch` (no auth header) — the `/api/public/` endpoint is
|
||||
* intentionally world-readable so anyone with the link can open it.
|
||||
*/
|
||||
export async function getPublicShareSnapshot(
|
||||
shareCode: string,
|
||||
): Promise<PublicShareSnapshot> {
|
||||
const response = await fetch(
|
||||
`${getBackendBaseURL()}/api/public/shares/${encodeURIComponent(shareCode)}`,
|
||||
);
|
||||
if (!response.ok) throw await parseError(response, "无法打开该分享");
|
||||
return response.json() as Promise<PublicShareSnapshot>;
|
||||
}
|
||||
|
||||
/** Build the shareable public URL for a `view`-mode share code. */
|
||||
export function buildPublicShareUrl(shareCode: string): string {
|
||||
// The app uses HashRouter, so the public viewer lives at `#/share/<code>`.
|
||||
return `${window.location.origin}${window.location.pathname}#/share/${shareCode}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a share code from arbitrary pasted text — accepts either a raw code
|
||||
* or a URL/link that contains one. Share codes are 6-12 chars from the
|
||||
* unambiguous alphabet (no 0/1/O/I/L).
|
||||
*/
|
||||
export function extractShareCode(input: string): string {
|
||||
const trimmed = input.trim();
|
||||
const matches = trimmed.toUpperCase().match(/[A-HJ-NP-Z2-9]{6,12}/g);
|
||||
return matches && matches.length > 0 ? matches[matches.length - 1] : trimmed;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import {
|
||||
createShare,
|
||||
importShare,
|
||||
listShares,
|
||||
previewShare,
|
||||
revokeShare,
|
||||
type ThreadShareMode,
|
||||
} from "./api";
|
||||
|
||||
export function useShares(enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: ["thread-shares"],
|
||||
queryFn: listShares,
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateShare() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
threadId,
|
||||
mode = "import",
|
||||
}: {
|
||||
threadId: string;
|
||||
mode?: ThreadShareMode;
|
||||
}) => createShare(threadId, mode),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["thread-shares"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useRevokeShare() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (shareCode: string) => revokeShare(shareCode),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["thread-shares"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function usePreviewShare() {
|
||||
return useMutation({
|
||||
mutationFn: (shareCode: string) => previewShare(shareCode),
|
||||
});
|
||||
}
|
||||
|
||||
export function useImportShare() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (shareCode: string) => importShare(shareCode),
|
||||
onSuccess: () => {
|
||||
// Imported conversations show up in the user's own thread list.
|
||||
void queryClient.invalidateQueries({ queryKey: ["threads"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user