refactor: unify AI capabilities and workspace integration
This commit is contained in:
+22
-351
@@ -15,23 +15,13 @@ import {
|
||||
Spin,
|
||||
Tag,
|
||||
TextArea,
|
||||
Toast,
|
||||
} from "@douyinfe/semi-ui-19";
|
||||
import {
|
||||
api,
|
||||
formatNumber,
|
||||
formatTime,
|
||||
jobLabels,
|
||||
jobStateLabels,
|
||||
post,
|
||||
stateLabels,
|
||||
} from "../api";
|
||||
import { BacktestToolCard } from "../backtests/BacktestToolCard";
|
||||
import { CatalogToolCard } from "../research/CatalogToolCard";
|
||||
import { PnlChart } from "../components/PnlChart";
|
||||
import type { Alpha, Job, Pnl, Research } from "../types";
|
||||
import { api, post } from "../api";
|
||||
import type { Job } from "../types";
|
||||
import { BusinessCard } from "./ToolCard";
|
||||
import { contextLabel } from "./workspace";
|
||||
import { chatTransport } from "./transport";
|
||||
import { runLabels, toolLabels } from "./types";
|
||||
import { runLabels } from "./types";
|
||||
import type {
|
||||
ChatMessage,
|
||||
Conversation,
|
||||
@@ -39,7 +29,7 @@ import type {
|
||||
ModelSettings,
|
||||
PageContext,
|
||||
RunSnapshot,
|
||||
ToolCard,
|
||||
Resource,
|
||||
UIAction,
|
||||
} from "./types";
|
||||
|
||||
@@ -66,7 +56,7 @@ export function ChatPanel({
|
||||
context: PageContext;
|
||||
onClose: () => void;
|
||||
onAction: (action: UIAction) => void;
|
||||
onChanged: () => void;
|
||||
onChanged: (resources: Resource[]) => void;
|
||||
onSettings: () => void;
|
||||
width: number;
|
||||
onWidth: (width: number) => void;
|
||||
@@ -85,34 +75,28 @@ export function ChatPanel({
|
||||
const input = useRef<HTMLDivElement>(null);
|
||||
const bottom = useRef<HTMLDivElement>(null);
|
||||
const previousFocus = useRef<HTMLElement | null>(null);
|
||||
const seenWrites = useRef(new Set<string>());
|
||||
const seenChanges = useRef(new Set<string>());
|
||||
const current = useRef({ conversationId, context });
|
||||
current.current = { conversationId, context };
|
||||
const refreshRef = useRef<() => Promise<void>>(async () => {});
|
||||
const changedRef = useRef(onChanged);
|
||||
changedRef.current = onChanged;
|
||||
const observeWrites = useCallback((items: RunSnapshot[]) => {
|
||||
let changed = false;
|
||||
const observeChanges = useCallback((items: RunSnapshot[]) => {
|
||||
const changed = new Set<Resource>();
|
||||
for (const run of items)
|
||||
for (const call of run.tools ?? []) {
|
||||
if (
|
||||
call.status === "completed" &&
|
||||
[
|
||||
"update_research",
|
||||
"bulk_update_research",
|
||||
"create_sync_job",
|
||||
"cancel_job",
|
||||
"retry_job",
|
||||
"start_backtest",
|
||||
"control_backtest",
|
||||
].includes(call.name) &&
|
||||
!seenWrites.current.has(call.id)
|
||||
call.presentation?.refresh.length &&
|
||||
!seenChanges.current.has(call.id)
|
||||
) {
|
||||
seenWrites.current.add(call.id);
|
||||
changed = true;
|
||||
seenChanges.current.add(call.id);
|
||||
call.presentation.refresh.forEach((resource) =>
|
||||
changed.add(resource),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (changed) changedRef.current();
|
||||
if (changed.size) changedRef.current([...changed]);
|
||||
}, []);
|
||||
const transport = useMemo(() => chatTransport(() => current.current), []);
|
||||
const chat = useChat<ChatMessage>({
|
||||
@@ -123,7 +107,7 @@ export function ChatPanel({
|
||||
if (part.type === "data-run") {
|
||||
const next = part.data;
|
||||
if (next.conversation_id !== current.current.conversationId) return;
|
||||
observeWrites([next]);
|
||||
observeChanges([next]);
|
||||
setRuns((items) => {
|
||||
const old = items.find((run) => run.id === next.id);
|
||||
const merged = {
|
||||
@@ -151,7 +135,7 @@ export function ChatPanel({
|
||||
if (current.current.conversationId !== id) return;
|
||||
chat.setMessages(detail.messages);
|
||||
setRuns(detail.runs);
|
||||
observeWrites(detail.runs);
|
||||
observeChanges(detail.runs);
|
||||
setConversations((items) =>
|
||||
items.map((item) =>
|
||||
item.id === id ? { id, title: detail.title } : item,
|
||||
@@ -160,7 +144,7 @@ export function ChatPanel({
|
||||
} catch (e) {
|
||||
setFailure((e as Error).message);
|
||||
}
|
||||
}, [chat.setMessages, observeWrites]);
|
||||
}, [chat.setMessages, observeChanges]);
|
||||
refreshRef.current = refreshConversation;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -301,7 +285,7 @@ export function ChatPanel({
|
||||
await post(`/ai/runs/${activeRun.id}/cancel`);
|
||||
await chat.stop();
|
||||
await refreshConversation();
|
||||
changedRef.current();
|
||||
// Completed tools are reconciled by refreshConversation; cancelling has no new business effect.
|
||||
} catch (e) {
|
||||
setFailure((e as Error).message);
|
||||
}
|
||||
@@ -498,15 +482,7 @@ export function ChatPanel({
|
||||
<div ref={bottom} />
|
||||
</div>
|
||||
<footer className="ai-composer" ref={input}>
|
||||
<div className="ai-context">
|
||||
{context.page === "backtests"
|
||||
? "上下文:回测研究"
|
||||
: context.page === "datasets"
|
||||
? `上下文:${context.dataset_id ?? "数据目录"}${context.catalog_scope ? ` · ${context.catalog_scope.region}/${context.catalog_scope.universe}/D${context.catalog_scope.delay}` : ""}${context.template_input_id ? " · 固定研究输入" : context.unsaved_field_selection ? " · 请先保存字段选择" : ""}(不发送未保存备注)`
|
||||
: context.page === "account"
|
||||
? "上下文:个人信息页"
|
||||
: `上下文:${context.alpha_id ? `Alpha ${context.alpha_id}` : "Alpha 列表"}${context.selected_ids?.length ? ` · 已选 ${context.selected_ids.length} 条` : ""}`}
|
||||
</div>
|
||||
<div className="ai-context">{contextLabel(context)}</div>
|
||||
<TextArea
|
||||
aria-label="发送给研究助手"
|
||||
placeholder={
|
||||
@@ -556,308 +532,3 @@ export function ChatPanel({
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function BusinessCard({
|
||||
call,
|
||||
onDecision,
|
||||
disabled,
|
||||
onAction,
|
||||
timezone,
|
||||
jobs,
|
||||
}: {
|
||||
call: ToolCard;
|
||||
onDecision: (id: string, approved: boolean) => Promise<void>;
|
||||
disabled: boolean;
|
||||
onAction: (action: UIAction) => void;
|
||||
timezone?: string;
|
||||
jobs: Job[];
|
||||
}) {
|
||||
const result = call.result ?? {};
|
||||
const jobId = result.job_id ?? result.id;
|
||||
const job = jobs.find((item) => item.id === jobId);
|
||||
const jobOperation = [
|
||||
"get_job_status",
|
||||
"create_sync_job",
|
||||
"retry_job",
|
||||
"cancel_job",
|
||||
].includes(call.name);
|
||||
const pending = call.status === "pending";
|
||||
const items = Array.isArray(result.items) ? result.items : [];
|
||||
const isSearch = call.name === "search_alphas";
|
||||
const alphas = (
|
||||
isSearch ? items : call.name === "get_alpha" && result.id ? [result] : []
|
||||
) as Alpha[];
|
||||
const labels: Record<string, string> = {
|
||||
pending: "待确认",
|
||||
completed: "已完成",
|
||||
failed: "失败",
|
||||
denied: "已拒绝",
|
||||
cancelled: "已取消",
|
||||
};
|
||||
const openAlpha = (id: string) =>
|
||||
onAction({ type: "open_alpha", alpha_id: id, nonce: Date.now() });
|
||||
return (
|
||||
<section className="ai-tool-card" data-status={call.status}>
|
||||
<div className="ai-card-title">
|
||||
<strong>{toolLabels[call.name] ?? "业务操作"}</strong>
|
||||
<Tag
|
||||
color={pending ? "orange" : call.status === "failed" ? "red" : "grey"}
|
||||
>
|
||||
{labels[call.status] ?? call.status}
|
||||
</Tag>
|
||||
</div>
|
||||
{call.name.includes("backtest") && (
|
||||
<BacktestToolCard call={call} onAction={onAction} />
|
||||
)}
|
||||
<CatalogToolCard call={call} onAction={onAction} />
|
||||
{call.preview.targets?.map((target) => (
|
||||
<details
|
||||
key={target.alpha_id}
|
||||
open={call.preview.targets!.length === 1}
|
||||
>
|
||||
<summary>{target.alpha_id} 的修改</summary>
|
||||
{(["note", "tags", "favorite", "state"] as const)
|
||||
.filter(
|
||||
(key) =>
|
||||
JSON.stringify(target.before[key]) !==
|
||||
JSON.stringify(target.after[key]),
|
||||
)
|
||||
.map((key) => (
|
||||
<div className="ai-diff" key={key}>
|
||||
<strong>
|
||||
{
|
||||
{
|
||||
note: "备注",
|
||||
tags: "标签",
|
||||
favorite: "收藏",
|
||||
state: "研究状态",
|
||||
}[key]
|
||||
}
|
||||
</strong>
|
||||
<del>
|
||||
<span>修改前</span>
|
||||
{researchValue(key, target.before[key])}
|
||||
</del>
|
||||
<ins>
|
||||
<span>修改后</span>
|
||||
{researchValue(key, target.after[key])}
|
||||
</ins>
|
||||
</div>
|
||||
))}
|
||||
</details>
|
||||
))}
|
||||
{call.preview.operation && (
|
||||
<p>
|
||||
{jobLabels[String(call.preview.operation.kind)] ?? "创建任务"} ·{" "}
|
||||
{Array.isArray(call.preview.operation.alpha_ids) &&
|
||||
call.preview.operation.alpha_ids.length
|
||||
? call.preview.operation.alpha_ids.join("、")
|
||||
: call.preview.operation.submission === "UNSUBMITTED"
|
||||
? "待提交 Alpha"
|
||||
: call.preview.operation.submission === "SUBMITTED"
|
||||
? "已提交 Alpha"
|
||||
: "全部 Alpha"}
|
||||
{call.preview.operation.kind === "daily_sync" && (
|
||||
<>
|
||||
{" · "}
|
||||
{call.preview.operation.submission === "UNSUBMITTED"
|
||||
? "创建日期"
|
||||
: "提交日期"}{" "}
|
||||
{String(call.preview.operation.date_from)} 至{" "}
|
||||
{String(call.preview.operation.date_to)}(UTC)
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{call.preview.job && (
|
||||
<p>
|
||||
{jobLabels[String(call.preview.job.kind)]} ·{" "}
|
||||
{String(call.preview.job.id)} ·{" "}
|
||||
{jobStateLabels[String(call.preview.job.status)]}
|
||||
</p>
|
||||
)}
|
||||
{pending && (
|
||||
<div className="ai-approval">
|
||||
<p className="muted">
|
||||
{call.preview.targets?.length
|
||||
? `将修改 ${call.preview.targets.length} 条研究记录。`
|
||||
: "将执行以上任务操作。"}
|
||||
确认后执行。
|
||||
</p>
|
||||
<div className="inline-actions">
|
||||
<Button
|
||||
theme="solid"
|
||||
disabled={disabled}
|
||||
onClick={() => void onDecision(call.id, true)}
|
||||
>
|
||||
确认执行
|
||||
</Button>
|
||||
<Button
|
||||
type="tertiary"
|
||||
disabled={disabled}
|
||||
onClick={() => void onDecision(call.id, false)}
|
||||
>
|
||||
拒绝
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{typeof result.error === "string" && (
|
||||
<p className="error-text">{result.error}</p>
|
||||
)}
|
||||
{result.denied === true && <p>已拒绝,未执行此操作。</p>}
|
||||
{alphas.length > 0 && (
|
||||
<div className="ai-alpha-results">
|
||||
{alphas.map((alpha) => (
|
||||
<div key={alpha.id}>
|
||||
<button className="text-link" onClick={() => openAlpha(alpha.id)}>
|
||||
{alpha.name || alpha.id}
|
||||
</button>
|
||||
<small>
|
||||
{alpha.id} · {alpha.region ?? "地区未提供"}
|
||||
</small>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Sharpe</th>
|
||||
<th>Fitness</th>
|
||||
<th>Turnover</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>{formatNumber(alpha.sharpe)}</td>
|
||||
<td>{formatNumber(alpha.fitness)}</td>
|
||||
<td>
|
||||
{alpha.turnover == null
|
||||
? "未提供"
|
||||
: `${formatNumber(alpha.turnover * 100)}%`}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<small>本地快照 · {formatTime(alpha.synced_at, timezone)}</small>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{isSearch && (
|
||||
<p>
|
||||
共 {String(result.total ?? 0)} 条,当前返回 {items.length} 条。
|
||||
{!!result.filters && (
|
||||
<button
|
||||
className="text-link"
|
||||
onClick={() =>
|
||||
onAction({
|
||||
type: "apply_filters",
|
||||
filters: result.filters as Record<string, unknown>,
|
||||
nonce: Date.now(),
|
||||
})
|
||||
}
|
||||
>
|
||||
应用到列表
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{call.name === "get_alpha_facets" && call.status === "completed" && (
|
||||
<p>
|
||||
已同步 {String(result.total ?? 0)} 条 Alpha · 收藏{" "}
|
||||
{String(result.favorites ?? 0)} 条<br />
|
||||
地区:
|
||||
{Array.isArray(result.region) ? result.region.join("、") : "未提供"}
|
||||
</p>
|
||||
)}
|
||||
{call.name === "get_alpha_pnl" && call.status === "completed" && (
|
||||
<ChatPnl result={result} timezone={timezone} />
|
||||
)}
|
||||
{call.name === "list_jobs" &&
|
||||
items.map((item) => {
|
||||
const job = item as Record<string, unknown>;
|
||||
return (
|
||||
<p key={String(job.id)}>
|
||||
{jobLabels[String(job.kind)]} ·{" "}
|
||||
{jobStateLabels[String(job.status)]}
|
||||
<small>{String(job.id)}</small>
|
||||
</p>
|
||||
);
|
||||
})}
|
||||
{jobOperation && !!jobId && (
|
||||
<p>
|
||||
{jobLabels[job?.kind ?? String(result.kind)] ?? "任务"} ·{" "}
|
||||
{jobStateLabels[job?.status ?? String(result.status)] ??
|
||||
String(result.status ?? "已处理")}
|
||||
{job && (
|
||||
<span>
|
||||
{" "}
|
||||
· {job.processed}/{job.total ?? "未知"},失败 {job.failed}
|
||||
{job.error ? ` · ${job.error}` : ""}
|
||||
</span>
|
||||
)}
|
||||
<small>{String(jobId)}</small>
|
||||
</p>
|
||||
)}
|
||||
{result.ok === true && (
|
||||
<p>
|
||||
操作已保存。
|
||||
{typeof result.alpha_id === "string" && (
|
||||
<button
|
||||
className="text-link"
|
||||
onClick={() => openAlpha(result.alpha_id as string)}
|
||||
>
|
||||
打开 Alpha
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{typeof result.updated === "number" && (
|
||||
<p>已更新 {result.updated} 条研究记录。</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function researchValue(key: keyof Research, value: unknown) {
|
||||
if (key === "favorite") return value ? "已收藏" : "未收藏";
|
||||
if (key === "state")
|
||||
return (
|
||||
stateLabels[String(value) as keyof typeof stateLabels] ?? String(value)
|
||||
);
|
||||
if (Array.isArray(value)) return value.join("、") || "无";
|
||||
return String(value || "空");
|
||||
}
|
||||
|
||||
function ChatPnl({
|
||||
result,
|
||||
timezone,
|
||||
}: {
|
||||
result: Record<string, unknown>;
|
||||
timezone?: string;
|
||||
}) {
|
||||
const [pnl, setPnl] = useState<Pnl | null>(null);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
if (result.cached && typeof result.alpha_id === "string")
|
||||
api<Pnl>(`/alphas/${encodeURIComponent(result.alpha_id)}/pnl`)
|
||||
.then((value) => {
|
||||
if (active) setPnl(value);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (active) Toast.error(error.message);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [result.alpha_id, result.fetched_at, result.cached]);
|
||||
return result.cached ? (
|
||||
<div>
|
||||
{pnl && <PnlChart points={pnl.points} />}
|
||||
<small>
|
||||
{String(result.count)} 条记录 · 缓存于{" "}
|
||||
{formatTime(result.fetched_at as string, timezone)}
|
||||
</small>
|
||||
</div>
|
||||
) : (
|
||||
<p>尚无 PnL 缓存,可以请求创建 PnL 刷新任务。</p>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user