报告沙箱

This commit is contained in:
董宏凯 committed 2026-05-27 17:20:41 +08:00
1 parent d6b88b842d
commit 198fc18c50
7 files changed
+736 -11

No files matched your search

@@ -16,6 +16,7 @@
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useArtifacts } from "@/components/workspace/artifacts";
import {
initMultiAgent,
streamMultiAgent,
@@ -44,6 +45,8 @@ export type Step2Dialogue = {
time: string;
confidence: string;
streaming?: boolean;
/** special 席位气泡对应的 LangGraph thread,用于沙箱预览。 */
agentThreadId?: string;
steps?: Array<{
id: string;
key: string;
@@ -53,6 +56,24 @@ export type Step2Dialogue = {
}>;
};
/**
* Stub AI message —— 用于把 special seat SSE 拿到的工具调用注入到 ThreadContext
* 的 `thread.messages` 里,让 `useArtifactContent` 在沙箱里通过虚拟 URL
* `write-file:<path>?message_id=...&tool_call_id=...` 直接读 `args.content`,
* 完全对齐主聊天 `chats/:threadId` 的 write_file 实时预览体验。
*/
export interface StubToolCall {
id: string;
name: string;
args: Record<string, unknown>;
}
export interface StubAiMessage {
id: string;
type: "ai";
content: string;
tool_calls: StubToolCall[];
}
/** Persona 抽屉的 per-seat 覆盖(prompt / temp 仅前端记录,model 真实生效)。 */
export type AgentConfig = {
model: string;
@@ -158,6 +179,24 @@ export interface UseStep2OrchestrationReturn {
hydrateFromDraft: (snapshot: Step2Snapshot) => void;
/** 「新建任务」清空 Step 2 数据(threadIds / dialogues / 共识等)。 */
resetStep2State: () => void;
/** 当前沙箱预览绑定的席位 thread id。 */
activeArtifactThreadId: string | null;
/**
* 各 special seat 的 stub messages —— 注入到沙箱 ThreadContext.thread.messages,
* 让 `useArtifactContent` 通过虚拟 URL 直接读 `args.content`(对齐主聊天)。
*/
seatStubMessages: Record<string, StubAiMessage[]>;
/** 从工具步骤或流式 write_file 打开沙箱预览。 */
openArtifactPreview: (
threadId: string,
path: string,
options?: { auto?: boolean },
) => void;
/** 点击气泡内工具步骤时打开沙箱。 */
openArtifactFromStep: (
dialogue: Step2Dialogue,
step: NonNullable<Step2Dialogue["steps"]>[number],
) => void;
}
export function useStep2Orchestration(
@@ -172,7 +211,26 @@ export function useStep2Orchestration(
loadedFromDraftRef,
} = options;
const {
artifacts,
setArtifacts,
select: selectArtifact,
setOpen: setArtifactsOpen,
deselect: deselectArtifact,
} = useArtifacts();
const artifactPathsRef = useRef<string[]>([]);
useEffect(() => {
artifactPathsRef.current = artifacts;
}, [artifacts]);
// ─── State ─────────────────────────────────────────────────────────
const [activeArtifactThreadId, setActiveArtifactThreadId] = useState<string | null>(
null,
);
const [seatStubMessages, setSeatStubMessages] = useState<
Record<string, StubAiMessage[]>
>({});
const seatStubMessagesRef = useRef<Record<string, StubAiMessage[]>>({});
const [selectedAgents, setSelectedAgents] = useState<SelectedAgent[]>(
DEFAULT_SELECTED_AGENTS,
);
@@ -251,6 +309,208 @@ export function useStep2Orchestration(
isOrchestratingRef.current = isOrchestrating;
}, [isOrchestrating]);
const resolveSeatThreadId = useCallback((ids: ThreadIdMap, agentName: string) => {
return ids[agentName] ?? ids[agentName.toLowerCase()];
}, []);
/**
* 把工具调用幂等地写进 seat 的 stub ai message —— **同 (toolName, path)** 视为同一次
* 调用,后续帧只更新 args(LangGraph 流式期间会多次发送完整 tool_calls 覆盖 args)。
* 返回的 `messageId`/`toolCallId` 用于拼出 `write-file:` 虚拟 URL,沙箱 useArtifactContent
* 据此从 thread.messages 取出 args.content,完全绕过 HTTP。
*/
const upsertSeatToolCall = useCallback(
(
seatThreadId: string,
toolName: string,
args: Record<string, unknown>,
): { messageId: string; toolCallId: string } => {
const path = typeof args.path === "string" ? args.path : "";
const current = seatStubMessagesRef.current[seatThreadId] ?? [];
const existing = current[0];
const baseMsg: StubAiMessage = existing ?? {
id: `roundtable-stub-${seatThreadId}`,
type: "ai",
content: "",
tool_calls: [],
};
const idx = baseMsg.tool_calls.findIndex(
(tc) =>
tc.name === toolName &&
String((tc.args as { path?: unknown })?.path ?? "") === path,
);
const toolCallId =
idx >= 0
? baseMsg.tool_calls[idx].id
: `tc-${seatThreadId}-${baseMsg.tool_calls.length}`;
const nextToolCall: StubToolCall = {
id: toolCallId,
name: toolName,
args,
};
const nextToolCalls =
idx >= 0
? baseMsg.tool_calls.map((tc, i) =>
i === idx ? nextToolCall : tc,
)
: [...baseMsg.tool_calls, nextToolCall];
const nextAiMsg: StubAiMessage = {
...baseMsg,
tool_calls: nextToolCalls,
};
const nextMap = {
...seatStubMessagesRef.current,
[seatThreadId]: [nextAiMsg],
};
seatStubMessagesRef.current = nextMap;
setSeatStubMessages(nextMap);
return { messageId: nextAiMsg.id, toolCallId };
},
[],
);
/**
* 用「虚拟 URL」(write-file: scheme)打开沙箱 —— 内容来自 stub messages 的 args.content,
* 不污染 `artifacts[]` 真实路径列表(列表后续可由 present_files / 显式 setArtifacts 填充)。
*/
const openSeatVirtualArtifact = useCallback(
(seatThreadId: string, virtualUrl: string, auto: boolean) => {
setActiveArtifactThreadId(seatThreadId);
const open = () => {
selectArtifact(virtualUrl, auto);
setArtifactsOpen(true);
};
if (auto) {
window.setTimeout(open, 100);
} else {
open();
}
},
[selectArtifact, setArtifactsOpen],
);
const buildWriteFileVirtualUrl = useCallback(
(path: string, messageId: string, toolCallId: string) =>
new URL(
`write-file:${path}?message_id=${encodeURIComponent(
messageId,
)}&tool_call_id=${encodeURIComponent(toolCallId)}`,
).toString(),
[],
);
/**
* `openArtifactPreview` —— 走真实路径(present_files 等已落盘场景),走 HTTP API 加载。
* 沙箱 write_file 实时预览请用 `openSeatVirtualArtifact`。
*/
const openArtifactPreview = useCallback(
(threadId: string, path: string, options?: { auto?: boolean }) => {
const normalized = path.trim();
if (!normalized || !threadId) return;
setActiveArtifactThreadId(threadId);
const prev = artifactPathsRef.current;
if (!prev.includes(normalized)) {
const next = [...prev, normalized];
artifactPathsRef.current = next;
setArtifacts(next);
}
const openPanel = () => {
selectArtifact(normalized, options?.auto ?? false);
setArtifactsOpen(true);
};
if (options?.auto) {
window.setTimeout(openPanel, 100);
} else {
openPanel();
}
},
[selectArtifact, setArtifacts, setArtifactsOpen],
);
const openArtifactFromStep = useCallback(
(
dialogue: Step2Dialogue,
step: NonNullable<Step2Dialogue["steps"]>[number],
) => {
const seatThreadId = dialogue.agentThreadId;
if (!seatThreadId) return;
const [, toolName] = step.key.split(":");
if (toolName === "write_file" || toolName === "str_replace") {
const path = step.args?.path;
if (typeof path !== "string" || !step.args) return;
const { messageId, toolCallId } = upsertSeatToolCall(
seatThreadId,
toolName,
step.args,
);
const virtualUrl = buildWriteFileVirtualUrl(path, messageId, toolCallId);
openSeatVirtualArtifact(seatThreadId, virtualUrl, false);
return;
}
if (toolName === "present_files") {
const filepaths = step.args?.filepaths;
if (Array.isArray(filepaths)) {
const first = filepaths.find(
(p): p is string => typeof p === "string" && p.length > 0,
);
if (first) openArtifactPreview(seatThreadId, first);
}
}
},
[
buildWriteFileVirtualUrl,
openArtifactPreview,
openSeatVirtualArtifact,
upsertSeatToolCall,
],
);
const handleArtifactToolPhase = useCallback(
(
phase: StreamPhase,
toolName: string | undefined,
args: Record<string, unknown> | undefined,
seatThreadId: string | undefined,
) => {
if (phase !== "tool_calling") return;
if (!seatThreadId) return;
const isArtifactTool =
toolName === "write_file" || toolName === "str_replace";
if (!isArtifactTool) return;
const path = args?.path;
if (typeof path !== "string" || !path || !args) {
if (typeof window !== "undefined") {
console.debug(
"[roundtable-sandbox] tool_calling without path yet",
{ toolName, args },
);
}
return;
}
const { messageId, toolCallId } = upsertSeatToolCall(
seatThreadId,
toolName as string,
args,
);
const virtualUrl = buildWriteFileVirtualUrl(path, messageId, toolCallId);
if (typeof window !== "undefined") {
console.debug(
"[roundtable-sandbox] auto-open from phase",
{ toolName, path, seatThreadId, virtualUrl },
);
}
openSeatVirtualArtifact(seatThreadId, virtualUrl, true);
},
[
buildWriteFileVirtualUrl,
openSeatVirtualArtifact,
upsertSeatToolCall,
],
);
// ─── Dialogue / Speaker helpers ────────────────────────────────────
const appendDialogue = useCallback(
(card: {
@@ -349,6 +609,7 @@ export function useStep2Orchestration(
avatarType: string;
initialContent?: string;
confidence?: string;
agentThreadId?: string;
}): number => {
const id = Date.now() + Math.random();
setStep2RoundtableDialogues((prev) => [
@@ -362,6 +623,7 @@ export function useStep2Orchestration(
confidence: card.confidence ?? "正在输出…",
streaming: true,
steps: [],
agentThreadId: card.agentThreadId,
},
]);
return id;
@@ -587,11 +849,13 @@ export function useStep2Orchestration(
? agentConfigsRef.current[meta.speakerId]?.model
: undefined;
const seatThreadId = resolveSeatThreadId(ids, subName);
const subBubbleId = appendStreamingDialogue({
sender: meta?.displayName ?? subName,
avatarType: meta?.avatarType ?? "blue",
initialContent: "",
confidence: "调度中",
agentThreadId: seatThreadId,
});
const subAborter = new AbortController();
@@ -616,6 +880,12 @@ export function useStep2Orchestration(
`${phase}:${toolName ?? ""}`,
args,
);
handleArtifactToolPhase(
phase,
toolName,
args,
seatThreadId,
);
},
});
if (orchestrationCancelRef.current) {
@@ -684,6 +954,8 @@ export function useStep2Orchestration(
markSpeakerIdle,
clearAllStreamingSpeakers,
triggerToast,
handleArtifactToolPhase,
resolveSeatThreadId,
],
);
@@ -960,8 +1232,14 @@ export function useStep2Orchestration(
setLastLeaderContent("");
setHasConsensus(false);
setConsensusPercentage(0);
setActiveArtifactThreadId(null);
artifactPathsRef.current = [];
setArtifacts([]);
seatStubMessagesRef.current = {};
setSeatStubMessages({});
deselectArtifact();
step2InitRef.current = false;
}, [abortAllInFlight]);
}, [abortAllInFlight, deselectArtifact, setArtifacts]);
return {
selectedAgents,
@@ -1003,5 +1281,9 @@ export function useStep2Orchestration(
handleSaveAgentAndRecalculate,
hydrateFromDraft,
resetStep2State,
activeArtifactThreadId,
seatStubMessages,
openArtifactPreview,
openArtifactFromStep,
};
}