Skip to content

Commit f4a3296

Browse files
committed
Add token count caching system to improve performance by persisting and reusing token calculations across sessions
1 parent a36b81e commit f4a3296

3 files changed

Lines changed: 136 additions & 25 deletions

File tree

‎packages/vscode/src/constants/state-keys.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ export const LAST_REFACTOR_INSTRUCTION_SOURCE_STATE_KEY =
3131
'last-refactor-instruction-source'
3232
export const LAST_REFACTOR_INSTRUCTION_STATE_KEY = 'last-refactor-instruction'
3333

34+
export const TOKEN_COUNTS_CACHE = 'token-count-cache'
35+
3436
export const CHECKPOINTS_STATE_KEY = 'checkpoints'
3537
export const TEMPORARY_CHECKPOINT_STATE_KEY = 'temporary-checkpoint'
3638
export const CHECKPOINT_OPERATION_IN_PROGRESS_STATE_KEY =

‎packages/vscode/src/context/providers/open-editors-provider.ts‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ export class OpenEditorsProvider
1818

1919
private _workspace_roots: string[] = []
2020
private _checked_items: Map<string, vscode.TreeItemCheckboxState> = new Map()
21-
private _file_token_counts: Map<string, number> = new Map()
2221
private _tab_change_handler: vscode.Disposable
2322
private _file_change_watcher: vscode.Disposable
2423
private _workspace_change_handler: vscode.Disposable
@@ -55,7 +54,7 @@ export class OpenEditorsProvider
5554
if (e.document.isDirty) return
5655

5756
const file_path = e.document.uri.fsPath
58-
this._file_token_counts.delete(file_path)
57+
this.workspace_provider.invalidate_token_counts_for_file(file_path)
5958
this._on_did_change_tree_data.fire()
6059
}
6160
)
@@ -186,12 +185,7 @@ export class OpenEditorsProvider
186185
this._non_preview_files.delete(key)
187186
this._preview_tabs.delete(key)
188187
})
189-
190-
keys_to_delete.forEach((key) => {
191-
this._file_token_counts.delete(key)
192-
})
193188
}
194-
195189
getTreeItem(element: FileItem): vscode.TreeItem {
196190
const key = element.resourceUri.fsPath
197191
const checkbox_state =
@@ -303,7 +297,8 @@ export class OpenEditorsProvider
303297

304298
const range = this.workspace_provider.get_range(file_path)
305299
const token_count =
306-
await this.workspace_provider.calculate_file_tokens(file_path)
300+
this.workspace_provider.get_cached_token_count(file_path) ||
301+
(await this.workspace_provider.calculate_file_tokens(file_path))
307302

308303
const item = new FileItem(
309304
file_name,
@@ -375,9 +370,6 @@ export class OpenEditorsProvider
375370
this._checked_items.set(file_path, vscode.TreeItemCheckboxState.Unchecked)
376371
}
377372

378-
// Force a complete tree refresh by clearing the file token count cache
379-
this._file_token_counts.clear()
380-
381373
// Fire the event with undefined to force full tree refresh
382374
this._on_did_change_tree_data.fire(undefined)
383375

‎packages/vscode/src/context/providers/workspace-provider.ts‎

Lines changed: 131 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,27 @@ import * as path from 'path'
44
import ignore, { Ignore } from 'ignore'
55
import {
66
CONTEXT_CHECKED_PATHS_STATE_KEY,
7-
RANGES_STATE_KEY
7+
RANGES_STATE_KEY,
8+
TOKEN_COUNTS_CACHE
89
} from '../../constants/state-keys'
910
import { IGNORE_PATTERNS } from '../../constants/ignore-patterns'
1011
import { natural_sort } from '../../utils/natural-sort'
1112
import { dictionary } from '@shared/constants/dictionary'
1213
import { Logger } from '@shared/utils/logger'
1314
import { display_token_count } from '@/utils/display-token-count'
1415

16+
type TokenCountsCache = {
17+
[workspace_root: string]: {
18+
modified_at: number
19+
files: {
20+
[file_path: string]: {
21+
modified_at: number
22+
token_count: number
23+
}
24+
}
25+
}
26+
}
27+
1528
const SHOW_COUNTING_NOTIFICATION_DELAY_MS = 3000
1629

1730
export class WorkspaceProvider
@@ -34,6 +47,7 @@ export class WorkspaceProvider
3447
private file_token_counts: Map<string, number> = new Map()
3548
private directory_token_counts: Map<string, number> = new Map()
3649
private directory_selected_token_counts: Map<string, number> = new Map()
50+
private token_cache: TokenCountsCache = {}
3751
private file_ranges: Map<string, string> = new Map()
3852

3953
private config_change_handler: vscode.Disposable
@@ -48,6 +62,8 @@ export class WorkspaceProvider
4862
private file_workspace_map: Map<string, string> = new Map()
4963
public gitignore_initialization: Promise<void>
5064
public ranges_initialization: Promise<void>
65+
private token_cache_update_timeout: NodeJS.Timeout | null = null
66+
private is_initialized = false
5167

5268
constructor(
5369
workspace_folders: vscode.WorkspaceFolder[],
@@ -87,6 +103,7 @@ export class WorkspaceProvider
87103
})
88104

89105
this.gitignore_initialization = this._load_all_gitignore_files()
106+
this._load_token_cache()
90107
this.ranges_watcher = vscode.workspace.createFileSystemWatcher(
91108
'**/.vscode/ranges.json'
92109
)
@@ -114,6 +131,44 @@ export class WorkspaceProvider
114131
}
115132
}
116133

134+
private _load_token_cache(): void {
135+
this.token_cache =
136+
this.context.globalState.get<TokenCountsCache>(TOKEN_COUNTS_CACHE) ?? {}
137+
}
138+
139+
private _update_token_counts_cache(): void {
140+
if (this.is_initialized) return
141+
142+
if (this.token_cache_update_timeout) {
143+
clearTimeout(this.token_cache_update_timeout)
144+
}
145+
146+
this.token_cache_update_timeout = setTimeout(async () => {
147+
const current_global_cache =
148+
this.context.globalState.get<TokenCountsCache>(TOKEN_COUNTS_CACHE) ?? {}
149+
150+
for (const root of this.workspace_roots) {
151+
if (this.token_cache[root]) {
152+
current_global_cache[root] = this.token_cache[root]
153+
}
154+
}
155+
156+
// Prune workspaces updated one week ago or later
157+
const one_week_ago = Date.now() - 7 * 24 * 60 * 60 * 1000
158+
for (const root in current_global_cache) {
159+
if (current_global_cache[root].modified_at < one_week_ago) {
160+
delete current_global_cache[root]
161+
}
162+
}
163+
164+
await this.context.globalState.update(
165+
TOKEN_COUNTS_CACHE,
166+
current_global_cache
167+
)
168+
this.is_initialized = true
169+
}, 10000)
170+
}
171+
117172
private async _with_token_counting_notification<T>(
118173
task: () => Promise<T>
119174
): Promise<T> {
@@ -135,7 +190,9 @@ export class WorkspaceProvider
135190
}, SHOW_COUNTING_NOTIFICATION_DELAY_MS)
136191

137192
try {
138-
return await task()
193+
const result = await task()
194+
195+
return result
139196
} finally {
140197
clearTimeout(timer)
141198
notification_stopper?.()
@@ -202,6 +259,10 @@ export class WorkspaceProvider
202259
if (this.refresh_timeout) {
203260
clearTimeout(this.refresh_timeout)
204261
}
262+
263+
if (this.token_cache_update_timeout) {
264+
clearTimeout(this.token_cache_update_timeout)
265+
}
205266
}
206267

207268
private _update_preview_tabs_state(): void {
@@ -296,6 +357,23 @@ export class WorkspaceProvider
296357
return path.basename(root_path)
297358
}
298359

360+
public invalidate_token_counts_for_file(changed_file_path: string): void {
361+
const workspace_root = this.get_workspace_root_for_file(changed_file_path)
362+
if (!workspace_root) {
363+
this.file_token_counts.delete(changed_file_path)
364+
return
365+
}
366+
367+
this.file_token_counts.delete(changed_file_path)
368+
369+
let dir_path = path.dirname(changed_file_path)
370+
while (dir_path.startsWith(workspace_root)) {
371+
this.directory_token_counts.delete(dir_path)
372+
this.directory_selected_token_counts.delete(dir_path)
373+
dir_path = path.dirname(dir_path)
374+
}
375+
}
376+
299377
private _on_file_system_changed(changed_file_path?: string): void {
300378
if (!changed_file_path) return
301379

@@ -310,14 +388,7 @@ export class WorkspaceProvider
310388
return
311389
}
312390

313-
this.file_token_counts.delete(changed_file_path)
314-
315-
let dir_path = path.dirname(changed_file_path)
316-
while (dir_path.startsWith(workspace_root)) {
317-
this.directory_token_counts.delete(dir_path)
318-
this.directory_selected_token_counts.delete(dir_path)
319-
dir_path = path.dirname(dir_path)
320-
}
391+
this.invalidate_token_counts_for_file(changed_file_path)
321392

322393
if (!fs.existsSync(changed_file_path)) {
323394
this.file_workspace_map.delete(changed_file_path)
@@ -416,6 +487,7 @@ export class WorkspaceProvider
416487
this.refresh_timeout = null
417488
}, 1000) // Debounce refresh to handle bulk file changes like builds
418489
}
490+
419491
public async clear_checks(): Promise<void> {
420492
const config = vscode.workspace.getConfiguration('codeWebChat')
421493
const clear_checks_in_workspace_behavior = config.get<string>(
@@ -600,13 +672,15 @@ export class WorkspaceProvider
600672

601673
if (this.workspace_roots.length == 1) {
602674
const single_root = this.workspace_roots[0]
603-
return this._with_token_counting_notification(() =>
675+
const items = await this._with_token_counting_notification(() =>
604676
this._get_files_and_directories(single_root)
605677
)
678+
return items
606679
} else {
607-
return this._with_token_counting_notification(() =>
680+
const items = await this._with_token_counting_notification(() =>
608681
this._get_workspace_folder_items()
609682
)
683+
return items
610684
}
611685
}
612686

@@ -789,16 +863,40 @@ export class WorkspaceProvider
789863
return sorted_indices.map((i) => lines[i - 1]).join('\n')
790864
}
791865

866+
public get_cached_token_count(file_path: string): number | undefined {
867+
return this.file_token_counts.get(file_path)
868+
}
869+
792870
public async calculate_file_tokens(file_path: string): Promise<number> {
793871
if (this.file_token_counts.has(file_path)) {
794872
return this.file_token_counts.get(file_path)!
795873
}
796874

875+
const workspace_root = this.get_workspace_root_for_file(file_path)
876+
const range = this.get_range(file_path)
877+
let mtime = 0
878+
879+
if (workspace_root && !range) {
880+
try {
881+
const stats = await fs.promises.stat(file_path)
882+
mtime = stats.mtimeMs
883+
if (
884+
this.token_cache[workspace_root]?.files?.[file_path]?.modified_at ==
885+
mtime
886+
) {
887+
const tokens =
888+
this.token_cache[workspace_root].files[file_path].token_count
889+
this.file_token_counts.set(file_path, tokens)
890+
return tokens
891+
}
892+
} catch {
893+
// Continue to calculate if stat fails
894+
}
895+
}
896+
797897
try {
798-
const workspace_root = this.get_workspace_root_for_file(file_path)
799898
let content = await fs.promises.readFile(file_path, 'utf8')
800899

801-
const range = this.get_range(file_path)
802900
if (range) {
803901
content = this.apply_range_to_content(content, range)
804902
}
@@ -824,6 +922,25 @@ export class WorkspaceProvider
824922

825923
const token_count = Math.floor(content_xml.length / 4)
826924
this.file_token_counts.set(file_path, token_count)
925+
926+
if (workspace_root && !range && mtime > 0) {
927+
if (
928+
!this.token_cache[workspace_root] ||
929+
!this.token_cache[workspace_root].files
930+
) {
931+
this.token_cache[workspace_root] = {
932+
modified_at: Date.now(),
933+
files: {}
934+
}
935+
}
936+
this.token_cache[workspace_root].files[file_path] = {
937+
modified_at: mtime,
938+
token_count: token_count
939+
}
940+
this.token_cache[workspace_root].modified_at = Date.now()
941+
this._update_token_counts_cache()
942+
}
943+
827944
return token_count
828945
} catch (error) {
829946
Logger.error({

0 commit comments

Comments
 (0)