Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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/quiet-hidden-diff-polling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Pause Changes, Review, and chat badge polling while their panels are hidden, and reuse unchanged file counts to reduce CPU use in large repositories.
19 changes: 12 additions & 7 deletions packages/kilo-vscode/src/KiloProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
private followupListeners: Array<(session: Session, directory: string) => void> = []
private statsPoller: GitStatsPoller | null = null
private statsGitOps: GitOps | null = null
private statsVisible = true
private cachedStats: unknown = null
private cachedGitRepo = false
private cachedGitDirectory: string | undefined
Expand Down Expand Up @@ -778,16 +779,13 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.visibilityDisposable?.dispose()
this.visibilityDisposable = webviewView.onDidChangeVisibility(() => {
this.setSidebarVisible(webviewView.visible)
if (this.statsPoller) {
this.statsPoller.setEnabled(webviewView.visible)
this.statsPoller.setVisible(webviewView.visible)
}
this.focusSession(webviewView.visible ? this.contextSessionID : undefined)
})
this.initializeConnection()
}

private setSidebarVisible(visible: boolean): void {
this.setStatsVisible(visible)
this.setStreamVisibility(visible)
vscode.commands.executeCommand("setContext", "kilo-code.new.sidebarVisible", visible)
if (!visible && this.opts.focusContext) {
Expand All @@ -811,12 +809,14 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.setupWebviewMessageHandler(panel.webview)
this.viewStateDisposable?.dispose()
this.viewStateDisposable = this.visibleTaskStreams.bindPanel(panel, () => {
this.setStatsVisible(panel.visible)
this.setStreamVisibility(panel.active && panel.visible)
if (this.opts.disableViewedRegistration) return
const id = this.contextSessionID
this.streams.focus(panel.visible ? id : undefined)
this.connectionService.registerVisible(this.instanceId, panel.visible && id ? [id] : [])
})
this.setStatsVisible(panel.visible)
this.setStreamVisibility(panel.active && panel.visible)
this.initializeConnection()
}
Expand Down Expand Up @@ -5485,6 +5485,12 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
}

// ── Worktree stats polling (sidebar diff badge) ──────────────────
private setStatsVisible(visible: boolean): void {
this.statsVisible = visible
this.statsPoller?.setEnabled(visible)
this.statsPoller?.setVisible(visible)
}

private startStatsPolling(): void {
if (this.opts.disableStatsPolling) return
this.statsPoller?.stop()
Expand All @@ -5509,8 +5515,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
log: () => {},
hiddenIntervalMs: 60000,
})
this.statsPoller.setEnabled(true)
this.statsPoller.setVisible(true)
this.setStatsVisible(this.statsVisible)
}

/**
Expand All @@ -5526,7 +5531,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.streams.focus(undefined)
this.connectionService.unregisterVisible(this.instanceId)
this.connectionService.unregisterAttached(this.instanceId)
this.statsPoller?.stop()
this.setStatsVisible(false)
this.statsGitOps?.dispose()
this.unsubscribeEvent?.()
this.unsubscribeState?.()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -393,12 +393,10 @@ export class AgentManagerProvider implements Disposable {
this.panel = ctx
this.browserLifecycle.replay()

this.statsPoller.setVisible(ctx.visible)
this.projectPollers.setVisible(ctx.visible)
for (const poller of [this.statsPoller, this.projectPollers, this.diffs]) void poller.setVisible(ctx.visible)
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
this.onVisibilityChange?.(ctx.visible)
ctx.onDidChangeVisibility((visible) => {
this.statsPoller.setVisible(visible)
this.projectPollers.setVisible(visible)
for (const poller of [this.statsPoller, this.projectPollers, this.diffs]) void poller.setVisible(visible)
this.visiblePresence.flush()
})

Expand Down
46 changes: 32 additions & 14 deletions packages/kilo-vscode/src/agent-manager/git-stats-snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ import { createHash } from "crypto"
import type { BigIntStats } from "fs"
import * as fs from "fs/promises"
import { LRUCache } from "lru-cache"
import { binaryFile } from "../diff/shared/binary"
import { probe } from "../diff/shared/binary"
import { resolveInside } from "../diff/shared/path"
import { serialize } from "../util/serialize"
import type { GitOps } from "./GitOps"
import { Semaphore } from "./semaphore"

type Measurement = { stamp: string; count: number; binary: boolean }

const MAX_BYTES = 1_000_000n
const reads = new Semaphore(16)
const cache = new LRUCache<string, { stamp: string; count: number }>({ max: 10_000 })
const cache = new LRUCache<string, Measurement>({ max: 10_000 })
let misses = 0

export interface DiffStats {
files: number
Expand Down Expand Up @@ -158,32 +161,47 @@ function numstat(raw: Buffer): DiffStats {
return result
}

export async function lines(file: string): Promise<number> {
export async function measure(file: string, classify = true): Promise<Measurement | undefined> {
return reads.run(async () => {
const stat = await fs.lstat(file, { bigint: true }).catch(() => undefined)
if (!stat) {
cache.delete(file)
return 0
return undefined
}
if (stat.size === 0n || stat.size > MAX_BYTES) return 0
if (!classify && (stat.size === 0n || stat.size > MAX_BYTES)) return { stamp: "", count: 0, binary: false }
const key = stamp(stat)
if (stat.size === 0n) return { stamp: key, count: 0, binary: false }
const hit = cache.get(file)
if (hit?.stamp === key) return hit.count
if (hit?.stamp === key) return hit

const count = await (async () => {
if (await binaryFile(file)) return 0
const content = stat.isSymbolicLink() ? await fs.readlink(file) : await fs.readFile(file, "utf8")
if (!content) return 0
return content.endsWith("\n") ? content.split("\n").length - 1 : content.split("\n").length
const value = await (async () => {
const binary = stat.isFile() ? await probe(file) : false
if (binary === undefined) return undefined
if (binary || stat.size > MAX_BYTES) return { binary, count: 0 }
const current = await fs.lstat(file, { bigint: true })
if (stamp(current) !== key) return undefined
const content = current.isSymbolicLink() ? await fs.readlink(file) : await fs.readFile(file, "utf8")
const count = !content ? 0 : content.endsWith("\n") ? content.split("\n").length - 1 : content.split("\n").length
return { binary, count }
})().catch(() => undefined)
if (count === undefined) return 0
if (!value) return { stamp: key, count: 0, binary: false }

const result = { stamp: key, ...value }
const current = await fs.lstat(file, { bigint: true }).catch(() => undefined)
if (current && stamp(current) === key) cache.set(file, { stamp: key, count })
return count
if (!current || stamp(current) !== key) return result
if (!cache.has(file) && cache.size === cache.max) {
misses = (misses + 1) % 16
if (misses !== 0) return result
}
cache.set(file, result)
return result
})
}

export async function lines(file: string): Promise<number> {
return (await measure(file, false))?.count ?? 0
}

export function refOID(refs: RefSnapshot | undefined, ref: string): string | undefined {
if (!refs) return undefined
if (ref.startsWith("refs/")) return refs.oids.get(ref)
Expand Down
40 changes: 11 additions & 29 deletions packages/kilo-vscode/src/agent-manager/local-diff.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as fs from "fs/promises"
import { binaryFile } from "../diff/shared/binary"
import { imageMime, loadImage, readImageFile } from "../diff/shared/image"
import { resolveInside } from "../diff/shared/path"
import type { GitOps } from "./GitOps"
import { measure } from "./git-stats-snapshot"
import { check, collect, fileSize, MAX_DETAIL_BYTES, readAfter, summarize, type Meta } from "./local-diff-batch"
import { createDiffCache } from "./local-diff-cache"
import type { WorktreeDiffEntry } from "./types"
Expand All @@ -11,10 +11,6 @@ type Status = Meta["status"]

type Log = (...args: unknown[]) => void

/** Cap untracked file reads so line-counting a multi-megabyte log file does
* not stall the poll. Matches `GitOps.workingTreeStats()`. */
const MAX_UNTRACKED_BYTES = 1_000_000

/** Cap per-side reads in the detail view. Opening very large tracked files
* used to spike `kilo serve`; now that the detail path runs in the
* extension host, the same file would spike VS Code's RSS. Over this
Expand Down Expand Up @@ -170,18 +166,6 @@ async function sizes(git: GitOps, dir: string, anc: string, meta: Meta, signal?:
])
}

async function lineCount(file: string): Promise<number> {
const stat = await fs.lstat(file).catch(() => undefined)
if (!stat || stat.size === 0) return 0
if (stat.size > MAX_UNTRACKED_BYTES) return 0
const content = stat.isSymbolicLink()
? await fs.readlink(file).catch(() => "")
: await fs.readFile(file, "utf-8").catch(() => "")
if (!content) return 0
if (content.endsWith("\n")) return content.split("\n").length - 1
return content.split("\n").length
}

function statusFromCode(code: string): Status {
if (code === "A") return "added"
if (code === "D") return "deleted"
Expand Down Expand Up @@ -252,18 +236,17 @@ async function list(git: GitOps, dir: string, anc: string, log?: Log): Promise<M
paths.slice(index, index + MAX_SUMMARY_FILES).map(async (file): Promise<Meta | undefined> => {
const full = resolveInside(dir, file)
if (!full) return undefined
const exists = await fs.lstat(full).catch(() => undefined)
if (!exists) return undefined
const binary = await binaryFile(full)
const value = await measure(full)
if (!value) return undefined
return {
file,
additions: binary ? 0 : await lineCount(full),
additions: value.count,
deletions: 0,
status: "added",
tracked: false,
generatedLike: generatedLike(file),
binary,
stamp: await statStamp(dir, file),
binary: value.binary,
stamp: value.stamp,
}
}),
)
Expand Down Expand Up @@ -321,18 +304,17 @@ async function detailMeta(
})
check(signal)
if (untracked.code !== 0 || !untracked.stdout.split("\n").includes(file)) return undefined
const exists = await fs.lstat(full).catch(() => undefined)
if (!exists) return undefined
const binary = await binaryFile(full)
const value = await measure(full)
if (!value) return undefined
return {
file,
additions: binary ? 0 : await lineCount(full),
additions: value.count,
deletions: 0,
status: "added",
tracked: false,
generatedLike: generatedLike(file),
binary,
stamp: await statStamp(dir, file),
binary: value.binary,
stamp: value.stamp,
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,10 @@ export class WorktreeDiffController {
void this.activate(id, true, true)
}

public setVisible(visible: boolean): Promise<void> {
return this.controller.setVisible(visible)
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
}

public stop(): void {
this.generation++
this.controller.stop()
Expand Down
2 changes: 2 additions & 0 deletions packages/kilo-vscode/src/diff/DiffViewerProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,15 @@ export class DiffViewerProvider implements vscode.Disposable {
(ctx) => this.catalog.listAvailable(ctx),
(msg) => void panel.webview.postMessage(msg),
)
void this.controller.setVisible(panel.visible)
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
if (this.ctx) this.controller.setContext(this.ctx)

this.fontConfigDisposable?.dispose()
this.fontConfigDisposable = watchFontSizeConfig((msg) => void panel.webview.postMessage(msg))

this.panelDisposables.push(
panel.webview.onDidReceiveMessage((msg) => this.onMessage(msg as Record<string, unknown>)),
panel.onDidChangeViewState(() => void this.controller?.setVisible(panel.visible)),
panel.onDidDispose(() => this.onPanelDisposed()),
)
}
Expand Down
31 changes: 24 additions & 7 deletions packages/kilo-vscode/src/diff/SourceController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ export class SourceController {
private interval: ReturnType<typeof setInterval> | undefined
private lastHash: string | undefined
private epoch = 0
private visible = true
private options: ActivateOptions = {}
private readonly fetches = new Map<DiffSource, Promise<boolean>>()

constructor(
Expand All @@ -88,6 +90,16 @@ export class SourceController {
return this.interval !== undefined
}

async setVisible(visible: boolean): Promise<void> {
if (this.visible === visible) return
this.visible = visible
if (!visible) {
this.stopPolling()
return
}
await this.resume()
}

/** Dispose the active source and bump the epoch so in-flight fetches are dropped. */
stop(): void {
this.epoch++
Expand All @@ -108,21 +120,16 @@ export class SourceController {
const ctx = this.ctx
if (!ctx) return
this.stop()
const epoch = this.epoch
this.activeId = id
this.options = opts

const source = this.build(id, ctx)
this.active = source

this.send(this.messages.available?.(this.listAvailable(ctx), id))
this.send(this.messages.capabilities?.(source.descriptor.capabilities))

if (opts.fetch === false) return

const keepPolling = await this.fetch(source, epoch, true)
// Prevents the polling interval from starting after teardown or swap.
if (this.epoch !== epoch || this.activeId !== id) return
if (opts.poll !== false && keepPolling) this.startPolling(source, epoch)
await this.resume()
}

/**
Expand Down Expand Up @@ -246,6 +253,15 @@ export class SourceController {
this.post(msg)
}

private async resume(): Promise<void> {
const source = this.active
const epoch = this.epoch
if (!source || !this.visible || this.options.fetch === false) return
const keep = await this.fetch(source, epoch, true)
if (this.epoch !== epoch || this.active !== source || !this.visible) return
if (this.options.poll !== false && keep) this.startPolling(source, epoch)
}

private startPolling(source: DiffSource, epoch: number): void {
this.stopPolling()
let busy = false
Expand All @@ -268,6 +284,7 @@ export class SourceController {
}

private fetch(source: DiffSource, epoch: number, initial: boolean, force = false): Promise<boolean> {
if (!this.visible) return Promise.resolve(false)
const current = this.fetches.get(source)
if (current && !force) return current
if (current) {
Expand Down
11 changes: 8 additions & 3 deletions packages/kilo-vscode/src/diff/shared/binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,21 @@ function binary(bytes: Uint8Array): boolean {
}

export async function binaryFile(file: string): Promise<boolean> {
return (await probe(file)) ?? false
}

export async function probe(file: string): Promise<boolean | undefined> {
const stat = await fs.lstat(file).catch(() => undefined)
if (!stat?.isFile()) return false
if (!stat) return undefined
if (!stat.isFile()) return false

const handle = await fs.open(file, "r").catch(() => undefined)
if (!handle) return false
if (!handle) return undefined
const sample = Buffer.alloc(SAMPLE_BYTES)
const read = await handle
.read(sample, 0, sample.length, 0)
.catch(() => undefined)
.finally(() => handle.close())
if (!read) return false
if (!read) return undefined
return binary(sample.subarray(0, read.bytesRead))
}
Loading
Loading