Skip to content
Merged
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
3 changes: 3 additions & 0 deletions internal/domain/runner_workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,9 @@ const (
// WorkspaceErrorTerminalActive: an exclusive human terminal holds the
// workspace; waiting does not help until the user closes it.
WorkspaceErrorTerminalActive = "workspace_terminal_active"
// WorkspaceErrorConversationState carries a safe, conversation-relative
// preparation error from the execution machine.
WorkspaceErrorConversationState = "conversation_state"
)

// WorkspaceRestoreStatus describes restoration separately from SOP execution.
Expand Down
24 changes: 18 additions & 6 deletions internal/httpapi/assistant.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ func (h *assistantHandlers) chat(c *gin.Context) {
sess.Notify = func(kind string, value any) {
if emit != nil {
emit(kind, value)
} else if event, ok := value.(assistantStreamEvent); kind == "thought" && ok {
activity.add(publicAssistantEvent(event, user))
}
}
sess.mu.Lock()
Expand Down Expand Up @@ -463,13 +465,20 @@ func (h *assistantHandlers) chat(c *gin.Context) {
}
c.JSON(status, payload)
}
failSetup := func(err error) {
status, _ := assistantGenerationFailure(modelCtx, err)
failure := assistantDiagnosticsFrom(modelCtx).fail(modelCtx, err, user)
fail(status, failure.Message)
}
var nativeSession *assistantNativeSession
// 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 {
fail(409, err.Error())
return
if !shared {
if _, err := runtime.ConversationSkillLinks(cliRoot); err != nil {
failSetup(err)
return
}
}
nativeContinuationReady := false
var turnUsage assistantTurnUsage
Expand Down Expand Up @@ -508,7 +517,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {
var err error
nativeSession, err = openAssistantNativeSession(req, saved, user, sourceRoot)
if err != nil {
fail(409, "共享会话缓存不可用或正在使用,请稍后重试")
failSetup(err)
return
}
defer nativeSession.Close()
Expand All @@ -521,7 +530,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {
turn = h.turnPrompt(req, sourceRoot, false)
}
if err = nativeSession.begin(); err != nil {
fail(500, "无法保存共享会话缓存")
failSetup(err)
return
}
cliRoot = nativeSession.root
Expand All @@ -545,12 +554,15 @@ func (h *assistantHandlers) chat(c *gin.Context) {
// drains output and lets each CLI commit tool results to its native
// journal before the next process is allowed to resume that journal.
restarted := false
reportSkillLinks := func(paths []string) {
reportRemovedConversationSkillLinks(ctx, u, paths, toolSession.Notify)
}
for switches := 0; switches < 8; switches++ {
if !resume {
workspaceRepositoryHash = ""
}
req.workspaceMode = toolSession.RuntimeMode == domain.AssistantModeWorkspace
if err := h.writeConversationAssets(cliRoot, req); err != nil {
if err := h.writeConversationAssets(cliRoot, req, reportSkillLinks); err != nil {
return "", err
}
mcp, settings, err := stageConversationToolFiles(cliRoot, toolFiles)
Expand Down
3 changes: 3 additions & 0 deletions internal/httpapi/assistant_diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ func (d *assistantDiagnosticsCollector) checkpointSnapshot(g domain.AssistantGen

func (d *assistantDiagnosticsCollector) fail(ctx context.Context, err error, user domain.User) domain.AssistantFailure {
f := classifyAssistantFailure(ctx, err)
if f.Code == "CONVERSATION_STATE_ERROR" {
f.Message = sanitizeAssistantDiagnostic(f.Message, user, 2048)
}
if d == nil {
return f
}
Expand Down
18 changes: 16 additions & 2 deletions internal/httpapi/assistant_failure.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,14 @@ func assistantCLIStreamFailure(line string) error {
func assistantGenerationFailure(ctx context.Context, err error) (int, string) {
failure := classifyAssistantFailure(ctx, err)
status := http.StatusBadGateway
if failure.Code == "EXECUTION_MACHINE_UNAVAILABLE" || failure.Code == "WORKSPACE_BOUND_ELSEWHERE" || failure.Code == "WORKSPACE_REBOUND" {
switch failure.Code {
case "SHARED_SESSION_BUSY":
status = http.StatusConflict
case "CONVERSATION_STATE_ERROR":
status = http.StatusInternalServerError
case "EXECUTION_MACHINE_UNAVAILABLE", "WORKSPACE_BOUND_ELSEWHERE", "WORKSPACE_REBOUND":
status = http.StatusServiceUnavailable
} else if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
case "EXECUTION_CANCELLED", "EXECUTION_TIMEOUT":
status = http.StatusGatewayTimeout
}
return status, failure.Message
Expand All @@ -94,6 +99,15 @@ func classifyAssistantFailure(ctx context.Context, err error) domain.AssistantFa
f.Code, f.Message = "EXECUTION_LIMIT", "AI 助手已达到执行轮数上限,未能完成回答,请重试"
return f
}
if errors.Is(err, errAssistantNativeBusy) {
f.Code, f.Phase, f.Message, f.Suggestion = "SHARED_SESSION_BUSY", "setup", errAssistantNativeBusy.Error(), "等待正在执行的请求结束后再发送消息。"
return f
}
var stateErr *runtime.ConversationStateError
if errors.As(err, &stateErr) {
f.Code, f.Phase, f.Message, f.Suggestion = "CONVERSATION_STATE_ERROR", "setup", stateErr.Error(), "请联系管理员检查提示中的会话路径。"
return f
}
if errors.Is(err, errAssistantExecutionUnavailable) {
f.Code, f.Phase, f.Message, f.Suggestion = "EXECUTION_MACHINE_UNAVAILABLE", "setup", "会话绑定的执行机器暂不可用,请等待原机器恢复后重试", "会话已固定在原执行机器上,请确认该 Runner 在线后再重试。"
return f
Expand Down
17 changes: 11 additions & 6 deletions internal/httpapi/assistant_native_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,22 @@ 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 := runtime.ConversationSkillLinks(root); err != nil {
return nil, err
}
if err := os.MkdirAll(root, 0o700); err != nil {
return nil, err
return nil, runtime.NewConversationStateError("创建共享会话目录", ".", err)
}
lock, err := os.OpenFile(filepath.Join(root, "session.lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
return nil, runtime.NewConversationStateError("打开共享会话锁", "session.lock", err)
}
if err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
_ = lock.Close()
if err == syscall.EWOULDBLOCK || err == syscall.EAGAIN {
return nil, errAssistantNativeBusy
}
return nil, err
return nil, runtime.NewConversationStateError("获取共享会话锁", "session.lock", err)
}
native := &assistantNativeSession{root: root, lock: lock}
if data, err := os.ReadFile(filepath.Join(root, "session.json")); err == nil {
Expand All @@ -81,7 +81,7 @@ func openAssistantNativeSession(req assistantRequest, saved domain.AssistantSess
}
} else if !os.IsNotExist(err) {
native.Close()
return nil, err
return nil, runtime.NewConversationStateError("读取共享会话缓存", "session.json", err)
}
// Model settings, mode, approval and selected assets can change without
// replacing the CLI journal. History edits explicitly bump its revision.
Expand Down Expand Up @@ -116,7 +116,12 @@ func (n *assistantNativeSession) Close() {
}
}

func (n *assistantNativeSession) writeCheckpoint() error {
func (n *assistantNativeSession) writeCheckpoint() (err error) {
defer func() {
if err != nil {
err = runtime.NewConversationStateError("写入共享会话缓存", "session.json", err)
}
}()
data, err := json.Marshal(n.checkpoint)
if err != nil {
return err
Expand Down
65 changes: 63 additions & 2 deletions internal/httpapi/assistant_native_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,12 +369,73 @@ func TestSharedNativeSessionFencesAStaleWriter(t *testing.T) {
t.Fatal(err)
}
defer writer.Close()
link := filepath.Join(writer.root, "home", ".agents", "skills", "waiting")
if err := os.MkdirAll(filepath.Dir(link), 0700); err != nil {
t.Fatal(err)
}
if err := os.Symlink("original", link); err != nil {
t.Fatal(err)
}
messages := append(append([]assistantMessage(nil), session.Messages...), assistantMessage{Role: "user", Content: "不能抢写"})
body, _ := json.Marshal(assistantRequest{ProjectID: session.ProjectID, RunID: session.RunID, SessionID: session.ID, Messages: messages})
c, w := workbenchContext(b, "POST", "/api/assistant/chat", bytes.NewBuffer(body))
(&assistantHandlers{deps: h.deps}).chat(c)
if w.Code != 409 || len(calls()) != 1 {
t.Fatalf("stale writer was not fenced: %d", w.Code)
if w.Code != 409 || len(calls()) != 1 || !strings.Contains(w.Body.String(), "SHARED_SESSION_BUSY") || !strings.Contains(w.Body.String(), "另一进程中生成") {
t.Fatalf("stale writer was not fenced or reported accurately: %d %s", w.Code, w.Body.String())
}
if target, err := os.Readlink(link); err != nil || target != "original" {
t.Fatalf("losing turn modified the locked conversation: %q %v", target, err)
}
}

func TestSharedNativeSessionContinuesAfterSkillInstallSymlink(t *testing.T) {
h, a, b, _, session := sharedWorkbenchFixture(t)
_, calls := nativeCLIRecorder(t)
session = sendNativeTurn(t, h, a, session, "安装技能")
root := assistantSharedSessionRoot(session.ID)
const skillPath = "home/.agents/skills/@publisher/design/SKILL.md"
const linkPath = "home/.agents/skills/design"
skill := filepath.Join(root, skillPath)
if err := os.MkdirAll(filepath.Dir(skill), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(skill, []byte("installed skill"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink("@publisher/design", filepath.Join(root, linkPath)); err != nil {
t.Fatal(err)
}
session = sendNativeTurn(t, h, b, session, "继续上次的工作")
recorded := calls()
if len(recorded) != 2 || recorded[1].flag("--resume") != recorded[0].flag("--session-id") {
t.Fatalf("turn did not resume the original native session: %+v", recorded)
}
if data, err := os.ReadFile(skill); err != nil || string(data) != "installed skill" {
t.Fatalf("skill files changed: %q %v", data, err)
}
reply := session.Messages[len(session.Messages)-1]
for _, event := range reply.Activity {
if event.Kind == "status" && strings.Contains(event.Text, linkPath) && strings.Contains(event.Text, "符号链接") {
return
}
}
t.Fatalf("turn did not record which link was removed: %+v", reply.Activity)
}

func TestSharedNativeSessionReportsCacheReadFailure(t *testing.T) {
h, a, _, _, session := sharedWorkbenchFixture(t)
_, calls := nativeCLIRecorder(t)
root := assistantSharedSessionRoot(session.ID)
if err := os.MkdirAll(filepath.Join(root, "session.json"), 0700); err != nil {
t.Fatal(err)
}
messages := append(session.Messages, assistantMessage{Role: "user", Content: "继续"})
body, _ := json.Marshal(assistantRequest{ProjectID: session.ProjectID, RunID: session.RunID, SessionID: session.ID, Messages: messages})
c, w := workbenchContext(a, "POST", "/api/assistant/chat", bytes.NewBuffer(body))
h.chat(c)
got := w.Body.String()
if w.Code != 500 || len(calls()) > 0 || !strings.Contains(got, "CONVERSATION_STATE_ERROR") || !strings.Contains(got, "读取共享会话缓存") || !strings.Contains(got, "session.json") || !strings.Contains(got, "is a directory") || strings.Contains(got, root) {
t.Fatalf("cache read failure lost its specific cause: %d %s", w.Code, got)
}
}

Expand Down
29 changes: 27 additions & 2 deletions internal/httpapi/assistant_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,14 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin
return runtime.ConversationProcessResult{}, fmt.Errorf("%w: %w", errAssistantExecutionUnavailable, err)
}
if response.Error != "" {
responseErr := errors.New(response.Error)
if response.Code == domain.WorkspaceErrorConversationState {
responseErr = &runtime.ConversationStateError{Message: response.Error}
}
if req.Operation == "start" {
return runtime.ConversationProcessResult{}, fmt.Errorf("%w: %s", runtime.ErrConversationNotStarted, response.Error)
return runtime.ConversationProcessResult{}, fmt.Errorf("%w: %w", runtime.ErrConversationNotStarted, responseErr)
}
return runtime.ConversationProcessResult{}, fmt.Errorf("%s", response.Error)
return runtime.ConversationProcessResult{}, responseErr
}
var result runtime.ConversationProcessResult
err = json.Unmarshal(response.Payload, &result)
Expand All @@ -213,6 +217,7 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin
if err != nil {
return "", err
}
reportRemovedConversationSkillLinks(ctx, s.User, prepared.RemovedSkillLinks, s.Notify)
if input, ok := command.Stdin.(*assistantLimitedImageInput); ok {
command, err = input.fit(command, root, prepared.Root)
if err != nil {
Expand Down Expand Up @@ -400,6 +405,26 @@ func assistantEngineBinary(kind string) string {
}
}

func reportRemovedConversationSkillLinks(ctx context.Context, user domain.User, paths []string, notify func(string, any)) {
if len(paths) == 0 {
return
}
const maxDisplayedPaths = 5
names := make([]string, 0, min(len(paths), maxDisplayedPaths))
for _, path := range paths[:min(len(paths), maxDisplayedPaths)] {
names = append(names, fmt.Sprintf("%q", truncateRunes(path, 250)))
}
summary := strings.Join(names, "、")
if len(paths) > maxDisplayedPaths {
summary += fmt.Sprintf(" 等 %d 项", len(paths))
}
message := fmt.Sprintf("技能目录不支持符号链接。已移除链接并继续执行(%s)。", summary)
assistantDiagnosticsFrom(ctx).platform("conversation.skill_links_removed", message, user)
if notify != nil {
notify("thought", assistantStreamEvent{Kind: "status", Text: sanitizeAssistantDiagnostic(message, user, 2048)})
}
}

// Synchronize generated configuration and selected assets, excluding native
// transcripts and the credentials written by the execution host.
func conversationInputFiles(root string) ([]runtime.ConversationFile, error) {
Expand Down
8 changes: 6 additions & 2 deletions internal/httpapi/assistant_subagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,14 @@ var rolePromptPlaceholder = regexp.MustCompile(`\{\{[^{}]+\}\}`)
// SKILL.md unless it is also the project's own, bound or mentioned. A turn
// 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 {
func (h *assistantHandlers) writeConversationAssets(root string, req assistantRequest, reportSkillLinks func([]string)) error {
removed, err := runtime.RemoveConversationSkillLinks(root)
if err != nil {
return err
}
if len(removed) > 0 && reportSkillLinks != nil {
reportSkillLinks(removed)
}
if err := writeConversationAttachments(root, req); err != nil {
return err
}
Expand Down
6 changes: 3 additions & 3 deletions internal/httpapi/assistant_subagents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func TestSkillMentionsAreScopedHintedAndWrittenToHome(t *testing.T) {
root := t.TempDir()
// Sharing installs the skill on a project turn that never mentions it.
plain := assistantRequest{ProjectID: "workbench", Messages: []assistantMessage{{Role: "user", Content: "写一下"}}}
if err := h.writeConversationAssets(root, plain); err != nil {
if err := h.writeConversationAssets(root, plain, nil); err != nil {
t.Fatal(err)
}
for _, name := range []string{"lint", "shareddoc"} {
Expand Down Expand Up @@ -257,7 +257,7 @@ func TestEverySharedSkillIsInstalledWithItsSkillMD(t *testing.T) {
req.skills = []domain.SkillDefinition{stored}
}
root := t.TempDir()
if err := h.writeConversationAssets(root, req); err != nil {
if err := h.writeConversationAssets(root, req, nil); err != nil {
t.Fatal(err)
}
dir := filepath.Join(root, "home", ".codebuddy", "skills")
Expand Down Expand Up @@ -320,7 +320,7 @@ func TestEverySharedSkillIsInstalledHoweverManyAreShared(t *testing.T) {
}
for _, project := range []string{"workbench", ""} {
root := t.TempDir()
if err := h.writeConversationAssets(root, assistantRequest{ProjectID: project}); err != nil {
if err := h.writeConversationAssets(root, assistantRequest{ProjectID: project}, nil); err != nil {
t.Fatal(err)
}
entries, err := os.ReadDir(filepath.Join(root, "home", ".codebuddy", "skills"))
Expand Down
8 changes: 7 additions & 1 deletion internal/runner/conversation.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"agentflow/internal/runtime"
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"regexp"
Expand Down Expand Up @@ -118,7 +119,12 @@ func (d *Daemon) conversationProcess(ctx context.Context, request domain.RunnerW
}
result, err := d.conversationProcesses.Handle(ctx, root, workspace, request.Sandbox, req, forward, factory)
if err != nil {
return runnerWorkspaceError(err)
response := runnerWorkspaceError(err)
var stateErr *runtime.ConversationStateError
if errors.As(err, &stateErr) {
response.Code = domain.WorkspaceErrorConversationState
}
return response
}
return runnerWorkspacePayload(result)
}
Expand Down
Loading
Loading