Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/opencode/src/cli/cmd/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ async function tool(part: ToolPart, printed?: string) {
const { toolInlineInfo, withoutRepeatedResult } = await import("./run/tool")
const next = toolInlineInfo(part)
if (next.mode === "block" && part.tool === "finish" && printed && next.body) {
const rest = withoutRepeatedResult(next.body, printed)
const rest = withoutRepeatedResult(next.dedupeBody ?? next.body, printed)
if (rest !== undefined) {
const info: Inline = { icon: next.icon, title: next.title, description: next.description }
if (rest) block(info, rest)
Expand Down
29 changes: 19 additions & 10 deletions packages/opencode/src/cli/cmd/run/tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ export type ToolInline = {
description?: string
mode?: "inline" | "block"
body?: string
// The untruncated finish body, used only for deduplication before display.
dedupeBody?: string
}

export type ToolPermissionInfo = {
Expand Down Expand Up @@ -588,10 +590,8 @@ function runExecute(p: ToolProps): ToolInline {
}

function runFinish(p: ToolProps): ToolInline {
const result = Locale.truncate(
stripAnsi(text(p.frame.state.output).trim() || text(p.frame.input.result).trim()),
2000,
)
const full = stripAnsi(text(p.frame.state.output).trim() || text(p.frame.input.result).trim())
const result = Locale.truncate(full, 2000)
if (p.frame.status === "error") {
const error = toolError(p.frame)
return {
Expand All @@ -607,7 +607,11 @@ function runFinish(p: ToolProps): ToolInline {
return {
icon: waiting ? "◌" : "✓",
title: waiting ? "Waiting for subagent execution..." : "Task completed",
...(result && { mode: "block" as const, body: result }),
...(result && {
mode: "block" as const,
body: result,
...(result !== full && { dedupeBody: full }),
}),
}
}

Expand Down Expand Up @@ -1804,10 +1808,15 @@ export function toolFiletype(input?: string): string | undefined {
}

// A finish body is the result, then a blank line and the effort/review status
// line. When the result only repeats text the run already printed, return what
// is left (possibly empty); otherwise undefined.
// line. When the result begins with text the run already printed, return what
// is left (possibly empty); otherwise undefined. The printed text can itself
// contain blank lines, so compare it before looking for the separator. Bound
// any remaining details only after comparing the full text.
export function withoutRepeatedResult(body: string, printed: string): string | undefined {
const [result = "", ...rest] = body.split(/\n\s*\n/)
if (result.trim() !== printed.trim()) return undefined
return rest.join("\n\n").trim()
const result = body.trim()
const text = printed.trim()
if (!text || !result.startsWith(text)) return undefined
const rest = result.slice(text.length)
if (rest && !/^[^\S\n]*\n\s*\n/.test(rest)) return undefined
return Locale.truncate(rest.trim(), 2000)
}
45 changes: 45 additions & 0 deletions packages/opencode/test/cli/run-finish-dedupe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,49 @@ describe("withoutRepeatedResult", () => {
test("keeps a result that adds something new", () => {
expect(withoutRepeatedResult(`Fixed calc.py\n\n${status}`, "OK")).toBeUndefined()
})

test("drops a repeated multi-paragraph result and keeps the status line", () => {
const answer = "First paragraph.\n\nSecond paragraph."
expect(withoutRepeatedResult(`${answer}\n\n${status}`, answer)).toBe(status)
expect(withoutRepeatedResult(answer, answer)).toBe("")
})

test("keeps new paragraphs after a repeated multi-paragraph result", () => {
const answer = "First paragraph.\n\nSecond paragraph."
expect(withoutRepeatedResult(`${answer}\n\nAdditional detail.\n\n${status}`, answer)).toBe(
`Additional detail.\n\n${status}`,
)
})

test("does not remove a prefix from a different result", () => {
expect(withoutRepeatedResult(`OK but not finished\n\n${status}`, "OK")).toBeUndefined()
expect(
withoutRepeatedResult(`First.\n\nSecond, with more detail.\n\n${status}`, "First.\n\nSecond"),
).toBeUndefined()
})

test("recognizes whitespace and CRLF around the paragraph boundary", () => {
const answer = "First paragraph.\r\n\r\nSecond paragraph."
expect(withoutRepeatedResult(` ${answer} \r\n \r\n${status} `, answer)).toBe(status)
})

test("compares the full long answer and keeps new details and status", () => {
const answer = `First paragraph.\n\n${"long answer ".repeat(200)}`
expect(answer.length).toBeGreaterThan(2000)
expect(withoutRepeatedResult(`${answer}\n\nAdditional detail.\n\n${status}`, answer)).toBe(
`Additional detail.\n\n${status}`,
)
})

test("truncates long remaining details after removing the repeated answer", () => {
const answer = "answer ".repeat(300)
const detail = "d".repeat(2200)
expect(withoutRepeatedResult(`${answer}\n\n${detail}\n\n${status}`, answer)).toBe(`${"d".repeat(1999)}…`)
})

test("does not remove a different result with a prefix longer than the display limit", () => {
const answer = "answer ".repeat(300)
expect(answer.length).toBeGreaterThan(2000)
expect(withoutRepeatedResult(`${answer} continued\n\n${status}`, answer)).toBeUndefined()
})
})
181 changes: 181 additions & 0 deletions packages/opencode/test/cli/run/run-finish-output.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import { expect } from "bun:test"
import { Effect } from "effect"
import { cliIt } from "../../lib/cli-process"
import { reply } from "../../lib/llm-server"
import { testProviderConfig } from "../../lib/test-provider"

const longAnswer = [
"Long answer start.",
Array.from({ length: 80 }, (_, index) => `Step ${index}: finding ${index} is complete.`).join("\n"),
"Long answer end.",
].join("\n\n")

function finishConfig(url: string) {
const config = testProviderConfig(url)
return {
OPENCODE_CONFIG_CONTENT: JSON.stringify({
...config,
agent: { ...config.agent, work: { finishTool: true } },
}),
}
}

cliIt.live("headless finish does not repeat an already printed multi-paragraph answer", ({ llm, opencode }) =>
Effect.gen(function* () {
const answer = "First paragraph of the answer.\n\nSecond paragraph of the answer."
yield* llm.push(reply().text(answer).tool("finish", { reason: "success", result: answer }).stop())

const result = yield* opencode.run("Summarize the result", { env: finishConfig(llm.url) })

opencode.expectExit(result, 0)
expect(result.stdout).toBe(`${answer}\n`)
expect(result.stderr).toContain("Task completed")
expect(result.stderr).toContain("[effort ")
expect(result.stderr).not.toContain("First paragraph of the answer.")
expect(result.stderr).not.toContain("Second paragraph of the answer.")
expect(yield* llm.misses).toEqual([])
expect(yield* llm.pending).toBe(0)
}),
)

cliIt.live(
"headless finish does not repeat an already printed answer longer than 2000 characters",
({ llm, opencode }) =>
Effect.gen(function* () {
expect(longAnswer.length).toBeGreaterThan(2000)
yield* llm.push(reply().text(longAnswer).tool("finish", { reason: "success", result: longAnswer }).stop())

const result = yield* opencode.run("Summarize the result", { env: finishConfig(llm.url) })

opencode.expectExit(result, 0)
expect(result.stdout).toBe(`${longAnswer}\n`)
expect(result.stderr.includes("Long answer start.")).toBe(false)
expect(result.stderr).not.toContain("Step 0: finding 0 is complete.")
expect(result.stderr).not.toContain("Long answer end.")
expect(result.stderr).toContain("Task completed")
expect(result.stderr).toContain("[effort ")
expect(yield* llm.misses).toEqual([])
expect(yield* llm.pending).toBe(0)
}),
)

cliIt.live("headless finish keeps new details after a repeated long answer", ({ llm, opencode }) =>
Effect.gen(function* () {
yield* llm.push(
reply()
.text(longAnswer)
.tool("finish", { reason: "success", result: `${longAnswer}\n\nAdditional detail.` })
.stop(),
)

const result = yield* opencode.run("Summarize the result", { env: finishConfig(llm.url) })

opencode.expectExit(result, 0)
expect(result.stdout).toBe(`${longAnswer}\n`)
expect(result.stderr).not.toContain("Long answer start.")
expect(result.stderr).toContain("Additional detail.")
expect(result.stderr).toContain("[effort ")
expect(yield* llm.misses).toEqual([])
expect(yield* llm.pending).toBe(0)
}),
)

cliIt.live("headless finish keeps a distinct result sharing a long answer prefix", ({ llm, opencode }) =>
Effect.gen(function* () {
const answer = longAnswer.slice(0, -1)
yield* llm.push(reply().text(answer).tool("finish", { reason: "success", result: longAnswer }).stop())

const result = yield* opencode.run("Summarize the result", { env: finishConfig(llm.url) })

opencode.expectExit(result, 0)
expect(result.stdout).toBe(`${answer}\n`)
expect(result.stderr).toContain("Long answer start.")
expect(result.stderr).not.toContain("Long answer end.")
expect(result.stderr).toContain("…")
expect(yield* llm.misses).toEqual([])
expect(yield* llm.pending).toBe(0)
}),
)

cliIt.live("headless finish truncates a long result when no answer was printed", ({ llm, opencode }) =>
Effect.gen(function* () {
yield* llm.push(reply().tool("finish", { reason: "success", result: longAnswer }).stop())

const result = yield* opencode.run("Summarize the result", { env: finishConfig(llm.url) })

opencode.expectExit(result, 0)
expect(result.stdout).toBe("")
expect(result.stderr).toContain("Long answer start.")
expect(result.stderr).not.toContain("Long answer end.")
expect(result.stderr).toContain("…")
expect(yield* llm.misses).toEqual([])
expect(yield* llm.pending).toBe(0)
}),
)

cliIt.live("headless finish keeps new details after the repeated answer", ({ llm, opencode }) =>
Effect.gen(function* () {
const answer = "First paragraph.\n\nSecond paragraph."
yield* llm.push(
reply()
.text(answer)
.tool("finish", { reason: "success", result: `${answer}\n\nAdditional detail.` })
.stop(),
)

const result = yield* opencode.run("Summarize the result", { env: finishConfig(llm.url) })

opencode.expectExit(result, 0)
expect(result.stdout).toBe(`${answer}\n`)
expect(result.stderr).not.toContain("First paragraph.")
expect(result.stderr).not.toContain("Second paragraph.")
expect(result.stderr).toContain("Additional detail.")
expect(result.stderr).toContain("[effort ")
expect(yield* llm.misses).toEqual([])
expect(yield* llm.pending).toBe(0)
}),
)

cliIt.live("headless finish keeps a distinct result that shares an answer prefix", ({ llm, opencode }) =>
Effect.gen(function* () {
const answer = "First paragraph.\n\nSecond paragraph"
const finishResult = `${answer}, with more detail.`
yield* llm.push(reply().text(answer).tool("finish", { reason: "success", result: finishResult }).stop())

const result = yield* opencode.run("Summarize the result", { env: finishConfig(llm.url) })

opencode.expectExit(result, 0)
expect(result.stdout).toBe(`${answer}\n`)
expect(result.stderr).toContain(finishResult)
expect(result.stderr).toContain("[effort ")
expect(yield* llm.misses).toEqual([])
expect(yield* llm.pending).toBe(0)
}),
)

cliIt.live("JSON finish events retain the complete raw result", ({ llm, opencode }) =>
Effect.gen(function* () {
const answer = longAnswer
yield* llm.push(reply().text(answer).tool("finish", { reason: "success", result: answer }).stop())

const result = yield* opencode.run("Summarize the result", { format: "json", env: finishConfig(llm.url) })

opencode.expectExit(result, 0)
const events = opencode.parseJsonEvents(result.stdout)
expect(events.map((event) => event.type)).toEqual(["step_start", "text", "tool_use", "step_finish"])
expect(events[1]?.part).toEqual(expect.objectContaining({ type: "text", text: answer }))
expect(events[2]?.part).toEqual(
expect.objectContaining({
type: "tool",
tool: "finish",
state: expect.objectContaining({
status: "completed",
input: expect.objectContaining({ result: answer }),
output: expect.stringContaining(answer),
}),
}),
)
expect(yield* llm.misses).toEqual([])
expect(yield* llm.pending).toBe(0)
}),
)
Loading