Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions internal/httpapi/assistant_conversation_attachments.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,20 @@ import (
"agentflow/internal/runtime"
)

// conversationAttachmentsDir holds the materialized attachments under a
// conversation's session root.
const conversationAttachmentsDir = "attachments"

func conversationAttachmentPath(id, name string) string {
name = filepath.Base(strings.ReplaceAll(name, "\\", "/"))
if name == "." || name == "" {
name = "attachment.bin"
}
return filepath.Join("attachments", id, name)
return filepath.Join(conversationAttachmentsDir, id, name)
}

func writeConversationAttachments(root string, req assistantRequest) error {
dir := filepath.Join(root, "attachments")
dir := filepath.Join(root, conversationAttachmentsDir)
if err := os.RemoveAll(dir); err != nil {
return err
}
Expand Down
18 changes: 18 additions & 0 deletions internal/httpapi/assistant_conversation_attachments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,24 @@ func TestConversationImageRoutingAcrossEngines(t *testing.T) {
if index < 0 || !slices.Equal(inv.command.Argv[index:], []string{"--file", imagePath, "--", prompt}) || !inv.command.AgentCLI.ImageInput {
t.Fatalf("wrong OpenCode file input: %v", inv.command.Argv)
}
// Read-only OpenCode denies paths outside ws; the note's
// attachment paths (text files included) must stay readable.
data, err := os.ReadFile(filepath.Join(root, "home", ".config", "opencode", "opencode.json"))
if err != nil {
t.Fatal(err)
}
var doc struct {
Permission struct {
External map[string]string `json:"external_directory"`
} `json:"permission"`
}
if err := json.Unmarshal(data, &doc); err != nil {
t.Fatalf("OpenCode chat config: %v\n%s", err, data)
}
documentPath := filepath.Join(root, conversationAttachmentPath(document.ID, document.Name))
if !strings.Contains(note, documentPath) || doc.Permission.External["*"] != "deny" || doc.Permission.External[filepath.Join(root, conversationAttachmentsDir, "*")] != "allow" {
t.Fatalf("OpenCode chat cannot read %s: %s", documentPath, data)
}
case runtime.AgentCLIPi:
if !slices.Contains(inv.command.Argv, "@"+imagePath) || !inv.command.AgentCLI.ImageInput {
t.Fatalf("wrong Pi file input: %v", inv.command.Argv)
Expand Down
8 changes: 7 additions & 1 deletion internal/httpapi/assistant_engine_agentcli.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@ func prepareAssistantAgentCLIInvocation(kind string, o assistantEngineInvocation
}
entries[id] = entry
}
if err := runtime.WriteAgentCLIMCPConfig(kind, runtime.AgentCLIHome{Base: o.Root, Rel: "home"}, entries, runtime.AgentCLIMCPOptions{ReadOnly: !o.Workspace}); err != nil {
mcpOptions := runtime.AgentCLIMCPOptions{ReadOnly: !o.Workspace}
if mcpOptions.ReadOnly {
// The prompt hands attachments over by their path under the session
// root (conversationAttachmentNote), outside the CLI's ws directory.
mcpOptions.ReadableDirs = []string{filepath.Join(o.Root, conversationAttachmentsDir)}
}
if err := runtime.WriteAgentCLIMCPConfig(kind, runtime.AgentCLIHome{Base: o.Root, Rel: "home"}, entries, mcpOptions); err != nil {
return assistantCLIInvocation{}, err
}
resume := ""
Expand Down
5 changes: 5 additions & 0 deletions internal/httpapi/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -1235,6 +1235,11 @@ func (h *catalogHandlers) workflow(c *gin.Context) {
c.JSON(400, gin.H{"error": "invalid workflow revision"})
return
}
// Restoring a generic template rewrites it, like PUT /api/workflows.
if v.Generic && !h.isPlatformAdmin(c.Request) {
c.JSON(http.StatusConflict, map[string]string{"error": "通用模板为只读,请先复制到本项目再修改"})
return
}
if workflowHasNotifications(restored) && !h.notifications.access(c, v.ProjectID, true) {
return
}
Expand Down
37 changes: 37 additions & 0 deletions internal/httpapi/generic_workflows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,43 @@ func TestPlatformAdminCanEditGenericTemplate(t *testing.T) {
}
}

func TestGenericTemplateRevisionRestoreIsAdminOnlyAndRewritesTemplate(t *testing.T) {
t.Setenv("AGENTFLOW_PLATFORM_ADMINS", "example-admin")
t.Setenv("AGENTFLOW_SESSION_SECRET", "generic-admin-session-secret")
h, s := newGenericTemplateServer(t)
for _, login := range []string{"example-admin", "alice"} {
if err := s.PutUser(domain.User{LoginName: login, ChineseName: login}); err != nil {
t.Fatal(err)
}
}
admin, _ := s.UserByLoginName("example-admin")
alice, _ := s.UserByLoginName("alice")
base := "/api/workflows/" + repo.GenericBackendDeliveryWorkflowID
original := requestJSONAuthed[domain.WorkflowDefinition](t, h, admin, http.MethodGet, base, nil, http.StatusOK)
edited := original
edited.Description = "admin patched the platform template"
requestJSONAuthed[domain.WorkflowDefinition](t, h, admin, http.MethodPut, "/api/workflows", edited, http.StatusOK)
revisions := requestJSONAuthed[[]domain.DefinitionRevision](t, h, admin, http.MethodGet, base+"/revisions", nil, http.StatusOK)
if len(revisions) == 0 {
t.Fatal("expected a revision of the template before the edit")
}
restorePath := base + "/revisions/" + revisions[0].ID + "/restore"
requestJSONAuthed[map[string]string](t, h, alice, http.MethodPost, restorePath, map[string]any{}, http.StatusConflict)
if workflowRowExists(t, s, repo.GenericBackendDeliveryWorkflowID) {
t.Fatal("a rejected restore must not write a workflows row")
}
restored := requestJSONAuthed[domain.WorkflowDefinition](t, h, admin, http.MethodPost, restorePath, map[string]any{}, http.StatusOK)
current := requestJSONAuthed[domain.WorkflowDefinition](t, h, admin, http.MethodGet, base, nil, http.StatusOK)
if restored.Description != original.Description || current.Description != original.Description || restored.Revision != current.Revision {
t.Fatalf("restore returned %q r%d, template %q r%d, want %q", restored.Description, restored.Revision, current.Description, current.Revision, original.Description)
}
if workflowRowExists(t, s, repo.GenericBackendDeliveryWorkflowID) {
t.Fatal("restoring a generic template must stay in generic_templates")
}
restored.Description = "edited after restore"
requestJSONAuthed[domain.WorkflowDefinition](t, h, admin, http.MethodPut, "/api/workflows", restored, http.StatusOK)
}

func TestGenericTemplateAgentsAreNotTheCurrentProjectCatalog(t *testing.T) {
t.Setenv("AGENTFLOW_PLATFORM_ADMINS", "example-admin")
t.Setenv("AGENTFLOW_SESSION_SECRET", "generic-admin-session-secret")
Expand Down
32 changes: 29 additions & 3 deletions internal/repo/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -1016,7 +1016,15 @@ func (r *CatalogRepo) RestoreWorkflowRevision(id string) (domain.WorkflowDefinit
if err := json.Unmarshal(rev.Payload, &wf); err != nil {
return domain.WorkflowDefinition{}, err
}
current, found := r.Workflow(wf.ID)
// A generic template lives in generic_templates, and UpdateGenericWorkflow
// snapshots it under the same id. Restoring it must rewrite the template,
// not add a workflows row that the template id would shadow.
if template, generic := r.GenericTemplateByWorkflow(wf.ID); generic {
wf.Revision = template.Workflow.Revision
wf.Version = max(wf.Version, template.Workflow.Version)
return r.UpdateGenericWorkflow(wf)
}
current, found := r.storedWorkflow(wf.ID)
if !found {
return domain.WorkflowDefinition{}, fmt.Errorf("workflow %s not found", wf.ID)
}
Expand All @@ -1025,7 +1033,17 @@ func (r *CatalogRepo) RestoreWorkflowRevision(id string) (domain.WorkflowDefinit
// draft on top of the latest release, so publishing it must not reuse a
// version number that already names different content.
wf.Version = max(wf.Version, current.Version)
return wf, r.PutWorkflow(wf)
if err := r.PutWorkflow(wf); err != nil {
return domain.WorkflowDefinition{}, err
}
// Return the stored row: PutWorkflow assigns the new revision, published
// marker and timestamps, and an editor that adopts this definition sends
// that revision back on its next save.
stored, ok := r.storedWorkflow(wf.ID)
if !ok {
return domain.WorkflowDefinition{}, fmt.Errorf("workflow %s not found", wf.ID)
}
return stored, nil
}

func (r *CatalogRepo) RestoreAgentRevision(id string) (domain.AgentDefinition, error) {
Expand All @@ -1040,7 +1058,15 @@ func (r *CatalogRepo) RestoreAgentRevision(id string) (domain.AgentDefinition, e
if current, found := r.Agent(agent.ID); found {
agent.Version = current.Version + 1
}
return agent, r.PutAgent(agent)
if err := r.PutAgent(agent); err != nil {
return domain.AgentDefinition{}, err
}
// Like workflows, report what PutAgent stored (timestamps, normalized refs).
stored, ok := r.Agent(agent.ID)
if !ok {
return domain.AgentDefinition{}, fmt.Errorf("agent %s not found", agent.ID)
}
return stored, nil
}

// ---------- Production LOOP ids ----------
Expand Down
86 changes: 86 additions & 0 deletions internal/repo/revisions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,51 @@ func TestWorkflowRevisionDiffAndRestore(t *testing.T) {
if got.Description != "first" {
t.Fatalf("stored description = %q", got.Description)
}
// The designer adopts the returned definition and saves the next edit with
// its revision, so it must be the stored one, not the snapshot's.
if restored.Revision != got.Revision || !restored.UpdatedAt.Equal(got.UpdatedAt) {
t.Fatalf("restore returned revision %d (%s), stored %d (%s)", restored.Revision, restored.UpdatedAt, got.Revision, got.UpdatedAt)
}
restored.Description = "third"
if err := s.PutWorkflow(restored); err != nil {
t.Fatalf("saving an edit right after restore: %v", err)
}
}

func TestWorkflowRevisionRestoreReturnsPublishedMarker(t *testing.T) {
s, err := OpenTest()
if err != nil {
t.Fatal(err)
}
defer s.Close()
wf := domain.WorkflowDefinition{ID: "rev-pub", Name: "Rev Published", Status: "draft", Description: "draft"}
if err := s.PutWorkflow(wf); err != nil {
t.Fatal(err)
}
published, err := s.PublishWorkflow(wf.ID)
if err != nil {
t.Fatal(err)
}
var draft domain.DefinitionRevision
for _, rev := range s.Revisions("workflow", wf.ID) {
var snap domain.WorkflowDefinition
if json.Unmarshal(rev.Payload, &snap) == nil && snap.PublishedRevision == 0 {
draft = rev
}
}
if draft.ID == "" {
t.Fatal("no revision holds the unpublished draft")
}
// Restoring a snapshot taken before the first release keeps the release
// marker of the stored LOOP rather than the snapshot's empty one.
restored, err := s.RestoreWorkflowRevision(draft.ID)
if err != nil {
t.Fatal(err)
}
got, _ := s.Workflow(wf.ID)
if restored.Revision != got.Revision || restored.PublishedRevision != published.PublishedRevision || got.PublishedRevision != published.PublishedRevision {
t.Fatalf("restored %d/%d, stored %d/%d, published %d", restored.Revision, restored.PublishedRevision, got.Revision, got.PublishedRevision, published.PublishedRevision)
}
}

func TestWorkflowRevisionRestoreKeepsVersionNumbersUnique(t *testing.T) {
Expand Down Expand Up @@ -111,4 +156,45 @@ func TestAgentRevisionRestore(t *testing.T) {
if restored.Prompt != "v1" {
t.Fatalf("restore instructions = %q", restored.Prompt)
}
got, _ := s.Agent(agent.ID)
if restored.Version != got.Version || !restored.UpdatedAt.Equal(got.UpdatedAt) {
t.Fatalf("restore returned v%d (%s), stored v%d (%s)", restored.Version, restored.UpdatedAt, got.Version, got.UpdatedAt)
}
}

func TestGenericWorkflowRevisionRestoreRewritesTemplate(t *testing.T) {
s := testStoreWithGenericTemplates(t)
before, ok := s.GenericWorkflowByID(GenericBackendDeliveryWorkflowID)
if !ok {
t.Fatal("backend template missing")
}
edited := before
edited.Description = "admin edit"
if _, err := s.UpdateGenericWorkflow(edited); err != nil {
t.Fatal(err)
}
revs := s.Revisions("workflow", GenericBackendDeliveryWorkflowID)
if len(revs) == 0 {
t.Fatal("expected a snapshot of the template before the edit")
}
restored, err := s.RestoreWorkflowRevision(revs[0].ID)
if err != nil {
t.Fatal(err)
}
got, _ := s.GenericWorkflowByID(GenericBackendDeliveryWorkflowID)
if restored.Description != before.Description || got.Description != before.Description {
t.Fatalf("restore returned %q, template is %q, want %q", restored.Description, got.Description, before.Description)
}
if !got.Generic || restored.Revision != got.Revision || !restored.UpdatedAt.Equal(got.UpdatedAt) {
t.Fatalf("restore returned revision %d (%s), template %d (%s)", restored.Revision, restored.UpdatedAt, got.Revision, got.UpdatedAt)
}
// The template id stays out of the workflows table.
if _, shadow := s.storedWorkflow(GenericBackendDeliveryWorkflowID); shadow {
t.Fatal("restoring a generic template wrote a workflows row")
}
// The designer saves its next edit with the returned revision.
restored.Description = "after restore"
if _, err := s.UpdateGenericWorkflow(restored); err != nil {
t.Fatalf("saving an edit right after restore: %v", err)
}
}
44 changes: 43 additions & 1 deletion internal/runtime/agent_cli.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package runtime

import (
"bytes"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -129,6 +130,47 @@ type AgentCLIMCPOptions struct {
// ReadOnly denies the CLI's own shell, edit and web tools (AI 对话 runs on
// the control plane); MCP tools stay available.
ReadOnly bool
// ReadableDirs are directories outside the working directory that a
// read-only CLI may still read, such as the conversation's attachments.
// Only CLIs that confine reads to the working directory need them.
ReadableDirs []string
}

// openCodeRules is one OpenCode permission as pattern rules. OpenCode applies
// the last matching rule, so the order is kept as written rather than sorted
// like a Go map.
type openCodeRules [][2]string

func (r openCodeRules) MarshalJSON() ([]byte, error) {
var b bytes.Buffer
b.WriteByte('{')
for i, rule := range r {
if i > 0 {
b.WriteByte(',')
}
pattern, _ := json.Marshal(rule[0])
action, _ := json.Marshal(rule[1])
b.Write(pattern)
b.WriteByte(':')
b.Write(action)
}
b.WriteByte('}')
return b.Bytes(), nil
}

// openCodeReadOnlyExternalDirectory denies paths outside the working
// directory except the given readable directories.
func openCodeReadOnlyExternalDirectory(dirs []string) any {
rules := openCodeRules{{"*", "deny"}}
for _, dir := range dirs {
if dir = strings.TrimSpace(dir); dir != "" {
rules = append(rules, [2]string{filepath.Join(filepath.Clean(dir), "*"), "allow"})
}
}
if len(rules) == 1 {
return "deny"
}
return rules
}

var dshServerNameRe = regexp.MustCompile(`[^A-Za-z0-9_-]`)
Expand Down Expand Up @@ -196,7 +238,7 @@ func WriteAgentCLIMCPConfig(kind string, home AgentCLIHome, entries map[string]a
case AgentCLIOpenCode:
permission := map[string]any{"edit": "allow", "bash": "allow", "webfetch": "allow", "external_directory": "allow", "doom_loop": "allow"}
if options.ReadOnly {
permission = map[string]any{"edit": "deny", "bash": "deny", "webfetch": "deny", "websearch": "deny", "external_directory": "deny", "task": "deny"}
permission = map[string]any{"edit": "deny", "bash": "deny", "webfetch": "deny", "websearch": "deny", "external_directory": openCodeReadOnlyExternalDirectory(options.ReadableDirs), "task": "deny"}
}
document = map[string]any{"$schema": "https://opencode.ai/config.json", "mcp": servers, "permission": permission, "autoupdate": false, "share": "disabled"}
case AgentCLIDeepSeek:
Expand Down
55 changes: 55 additions & 0 deletions internal/runtime/agent_cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,61 @@ func TestWriteAgentCLIMCPConfigChat(t *testing.T) {
}
}

// AI 对话 hands attachments over by a path outside OpenCode's working
// directory. Read-only chat must still read them, and nothing else outside.
func TestOpenCodeReadOnlyAllowsReadableDirs(t *testing.T) {
home := t.TempDir()
attachments := filepath.Join(t.TempDir(), "attachments")
if err := WriteAgentCLIMCPConfig(AgentCLIOpenCode, HostAgentCLIHome(home), map[string]any{}, AgentCLIMCPOptions{ReadOnly: true, ReadableDirs: []string{attachments, " "}}); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join(home, ".config/opencode/opencode.json"))
if err != nil {
t.Fatal(err)
}
var doc struct {
Permission map[string]json.RawMessage `json:"permission"`
}
if err := json.Unmarshal(data, &doc); err != nil {
t.Fatal(err)
}
// OpenCode applies the last matching rule: the catch-all must come first.
want := `{"*":"deny",` + string(mustJSONString(t, filepath.Join(attachments, "*"))) + `:"allow"}`
if got := string(doc.Permission["external_directory"]); strings.Join(strings.Fields(got), "") != want {
t.Fatalf("external_directory = %s, want %s", got, want)
}
for _, tool := range []string{"edit", "bash", "webfetch", "task"} {
if got := string(doc.Permission[tool]); got != `"deny"` {
t.Fatalf("%s = %s, want deny", tool, got)
}
}
// Without readable directories everything outside stays denied, and LOOP
// invocations keep full access.
if err := WriteAgentCLIMCPConfig(AgentCLIOpenCode, HostAgentCLIHome(home), map[string]any{}, AgentCLIMCPOptions{ReadOnly: true}); err != nil {
t.Fatal(err)
}
data, _ = os.ReadFile(filepath.Join(home, ".config/opencode/opencode.json"))
if !strings.Contains(string(data), `"external_directory": "deny"`) {
t.Fatalf("read-only without dirs: %s", data)
}
if err := WriteAgentCLIMCPConfig(AgentCLIOpenCode, HostAgentCLIHome(home), map[string]any{}, AgentCLIMCPOptions{ReadableDirs: []string{attachments}}); err != nil {
t.Fatal(err)
}
data, _ = os.ReadFile(filepath.Join(home, ".config/opencode/opencode.json"))
if !strings.Contains(string(data), `"external_directory": "allow"`) {
t.Fatalf("LOOP permission: %s", data)
}
}

func mustJSONString(t *testing.T, s string) []byte {
t.Helper()
data, err := json.Marshal(s)
if err != nil {
t.Fatal(err)
}
return data
}

func TestWriteKimiChatAgent(t *testing.T) {
path := filepath.Join(t.TempDir(), "agent.md")
if err := WriteKimiChatAgent(path, "Be terse."); err != nil {
Expand Down
Loading