diff --git a/internal/httpapi/agent_tool_session.go b/internal/httpapi/agent_tool_session.go index 0b501ed35..aa1a0bcfc 100644 --- a/internal/httpapi/agent_tool_session.go +++ b/internal/httpapi/agent_tool_session.go @@ -86,8 +86,11 @@ type AgentToolSession struct { workspaceRunID string workspaceMu sync.Mutex workspaceTurn *assistantWorkspaceTurn - SpaceID string - Surface string // entry of the turn; see sopDesigner + // The rest of this turn stays in platform mode after a startup failure. + workspaceStartFailed atomic.Bool + + SpaceID string + Surface string // entry of the turn; see sopDesigner // DesignerCanvas is the canvas a designer turn edits; operations in its // workflows_save draft are applied to it. DesignerCanvas json.RawMessage diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index e77886945..d21c5e49f 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -404,7 +404,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { sess.AttachmentOwners = req.attachmentOwners toolFiles = files defer sess.Close() - defer files.Cleanup() + defer func() { toolFiles.Cleanup() }() if req.RunID == "" && h.engine != nil { sess.workspaceTurn = newAssistantWorkspaceTurn(h.engine, cancelModel) if scope := assistantControlScopeFrom(modelCtx); scope.GenerationID != "" { @@ -511,6 +511,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { if generate == nil { resume := false var workspaceRepositoryHash string + var initialCheckpoint assistantNativeCheckpoint branch := false rewritten := false if saved, err := loadAssistantConversation(h.repo, assistantStorageOwner(h.repo, req.SessionID, user.ID), req.SessionID); err == nil { @@ -539,13 +540,11 @@ func (h *assistantHandlers) chat(c *gin.Context) { } defer nativeSession.Close() resume = nativeSession.resume - cliSessionID = nativeSession.checkpoint.SessionID - workspaceRepositoryHash = nativeSession.checkpoint.WorkspaceRepositoryHash - if resume { - turn = assistantIncrementalPrompt(req, nativeSession.checkpoint) - } else { - turn = h.turnPrompt(req, sourceRoot, false) - } + // begin records the submitted messages. Keep the preceding checkpoint + // for rebuilding this turn's input if the first phase cannot start. + initialCheckpoint = nativeSession.checkpoint + cliSessionID = initialCheckpoint.SessionID + workspaceRepositoryHash = initialCheckpoint.WorkspaceRepositoryHash if err = nativeSession.begin(); err != nil { failSetup(err) return @@ -564,7 +563,25 @@ func (h *assistantHandlers) chat(c *gin.Context) { resume = !state.Unstarted workspaceRepositoryHash = state.WorkspaceRepositoryHash } - turn = h.turnPrompt(req, sourceRoot, resume) + } + promptForTurn := func() string { + if nativeSession != nil && resume { + return assistantIncrementalPrompt(req, initialCheckpoint) + } + return h.turnPrompt(req, sourceRoot, resume) + } + turn = promptForTurn() + switchMode := func(mode string) error { + next, err := h.switchConversationProcessMode(toolSession, cliRoot, mode) + if err != nil { + return err + } + toolFiles.Cleanup() + toolFiles = next + if streaming { + emit("runtime_mode", map[string]string{"mode": mode, "workspaceRunId": toolSession.conversationWorkspace()}) + } + return nil } generate = func(ctx context.Context, prompt string, u domain.User) (string, error) { // A mode request completes its CLI phase normally. Waiting for exit @@ -587,13 +604,13 @@ func (h *assistantHandlers) chat(c *gin.Context) { return "", err } system := assistantSystemPromptForRequest(req, approvalMode) - prompt += conversationAttachmentNote(cliRoot, req, turnEngine) + phasePrompt := prompt + conversationAttachmentNote(cliRoot, req, turnEngine) var sentRepositoryHash string if req.workspaceMode { system = assistantWorkspaceSystemPrompt prefix := assistantWorkspaceSystemPrompt + "\n审批模式:" + approvalMode + "。\n" var repositoryPrompt string - repositoryPrompt, sentRepositoryHash, err = h.workspaceRepositoryPrompt(toolSession, cliRoot, workspaceRepositoryHash, len(prefix)+len(prompt)) + repositoryPrompt, sentRepositoryHash, err = h.workspaceRepositoryPrompt(toolSession, cliRoot, workspaceRepositoryHash, len(prefix)+len(phasePrompt)) if err != nil { return "", err } @@ -601,11 +618,14 @@ func (h *assistantHandlers) chat(c *gin.Context) { // The journal's catalogue is uncertain until the phase completes. workspaceRepositoryHash = "" } - prompt = prefix + repositoryPrompt + projectCredentialNote + prompt + phasePrompt = prefix + repositoryPrompt + projectCredentialNote + phasePrompt } else if !req.sopDesigner() { - prompt = assistantPlatformExecutionReminder + "\n" + projectCredentialNote + prompt + phasePrompt = assistantPlatformExecutionReminder + "\n" + projectCredentialNote + phasePrompt } - cliReq := assistantCLIRequest{Executor: req.Executor, Prompt: prompt, Model: cliModel, Effort: req.Effort, SessionID: cliSessionID, Resume: resume, UserID: u.ID, Native: true, MCPConfig: mcp, Settings: settings, SystemPrompt: system, SessionRoot: cliRoot, RunnerLogin: runnerLogin, OnUsage: func(usage domain.TokenUsage) { + if toolSession.workspaceStartFailed.Load() { + phasePrompt += "\n" + assistantWorkspaceFallbackPrompt + } + cliReq := assistantCLIRequest{Executor: req.Executor, Prompt: phasePrompt, Model: cliModel, Effort: req.Effort, SessionID: cliSessionID, Resume: resume, UserID: u.ID, Native: true, MCPConfig: mcp, Settings: settings, SystemPrompt: system, SessionRoot: cliRoot, RunnerLogin: runnerLogin, OnUsage: func(usage domain.TokenUsage) { turnUsage.add(domain.PriceScheduleExecutionUsage(replyModel, usage)) }, Workspace: req.workspaceMode, RemoteBinary: req.workspaceMode || toolSession.ExecutionRunnerID != "", Execute: h.conversationExecutor(toolSession, cliRoot)} cliReq.ImageInput = conversationHasImageAttachments(req) @@ -670,6 +690,27 @@ func (h *assistantHandlers) chat(c *gin.Context) { assistantDiagnosticsFrom(ctx).platform("cli.handoff_phase_error", "交接已开始,旧阶段异常结束:"+err.Error()+";继续交接", u) err = nil } + if req.workspaceMode && !progressed.Load() && assistantWorkspaceStartupFailed(ctx, err) { + toolSession.workspaceStartFailed.Store(true) + if err := switchMode(domain.AssistantModePlatform); err != nil { + return "", fmt.Errorf("回退平台模式失败:%w", err) + } + assistantDiagnosticsFrom(ctx).platform("cli.workspace_fallback", assistantWorkspaceFallbackStatus, u) + toolSession.Notify("thought", assistantStreamEvent{Kind: "status", Text: assistantWorkspaceFallbackStatus}) + req.workspaceMode = false + switch { + case !nativeContinuationReady: + prompt = promptForTurn() + case !resume: + prompt = h.freshPhasePrompt(req, sourceRoot, switches) + case switches > 0: + prompt = "沿用当前原生会话和已有的工具结果,先核对已执行的操作,避免重复执行。" + } + // Retry this phase with the same input and journal. In particular, + // a failed first phase has not sent its image inputs yet. + switches-- + continue + } if err != nil && resume && !restarted && !progressed.Load() && assistantResumeRecoverable(ctx, err) { // The native journal is missing or the provider rejected it // before this phase produced anything, so no tool ran. Start @@ -710,15 +751,9 @@ func (h *assistantHandlers) chat(c *gin.Context) { if ctx.Err() != nil { return "", ctx.Err() } - next, err := h.switchConversationProcessMode(toolSession, cliRoot, mode) - if err != nil { + if err := switchMode(mode); err != nil { return "", err } - toolFiles = next - defer next.Cleanup() - if streaming { - emit("runtime_mode", map[string]string{"mode": mode, "workspaceRunId": toolSession.conversationWorkspace()}) - } prompt = "内部控制信息,不向用户解释或复述:运行环境已切换为「" + mode + "」,当前原生会话及之前的工具结果全部保留。直接使用当前工具继续完成本轮用户请求,先核对已执行操作,避免重复执行。面向用户只说明任务进展和结果,不提交接、进程重启、工具注入或运行模式。" // Each phase may start over once: a journal that a new // process cannot resume must not fail the whole turn. diff --git a/internal/httpapi/assistant_resume_recovery.go b/internal/httpapi/assistant_resume_recovery.go index 50f9f14b5..dc48c9fe1 100644 --- a/internal/httpapi/assistant_resume_recovery.go +++ b/internal/httpapi/assistant_resume_recovery.go @@ -69,6 +69,17 @@ func assistantResumeRecoverable(ctx context.Context, err error) bool { return failure.Code == "MISSING_RESULT" || failure.Code == "CLI_EXIT_NONZERO" } +const assistantWorkspaceFallbackStatus = "工作区启动失败,已回到平台模式,继续本轮对话。" + +const assistantWorkspaceFallbackPrompt = "工作区启动失败。本轮请用平台工具继续处理用户请求,如实说明仍需工作区的步骤。后续轮次有需要时可重新打开工作区。" + +// Only retry in platform mode when the workspace CLI is known not to have +// run. A transport error can leave an active CLI on the execution machine. +func assistantWorkspaceStartupFailed(ctx context.Context, err error) bool { + return ctx.Err() == nil && errors.Is(err, runtime.ErrConversationNotStarted) && + !errors.Is(err, errAssistantExecutionUnavailable) && !errors.Is(err, errAssistantRunnerAccessRevoked) +} + // assistantHandoffOutlivesPhaseError reports whether a phase error should be // ignored because a mode handoff already succeeded in that phase. The old CLI // may end without type=result once it has nothing left to do; failing the diff --git a/internal/httpapi/assistant_resume_recovery_test.go b/internal/httpapi/assistant_resume_recovery_test.go index c20961874..773ef5a38 100644 --- a/internal/httpapi/assistant_resume_recovery_test.go +++ b/internal/httpapi/assistant_resume_recovery_test.go @@ -128,3 +128,25 @@ func TestPhaseProgressIgnoresStatusOnly(t *testing.T) { } } } + +func TestWorkspaceFallbackRequiresConfirmedStartFailure(t *testing.T) { + ctx := context.Background() + timeout := fmt.Errorf("%w: %w", runtime.ErrConversationNotStarted, context.DeadlineExceeded) + if !assistantWorkspaceStartupFailed(ctx, timeout) { + t.Fatal("a CLI setup deadline must allow recovery while the turn is live") + } + for _, err := range []error{ + context.DeadlineExceeded, + fmt.Errorf("%w: %w", runtime.ErrConversationNotStarted, errAssistantExecutionUnavailable), + fmt.Errorf("%w: %w", runtime.ErrConversationNotStarted, errAssistantRunnerAccessRevoked), + } { + if assistantWorkspaceStartupFailed(ctx, err) { + t.Fatalf("attempted fallback for %v", err) + } + } + canceled, cancel := context.WithCancel(ctx) + cancel() + if assistantWorkspaceStartupFailed(canceled, timeout) { + t.Fatal("a stopped turn must not launch a platform CLI") + } +} diff --git a/internal/httpapi/assistant_workspace_fallback_test.go b/internal/httpapi/assistant_workspace_fallback_test.go new file mode 100644 index 000000000..ff4c5721c --- /dev/null +++ b/internal/httpapi/assistant_workspace_fallback_test.go @@ -0,0 +1,191 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "os" + "slices" + "strings" + "sync" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/engine" + "agentflow/internal/runtime" +) + +func TestConversationWorkspaceStartupFailureFallsBackToPlatform(t *testing.T) { + for _, tc := range []struct { + name string + startError string + fromHandoff bool + }{ + {"Docker mount failure during handoff", "docker start: invalid mount configuration", true}, + {"CLI install timeout in saved workspace", "准备 codebuddy 原生CLI失败:context deadline exceeded", false}, + } { + t.Run(tc.name, func(t *testing.T) { + h, user := workbenchFixture(t) + h.sourceRoot = t.TempDir() + h.engine = engine.New(h.repo, runtime.NewManager(t.TempDir())) + h.runnerControls = quietRunnerHub() + const chatID = "workspace-fallback" + const workspaceID = "bound-workspace" + const runnerID = "workspace-runner" + const question = "请查询当前项目的需求" + target := domain.AssistantExecutionTarget{Pool: domain.ExecutionModeRunner, RunnerID: runnerID} + if err := h.repo.PutRunner(domain.Runner{ID: runnerID, OwnerUserID: user.ID, Status: domain.RunnerStatusOnline, RunnerVersion: domain.RunnerVersionConversationCLI}); err != nil { + t.Fatal(err) + } + if err := h.repo.SetRunnerSharedProjects(runnerID, user.ID, []string{"workbench"}); err != nil { + t.Fatal(err) + } + run := domain.Run{ + ID: workspaceID, Kind: domain.RunKindWorkspace, Status: "waiting", + ExecutionContext: domain.TelemetryContext{ + ProjectID: "workbench", ExecutionMode: target.Pool, ExecutionRunnerID: runnerID, ResponsibleUserID: user.ID, + }, + WorkflowSnapshot: domain.WorkflowDefinition{ + ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "docker", + SandboxSnapshot: &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{ID: "docker", Driver: domain.SandboxDriverDocker}}, + }, + } + if err := h.repo.PutRun(run); err != nil { + t.Fatal(err) + } + conversation := domain.AssistantSession{ID: chatID, ProjectID: "workbench", WorkspaceRunID: workspaceID, ExecutionTarget: &target} + if !tc.fromHandoff { + conversation.Messages = []assistantMessage{{Role: "user", Content: "旧问题"}, {Role: "assistant", Content: "旧回复"}} + } + if err := h.repo.PutAssistantSession(user.ID, conversation); err != nil { + t.Fatal(err) + } + if !tc.fromHandoff { + if err := h.repo.SetAssistantRuntimeMode(user.ID, chatID, conversation.ProjectID, domain.AssistantModeWorkspace); err != nil { + t.Fatal(err) + } + old := assistantNativeSession{root: assistantSharedSessionRoot(chatID), checkpoint: assistantNativeCheckpoint{ + SessionID: "previous-native-session", Ready: true, MessageHashes: assistantMessageHashes(conversation.Messages), + }} + if err := os.MkdirAll(old.root, 0o700); err != nil { + t.Fatal(err) + } + if err := old.writeCheckpoint(); err != nil { + t.Fatal(err) + } + } + h.engine.WorkspaceCheckpointTransport = func(_ context.Context, _ domain.Run, req domain.RunnerWorkspaceRequest) (domain.RunnerWorkspaceResponse, error) { + if req.Operation == domain.RunnerWorkspaceOperationPrepare { + return domain.RunnerWorkspaceResponse{Status: 200}, nil + } + return domain.RunnerWorkspaceResponse{Status: 404, Error: "no remote workspace files in fixture"}, nil + } + t.Cleanup(func() { waitWorkspaceCheckpointSettled(t, h.repo, workspaceID) }) + + type cliStart struct { + workspace string + request runtime.ConversationProcessRequest + } + var mu sync.Mutex + var starts []cliStart + fakeRunnerConnection(t, h.runnerControls, runnerID, func(envelope domain.RunnerWorkspaceRequest) domain.RunnerWorkspaceResponse { + var req runtime.ConversationProcessRequest + if err := json.Unmarshal(envelope.Conversation, &req); err != nil { + return domain.RunnerWorkspaceResponse{Status: 400, Error: err.Error()} + } + mu.Lock() + defer mu.Unlock() + result := runtime.ConversationProcessResult{ID: req.ID, Root: req.SourceRoot} + switch req.Operation { + case "start": + starts = append(starts, cliStart{workspace: envelope.RunID, request: req}) + if envelope.RunID != "" { + return domain.RunnerWorkspaceResponse{Status: 409, Error: tc.startError} + } + s, ok := agentToolSessions.get(req.Token) + if !ok { + t.Error("platform phase has no tool session") + break + } + if tc.fromHandoff && len(starts) == 1 { + // The workspace-open tool has prepared the existing binding. + s.requestMode(domain.AssistantModeWorkspace) + break + } + gateway := &agentToolGateway{deps: h.deps} + _, err := gateway.openConversationWorkspace(context.Background(), s, nil) + if err == nil || err.Error() != assistantWorkspaceFallbackPrompt { + t.Errorf("fallback phase allowed another workspace handoff: %v", err) + } + case "poll": + reply := `{"type":"result","result":"已查询项目需求。"}` + if tc.fromHandoff && len(starts) == 1 { + reply = `{"type":"result","result":"好的。"}` + } + result.Done = true + result.Sequence = 1 + result.Events = []domain.TelemetryEvent{{Name: "process.stdout", Message: reply}} + } + payload, _ := json.Marshal(result) + return domain.RunnerWorkspaceResponse{Status: 200, Payload: payload} + }) + body, _ := json.Marshal(assistantRequest{ + ProjectID: conversation.ProjectID, SessionID: chatID, + Messages: append(conversation.Messages, assistantMessage{Role: "user", Content: question}), + }) + c, response := workbenchContext(user, "POST", "/api/assistant/generations", bytes.NewBuffer(body)) + h.startGeneration(c) + if response.Code != 202 { + t.Fatalf("start generation: %d %s", response.Code, response.Body.String()) + } + g := waitGeneration(t, h, user.ID, chatID, func(g domain.AssistantGeneration) bool { return g.Status != "" && g.Status != "running" }) + if g.Status != "completed" || g.RuntimeMode != domain.AssistantModePlatform || g.WorkspaceRunID != workspaceID || + !strings.Contains(string(g.Reply), "已查询项目需求。") { + t.Fatalf("generation did not continue in platform mode: %+v", g) + } + if !slices.ContainsFunc(g.Events, func(event domain.AssistantGenerationEvent) bool { + return bytes.Contains(event.Data, []byte(assistantWorkspaceFallbackStatus)) + }) { + t.Fatal("missing fallback notice in the generation stream") + } + saved, _ := h.repo.AssistantSession(user.ID, chatID) + if saved.Mode() != domain.AssistantModePlatform || saved.WorkspaceRunID != workspaceID || saved.Execution() != target || + len(saved.Messages) != len(conversation.Messages)+2 || saved.Messages[len(saved.Messages)-2].Content != question { + t.Fatalf("fallback did not preserve the conversation: %+v", saved) + } + + mu.Lock() + defer mu.Unlock() + want := []string{workspaceID, ""} + if tc.fromHandoff { + want = append([]string{""}, want...) + } + if len(starts) != len(want) { + t.Fatalf("started %d phases, want %d", len(starts), len(want)) + } + for i, phase := range starts { + if phase.workspace != want[i] { + t.Fatalf("phase %d used workspace %q, want %q", i, phase.workspace, want[i]) + } + } + failed, fallback := starts[len(starts)-2].request, starts[len(starts)-1].request + resume := func(req runtime.ConversationProcessRequest) string { + args := req.Command.Argv + if i := slices.Index(args, "--resume"); i >= 0 && i+1 < len(args) { + return args[i+1] + } + return "" + } + if resume(failed) == "" || resume(fallback) != resume(failed) || fallback.Token == failed.Token { + t.Fatal("fallback must resume the same CLI journal with a fresh tool token") + } + prompt := fallback.Command.Argv[len(fallback.Command.Argv)-1] + if !strings.Contains(prompt, assistantWorkspaceFallbackPrompt) || strings.Contains(prompt, assistantWorkspaceSystemPrompt) { + t.Fatal("fallback received stale workspace instructions") + } + if tc.fromHandoff == strings.Contains(prompt, question) { + t.Errorf("unexpected user prompt replay with handoff=%t", tc.fromHandoff) + } + }) + } +} diff --git a/internal/httpapi/assistant_workspace_open.go b/internal/httpapi/assistant_workspace_open.go index 549c77ad8..b844004c8 100644 --- a/internal/httpapi/assistant_workspace_open.go +++ b/internal/httpapi/assistant_workspace_open.go @@ -226,6 +226,9 @@ func parseWorkspaceOpenChoice(args map[string]any) (workspaceOpenChoice, error) // and hands the CLI over to it. A task conversation enters its task's // workspace once the SOP has stopped. func (h *agentToolGateway) openConversationWorkspace(ctx context.Context, s *AgentToolSession, args map[string]any) (string, error) { + if s.workspaceStartFailed.Load() { + return "", errors.New(assistantWorkspaceFallbackPrompt) + } choice, err := parseWorkspaceOpenChoice(args) if err != nil { return "", err diff --git a/internal/runtime/sandbox_docker.go b/internal/runtime/sandbox_docker.go index c47ab7223..a835e2cd2 100644 --- a/internal/runtime/sandbox_docker.go +++ b/internal/runtime/sandbox_docker.go @@ -141,7 +141,7 @@ func DockerReady() bool { func (s *dockerSandbox) Exec(ctx context.Context, command CommandSpec, sink EventSink) (string, error) { if err := s.ensureStarted(ctx); err != nil { - return "", err + return "", fmt.Errorf("%w: %w", errProcessNotStarted, err) } s.execGate.RLock() out, err := s.execOnce(ctx, command, sink)