diff --git a/frontend/src/composables/useChatStreamHandler.test.mjs b/frontend/src/composables/useChatStreamHandler.test.mjs index afc21ecf..bf7479b5 100644 --- a/frontend/src/composables/useChatStreamHandler.test.mjs +++ b/frontend/src/composables/useChatStreamHandler.test.mjs @@ -11,3 +11,8 @@ test('failed tool results keep stdout/output instead of replacing it with the sh /toolCallEvent\.output = success\s*\?[\s\S]*dataPayload\.error/, ) }) + +test('later tool_call events merge arguments onto the same pending card', () => { + assert.match(source, /function mergeToolCallArguments/) + assert.match(source, /toolCallEvent\.arguments = mergeToolCallArguments\(toolCallEvent\.arguments, incomingArguments\)/) +}) diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.ts index d591a38d..46bd29b6 100644 --- a/frontend/src/composables/useChatStreamHandler.ts +++ b/frontend/src/composables/useChatStreamHandler.ts @@ -33,6 +33,18 @@ export interface UseChatStreamHandlerOptions { debug?: boolean } +function mergeToolCallArguments(previous: unknown, incoming: unknown): Record { + const prev = + previous && typeof previous === 'object' && !Array.isArray(previous) + ? (previous as Record) + : {} + const next = + incoming && typeof incoming === 'object' && !Array.isArray(incoming) + ? (incoming as Record) + : { value: incoming } + return { ...prev, ...next } +} + export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { const { t } = useI18n() const { @@ -731,7 +743,9 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) { } if (toolCallEvent) { if (incomingToolName) toolCallEvent.tool_name = incomingToolName - if (incomingArguments) toolCallEvent.arguments = incomingArguments + if (incomingArguments) { + toolCallEvent.arguments = mergeToolCallArguments(toolCallEvent.arguments, incomingArguments) + } toolCallEvent.pending = true if (!toolCallEvent.timestamp) toolCallEvent.timestamp = Date.now() pending.set(toolCallId, toolCallEvent) diff --git a/frontend/src/i18n/embed.ts b/frontend/src/i18n/embed.ts index 3cd7cf3b..5ca099cc 100644 --- a/frontend/src/i18n/embed.ts +++ b/frontend/src/i18n/embed.ts @@ -355,7 +355,8 @@ const messages = { "truncated": "列表已截断", "wrote": "已写入", "edited": "已编辑", - "replacements": "替换 {count} 处" + "replacements": "替换 {count} 处", + "moreLines": "另有 {count} 行" }, "shellExec": { "workDir": "目录", @@ -881,7 +882,8 @@ const messages = { "truncated": "List truncated", "wrote": "Wrote", "edited": "Edited", - "replacements": "Replaced {count}" + "replacements": "Replaced {count}", + "moreLines": "{count} more lines" }, "shellExec": { "workDir": "Directory", diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index bfa516f9..c738e459 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -5421,7 +5421,8 @@ export default { truncated: 'List truncated', wrote: 'Wrote', edited: 'Edited', - replacements: 'Replaced {count}' + replacements: 'Replaced {count}', + moreLines: '{count} more lines' }, shellExec: { workDir: 'Directory', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index dfbca04e..89add590 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -1329,7 +1329,8 @@ export default { truncated: '목록이 잘림', wrote: '씀', edited: '편집함', - replacements: '{count}곳 치환' + replacements: '{count}곳 치환', + moreLines: '{count}줄 더' }, shellExec: { workDir: '디렉터리', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index c2a66462..c3f9aecd 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -1329,7 +1329,8 @@ export default { truncated: 'Список обрезан', wrote: 'Записано', edited: 'Изменено', - replacements: 'Замен: {count}' + replacements: 'Замен: {count}', + moreLines: 'ещё {count} строк' }, shellExec: { workDir: 'Каталог', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 6a9fa34b..8d48b4be 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -1331,7 +1331,8 @@ export default { truncated: '列表已截断', wrote: '已写入', edited: '已编辑', - replacements: '替换 {count} 处' + replacements: '替换 {count} 处', + moreLines: '另有 {count} 行' }, shellExec: { workDir: '目录', diff --git a/frontend/src/types/tool-results.ts b/frontend/src/types/tool-results.ts index f1cdc455..7b38b670 100644 --- a/frontend/src/types/tool-results.ts +++ b/frontend/src/types/tool-results.ts @@ -367,6 +367,9 @@ export interface WriteSandboxFileData { name?: string; size?: number; replacements?: number; + added_lines?: number; + removed_lines?: number; + preview?: string; } export interface ReadSkillData { diff --git a/frontend/src/utils/skillToolDisplay.test.ts b/frontend/src/utils/skillToolDisplay.test.ts index a69e9bbb..2915857c 100644 --- a/frontend/src/utils/skillToolDisplay.test.ts +++ b/frontend/src/utils/skillToolDisplay.test.ts @@ -5,7 +5,10 @@ import { getEventSkillName, getReadSkillTarget, getSandboxToolPath, + getSandboxDiffStat, + getSandboxFilePreview, sandboxFileListItems, + sandboxPreviewRemaining, skillFileListItems, skillScriptTitleCommand, } from './skillToolDisplay.ts' @@ -77,3 +80,35 @@ test('getSandboxToolPath reads the listed directory', () => { '/workspace/output/charts', ) }) + +test('getSandboxDiffStat prefers tool_data over arguments', () => { + assert.deepEqual( + getSandboxDiffStat({ + arguments: { added_lines: 3, removed_lines: 1 }, + tool_data: { added_lines: 12, removed_lines: 4 }, + }), + { added: 12, removed: 4 }, + ) + assert.equal(getSandboxDiffStat({ arguments: { path: '/workspace/a.py' } }), null) +}) + +test('getSandboxFilePreview reads the truncated write preview', () => { + assert.equal( + getSandboxFilePreview({ + arguments: { preview: 'line1\nline2' }, + }), + 'line1\nline2', + ) +}) + +test('sandboxPreviewRemaining counts lines beyond the preview cap', () => { + assert.equal( + sandboxPreviewRemaining({ + arguments: { + added_lines: 15, + preview: 'a\nb\nc', + }, + }), + 12, + ) +}) diff --git a/frontend/src/utils/skillToolDisplay.ts b/frontend/src/utils/skillToolDisplay.ts index b76843d1..3ed1bf47 100644 --- a/frontend/src/utils/skillToolDisplay.ts +++ b/frontend/src/utils/skillToolDisplay.ts @@ -72,6 +72,41 @@ export function getSandboxToolPath(event: ToolEventLike | null | undefined): str return stringField(eventFields(event), 'path') } +export type SandboxDiffStat = { + added: number + removed: number +} + +function numberField(record: Record, key: string): number { + const value = record[key] + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string' && value.trim()) { + const parsed = Number(value) + if (Number.isFinite(parsed)) return parsed + } + return 0 +} + +export function getSandboxDiffStat(event: ToolEventLike | null | undefined): SandboxDiffStat | null { + const fields = eventFields(event) + const added = Math.max(0, Math.trunc(numberField(fields, 'added_lines'))) + const removed = Math.max(0, Math.trunc(numberField(fields, 'removed_lines'))) + if (added <= 0 && removed <= 0) return null + return { added, removed } +} + +export function getSandboxFilePreview(event: ToolEventLike | null | undefined): string { + return stringField(eventFields(event), 'preview') +} + +export function sandboxPreviewRemaining(event: ToolEventLike | null | undefined): number { + const stat = getSandboxDiffStat(event) + const preview = getSandboxFilePreview(event) + if (!stat || !preview) return 0 + const previewLines = preview.split('\n').filter((line, index, lines) => !(index === lines.length - 1 && line === '')).length + return Math.max(0, stat.added - previewLines) +} + export function skillScriptTitleCommand(skillName: string, command: string): string { const trimmed = command.trim() if (!trimmed) return '' diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 204c82fa..e5b49698 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -155,6 +155,17 @@ {{ getToolTitle(event) }} + + +{{ getSandboxDiffStat(event)?.added }} + -{{ getSandboxDiffStat(event)?.removed }} + + + + +
+
{{ getSandboxFilePreview(event) }}
+
+ {{ t('agentStream.sandboxFiles.moreLines', { count: sandboxPreviewRemaining(event) }) }}
@@ -433,6 +444,17 @@ {{ getToolTitle(event) }} + + +{{ getSandboxDiffStat(event)?.added }} + -{{ getSandboxDiffStat(event)?.removed }} + + + + +
+
{{ getSandboxFilePreview(event) }}
+
+ {{ t('agentStream.sandboxFiles.moreLines', { count: sandboxPreviewRemaining(event) }) }}
@@ -608,7 +630,10 @@ import { formatToolTitleWithDetail, getEventSkillName, getReadSkillTarget, + getSandboxDiffStat, + getSandboxFilePreview, getSandboxToolPath, + sandboxPreviewRemaining, skillScriptTitleCommand, } from '@/utils/skillToolDisplay'; import { previewShellCommand } from '@/utils/shellExecResult'; @@ -3588,6 +3613,51 @@ const handleAddToKnowledge = (answerEvent: any) => { vertical-align: middle; } +.sandbox-diff-stat { + display: inline-flex; + align-items: center; + gap: 6px; + margin-left: 4px; + font-variant-numeric: tabular-nums; + font-size: 12px; + font-weight: 600; + flex-shrink: 0; + letter-spacing: 0.02em; + + .diff-add { + color: var(--td-success-color); + } + + .diff-del { + color: var(--td-error-color); + } +} + +.sandbox-file-preview { + margin: 6px 0 0; + padding: 8px 10px; + font-family: var(--app-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace); + font-size: 12px; + line-height: 1.5; + color: var(--td-text-color-secondary); + background: var(--td-bg-color-secondarycontainer); + border-radius: 6px; + + pre { + margin: 0; + white-space: pre-wrap; + word-break: break-word; + max-height: 180px; + overflow: hidden; + } +} + +.sandbox-file-preview-more { + margin-top: 4px; + font-size: 12px; + color: var(--td-text-color-placeholder); +} + .action-show-icon { font-size: 12px; padding: 0 2px; diff --git a/frontend/src/views/chat/components/tool-results/WriteSandboxFileResult.vue b/frontend/src/views/chat/components/tool-results/WriteSandboxFileResult.vue index c0cbc4e0..700a30b5 100644 --- a/frontend/src/views/chat/components/tool-results/WriteSandboxFileResult.vue +++ b/frontend/src/views/chat/components/tool-results/WriteSandboxFileResult.vue @@ -38,8 +38,14 @@ const title = computed(() => { const meta = computed(() => { const size = record.value.size const replacements = record.value.replacements + const added = record.value.added_lines + const removed = record.value.removed_lines const isEdit = record.value.display_type === 'edit_sandbox_file' || typeof replacements === 'number' const parts = [t(isEdit ? 'agentStream.sandboxFiles.edited' : 'agentStream.sandboxFiles.wrote')] + const addedN = typeof added === 'number' && Number.isFinite(added) ? added : 0 + const removedN = typeof removed === 'number' && Number.isFinite(removed) ? removed : 0 + if (addedN > 0) parts.push(`+${addedN}`) + if (removedN > 0) parts.push(`-${removedN}`) if (isEdit && typeof replacements === 'number' && Number.isFinite(replacements)) { parts.push(t('agentStream.sandboxFiles.replacements', { count: replacements })) } diff --git a/internal/agent/act.go b/internal/agent/act.go index e35a5015..232a84d3 100644 --- a/internal/agent/act.go +++ b/internal/agent/act.go @@ -456,7 +456,7 @@ func (e *AgentEngine) runToolCall( Data: event.AgentToolCallData{ ToolCallID: tc.ID, ToolName: tc.Function.Name, - Arguments: args, + Arguments: agenttools.SanitizeSandboxFileCallArgs(tc.Function.Name, args), Iteration: iteration, Hint: toolHint, }, diff --git a/internal/agent/think.go b/internal/agent/think.go index 7a240f15..36bee58a 100644 --- a/internal/agent/think.go +++ b/internal/agent/think.go @@ -340,6 +340,7 @@ func (e *AgentEngine) streamThinkingToEventBus( if chunk.ResponseType == types.ResponseTypeToolCall && chunk.Data != nil { toolCallID, _ := chunk.Data["tool_call_id"].(string) toolName, _ := chunk.Data["tool_name"].(string) + args, _ := chunk.Data["arguments"].(map[string]any) if toolCallID != "" && toolName != "" && !pendingToolCalls[toolCallID] { pendingToolCalls[toolCallID] = true @@ -351,6 +352,20 @@ func (e *AgentEngine) streamThinkingToEventBus( Data: event.AgentToolCallData{ ToolCallID: toolCallID, ToolName: toolName, + Arguments: args, + Iteration: iteration, + }, + }) + } else if toolCallID != "" && pendingToolCalls[toolCallID] && args != nil { + emittedEventTypes["tool_call_progress"]++ + _ = e.eventBus.Emit(ctx, event.Event{ + ID: fmt.Sprintf("%s-tool-call-progress", toolCallID), + Type: event.EventAgentToolCall, + SessionID: sessionID, + Data: event.AgentToolCallData{ + ToolCallID: toolCallID, + ToolName: toolName, + Arguments: args, Iteration: iteration, }, }) diff --git a/internal/agent/tools/persist.go b/internal/agent/tools/persist.go index eaf14d28..e84b8544 100644 --- a/internal/agent/tools/persist.go +++ b/internal/agent/tools/persist.go @@ -332,6 +332,11 @@ func compactToolSummary(success bool, errMsg string, data map[string]interface{} path := stringField(data, "path") size := intField(data, "size") if path != "" { + added := intField(data, "added_lines") + removed := intField(data, "removed_lines") + if stat := formatSandboxDiffStat(added, removed); stat != "" { + return fmt.Sprintf("Wrote %s (%s, %d bytes)", path, stat, size) + } return fmt.Sprintf("Wrote %s (%d bytes)", path, size) } case "edit_sandbox_file": @@ -339,6 +344,11 @@ func compactToolSummary(success bool, errMsg string, data map[string]interface{} size := intField(data, "size") n := intField(data, "replacements") if path != "" { + added := intField(data, "added_lines") + removed := intField(data, "removed_lines") + if stat := formatSandboxDiffStat(added, removed); stat != "" { + return fmt.Sprintf("Edited %s (%s, %d replacement(s), %d bytes)", path, stat, n, size) + } return fmt.Sprintf("Edited %s (%d replacement(s), %d bytes)", path, n, size) } case "attachment_parsing": diff --git a/internal/agent/tools/persist_test.go b/internal/agent/tools/persist_test.go index 09f69964..2e66d3de 100644 --- a/internal/agent/tools/persist_test.go +++ b/internal/agent/tools/persist_test.go @@ -315,3 +315,36 @@ func TestCompactToolOutputForHistory_editSandboxFileKeepsPath(t *testing.T) { t.Fatalf("history should keep path, replacements, and size, got %q", history) } } + +func TestCompactToolOutputForHistory_writeSandboxFileIncludesDiffStat(t *testing.T) { + history := CompactToolOutputForHistory(ToolWriteSandboxFile, &types.ToolResult{ + Success: true, + Data: map[string]interface{}{ + "display_type": ToolWriteSandboxFile, + "path": "/workspace/output/a.py", + "size": 80, + "added_lines": 12, + "removed_lines": 0, + }, + }) + if history != "Wrote /workspace/output/a.py (+12, 80 bytes)" { + t.Fatalf("history should include +N, got %q", history) + } +} + +func TestCompactToolOutputForHistory_editSandboxFileIncludesDiffStat(t *testing.T) { + history := CompactToolOutputForHistory(ToolEditSandboxFile, &types.ToolResult{ + Success: true, + Data: map[string]interface{}{ + "display_type": ToolEditSandboxFile, + "path": "/workspace/output/a.py", + "size": 80, + "replacements": 2, + "added_lines": 5, + "removed_lines": 3, + }, + }) + if history != "Edited /workspace/output/a.py (+5 -3, 2 replacement(s), 80 bytes)" { + t.Fatalf("history should include +/- and replacements, got %q", history) + } +} diff --git a/internal/agent/tools/sandbox_diff.go b/internal/agent/tools/sandbox_diff.go new file mode 100644 index 00000000..fc53ab3c --- /dev/null +++ b/internal/agent/tools/sandbox_diff.go @@ -0,0 +1,158 @@ +package tools + +import ( + "fmt" + "strings" +) + +const sandboxFilePreviewMaxLines = 10 + +// CountContentLines is the +N / -M unit for sandbox file mutations: empty is +// 0, a trailing newline does not add an extra line. +func CountContentLines(s string) int { + if s == "" { + return 0 + } + n := strings.Count(s, "\n") + if s[len(s)-1] != '\n' { + n++ + } + return n +} + +func sandboxContentPreview(s string) string { + if s == "" { + return "" + } + lines := strings.Split(s, "\n") + end := len(lines) + if end > 0 && lines[end-1] == "" { + end-- + } + lines = lines[:end] + if len(lines) > sandboxFilePreviewMaxLines { + lines = lines[:sandboxFilePreviewMaxLines] + } + return strings.Join(lines, "\n") +} + +func isSandboxMutationTool(name string) bool { + return name == ToolWriteSandboxFile || name == ToolEditSandboxFile +} + +func attachSandboxDiffStats(data map[string]interface{}, added, removed int) { + if data == nil { + return + } + data["added_lines"] = added + data["removed_lines"] = removed +} + +func sandboxEditDiffStats(content string, edits []SandboxEdit) (added, removed int) { + for _, e := range edits { + found := indexAllNonOverlapping(content, e.OldString) + n := len(found) + if n == 0 { + continue + } + if !e.ReplaceAll { + n = 1 + } + removed += n * CountContentLines(e.OldString) + added += n * CountContentLines(e.NewString) + } + return added, removed +} + +func editArgsLineStats(args map[string]any) (added, removed int) { + edits, _ := args["edits"].([]any) + for _, raw := range edits { + m, ok := raw.(map[string]any) + if !ok { + continue + } + oldS := stringArg(m, "old_string", "oldText") + newS := stringArg(m, "new_string", "newText") + removed += CountContentLines(oldS) + added += CountContentLines(newS) + } + if added == 0 && removed == 0 { + removed = CountContentLines(stringArg(args, "old_string", "oldText")) + added = CountContentLines(stringArg(args, "new_string", "newText")) + } + return added, removed +} + +func stringArg(m map[string]any, keys ...string) string { + for _, key := range keys { + if s, ok := m[key].(string); ok { + return s + } + } + return "" +} + +// SandboxFileCallProgress is the UI payload for a write/edit call: path, +// running +/− line counts, and a short preview. File bodies stay off the wire. +func SandboxFileCallProgress(toolName string, args map[string]any) map[string]any { + if args == nil { + return nil + } + out := map[string]any{} + if path := stringArg(args, "path", "file_path"); path != "" { + out["path"] = path + } + switch toolName { + case ToolWriteSandboxFile: + content := stringArg(args, "content") + if mode := stringArg(args, "mode"); mode != "" { + out["mode"] = mode + } + out["added_lines"] = CountContentLines(content) + out["removed_lines"] = 0 + out["bytes"] = len(content) + if preview := sandboxContentPreview(content); preview != "" { + out["preview"] = preview + } + case ToolEditSandboxFile: + added, removed := editArgsLineStats(args) + out["added_lines"] = added + out["removed_lines"] = removed + } + if len(out) == 0 { + return nil + } + return out +} + +// SanitizeSandboxFileCallArgs strips write/edit file bodies from arguments +// sent to the client. Live progress events already carry stats only; this +// covers the later "tool hint" emit that still has the full JSON. +func SanitizeSandboxFileCallArgs(toolName string, args map[string]any) map[string]any { + if !isSandboxMutationTool(toolName) { + return args + } + if args == nil { + return nil + } + if _, hasContent := args["content"]; hasContent { + return SandboxFileCallProgress(toolName, args) + } + if _, hasEdits := args["edits"]; hasEdits { + return SandboxFileCallProgress(toolName, args) + } + return args +} + +func formatSandboxDiffStat(added, removed int) string { + switch { + case added > 0 && removed > 0: + return fmt.Sprintf("+%d -%d", added, removed) + case added > 0: + return fmt.Sprintf("+%d", added) + case removed > 0: + return fmt.Sprintf("-%d", removed) + default: + return "" + } +} diff --git a/internal/agent/tools/sandbox_diff_test.go b/internal/agent/tools/sandbox_diff_test.go new file mode 100644 index 00000000..440fdc1e --- /dev/null +++ b/internal/agent/tools/sandbox_diff_test.go @@ -0,0 +1,57 @@ +package tools + +import ( + "strings" + "testing" +) + +func TestSanitizeSandboxFileCallArgsStripsWriteBody(t *testing.T) { + content := strings.Repeat("x\n", 15) + out := SanitizeSandboxFileCallArgs(ToolWriteSandboxFile, map[string]any{ + "path": "/workspace/output/a.py", + "content": content, + "mode": "overwrite", + }) + if _, ok := out["content"]; ok { + t.Fatal("write progress must not carry the file body") + } + if out["path"] != "/workspace/output/a.py" { + t.Fatalf("path = %v", out["path"]) + } + if out["added_lines"] != 15 { + t.Fatalf("added_lines = %v, want 15", out["added_lines"]) + } + if out["removed_lines"] != 0 { + t.Fatalf("removed_lines = %v", out["removed_lines"]) + } + preview, _ := out["preview"].(string) + if strings.Count(preview, "\n")+1 != sandboxFilePreviewMaxLines { + t.Fatalf("preview lines = %q", preview) + } +} + +func TestSanitizeSandboxFileCallArgsStripsEditBodies(t *testing.T) { + out := SanitizeSandboxFileCallArgs(ToolEditSandboxFile, map[string]any{ + "path": "/workspace/a.py", + "edits": []any{ + map[string]any{"old_string": "a\nb\n", "new_string": "a\nb\nc\n"}, + }, + }) + if _, ok := out["edits"]; ok { + t.Fatal("edit progress must not carry edits") + } + if out["removed_lines"] != 2 { + t.Fatalf("removed_lines = %v, want 2", out["removed_lines"]) + } + if out["added_lines"] != 3 { + t.Fatalf("added_lines = %v, want 3", out["added_lines"]) + } +} + +func TestSanitizeSandboxFileCallArgsLeavesOtherToolsAlone(t *testing.T) { + args := map[string]any{"command": "ls"} + out := SanitizeSandboxFileCallArgs(ToolShellExec, args) + if out["command"] != "ls" { + t.Fatalf("unrelated args = %#v", out) + } +} diff --git a/internal/agent/tools/sandbox_edit.go b/internal/agent/tools/sandbox_edit.go index 37ac308e..4532d155 100644 --- a/internal/agent/tools/sandbox_edit.go +++ b/internal/agent/tools/sandbox_edit.go @@ -285,32 +285,10 @@ func (t *EditSandboxFileTool) Execute(ctx context.Context, args json.RawMessage) logger.Infof(ctx, "[Tool][EditSandboxFile] session=%s path=%s replacements=%d bytes=%d", sessionID, clean, replacements, len(content)) - if hint := pythonScriptSyntaxHint(clean, updated, ToolEditSandboxFile); hint != "" { - return &types.ToolResult{ - Success: false, - Error: hint, - Output: fmt.Sprintf("=== Edited sandbox file with syntax problems: %s ===\n\n%s\n", clean, hint), - Data: map[string]interface{}{ - "display_type": ToolEditSandboxFile, - "session_id": sessionID, - "path": clean, - "root": rootDir, - "name": path.Base(clean), - "size": len(content), - "replacements": replacements, - "syntax_error": true, - }, - }, nil - } + added, removed := sandboxEditDiffStats(string(raw), input.Edits) - output := fmt.Sprintf( - "=== Edited sandbox file: %s ===\n\nreplacements=%d\nbytes=%d\n", - clean, replacements, len(content), - ) - return &types.ToolResult{ - Success: true, - Output: output, - Data: map[string]interface{}{ + if hint := pythonScriptSyntaxHint(clean, updated, ToolEditSandboxFile); hint != "" { + data := map[string]interface{}{ "display_type": ToolEditSandboxFile, "session_id": sessionID, "path": clean, @@ -318,7 +296,39 @@ func (t *EditSandboxFileTool) Execute(ctx context.Context, args json.RawMessage) "name": path.Base(clean), "size": len(content), "replacements": replacements, - }, + "syntax_error": true, + } + attachSandboxDiffStats(data, added, removed) + return &types.ToolResult{ + Success: false, + Error: hint, + Output: fmt.Sprintf("=== Edited sandbox file with syntax problems: %s ===\n\n%s\n", clean, hint), + Data: data, + }, nil + } + + diffStat := formatSandboxDiffStat(added, removed) + if diffStat == "" { + diffStat = fmt.Sprintf("replacements=%d", replacements) + } + output := fmt.Sprintf( + "=== Edited sandbox file: %s ===\n\n%s\nreplacements=%d\nbytes=%d\n", + clean, diffStat, replacements, len(content), + ) + data := map[string]interface{}{ + "display_type": ToolEditSandboxFile, + "session_id": sessionID, + "path": clean, + "root": rootDir, + "name": path.Base(clean), + "size": len(content), + "replacements": replacements, + } + attachSandboxDiffStats(data, added, removed) + return &types.ToolResult{ + Success: true, + Output: output, + Data: data, }, nil } diff --git a/internal/agent/tools/sandbox_edit_test.go b/internal/agent/tools/sandbox_edit_test.go index d04dea5e..37d56a36 100644 --- a/internal/agent/tools/sandbox_edit_test.go +++ b/internal/agent/tools/sandbox_edit_test.go @@ -259,6 +259,8 @@ func TestEditSandboxFileReplacesUniqueSnippet(t *testing.T) { assert.Equal(t, 1, editor.writes) assert.Equal(t, 1, result.Data["replacements"]) assert.Equal(t, path, result.Data["path"]) + assert.Equal(t, 1, result.Data["added_lines"]) + assert.Equal(t, 1, result.Data["removed_lines"]) assert.Contains(t, string(editor.files[path]), "/workspace/output/Windows_Server_2008_WiFi连接指南.pptx") assert.NotContains(t, string(editor.files[path]), "/home/user/Desktop") assert.NotContains(t, result.Output, original) diff --git a/internal/agent/tools/sandbox_write.go b/internal/agent/tools/sandbox_write.go index abe433b9..2e98b5f8 100644 --- a/internal/agent/tools/sandbox_write.go +++ b/internal/agent/tools/sandbox_write.go @@ -331,21 +331,25 @@ func (t *WriteSandboxFileTool) Execute(ctx context.Context, args json.RawMessage // Check the whole file, not just this chunk: a chunk boundary lands in the // middle of the source, so only the assembled result can be judged. + added := CountContentLines(string(chunk)) + if hint := pythonScriptSyntaxHint(clean, string(content), ToolEditSandboxFile); hint != "" { + data := map[string]interface{}{ + "display_type": ToolWriteSandboxFile, + "session_id": sessionID, + "path": clean, + "root": rootDir, + "name": path.Base(clean), + "size": len(content), + "mode": mode, + "syntax_error": true, + } + attachSandboxDiffStats(data, added, 0) return &types.ToolResult{ Success: false, Error: hint, Output: fmt.Sprintf("=== Wrote sandbox file with syntax problems: %s ===\n\n%s\n", clean, hint), - Data: map[string]interface{}{ - "display_type": ToolWriteSandboxFile, - "session_id": sessionID, - "path": clean, - "root": rootDir, - "name": path.Base(clean), - "size": len(content), - "mode": mode, - "syntax_error": true, - }, + Data: data, }, nil } @@ -353,6 +357,9 @@ func (t *WriteSandboxFileTool) Execute(ctx context.Context, args json.RawMessage if mode == writeModeAppend { sizeLine = fmt.Sprintf("appended=%d, total_bytes=%d", len(chunk), len(content)) } + if stat := formatSandboxDiffStat(added, 0); stat != "" { + sizeLine = stat + ", " + sizeLine + } output := fmt.Sprintf( "=== Wrote sandbox file: %s ===\n\n%s\n\n"+ "If this script needs a skill's packages, run it with\n"+ @@ -362,19 +369,21 @@ func (t *WriteSandboxFileTool) Execute(ctx context.Context, args json.RawMessage "User-facing artifacts should land under %s.\n", clean, sizeLine, clean, clean, sandbox.SessionOutputRoot, ) + data := map[string]interface{}{ + "display_type": ToolWriteSandboxFile, + "session_id": sessionID, + "path": clean, + "root": rootDir, + "name": path.Base(clean), + "size": len(content), + "mode": mode, + "appended": len(chunk), + } + attachSandboxDiffStats(data, added, 0) return &types.ToolResult{ Success: true, Output: output, - Data: map[string]interface{}{ - "display_type": ToolWriteSandboxFile, - "session_id": sessionID, - "path": clean, - "root": rootDir, - "name": path.Base(clean), - "size": len(content), - "mode": mode, - "appended": len(chunk), - }, + Data: data, }, nil } diff --git a/internal/agent/tools/sandbox_write_test.go b/internal/agent/tools/sandbox_write_test.go index 70000143..25053ab5 100644 --- a/internal/agent/tools/sandbox_write_test.go +++ b/internal/agent/tools/sandbox_write_test.go @@ -80,6 +80,9 @@ func TestWriteSandboxFileWritesTextUnderOutput(t *testing.T) { assert.Equal(t, script, string(sink.content)) assert.Equal(t, "/workspace/output/generate_ppt.py", result.Data["path"]) assert.Equal(t, len(script), result.Data["size"]) + assert.Equal(t, CountContentLines(script), result.Data["added_lines"]) + assert.Equal(t, 0, result.Data["removed_lines"]) + assert.Contains(t, result.Output, formatSandboxDiffStat(CountContentLines(script), 0)) assert.NotContains(t, result.Output, script) assert.Contains(t, result.Output, "execute_skill_script") assert.Contains(t, result.Output, "/workspace/output/generate_ppt.py") diff --git a/internal/application/service/tenant_skill_transcript.go b/internal/application/service/tenant_skill_transcript.go index c08a070f..19158389 100644 --- a/internal/application/service/tenant_skill_transcript.go +++ b/internal/application/service/tenant_skill_transcript.go @@ -256,6 +256,11 @@ func (tr *installTranscript) onToolCall(_ context.Context, evt event.Event) erro return nil } tr.mu.Lock() + _, seen := tr.starts[data.ToolCallID] + if seen { + tr.mu.Unlock() + return nil + } tr.starts[data.ToolCallID] = time.Now() // This round called a tool, so it is not the round that ends the run: any // prose it streamed was a preamble and must not reach Message.Content. diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.go index 9b454c55..47729dce 100644 --- a/internal/handler/session/agent_stream_handler.go +++ b/internal/handler/session/agent_stream_handler.go @@ -184,27 +184,29 @@ func (h *AgentStreamHandler) handleToolCall(ctx context.Context, evt event.Event } h.mu.Lock() - // Track start time for this tool call (use tool_call_id as key) - h.eventStartTimes[data.ToolCallID] = time.Now() - // Any answer text streamed before this tool call was a non-terminal round's - // preamble, not the final answer (the agent only ends by stopping naturally - // with plain text and no tool calls). Drop those segments from the persisted - // answer so the preamble never leaks into Message.Content. - supersededAny := false - for _, seg := range h.answerSegments { - if !seg.superseded && seg.content != "" { - seg.superseded = true - supersededAny = true + _, first := h.eventStartTimes[data.ToolCallID] + if !first { + h.eventStartTimes[data.ToolCallID] = time.Now() + // Any answer text streamed before this tool call was a non-terminal round's + // preamble, not the final answer (the agent only ends by stopping naturally + // with plain text and no tool calls). Drop those segments from the persisted + // answer so the preamble never leaks into Message.Content. + supersededAny := false + for _, seg := range h.answerSegments { + if !seg.superseded && seg.content != "" { + seg.superseded = true + supersededAny = true + } + } + if supersededAny { + h.finalAnswer = h.composeFinalAnswer() } - } - if supersededAny { - h.finalAnswer = h.composeFinalAnswer() } h.mu.Unlock() metadata := map[string]interface{}{ "tool_name": data.ToolName, - "arguments": data.Arguments, + "arguments": agenttools.SanitizeSandboxFileCallArgs(data.ToolName, data.Arguments), "tool_call_id": data.ToolCallID, } diff --git a/internal/im/service.go b/internal/im/service.go index b1733e14..729a5f84 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -2669,6 +2669,14 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage, } bufMu.Lock() if seenToolCalls[data.ToolCallID] { + if useAgent { + upsertIMToolStep(&agentToolSteps, agentToolIdx, data.ToolCallID, func(step *IMToolStep) { + if data.Arguments != nil { + step.Arguments = data.Arguments + } + }) + streamedAny = true + } bufMu.Unlock() return nil } diff --git a/internal/im/tool_display.go b/internal/im/tool_display.go index 992293f4..158015e7 100644 --- a/internal/im/tool_display.go +++ b/internal/im/tool_display.go @@ -306,6 +306,59 @@ func FormatIMRagPipelineLine(step IMToolStep) string { } } +func imSandboxMutationTitle(step IMToolStep, pending bool) string { + name := imLocalizedToolName(step.ToolName) + path := imSandboxFilePath(step) + stat := imSandboxDiffStat(step) + base := name + if pending { + base = name + "..." + } + if path != "" { + base = imAppendQueryTitle(name, path) + if pending { + base += "..." + } + } + if stat != "" { + return base + " " + stat + } + return base +} + +func imSandboxFilePath(step IMToolStep) string { + if step.Data != nil { + if p, ok := step.Data["path"].(string); ok && strings.TrimSpace(p) != "" { + return strings.TrimSpace(p) + } + } + if step.Arguments != nil { + if p, ok := step.Arguments["path"].(string); ok && strings.TrimSpace(p) != "" { + return strings.TrimSpace(p) + } + } + return "" +} + +func imSandboxDiffStat(step IMToolStep) string { + added := imIntField(step.Arguments, "added_lines") + removed := imIntField(step.Arguments, "removed_lines") + if added == 0 && removed == 0 { + added = imIntField(step.Data, "added_lines") + removed = imIntField(step.Data, "removed_lines") + } + switch { + case added > 0 && removed > 0: + return fmt.Sprintf("+%d -%d", added, removed) + case added > 0: + return fmt.Sprintf("+%d", added) + case removed > 0: + return fmt.Sprintf("-%d", removed) + default: + return "" + } +} + func imAgentToolTitle(step IMToolStep) string { if step.Pending { switch step.ToolName { @@ -313,6 +366,8 @@ func imAgentToolTitle(step IMToolStep) string { return "正在查看图片内容..." case "wiki_search", "wiki_read_page": return imLocalizedToolName(step.ToolName) + "..." + case "write_sandbox_file", "edit_sandbox_file": + return imSandboxMutationTitle(step, true) default: return fmt.Sprintf("正在调用 %s...", imLocalizedToolName(step.ToolName)) } @@ -356,6 +411,10 @@ func imAgentToolTitle(step IMToolStep) string { return imAppendQueryTitle(base, pageLabel) } + if toolName == "write_sandbox_file" || toolName == "edit_sandbox_file" { + return imSandboxMutationTitle(step, false) + } + if summary := imToolHeaderSummary(step); summary != "" { return summary } diff --git a/internal/im/tool_display_test.go b/internal/im/tool_display_test.go index e6a0f380..60347045 100644 --- a/internal/im/tool_display_test.go +++ b/internal/im/tool_display_test.go @@ -101,3 +101,18 @@ func TestIMGetQueryText_joinsUniqueQueries(t *testing.T) { t.Fatalf("query text = %q", got) } } + +func TestFormatIMToolLine_writeSandboxPendingShowsDiffStat(t *testing.T) { + line := FormatIMToolLine(IMToolStep{ + ToolName: "write_sandbox_file", + Pending: true, + Arguments: map[string]any{ + "path": "/workspace/output/a.py", + "added_lines": 12, + "removed_lines": 0, + }, + }) + if line != "写入沙箱文件:「/workspace/output/a.py」... +12" { + t.Fatalf("pending write line = %q", line) + } +} diff --git a/internal/models/chat/openai_stream.go b/internal/models/chat/openai_stream.go index be7b4673..555f52cc 100644 --- a/internal/models/chat/openai_stream.go +++ b/internal/models/chat/openai_stream.go @@ -312,8 +312,9 @@ type streamState struct { lastFunctionName map[int]string nameNotified map[int]bool fieldExtractors map[int]*jsonFieldExtractor // per tool-call-index extractors for streaming field extraction - usage *types.TokenUsage // captured from the final stream chunk when include_usage is enabled - lastFinishReason string // last observed finish_reason for EOF handler fallback + fileProgress map[int]*sandboxFileProgress + usage *types.TokenUsage // captured from the final stream chunk when include_usage is enabled + lastFinishReason string // last observed finish_reason for EOF handler fallback // Diagnostic flags (fire-once) used to log earliest signals of tool_call // presence/absence at the OpenAI-protocol level. These are independent of @@ -334,6 +335,7 @@ func newStreamState() *streamState { lastFunctionName: make(map[int]string), nameNotified: make(map[int]bool), fieldExtractors: make(map[int]*jsonFieldExtractor), + fileProgress: make(map[int]*sandboxFileProgress), streamStartedAt: time.Now(), } } @@ -557,11 +559,39 @@ func (c *RemoteAPIChat) processToolCallsDelta( } currName := toolCallEntry.Function.Name + var progressArgs map[string]any + if isSandboxMutationTool(currName) && argsUpdated && tc.Function.Arguments != "" { + prog := state.fileProgress[toolCallIndex] + if prog == nil { + prog = newSandboxFileProgress(currName) + state.fileProgress[toolCallIndex] = prog + } + if payload, ok := prog.Feed(tc.Function.Arguments); ok { + progressArgs = payload + } + } + if currName != "" && currName == state.lastFunctionName[toolCallIndex] && argsUpdated && !state.nameNotified[toolCallIndex] && toolCallEntry.ID != "" { + data := map[string]interface{}{ + "tool_name": currName, + "tool_call_id": toolCallEntry.ID, + } + if progressArgs != nil { + data["arguments"] = progressArgs + } + streamChan <- types.StreamResponse{ + ResponseType: types.ResponseTypeToolCall, + Content: "", + Done: false, + Data: data, + } + state.nameNotified[toolCallIndex] = true + progressArgs = nil + } else if progressArgs != nil && toolCallEntry.ID != "" && currName != "" { streamChan <- types.StreamResponse{ ResponseType: types.ResponseTypeToolCall, Content: "", @@ -569,9 +599,9 @@ func (c *RemoteAPIChat) processToolCallsDelta( Data: map[string]interface{}{ "tool_name": currName, "tool_call_id": toolCallEntry.ID, + "arguments": progressArgs, }, } - state.nameNotified[toolCallIndex] = true } state.lastFunctionName[toolCallIndex] = currName diff --git a/internal/models/chat/sandbox_file_progress.go b/internal/models/chat/sandbox_file_progress.go new file mode 100644 index 00000000..c77515ec --- /dev/null +++ b/internal/models/chat/sandbox_file_progress.go @@ -0,0 +1,293 @@ +package chat + +import ( + "encoding/json" + "strings" + "time" +) + +// Live write/edit progress while the model is still emitting tool-call JSON: +// path as soon as it appears, then a running +N / -M as content lands. The +// SSE payload is only those stats plus a short preview — never the whole file. + +const ( + sandboxFilePreviewMaxLines = 10 + writeSandboxFileName = "write_sandbox_file" + editSandboxFileName = "edit_sandbox_file" +) + +// sandboxProgressMinInterval caps how often we emit when only byte counts +// change (a long line with no newline). Line-count changes always emit. +var sandboxProgressMinInterval = 120 * time.Millisecond + +func isSandboxMutationTool(name string) bool { + return name == writeSandboxFileName || name == editSandboxFileName +} + +type sandboxFileProgress struct { + toolName string + pathEx *jsonFieldExtractor + contentEx *jsonFieldExtractor + path string + content string + buf string + + added int + removed int + bytes int + preview string + + lastPath string + lastAdded int + lastRemoved int + lastBytes int + lastPreview string + lastEmit time.Time + emitted bool + + lastParseAt time.Time + lastParseLen int +} + +func newSandboxFileProgress(toolName string) *sandboxFileProgress { + return &sandboxFileProgress{toolName: toolName} +} + +// Feed consumes one arguments delta. ok is true when the UI should be sent +// an updated stats payload. +func (p *sandboxFileProgress) Feed(delta string) (map[string]any, bool) { + if p == nil || delta == "" { + return nil, false + } + switch p.toolName { + case writeSandboxFileName: + p.feedWrite(delta) + case editSandboxFileName: + p.feedEdit(delta) + default: + return nil, false + } + if !p.shouldEmit() { + return nil, false + } + p.markEmitted() + return p.payload(), true +} + +func (p *sandboxFileProgress) feedWrite(delta string) { + if p.pathEx == nil { + p.pathEx = newJSONFieldExtractor("path") + } + if p.contentEx == nil { + p.contentEx = newJSONFieldExtractor("content") + } + if chunk := p.pathEx.Feed(delta); chunk != "" { + p.path += chunk + } + if chunk := p.contentEx.Feed(delta); chunk != "" { + p.content += chunk + } + p.added = countContentLines(p.content) + p.removed = 0 + p.bytes = len(p.content) + p.preview = sandboxContentPreview(p.content) +} + +func (p *sandboxFileProgress) feedEdit(delta string) { + p.buf += delta + if p.pathEx == nil { + p.pathEx = newJSONFieldExtractor("path") + } + if chunk := p.pathEx.Feed(delta); chunk != "" { + p.path += chunk + } + + now := time.Now() + if p.lastParseLen > 0 && + len(p.buf)-p.lastParseLen < 512 && + now.Sub(p.lastParseAt) < sandboxProgressMinInterval { + return + } + p.lastParseAt = now + p.lastParseLen = len(p.buf) + + obj := parsePartialJSONObject(p.buf) + if obj == nil { + return + } + if path, _ := obj["path"].(string); path != "" && p.path == "" { + p.path = path + } + p.added, p.removed = editArgsLineStats(obj) + p.bytes = len(p.buf) + p.preview = "" +} + +func (p *sandboxFileProgress) shouldEmit() bool { + if p.path == "" && p.added == 0 && p.removed == 0 && p.bytes == 0 { + return false + } + pathChanged := p.path != p.lastPath + linesChanged := p.added != p.lastAdded || p.removed != p.lastRemoved + if !p.emitted || pathChanged || linesChanged { + return true + } + if p.bytes == p.lastBytes && p.preview == p.lastPreview { + return false + } + return time.Since(p.lastEmit) >= sandboxProgressMinInterval +} + +func (p *sandboxFileProgress) markEmitted() { + p.emitted = true + p.lastPath = p.path + p.lastAdded = p.added + p.lastRemoved = p.removed + p.lastBytes = p.bytes + p.lastPreview = p.preview + p.lastEmit = time.Now() +} + +func (p *sandboxFileProgress) payload() map[string]any { + out := map[string]any{ + "added_lines": p.added, + "removed_lines": p.removed, + "bytes": p.bytes, + } + if p.path != "" { + out["path"] = p.path + } + if p.preview != "" { + out["preview"] = p.preview + } + return out +} + +func countContentLines(s string) int { + if s == "" { + return 0 + } + n := strings.Count(s, "\n") + if s[len(s)-1] != '\n' { + n++ + } + return n +} + +func sandboxContentPreview(s string) string { + if s == "" { + return "" + } + lines := strings.Split(s, "\n") + end := len(lines) + if end > 0 && lines[end-1] == "" { + end-- + } + lines = lines[:end] + if len(lines) > sandboxFilePreviewMaxLines { + lines = lines[:sandboxFilePreviewMaxLines] + } + return strings.Join(lines, "\n") +} + +func parsePartialJSONObject(s string) map[string]any { + var m map[string]any + if json.Unmarshal([]byte(s), &m) == nil { + return m + } + closed := closePartialJSON(s) + if closed == s { + return nil + } + if json.Unmarshal([]byte(closed), &m) == nil { + return m + } + return nil +} + +// closePartialJSON closes an unterminated string and missing braces so a +// streaming prefix can be unmarshalled. Structural characters are ASCII, so +// byte iteration is enough. +func closePartialJSON(s string) string { + inString := false + escaped := false + var stack []byte + for i := 0; i < len(s); i++ { + c := s[i] + if escaped { + escaped = false + continue + } + if inString { + if c == '\\' { + escaped = true + continue + } + if c == '"' { + inString = false + } + continue + } + switch c { + case '"': + inString = true + case '{': + stack = append(stack, '}') + case '[': + stack = append(stack, ']') + case '}', ']': + if n := len(stack); n > 0 && stack[n-1] == c { + stack = stack[:n-1] + } + } + } + if !inString && !escaped && len(stack) == 0 { + return s + } + var b strings.Builder + b.Grow(len(s) + len(stack) + 2) + b.WriteString(s) + if escaped { + b.WriteByte('\\') + } + if inString || escaped { + b.WriteByte('"') + } + for i := len(stack) - 1; i >= 0; i-- { + b.WriteByte(stack[i]) + } + return b.String() +} + +func editArgsLineStats(obj map[string]any) (added, removed int) { + edits, _ := obj["edits"].([]any) + for _, raw := range edits { + m, ok := raw.(map[string]any) + if !ok { + continue + } + oldS := stringFromMap(m, "old_string", "oldText") + newS := stringFromMap(m, "new_string", "newText") + if oldS == "" && newS == "" { + continue + } + removed += countContentLines(oldS) + added += countContentLines(newS) + } + if added == 0 && removed == 0 { + oldS := stringFromMap(obj, "old_string", "oldText") + newS := stringFromMap(obj, "new_string", "newText") + removed = countContentLines(oldS) + added = countContentLines(newS) + } + return added, removed +} + +func stringFromMap(m map[string]any, keys ...string) string { + for _, key := range keys { + if s, ok := m[key].(string); ok { + return s + } + } + return "" +} diff --git a/internal/models/chat/sandbox_file_progress_test.go b/internal/models/chat/sandbox_file_progress_test.go new file mode 100644 index 00000000..7b9979e9 --- /dev/null +++ b/internal/models/chat/sandbox_file_progress_test.go @@ -0,0 +1,132 @@ +package chat + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +func TestCountContentLines(t *testing.T) { + cases := []struct { + in string + want int + }{ + {"", 0}, + {"hello", 1}, + {"hello\n", 1}, + {"hello\nworld", 2}, + {"hello\nworld\n", 2}, + {"a\n\nb", 3}, + } + for _, tc := range cases { + if got := countContentLines(tc.in); got != tc.want { + t.Errorf("countContentLines(%q) = %d, want %d", tc.in, got, tc.want) + } + } +} + +func TestSandboxFileProgressWriteStreamsLineCount(t *testing.T) { + p := newSandboxFileProgress(writeSandboxFileName) + + if _, ok := p.Feed(`{"path":"`); ok { + t.Fatal("path still open, should not emit yet") + } + payload, ok := p.Feed(`/workspace/output/deck.py","content":"`) + if !ok { + t.Fatal("expected emit once path is complete") + } + if payload["path"] != "/workspace/output/deck.py" { + t.Fatalf("path = %v", payload["path"]) + } + if payload["added_lines"] != 0 { + t.Fatalf("no content yet, added_lines = %v", payload["added_lines"]) + } + + payload, ok = p.Feed(`line1\nline2\nline3`) + if !ok { + t.Fatal("expected emit when line count grows") + } + if payload["added_lines"] != 3 { + t.Fatalf("added_lines = %v, want 3", payload["added_lines"]) + } + preview, _ := payload["preview"].(string) + if !strings.Contains(preview, "line1") || !strings.Contains(preview, "line3") { + t.Fatalf("preview = %q", preview) + } + if _, exists := payload["content"]; exists { + t.Fatal("progress payload must not carry the file body") + } +} + +func TestSandboxFileProgressWritePreviewCapsAtTenLines(t *testing.T) { + p := newSandboxFileProgress(writeSandboxFileName) + var body strings.Builder + body.WriteString(`{"path":"/workspace/a.py","content":"`) + for i := 0; i < 15; i++ { + if i > 0 { + body.WriteString(`\n`) + } + body.WriteString("x") + } + body.WriteString(`"}`) + payload, ok := p.Feed(body.String()) + if !ok { + t.Fatal("expected emit") + } + if payload["added_lines"] != 15 { + t.Fatalf("added_lines = %v, want 15", payload["added_lines"]) + } + preview, _ := payload["preview"].(string) + if strings.Count(preview, "\n")+1 != sandboxFilePreviewMaxLines { + t.Fatalf("preview lines = %q", preview) + } +} + +func TestSandboxFileProgressEditCountsOldAndNew(t *testing.T) { + p := newSandboxFileProgress(editSandboxFileName) + payload, ok := p.Feed( + `{"path":"/workspace/a.py","edits":[{"old_string":"a\nb\n","new_string":"a\nb\nc\nd\n"}]}`, + ) + if !ok { + t.Fatal("expected emit for complete edit JSON") + } + if payload["path"] != "/workspace/a.py" { + t.Fatalf("path = %v", payload["path"]) + } + if payload["removed_lines"] != 2 { + t.Fatalf("removed_lines = %v, want 2", payload["removed_lines"]) + } + if payload["added_lines"] != 4 { + t.Fatalf("added_lines = %v, want 4", payload["added_lines"]) + } +} + +func TestSandboxFileProgressEditPartialJSON(t *testing.T) { + p := newSandboxFileProgress(editSandboxFileName) + sandboxProgressMinInterval = 0 + t.Cleanup(func() { sandboxProgressMinInterval = 120 * time.Millisecond }) + + payload, ok := p.Feed(`{"path":"/workspace/a.py","edits":[{"old_string":"foo","new_string":"foo\nbar\nbaz`) + if !ok { + t.Fatal("expected emit for closable partial JSON") + } + if payload["path"] != "/workspace/a.py" { + t.Fatalf("path = %v", payload["path"]) + } + added, _ := payload["added_lines"].(int) + if added < 2 { + t.Fatalf("added_lines = %v, want at least 2 from the partial new_string", payload["added_lines"]) + } +} + +func TestClosePartialJSON(t *testing.T) { + closed := closePartialJSON(`{"path":"/x","content":"hello`) + var m map[string]any + if err := json.Unmarshal([]byte(closed), &m); err != nil { + t.Fatalf("closed JSON should parse: %v (%s)", err, closed) + } + if m["content"] != "hello" { + t.Fatalf("content = %v", m["content"]) + } +}