mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 20:01:51 +08:00
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:
1 parent
8bac4960e7
commit
b18cf89b77
9 files changed
+531
-57
No files matched your search
+52
-10
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
)
|
||||
|
||||
// sandboxTargetForTrigger matches the container a triggered run actually executes
|
||||
// in. A reporter bound to one task reuses that task's sandbox. Merged multi-task
|
||||
// runs and every other agent keep a session container.
|
||||
func sandboxTargetForTrigger(agentKey string, taskID int64, multiTask bool, convID int64) sandbox.Target {
|
||||
if agentKey == "reporter" && taskID > 0 && !multiTask {
|
||||
return sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: strconv.FormatInt(taskID, 10)}
|
||||
}
|
||||
return sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: "conv-" + strconv.FormatInt(convID, 10)}
|
||||
}
|
||||
|
||||
func storedConversationSandbox(c *db.Conversation) (string, string, bool) {
|
||||
if c == nil {
|
||||
return "", "", false
|
||||
}
|
||||
scope := strings.TrimSpace(c.SandboxScope)
|
||||
owner := strings.TrimSpace(c.SandboxOwnerID)
|
||||
if (scope == string(sandbox.ScopeTask) || scope == string(sandbox.ScopeSession)) && owner != "" {
|
||||
return scope, owner, true
|
||||
}
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
// resolveConversationSandbox prefers a binding already saved on the conversation.
|
||||
// fallbackTaskID is used only when nothing is saved and every linked finding
|
||||
// belongs to that one task. hasFallback distinguishes "no row" from task 0.
|
||||
func resolveConversationSandbox(c *db.Conversation, fallbackTaskID int64, hasFallback bool) (string, string) {
|
||||
if scope, owner, ok := storedConversationSandbox(c); ok {
|
||||
return scope, owner
|
||||
}
|
||||
if c == nil {
|
||||
return "", ""
|
||||
}
|
||||
if hasFallback && fallbackTaskID > 0 {
|
||||
return string(sandbox.ScopeTask), strconv.FormatInt(fallbackTaskID, 10)
|
||||
}
|
||||
return string(sandbox.ScopeSession), "conv-" + strconv.FormatInt(c.ID, 10)
|
||||
}
|
||||
|
||||
// fillConversationSandboxes writes the sandbox the chat badge should query.
|
||||
// Saved bindings win. Older reporter threads that never stored one fall back to
|
||||
// the single task that owns their findings.
|
||||
func (s *Server) fillConversationSandboxes(cs []*db.Conversation) {
|
||||
if len(cs) == 0 || s == nil || s.m == nil || s.m.pg == nil {
|
||||
return
|
||||
}
|
||||
pending := make([]int64, 0, len(cs))
|
||||
for _, c := range cs {
|
||||
if _, _, ok := storedConversationSandbox(c); !ok && c != nil {
|
||||
pending = append(pending, c.ID)
|
||||
}
|
||||
}
|
||||
fallbacks := map[int64]int64{}
|
||||
if len(pending) > 0 {
|
||||
got, err := s.m.pg.ReportTaskSandboxFallbacks(pending)
|
||||
if err != nil {
|
||||
log.Printf("[conv] sandbox fallback: %v", err)
|
||||
} else if got != nil {
|
||||
fallbacks = got
|
||||
}
|
||||
}
|
||||
for _, c := range cs {
|
||||
if c == nil {
|
||||
continue
|
||||
}
|
||||
taskID, ok := fallbacks[c.ID]
|
||||
scope, owner := resolveConversationSandbox(c, taskID, ok)
|
||||
c.SandboxScope = scope
|
||||
c.SandboxOwnerID = owner
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) fillConversationSandbox(c *db.Conversation) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
s.fillConversationSandboxes([]*db.Conversation{c})
|
||||
}
|
||||
|
||||
// ensureConversationSandbox binds a live turn to the conversation's sandbox.
|
||||
// A trigger may already have placed the target on ctx; that value wins so the
|
||||
// turn cannot drift back to a session container. Local mode leaves the context
|
||||
// alone because there is no container to select.
|
||||
func (s *Server) ensureConversationSandbox(ctx context.Context, c *db.Conversation) context.Context {
|
||||
if mgr := sandbox.Default(); mgr == nil || !mgr.Enabled() {
|
||||
return ctx
|
||||
}
|
||||
if preset, ok := sandbox.TargetFrom(ctx); ok && preset.Valid() {
|
||||
return ctx
|
||||
}
|
||||
if c == nil || s == nil || s.m == nil || s.m.pg == nil {
|
||||
return ctx
|
||||
}
|
||||
scope, owner, stored := storedConversationSandbox(c)
|
||||
if !stored {
|
||||
fallbacks, err := s.m.pg.ReportTaskSandboxFallbacks([]int64{c.ID})
|
||||
if err != nil {
|
||||
log.Printf("[conv %d] sandbox fallback: %v", c.ID, err)
|
||||
fallbacks = nil
|
||||
}
|
||||
taskID, ok := fallbacks[c.ID]
|
||||
scope, owner = resolveConversationSandbox(c, taskID, ok)
|
||||
if err == nil && scope != "" && owner != "" {
|
||||
if saveErr := s.m.pg.SetConversationSandbox(c.ID, scope, owner); saveErr != nil {
|
||||
log.Printf("[conv %d] save sandbox binding: %v", c.ID, saveErr)
|
||||
} else {
|
||||
c.SandboxScope = scope
|
||||
c.SandboxOwnerID = owner
|
||||
}
|
||||
}
|
||||
}
|
||||
target := sandbox.Target{Scope: sandbox.Scope(scope), OwnerID: owner}
|
||||
if !target.Valid() {
|
||||
return ctx
|
||||
}
|
||||
return sandbox.WithTarget(ctx, target)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
)
|
||||
|
||||
func TestSandboxTargetForTrigger(t *testing.T) {
|
||||
task := sandboxTargetForTrigger("reporter", 5, false, 18)
|
||||
if task.Scope != sandbox.ScopeTask || task.OwnerID != "5" {
|
||||
t.Fatalf("reporter task = %+v", task)
|
||||
}
|
||||
merged := sandboxTargetForTrigger("reporter", 5, true, 19)
|
||||
if merged.Scope != sandbox.ScopeSession || merged.OwnerID != "conv-19" {
|
||||
t.Fatalf("multi-task reporter = %+v", merged)
|
||||
}
|
||||
other := sandboxTargetForTrigger("auto", 5, false, 20)
|
||||
if other.Scope != sandbox.ScopeSession || other.OwnerID != "conv-20" {
|
||||
t.Fatalf("non-reporter = %+v", other)
|
||||
}
|
||||
noTask := sandboxTargetForTrigger("reporter", 0, false, 21)
|
||||
if noTask.Scope != sandbox.ScopeSession || noTask.OwnerID != "conv-21" {
|
||||
t.Fatalf("reporter without task = %+v", noTask)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveConversationSandbox(t *testing.T) {
|
||||
savedTask := &db.Conversation{ID: 18, SandboxScope: "task", SandboxOwnerID: "5"}
|
||||
scope, owner := resolveConversationSandbox(savedTask, 9, true)
|
||||
if scope != "task" || owner != "5" {
|
||||
t.Fatalf("stored task binding must win, got %s %s", scope, owner)
|
||||
}
|
||||
|
||||
savedSession := &db.Conversation{ID: 19, SandboxScope: "session", SandboxOwnerID: "conv-19"}
|
||||
scope, owner = resolveConversationSandbox(savedSession, 5, true)
|
||||
if scope != "session" || owner != "conv-19" {
|
||||
t.Fatalf("stored session binding must win over findings, got %s %s", scope, owner)
|
||||
}
|
||||
|
||||
historical := &db.Conversation{ID: 20}
|
||||
scope, owner = resolveConversationSandbox(historical, 7, true)
|
||||
if scope != "task" || owner != "7" {
|
||||
t.Fatalf("historical finding fallback = %s %s", scope, owner)
|
||||
}
|
||||
|
||||
plain := &db.Conversation{ID: 21}
|
||||
scope, owner = resolveConversationSandbox(plain, 0, false)
|
||||
if scope != "session" || owner != "conv-21" {
|
||||
t.Fatalf("plain conversation = %s %s", scope, owner)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConversationListReturnsSandboxTarget(t *testing.T) {
|
||||
s, _ := newRetestServer(t)
|
||||
pg := s.m.pg
|
||||
task, err := pg.CreateTask("conversation sandbox api", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reporter, err := pg.CreateConversation("reporter", "historical report", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
merged, err := pg.CreateConversation("reporter", "merged report", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain, err := pg.CreateConversation("auto", "plain", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = pg.Exec(`DELETE FROM findings WHERE report_conversation_id IN ($1,$2)`, reporter.ID, merged.ID)
|
||||
_, _ = pg.Exec(`DELETE FROM conversations WHERE id IN ($1,$2,$3)`, reporter.ID, merged.ID, plain.ID)
|
||||
_ = pg.DeleteTask(task.ID)
|
||||
})
|
||||
|
||||
fid, err := pg.AddFinding(task.ID, 0, "xss", "name", "high", "summary", "evidence", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pg.SetFindingReportConversationID(fid, reporter.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mergedFinding, err := pg.AddFinding(task.ID, 0, "xss", "name", "high", "summary", "evidence", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pg.SetFindingReportConversationID(mergedFinding, merged.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pg.SetConversationSandbox(merged.ID, "session", "conv-"+strconv.FormatInt(merged.ID, 10)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := retestRequest(s.pgListConversations, http.MethodGet, 0, "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Conversations []conversationListItem `json:"conversations"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := map[int64]conversationListItem{}
|
||||
for _, item := range body.Conversations {
|
||||
if item.ID == reporter.ID || item.ID == merged.ID || item.ID == plain.ID {
|
||||
found[item.ID] = item
|
||||
}
|
||||
}
|
||||
if len(found) != 3 {
|
||||
t.Fatalf("found %d conversations", len(found))
|
||||
}
|
||||
if found[reporter.ID].SandboxScope != "task" || found[reporter.ID].SandboxOwnerID != strconv.FormatInt(task.ID, 10) {
|
||||
t.Fatalf("historical reporter = %+v", found[reporter.ID].Conversation)
|
||||
}
|
||||
if found[merged.ID].SandboxScope != "session" || found[merged.ID].SandboxOwnerID != "conv-"+strconv.FormatInt(merged.ID, 10) {
|
||||
t.Fatalf("stored multi-task session = %+v", found[merged.ID].Conversation)
|
||||
}
|
||||
if found[plain.ID].SandboxScope != "session" || found[plain.ID].SandboxOwnerID != "conv-"+strconv.FormatInt(plain.ID, 10) {
|
||||
t.Fatalf("plain conversation = %+v", found[plain.ID].Conversation)
|
||||
}
|
||||
}
|
||||
+18
-14
@@ -63,6 +63,7 @@ func (s *Server) pgListConversations(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.fillConversationSandboxes(cs)
|
||||
items := make([]conversationListItem, 0, len(cs))
|
||||
s.chatMu.Lock()
|
||||
for _, c := range cs {
|
||||
@@ -126,6 +127,7 @@ func (s *Server) pgCreateConversation(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.fillConversationSandbox(c)
|
||||
writeJSON(w, 200, c)
|
||||
}
|
||||
|
||||
@@ -217,6 +219,7 @@ func (s *Server) pgRenameConversation(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 404, "conversation not found")
|
||||
return
|
||||
}
|
||||
s.fillConversationSandbox(updated)
|
||||
writeJSON(w, 200, updated)
|
||||
}
|
||||
|
||||
@@ -677,6 +680,7 @@ func (s *Server) runConversationTurn(ctx context.Context, cancel context.CancelC
|
||||
webSearch = a.WebSearch
|
||||
}
|
||||
sessionID := s.convBusyKey(c.ID) // "conv-<id>" transcript session
|
||||
ctx = s.ensureConversationSandbox(ctx, c)
|
||||
emit := func(rec db.Activity) {
|
||||
if _, err := pg.AppendConvActivity(c.ID, rec); err != nil {
|
||||
log.Printf("[conv %d] append activity failed: %v", c.ID, err)
|
||||
@@ -982,26 +986,26 @@ func (s *Server) runTriggeredRun(item triggeredRun) {
|
||||
s.chatMu.Lock()
|
||||
s.chatBusy[busyKey] = true
|
||||
s.chatMu.Unlock()
|
||||
var preset sandbox.Target
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
if item.agentKey == "reporter" && item.taskID > 0 && !item.multiTask {
|
||||
preset = sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: strconv.FormatInt(item.taskID, 10)}
|
||||
}
|
||||
target := sandboxTargetForTrigger(item.agentKey, item.taskID, item.multiTask, c.ID)
|
||||
if err := pg.SetConversationSandbox(c.ID, string(target.Scope), target.OwnerID); err != nil {
|
||||
log.Printf("[trigger] save sandbox binding for conv %d failed: %v", c.ID, err)
|
||||
} else {
|
||||
c.SandboxScope = string(target.Scope)
|
||||
c.SandboxOwnerID = target.OwnerID
|
||||
}
|
||||
if preset.Valid() {
|
||||
s.runConversationSync(c, msg, busyKey, preset)
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
if t, ok := s.m.Task(preset.OwnerID); !ok || s.resolvedTaskStatus(t) != "running" {
|
||||
mgr.RequestIdleStop(preset)
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && target.Valid() {
|
||||
s.runConversationSync(c, msg, busyKey, target)
|
||||
if target.Scope == sandbox.ScopeTask {
|
||||
if t, ok := s.m.Task(target.OwnerID); !ok || s.resolvedTaskStatus(t) != "running" {
|
||||
mgr.RequestIdleStop(target)
|
||||
}
|
||||
} else {
|
||||
// Triggered one-shot sessions (no bound task) do not need to sit idle for 20m.
|
||||
mgr.RequestIdleStop(target)
|
||||
}
|
||||
return
|
||||
}
|
||||
s.runConversationSync(c, msg, busyKey)
|
||||
// Triggered one-shot sessions (no bound task) do not need to sit idle for 20m.
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
mgr.RequestIdleStop(sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: busyKey})
|
||||
}
|
||||
}
|
||||
|
||||
// firstLine returns a single-line, length-capped preview (shared with summaries).
|
||||
|
||||
@@ -64,15 +64,23 @@ function fmtUptime(startedAt?: string): string {
|
||||
|
||||
export function SessionSandboxControl({
|
||||
conversationId,
|
||||
sandboxScope,
|
||||
sandboxOwnerId,
|
||||
running: chatRunning,
|
||||
}: {
|
||||
conversationId: number;
|
||||
sandboxScope?: string;
|
||||
sandboxOwnerId?: string;
|
||||
running: boolean;
|
||||
}) {
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const ownerID = `conv-${conversationId}`;
|
||||
const scope = sandboxScope === "task" ? "task" : "session";
|
||||
const ownerID = sandboxOwnerId ?? `conv-${conversationId}`;
|
||||
const taskBound = scope === "task";
|
||||
const boxZh = taskBound ? "任务沙箱" : "会话沙箱";
|
||||
const boxEn = taskBound ? "Task sandbox" : "Session sandbox";
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [info, setInfo] = React.useState<SandboxContainerInfo | null>(null);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
@@ -88,7 +96,7 @@ export function SessionSandboxControl({
|
||||
const seq = ++reqSeqRef.current;
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
const res = await api.sandboxContainer("session", ownerID, withStats);
|
||||
const res = await api.sandboxContainer(scope, ownerID, withStats);
|
||||
if (seq === reqSeqRef.current) {
|
||||
setInfo(res);
|
||||
}
|
||||
@@ -100,7 +108,7 @@ export function SessionSandboxControl({
|
||||
}
|
||||
}
|
||||
},
|
||||
[ownerID],
|
||||
[scope, ownerID],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -173,10 +181,10 @@ export function SessionSandboxControl({
|
||||
const handleStart = async () => {
|
||||
setBusy("start");
|
||||
try {
|
||||
const res = await api.startSandboxContainer("session", ownerID);
|
||||
const res = await api.startSandboxContainer(scope, ownerID);
|
||||
reqSeqRef.current += 1;
|
||||
setInfo(res);
|
||||
toast.success(L("会话沙箱容器已启动", "Session sandbox container started"));
|
||||
toast.success(L(`${boxZh}容器已启动`, `${boxEn} container started`));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
@@ -187,10 +195,10 @@ export function SessionSandboxControl({
|
||||
const handleStop = async () => {
|
||||
setBusy("stop");
|
||||
try {
|
||||
const res = await api.stopSandboxContainer("session", ownerID);
|
||||
const res = await api.stopSandboxContainer(scope, ownerID);
|
||||
reqSeqRef.current += 1;
|
||||
setInfo(res);
|
||||
toast.success(L("会话沙箱容器已停止(内存已释放)", "Session sandbox container stopped"));
|
||||
toast.success(L(`${boxZh}容器已停止(内存已释放)`, `${boxEn} container stopped`));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
@@ -204,13 +212,13 @@ export function SessionSandboxControl({
|
||||
setClearWorkspace(false);
|
||||
setBusy("recreate");
|
||||
try {
|
||||
const res = await api.recreateSandboxContainer("session", ownerID, { clear_workspace: wipe });
|
||||
const res = await api.recreateSandboxContainer(scope, ownerID, { clear_workspace: wipe });
|
||||
reqSeqRef.current += 1;
|
||||
setInfo(res);
|
||||
toast.success(
|
||||
wipe
|
||||
? L("会话沙箱已重建并清空工作区", "Session sandbox recreated with clean workspace")
|
||||
: L("会话沙箱已重建(工作区文件已保留)", "Session sandbox recreated"),
|
||||
? L(`${boxZh}已重建并清空工作区`, `${boxEn} recreated with clean workspace`)
|
||||
: L(`${boxZh}已重建(工作区文件已保留)`, `${boxEn} recreated`),
|
||||
);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
@@ -223,9 +231,9 @@ export function SessionSandboxControl({
|
||||
setRemoveOpen(false);
|
||||
setBusy("remove");
|
||||
try {
|
||||
await api.removeSandboxContainer("session", ownerID);
|
||||
await api.removeSandboxContainer(scope, ownerID);
|
||||
await fetchInfo(false);
|
||||
toast.success(L("会话沙箱容器已删除(工作区文件已保留)", "Session sandbox container removed"));
|
||||
toast.success(L(`${boxZh}容器已删除(工作区文件已保留)`, `${boxEn} container removed`));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
@@ -247,21 +255,28 @@ export function SessionSandboxControl({
|
||||
<PopoverTitle className="flex items-center justify-between text-sm">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<BoxIcon className="size-4" />
|
||||
{L("对话隔离沙箱", "Chat Sandbox")}
|
||||
{L(taskBound ? "任务沙箱" : "对话隔离沙箱", taskBound ? "Task Sandbox" : "Chat Sandbox")}
|
||||
</span>
|
||||
<Badge variant={running ? "default" : "secondary"}>{info.state}</Badge>
|
||||
</PopoverTitle>
|
||||
<PopoverDescription className="text-xs">
|
||||
{L(
|
||||
"本对话调用命令、脚本或浏览器时将在此独立非 root 容器内执行(按需自动创建,空闲自动停机)。",
|
||||
"Commands, scripts, and browser tools in this chat run inside this isolated non-root container (created on demand).",
|
||||
)}
|
||||
{taskBound
|
||||
? L(
|
||||
"本对话调用命令、脚本或浏览器时,实际跑在关联任务的沙箱容器里,不会另开一个对话容器。",
|
||||
"Commands, scripts, and browser tools in this chat run in the linked task sandbox, not a separate chat container.",
|
||||
)
|
||||
: L(
|
||||
"本对话调用命令、脚本或浏览器时将在此独立非 root 容器内执行(按需自动创建,空闲自动停机)。",
|
||||
"Commands, scripts, and browser tools in this chat run inside this isolated non-root container (created on demand).",
|
||||
)}
|
||||
</PopoverDescription>
|
||||
</PopoverHeader>
|
||||
|
||||
<div className="space-y-1.5 rounded-md border bg-muted/40 p-2.5 font-mono text-[11px]">
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground">{L("会话", "Session")}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{L(taskBound ? "任务" : "会话", taskBound ? "Task" : "Session")}
|
||||
</span>
|
||||
<span className="truncate">{ownerID}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
@@ -371,7 +386,18 @@ export function SessionSandboxControl({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end border-t pt-2">
|
||||
<div className="flex items-center justify-between gap-2 border-t pt-2">
|
||||
{taskBound ? (
|
||||
<Link
|
||||
href={`/function/tasks/detail?id=${encodeURIComponent(ownerID)}`}
|
||||
className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{L("查看关联任务", "Open task")}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</Link>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<Link
|
||||
href="/system/sandbox"
|
||||
className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
|
||||
@@ -386,12 +412,22 @@ export function SessionSandboxControl({
|
||||
<AlertDialog open={recreateOpen} onOpenChange={setRecreateOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{L("重建对话沙箱容器", "Recreate Chat Sandbox")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
<AlertDialogTitle>
|
||||
{L(
|
||||
"确定销毁当前对话的旧容器并按最新镜像与资源配额重新创建启动吗?",
|
||||
"Replace this chat's sandbox container with a fresh one using the latest image and limits?",
|
||||
taskBound ? "重建任务沙箱容器" : "重建对话沙箱容器",
|
||||
taskBound ? "Recreate Task Sandbox" : "Recreate Chat Sandbox",
|
||||
)}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{taskBound
|
||||
? L(
|
||||
"确定销毁关联任务的沙箱容器,并按最新镜像与资源配额重新创建吗?这会影响该任务,不会另开对话容器。",
|
||||
"Replace the linked task's sandbox container with a fresh one? This affects that task.",
|
||||
)
|
||||
: L(
|
||||
"确定销毁当前对话的旧容器并按最新镜像与资源配额重新创建启动吗?",
|
||||
"Replace this chat's sandbox container with a fresh one using the latest image and limits?",
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="flex items-start gap-2.5 rounded-md border bg-muted/30 p-3 text-xs">
|
||||
@@ -406,10 +442,15 @@ export function SessionSandboxControl({
|
||||
{L("同时清空工作区文件 (/workspace)", "Also clear workspace files (/workspace)")}
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{L(
|
||||
"默认保留本对话上传与生成的文件;勾选后将清空 /workspace 下所有文件。",
|
||||
"Session files are preserved by default. Check to wipe /workspace.",
|
||||
)}
|
||||
{taskBound
|
||||
? L(
|
||||
"默认保留任务工作区;勾选后会清空该任务 /workspace 下的文件,包括已有截图和脚本。",
|
||||
"Task files are kept by default. Check to wipe this task's /workspace, including screenshots and scripts.",
|
||||
)
|
||||
: L(
|
||||
"默认保留本对话上传与生成的文件;勾选后将清空 /workspace 下所有文件。",
|
||||
"Session files are preserved by default. Check to wipe /workspace.",
|
||||
)}
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
@@ -425,12 +466,22 @@ export function SessionSandboxControl({
|
||||
<AlertDialog open={removeOpen} onOpenChange={setRemoveOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{L("删除对话沙箱容器", "Delete Chat Sandbox")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
<AlertDialogTitle>
|
||||
{L(
|
||||
"确定删除该对话的沙箱容器吗?宿主机工作区文件会保留,后续调用工具时将自动重新创建。",
|
||||
"Remove this chat's sandbox container? Host workspace files will be preserved.",
|
||||
taskBound ? "删除任务沙箱容器" : "删除对话沙箱容器",
|
||||
taskBound ? "Delete Task Sandbox" : "Delete Chat Sandbox",
|
||||
)}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{taskBound
|
||||
? L(
|
||||
"确定删除关联任务的沙箱容器吗?任务工作区文件会保留,下次执行命令时会重新创建。",
|
||||
"Remove the linked task's sandbox container? Task workspace files will be preserved.",
|
||||
)
|
||||
: L(
|
||||
"确定删除该对话的沙箱容器吗?宿主机工作区文件会保留,后续调用工具时将自动重新创建。",
|
||||
"Remove this chat's sandbox container? Host workspace files will be preserved.",
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
|
||||
@@ -756,7 +756,9 @@ function ChatView({
|
||||
if (files.length === 0) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const r = await api.chatUpload("session", `conv-${conv.id}`, files);
|
||||
const uploadScope = conv.sandbox_scope === "task" ? "task" : "session";
|
||||
const uploadOwner = conv.sandbox_owner_id ?? `conv-${conv.id}`;
|
||||
const r = await api.chatUpload(uploadScope, uploadOwner, files);
|
||||
setAttachments((prev) => [...prev, ...r.attachments]);
|
||||
} catch (e) {
|
||||
toast.error(translate("overview.uploadFailedPrefix") + localizedError(e, translate));
|
||||
@@ -825,7 +827,12 @@ function ChatView({
|
||||
)}
|
||||
{running && <LiveBadge />}
|
||||
<SideQuestionButton side={side} />
|
||||
<SessionSandboxControl conversationId={conv.id} running={running} />
|
||||
<SessionSandboxControl
|
||||
conversationId={conv.id}
|
||||
sandboxScope={conv.sandbox_scope}
|
||||
sandboxOwnerId={conv.sandbox_owner_id}
|
||||
running={running}
|
||||
/>
|
||||
<div className="text-muted-foreground ml-auto flex min-w-0 max-w-full items-center justify-end gap-x-3 gap-y-1 text-xs max-sm:w-full max-sm:flex-wrap">
|
||||
{tokenTotal.turns > 0 && (
|
||||
<span title={translate("overview.roundsHint")} className="tabular-nums">
|
||||
|
||||
@@ -821,6 +821,9 @@ export interface Conversation {
|
||||
llm_profile_id?: number;
|
||||
pinned?: boolean;
|
||||
pinned_at?: string | null;
|
||||
// Sandbox the conversation's commands actually use. task → that task's container.
|
||||
sandbox_scope?: string;
|
||||
sandbox_owner_id?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user