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
6 changes: 6 additions & 0 deletions .changeset/faster-vscode-settings-save.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"kilo-code": patch
"@kilocode/cli": patch
---

Speed up VS Code settings saves by draining pending prompts and disposing worktree instances concurrently.
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,108 @@ describe("KiloConnectionService drainPendingPrompts", () => {

await expect(service.drainPendingPrompts()).resolves.toBeUndefined()
})

test("drains four directories concurrently and suggestions once", async () => {
const service = new KiloConnectionService({} as any)
const dirs = ["/tmp/a", "/tmp/b", "/tmp/c", "/tmp/d", "/tmp/e"]
const gates = new Map(dirs.map((dir) => [dir, Promise.withResolvers<void>()]))
const fifth = Promise.withResolvers<void>()
const calls: string[] = []
let cleared = 0
const client = {
permission: {
list: async ({ directory }: { directory: string }) => {
calls.push(`permission:${directory}`)
if (directory === dirs[4]) fifth.resolve()
await gates.get(directory)!.promise
return { data: [] }
},
},
question: {
list: async ({ directory }: { directory: string }) => {
calls.push(`question:${directory}`)
return { data: [] }
},
},
suggestion: {
list: async ({ directory }: { directory: string }) => {
calls.push(`suggestion:${directory}`)
return { data: [] }
},
},
network: {
list: async ({ directory }: { directory: string }) => {
calls.push(`network:${directory}`)
return { data: [] }
},
},
}

;(service as any).client = client
;(service as any).directoryProviders.add(() => dirs)
service.onClearPendingPrompts(() => cleared++)

const pending = service.drainPendingPrompts()
expect(calls).toEqual(dirs.slice(0, 4).map((dir) => `permission:${dir}`))

gates.get(dirs[0])!.resolve()
await fifth.promise
expect(calls.filter((call) => call.startsWith("permission:"))).toEqual(dirs.map((dir) => `permission:${dir}`))

for (const gate of gates.values()) gate.resolve()
await pending

expect(calls.filter((call) => call.startsWith("suggestion:"))).toEqual([`suggestion:${dirs[0]}`])
const suggestion = calls.findIndex((call) => call.startsWith("suggestion:"))
expect(calls.filter((call) => call.startsWith("question:")).every((call) => calls.indexOf(call) < suggestion)).toBe(
true,
)
expect(calls.filter((call) => call.startsWith("network:")).every((call) => calls.indexOf(call) > suggestion)).toBe(
true,
)
expect(cleared).toBe(1)
})

test("waits for active drains and skips queued directories after a failure", async () => {
const service = new KiloConnectionService({} as any)
const dirs = ["/tmp/a", "/tmp/b", "/tmp/c", "/tmp/d", "/tmp/e"]
const release = Promise.withResolvers<void>()
const calls: string[] = []
let cleared = 0
const client = {
permission: {
list: async ({ directory }: { directory: string }) => {
calls.push(directory)
if (directory === dirs[0]) await release.promise
if (directory === dirs[1]) return { error: "failed" }
return { data: [] }
},
},
question: { list: async () => ({ data: [] }) },
suggestion: { list: async () => ({ data: [] }) },
network: { list: async () => ({ data: [] }) },
}

;(service as any).client = client
;(service as any).directoryProviders.add(() => dirs)
service.onClearPendingPrompts(() => cleared++)

const pending = service.drainPendingPrompts()
expect(calls).toEqual(dirs.slice(0, 4))
expect(
await Promise.race([
pending.then(
() => "settled",
() => "settled",
),
Promise.resolve("pending"),
]),
).toBe("pending")
expect(calls).not.toContain(dirs[4])

release.resolve()
await expect(pending).rejects.toThrow(`Failed to list permissions for ${dirs[1]}`)
expect(calls).not.toContain(dirs[4])
expect(cleared).toBe(0)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,31 @@ type FavoritesChangeListener = (favorites: Array<{ providerID: string; modelID:
type ModelSelectorExpandedListener = (value: boolean) => void
type ClearPendingPromptsListener = () => void
type DirectoryProvider = () => string[]
const DRAIN_CONCURRENCY = 4

async function parallel(items: string[], fn: (item: string) => Promise<void>): Promise<void> {
let next = 0
const errors = new Map<number, unknown>()
const worker = async () => {
while (errors.size === 0) {
const index = next++
if (index >= items.length) return
try {
await fn(items[index]!)
} catch (error) {
errors.set(index, error)
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
}
}
}

await Promise.all(Array.from({ length: Math.min(DRAIN_CONCURRENCY, items.length) }, worker))
if (errors.size === 0) return
const failures = [...errors].sort((a, b) => a[0] - b[0])
for (const [index, error] of failures.slice(1)) {
console.warn(`[Kilo New] ConnectionService: Additional prompt drain failed for ${items[index]}:`, error)
}
throw failures[0]![1]
}

function isNotFound(err: unknown) {
if (!err || typeof err !== "object") return false
Expand Down Expand Up @@ -505,7 +530,8 @@ export class KiloConnectionService {
* destructive operation.
*/
async drainPendingPrompts(): Promise<void> {
if (!this.client) return
const client = this.client
if (!client) return

// Only drain directories from currently-mounted providers (root + worktree dirs).
// Previously this also called project.list() to include every historically-opened
Expand All @@ -519,26 +545,29 @@ export class KiloConnectionService {
}
}

for (const dir of dirs) {
const { data: perms, error: permsErr } = await this.client.permission.list({ directory: dir })
const list = [...dirs]
await parallel(list, async (dir) => {
const { data: perms, error: permsErr } = await client.permission.list({ directory: dir })
if (permsErr) throw new Error(`Failed to list permissions for ${dir}: ${String(permsErr)}`)
if (perms) {
for (const perm of perms) {
const { error } = await this.client.permission.reply({ requestID: perm.id, reply: "reject", directory: dir })
const { error } = await client.permission.reply({ requestID: perm.id, reply: "reject", directory: dir })
if (error && !isNotFound(error)) throw new Error(`Failed to reject permission ${perm.id}: ${String(error)}`)
}
}
const { data: qs, error: qsErr } = await this.client.question.list({ directory: dir })
const { data: qs, error: qsErr } = await client.question.list({ directory: dir })
if (qsErr) throw new Error(`Failed to list questions for ${dir}: ${String(qsErr)}`)
if (qs) {
for (const q of qs) {
const { error } = await this.client.question.reject({ requestID: q.id, directory: dir })
const { error } = await client.question.reject({ requestID: q.id, directory: dir })
if (error && !isNotFound(error)) throw new Error(`Failed to reject question ${q.id}: ${String(error)}`)
}
}
await drainSuggestions(this.client, dir)
await drainNetworkWaits(this.client, dir)
}
})

// Suggestions are backend-global despite the directory-bearing SDK route.
if (list[0]) await drainSuggestions(client, list[0])
await parallel(list, (dir) => drainNetworkWaits(client, dir))
for (const listener of this.clearPendingPromptsListeners) {
listener()
}
Expand Down
31 changes: 22 additions & 9 deletions packages/opencode/src/project/instance-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,12 @@ export const layer: Layer.Layer<Service, never, Project.Service | InstanceBootst

const disposeEntry = Effect.fnUntraced(function* (directory: string, entry: Entry, ctx: InstanceContext) {
if (cache.get(directory) !== entry) return false
yield* disposeContext(ctx)
if (cache.get(directory) !== entry) return false
cache.delete(directory)
return true
// kilocode_change start - remove disposed entries even when event publication fails
const exit = yield* Effect.exit(disposeContext(ctx))
const removed = yield* removeEntry(directory, entry)
yield* exit
return removed
// kilocode_change end
})

const load = (input: LoadInput): Effect.Effect<InstanceContext> => {
Expand Down Expand Up @@ -163,8 +165,10 @@ export const layer: Layer.Layer<Service, never, Project.Service | InstanceBootst

const disposeAllOnce = Effect.fnUntraced(function* () {
yield* Effect.logInfo("disposing all instances")
yield* Effect.forEach(
[...cache.entries()],
// kilocode_change start - dispose independent worktrees concurrently without interrupting siblings
const entries = [...cache.entries()]
const exits = yield* Effect.forEach(
entries,
(item) =>
Effect.gen(function* () {
const exit = yield* Deferred.await(item[1].deferred).pipe(Effect.exit)
Expand All @@ -176,9 +180,18 @@ export const layer: Layer.Layer<Service, never, Project.Service | InstanceBootst
return
}
yield* disposeEntry(item[0], item[1], exit.value)
}),
{ discard: true },
)
}).pipe(Effect.exit),
{ concurrency: 4 },
).pipe(Effect.uninterruptible)
for (const [index, exit] of exits.entries()) {
if (Exit.isSuccess(exit)) continue
yield* Effect.logWarning("instance dispose failed").pipe(
Effect.annotateLogs({ key: entries[index]![0], cause: exit.cause }),
)
}
const failure = exits.find(Exit.isFailure)
if (failure) yield* failure
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
// kilocode_change end
})

const cachedDisposeAll = yield* Effect.cachedWithTTL(disposeAllOnce(), Duration.zero)
Expand Down
117 changes: 117 additions & 0 deletions packages/opencode/test/kilocode/project/instance-store.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { describe, expect } from "bun:test"
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
import { Deferred, Effect, Exit, Fiber, Layer, Scope } from "effect"
import { GlobalBus } from "../../../src/bus/global"
import { registerDisposer } from "../../../src/effect/instance-registry"
import { InstanceBootstrap } from "../../../src/project/bootstrap-service"
import { InstanceStore } from "../../../src/project/instance-store"
import { tmpdirScoped } from "../../fixture/fixture"
import { awaitWithTimeout, testEffect } from "../../lib/effect"

const bootstrap = Layer.succeed(InstanceBootstrap.Service, InstanceBootstrap.Service.of({ run: Effect.void }))
const it = testEffect(
Layer.mergeAll(InstanceStore.defaultLayer, CrossSpawnSpawner.defaultLayer).pipe(Layer.provide(bootstrap)),
)

const register = (disposer: (directory: string) => Promise<void>) =>
Effect.acquireRelease(
Effect.sync(() => registerDisposer(disposer)),
(off) => Effect.sync(off),
)

describe("InstanceStore disposal", () => {
it.live("disposes four directories concurrently", () =>
Effect.gen(function* () {
const dirs = yield* Effect.all(
Array.from({ length: 4 }, () => tmpdirScoped({ git: true })),
{ concurrency: "unbounded" },
)
const store = yield* InstanceStore.Service
const ready = yield* Deferred.make<void>()
const release = yield* Deferred.make<void>()
const started = new Set<string>()

yield* Effect.addFinalizer(() => Deferred.succeed(release, undefined).pipe(Effect.ignore))
yield* register(async (directory) => {
if (!dirs.includes(directory)) return
started.add(directory)
if (started.size === dirs.length) Deferred.doneUnsafe(ready, Effect.void)
await Effect.runPromise(Deferred.await(release))
})

yield* Effect.forEach(dirs, (directory) => store.load({ directory }), { discard: true })
const fiber = yield* store.disposeAll().pipe(Effect.forkScoped)

yield* awaitWithTimeout(Deferred.await(ready), "instance disposal remained serial")
expect(started).toEqual(new Set(dirs))

yield* Deferred.succeed(release, undefined)
yield* Fiber.join(fiber)
}),
)

it.live("finishes sibling disposal when an event listener throws", () =>
Effect.gen(function* () {
const dirs = yield* Effect.all(
Array.from({ length: 4 }, () => tmpdirScoped({ git: true })),
{ concurrency: "unbounded" },
)
const store = yield* InstanceStore.Service
const before = yield* Effect.forEach(dirs, (directory) => store.load({ directory }))
const disposed = new Set<string>()
const listener = (event: { directory?: string; payload?: { type?: string } }) => {
if (event.payload?.type === "server.instance.disposed" && event.directory === dirs[0]) {
throw new Error("listener failed")
}
}

yield* register(async (directory) => {
if (dirs.includes(directory)) disposed.add(directory)
})
GlobalBus.on("event", listener)
yield* Effect.addFinalizer(() => Effect.sync(() => GlobalBus.off("event", listener)))

const exit = yield* Effect.exit(store.disposeAll())
GlobalBus.off("event", listener)

expect(Exit.isFailure(exit)).toBe(true)
expect(disposed).toEqual(new Set(dirs))

const after = yield* Effect.forEach(dirs, (directory) => store.load({ directory }))
for (const [index, ctx] of after.entries()) {
expect(ctx).not.toBe(before[index])
}
}),
)

it.live("finishes queued disposal when the caller is interrupted", () =>
Effect.gen(function* () {
const dirs = yield* Effect.all(
Array.from({ length: 5 }, () => tmpdirScoped({ git: true })),
{ concurrency: "unbounded" },
)
const store = yield* InstanceStore.Service
const ready = yield* Deferred.make<void>()
const release = yield* Deferred.make<void>()
const started = new Set<string>()

yield* Effect.addFinalizer(() => Deferred.succeed(release, undefined).pipe(Effect.ignore))
yield* register(async (directory) => {
if (!dirs.includes(directory)) return
started.add(directory)
if (started.size === 4) Deferred.doneUnsafe(ready, Effect.void)
await Effect.runPromise(Deferred.await(release))
})
yield* Effect.forEach(dirs, (directory) => store.load({ directory }), { discard: true })

const disposal = yield* store.disposeAll().pipe(Effect.forkScoped)
yield* awaitWithTimeout(Deferred.await(ready), "bounded disposal did not start")
const scope = yield* Scope.Scope
const interrupted = yield* Fiber.interrupt(disposal).pipe(Effect.forkIn(scope, { startImmediately: true }))
yield* Deferred.succeed(release, undefined)
yield* Fiber.join(interrupted)

expect(started).toEqual(new Set(dirs))
}),
)
})
Loading