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
2 changes: 1 addition & 1 deletion internal/httpapi/assistant.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {
// Every conversation runs in its own CLI root; shared ones switch to the
// native session root below. The root's home also carries the skills.
cliRoot := assistantConversationRoot(ownerID, req.SessionID)
if err := runtime.ValidateConversationRoot(cliRoot); err != nil {
if err := validateConversationAssetRefresh(cliRoot, assistantConversationAssetHome(req.Model)); err != nil {
fail(409, err.Error())
return
}
Expand Down
3 changes: 1 addition & 2 deletions internal/httpapi/assistant_native_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"syscall"

"agentflow/internal/domain"
"agentflow/internal/runtime"
)

var (
Expand Down Expand Up @@ -57,7 +56,7 @@ func assistantMessageHashes(messages []assistantMessage) []string {

func openAssistantNativeSession(req assistantRequest, saved domain.AssistantSession, user domain.User, sourceRoot string) (*assistantNativeSession, error) {
root := assistantSharedSessionRoot(saved.ID)
if err := runtime.ValidateConversationRoot(root); err != nil {
if err := validateConversationAssetRefresh(root, assistantConversationAssetHome(req.Model)); err != nil {
return nil, err
}
if err := os.MkdirAll(root, 0o700); err != nil {
Expand Down
77 changes: 77 additions & 0 deletions internal/httpapi/assistant_native_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,83 @@ func TestSharedNativeSessionFencesAStaleWriter(t *testing.T) {
}
}

func TestNativeSessionResumesAfterAssetRefresh(t *testing.T) {
for _, tc := range []struct{ name, project string }{{"personal", ""}, {"shared", "workbench"}} {
t.Run(tc.name, func(t *testing.T) {
h, actor := workbenchFixture(t)
_, calls := nativeCLIRecorder(t)
const sessionID = "asset-refresh"
if err := h.repo.PutAssistantSession(actor.ID, domain.AssistantSession{ID: sessionID, ProjectID: tc.project}); err != nil {
t.Fatal(err)
}
skill := domain.SkillDefinition{ID: "review", Name: "Review", ProjectID: tc.project, Shared: true, Content: "Review the changes."}
if err := h.repo.PutSkill(skill); err != nil {
t.Fatal(err)
}
const attachmentContent = "Review notes"
attachment, err := saveWorkbenchImage(actor.ID, "notes.txt", "text/plain", []byte(attachmentContent), tc.project)
if err != nil {
t.Fatal(err)
}
send := func(message assistantMessage) {
t.Helper()
saved, _ := h.repo.AssistantSession(actor.ID, sessionID)
body, _ := json.Marshal(assistantRequest{ProjectID: tc.project, SessionID: sessionID, Messages: append(saved.Messages, message)})
c, w := workbenchContext(actor, "POST", "/api/assistant/chat", bytes.NewBuffer(body))
h.chat(c)
if w.Code != 200 {
t.Fatalf("chat status %d: %s", w.Code, w.Body.String())
}
}
send(assistantMessage{Role: "user", Content: "Use the review skill", Attachments: []domain.AssistantAttachment{attachment}})
root := assistantConversationRoot(actor.ID, sessionID)
if tc.project != "" {
root = assistantSharedSessionRoot(sessionID)
}
skillTree := filepath.Join(root, "home", ".codebuddy", "skills")
workspaceFile := filepath.Join(root, "ws", "installed.md")
if err := os.WriteFile(workspaceFile, []byte("Installed content"), 0o600); err != nil {
t.Fatal(err)
}
var links []string
for _, dir := range []string{skillTree, filepath.Join(root, "home", ".codebuddy", "agents"), filepath.Join(root, "attachments")} {
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
target, err := filepath.Rel(dir, workspaceFile)
if err != nil {
t.Fatal(err)
}
link := filepath.Join(dir, "installed.md")
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
links = append(links, link)
}

send(assistantMessage{Role: "user", Content: "Continue the review"})
got := calls()
if len(got) != 2 || got[0].flag("--session-id") == "" || got[1].flag("--resume") != got[0].flag("--session-id") {
t.Fatal("the next turn did not resume the native session")
}
for _, link := range links {
if _, err := os.Lstat(link); !os.IsNotExist(err) {
t.Fatalf("generated tree still contains %s: %v", link, err)
}
}
for name, want := range map[string]string{
workspaceFile: "Installed content",
filepath.Join(skillTree, skill.ID, "SKILL.md"): skill.Content,
filepath.Join(root, conversationAttachmentPath(attachment.ID, attachment.Name)): attachmentContent,
} {
if data, err := os.ReadFile(name); err != nil || !strings.Contains(string(data), want) {
t.Fatalf("asset %s has content %q: %v", name, data, err)
}
}
})
}
}

func TestSharedDirectChatExcludesOtherHandlersAndBackgroundGenerations(t *testing.T) {
h, a, b, _, session := sharedWorkbenchFixture(t)
entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
Expand Down
36 changes: 22 additions & 14 deletions internal/httpapi/assistant_subagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,24 @@ func subagentRolePrompt(prompt string) string {

var rolePromptPlaceholder = regexp.MustCompile(`\{\{[^{}]+\}\}`)

func assistantConversationAssetHome(model string) string {
engine, _ := assistantModelEngine(model)
configDir := assistantEngineConfigDir(engine)
switch {
case engine == runtime.AgentCLIPi:
configDir = ".pi/agent"
case engine == runtime.AgentCLIAntigravity:
configDir = ".gemini/config"
case runtime.IsAgentCLI(engine):
configDir = ".agents"
}
return path.Join("home", configDir)
}

func validateConversationAssetRefresh(root, assetHome string) error {
return runtime.ValidateConversationRoot(root, "attachments", path.Join(assetHome, "skills"), path.Join(assetHome, "agents"))
}

// writeConversationAssets rewrites the conversation's CLI home each turn:
// skills holds the project's own skills and the shared skills, plus those of
// its roles and the mentioned ones, and agents holds one subagent per role,
Expand All @@ -186,7 +204,8 @@ var rolePromptPlaceholder = regexp.MustCompile(`\{\{[^{}]+\}\}`)
// with no project, no shared skills and no mentioned roles gets empty
// directories.
func (h *assistantHandlers) writeConversationAssets(root string, req assistantRequest) error {
if err := runtime.ValidateConversationRoot(root); err != nil {
assetHome := assistantConversationAssetHome(req.Model)
if err := validateConversationAssetRefresh(root, assetHome); err != nil {
return err
}
if err := writeConversationAttachments(root, req); err != nil {
Expand Down Expand Up @@ -246,25 +265,14 @@ func (h *assistantHandlers) writeConversationAssets(root string, req assistantRe
skill.FileRefs = nil
add(skill, contents)
}
engine, _ := assistantModelEngine(req.Model)
home := filepath.Join(root, "home", assistantEngineConfigDir(engine))
if runtime.IsAgentCLI(engine) {
home = filepath.Join(root, "home", ".agents")
}
if engine == runtime.AgentCLIPi {
home = filepath.Join(root, "home", ".pi", "agent")
}
if engine == runtime.AgentCLIAntigravity {
home = filepath.Join(root, "home", ".gemini", "config")
}
writer := runtime.WriteInertSkillTree
if req.workspaceMode {
writer = runtime.WriteSkillTree
}
if _, err := writer(filepath.Join(home, "skills"), skills, files); err != nil {
if _, err := writer(filepath.Join(root, assetHome, "skills"), skills, files); err != nil {
return err
}
agents := filepath.Join(home, "agents")
agents := filepath.Join(root, assetHome, "agents")
if err := os.RemoveAll(agents); err != nil {
return err
}
Expand Down
8 changes: 6 additions & 2 deletions internal/runtime/conversation_assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
)

// Only inspect paths used by platform-side materialization. Native CLIs own
// their logs and caches (including debug/latest links); WalkDir never follows
// those links, and the platform does not read or write through them.
func ValidateConversationRoot(root string) error {
// Callers preparing to replace or discard generated asset trees can skip
// their old contents. The tree directories and their ancestors are checked.
func ValidateConversationRoot(root string, replacedAssetTrees ...string) error {
return filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
if os.IsNotExist(err) && path == root {
return nil
Expand All @@ -32,7 +35,8 @@ func ValidateConversationRoot(root string) error {
if entry.Type()&os.ModeSymlink != 0 {
return fmt.Errorf("会话状态包含符号链接,拒绝宿主访问:%s", path)
}
if entry.IsDir() && path == filepath.Join(root, "ws") {
replacingTree := slices.Contains(replacedAssetTrees, rel) && slices.Contains(conversationAssetTrees, rel)
if entry.IsDir() && (rel == "ws" || replacingTree) {
return filepath.SkipDir
}
return nil
Expand Down
51 changes: 51 additions & 0 deletions internal/runtime/conversation_assets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,52 @@ func TestConversationNativeCacheLinksDoNotBlockNextTurn(t *testing.T) {
}
}

func TestConversationAssetCleanupHandlesStaleLinks(t *testing.T) {
for _, operation := range []string{"resetAssets", "discard"} {
t.Run(operation, func(t *testing.T) {
dir := t.TempDir()
root := filepath.Join(dir, "conversation")
original := filepath.Join(dir, "original.md")
if err := os.WriteFile(original, []byte("Original asset"), 0o600); err != nil {
t.Fatal(err)
}
for _, tree := range conversationAssetTrees {
assetDir := filepath.Join(root, tree)
if err := os.MkdirAll(assetDir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.Symlink(original, filepath.Join(assetDir, "stale.md")); err != nil {
t.Fatal(err)
}
}

pool := &ConversationProcessPool{}
if _, err := pool.Handle(t.Context(), root, "", nil, ConversationProcessRequest{Operation: "prepare"}, nil); err != nil {
t.Fatalf("prepare failed with stale asset links: %v", err)
}
if _, err := pool.Handle(t.Context(), root, "", nil, ConversationProcessRequest{Operation: "sync"}, nil); err == nil {
t.Fatal("sync accepted links before asset cleanup")
}
if _, err := pool.Handle(t.Context(), root, "", nil, ConversationProcessRequest{Operation: operation, Transient: operation == "discard"}, nil); err != nil {
t.Fatalf("%s failed with stale asset links: %v", operation, err)
}
for _, tree := range conversationAssetTrees {
if _, err := os.Lstat(filepath.Join(root, tree)); !os.IsNotExist(err) {
t.Fatalf("%s did not remove generated tree %s: %v", operation, tree, err)
}
}
if operation == "discard" {
if _, err := os.Lstat(root); !os.IsNotExist(err) {
t.Fatalf("transient conversation root survived discard: %v", err)
}
}
if data, err := os.ReadFile(original); err != nil || string(data) != "Original asset" {
t.Fatalf("asset cleanup changed the link target: %q %v", data, err)
}
})
}
}

func TestConversationPlatformPathsRejectLinks(t *testing.T) {
paths := []string{"home", "ws", "attachments", "session.json", "session.lock", "codex-threads.json", "agent-cli-sessions.json", "native-approval.py", "current-settings.json", "home/tmp", "home/.codebuddy", "home/.config", "home/.config/opencode/plugins", "home/.agents/skills/x/run.sh"}
paths = append(paths, conversationAssetTrees...)
Expand All @@ -53,6 +99,11 @@ func TestConversationPlatformPathsRejectLinks(t *testing.T) {
if err := ValidateConversationRoot(root); err == nil {
t.Fatal("platform accepted a symlink on a materialization path")
}
if rel != "home/.agents/skills/x/run.sh" {
if err := ValidateConversationRoot(root, conversationAssetTrees...); err == nil {
t.Fatal("asset refresh accepted a symlink outside the disposable tree contents")
}
}
})
}
}
8 changes: 7 additions & 1 deletion internal/runtime/conversation_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,13 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st
if active {
return ConversationProcessResult{}, fmt.Errorf("会话原生进程仍在运行,不能替换资产或启动新进程")
}
if err = ValidateConversationRoot(root); err != nil {
var replacedAssetTrees []string
if req.Operation != "sync" {
// Prepare does not read generated files. Reset and transient discard
// remove whole trees without following their old entries.
replacedAssetTrees = conversationAssetTrees
}
if err = ValidateConversationRoot(root, replacedAssetTrees...); err != nil {
return ConversationProcessResult{}, err
}
if req.Operation == "discard" {
Expand Down
Loading