|
|
@@ -0,0 +1,703 @@
|
|
|
+import { createEffect, createMemo, mapArray, on, onCleanup, onMount, untrack } from "solid-js"
|
|
|
+import { createChatCache } from "./chat-cache"
|
|
|
+import { createStore, reconcile, unwrap } from "solid-js/store"
|
|
|
+import {
|
|
|
+ paasRecord,
|
|
|
+ paasRows,
|
|
|
+ paasRunDetail,
|
|
|
+ paasRun,
|
|
|
+ paasStatus,
|
|
|
+ paasTerminalStatuses,
|
|
|
+ paasText,
|
|
|
+ type PaasFile,
|
|
|
+ type PaasPlatform,
|
|
|
+ type PaasProgress,
|
|
|
+ type PaasEffort,
|
|
|
+} from "@/paas"
|
|
|
+
|
|
|
+export type ResearchMessage = {
|
|
|
+ id: string
|
|
|
+ role: "user" | "assistant"
|
|
|
+ text: string
|
|
|
+ status?: string
|
|
|
+ runID?: string
|
|
|
+ requestID?: string
|
|
|
+ replyTo?: string
|
|
|
+ recovery?: string
|
|
|
+ executionID?: string
|
|
|
+ activity?: PaasProgress[]
|
|
|
+ started?: number
|
|
|
+ updated?: number
|
|
|
+ submitted?: { input: string; files: PaasFile[] }
|
|
|
+ error?: string
|
|
|
+}
|
|
|
+export type ResearchChat = {
|
|
|
+ id: string
|
|
|
+ agentID: string
|
|
|
+ name: string
|
|
|
+ title: string
|
|
|
+ threadID: string
|
|
|
+ draft: string
|
|
|
+ files: PaasFile[]
|
|
|
+ effort?: PaasEffort
|
|
|
+ messages: ResearchMessage[]
|
|
|
+ cache?: { source: string; ids: string[]; loaded: boolean }
|
|
|
+ titleManual?: boolean
|
|
|
+ archived?: boolean
|
|
|
+}
|
|
|
+export const working = (message?: ResearchMessage) => !!message?.status && !paasTerminalStatuses.has(message.status)
|
|
|
+
|
|
|
+export function createResearchChats(props: {
|
|
|
+ api?: PaasPlatform
|
|
|
+ connected: boolean
|
|
|
+ scope?: string
|
|
|
+ windowID?: string
|
|
|
+ onNotice?: (notice: { chatID: string; title: string; body: string }) => void
|
|
|
+}) {
|
|
|
+ const [state, setState] = createStore({
|
|
|
+ chats: [] as ResearchChat[],
|
|
|
+ active: "",
|
|
|
+ error: "",
|
|
|
+ storageError: "",
|
|
|
+ restored: false,
|
|
|
+ focusRun: "",
|
|
|
+ syncing: "",
|
|
|
+ cacheVersion: 0,
|
|
|
+ })
|
|
|
+ const life = {
|
|
|
+ active: true,
|
|
|
+ epoch: 0,
|
|
|
+ key: "",
|
|
|
+ polling: false,
|
|
|
+ navigation: 0,
|
|
|
+ }
|
|
|
+ const current = createMemo(() => state.chats.find((chat) => chat.id === state.active))
|
|
|
+ const job = (chat = current()) =>
|
|
|
+ chat?.messages.findLast((message) => message.role === "assistant" && working(message))
|
|
|
+ const persistence: { current?: ReturnType<typeof createChatCache> } = {}
|
|
|
+ const save = () => {
|
|
|
+ if (current()) persistence.current?.stage(current()!)
|
|
|
+ persistence.current?.index(
|
|
|
+ state.chats.map((c) => c.id),
|
|
|
+ state.active,
|
|
|
+ )
|
|
|
+ persistence.current?.flush()
|
|
|
+ }
|
|
|
+ const hydrate = (chat: ResearchChat) => {
|
|
|
+ if (chat.cache?.loaded !== false || !persistence.current) return
|
|
|
+ try {
|
|
|
+ const messages = persistence.current.hydrate(chat)
|
|
|
+ setState("chats", (c) => c.id === chat.id, { messages, cache: { ...chat.cache, loaded: true } })
|
|
|
+ } catch {
|
|
|
+ setState("storageError", "该会话的本机缓存读取失败,可同步平台记录;草稿仍保留。")
|
|
|
+ }
|
|
|
+ }
|
|
|
+ const beginNavigation = () => ({ epoch: life.epoch, revision: ++life.navigation })
|
|
|
+ const selected = (ticket: ReturnType<typeof beginNavigation>) =>
|
|
|
+ life.active && ticket.epoch === life.epoch && ticket.revision === life.navigation
|
|
|
+ const show = (id: string) => {
|
|
|
+ const chat = state.chats.find((c) => c.id === id)
|
|
|
+ if (chat) hydrate(chat)
|
|
|
+ setState({ active: id, error: "", focusRun: "", syncing: "" })
|
|
|
+ save()
|
|
|
+ }
|
|
|
+ const activate = (id: string) => {
|
|
|
+ const ticket = beginNavigation()
|
|
|
+ const chat = state.chats.find((c) => c.id === id)
|
|
|
+ if (!chat) return
|
|
|
+ show(id)
|
|
|
+ if (chat.threadID && props.connected)
|
|
|
+ void loadThread({ id: chat.agentID, name: chat.name }, chat.threadID, chat.title, ticket)
|
|
|
+ }
|
|
|
+ const update = (chatID: string, messageID: string, run: Record<string, unknown>, notify = true) => {
|
|
|
+ const chat = state.chats.find((c) => c.id === chatID)
|
|
|
+ const previous = chat?.messages.find((m) => m.id === messageID)
|
|
|
+ if (!previous) return
|
|
|
+ const status = paasStatus(run)
|
|
|
+ if (paasTerminalStatuses.has(previous.status || "") && !paasTerminalStatuses.has(status)) return
|
|
|
+ const text = paasText(run.output) || previous.text
|
|
|
+ const error = paasText(run.error_message)
|
|
|
+ const changed = status !== previous.status || text !== previous.text || error !== previous.error
|
|
|
+ if (changed) {
|
|
|
+ const before = previous.status
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chatID,
|
|
|
+ "messages",
|
|
|
+ (m) => m.id === messageID,
|
|
|
+ { status, text, error, updated: Date.now() },
|
|
|
+ )
|
|
|
+ if (notify && before && before !== status && (paasTerminalStatuses.has(status) || status.startsWith("waiting")))
|
|
|
+ props.onNotice?.({
|
|
|
+ chatID,
|
|
|
+ title: status.startsWith("waiting") ? "研究任务需要确认" : "研究任务已有结果",
|
|
|
+ body: chat?.title || "打开会话查看",
|
|
|
+ })
|
|
|
+ }
|
|
|
+ const thread = paasText(run.thread_id) || paasText(run.session_id)
|
|
|
+ if (thread && chat?.threadID !== thread) setState("chats", (c) => c.id === chatID, "threadID", thread)
|
|
|
+ }
|
|
|
+ const lookups = new Map<string, number>()
|
|
|
+ async function lookup(chatID: string, messageID: string) {
|
|
|
+ const chat = state.chats.find((c) => c.id === chatID)
|
|
|
+ const message = chat?.messages.find((m) => m.id === messageID)
|
|
|
+ if (
|
|
|
+ !chat ||
|
|
|
+ !message?.requestID ||
|
|
|
+ message.runID ||
|
|
|
+ !props.connected ||
|
|
|
+ !props.api ||
|
|
|
+ lookups.get(messageID) === life.epoch
|
|
|
+ )
|
|
|
+ return
|
|
|
+ const epoch = life.epoch
|
|
|
+ lookups.set(messageID, epoch)
|
|
|
+ try {
|
|
|
+ const receipt = paasRecord(
|
|
|
+ await props.api.request({ action: "lookup-request", agentID: chat.agentID, requestID: message.requestID }),
|
|
|
+ )
|
|
|
+ if (!life.active || epoch !== life.epoch || !working(message)) return
|
|
|
+ if (receipt?.found !== true) {
|
|
|
+ if (receipt?.found !== false) throw new Error("平台未返回有效的提交回执。")
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chatID,
|
|
|
+ "messages",
|
|
|
+ (m) => m.id === messageID,
|
|
|
+ "recovery",
|
|
|
+ "平台暂未查到记录,将继续自动核对,不会自动重复执行。",
|
|
|
+ )
|
|
|
+ return
|
|
|
+ }
|
|
|
+ const run = paasRun(receipt.run)
|
|
|
+ if (run.agent_id && run.agent_id !== chat.agentID) throw new Error("提交回执的智能体不匹配。")
|
|
|
+ // A history refresh can discover this run before receipt recovery. Keep the original message and draft backup.
|
|
|
+ const duplicate = chat.messages.find(
|
|
|
+ (m) => m.role === "assistant" && m.id !== messageID && m.runID === run.run_id,
|
|
|
+ )
|
|
|
+ if (duplicate) {
|
|
|
+ const index = chat.messages.findIndex((m) => m.id === duplicate.id)
|
|
|
+ const userID =
|
|
|
+ duplicate.replyTo || (chat.messages[index - 1]?.role === "user" ? chat.messages[index - 1].id : "")
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chatID,
|
|
|
+ "messages",
|
|
|
+ (rows) => rows.filter((m) => m.id !== duplicate.id && m.id !== userID),
|
|
|
+ )
|
|
|
+ }
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chatID,
|
|
|
+ "messages",
|
|
|
+ (m) => m.id === messageID,
|
|
|
+ { runID: run.run_id, recovery: "已自动找回原任务,未重新提交。" },
|
|
|
+ )
|
|
|
+ update(chatID, messageID, run)
|
|
|
+ save()
|
|
|
+ } catch (error) {
|
|
|
+ if (life.active && epoch === life.epoch)
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chatID,
|
|
|
+ "messages",
|
|
|
+ (m) => m.id === messageID,
|
|
|
+ "recovery",
|
|
|
+ error instanceof Error && /HTTP (404|405)\b/.test(error.message)
|
|
|
+ ? "当前平台不支持按提交编号核对,可在任务中心检查;客户端不会自动重发。"
|
|
|
+ : "暂时无法核对提交回执,连接恢复后将继续查询。",
|
|
|
+ )
|
|
|
+ } finally {
|
|
|
+ if (lookups.get(messageID) === epoch) lookups.delete(messageID)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ async function refresh() {
|
|
|
+ if (life.polling || !props.connected || !props.api) return
|
|
|
+ life.polling = true
|
|
|
+ const epoch = life.epoch
|
|
|
+ try {
|
|
|
+ const unresolved = state.chats.flatMap((chat) =>
|
|
|
+ chat.messages
|
|
|
+ .filter((m) => m.status === "unknown" && !m.runID && m.requestID && !m.recovery?.startsWith("当前平台不支持"))
|
|
|
+ .map((message) => ({ chatID: chat.id, messageID: message.id })),
|
|
|
+ )
|
|
|
+ for (let start = 0; start < unresolved.length; start += 4)
|
|
|
+ await Promise.all(unresolved.slice(start, start + 4).map((task) => lookup(task.chatID, task.messageID)))
|
|
|
+ if (!life.active || epoch !== life.epoch) return
|
|
|
+ const tasks = state.chats.flatMap((chat) =>
|
|
|
+ chat.messages
|
|
|
+ .filter((m) => working(m) && m.runID)
|
|
|
+ .map((message) => ({
|
|
|
+ chatID: chat.id,
|
|
|
+ agentID: chat.agentID,
|
|
|
+ messageID: message.id,
|
|
|
+ runID: message.runID!,
|
|
|
+ updated: message.updated,
|
|
|
+ })),
|
|
|
+ )
|
|
|
+ for (let start = 0; start < tasks.length; start += 4) {
|
|
|
+ await Promise.all(
|
|
|
+ tasks.slice(start, start + 4).map(async (task) => {
|
|
|
+ try {
|
|
|
+ const run = await paasRunDetail(props.api!, task.agentID, task.runID)
|
|
|
+ if (
|
|
|
+ life.active &&
|
|
|
+ epoch === life.epoch &&
|
|
|
+ state.chats.find((c) => c.id === task.chatID)?.messages.find((m) => m.id === task.messageID)
|
|
|
+ ?.updated === task.updated
|
|
|
+ )
|
|
|
+ update(task.chatID, task.messageID, run)
|
|
|
+ } catch {
|
|
|
+ /* Preserve the last confirmed state; panels expose retry details. */
|
|
|
+ }
|
|
|
+ }),
|
|
|
+ )
|
|
|
+ }
|
|
|
+ } finally {
|
|
|
+ if (epoch === life.epoch) life.polling = false
|
|
|
+ }
|
|
|
+ }
|
|
|
+ createEffect(
|
|
|
+ on([() => props.scope, () => props.connected], ([scope, connected]) => {
|
|
|
+ life.epoch++
|
|
|
+ life.navigation++
|
|
|
+ setState("syncing", "")
|
|
|
+ life.polling = false
|
|
|
+ save()
|
|
|
+ if (!connected) {
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ () => true,
|
|
|
+ "messages",
|
|
|
+ (m) => working(m) && !m.runID,
|
|
|
+ { status: "unknown", error: "连接中断,提交结果尚未确认,请先核对平台任务。" },
|
|
|
+ )
|
|
|
+ save()
|
|
|
+ return
|
|
|
+ }
|
|
|
+ const key = scope ? `lambda-scientist.chats.v2:${scope}:${props.windowID || "main"}` : ""
|
|
|
+ if (key !== life.key || !state.restored) {
|
|
|
+ persistence.current?.close()
|
|
|
+ life.key = key
|
|
|
+ persistence.current = scope
|
|
|
+ ? createChatCache(localStorage, scope, props.windowID || "main", (message) =>
|
|
|
+ setState("storageError", message),
|
|
|
+ )
|
|
|
+ : undefined
|
|
|
+ const data = persistence.current?.load() || { chats: [], active: "" }
|
|
|
+ const chats = Array.isArray(data.chats)
|
|
|
+ ? data.chats
|
|
|
+ .filter(
|
|
|
+ (c) => c && typeof c.id === "string" && typeof c.agentID === "string" && Array.isArray(c.messages),
|
|
|
+ )
|
|
|
+ .map((c) => ({
|
|
|
+ ...c,
|
|
|
+ name: typeof c.name === "string" ? c.name : "研究助手",
|
|
|
+ title: typeof c.title === "string" ? c.title : "历史会话",
|
|
|
+ threadID: typeof c.threadID === "string" ? c.threadID : "",
|
|
|
+ draft: typeof c.draft === "string" ? c.draft : "",
|
|
|
+ files: Array.isArray(c.files)
|
|
|
+ ? c.files.filter((f) => f && typeof f.file_id === "string" && typeof f.name === "string")
|
|
|
+ : [],
|
|
|
+ messages: c.messages
|
|
|
+ .filter(
|
|
|
+ (m) =>
|
|
|
+ m &&
|
|
|
+ typeof m.id === "string" &&
|
|
|
+ typeof m.text === "string" &&
|
|
|
+ ["user", "assistant"].includes(m.role),
|
|
|
+ )
|
|
|
+ .map((m) =>
|
|
|
+ working(m) && !m.runID
|
|
|
+ ? { ...m, status: "unknown", error: "上次提交结果尚未确认,请先核对平台任务。" }
|
|
|
+ : m,
|
|
|
+ ),
|
|
|
+ }))
|
|
|
+ : []
|
|
|
+ // Stage migration bodies before publishing the new index. Unloaded histories retain their source.
|
|
|
+ chats.forEach((chat) => persistence.current?.stage(chat))
|
|
|
+ setState("chats", reconcile(chats))
|
|
|
+ setState("cacheVersion", (version) => version + 1)
|
|
|
+ setState({
|
|
|
+ active: chats.some((c) => c.id === data.active) ? data.active! : chats[0]?.id || "",
|
|
|
+ restored: true,
|
|
|
+ error: "",
|
|
|
+ })
|
|
|
+ }
|
|
|
+ void refresh()
|
|
|
+ const chat = current()
|
|
|
+ if (chat?.threadID)
|
|
|
+ void loadThread({ id: chat.agentID, name: chat.name }, chat.threadID, chat.title, beginNavigation())
|
|
|
+ }),
|
|
|
+ )
|
|
|
+ createEffect(
|
|
|
+ mapArray(
|
|
|
+ () => state.chats,
|
|
|
+ (chat) => {
|
|
|
+ createEffect(() => {
|
|
|
+ state.cacheVersion
|
|
|
+ persistence.current?.metadata(chat)
|
|
|
+ })
|
|
|
+ createEffect(
|
|
|
+ mapArray(
|
|
|
+ () => chat.messages,
|
|
|
+ (message) => {
|
|
|
+ createEffect(() => {
|
|
|
+ state.cacheVersion
|
|
|
+ const serialized = JSON.stringify(message)
|
|
|
+ untrack(() => persistence.current?.message(chat.id, message.id, serialized))
|
|
|
+ })
|
|
|
+ return message.id
|
|
|
+ },
|
|
|
+ ),
|
|
|
+ )
|
|
|
+ return chat.id
|
|
|
+ },
|
|
|
+ ),
|
|
|
+ )
|
|
|
+ createEffect(() => {
|
|
|
+ state.cacheVersion
|
|
|
+ persistence.current?.index(
|
|
|
+ state.chats.map((c) => c.id),
|
|
|
+ state.active,
|
|
|
+ )
|
|
|
+ })
|
|
|
+ onMount(() => {
|
|
|
+ const unsubscribe = props.api?.onProgress?.((event) => {
|
|
|
+ if (!props.connected) return
|
|
|
+ const chat = state.chats.find((c) => c.messages.some((m) => m.executionID === event.executionID))
|
|
|
+ const message = chat?.messages.find((m) => m.executionID === event.executionID)
|
|
|
+ if (!chat || !message) return
|
|
|
+ const next =
|
|
|
+ event.type === "approval_required"
|
|
|
+ ? "waiting_human"
|
|
|
+ : event.type === "started"
|
|
|
+ ? "running"
|
|
|
+ : event.status || message.status
|
|
|
+ if (next && next !== message.status && (paasTerminalStatuses.has(next) || next.startsWith("waiting")))
|
|
|
+ props.onNotice?.({
|
|
|
+ chatID: chat.id,
|
|
|
+ title: next.startsWith("waiting") ? "研究任务需要确认" : "研究任务已有结果",
|
|
|
+ body: chat.title,
|
|
|
+ })
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chat.id,
|
|
|
+ "messages",
|
|
|
+ (m) => m.id === message.id,
|
|
|
+ {
|
|
|
+ ...(event.runID ? { runID: event.runID } : {}),
|
|
|
+ updated: Date.now(),
|
|
|
+ status: next,
|
|
|
+ activity: [...(message.activity || []).slice(-79), event],
|
|
|
+ },
|
|
|
+ )
|
|
|
+ if (event.threadID) setState("chats", (c) => c.id === chat.id, "threadID", event.threadID)
|
|
|
+ if (event.runID) save()
|
|
|
+ })
|
|
|
+ const timer = setInterval(() => void refresh(), 5000)
|
|
|
+ const visible = () => {
|
|
|
+ if (!document.hidden) void refresh()
|
|
|
+ }
|
|
|
+ document.addEventListener("visibilitychange", visible)
|
|
|
+ window.addEventListener("pagehide", save)
|
|
|
+ onCleanup(() => {
|
|
|
+ unsubscribe?.()
|
|
|
+ clearInterval(timer)
|
|
|
+ document.removeEventListener("visibilitychange", visible)
|
|
|
+ window.removeEventListener("pagehide", save)
|
|
|
+ })
|
|
|
+ })
|
|
|
+ onCleanup(() => {
|
|
|
+ save()
|
|
|
+ persistence.current?.close()
|
|
|
+ life.active = false
|
|
|
+ life.epoch++
|
|
|
+ })
|
|
|
+
|
|
|
+ function choose(agent: Record<string, unknown>, fresh = false) {
|
|
|
+ const agentID = paasText(agent.id)
|
|
|
+ const existing = state.chats.find((c) => c.agentID === agentID && !c.archived)
|
|
|
+ if (!fresh && existing) {
|
|
|
+ activate(existing.id)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ const chat: ResearchChat = {
|
|
|
+ id: crypto.randomUUID(),
|
|
|
+ agentID,
|
|
|
+ name: paasText(agent.name),
|
|
|
+ title: "新会话",
|
|
|
+ threadID: "",
|
|
|
+ draft: "",
|
|
|
+ files: [],
|
|
|
+ messages: [],
|
|
|
+ }
|
|
|
+ setState("chats", (chats) => [...chats, chat])
|
|
|
+ activate(chat.id)
|
|
|
+ }
|
|
|
+ function mergeRuns(chatID: string, runs: Record<string, unknown>[], observed: Map<string, number | undefined>) {
|
|
|
+ for (const source of runs) {
|
|
|
+ const run: Record<string, unknown> = paasRun(source)
|
|
|
+ const chat = state.chats.find((c) => c.id === chatID)!
|
|
|
+ if (paasText(run.agent_id) && run.agent_id !== chat.agentID) throw new Error("会话记录的智能体不匹配。")
|
|
|
+ const existing = chat.messages.find((m) => m.role === "assistant" && m.runID === run.run_id)
|
|
|
+ if (existing) {
|
|
|
+ if (observed.has(existing.id) && existing.updated !== observed.get(existing.id)) continue
|
|
|
+ update(chatID, existing.id, run, false)
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ const userID = crypto.randomUUID()
|
|
|
+ const status = paasStatus(run)
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chatID,
|
|
|
+ "messages",
|
|
|
+ (rows) => [
|
|
|
+ ...rows,
|
|
|
+ { id: userID, role: "user" as const, text: paasText(run.input), runID: paasText(run.run_id) },
|
|
|
+ {
|
|
|
+ id: crypto.randomUUID(),
|
|
|
+ role: "assistant" as const,
|
|
|
+ replyTo: userID,
|
|
|
+ runID: paasText(run.run_id),
|
|
|
+ text: paasText(run.output),
|
|
|
+ status,
|
|
|
+ started:
|
|
|
+ !paasTerminalStatuses.has(status) || run.completed_at || run.updated_at
|
|
|
+ ? Date.parse(paasText(run.created_at)) || undefined
|
|
|
+ : undefined,
|
|
|
+ updated: Date.parse(paasText(run.completed_at) || paasText(run.updated_at)) || undefined,
|
|
|
+ },
|
|
|
+ ],
|
|
|
+ )
|
|
|
+ }
|
|
|
+ }
|
|
|
+ async function loadThread(
|
|
|
+ agent: Record<string, unknown>,
|
|
|
+ threadID: string,
|
|
|
+ title: string,
|
|
|
+ ticket: ReturnType<typeof beginNavigation>,
|
|
|
+ focusRun = "",
|
|
|
+ ) {
|
|
|
+ const existing = state.chats.find((c) => c.agentID === agent.id && c.threadID === threadID)
|
|
|
+ if (existing) hydrate(existing)
|
|
|
+ const observed = new Map(existing?.messages.map((m) => [m.id, m.updated]))
|
|
|
+ if (existing && selected(ticket)) show(existing.id)
|
|
|
+ setState("syncing", threadID)
|
|
|
+ try {
|
|
|
+ const result = await props.api!.request({ action: "thread-runs", agentID: paasText(agent.id), threadID })
|
|
|
+ if (!selected(ticket)) return
|
|
|
+ if (paasRecord(result)?.thread_id !== threadID) throw new Error("会话编号不匹配,请刷新历史。")
|
|
|
+ const runs = paasRows(result, "runs")
|
|
|
+ // Validate the full response before touching a cached conversation.
|
|
|
+ runs.forEach((run) => {
|
|
|
+ const value = paasRun(run)
|
|
|
+ if (value.agent_id && value.agent_id !== agent.id) throw new Error("会话记录的智能体不匹配。")
|
|
|
+ })
|
|
|
+ const chat = state.chats.find((c) => c.agentID === agent.id && c.threadID === threadID)
|
|
|
+ const id = chat?.id || crypto.randomUUID()
|
|
|
+ if (!chat)
|
|
|
+ setState("chats", (rows) => [
|
|
|
+ ...rows,
|
|
|
+ {
|
|
|
+ id,
|
|
|
+ agentID: paasText(agent.id),
|
|
|
+ name: paasText(agent.name),
|
|
|
+ title,
|
|
|
+ threadID,
|
|
|
+ draft: "",
|
|
|
+ files: [],
|
|
|
+ messages: [],
|
|
|
+ },
|
|
|
+ ])
|
|
|
+ if (chat?.cache?.loaded === false) setState("chats", (c) => c.id === id, "cache", { ...chat.cache, loaded: true })
|
|
|
+ mergeRuns(id, runs, observed)
|
|
|
+ show(id)
|
|
|
+ setState("focusRun", focusRun)
|
|
|
+ save()
|
|
|
+ } catch (error) {
|
|
|
+ if (selected(ticket)) setState("error", error instanceof Error ? error.message : "会话读取失败,本地草稿仍保留。")
|
|
|
+ } finally {
|
|
|
+ if (selected(ticket)) setState("syncing", "")
|
|
|
+ }
|
|
|
+ }
|
|
|
+ async function restore(agent: Record<string, unknown>, threadID: string, title: string) {
|
|
|
+ return loadThread(agent, threadID, title, beginNavigation())
|
|
|
+ }
|
|
|
+ async function openTask(agent: Record<string, unknown>, runID: string) {
|
|
|
+ const ticket = beginNavigation()
|
|
|
+ setState({ error: "", focusRun: "" })
|
|
|
+ try {
|
|
|
+ const run: Record<string, unknown> = await paasRunDetail(props.api!, paasText(agent.id), runID)
|
|
|
+ if (!selected(ticket)) return
|
|
|
+ const thread = paasText(run.thread_id) || paasText(run.session_id)
|
|
|
+ if (thread) return loadThread(agent, thread, paasText(run.input) || "研究任务", ticket, runID)
|
|
|
+ const existing = state.chats.find((c) => c.agentID === agent.id && c.messages.some((m) => m.runID === runID))
|
|
|
+ const id = existing?.id || crypto.randomUUID()
|
|
|
+ if (!existing)
|
|
|
+ setState("chats", (rows) => [
|
|
|
+ ...rows,
|
|
|
+ {
|
|
|
+ id,
|
|
|
+ agentID: paasText(agent.id),
|
|
|
+ name: paasText(agent.name),
|
|
|
+ title: paasText(run.input) || "研究任务",
|
|
|
+ threadID: "",
|
|
|
+ draft: "",
|
|
|
+ files: [],
|
|
|
+ messages: [],
|
|
|
+ },
|
|
|
+ ])
|
|
|
+ mergeRuns(id, [run], new Map(existing?.messages.map((m) => [m.id, m.updated])))
|
|
|
+ show(id)
|
|
|
+ setState("focusRun", runID)
|
|
|
+ } catch (error) {
|
|
|
+ if (selected(ticket)) setState("error", error instanceof Error ? error.message : "无法打开任务")
|
|
|
+ }
|
|
|
+ }
|
|
|
+ async function send() {
|
|
|
+ const chat = current()
|
|
|
+ if (!chat || !chat.draft.trim() || job(chat) || !props.connected || !props.api) return
|
|
|
+ if (chat.draft.trim().length > 100000) {
|
|
|
+ setState("error", "单次任务最多支持 100000 个字符,可将较长内容作为研究材料上传。")
|
|
|
+ return
|
|
|
+ }
|
|
|
+ life.navigation++
|
|
|
+ setState("syncing", "")
|
|
|
+ const epoch = life.epoch
|
|
|
+ const input = chat.draft.trim(),
|
|
|
+ files = structuredClone(unwrap(chat.files)),
|
|
|
+ executionID = crypto.randomUUID(),
|
|
|
+ id = crypto.randomUUID(),
|
|
|
+ userID = crypto.randomUUID()
|
|
|
+ const threadID = chat.threadID,
|
|
|
+ agentID = chat.agentID,
|
|
|
+ chatID = chat.id
|
|
|
+ setState("chats", (c) => c.id === chatID, {
|
|
|
+ draft: "",
|
|
|
+ files: [],
|
|
|
+ title: chat.messages.length || chat.titleManual ? chat.title : input.slice(0, 32),
|
|
|
+ messages: [
|
|
|
+ ...chat.messages,
|
|
|
+ { id: userID, role: "user", text: input },
|
|
|
+ {
|
|
|
+ id,
|
|
|
+ role: "assistant",
|
|
|
+ text: "",
|
|
|
+ status: "submitting",
|
|
|
+ executionID,
|
|
|
+ requestID: executionID,
|
|
|
+ replyTo: userID,
|
|
|
+ started: Date.now(),
|
|
|
+ updated: Date.now(),
|
|
|
+ submitted: { input, files },
|
|
|
+ activity: [],
|
|
|
+ },
|
|
|
+ ],
|
|
|
+ })
|
|
|
+ save()
|
|
|
+ try {
|
|
|
+ const result = paasRecord(
|
|
|
+ await props.api.request({
|
|
|
+ action: "execute",
|
|
|
+ agentID,
|
|
|
+ input,
|
|
|
+ files,
|
|
|
+ threadID: threadID || undefined,
|
|
|
+ executionID,
|
|
|
+ requestID: executionID,
|
|
|
+ effort: chat.effort,
|
|
|
+ }),
|
|
|
+ )
|
|
|
+ if (!life.active || epoch !== life.epoch) return
|
|
|
+ if (!result) throw new Error("平台未返回有效记录,请核对任务状态。")
|
|
|
+ const runID = paasText(result.run_id) || paasText(result.id)
|
|
|
+ if (runID)
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chatID,
|
|
|
+ "messages",
|
|
|
+ (m) => m.id === id,
|
|
|
+ "runID",
|
|
|
+ runID,
|
|
|
+ )
|
|
|
+ update(chatID, id, result)
|
|
|
+ } catch (error) {
|
|
|
+ if (life.active && epoch === life.epoch)
|
|
|
+ setState(
|
|
|
+ "chats",
|
|
|
+ (c) => c.id === chatID,
|
|
|
+ "messages",
|
|
|
+ (m) => m.id === id,
|
|
|
+ {
|
|
|
+ status:
|
|
|
+ error instanceof Error && /HTTP (400|401|403|404|413|422)\b/.test(error.message) ? "failed" : "unknown",
|
|
|
+ error: error instanceof Error ? error.message : "提交状态未确认,请核对平台任务。",
|
|
|
+ updated: Date.now(),
|
|
|
+ },
|
|
|
+ )
|
|
|
+ } finally {
|
|
|
+ if (life.active && epoch === life.epoch) {
|
|
|
+ save()
|
|
|
+ const message = state.chats.find((c) => c.id === chatID)?.messages.find((m) => m.id === id)
|
|
|
+ if (message?.status === "unknown" && !message.runID) void lookup(chatID, id)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ function recover(message: ResearchMessage) {
|
|
|
+ const chat = current()
|
|
|
+ if (!chat || !message.submitted) return
|
|
|
+ setState("chats", (c) => c.id === chat.id, {
|
|
|
+ draft: !chat.draft
|
|
|
+ ? message.submitted.input
|
|
|
+ : chat.draft.includes(message.submitted.input)
|
|
|
+ ? chat.draft
|
|
|
+ : `${message.submitted.input}\n\n补充要求:\n${chat.draft}`,
|
|
|
+ files: [
|
|
|
+ ...chat.files,
|
|
|
+ ...structuredClone(unwrap(message.submitted.files)).filter(
|
|
|
+ (file) => !chat.files.some((existing) => existing.file_id === file.file_id),
|
|
|
+ ),
|
|
|
+ ],
|
|
|
+ })
|
|
|
+ save()
|
|
|
+ }
|
|
|
+ function rename(title: string) {
|
|
|
+ const chat = current()
|
|
|
+ if (!chat || !title.trim()) return
|
|
|
+ setState("chats", (c) => c.id === chat.id, { title: title.trim(), titleManual: true })
|
|
|
+ save()
|
|
|
+ }
|
|
|
+ function archive() {
|
|
|
+ const chat = current()
|
|
|
+ if (!chat) return
|
|
|
+ setState("chats", (c) => c.id === chat.id, "archived", !chat.archived)
|
|
|
+ save()
|
|
|
+ }
|
|
|
+ function continueFrom(message: ResearchMessage) {
|
|
|
+ const chat = current()
|
|
|
+ if (!chat || !message.text) return
|
|
|
+ const context = `请基于以下方案继续研究:\n\n${message.text}`
|
|
|
+ setState("chats", (c) => c.id === chat.id, "draft", chat.draft.trim() ? `${chat.draft}\n\n${context}` : context)
|
|
|
+ save()
|
|
|
+ }
|
|
|
+ return {
|
|
|
+ state,
|
|
|
+ setState,
|
|
|
+ current,
|
|
|
+ job,
|
|
|
+ choose,
|
|
|
+ activate,
|
|
|
+ restore,
|
|
|
+ openTask,
|
|
|
+ lookup,
|
|
|
+ send,
|
|
|
+ refresh,
|
|
|
+ update,
|
|
|
+ recover,
|
|
|
+ rename,
|
|
|
+ archive,
|
|
|
+ continueFrom,
|
|
|
+ save,
|
|
|
+ }
|
|
|
+}
|