diff --git a/CHANGELOG.md b/CHANGELOG.md index 98415cbf..ad6ea0e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,6 +103,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `--dangerously-bypass-approvals-and-sandbox`, on the host. Resumed turns now use the first turn's choice, including `bypass_sandbox`, and keep the approvals for the MCP servers skill-up installed. +- Preserve text and tool event order within a Qwen session message. The final + message is the text after the last tool event, as for other engines, and a + message split around a tool call still counts as one turn. - Use prompt-file delivery for resumed Claude Code and Qoder turns when the prompt exceeds the inline limit or the target is Windows, preserving prompt delivery metadata and failing before execution if the file cannot be uploaded. diff --git a/internal/agent/qwen_code.go b/internal/agent/qwen_code.go index 782d45e4..e53a1297 100644 --- a/internal/agent/qwen_code.go +++ b/internal/agent/qwen_code.go @@ -258,6 +258,7 @@ func (a *QwenCodeAgent) buildSessionResult(ctx context.Context, rt Runtime, opts var trans transcript.Transcript var finalMsg string var inputTokens, outputTokens int + responses := -1 cleanupCtx, cleanupCancel := sessionCleanupContext(ctx) defer cleanupCancel() @@ -273,10 +274,11 @@ func (a *QwenCodeAgent) buildSessionResult(ctx context.Context, rt Runtime, opts generatedFiles, cleanupSession = withDownloadedSession( cleanupCtx, rt, opts.ArtifactDir, findQwenCodeSessionFile(cleanupCtx, rt), generatedFiles, func(artifactPath string) { - t, f, inTok, outTok := parseQwenSessionFile(artifactPath) + t, f, inTok, outTok, n := parseQwenSessionFile(artifactPath) if len(t) > 0 { trans = t finalMsg = f + responses = n } inputTokens, outputTokens = inTok, outTok }, @@ -298,12 +300,16 @@ func (a *QwenCodeAgent) buildSessionResult(ctx context.Context, rt Runtime, opts if finalMsg == "" { finalMsg = trans.FinalAssistantMessage() } + turns := responses + if turns < 0 { + turns = countTurns(trans) + } return &SessionResult{ Engine: a.Name(), ExitCode: result.ExitCode, DurationMs: time.Since(start).Milliseconds(), - Turns: countTurns(trans), + Turns: turns, InputTokens: inputTokens, OutputTokens: outputTokens, FinalMessage: finalMsg, @@ -375,13 +381,15 @@ type qwenUsageMetadata struct { } // parseQwenSessionFile reads qwen's chat JSONL and returns the transcript, the -// final assistant message, and high-water token counts. Token semantics follow -// the other agents: max input (promptTokenCount) and max output -// (candidatesTokenCount + thoughtsTokenCount) across assistant lines. -func parseQwenSessionFile(sf string) (trans transcript.Transcript, finalMsg string, inputTokens, outputTokens int) { //nolint:nonamedreturns // named returns document the four positional results +// final assistant message, high-water token counts, and the number of +// assistant lines with visible text. Token semantics follow the other agents: +// max input (promptTokenCount) and max output (candidatesTokenCount + +// thoughtsTokenCount) across assistant lines. The response count is taken per +// line because one line can split into several transcript entries. +func parseQwenSessionFile(sf string) (trans transcript.Transcript, finalMsg string, inputTokens, outputTokens, responses int) { //nolint:nonamedreturns // named returns document the five positional results file, err := os.Open(sf) if err != nil { - return nil, "", 0, 0 + return nil, "", 0, 0, 0 } defer file.Close() //nolint:errcheck @@ -409,6 +417,7 @@ func parseQwenSessionFile(sf string) (trans transcript.Transcript, finalMsg stri } if final := appendQwenMessageParts(&messages, ev, max(turn, 1)); final != "" { finalMsg = final + responses++ } if ev.Type == qwenTypeAssistant && ev.UsageMetadata != nil { inputTokens = max(inputTokens, ev.UsageMetadata.PromptTokenCount) @@ -419,20 +428,30 @@ func parseQwenSessionFile(sf string) (trans transcript.Transcript, finalMsg stri if finalMsg == "" { finalMsg = transcript.Transcript(messages).FinalAssistantMessage() } - return messages, finalMsg, inputTokens, outputTokens + return messages, finalMsg, inputTokens, outputTokens, responses } // appendQwenMessageParts projects one session line's parts into transcript // messages (text → user/assistant, functionCall → tool_call, functionResponse -// → tool_result) and returns the assistant text when the line is an assistant -// turn, so the caller can track the final message. +// → tool_result). For an assistant line it returns the text after the last +// tool event, which is the line's last transcript entry and therefore what +// Transcript.FinalAssistantMessage reports, so the caller can track the final +// message. func appendQwenMessageParts(messages *[]transcript.Message, ev qwenSessionEvent, turn int) string { role := transcript.RoleAssistant if ev.Type == qwenTypeUser { role = transcript.RoleUser } - var textParts []string + var pending []string + var last string + flushText := func() { + if len(pending) > 0 { + last = strings.Join(pending, "\n\n") + *messages = append(*messages, transcript.Message{Role: role, Content: last, Turn: turn}) + pending = nil + } + } for _, p := range ev.Message.Parts { switch { case p.Thought: @@ -441,6 +460,7 @@ func appendQwenMessageParts(messages *[]transcript.Message, ev qwenSessionEvent, // FinalMessage while preserving tool calls and the final answer. continue case p.FunctionCall != nil: + flushText() *messages = append(*messages, transcript.Message{ Role: transcript.RoleToolCall, ToolCall: &transcript.ToolCallInfo{ @@ -451,6 +471,7 @@ func appendQwenMessageParts(messages *[]transcript.Message, ev qwenSessionEvent, Turn: turn, }) case p.FunctionResponse != nil: + flushText() *messages = append(*messages, transcript.Message{ Role: transcript.RoleToolResult, ToolResult: &transcript.ToolResultInfo{ @@ -461,17 +482,13 @@ func appendQwenMessageParts(messages *[]transcript.Message, ev qwenSessionEvent, Turn: turn, }) case p.Text != "": - textParts = append(textParts, p.Text) + pending = append(pending, p.Text) } } - if len(textParts) == 0 { - return "" - } - content := strings.Join(textParts, "\n\n") - *messages = append(*messages, transcript.Message{Role: role, Content: content, Turn: turn}) + flushText() if role == transcript.RoleAssistant { - return content + return last } return "" } diff --git a/internal/agent/qwen_code_test.go b/internal/agent/qwen_code_test.go index 69883b73..a60050fc 100644 --- a/internal/agent/qwen_code_test.go +++ b/internal/agent/qwen_code_test.go @@ -292,7 +292,7 @@ func TestParseQwenSessionFile(t *testing.T) { t.Fatalf("write fixture: %v", err) } - trans, finalMsg, inTok, outTok := parseQwenSessionFile(path) + trans, finalMsg, inTok, outTok, _ := parseQwenSessionFile(path) if finalMsg != "There are two files: a.txt and b.txt." { t.Fatalf("unexpected final message: %q", finalMsg) @@ -325,6 +325,27 @@ func TestParseQwenSessionFile(t *testing.T) { } } +func TestQwenSessionPreservesTextAroundToolCalls(t *testing.T) { + t.Parallel() + path := filepath.Join(t.TempDir(), "session.jsonl") + line := `{"type":"assistant","message":{"parts":[{"text":"Checking."},{"functionCall":{"id":"tool1","name":"lookup"}},{"text":"Done."}]}}` + if err := os.WriteFile(path, []byte(line), 0o600); err != nil { + t.Fatal(err) + } + messages, final, _, _, responses := parseQwenSessionFile(path) + if len(messages) != 3 || messages[0].Content != "Checking." || messages[1].Role != transcript.RoleToolCall || messages[2].Content != "Done." { + t.Fatalf("unexpected transcript order: %#v", messages) + } + // The evaluator replaces FinalMessage with the transcript's last assistant + // entry, so the parser must report the same text. + if want := messages.FinalAssistantMessage(); final != "Done." || final != want { + t.Fatalf("final assistant text = %q, transcript final = %q, want %q", final, want, "Done.") + } + if responses != 1 { + t.Fatalf("one source response split around a tool call counted as %d", responses) + } +} + func TestParseQwenSessionFile_SkipsThoughtText(t *testing.T) { t.Parallel() @@ -341,11 +362,14 @@ func TestParseQwenSessionFile_SkipsThoughtText(t *testing.T) { t.Fatalf("write fixture: %v", err) } - trans, finalMsg, _, _ := parseQwenSessionFile(path) + trans, finalMsg, _, _, responses := parseQwenSessionFile(path) if finalMsg != "The workspace contains a.txt." { t.Fatalf("unexpected final message: %q", finalMsg) } + if responses != 1 { + t.Fatalf("thought-only and tool-only lines counted as responses: got %d, want 1", responses) + } if len(trans) != 4 { t.Fatalf("expected user, tool call, tool result, and final answer; got %d messages: %#v", len(trans), trans) } @@ -358,7 +382,7 @@ func TestParseQwenSessionFile_SkipsThoughtText(t *testing.T) { func TestParseQwenSessionFile_Missing(t *testing.T) { t.Parallel() - trans, finalMsg, inTok, outTok := parseQwenSessionFile(filepath.Join(t.TempDir(), "nope.jsonl")) + trans, finalMsg, inTok, outTok, _ := parseQwenSessionFile(filepath.Join(t.TempDir(), "nope.jsonl")) if trans != nil || finalMsg != "" || inTok != 0 || outTok != 0 { t.Fatalf("expected empty result for missing file, got %v %q %d %d", trans, finalMsg, inTok, outTok) }