Skip to content
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
5df7aa4
fix(vscode): clear unsent drafts on session deletion
IamCoder18 Jun 19, 2026
494817d
fix(vscode): prevent draftKey effect from recreating deleted-session …
IamCoder18 Jun 19, 2026
f310d46
Merge branch 'main' into vscode/cleanup-drafts-on-session-delete
IamCoder18 Jun 19, 2026
152cf66
fix(vscode): forward external session deletions and decouple draft id…
IamCoder18 Jun 19, 2026
d4be9ec
fix(vscode): don't re-track deleted sessions and purge per-session mo…
IamCoder18 Jun 19, 2026
67691a2
fix(vscode): prune per-session state on every deletion path
IamCoder18 Jun 19, 2026
8b7f1ab
merge: upstream main into vscode/cleanup-drafts-on-session-delete
IamCoder18 Jun 19, 2026
faa47d0
fix(vscode): drop sessionStatusMap and respondingPermissions on delete
IamCoder18 Jun 19, 2026
fbe5f4c
fix(vscode): recover from external session deletes during send
IamCoder18 Jun 23, 2026
2db9934
Merge branch 'main' into vscode/cleanup-drafts-on-session-delete
IamCoder18 Jun 23, 2026
2a3f0b0
fix(vscode): restore failed draft into current bucket, not stale session
IamCoder18 Jun 23, 2026
9fc017c
fix(vscode): only restore failed draft into buckets the send was scop…
IamCoder18 Jun 23, 2026
454d35c
fix(vscode): accept :new as restoreFailed candidate when user is back…
IamCoder18 Jun 23, 2026
68f70e2
fix(vscode): suppress :new restoreFailed candidate after user-initiat…
IamCoder18 Jun 23, 2026
1974ddc
fix(vscode): early-return restoreFailed when user explicitly cleared …
IamCoder18 Jun 24, 2026
409ea5f
docs(changeset): note mid-send restore recovery in cleanup-drafts cha…
IamCoder18 Jun 24, 2026
b36b740
fix(vscode): clear userClearedSession when user starts a new draft fr…
IamCoder18 Jun 24, 2026
74f9bf6
Merge branch 'main' into vscode/cleanup-drafts-on-session-delete
IamCoder18 Jun 24, 2026
0601898
fix(vscode): reset userClearedSession on cloud session select and import
IamCoder18 Jun 30, 2026
a63517e
fix(vscode): migrate draftSessionID and prune cloud parts on import
IamCoder18 Jun 30, 2026
b9febc6
fix(vscode): clear draftSessionID on cloudSessionImportFailed
IamCoder18 Jun 30, 2026
0c91183
fix(vscode): guard draftSessionID clear on cloud import failure
IamCoder18 Jun 30, 2026
12ee9ef
fix(vscode): guard currentSessionID clear on cloud import failure
IamCoder18 Jun 30, 2026
733d11d
fix(vscode): guard cloudPreviewId clear on cloud import failure
IamCoder18 Jun 30, 2026
57c09d2
fix(vscode): guard loading clear on cloud import failure
IamCoder18 Jun 30, 2026
37bbbd0
fix(vscode): order loading clear before cloudPreviewId clear on failure
IamCoder18 Jun 30, 2026
9d3b150
Merge remote-tracking branch 'upstream/main' into vscode/cleanup-draf…
IamCoder18 Jun 30, 2026
5eabe93
refactor(vscode): extract cloud-prune helpers and compact session.tsx
IamCoder18 Jul 1, 2026
e4f98ca
fix(vscode): move createCloudPrune inside SessionProvider
IamCoder18 Jul 1, 2026
80a8ee0
fix(vscode): restore prompt-send contract shapes after cloud-prune re…
IamCoder18 Jul 1, 2026
14f6f2d
test(vscode): exercise clearIfOn helper instead of source-grep
IamCoder18 Jul 1, 2026
8f251ad
style(vscode): fix Prettier formatting in KiloProvider.ts
IamCoder18 Jul 1, 2026
3795ae0
fix(vscode): clear cloud preview state on import failure using raw se…
marius-kilocode Jul 3, 2026
d650fb5
Merge origin/main into vscode/cleanup-drafts-on-session-delete
marius-kilocode Jul 3, 2026
33206d7
refactor(vscode): compact session delete cleanup to satisfy max-lines
marius-kilocode Jul 3, 2026
30acec7
refactor(vscode): reduce diff noise vs main
marius-kilocode Jul 3, 2026
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/cleanup-drafts-on-session-delete.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"kilo-code": patch
---

Free webview memory for deleted VS Code sessions by clearing unsent prompt text, review comments, and pending image attachments that were retained in the per-session draft cache after `sessionDeleted`.

Also restores an in-flight failed draft into the live prompt after a session is deleted mid-send (whether user-initiated or via external CLI/TUI/cascade delete), while never rehydrating it into a prompt the user explicitly cleared.
71 changes: 57 additions & 14 deletions packages/kilo-vscode/src/KiloProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1497,6 +1497,16 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
// for the busy-session warning on Save.
if (event.type === "session.status") return true

// session.deleted must always pass through so the webview can run its cleanup
// (messages, parts, stash, todos, permissions, drafts, etc.) — including for
// sessions that were never explicitly tracked here (e.g. child sessions
// cascade-deleted with the parent, or external CLI deletions). We deliberately
// do NOT re-track the deleted id: handleLoadMessages intentionally drops late
// responses for sessions that have been pruned, and re-tracking would let an
// in-flight messagesLoaded response resurrect transcript state for a session
// the webview just cleaned up.
if (event.type === "session.deleted") return true

return this.trackedSessionIds.has(sessionId)
},
(payload, directory) => {
Expand Down Expand Up @@ -1939,6 +1949,37 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
}
}

/**
* Drops every per-session cache entry we hold for the given id. Shared between
* the user-initiated delete path (handleDeleteSession, after the backend
* confirms) and the SSE session.deleted path (cascaded child deletes and
* external CLI/TUI deletes that arrive via the event stream), so both paths
* leave trackedSessionIds, sessionDirectories, and the related Maps in the
* same state — including currentSession / contextSessionID / focused-session
* registration. Without clearing those three, resolveSession() would still
* see the deleted id via this.currentSession and the next send would target
* a session the backend has already deleted.
*/
private pruneDeletedSession(sessionID: string): void {
Comment thread
IamCoder18 marked this conversation as resolved.
Resolved
this.trackedSessionIds.delete(sessionID)
this.streams.drop(sessionID)
this.visibleTaskStreams.delete(sessionID)
this.syncedChildSessions.delete(sessionID)
this.sessionDirectories.delete(sessionID)
this.aborts.delete(sessionID)
this.lastReconciledAt.delete(sessionID)
this.checkpoints.delete(sessionID)
this.revisions.delete(sessionID)
this.refreshes.delete(sessionID)
this.sessionStatusMap.delete(sessionID)
this.connectionService.pruneSession(sessionID)
if (this.currentSession?.id === sessionID) {
this.contextSessionID = undefined
this.setCurrentSession(null)
}
if (this.streams.active === sessionID) this.focusSession(undefined)
}

/**
* Handle deleting a session.
*/
Expand All @@ -1955,17 +1996,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
)
await stopSessionProcesses(this.client, sessionID, workspaceDir)
await this.client.session.delete({ sessionID, directory: workspaceDir }, { throwOnError: true })
this.trackedSessionIds.delete(sessionID)
this.streams.drop(sessionID)
this.visibleTaskStreams.delete(sessionID)
this.syncedChildSessions.delete(sessionID)
this.sessionDirectories.delete(sessionID)
this.aborts.delete(sessionID)
this.lastReconciledAt.delete(sessionID)
this.checkpoints.delete(sessionID)
this.revisions.delete(sessionID)
this.refreshes.delete(sessionID)
this.connectionService.pruneSession(sessionID)
this.pruneDeletedSession(sessionID)
if (this.currentSession?.id === sessionID) {
this.contextSessionID = undefined
this.setCurrentSession(null)
Expand Down Expand Up @@ -3624,9 +3655,12 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
// message.part.* events are always session-scoped; drop if session unknown.
if (!sessionID && isSessionScopedPartEvent(event.type)) return
if (this.postModelUsageChanged(event, sessionID)) return
if (event.type !== "indexing.status" && sessionID && !this.trackedSessionIds.has(sessionID)) {
return
}
if (
event.type !== "indexing.status" &&
event.type !== "session.deleted" &&
Comment thread
IamCoder18 marked this conversation as resolved.
Resolved
sessionID &&
!this.trackedSessionIds.has(sessionID)
) return

if (event.type === "session.updated") {
// Full bus snapshots duplicate sync patches with the same event ID but no sequence metadata.
Expand Down Expand Up @@ -3700,6 +3734,15 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
}
}

// Drop the per-session caches for deleted sessions so a late
// handleLoadMessages response (or any other guarded read) can't resurrect
// transcript state for a session the webview just cleaned up. The
// prefilter lets session.deleted through without re-tracking, and the
// handleEvent guard does the same — this is the matching prune.
if (event.type === "session.deleted" && sessionID) {
this.pruneDeletedSession(sessionID)
}

if (!isLegacySyncEvent(event)) {
const props = event.properties
handleNetworkEvent(
Expand Down
29 changes: 17 additions & 12 deletions packages/kilo-vscode/src/kilo-provider/session-stream-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ function mergePartUpdate(prev: PartUpdate | undefined, msg: PartUpdate): PartUpd
}

export class SessionStreamScheduler {
private active: string | undefined
private _active: string | undefined
private atimer: ReturnType<typeof setTimeout> | null = null
private vtimer: ReturnType<typeof setTimeout> | null = null
private btimer: ReturnType<typeof setTimeout> | null = null
Expand Down Expand Up @@ -146,17 +146,22 @@ export class SessionStreamScheduler {
}

focus(sessionID?: string): void {
if (this.active === sessionID) return
const prev = this.active
if (this._active === sessionID) return
const prev = this._active
if (this.atimer) {
clearTimeout(this.atimer)
this.atimer = null
}
this.active = sessionID
this._active = sessionID
if (prev && this.queues.get(prev)?.size) this.schedule(prev)
if (sessionID) this.flush(sessionID)
}

/** Currently focused (active-lane) session ID, if any. */
get active(): string | undefined {
return this._active
}

setVisible(sessionID: string, visible: boolean): void {
const changed = visible ? !this.visible.has(sessionID) : this.visible.has(sessionID)
if (!changed) return
Expand Down Expand Up @@ -202,7 +207,7 @@ export class SessionStreamScheduler {
return
}

if (this.active === sessionID && this.atimer) {
if (this._active === sessionID && this.atimer) {
clearTimeout(this.atimer)
this.atimer = null
}
Expand Down Expand Up @@ -261,7 +266,7 @@ export class SessionStreamScheduler {

private schedule(sessionID: string): void {
if (!this.queues.get(sessionID)?.size) return
if (this.active === sessionID) {
if (this._active === sessionID) {
if (this.atimer) return
this.atimer = setTimeout(() => this.flushActive(), this.activeMs)
return
Expand Down Expand Up @@ -300,7 +305,7 @@ export class SessionStreamScheduler {

private flushActive(): void {
this.atimer = null
if (this.active) this.emit(this.take(this.active))
if (this._active) this.emit(this.take(this._active))
}

private flushBackground(): void {
Expand Down Expand Up @@ -331,7 +336,7 @@ export class SessionStreamScheduler {
private takeBackground(): PartUpdate[] {
const updates: PartUpdate[] = []
for (const [sid, queue] of this.queues) {
if (sid === this.active) continue
if (sid === this._active) continue
if (this.visible.has(sid)) continue
updates.push(...queue.values())
this.queues.delete(sid)
Expand All @@ -342,7 +347,7 @@ export class SessionStreamScheduler {
private takeVisible(): PartUpdate[] {
const updates: PartUpdate[] = []
for (const [sid, queue] of this.queues) {
if (sid === this.active || !this.visible.has(sid)) continue
if (sid === this._active || !this.visible.has(sid)) continue
updates.push(...queue.values())
this.queues.delete(sid)
}
Expand All @@ -352,15 +357,15 @@ export class SessionStreamScheduler {
private visibleCount(): number {
let n = 0
for (const [sid, queue] of this.queues) {
if (sid !== this.active && this.visible.has(sid) && queue.size > 0) n++
if (sid !== this._active && this.visible.has(sid) && queue.size > 0) n++
}
return n
}

private backgroundCount(): number {
let n = 0
for (const [sid, queue] of this.queues) {
if (sid !== this.active && !this.visible.has(sid) && queue.size > 0) n++
if (sid !== this._active && !this.visible.has(sid) && queue.size > 0) n++
}
return n
}
Expand Down Expand Up @@ -393,7 +398,7 @@ export class SessionStreamScheduler {
}

private countLane(sessionID: string): void {
if (sessionID === this.active) this.counters.active++
if (sessionID === this._active) this.counters.active++
else if (this.visible.has(sessionID)) this.counters.visible++
else this.counters.background++
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,11 +257,25 @@ export class KiloConnectionService {
* Remove all messageID → sessionID entries for a given session.
* Called when a session is deleted or otherwise pruned so the map
* does not grow unbounded over the extension lifetime.
*
* Also drops the session from any provider's focused or opened set
* so the server's `viewed` notification stops advertising a deleted
* id after external (CLI/TUI/cascade) deletes arrive via SSE.
*/
pruneSession(sessionId: string): void {
for (const [mid, sid] of this.messageSessionIdsByMessageId) {
if (sid === sessionId) this.messageSessionIdsByMessageId.delete(mid)
}
for (const [key, sid] of this.focused) {
if (sid === sessionId) this.focused.delete(key)
}
for (const [key, ids] of this.opened) {
if (!ids.includes(sessionId)) continue
const next = ids.filter((id) => id !== sessionId)
if (next.length === 0) this.opened.delete(key)
else this.opened.set(key, next)
}
this.flushViewed()
}

/**
Expand Down
100 changes: 99 additions & 1 deletion packages/kilo-vscode/tests/unit/prompt-drafts.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { describe, it, expect } from "bun:test"
import { beforeEach, describe, it, expect } from "bun:test"
import { createEffect, createRoot, createSignal, on } from "solid-js"
import { deleteDraftsForSession, drafts, imageDrafts, reviewDrafts } from "../../webview-ui/src/utils/draft-store"
import {
createdDraftKey,
movePromptDraft,
Expand All @@ -7,6 +9,102 @@ import {
sessionDraftKey,
} from "../../webview-ui/src/utils/prompt-drafts"

beforeEach(() => {
drafts.clear()
reviewDrafts.clear()
imageDrafts.clear()
})

describe("deleteDraftsForSession", () => {
it("clears deleted-session drafts without touching other sessions", () => {
drafts.set("prompt:default:session:a", "draft a")
drafts.set("prompt:default:pending:a", "pending a")
drafts.set("prompt:default:session:b", "draft b")
reviewDrafts.set("prompt:default:session:a", [])
imageDrafts.set("prompt:default:session:a", [])

deleteDraftsForSession("a")

expect(drafts.has("prompt:default:session:a")).toBe(false)
expect(drafts.has("prompt:default:pending:a")).toBe(false)
expect(drafts.get("prompt:default:session:b")).toBe("draft b")
expect(reviewDrafts.has("prompt:default:session:a")).toBe(false)
expect(imageDrafts.has("prompt:default:session:a")).toBe(false)
})

it("is a no-op when given an empty id", () => {
drafts.set("prompt:default:session:a", "draft a")
deleteDraftsForSession("")
expect(drafts.get("prompt:default:session:a")).toBe("draft a")
})

it("clears drafts that PromptInput's draftKey effect recreates after the batch", () => {
Comment thread
IamCoder18 marked this conversation as resolved.
Resolved
// Production race that motivated the post-batch deleteDraftsForSession call:
// 1. handleSessionDeleted batches setCurrentSessionID(undefined) +
// setDraftSessionID(undefined). PromptInput's draftKey memo transitions from
// ":session:<id>" to the "new" bucket.
// 2. PromptInput's createEffect(on(draftKey, ...)) runs after the batch and calls
// saveDraft(prev, currentText, currentImages), writing the live prompt and any
// attached image data URLs back into the just-cleared ":session:<id>" key.
// 3. deleteDraftsForSession runs after the effect and clears the re-added entry.
//
// The test wires the same reactive plumbing — real Solid createSignal/createEffect/on
// against the same scopeDraftKey/sessionDraftKey/pendingDraftKey helpers PromptInput
// uses — so a regression that moves the cleanup back inside the batch (or drops it
// entirely) leaks the recreated draft and the final assertion fails.
const img = {
id: "i1",
filename: "x.png",
mime: "image/png",
dataUrl: "data:image/png;base64,AAAA",
}
const draftKey = "prompt:default:session:race"

createRoot((dispose) => {
// Live prompt state, the way PromptInput tracks it.
const [text, setText] = createSignal("draft a")
const [images] = createSignal([img])
const [currentSessionID, setCurrentSessionID] = createSignal<string | undefined>("race")
const [draftSessionID, setDraftSessionID] = createSignal<string | undefined>("race")

const boxKey = "prompt:default"
const rawKey = () =>
sessionDraftKey(currentSessionID()) ?? pendingDraftKey(draftSessionID() ?? undefined) ?? "new"
const key = () => scopeDraftKey(boxKey, rawKey())

// Pre-deletion: the user has unsent text and an attached image for this session.
drafts.set(draftKey, text())
imageDrafts.set(draftKey, images())

// Mirror the saveDraft behavior PromptInput's effect runs when draftKey transitions.
createEffect(
on(key, (k, prev) => {
if (prev !== undefined && prev !== k) {
drafts.set(prev, text())
imageDrafts.set(prev, images())
}
}),
)

// Production batch: clear the ids so draftKey transitions off ":session:<id>".
setCurrentSessionID(undefined)
setDraftSessionID(undefined)
// Solid has now run the effect; the recreate happened. Sanity-check before cleanup.
expect(drafts.has(draftKey)).toBe(true)
expect(imageDrafts.has(draftKey)).toBe(true)

// The post-batch cleanup. A single in-batch call (run before the effect) would
// have been wiped by the recreate above and not catch this — the post-batch
// call is what actually frees the entry.
deleteDraftsForSession("race")
dispose()
})

expect(drafts.has(draftKey)).toBe(false)
expect(imageDrafts.has(draftKey)).toBe(false)
})
})

describe("sessionDraftKey", () => {
it("prefixes session ids", () => {
expect(sessionDraftKey("abc")).toBe("session:abc")
Expand Down
Loading
Loading