fix(chat): show the sandbox container a conversation actually uses

A reporter chat bound to one task ran commands in that task's sandbox, while the chat page kept querying the empty session container. Save the task or session target on the conversation and point the badge, uploads, and later turns at it.
This commit is contained in:
ji ruo committed 2026-12-02 17:45:28 +08:00
1 parent 8bac4960e7
commit b18cf89b77
9 files changed
+531 -57

No files matched your search

+52 -10
View File
@@ -50,14 +50,16 @@ GROUP BY c.id`)
// Conversation is one ChatGPT-style chat thread bound to an agent key. It lives
// independent of the pentest exploration graph — see schema.sql §I.
type Conversation struct {
ID int64 `json:"id"`
AgentKey string `json:"agent_key"`
Title string `json:"title"`
LLMProfileID *int64 `json:"llm_profile_id,omitempty"`
Pinned bool `json:"pinned"`
PinnedAt *time.Time `json:"pinned_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID int64 `json:"id"`
AgentKey string `json:"agent_key"`
Title string `json:"title"`
LLMProfileID *int64 `json:"llm_profile_id,omitempty"`
Pinned bool `json:"pinned"`
PinnedAt *time.Time `json:"pinned_at,omitempty"`
SandboxScope string `json:"sandbox_scope"`
SandboxOwnerID string `json:"sandbox_owner_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// ConversationPatch updates only the fields whose pointers are non-nil.
@@ -66,12 +68,12 @@ type ConversationPatch struct {
Pinned *bool
}
const convCols = `id, agent_key, title, llm_profile_id, pinned_at, created_at, updated_at`
const convCols = `id, agent_key, title, llm_profile_id, pinned_at, created_at, updated_at, sandbox_scope, sandbox_owner_id`
func scanConv(row interface{ Scan(...any) error }) (Conversation, error) {
var c Conversation
var pinnedAt sql.NullTime
err := row.Scan(&c.ID, &c.AgentKey, &c.Title, &c.LLMProfileID, &pinnedAt, &c.CreatedAt, &c.UpdatedAt)
err := row.Scan(&c.ID, &c.AgentKey, &c.Title, &c.LLMProfileID, &pinnedAt, &c.CreatedAt, &c.UpdatedAt, &c.SandboxScope, &c.SandboxOwnerID)
if pinnedAt.Valid {
c.Pinned = true
c.PinnedAt = &pinnedAt.Time
@@ -206,6 +208,46 @@ WHERE id=$1 AND title IN ('', '新对话', $3)`, id, title, initial)
return err
}
// SetConversationSandbox records which sandbox container this conversation's
// commands actually run in. scope is "task" or "session".
func (d *DB) SetConversationSandbox(id int64, scope, ownerID string) error {
_, err := d.Exec(`UPDATE conversations SET sandbox_scope=$2, sandbox_owner_id=$3 WHERE id=$1`, id, scope, ownerID)
return err
}
// ReportTaskSandboxFallbacks maps a conversation to the single task that owns
// every finding whose report was written in that conversation. Conversations
// with no such finding, a null task, or more than one task are omitted.
func (d *DB) ReportTaskSandboxFallbacks(convIDs []int64) (map[int64]int64, error) {
out := map[int64]int64{}
if len(convIDs) == 0 {
return out, nil
}
rows, err := d.Query(`
SELECT report_conversation_id,
COUNT(DISTINCT task_id) FILTER (WHERE task_id IS NOT NULL),
COUNT(*) FILTER (WHERE task_id IS NULL),
MIN(task_id) FILTER (WHERE task_id IS NOT NULL)
FROM findings
WHERE report_conversation_id = ANY($1::bigint[])
GROUP BY report_conversation_id`, convIDs)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var convID, distinctTasks, nullTasks int64
var taskID sql.NullInt64
if err := rows.Scan(&convID, &distinctTasks, &nullTasks, &taskID); err != nil {
return nil, err
}
if distinctTasks == 1 && nullTasks == 0 && taskID.Valid && taskID.Int64 > 0 {
out[convID] = taskID.Int64
}
}
return out, rows.Err()
}
// TouchConversation bumps updated_at so the thread floats to the top of the list.
func (d *DB) TouchConversation(id int64) error {
_, err := d.Exec(`UPDATE conversations SET updated_at=now() WHERE id=$1`, id)
+105
View File
@@ -0,0 +1,105 @@
package db
import (
"strconv"
"testing"
)
func TestConversationSandboxBindingAndFindingFallback(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
t.Skipf("postgres unavailable (%v) — skipping", err)
}
defer d.Close()
taskA, err := d.CreateTask("sandbox-fallback-a", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
taskB, err := d.CreateTask("sandbox-fallback-b", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
reporter, err := d.CreateConversation("reporter", "single-task report", nil)
if err != nil {
t.Fatal(err)
}
mixed, err := d.CreateConversation("reporter", "mixed-task report", nil)
if err != nil {
t.Fatal(err)
}
plain, err := d.CreateConversation("auto", "plain chat", nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM findings WHERE task_id IN ($1,$2)`, taskA.ID, taskB.ID)
_, _ = d.Exec(`DELETE FROM conversations WHERE id IN ($1,$2,$3)`, reporter.ID, mixed.ID, plain.ID)
_ = d.DeleteTask(taskA.ID)
_ = d.DeleteTask(taskB.ID)
})
if reporter.SandboxScope != "" || reporter.SandboxOwnerID != "" {
t.Fatalf("new conversation should not have a sandbox binding: %+v", reporter)
}
if err := d.SetConversationSandbox(plain.ID, "session", "conv-"+strconv.FormatInt(plain.ID, 10)); err != nil {
t.Fatal(err)
}
got, err := d.GetConversation(plain.ID)
if err != nil || got == nil {
t.Fatal(err)
}
if got.SandboxScope != "session" || got.SandboxOwnerID != "conv-"+strconv.FormatInt(plain.ID, 10) {
t.Fatalf("stored session binding = %+v", got)
}
add := func(taskID, convID int64) {
t.Helper()
fid, err := d.AddFinding(taskID, 0, "xss", "name", "high", "summary", "evidence", "worker", nil)
if err != nil {
t.Fatal(err)
}
if err := d.SetFindingReportConversationID(fid, convID); err != nil {
t.Fatal(err)
}
}
add(taskA.ID, reporter.ID)
add(taskA.ID, reporter.ID)
add(taskA.ID, mixed.ID)
add(taskB.ID, mixed.ID)
fallbacks, err := d.ReportTaskSandboxFallbacks([]int64{reporter.ID, mixed.ID, plain.ID})
if err != nil {
t.Fatal(err)
}
if fallbacks[reporter.ID] != taskA.ID {
t.Fatalf("single-task report fallback = %d, want %d", fallbacks[reporter.ID], taskA.ID)
}
if _, ok := fallbacks[mixed.ID]; ok {
t.Fatalf("mixed tasks must not bind to one task: %+v", fallbacks)
}
if _, ok := fallbacks[plain.ID]; ok {
t.Fatalf("conversation without findings must not fall back: %+v", fallbacks)
}
nullConv, err := d.CreateConversation("reporter", "null-task report", nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM conversations WHERE id=$1`, nullConv.ID) })
fid, err := d.AddFinding(0, 0, "xss", "name", "low", "summary", "evidence", "worker", nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.DeleteFinding(fid) })
if err := d.SetFindingReportConversationID(fid, nullConv.ID); err != nil {
t.Fatal(err)
}
fallbacks, err = d.ReportTaskSandboxFallbacks([]int64{nullConv.ID})
if err != nil {
t.Fatal(err)
}
if _, ok := fallbacks[nullConv.ID]; ok {
t.Fatalf("null task_id must not fall back: %+v", fallbacks)
}
}
+5
View File
@@ -987,10 +987,15 @@ CREATE TABLE IF NOT EXISTS conversations (
title TEXT NOT NULL DEFAULT '',
llm_profile_id BIGINT REFERENCES llm_profiles(id) ON DELETE SET NULL,
pinned_at TIMESTAMPTZ,
-- 这条对话实际执行命令时使用的沙箱。空表示尚未写入,读取时再按漏洞报告回退。
sandbox_scope TEXT NOT NULL DEFAULT '',
sandbox_owner_id TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE conversations ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;
ALTER TABLE conversations ADD COLUMN IF NOT EXISTS sandbox_scope TEXT NOT NULL DEFAULT '';
ALTER TABLE conversations ADD COLUMN IF NOT EXISTS sandbox_owner_id TEXT NOT NULL DEFAULT '';
CREATE INDEX IF NOT EXISTS idx_conversations_llm_profile ON conversations(llm_profile_id) WHERE llm_profile_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_conversations_pinned ON conversations(pinned_at DESC) WHERE pinned_at IS NOT NULL;
DROP TRIGGER IF EXISTS trg_conversations_upd ON conversations;