diff --git a/core/core.ts b/core/core.ts index 200cfae6f..2db7856d1 100644 --- a/core/core.ts +++ b/core/core.ts @@ -603,7 +603,7 @@ export class Core { const outcome = await this.nextEditProvider.provideInlineCompletionItems( msg.data, undefined, - false, + { withChain: false }, ); return outcome ? [outcome.completion, outcome.originalEditableRange] : []; }); diff --git a/core/nextEdit/DocumentHistoryTracker.ts b/core/nextEdit/DocumentHistoryTracker.ts index 34ea763bf..7cca91f56 100644 --- a/core/nextEdit/DocumentHistoryTracker.ts +++ b/core/nextEdit/DocumentHistoryTracker.ts @@ -63,11 +63,12 @@ export class DocumentHistoryTracker { if (!astHistory || !documentHistory) { console.error(`Document ${documentPath} not found in AST tracker`); this.addDocument(documentPath, documentContent, ast); + return; // Early return - document was added with initial state } - // Push to top (LIFO). - astHistory!.unshift(ast); - documentHistory!.unshift(documentContent); + // Only execute this if the arrays already existed + astHistory.unshift(ast); + documentHistory.unshift(documentContent); } /** diff --git a/core/nextEdit/DocumentHistoryTracker.vitest.ts b/core/nextEdit/DocumentHistoryTracker.vitest.ts new file mode 100644 index 000000000..f6c9b2dd4 --- /dev/null +++ b/core/nextEdit/DocumentHistoryTracker.vitest.ts @@ -0,0 +1,228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import Parser from "web-tree-sitter"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; + +// Mock the Parser.Tree class +vi.mock("web-tree-sitter", () => { + return { + default: { + Tree: class MockTree { + constructor() { + // Mock implementation + } + }, + }, + }; +}); + +describe("DocumentHistoryTracker", () => { + let tracker: DocumentHistoryTracker; + let mockAst1: Parser.Tree; + let mockAst2: Parser.Tree; + const testDocPath = "/test/document.ts"; + const testContent1 = "const x = 1;"; + const testContent2 = "const x = 2;"; + + beforeEach(() => { + // Reset singleton instance for each test + // @ts-ignore - accessing private static property for testing + DocumentHistoryTracker.instance = null; + tracker = DocumentHistoryTracker.getInstance(); + + // Create mock ASTs + //@ts-ignore + mockAst1 = new Parser.Tree() as Parser.Tree; + //@ts-ignore + mockAst2 = new Parser.Tree() as Parser.Tree; + }); + + afterEach(() => { + // Clear the tracker after each test + tracker.clearMap(); + }); + + describe("getInstance", () => { + it("should return a singleton instance", () => { + const instance1 = DocumentHistoryTracker.getInstance(); + const instance2 = DocumentHistoryTracker.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("addDocument", () => { + it("should add a document to the tracker", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBe(mockAst1); + expect(content).toBe(testContent1); + }); + }); + + describe("push", () => { + it("should push a new AST to an existing document's history stack", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBe(mockAst2); + expect(content).toBe(testContent2); + }); + + it("should add a document if it doesn't exist when pushing", () => { + tracker.push(testDocPath, testContent1, mockAst1); + + // Check if document was actually added + const ast = tracker.getMostRecentAst(testDocPath); + expect(ast).toBe(mockAst1); + }); + }); + + describe("getMostRecentAst", () => { + it("should return the most recent AST of a document", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const ast = tracker.getMostRecentAst(testDocPath); + + expect(ast).toBe(mockAst2); + }); + + it("should return null if the document doesn't exist", () => { + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst("nonexistent-path"); + + expect(ast).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Document nonexistent-path not found in AST tracker", + ); + + consoleErrorSpy.mockRestore(); + }); + + it("should return null if the document has no ASTs", () => { + // This test would require modifying private properties + // So we'll mock an empty array situation + tracker.addDocument(testDocPath, testContent1, mockAst1); + + // @ts-ignore - accessing private property for testing + tracker.documentAstMap.set(testDocPath, []); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst(testDocPath); + + expect(ast).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} has no ASTs`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("getMostRecentDocumentHistory", () => { + it("should return the most recent document history", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(content).toBe(testContent2); + }); + + it("should return null if the document doesn't exist", () => { + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const content = tracker.getMostRecentDocumentHistory("nonexistent-path"); + + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Document nonexistent-path not found in AST tracker", + ); + + consoleErrorSpy.mockRestore(); + }); + + it("should return null if the document has no history", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + + // @ts-ignore - accessing private property for testing + tracker.documentContentHistoryMap.set(testDocPath, []); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} has no history`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("deleteDocument", () => { + it("should delete a document from the tracker", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.deleteDocument(testDocPath); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBeNull(); + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} not found in AST tracker`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("clearMap", () => { + it("should clear all documents from the tracker", () => { + const anotherDocPath = "/test/another-document.ts"; + + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.addDocument(anotherDocPath, testContent1, mockAst1); + + tracker.clearMap(); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + expect(tracker.getMostRecentAst(testDocPath)).toBeNull(); + expect(tracker.getMostRecentAst(anotherDocPath)).toBeNull(); + expect(tracker.getMostRecentDocumentHistory(testDocPath)).toBeNull(); + expect(tracker.getMostRecentDocumentHistory(anotherDocPath)).toBeNull(); + + consoleErrorSpy.mockRestore(); + }); + }); +}); diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 5a398a8dd..b4c30d99f 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -252,7 +252,9 @@ export class NextEditProvider { public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, - withChain: boolean, + opts?: { + withChain: boolean; + }, ): Promise { try { this.previousRequest = input; @@ -273,7 +275,9 @@ export class NextEditProvider { // Depending on whether this method is called from provideInlineCompletionItemsWithChain, // shift the next editable regions. - if (withChain) { + // This is handled here because this must run after the debouncer + // to prevent excessive shifts. + if (opts?.withChain) { this.shiftNextEditableRegionsInTheCurrentChain(); } @@ -566,8 +570,9 @@ export class NextEditProvider { return undefined; } - const WITH_CHAIN = true; - return await this.provideInlineCompletionItems(input, token, WITH_CHAIN); + return await this.provideInlineCompletionItems(input, token, { + withChain: true, + }); } catch (e: any) { this.onError(e); } diff --git a/docs/customization/rules.mdx b/docs/customization/rules.mdx index 8850e603f..e0b405dd4 100644 --- a/docs/customization/rules.mdx +++ b/docs/customization/rules.mdx @@ -15,6 +15,4 @@ By implementing rules, you transform the AI from a generic coding assistant into Your assistant detects rule blocks and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes. -## Learn More - -Learn more in the [rules deep dive](/customization/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. +Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. diff --git a/docs/features/agent/how-to-customize.mdx b/docs/features/agent/how-to-customize.mdx index a912292d2..7e5fd634b 100644 --- a/docs/features/agent/how-to-customize.mdx +++ b/docs/features/agent/how-to-customize.mdx @@ -2,6 +2,21 @@ Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details. +## Customize System Messages + +You can customize the system messages for Chat, Agent, and Plan modes using model-level configuration: + +```yaml +models: + - name: GPT-4o + provider: openai + model: gpt-4o + chatOptions: + baseSystemMessage: "You are a helpful coding assistant." + baseAgentSystemMessage: "You are a systematic coding assistant. Break down problems methodically." + basePlanSystemMessage: "You are a planning assistant. Create clear, actionable steps." +``` + ## Add MCP Tools You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details. diff --git a/docs/reference.mdx b/docs/reference.mdx index 7ea087fc5..836d8e7dc 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -184,6 +184,8 @@ The `models` section defines the language models used in your configuration. Mod - `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: - `baseSystemMessage`: Can be used to override the default system prompt for **Chat** mode. + - `baseAgentSystemMessage`: Can be used to override the default system prompt for **Agent** mode. + - `basePlanSystemMessage`: Can be used to override the default system prompt for **Plan** mode. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index e52a69711..edb2a167c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -1,6 +1,6 @@ package com.github.continuedev.continueintellijextension.auth -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson @@ -90,7 +90,7 @@ class ContinueAuthService { ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC) .handleUpdatedSessionInfo(sessionInfo) } catch (e: Exception) { - service().report(e, "Exception while refreshing token ${e.message}") + service().report(e, "Exception while refreshing token ${e.message}") } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt index 71b367e20..4acfb461d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt @@ -1,8 +1,6 @@ package com.github.continuedev.continueintellijextension.`continue` -import com.github.continuedev.continueintellijextension.services.TelemetryService -import com.github.continuedev.continueintellijextension.utils.castNestedOrNull -import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID +import com.github.continuedev.continueintellijextension.error.ContinuePostHogService import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project @@ -20,10 +18,6 @@ class CoreMessengerManager( private var backoffIntervalSeconds = 1 private val log = Logger.getInstance(CoreMessengerManager::class.java) - init { - setupAnonymousTelemetry() - } - private fun onUnexpectedExit() { coroutineScope.launch { try { @@ -32,17 +26,8 @@ class CoreMessengerManager( log.warn("Continue process terminated externally, retrying in $backoffIntervalSeconds seconds") coreMessenger.restart() } catch (e: Exception) { - service().capture("jetbrains_core_start_error", mapOf("error" to e)) + service().capture("jetbrains_core_start_error", mapOf("error" to e)) } } } - - private fun setupAnonymousTelemetry() { - coreMessenger.request("config/getSerializedProfileInfo", null, null) { response -> - val allowAnonymousTelemetry = - response.castNestedOrNull("content", "result", "config", "allowAnonymousTelemetry") - if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) - service().setup(getMachineUniqueID()) - } - } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 693dfe15c..983b7cbda 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -6,7 +6,7 @@ import com.github.continuedev.continueintellijextension.activities.showTutorial import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.editor.EditorUtils -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.github.continuedev.continueintellijextension.protocol.* import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService @@ -473,7 +473,7 @@ class IdeProtocolClient( } } catch (exception: Exception) { val exceptionMessage = "Error handling message of type $messageType: $exception" - service().report(exception, exceptionMessage) + service().report(exception, exceptionMessage) ide.showToast(ToastType.ERROR, exceptionMessage) } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 542d9c338..d377cb3b1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -4,7 +4,7 @@ import com.github.continuedev.continueintellijextension.* import com.github.continuedev.continueintellijextension.constants.ContinueConstants import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.* @@ -28,7 +28,6 @@ import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.vfs.LocalFileSystem -import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile @@ -374,7 +373,7 @@ class IntelliJIDE( return results.split("\n") } catch (exception: Exception) { val message = "Error executing ripgrep: ${exception.message}" - service().report(exception, message) + service().report(exception, message) showToast(ToastType.ERROR, message) return emptyList() } @@ -416,7 +415,7 @@ class IntelliJIDE( return ExecUtil.execAndGetOutput(command).stdout } catch (exception: Exception) { val message = "Error executing ripgrep: ${exception.message}" - service().report(exception, message) + service().report(exception, message) showToast(ToastType.ERROR, message) return "Error: Unable to execute ripgrep command." } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt index 6ef0c335b..38631446e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt @@ -1,8 +1,8 @@ package com.github.continuedev.continueintellijextension.`continue`.process import com.github.continuedev.continueintellijextension.proxy.ProxySettings -import com.github.continuedev.continueintellijextension.error.ContinueErrorService -import com.github.continuedev.continueintellijextension.services.TelemetryService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService +import com.github.continuedev.continueintellijextension.error.ContinuePostHogService import com.github.continuedev.continueintellijextension.utils.OS import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath import com.github.continuedev.continueintellijextension.utils.getOS @@ -53,8 +53,8 @@ class ContinueBinaryProcess( err = err.substring(doneIndex + delimiter.length) } } - service().reportMessage("Core process exited with output: $err") - service().capture("jetbrains_core_exit", mapOf("error" to err)) + service().reportMessage("Core process exited with output: $err") + service().capture("jetbrains_core_exit", mapOf("error" to err)) } private companion object { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt index 8e918b2c3..04e4d3d2e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt @@ -1,6 +1,6 @@ package com.github.continuedev.continueintellijextension.`continue`.process -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import kotlinx.coroutines.* @@ -32,13 +32,13 @@ class ContinueProcessHandler( log.debug("Handle: $line") handleMessage(line) } catch (e: Exception) { - service().report(e, "Error handling message: $line") + service().report(e, "Error handling message: $line") } } else delay(100) } } catch (e: IOException) { - service().report(e) + service().report(e) } } scope.launch(Dispatchers.IO) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt index 3f30c17a8..69ea9b911 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt @@ -23,10 +23,11 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() { try { val event = events.filterIsInstance() .firstOrNull() ?: return false - service().report( + service().report( throwable = event.data.throwable, message = additionalInfo ?: event.data.message, - attachments = event.data.allAttachments + attachments = event.data.allAttachments, + ignoreTelemetrySettings = true ) } catch (_: Exception) { consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED)) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinuePostHogService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinuePostHogService.kt new file mode 100644 index 000000000..bd9b70942 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinuePostHogService.kt @@ -0,0 +1,32 @@ +package com.github.continuedev.continueintellijextension.error + +import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.diagnostic.Logger +import com.posthog.java.PostHog + +@Service +class ContinuePostHogService( + private val telemetryStatus: ContinueTelemetryStatus = service(), + private val posthog: PostHog = PostHog.Builder(POSTHOG_API_KEY).host("https://app.posthog.com").build() +) { + private val log = Logger.getInstance(ContinuePostHogService::class.java) + private val distinctId: String = getMachineUniqueID() + + fun capture(eventName: String, properties: Map) { + if (!telemetryStatus.allowAnonymousTelemetry) { + log.warn("PostHog capture was ignored because telemetry is disabled") + return + } + try { + posthog.capture(distinctId, eventName, properties) + log.warn("Telemetry sent to PostHog: $eventName") + } catch (_: Exception) { + } + } + + private companion object { + private const val POSTHOG_API_KEY = "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs" + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueSentryService.kt similarity index 76% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueSentryService.kt index 35e23d8a2..6e35a18ca 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueSentryService.kt @@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.error import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId @@ -16,8 +17,10 @@ import io.sentry.protocol.Message private typealias SentryAttachment = io.sentry.Attachment @Service -class ContinueErrorService { - private val log = Logger.getInstance(ContinueErrorService::class.java) +class ContinueSentryService( + private val telemetryStatus: ContinueTelemetryStatus = service() +) { + private val log = Logger.getInstance(ContinueSentryService::class.java) init { Sentry.init { config -> @@ -35,8 +38,13 @@ class ContinueErrorService { fun report( throwable: Throwable, message: String? = null, - attachments: List? = null + attachments: List? = null, + ignoreTelemetrySettings: Boolean = false ) { + if (!ignoreTelemetrySettings && !telemetryStatus.allowAnonymousTelemetry) { + log.warn("Sentry report was ignored because telemetry is disabled") + return + } val sentryEvent = SentryEvent() sentryEvent.throwable = throwable sentryEvent.message = Message().apply { this.message = message } @@ -48,6 +56,10 @@ class ContinueErrorService { fun reportMessage( message: String, ) { + if (!telemetryStatus.allowAnonymousTelemetry) { + log.warn("Sentry message report was ignored because telemetry is disabled") + return + } Sentry.captureMessage(message) log.warn("Message sent to Sentry: $message") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatus.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatus.kt new file mode 100644 index 000000000..bbc9eb1ee --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatus.kt @@ -0,0 +1,5 @@ +package com.github.continuedev.continueintellijextension.error + +interface ContinueTelemetryStatus { + val allowAnonymousTelemetry: Boolean +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatusService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatusService.kt new file mode 100644 index 000000000..192f81caf --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatusService.kt @@ -0,0 +1,44 @@ +package com.github.continuedev.continueintellijextension.error + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.project.ProjectManager +import kotlinx.coroutines.* +import kotlin.time.Duration.Companion.seconds + +@Service +class ContinueTelemetryStatusService : ContinueTelemetryStatus { + private val scope = CoroutineScope(Dispatchers.Default) + + @Volatile + override var allowAnonymousTelemetry: Boolean = DISABLED_FALLBACK + private set + + init { + scope.launch { + while (isActive) { + poolTelemetryStatus() + delay(10.seconds) + } + } + } + + private fun poolTelemetryStatus() { + // this works, but ideally, the project should be a dependency injected via constructor + val project = ProjectManager.getInstance().openProjects.firstOrNull() + ?: return + val coreMessenger = project.service().coreMessenger + ?: return + coreMessenger.request("config/getSerializedProfileInfo", null, null) { response -> + allowAnonymousTelemetry = + response.castNestedOrNull("content", "result", "config", "allowAnonymousTelemetry") + ?: DISABLED_FALLBACK + } + } + + private companion object { + const val DISABLED_FALLBACK = false + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 057a87593..a2731dd0f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -1,7 +1,7 @@ package com.github.continuedev.continueintellijextension.services import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent @@ -132,7 +132,7 @@ open class ContinueExtensionSettings : PersistentStateComponent().report(e, "Unexpected exception during remote config sync") + service().report(e, "Unexpected exception during remote config sync") } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt deleted file mode 100644 index 3b3041ff3..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.github.continuedev.continueintellijextension.services - -import com.intellij.openapi.components.Service -import com.posthog.java.PostHog -import com.posthog.java.PostHog.Builder - -@Service -class TelemetryService { - private val POSTHOG_API_KEY = "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs" - private var posthog: PostHog? = null; - private var distinctId: String? = null; - - fun setup(distinctId: String) { - this.posthog = Builder(POSTHOG_API_KEY).host("https://app.posthog.com").build() - this.distinctId = distinctId - } - - fun capture(eventName: String, properties: Map) { - if (this.posthog == null || this.distinctId == null) { - return; - } - try { - this.posthog?.capture(this.distinctId, eventName, properties) - } catch (e: Exception) {} - } - - fun shutdown() { - this.posthog?.shutdown() - } -} \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinuePostHogServiceTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinuePostHogServiceTest.kt new file mode 100644 index 000000000..d69f610fa --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinuePostHogServiceTest.kt @@ -0,0 +1,29 @@ +package com.github.continuedev.continueintellijextension.unit + +import com.github.continuedev.continueintellijextension.error.ContinuePostHogService +import com.github.continuedev.continueintellijextension.error.ContinueTelemetryStatus +import com.posthog.java.PostHog +import io.mockk.mockk +import io.mockk.verify +import junit.framework.TestCase + +class ContinuePostHogServiceTest : TestCase() { + + fun `test report when telemetry is enabled`() { + val postHog = mockk(relaxed = true) + val service = ContinuePostHogService(TestTelemetryService(true), postHog) + service.capture("test", mapOf("test" to "test")) + verify { postHog.capture(any(), any(), any()) } + } + + fun `test don't report when telemetry is disabled`() { + val postHog = mockk(relaxed = true) + val service = ContinuePostHogService(TestTelemetryService(false), postHog) + service.capture("test", mapOf("test" to "test")) + verify(exactly = 0) { postHog.capture(any(), any(), any()) } + } + + private class TestTelemetryService( + override val allowAnonymousTelemetry: Boolean + ) : ContinueTelemetryStatus +} \ No newline at end of file diff --git a/extensions/vscode/src/activation/JumpManager.vitest.ts b/extensions/vscode/src/activation/JumpManager.vitest.ts new file mode 100644 index 000000000..3a74f479b --- /dev/null +++ b/extensions/vscode/src/activation/JumpManager.vitest.ts @@ -0,0 +1,458 @@ +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { NextEditOutcome } from "core/nextEdit/types"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; +import { CompletionDataForAfterJump, JumpManager } from "./JumpManager"; + +// Mock VSCode API +vi.mock("vscode", () => { + return { + window: { + createTextEditorDecorationType: vi.fn(() => ({ + dispose: vi.fn(), + })), + activeTextEditor: { + document: { + lineAt: vi.fn((line) => ({ + text: "Test line content", + lineNumber: line, + })), + lineCount: 10, + }, + setDecorations: vi.fn(), + selection: { active: { line: 0, character: 0 } }, + revealRange: vi.fn(), + visibleRanges: [{ start: { line: 0 }, end: { line: 5 } }], + }, + onDidChangeTextEditorSelection: vi.fn(() => ({ + dispose: vi.fn(), + })), + }, + commands: { + executeCommand: vi.fn(), + registerCommand: vi.fn(() => ({ + dispose: vi.fn(), + })), + }, + Position: class { + line: number; + character: number; + constructor(line: number, character: number) { + this.line = line; + this.character = character; + } + isEqual(other: any): boolean { + return this.line === other.line && this.character === other.character; + } + }, + Range: class { + start: any; + end: any; + constructor( + startLine: number, + startChar: number, + endLine: number, + endChar: number, + ) { + this.start = { line: startLine, character: startChar }; + this.end = { line: endLine, character: endChar }; + } + }, + Selection: class { + anchor: any; + active: any; + constructor(anchor: any, active: any) { + this.anchor = anchor; + this.active = active; + } + }, + TextEditorDecorationType: class { + dispose: () => void; + constructor() { + this.dispose = vi.fn(); + } + }, + TextEditorRevealType: { + InCenter: "inCenter", + }, + ThemeColor: class { + id: string; + constructor(id: string) { + this.id = id; + } + }, + }; +}); + +// Mock NextEditProvider +vi.mock("core/nextEdit/NextEditProvider", () => { + const mockDeleteChain = vi.fn(); + const mockGetInstance = vi.fn(() => ({ + deleteChain: mockDeleteChain, + })); + + return { + NextEditProvider: { + getInstance: mockGetInstance, + }, + }; +}); + +const createMockNextEditOutcome = ( + overrides: Partial = {}, +): NextEditOutcome => { + return { + // TabAutocompleteOptions properties + disable: false, + maxPromptTokens: 2048, + debounceDelay: 300, + modelTimeout: 5000, + maxSuffixPercentage: 0.5, + prefixPercentage: 0.8, + transform: true, + template: "default", + multilineCompletions: "auto", + slidingWindowPrefixPercentage: 0.5, + slidingWindowSize: 100, + useCache: true, + onlyMyCode: false, + useRecentlyEdited: true, + useRecentlyOpened: true, + disableInFiles: [".env", "node_modules/**"], + useImports: true, + showWhateverWeHaveAtXMs: 2000, + experimental_includeClipboard: true, + experimental_includeRecentlyVisitedRanges: true, + experimental_includeRecentlyEditedRanges: true, + experimental_includeDiff: true, + experimental_enableStaticContextualization: false, + // Base properties + elapsed: 1500, + modelProvider: "openai", + modelName: "gpt-4", + completionOptions: { + temperature: 0.7, + max_tokens: 1000, + }, + completionId: "comp_12345abcde", + uniqueId: "ne_67890fghij", + timestamp: Date.now(), + gitRepo: "continuedev/continue", + + // NextEdit specific properties + fileUri: "file:///workspace/project/src/main.ts", + workspaceDirUri: "file:///workspace/project", + prompt: "Add error handling to this function", + userEdits: "// I added a try/catch block", + userExcerpts: "function example() { ... }", + originalEditableRange: "function example() {\n return fetch(url);\n}", + completion: + "function example() {\n try {\n return fetch(url);\n } catch (error) {\n console.error('Fetch failed:', error);\n throw error;\n }\n}", + cursorPosition: { line: 2, character: 10 }, + finalCursorPosition: { line: 4, character: 5 }, + accepted: true, + editableRegionStartLine: 1, + editableRegionEndLine: 3, + + // Apply any overrides + ...overrides, + }; +}; + +describe("JumpManager", () => { + let jumpManager: JumpManager; + + beforeEach(() => { + // Reset mocks + vi.resetAllMocks(); + + // Clear any existing instance + JumpManager.clearInstance(); + + // Get a fresh instance + jumpManager = JumpManager.getInstance(); + }); + + afterEach(() => { + jumpManager.dispose(); + }); + + describe("getInstance", () => { + it("should return the same instance on multiple calls", () => { + const instance1 = JumpManager.getInstance(); + const instance2 = JumpManager.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("clearInstance", () => { + it("should dispose the current instance and clear it", () => { + const instance = JumpManager.getInstance(); + const disposeSpy = vi.spyOn(instance, "dispose"); + + JumpManager.clearInstance(); + + expect(disposeSpy).toHaveBeenCalled(); + + // Get a new instance + const newInstance = JumpManager.getInstance(); + expect(newInstance).not.toBe(instance); + }); + }); + + describe("suggestJump", () => { + it("should set jumpInProgress to true", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(3, 0); + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + expect(jumpManager.isJumpInProgress()).toBe(true); + }); + + it("should not suggest jump if completion content matches document content", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(3, 0); + const completionContent = "Test line content"; + + // Mock document content to match the completion content + vscode.window.activeTextEditor!.document.lineAt = vi.fn(() => ({ + text: "Test line content", + lineNumber: 3, + })) as any; + + await jumpManager.suggestJump( + currentPosition, + nextJumpLocation, + completionContent, + ); + + // Jump should not be suggested, so decorations should not be created + expect( + vscode.window.createTextEditorDecorationType, + ).not.toHaveBeenCalled(); + }); + + it("should render decoration for jump location outside visible range (below)", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(8, 0); // Outside visible range (below) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + // Should set context + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + true, + ); + // Should register key listeners + expect(vscode.commands.registerCommand).toHaveBeenCalledWith( + "continue.acceptJump", + expect.any(Function), + ); + expect(vscode.commands.registerCommand).toHaveBeenCalledWith( + "continue.rejectJump", + expect.any(Function), + ); + }); + + it("should render decoration for jump location outside visible range (above)", async () => { + // Set visible range to be below the jump target + // @ts-ignore + vscode.window.activeTextEditor!.visibleRanges = [ + { start: { line: 5 }, end: { line: 10 } }, + ]; + + const currentPosition = new vscode.Position(6, 0); + const nextJumpLocation = new vscode.Position(2, 0); // Outside visible range (above) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + }); + }); + + describe("registerKeyListeners", () => { + it("should register acceptJump command that moves cursor", async () => { + // Setup private method access (this is a bit of a hack for testing private methods) + const privateJumpManager = jumpManager as any; + + // Mock context + privateJumpManager._jumpDecorationVisible = true; + + // Create editor mock + const editor = { + selection: null, + setSelection: vi.fn(), + }; + + // Create jump position + const jumpPosition = new vscode.Position(3, 5); + + // Call the private method + await privateJumpManager.registerKeyListeners(editor, jumpPosition); + + // Find the command handler + //@ts-ignore + const commandArgs = vscode.commands.registerCommand.mock.calls.find( + (call: any) => call[0] === "continue.acceptJump", + ); + const acceptJumpHandler = commandArgs[1]; + + // Call the handler + await acceptJumpHandler(); + + // Expect selection to be updated + expect(editor.selection).toEqual( + new vscode.Selection(jumpPosition, jumpPosition), + ); + // Expect decoration to be cleared + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + + it("should register rejectJump command that deletes the chain", async () => { + // Setup private method access + const privateJumpManager = jumpManager as any; + + // Mock context + privateJumpManager._jumpDecorationVisible = true; + + // Get a reference to the mocked deleteChain + const mockDeleteChain = vi.mocked( + NextEditProvider.getInstance().deleteChain, + ); + mockDeleteChain.mockClear(); + + // Call the private method + await privateJumpManager.registerKeyListeners( + {} as vscode.TextEditor, + new vscode.Position(0, 0), + ); + + // Find the command handler + //@ts-ignore + const commandArgs = vscode.commands.registerCommand.mock.calls.find( + (call: any) => call[0] === "continue.rejectJump", + ); + expect(commandArgs).toBeDefined(); + const rejectJumpHandler = commandArgs?.[1]; + expect(rejectJumpHandler).toBeDefined(); + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the handler + await rejectJumpHandler(); + + // Debug: Log state after calling handler + console.log("mockDeleteChain called:", mockDeleteChain.mock.calls.length); + + // Expect NextEditProvider.deleteChain to be called + expect(mockDeleteChain).toHaveBeenCalled(); + + // Expect decoration to be cleared + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + }); + + describe("setCompletionAfterJump", () => { + it("should store completion data", () => { + const completionData: CompletionDataForAfterJump = { + completionId: "test-id", + outcome: createMockNextEditOutcome(), + currentPosition: new vscode.Position(1, 0), + }; + + // Set the completion data + jumpManager.setCompletionAfterJump(completionData); + + // Verify the completion data was stored correctly + expect((jumpManager as any)._completionAfterJump).toEqual(completionData); + }); + + it("should process completion data when jump is completed", async () => { + const completionData: CompletionDataForAfterJump = { + completionId: "test-id", + outcome: createMockNextEditOutcome(), + currentPosition: new vscode.Position(1, 0), + }; + + // Set the completion data + jumpManager.setCompletionAfterJump(completionData); + + // Verify the completion data was set correctly + expect((jumpManager as any)._completionAfterJump).toEqual(completionData); + + // Reset executeCommand mock to clear previous calls + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Directly simulate what happens when a jump is completed + // by manipulating the internal state + (jumpManager as any)._jumpInProgress = false; + + // Now directly call the method that would show the completion + // We need to manually implement what the callback would do + if ((jumpManager as any)._completionAfterJump) { + vscode.commands.executeCommand( + "continue.showNextEditAfterJump", + (jumpManager as any)._completionAfterJump, + ); + (jumpManager as any)._completionAfterJump = null; + } + + // Verify that the command was called with the completion data + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "continue.showNextEditAfterJump", + completionData, + ); + + // Verify that _completionAfterJump was reset to null + expect((jumpManager as any)._completionAfterJump).toBeNull(); + }); + }); + + describe("clearJumpDecoration", () => { + it("should dispose decoration and reset state", async () => { + // Setup private method access + const privateJumpManager = jumpManager as any; + + // Create a mock decoration with a spy on dispose + const mockDispose = vi.fn(); + privateJumpManager._jumpDecoration = { + dispose: mockDispose, + }; + privateJumpManager._jumpDecorationVisible = true; + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the method + await privateJumpManager.clearJumpDecoration(); + + // Expect dispose to have been called + expect(mockDispose).toHaveBeenCalled(); + + // Expect decoration to be undefined after clearing + expect(privateJumpManager._jumpDecoration).toBeUndefined(); + expect(privateJumpManager._jumpDecorationVisible).toBe(false); + + // Expect context to be reset + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + }); +}); diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d6d7875d5..949494c99 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -285,7 +285,7 @@ export class ContinueCompletionProvider outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, - false, + { withChain: false }, ); if (!outcome || !outcome.completion) { diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx index 5aee1466f..49217c1b7 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx @@ -59,7 +59,7 @@ export const ToolPoliciesSection = () => { return ( <> {(mode === "chat" || mode === "plan") && ( -
+
{message} diff --git a/scripts/oneper b/scripts/oneper index e68ad0a6e..0a0485bea 100755 --- a/scripts/oneper +++ b/scripts/oneper @@ -22,20 +22,22 @@ show_help() { echo " Download and install VSIX from specified PR number" echo " Platform options: macos, linux (auto-detected by default)" echo " install --latest Install latest pre-release from VS Code marketplace" - echo " setup-cron Set up automatic updates every 10 minutes" + echo " setup-cron [--interval ] Set up automatic updates (default: 10 minutes)" echo " remove-cron Remove automatic updates" echo " clean Remove all downloaded VSIX files from oneper cache" echo "" echo "Options:" echo " -h, --help Show this help message" - echo " --platform Specify platform for builds (macos, linux)" + echo " --platform Specify platform for builds (macos, linux) + --interval Set update interval in minutes (for setup-cron)" echo "" echo "Examples:" echo " oneper install # Install latest build from main branch" echo " oneper install --pr 123 # Install VSIX from PR #123" echo " oneper install --pr 123 --platform linux # Install Linux VSIX from PR #123" echo " oneper install --latest # Install latest pre-release" - echo " oneper setup-cron # Auto-update every 10 minutes" + echo " oneper setup-cron # Auto-update every 10 minutes + oneper setup-cron --interval 5 # Auto-update every 5 minutes" echo " oneper remove-cron # Stop auto-updates" echo " oneper clean # Clear cached VSIX files" echo " oneper -h # Show help" @@ -350,23 +352,24 @@ check_and_install_if_new() { fi if [ "$current_run_id" != "$last_run_id" ]; then - echo "$(date): 🔄 New build detected (run $current_run_id), installing..." + echo "$(date): 🔄 New build detected (https://github.com/$REPO/runs/$current_run_id), installing..." # Install from main silently if install_from_main > /dev/null 2>&1; then echo "$current_run_id" > "$last_run_file" - echo "$(date): ✅ Successfully installed new build from run $current_run_id" + echo "$(date): ✅ Successfully installed new build from https://github.com/$REPO/actions/runs/$current_run_id" else echo "$(date): ❌ Failed to install new build" >&2 return 1 fi else - echo "$(date): 🔍 No new builds (current: $current_run_id)" + echo "$(date): 🔍 No new builds (current: https://github.com/$REPO/actions/runs/$current_run_id)" fi } setup_cron() { - echo "🔧 Setting up automatic updates every 10 minutes..." + local interval=${1:-10} # Default to 10 minutes if not specified + echo "🔧 Setting up automatic updates every $interval minutes..." # Get the absolute path to this script local script_path=$(realpath "$0") @@ -377,7 +380,7 @@ setup_cron() { cat > "$cron_script" << EOF #!/bin/bash # Auto-generated oneper cron script -export PATH="/usr/local/bin:/usr/bin:/bin:\$PATH" +export PATH="/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:\$PATH" cd "\$(dirname "$script_path")" "$script_path" --cron-check EOF @@ -389,7 +392,7 @@ EOF touch "$log_file" # Add to crontab - local cron_line="*/10 * * * * $cron_script >> $log_file 2>&1" + local cron_line="*/$interval * * * * $cron_script >> $log_file 2>&1" # Check if cron job already exists if crontab -l 2>/dev/null | grep -q "oneper-cron.sh"; then @@ -511,7 +514,17 @@ main() { esac ;; "setup-cron") - setup_cron + # Check for --interval option + local interval=10 + if [ "$2" = "--interval" ] && [ -n "$3" ]; then + interval="$3" + # Validate interval is a positive integer + if ! [[ "$interval" =~ ^[1-9][0-9]*$ ]]; then + echo "❌ Invalid interval: $interval. Must be a positive integer." + exit 1 + fi + fi + setup_cron "$interval" ;; "remove-cron") remove_cron