mirror of
https://github.com/Ed1s0nZ/CyberStrikeAI.git
synced 2026-08-14 07:00:23 +02:00
优化项目对话、刷新续流、实时滚动与工具状态恢复 (#245)
* feat(chat): add project-based conversation sidebar * feat(chat): refine Codex-style conversation UI * feat(chat): add Codex-style conversation workflow * feat(ui): 优化对话框与项目侧边栏交互 * fix(chat): 修复暗色输入框圆角填色 * fix(chat): 恢复输入区分层错位布局 * fix(hitl): isolate reviewer state per conversation * feat(hitl): 增加双入口审批与倒计时进度 * fix(hitl): 汇总项目审批并隔离对话状态 * fix(ui): 修复审批状态与无项目新任务 * fix(ui): 优化审批状态与对话切换性能 * fix(ui): 修复中断任务审批仍计时 * fix(ui): 修复多对话并发切换卡顿 * fix(hitl): 主动同步审批并关闭中断状态 * fix(ui): 固定项目审批汇总为绿色 * feat(ui): 同步系统模型与推理强度 * feat(ui): 完善项目侧栏预览与新建入口 * fix(ui): 防止无项目文件夹误展开 * fix(ui): 防止长历史对话滚动误触审批 * fix(ui): 修复对话操作并补充项目置顶 * fix(ui): 移除对话分组并调整项目置顶排序 * feat(ui): 优化迭代导航与审批交互 * fix(hitl): 将 write_file 加入内置免审批工具 * fix(chat): 支持回车发送与 Shift 回车换行 * fix(chat): 优化对话刷新与 Codex 风格交互 * fix(ui): 显示对话具体更新时间 * fix(ui): 优化对话刷新与项目加载 * fix(ui): 修复 Agent 审查文字裁切 * fix(chat): 修复刷新续流与多标签页同步 * fix(chat): 修复滚动跟随与中断任务终态 * fix(ui): 修复流式滚动跳动与工具状态恢复 * fix(ui): 修复刷新后流式输出停止粘底
This commit is contained in:
@@ -1353,6 +1353,39 @@ func (db *DB) AddProcessDetailWithID(messageID, conversationID, eventType, messa
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// UpdateProcessDetailContent 更新流式聚合详情的正文与元数据。使用固定记录 ID,
|
||||
// 避免每个 token 新增一行,同时让页面刷新能读取到尚未结束的规划输出。
|
||||
func (db *DB) UpdateProcessDetailContent(id, message string, data interface{}) error {
|
||||
var dataJSON string
|
||||
if data != nil {
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("序列化过程详情数据失败: %w", err)
|
||||
}
|
||||
dataJSON = string(jsonData)
|
||||
}
|
||||
result, err := db.Exec(
|
||||
"UPDATE process_details SET message = ?, data = ? WHERE id = ?",
|
||||
message, dataJSON, strings.TrimSpace(id),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新过程详情失败: %w", err)
|
||||
}
|
||||
if affected, affectedErr := result.RowsAffected(); affectedErr == nil && affected == 0 {
|
||||
return fmt.Errorf("过程详情不存在: %s", id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteProcessDetail 删除被判定为工具结果回显的临时规划记录。
|
||||
func (db *DB) DeleteProcessDetail(id string) error {
|
||||
_, err := db.Exec("DELETE FROM process_details WHERE id = ?", strings.TrimSpace(id))
|
||||
if err != nil {
|
||||
return fmt.Errorf("删除过程详情失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetProcessDetails 获取消息的过程详情
|
||||
func (db *DB) GetProcessDetails(messageID string) ([]ProcessDetail, error) {
|
||||
rows, err := db.Query(
|
||||
@@ -1420,6 +1453,10 @@ type ProcessDetailsSummary struct {
|
||||
ToolCount int `json:"toolCount"`
|
||||
ToolExecutions []ProcessDetailsToolExecution `json:"toolExecutions,omitempty"`
|
||||
MCPExecutionIDs []string `json:"mcpExecutionIds,omitempty"`
|
||||
StartedAt *time.Time `json:"startedAt,omitempty"`
|
||||
CompletedAt *time.Time `json:"completedAt,omitempty"`
|
||||
DurationMs int64 `json:"durationMs"`
|
||||
Status string `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
type ProcessDetailsToolExecution struct {
|
||||
@@ -1442,6 +1479,54 @@ func (db *DB) GetProcessDetailsSummary(messageID string) (*ProcessDetailsSummary
|
||||
}
|
||||
|
||||
summary := &ProcessDetailsSummary{Total: total}
|
||||
var messageCreatedAt, messageUpdatedAt sql.NullString
|
||||
var messageContent string
|
||||
if err := db.QueryRow(
|
||||
"SELECT created_at, updated_at, content FROM messages WHERE id = ?",
|
||||
messageID,
|
||||
).Scan(&messageCreatedAt, &messageUpdatedAt, &messageContent); err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, fmt.Errorf("查询过程详情耗时失败: %w", err)
|
||||
}
|
||||
if messageCreatedAt.Valid {
|
||||
if startedAt := parseDBTime(messageCreatedAt.String); !startedAt.IsZero() {
|
||||
summary.StartedAt = &startedAt
|
||||
}
|
||||
}
|
||||
var terminalEvent, terminalCreatedAt string
|
||||
terminalErr := db.QueryRow(`
|
||||
SELECT event_type, created_at
|
||||
FROM process_details
|
||||
WHERE message_id = ? AND event_type IN ('cancelled', 'timeout', 'error')
|
||||
ORDER BY created_at DESC, rowid DESC
|
||||
LIMIT 1`, messageID).Scan(&terminalEvent, &terminalCreatedAt)
|
||||
if terminalErr != nil && !errors.Is(terminalErr, sql.ErrNoRows) {
|
||||
return nil, fmt.Errorf("查询过程详情终态失败: %w", terminalErr)
|
||||
}
|
||||
if terminalEvent != "" {
|
||||
switch terminalEvent {
|
||||
case "cancelled":
|
||||
summary.Status = "cancelled"
|
||||
case "timeout":
|
||||
summary.Status = "timeout"
|
||||
default:
|
||||
summary.Status = "failed"
|
||||
}
|
||||
if completedAt := parseDBTime(terminalCreatedAt); !completedAt.IsZero() {
|
||||
summary.CompletedAt = &completedAt
|
||||
}
|
||||
} else if strings.TrimSpace(messageContent) == "处理中..." || strings.TrimSpace(messageContent) == "Processing..." {
|
||||
summary.Status = "running"
|
||||
} else {
|
||||
summary.Status = "completed"
|
||||
if messageUpdatedAt.Valid {
|
||||
if completedAt := parseDBTime(messageUpdatedAt.String); !completedAt.IsZero() {
|
||||
summary.CompletedAt = &completedAt
|
||||
}
|
||||
}
|
||||
}
|
||||
if summary.StartedAt != nil && summary.CompletedAt != nil && !summary.CompletedAt.Before(*summary.StartedAt) {
|
||||
summary.DurationMs = summary.CompletedAt.Sub(*summary.StartedAt).Milliseconds()
|
||||
}
|
||||
if total == 0 {
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package database
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -105,6 +106,63 @@ func TestProcessDetailsSummaryDoesNotReportPersistedOrphanAsRunning(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessDetailsSummaryIncludesPersistedTurnTiming(t *testing.T) {
|
||||
db, _, messageID := setupProcessDetailsSummaryTest(t)
|
||||
startedAt := "2026-08-10T08:00:00Z"
|
||||
completedAt := "2026-08-10T08:12:59Z"
|
||||
if _, err := db.Exec(
|
||||
"UPDATE messages SET content = ?, created_at = ?, updated_at = ? WHERE id = ?",
|
||||
"done", startedAt, completedAt, messageID,
|
||||
); err != nil {
|
||||
t.Fatalf("update message timing: %v", err)
|
||||
}
|
||||
|
||||
summary, err := db.GetProcessDetailsSummary(messageID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetProcessDetailsSummary: %v", err)
|
||||
}
|
||||
if summary.Status != "completed" {
|
||||
t.Fatalf("status = %q, want completed", summary.Status)
|
||||
}
|
||||
if summary.StartedAt == nil || summary.CompletedAt == nil {
|
||||
t.Fatalf("timing missing: %#v", summary)
|
||||
}
|
||||
if want := int64((12*time.Minute + 59*time.Second) / time.Millisecond); summary.DurationMs != want {
|
||||
t.Fatalf("durationMs = %d, want %d", summary.DurationMs, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessDetailsSummaryTreatsCancelledPlaceholderAsTerminal(t *testing.T) {
|
||||
db, conversationID, messageID := setupProcessDetailsSummaryTest(t)
|
||||
startedAt := "2026-08-10T08:00:00Z"
|
||||
if _, err := db.Exec(
|
||||
"UPDATE messages SET content = ?, created_at = ?, updated_at = ? WHERE id = ?",
|
||||
"处理中...", startedAt, startedAt, messageID,
|
||||
); err != nil {
|
||||
t.Fatalf("update running placeholder: %v", err)
|
||||
}
|
||||
if _, err := db.Exec(`
|
||||
INSERT INTO process_details (id, message_id, conversation_id, event_type, message, data, created_at)
|
||||
VALUES ('cancelled-detail', ?, ?, 'cancelled', 'interrupted', '{}', '2026-08-10T08:02:05Z')`,
|
||||
messageID, conversationID); err != nil {
|
||||
t.Fatalf("insert cancelled detail: %v", err)
|
||||
}
|
||||
|
||||
summary, err := db.GetProcessDetailsSummary(messageID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetProcessDetailsSummary: %v", err)
|
||||
}
|
||||
if summary.Status != "cancelled" {
|
||||
t.Fatalf("status = %q, want cancelled", summary.Status)
|
||||
}
|
||||
if summary.CompletedAt == nil {
|
||||
t.Fatal("cancelled summary should expose a fixed completion time")
|
||||
}
|
||||
if want := int64((2*time.Minute + 5*time.Second) / time.Millisecond); summary.DurationMs != want {
|
||||
t.Fatalf("durationMs = %d, want %d", summary.DurationMs, want)
|
||||
}
|
||||
}
|
||||
|
||||
func setupProcessDetailsSummaryTest(t *testing.T) (*DB, string, string) {
|
||||
t.Helper()
|
||||
db, err := NewDB(filepath.Join(t.TempDir(), "process-details.db"), zap.NewNop())
|
||||
|
||||
+56
-23
@@ -75,8 +75,11 @@ found:
|
||||
|
||||
// responsePlanAgg buffers main-assistant response_stream chunks for one "planning" process_detail row.
|
||||
type responsePlanAgg struct {
|
||||
meta map[string]interface{}
|
||||
b strings.Builder
|
||||
meta map[string]interface{}
|
||||
b strings.Builder
|
||||
detailID string
|
||||
lastPersistAt time.Time
|
||||
lastPersistSize int
|
||||
}
|
||||
|
||||
// thinkingBuf aggregates thinking_stream_* / reasoning_chain_stream_* before flush to process_details.
|
||||
@@ -145,30 +148,36 @@ func responseStreamIterationFromMeta(m map[string]interface{}) int {
|
||||
}
|
||||
}
|
||||
|
||||
func discardPlanningIfEchoesToolResult(respPlan *responsePlanAgg, toolData interface{}) {
|
||||
func discardPlanningIfEchoesToolResult(respPlan *responsePlanAgg, toolData interface{}) string {
|
||||
if respPlan == nil {
|
||||
return
|
||||
return ""
|
||||
}
|
||||
plan := normalizeProcessDetailText(respPlan.b.String())
|
||||
if plan == "" {
|
||||
return
|
||||
return ""
|
||||
}
|
||||
dataMap, ok := toolData.(map[string]interface{})
|
||||
if !ok {
|
||||
return
|
||||
return ""
|
||||
}
|
||||
res, ok := dataMap["result"].(string)
|
||||
if !ok {
|
||||
return
|
||||
return ""
|
||||
}
|
||||
r := normalizeProcessDetailText(res)
|
||||
if r == "" {
|
||||
return
|
||||
return ""
|
||||
}
|
||||
if plan == r || strings.HasSuffix(plan, r) {
|
||||
detailID := respPlan.detailID
|
||||
respPlan.meta = nil
|
||||
respPlan.b.Reset()
|
||||
respPlan.detailID = ""
|
||||
respPlan.lastPersistAt = time.Time{}
|
||||
respPlan.lastPersistSize = 0
|
||||
return detailID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// AgentHandler Agent处理器
|
||||
@@ -976,14 +985,15 @@ func (h *AgentHandler) createProgressCallback(runCtx context.Context, cancelRun
|
||||
syncHitlCognition := func() {
|
||||
h.syncHitlCognitionFromProgress(conversationID, assistantMessageID, thinkingStreams, &respPlan)
|
||||
}
|
||||
flushResponsePlan := func() {
|
||||
persistResponsePlan := func(reset bool) {
|
||||
if assistantMessageID == "" {
|
||||
return
|
||||
}
|
||||
content := strings.TrimSpace(respPlan.b.String())
|
||||
if content == "" {
|
||||
respPlan.meta = nil
|
||||
respPlan.b.Reset()
|
||||
if reset {
|
||||
respPlan = responsePlanAgg{}
|
||||
}
|
||||
return
|
||||
}
|
||||
data := map[string]interface{}{
|
||||
@@ -992,13 +1002,26 @@ func (h *AgentHandler) createProgressCallback(runCtx context.Context, cancelRun
|
||||
for k, v := range respPlan.meta {
|
||||
data[k] = v
|
||||
}
|
||||
if err := h.db.AddProcessDetail(assistantMessageID, conversationID, "planning", content, data); err != nil {
|
||||
var err error
|
||||
if respPlan.detailID == "" {
|
||||
respPlan.detailID, err = h.db.AddProcessDetailWithID(
|
||||
assistantMessageID, conversationID, "planning", content, data,
|
||||
)
|
||||
} else {
|
||||
err = h.db.UpdateProcessDetailContent(respPlan.detailID, content, data)
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Warn("保存过程详情失败", zap.Error(err), zap.String("eventType", "planning"))
|
||||
} else {
|
||||
respPlan.lastPersistAt = time.Now()
|
||||
respPlan.lastPersistSize = respPlan.b.Len()
|
||||
}
|
||||
syncHitlCognition()
|
||||
respPlan.meta = nil
|
||||
respPlan.b.Reset()
|
||||
if reset {
|
||||
respPlan = responsePlanAgg{}
|
||||
}
|
||||
}
|
||||
flushResponsePlan := func() { persistResponsePlan(true) }
|
||||
|
||||
flushThinkingStreams := func() {
|
||||
if assistantMessageID == "" {
|
||||
@@ -1068,15 +1091,15 @@ func (h *AgentHandler) createProgressCallback(runCtx context.Context, cancelRun
|
||||
}
|
||||
|
||||
deferToolProgressSend := eventType == "tool_call" || eventType == "tool_result"
|
||||
// 流式:写 HTTP SSE;非流式(机器人等):镜像到 taskEventBus 供 Web 订阅。
|
||||
// 工具事件需先落库拿 processDetailId,再向前端发送摘要,避免大 payload 默认进入浏览器。
|
||||
// 主 HTTP SSE 与 taskEventBus 必须同时写入:页面刷新会切断原连接,刷新后的
|
||||
// GET task-events 订阅依赖 eventBus 才能继续收到后续迭代。机器人等无主 SSE
|
||||
// 的来源同样只写 eventBus。工具事件需先落库拿 processDetailId,再发送摘要。
|
||||
if !deferToolProgressSend {
|
||||
clientData := enrichProgressEventData(data, conversationID, assistantMessageID)
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc(eventType, message, clientData)
|
||||
} else {
|
||||
h.publishProgressToTaskEventBus(conversationID, eventType, message, clientData)
|
||||
}
|
||||
h.publishProgressToTaskEventBus(conversationID, eventType, message, clientData)
|
||||
}
|
||||
|
||||
// 保存tool_call事件中的参数
|
||||
@@ -1329,6 +1352,14 @@ func (h *AgentHandler) createProgressCallback(runCtx context.Context, cancelRun
|
||||
respPlan.meta[k] = v
|
||||
}
|
||||
}
|
||||
// 运行中的主回复不能只保存在内存:刷新会销毁旧页面,新的 task-events
|
||||
// 订阅只能收到未来增量。按时间或增量大小节流更新同一条 planning 记录,
|
||||
// 这样刷新时能从数据库恢复刷新前已经展示的全部文本。
|
||||
if respPlan.lastPersistAt.IsZero() ||
|
||||
time.Since(respPlan.lastPersistAt) >= 300*time.Millisecond ||
|
||||
respPlan.b.Len()-respPlan.lastPersistSize >= 1024 {
|
||||
persistResponsePlan(false)
|
||||
}
|
||||
syncHitlCognition()
|
||||
return
|
||||
}
|
||||
@@ -1439,7 +1470,11 @@ func (h *AgentHandler) createProgressCallback(runCtx context.Context, cancelRun
|
||||
eventType != "eino_agent_reply_stream_delta" &&
|
||||
eventType != "eino_agent_reply_stream_end" {
|
||||
if eventType == "tool_result" {
|
||||
discardPlanningIfEchoesToolResult(&respPlan, data)
|
||||
if detailID := discardPlanningIfEchoesToolResult(&respPlan, data); detailID != "" {
|
||||
if err := h.db.DeleteProcessDetail(detailID); err != nil {
|
||||
h.logger.Warn("删除工具结果回显规划失败", zap.Error(err), zap.String("processDetailId", detailID))
|
||||
}
|
||||
}
|
||||
}
|
||||
// 在关键过程事件落库前,先把「规划中」与聚合中的 thinking / reasoning_chain 流落库
|
||||
flushResponsePlan()
|
||||
@@ -1455,17 +1490,15 @@ func (h *AgentHandler) createProgressCallback(runCtx context.Context, cancelRun
|
||||
}
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc(eventType, message, clientData)
|
||||
} else {
|
||||
h.publishProgressToTaskEventBus(conversationID, eventType, message, clientData)
|
||||
}
|
||||
h.publishProgressToTaskEventBus(conversationID, eventType, message, clientData)
|
||||
}
|
||||
} else if deferToolProgressSend {
|
||||
clientData := enrichProgressEventData(summarizeProcessDetailData(eventType, data), conversationID, assistantMessageID)
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc(eventType, message, clientData)
|
||||
} else {
|
||||
h.publishProgressToTaskEventBus(conversationID, eventType, message, clientData)
|
||||
}
|
||||
h.publishProgressToTaskEventBus(conversationID, eventType, message, clientData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,10 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/database"
|
||||
@@ -51,6 +53,77 @@ func TestCreateProgressCallback_ConcurrentToolEvents(t *testing.T) {
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// TestCreateProgressCallback_MirrorsWebStreamEvents 页面刷新后 task-events 订阅必须
|
||||
// 继续收到原 Web SSE 任务的后续事件,不能只等数据库最终结果。
|
||||
func TestCreateProgressCallback_MirrorsWebStreamEvents(t *testing.T) {
|
||||
bus := NewTaskEventBus()
|
||||
h := &AgentHandler{logger: zap.NewNop(), config: &config.Config{}, taskEventBus: bus}
|
||||
_, events := bus.Subscribe("conv-refresh-stream")
|
||||
primaryCalls := 0
|
||||
cb := h.createProgressCallback(
|
||||
context.Background(), nil, "conv-refresh-stream", "",
|
||||
func(eventType, message string, data interface{}) { primaryCalls++ },
|
||||
)
|
||||
|
||||
cb("progress", "第 3 轮", map[string]interface{}{"iteration": 3})
|
||||
if primaryCalls != 1 {
|
||||
t.Fatalf("expected primary SSE callback once, got %d", primaryCalls)
|
||||
}
|
||||
select {
|
||||
case payload := <-events:
|
||||
body := string(payload)
|
||||
if !strings.Contains(body, `"type":"progress"`) || !strings.Contains(body, `"conversationId":"conv-refresh-stream"`) {
|
||||
t.Fatalf("unexpected mirrored event: %s", body)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("expected progress event mirrored to task event bus")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateProgressCallback_PersistsRunningResponseBeforeDone(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
db, err := database.NewDB(filepath.Join(tmp, "test.sqlite"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatalf("NewDB: %v", err)
|
||||
}
|
||||
conv, err := db.CreateConversation("refresh-running", database.ConversationCreateMeta{})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateConversation: %v", err)
|
||||
}
|
||||
asst, err := db.AddMessage(conv.ID, "assistant", "处理中...", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("AddMessage: %v", err)
|
||||
}
|
||||
|
||||
h := &AgentHandler{logger: zap.NewNop(), db: db}
|
||||
cb := h.createProgressCallback(context.Background(), nil, conv.ID, asst.ID, nil)
|
||||
meta := map[string]interface{}{
|
||||
"streamId": "response-refresh-1",
|
||||
"einoAgent": "cyberstrike-eino-single",
|
||||
"orchestration": "eino_single",
|
||||
}
|
||||
cb("response_start", "", meta)
|
||||
cb("response_delta", "刷新前已生成的第一部分", openai.WithSSEAccumulated(meta, "刷新前已生成的第一部分"))
|
||||
|
||||
details, err := db.GetProcessDetails(asst.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetProcessDetails: %v", err)
|
||||
}
|
||||
if len(details) != 1 || details[0].EventType != "planning" || details[0].Message != "刷新前已生成的第一部分" {
|
||||
t.Fatalf("expected one running planning snapshot, got %+v", details)
|
||||
}
|
||||
|
||||
longer := "刷新前已生成的第一部分" + strings.Repeat("继续迭代", 300)
|
||||
cb("response_delta", "继续迭代", openai.WithSSEAccumulated(meta, longer))
|
||||
details, err = db.GetProcessDetails(asst.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetProcessDetails after update: %v", err)
|
||||
}
|
||||
if len(details) != 1 || details[0].Message != longer {
|
||||
t.Fatalf("running snapshot should update in-place, rows=%d len=%d", len(details), len(details[0].Message))
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateProgressCallback_FlushesReasoningOnDone 流式推理聚合须在 done/response 时落库,刷新后可回放。
|
||||
func TestCreateProgressCallback_FlushesReasoningOnDone(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
|
||||
+280
-57
@@ -74,6 +74,7 @@ CREATE TABLE IF NOT EXISTS hitl_interrupts (
|
||||
tool_call_id TEXT,
|
||||
payload TEXT,
|
||||
status TEXT NOT NULL,
|
||||
reviewer TEXT NOT NULL DEFAULT 'human',
|
||||
decision TEXT,
|
||||
decision_comment TEXT,
|
||||
created_at DATETIME NOT NULL,
|
||||
@@ -98,15 +99,179 @@ CREATE TABLE IF NOT EXISTS hitl_conversation_configs (
|
||||
// On startup, cancel all orphaned pending interrupts from previous process.
|
||||
// Their in-memory channels are gone, so they can never be resolved.
|
||||
res, err := m.db.Exec(`UPDATE hitl_interrupts SET status='cancelled', decision='reject',
|
||||
decision_comment='process restarted', decided_at=CURRENT_TIMESTAMP WHERE status='pending'`)
|
||||
decision_comment='process restarted', decided_at=CURRENT_TIMESTAMP, decided_by='system'
|
||||
WHERE status='pending'`)
|
||||
if err != nil {
|
||||
m.logger.Warn("failed to cancel orphaned HITL interrupts", zap.Error(err))
|
||||
} else if n, _ := res.RowsAffected(); n > 0 {
|
||||
m.logger.Info("cancelled orphaned HITL interrupts from previous process", zap.Int64("count", n))
|
||||
}
|
||||
if err := m.reconcileRestartInterruptedMessages(); err != nil {
|
||||
m.logger.Warn("failed to finalize assistant messages interrupted by process restart", zap.Error(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reconcileRestartInterruptedMessages completes durable terminal state for
|
||||
// historical assistant placeholders that have explicit evidence of being over:
|
||||
// a terminal HITL/process event, or a later message in the same conversation.
|
||||
// The evidence requirement avoids rewriting a placeholder that could still be
|
||||
// recoverable by another runtime.
|
||||
func (m *HITLManager) reconcileRestartInterruptedMessages() error {
|
||||
rows, err := m.db.Query(`
|
||||
SELECT msg.id, msg.conversation_id,
|
||||
COALESCE((
|
||||
SELECT pd.event_type
|
||||
FROM process_details pd
|
||||
WHERE pd.message_id = msg.id
|
||||
AND pd.event_type IN ('cancelled', 'timeout', 'error')
|
||||
ORDER BY pd.created_at DESC LIMIT 1
|
||||
), '') AS terminal_event,
|
||||
COALESCE((
|
||||
SELECT hi.status
|
||||
FROM hitl_interrupts hi
|
||||
WHERE hi.message_id = msg.id
|
||||
ORDER BY COALESCE(hi.decided_at, hi.created_at) DESC LIMIT 1
|
||||
), '') AS hitl_status,
|
||||
COALESCE((
|
||||
SELECT hi.decision
|
||||
FROM hitl_interrupts hi
|
||||
WHERE hi.message_id = msg.id
|
||||
ORDER BY COALESCE(hi.decided_at, hi.created_at) DESC LIMIT 1
|
||||
), '') AS hitl_decision,
|
||||
COALESCE((
|
||||
SELECT hi.decision_comment
|
||||
FROM hitl_interrupts hi
|
||||
WHERE hi.message_id = msg.id
|
||||
ORDER BY COALESCE(hi.decided_at, hi.created_at) DESC LIMIT 1
|
||||
), '') AS decision_comment,
|
||||
COALESCE((
|
||||
SELECT MAX(COALESCE(hi.decided_at, hi.created_at))
|
||||
FROM hitl_interrupts hi
|
||||
WHERE hi.message_id = msg.id
|
||||
), (
|
||||
SELECT MIN(later.created_at)
|
||||
FROM messages later
|
||||
WHERE later.conversation_id = msg.conversation_id
|
||||
AND later.created_at > msg.created_at
|
||||
), (
|
||||
SELECT MAX(pd.created_at)
|
||||
FROM process_details pd
|
||||
WHERE pd.message_id = msg.id
|
||||
), msg.updated_at, msg.created_at) AS interrupted_at
|
||||
FROM messages msg
|
||||
WHERE msg.role = 'assistant'
|
||||
AND TRIM(msg.content) IN ('处理中...', 'Processing...')
|
||||
AND (
|
||||
EXISTS (
|
||||
SELECT 1 FROM hitl_interrupts hi
|
||||
WHERE hi.message_id = msg.id
|
||||
AND (hi.status IN ('cancelled', 'timeout')
|
||||
OR (hi.status = 'decided' AND hi.decision = 'reject'))
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM process_details pd
|
||||
WHERE pd.message_id = msg.id
|
||||
AND pd.event_type IN ('cancelled', 'timeout', 'error')
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM messages later
|
||||
WHERE later.conversation_id = msg.conversation_id
|
||||
AND later.created_at > msg.created_at
|
||||
)
|
||||
)`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type interruptedMessage struct {
|
||||
messageID string
|
||||
conversationID string
|
||||
terminalEvent string
|
||||
hitlStatus string
|
||||
hitlDecision string
|
||||
decisionComment string
|
||||
interruptedAt string
|
||||
}
|
||||
var interrupted []interruptedMessage
|
||||
for rows.Next() {
|
||||
var item interruptedMessage
|
||||
if err := rows.Scan(&item.messageID, &item.conversationID, &item.terminalEvent,
|
||||
&item.hitlStatus, &item.hitlDecision, &item.decisionComment, &item.interruptedAt); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
interrupted = append(interrupted, item)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(interrupted) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
tx, err := m.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
for _, item := range interrupted {
|
||||
eventType := strings.ToLower(strings.TrimSpace(item.terminalEvent))
|
||||
decision := strings.ToLower(strings.TrimSpace(item.hitlDecision))
|
||||
comment := strings.ToLower(strings.TrimSpace(item.decisionComment))
|
||||
if eventType == "" {
|
||||
if strings.EqualFold(strings.TrimSpace(item.hitlStatus), "timeout") || strings.Contains(comment, "timeout") {
|
||||
eventType = "timeout"
|
||||
} else {
|
||||
eventType = "cancelled"
|
||||
}
|
||||
}
|
||||
|
||||
notice := "任务因服务重启已中断。"
|
||||
reason := "process_restarted"
|
||||
switch eventType {
|
||||
case "timeout":
|
||||
notice = "任务等待审批超时,已自动拒绝。"
|
||||
reason = "hitl_timeout"
|
||||
case "error":
|
||||
notice = "任务执行失败,已停止。"
|
||||
reason = "execution_error"
|
||||
case "cancelled":
|
||||
if decision == "reject" && comment != "process restarted" {
|
||||
notice = "任务审批已拒绝,执行已停止。"
|
||||
reason = "hitl_rejected"
|
||||
} else if comment == "process restarted" {
|
||||
notice = "任务因服务重启已中断,审批已取消。"
|
||||
}
|
||||
default:
|
||||
eventType = "cancelled"
|
||||
}
|
||||
detailData, _ := json.Marshal(map[string]string{"reason": reason, "status": eventType})
|
||||
result, err := tx.Exec(`
|
||||
UPDATE messages
|
||||
SET content = ?, updated_at = ?
|
||||
WHERE id = ? AND TRIM(content) IN ('处理中...', 'Processing...')`,
|
||||
notice, item.interruptedAt, item.messageID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
updated, _ := result.RowsAffected()
|
||||
if updated == 0 {
|
||||
continue
|
||||
}
|
||||
if _, err := tx.Exec(`
|
||||
INSERT INTO process_details (id, message_id, conversation_id, event_type, message, data, created_at)
|
||||
SELECT ?, ?, ?, ?, ?, ?, ?
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM process_details
|
||||
WHERE message_id = ? AND event_type IN ('cancelled', 'timeout', 'error')
|
||||
)`, uuid.NewString(), item.messageID, item.conversationID, eventType, notice, string(detailData),
|
||||
item.interruptedAt, item.messageID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func normalizeHitlMode(mode string) string {
|
||||
v := strings.ToLower(strings.TrimSpace(mode))
|
||||
if v == "" {
|
||||
@@ -234,13 +399,14 @@ func (m *HITLManager) NeedsToolApproval(conversationID, toolName string) bool {
|
||||
return need
|
||||
}
|
||||
|
||||
func (m *HITLManager) CreatePendingInterrupt(conversationID, assistantMessageID, mode, toolName, toolCallID, payload string) (*pendingInterrupt, error) {
|
||||
func (m *HITLManager) CreatePendingInterrupt(conversationID, assistantMessageID, mode, toolName, toolCallID, payload, reviewer string) (*pendingInterrupt, error) {
|
||||
now := time.Now()
|
||||
id := "hitl_" + strings.ReplaceAll(uuid.New().String(), "-", "")
|
||||
reviewer = normalizeHitlReviewer(reviewer)
|
||||
if _, err := m.db.Exec(`INSERT INTO hitl_interrupts
|
||||
(id, conversation_id, message_id, mode, tool_name, tool_call_id, payload, status, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)`,
|
||||
id, conversationID, assistantMessageID, mode, toolName, toolCallID, payload, now); err != nil {
|
||||
(id, conversation_id, message_id, mode, tool_name, tool_call_id, payload, status, reviewer, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,
|
||||
id, conversationID, assistantMessageID, mode, toolName, toolCallID, payload, reviewer, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 刷新页面后侧栏依赖 DB 配置;若仅内存 Activate 未落库,会导致「有待审批却显示关闭」
|
||||
@@ -253,9 +419,12 @@ func (m *HITLManager) CreatePendingInterrupt(conversationID, assistantMessageID,
|
||||
ToolCallID: toolCallID,
|
||||
decideCh: make(chan hitlDecision, 1),
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.pending[id] = p
|
||||
m.mu.Unlock()
|
||||
// Agent 审查不会等待人工决策,也不应进入人工审批的内存待办队列。
|
||||
if reviewer != "audit_agent" {
|
||||
m.mu.Lock()
|
||||
m.pending[id] = p
|
||||
m.mu.Unlock()
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
@@ -471,66 +640,107 @@ func (h *AgentHandler) waitHITLApproval(runCtx context.Context, cancelRun contex
|
||||
return nil, nil
|
||||
}
|
||||
h.enrichHitlApprovalPayload(conversationID, assistantMessageID, payload)
|
||||
approvalStartedAt := time.Now().UTC()
|
||||
timeoutSeconds := int(cfg.Timeout / time.Second)
|
||||
var approvalExpiresAt *time.Time
|
||||
if timeoutSeconds > 0 {
|
||||
expiresAt := approvalStartedAt.Add(cfg.Timeout)
|
||||
approvalExpiresAt = &expiresAt
|
||||
}
|
||||
payload["hitlApproval"] = map[string]interface{}{
|
||||
"createdAt": approvalStartedAt,
|
||||
"timeoutSeconds": timeoutSeconds,
|
||||
"expiresAt": approvalExpiresAt,
|
||||
}
|
||||
payloadRaw, _ := json.Marshal(payload)
|
||||
p, err := h.hitlManager.CreatePendingInterrupt(conversationID, assistantMessageID, cfg.Mode, toolName, toolCallID, string(payloadRaw))
|
||||
p, err := h.hitlManager.CreatePendingInterrupt(conversationID, assistantMessageID, cfg.Mode, toolName, toolCallID, string(payloadRaw), cfg.Reviewer)
|
||||
if err != nil {
|
||||
h.logger.Warn("创建 HITL 中断失败", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
emitHITL := func(eventType, message string, eventData map[string]interface{}) {
|
||||
clientData := enrichProgressEventData(eventData, conversationID, assistantMessageID)
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc(eventType, message, clientData)
|
||||
}
|
||||
if strings.TrimSpace(assistantMessageID) != "" && h.db != nil {
|
||||
if err := h.db.AddProcessDetail(assistantMessageID, conversationID, eventType, message, clientData); err != nil {
|
||||
h.logger.Warn("保存 HITL 过程详情失败", zap.Error(err), zap.String("eventType", eventType))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Reviewer == "audit_agent" {
|
||||
emitHITL("hitl_audit_agent_started", "审计 Agent 正在审查此请求", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"toolCallId": toolCallID,
|
||||
"mode": cfg.Mode,
|
||||
"reviewer": "audit_agent",
|
||||
"status": "audit_running",
|
||||
"payload": payload,
|
||||
})
|
||||
ad := h.auditAgentReview(runCtx, cfg.Mode, toolName, payload)
|
||||
now := time.Now()
|
||||
_, _ = h.db.Exec(`UPDATE hitl_interrupts SET status='decided', decision=?, decision_comment=?, decided_at=?, decided_by='audit_agent' WHERE id=?`,
|
||||
ad.Decision, ad.Comment, now, p.InterruptID)
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc("hitl_audit_agent", "审计 Agent 已裁决", map[string]interface{}{
|
||||
emitHITL("hitl_audit_agent", "审计 Agent 已裁决", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"toolCallId": toolCallID,
|
||||
"mode": cfg.Mode,
|
||||
"status": "decided",
|
||||
"decision": ad.Decision,
|
||||
"comment": ad.Comment,
|
||||
"editedArgs": ad.EditedArguments,
|
||||
"decidedBy": "audit_agent",
|
||||
"reviewer": "audit_agent",
|
||||
})
|
||||
if ad.Decision == "reject" {
|
||||
emitHITL("hitl_rejected", "审计 Agent 拒绝本次工具调用", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"toolCallId": toolCallID,
|
||||
"mode": cfg.Mode,
|
||||
"decision": ad.Decision,
|
||||
"decision": "reject",
|
||||
"comment": ad.Comment,
|
||||
"editedArgs": ad.EditedArguments,
|
||||
"decidedBy": "audit_agent",
|
||||
"reviewer": "audit_agent",
|
||||
})
|
||||
}
|
||||
if ad.Decision == "reject" {
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc("hitl_rejected", "审计 Agent 拒绝本次工具调用", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"comment": ad.Comment,
|
||||
"decidedBy": "audit_agent",
|
||||
})
|
||||
}
|
||||
return &ad, nil
|
||||
}
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc("hitl_resumed", "审计 Agent 已通过,继续执行", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"comment": ad.Comment,
|
||||
"editedArgs": ad.EditedArguments,
|
||||
"decidedBy": "audit_agent",
|
||||
})
|
||||
}
|
||||
emitHITL("hitl_resumed", "审计 Agent 已通过,继续执行", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"toolCallId": toolCallID,
|
||||
"mode": cfg.Mode,
|
||||
"decision": "approve",
|
||||
"comment": ad.Comment,
|
||||
"editedArgs": ad.EditedArguments,
|
||||
"decidedBy": "audit_agent",
|
||||
"reviewer": "audit_agent",
|
||||
})
|
||||
h.hitlManager.TrackApprovedHitlExecution(p.InterruptID, conversationID, toolName, toolCallID)
|
||||
return &ad, nil
|
||||
}
|
||||
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc("hitl_interrupt", "命中人机协同审批", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"mode": cfg.Mode,
|
||||
"toolName": toolName,
|
||||
"toolCallId": toolCallID,
|
||||
"payload": payload,
|
||||
})
|
||||
}
|
||||
emitHITL("hitl_interrupt", "命中人机协同审批", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"mode": cfg.Mode,
|
||||
"toolName": toolName,
|
||||
"toolCallId": toolCallID,
|
||||
"reviewer": "human",
|
||||
"status": "pending",
|
||||
"createdAt": approvalStartedAt,
|
||||
"timeoutSeconds": timeoutSeconds,
|
||||
"expiresAt": approvalExpiresAt,
|
||||
"payload": payload,
|
||||
})
|
||||
d, waitErr := h.hitlManager.waitDecision(runCtx, p, cfg.Timeout)
|
||||
if waitErr != nil {
|
||||
if cancelRun != nil && (errors.Is(waitErr, context.Canceled) || errors.Is(waitErr, context.DeadlineExceeded)) {
|
||||
@@ -550,28 +760,41 @@ func (h *AgentHandler) waitHITLApproval(runCtx context.Context, cancelRun contex
|
||||
}
|
||||
if d.Decision == "reject" {
|
||||
rejectMsg := "人工拒绝本次工具调用,模型将基于反馈继续迭代"
|
||||
if strings.Contains(strings.ToLower(strings.TrimSpace(d.Comment)), "timeout") {
|
||||
timedOut := strings.Contains(strings.ToLower(strings.TrimSpace(d.Comment)), "timeout")
|
||||
if timedOut {
|
||||
rejectMsg = "审批超时,安全起见已自动拒绝,模型将基于反馈继续迭代"
|
||||
}
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc("hitl_rejected", rejectMsg, map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"comment": d.Comment,
|
||||
})
|
||||
status := "decided"
|
||||
decidedBy := "human"
|
||||
if timedOut {
|
||||
status = "timeout"
|
||||
decidedBy = "system"
|
||||
}
|
||||
return &d, nil
|
||||
}
|
||||
if sendEventFunc != nil {
|
||||
sendEventFunc("hitl_resumed", "人工确认通过,继续执行", map[string]interface{}{
|
||||
emitHITL("hitl_rejected", rejectMsg, map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"toolCallId": toolCallID,
|
||||
"mode": cfg.Mode,
|
||||
"status": status,
|
||||
"decision": "reject",
|
||||
"comment": d.Comment,
|
||||
"editedArgs": d.EditedArguments,
|
||||
"decidedBy": decidedBy,
|
||||
"reviewer": "human",
|
||||
})
|
||||
return &d, nil
|
||||
}
|
||||
emitHITL("hitl_resumed", "人工确认通过,继续执行", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
"interruptId": p.InterruptID,
|
||||
"toolName": toolName,
|
||||
"toolCallId": toolCallID,
|
||||
"mode": cfg.Mode,
|
||||
"decision": "approve",
|
||||
"comment": d.Comment,
|
||||
"editedArgs": d.EditedArguments,
|
||||
"reviewer": "human",
|
||||
})
|
||||
h.hitlManager.TrackApprovedHitlExecution(p.InterruptID, conversationID, toolName, toolCallID)
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
@@ -39,11 +39,14 @@ func normalizeHitlDecidedBy(v string) string {
|
||||
|
||||
func (m *HITLManager) migrateHitlSchemaColumns() {
|
||||
_, _ = m.db.Exec(`ALTER TABLE hitl_interrupts ADD COLUMN decided_by TEXT NOT NULL DEFAULT 'human'`)
|
||||
_, _ = m.db.Exec(`ALTER TABLE hitl_interrupts ADD COLUMN reviewer TEXT NOT NULL DEFAULT 'human'`)
|
||||
_, _ = m.db.Exec(`UPDATE hitl_interrupts SET reviewer='audit_agent'
|
||||
WHERE COALESCE(decided_by, '') IN ('audit_agent', 'agent', 'ai')`)
|
||||
_, _ = m.db.Exec(`ALTER TABLE hitl_conversation_configs ADD COLUMN reviewer TEXT NOT NULL DEFAULT 'human'`)
|
||||
}
|
||||
|
||||
func hitlInterruptRowToMap(
|
||||
id, cid, mode, toolName, toolCallID, payload, rowStatus, decidedBy string,
|
||||
id, cid, mode, toolName, toolCallID, payload, rowStatus, reviewer, decidedBy string,
|
||||
messageID sql.NullString,
|
||||
decision, comment sql.NullString,
|
||||
createdAt time.Time,
|
||||
@@ -62,6 +65,7 @@ func hitlInterruptRowToMap(
|
||||
"toolCallId": toolCallID,
|
||||
"payload": payload,
|
||||
"status": rowStatus,
|
||||
"reviewer": reviewer,
|
||||
"decision": decision.String,
|
||||
"comment": comment.String,
|
||||
"decidedBy": decidedBy,
|
||||
@@ -77,7 +81,7 @@ func hitlInterruptRowToMap(
|
||||
|
||||
func (h *AgentHandler) buildHitlListQuery(logs bool) (string, []interface{}) {
|
||||
where, args := h.buildHitlLogsWhere(logs)
|
||||
q := `SELECT id, conversation_id, message_id, mode, tool_name, tool_call_id, payload, status, decision, decision_comment, COALESCE(decided_by,'human'), created_at, decided_at FROM hitl_interrupts` + where
|
||||
q := `SELECT id, conversation_id, message_id, mode, tool_name, tool_call_id, payload, status, COALESCE(reviewer,'human'), decision, decision_comment, COALESCE(decided_by,'human'), created_at, decided_at FROM hitl_interrupts` + where
|
||||
return q, args
|
||||
}
|
||||
|
||||
@@ -87,7 +91,9 @@ func (h *AgentHandler) buildHitlLogsWhere(logs bool) (string, []interface{}) {
|
||||
if logs {
|
||||
q += " AND status != 'pending'"
|
||||
} else {
|
||||
q += " AND status = 'pending'"
|
||||
// 该接口只返回真正等待用户操作的人工审批。Agent 审查即使正在运行,
|
||||
// 也不应触发弹窗、倒计时或项目待审批计数。
|
||||
q += " AND status = 'pending' AND COALESCE(reviewer,'human') = 'human'"
|
||||
}
|
||||
return q, args
|
||||
}
|
||||
@@ -131,15 +137,15 @@ func (h *AgentHandler) appendHitlListFilters(q string, args []interface{}, c *gi
|
||||
func (h *AgentHandler) scanHitlInterruptRows(rows *sql.Rows) ([]map[string]interface{}, error) {
|
||||
items := make([]map[string]interface{}, 0)
|
||||
for rows.Next() {
|
||||
var id, cid, mode, toolName, toolCallID, payload, rowStatus, decidedBy string
|
||||
var id, cid, mode, toolName, toolCallID, payload, rowStatus, reviewer, decidedBy string
|
||||
var messageID sql.NullString
|
||||
var decision, comment sql.NullString
|
||||
var createdAt time.Time
|
||||
var decidedAt sql.NullTime
|
||||
if err := rows.Scan(&id, &cid, &messageID, &mode, &toolName, &toolCallID, &payload, &rowStatus, &decision, &comment, &decidedBy, &createdAt, &decidedAt); err != nil {
|
||||
if err := rows.Scan(&id, &cid, &messageID, &mode, &toolName, &toolCallID, &payload, &rowStatus, &reviewer, &decision, &comment, &decidedBy, &createdAt, &decidedAt); err != nil {
|
||||
continue
|
||||
}
|
||||
items = append(items, hitlInterruptRowToMap(id, cid, mode, toolName, toolCallID, payload, rowStatus, decidedBy, messageID, decision, comment, createdAt, decidedAt))
|
||||
items = append(items, hitlInterruptRowToMap(id, cid, mode, toolName, toolCallID, payload, rowStatus, reviewer, decidedBy, messageID, decision, comment, createdAt, decidedAt))
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -252,13 +258,13 @@ func (h *AgentHandler) GetHITLLog(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
|
||||
return
|
||||
}
|
||||
q := `SELECT id, conversation_id, message_id, mode, tool_name, tool_call_id, payload, status, decision, decision_comment, COALESCE(decided_by,'human'), created_at, decided_at FROM hitl_interrupts WHERE id = ?`
|
||||
var rowID, cid, mode, toolName, toolCallID, payload, rowStatus, decidedBy string
|
||||
q := `SELECT id, conversation_id, message_id, mode, tool_name, tool_call_id, payload, status, COALESCE(reviewer,'human'), decision, decision_comment, COALESCE(decided_by,'human'), created_at, decided_at FROM hitl_interrupts WHERE id = ?`
|
||||
var rowID, cid, mode, toolName, toolCallID, payload, rowStatus, reviewer, decidedBy string
|
||||
var messageID sql.NullString
|
||||
var decision, comment sql.NullString
|
||||
var createdAt time.Time
|
||||
var decidedAt sql.NullTime
|
||||
err := h.db.QueryRow(q, id).Scan(&rowID, &cid, &messageID, &mode, &toolName, &toolCallID, &payload, &rowStatus, &decision, &comment, &decidedBy, &createdAt, &decidedAt)
|
||||
err := h.db.QueryRow(q, id).Scan(&rowID, &cid, &messageID, &mode, &toolName, &toolCallID, &payload, &rowStatus, &reviewer, &decision, &comment, &decidedBy, &createdAt, &decidedAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
@@ -271,7 +277,7 @@ func (h *AgentHandler) GetHITLLog(c *gin.Context) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "无权访问该资源"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, hitlInterruptRowToMap(rowID, cid, mode, toolName, toolCallID, payload, rowStatus, decidedBy, messageID, decision, comment, createdAt, decidedAt))
|
||||
c.JSON(http.StatusOK, hitlInterruptRowToMap(rowID, cid, mode, toolName, toolCallID, payload, rowStatus, reviewer, decidedBy, messageID, decision, comment, createdAt, decidedAt))
|
||||
}
|
||||
|
||||
func (h *AgentHandler) filterAllowedHitlInterruptIDs(c *gin.Context, ids []string) ([]string, error) {
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/database"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestEnsureSchemaCancelsPendingInterruptsAfterRestart(t *testing.T) {
|
||||
db, err := database.NewDB(filepath.Join(t.TempDir(), "hitl-restart.db"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
manager := NewHITLManager(db, zap.NewNop())
|
||||
if err := manager.EnsureSchema(); err != nil {
|
||||
t.Fatalf("ensure schema: %v", err)
|
||||
}
|
||||
conversation, err := db.CreateConversation("restart interrupted", database.ConversationCreateMeta{})
|
||||
if err != nil {
|
||||
t.Fatalf("create conversation: %v", err)
|
||||
}
|
||||
message, err := db.AddMessage(conversation.ID, "assistant", "处理中...", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create assistant placeholder: %v", err)
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO hitl_interrupts
|
||||
(id, conversation_id, message_id, mode, tool_name, tool_call_id, payload, status, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', CURRENT_TIMESTAMP)`,
|
||||
"restart-pending", conversation.ID, message.ID, "approval", "browser", "tool-call-1", `{}`); err != nil {
|
||||
t.Fatalf("insert pending interrupt: %v", err)
|
||||
}
|
||||
|
||||
if err := manager.EnsureSchema(); err != nil {
|
||||
t.Fatalf("reconcile restart: %v", err)
|
||||
}
|
||||
|
||||
var status, decision, comment, decidedBy string
|
||||
var decidedAt sql.NullTime
|
||||
if err := db.QueryRow(`SELECT status, decision, decision_comment, decided_by, decided_at
|
||||
FROM hitl_interrupts WHERE id = ?`, "restart-pending").
|
||||
Scan(&status, &decision, &comment, &decidedBy, &decidedAt); err != nil {
|
||||
t.Fatalf("query reconciled interrupt: %v", err)
|
||||
}
|
||||
if status != "cancelled" || decision != "reject" || comment != "process restarted" {
|
||||
t.Fatalf("unexpected restart decision: status=%q decision=%q comment=%q", status, decision, comment)
|
||||
}
|
||||
if decidedBy != "system" {
|
||||
t.Fatalf("decided_by=%q, want system", decidedBy)
|
||||
}
|
||||
if !decidedAt.Valid {
|
||||
t.Fatal("decided_at should be set after restart reconciliation")
|
||||
}
|
||||
|
||||
var content string
|
||||
var updatedAt sql.NullTime
|
||||
if err := db.QueryRow(`SELECT content, updated_at FROM messages WHERE id = ?`, message.ID).
|
||||
Scan(&content, &updatedAt); err != nil {
|
||||
t.Fatalf("query reconciled assistant message: %v", err)
|
||||
}
|
||||
if content != "任务因服务重启已中断,审批已取消。" {
|
||||
t.Fatalf("assistant content=%q, want restart interruption notice", content)
|
||||
}
|
||||
if !updatedAt.Valid {
|
||||
t.Fatal("assistant updated_at should be set to the interruption time")
|
||||
}
|
||||
var eventType, eventMessage string
|
||||
if err := db.QueryRow(`SELECT event_type, message FROM process_details WHERE message_id = ?`, message.ID).
|
||||
Scan(&eventType, &eventMessage); err != nil {
|
||||
t.Fatalf("query restart cancellation process detail: %v", err)
|
||||
}
|
||||
if eventType != "cancelled" || eventMessage != content {
|
||||
t.Fatalf("unexpected terminal detail: type=%q message=%q", eventType, eventMessage)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureSchemaFinalizesOnlyHistoricalPlaceholdersWithTerminalEvidence(t *testing.T) {
|
||||
db, err := database.NewDB(filepath.Join(t.TempDir(), "hitl-history.db"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
manager := NewHITLManager(db, zap.NewNop())
|
||||
if err := manager.EnsureSchema(); err != nil {
|
||||
t.Fatalf("ensure schema: %v", err)
|
||||
}
|
||||
|
||||
supersededConversation, err := db.CreateConversation("superseded placeholder", database.ConversationCreateMeta{})
|
||||
if err != nil {
|
||||
t.Fatalf("create superseded conversation: %v", err)
|
||||
}
|
||||
superseded, err := db.AddMessage(supersededConversation.ID, "assistant", "处理中...", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create superseded placeholder: %v", err)
|
||||
}
|
||||
if _, err := db.AddMessage(supersededConversation.ID, "user", "继续", nil); err != nil {
|
||||
t.Fatalf("create later message: %v", err)
|
||||
}
|
||||
|
||||
timeoutConversation, err := db.CreateConversation("timeout placeholder", database.ConversationCreateMeta{})
|
||||
if err != nil {
|
||||
t.Fatalf("create timeout conversation: %v", err)
|
||||
}
|
||||
timedOut, err := db.AddMessage(timeoutConversation.ID, "assistant", "处理中...", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create timeout placeholder: %v", err)
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO hitl_interrupts
|
||||
(id, conversation_id, message_id, mode, tool_name, status, decision, decision_comment, created_at, decided_at)
|
||||
VALUES (?, ?, ?, 'approval', 'browser', 'timeout', 'reject', 'HITL timeout auto-reject for safety', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`,
|
||||
"timeout-interrupt", timeoutConversation.ID, timedOut.ID); err != nil {
|
||||
t.Fatalf("insert timeout interrupt: %v", err)
|
||||
}
|
||||
|
||||
rejectedConversation, err := db.CreateConversation("rejected placeholder", database.ConversationCreateMeta{})
|
||||
if err != nil {
|
||||
t.Fatalf("create rejected conversation: %v", err)
|
||||
}
|
||||
rejected, err := db.AddMessage(rejectedConversation.ID, "assistant", "处理中...", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create rejected placeholder: %v", err)
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO hitl_interrupts
|
||||
(id, conversation_id, message_id, mode, tool_name, status, decision, decision_comment, created_at, decided_at)
|
||||
VALUES (?, ?, ?, 'approval', 'exec', 'decided', 'reject', 'user rejected', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`,
|
||||
"rejected-interrupt", rejectedConversation.ID, rejected.ID); err != nil {
|
||||
t.Fatalf("insert rejected interrupt: %v", err)
|
||||
}
|
||||
|
||||
activeConversation, err := db.CreateConversation("potentially active placeholder", database.ConversationCreateMeta{})
|
||||
if err != nil {
|
||||
t.Fatalf("create active conversation: %v", err)
|
||||
}
|
||||
potentiallyActive, err := db.AddMessage(activeConversation.ID, "assistant", "处理中...", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create potentially active placeholder: %v", err)
|
||||
}
|
||||
|
||||
if err := manager.EnsureSchema(); err != nil {
|
||||
t.Fatalf("reconcile historical placeholders: %v", err)
|
||||
}
|
||||
|
||||
assertTerminal := func(messageID, wantContent, wantEvent string) {
|
||||
t.Helper()
|
||||
var content, eventType string
|
||||
if err := db.QueryRow(`SELECT content FROM messages WHERE id = ?`, messageID).Scan(&content); err != nil {
|
||||
t.Fatalf("query message %s: %v", messageID, err)
|
||||
}
|
||||
if content != wantContent {
|
||||
t.Fatalf("message %s content=%q, want %q", messageID, content, wantContent)
|
||||
}
|
||||
if err := db.QueryRow(`SELECT event_type FROM process_details WHERE message_id = ?
|
||||
AND event_type IN ('cancelled', 'timeout', 'error')`, messageID).Scan(&eventType); err != nil {
|
||||
t.Fatalf("query terminal detail %s: %v", messageID, err)
|
||||
}
|
||||
if eventType != wantEvent {
|
||||
t.Fatalf("message %s event=%q, want %q", messageID, eventType, wantEvent)
|
||||
}
|
||||
}
|
||||
assertTerminal(superseded.ID, "任务因服务重启已中断。", "cancelled")
|
||||
assertTerminal(timedOut.ID, "任务等待审批超时,已自动拒绝。", "timeout")
|
||||
assertTerminal(rejected.ID, "任务审批已拒绝,执行已停止。", "cancelled")
|
||||
|
||||
var activeContent string
|
||||
if err := db.QueryRow(`SELECT content FROM messages WHERE id = ?`, potentiallyActive.ID).Scan(&activeContent); err != nil {
|
||||
t.Fatalf("query potentially active message: %v", err)
|
||||
}
|
||||
if activeContent != "处理中..." {
|
||||
t.Fatalf("potentially active message was rewritten to %q", activeContent)
|
||||
}
|
||||
var terminalCount int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM process_details WHERE message_id = ?
|
||||
AND event_type IN ('cancelled', 'timeout', 'error')`, potentiallyActive.ID).Scan(&terminalCount); err != nil {
|
||||
t.Fatalf("count active terminal details: %v", err)
|
||||
}
|
||||
if terminalCount != 0 {
|
||||
t.Fatalf("potentially active message got %d terminal details", terminalCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditAgentInterruptIsNotHumanPendingWork(t *testing.T) {
|
||||
db, err := database.NewDB(filepath.Join(t.TempDir(), "hitl-reviewer.db"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
manager := NewHITLManager(db, zap.NewNop())
|
||||
if err := manager.EnsureSchema(); err != nil {
|
||||
t.Fatalf("ensure schema: %v", err)
|
||||
}
|
||||
|
||||
audit, err := manager.CreatePendingInterrupt("conversation-audit", "message-audit", "review_edit", "exec", "call-audit", `{}`, "audit_agent")
|
||||
if err != nil {
|
||||
t.Fatalf("create audit interrupt: %v", err)
|
||||
}
|
||||
human, err := manager.CreatePendingInterrupt("conversation-human", "message-human", "approval", "exec", "call-human", `{}`, "human")
|
||||
if err != nil {
|
||||
t.Fatalf("create human interrupt: %v", err)
|
||||
}
|
||||
|
||||
manager.mu.RLock()
|
||||
_, auditWaitsForHuman := manager.pending[audit.InterruptID]
|
||||
_, humanWaitsForHuman := manager.pending[human.InterruptID]
|
||||
manager.mu.RUnlock()
|
||||
if auditWaitsForHuman {
|
||||
t.Fatal("audit-agent interrupt must not enter the human pending queue")
|
||||
}
|
||||
if !humanWaitsForHuman {
|
||||
t.Fatal("human interrupt should enter the human pending queue")
|
||||
}
|
||||
|
||||
query, args := (&AgentHandler{}).buildHitlListQuery(false)
|
||||
if len(args) != 0 {
|
||||
t.Fatalf("unexpected pending query args: %v", args)
|
||||
}
|
||||
if !strings.Contains(query, "COALESCE(reviewer,'human') = 'human'") {
|
||||
t.Fatalf("pending query must filter out audit-agent work: %s", query)
|
||||
}
|
||||
rows, err := db.Query(query)
|
||||
if err != nil {
|
||||
t.Fatalf("query human pending interrupts: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items, err := (&AgentHandler{}).scanHitlInterruptRows(rows)
|
||||
if err != nil {
|
||||
t.Fatalf("scan human pending interrupts: %v", err)
|
||||
}
|
||||
if len(items) != 1 || items[0]["id"] != human.InterruptID || items[0]["reviewer"] != "human" {
|
||||
t.Fatalf("unexpected human pending result: %#v", items)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package handler
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestHITLBuiltInWhitelistExemptsWriteFile(t *testing.T) {
|
||||
h := &AgentHandler{}
|
||||
req := h.hitlRequestWithMergedConfigWhitelist(&HITLRequest{
|
||||
Enabled: true,
|
||||
Mode: "approval",
|
||||
})
|
||||
|
||||
manager := NewHITLManager(nil, nil)
|
||||
manager.ActivateConversation("conversation-1", req)
|
||||
|
||||
if manager.NeedsToolApproval("conversation-1", "write_file") {
|
||||
t.Fatal("write_file should use the built-in HITL exemption")
|
||||
}
|
||||
if !manager.NeedsToolApproval("conversation-1", "exec") {
|
||||
t.Fatal("non-exempt tools should still require approval")
|
||||
}
|
||||
}
|
||||
@@ -8,13 +8,15 @@ import (
|
||||
|
||||
const toolSearchToolName = "tool_search"
|
||||
|
||||
// HitlExemptMetaTools 为编排/元工具:不直接执行攻击动作,但会阻塞 agent 控制流。
|
||||
// tool_search 必须免审批,否则其 HITL 拒绝结果与 Eino toolsearch 中间件不兼容(会硬崩 ChatModel)。
|
||||
// HitlExemptMetaTools 为 HITL 内置免审批工具:包括编排/元工具,以及模型输出修复链路依赖的 write_file。
|
||||
// tool_search 必须免审批,否则其 HITL 拒绝结果与 Eino toolsearch 中间件不兼容(会硬崩 ChatModel);
|
||||
// write_file 必须免审批,否则长脚本或请求体无法先安全落盘,模型输出修复链路会被再次阻塞。
|
||||
var HitlExemptMetaTools = []string{
|
||||
toolSearchToolName,
|
||||
"skill",
|
||||
"task",
|
||||
"write_todos",
|
||||
"write_file",
|
||||
"transfer_to_agent",
|
||||
"exit",
|
||||
"TaskCreate",
|
||||
|
||||
@@ -33,29 +33,30 @@ func TestHitlRejectToolResult_otherToolKeepsLegacyText(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeHitlExemptMetaTools_includesToolSearch(t *testing.T) {
|
||||
func TestMergeHitlExemptMetaTools_includesBuiltInExemptTools(t *testing.T) {
|
||||
merged := MergeHitlExemptMetaTools([]string{"read_file"})
|
||||
found := false
|
||||
foundToolSearch := false
|
||||
for _, name := range merged {
|
||||
if IsToolSearchTool(name) {
|
||||
found = true
|
||||
foundToolSearch = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if !foundToolSearch {
|
||||
t.Fatalf("tool_search missing from %v", merged)
|
||||
}
|
||||
foundProjectFactTools := map[string]bool{
|
||||
foundBuiltInTools := map[string]bool{
|
||||
"write_file": false,
|
||||
"upsert_project_fact": false,
|
||||
"get_project_fact": false,
|
||||
}
|
||||
for _, name := range merged {
|
||||
normalized := strings.ToLower(strings.TrimSpace(name))
|
||||
if _, ok := foundProjectFactTools[normalized]; ok {
|
||||
foundProjectFactTools[normalized] = true
|
||||
if _, ok := foundBuiltInTools[normalized]; ok {
|
||||
foundBuiltInTools[normalized] = true
|
||||
}
|
||||
}
|
||||
for name, found := range foundProjectFactTools {
|
||||
for name, found := range foundBuiltInTools {
|
||||
if !found {
|
||||
t.Fatalf("%s missing from %v", name, merged)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user