From 8c8888a977dd2a9e03428847cf83fe6e4036b4ee Mon Sep 17 00:00:00 2001 From: Daniel <57051444+daniel-lxs@users.noreply.github.com> Date: Wed, 16 Jul 2025 08:30:33 -0500 Subject: [PATCH 01/19] feat: increase Ollama API timeout values and extract as constants (#5778) - Increase embedding request timeout from 10s to 60s - Increase validation request timeouts from 5s to 30s - Extract timeout values as module-level constants for better maintainability - OLLAMA_EMBEDDING_TIMEOUT_MS = 60000 (60 seconds) - OLLAMA_VALIDATION_TIMEOUT_MS = 30000 (30 seconds) --- src/services/code-index/embedders/ollama.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/services/code-index/embedders/ollama.ts b/src/services/code-index/embedders/ollama.ts index 20b22b92bf..c160d39490 100644 --- a/src/services/code-index/embedders/ollama.ts +++ b/src/services/code-index/embedders/ollama.ts @@ -7,6 +7,10 @@ import { withValidationErrorHandling, sanitizeErrorMessage } from "../shared/val import { TelemetryService } from "@roo-code/telemetry" import { TelemetryEventName } from "@roo-code/types" +// Timeout constants for Ollama API requests +const OLLAMA_EMBEDDING_TIMEOUT_MS = 60000 // 60 seconds for embedding requests +const OLLAMA_VALIDATION_TIMEOUT_MS = 30000 // 30 seconds for validation requests + /** * Implements the IEmbedder interface using a local Ollama instance. */ @@ -61,7 +65,7 @@ export class CodeIndexOllamaEmbedder implements IEmbedder { // Add timeout to prevent indefinite hanging const controller = new AbortController() - const timeoutId = setTimeout(() => controller.abort(), 10000) // 10 second timeout + const timeoutId = setTimeout(() => controller.abort(), OLLAMA_EMBEDDING_TIMEOUT_MS) const response = await fetch(url, { method: "POST", @@ -140,7 +144,7 @@ export class CodeIndexOllamaEmbedder implements IEmbedder { // Add timeout to prevent indefinite hanging const controller = new AbortController() - const timeoutId = setTimeout(() => controller.abort(), 5000) // 5 second timeout + const timeoutId = setTimeout(() => controller.abort(), OLLAMA_VALIDATION_TIMEOUT_MS) const modelsResponse = await fetch(modelsUrl, { method: "GET", @@ -197,7 +201,7 @@ export class CodeIndexOllamaEmbedder implements IEmbedder { // Add timeout for test request too const testController = new AbortController() - const testTimeoutId = setTimeout(() => testController.abort(), 5000) + const testTimeoutId = setTimeout(() => testController.abort(), OLLAMA_VALIDATION_TIMEOUT_MS) const testResponse = await fetch(testUrl, { method: "POST", From 0f994fcf2285d350ac6dab59c1f6eb6000cb96b1 Mon Sep 17 00:00:00 2001 From: Matt Rubens Date: Wed, 16 Jul 2025 10:57:34 -0400 Subject: [PATCH 02/19] Fix settings dirty check (#5779) --- webview-ui/src/components/settings/ApiOptions.tsx | 4 ++-- webview-ui/src/components/settings/SettingsView.tsx | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index d0ec50abad..06994b16b9 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -167,10 +167,10 @@ const ApiOptions = ({ // Update `apiModelId` whenever `selectedModelId` changes. useEffect(() => { - if (selectedModelId) { + if (selectedModelId && apiConfiguration.apiModelId !== selectedModelId) { setApiConfigurationField("apiModelId", selectedModelId) } - }, [selectedModelId, setApiConfigurationField]) + }, [selectedModelId, setApiConfigurationField, apiConfiguration.apiModelId]) // Debounced refresh model updates, only executed 250ms after the user // stops typing. diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index cf9e779cbd..fd3a8a129b 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -218,7 +218,15 @@ const SettingsView = forwardRef(({ onDone, t return prevState } - setChangeDetected(true) + const previousValue = prevState.apiConfiguration?.[field] + + // Don't treat initial sync from undefined to a defined value as a user change + // This prevents the dirty state when the component initializes and auto-syncs the model ID + const isInitialSync = previousValue === undefined && value !== undefined + + if (!isInitialSync) { + setChangeDetected(true) + } return { ...prevState, apiConfiguration: { ...prevState.apiConfiguration, [field]: value } } }) }, From a7a6bcb30f7972782c0f6c8f230d2f40767808ab Mon Sep 17 00:00:00 2001 From: Daniel <57051444+daniel-lxs@users.noreply.github.com> Date: Wed, 16 Jul 2025 14:06:26 -0500 Subject: [PATCH 03/19] fix: resolve DirectoryScanner memory leak and improve file limit handling (#5785) --- src/services/code-index/constants/index.ts | 2 +- .../code-index/interfaces/file-processor.ts | 1 - .../processors/__tests__/scanner.spec.ts | 36 +++++++------ src/services/code-index/processors/scanner.ts | 50 ++++++++++++------- 4 files changed, 55 insertions(+), 34 deletions(-) diff --git a/src/services/code-index/constants/index.ts b/src/services/code-index/constants/index.ts index c2567f5635..706a73935a 100644 --- a/src/services/code-index/constants/index.ts +++ b/src/services/code-index/constants/index.ts @@ -15,7 +15,7 @@ export const QDRANT_CODE_BLOCK_NAMESPACE = "f47ac10b-58cc-4372-a567-0e02b2c3d479 export const MAX_FILE_SIZE_BYTES = 1 * 1024 * 1024 // 1MB /**Directory Scanner */ -export const MAX_LIST_FILES_LIMIT = 3_000 +export const MAX_LIST_FILES_LIMIT_CODE_INDEX = 50_000 export const BATCH_SEGMENT_THRESHOLD = 60 // Number of code segments to batch for embeddings/upserts export const MAX_BATCH_RETRIES = 3 export const INITIAL_RETRY_DELAY_MS = 500 diff --git a/src/services/code-index/interfaces/file-processor.ts b/src/services/code-index/interfaces/file-processor.ts index f00c19c619..88b19007c3 100644 --- a/src/services/code-index/interfaces/file-processor.ts +++ b/src/services/code-index/interfaces/file-processor.ts @@ -38,7 +38,6 @@ export interface IDirectoryScanner { onBlocksIndexed?: (indexedCount: number) => void, onFileParsed?: (fileBlockCount: number) => void, ): Promise<{ - codeBlocks: CodeBlock[] stats: { processed: number skipped: number diff --git a/src/services/code-index/processors/__tests__/scanner.spec.ts b/src/services/code-index/processors/__tests__/scanner.spec.ts index f90a6c8159..4d4150b443 100644 --- a/src/services/code-index/processors/__tests__/scanner.spec.ts +++ b/src/services/code-index/processors/__tests__/scanner.spec.ts @@ -168,7 +168,16 @@ describe("DirectoryScanner", () => { expect(mockCodeParser.parseFile).not.toHaveBeenCalled() }) - it("should parse changed files and return code blocks", async () => { + it("should parse changed files and return empty codeBlocks array", async () => { + // Create scanner without embedder to test the non-embedding path + const scannerNoEmbeddings = new DirectoryScanner( + null as any, // No embedder + null as any, // No vector store + mockCodeParser, + mockCacheManager, + mockIgnoreInstance, + ) + const { listFiles } = await import("../../../glob/list-files") vi.mocked(listFiles).mockResolvedValue([["test/file1.js"], false]) const mockBlocks: any[] = [ @@ -185,8 +194,7 @@ describe("DirectoryScanner", () => { ] ;(mockCodeParser.parseFile as any).mockResolvedValue(mockBlocks) - const result = await scanner.scanDirectory("/test") - expect(result.codeBlocks).toEqual(mockBlocks) + const result = await scannerNoEmbeddings.scanDirectory("/test") expect(result.stats.processed).toBe(1) }) @@ -252,6 +260,15 @@ describe("DirectoryScanner", () => { }) it("should process markdown files alongside code files", async () => { + // Create scanner without embedder to test the non-embedding path + const scannerNoEmbeddings = new DirectoryScanner( + null as any, // No embedder + null as any, // No vector store + mockCodeParser, + mockCacheManager, + mockIgnoreInstance, + ) + const { listFiles } = await import("../../../glob/list-files") vi.mocked(listFiles).mockResolvedValue([["test/README.md", "test/app.js", "docs/guide.markdown"], false]) @@ -306,7 +323,7 @@ describe("DirectoryScanner", () => { return [] }) - const result = await scanner.scanDirectory("/test") + const result = await scannerNoEmbeddings.scanDirectory("/test") // Verify all files were processed expect(mockCodeParser.parseFile).toHaveBeenCalledTimes(3) @@ -314,16 +331,7 @@ describe("DirectoryScanner", () => { expect(mockCodeParser.parseFile).toHaveBeenCalledWith("test/app.js", expect.any(Object)) expect(mockCodeParser.parseFile).toHaveBeenCalledWith("docs/guide.markdown", expect.any(Object)) - // Verify code blocks include both markdown and code content - expect(result.codeBlocks).toHaveLength(3) - expect(result.codeBlocks).toEqual( - expect.arrayContaining([ - expect.objectContaining({ type: "markdown_header_h1" }), - expect.objectContaining({ type: "function" }), - expect.objectContaining({ type: "markdown_header_h2" }), - ]), - ) - + // Verify processing still works without codeBlocks accumulation expect(result.stats.processed).toBe(3) }) diff --git a/src/services/code-index/processors/scanner.ts b/src/services/code-index/processors/scanner.ts index 538a1252d7..e6ca297399 100644 --- a/src/services/code-index/processors/scanner.ts +++ b/src/services/code-index/processors/scanner.ts @@ -17,7 +17,7 @@ import { t } from "../../../i18n" import { QDRANT_CODE_BLOCK_NAMESPACE, MAX_FILE_SIZE_BYTES, - MAX_LIST_FILES_LIMIT, + MAX_LIST_FILES_LIMIT_CODE_INDEX, BATCH_SEGMENT_THRESHOLD, MAX_BATCH_RETRIES, INITIAL_RETRY_DELAY_MS, @@ -51,13 +51,13 @@ export class DirectoryScanner implements IDirectoryScanner { onError?: (error: Error) => void, onBlocksIndexed?: (indexedCount: number) => void, onFileParsed?: (fileBlockCount: number) => void, - ): Promise<{ codeBlocks: CodeBlock[]; stats: { processed: number; skipped: number }; totalBlockCount: number }> { + ): Promise<{ stats: { processed: number; skipped: number }; totalBlockCount: number }> { const directoryPath = directory // Capture workspace context at scan start const scanWorkspace = getWorkspacePathForContext(directoryPath) // Get all files recursively (handles .gitignore automatically) - const [allPaths, _] = await listFiles(directoryPath, true, MAX_LIST_FILES_LIMIT) + const [allPaths, _] = await listFiles(directoryPath, true, MAX_LIST_FILES_LIMIT_CODE_INDEX) // Filter out directories (marked with trailing '/') const filePaths = allPaths.filter((p) => !p.endsWith("/")) @@ -85,7 +85,6 @@ export class DirectoryScanner implements IDirectoryScanner { // Initialize tracking variables const processedFiles = new Set() - const codeBlocks: CodeBlock[] = [] let processedCount = 0 let skippedCount = 0 @@ -98,7 +97,7 @@ export class DirectoryScanner implements IDirectoryScanner { let currentBatchBlocks: CodeBlock[] = [] let currentBatchTexts: string[] = [] let currentBatchFileInfos: { filePath: string; fileHash: string; isNew: boolean }[] = [] - const activeBatchPromises: Promise[] = [] + const activeBatchPromises = new Set>() // Initialize block counter let totalBlockCount = 0 @@ -125,6 +124,7 @@ export class DirectoryScanner implements IDirectoryScanner { // Check against cache const cachedFileHash = this.cacheManager.getHash(filePath) + const isNewFile = !cachedFileHash if (cachedFileHash === currentFileHash) { // File is unchanged skippedCount++ @@ -135,7 +135,6 @@ export class DirectoryScanner implements IDirectoryScanner { const blocks = await this.codeParser.parseFile(filePath, { content, fileHash: currentFileHash }) const fileBlockCount = blocks.length onFileParsed?.(fileBlockCount) - codeBlocks.push(...blocks) processedCount++ // Process embeddings if configured @@ -146,20 +145,11 @@ export class DirectoryScanner implements IDirectoryScanner { const trimmedContent = block.content.trim() if (trimmedContent) { const release = await mutex.acquire() - totalBlockCount += fileBlockCount try { currentBatchBlocks.push(block) currentBatchTexts.push(trimmedContent) addedBlocksFromFile = true - if (addedBlocksFromFile) { - currentBatchFileInfos.push({ - filePath, - fileHash: currentFileHash, - isNew: !this.cacheManager.getHash(filePath), - }) - } - // Check if batch threshold is met if (currentBatchBlocks.length >= BATCH_SEGMENT_THRESHOLD) { // Copy current batch data and clear accumulators @@ -181,13 +171,33 @@ export class DirectoryScanner implements IDirectoryScanner { onBlocksIndexed, ), ) - activeBatchPromises.push(batchPromise) + activeBatchPromises.add(batchPromise) + + // Clean up completed promises to prevent memory accumulation + batchPromise.finally(() => { + activeBatchPromises.delete(batchPromise) + }) } } finally { release() } } } + + // Add file info once per file (outside the block loop) + if (addedBlocksFromFile) { + const release = await mutex.acquire() + try { + totalBlockCount += fileBlockCount + currentBatchFileInfos.push({ + filePath, + fileHash: currentFileHash, + isNew: isNewFile, + }) + } finally { + release() + } + } } else { // Only update hash if not being processed in a batch await this.cacheManager.updateHash(filePath, currentFileHash) @@ -232,7 +242,12 @@ export class DirectoryScanner implements IDirectoryScanner { const batchPromise = batchLimiter(() => this.processBatch(batchBlocks, batchTexts, batchFileInfos, scanWorkspace, onError, onBlocksIndexed), ) - activeBatchPromises.push(batchPromise) + activeBatchPromises.add(batchPromise) + + // Clean up completed promises to prevent memory accumulation + batchPromise.finally(() => { + activeBatchPromises.delete(batchPromise) + }) } finally { release() } @@ -280,7 +295,6 @@ export class DirectoryScanner implements IDirectoryScanner { } return { - codeBlocks, stats: { processed: processedCount, skipped: skippedCount, From a92ee567df44806908dc67cb18519e9e0e7f7a09 Mon Sep 17 00:00:00 2001 From: Christiaan Arnoldus Date: Wed, 16 Jul 2025 21:58:11 +0200 Subject: [PATCH 04/19] Format time in ISO 8601 (#5793) --- src/core/environment/getEnvironmentDetails.ts | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/core/environment/getEnvironmentDetails.ts b/src/core/environment/getEnvironmentDetails.ts index 8d4f157f4d..6f0c9fe2bf 100644 --- a/src/core/environment/getEnvironmentDetails.ts +++ b/src/core/environment/getEnvironmentDetails.ts @@ -179,22 +179,12 @@ export async function getEnvironmentDetails(cline: Task, includeFileDetails: boo // Add current time information with timezone. const now = new Date() - const formatter = new Intl.DateTimeFormat(undefined, { - year: "numeric", - month: "numeric", - day: "numeric", - hour: "numeric", - minute: "numeric", - second: "numeric", - hour12: true, - }) - - const timeZone = formatter.resolvedOptions().timeZone + const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone const timeZoneOffset = -now.getTimezoneOffset() / 60 // Convert to hours and invert sign to match conventional notation const timeZoneOffsetHours = Math.floor(Math.abs(timeZoneOffset)) const timeZoneOffsetMinutes = Math.abs(Math.round((Math.abs(timeZoneOffset) - timeZoneOffsetHours) * 60)) const timeZoneOffsetStr = `${timeZoneOffset >= 0 ? "+" : "-"}${timeZoneOffsetHours}:${timeZoneOffsetMinutes.toString().padStart(2, "0")}` - details += `\n\n# Current Time\n${formatter.format(now)} (${timeZone}, UTC${timeZoneOffsetStr})` + details += `\n\n# Current Time\nCurrent time in ISO 8601 UTC format: ${now.toISOString()}\nUser time zone: ${timeZone}, UTC${timeZoneOffsetStr}` // Add context tokens information. const { contextTokens, totalCost } = getApiMetrics(cline.clineMessages) From 2458751424e7f4e72f0284e910fbd3781a9b161e Mon Sep 17 00:00:00 2001 From: Daniel <57051444+daniel-lxs@users.noreply.github.com> Date: Wed, 16 Jul 2025 16:50:14 -0500 Subject: [PATCH 05/19] fix: prevent empty mode names from being saved (#5766) (#5794) --- src/core/config/CustomModesManager.ts | 8 +++++ webview-ui/src/components/modes/ModesView.tsx | 36 +++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/core/config/CustomModesManager.ts b/src/core/config/CustomModesManager.ts index b4bcfa62d6..3da22d1be8 100644 --- a/src/core/config/CustomModesManager.ts +++ b/src/core/config/CustomModesManager.ts @@ -401,6 +401,14 @@ export class CustomModesManager { public async updateCustomMode(slug: string, config: ModeConfig): Promise { try { + // Validate the mode configuration before saving + const validationResult = modeConfigSchema.safeParse(config) + if (!validationResult.success) { + const errors = validationResult.error.errors.map((e) => e.message).join(", ") + logger.error(`Invalid mode configuration for ${slug}`, { errors: validationResult.error.errors }) + throw new Error(`Invalid mode configuration: ${errors}`) + } + const isProjectMode = config.source === "project" let targetPath: string diff --git a/webview-ui/src/components/modes/ModesView.tsx b/webview-ui/src/components/modes/ModesView.tsx index 620797290d..170d03b0e4 100644 --- a/webview-ui/src/components/modes/ModesView.tsx +++ b/webview-ui/src/components/modes/ModesView.tsx @@ -110,6 +110,10 @@ const ModesView = ({ onDone }: ModesViewProps) => { const [searchValue, setSearchValue] = useState("") const searchInputRef = useRef(null) + // Local state for mode name input to allow visual emptying + const [localModeName, setLocalModeName] = useState("") + const [currentEditingModeSlug, setCurrentEditingModeSlug] = useState(null) + // Direct update functions const updateAgentPrompt = useCallback( (mode: Mode, promptData: PromptComponent) => { @@ -218,6 +222,14 @@ const ModesView = ({ onDone }: ModesViewProps) => { } }, [getCurrentMode, checkRulesDirectory, hasRulesToExport]) + // Reset local name state when mode changes + useEffect(() => { + if (currentEditingModeSlug && currentEditingModeSlug !== visualMode) { + setCurrentEditingModeSlug(null) + setLocalModeName("") + } + }, [visualMode, currentEditingModeSlug]) + // Helper function to safely access mode properties const getModeProperty = ( mode: ModeConfig | undefined, @@ -725,16 +737,34 @@ const ModesView = ({ onDone }: ModesViewProps) => {
{ + value={ + currentEditingModeSlug === visualMode + ? localModeName + : (getModeProperty(findModeBySlug(visualMode, customModes), "name") ?? + "") + } + onFocus={() => { const customMode = findModeBySlug(visualMode, customModes) if (customMode) { + setCurrentEditingModeSlug(visualMode) + setLocalModeName(customMode.name) + } + }} + onChange={(e) => { + setLocalModeName(e.target.value) + }} + onBlur={() => { + const customMode = findModeBySlug(visualMode, customModes) + if (customMode && localModeName.trim()) { + // Only update if the name is not empty updateCustomMode(visualMode, { ...customMode, - name: e.target.value, + name: localModeName, source: customMode.source || "global", }) } + // Clear the editing state + setCurrentEditingModeSlug(null) }} className="w-full" /> From 6cf376f832c1d26005f13b0c44a748f362993053 Mon Sep 17 00:00:00 2001 From: Hannes Rudolph Date: Wed, 16 Jul 2025 15:52:29 -0600 Subject: [PATCH 06/19] fix: Resolve confusing auto-approve checkbox states (#5602) Co-authored-by: Daniel Riccio --- .../src/components/chat/AutoApproveMenu.tsx | 121 +++-- webview-ui/src/components/chat/ChatView.tsx | 14 + .../chat/__tests__/AutoApproveMenu.spec.tsx | 307 +++++++++++ .../ChatView.auto-approve-new.spec.tsx | 480 ++++++++++++++++++ .../settings/AutoApproveSettings.tsx | 34 +- .../__tests__/useAutoApprovalState.spec.ts | 282 ++++++++++ webview-ui/src/hooks/useAutoApprovalState.ts | 29 ++ .../src/hooks/useAutoApprovalToggles.ts | 50 ++ webview-ui/src/i18n/locales/ca/chat.json | 5 +- webview-ui/src/i18n/locales/ca/settings.json | 5 +- webview-ui/src/i18n/locales/de/chat.json | 5 +- webview-ui/src/i18n/locales/de/settings.json | 5 +- webview-ui/src/i18n/locales/en/chat.json | 5 +- webview-ui/src/i18n/locales/en/settings.json | 5 +- webview-ui/src/i18n/locales/es/chat.json | 5 +- webview-ui/src/i18n/locales/es/settings.json | 5 +- webview-ui/src/i18n/locales/fr/chat.json | 5 +- webview-ui/src/i18n/locales/fr/settings.json | 3 + webview-ui/src/i18n/locales/hi/chat.json | 5 +- webview-ui/src/i18n/locales/hi/settings.json | 5 +- webview-ui/src/i18n/locales/id/chat.json | 5 +- webview-ui/src/i18n/locales/id/settings.json | 5 +- webview-ui/src/i18n/locales/it/chat.json | 5 +- webview-ui/src/i18n/locales/it/settings.json | 5 +- webview-ui/src/i18n/locales/ja/chat.json | 5 +- webview-ui/src/i18n/locales/ja/settings.json | 5 +- webview-ui/src/i18n/locales/ko/chat.json | 5 +- webview-ui/src/i18n/locales/ko/settings.json | 5 +- webview-ui/src/i18n/locales/nl/chat.json | 5 +- webview-ui/src/i18n/locales/nl/settings.json | 5 +- webview-ui/src/i18n/locales/pl/chat.json | 5 +- webview-ui/src/i18n/locales/pl/settings.json | 5 +- webview-ui/src/i18n/locales/pt-BR/chat.json | 5 +- .../src/i18n/locales/pt-BR/settings.json | 5 +- webview-ui/src/i18n/locales/ru/chat.json | 5 +- webview-ui/src/i18n/locales/ru/settings.json | 5 +- webview-ui/src/i18n/locales/tr/chat.json | 5 +- webview-ui/src/i18n/locales/tr/settings.json | 5 +- webview-ui/src/i18n/locales/vi/chat.json | 5 +- webview-ui/src/i18n/locales/vi/settings.json | 5 +- webview-ui/src/i18n/locales/zh-CN/chat.json | 5 +- .../src/i18n/locales/zh-CN/settings.json | 5 +- webview-ui/src/i18n/locales/zh-TW/chat.json | 5 +- .../src/i18n/locales/zh-TW/settings.json | 5 +- 44 files changed, 1414 insertions(+), 81 deletions(-) create mode 100644 webview-ui/src/components/chat/__tests__/AutoApproveMenu.spec.tsx create mode 100644 webview-ui/src/components/chat/__tests__/ChatView.auto-approve-new.spec.tsx create mode 100644 webview-ui/src/hooks/__tests__/useAutoApprovalState.spec.ts create mode 100644 webview-ui/src/hooks/useAutoApprovalState.ts create mode 100644 webview-ui/src/hooks/useAutoApprovalToggles.ts diff --git a/webview-ui/src/components/chat/AutoApproveMenu.tsx b/webview-ui/src/components/chat/AutoApproveMenu.tsx index ae363a7b63..2e987b7c49 100644 --- a/webview-ui/src/components/chat/AutoApproveMenu.tsx +++ b/webview-ui/src/components/chat/AutoApproveMenu.tsx @@ -6,6 +6,9 @@ import { vscode } from "@src/utils/vscode" import { useExtensionState } from "@src/context/ExtensionStateContext" import { useAppTranslation } from "@src/i18n/TranslationContext" import { AutoApproveToggle, AutoApproveSetting, autoApproveSettingsConfig } from "../settings/AutoApproveToggle" +import { StandardTooltip } from "@src/components/ui" +import { useAutoApprovalState } from "@src/hooks/useAutoApprovalState" +import { useAutoApprovalToggles } from "@src/hooks/useAutoApprovalToggles" interface AutoApproveMenuProps { style?: React.CSSProperties @@ -17,16 +20,7 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => { const { autoApprovalEnabled, setAutoApprovalEnabled, - alwaysAllowReadOnly, - alwaysAllowWrite, - alwaysAllowExecute, - alwaysAllowBrowser, - alwaysAllowMcp, - alwaysAllowModeSwitch, - alwaysAllowSubtasks, alwaysApproveResubmit, - alwaysAllowFollowupQuestions, - alwaysAllowUpdateTodoList, allowedMaxRequests, setAlwaysAllowReadOnly, setAlwaysAllowWrite, @@ -43,10 +37,24 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => { const { t } = useAppTranslation() + const baseToggles = useAutoApprovalToggles() + + // AutoApproveMenu needs alwaysApproveResubmit in addition to the base toggles + const toggles = useMemo( + () => ({ + ...baseToggles, + alwaysApproveResubmit: alwaysApproveResubmit, + }), + [baseToggles, alwaysApproveResubmit], + ) + + const { hasEnabledOptions, effectiveAutoApprovalEnabled } = useAutoApprovalState(toggles, autoApprovalEnabled) + const onAutoApproveToggle = useCallback( (key: AutoApproveSetting, value: boolean) => { vscode.postMessage({ type: key, bool: value }) + // Update the specific toggle state switch (key) { case "alwaysAllowReadOnly": setAlwaysAllowReadOnly(value) @@ -79,8 +87,30 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => { setAlwaysAllowUpdateTodoList(value) break } + + // Check if we need to update the master auto-approval state + // Create a new toggles state with the updated value + const updatedToggles = { + ...toggles, + [key]: value, + } + + const willHaveEnabledOptions = Object.values(updatedToggles).some((v) => !!v) + + // If enabling the first option, enable master auto-approval + if (value && !hasEnabledOptions && willHaveEnabledOptions) { + setAutoApprovalEnabled(true) + vscode.postMessage({ type: "autoApprovalEnabled", bool: true }) + } + // If disabling the last option, disable master auto-approval + else if (!value && hasEnabledOptions && !willHaveEnabledOptions) { + setAutoApprovalEnabled(false) + vscode.postMessage({ type: "autoApprovalEnabled", bool: false }) + } }, [ + toggles, + hasEnabledOptions, setAlwaysAllowReadOnly, setAlwaysAllowWrite, setAlwaysAllowExecute, @@ -91,43 +121,32 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => { setAlwaysApproveResubmit, setAlwaysAllowFollowupQuestions, setAlwaysAllowUpdateTodoList, + setAutoApprovalEnabled, ], ) - const toggleExpanded = useCallback(() => setIsExpanded((prev) => !prev), []) + const toggleExpanded = useCallback(() => { + setIsExpanded((prev) => !prev) + }, []) - const toggles = useMemo( - () => ({ - alwaysAllowReadOnly: alwaysAllowReadOnly, - alwaysAllowWrite: alwaysAllowWrite, - alwaysAllowExecute: alwaysAllowExecute, - alwaysAllowBrowser: alwaysAllowBrowser, - alwaysAllowMcp: alwaysAllowMcp, - alwaysAllowModeSwitch: alwaysAllowModeSwitch, - alwaysAllowSubtasks: alwaysAllowSubtasks, - alwaysApproveResubmit: alwaysApproveResubmit, - alwaysAllowFollowupQuestions: alwaysAllowFollowupQuestions, - alwaysAllowUpdateTodoList: alwaysAllowUpdateTodoList, - }), - [ - alwaysAllowReadOnly, - alwaysAllowWrite, - alwaysAllowExecute, - alwaysAllowBrowser, - alwaysAllowMcp, - alwaysAllowModeSwitch, - alwaysAllowSubtasks, - alwaysApproveResubmit, - alwaysAllowFollowupQuestions, - alwaysAllowUpdateTodoList, - ], - ) + // Disable main checkbox while menu is open or no options selected + const isCheckboxDisabled = useMemo(() => { + return !hasEnabledOptions || isExpanded + }, [hasEnabledOptions, isExpanded]) const enabledActionsList = Object.entries(toggles) .filter(([_key, value]) => !!value) .map(([key]) => t(autoApproveSettingsConfig[key as AutoApproveSetting].labelKey)) .join(", ") + // Update displayed text logic + const displayText = useMemo(() => { + if (!effectiveAutoApprovalEnabled || !hasEnabledOptions) { + return t("chat:autoApprove.none") + } + return enabledActionsList || t("chat:autoApprove.none") + }, [effectiveAutoApprovalEnabled, hasEnabledOptions, enabledActionsList, t]) + const handleOpenSettings = useCallback( () => window.postMessage({ type: "action", action: "settingsButtonClicked", values: { section: "autoApprove" } }), @@ -155,14 +174,26 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => { }} onClick={toggleExpanded}>
e.stopPropagation()}> - { - const newValue = !(autoApprovalEnabled ?? false) - setAutoApprovalEnabled(newValue) - vscode.postMessage({ type: "autoApprovalEnabled", bool: newValue }) - }} - /> + + { + if (hasEnabledOptions) { + const newValue = !(autoApprovalEnabled ?? false) + setAutoApprovalEnabled(newValue) + vscode.postMessage({ type: "autoApprovalEnabled", bool: newValue }) + } + // If no options enabled, do nothing + }} + /> +
{ flex: 1, minWidth: 0, }}> - {enabledActionsList || t("chat:autoApprove.none")} + {displayText} { + // First check if auto-approval is enabled AND we have at least one permission if (!autoApprovalEnabled || !message || message.type !== "ask") { return false } + // Use the hook's result instead of duplicating the logic + if (!hasEnabledOptions) { + return false + } + if (message.ask === "followup") { return alwaysAllowFollowupQuestions } @@ -1038,6 +1051,7 @@ const ChatViewComponent: React.ForwardRefRenderFunction ({ + vscode: { + postMessage: vi.fn(), + }, +})) + +// Mock ExtensionStateContext +vi.mock("@src/context/ExtensionStateContext") + +// Mock translation hook +vi.mock("@src/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ + t: (key: string) => { + const translations: Record = { + "chat:autoApprove.title": "Auto-approve", + "chat:autoApprove.none": "None selected", + "chat:autoApprove.selectOptionsFirst": "Select at least one option below to enable auto-approval", + "chat:autoApprove.description": "Configure auto-approval settings", + "settings:autoApprove.readOnly.label": "Read-only operations", + "settings:autoApprove.write.label": "Write operations", + "settings:autoApprove.execute.label": "Execute operations", + "settings:autoApprove.browser.label": "Browser operations", + "settings:autoApprove.modeSwitch.label": "Mode switches", + "settings:autoApprove.mcp.label": "MCP operations", + "settings:autoApprove.subtasks.label": "Subtasks", + "settings:autoApprove.resubmit.label": "Resubmit", + "settings:autoApprove.followupQuestions.label": "Follow-up questions", + "settings:autoApprove.updateTodoList.label": "Update todo list", + "settings:autoApprove.apiRequestLimit.title": "API request limit", + "settings:autoApprove.apiRequestLimit.unlimited": "Unlimited", + "settings:autoApprove.apiRequestLimit.description": "Limit the number of API requests", + "settings:autoApprove.readOnly.outsideWorkspace": "Also allow outside workspace", + "settings:autoApprove.write.outsideWorkspace": "Also allow outside workspace", + "settings:autoApprove.write.delay": "Delay", + } + return translations[key] || key + }, + }), +})) + +// Get the mocked postMessage function +const mockPostMessage = vscode.postMessage as ReturnType + +describe("AutoApproveMenu", () => { + const defaultExtensionState = { + autoApprovalEnabled: true, + alwaysAllowReadOnly: false, + alwaysAllowReadOnlyOutsideWorkspace: false, + alwaysAllowWrite: false, + alwaysAllowWriteOutsideWorkspace: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowMcp: false, + alwaysAllowModeSwitch: false, + alwaysAllowSubtasks: false, + alwaysApproveResubmit: false, + alwaysAllowFollowupQuestions: false, + alwaysAllowUpdateTodoList: false, + writeDelayMs: 3000, + allowedMaxRequests: undefined, + setAutoApprovalEnabled: vi.fn(), + setAlwaysAllowReadOnly: vi.fn(), + setAlwaysAllowWrite: vi.fn(), + setAlwaysAllowExecute: vi.fn(), + setAlwaysAllowBrowser: vi.fn(), + setAlwaysAllowMcp: vi.fn(), + setAlwaysAllowModeSwitch: vi.fn(), + setAlwaysAllowSubtasks: vi.fn(), + setAlwaysApproveResubmit: vi.fn(), + setAlwaysAllowFollowupQuestions: vi.fn(), + setAlwaysAllowUpdateTodoList: vi.fn(), + setAllowedMaxRequests: vi.fn(), + } + + beforeEach(() => { + vi.clearAllMocks() + ;(useExtensionState as ReturnType).mockReturnValue(defaultExtensionState) + }) + + describe("Master checkbox behavior", () => { + it("should show 'None selected' when no sub-options are selected", () => { + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + autoApprovalEnabled: false, + alwaysAllowReadOnly: false, + alwaysAllowWrite: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowModeSwitch: false, + }) + + render() + + // Check that the text shows "None selected" + expect(screen.getByText("None selected")).toBeInTheDocument() + }) + + it("should show enabled options when sub-options are selected", () => { + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, + alwaysAllowWrite: false, + }) + + render() + + // Check that the text shows the enabled option + expect(screen.getByText("Read-only operations")).toBeInTheDocument() + }) + + it("should not allow toggling master checkbox when no options are selected", () => { + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + autoApprovalEnabled: false, + alwaysAllowReadOnly: false, + }) + + render() + + // Click on the master checkbox + const masterCheckbox = screen.getByRole("checkbox") + fireEvent.click(masterCheckbox) + + // Should not send any message since no options are selected + expect(mockPostMessage).not.toHaveBeenCalled() + }) + + it("should toggle master checkbox when options are selected", () => { + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, + }) + + render() + + // Click on the master checkbox + const masterCheckbox = screen.getByRole("checkbox") + fireEvent.click(masterCheckbox) + + // Should toggle the master checkbox + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "autoApprovalEnabled", + bool: false, + }) + }) + }) + + describe("Sub-option toggles", () => { + it("should toggle read-only operations", async () => { + const mockSetAlwaysAllowReadOnly = vi.fn() + + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + setAlwaysAllowReadOnly: mockSetAlwaysAllowReadOnly, + }) + + render() + + // Expand the menu + const menuContainer = screen.getByText("Auto-approve").parentElement + fireEvent.click(menuContainer!) + + // Wait for the menu to expand and find the read-only button + await waitFor(() => { + expect(screen.getByTestId("always-allow-readonly-toggle")).toBeInTheDocument() + }) + + const readOnlyButton = screen.getByTestId("always-allow-readonly-toggle") + fireEvent.click(readOnlyButton) + + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "alwaysAllowReadOnly", + bool: true, + }) + }) + + it("should toggle write operations", async () => { + const mockSetAlwaysAllowWrite = vi.fn() + + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + setAlwaysAllowWrite: mockSetAlwaysAllowWrite, + }) + + render() + + // Expand the menu + const menuContainer = screen.getByText("Auto-approve").parentElement + fireEvent.click(menuContainer!) + + await waitFor(() => { + expect(screen.getByTestId("always-allow-write-toggle")).toBeInTheDocument() + }) + + const writeButton = screen.getByTestId("always-allow-write-toggle") + fireEvent.click(writeButton) + + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "alwaysAllowWrite", + bool: true, + }) + }) + }) + + describe("Complex scenarios", () => { + it("should display multiple enabled options in summary text", () => { + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, + alwaysAllowWrite: true, + alwaysAllowExecute: true, + }) + + render() + + // Should show all enabled options in the summary + expect(screen.getByText("Read-only operations, Write operations, Execute operations")).toBeInTheDocument() + }) + + it("should handle enabling first option when none selected", async () => { + const mockSetAutoApprovalEnabled = vi.fn() + const mockSetAlwaysAllowReadOnly = vi.fn() + + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + autoApprovalEnabled: false, + alwaysAllowReadOnly: false, + setAutoApprovalEnabled: mockSetAutoApprovalEnabled, + setAlwaysAllowReadOnly: mockSetAlwaysAllowReadOnly, + }) + + render() + + // Expand the menu + const menuContainer = screen.getByText("Auto-approve").parentElement + fireEvent.click(menuContainer!) + + await waitFor(() => { + expect(screen.getByTestId("always-allow-readonly-toggle")).toBeInTheDocument() + }) + + // Enable read-only + const readOnlyButton = screen.getByTestId("always-allow-readonly-toggle") + fireEvent.click(readOnlyButton) + + // Should enable the sub-option + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "alwaysAllowReadOnly", + bool: true, + }) + + // Should also enable master auto-approval + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "autoApprovalEnabled", + bool: true, + }) + }) + + it("should handle disabling last option", async () => { + const mockSetAutoApprovalEnabled = vi.fn() + const mockSetAlwaysAllowReadOnly = vi.fn() + + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, + setAutoApprovalEnabled: mockSetAutoApprovalEnabled, + setAlwaysAllowReadOnly: mockSetAlwaysAllowReadOnly, + }) + + render() + + // Expand the menu + const menuContainer = screen.getByText("Auto-approve").parentElement + fireEvent.click(menuContainer!) + + await waitFor(() => { + expect(screen.getByTestId("always-allow-readonly-toggle")).toBeInTheDocument() + }) + + // Disable read-only (the last enabled option) + const readOnlyButton = screen.getByTestId("always-allow-readonly-toggle") + fireEvent.click(readOnlyButton) + + // Should disable the sub-option + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "alwaysAllowReadOnly", + bool: false, + }) + + // Should also disable master auto-approval + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "autoApprovalEnabled", + bool: false, + }) + }) + }) +}) diff --git a/webview-ui/src/components/chat/__tests__/ChatView.auto-approve-new.spec.tsx b/webview-ui/src/components/chat/__tests__/ChatView.auto-approve-new.spec.tsx new file mode 100644 index 0000000000..b00e3f592e --- /dev/null +++ b/webview-ui/src/components/chat/__tests__/ChatView.auto-approve-new.spec.tsx @@ -0,0 +1,480 @@ +// npx vitest run src/components/chat/__tests__/ChatView.auto-approve-new.spec.tsx + +import { render, waitFor } from "@/utils/test-utils" +import { QueryClient, QueryClientProvider } from "@tanstack/react-query" + +import { ExtensionStateContextProvider } from "@src/context/ExtensionStateContext" +import { vscode } from "@src/utils/vscode" + +import ChatView, { ChatViewProps } from "../ChatView" + +// Mock vscode API +vi.mock("@src/utils/vscode", () => ({ + vscode: { + postMessage: vi.fn(), + }, +})) + +// Mock all problematic dependencies +vi.mock("rehype-highlight", () => ({ + default: () => () => {}, +})) + +vi.mock("hast-util-to-text", () => ({ + default: () => "", +})) + +// Mock components that use ESM dependencies +vi.mock("../BrowserSessionRow", () => ({ + default: function MockBrowserSessionRow({ messages }: { messages: any[] }) { + return
{JSON.stringify(messages)}
+ }, +})) + +vi.mock("../ChatRow", () => ({ + default: function MockChatRow({ message }: { message: any }) { + return
{JSON.stringify(message)}
+ }, +})) + +vi.mock("../TaskHeader", () => ({ + default: function MockTaskHeader({ task }: { task: any }) { + return
{JSON.stringify(task)}
+ }, +})) + +vi.mock("../AutoApproveMenu", () => ({ + default: () => null, +})) + +vi.mock("@src/components/common/CodeBlock", () => ({ + default: () => null, + CODE_BLOCK_BG_COLOR: "rgb(30, 30, 30)", +})) + +vi.mock("@src/components/common/CodeAccordion", () => ({ + default: () => null, +})) + +vi.mock("@src/components/chat/ContextMenu", () => ({ + default: () => null, +})) + +// Mock window.postMessage to trigger state hydration +const mockPostMessage = (state: any) => { + window.postMessage( + { + type: "state", + state: { + version: "1.0.0", + clineMessages: [], + taskHistory: [], + shouldShowAnnouncement: false, + allowedCommands: [], + alwaysAllowExecute: false, + autoApprovalEnabled: true, + ...state, + }, + }, + "*", + ) +} + +const queryClient = new QueryClient() + +const defaultProps: ChatViewProps = { + isHidden: false, + showAnnouncement: false, + hideAnnouncement: () => {}, +} + +const renderChatView = (props: Partial = {}) => { + return render( + + + + + , + ) +} + +describe("ChatView - New Auto Approval Logic Tests", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + describe("Master auto-approval with no sub-options enabled", () => { + it("should NOT auto-approve when autoApprovalEnabled is true but no sub-options are enabled", async () => { + renderChatView() + + // First hydrate state with initial task + mockPostMessage({ + autoApprovalEnabled: true, // Master is enabled + alwaysAllowReadOnly: false, // But no sub-options are enabled + alwaysAllowWrite: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowModeSwitch: false, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + ], + }) + + // Then send a read tool ask message + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: false, + alwaysAllowWrite: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowModeSwitch: false, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + { + type: "ask", + ask: "tool", + ts: Date.now(), + text: JSON.stringify({ tool: "readFile", path: "test.txt" }), + partial: false, + }, + ], + }) + + // Wait and verify no auto-approval message was sent + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(vscode.postMessage).not.toHaveBeenCalledWith({ + type: "askResponse", + askResponse: "yesButtonClicked", + }) + }) + + it("should NOT auto-approve write operations when only master is enabled", async () => { + renderChatView() + + // First hydrate state with initial task + mockPostMessage({ + autoApprovalEnabled: true, // Master is enabled + alwaysAllowReadOnly: false, + alwaysAllowWrite: false, // Write is not enabled + writeDelayMs: 0, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + ], + }) + + // Then send a write tool ask message + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: false, + alwaysAllowWrite: false, + writeDelayMs: 0, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + { + type: "ask", + ask: "tool", + ts: Date.now(), + text: JSON.stringify({ tool: "editedExistingFile", path: "test.txt" }), + partial: false, + }, + ], + }) + + // Wait and verify no auto-approval message was sent + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(vscode.postMessage).not.toHaveBeenCalledWith({ + type: "askResponse", + askResponse: "yesButtonClicked", + }) + }) + + it("should NOT auto-approve browser actions when only master is enabled", async () => { + renderChatView() + + // First hydrate state with initial task + mockPostMessage({ + autoApprovalEnabled: true, // Master is enabled + alwaysAllowBrowser: false, // Browser is not enabled + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + ], + }) + + // Then send a browser action ask message + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowBrowser: false, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + { + type: "ask", + ask: "browser_action_launch", + ts: Date.now(), + text: JSON.stringify({ action: "launch", url: "http://example.com" }), + partial: false, + }, + ], + }) + + // Wait and verify no auto-approval message was sent + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(vscode.postMessage).not.toHaveBeenCalledWith({ + type: "askResponse", + askResponse: "yesButtonClicked", + }) + }) + }) + + describe("Correct auto-approval with sub-options enabled", () => { + it("should auto-approve when master and at least one sub-option are enabled", async () => { + renderChatView() + + // First hydrate state with initial task + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, // At least one sub-option is enabled + alwaysAllowWrite: false, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + ], + }) + + // Then send a read tool ask message + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, + alwaysAllowWrite: false, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + { + type: "ask", + ask: "tool", + ts: Date.now(), + text: JSON.stringify({ tool: "readFile", path: "test.txt" }), + partial: false, + }, + ], + }) + + // Wait for the auto-approval message + await waitFor(() => { + expect(vscode.postMessage).toHaveBeenCalledWith({ + type: "askResponse", + askResponse: "yesButtonClicked", + }) + }) + }) + + it("should auto-approve when multiple sub-options are enabled", async () => { + renderChatView() + + // First hydrate state with initial task + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, // Multiple sub-options enabled + alwaysAllowWrite: true, + alwaysAllowExecute: true, + writeDelayMs: 0, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + ], + }) + + // Then send a write tool ask message + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, + alwaysAllowWrite: true, + alwaysAllowExecute: true, + writeDelayMs: 0, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + { + type: "ask", + ask: "tool", + ts: Date.now(), + text: JSON.stringify({ tool: "editedExistingFile", path: "test.txt" }), + partial: false, + }, + ], + }) + + // Wait for the auto-approval message + await waitFor(() => { + expect(vscode.postMessage).toHaveBeenCalledWith({ + type: "askResponse", + askResponse: "yesButtonClicked", + }) + }) + }) + }) + + describe("Edge cases", () => { + it("should handle state transitions correctly", async () => { + renderChatView() + + // Start with auto-approval properly configured + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: true, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + ], + }) + + // Then transition to a state where no sub-options are enabled + mockPostMessage({ + autoApprovalEnabled: true, // Master still true + alwaysAllowReadOnly: false, // All sub-options now false + alwaysAllowWrite: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowModeSwitch: false, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + { + type: "ask", + ask: "tool", + ts: Date.now(), + text: JSON.stringify({ tool: "readFile", path: "test.txt" }), + partial: false, + }, + ], + }) + + // Wait and verify no auto-approval message was sent + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(vscode.postMessage).not.toHaveBeenCalledWith({ + type: "askResponse", + askResponse: "yesButtonClicked", + }) + }) + + it("should respect the hasEnabledOptions check in isAutoApproved", async () => { + renderChatView() + + // Configure state where master is true but effective approval should be false + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: false, + alwaysAllowReadOnlyOutsideWorkspace: false, + alwaysAllowWrite: false, + alwaysAllowWriteOutsideWorkspace: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowModeSwitch: false, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + ], + }) + + // Try various tool types - none should auto-approve + const toolRequests = [ + { tool: "readFile", path: "test.txt" }, + { tool: "editedExistingFile", path: "test.txt" }, + { tool: "executeCommand", command: "ls" }, + { tool: "switchMode", mode: "architect" }, + ] + + for (const toolRequest of toolRequests) { + vi.clearAllMocks() + + mockPostMessage({ + autoApprovalEnabled: true, + alwaysAllowReadOnly: false, + alwaysAllowWrite: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowModeSwitch: false, + clineMessages: [ + { + type: "say", + say: "task", + ts: Date.now() - 2000, + text: "Initial task", + }, + { + type: "ask", + ask: "tool", + ts: Date.now(), + text: JSON.stringify(toolRequest), + partial: false, + }, + ], + }) + + // Wait and verify no auto-approval for any tool type + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(vscode.postMessage).not.toHaveBeenCalledWith({ + type: "askResponse", + askResponse: "yesButtonClicked", + }) + } + }) + }) +}) diff --git a/webview-ui/src/components/settings/AutoApproveSettings.tsx b/webview-ui/src/components/settings/AutoApproveSettings.tsx index fe8a359832..e1d3c52cb9 100644 --- a/webview-ui/src/components/settings/AutoApproveSettings.tsx +++ b/webview-ui/src/components/settings/AutoApproveSettings.tsx @@ -4,12 +4,15 @@ import { X } from "lucide-react" import { useAppTranslation } from "@/i18n/TranslationContext" import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" import { vscode } from "@/utils/vscode" -import { Button, Input, Slider } from "@/components/ui" +import { Button, Input, Slider, StandardTooltip } from "@/components/ui" import { SetCachedStateField } from "./types" import { SectionHeader } from "./SectionHeader" import { Section } from "./Section" import { AutoApproveToggle } from "./AutoApproveToggle" +import { useExtensionState } from "@/context/ExtensionStateContext" +import { useAutoApprovalState } from "@/hooks/useAutoApprovalState" +import { useAutoApprovalToggles } from "@/hooks/useAutoApprovalToggles" type AutoApproveSettingsProps = HTMLAttributes & { alwaysAllowReadOnly?: boolean @@ -77,6 +80,11 @@ export const AutoApproveSettings = ({ const { t } = useAppTranslation() const [commandInput, setCommandInput] = useState("") const [deniedCommandInput, setDeniedCommandInput] = useState("") + const { autoApprovalEnabled, setAutoApprovalEnabled } = useExtensionState() + + const toggles = useAutoApprovalToggles() + + const { hasEnabledOptions, effectiveAutoApprovalEnabled } = useAutoApprovalState(toggles, autoApprovalEnabled) const handleAddCommand = () => { const currentCommands = allowedCommands ?? [] @@ -104,6 +112,30 @@ export const AutoApproveSettings = ({
+ {!hasEnabledOptions ? ( + + { + // Do nothing when no options are enabled + return + }} + /> + + ) : ( + { + const newValue = !(autoApprovalEnabled ?? false) + setAutoApprovalEnabled(newValue) + vscode.postMessage({ type: "autoApprovalEnabled", bool: newValue }) + }} + /> + )}
{t("settings:sections.autoApprove")}
diff --git a/webview-ui/src/hooks/__tests__/useAutoApprovalState.spec.ts b/webview-ui/src/hooks/__tests__/useAutoApprovalState.spec.ts new file mode 100644 index 0000000000..a0c2d65f84 --- /dev/null +++ b/webview-ui/src/hooks/__tests__/useAutoApprovalState.spec.ts @@ -0,0 +1,282 @@ +import { renderHook } from "@testing-library/react" +import { useAutoApprovalState } from "../useAutoApprovalState" + +describe("useAutoApprovalState", () => { + describe("hasEnabledOptions", () => { + it("should return false when all toggles are false", () => { + const toggles = { + alwaysAllowReadOnly: false, + alwaysAllowWrite: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowMcp: false, + alwaysAllowModeSwitch: false, + alwaysAllowSubtasks: false, + alwaysApproveResubmit: false, + alwaysAllowFollowupQuestions: false, + alwaysAllowUpdateTodoList: false, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.hasEnabledOptions).toBe(false) + }) + + it("should return false when all toggles are undefined", () => { + const toggles = { + alwaysAllowReadOnly: undefined, + alwaysAllowWrite: undefined, + alwaysAllowExecute: undefined, + alwaysAllowBrowser: undefined, + alwaysAllowMcp: undefined, + alwaysAllowModeSwitch: undefined, + alwaysAllowSubtasks: undefined, + alwaysApproveResubmit: undefined, + alwaysAllowFollowupQuestions: undefined, + alwaysAllowUpdateTodoList: undefined, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.hasEnabledOptions).toBe(false) + }) + + it("should return true when at least one toggle is true", () => { + const toggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowMcp: false, + alwaysAllowModeSwitch: false, + alwaysAllowSubtasks: false, + alwaysApproveResubmit: false, + alwaysAllowFollowupQuestions: false, + alwaysAllowUpdateTodoList: false, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.hasEnabledOptions).toBe(true) + }) + + it("should return true when multiple toggles are true", () => { + const toggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: true, + alwaysAllowExecute: true, + alwaysAllowBrowser: false, + alwaysAllowMcp: false, + alwaysAllowModeSwitch: false, + alwaysAllowSubtasks: false, + alwaysApproveResubmit: false, + alwaysAllowFollowupQuestions: false, + alwaysAllowUpdateTodoList: false, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.hasEnabledOptions).toBe(true) + }) + + it("should return true when all toggles are true", () => { + const toggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: true, + alwaysAllowExecute: true, + alwaysAllowBrowser: true, + alwaysAllowMcp: true, + alwaysAllowModeSwitch: true, + alwaysAllowSubtasks: true, + alwaysApproveResubmit: true, + alwaysAllowFollowupQuestions: true, + alwaysAllowUpdateTodoList: true, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.hasEnabledOptions).toBe(true) + }) + }) + + describe("effectiveAutoApprovalEnabled", () => { + it("should return false when autoApprovalEnabled is false regardless of toggles", () => { + const toggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: true, + alwaysAllowExecute: true, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, false)) + + expect(result.current.effectiveAutoApprovalEnabled).toBe(false) + }) + + it("should return false when autoApprovalEnabled is undefined regardless of toggles", () => { + const toggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: true, + alwaysAllowExecute: true, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, undefined)) + + expect(result.current.effectiveAutoApprovalEnabled).toBe(false) + }) + + it("should return false when autoApprovalEnabled is true but no toggles are enabled", () => { + const toggles = { + alwaysAllowReadOnly: false, + alwaysAllowWrite: false, + alwaysAllowExecute: false, + alwaysAllowBrowser: false, + alwaysAllowMcp: false, + alwaysAllowModeSwitch: false, + alwaysAllowSubtasks: false, + alwaysApproveResubmit: false, + alwaysAllowFollowupQuestions: false, + alwaysAllowUpdateTodoList: false, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.effectiveAutoApprovalEnabled).toBe(false) + }) + + it("should return true when autoApprovalEnabled is true and at least one toggle is enabled", () => { + const toggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: false, + alwaysAllowExecute: false, + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.effectiveAutoApprovalEnabled).toBe(true) + }) + }) + + describe("memoization", () => { + it("should not recompute hasEnabledOptions when toggles object reference changes but values are the same", () => { + const initialToggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: false, + } + + const { result, rerender } = renderHook( + ({ toggles, autoApprovalEnabled }) => useAutoApprovalState(toggles, autoApprovalEnabled), + { + initialProps: { + toggles: initialToggles, + autoApprovalEnabled: true, + }, + }, + ) + + const firstHasEnabledOptions = result.current.hasEnabledOptions + const firstEffectiveAutoApprovalEnabled = result.current.effectiveAutoApprovalEnabled + + // Create new object with same values + const newToggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: false, + } + + rerender({ toggles: newToggles, autoApprovalEnabled: true }) + + // The computed values should be the same due to memoization + expect(result.current.hasEnabledOptions).toBe(firstHasEnabledOptions) + expect(result.current.effectiveAutoApprovalEnabled).toBe(firstEffectiveAutoApprovalEnabled) + }) + + it("should recompute when toggle values change", () => { + const initialToggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: false, + } + + const { result, rerender } = renderHook( + ({ toggles, autoApprovalEnabled }) => useAutoApprovalState(toggles, autoApprovalEnabled), + { + initialProps: { + toggles: initialToggles, + autoApprovalEnabled: true, + }, + }, + ) + + expect(result.current.hasEnabledOptions).toBe(true) + expect(result.current.effectiveAutoApprovalEnabled).toBe(true) + + // Change toggle values + const newToggles = { + alwaysAllowReadOnly: false, + alwaysAllowWrite: false, + } + + rerender({ toggles: newToggles, autoApprovalEnabled: true }) + + expect(result.current.hasEnabledOptions).toBe(false) + expect(result.current.effectiveAutoApprovalEnabled).toBe(false) + }) + + it("should recompute effectiveAutoApprovalEnabled when autoApprovalEnabled changes", () => { + const toggles = { + alwaysAllowReadOnly: true, + alwaysAllowWrite: false, + } + + const { result, rerender } = renderHook( + ({ toggles, autoApprovalEnabled }) => useAutoApprovalState(toggles, autoApprovalEnabled), + { + initialProps: { + toggles, + autoApprovalEnabled: true, + }, + }, + ) + + expect(result.current.effectiveAutoApprovalEnabled).toBe(true) + + rerender({ toggles, autoApprovalEnabled: false }) + + expect(result.current.effectiveAutoApprovalEnabled).toBe(false) + }) + }) + + describe("edge cases", () => { + it("should handle partial toggle objects", () => { + const toggles = { + alwaysAllowReadOnly: true, + // Other properties are optional + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.hasEnabledOptions).toBe(true) + expect(result.current.effectiveAutoApprovalEnabled).toBe(true) + }) + + it("should handle empty toggle object", () => { + const toggles = {} + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.hasEnabledOptions).toBe(false) + expect(result.current.effectiveAutoApprovalEnabled).toBe(false) + }) + + it("should handle mixed truthy/falsy values correctly", () => { + const toggles = { + alwaysAllowReadOnly: 1 as any, // truthy non-boolean + alwaysAllowWrite: "" as any, // falsy non-boolean + alwaysAllowExecute: null as any, // falsy non-boolean + alwaysAllowBrowser: "yes" as any, // truthy non-boolean + } + + const { result } = renderHook(() => useAutoApprovalState(toggles, true)) + + expect(result.current.hasEnabledOptions).toBe(true) // Because some values are truthy + }) + }) +}) diff --git a/webview-ui/src/hooks/useAutoApprovalState.ts b/webview-ui/src/hooks/useAutoApprovalState.ts new file mode 100644 index 0000000000..74a165c09b --- /dev/null +++ b/webview-ui/src/hooks/useAutoApprovalState.ts @@ -0,0 +1,29 @@ +import { useMemo } from "react" + +interface AutoApprovalToggles { + alwaysAllowReadOnly?: boolean + alwaysAllowWrite?: boolean + alwaysAllowExecute?: boolean + alwaysAllowBrowser?: boolean + alwaysAllowMcp?: boolean + alwaysAllowModeSwitch?: boolean + alwaysAllowSubtasks?: boolean + alwaysApproveResubmit?: boolean + alwaysAllowFollowupQuestions?: boolean + alwaysAllowUpdateTodoList?: boolean +} + +export function useAutoApprovalState(toggles: AutoApprovalToggles, autoApprovalEnabled?: boolean) { + const hasEnabledOptions = useMemo(() => { + return Object.values(toggles).some((value) => !!value) + }, [toggles]) + + const effectiveAutoApprovalEnabled = useMemo(() => { + return hasEnabledOptions && (autoApprovalEnabled ?? false) + }, [hasEnabledOptions, autoApprovalEnabled]) + + return { + hasEnabledOptions, + effectiveAutoApprovalEnabled, + } +} diff --git a/webview-ui/src/hooks/useAutoApprovalToggles.ts b/webview-ui/src/hooks/useAutoApprovalToggles.ts new file mode 100644 index 0000000000..9fe0858c93 --- /dev/null +++ b/webview-ui/src/hooks/useAutoApprovalToggles.ts @@ -0,0 +1,50 @@ +import { useMemo } from "react" +import { useExtensionState } from "@src/context/ExtensionStateContext" + +/** + * Custom hook that creates and returns the auto-approval toggles object + * This encapsulates the logic for creating the toggles object from extension state + */ +export function useAutoApprovalToggles() { + const { + alwaysAllowReadOnly, + alwaysAllowWrite, + alwaysAllowExecute, + alwaysAllowBrowser, + alwaysAllowMcp, + alwaysAllowModeSwitch, + alwaysAllowSubtasks, + alwaysApproveResubmit, + alwaysAllowFollowupQuestions, + alwaysAllowUpdateTodoList, + } = useExtensionState() + + const toggles = useMemo( + () => ({ + alwaysAllowReadOnly, + alwaysAllowWrite, + alwaysAllowExecute, + alwaysAllowBrowser, + alwaysAllowMcp, + alwaysAllowModeSwitch, + alwaysAllowSubtasks, + alwaysApproveResubmit, + alwaysAllowFollowupQuestions, + alwaysAllowUpdateTodoList, + }), + [ + alwaysAllowReadOnly, + alwaysAllowWrite, + alwaysAllowExecute, + alwaysAllowBrowser, + alwaysAllowMcp, + alwaysAllowModeSwitch, + alwaysAllowSubtasks, + alwaysApproveResubmit, + alwaysAllowFollowupQuestions, + alwaysAllowUpdateTodoList, + ], + ) + + return toggles +} diff --git a/webview-ui/src/i18n/locales/ca/chat.json b/webview-ui/src/i18n/locales/ca/chat.json index bcc41d2052..4c24d69f08 100644 --- a/webview-ui/src/i18n/locales/ca/chat.json +++ b/webview-ui/src/i18n/locales/ca/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Aprovació automàtica:", "none": "Cap", - "description": "L'aprovació automàtica permet a Roo Code realitzar accions sense demanar permís. Activa-la només per a accions en les que confies plenament. Configuració més detallada disponible a la Configuració." + "description": "L'aprovació automàtica permet a Roo Code realitzar accions sense demanar permís. Activa-la només per a accions en les que confies plenament. Configuració més detallada disponible a la Configuració.", + "selectOptionsFirst": "Selecciona almenys una opció a continuació per activar l'aprovació automàtica", + "toggleAriaLabel": "Commuta l'aprovació automàtica", + "disabledAriaLabel": "Aprovació automàtica desactivada: seleccioneu primer les opcions" }, "reasoning": { "thinking": "Pensant", diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index 207fc88fd9..15018e64ab 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Permet que Roo realitzi operacions automàticament sense requerir aprovació. Activeu aquesta configuració només si confieu plenament en la IA i enteneu els riscos de seguretat associats.", + "toggleAriaLabel": "Commuta l'aprovació automàtica", + "disabledAriaLabel": "Aprovació automàtica desactivada: seleccioneu primer les opcions", "readOnly": { "label": "Llegir", "description": "Quan està activat, Roo veurà automàticament el contingut del directori i llegirà fitxers sense que calgui fer clic al botó Aprovar.", @@ -190,7 +192,8 @@ "title": "Màximes Sol·licituds", "description": "Fes aquesta quantitat de sol·licituds API automàticament abans de demanar aprovació per continuar amb la tasca.", "unlimited": "Il·limitat" - } + }, + "selectOptionsFirst": "Seleccioneu almenys una opció a continuació per activar l'aprovació automàtica" }, "providers": { "providerDocumentation": "Documentació de {{provider}}", diff --git a/webview-ui/src/i18n/locales/de/chat.json b/webview-ui/src/i18n/locales/de/chat.json index 2c85048bf0..8f09fab831 100644 --- a/webview-ui/src/i18n/locales/de/chat.json +++ b/webview-ui/src/i18n/locales/de/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Automatische Genehmigung:", "none": "Keine", - "description": "Automatische Genehmigung erlaubt Roo Code, Aktionen ohne Nachfrage auszuführen. Aktiviere dies nur für Aktionen, denen du vollständig vertraust. Detailliertere Konfiguration verfügbar in den Einstellungen." + "description": "Automatische Genehmigung erlaubt Roo Code, Aktionen ohne Nachfrage auszuführen. Aktiviere dies nur für Aktionen, denen du vollständig vertraust. Detailliertere Konfiguration verfügbar in den Einstellungen.", + "selectOptionsFirst": "Wähle mindestens eine der folgenden Optionen aus, um die automatische Genehmigung zu aktivieren", + "toggleAriaLabel": "Automatische Genehmigung umschalten", + "disabledAriaLabel": "Automatische Genehmigung deaktiviert - zuerst Optionen auswählen" }, "reasoning": { "thinking": "Denke nach", diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index 68e9f8f97d..bb5ed1146b 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Erlaubt Roo, Operationen automatisch ohne Genehmigung durchzuführen. Aktiviere diese Einstellungen nur, wenn du der KI vollständig vertraust und die damit verbundenen Sicherheitsrisiken verstehst.", + "toggleAriaLabel": "Automatische Genehmigung umschalten", + "disabledAriaLabel": "Automatische Genehmigung deaktiviert - zuerst Optionen auswählen", "readOnly": { "label": "Lesen", "description": "Wenn aktiviert, wird Roo automatisch Verzeichnisinhalte anzeigen und Dateien lesen, ohne dass du auf die Genehmigen-Schaltfläche klicken musst.", @@ -190,7 +192,8 @@ "title": "Maximale Anfragen", "description": "Automatisch so viele API-Anfragen stellen, bevor du um die Erlaubnis gebeten wirst, mit der Aufgabe fortzufahren.", "unlimited": "Unbegrenzt" - } + }, + "selectOptionsFirst": "Wähle mindestens eine Option unten aus, um die automatische Genehmigung zu aktivieren" }, "providers": { "providerDocumentation": "{{provider}}-Dokumentation", diff --git a/webview-ui/src/i18n/locales/en/chat.json b/webview-ui/src/i18n/locales/en/chat.json index a5c8bd8337..53e529d4e4 100644 --- a/webview-ui/src/i18n/locales/en/chat.json +++ b/webview-ui/src/i18n/locales/en/chat.json @@ -244,7 +244,10 @@ "autoApprove": { "title": "Auto-approve:", "none": "None", - "description": "Auto-approve allows Roo Code to perform actions without asking for permission. Only enable for actions you fully trust. More detailed configuration available in Settings." + "description": "Auto-approve allows Roo Code to perform actions without asking for permission. Only enable for actions you fully trust. More detailed configuration available in Settings.", + "selectOptionsFirst": "Select at least one option below to enable auto-approval", + "toggleAriaLabel": "Toggle auto-approval", + "disabledAriaLabel": "Auto-approval disabled - select options first" }, "announcement": { "title": "🎉 Roo Code {{version}} Released", diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index fa1fbab13c..728e856502 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -190,7 +190,10 @@ "title": "Max Requests", "description": "Automatically make this many API requests before asking for approval to continue with the task.", "unlimited": "Unlimited" - } + }, + "toggleAriaLabel": "Toggle auto-approval", + "disabledAriaLabel": "Auto-approval disabled - select options first", + "selectOptionsFirst": "Select at least one option below to enable auto-approval" }, "providers": { "providerDocumentation": "{{provider}} documentation", diff --git a/webview-ui/src/i18n/locales/es/chat.json b/webview-ui/src/i18n/locales/es/chat.json index 711fe7712b..bb84baa555 100644 --- a/webview-ui/src/i18n/locales/es/chat.json +++ b/webview-ui/src/i18n/locales/es/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Auto-aprobar:", "none": "Ninguno", - "description": "Auto-aprobar permite a Roo Code realizar acciones sin pedir permiso. Habilita solo para acciones en las que confíes plenamente. Configuración más detallada disponible en Configuración." + "description": "Auto-aprobar permite a Roo Code realizar acciones sin pedir permiso. Habilita solo para acciones en las que confíes plenamente. Configuración más detallada disponible en Configuración.", + "selectOptionsFirst": "Selecciona al menos una opción a continuación para habilitar la aprobación automática", + "toggleAriaLabel": "Alternar aprobación automática", + "disabledAriaLabel": "Aprobación automática desactivada: seleccione primero las opciones" }, "reasoning": { "thinking": "Pensando", diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index 80de7042b0..5836933b46 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Permitir que Roo realice operaciones automáticamente sin requerir aprobación. Habilite esta configuración solo si confía plenamente en la IA y comprende los riesgos de seguridad asociados.", + "toggleAriaLabel": "Alternar aprobación automática", + "disabledAriaLabel": "Aprobación automática desactivada: seleccione primero las opciones", "readOnly": { "label": "Lectura", "description": "Cuando está habilitado, Roo verá automáticamente el contenido del directorio y leerá archivos sin que necesite hacer clic en el botón Aprobar.", @@ -190,7 +192,8 @@ "title": "Solicitudes máximas", "description": "Realizar automáticamente esta cantidad de solicitudes a la API antes de pedir aprobación para continuar con la tarea.", "unlimited": "Ilimitado" - } + }, + "selectOptionsFirst": "Selecciona al menos una opción a continuación para habilitar la aprobación automática" }, "providers": { "providerDocumentation": "Documentación de {{provider}}", diff --git a/webview-ui/src/i18n/locales/fr/chat.json b/webview-ui/src/i18n/locales/fr/chat.json index f3832174e6..70bd6011dd 100644 --- a/webview-ui/src/i18n/locales/fr/chat.json +++ b/webview-ui/src/i18n/locales/fr/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Auto-approbation :", "none": "Aucune", - "description": "L'auto-approbation permet à Roo Code d'effectuer des actions sans demander d'autorisation. Activez-la uniquement pour les actions auxquelles vous faites entièrement confiance. Configuration plus détaillée disponible dans les Paramètres." + "description": "L'auto-approbation permet à Roo Code d'effectuer des actions sans demander d'autorisation. Activez-la uniquement pour les actions auxquelles vous faites entièrement confiance. Configuration plus détaillée disponible dans les Paramètres.", + "selectOptionsFirst": "Sélectionnez au moins une option ci-dessous pour activer l'auto-approbation", + "toggleAriaLabel": "Activer/désactiver l'approbation automatique", + "disabledAriaLabel": "Approbation automatique désactivée - sélectionnez d'abord les options" }, "reasoning": { "thinking": "Réflexion", diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index e10b3ae35f..833a789e5a 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -123,6 +123,9 @@ }, "autoApprove": { "description": "Permettre à Roo d'effectuer automatiquement des opérations sans requérir d'approbation. Activez ces paramètres uniquement si vous faites entièrement confiance à l'IA et que vous comprenez les risques de sécurité associés.", + "toggleAriaLabel": "Activer/désactiver l'approbation automatique", + "disabledAriaLabel": "Approbation automatique désactivée - sélectionnez d'abord les options", + "selectOptionsFirst": "Sélectionnez au moins une option ci-dessous pour activer l'approbation automatique", "readOnly": { "label": "Lecture", "description": "Lorsque cette option est activée, Roo affichera automatiquement le contenu des répertoires et lira les fichiers sans que vous ayez à cliquer sur le bouton Approuver.", diff --git a/webview-ui/src/i18n/locales/hi/chat.json b/webview-ui/src/i18n/locales/hi/chat.json index 34e80597a8..0fa95c2708 100644 --- a/webview-ui/src/i18n/locales/hi/chat.json +++ b/webview-ui/src/i18n/locales/hi/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "स्वत:-स्वीकृति:", "none": "कोई नहीं", - "description": "स्वत:-स्वीकृति Roo Code को अनुमति मांगे बिना क्रियाएँ करने की अनुमति देती है। केवल उन क्रियाओं के लिए सक्षम करें जिन पर आप पूरी तरह से विश्वास करते हैं। अधिक विस्तृत कॉन्फ़िगरेशन सेटिंग्स में उपलब्ध है।" + "description": "स्वत:-स्वीकृति Roo Code को अनुमति मांगे बिना क्रियाएँ करने की अनुमति देती है। केवल उन क्रियाओं के लिए सक्षम करें जिन पर आप पूरी तरह से विश्वास करते हैं। अधिक विस्तृत कॉन्फ़िगरेशन सेटिंग्स में उपलब्ध है।", + "selectOptionsFirst": "स्वतः-अनुमोदन सक्षम करने के लिए नीचे दिए گئے विकल्पों में से कम से कम एक का चयन करें", + "toggleAriaLabel": "स्वतः-अनुमोदन टॉगल करें", + "disabledAriaLabel": "स्वतः-अनुमोदन अक्षम - पहले विकल्प चुनें" }, "reasoning": { "thinking": "विचार कर रहा है", diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index 5b64359f8f..0749943508 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Roo को अनुमोदन की आवश्यकता के बिना स्वचालित रूप से ऑपरेशन करने की अनुमति दें। इन सेटिंग्स को केवल तभी सक्षम करें जब आप AI पर पूरी तरह से भरोसा करते हों और संबंधित सुरक्षा जोखिमों को समझते हों।", + "toggleAriaLabel": "स्वतः-अनुमोदन टॉगल करें", + "disabledAriaLabel": "स्वतः-अनुमोदन अक्षम - पहले विकल्प चुनें", "readOnly": { "label": "पढ़ें", "description": "जब सक्षम होता है, तो Roo आपके अनुमोदित बटन पर क्लिक किए बिना स्वचालित रूप से निर्देशिका सामग्री देखेगा और फाइलें पढ़ेगा।", @@ -190,7 +192,8 @@ "title": "अधिकतम अनुरोध", "description": "कार्य जारी रखने के लिए अनुमति मांगने से पहले स्वचालित रूप से इतने API अनुरोध करें।", "unlimited": "असीमित" - } + }, + "selectOptionsFirst": "स्वतः-अनुमोदन सक्षम करने के लिए नीचे से कम से कम एक विकल्प चुनें" }, "providers": { "providerDocumentation": "{{provider}} दस्तावेज़ीकरण", diff --git a/webview-ui/src/i18n/locales/id/chat.json b/webview-ui/src/i18n/locales/id/chat.json index c6f9c57644..f8e2a5cb0e 100644 --- a/webview-ui/src/i18n/locales/id/chat.json +++ b/webview-ui/src/i18n/locales/id/chat.json @@ -250,7 +250,10 @@ "autoApprove": { "title": "Auto-approve:", "none": "Tidak Ada", - "description": "Auto-approve memungkinkan Roo Code melakukan aksi tanpa meminta izin. Hanya aktifkan untuk aksi yang benar-benar kamu percayai. Konfigurasi lebih detail tersedia di Pengaturan." + "description": "Auto-approve memungkinkan Roo Code melakukan aksi tanpa meminta izin. Hanya aktifkan untuk aksi yang benar-benar kamu percayai. Konfigurasi lebih detail tersedia di Pengaturan.", + "selectOptionsFirst": "Pilih setidaknya satu opsi di bawah untuk mengaktifkan persetujuan otomatis", + "toggleAriaLabel": "Beralih persetujuan otomatis", + "disabledAriaLabel": "Persetujuan otomatis dinonaktifkan - pilih opsi terlebih dahulu" }, "announcement": { "title": "🎉 Roo Code {{version}} Dirilis", diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index 24404dec3d..4a0c51d39d 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Izinkan Roo untuk secara otomatis melakukan operasi tanpa memerlukan persetujuan. Aktifkan pengaturan ini hanya jika kamu sepenuhnya mempercayai AI dan memahami risiko keamanan yang terkait.", + "toggleAriaLabel": "Beralih persetujuan otomatis", + "disabledAriaLabel": "Persetujuan otomatis dinonaktifkan - pilih opsi terlebih dahulu", "readOnly": { "label": "Baca", "description": "Ketika diaktifkan, Roo akan secara otomatis melihat konten direktori dan membaca file tanpa memerlukan kamu mengklik tombol Setujui.", @@ -194,7 +196,8 @@ "title": "Permintaan Maks", "description": "Secara otomatis membuat sejumlah permintaan API ini sebelum meminta persetujuan untuk melanjutkan tugas.", "unlimited": "Tidak terbatas" - } + }, + "selectOptionsFirst": "Pilih setidaknya satu opsi di bawah ini untuk mengaktifkan persetujuan otomatis" }, "providers": { "providerDocumentation": "Dokumentasi {{provider}}", diff --git a/webview-ui/src/i18n/locales/it/chat.json b/webview-ui/src/i18n/locales/it/chat.json index 080d6883aa..bea63c047a 100644 --- a/webview-ui/src/i18n/locales/it/chat.json +++ b/webview-ui/src/i18n/locales/it/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Auto-approvazione:", "none": "Nessuna", - "description": "L'auto-approvazione permette a Roo Code di eseguire azioni senza chiedere permesso. Abilita solo per azioni di cui ti fidi completamente. Configurazione più dettagliata disponibile nelle Impostazioni." + "description": "L'auto-approvazione permette a Roo Code di eseguire azioni senza chiedere permesso. Abilita solo per azioni di cui ti fidi completamente. Configurazione più dettagliata disponibile nelle Impostazioni.", + "selectOptionsFirst": "Seleziona almeno un'opzione qui sotto per abilitare l'auto-approvazione", + "toggleAriaLabel": "Attiva/disattiva approvazione automatica", + "disabledAriaLabel": "Approvazione automatica disabilitata - seleziona prima le opzioni" }, "reasoning": { "thinking": "Sto pensando", diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index bacf7a40ef..9d9be82868 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Permetti a Roo di eseguire automaticamente operazioni senza richiedere approvazione. Abilita queste impostazioni solo se ti fidi completamente dell'IA e comprendi i rischi di sicurezza associati.", + "toggleAriaLabel": "Attiva/disattiva approvazione automatica", + "disabledAriaLabel": "Approvazione automatica disabilitata - seleziona prima le opzioni", "readOnly": { "label": "Leggi", "description": "Quando abilitato, Roo visualizzerà automaticamente i contenuti della directory e leggerà i file senza richiedere di cliccare sul pulsante Approva.", @@ -190,7 +192,8 @@ "title": "Richieste massime", "description": "Esegui automaticamente questo numero di richieste API prima di chiedere l'approvazione per continuare con l'attività.", "unlimited": "Illimitato" - } + }, + "selectOptionsFirst": "Seleziona almeno un'opzione qui sotto per abilitare l'approvazione automatica" }, "providers": { "providerDocumentation": "Documentazione {{provider}}", diff --git a/webview-ui/src/i18n/locales/ja/chat.json b/webview-ui/src/i18n/locales/ja/chat.json index 6bb74ad5e2..ca6443b3d8 100644 --- a/webview-ui/src/i18n/locales/ja/chat.json +++ b/webview-ui/src/i18n/locales/ja/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "自動承認:", "none": "なし", - "description": "自動承認はRoo Codeに許可を求めずに操作を実行する権限を与えます。完全に信頼できる操作のみ有効にしてください。より詳細な設定は設定で利用できます。" + "description": "自動承認はRoo Codeに許可を求めずに操作を実行する権限を与えます。完全に信頼できる操作のみ有効にしてください。より詳細な設定は設定で利用できます。", + "selectOptionsFirst": "自動承認を有効にするには、以下のオプションを少なくとも1つ選択してください", + "toggleAriaLabel": "自動承認の切り替え", + "disabledAriaLabel": "自動承認が無効です - 最初にオプションを選択してください" }, "reasoning": { "thinking": "考え中", diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index c588edead2..9fc03cbfb1 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Rooが承認なしで自動的に操作を実行できるようにします。AIを完全に信頼し、関連するセキュリティリスクを理解している場合にのみ、これらの設定を有効にしてください。", + "toggleAriaLabel": "自動承認の切り替え", + "disabledAriaLabel": "自動承認が無効です - 最初にオプションを選択してください", "readOnly": { "label": "読み取り", "description": "有効にすると、Rooは承認ボタンをクリックすることなく、自動的にディレクトリの内容を表示してファイルを読み取ります。", @@ -190,7 +192,8 @@ "title": "最大リクエスト数", "description": "タスクを続行するための承認を求める前に、自動的にこの数のAPIリクエストを行います。", "unlimited": "無制限" - } + }, + "selectOptionsFirst": "自動承認を有効にするには、以下のオプションを少なくとも1つ選択してください" }, "providers": { "providerDocumentation": "{{provider}}のドキュメント", diff --git a/webview-ui/src/i18n/locales/ko/chat.json b/webview-ui/src/i18n/locales/ko/chat.json index 812579a850..7e2c4467cd 100644 --- a/webview-ui/src/i18n/locales/ko/chat.json +++ b/webview-ui/src/i18n/locales/ko/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "자동 승인:", "none": "없음", - "description": "자동 승인을 사용하면 Roo Code가 권한을 요청하지 않고 작업을 수행할 수 있습니다. 완전히 신뢰할 수 있는 작업에만 활성화하세요. 더 자세한 구성은 설정에서 사용할 수 있습니다." + "description": "자동 승인을 사용하면 Roo Code가 권한을 요청하지 않고 작업을 수행할 수 있습니다. 완전히 신뢰할 수 있는 작업에만 활성화하세요. 더 자세한 구성은 설정에서 사용할 수 있습니다.", + "selectOptionsFirst": "자동 승인을 활성화하려면 아래 옵션 중 하나 이상을 선택하세요", + "toggleAriaLabel": "자동 승인 전환", + "disabledAriaLabel": "자동 승인 비활성화됨 - 먼저 옵션을 선택하세요" }, "reasoning": { "thinking": "생각 중", diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index 84c329ffd7..219daa05a4 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Roo가 승인 없이 자동으로 작업을 수행할 수 있도록 허용합니다. AI를 완전히 신뢰하고 관련 보안 위험을 이해하는 경우에만 이러한 설정을 활성화하세요.", + "toggleAriaLabel": "자동 승인 전환", + "disabledAriaLabel": "자동 승인 비활성화됨 - 먼저 옵션을 선택하세요", "readOnly": { "label": "읽기", "description": "활성화되면 Roo는 승인 버튼을 클릭하지 않고도 자동으로 디렉토리 내용을 보고 파일을 읽습니다.", @@ -190,7 +192,8 @@ "title": "최대 요청 수", "description": "작업을 계속하기 위한 승인을 요청하기 전에 자동으로 이 수의 API 요청을 수행합니다.", "unlimited": "무제한" - } + }, + "selectOptionsFirst": "자동 승인을 활성화하려면 아래에서 하나 이상의 옵션을 선택하세요" }, "providers": { "providerDocumentation": "{{provider}} 문서", diff --git a/webview-ui/src/i18n/locales/nl/chat.json b/webview-ui/src/i18n/locales/nl/chat.json index c0e5e92d66..e123b5e8f2 100644 --- a/webview-ui/src/i18n/locales/nl/chat.json +++ b/webview-ui/src/i18n/locales/nl/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Automatisch goedkeuren:", "none": "Geen", - "description": "Met automatisch goedkeuren kan Roo Code acties uitvoeren zonder om toestemming te vragen. Schakel dit alleen in voor acties die je volledig vertrouwt. Meer gedetailleerde configuratie beschikbaar in de Instellingen." + "description": "Met automatisch goedkeuren kan Roo Code acties uitvoeren zonder om toestemming te vragen. Schakel dit alleen in voor acties die je volledig vertrouwt. Meer gedetailleerde configuratie beschikbaar in de Instellingen.", + "selectOptionsFirst": "Selecteer hieronder minstens één optie om automatische goedkeuring in te schakelen", + "toggleAriaLabel": "Automatisch goedkeuren in-/uitschakelen", + "disabledAriaLabel": "Automatisch goedkeuren uitgeschakeld - selecteer eerst opties" }, "announcement": { "title": "🎉 Roo Code {{version}} uitgebracht", diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index 343008ae51..e184f4d85e 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Sta Roo toe om automatisch handelingen uit te voeren zonder goedkeuring. Schakel deze instellingen alleen in als je de AI volledig vertrouwt en de bijbehorende beveiligingsrisico's begrijpt.", + "toggleAriaLabel": "Automatisch goedkeuren in-/uitschakelen", + "disabledAriaLabel": "Automatisch goedkeuren uitgeschakeld - selecteer eerst opties", "readOnly": { "label": "Lezen", "description": "Indien ingeschakeld, bekijkt Roo automatisch de inhoud van mappen en leest bestanden zonder dat je op de Goedkeuren-knop hoeft te klikken.", @@ -190,7 +192,8 @@ "title": "Maximale verzoeken", "description": "Voer automatisch dit aantal API-verzoeken uit voordat om goedkeuring wordt gevraagd om door te gaan met de taak.", "unlimited": "Onbeperkt" - } + }, + "selectOptionsFirst": "Selecteer ten minste één optie hieronder om automatische goedkeuring in te schakelen" }, "providers": { "providerDocumentation": "{{provider}} documentatie", diff --git a/webview-ui/src/i18n/locales/pl/chat.json b/webview-ui/src/i18n/locales/pl/chat.json index 3e59b4f981..f772256b10 100644 --- a/webview-ui/src/i18n/locales/pl/chat.json +++ b/webview-ui/src/i18n/locales/pl/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Automatyczne zatwierdzanie:", "none": "Brak", - "description": "Automatyczne zatwierdzanie pozwala Roo Code wykonywać działania bez pytania o pozwolenie. Włącz tylko dla działań, którym w pełni ufasz. Bardziej szczegółowa konfiguracja dostępna w Ustawieniach." + "description": "Automatyczne zatwierdzanie pozwala Roo Code wykonywać działania bez pytania o pozwolenie. Włącz tylko dla działań, którym w pełni ufasz. Bardziej szczegółowa konfiguracja dostępna w Ustawieniach.", + "selectOptionsFirst": "Wybierz co najmniej jedną opcję poniżej, aby włączyć automatyczne zatwierdzanie", + "toggleAriaLabel": "Przełącz automatyczne zatwierdzanie", + "disabledAriaLabel": "Automatyczne zatwierdzanie wyłączone - najpierw wybierz opcje" }, "reasoning": { "thinking": "Myślenie", diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index 2f300384e4..23d3ce707d 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Pozwól Roo na automatyczne wykonywanie operacji bez wymagania zatwierdzenia. Włącz te ustawienia tylko jeśli w pełni ufasz AI i rozumiesz związane z tym zagrożenia bezpieczeństwa.", + "toggleAriaLabel": "Przełącz automatyczne zatwierdzanie", + "disabledAriaLabel": "Automatyczne zatwierdzanie wyłączone - najpierw wybierz opcje", "readOnly": { "label": "Odczyt", "description": "Gdy włączone, Roo automatycznie będzie wyświetlać zawartość katalogów i czytać pliki bez konieczności klikania przycisku Zatwierdź.", @@ -190,7 +192,8 @@ "title": "Maksymalna liczba żądań", "description": "Automatycznie wykonaj tyle żądań API przed poproszeniem o zgodę na kontynuowanie zadania.", "unlimited": "Bez limitu" - } + }, + "selectOptionsFirst": "Wybierz co najmniej jedną opcję poniżej, aby włączyć automatyczne zatwierdzanie" }, "providers": { "providerDocumentation": "Dokumentacja {{provider}}", diff --git a/webview-ui/src/i18n/locales/pt-BR/chat.json b/webview-ui/src/i18n/locales/pt-BR/chat.json index 8f7dcd5dcd..08eb496d0a 100644 --- a/webview-ui/src/i18n/locales/pt-BR/chat.json +++ b/webview-ui/src/i18n/locales/pt-BR/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Aprovação automática:", "none": "Nenhuma", - "description": "A aprovação automática permite que o Roo Code execute ações sem pedir permissão. Ative apenas para ações nas quais você confia totalmente. Configuração mais detalhada disponível nas Configurações." + "description": "A aprovação automática permite que o Roo Code execute ações sem pedir permissão. Ative apenas para ações nas quais você confia totalmente. Configuração mais detalhada disponível nas Configurações.", + "selectOptionsFirst": "Selecione pelo menos uma opção abaixo para ativar a aprovação automática", + "toggleAriaLabel": "Alternar aprovação automática", + "disabledAriaLabel": "Aprovação automática desativada - selecione as opções primeiro" }, "reasoning": { "thinking": "Pensando", diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index 11e4d01aac..102036622c 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Permitir que o Roo realize operações automaticamente sem exigir aprovação. Ative essas configurações apenas se confiar totalmente na IA e compreender os riscos de segurança associados.", + "toggleAriaLabel": "Alternar aprovação automática", + "disabledAriaLabel": "Aprovação automática desativada - selecione as opções primeiro", "readOnly": { "label": "Leitura", "description": "Quando ativado, o Roo visualizará automaticamente o conteúdo do diretório e lerá arquivos sem que você precise clicar no botão Aprovar.", @@ -190,7 +192,8 @@ "title": "Máximo de Solicitações", "description": "Fazer automaticamente este número de requisições à API antes de pedir aprovação para continuar com a tarefa.", "unlimited": "Ilimitado" - } + }, + "selectOptionsFirst": "Selecione pelo menos uma opção abaixo para habilitar a aprovação automática" }, "providers": { "providerDocumentation": "Documentação do {{provider}}", diff --git a/webview-ui/src/i18n/locales/ru/chat.json b/webview-ui/src/i18n/locales/ru/chat.json index 89502fbc76..07e0501505 100644 --- a/webview-ui/src/i18n/locales/ru/chat.json +++ b/webview-ui/src/i18n/locales/ru/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Автоодобрение:", "none": "Нет", - "description": "Автоодобрение позволяет Roo Code выполнять действия без запроса разрешения. Включайте только для полностью доверенных действий. Более подробная настройка доступна в Настройках." + "description": "Автоодобрение позволяет Roo Code выполнять действия без запроса разрешения. Включайте только для полностью доверенных действий. Более подробная настройка доступна в Настройках.", + "selectOptionsFirst": "Выберите хотя бы один параметр ниже, чтобы включить автоодобрение", + "toggleAriaLabel": "Переключить автоодобрение", + "disabledAriaLabel": "Автоодобрение отключено - сначала выберите опции" }, "announcement": { "title": "🎉 Выпущен Roo Code {{version}}", diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 35eb9b1966..5952dd8c89 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Разрешить Roo автоматически выполнять операции без необходимости одобрения. Включайте эти параметры только если полностью доверяете ИИ и понимаете связанные с этим риски безопасности.", + "toggleAriaLabel": "Переключить автоодобрение", + "disabledAriaLabel": "Автоодобрение отключено - сначала выберите опции", "readOnly": { "label": "Чтение", "description": "Если включено, Roo будет автоматически просматривать содержимое каталогов и читать файлы без необходимости нажимать кнопку \"Одобрить\".", @@ -190,7 +192,8 @@ "title": "Максимум запросов", "description": "Автоматически выполнять это количество API-запросов перед запросом разрешения на продолжение задачи.", "unlimited": "Без ограничений" - } + }, + "selectOptionsFirst": "Выберите хотя бы один вариант ниже, чтобы включить автоодобрение" }, "providers": { "providerDocumentation": "Документация {{provider}}", diff --git a/webview-ui/src/i18n/locales/tr/chat.json b/webview-ui/src/i18n/locales/tr/chat.json index 94910edf89..ee16f56f72 100644 --- a/webview-ui/src/i18n/locales/tr/chat.json +++ b/webview-ui/src/i18n/locales/tr/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Otomatik-onay:", "none": "Hiçbiri", - "description": "Otomatik onay, Roo Code'un izin istemeden işlemler gerçekleştirmesine olanak tanır. Yalnızca tamamen güvendiğiniz eylemler için etkinleştirin. Daha detaylı yapılandırma Ayarlar'da mevcuttur." + "description": "Otomatik onay, Roo Code'un izin istemeden işlemler gerçekleştirmesine olanak tanır. Yalnızca tamamen güvendiğiniz eylemler için etkinleştirin. Daha detaylı yapılandırma Ayarlar'da mevcuttur.", + "selectOptionsFirst": "Otomatik onayı etkinleştirmek için aşağıdan en az bir seçenek belirleyin", + "toggleAriaLabel": "Otomatik onayı değiştir", + "disabledAriaLabel": "Otomatik onay devre dışı - önce seçenekleri belirleyin" }, "reasoning": { "thinking": "Düşünüyor", diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index 9b90c97fb3..625ca4d5ea 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Roo'nun onay gerektirmeden otomatik olarak işlemler gerçekleştirmesine izin verin. Bu ayarları yalnızca yapay zekaya tamamen güveniyorsanız ve ilgili güvenlik risklerini anlıyorsanız etkinleştirin.", + "toggleAriaLabel": "Otomatik onayı değiştir", + "disabledAriaLabel": "Otomatik onay devre dışı - önce seçenekleri belirleyin", "readOnly": { "label": "Okuma", "description": "Etkinleştirildiğinde, Roo otomatik olarak dizin içeriğini görüntüleyecek ve Onayla düğmesine tıklamanıza gerek kalmadan dosyaları okuyacaktır.", @@ -190,7 +192,8 @@ "title": "Maksimum İstek", "description": "Göreve devam etmek için onay istemeden önce bu sayıda API isteği otomatik olarak yap.", "unlimited": "Sınırsız" - } + }, + "selectOptionsFirst": "Otomatik onayı etkinleştirmek için aşağıdan en az bir seçenek seçin" }, "providers": { "providerDocumentation": "{{provider}} Dokümantasyonu", diff --git a/webview-ui/src/i18n/locales/vi/chat.json b/webview-ui/src/i18n/locales/vi/chat.json index 02f27f9e37..e56f63a91e 100644 --- a/webview-ui/src/i18n/locales/vi/chat.json +++ b/webview-ui/src/i18n/locales/vi/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "Tự động phê duyệt:", "none": "Không", - "description": "Tự động phê duyệt cho phép Roo Code thực hiện hành động mà không cần xin phép. Chỉ bật cho các hành động bạn hoàn toàn tin tưởng. Cấu hình chi tiết hơn có sẵn trong Cài đặt." + "description": "Tự động phê duyệt cho phép Roo Code thực hiện hành động mà không cần xin phép. Chỉ bật cho các hành động bạn hoàn toàn tin tưởng. Cấu hình chi tiết hơn có sẵn trong Cài đặt.", + "selectOptionsFirst": "Chọn ít nhất một tùy chọn bên dưới để bật tự động phê duyệt", + "toggleAriaLabel": "Chuyển đổi tự động phê duyệt", + "disabledAriaLabel": "Tự động phê duyệt bị vô hiệu hóa - hãy chọn các tùy chọn trước" }, "reasoning": { "thinking": "Đang suy nghĩ", diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index 19b574af36..52a9db5b93 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "Cho phép Roo tự động thực hiện các hoạt động mà không cần phê duyệt. Chỉ bật những cài đặt này nếu bạn hoàn toàn tin tưởng AI và hiểu rõ các rủi ro bảo mật liên quan.", + "toggleAriaLabel": "Chuyển đổi tự động phê duyệt", + "disabledAriaLabel": "Tự động phê duyệt bị vô hiệu hóa - hãy chọn các tùy chọn trước", "readOnly": { "label": "Đọc", "description": "Khi được bật, Roo sẽ tự động xem nội dung thư mục và đọc tệp mà không yêu cầu bạn nhấp vào nút Phê duyệt.", @@ -190,7 +192,8 @@ "title": "Số lượng yêu cầu tối đa", "description": "Tự động thực hiện số lượng API request này trước khi yêu cầu phê duyệt để tiếp tục với nhiệm vụ.", "unlimited": "Không giới hạn" - } + }, + "selectOptionsFirst": "Chọn ít nhất một tùy chọn bên dưới để bật tự động phê duyệt" }, "providers": { "providerDocumentation": "Tài liệu {{provider}}", diff --git a/webview-ui/src/i18n/locales/zh-CN/chat.json b/webview-ui/src/i18n/locales/zh-CN/chat.json index 370543f294..d98dbe6f05 100644 --- a/webview-ui/src/i18n/locales/zh-CN/chat.json +++ b/webview-ui/src/i18n/locales/zh-CN/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "自动批准:", "none": "无", - "description": "允许直接执行操作无需确认,请谨慎启用。前往设置调整" + "description": "允许直接执行操作无需确认,请谨慎启用。前往设置调整", + "selectOptionsFirst": "选择至少一个下面的选项以启用自动批准", + "toggleAriaLabel": "切换自动批准", + "disabledAriaLabel": "自动批准已禁用 - 请先选择选项" }, "reasoning": { "thinking": "思考中", diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index 402de1e683..151ee9e744 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "允许 Roo 自动执行操作而无需批准。只有在您完全信任 AI 并了解相关安全风险的情况下才启用这些设置。", + "toggleAriaLabel": "切换自动批准", + "disabledAriaLabel": "自动批准已禁用 - 请先选择选项", "readOnly": { "label": "读取", "description": "启用后,Roo 将自动浏览目录和读取文件内容,无需人工确认。", @@ -190,7 +192,8 @@ "title": "最大请求数", "description": "在请求批准以继续执行任务之前,自动发出此数量的 API 请求。", "unlimited": "无限制" - } + }, + "selectOptionsFirst": "请至少选择以下一个选项以启用自动批准" }, "providers": { "providerDocumentation": "{{provider}} 文档", diff --git a/webview-ui/src/i18n/locales/zh-TW/chat.json b/webview-ui/src/i18n/locales/zh-TW/chat.json index 3b9dcc795c..e5dcd13a42 100644 --- a/webview-ui/src/i18n/locales/zh-TW/chat.json +++ b/webview-ui/src/i18n/locales/zh-TW/chat.json @@ -223,7 +223,10 @@ "autoApprove": { "title": "自動核准:", "none": "無", - "description": "自動核准讓 Roo Code 可以在無需徵求您同意的情況下執行動作。請僅對您完全信任的動作啟用此功能。您可以在設定中進行更詳細的調整。" + "description": "自動核准讓 Roo Code 可以在無需徵求您同意的情況下執行動作。請僅對您完全信任的動作啟用此功能。您可以在設定中進行更詳細的調整。", + "selectOptionsFirst": "請至少選擇以下一個選項以啟用自動核准", + "toggleAriaLabel": "切換自動核准", + "disabledAriaLabel": "自動核准已停用 - 請先選取選項" }, "reasoning": { "thinking": "思考中", diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index 068e64d21f..ab4caeea5b 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -123,6 +123,8 @@ }, "autoApprove": { "description": "允許 Roo 無需核准即執行操作。僅在您完全信任 AI 並了解相關安全風險時啟用這些設定。", + "toggleAriaLabel": "切換自動核准", + "disabledAriaLabel": "自動核准已停用 - 請先選取選項", "readOnly": { "label": "讀取", "description": "啟用後,Roo 將自動檢視目錄內容並讀取檔案,無需點選核准按鈕。", @@ -190,7 +192,8 @@ "title": "最大請求數", "description": "在請求批准以繼續執行工作之前,自動發出此數量的 API 請求。", "unlimited": "無限制" - } + }, + "selectOptionsFirst": "請至少選擇以下一個選項以啟用自動核准" }, "providers": { "providerDocumentation": "{{provider}} 文件", From fb374b3e949dfaa5bea34f885dd9e103033b4686 Mon Sep 17 00:00:00 2001 From: Will Li Date: Thu, 17 Jul 2025 07:16:57 -0700 Subject: [PATCH 07/19] Message edit/delete overhaul (#5538) * improved chat row first pass * big UI improvements * working functionality * tests working * ok finally tests working for real! * translations * add back hidden flag * remove option to skip notif * fixed image issue * ui fix * put back edit flag * oops test fix * reduce margins * code review --- .../webview/__tests__/ClineProvider.spec.ts | 355 +++++---- .../__tests__/webviewMessageHandler.spec.ts | 52 ++ src/core/webview/webviewMessageHandler.ts | 138 ++-- src/i18n/locales/ca/common.json | 7 +- src/i18n/locales/de/common.json | 7 +- src/i18n/locales/en/common.json | 7 +- src/i18n/locales/es/common.json | 7 +- src/i18n/locales/fr/common.json | 7 +- src/i18n/locales/hi/common.json | 7 +- src/i18n/locales/id/common.json | 7 +- src/i18n/locales/it/common.json | 7 +- src/i18n/locales/ja/common.json | 7 +- src/i18n/locales/ko/common.json | 7 +- src/i18n/locales/nl/common.json | 7 +- src/i18n/locales/pl/common.json | 7 +- src/i18n/locales/pt-BR/common.json | 7 +- src/i18n/locales/ru/common.json | 7 +- src/i18n/locales/tr/common.json | 7 +- src/i18n/locales/vi/common.json | 7 +- src/i18n/locales/zh-CN/common.json | 7 +- src/i18n/locales/zh-TW/common.json | 7 +- src/shared/ExtensionMessage.ts | 4 + src/shared/WebviewMessage.ts | 4 + webview-ui/src/App.tsx | 83 +- webview-ui/src/components/chat/ChatRow.tsx | 68 +- .../src/components/chat/ChatTextArea.tsx | 736 ++++++++++-------- webview-ui/src/components/chat/ChatView.tsx | 8 +- .../src/components/chat/EditModeControls.tsx | 115 +++ .../MessageModificationConfirmationDialog.tsx | 62 ++ .../chat/__tests__/ChatTextArea.spec.tsx | 50 ++ .../chat/__tests__/EditModeControls.spec.tsx | 138 ++++ webview-ui/src/i18n/locales/ca/chat.json | 5 +- webview-ui/src/i18n/locales/ca/common.json | 7 + webview-ui/src/i18n/locales/de/chat.json | 5 +- webview-ui/src/i18n/locales/de/common.json | 7 + webview-ui/src/i18n/locales/en/chat.json | 5 +- webview-ui/src/i18n/locales/en/common.json | 7 + webview-ui/src/i18n/locales/es/chat.json | 5 +- webview-ui/src/i18n/locales/es/common.json | 7 + webview-ui/src/i18n/locales/fr/chat.json | 5 +- webview-ui/src/i18n/locales/fr/common.json | 7 + webview-ui/src/i18n/locales/hi/chat.json | 5 +- webview-ui/src/i18n/locales/hi/common.json | 7 + webview-ui/src/i18n/locales/id/chat.json | 5 +- webview-ui/src/i18n/locales/id/common.json | 7 + webview-ui/src/i18n/locales/it/chat.json | 5 +- webview-ui/src/i18n/locales/it/common.json | 7 + webview-ui/src/i18n/locales/ja/chat.json | 5 +- webview-ui/src/i18n/locales/ja/common.json | 7 + webview-ui/src/i18n/locales/ko/chat.json | 5 +- webview-ui/src/i18n/locales/ko/common.json | 7 + webview-ui/src/i18n/locales/nl/chat.json | 5 +- webview-ui/src/i18n/locales/nl/common.json | 7 + webview-ui/src/i18n/locales/pl/chat.json | 5 +- webview-ui/src/i18n/locales/pl/common.json | 7 + webview-ui/src/i18n/locales/pt-BR/chat.json | 5 +- webview-ui/src/i18n/locales/pt-BR/common.json | 7 + webview-ui/src/i18n/locales/ru/chat.json | 5 +- webview-ui/src/i18n/locales/ru/common.json | 7 + webview-ui/src/i18n/locales/tr/chat.json | 5 +- webview-ui/src/i18n/locales/tr/common.json | 7 + webview-ui/src/i18n/locales/vi/chat.json | 5 +- webview-ui/src/i18n/locales/vi/common.json | 7 + webview-ui/src/i18n/locales/zh-CN/chat.json | 5 +- webview-ui/src/i18n/locales/zh-CN/common.json | 7 + webview-ui/src/i18n/locales/zh-TW/chat.json | 5 +- webview-ui/src/i18n/locales/zh-TW/common.json | 7 + webview-ui/src/utils/imageUtils.ts | 17 + 68 files changed, 1461 insertions(+), 711 deletions(-) create mode 100644 webview-ui/src/components/chat/EditModeControls.tsx create mode 100644 webview-ui/src/components/chat/MessageModificationConfirmationDialog.tsx create mode 100644 webview-ui/src/components/chat/__tests__/EditModeControls.spec.tsx create mode 100644 webview-ui/src/utils/imageUtils.ts diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 19c9a7c9fc..dd9ee12bfc 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -1163,15 +1163,10 @@ describe("ClineProvider", () => { describe("deleteMessage", () => { beforeEach(async () => { - // Mock window.showInformationMessage - ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) - test('handles "Just this message" deletion correctly', async () => { - // Mock user selecting "Just this message" - ;(vscode.window.showInformationMessage as any).mockResolvedValue("confirmation.delete_just_this_message") - + test("handles deletion with confirmation dialog", async () => { // Setup mock messages const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback" }, // User message 1 @@ -1202,103 +1197,58 @@ describe("ClineProvider", () => { historyItem: { id: "test-task-id" }, }) + // Mock initClineWithHistoryItem + ;(provider as any).initClineWithHistoryItem = vi.fn() + // Trigger message deletion const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "deleteMessage", value: 4000 }) - // Verify correct messages were kept - expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([ - mockMessages[0], - mockMessages[1], - mockMessages[4], - mockMessages[5], - ]) + // Verify that the dialog message was sent to webview + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showDeleteMessageDialog", + messageTs: 4000, + }) - // Verify correct API messages were kept + // Simulate user confirming deletion through the dialog + await messageHandler({ type: "deleteMessageConfirm", messageTs: 4000 }) + + // Verify only messages before the deleted message were kept + expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([mockMessages[0], mockMessages[1]]) + + // Verify only API messages before the deleted message were kept expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([ mockApiHistory[0], mockApiHistory[1], - mockApiHistory[4], - mockApiHistory[5], ]) + + // Verify initClineWithHistoryItem was called + expect((provider as any).initClineWithHistoryItem).toHaveBeenCalledWith({ id: "test-task-id" }) }) - test('handles "This and all subsequent messages" deletion correctly', async () => { - // Mock user selecting "This and all subsequent messages" - ;(vscode.window.showInformationMessage as any).mockResolvedValue("confirmation.delete_this_and_subsequent") - - // Setup mock messages - const mockMessages = [ - { ts: 1000, type: "say", say: "user_feedback" }, - { ts: 2000, type: "say", say: "text", value: 3000 }, // Message to delete - { ts: 3000, type: "say", say: "user_feedback" }, - { ts: 4000, type: "say", say: "user_feedback" }, - ] as ClineMessage[] - - const mockApiHistory = [ - { ts: 1000 }, - { ts: 2000 }, - { ts: 3000 }, - { ts: 4000 }, - ] as (Anthropic.MessageParam & { - ts?: number - })[] - - // Setup Cline instance with auto-mock from the top of the file - const mockCline = new Task(defaultTaskOptions) // Create a new mocked instance - mockCline.clineMessages = mockMessages - mockCline.apiConversationHistory = mockApiHistory - await provider.addClineToStack(mockCline) - - // Mock getTaskWithId - ;(provider as any).getTaskWithId = vi.fn().mockResolvedValue({ - historyItem: { id: "test-task-id" }, - }) - - // Trigger message deletion - const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] - await messageHandler({ type: "deleteMessage", value: 3000 }) - - // Verify only messages before the deleted message were kept - expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([mockMessages[0]]) - - // Verify only API messages before the deleted message were kept - expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([mockApiHistory[0]]) - }) - - test("handles Cancel correctly", async () => { - // Mock user selecting "Cancel" - ;(vscode.window.showInformationMessage as any).mockResolvedValue("Cancel") - - // Setup Cline instance with auto-mock from the top of the file - const mockCline = new Task(defaultTaskOptions) // Create a new mocked instance - mockCline.clineMessages = [{ ts: 1000 }, { ts: 2000 }] as ClineMessage[] - mockCline.apiConversationHistory = [{ ts: 1000 }, { ts: 2000 }] as (Anthropic.MessageParam & { - ts?: number - })[] - await provider.addClineToStack(mockCline) + test("handles case when no current task exists", async () => { + // Clear the cline stack + ;(provider as any).clineStack = [] // Trigger message deletion const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] await messageHandler({ type: "deleteMessage", value: 2000 }) - // Verify no messages were deleted - expect(mockCline.overwriteClineMessages).not.toHaveBeenCalled() - expect(mockCline.overwriteApiConversationHistory).not.toHaveBeenCalled() + // Verify no dialog was shown since there's no current cline + expect(mockPostMessage).not.toHaveBeenCalledWith( + expect.objectContaining({ + type: "showDeleteMessageDialog", + }), + ) }) }) describe("editMessage", () => { beforeEach(async () => { - // Mock window.showWarningMessage - ;(vscode.window.showWarningMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) - test('handles "Proceed" edit correctly', async () => { - // Mock user selecting "Proceed" - need to use the localized string key - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - + test("handles edit with confirmation dialog", async () => { // Setup mock messages const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback" }, // User message 1 @@ -1346,6 +1296,20 @@ describe("ClineProvider", () => { editedMessageContent: "Edited message content", }) + // Verify that the dialog message was sent to webview + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 4000, + text: "Edited message content", + }) + + // Simulate user confirming edit through the dialog + await messageHandler({ + type: "editMessageConfirm", + messageTs: 4000, + text: "Edited message content", + }) + // Verify correct messages were kept (only messages before the edited one) expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([mockMessages[0], mockMessages[1]]) @@ -1355,12 +1319,9 @@ describe("ClineProvider", () => { mockApiHistory[1], ]) - // Verify handleWebviewAskResponse was called with the edited content - expect(mockCline.handleWebviewAskResponse).toHaveBeenCalledWith( - "messageResponse", - "Edited message content", - undefined, - ) + // The new flow calls webviewMessageHandler recursively with askResponse + // We need to verify the recursive call happened by checking if the handler was called again + expect((mockWebviewView.webview.onDidReceiveMessage as any).mock.calls.length).toBeGreaterThanOrEqual(1) }) }) @@ -2705,13 +2666,10 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { describe("Edit Messages with Images and Attachments", () => { beforeEach(async () => { - ;(vscode.window.showInformationMessage as any) = vi.fn() await provider.resolveWebviewView(mockWebviewView) }) test("handles editing messages containing images", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message" }, { @@ -2746,17 +2704,26 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { editedMessageContent: "Edited message with preserved images", }) - expect(mockCline.overwriteClineMessages).toHaveBeenCalled() - expect(mockCline.handleWebviewAskResponse).toHaveBeenCalledWith( - "messageResponse", - "Edited message with preserved images", - undefined, - ) + // Verify dialog was shown + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 3000, + text: "Edited message with preserved images", + }) + + // Simulate confirmation + await messageHandler({ + type: "editMessageConfirm", + messageTs: 3000, + text: "Edited message with preserved images", + }) + + // Verify messages were edited correctly - only the first message should remain + expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([mockMessages[0]]) + expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([{ ts: 1000 }]) }) test("handles editing messages with file attachments", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - const mockMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message" }, { @@ -2789,6 +2756,20 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { editedMessageContent: "Edited message with file attachment", }) + // Verify dialog was shown + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 3000, + text: "Edited message with file attachment", + }) + + // Simulate user confirming the edit + await messageHandler({ + type: "editMessageConfirm", + messageTs: 3000, + text: "Edited message with file attachment", + }) + expect(mockCline.overwriteClineMessages).toHaveBeenCalled() expect(mockCline.handleWebviewAskResponse).toHaveBeenCalledWith( "messageResponse", @@ -2805,8 +2786,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("handles network timeout during edit submission", async () => { - ;(vscode.window.showInformationMessage as any).mockResolvedValue("confirmation.proceed") - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message", value: 2000 }, @@ -2833,12 +2812,20 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }), ).resolves.toBeUndefined() + // Verify dialog was shown + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 2000, + text: "Edited message", + }) + + // Simulate user confirming the edit + await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message" }) + expect(mockCline.overwriteClineMessages).toHaveBeenCalled() }) test("handles connection drops during edit operation", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message", value: 2000 }, @@ -2865,6 +2852,17 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }), ).resolves.toBeUndefined() + // Verify dialog was shown + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 2000, + text: "Edited message", + }) + + // Simulate user confirming the edit + await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message" }) + + // The error should be caught and shown expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Error editing message: Connection lost") }) }) @@ -2876,8 +2874,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("handles race conditions with simultaneous edits", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message 1", value: 2000 }, @@ -2912,6 +2908,22 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { await Promise.all([edit1Promise, edit2Promise]) + // Verify dialogs were shown for both edits + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 2000, + text: "Edited message 1", + }) + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 4000, + text: "Edited message 2", + }) + + // Simulate user confirming both edits + await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message 1" }) + await messageHandler({ type: "editMessageConfirm", messageTs: 4000, text: "Edited message 2" }) + // Both operations should complete without throwing expect(mockCline.overwriteClineMessages).toHaveBeenCalled() }) @@ -2940,8 +2952,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("handles authorization failures during edit", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message", value: 2000 }, @@ -2965,6 +2975,13 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { editedMessageContent: "Edited message", }) + // Simulate confirmation + await messageHandler({ + type: "editMessageConfirm", + messageTs: 2000, + text: "Edited message", + }) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Error editing message: Unauthorized") }) @@ -3058,8 +3075,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("handles edit operations on deleted messages", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Existing message" }, @@ -3083,17 +3098,26 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { editedMessageContent: "Edited non-existent message", }) - // Should show confirmation dialog but not perform any operations - expect(vscode.window.showWarningMessage).toHaveBeenCalled() + // Should show edit dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 5000, + text: "Edited non-existent message", + }) + + // Simulate user confirming the edit + await messageHandler({ + type: "editMessageConfirm", + messageTs: 5000, + text: "Edited non-existent message", + }) + + // Should not perform any operations since message doesn't exist expect(mockCline.overwriteClineMessages).not.toHaveBeenCalled() expect(mockCline.handleWebviewAskResponse).not.toHaveBeenCalled() }) test("handles delete operations on non-existent messages", async () => { - ;(vscode.window.showInformationMessage as any).mockResolvedValue( - "confirmation.delete_just_this_message", - ) - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Existing message" }, @@ -3115,8 +3139,16 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { value: 5000, }) - // Should show confirmation dialog but not perform any operations - expect(vscode.window.showInformationMessage).toHaveBeenCalled() + // Should show delete dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showDeleteMessageDialog", + messageTs: 5000, + }) + + // Simulate user confirming the delete + await messageHandler({ type: "deleteMessageConfirm", messageTs: 5000 }) + + // Should not perform any operations since message doesn't exist expect(mockCline.overwriteClineMessages).not.toHaveBeenCalled() }) }) @@ -3128,8 +3160,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("validates proper cleanup during failed edit operations", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Original message", value: 2000 }, @@ -3159,16 +3189,22 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { editedMessageContent: "Edited message", }) + // Should show edit dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 2000, + text: "Edited message", + }) + + // Simulate user confirming the edit + await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: "Edited message" }) + // Verify cleanup was attempted before failure expect(cleanupSpy).toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Error editing message: Operation failed") }) test("validates proper cleanup during failed delete operations", async () => { - ;(vscode.window.showInformationMessage as any).mockResolvedValue( - "confirmation.delete_just_this_message", - ) - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message to delete" }, @@ -3193,6 +3229,15 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { await messageHandler({ type: "deleteMessage", value: 2000 }) + // Should show delete dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showDeleteMessageDialog", + messageTs: 2000, + }) + + // Simulate user confirming the delete + await messageHandler({ type: "deleteMessageConfirm", messageTs: 2000 }) + // Verify cleanup was attempted before failure expect(cleanupSpy).toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( @@ -3208,8 +3253,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("handles editing messages with large text content", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - // Create a large message (10KB of text) const largeText = "A".repeat(10000) const mockMessages = [ @@ -3238,6 +3281,16 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { editedMessageContent: largeEditedContent, }) + // Should show edit dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 2000, + text: largeEditedContent, + }) + + // Simulate user confirming the edit + await messageHandler({ type: "editMessageConfirm", messageTs: 2000, text: largeEditedContent }) + expect(mockCline.overwriteClineMessages).toHaveBeenCalled() expect(mockCline.handleWebviewAskResponse).toHaveBeenCalledWith( "messageResponse", @@ -3247,10 +3300,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("handles deleting messages with large payloads", async () => { - ;(vscode.window.showInformationMessage as any).mockResolvedValue( - "confirmation.delete_this_and_subsequent", - ) - // Create messages with large payloads const largeText = "X".repeat(50000) const mockMessages = [ @@ -3275,6 +3324,15 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { await messageHandler({ type: "deleteMessage", value: 3000 }) + // Should show delete dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showDeleteMessageDialog", + messageTs: 3000, + }) + + // Simulate user confirming the delete + await messageHandler({ type: "deleteMessageConfirm", messageTs: 3000 }) + // Should handle large payloads without issues expect(mockCline.overwriteClineMessages).toHaveBeenCalledWith([mockMessages[0]]) expect(mockCline.overwriteApiConversationHistory).toHaveBeenCalledWith([{ ts: 1000 }]) @@ -3285,10 +3343,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { // Note: Error messaging test removed as the implementation may not have proper error handling in place test("provides user feedback for successful operations", async () => { - ;(vscode.window.showInformationMessage as any).mockResolvedValue( - "confirmation.delete_just_this_message", - ) - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message to delete" }, @@ -3308,6 +3362,15 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { await messageHandler({ type: "deleteMessage", value: 2000 }) + // Should show delete dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showDeleteMessageDialog", + messageTs: 2000, + }) + + // Simulate user confirming the delete + await messageHandler({ type: "deleteMessageConfirm", messageTs: 2000 }) + // Verify successful operation completed expect(mockCline.overwriteClineMessages).toHaveBeenCalled() expect(provider.initClineWithHistoryItem).toHaveBeenCalled() @@ -3315,8 +3378,7 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("handles user cancellation gracefully", async () => { - // Mock user canceling the operation - ;(vscode.window.showWarningMessage as any).mockResolvedValue(undefined) + // Test cancellation by not sending confirmation const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ @@ -3353,10 +3415,6 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { }) test("handles messages with identical timestamps", async () => { - ;(vscode.window.showInformationMessage as any).mockResolvedValue( - "confirmation.delete_just_this_message", - ) - const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ { ts: 1000, type: "say", say: "user_feedback", text: "Message 1" }, @@ -3377,13 +3435,20 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { await messageHandler({ type: "deleteMessage", value: 1000 }) + // Should show delete dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showDeleteMessageDialog", + messageTs: 1000, + }) + + // Simulate user confirming the delete + await messageHandler({ type: "deleteMessageConfirm", messageTs: 1000 }) + // Should handle identical timestamps gracefully expect(mockCline.overwriteClineMessages).toHaveBeenCalled() }) test("handles messages with future timestamps", async () => { - ;(vscode.window.showWarningMessage as any).mockResolvedValue("confirmation.proceed") - const futureTimestamp = Date.now() + 100000 // Future timestamp const mockCline = new Task(defaultTaskOptions) mockCline.clineMessages = [ @@ -3419,6 +3484,20 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { editedMessageContent: "Edited future message", }) + // Should show edit dialog + expect(mockPostMessage).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: futureTimestamp + 1000, + text: "Edited future message", + }) + + // Simulate user confirming the edit + await messageHandler({ + type: "editMessageConfirm", + messageTs: futureTimestamp + 1000, + text: "Edited future message", + }) + // Should handle future timestamps correctly expect(mockCline.overwriteClineMessages).toHaveBeenCalled() expect(mockCline.handleWebviewAskResponse).toHaveBeenCalled() diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 2f356aef55..284ee98944 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -28,9 +28,13 @@ const mockClineProvider = { globalStorageUri: { fsPath: "/mock/global/storage" }, }, setValue: vi.fn(), + getValue: vi.fn(), }, log: vi.fn(), postStateToWebview: vi.fn(), + getCurrentCline: vi.fn(), + getTaskWithId: vi.fn(), + initClineWithHistoryItem: vi.fn(), } as unknown as ClineProvider import { t } from "../../../i18n" @@ -482,3 +486,51 @@ describe("webviewMessageHandler - deleteCustomMode", () => { expect(mockClineProvider.postMessageToWebview).not.toHaveBeenCalled() }) }) + +describe("webviewMessageHandler - message dialog preferences", () => { + beforeEach(() => { + vi.clearAllMocks() + // Mock a current Cline instance + vi.mocked(mockClineProvider.getCurrentCline).mockReturnValue({ + taskId: "test-task-id", + apiConversationHistory: [], + clineMessages: [], + } as any) + // Reset getValue mock + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(false) + }) + + describe("deleteMessage", () => { + it("should always show dialog for delete confirmation", async () => { + vi.mocked(mockClineProvider.getCurrentCline).mockReturnValue({} as any) // Mock current cline exists + + await webviewMessageHandler(mockClineProvider, { + type: "deleteMessage", + value: 123456789, // Changed from messageTs to value + }) + + expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "showDeleteMessageDialog", + messageTs: 123456789, + }) + }) + }) + + describe("submitEditedMessage", () => { + it("should always show dialog for edit confirmation", async () => { + vi.mocked(mockClineProvider.getCurrentCline).mockReturnValue({} as any) // Mock current cline exists + + await webviewMessageHandler(mockClineProvider, { + type: "submitEditedMessage", + value: 123456789, // messageTs as number + editedMessageContent: "edited content", // text content in editedMessageContent field + }) + + expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "showEditMessageDialog", + messageTs: 123456789, + text: "edited content", + }) + }) + }) +}) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index e70b39df8f..2efb2cbdff 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -77,55 +77,6 @@ export const webviewMessageHandler = async ( return { messageIndex, apiConversationHistoryIndex } } - /** - * Removes just the target message, preserving messages after the next user message - */ - const removeMessagesJustThis = async ( - currentCline: any, - messageIndex: number, - apiConversationHistoryIndex: number, - ) => { - // Find the next user message first - const nextUserMessage = currentCline.clineMessages - .slice(messageIndex + 1) - .find((msg: ClineMessage) => msg.type === "say" && msg.say === "user_feedback") - - // Handle UI messages - if (nextUserMessage) { - // Find absolute index of next user message - const nextUserMessageIndex = currentCline.clineMessages.findIndex( - (msg: ClineMessage) => msg === nextUserMessage, - ) - - // Keep messages before current message and after next user message - await currentCline.overwriteClineMessages([ - ...currentCline.clineMessages.slice(0, messageIndex), - ...currentCline.clineMessages.slice(nextUserMessageIndex), - ]) - } else { - // If no next user message, keep only messages before current message - await currentCline.overwriteClineMessages(currentCline.clineMessages.slice(0, messageIndex)) - } - - // Handle API messages - if (apiConversationHistoryIndex !== -1) { - if (nextUserMessage && nextUserMessage.ts) { - // Keep messages before current API message and after next user message - await currentCline.overwriteApiConversationHistory([ - ...currentCline.apiConversationHistory.slice(0, apiConversationHistoryIndex), - ...currentCline.apiConversationHistory.filter( - (msg: ApiMessage) => msg.ts && msg.ts >= nextUserMessage.ts, - ), - ]) - } else { - // If no next user message, keep only messages before current API message - await currentCline.overwriteApiConversationHistory( - currentCline.apiConversationHistory.slice(0, apiConversationHistoryIndex), - ) - } - } - } - /** * Removes the target message and all subsequent messages */ @@ -148,19 +99,19 @@ export const webviewMessageHandler = async ( * Handles message deletion operations with user confirmation */ const handleDeleteOperation = async (messageTs: number): Promise => { - const options = [ - t("common:confirmation.delete_just_this_message"), - t("common:confirmation.delete_this_and_subsequent"), - ] + // Send message to webview to show delete confirmation dialog + await provider.postMessageToWebview({ + type: "showDeleteMessageDialog", + messageTs, + }) + } - const answer = await vscode.window.showInformationMessage( - t("common:confirmation.delete_message"), - { modal: true }, - ...options, - ) - - // Only proceed if user selected one of the options and we have a current cline - if (answer && options.includes(answer) && provider.getCurrentCline()) { + /** + * Handles confirmed message deletion from webview dialog + */ + const handleDeleteMessageConfirm = async (messageTs: number): Promise => { + // Only proceed if we have a current cline + if (provider.getCurrentCline()) { const currentCline = provider.getCurrentCline()! const { messageIndex, apiConversationHistoryIndex } = findMessageIndices(messageTs, currentCline) @@ -168,14 +119,8 @@ export const webviewMessageHandler = async ( try { const { historyItem } = await provider.getTaskWithId(currentCline.taskId) - // Check which option the user selected - if (answer === options[0]) { - // Delete just this message - await removeMessagesJustThis(currentCline, messageIndex, apiConversationHistoryIndex) - } else if (answer === options[1]) { - // Delete this message and all subsequent - await removeMessagesThisAndSubsequent(currentCline, messageIndex, apiConversationHistoryIndex) - } + // Delete this message and all subsequent messages + await removeMessagesThisAndSubsequent(currentCline, messageIndex, apiConversationHistoryIndex) // Initialize with history item after deletion await provider.initClineWithHistoryItem(historyItem) @@ -192,15 +137,26 @@ export const webviewMessageHandler = async ( /** * Handles message editing operations with user confirmation */ - const handleEditOperation = async (messageTs: number, editedContent: string): Promise => { - const answer = await vscode.window.showWarningMessage( - t("common:confirmation.edit_warning"), - { modal: true }, - t("common:confirmation.proceed"), - ) + const handleEditOperation = async (messageTs: number, editedContent: string, images?: string[]): Promise => { + // Send message to webview to show edit confirmation dialog + await provider.postMessageToWebview({ + type: "showEditMessageDialog", + messageTs, + text: editedContent, + images, + }) + } - // Only proceed if user selected "Proceed" and we have a current cline - if (answer === t("common:confirmation.proceed") && provider.getCurrentCline()) { + /** + * Handles confirmed message editing from webview dialog + */ + const handleEditMessageConfirm = async ( + messageTs: number, + editedContent: string, + images?: string[], + ): Promise => { + // Only proceed if we have a current cline + if (provider.getCurrentCline()) { const currentCline = provider.getCurrentCline()! // Use findMessageIndices to find messages based on timestamp @@ -217,6 +173,7 @@ export const webviewMessageHandler = async ( type: "askResponse", askResponse: "messageResponse", text: editedContent, + images, }) // Don't initialize with history item for edit operations @@ -242,11 +199,12 @@ export const webviewMessageHandler = async ( messageTs: number, operation: "delete" | "edit", editedContent?: string, + images?: string[], ): Promise => { if (operation === "delete") { await handleDeleteOperation(messageTs) } else if (operation === "edit" && editedContent) { - await handleEditOperation(messageTs, editedContent) + await handleEditOperation(messageTs, editedContent, images) } } @@ -416,7 +374,12 @@ export const webviewMessageHandler = async ( break case "selectImages": const images = await selectImages() - await provider.postMessageToWebview({ type: "selectedImages", images }) + await provider.postMessageToWebview({ + type: "selectedImages", + images, + context: message.context, + messageTs: message.messageTs, + }) break case "exportCurrentTask": const currentTaskId = provider.getCurrentCline()?.taskId @@ -1209,7 +1172,12 @@ export const webviewMessageHandler = async ( message.value && message.editedMessageContent ) { - await handleMessageModificationsOperation(message.value, "edit", message.editedMessageContent) + await handleMessageModificationsOperation( + message.value, + "edit", + message.editedMessageContent, + message.images, + ) } break } @@ -1542,6 +1510,16 @@ export const webviewMessageHandler = async ( } } break + case "deleteMessageConfirm": + if (message.messageTs) { + await handleDeleteMessageConfirm(message.messageTs) + } + break + case "editMessageConfirm": + if (message.messageTs && message.text) { + await handleEditMessageConfirm(message.messageTs, message.text, message.images) + } + break case "getListApiConfiguration": try { const listApiConfig = await provider.providerSettingsManager.listConfig() diff --git a/src/i18n/locales/ca/common.json b/src/i18n/locales/ca/common.json index 7dac4d7431..772156286e 100644 --- a/src/i18n/locales/ca/common.json +++ b/src/i18n/locales/ca/common.json @@ -21,12 +21,7 @@ "confirmation": { "reset_state": "Estàs segur que vols restablir tots els estats i emmagatzematge secret a l'extensió? Això no es pot desfer.", "delete_config_profile": "Estàs segur que vols eliminar aquest perfil de configuració?", - "delete_custom_mode_with_rules": "Esteu segur que voleu suprimir aquest mode {scope}?\n\nAixò també suprimirà la carpeta de regles associada a:\n{rulesFolderPath}", - "delete_message": "Què vols eliminar?", - "edit_warning": "Editar aquest missatge eliminarà tots els missatges posteriors de la conversa. Vols continuar?", - "delete_just_this_message": "Només aquest missatge", - "delete_this_and_subsequent": "Aquest i tots els missatges posteriors", - "proceed": "Continuar" + "delete_custom_mode_with_rules": "Esteu segur que voleu suprimir aquest mode {scope}?\n\nAixò també suprimirà la carpeta de regles associada a:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Format d'URI de dades no vàlid", diff --git a/src/i18n/locales/de/common.json b/src/i18n/locales/de/common.json index db9ba9b51c..c136fba809 100644 --- a/src/i18n/locales/de/common.json +++ b/src/i18n/locales/de/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Möchtest du wirklich alle Zustände und geheimen Speicher in der Erweiterung zurücksetzen? Dies kann nicht rückgängig gemacht werden.", "delete_config_profile": "Möchtest du dieses Konfigurationsprofil wirklich löschen?", - "delete_custom_mode_with_rules": "Bist du sicher, dass du diesen {scope}-Modus löschen möchtest?\n\nDadurch wird auch der zugehörige Regelordner unter folgender Adresse gelöscht:\n{rulesFolderPath}", - "delete_message": "Was möchtest du löschen?", - "edit_warning": "Das Bearbeiten dieser Nachricht wird alle nachfolgenden Nachrichten in der Unterhaltung löschen. Möchtest du fortfahren?", - "delete_just_this_message": "Nur diese Nachricht", - "delete_this_and_subsequent": "Diese und alle nachfolgenden Nachrichten", - "proceed": "Fortfahren" + "delete_custom_mode_with_rules": "Bist du sicher, dass du diesen {scope}-Modus löschen möchtest?\n\nDadurch wird auch der zugehörige Regelordner unter folgender Adresse gelöscht:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Ungültiges Daten-URI-Format", diff --git a/src/i18n/locales/en/common.json b/src/i18n/locales/en/common.json index 84d3798519..b0fdb9d8df 100644 --- a/src/i18n/locales/en/common.json +++ b/src/i18n/locales/en/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Are you sure you want to reset all state and secret storage in the extension? This cannot be undone.", "delete_config_profile": "Are you sure you want to delete this configuration profile?", - "delete_custom_mode_with_rules": "Are you sure you want to delete this {scope} mode?\n\nThis will also delete the associated rules folder at:\n{rulesFolderPath}", - "delete_message": "What would you like to delete?", - "edit_warning": "Editing this message will delete all subsequent messages in the conversation. Do you want to proceed?", - "delete_just_this_message": "Just this message", - "delete_this_and_subsequent": "This and all subsequent messages", - "proceed": "Proceed" + "delete_custom_mode_with_rules": "Are you sure you want to delete this {scope} mode?\n\nThis will also delete the associated rules folder at:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Invalid data URI format", diff --git a/src/i18n/locales/es/common.json b/src/i18n/locales/es/common.json index cdd26831a5..39cf48383e 100644 --- a/src/i18n/locales/es/common.json +++ b/src/i18n/locales/es/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "¿Estás seguro de que deseas restablecer todo el estado y el almacenamiento secreto en la extensión? Esta acción no se puede deshacer.", "delete_config_profile": "¿Estás seguro de que deseas eliminar este perfil de configuración?", - "delete_custom_mode_with_rules": "¿Estás seguro de que quieres eliminar este modo {scope}?\n\nEsto también eliminará la carpeta de reglas asociada en:\n{rulesFolderPath}", - "delete_message": "¿Qué deseas eliminar?", - "edit_warning": "Editar este mensaje eliminará todos los mensajes posteriores en la conversación. ¿Deseas continuar?", - "delete_just_this_message": "Solo este mensaje", - "delete_this_and_subsequent": "Este y todos los mensajes posteriores", - "proceed": "Continuar" + "delete_custom_mode_with_rules": "¿Estás seguro de que quieres eliminar este modo {scope}?\n\nEsto también eliminará la carpeta de reglas asociada en:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Formato de URI de datos no válido", diff --git a/src/i18n/locales/fr/common.json b/src/i18n/locales/fr/common.json index 3ddacdda59..ace5bbe47a 100644 --- a/src/i18n/locales/fr/common.json +++ b/src/i18n/locales/fr/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Êtes-vous sûr de vouloir réinitialiser le global state et le stockage de secrets de l'extension ? Cette action est irréversible.", "delete_config_profile": "Êtes-vous sûr de vouloir supprimer ce profil de configuration ?", - "delete_custom_mode_with_rules": "Êtes-vous sûr de vouloir supprimer ce mode {scope} ?\n\nCela supprimera également le dossier de règles associé à l'adresse :\n{rulesFolderPath}", - "delete_message": "Que souhaitez-vous supprimer ?", - "edit_warning": "Modifier ce message supprimera tous les messages suivants dans la conversation. Voulez-vous continuer ?", - "delete_just_this_message": "Uniquement ce message", - "delete_this_and_subsequent": "Ce message et tous les messages suivants", - "proceed": "Continuer" + "delete_custom_mode_with_rules": "Êtes-vous sûr de vouloir supprimer ce mode {scope} ?\n\nCela supprimera également le dossier de règles associé à l'adresse :\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Format d'URI de données invalide", diff --git a/src/i18n/locales/hi/common.json b/src/i18n/locales/hi/common.json index 8637426846..84dbe9052a 100644 --- a/src/i18n/locales/hi/common.json +++ b/src/i18n/locales/hi/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "क्या आप वाकई एक्सटेंशन में सभी स्टेट और गुप्त स्टोरेज रीसेट करना चाहते हैं? इसे पूर्ववत नहीं किया जा सकता है।", "delete_config_profile": "क्या आप वाकई इस कॉन्फ़िगरेशन प्रोफ़ाइल को हटाना चाहते हैं?", - "delete_custom_mode_with_rules": "क्या आप वाकई इस {scope} मोड को हटाना चाहते हैं?\n\nयह संबंधित नियम फ़ोल्डर को भी यहाँ हटा देगा:\n{rulesFolderPath}", - "delete_message": "आप क्या हटाना चाहते हैं?", - "edit_warning": "इस संदेश को संपादित करने से बातचीत के सभी बाद के संदेश हट जाएंगे। क्या आप जारी रखना चाहते हैं?", - "delete_just_this_message": "सिर्फ यह संदेश", - "delete_this_and_subsequent": "यह और सभी बाद के संदेश", - "proceed": "जारी रखें" + "delete_custom_mode_with_rules": "क्या आप वाकई इस {scope} मोड को हटाना चाहते हैं?\n\nयह संबंधित नियम फ़ोल्डर को भी यहाँ हटा देगा:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "अमान्य डेटा URI फॉर्मेट", diff --git a/src/i18n/locales/id/common.json b/src/i18n/locales/id/common.json index df3fe2cefb..fb2a30994e 100644 --- a/src/i18n/locales/id/common.json +++ b/src/i18n/locales/id/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Apakah kamu yakin ingin mereset semua state dan secret storage di ekstensi? Ini tidak dapat dibatalkan.", "delete_config_profile": "Apakah kamu yakin ingin menghapus profil konfigurasi ini?", - "delete_custom_mode_with_rules": "Anda yakin ingin menghapus mode {scope} ini?\n\nIni juga akan menghapus folder aturan terkait di:\n{rulesFolderPath}", - "delete_message": "Apa yang ingin kamu hapus?", - "edit_warning": "Mengedit pesan ini akan menghapus semua pesan selanjutnya dalam percakapan. Apakah kamu ingin melanjutkan?", - "delete_just_this_message": "Hanya pesan ini", - "delete_this_and_subsequent": "Ini dan semua pesan selanjutnya", - "proceed": "Lanjutkan" + "delete_custom_mode_with_rules": "Anda yakin ingin menghapus mode {scope} ini?\n\nIni juga akan menghapus folder aturan terkait di:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Format data URI tidak valid", diff --git a/src/i18n/locales/it/common.json b/src/i18n/locales/it/common.json index d12e376c0c..4681612e9d 100644 --- a/src/i18n/locales/it/common.json +++ b/src/i18n/locales/it/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Sei sicuro di voler reimpostare tutti gli stati e l'archiviazione segreta nell'estensione? Questa azione non può essere annullata.", "delete_config_profile": "Sei sicuro di voler eliminare questo profilo di configurazione?", - "delete_custom_mode_with_rules": "Sei sicuro di voler eliminare questa modalità {scope}?\n\nQuesto eliminerà anche la cartella delle regole associata in:\n{rulesFolderPath}", - "delete_message": "Cosa desideri eliminare?", - "edit_warning": "Modificare questo messaggio eliminerà tutti i messaggi successivi nella conversazione. Vuoi continuare?", - "delete_just_this_message": "Solo questo messaggio", - "delete_this_and_subsequent": "Questo e tutti i messaggi successivi", - "proceed": "Continua" + "delete_custom_mode_with_rules": "Sei sicuro di voler eliminare questa modalità {scope}?\n\nQuesto eliminerà anche la cartella delle regole associata in:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Formato URI dati non valido", diff --git a/src/i18n/locales/ja/common.json b/src/i18n/locales/ja/common.json index 56be64c44c..38fc9d27c5 100644 --- a/src/i18n/locales/ja/common.json +++ b/src/i18n/locales/ja/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "拡張機能のすべての状態とシークレットストレージをリセットしてもよろしいですか?この操作は元に戻せません。", "delete_config_profile": "この設定プロファイルを削除してもよろしいですか?", - "delete_custom_mode_with_rules": "この{scope}モードを削除してもよろしいですか?\n\nこれにより、関連するルールフォルダも次の場所で削除されます:\n{rulesFolderPath}", - "delete_message": "何を削除しますか?", - "edit_warning": "このメッセージを編集すると、会話内のすべての後続メッセージが削除されます。続行しますか?", - "delete_just_this_message": "このメッセージのみ", - "delete_this_and_subsequent": "これ以降のすべてのメッセージ", - "proceed": "続行" + "delete_custom_mode_with_rules": "この{scope}モードを削除してもよろしいですか?\n\nこれにより、関連するルールフォルダも次の場所で削除されます:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "データURIフォーマットが無効です", diff --git a/src/i18n/locales/ko/common.json b/src/i18n/locales/ko/common.json index 0b12455c0f..d76a82a7c2 100644 --- a/src/i18n/locales/ko/common.json +++ b/src/i18n/locales/ko/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "확장 프로그램의 모든 상태와 보안 저장소를 재설정하시겠습니까? 이 작업은 취소할 수 없습니다.", "delete_config_profile": "이 구성 프로필을 삭제하시겠습니까?", - "delete_custom_mode_with_rules": "이 {scope} 모드를 삭제하시겠습니까?\n\n이렇게 하면 연결된 규칙 폴더도 다음 위치에서 삭제됩니다:\n{rulesFolderPath}", - "delete_message": "무엇을 삭제하시겠습니까?", - "edit_warning": "이 메시지를 편집하면 대화의 모든 후속 메시지가 삭제됩니다. 계속하시겠습니까?", - "delete_just_this_message": "이 메시지만", - "delete_this_and_subsequent": "이 메시지와 모든 후속 메시지", - "proceed": "계속" + "delete_custom_mode_with_rules": "이 {scope} 모드를 삭제하시겠습니까?\n\n이렇게 하면 연결된 규칙 폴더도 다음 위치에서 삭제됩니다:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "잘못된 데이터 URI 형식", diff --git a/src/i18n/locales/nl/common.json b/src/i18n/locales/nl/common.json index 43fda70dc2..5caa0534ee 100644 --- a/src/i18n/locales/nl/common.json +++ b/src/i18n/locales/nl/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Weet je zeker dat je alle status en geheime opslag in de extensie wilt resetten? Dit kan niet ongedaan worden gemaakt.", "delete_config_profile": "Weet je zeker dat je dit configuratieprofiel wilt verwijderen?", - "delete_custom_mode_with_rules": "Weet je zeker dat je deze {scope}-modus wilt verwijderen?\n\nDit verwijdert ook de bijbehorende regelsmap op:\n{rulesFolderPath}", - "delete_message": "Wat wil je verwijderen?", - "delete_just_this_message": "Alleen dit bericht", - "delete_this_and_subsequent": "Dit en alle volgende berichten", - "edit_warning": "Het bewerken van dit bericht zal alle volgende berichten in het gesprek verwijderen. Wil je doorgaan?", - "proceed": "Doorgaan" + "delete_custom_mode_with_rules": "Weet je zeker dat je deze {scope}-modus wilt verwijderen?\n\nDit verwijdert ook de bijbehorende regelsmap op:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Ongeldig data-URI-formaat", diff --git a/src/i18n/locales/pl/common.json b/src/i18n/locales/pl/common.json index 80a299c7df..77008aa0ab 100644 --- a/src/i18n/locales/pl/common.json +++ b/src/i18n/locales/pl/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Czy na pewno chcesz zresetować wszystkie stany i tajne magazyny w rozszerzeniu? Tej operacji nie można cofnąć.", "delete_config_profile": "Czy na pewno chcesz usunąć ten profil konfiguracyjny?", - "delete_custom_mode_with_rules": "Czy na pewno chcesz usunąć ten tryb {scope}?\n\nSpowoduje to również usunięcie powiązanego folderu reguł pod adresem:\n{rulesFolderPath}", - "delete_message": "Co chcesz usunąć?", - "delete_just_this_message": "Tylko tę wiadomość", - "delete_this_and_subsequent": "Tę i wszystkie kolejne wiadomości", - "edit_warning": "Edytowanie tej wiadomości usunie wszystkie kolejne wiadomości w rozmowie. Czy chcesz kontynuować?", - "proceed": "Kontynuuj" + "delete_custom_mode_with_rules": "Czy na pewno chcesz usunąć ten tryb {scope}?\n\nSpowoduje to również usunięcie powiązanego folderu reguł pod adresem:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Nieprawidłowy format URI danych", diff --git a/src/i18n/locales/pt-BR/common.json b/src/i18n/locales/pt-BR/common.json index 6205a5fb7a..6f63d9d1ed 100644 --- a/src/i18n/locales/pt-BR/common.json +++ b/src/i18n/locales/pt-BR/common.json @@ -21,12 +21,7 @@ "confirmation": { "reset_state": "Tem certeza de que deseja redefinir todo o estado e armazenamento secreto na extensão? Isso não pode ser desfeito.", "delete_config_profile": "Tem certeza de que deseja excluir este perfil de configuração?", - "delete_custom_mode_with_rules": "Tem certeza de que deseja excluir este modo {scope}?\n\nIsso também excluirá a pasta de regras associada em:\n{rulesFolderPath}", - "delete_message": "O que você gostaria de excluir?", - "delete_just_this_message": "Apenas esta mensagem", - "delete_this_and_subsequent": "Esta e todas as mensagens subsequentes", - "edit_warning": "Editar esta mensagem excluirá todas as mensagens subsequentes na conversa. Deseja continuar?", - "proceed": "Continuar" + "delete_custom_mode_with_rules": "Tem certeza de que deseja excluir este modo {scope}?\n\nIsso também excluirá a pasta de regras associada em:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Formato de URI de dados inválido", diff --git a/src/i18n/locales/ru/common.json b/src/i18n/locales/ru/common.json index f537d1a2d3..4e354bcbc5 100644 --- a/src/i18n/locales/ru/common.json +++ b/src/i18n/locales/ru/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Вы уверены, что хотите сбросить все состояние и секретное хранилище в расширении? Это действие нельзя отменить.", "delete_config_profile": "Вы уверены, что хотите удалить этот профиль конфигурации?", - "delete_custom_mode_with_rules": "Вы уверены, что хотите удалить этот режим {scope}?\n\nЭто также приведет к удалению соответствующей папки правил по адресу:\n{rulesFolderPath}", - "delete_message": "Что вы хотите удалить?", - "delete_just_this_message": "Только это сообщение", - "delete_this_and_subsequent": "Это и все последующие сообщения", - "edit_warning": "Редактирование этого сообщения удалит все последующие сообщения в разговоре. Хотите продолжить?", - "proceed": "Продолжить" + "delete_custom_mode_with_rules": "Вы уверены, что хотите удалить этот режим {scope}?\n\nЭто также приведет к удалению соответствующей папки правил по адресу:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Неверный формат URI данных", diff --git a/src/i18n/locales/tr/common.json b/src/i18n/locales/tr/common.json index 61e244186e..5de82d00c6 100644 --- a/src/i18n/locales/tr/common.json +++ b/src/i18n/locales/tr/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Uzantıdaki tüm durumları ve gizli depolamayı sıfırlamak istediğinizden emin misiniz? Bu işlem geri alınamaz.", "delete_config_profile": "Bu yapılandırma profilini silmek istediğinizden emin misiniz?", - "delete_custom_mode_with_rules": "Bu {scope} modunu silmek istediğinizden emin misiniz?\n\nBu işlem, ilişkili kurallar klasörünü de şu konumdan silecektir:\n{rulesFolderPath}", - "delete_message": "Neyi silmek istersiniz?", - "delete_just_this_message": "Sadece bu mesajı", - "delete_this_and_subsequent": "Bu ve sonraki tüm mesajları", - "edit_warning": "Bu mesajı düzenlemek konuşmadaki tüm sonraki mesajları silecektir. Devam etmek istiyor musunuz?", - "proceed": "Devam et" + "delete_custom_mode_with_rules": "Bu {scope} modunu silmek istediğinizden emin misiniz?\n\nBu işlem, ilişkili kurallar klasörünü de şu konumdan silecektir:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Geçersiz veri URI formatı", diff --git a/src/i18n/locales/vi/common.json b/src/i18n/locales/vi/common.json index 6106f71fa0..014bddda58 100644 --- a/src/i18n/locales/vi/common.json +++ b/src/i18n/locales/vi/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "Bạn có chắc chắn muốn đặt lại tất cả trạng thái và lưu trữ bí mật trong tiện ích mở rộng không? Hành động này không thể hoàn tác.", "delete_config_profile": "Bạn có chắc chắn muốn xóa hồ sơ cấu hình này không?", - "delete_custom_mode_with_rules": "Bạn có chắc chắn muốn xóa chế độ {scope} này không?\n\nThao tác này cũng sẽ xóa thư mục quy tắc liên quan tại:\n{rulesFolderPath}", - "delete_message": "Bạn muốn xóa gì?", - "delete_just_this_message": "Chỉ tin nhắn này", - "delete_this_and_subsequent": "Tin nhắn này và tất cả tin nhắn tiếp theo", - "edit_warning": "Chỉnh sửa tin nhắn này sẽ xóa tất cả tin nhắn tiếp theo trong cuộc trò chuyện. Bạn có muốn tiếp tục không?", - "proceed": "Tiếp tục" + "delete_custom_mode_with_rules": "Bạn có chắc chắn muốn xóa chế độ {scope} này không?\n\nThao tác này cũng sẽ xóa thư mục quy tắc liên quan tại:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "Định dạng URI dữ liệu không hợp lệ", diff --git a/src/i18n/locales/zh-CN/common.json b/src/i18n/locales/zh-CN/common.json index a629ba6507..268ee5fbb1 100644 --- a/src/i18n/locales/zh-CN/common.json +++ b/src/i18n/locales/zh-CN/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "您确定要重置扩展中的所有状态和密钥存储吗?此操作无法撤消。", "delete_config_profile": "您确定要删除此配置文件吗?", - "delete_custom_mode_with_rules": "您确定要删除此 {scope} 模式吗?\n\n这也将删除位于以下位置的关联规则文件夹:\n{rulesFolderPath}", - "delete_message": "您想删除什么?", - "edit_warning": "编辑此消息将删除对话中的所有后续消息。您要继续吗?", - "delete_just_this_message": "仅此消息", - "delete_this_and_subsequent": "此消息及所有后续消息", - "proceed": "继续" + "delete_custom_mode_with_rules": "您确定要删除此 {scope} 模式吗?\n\n这也将删除位于以下位置的关联规则文件夹:\n{rulesFolderPath}" }, "errors": { "invalid_mcp_config": "项目MCP配置格式无效", diff --git a/src/i18n/locales/zh-TW/common.json b/src/i18n/locales/zh-TW/common.json index 48a37c1438..dec20a1f9a 100644 --- a/src/i18n/locales/zh-TW/common.json +++ b/src/i18n/locales/zh-TW/common.json @@ -17,12 +17,7 @@ "confirmation": { "reset_state": "您確定要重設擴充套件中的所有狀態和金鑰儲存嗎?此操作無法復原。", "delete_config_profile": "您確定要刪除此設定檔案嗎?", - "delete_custom_mode_with_rules": "您確定要刪除此 {scope} 模式嗎?\n\n這也將刪除位於以下位置的關聯規則資料夾:\n{rulesFolderPath}", - "delete_message": "您想刪除哪些內容?", - "edit_warning": "編輯此訊息將刪除對話中的所有後續訊息。您要繼續嗎?", - "delete_just_this_message": "僅這則訊息", - "delete_this_and_subsequent": "這則訊息及所有後續訊息", - "proceed": "繼續" + "delete_custom_mode_with_rules": "您確定要刪除此 {scope} 模式嗎?\n\n這也將刪除位於以下位置的關聯規則資料夾:\n{rulesFolderPath}" }, "errors": { "invalid_data_uri": "資料 URI 格式無效", diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index 833c51336b..98f3aa7d29 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -105,6 +105,8 @@ export interface ExtensionMessage { | "shareTaskSuccess" | "codeIndexSettingsSaved" | "codeIndexSecretStatus" + | "showDeleteMessageDialog" + | "showEditMessageDialog" text?: string payload?: any // Add a generic payload for now, can refine later action?: @@ -157,6 +159,8 @@ export interface ExtensionMessage { visibility?: ShareVisibility rulesFolderPath?: string settings?: any + messageTs?: number + context?: string } export type ExtensionState = Pick< diff --git a/src/shared/WebviewMessage.ts b/src/shared/WebviewMessage.ts index d5dc3f8c28..5d6ec0f41c 100644 --- a/src/shared/WebviewMessage.ts +++ b/src/shared/WebviewMessage.ts @@ -111,7 +111,9 @@ export interface WebviewMessage { | "enhancedPrompt" | "draggedImages" | "deleteMessage" + | "deleteMessageConfirm" | "submitEditedMessage" + | "editMessageConfirm" | "terminalOutputLineLimit" | "terminalShellIntegrationTimeout" | "terminalShellIntegrationDisabled" @@ -198,6 +200,7 @@ export interface WebviewMessage { editedMessageContent?: string tab?: "settings" | "history" | "mcp" | "modes" | "chat" | "marketplace" | "account" disabled?: boolean + context?: string dataUri?: string askResponse?: ClineAskResponse apiConfiguration?: ProviderSettings @@ -226,6 +229,7 @@ export interface WebviewMessage { ids?: string[] hasSystemPromptOverride?: boolean terminalOperation?: "continue" | "abort" + messageTs?: number historyPreviewCollapsed?: boolean filters?: { type?: string; search?: string; tags?: string[] } url?: string // For openExternal diff --git a/webview-ui/src/App.tsx b/webview-ui/src/App.tsx index 332ef18511..3c4c14f5df 100644 --- a/webview-ui/src/App.tsx +++ b/webview-ui/src/App.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState, useMemo } from "react" +import React, { useCallback, useEffect, useRef, useState, useMemo } from "react" import { useEvent } from "react-use" import { QueryClient, QueryClientProvider } from "@tanstack/react-query" @@ -18,6 +18,7 @@ import McpView from "./components/mcp/McpView" import { MarketplaceView } from "./components/marketplace/MarketplaceView" import ModesView from "./components/modes/ModesView" import { HumanRelayDialog } from "./components/human-relay/HumanRelayDialog" +import { DeleteMessageDialog, EditMessageDialog } from "./components/chat/MessageModificationConfirmationDialog" import { AccountView } from "./components/account/AccountView" import { useAddNonInteractiveClickListener } from "./components/ui/hooks/useNonInteractiveClick" import { TooltipProvider } from "./components/ui/tooltip" @@ -25,6 +26,29 @@ import { STANDARD_TOOLTIP_DELAY } from "./components/ui/standard-tooltip" type Tab = "settings" | "history" | "mcp" | "modes" | "chat" | "marketplace" | "account" +interface HumanRelayDialogState { + isOpen: boolean + requestId: string + promptText: string +} + +interface DeleteMessageDialogState { + isOpen: boolean + messageTs: number +} + +interface EditMessageDialogState { + isOpen: boolean + messageTs: number + text: string + images?: string[] +} + +// Memoize dialog components to prevent unnecessary re-renders +const MemoizedDeleteMessageDialog = React.memo(DeleteMessageDialog) +const MemoizedEditMessageDialog = React.memo(EditMessageDialog) +const MemoizedHumanRelayDialog = React.memo(HumanRelayDialog) + const tabsByMessageAction: Partial, Tab>> = { chatButtonClicked: "chat", settingsButtonClicked: "settings", @@ -56,16 +80,24 @@ const App = () => { const [showAnnouncement, setShowAnnouncement] = useState(false) const [tab, setTab] = useState("chat") - const [humanRelayDialogState, setHumanRelayDialogState] = useState<{ - isOpen: boolean - requestId: string - promptText: string - }>({ + const [humanRelayDialogState, setHumanRelayDialogState] = useState({ isOpen: false, requestId: "", promptText: "", }) + const [deleteMessageDialogState, setDeleteMessageDialogState] = useState({ + isOpen: false, + messageTs: 0, + }) + + const [editMessageDialogState, setEditMessageDialogState] = useState({ + isOpen: false, + messageTs: 0, + text: "", + images: [], + }) + const settingsRef = useRef(null) const chatViewRef = useRef(null) @@ -121,6 +153,19 @@ const App = () => { setHumanRelayDialogState({ isOpen: true, requestId, promptText }) } + if (message.type === "showDeleteMessageDialog" && message.messageTs) { + setDeleteMessageDialogState({ isOpen: true, messageTs: message.messageTs }) + } + + if (message.type === "showEditMessageDialog" && message.messageTs && message.text) { + setEditMessageDialogState({ + isOpen: true, + messageTs: message.messageTs, + text: message.text, + images: message.images || [], + }) + } + if (message.type === "acceptInput") { chatViewRef.current?.acceptInput() } @@ -199,7 +244,7 @@ const App = () => { showAnnouncement={showAnnouncement} hideAnnouncement={() => setShowAnnouncement(false)} /> - { onSubmit={(requestId, text) => vscode.postMessage({ type: "humanRelayResponse", requestId, text })} onCancel={(requestId) => vscode.postMessage({ type: "humanRelayCancel", requestId })} /> + setDeleteMessageDialogState((prev) => ({ ...prev, isOpen: open }))} + onConfirm={() => { + vscode.postMessage({ + type: "deleteMessageConfirm", + messageTs: deleteMessageDialogState.messageTs, + }) + setDeleteMessageDialogState((prev) => ({ ...prev, isOpen: false })) + }} + /> + setEditMessageDialogState((prev) => ({ ...prev, isOpen: open }))} + onConfirm={() => { + vscode.postMessage({ + type: "editMessageConfirm", + messageTs: editMessageDialogState.messageTs, + text: editMessageDialogState.text, + images: editMessageDialogState.images, + }) + setEditMessageDialogState((prev) => ({ ...prev, isOpen: false })) + }} + /> ) } diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index c508f7e906..926bd400f0 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -1,4 +1,5 @@ import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react" +import { appendImages } from "@src/utils/imageUtils" import { McpExecution } from "./McpExecution" import { useSize } from "react-use" import { useTranslation, Trans } from "react-i18next" @@ -6,6 +7,7 @@ import deepEqual from "fast-deep-equal" import { VSCodeBadge, VSCodeButton } from "@vscode/webview-ui-toolkit/react" import type { ClineMessage } from "@roo-code/types" +import { Mode } from "@roo/modes" import { ClineApiReqInfo, ClineAskUseMcpServer, ClineSayTool } from "@roo/ExtensionMessage" import { COMMAND_OUTPUT_STRING } from "@roo/combineCommandSequences" @@ -20,6 +22,9 @@ import { removeLeadingNonAlphanumeric } from "@src/utils/removeLeadingNonAlphanu import { getLanguageFromPath } from "@src/utils/getLanguageFromPath" import { Button } from "@src/components/ui" +import ChatTextArea from "./ChatTextArea" +import { MAX_IMAGES_PER_MESSAGE } from "./ChatView" + import { ToolUseBlock, ToolUseBlockHeader } from "../common/ToolUseBlock" import UpdateTodoListToolBlock from "./UpdateTodoListToolBlock" import CodeAccordian from "../common/CodeAccordian" @@ -109,14 +114,29 @@ export const ChatRowContent = ({ editable, }: ChatRowContentProps) => { const { t } = useTranslation() - const { mcpServers, alwaysAllowMcp, currentCheckpoint } = useExtensionState() + const { mcpServers, alwaysAllowMcp, currentCheckpoint, mode } = useExtensionState() const [reasoningCollapsed, setReasoningCollapsed] = useState(true) const [isDiffErrorExpanded, setIsDiffErrorExpanded] = useState(false) const [showCopySuccess, setShowCopySuccess] = useState(false) const [isEditing, setIsEditing] = useState(false) const [editedContent, setEditedContent] = useState("") + const [editMode, setEditMode] = useState(mode || "code") + const [editImages, setEditImages] = useState([]) const { copyWithFeedback } = useCopyToClipboard() + // Handle message events for image selection during edit mode + useEffect(() => { + const handleMessage = (event: MessageEvent) => { + const msg = event.data + if (msg.type === "selectedImages" && msg.context === "edit" && msg.messageTs === message.ts && isEditing) { + setEditImages((prevImages) => appendImages(prevImages, msg.images, MAX_IMAGES_PER_MESSAGE)) + } + } + + window.addEventListener("message", handleMessage) + return () => window.removeEventListener("message", handleMessage) + }, [isEditing, message.ts]) + // Memoized callback to prevent re-renders caused by inline arrow functions const handleToggleExpand = useCallback(() => { onToggleExpand(message.ts) @@ -126,15 +146,19 @@ export const ChatRowContent = ({ const handleEditClick = useCallback(() => { setIsEditing(true) setEditedContent(message.text || "") + setEditImages(message.images || []) + setEditMode(mode || "code") // Edit mode is now handled entirely in the frontend // No need to notify the backend - }, [message.text]) + }, [message.text, message.images, mode]) // Handle cancel edit const handleCancelEdit = useCallback(() => { setIsEditing(false) setEditedContent(message.text || "") - }, [message.text]) + setEditImages(message.images || []) + setEditMode(mode || "code") + }, [message.text, message.images, mode]) // Handle save edit const handleSaveEdit = useCallback(() => { @@ -144,8 +168,14 @@ export const ChatRowContent = ({ type: "submitEditedMessage", value: message.ts, editedMessageContent: editedContent, + images: editImages, }) - }, [message.ts, editedContent]) + }, [message.ts, editedContent, editImages]) + + // Handle image selection for editing + const handleSelectImages = useCallback(() => { + vscode.postMessage({ type: "selectImages", context: "edit", messageTs: message.ts }) + }, [message.ts]) const [cost, apiReqCancelReason, apiReqStreamingFailedMessage] = useMemo(() => { if (message.text !== null && message.text !== undefined && message.say === "api_req_started") { @@ -1032,21 +1062,23 @@ export const ChatRowContent = ({
{isEditing ? (
-