mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-22 22:12:01 +00:00
对话有上下文了,左边也能选会话
三条 run(d983c4e6 / 14103db5 / 08c3de1c)在用户看来是一次对话,系统里却
毫无关联。查下来不是哪里传漏了,是整层缺失:
- 每轮 base_graph=None 从零建图,Copilot 不知道上一轮问过什么
- 每轮 thread_id = run.id,三条独立的 checkpoint 线程
- 前端 turns 只活在 zustand 里,刷新页面就全没了——那三轮当时在界面上
已经找不回来,只剩 runs 表里三条互不相干的记录
- 后端 13 张表里没有会话这个概念
加两张表(conversations / conversation_turns)。失败的轮次也记:只记成功的,
历史就成了一份美化过的记录,而人回来最想搞清楚的恰恰是上次卡在哪。
Copilot 的上下文带三样:前几轮问答、上一轮那张图(走 _slim 去掉坐标噪音)。
只给问答文字不够——"再按月份拆一下"会让模型重新设计一张图,实测经常接到另
一张表上,答案对不上前一轮。运行时另外注入 {{ input.history }},管的是指代:
用户问"它们平均多少",图里的 agent 得知道"它们"是上一轮那 12 家店。
左侧会话栏只在问数据页出现,可折叠、可改名删除,当前会话存 localStorage。
轮次按会话分桶缓存——切走再切回来要看得到原来的步骤,回源只拿得到问答。
历史轮次的执行过程不预加载,点「看执行过程」才取事件、走现成的 decodeRun。
画布右栏的 Copilot 依附工作流各有一条会话,连说两次"再加一个节点"能接上了
(base_graph 带的是图的结果,带不出"你刚才要我干什么"),但不进左侧列表。
过程中修掉的两个自己引入的坑:
- 第一版在列表为空时自动建一条会话。create 是异步的、StrictMode 把 effect
跑两遍,于是每次进页面都留下两三条"新对话"。改成用户开口那一刻按需建
- 加了"在上一轮的图上改"这条指令之后,模型照改图协议只发 update_node,
而问数据页这条路径的累加器从空图起步,操作全部落空,用户收到的是
"图校验未通过:图是空的,先拖一个节点进来"(会话 f5db9809 的第二轮,
而它的 explanation 证明上下文其实完全读懂了)。指令改成沿用 id 和 config
但完整重发,另加一道兜底:空图且上一轮有图时把操作重放到那张图上
check-ui 多一节「会话」:切换、刷新还在、逛一圈不多出空会话。
This commit is contained in:
+221
-47
@@ -1,6 +1,8 @@
|
||||
import { create } from 'zustand'
|
||||
import { api, streamCopilot, streamRun } from '../api/client'
|
||||
import type { CopilotOp } from '../run/decode'
|
||||
import { decodeRun } from '../run/decode'
|
||||
import { useConversations } from './conversations'
|
||||
import type { GraphSpec, Run, RunEvent } from '../types'
|
||||
|
||||
/**
|
||||
@@ -16,6 +18,10 @@ import type { GraphSpec, Run, RunEvent } from '../types'
|
||||
* 这里**只存原始流**(Copilot 的操作、运行的事件),不在 store 里翻译。
|
||||
* 翻译归 run/decode.ts,全站一份;store 里再译一遍的结果是同一次运行在
|
||||
* 对话页和画布上讲出两个不同的故事,而用户没法判断哪个是真的。
|
||||
*
|
||||
* 轮次按会话分桶存放。之前是单个 turns 数组,于是"对话"只存在于内存里:
|
||||
* 刷新页面就全没了,而每轮又各自从零建图、互不知情。现在每一轮同时写进
|
||||
* 后端的 conversation_turns,刷新能恢复,下一轮也拿得到上一轮的上下文。
|
||||
*/
|
||||
|
||||
export type Phase =
|
||||
@@ -29,6 +35,8 @@ export type Phase =
|
||||
|
||||
export interface ChatTurn {
|
||||
id: string
|
||||
/** 后端 conversation_turns 里的 id。回填靠它 */
|
||||
serverId: string | null
|
||||
question: string
|
||||
phase: Phase
|
||||
/** 一句话进度,给人看"现在到哪了" */
|
||||
@@ -53,18 +61,29 @@ export interface ChatTurn {
|
||||
/** 这一轮自己的取消句柄。放 turn 上而不是 store 上:store 单值会被
|
||||
* 下一轮 ask 覆盖,上一轮的 WebSocket 就再也关不掉了 */
|
||||
cancel: (() => void) | null
|
||||
/** 从库里恢复的历史轮次。它没有事件流,步骤要点开才去取 */
|
||||
restored?: boolean
|
||||
/** 已经补取过事件(或正在取),别重复拉 */
|
||||
stepsLoaded?: boolean
|
||||
}
|
||||
|
||||
interface ChatState {
|
||||
turns: ChatTurn[]
|
||||
/** 按会话分桶。切走再切回来要能看到原来的步骤,所以内存里有就不回源 */
|
||||
byConversation: Record<string, ChatTurn[]>
|
||||
busy: boolean
|
||||
cancel: (() => void) | null
|
||||
loading: boolean
|
||||
|
||||
ask: (question: string) => void
|
||||
stop: () => void
|
||||
clear: () => void
|
||||
turnsOf: (conversationId: string | null) => ChatTurn[]
|
||||
load: (conversationId: string) => Promise<void>
|
||||
ask: (conversationId: string, question: string) => void
|
||||
stop: (conversationId: string) => void
|
||||
/** 审批完成后重新接上运行 */
|
||||
reattach: (turnId: string) => Promise<void>
|
||||
reattach: (conversationId: string, turnId: string) => Promise<void>
|
||||
/** 历史轮次点开"执行过程"时才去取事件 */
|
||||
loadSteps: (conversationId: string, turnId: string) => Promise<void>
|
||||
/** 会话被删了,把内存里那一桶也丢掉 */
|
||||
forget: (conversationId: string) => void
|
||||
}
|
||||
|
||||
let seq = 0
|
||||
@@ -80,35 +99,136 @@ const PHASE_TEXT: Record<Phase, string> = {
|
||||
error: '出错了',
|
||||
}
|
||||
|
||||
const EMPTY: ChatTurn[] = []
|
||||
|
||||
type Patch = (fn: (t: ChatTurn) => Partial<ChatTurn>) => void
|
||||
|
||||
/**
|
||||
* 成果 dict 压成一句话,存进 conversation_turns.answer。
|
||||
*
|
||||
* 它有两个去处:刷新页面后重建界面,以及下一轮拼进 Copilot 的上下文。
|
||||
* 后者决定了这里不能只存个 "[object Object]"——模型要靠它知道上一轮
|
||||
* 答了什么,才接得住"再按月份拆一下"。
|
||||
*/
|
||||
function answerText(output: Record<string, any> | null): string {
|
||||
if (!output) return ''
|
||||
const parts: string[] = []
|
||||
for (const [key, value] of Object.entries(output)) {
|
||||
if (key.startsWith('_') || value == null || value === '') continue
|
||||
parts.push(typeof value === 'string' ? value : JSON.stringify(value))
|
||||
}
|
||||
return parts.join('\n').slice(0, 4000)
|
||||
}
|
||||
|
||||
export const useChat = create<ChatState>((set, get) => ({
|
||||
turns: [],
|
||||
byConversation: {},
|
||||
busy: false,
|
||||
cancel: null,
|
||||
loading: false,
|
||||
|
||||
ask: (question) => {
|
||||
const id = newId()
|
||||
const patch: Patch = (fn) =>
|
||||
set((s) => ({
|
||||
turns: s.turns.map((t) => (t.id === id ? { ...t, ...fn(t) } : t)),
|
||||
turnsOf: (conversationId) =>
|
||||
(conversationId && get().byConversation[conversationId]) || EMPTY,
|
||||
|
||||
forget: (conversationId) =>
|
||||
set((s) => {
|
||||
get().byConversation[conversationId]?.forEach((t) => t.cancel?.())
|
||||
const { [conversationId]: _gone, ...rest } = s.byConversation
|
||||
return { byConversation: rest }
|
||||
}),
|
||||
|
||||
load: async (conversationId) => {
|
||||
// 内存里有就用内存里的:那一份带着这次会话跑出来的完整步骤,
|
||||
// 回源拿到的只有问题和答案。切走再切回来不该丢掉过程
|
||||
if (get().byConversation[conversationId]) return
|
||||
set({ loading: true })
|
||||
try {
|
||||
const detail = await api.conversations.get(conversationId)
|
||||
const turns: ChatTurn[] = detail.turns.map((t) => ({
|
||||
id: t.id,
|
||||
serverId: t.id,
|
||||
question: t.question,
|
||||
phase: t.status === 'error' ? 'error' : t.status === 'running' ? 'error' : 'done',
|
||||
status: t.status === 'error' ? PHASE_TEXT.error : PHASE_TEXT.done,
|
||||
thinking: '',
|
||||
ops: [],
|
||||
events: [],
|
||||
graph: (t.graph as GraphSpec) ?? null,
|
||||
explanation: t.explanation ?? '',
|
||||
// 只留 id:usage / run_class 这些恢复时用不上,真要看详情那一栏
|
||||
// 自己会去取。给个空壳比不给强——「看执行过程」全靠它找到那次运行
|
||||
run: t.run_id ? ({ id: t.run_id } as Run) : null,
|
||||
output: t.answer ? { answer: t.answer } : null,
|
||||
// running 说明上次是被强杀/关标签页断在半路的。标成出错而不是留一个
|
||||
// 永远转圈的行——它不会再动了,转圈只是在骗人
|
||||
error: t.status === 'running' ? '上次没有跑完' : (t.error ?? ''),
|
||||
startedAt: Date.parse(t.created_at ?? '') || Date.now(),
|
||||
lastSeq: 0,
|
||||
cancel: null,
|
||||
restored: true,
|
||||
stepsLoaded: false,
|
||||
}))
|
||||
set((s) => ({
|
||||
byConversation: { ...s.byConversation, [conversationId]: turns },
|
||||
loading: false,
|
||||
}))
|
||||
} catch {
|
||||
set({ loading: false })
|
||||
}
|
||||
},
|
||||
|
||||
loadSteps: async (conversationId, turnId) => {
|
||||
const turn = get().byConversation[conversationId]?.find((t) => t.id === turnId)
|
||||
if (!turn || turn.stepsLoaded) return
|
||||
const runId = turn.run?.id
|
||||
if (!runId) return
|
||||
const patch = patcher(set, conversationId, turnId)
|
||||
patch(() => ({ stepsLoaded: true }))
|
||||
try {
|
||||
const events = await api.runs.events(runId)
|
||||
patch(() => ({ events }))
|
||||
} catch {
|
||||
patch(() => ({ stepsLoaded: false })) // 取失败就还能再点一次
|
||||
}
|
||||
},
|
||||
|
||||
ask: (conversationId, question) => {
|
||||
const id = newId()
|
||||
const patch = patcher(set, conversationId, id)
|
||||
|
||||
set((s) => ({
|
||||
busy: true,
|
||||
turns: [
|
||||
...s.turns,
|
||||
{
|
||||
id, question, phase: 'planning', status: PHASE_TEXT.planning,
|
||||
thinking: '', ops: [], events: [], graph: null, explanation: '',
|
||||
run: null, output: null, error: '', startedAt: Date.now(),
|
||||
lastSeq: 0, cancel: null,
|
||||
},
|
||||
],
|
||||
byConversation: {
|
||||
...s.byConversation,
|
||||
[conversationId]: [
|
||||
...(s.byConversation[conversationId] ?? []),
|
||||
{
|
||||
id, serverId: null, question, phase: 'planning', status: PHASE_TEXT.planning,
|
||||
thinking: '', ops: [], events: [], graph: null, explanation: '',
|
||||
run: null, output: null, error: '', startedAt: Date.now(),
|
||||
lastSeq: 0, cancel: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
}))
|
||||
|
||||
useConversations.getState().touch(conversationId, question)
|
||||
|
||||
// 先开一轮,拿到 serverId 再开始建图。顺序不能反:Copilot 那边要读
|
||||
// 这次会话的历史,而"这一轮"必须已经是 running 状态才不会被算进自己的上下文
|
||||
const started = api.conversations.startTurn(conversationId, question)
|
||||
.then((turn) => { patch(() => ({ serverId: turn.id })); return turn.id })
|
||||
.catch(() => null)
|
||||
|
||||
const save = async (body: Record<string, any>) => {
|
||||
const serverId = await started
|
||||
if (!serverId) return
|
||||
try {
|
||||
await api.conversations.patchTurn(conversationId, serverId, body)
|
||||
} catch { /* 存不下不该影响正在进行的对话 */ }
|
||||
}
|
||||
|
||||
const cancelCopilot = streamCopilot(
|
||||
{ instruction: question, base_graph: null, intent: 'answer' },
|
||||
{ instruction: question, base_graph: null, intent: 'answer', conversation_id: conversationId },
|
||||
(op) => {
|
||||
// 先原样收下,翻译交给 decodeCopilot。thinking 合并在写入时做:
|
||||
// 一次生成几百上千条 delta,逐条存下来光数组就比图大一个量级
|
||||
@@ -150,12 +270,14 @@ export const useChat = create<ChatState>((set, get) => ({
|
||||
graph, phase: 'running', status: PHASE_TEXT.running,
|
||||
explanation: op.explanation ?? '',
|
||||
}))
|
||||
void launch(id, graph, question, patch, set)
|
||||
void save({ graph, explanation: op.explanation ?? '' })
|
||||
void launch(conversationId, id, graph, question, patch, set, save)
|
||||
break
|
||||
}
|
||||
case 'error':
|
||||
patch(() => ({ phase: 'error', error: op.message ?? '生成失败' }))
|
||||
set({ busy: false, cancel: null })
|
||||
void save({ status: 'error', error: op.message ?? '生成失败' })
|
||||
break
|
||||
}
|
||||
},
|
||||
@@ -163,47 +285,70 @@ export const useChat = create<ChatState>((set, get) => ({
|
||||
if (!error) return
|
||||
patch((t) => (t.phase === 'error' ? {} : { phase: 'error', error }))
|
||||
set({ busy: false, cancel: null })
|
||||
void save({ status: 'error', error })
|
||||
},
|
||||
)
|
||||
patch(() => ({ cancel: cancelCopilot }))
|
||||
set({ cancel: cancelCopilot })
|
||||
},
|
||||
|
||||
stop: () => {
|
||||
stop: (conversationId) => {
|
||||
// 只停最后一轮。把所有非终态 turn 一律标成"已取消"会误杀正等人工介入的
|
||||
// 历史轮次——那些是等着用户回来处理的,不是卡住的。
|
||||
const turns = get().turns
|
||||
const turns = get().byConversation[conversationId] ?? []
|
||||
const last = turns[turns.length - 1]
|
||||
last?.cancel?.()
|
||||
get().cancel?.()
|
||||
if (last?.serverId && !['done', 'error', 'waiting'].includes(last.phase)) {
|
||||
void api.conversations
|
||||
.patchTurn(conversationId, last.serverId, { status: 'error', error: '已取消' })
|
||||
.catch(() => undefined)
|
||||
}
|
||||
set((s) => ({
|
||||
busy: false,
|
||||
cancel: null,
|
||||
turns: s.turns.map((t) =>
|
||||
t.id === last?.id && !['done', 'error', 'waiting'].includes(t.phase)
|
||||
? { ...t, phase: 'error', error: '已取消', cancel: null }
|
||||
: t,
|
||||
),
|
||||
byConversation: {
|
||||
...s.byConversation,
|
||||
[conversationId]: turns.map((t) =>
|
||||
t.id === last?.id && !['done', 'error', 'waiting'].includes(t.phase)
|
||||
? { ...t, phase: 'error' as Phase, error: '已取消', cancel: null }
|
||||
: t,
|
||||
),
|
||||
},
|
||||
}))
|
||||
},
|
||||
|
||||
clear: () => {
|
||||
get().cancel?.()
|
||||
get().turns.forEach((t) => t.cancel?.()) // 每轮各有各的订阅,逐个关
|
||||
set({ turns: [], busy: false, cancel: null })
|
||||
},
|
||||
|
||||
reattach: async (turnId) => {
|
||||
const turn = get().turns.find((t) => t.id === turnId)
|
||||
reattach: async (conversationId, turnId) => {
|
||||
const turn = get().byConversation[conversationId]?.find((t) => t.id === turnId)
|
||||
if (!turn?.run) return
|
||||
const patch: Patch = (fn) =>
|
||||
set((s) => ({ turns: s.turns.map((t) => (t.id === turnId ? { ...t, ...fn(t) } : t)) }))
|
||||
const patch = patcher(set, conversationId, turnId)
|
||||
const save = async (body: Record<string, any>) => {
|
||||
if (!turn.serverId) return
|
||||
try {
|
||||
await api.conversations.patchTurn(conversationId, turn.serverId, body)
|
||||
} catch { /* 同上 */ }
|
||||
}
|
||||
patch(() => ({ phase: 'running', status: PHASE_TEXT.running }))
|
||||
set({ busy: true })
|
||||
watch(turn.run.id, turnId, patch, set, turn.lastSeq)
|
||||
watch(turn.run.id, patch, set, save, turn.lastSeq)
|
||||
},
|
||||
}))
|
||||
|
||||
/** 定点更新某个会话里的某一轮。认的是 turn id,所以切走看别的会话也不受影响 */
|
||||
function patcher(set: any, conversationId: string, turnId: string): Patch {
|
||||
return (fn) =>
|
||||
set((s: ChatState) => {
|
||||
const turns = s.byConversation[conversationId]
|
||||
if (!turns) return s
|
||||
return {
|
||||
byConversation: {
|
||||
...s.byConversation,
|
||||
[conversationId]: turns.map((t) => (t.id === turnId ? { ...t, ...fn(t) } : t)),
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户的问题填进这张图的入口字段。
|
||||
*
|
||||
@@ -213,13 +358,18 @@ export const useChat = create<ChatState>((set, get) => ({
|
||||
* 错误里提的那个字段名他从来没见过——那是生成的图里的东西。
|
||||
*
|
||||
* 之前"能跑"纯属运气:Copilot 那一次恰好没声明字段。
|
||||
*
|
||||
* history 是另一件事:图跑起来的时候,模型得知道"它们"指的是上一轮那批数据。
|
||||
* Copilot 侧的上下文只影响图长什么样,管不到这个。
|
||||
*/
|
||||
function fillInput(graph: GraphSpec, question: string): Record<string, any> {
|
||||
export function fillInput(
|
||||
graph: GraphSpec, question: string, history = '',
|
||||
): Record<string, any> {
|
||||
const entry = (graph.nodes ?? []).find((n: any) => n.type === 'input')
|
||||
const fields: any[] = (entry?.data?.config?.fields ?? []) as any[]
|
||||
if (!fields.length) return { question } // 没声明字段也带上,下游可能用 input.question
|
||||
if (!fields.length) return { question, history } // 没声明字段也带上,下游可能用 input.question
|
||||
|
||||
const payload: Record<string, any> = {}
|
||||
const payload: Record<string, any> = { history }
|
||||
for (const f of fields) {
|
||||
if (f?.name) payload[f.name] = f.default ?? ''
|
||||
}
|
||||
@@ -232,17 +382,34 @@ function fillInput(graph: GraphSpec, question: string): Record<string, any> {
|
||||
return payload
|
||||
}
|
||||
|
||||
/** 把这次会话之前几轮压成纯文本,塞进 input.history */
|
||||
function historyOf(conversationId: string, upToTurnId: string): string {
|
||||
const turns = useChat.getState().byConversation[conversationId] ?? []
|
||||
const lines: string[] = []
|
||||
for (const t of turns) {
|
||||
if (t.id === upToTurnId) break
|
||||
const answer = answerText(t.output) || t.explanation
|
||||
if (t.question && answer) lines.push(`问:${t.question}\n答:${answer.slice(0, 600)}`)
|
||||
}
|
||||
return lines.slice(-6).join('\n\n')
|
||||
}
|
||||
|
||||
/** 图建好了就直接跑——用户要的是答案,不是一张图。 */
|
||||
async function launch(
|
||||
turnId: string, graph: GraphSpec, question: string, patch: Patch, set: any,
|
||||
conversationId: string, turnId: string, graph: GraphSpec, question: string,
|
||||
patch: Patch, set: any, save: (body: Record<string, any>) => Promise<void>,
|
||||
) {
|
||||
try {
|
||||
const run = await api.runs.start({ graph, input: fillInput(graph, question) })
|
||||
const run = await api.runs.start({
|
||||
graph, input: fillInput(graph, question, historyOf(conversationId, turnId)),
|
||||
})
|
||||
patch(() => ({ run }))
|
||||
watch(run.id, turnId, patch, set)
|
||||
void save({ run_id: run.id })
|
||||
watch(run.id, patch, set, save)
|
||||
} catch (e: any) {
|
||||
patch(() => ({ phase: 'error', error: e?.message ?? '启动失败' }))
|
||||
set({ busy: false, cancel: null })
|
||||
void save({ status: 'error', error: e?.message ?? '启动失败' })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,7 +419,10 @@ async function launch(
|
||||
* 只做两件事:把事件原样存进这一轮,以及更新那几个驱动 UI 状态机的相位。
|
||||
* "查了哪张表、跑了什么 SQL"不在这里翻译——decodeRun 会从同一批事件里读出来。
|
||||
*/
|
||||
function watch(runId: string, turnId: string, patch: Patch, set: any, after = 0) {
|
||||
function watch(
|
||||
runId: string, patch: Patch, set: any,
|
||||
save: (body: Record<string, any>) => Promise<void>, after = 0,
|
||||
) {
|
||||
const stop = streamRun(runId, (event: RunEvent) => {
|
||||
const d: any = event.data ?? {}
|
||||
patch((t) => ({
|
||||
@@ -280,6 +450,7 @@ function watch(runId: string, turnId: string, patch: Patch, set: any, after = 0)
|
||||
case 'run.failed':
|
||||
patch(() => ({ phase: 'error', error: String(d.error ?? '运行失败') }))
|
||||
set({ busy: false, cancel: null })
|
||||
void save({ status: 'error', error: String(d.error ?? '运行失败') })
|
||||
break
|
||||
case 'run.finished':
|
||||
// 成果在事件里就有,不必再取一次 run;但 run 对象带着 usage 和
|
||||
@@ -288,6 +459,7 @@ function watch(runId: string, turnId: string, patch: Patch, set: any, after = 0)
|
||||
phase: 'done', status: PHASE_TEXT.done, output: d.output ?? null,
|
||||
}))
|
||||
set({ busy: false, cancel: null })
|
||||
void save({ status: 'done', answer: answerText(d.output ?? null) })
|
||||
void api.runs.get(runId)
|
||||
.then((run) => patch(() => ({ run })))
|
||||
.catch(() => undefined)
|
||||
@@ -299,3 +471,5 @@ function watch(runId: string, turnId: string, patch: Patch, set: any, after = 0)
|
||||
patch(() => ({ cancel: stop }))
|
||||
set({ cancel: stop })
|
||||
}
|
||||
|
||||
export { decodeRun }
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { create } from 'zustand'
|
||||
import { api } from '../api/client'
|
||||
import type { Conversation } from '../types'
|
||||
|
||||
/**
|
||||
* 会话列表的状态。
|
||||
*
|
||||
* 只管"有哪些对话、当前在看哪个"。对话里的内容归 chat store —— 两者分开是
|
||||
* 因为列表要常驻(切换时不能闪),而内容是按会话缓存的一大坨东西。
|
||||
*
|
||||
* 当前会话 id 存进 localStorage:刷新后回到刚才那个对话,而不是甩回空白页。
|
||||
* 这是"对话持久化"里用户最先感知到的一半——另一半(内容本身)在 chat store。
|
||||
*/
|
||||
|
||||
const LAST_KEY = 'agentlab.lastConversation'
|
||||
|
||||
interface ConversationState {
|
||||
list: Conversation[]
|
||||
currentId: string | null
|
||||
loading: boolean
|
||||
|
||||
load: () => Promise<void>
|
||||
create: () => Promise<string>
|
||||
select: (id: string | null) => void
|
||||
rename: (id: string, title: string) => Promise<void>
|
||||
remove: (id: string) => Promise<void>
|
||||
/** 有人在这个会话里说话了,把它顶到列表最前并刷新副标题 */
|
||||
touch: (id: string, lastQuestion?: string) => void
|
||||
}
|
||||
|
||||
export const useConversations = create<ConversationState>((set, get) => ({
|
||||
list: [],
|
||||
currentId: localStorage.getItem(LAST_KEY),
|
||||
loading: false,
|
||||
|
||||
load: async () => {
|
||||
set({ loading: true })
|
||||
try {
|
||||
const list = await api.conversations.list('chat')
|
||||
// 记着的那个可能已经被删了(另一个标签页里删的)。指着一个不存在的
|
||||
// 会话会让页面停在空白,这时候退回最近一条,而不是让人对着空屏幕
|
||||
const current = get().currentId
|
||||
const alive = current && list.some((c) => c.id === current)
|
||||
const next = alive ? current : (list[0]?.id ?? null)
|
||||
if (next !== current) {
|
||||
if (next) localStorage.setItem(LAST_KEY, next)
|
||||
else localStorage.removeItem(LAST_KEY)
|
||||
}
|
||||
set({ list, currentId: next, loading: false })
|
||||
} catch {
|
||||
set({ loading: false })
|
||||
}
|
||||
},
|
||||
|
||||
create: async () => {
|
||||
// 已经有一条空会话就直接用它。连点几次"新对话"不该留下一串一模一样的
|
||||
// 空壳——用户的意思是"我要从头开始说",不是"我要三个空对话"
|
||||
const blank = get().list.find((c) => c.turn_count === 0)
|
||||
if (blank) {
|
||||
get().select(blank.id)
|
||||
return blank.id
|
||||
}
|
||||
const created = await api.conversations.create({ kind: 'chat' })
|
||||
localStorage.setItem(LAST_KEY, created.id)
|
||||
set((s) => ({ list: [created, ...s.list], currentId: created.id }))
|
||||
return created.id
|
||||
},
|
||||
|
||||
select: (id) => {
|
||||
if (id) localStorage.setItem(LAST_KEY, id)
|
||||
else localStorage.removeItem(LAST_KEY)
|
||||
set({ currentId: id })
|
||||
},
|
||||
|
||||
rename: async (id, title) => {
|
||||
const clean = title.trim()
|
||||
if (!clean) return
|
||||
// 先改本地再发请求:改名是个不该等一次往返的动作
|
||||
set((s) => ({ list: s.list.map((c) => (c.id === id ? { ...c, title: clean } : c)) }))
|
||||
try {
|
||||
await api.conversations.update(id, { title: clean })
|
||||
} catch {
|
||||
void get().load() // 没改成就回源,别让界面上留着一个假名字
|
||||
}
|
||||
},
|
||||
|
||||
remove: async (id) => {
|
||||
await api.conversations.remove(id)
|
||||
set((s) => {
|
||||
const list = s.list.filter((c) => c.id !== id)
|
||||
const currentId = s.currentId === id ? (list[0]?.id ?? null) : s.currentId
|
||||
if (currentId) localStorage.setItem(LAST_KEY, currentId)
|
||||
else localStorage.removeItem(LAST_KEY)
|
||||
return { list, currentId }
|
||||
})
|
||||
},
|
||||
|
||||
touch: (id, lastQuestion) => {
|
||||
set((s) => {
|
||||
const hit = s.list.find((c) => c.id === id)
|
||||
if (!hit) return s
|
||||
const updated: Conversation = {
|
||||
...hit,
|
||||
last_question: lastQuestion ?? hit.last_question,
|
||||
// 第一句话会成为标题,本地先顶上,省得列表里那条还写着"新对话"
|
||||
title: hit.title === '新对话' && lastQuestion
|
||||
? (lastQuestion.length > 24 ? lastQuestion.slice(0, 24) + '…' : lastQuestion)
|
||||
: hit.title,
|
||||
turn_count: hit.turn_count + (lastQuestion ? 1 : 0),
|
||||
}
|
||||
return { list: [updated, ...s.list.filter((c) => c.id !== id)] }
|
||||
})
|
||||
},
|
||||
}))
|
||||
@@ -86,6 +86,44 @@ export interface CopilotTurn {
|
||||
// 无上限地攒着只会把内存和滚动条都撑坏。
|
||||
const COPILOT_TURN_LIMIT = 10
|
||||
|
||||
/**
|
||||
* 找出(或建出)这张图的 Copilot 会话。
|
||||
*
|
||||
* 画布的对话依附工作流:打开这张图就接着上次聊。之前连说两次"再加一个节点",
|
||||
* 第二次并不知道第一次说了什么——base_graph 带的是图的**结果**,带不出
|
||||
* "你刚才要我干什么",所以模型经常把上一条的意图又做一遍或者做反。
|
||||
*
|
||||
* 不进左侧列表:那边列的是"问题",这里是"改图指令",两种东西混在一个列表里
|
||||
* 只会让两种都更难找。
|
||||
*
|
||||
* 没保存过的草稿(workflow 为空)没有会话——它还没有一个能挂历史的身份。
|
||||
*/
|
||||
async function ensureCanvasConversation(
|
||||
workflowId: string, set: (partial: Partial<StudioState>) => void,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const existing = await api.conversations.list('canvas', workflowId)
|
||||
const id = existing[0]?.id
|
||||
?? (await api.conversations.create({ kind: 'canvas', workflow_id: workflowId })).id
|
||||
set({ copilotConversationId: id })
|
||||
return id
|
||||
} catch {
|
||||
return null // 记不下来也不该挡着人改图
|
||||
}
|
||||
}
|
||||
|
||||
/** 把画布上这一轮记进会话,下一条指令才接得上 */
|
||||
function recordCanvasTurn(
|
||||
conversationId: string | null,
|
||||
instruction: string,
|
||||
patch: { graph?: any; explanation?: string; status?: 'done' | 'error'; error?: string },
|
||||
): void {
|
||||
if (!conversationId) return
|
||||
void api.conversations.startTurn(conversationId, instruction)
|
||||
.then((turn) => api.conversations.patchTurn(conversationId, turn.id, patch))
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
interface StudioState {
|
||||
workflow: Workflow | null
|
||||
nodes: FlowNode[]
|
||||
@@ -105,6 +143,9 @@ interface StudioState {
|
||||
streaming: boolean
|
||||
unsubscribe: (() => void) | null
|
||||
|
||||
/** 这张图的 Copilot 会话 id。一张图一条,用来让连续几条改图指令互相知情 */
|
||||
copilotConversationId: string | null
|
||||
|
||||
copilot: {
|
||||
active: boolean
|
||||
lastOp: string
|
||||
@@ -220,6 +261,7 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
activeEdges: [],
|
||||
streaming: false,
|
||||
unsubscribe: null,
|
||||
copilotConversationId: null,
|
||||
copilot: { active: false, lastOp: '', explanation: '', error: '', model: '',
|
||||
phase: '', thinking: '', elapsedMs: 0, lastInstruction: '', lastUseBase: false },
|
||||
copilotNew: [],
|
||||
@@ -234,7 +276,11 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
run: null, events: [], runtime: {}, activeEdges: [], streaming: false, unsubscribe: null,
|
||||
// 换了一张图,之前那些"我让它改成这样"就不再指向眼前这张图了
|
||||
copilotTurns: [],
|
||||
// 先清空再去解析:留着上一张图的会话 id,这中间的任何一条指令
|
||||
// 都会带着别的图的上下文发出去
|
||||
copilotConversationId: null,
|
||||
})
|
||||
void ensureCanvasConversation(workflow.id, set)
|
||||
void get().validate()
|
||||
},
|
||||
|
||||
@@ -470,6 +516,7 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
instruction,
|
||||
base_graph: useBase && state.nodes.length ? toGraph(state.nodes, state.edges) : null,
|
||||
model: model ?? undefined,
|
||||
conversation_id: state.copilotConversationId,
|
||||
},
|
||||
(op) => {
|
||||
const s = get()
|
||||
@@ -576,6 +623,9 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
thinking: '', elapsedMs: 0, error: '',
|
||||
explanation: op.explanation ?? get().copilot.explanation } })
|
||||
settle({ phase: 'done', explanation: op.explanation ?? get().copilot.explanation })
|
||||
recordCanvasTurn(get().copilotConversationId, instruction, {
|
||||
graph: op.graph, explanation: op.explanation ?? '', status: 'done',
|
||||
})
|
||||
void get().validate()
|
||||
setTimeout(() => set({ copilotNew: [] }), 6000)
|
||||
break
|
||||
@@ -585,6 +635,9 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
set({ copilot: { ...get().copilot, active: false, lastOp: '', phase: '',
|
||||
thinking: '', explanation: '', error: op.message ?? '生成失败' } })
|
||||
settle({ phase: 'error', error: op.message ?? '生成失败' })
|
||||
recordCanvasTurn(get().copilotConversationId, instruction, {
|
||||
status: 'error', error: op.message ?? '生成失败',
|
||||
})
|
||||
break
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user