diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index b696a0e3..bb28b36d 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -551,7 +551,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { } else { prompt = assistantPlatformExecutionReminder + "\n" + prompt } - 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: turnUsage.add, Workspace: req.workspaceMode, RemoteBinary: req.workspaceMode || toolSession.ExecutionRunnerID != "", Execute: h.conversationExecutor(toolSession, cliRoot)} + 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: turnUsage.add, Workspace: req.workspaceMode, RemoteBinary: req.workspaceMode || toolSession.ExecutionRunnerID != "", Execute: h.conversationExecutor(toolSession, cliRoot), TerminalSession: toolSession} persistAttempt := func(unstarted bool) error { if nativeSession != nil { nativeSession.checkpoint.Unstarted = unstarted @@ -1465,6 +1465,9 @@ type assistantCLIRequest struct { ReviewOnly bool Native bool MCPConfig, Settings string + // TerminalSession owns the reply whose commit deliberately stops this CLI. + // Review and helper invocations must leave it nil. + TerminalSession *AgentToolSession // OnUsage receives the usage of this CLI invocation once its result event // reports one; the result event covers only this process, not the session. OnUsage func(domain.TokenUsage) @@ -1484,6 +1487,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U engineModel = "" } attempt := assistantDiagnosticsFrom(ctx).begin(engine, engineModel, req.Resume, user) + if attempt != nil { + attempt.terminalSession = req.TerminalSession + } defer func() { attempt.finish(returnedErr) }() if engine != assistantEngineCodeBuddy && (req.ReportOnly || (!req.Native && !req.ReviewOnly)) { return "", "", errAssistantEngineUnsupported diff --git a/internal/httpapi/assistant_diagnostic_terminal_test.go b/internal/httpapi/assistant_diagnostic_terminal_test.go new file mode 100644 index 00000000..38cffcc7 --- /dev/null +++ b/internal/httpapi/assistant_diagnostic_terminal_test.go @@ -0,0 +1,127 @@ +package httpapi + +import ( + "bytes" + "context" + "errors" + "testing" + "time" + + "agentflow/internal/domain" + "agentflow/internal/runtime" +) + +func TestAssistantDiagnosticTerminalCommitDistinguishesCancellation(t *testing.T) { + for _, tt := range []struct { + name string + commit bool + err error + wantState string + }{ + {"terminal cleanup", true, context.Canceled, "completed"}, + {"external cancellation", false, context.Canceled, "cancelled"}, + {"deadline", false, context.DeadlineExceeded, "failed"}, + {"unrelated failure after commit", true, errors.New("provider failed"), "failed"}, + } { + t.Run(tt.name, func(t *testing.T) { + g := domain.AssistantGeneration{ID: tt.name, Status: "running", StartedAt: time.Now().UTC()} + d := newAssistantDiagnosticsCollector(g) + ctx, cancel := context.WithCancel(context.WithValue(context.Background(), assistantDiagnosticsKey{}, d)) + defer cancel() + attempt := d.begin("codebuddy", "test-model", false, domain.User{}) + session := &AgentToolSession{ctx: ctx, Final: make(chan AgentTerminalResult, 1), CancelModel: cancel} + attempt.terminalSession = session + if tt.commit { + if err := session.commitFinal(AgentTerminalResult{Kind: AgentTerminalAssistant, Assistant: &assistantReply{Message: "Done"}}); err != nil { + t.Fatal(err) + } + if ctx.Err() != context.Canceled { + t.Fatal("terminal commit did not cancel the model") + } + } else { + cancel() + } + attempt.finish(tt.err) + report := d.snapshot(g) + got := report.Attempts[0] + if got.Status != tt.wantState || got.FinishedAt == nil { + t.Fatalf("attempt outcome = %+v, want %s", got, tt.wantState) + } + if tt.wantState == "completed" && got.Error != "" { + t.Fatalf("normal terminal cleanup recorded an error: %s", got.Error) + } + if tt.wantState != "completed" && got.Error == "" { + t.Fatal("lost real failure or cancellation evidence") + } + last := report.Timeline[len(report.Timeline)-1] + if last.Kind != "cli."+tt.wantState { + t.Fatalf("timeline outcome = %+v", last) + } + }) + } +} + +func TestAssistantDiagnosticTerminalReplyPersistsCompletedGeneration(t *testing.T) { + h, user := workbenchFixture(t) + const sessionID = "terminal-completed-diagnostic" + root := t.TempDir() + h.generate = func(ctx context.Context, prompt string, user domain.User) (string, error) { + session := assistantToolSessionForChat(sessionID) + if session == nil { + return "", errors.New("missing assistant tool session") + } + raw, _, err := runAssistantCLI(ctx, assistantCLIRequest{ + Prompt: prompt, SessionRoot: root, Native: true, RemoteBinary: true, TerminalSession: session, + Execute: func(ctx context.Context, _ string, _ runtime.CommandSpec, _ runtime.RunCredentials, _ runtime.EventSink) (string, error) { + session := assistantToolSessionForChat(sessionID) + if session == nil { + return "", errors.New("missing assistant tool session") + } + if err := session.commitFinal(AgentTerminalResult{Kind: AgentTerminalAssistant, Assistant: &assistantReply{Message: "已完成需求分析"}}); err != nil { + return "", err + } + return "", ctx.Err() + }, + }, user, nil) + return raw, err + } + c, rec := workbenchContext(user, "POST", "/api/assistant/generations", bytes.NewBufferString(`{"projectId":"workbench","sessionId":"`+sessionID+`","messages":[{"role":"user","content":"分析需求"}]}`)) + h.startGeneration(c) + if rec.Code != 202 { + t.Fatalf("start: %d %s", rec.Code, rec.Body.String()) + } + g := waitGeneration(t, h, user.ID, sessionID, func(g domain.AssistantGeneration) bool { return g.Status != "running" }) + report, ok := h.repo.AssistantDiagnostics(user.ID, sessionID, g.ID) + if !ok || g.Status != "completed" || report.Status != "completed" || report.Error != "" || len(report.Attempts) != 1 { + t.Fatalf("terminal reply did not persist a completed diagnostic: generation=%+v report=%+v", g, report) + } + if report.Attempts[0].Status != "completed" || report.Attempts[0].Error != "" { + t.Fatalf("successful terminal reply recorded a cancelled attempt: %+v", report.Attempts[0]) + } +} + +func TestAssistantDiagnosticTerminalCommitOnlyCompletesActiveAttempt(t *testing.T) { + g := domain.AssistantGeneration{ID: "terminal-attempts", Status: "running", StartedAt: time.Now().UTC()} + d := newAssistantDiagnosticsCollector(g) + ctx, cancel := context.WithCancel(context.WithValue(context.Background(), assistantDiagnosticsKey{}, d)) + defer cancel() + previous := d.begin("codebuddy", "test-model", false, domain.User{}) + previous.finish(context.Canceled) + active := d.begin("codebuddy", "test-model", true, domain.User{}) + review := d.begin("codebuddy", "review-model", false, domain.User{}) + session := &AgentToolSession{ctx: ctx, Final: make(chan AgentTerminalResult, 1), CancelModel: cancel} + active.terminalSession = session + if err := session.commitFinal(AgentTerminalResult{Kind: AgentTerminalAssistant, Assistant: &assistantReply{Message: "Done"}}); err != nil { + t.Fatal(err) + } + active.finish(context.Canceled) + review.finish(context.Canceled) + later := d.begin("codebuddy", "test-model", true, domain.User{}) + later.finish(context.Canceled) + report := d.snapshot(g) + for i, want := range []string{"cancelled", "completed", "cancelled", "cancelled"} { + if report.Attempts[i].Status != want { + t.Fatalf("attempt %d status = %s, want %s", i, report.Attempts[i].Status, want) + } + } +} diff --git a/internal/httpapi/assistant_diagnostics.go b/internal/httpapi/assistant_diagnostics.go index e40530b3..761149a2 100644 --- a/internal/httpapi/assistant_diagnostics.go +++ b/internal/httpapi/assistant_diagnostics.go @@ -162,6 +162,9 @@ type assistantDiagnosticAttempt struct { d *assistantDiagnosticsCollector id string user domain.User + // Only the CLI serving this session may treat its terminal cancellation + // as completion. Concurrent approval-review attempts have no such owner. + terminalSession *AgentToolSession } func (d *assistantDiagnosticsCollector) termination() *domain.AssistantDiagnosticTermination { @@ -231,6 +234,12 @@ func (a *assistantDiagnosticAttempt) phase(phase string) { func (a *assistantDiagnosticAttempt) finish(err error) { a.update(func(attempt *domain.AssistantCLIAttempt) { + if errors.Is(err, context.Canceled) && a.terminalSession.finished() { + // The accepted terminal result ends the model process by design. + // Other attempts and non-cancellation failures keep their outcome. + a.d.appendTimelineLocked(domain.AssistantDiagnosticEvent{Source: "platform", Kind: "cli.terminal_committed", AttemptID: a.id, Phase: attempt.Phase}) + err = nil + } now := time.Now().UTC() attempt.FinishedAt = &now attempt.Status = "completed" diff --git a/internal/httpapi/assistant_notification_report.go b/internal/httpapi/assistant_notification_report.go index aaf39210..e9d87cc8 100644 --- a/internal/httpapi/assistant_notification_report.go +++ b/internal/httpapi/assistant_notification_report.go @@ -37,7 +37,7 @@ func (h *assistantHandlers) generateReport(ctx context.Context, run domain.Run, generate := h.generate if generate == nil { generate = func(callCtx context.Context, input string, u domain.User) (string, error) { - raw, _, err := runAssistantCLI(callCtx, assistantCLIRequest{Prompt: input, Model: model, UserID: u.ID, ReportOnly: true, Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings, SystemPrompt: system}, u, nil) + raw, _, err := runAssistantCLI(callCtx, assistantCLIRequest{Prompt: input, Model: model, UserID: u.ID, ReportOnly: true, Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings, SystemPrompt: system, TerminalSession: session}, u, nil) return raw, err } } diff --git a/internal/httpapi/bot_interactions.go b/internal/httpapi/bot_interactions.go index c48d0b06..ab25e1dd 100644 --- a/internal/httpapi/bot_interactions.go +++ b/internal/httpapi/bot_interactions.go @@ -100,7 +100,7 @@ func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.Not cliSessionID := newAssistantSessionID() resume := false generate = func(callCtx context.Context, prompt string, u domain.User) (string, error) { - raw, _, err := runAssistantCLI(callCtx, assistantCLIRequest{Prompt: prompt, Model: model, SessionID: cliSessionID, Resume: resume, UserID: u.ID, Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings, SystemPrompt: assistantSystemPromptForMode(AssistantApprovalAuto)}, u, func(ev assistantStreamEvent) { + raw, _, err := runAssistantCLI(callCtx, assistantCLIRequest{Prompt: prompt, Model: model, SessionID: cliSessionID, Resume: resume, UserID: u.ID, Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings, SystemPrompt: assistantSystemPromptForMode(AssistantApprovalAuto), TerminalSession: session}, u, func(ev assistantStreamEvent) { switch ev.Kind { case "tool": if strings.Contains(ev.Tool, "submit_assistant_reply") {