fix git diff cache

This commit is contained in:
Dallin Romney 2025-05-28 14:52:37 -07:00
parent cec16dc7fc
commit f32f78c550
17 changed files with 91 additions and 179 deletions

View file

@ -1,50 +0,0 @@
import { DiffSnippetsCache } from "./diffSnippetCache";
test("DiffSnippetsCache getInstance returns singleton instance", () => {
const instance1 = DiffSnippetsCache.getInstance();
const instance2 = DiffSnippetsCache.getInstance();
expect(instance1).toBe(instance2);
});
test("DiffSnippetsCache set stores value and returns it", () => {
const cache = DiffSnippetsCache.getInstance();
const timestamp = Date.now();
const value = { test: "data" };
const result = cache.set(timestamp, value);
expect(result).toBe(value);
expect(cache.get(timestamp)).toBe(value);
});
test("DiffSnippetsCache get returns undefined for non-existent timestamp", () => {
const cache = DiffSnippetsCache.getInstance();
const timestamp = Date.now();
expect(cache.get(timestamp + 1000)).toBeUndefined();
});
test("DiffSnippetsCache set clears cache when timestamp changes", () => {
const cache = DiffSnippetsCache.getInstance();
const timestamp1 = Date.now();
const timestamp2 = timestamp1 + 1000;
const value1 = { test: "data1" };
const value2 = { test: "data2" };
cache.set(timestamp1, value1);
cache.set(timestamp2, value2);
expect(cache.get(timestamp1)).toBeUndefined();
expect(cache.get(timestamp2)).toBe(value2);
});
test("DiffSnippetsCache set maintains cache with same timestamp", () => {
const cache = DiffSnippetsCache.getInstance();
const timestamp = Date.now();
const value1 = { test: "data1" };
const value2 = { test: "data2" };
cache.set(timestamp, value1);
cache.set(timestamp, value2);
expect(cache.get(timestamp)).toBe(value2);
});

View file

@ -1,28 +1,70 @@
export class DiffSnippetsCache {
private static instance: DiffSnippetsCache;
private cache: Map<number, any> = new Map();
private lastTimestamp: number = 0;
import { IDE } from "../..";
private constructor() {}
type GetDiffFn = () => Promise<string[]>;
public static getInstance(): DiffSnippetsCache {
if (!DiffSnippetsCache.instance) {
DiffSnippetsCache.instance = new DiffSnippetsCache();
}
return DiffSnippetsCache.instance;
export class GitDiffCache {
private static instance: GitDiffCache | null = null;
private cachedDiff: string[] | undefined = undefined;
private lastFetchTime: number = 0;
private pendingRequest: Promise<string[]> | null = null;
private getDiffFn: GetDiffFn;
private cacheTimeMs: number;
private constructor(getDiffFn: GetDiffFn, cacheTimeSeconds: number = 20) {
this.getDiffFn = getDiffFn;
this.cacheTimeMs = cacheTimeSeconds * 1000;
}
public set<T>(timestamp: number, value: T): T {
// Clear old cache entry if exists
if (this.lastTimestamp !== timestamp) {
this.cache.clear();
public static getInstance(
getDiffFn: GetDiffFn,
cacheTimeSeconds?: number,
): GitDiffCache {
if (!GitDiffCache.instance) {
GitDiffCache.instance = new GitDiffCache(getDiffFn, cacheTimeSeconds);
}
this.lastTimestamp = timestamp;
this.cache.set(timestamp, value);
return value;
return GitDiffCache.instance;
}
public get(timestamp: number): any | undefined {
return this.cache.get(timestamp);
private async getDiffPromise(): Promise<string[]> {
try {
const diff = await this.getDiffFn();
this.cachedDiff = diff;
this.lastFetchTime = Date.now();
return this.cachedDiff;
} finally {
this.pendingRequest = null;
}
}
public async get(): Promise<string[]> {
if (
this.cachedDiff !== undefined &&
Date.now() - this.lastFetchTime < this.cacheTimeMs
) {
return this.cachedDiff;
}
// If there's already a request in progress, return that instead of starting a new one
if (this.pendingRequest) {
return this.pendingRequest;
}
this.pendingRequest = this.getDiffPromise();
return this.pendingRequest;
}
public invalidate(): void {
this.cachedDiff = undefined;
this.pendingRequest = null;
}
}
// factory to make diff cache more testable
export function getDiffFn(ide: IDE): GetDiffFn {
return () => ide.getDiff(true);
}
export async function getDiffsFromCache(ide: IDE): Promise<string[]> {
const diffCache = GitDiffCache.getInstance(getDiffFn(ide));
return await diffCache.get();
}

View file

@ -1,9 +1,9 @@
import { IDE, IdeInfo } from "../../index";
import { IDE } from "../../index";
import { findUriInDirs } from "../../util/uri";
import { ContextRetrievalService } from "../context/ContextRetrievalService";
import { GetLspDefinitionsFunction } from "../types";
import { HelperVars } from "../util/HelperVars";
import { DiffSnippetsCache } from "./diffSnippetCache";
import { getDiffsFromCache } from "./diffSnippetCache";
import {
AutocompleteClipboardSnippet,
@ -92,44 +92,15 @@ const getClipboardSnippets = async (
const getDiffSnippets = async (
ide: IDE,
ideInfo: IdeInfo | undefined,
): Promise<AutocompleteDiffSnippet[]> => {
const diffSnippetsCache = DiffSnippetsCache.getInstance();
if (ideInfo?.ideType !== "vscode") {
// Disabling for non-vscode IDEs for now
// See https://github.com/continuedev/continue/issues/4130
// https://github.com/continuedev/continue/issues/5819
return [];
}
const currentTimestamp = ide.getLastFileSaveTimestamp
? ide.getLastFileSaveTimestamp()
: Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
const diffs = await getDiffsFromCache(ide);
// Check cache first
const cached = diffSnippetsCache.get(
currentTimestamp,
) as AutocompleteDiffSnippet[];
if (cached) {
return cached;
}
let diff: string[] = [];
try {
diff = await ide.getDiff(true);
} catch (e) {
console.error("Error getting diff for autocomplete", e);
}
return diffSnippetsCache.set(
currentTimestamp,
diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
}),
);
return diffs.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
});
};
export const getAllSnippets = async ({
@ -160,7 +131,7 @@ export const getAllSnippets = async ({
IDE_SNIPPETS_ENABLED
? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp))
: [],
racePromise(getDiffSnippets(ide, helper.ideInfo)),
racePromise(getDiffSnippets(ide)),
racePromise(getClipboardSnippets(ide)),
]);

View file

@ -1,4 +1,4 @@
import { IDE, IdeInfo, TabAutocompleteOptions } from "../..";
import { IDE, TabAutocompleteOptions } from "../..";
import {
countTokens,
pruneLinesFromBottom,
@ -21,7 +21,6 @@ export class HelperVars {
lang: AutocompleteLanguageInfo;
treePath: AstPath | undefined;
workspaceUris: string[] = [];
ideInfo: IdeInfo | undefined;
private _fileContents: string | undefined;
private _fileLines: string[] | undefined;
@ -44,7 +43,6 @@ export class HelperVars {
if (this._fileContents !== undefined) {
return;
}
this.ideInfo = await this.ide.getIdeInfo();
this.workspaceUris = await this.ide.getWorkspaceDirs();
this._fileContents =

View file

@ -17,16 +17,15 @@ class DiffContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const diff = await extras.ide.getDiff(
this.options?.includeUnstaged ?? true,
);
const includeUnstaged = this.options?.includeUnstaged ?? true;
const diffs = await extras.ide.getDiff(includeUnstaged); // TODO use diff cache (currently cache always includes unstaged)
return [
{
description: "The current git diff",
content:
diff.length === 0
diffs.length === 0
? "Git shows no current changes."
: `\`\`\`git diff\n${diff.join("\n")}\n\`\`\``,
: `\`\`\`git diff\n${diffs.join("\n")}\n\`\`\``,
name: "Git Diff",
},
];

View file

@ -45,6 +45,10 @@ import {
} from ".";
import { ConfigYaml } from "@continuedev/config-yaml";
import {
getDiffFn,
GitDiffCache,
} from "./autocomplete/snippets/diffSnippetCache";
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
import {
setupBestConfig,
@ -808,6 +812,8 @@ export class Core {
uris?: string[];
}>) {
if (data?.uris?.length) {
const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
diffCache.invalidate();
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
for (const uri of data.uris) {
const currentProfileUri =

6
core/index.d.ts vendored
View file

@ -776,10 +776,6 @@ export interface IDE {
}
>;
getLastFileSaveTimestamp?(): number;
updateLastFileSaveTimestamp?(): void;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
@ -1141,7 +1137,7 @@ export interface StreamableHTTPOptions {
requestOptions?: RequestOptions;
}
export type TransportOptions =
export type TransportOptions =
| StdioOptions
| WebSocketOptions
| SSEOptions

View file

@ -1,4 +1,5 @@
import { ContinueSDK, SlashCommand } from "../..";
import { getDiffsFromCache } from "../../autocomplete/snippets/diffSnippetCache";
import { renderChatMessage } from "../../util/messageContent";
import { getLastNPathParts } from "../../util/uri";
import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
@ -32,8 +33,8 @@ async function renderPromptV1(
// A few context providers that don't need to be in config.json to work in .prompt files
if (helpers?.find((helper) => helper[0] === "diff")) {
const diff = await context.ide.getDiff(true);
inputData.diff = diff.join("\n");
const diffs = await getDiffsFromCache(context.ide);
inputData.diff = diffs.join("\n");
}
if (helpers?.find((helper) => helper[0] === "currentFile")) {
const currentFile = await context.ide.getCurrentFile();

View file

@ -1,12 +1,15 @@
import { ToolImpl } from ".";
import { getDiffsFromCache } from "../../autocomplete/snippets/diffSnippetCache";
export const viewDiffImpl: ToolImpl = async (args, extras) => {
const diff = await extras.ide.getDiff(true);
const diffs = await getDiffsFromCache(extras.ide); // const diffs = await extras.ide.getDiff(true);
// TODO includeUnstaged should be an option
return [
{
name: "Diff",
description: "The current git diff",
content: diff.join("\n"),
content: diffs.join("\n"),
},
];
};

View file

@ -182,8 +182,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
// Notify core of content changes
if (changedURIs.isNotEmpty()) {
continuePluginService.updateLastFileSaveTimestamp()
val data = mapOf("uris" to changedURIs)
continuePluginService.coreMessenger?.request("files/changed", data, null) { _ -> }
}

View file

@ -13,33 +13,12 @@ class GitService(
private val project: Project,
private val continuePluginService: ContinuePluginService
) {
// Add a simple cache for diff results
private data class DiffCache(
val timestamp: Long,
val diffs: List<String>
)
// Cache the last diff result
private var diffCache: DiffCache? = null
private var lastFileSaveTimestamp: Long = System.currentTimeMillis()
/**
* Updates the timestamp when a file is saved
*/
fun updateLastFileSaveTimestamp() {
lastFileSaveTimestamp = System.currentTimeMillis()
}
/**
* Returns the git diff for all workspace directories
*/
suspend fun getDiff(includeUnstaged: Boolean): List<String> {
// Check if we have a valid cache entry
if (diffCache != null && diffCache!!.timestamp == lastFileSaveTimestamp) {
return diffCache!!.diffs
}
// If no cache hit, compute the diff
val workspaceDirs = workspaceDirectories()
val diffs = mutableListOf<String>()
@ -74,8 +53,6 @@ class GitService(
diffs.add(output.toString())
}
// Cache the result
diffCache = DiffCache(lastFileSaveTimestamp, diffs)
return diffs
}

View file

@ -50,10 +50,6 @@ class IdeProtocolClient(
)
}
fun updateLastFileSaveTimestamp() {
(ide as IntelliJIDE).updateLastFileSaveTimestamp()
}
fun handleMessage(msg: String, respond: (Any?) -> Unit) {
coroutineScope.launch(limitedDispatcher) {
val message = Gson().fromJson(msg, Message::class.java)

View file

@ -66,13 +66,6 @@ class IntelliJIDE(
}
}
/**
* Updates the timestamp when a file is saved
*/
override fun updateLastFileSaveTimestamp() {
gitService.updateLastFileSaveTimestamp()
}
override suspend fun getIdeInfo(): IdeInfo {
val applicationInfo = ApplicationInfo.getInstance()
val ideName: String = applicationInfo.fullApplicationName

View file

@ -63,8 +63,4 @@ class ContinuePluginService : Disposable, DumbAware {
listener()
}
}
fun updateLastFileSaveTimestamp() {
ideProtocolClient?.updateLastFileSaveTimestamp()
}
}

View file

@ -194,10 +194,6 @@ interface IDE {
// Callbacks
fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit)
fun updateLastFileSaveTimestamp() {
// Default implementation does nothing
}
}
data class GetGhTokenArgs(

View file

@ -33,7 +33,6 @@ import type {
class VsCodeIde implements IDE {
ideUtils: VsCodeIdeUtils;
secretStorage: SecretStorage;
private lastFileSaveTimestamp: number = Date.now();
constructor(
private readonly vscodeWebviewProtocolPromise: Promise<VsCodeWebviewProtocol>,
@ -43,14 +42,6 @@ class VsCodeIde implements IDE {
this.secretStorage = new SecretStorage(context);
}
public updateLastFileSaveTimestamp(): void {
this.lastFileSaveTimestamp = Date.now();
}
public getLastFileSaveTimestamp(): number {
return this.lastFileSaveTimestamp;
}
async readSecrets(keys: string[]): Promise<Record<string, string>> {
const secretValuePromises = keys.map((key) => this.secretStorage.get(key));
const secretValues = await Promise.all(secretValuePromises);

View file

@ -282,7 +282,6 @@ export class VsCodeExtension {
});
vscode.workspace.onDidSaveTextDocument(async (event) => {
this.ide.updateLastFileSaveTimestamp();
this.core.invoke("files/changed", {
uris: [event.uri.toString()],
});