continue-custom/extensions/vscode/src/diff/horizontal.ts
Nate Sesti 04c08c7159
dev (#1542)
* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>
2024-06-28 16:21:36 -07:00

336 lines
10 KiB
TypeScript

import { devDataPath } from "core/util/paths";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import * as vscode from "vscode";
import { getMetaKeyLabel, getPlatform } from "../util/util";
import { uriFromFilePath } from "../util/vscode";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
interface DiffInfo {
originalFilepath: string;
newFilepath: string;
editor?: vscode.TextEditor;
step_index: number;
range: vscode.Range;
}
async function readFile(path: string): Promise<string> {
return await vscode.workspace.fs
.readFile(uriFromFilePath(path))
.then((bytes) => new TextDecoder().decode(bytes));
}
async function writeFile(uri: vscode.Uri, contents: string) {
await vscode.workspace.fs.writeFile(uri, new TextEncoder().encode(contents));
}
// THIS IS LOCAL
export const DIFF_DIRECTORY = path
.join(os.homedir(), ".continue", ".diffs")
.replace(/^C:/, "c:");
export class DiffManager {
// Create a temporary file in the global .continue directory which displays the updated version
// Doing this because virtual files are read-only
private diffs: Map<string, DiffInfo> = new Map();
diffAtNewFilepath(newFilepath: string): DiffInfo | undefined {
return this.diffs.get(newFilepath);
}
private async setupDirectory() {
// Make sure the diff directory exists
if (!fs.existsSync(DIFF_DIRECTORY)) {
fs.mkdirSync(DIFF_DIRECTORY, {
recursive: true,
});
}
}
webviewProtocol: VsCodeWebviewProtocol | undefined;
constructor(private readonly extensionContext: vscode.ExtensionContext) {
this.setupDirectory();
// Listen for file closes, and if it's a diff file, clean up
vscode.workspace.onDidCloseTextDocument((document) => {
const newFilepath = document.uri.fsPath;
const diffInfo = this.diffs.get(newFilepath);
if (diffInfo) {
this.cleanUpDiff(diffInfo, false);
}
});
}
private escapeFilepath(filepath: string): string {
return filepath
.replace(/\//g, "_f_")
.replace(/\\/g, "_b_")
.replace(/:/g, "_c_");
}
private remoteTmpDir = "/tmp/continue";
private getNewFilepath(originalFilepath: string): string {
if (vscode.env.remoteName) {
// If we're in a remote, use the remote's temp directory
// Doing this because there's no easy way to find the home directory,
// and there aren't write permissions to the root directory
// and writing these to local causes separate issues
// because the vscode.diff command will always try to read from remote
vscode.workspace.fs.createDirectory(uriFromFilePath(this.remoteTmpDir));
return path.join(
this.remoteTmpDir,
this.escapeFilepath(originalFilepath),
);
}
return path.join(DIFF_DIRECTORY, this.escapeFilepath(originalFilepath));
}
private async openDiffEditor(
originalFilepath: string,
newFilepath: string,
): Promise<vscode.TextEditor | undefined> {
// If the file doesn't yet exist or the basename is a single digit number (vscode terminal), don't open the diff editor
try {
await vscode.workspace.fs.stat(uriFromFilePath(newFilepath));
} catch (e) {
console.log("File doesn't exist, not opening diff editor", e);
return undefined;
}
if (path.basename(originalFilepath).match(/^\d$/)) {
return undefined;
}
const rightUri = uriFromFilePath(newFilepath);
const leftUri = uriFromFilePath(originalFilepath);
const title = "Continue Diff";
vscode.commands.executeCommand("vscode.diff", leftUri, rightUri, title);
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
// Change the vscode setting to allow codeLens in diff editor
vscode.workspace
.getConfiguration("diffEditor", editor.document.uri)
.update("codeLens", true, vscode.ConfigurationTarget.Global);
if (
this.extensionContext.globalState.get<boolean>(
"continue.showDiffInfoMessage",
) !== false
) {
vscode.window
.showInformationMessage(
`Accept (${getMetaKeyLabel()}⇧⏎) or reject (${getMetaKeyLabel()}⇧⌫) at the top of the file.`,
"Got it",
"Don't show again",
)
.then((selection) => {
if (selection === "Don't show again") {
// Get the global state
this.extensionContext.globalState.update(
"continue.showDiffInfoMessage",
false,
);
}
});
}
return editor;
}
private _findFirstDifferentLine(contentA: string, contentB: string): number {
const linesA = contentA.split("\n");
const linesB = contentB.split("\n");
for (let i = 0; i < linesA.length && i < linesB.length; i++) {
if (linesA[i] !== linesB[i]) {
return i;
}
}
return 0;
}
async writeDiff(
originalFilepath: string,
newContent: string,
step_index: number,
): Promise<string> {
await this.setupDirectory();
// Create or update existing diff
const newFilepath = this.getNewFilepath(originalFilepath);
await writeFile(uriFromFilePath(newFilepath), newContent);
// Open the diff editor if this is a new diff
if (!this.diffs.has(newFilepath)) {
// Figure out the first line that is different
const oldContent = await readFile(originalFilepath);
const line = this._findFirstDifferentLine(oldContent, newContent);
const diffInfo: DiffInfo = {
originalFilepath,
newFilepath,
step_index,
range: new vscode.Range(line, 0, line + 1, 0),
};
this.diffs.set(newFilepath, diffInfo);
}
// Open the editor if it hasn't been opened yet
const diffInfo = this.diffs.get(newFilepath);
if (diffInfo && !diffInfo?.editor) {
diffInfo.editor = await this.openDiffEditor(
originalFilepath,
newFilepath,
);
this.diffs.set(newFilepath, diffInfo);
}
if (getPlatform() === "windows") {
// Just a matter of how it renders
// Lags on windows without this
// Flashes too much on mac with it
vscode.commands.executeCommand(
"workbench.action.files.revert",
uriFromFilePath(newFilepath),
);
}
return newFilepath;
}
cleanUpDiff(diffInfo: DiffInfo, hideEditor = true) {
// Close the editor, remove the record, delete the file
if (hideEditor && diffInfo.editor) {
try {
vscode.window.showTextDocument(diffInfo.editor.document);
vscode.commands.executeCommand("workbench.action.closeActiveEditor");
} catch {}
}
this.diffs.delete(diffInfo.newFilepath);
vscode.workspace.fs.delete(uriFromFilePath(diffInfo.newFilepath));
}
private inferNewFilepath() {
const activeEditorPath =
vscode.window.activeTextEditor?.document.uri.fsPath;
if (activeEditorPath && path.dirname(activeEditorPath) === DIFF_DIRECTORY) {
return activeEditorPath;
}
const visibleEditors = vscode.window.visibleTextEditors.map(
(editor) => editor.document.uri.fsPath,
);
for (const editorPath of visibleEditors) {
if (path.dirname(editorPath) === DIFF_DIRECTORY) {
for (const otherEditorPath of visibleEditors) {
if (
path.dirname(otherEditorPath) !== DIFF_DIRECTORY &&
this.getNewFilepath(otherEditorPath) === editorPath
) {
return editorPath;
}
}
}
}
if (this.diffs.size === 1) {
return Array.from(this.diffs.keys())[0];
}
return undefined;
}
async acceptDiff(newFilepath?: string) {
// When coming from a keyboard shortcut, we have to infer the newFilepath from visible text editors
if (!newFilepath) {
newFilepath = this.inferNewFilepath();
}
if (!newFilepath) {
console.log("No newFilepath provided to accept the diff");
return;
}
// Get the diff info, copy new file to original, then delete from record and close the corresponding editor
const diffInfo = this.diffs.get(newFilepath);
if (!diffInfo) {
console.log("No corresponding diffInfo found for newFilepath");
return;
}
// Save the right-side file, then copy over to original
vscode.workspace.textDocuments
.find((doc) => doc.uri.fsPath === newFilepath)
?.save()
.then(async () => {
await writeFile(
uriFromFilePath(diffInfo.originalFilepath),
await readFile(diffInfo.newFilepath),
);
this.cleanUpDiff(diffInfo);
});
await recordAcceptReject(true, diffInfo);
}
async rejectDiff(newFilepath?: string) {
// If no newFilepath is provided and there is only one in the dictionary, use that
if (!newFilepath) {
newFilepath = this.inferNewFilepath();
}
if (!newFilepath) {
console.log(
"No newFilepath provided to reject the diff, diffs.size was",
this.diffs.size,
);
return;
}
const diffInfo = this.diffs.get(newFilepath);
if (!diffInfo) {
console.log("No corresponding diffInfo found for newFilepath");
return;
}
// Stop the step at step_index in case it is still streaming
this.webviewProtocol?.request("setInactive", undefined);
vscode.workspace.textDocuments
.find((doc) => doc.uri.fsPath === newFilepath)
?.save()
.then(() => {
this.cleanUpDiff(diffInfo);
});
await recordAcceptReject(false, diffInfo);
}
}
async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) {
const devDataDir = devDataPath();
const suggestionsPath = path.join(devDataDir, "suggestions.json");
// Initialize suggestions list
let suggestions = [];
// Check if suggestions.json exists
try {
const rawData = await readFile(suggestionsPath);
suggestions = JSON.parse(rawData);
} catch {}
// Add the new suggestion to the list
suggestions.push({
accepted,
timestamp: Date.now(),
suggestion: diffInfo.originalFilepath,
});
// Send the suggestion to the server
// ideProtocolClient.sendAcceptRejectSuggestion(accepted);
// Write the updated suggestions back to the file
await writeFile(
vscode.Uri.file(suggestionsPath),
JSON.stringify(suggestions, null, 4),
);
}