Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
7 changes: 7 additions & 0 deletions .changeset/improve-background-agent-control.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"kilo-code": patch
"@kilocode/cli": patch
"@kilocode/sdk": patch
---

Keep background agents running when you stop the main agent. Show their activity beside the session controls and open the existing agent bar to stop individual agents or all background work.
16 changes: 10 additions & 6 deletions packages/kilo-vscode/src/KiloProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1152,7 +1152,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
}
case "abort":
this.cancelRetry(message.sessionID ?? "")
await this.handleAbort(message.sessionID)
await this.handleAbort(message.sessionID, message.scope)
break
case "revertSession":
this.checkpoint(message.sessionID, () =>
Expand Down Expand Up @@ -4205,14 +4205,18 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
await Promise.all([...targets].map((sid) => this.stopSession(sid)))
}

private stopSession(sid: string): Promise<boolean> {
private stopSession(sid: string, scope?: "session" | "tree"): Promise<boolean> {
this.cancelRetry(sid)
const client = this.client
if (!client) return Promise.resolve(false)
const dir = this.getWorkspaceDirectory(sid)
this.aborts.preserve(sid, this.sessionStatusMap.get(sid), dir)
return this.aborts.stop(client, sid, dir, (dir, action) =>
this.connectionService.runExplicitAbort(sid, dir, action),
return this.aborts.stop(
client,
sid,
dir,
(dir, action) => this.connectionService.runExplicitAbort(sid, dir, action),
scope,
)
}

Expand All @@ -4237,9 +4241,9 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
}
}

private async handleAbort(sessionID?: string): Promise<void> {
private async handleAbort(sessionID?: string, scope?: "session" | "tree"): Promise<void> {
const sid = sessionID || this.currentSession?.id
if (!sid || !(await this.stopSession(sid))) return
if (!sid || !(await this.stopSession(sid, scope))) return
this.mark(sid)
this.publish(sid, { type: "idle" })
}
Expand Down
1 change: 1 addition & 0 deletions packages/kilo-vscode/src/agent-manager/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -985,6 +985,7 @@ interface ForkSessionIn {
interface AbortIn {
type: "abort"
sessionID: string
scope?: "session" | "tree"
}

interface ContinueInWorktreeIn {
Expand Down
15 changes: 12 additions & 3 deletions packages/kilo-vscode/src/kilo-provider/abort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,14 @@ export class SessionAbort {
sessionID: string,
fallback: string,
run?: (dir: string, action: () => Promise<void>) => Promise<void>,
scope?: "session" | "tree",
) {
const known = this.active.has(sessionID)
const dirs = [...(this.active.get(sessionID) ?? [])]
if (!dirs.some((dir) => sameDirectory(dir, fallback))) dirs.push(fallback)
const results = await Promise.allSettled(
dirs.map((dir) => {
const action = () => abortSession({ client, sessionID, dir })
const action = () => abortSession({ client, sessionID, dir, scope })
return known && run ? run(dir, action) : action()
}),
)
Expand Down Expand Up @@ -75,6 +76,14 @@ export class SessionAbort {
}
}

export async function abortSession(input: { client: KiloClient; sessionID: string; dir: string }) {
await input.client.session.abort({ sessionID: input.sessionID, directory: input.dir }, { throwOnError: true })
export async function abortSession(input: {
client: KiloClient
sessionID: string
dir: string
scope?: "session" | "tree"
}) {
await input.client.session.abort(
{ sessionID: input.sessionID, directory: input.dir, scope: input.scope },
{ throwOnError: true },
)
}
136 changes: 136 additions & 0 deletions packages/kilo-vscode/tests/prompt-background-agents.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { expect, test, type Locator, type Page } from "@playwright/test"
import type { WebviewMessage } from "../webview-ui/src/types/messages"

const globals = "colorScheme:dark;theme:kilo-vscode;vscodeTheme:dark-modern"
const count = ".session-background-agents:visible"
const header = '[data-component="task-header-agents"]'
const parent = "background-parent"

async function open(page: Page, width = 420) {
await page.setViewportSize({ width, height: 720 })
await page.goto(`/iframe.html?id=chat--chat-view-background-agents&viewMode=story&globals=${globals}`)
await page.addStyleTag({
content: "*, *::before, *::after { animation-duration: 0s !important; transition-duration: 0s !important; }",
})
await expect(page.locator(count)).toHaveText("2")
await expect(page.locator(count)).toHaveAttribute("aria-label", "2 background agents")
await page.evaluate(() => document.fonts.ready)
}

async function events(page: Page, type: WebviewMessage["type"]) {
const messages = JSON.parse((await page.getByTestId("background-events").textContent()) ?? "[]") as WebviewMessage[]
return messages.filter((message) => message.type === type)
}

async function bounds(node: Locator) {
const rect = await node.boundingBox()
expect(rect).not.toBeNull()
return rect!
}

for (const width of [200, 420]) {
test(`one count button shares the dock row and focuses the top bar at ${width}px`, async ({ page }) => {
await open(page, width)
const dock = page.locator('[data-component="session-dock"]')
const height = (await bounds(dock)).height
for (const selector of [".session-actions-row", ".working-indicator"]) {
await expect(page.locator(count)).toHaveCount(1)
await expect(page.locator(`${selector} ${count}`)).toHaveCount(1)
await expect(dock.locator('.session-dock-state[aria-hidden="true"] .session-background-agents')).toHaveCount(1)
await expect(page.locator(".prompt-input-container .session-background-agents")).toHaveCount(0)
const rect = await bounds(page.locator(count))
const peers = await page
.locator(`${selector}:visible`)
.locator("button:not(.session-background-agents), .working-status, .working-elapsed")
.evaluateAll((nodes) =>
nodes.map((node) => {
const box = node.getBoundingClientRect()
return { left: box.left, right: box.right, top: box.top, bottom: box.bottom }
}),
)
expect(rect.x).toBeGreaterThanOrEqual(0)
expect(rect.x + rect.width).toBeLessThanOrEqual(width)
expect(rect.y + rect.height).toBeLessThanOrEqual((await bounds(page.locator(".prompt-input-container"))).y)
const shared = peers.some((peer) => peer.top < rect.y + rect.height && peer.bottom > rect.y)
expect.soft(shared, `${selector} shares the count row`).toBe(true)
for (const peer of peers) {
const x = Math.min(rect.x + rect.width, peer.right) - Math.max(rect.x, peer.left)
const y = Math.min(rect.y + rect.height, peer.bottom) - Math.max(rect.y, peer.top)
expect(x > 0.5 && y > 0.5, `count overlaps ${selector} control at ${width}px`).toBe(false)
}
await page.locator(count).click()
await expect(page.locator(`${header} [data-slot="task-header-todos-list"]`)).toBeVisible()
await expect(page.locator(`${header} [data-slot="task-header-agents-toggle"]`)).toBeFocused()
await page.locator(`${header} [data-slot="task-header-agents-toggle"]`).click()
await page.getByTestId("toggle-busy").click()
await expect.poll(async () => (await bounds(dock)).height).toBe(height)
}
})
}

test("top bar opens, stops, and dismisses individual agents", async ({ page }) => {
await open(page)
await page.locator(count).click()
const list = page.locator(`${header} [data-slot="task-header-todos-list"]`)
const rows = list.locator('[data-slot="task-header-agent"]')
await expect(rows).toHaveCount(3)
await expect(list.getByText("Other session task", { exact: true })).toHaveCount(0)
await list.getByRole("button", { name: "Open background agent: Trace request limits", exact: true }).click()
await expect
.poll(() => events(page, "openSubAgentViewer"))
.toEqual([
{
type: "openSubAgentViewer",
sessionID: "background-limits",
title: "Trace request limits",
parentSessionID: parent,
},
])
await list.getByRole("button", { name: "Stop: Trace request limits", exact: true }).click()
await expect
.poll(() => events(page, "cancelBackgroundJob"))
.toEqual([{ type: "cancelBackgroundJob", sessionID: parent, jobID: "job-limits", requestID: expect.any(String) }])
await expect(rows.filter({ hasText: "Trace request limits" })).toHaveAttribute("data-status", "cancelled")
await expect(rows.filter({ hasText: "Check prompt layout" })).toHaveAttribute("data-status", "running")
await expect(page.locator(count)).toHaveAttribute("aria-label", "1 background agent")
await expect(page.locator(`${header} [data-slot="task-header-agents-actions"]`)).toHaveText("Stop all (1)")
await list.getByRole("button", { name: "Dismiss: Trace request limits", exact: true }).click()
await expect(rows).toHaveCount(2)
await expect(rows.filter({ hasText: "Trace request limits" })).toHaveCount(0)
expect(await events(page, "abort")).toEqual([])
})

for (const action of ["Escape", "Stop"]) {
test(`main ${action} stops only the parent with the top bar open`, async ({ page }) => {
await open(page)
await page.getByTestId("toggle-busy").click()
await page.locator(count).click()
await (action === "Escape"
? page.keyboard.press(action)
: page.locator(".prompt-input-hint-actions").getByRole("button", { name: "Stop", exact: true }).click())
await expect.poll(() => events(page, "abort")).toEqual([{ type: "abort", sessionID: parent, scope: "session" }])
await expect(page.getByTestId("background-fixture")).toHaveAttribute("data-status", "idle")
await expect(page.locator(count)).toHaveText("2")
expect(await events(page, "cancelBackgroundJob")).toEqual([])
})
}

test("Stop all immediately stops this session's running tasks without a dialog or parent abort", async ({ page }) => {
await open(page)
await page.getByTestId("toggle-busy").click()
await page.locator(count).click()
await page
.locator(`${header} [data-slot="task-header-agents-actions"]`)
.getByRole("button", { name: "Stop all (2)", exact: true })
.click()
await expect(page.getByRole("dialog")).toHaveCount(0)
await expect
.poll(() => events(page, "cancelBackgroundJob"))
.toEqual([
{ type: "cancelBackgroundJob", sessionID: parent, jobID: "job-limits", requestID: expect.any(String) },
{ type: "cancelBackgroundJob", sessionID: parent, jobID: "job-layout", requestID: expect.any(String) },
])
await expect(page.locator(count)).toHaveCount(0)
await expect(page.getByTestId("background-fixture")).toHaveAttribute("data-status", "busy")
expect(await events(page, "abort")).toEqual([])
})
39 changes: 21 additions & 18 deletions packages/kilo-vscode/tests/unit/abort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,28 @@ function client(calls: unknown[], fail = false) {
}

describe("SessionAbort", () => {
it("stops the active owner and current mapped directory", async () => {
const calls: unknown[] = []
const aborts = new SessionAbort()
aborts.observe("session_1", "busy", "/repo")
it.each([undefined, "session", "tree"] as const)(
"stops the active owner and current mapped directory with %s scope",
async (scope) => {
const calls: unknown[] = []
const aborts = new SessionAbort()
aborts.observe("session_1", "busy", "/repo")

expect(await aborts.stop(client(calls), "session_1", "/repo/worktree")).toBe(true)
expect(calls).toEqual([
{
type: "abort",
params: { sessionID: "session_1", directory: "/repo" },
opts: { throwOnError: true },
},
{
type: "abort",
params: { sessionID: "session_1", directory: "/repo/worktree" },
opts: { throwOnError: true },
},
])
})
expect(await aborts.stop(client(calls), "session_1", "/repo/worktree", undefined, scope)).toBe(true)
expect(calls).toEqual([
{
type: "abort",
params: { sessionID: "session_1", directory: "/repo", scope },
opts: { throwOnError: true },
},
{
type: "abort",
params: { sessionID: "session_1", directory: "/repo/worktree", scope },
opts: { throwOnError: true },
},
])
},
)

it("forgets an owner when its instance becomes idle", async () => {
const calls: unknown[] = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, it, expect, spyOn } from "bun:test"
import type { SessionStatus } from "@kilocode/sdk/v2/client"
import * as vscode from "vscode"
import type { PartUpdate } from "../../src/shared/stream-messages"
import type { AbortRequest } from "../../webview-ui/src/types/messages/webview-messages"

// vscode mock is provided by the shared preload (tests/setup/vscode-mock.ts)
const { KiloProvider, unwrapSyncEvent } = await import("../../src/KiloProvider")
Expand Down Expand Up @@ -79,7 +80,7 @@ function createClient(options?: {
}) {
const calls: { before?: string; limit?: number }[] = []
const stopped: { sessionID: string; directory?: string }[] = []
const aborted: { sessionID: string; directory?: string }[] = []
const aborted: { sessionID: string; directory?: string; scope?: "session" | "tree" }[] = []
const deleted: { sessionID: string; directory?: string }[] = []
const deletedMessages: Array<{
sessionID: string
Expand Down Expand Up @@ -126,7 +127,7 @@ function createClient(options?: {
prompted.push(params)
return { data: undefined }
},
abort: async (params: { sessionID: string; directory?: string }) => {
abort: async (params: { sessionID: string; directory?: string; scope?: "session" | "tree" }) => {
aborted.push(params)
if (params.directory && options?.abortFailures?.includes(params.directory)) throw new Error("abort failed")
await options?.abortDeferred?.promise
Expand Down Expand Up @@ -252,7 +253,8 @@ type ProviderInternals = {
seedSessionStatusMap: (reconcile?: boolean) => Promise<void>
stopCurrentSessionProcesses: (next?: string) => void
handleEvent: (event: unknown, directory?: string) => void
handleAbort: (sid?: string) => Promise<void>
setupWebviewMessageHandler: (webview: unknown) => void
handleAbort: (sid?: string, scope?: "session" | "tree") => Promise<void>
resolveSession: (sid?: string, draft?: string, context?: string, dir?: string) => Promise<unknown>
handleCostAlertResponse: (sid: string, limit: number, response: "continue" | "stop") => Promise<void>
setMaxCost: (value: unknown) => void
Expand Down Expand Up @@ -291,6 +293,32 @@ function mockMaxCost(internal: ProviderInternals, value: number) {
}

describe("KiloProvider.handleAbort", () => {
it.each([undefined, "session", "tree"] as const)(
"forwards %s abort scope without extra child or process stops",
async (scope) => {
const client = createClient()
const { provider, internal } = makeProvider(client)
const listener = Promise.withResolvers<(message: AbortRequest) => Promise<void>>()
internal.setupWebviewMessageHandler({
onDidReceiveMessage: (handler: (message: AbortRequest) => Promise<void>) => {
listener.resolve(handler)
return { dispose: () => {} }
},
})
const receive = await listener.promise
status(internal, "busy")
status(internal, "busy", "/repo", "child")

await receive({ type: "abort", sessionID: "s1", scope })

expect(client.aborted).toEqual([{ sessionID: "s1", directory: "/repo", scope }])
expect(client.stopped).toEqual([])
expect(internal.sessionStatusMap.get("s1")).toBe("idle")
expect(internal.sessionStatusMap.get("child")).toBe("busy")
provider.dispose()
},
)

it("aborts a session whose busy status was seeded without an SSE event", async () => {
const client = createClient()
const { internal, sent } = makeProvider(client)
Expand Down
26 changes: 26 additions & 0 deletions packages/kilo-vscode/tests/unit/prompt-continue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,32 @@ describe("empty prompt continuation", () => {
expect(continuation({ ...input, messages: [user, { ...assistant, finish: "stop" }] })).toBe(assistant.id)
})

it("keeps a stopped turn resumable while background results wait for user input", () => {
const job = { ...user, id: "background" }
const part: Part = {
id: "result",
sessionID: "session",
messageID: job.id,
type: "text",
text: "Background task completed",
synthetic: true,
metadata: { background: true },
}
const next = {
...input,
messages: [user, assistant, job],
parts: (id: string) => (id === job.id ? [part] : []),
}
expect(continuation(next)).toBe(assistant.id)
expect(continuation({ ...next, parts: () => [{ ...part, metadata: {} }] })).toBeUndefined()
expect(
continuation({
...next,
messages: [...next.messages, { ...assistant, id: "reply", parentID: job.id, error: undefined, finish: "stop" }],
}),
).toBeUndefined()
})

it("accepts unfinished assistant and tool-call turns", () => {
for (const finish of [undefined, "tool-calls"]) {
expect(continuation({ ...input, messages: [user, { ...assistant, error: undefined, finish }] })).toBe(
Expand Down
Loading