Merge remote-tracking branch 'origin/master' into ji
# Conflicts: # .gitignore # frontend-web/src/components/workspace/artifacts/context.tsx # frontend-web/src/components/workspace/messages/message-group.tsx # offline-backend-20260512/backend/CLAUDE.md # offline-backend-20260512/backend/README.md # offline-backend-20260512/backend/app/gateway/app.py # offline-backend-20260512/backend/app/gateway/deps.py # offline-backend-20260512/backend/app/gateway/routers/llmwiki.py
This commit is contained in:
commit
e818c24769
262 files changed
+29527
-5236
No files matched your search
@@ -3,7 +3,12 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
import type { CompactMenuOverride } from "@/core/page-layout/compact-menu-overrides";
|
||||
import {
|
||||
getRuntimeCompactMenuType,
|
||||
isDefaultCompactMenuType,
|
||||
type CompactMenuOverride,
|
||||
type CompactMenuType,
|
||||
} from "@/core/page-layout/compact-menu-overrides";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/compact-menu-overrides`;
|
||||
|
||||
@@ -12,6 +17,7 @@ interface ServerCompactOverride {
|
||||
placement: "sidebar" | "settings";
|
||||
sort_order: number;
|
||||
label: string | null;
|
||||
menu_type?: string | null;
|
||||
}
|
||||
|
||||
function toOverride(s: ServerCompactOverride): CompactMenuOverride {
|
||||
@@ -44,27 +50,40 @@ async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
export async function listCompactMenuOverrides(): Promise<CompactMenuOverride[]> {
|
||||
const res = await apiFetch(BASE(), { method: "GET" });
|
||||
export async function listCompactMenuOverrides(
|
||||
menuType: CompactMenuType = getRuntimeCompactMenuType(),
|
||||
): Promise<CompactMenuOverride[]> {
|
||||
// 旧页面 / 未配置 VITE_COMPACT_MENU_TYPE 时不带参数,后端按类型 A 返回原来的数据。
|
||||
const url = isDefaultCompactMenuType(menuType)
|
||||
? BASE()
|
||||
: `${BASE()}?menu_type=${encodeURIComponent(menuType)}`;
|
||||
const res = await apiFetch(url, { method: "GET" });
|
||||
const data = await readJson<{ overrides: ServerCompactOverride[] }>(res, "list compact menu overrides");
|
||||
return (data.overrides ?? []).map(toOverride);
|
||||
}
|
||||
|
||||
export async function replaceCompactMenuOverrides(
|
||||
overrides: CompactMenuOverride[],
|
||||
menuType: CompactMenuType = getRuntimeCompactMenuType(),
|
||||
): Promise<CompactMenuOverride[]> {
|
||||
const body: { overrides: ServerCompactOverride[]; menu_type?: CompactMenuType } = {
|
||||
overrides: overrides.map(toBody),
|
||||
};
|
||||
if (!isDefaultCompactMenuType(menuType)) {
|
||||
body.menu_type = menuType;
|
||||
}
|
||||
const res = await apiFetch(BASE(), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ overrides: overrides.map(toBody) }),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await readJson<{ overrides: ServerCompactOverride[] }>(res, "save compact menu overrides");
|
||||
const saved = (data.overrides ?? []).map(toOverride);
|
||||
writeYLog({
|
||||
optType: OptType.edit,
|
||||
optDetail: "CM助手-简介-菜单管理-保存",
|
||||
optDetail: `CM助手-简介-菜单管理-保存-类型${menuType}`,
|
||||
url: "/api/compact-menu-overrides",
|
||||
reqParam: { overrides },
|
||||
reqParam: { menuType, overrides },
|
||||
returnParam: saved,
|
||||
});
|
||||
return saved;
|
||||
@@ -72,21 +91,23 @@ export async function replaceCompactMenuOverrides(
|
||||
|
||||
const COMPACT_MENU_OVERRIDES_KEY = "compact-menu-overrides";
|
||||
|
||||
export function useCompactMenuOverrides() {
|
||||
export function useCompactMenuOverrides(menuType?: CompactMenuType) {
|
||||
const type = menuType ?? getRuntimeCompactMenuType();
|
||||
return useQuery({
|
||||
queryKey: [COMPACT_MENU_OVERRIDES_KEY],
|
||||
queryFn: listCompactMenuOverrides,
|
||||
queryKey: [COMPACT_MENU_OVERRIDES_KEY, type],
|
||||
queryFn: () => listCompactMenuOverrides(type),
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCompactMenuOverrideActions() {
|
||||
export function useCompactMenuOverrideActions(menuType?: CompactMenuType) {
|
||||
const queryClient = useQueryClient();
|
||||
const type = menuType ?? getRuntimeCompactMenuType();
|
||||
return {
|
||||
save: useMutation({
|
||||
mutationFn: replaceCompactMenuOverrides,
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: [COMPACT_MENU_OVERRIDES_KEY] }),
|
||||
mutationFn: (overrides: CompactMenuOverride[]) => replaceCompactMenuOverrides(overrides, type),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: [COMPACT_MENU_OVERRIDES_KEY, type] }),
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { createClientId } from "@/lib/client-id";
|
||||
import type {
|
||||
DocumentRewriteSummary,
|
||||
DocumentRewriteStreamEvent,
|
||||
@@ -338,9 +339,10 @@ export interface StartJobOptions {
|
||||
requestId?: string;
|
||||
/**
|
||||
* "chat" harvests the collector-agent conversation's materials as the pool;
|
||||
* "legacy" (default) keeps the runner-driven search tiers.
|
||||
* "legacy" (default) keeps the runner-driven search tiers; "regenerate"
|
||||
* runs the same report engine again over the variant's selected source pool.
|
||||
*/
|
||||
entry?: "chat" | "legacy";
|
||||
entry?: "chat" | "legacy" | "regenerate";
|
||||
/** Report-config card choices merged over the frozen session snapshot. */
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
@@ -355,7 +357,7 @@ export async function startJob(
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
request_id: opts.requestId ?? crypto.randomUUID(),
|
||||
request_id: opts.requestId ?? createClientId(),
|
||||
entry: opts.entry ?? "legacy",
|
||||
config: opts.config ?? null,
|
||||
}),
|
||||
@@ -628,6 +630,36 @@ export function streamResearchRewrite(
|
||||
return streamResearchMessage(sessionId, instruction, handlers, signal, "rewrite");
|
||||
}
|
||||
|
||||
export async function listReportVariants(parentSessionId: string): Promise<DeepResearchSession[]> {
|
||||
const res = await apiFetch(
|
||||
`${BASE()}/sessions/${encodeURIComponent(parentSessionId)}/report-variants`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
const data = await readJson<WireRecord>(res, "listReportVariants");
|
||||
return asItems(data.items).map(normalizeSession);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fork a completed report before generating it under another structure.
|
||||
* The returned session owns its own report and selected-source snapshot, so
|
||||
* its durable rewrite cannot replace the parent report.
|
||||
*/
|
||||
export async function createResearchReportVariant(
|
||||
sessionId: string,
|
||||
input: { reportOutline?: string; structureMode?: "fixed" | "adaptive" },
|
||||
): Promise<DeepResearchSession> {
|
||||
const response = await apiFetch(
|
||||
`${BASE()}/sessions/${encodeURIComponent(sessionId)}/report-variants`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
},
|
||||
);
|
||||
const data = await readJson<WireRecord>(response, "createResearchReportVariant");
|
||||
return normalizeSession(data);
|
||||
}
|
||||
|
||||
export async function cancelFullResearchReportRewrite(jobId: string): Promise<void> {
|
||||
await cancelJob(jobId);
|
||||
}
|
||||
@@ -635,7 +667,13 @@ export async function cancelFullResearchReportRewrite(jobId: string): Promise<vo
|
||||
export interface LatestFullReportRewrite {
|
||||
job: DeepResearchJob | null;
|
||||
result: Record<string, unknown>;
|
||||
request: { instruction: string; style: DocumentRewriteStyle; modelName?: string | null };
|
||||
request: {
|
||||
operation: "rewrite" | "generate";
|
||||
instruction: string;
|
||||
style: DocumentRewriteStyle;
|
||||
modelName?: string | null;
|
||||
reportOutline?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export async function getLatestFullResearchReportRewrite(
|
||||
@@ -652,9 +690,11 @@ export async function getLatestFullResearchReportRewrite(
|
||||
job: jobRecord ? normalizeJob(jobRecord) : null,
|
||||
result: asRecord(data.result),
|
||||
request: {
|
||||
operation: request.operation === "generate" ? "generate" : "rewrite",
|
||||
instruction: String(request.instruction ?? ""),
|
||||
style: (request.style ?? "formal_analysis") as DocumentRewriteStyle,
|
||||
modelName: typeof request.modelName === "string" ? request.modelName : null,
|
||||
reportOutline: typeof request.reportOutline === "string" ? request.reportOutline : "",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -744,6 +784,11 @@ export async function* joinFullResearchReportRewrite(
|
||||
modelName: String(raw.modelName ?? "deep_research_smart_model"),
|
||||
plan: typeof raw.plan === "string" ? raw.plan : undefined,
|
||||
};
|
||||
} else if (type === "thinking") {
|
||||
// Deep Research uses the same shared rewrite hook/timeline as
|
||||
// sandbox Markdown. Preserve provider reasoning chunks instead
|
||||
// of silently dropping them in this custom durable-SSE adapter.
|
||||
yield { type, chunk: String(raw.chunk ?? "") };
|
||||
} else if (type === "rewrite_delta") {
|
||||
yield { type, delta: String(raw.delta ?? ""), charCount: Number(raw.charCount ?? 0) };
|
||||
} else if (type === "rewrite_checkpoint") {
|
||||
@@ -766,12 +811,14 @@ export async function* joinFullResearchReportRewrite(
|
||||
content: String(raw.content ?? ""),
|
||||
committedHash: String(raw.committedHash ?? ""),
|
||||
versionId: typeof raw.versionId === "string" ? raw.versionId : undefined,
|
||||
versionSnapshotFailed: raw.versionSnapshotFailed === true,
|
||||
};
|
||||
} else if (type === "done") {
|
||||
yield {
|
||||
type,
|
||||
committedHash: String(raw.committedHash ?? ""),
|
||||
versionId: typeof raw.versionId === "string" ? raw.versionId : undefined,
|
||||
versionSnapshotFailed: raw.versionSnapshotFailed === true,
|
||||
};
|
||||
terminal = true;
|
||||
} else if (type === "conflict") {
|
||||
@@ -807,7 +854,14 @@ export async function* joinFullResearchReportRewrite(
|
||||
/** Start and join the sandbox's durable complete-report rewrite. */
|
||||
export async function* streamFullResearchReportRewrite(
|
||||
sessionId: string,
|
||||
input: { instruction: string; style: DocumentRewriteStyle; modelName?: string },
|
||||
input: {
|
||||
operation?: "rewrite" | "generate";
|
||||
instruction: string;
|
||||
style: DocumentRewriteStyle;
|
||||
modelName?: string;
|
||||
reportOutline?: string;
|
||||
structureMode?: "fixed" | "adaptive";
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
onJobStarted?: (jobId: string) => void,
|
||||
): AsyncGenerator<DocumentRewriteStreamEvent> {
|
||||
@@ -876,6 +930,7 @@ export const DEEP_RESEARCH_SESSION_KEY = "deep-research-session";
|
||||
export const DEEP_RESEARCH_SOURCES_KEY = "deep-research-sources";
|
||||
export const DEEP_RESEARCH_MESSAGES_KEY = "deep-research-messages";
|
||||
export const DEEP_RESEARCH_CAPABILITIES_KEY = "deep-research-capabilities";
|
||||
export const DEEP_RESEARCH_REPORT_VARIANTS_KEY = "deep-research-report-variants";
|
||||
|
||||
export function useResearchSessions(limit = 50) {
|
||||
return useQuery({
|
||||
@@ -895,6 +950,15 @@ export function useResearchSession(id: string | null) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useResearchReportVariants(parentSessionId: string | null) {
|
||||
return useQuery({
|
||||
queryKey: [DEEP_RESEARCH_REPORT_VARIANTS_KEY, parentSessionId],
|
||||
queryFn: () => listReportVariants(parentSessionId!),
|
||||
enabled: !!parentSessionId,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useResearchSources(sessionId: string | null) {
|
||||
return useQuery({
|
||||
queryKey: [DEEP_RESEARCH_SOURCES_KEY, sessionId],
|
||||
@@ -938,7 +1002,7 @@ export function useResearchActions() {
|
||||
config,
|
||||
}: {
|
||||
sessionId: string;
|
||||
entry?: "chat" | "legacy";
|
||||
entry?: "chat" | "legacy" | "regenerate";
|
||||
config?: Record<string, unknown>;
|
||||
}) => startJob(sessionId, { entry, config }),
|
||||
onSuccess: (_result, { sessionId }) => {
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
const API = () => `${getBackendBaseURL()}/api/enterprise-research`;
|
||||
|
||||
/**
|
||||
* Enterprise research snapshots raw WeKnora evidence chunks. This is
|
||||
* intentionally separate from LlmWikiSearchResult, whose public search shape
|
||||
* now represents processed Wiki pages only.
|
||||
*/
|
||||
export interface EnterpriseResearchEvidence {
|
||||
chunk_id: string;
|
||||
content: string;
|
||||
knowledge_id: string;
|
||||
knowledge_base_id: string;
|
||||
knowledge_base_name: string;
|
||||
title: string;
|
||||
filename: string;
|
||||
score: number;
|
||||
chunk_index: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export type EnterpriseResearchTaskStatus = "draft" | "collecting" | "ready" | "partial" | "failed";
|
||||
|
||||
export interface EnterpriseResearchTask {
|
||||
id: string;
|
||||
subject: string;
|
||||
focus: string;
|
||||
template_id: string;
|
||||
knowledge_base_ids: string[];
|
||||
queries: string[];
|
||||
selected_source_ids: string[];
|
||||
sources: EnterpriseResearchEvidence[];
|
||||
plan_markdown?: string | null;
|
||||
report_markdown?: string | null;
|
||||
report_summary?: string | null;
|
||||
report_model_name?: string | null;
|
||||
active_report_job_id?: string | null;
|
||||
status: EnterpriseResearchTaskStatus;
|
||||
warning?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export type EnterpriseResearchReportJobStatus = "queued" | "running" | "completed" | "failed" | "cancelled";
|
||||
|
||||
export interface EnterpriseResearchReportJob {
|
||||
id: string;
|
||||
task_id: string;
|
||||
status: EnterpriseResearchReportJobStatus;
|
||||
phase: string;
|
||||
model_name?: string | null;
|
||||
action: "initial" | "rewrite" | "followup";
|
||||
instruction?: string | null;
|
||||
style?: string | null;
|
||||
target_length?: number | null;
|
||||
original_report?: string | null;
|
||||
report_markdown: string;
|
||||
report_summary?: string | null;
|
||||
error_message?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export type EnterpriseResearchReportEvent =
|
||||
| { type: "snapshot"; job: EnterpriseResearchReportJob }
|
||||
| { type: "phase"; phase: string; status: EnterpriseResearchReportJobStatus }
|
||||
| { type: "report_delta"; delta: string }
|
||||
| { type: "reasoning_delta"; delta: string }
|
||||
| { type: "completed" | "failed" | "cancelled"; job: EnterpriseResearchReportJob | null }
|
||||
| { type: "heartbeat"; status: EnterpriseResearchReportJobStatus; phase: string };
|
||||
|
||||
export interface CreateEnterpriseResearchTaskInput {
|
||||
subject: string;
|
||||
focus: string;
|
||||
template_id: string;
|
||||
knowledge_base_ids: string[];
|
||||
queries: string[];
|
||||
}
|
||||
|
||||
async function readJson<T>(response: Response, context: string): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null as unknown);
|
||||
const detail = payload && typeof payload === "object" && "detail" in payload
|
||||
? String((payload as { detail: unknown }).detail)
|
||||
: `${context}失败(${response.status})`;
|
||||
throw new Error(detail);
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export async function listEnterpriseResearchTasks(limit = 20): Promise<EnterpriseResearchTask[]> {
|
||||
const payload = await readJson<{ tasks?: EnterpriseResearchTask[] }>(
|
||||
await apiFetch(`${API()}/tasks?limit=${encodeURIComponent(limit)}`),
|
||||
"读取研究任务",
|
||||
);
|
||||
return payload.tasks ?? [];
|
||||
}
|
||||
|
||||
export async function createEnterpriseResearchTask(input: CreateEnterpriseResearchTaskInput): Promise<EnterpriseResearchTask> {
|
||||
return readJson<EnterpriseResearchTask>(
|
||||
await apiFetch(`${API()}/tasks`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
"创建研究任务",
|
||||
);
|
||||
}
|
||||
|
||||
export async function collectEnterpriseResearchTask(taskId: string): Promise<EnterpriseResearchTask> {
|
||||
return readJson<EnterpriseResearchTask>(
|
||||
await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}/collect`, { method: "POST" }),
|
||||
"收集研究证据",
|
||||
);
|
||||
}
|
||||
|
||||
export async function createEnterpriseResearchPlanDraft(taskId: string): Promise<EnterpriseResearchTask> {
|
||||
return readJson<EnterpriseResearchTask>(
|
||||
await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}/plan/draft`, { method: "POST" }),
|
||||
"生成研究计划",
|
||||
);
|
||||
}
|
||||
|
||||
export async function createEnterpriseResearchAiPlan(
|
||||
taskId: string,
|
||||
input: { model_name?: string | null; instruction?: string } = {},
|
||||
): Promise<EnterpriseResearchTask> {
|
||||
return readJson<EnterpriseResearchTask>(
|
||||
await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}/plan/ai`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
"AI 优化研究计划",
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateEnterpriseResearchPlan(
|
||||
taskId: string,
|
||||
input: { plan_markdown: string; selected_source_ids: string[] },
|
||||
): Promise<EnterpriseResearchTask> {
|
||||
return readJson<EnterpriseResearchTask>(
|
||||
await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}/plan`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
"保存研究计划",
|
||||
);
|
||||
}
|
||||
|
||||
export async function createEnterpriseResearchReportJob(
|
||||
taskId: string,
|
||||
input: {
|
||||
model_name?: string | null;
|
||||
action?: "initial" | "rewrite" | "followup";
|
||||
instruction?: string;
|
||||
style?: "formal" | "analytical" | "concise";
|
||||
target_length?: number | null;
|
||||
} = {},
|
||||
): Promise<EnterpriseResearchReportJob> {
|
||||
return readJson<EnterpriseResearchReportJob>(
|
||||
await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}/report-jobs`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
"创建报告写作任务",
|
||||
);
|
||||
}
|
||||
|
||||
export async function cancelEnterpriseResearchReportJob(
|
||||
taskId: string,
|
||||
jobId: string,
|
||||
): Promise<EnterpriseResearchReportJob> {
|
||||
return readJson<EnterpriseResearchReportJob>(
|
||||
await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}/report-jobs/${encodeURIComponent(jobId)}/cancel`, {
|
||||
method: "POST",
|
||||
}),
|
||||
"取消报告任务",
|
||||
);
|
||||
}
|
||||
|
||||
export async function restoreEnterpriseResearchReportVersion(
|
||||
taskId: string,
|
||||
jobId: string,
|
||||
): Promise<EnterpriseResearchTask> {
|
||||
return readJson<EnterpriseResearchTask>(
|
||||
await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}/report-jobs/${encodeURIComponent(jobId)}/restore`, {
|
||||
method: "POST",
|
||||
}),
|
||||
"恢复报告版本",
|
||||
);
|
||||
}
|
||||
|
||||
export async function listEnterpriseResearchReportJobs(taskId: string): Promise<EnterpriseResearchReportJob[]> {
|
||||
const payload = await readJson<{ jobs?: EnterpriseResearchReportJob[] }>(
|
||||
await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}/report-jobs`),
|
||||
"读取报告写作任务",
|
||||
);
|
||||
return payload.jobs ?? [];
|
||||
}
|
||||
|
||||
/** Parse the endpoint's standard SSE frames without introducing an EventSource auth gap. */
|
||||
export async function streamEnterpriseResearchReportJob(
|
||||
taskId: string,
|
||||
jobId: string,
|
||||
handlers: { onEvent: (event: EnterpriseResearchReportEvent) => void; signal?: AbortSignal },
|
||||
): Promise<void> {
|
||||
const response = await apiFetch(
|
||||
`${API()}/tasks/${encodeURIComponent(taskId)}/report-jobs/${encodeURIComponent(jobId)}/stream`,
|
||||
{ headers: { Accept: "text/event-stream" }, signal: handlers.signal },
|
||||
);
|
||||
if (!response.ok || !response.body) {
|
||||
await readJson(response, "连接报告流");
|
||||
return;
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let pending = "";
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
pending += decoder.decode(value, { stream: true });
|
||||
const frames = pending.split("\n\n");
|
||||
pending = frames.pop() ?? "";
|
||||
for (const frame of frames) {
|
||||
const dataLine = frame.split("\n").find((line) => line.startsWith("data: "));
|
||||
if (!dataLine) continue;
|
||||
try {
|
||||
handlers.onEvent(JSON.parse(dataLine.slice(6)) as EnterpriseResearchReportEvent);
|
||||
} catch {
|
||||
// One malformed frame must not discard an otherwise healthy stream.
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteEnterpriseResearchTask(taskId: string): Promise<void> {
|
||||
const response = await apiFetch(`${API()}/tasks/${encodeURIComponent(taskId)}`, { method: "DELETE" });
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null as unknown);
|
||||
const detail = payload && typeof payload === "object" && "detail" in payload
|
||||
? String((payload as { detail: unknown }).detail)
|
||||
: `删除研究任务失败(${response.status})`;
|
||||
throw new Error(detail);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
/**
|
||||
* 深度研究「工作流配置 / 报告结构」API 客户端 + React Query hooks。
|
||||
*
|
||||
* 后端:`/api/report-structures`(见 app/gateway/routers/report_structures.py)。
|
||||
* 全局共享、无用户隔离;新增永远默认启用(服务端强制,不收 enabled 字段)。
|
||||
* snake_case ⇄ camelCase 在此边界收敛。
|
||||
*/
|
||||
|
||||
import {
|
||||
keepPreviousData,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
export type ReportStructureMode = "fixed" | "adaptive";
|
||||
|
||||
export const DEFAULT_REPORT_STRUCTURE_MODE: ReportStructureMode = "adaptive";
|
||||
|
||||
export const REPORT_STRUCTURE_MODE_OPTIONS: {
|
||||
value: ReportStructureMode;
|
||||
label: string;
|
||||
description: string;
|
||||
}[] = [
|
||||
{
|
||||
value: "fixed",
|
||||
label: "固定大纲",
|
||||
description: "按结构内容的章节标题与层级逐一成文,不得改写、合并或省略。",
|
||||
},
|
||||
{
|
||||
value: "adaptive",
|
||||
label: "弹性大纲",
|
||||
description: "保留现有成文策略,可按材料对无依据小节做合并或省略。",
|
||||
},
|
||||
];
|
||||
|
||||
export function normalizeReportStructureMode(value: unknown): ReportStructureMode {
|
||||
return value === "fixed" ? "fixed" : "adaptive";
|
||||
}
|
||||
|
||||
export function reportStructureModeLabel(mode: ReportStructureMode): string {
|
||||
return mode === "fixed" ? "固定大纲" : "弹性大纲";
|
||||
}
|
||||
|
||||
export const MAX_RETRIEVAL_DIRECTIONS = 12;
|
||||
export const MAX_RETRIEVAL_DIRECTION_CHARS = 200;
|
||||
export const MAX_RETRIEVAL_SKILLS = 8;
|
||||
export const MAX_RETRIEVAL_SKILL_CHARS = 64;
|
||||
|
||||
const EMPTY_LIST_TOKENS = new Set(["", "[]", "{}", "null", "none", "undefined"]);
|
||||
|
||||
function coerceListish(value: unknown): unknown[] {
|
||||
if (value == null || typeof value === "boolean") return [];
|
||||
if (Array.isArray(value)) return value;
|
||||
if (typeof value === "string") {
|
||||
const text = value.trim();
|
||||
if (!text || EMPTY_LIST_TOKENS.has(text.toLowerCase())) return [];
|
||||
if (text.startsWith("[") || text.startsWith("{")) {
|
||||
try {
|
||||
const parsed = JSON.parse(text) as unknown;
|
||||
if (parsed == null) return [];
|
||||
if (Array.isArray(parsed)) return parsed;
|
||||
return [];
|
||||
} catch {
|
||||
return [value];
|
||||
}
|
||||
}
|
||||
return [value];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function normalizeRetrievalDirections(value: unknown): string[] {
|
||||
const parts = coerceListish(value);
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const item of parts) {
|
||||
const text = String(item ?? "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.slice(0, MAX_RETRIEVAL_DIRECTION_CHARS);
|
||||
if (!text || EMPTY_LIST_TOKENS.has(text.toLowerCase())) continue;
|
||||
const key = text.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(text);
|
||||
if (out.length >= MAX_RETRIEVAL_DIRECTIONS) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeRetrievalSkills(value: unknown): string[] {
|
||||
const parts = coerceListish(value);
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const item of parts) {
|
||||
const text = String(item ?? "")
|
||||
.replace(/[\x00\r\n]/g, "")
|
||||
.trim()
|
||||
.slice(0, MAX_RETRIEVAL_SKILL_CHARS);
|
||||
if (!text || EMPTY_LIST_TOKENS.has(text.toLowerCase()) || /\s/.test(text)) continue;
|
||||
const key = text.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(text);
|
||||
if (out.length >= MAX_RETRIEVAL_SKILLS) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const COLLECTOR_DIRECTION_INTRO =
|
||||
"请按以下检索方向拆分检索词(这是拆词约束,不是检索词本身):每个方向拆成若干具体、可检索的检索词(含课题中的专名、时间、地点、同义/中英对照等),不要直接把方向名称拿去搜索——方向标签往往搜不到结果。覆盖列出的每一个方向;未列出的方面不必主动扩展。某个检索词没有结果时,换更具体或更短的词再试,仍不要改用未列出的方向。";
|
||||
|
||||
const COLLECTOR_SKILL_INTRO =
|
||||
"请严格按照以下技能收集素材:先用 read_file 读取每个技能的 SKILL.md,再按其说明调用工具检索。不要改用未列出的技能,也不要自行改成纯 web_search(除非技能说明要求联网)。每个技能至少使用一轮。";
|
||||
|
||||
/** First collector turn: append direction / skill blocks only when they exist. */
|
||||
export function composeCollectorQueryWithDirections(
|
||||
query: string,
|
||||
directions: unknown,
|
||||
skills?: unknown,
|
||||
): string {
|
||||
let topic = query.trim();
|
||||
if (!topic) return topic;
|
||||
const cleanedDirections = normalizeRetrievalDirections(directions);
|
||||
if (cleanedDirections.length > 0 && !topic.includes("<retrieval-directions>")) {
|
||||
const lines = cleanedDirections.map((item, index) => `${index + 1}. ${item}`).join("\n");
|
||||
topic = `${topic}\n\n<retrieval-directions>\n${COLLECTOR_DIRECTION_INTRO}\n${lines}\n</retrieval-directions>`;
|
||||
}
|
||||
const cleanedSkills = normalizeRetrievalSkills(skills);
|
||||
if (cleanedSkills.length > 0 && !topic.includes("<retrieval-skills>")) {
|
||||
const lines = cleanedSkills.map((item, index) => `${index + 1}. ${item}`).join("\n");
|
||||
topic = `${topic}\n\n<retrieval-skills>\n${COLLECTOR_SKILL_INTRO}\n${lines}\n</retrieval-skills>`;
|
||||
}
|
||||
return topic;
|
||||
}
|
||||
|
||||
export interface ReportStructure {
|
||||
id: string;
|
||||
/** 标题:卡片主标签,也是列表「标题筛选」的目标。 */
|
||||
title: string;
|
||||
/** 描述:一句话说明这套结构的适用场景(存储列沿用 name)。 */
|
||||
name: string;
|
||||
/** 接口内容:选中卡片后应用到报告结构(custom_outline)的 Markdown 文本。 */
|
||||
content: string;
|
||||
/** 结构约束:固定大纲逐章对照;弹性大纲沿用现有材料驱动写法。 */
|
||||
structureMode: ReportStructureMode;
|
||||
/** 检索方向:选中后收集员按这些方向拆分具体检索词;空则沿用收集员自行拆词。 */
|
||||
retrievalDirections: string[];
|
||||
/** 检索来源:选中后收集素材调用这些技能;空则沿用收集员默认工具。 */
|
||||
retrievalSkills: string[];
|
||||
enabled: boolean;
|
||||
/** 创建用户名(本部署为邮箱;系统内置种子为“系统内置”)。 */
|
||||
createdBy: string | null;
|
||||
createdAt: string | null;
|
||||
/** 最后修改时间(编辑、启停都会刷新)。 */
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export type ReportStructureInput = {
|
||||
title: string;
|
||||
name: string;
|
||||
content: string;
|
||||
structureMode: ReportStructureMode;
|
||||
retrievalDirections: string[];
|
||||
retrievalSkills: string[];
|
||||
};
|
||||
|
||||
export type ReportStructurePatch = Partial<ReportStructureInput>;
|
||||
|
||||
export type ReportStructureStatusFilter = "all" | "enabled" | "disabled";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/report-structures`;
|
||||
|
||||
interface ServerStructure {
|
||||
id: string;
|
||||
title: string;
|
||||
name: string;
|
||||
content: string;
|
||||
structure_mode?: string | null;
|
||||
retrieval_directions?: string[] | null;
|
||||
retrieval_skills?: string[] | null;
|
||||
enabled: boolean;
|
||||
created_by: string | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
}
|
||||
|
||||
function toStructure(s: ServerStructure): ReportStructure {
|
||||
return {
|
||||
id: s.id,
|
||||
title: s.title,
|
||||
name: s.name ?? "",
|
||||
content: s.content,
|
||||
structureMode: normalizeReportStructureMode(s.structure_mode),
|
||||
retrievalDirections: normalizeRetrievalDirections(s.retrieval_directions),
|
||||
retrievalSkills: normalizeRetrievalSkills(s.retrieval_skills),
|
||||
enabled: s.enabled ?? true,
|
||||
createdBy: s.created_by ?? null,
|
||||
createdAt: s.created_at ?? null,
|
||||
updatedAt: s.updated_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null as unknown);
|
||||
const detail =
|
||||
data && typeof data === "object" && "detail" in data
|
||||
? String((data as { detail: unknown }).detail)
|
||||
: `${ctx} failed (${res.status})`;
|
||||
throw new Error(detail);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
export async function listReportStructures(params: {
|
||||
status?: ReportStructureStatusFilter;
|
||||
title?: string;
|
||||
} = {}): Promise<ReportStructure[]> {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.status === "enabled") qs.set("enabled", "true");
|
||||
if (params.status === "disabled") qs.set("enabled", "false");
|
||||
const title = params.title?.trim();
|
||||
if (title) qs.set("title", title);
|
||||
const query = qs.toString();
|
||||
const res = await apiFetch(`${BASE()}${query ? `?${query}` : ""}`, { method: "GET" });
|
||||
const data = await readJson<{ structures: ServerStructure[] }>(res, "list report structures");
|
||||
return (data.structures ?? []).map(toStructure);
|
||||
}
|
||||
|
||||
export async function createReportStructure(input: ReportStructureInput): Promise<ReportStructure> {
|
||||
const res = await apiFetch(BASE(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title: input.title,
|
||||
name: input.name,
|
||||
content: input.content,
|
||||
structure_mode: normalizeReportStructureMode(input.structureMode),
|
||||
retrieval_directions: normalizeRetrievalDirections(input.retrievalDirections),
|
||||
retrieval_skills: normalizeRetrievalSkills(input.retrievalSkills),
|
||||
}),
|
||||
});
|
||||
return toStructure(await readJson<ServerStructure>(res, "create report structure"));
|
||||
}
|
||||
|
||||
export async function updateReportStructure(
|
||||
id: string,
|
||||
patch: ReportStructurePatch,
|
||||
): Promise<ReportStructure> {
|
||||
const body: Record<string, unknown> = {};
|
||||
if (patch.title !== undefined) body.title = patch.title;
|
||||
if (patch.name !== undefined) body.name = patch.name;
|
||||
if (patch.content !== undefined) body.content = patch.content;
|
||||
if (patch.structureMode !== undefined) body.structure_mode = normalizeReportStructureMode(patch.structureMode);
|
||||
if (patch.retrievalDirections !== undefined) {
|
||||
body.retrieval_directions = normalizeRetrievalDirections(patch.retrievalDirections);
|
||||
}
|
||||
if (patch.retrievalSkills !== undefined) {
|
||||
body.retrieval_skills = normalizeRetrievalSkills(patch.retrievalSkills);
|
||||
}
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return toStructure(await readJson<ServerStructure>(res, "update report structure"));
|
||||
}
|
||||
|
||||
export async function setReportStructureEnabled(id: string, enabled: boolean): Promise<ReportStructure> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}/enabled`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ enabled }),
|
||||
});
|
||||
return toStructure(await readJson<ServerStructure>(res, "toggle report structure"));
|
||||
}
|
||||
|
||||
export async function deleteReportStructure(id: string): Promise<void> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "DELETE" });
|
||||
// 204 无响应体,不能再走 readJson 的 res.json()。
|
||||
if (!res.ok) {
|
||||
const data = (await res.json().catch(() => null)) as { detail?: unknown } | null;
|
||||
throw new Error(
|
||||
data && typeof data.detail === "string" ? data.detail : `delete report structure failed (${res.status})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── React Query hooks(工作流配置弹窗内各视图共用缓存) ──────────────────────
|
||||
|
||||
const REPORT_STRUCTURES_KEY = "report-structures";
|
||||
|
||||
export function useReportStructures(params: { status?: ReportStructureStatusFilter; title?: string } = {}) {
|
||||
return useQuery({
|
||||
queryKey: [REPORT_STRUCTURES_KEY, "list", params.status ?? "all", params.title ?? ""],
|
||||
queryFn: () => listReportStructures(params),
|
||||
placeholderData: keepPreviousData,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useReportStructureMutations() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey: [REPORT_STRUCTURES_KEY] });
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: (input: ReportStructureInput) => createReportStructure(input),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
const update = useMutation({
|
||||
mutationFn: ({ id, patch }: { id: string; patch: ReportStructurePatch }) =>
|
||||
updateReportStructure(id, patch),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
const toggleEnabled = useMutation({
|
||||
mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) =>
|
||||
setReportStructureEnabled(id, enabled),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: string) => deleteReportStructure(id),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
|
||||
return { create, update, toggleEnabled, remove };
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import {
|
||||
AppWindow,
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
ExternalLink,
|
||||
@@ -257,6 +258,7 @@ function TaskSideJumpMenu({
|
||||
|
||||
function renderTaskJumpIcon(btn: TaskButton, className: string) {
|
||||
if (btn.linkType === "url") return <ExternalLink className={className} />;
|
||||
if (btn.linkType === "host") return <AppWindow className={className} />;
|
||||
if (btn.linkType === "purpose") return <Maximize2 className={className} />;
|
||||
return <ArrowRight className={className} />;
|
||||
}
|
||||
@@ -264,6 +266,7 @@ function renderTaskJumpIcon(btn: TaskButton, className: string) {
|
||||
function renderRoundtableMenuIcon(btn: TaskButton) {
|
||||
const className = "h-4 w-4";
|
||||
if (btn.linkType === "purpose") return <Maximize2 className={className} />;
|
||||
if (btn.linkType === "host") return <AppWindow className={className} />;
|
||||
if (btn.linkType === "url") return <FileSearch className={className} />;
|
||||
if (btn.target === "3qfx") return <Network className={className} />;
|
||||
if (btn.target === "xdfx") return <Workflow className={className} />;
|
||||
@@ -272,6 +275,12 @@ function renderRoundtableMenuIcon(btn: TaskButton) {
|
||||
}
|
||||
|
||||
function getRoundtableMenuTone(btn: TaskButton) {
|
||||
if (btn.linkType === "host") {
|
||||
return {
|
||||
item: "hover:text-indigo-700 dark:hover:text-indigo-100",
|
||||
icon: "bg-indigo-50 text-indigo-600 dark:bg-indigo-400/10 dark:text-indigo-200",
|
||||
};
|
||||
}
|
||||
if (btn.linkType === "url") {
|
||||
return {
|
||||
item: "hover:text-rose-700 dark:hover:text-rose-100",
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import type { LightApp, LightAppRouteParam } from "@/strategy-components/api/light-apps";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { authStorageGet } from "@/core/auth/scoped-storage";
|
||||
import { readCurrentExternalAccessTokenValue } from "@/core/auth/external-access-token";
|
||||
|
||||
@@ -26,13 +27,14 @@ export function mountLabel(value: string | null | undefined): string {
|
||||
/**
|
||||
* 登录参数可选来源;值均可在 userInfo 中取到,"other" 表示自填。
|
||||
* accessToken / yUserId 取登录路由透传值(写入 userInfo 的同名键);
|
||||
* userName / gateDepartName / typeName 取 consumer 接口 userDetailByYuserId 的返回值。
|
||||
* userName 优先取当前鉴权会话的原始登录名;gateDepartName / typeName 取 consumer
|
||||
* 接口 userDetailByYuserId 的返回值。
|
||||
*/
|
||||
export const LOGIN_SOURCE_OPTIONS: { label: string; value: string }[] = [
|
||||
{ label: "access_token", value: "access_token" },
|
||||
{ label: "accessToken(兼容旧配置)", value: "accessToken" },
|
||||
{ label: "yUserId", value: "yUserId" },
|
||||
{ label: "userName", value: "userName" },
|
||||
{ label: "userName(当前登录账号)", value: "userName" },
|
||||
{ label: "gateDepartName", value: "gateDepartName" },
|
||||
{ label: "typeName", value: "typeName" },
|
||||
{ label: "其他(自定义值)", value: "other" },
|
||||
@@ -152,6 +154,25 @@ export function resolveRouteParamValue(
|
||||
return param.customValue ?? "";
|
||||
}
|
||||
if (param.source) {
|
||||
// `userInfo.userName` can belong to a prior external-login flow (for
|
||||
// example a stale "guest" value). Route parameters must follow the user
|
||||
// currently authenticated in DeerFlow, so prefer the backend's original
|
||||
// login username and only fall back to userInfo for older backends.
|
||||
if (param.source === "userName") {
|
||||
const auth = getStoredAuth();
|
||||
const loginUsername = auth?.username?.trim();
|
||||
if (loginUsername) return loginUsername;
|
||||
|
||||
const accountName = (auth?.email ?? "").split("@")[0]?.trim() || auth?.user_id;
|
||||
if (accountName) return accountName;
|
||||
|
||||
const userInfoName = userInfo.userName;
|
||||
if (typeof userInfoName === "string" && userInfoName.trim()) {
|
||||
return userInfoName.trim();
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
const value = userInfo[param.source];
|
||||
if (param.source === "access_token" || param.source === "accessToken") {
|
||||
return readCurrentExternalAccessTokenValue(userInfo);
|
||||
|
||||
Reference in new issue
Block a user