From 8773f5fd21e52fa66a74b09d7d8a34e564f23fa8 Mon Sep 17 00:00:00 2001 From: karanb192 Date: Sat, 28 Nov 2026 08:38:04 +0530 Subject: [PATCH 1/2] fix(qwen): preserve text order around transcript tool calls --- CHANGELOG.md | 1 + internal/agent/qwen_code.go | 18 ++++++++++++------ internal/agent/qwen_code_test.go | 16 ++++++++++++++++ 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98415cbf..6c57aae7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,6 +103,7 @@ 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. - 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..57f06a39 100644 --- a/internal/agent/qwen_code.go +++ b/internal/agent/qwen_code.go @@ -433,6 +433,14 @@ func appendQwenMessageParts(messages *[]transcript.Message, ev qwenSessionEvent, } var textParts []string + emitted := 0 + flushText := func() { + if emitted < len(textParts) { + content := strings.Join(textParts[emitted:], "\n\n") + *messages = append(*messages, transcript.Message{Role: role, Content: content, Turn: turn}) + emitted = len(textParts) + } + } for _, p := range ev.Message.Parts { switch { case p.Thought: @@ -441,6 +449,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 +460,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{ @@ -465,13 +475,9 @@ func appendQwenMessageParts(messages *[]transcript.Message, ev qwenSessionEvent, } } - 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 strings.Join(textParts, "\n\n") } return "" } diff --git a/internal/agent/qwen_code_test.go b/internal/agent/qwen_code_test.go index 69883b73..d5ddfe58 100644 --- a/internal/agent/qwen_code_test.go +++ b/internal/agent/qwen_code_test.go @@ -325,6 +325,22 @@ 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, _, _ := 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) + } + if final != "Checking.\n\nDone." { + t.Fatalf("final assistant text = %q", final) + } +} + func TestParseQwenSessionFile_SkipsThoughtText(t *testing.T) { t.Parallel() From b33689492c2bbefbc0f36cee8eda4b732d8d4bea Mon Sep 17 00:00:00 2001 From: Karan Bansal Date: Mon, 30 Nov 2026 08:54:04 +0530 Subject: [PATCH 2/2] fix(qwen): count split responses once and match the final message Splitting a session line around a tool call gave it several assistant transcript entries. countTurns counted each one, so a single response raised turns and turns_executed. Count assistant lines with visible text in the parser instead, as before the split. The parser also returned the joined text of the line as the final message, while the evaluator replaces FinalMessage with the transcript's last assistant entry. Return the text after the last tool event, so both agree and match the other engines. --- CHANGELOG.md | 4 ++- internal/agent/qwen_code.go | 47 ++++++++++++++++++++------------ internal/agent/qwen_code_test.go | 20 ++++++++++---- 3 files changed, 46 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c57aae7..ad6ea0e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,7 +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. +- 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 57f06a39..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,26 +428,28 @@ 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 - emitted := 0 + var pending []string + var last string flushText := func() { - if emitted < len(textParts) { - content := strings.Join(textParts[emitted:], "\n\n") - *messages = append(*messages, transcript.Message{Role: role, Content: content, Turn: turn}) - emitted = len(textParts) + 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 { @@ -471,13 +482,13 @@ func appendQwenMessageParts(messages *[]transcript.Message, ev qwenSessionEvent, Turn: turn, }) case p.Text != "": - textParts = append(textParts, p.Text) + pending = append(pending, p.Text) } } flushText() if role == transcript.RoleAssistant { - return strings.Join(textParts, "\n\n") + return last } return "" } diff --git a/internal/agent/qwen_code_test.go b/internal/agent/qwen_code_test.go index d5ddfe58..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) @@ -332,12 +332,17 @@ func TestQwenSessionPreservesTextAroundToolCalls(t *testing.T) { if err := os.WriteFile(path, []byte(line), 0o600); err != nil { t.Fatal(err) } - messages, final, _, _ := parseQwenSessionFile(path) + 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) } - if final != "Checking.\n\nDone." { - t.Fatalf("final assistant text = %q", final) + // 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) } } @@ -357,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) } @@ -374,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) }