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
5 changes: 5 additions & 0 deletions .changeset/steady-compaction-turns.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kilocode/cli": patch
---

Resume pending requests after automatic compaction without replaying requests that already completed.
25 changes: 20 additions & 5 deletions packages/opencode/src/session/compaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,18 @@ const layer = Layer.effect(
for (let i = idx - 1; i >= 0; i--) {
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
const msg = input.messages[i]
if (msg.info.role === "user" && !msg.parts.some((p) => p.type === "compaction")) {
const progress = input.messages
.slice(i + 1, idx)
Comment thread
WebReflection marked this conversation as resolved.
Resolved
.some(
(item) =>
item.info.role === "assistant" &&
(item.info.finish ||
item.parts.some(
(part) =>
part.type === "tool" || ((part.type === "text" || part.type === "reasoning") && !!part.text),
)),
)
if (progress) break
replay = { info: msg.info, parts: msg.parts }
messages = input.messages.slice(0, i)
break
Expand All @@ -368,11 +380,12 @@ const layer = Layer.effect(
const prior = completedCompactions(history)
const hidden = new Set(prior.flatMap((item) => [item.userIndex, item.assistantIndex]))
const previousSummary = prior.at(-1)?.summary
const selected = yield* select({
messages: history.filter((_, index) => !hidden.has(index)),
cfg,
model,
})
// kilocode_change start
const available = history.filter((_, index) => !hidden.has(index))
const selected = replay
? { head: available, tail_start_id: undefined }
: yield* select({ messages: available, cfg, model })
// kilocode_change end
// Allow plugins to inject context or replace compaction prompt.
const compacting = yield* plugin.trigger(
"experimental.session.compacting",
Expand Down Expand Up @@ -520,6 +533,7 @@ const layer = Layer.effect(
format: original.format,
tools: original.tools,
system: original.system,
editorContext: original.editorContext, // kilocode_change
Comment thread
WebReflection marked this conversation as resolved.
Resolved
})
KiloSessionPromptQueue.retarget(input.sessionID, replayMsg.id) // kilocode_change - expose replay to scope()
for (const part of replay.parts) {
Expand All @@ -531,6 +545,7 @@ const layer = Layer.effect(
: part
yield* session.updatePart({
...replayPart,
...(replayPart.type === "text" && { synthetic: true }),
Comment thread
WebReflection marked this conversation as resolved.
Resolved
id: PartID.ascending(),
messageID: replayMsg.id,
sessionID: input.sessionID,
Expand Down
49 changes: 28 additions & 21 deletions packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1581,7 +1581,7 @@ export const layer = Layer.effect(
if (task?.type === "compaction") {
const result = yield* compaction.process({
messages: msgs,
parentID: lastUser.id,
parentID: task.messageID, // kilocode_change
sessionID,
auto: task.auto,
overflow: task.overflow,
Expand Down Expand Up @@ -1617,7 +1617,7 @@ export const layer = Layer.effect(
}
compactionAttempts++
// kilocode_change end
yield* compaction.create({ sessionID, agent: lastUser.agent, model: lastUser.model, auto: true })
yield* compaction.create({ sessionID, agent: lastUser.agent, model: lastUser.model, auto: true, overflow: false }) // kilocode_change
continue
}

Expand Down Expand Up @@ -1839,27 +1839,34 @@ export const layer = Layer.effect(
// kilocode_change end
if (result === "compact") {
// kilocode_change start
const guard = KiloSessionPrompt.guardCompactionAttempt({
sessionID,
attempts: compactionAttempts,
closeReasons,
message: handle.message,
})
if (guard.exhausted) {
yield* sessions.updateMessage(handle.message)
yield* events.publish(Session.Event.Error, { sessionID, error: guard.error })
return "break" as const
const parts = yield* MessageV2.parts(handle.message.id).pipe(
Effect.provideService(Database.Service, database),
)
const tools = parts.some(
(part) => part.type === "tool" && !part.metadata?.providerExecuted && !isOrphanedInterruptedTool(part),
)
if (!handle.message.finish || ["tool-calls", "unknown"].includes(handle.message.finish) || tools) {
const guard = KiloSessionPrompt.guardCompactionAttempt({
sessionID,
attempts: compactionAttempts,
closeReasons,
message: handle.message,
})
if (guard.exhausted) {
yield* sessions.updateMessage(handle.message)
yield* events.publish(Session.Event.Error, { sessionID, error: guard.error })
return "break" as const
}
compactionAttempts++
yield* compaction.create({
sessionID,
agent: lastUser.agent,
model: lastUser.model,
auto: true,
overflow: handle.message.finish ? undefined : handle.compactError?.() !== undefined,
})
}
compactionAttempts++
// kilocode_change end
yield* compaction.create({
sessionID,
agent: lastUser.agent,
model: lastUser.model,
auto: true,
// kilocode_change - preflight compaction replays the pending turn without treating media as provider overflow
overflow: !handle.message.finish && handle.compactError?.() !== undefined, // kilocode_change
})
}
// kilocode_change start — break out so a newer queued prompt can take over
// instead of starting another LLM step for the now-superseded turn. The
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import * as Log from "@opencode-ai/core/util/log"
import { MemoryService } from "@kilocode/kilo-memory/effect/service"
import { provideTmpdirServer } from "../fixture/fixture"
import { testEffect } from "../lib/effect"
import { TestLLMServer } from "../lib/llm-server"
import { reply, TestLLMServer } from "../lib/llm-server"

Log.init({ print: false })

Expand Down Expand Up @@ -254,7 +254,7 @@ const user = Effect.fn("prompt-safety.user")(function* (
const assistant = Effect.fn("prompt-safety.assistant")(function* (
sessionID: SessionID,
parentID: MessageID,
input?: { text?: string; summary?: boolean },
input?: { text?: string; summary?: boolean; tokens?: MessageV2.Assistant["tokens"]; finish?: string },
) {
const sessions = yield* Session.Service
const msg = yield* sessions.updateMessage({
Expand All @@ -266,11 +266,11 @@ const assistant = Effect.fn("prompt-safety.assistant")(function* (
agent: "code",
path: { cwd: "/tmp", root: "/tmp" },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
tokens: input?.tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
modelID: ref.modelID,
providerID: ref.providerID,
time: { created: Date.now() },
finish: "end_turn",
finish: input?.finish ?? "end_turn",
summary: input?.summary,
} satisfies MessageV2.Assistant)
yield* sessions.updatePart({
Expand Down Expand Up @@ -363,6 +363,127 @@ describe("SessionPrompt compaction safety", () => {
),
)

it.live(
"answers a pending request once after prior usage triggers compaction",
() =>
provideTmpdirServer(
Effect.fnUntraced(function* ({ llm }) {
const prompt = yield* SessionPrompt.Service
const sessions = yield* Session.Service
const chat = yield* sessions.create({})
const old = yield* user(chat.id, "old request")
yield* assistant(chat.id, old.id, {
tokens: { input: 95_000, output: 100, reasoning: 0, cache: { read: 0, write: 0 } },
})
const editor = { activeFile: "src/app.ts", openTabs: ["src/app.ts"] }
const pending = yield* user(chat.id, "pending request", { editorContext: editor })
yield* file(chat.id, pending.id, { mime: "image/png", name: "pending.png", body: "PENDINGIMAGE" })
yield* llm.text("summary")
yield* llm.text("answer")

const result = yield* prompt.loop({ sessionID: chat.id })

expect(yield* llm.calls).toBe(2)
expect(result.parts.some((part) => part.type === "text" && part.text === "answer")).toBe(true)
const body = JSON.stringify((yield* llm.inputs).at(-1)?.messages)
expect(body.match(/pending request/g)).toHaveLength(1)
expect(body).toContain("PENDINGIMAGE")
const messages = yield* sessions.messages({ sessionID: chat.id })
const resumed = messages.findLast((msg) => msg.info.role === "user")
expect(resumed?.info.role === "user" ? resumed.info.editorContext : undefined).toEqual(editor)
expect(
messages
.flatMap((msg) => msg.parts)
.filter((part) => part.type === "text" && part.text === "pending request" && !part.synthetic),
).toHaveLength(1)
}),
{ git: true, config: providerCfg },
),
30_000,
)

for (const finish of ["stop", "tool_calls", "length"] as const) {
it.live(
`does not replay completed work after a ${finish} response exceeds the budget`,
() =>
provideTmpdirServer(
Effect.fnUntraced(function* ({ llm }) {
const prompt = yield* SessionPrompt.Service
const sessions = yield* Session.Service
const tools = finish !== "stop"
const chat = yield* sessions.create({ permission: [{ permission: "*", pattern: "*", action: "allow" }] })
yield* llm.push(
(tools ? reply().tool("glob", { pattern: "*.txt" }) : reply().text("answer"))
.finish(finish)
.usage({ input: 95_000, output: 100 }),
)
if (tools) {
yield* llm.text("tool progress summary")
yield* llm.text("answer")
}
yield* user(chat.id, "perform this once")

const result = yield* prompt.loop({ sessionID: chat.id })

expect(yield* llm.calls).toBe(tools ? 3 : 1)
expect(result.parts.some((part) => part.type === "text" && part.text === "answer")).toBe(true)
const parts = (yield* sessions.messages({ sessionID: chat.id })).flatMap((msg) => msg.parts)
expect(parts.filter((part) => part.type === "text" && part.text === "perform this once")).toHaveLength(1)
expect(parts.filter((part) => part.type === "tool")).toHaveLength(tools ? 1 : 0)
}),
{ git: true, config: providerCfg },
),
30_000,
)
}

it.live(
"includes completed tool progress when a saved marker requests replay",
() =>
provideTmpdirServer(
Effect.fnUntraced(function* ({ llm }) {
const prompt = yield* SessionPrompt.Service
const sessions = yield* Session.Service
const compaction = yield* SessionCompaction.Service
const chat = yield* sessions.create({})
const old = yield* user(chat.id, "old request")
yield* assistant(chat.id, old.id)
const request = yield* user(chat.id, "run the tool")
const response = yield* assistant(chat.id, request.id, { finish: "tool-calls" })
yield* sessions.updatePart({
id: PartID.ascending(),
sessionID: chat.id,
messageID: response.id,
type: "tool",
callID: "call_glob",
tool: "glob",
state: {
status: "completed",
input: { pattern: "*.txt" },
output: "already ran glob",
title: "glob",
metadata: {},
time: { start: Date.now(), end: Date.now() },
},
})
yield* compaction.create({ sessionID: chat.id, agent: "code", model: ref, auto: true, overflow: false })
yield* llm.text("tool progress summary")
yield* llm.text("answer")

yield* prompt.loop({ sessionID: chat.id })

expect(yield* llm.calls).toBe(2)
expect(JSON.stringify((yield* llm.inputs)[0]?.messages)).toContain("already ran glob")
const messages = yield* sessions.messages({ sessionID: chat.id })
expect(
messages.flatMap((msg) => msg.parts).filter((part) => part.type === "text" && part.text === "run the tool"),
).toHaveLength(1)
}),
{ git: true, config: providerCfg },
),
30_000,
)

it.live("trims plain-text summary history before provider request", () =>
provideTmpdirServer(
Effect.fnUntraced(function* ({ llm }) {
Expand Down
Loading