Merge pull request #26 from RuoJi6/codex/task-intelligence

feat: 新增可选的任务情报自动记录与查看
This commit is contained in:
RuoJi6 authored and GitHub committed 2026-10-20 13:23:26 +08:00
commit 620ca5d96c
35 files changed
+3692 -58

No files matched your search

+82 -3
View File
@@ -2,6 +2,8 @@
import * as React from "react";
import { useSearchParams } from "next/navigation";
import {
BuildingIcon,
ChevronLeftIcon,
@@ -19,6 +21,7 @@ import {
import { toast } from "sonner";
import { AssetDslSearch } from "@/components/asset-dsl-search";
import { IntelligencePanel } from "@/components/intelligence-panel";
import { ScopeTextEditor } from "@/components/scope-text-editor";
import {
AlertDialog,
@@ -107,7 +110,38 @@ const TABS: { key: string; label: string; icon: LucideIcon }[] = [
{ key: "endpoint", label: "接口", icon: LinkIcon },
];
export default function AssetsPage() {
function AssetsContent() {
const searchParams = useSearchParams();
const requestedAsset = searchParams.get("asset") ?? "";
const [assetTarget, setAssetTarget] = React.useState<{ id: number; type: string }>();
const [assetTargetError, setAssetTargetError] = React.useState("");
React.useEffect(() => {
let alive = true;
setAssetTarget(undefined);
setAssetTargetError("");
if (!/^[1-9]\d*$/.test(requestedAsset)) return;
api
.searchAssets(`id==${requestedAsset}`, "", 1)
.then((r) => {
if (!alive) return;
const asset = r.assets[0];
if (!asset) {
setAssetTargetError(`资产 #${requestedAsset} 不存在或已删除`);
return;
}
setAssetTarget({ id: asset.id, type: asset.type });
setTab(asset.type);
setPage(0);
setIntelligenceAsset(null);
})
.catch((e) => {
if (alive) setAssetTargetError((e as Error).message);
});
return () => {
alive = false;
};
}, [requestedAsset]);
const [intelligenceAsset, setIntelligenceAsset] = React.useState<number | null>(null);
const [rows, setRows] = React.useState<Asset[]>([]);
const [total, setTotal] = React.useState(0);
const [companies, setCompanies] = React.useState<Company[]>([]);
@@ -230,14 +264,14 @@ export default function AssetsPage() {
// Reset query + page + selection when switching tabs
// biome-ignore lint/correctness/useExhaustiveDependencies: tab changes intentionally reset tab-local controls.
React.useEffect(() => {
setQuery("");
setQuery(assetTarget?.type === tab ? `id==${assetTarget.id}` : "");
setDslError("");
setSelected(new Set());
setRows([]);
setRowsTab("");
setTotal(0);
setLoaded(false);
}, [tab]);
}, [tab, assetTarget]);
// biome-ignore lint/correctness/useExhaustiveDependencies: these controls intentionally reset server pagination.
React.useEffect(() => setPage(0), [tab, size, query]);
@@ -314,6 +348,32 @@ export default function AssetsPage() {
return (
<div className="flex h-[calc(100vh-6rem)] min-h-0 flex-col gap-4">
{assetTargetError ? (
<p role="alert" className="text-sm text-destructive">
{assetTargetError}
</p>
) : null}
<Dialog
open={intelligenceAsset !== null}
onOpenChange={(open) => {
if (!open) setIntelligenceAsset(null);
}}
>
<DialogContent className="sm:max-w-5xl">
<DialogHeader>
<DialogTitle>资产 #{intelligenceAsset} 的关联情报</DialogTitle>
<DialogDescription>按来源任务查看凭据、线索和敏感数据。</DialogDescription>
</DialogHeader>
{intelligenceAsset !== null ? (
<IntelligencePanel
key={intelligenceAsset}
scope="assets"
scopeId={String(intelligenceAsset)}
onNavigate={() => setIntelligenceAsset(null)}
/>
) : null}
</DialogContent>
</Dialog>
<div className="flex items-center justify-between gap-4">
<div>
<h1 className="text-xl font-semibold tracking-tight">资产</h1>
@@ -322,6 +382,17 @@ export default function AssetsPage() {
<span className="text-sm text-muted-foreground">
共 <span className="tabular-nums">{totalAssets}</span> 项资产
</span>
{tab !== "company" ? (
<Button
variant="outline"
size="sm"
disabled={selected.size !== 1}
title="选择一项资产查看关联情报"
onClick={() => setIntelligenceAsset(Array.from(selected)[0])}
>
关联情报
</Button>
) : null}
{selected.size > 0 && (
<Button variant="destructive" size="sm" onClick={() => openDelete(Array.from(selected) as number[])}>
<Trash2Icon className="size-3.5" /> 删除已选 ({selected.size})
@@ -1214,3 +1285,11 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
</Dialog>
);
}
export default function AssetsPage() {
return (
<React.Suspense fallback={null}>
<AssetsContent />
</React.Suspense>
);
}
@@ -478,9 +478,32 @@ function WorkerAssetBadge({ assets }: { assets: IntentAsset[] }) {
);
}
export function SessionsTab({ taskId }: { taskId: string }) {
export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string; requestedSession?: string }) {
const approvalFocus = useApprovalFocus({ taskId });
const [selectedSessionId, setActiveId] = React.useState(MAIN_ID);
const [linkedSession, setLinkedSession] = React.useState<Session>();
const hasRequestedSession = React.useRef(false);
hasRequestedSession.current = /^(intent:[1-9]\d*|main:\d+|plan)$/.test(requestedSession);
React.useEffect(() => {
let session: Session | undefined;
if (/^intent:[1-9]\d*$/.test(requestedSession)) {
const id = requestedSession.slice(7);
session = {
id,
intent_id: id,
role: "worker",
title: `Worker #${id}`,
status: "done",
live: false,
last_activity: "",
};
} else if (/^main:\d+$/.test(requestedSession)) {
const seg = Number(requestedSession.slice(5));
session = { ...MAIN_SESSION, id: mainSessionId(seg), seg, title: mainSessionTitle(seg) };
} else if (requestedSession === "plan") session = PLANNER_SESSION;
setLinkedSession(session);
if (session) setActiveId(session.id);
}, [requestedSession]);
const focusSession = React.useMemo<Session | undefined>(() => {
const source = approvalFocus.state?.source;
if (!source) return undefined;
@@ -887,7 +910,7 @@ export function SessionsTab({ taskId }: { taskId: string }) {
setSessionTokens({});
setLLMResolutions(null);
setSseLive(false);
setActiveId(MAIN_ID); // a stale worker id from the previous task must not leak in
if (!hasRequestedSession.current) setActiveId(MAIN_ID); // preserve an explicit session deep link
setMainSegs([{ seq: 0, created_at: "" }]);
setCurrentSeg(0);
snapshotRef.current = 0;
@@ -949,7 +972,7 @@ export function SessionsTab({ taskId }: { taskId: string }) {
bootKey = mainSessionKey(ms.current);
if (bootKey !== mainSessionKey(0)) loadingKeysRef.current.delete(mainSessionKey(0));
loadingKeysRef.current.add(bootKey);
setActiveId(mainSessionId(ms.current));
if (!hasRequestedSession.current) setActiveId(mainSessionId(ms.current));
patchStore(bootKey, (s) => ({ ...s, loading: true }));
return api.activityHistory(taskId, bootKey, 0, PAGE);
})
@@ -969,7 +992,9 @@ export function SessionsTab({ taskId }: { taskId: string }) {
};
});
// Open the single task SSE from the snapshot cursor.
const es = openSSE(`/api/exploration/activity/stream?task=${encodeURIComponent(taskId)}&since=${snapshotRef.current}`);
const es = openSSE(
`/api/exploration/activity/stream?task=${encodeURIComponent(taskId)}&since=${snapshotRef.current}`,
);
esRef.current = es;
es.onopen = () => setSseLive(true);
es.onerror = () => setSseLive(false); // EventSource auto-reconnects; DB compensates the gap
@@ -1244,10 +1269,10 @@ export function SessionsTab({ taskId }: { taskId: string }) {
const sessions = React.useMemo(() => {
const items = [...mainSessions, { ...PLANNER_SESSION, live: plannerLive }, ...workerSessions, SYSTEM_SESSION];
const located = focusSession ?? retainedSession;
const located = focusSession ?? retainedSession ?? linkedSession;
if (located && !items.some((s) => s.id === located.id)) items.push(located);
return items;
}, [mainSessions, workerSessions, plannerLive, focusSession, retainedSession]);
}, [mainSessions, workerSessions, plannerLive, focusSession, retainedSession, linkedSession]);
const grouped = {
mainagent: sessions.filter((s) => s.role === "mainagent"),
@@ -8,6 +8,7 @@ import { useRouter, useSearchParams } from "next/navigation";
import { ArchiveIcon, ArrowLeftIcon, BrainIcon, CheckIcon, CircleAlertIcon, PauseIcon, PlayIcon } from "lucide-react";
import { toast } from "sonner";
import { IntelligencePanel } from "@/components/intelligence-panel";
import { StatusBadge } from "@/components/status-badge";
import { TaskLLMProfileChain } from "@/components/task-llm-profile-chain";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
@@ -56,6 +57,7 @@ const TABS = [
{ value: "graph", label: "探索链路" },
{ value: "broadcast", label: "播报板" },
{ value: "findings", label: "发现" },
{ value: "intelligence", label: "任务情报" },
{ value: "retests", label: "复测" },
{ value: "assets", label: "测试资产" },
{ value: "coverage", label: "资产覆盖图" },
@@ -209,7 +211,11 @@ function TaskDetailInner() {
const [task, setTask] = React.useState<Task | null>(null);
const [paused, setPaused] = React.useState(false);
const [loaded, setLoaded] = React.useState(false);
const [tab, setTab] = React.useState("sessions");
const requestedTab = searchParams.get("tab") ?? "sessions";
const [tab, setTab] = React.useState(TABS.some((item) => item.value === requestedTab) ? requestedTab : "sessions");
React.useEffect(() => {
if (TABS.some((item) => item.value === requestedTab)) setTab(requestedTab);
}, [requestedTab]);
const [interceptPendingCount, setInterceptPendingCount] = React.useState(0);
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [archiving, setArchiving] = React.useState(false);
@@ -418,7 +424,7 @@ function TaskDetailInner() {
{/* Tab content */}
<div className="flex-1 p-4 lg:p-6">
<TabsContent value="sessions" className="mt-0">
<SessionsTab taskId={id} />
<SessionsTab key={id} taskId={id} requestedSession={searchParams.get("session") ?? ""} />
</TabsContent>
<TabsContent value="overview" className="mt-0">
<OverviewTab taskId={id} />
@@ -429,6 +435,9 @@ function TaskDetailInner() {
<TabsContent value="broadcast" className="mt-0">
<BroadcastTab taskId={id} />
</TabsContent>
<TabsContent value="intelligence" className="mt-0">
<IntelligencePanel scope="tasks" scopeId={id} />
</TabsContent>
<TabsContent value="findings" className="mt-0">
<FindingsTab taskId={id} />
</TabsContent>
+97 -3
View File
@@ -7,6 +7,7 @@ import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldContent, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
@@ -15,10 +16,15 @@ import { api } from "@/lib/api";
import { CHAT_SEND_MODE_OPTIONS, type ChatSendMode, setChatSendMode, useChatSendMode } from "@/lib/chat-send-mode";
import type { Settings } from "@/lib/types";
import { UpdateCard } from "./_components/update-card";
import { BasicAuthCard } from "./_components/basic-auth-card";
import { UpdateCard } from "./_components/update-card";
export default function SystemSettingsPage() {
const [credentialAgent, setCredentialAgent] = React.useState(false);
const [credentialBinding, setCredentialBinding] = React.useState(false);
const [savingCredentials, setSavingCredentials] = React.useState(false);
const [intelligenceEnabled, setIntelligenceEnabled] = React.useState(false);
const [savingIntelligence, setSavingIntelligence] = React.useState(false);
const [trafficCapture, setTrafficCapture] = React.useState(false);
const [agentTrafficBinding, setAgentTrafficBinding] = React.useState(false);
const [webSearch, setWebSearch] = React.useState(false);
@@ -48,6 +54,9 @@ export default function SystemSettingsPage() {
const sendMode = useChatSendMode();
const apply = React.useCallback((s: Settings) => {
setCredentialAgent(!!s.credential_agent_enabled);
setCredentialBinding(!!s.credential_traffic_binding);
setIntelligenceEnabled(!!s.task_intelligence_enabled);
setTrafficCapture(!!s.traffic_capture);
setAgentTrafficBinding(!!s.agent_traffic_binding);
setWebSearch(!!s.web_search_enabled);
@@ -255,6 +264,20 @@ export default function SystemSettingsPage() {
// brave-free selected but no key stored and none being entered → tool stays off.
const braveNeedsKey = webSearch && backend === "brave-free" && !braveKeySet;
const saveCredentialOptions = async (patch: Partial<Settings>) => {
setSavingCredentials(true);
try {
const s = await api.setSettings(patch);
setCredentialAgent(!!s.credential_agent_enabled);
setCredentialBinding(!!s.credential_traffic_binding);
setIntelligenceEnabled(!!s.task_intelligence_enabled);
toast.success("凭据处理设置已保存");
} catch (e) {
toast.error("保存失败:" + (e as Error).message);
} finally {
setSavingCredentials(false);
}
};
return (
<div className="flex flex-1 flex-col gap-4 md:gap-6">
<div>
@@ -434,6 +457,77 @@ export default function SystemSettingsPage() {
</CardContent>
</Card>
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle>任务情报</CardTitle>
<CardDescription>自动记录任务中获取的凭据、重要线索和敏感数据,并保留来源证据。</CardDescription>
</CardHeader>
<CardContent>
<Field orientation="horizontal">
<FieldContent>
<FieldLabel htmlFor="task-intelligence">Agent 自动记录</FieldLabel>
<FieldDescription>
默认关闭。任务执行时上报凭据、重要线索和敏感数据,会增加任务 Agent 的提示与上报
Token。仅负责记录,不启动凭据整理。关闭后同时停用下方 Agent 与流量绑定,已有情报和整理结果仍可查看。
</FieldDescription>
</FieldContent>
<Switch
id="task-intelligence"
checked={intelligenceEnabled}
disabled={!loaded || savingIntelligence || savingCredentials}
onCheckedChange={async (value) => {
setSavingIntelligence(true);
try {
const settings = await api.setSettings({ task_intelligence_enabled: value });
setIntelligenceEnabled(!!settings.task_intelligence_enabled);
setCredentialAgent(!!settings.credential_agent_enabled);
setCredentialBinding(!!settings.credential_traffic_binding);
toast.success(value ? "任务情报自动记录已开启" : "任务情报自动记录已关闭");
} catch (error) {
toast.error("保存失败:" + (error as Error).message);
} finally {
setSavingIntelligence(false);
}
}}
/>
</Field>
<Field orientation="horizontal" className="mt-5">
<FieldContent>
<FieldLabel htmlFor="credential-agent">Agent 开关</FieldLabel>
<FieldDescription>
默认关闭。独立整理已有和新增凭据,拆分并高亮账号、密码、Token 和
Cookie,不改变原始上报或验证状态。复杂文本会使用额外模型 Token;可解析的 JSON
无需模型。需先开启上方自动记录。模型可在「Agent → 凭据整理」中配置。
</FieldDescription>
</FieldContent>
<Switch
id="credential-agent"
checked={credentialAgent}
disabled={!loaded || savingCredentials || savingIntelligence || !intelligenceEnabled}
onCheckedChange={(value) => void saveCredentialOptions({ credential_agent_enabled: value })}
/>
</Field>
{credentialAgent ? (
<Field orientation="horizontal" className="mt-5">
<FieldContent>
<FieldLabel htmlFor="credential-traffic">绑定流量</FieldLabel>
<FieldDescription>
默认关闭,仅在 Agent
开关开启时可用。核对已抓取流量中的资产与凭据,关联真实请求或响应并保存匹配片段;不主动登录,也不把匹配流量视为验证成功。关闭
Agent 时同时停用,已有绑定保留。
</FieldDescription>
</FieldContent>
<Switch
id="credential-traffic"
checked={credentialBinding}
disabled={!loaded || savingCredentials}
onCheckedChange={(value) => void saveCredentialOptions({ credential_traffic_binding: value })}
/>
</Field>
) : null}
</CardContent>
</Card>
<Card className="mb-4 break-inside-avoid md:mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
@@ -446,8 +540,8 @@ export default function SystemSettingsPage() {
记录代理,独立于流量捕获。
<br />
来源可选 <b>DuckDuckGo(ddgs)</b>(无需 Key)、<b>Brave(免费版)</b>(需填写 Brave API Key)、{" "}
<b>Tavily</b>(需填写 Tavily API Key)或 <b>DeepSeek</b>(复用当前 LLM 配置)。总开关关闭时,各
Agent 的网络搜索开关不可用。
<b>Tavily</b>(需填写 Tavily API Key)或 <b>DeepSeek</b>(复用当前 LLM 配置)。总开关关闭时,各 Agent
的网络搜索开关不可用。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">