From bfa86b086ffade654a05c87b266d7853b2036008 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Wed, 14 Oct 2026 09:17:50 +0200 Subject: [PATCH 01/52] fix: enforce and persist workspace-scoped auto-approve command lists (#1939) Workspace-scope zoo-code.allowedCommands/deniedCommands settings were never enforced, and saving the auto-approve dialog flattened the merged dialog list into user-global settings, leaking project entries into every workspace. Activation additionally seeded global state from the effective config, permanently copying workspace overrides into global settings. - Read/enforcement: new src/core/auto-approval/commandScope.ts unions the extension global-state layer with the workspace layer from inspect().workspaceFolderValue ?? workspaceValue; ClineProvider.getState() and getStateToPostToWebview() share the same merged value so enforcement and display cannot drift (old mergeCommandLists deleted). - Write/scope-leak: splitCommandListScopes() + resolveWorkspaceWriteTarget() keep workspace entries in their folder/workspace scope, route new entries to Global, remove deleted entries from the owning scope, and persist only the global layer to extension global state. - Activation seed leak: seedAllowedCommands.ts reads inspect().globalValue only, so workspace overrides are no longer folded into (and copied permanently to) global state at activation. - Dead code: remove vestigial allowedCommands/deniedCommands webview message handlers (zero senders), their WebviewMessage union members, and the orphaned commands payload. Closes #1939 --- packages/types/src/vscode-extension-host.ts | 3 - src/__tests__/extension.spec.ts | 71 ++++- .../__tests__/commandScope.spec.ts | 247 ++++++++++++++++++ src/core/auto-approval/commandScope.ts | 139 ++++++++++ src/core/webview/ClineProvider.ts | 73 +----- .../webview/__tests__/ClineProvider.spec.ts | 69 +++++ .../__tests__/webviewMessageHandler.spec.ts | 90 +++++++ src/core/webview/webviewMessageHandler.ts | 80 +++--- src/extension.ts | 9 +- .../__tests__/seedAllowedCommands.spec.ts | 121 +++++++++ src/utils/seedAllowedCommands.ts | 40 +++ 11 files changed, 824 insertions(+), 118 deletions(-) create mode 100644 src/core/auto-approval/__tests__/commandScope.spec.ts create mode 100644 src/core/auto-approval/commandScope.ts create mode 100644 src/utils/__tests__/seedAllowedCommands.spec.ts create mode 100644 src/utils/seedAllowedCommands.ts diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 2f1222f8ee..95316f5e74 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -603,9 +603,7 @@ export interface WebviewMessage { | "getDismissedUpsells" | "openMarkdownPreview" | "updateSettings" - | "allowedCommands" | "getTaskWithAggregatedCosts" - | "deniedCommands" | "openDebugApiHistory" | "openDebugUiHistory" | "downloadErrorDiagnostics" @@ -662,7 +660,6 @@ export interface WebviewMessage { stepIndex?: number isLaunchAction?: boolean forceShow?: boolean - commands?: string[] audioType?: AudioType serverName?: string toolName?: string diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index d0a8b274b8..ba8c885c0a 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -18,6 +18,7 @@ vi.mock("vscode", () => ({ registerTextDocumentContentProvider: vi.fn(), getConfiguration: vi.fn().mockReturnValue({ get: vi.fn().mockReturnValue([]), + inspect: vi.fn(), }), createFileSystemWatcher: vi.fn().mockReturnValue({ onDidCreate: vi.fn(), @@ -222,15 +223,17 @@ vi.mock("../api/providers/fetchers/modelCache", () => ({ describe("extension.ts", () => { let mockContext: vscode.ExtensionContext + let globalStateValues: Map let settingsUpdatedHandler: ((data: Record) => void | Promise) | undefined beforeEach(() => { vi.clearAllMocks() + globalStateValues = new Map() mockContext = { extensionPath: "/test/path", globalState: { - get: vi.fn().mockReturnValue(undefined), + get: vi.fn((key: string) => globalStateValues.get(key)), update: vi.fn(), }, subscriptions: [], @@ -404,6 +407,72 @@ describe("extension.ts", () => { expect(dotenv.config).toHaveBeenCalledTimes(1) }) + describe("allowedCommands activation seeding", () => { + function setConfigScope( + vscode: typeof import("vscode"), + scope: { globalValue?: string[]; workspaceValue?: string[] }, + ) { + const { globalValue, workspaceValue } = scope + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + // Key-scoped so proxy/other activation reads still see no value. + get: vi.fn((key: string) => + key === "allowedCommands" ? [...(globalValue ?? []), ...(workspaceValue ?? [])] : undefined, + ), + inspect: vi.fn().mockReturnValue({ + key: "allowedCommands", + globalValue, + workspaceValue, + }), + update: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) + } + + beforeEach(() => { + vi.resetModules() + }) + + afterEach(async () => { + const vscode = await import("vscode") + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn().mockReturnValue([]), + inspect: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) + }) + + test("does not seed global state from a workspace-scoped override", async () => { + const vscode = await import("vscode") + setConfigScope(vscode, { workspaceValue: ["docker"] }) + + const { activate } = await import("../extension") + await activate(mockContext) + + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("allowedCommands", expect.anything()) + expect(globalStateValues.get("allowedCommands")).toBeUndefined() + }) + + test("seeds global state from the user-scoped value when it is empty", async () => { + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"] }) + + const { activate } = await import("../extension") + await activate(mockContext) + + expect(mockContext.globalState.update).toHaveBeenCalledWith("allowedCommands", ["git"]) + }) + + test("does not overwrite global state that is already populated", async () => { + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"] }) + globalStateValues.set("allowedCommands", ["npm"]) + + const { activate } = await import("../extension") + await activate(mockContext) + + expect(mockContext.globalState.update).not.toHaveBeenCalledWith("allowedCommands", expect.anything()) + expect(globalStateValues.get("allowedCommands")).toEqual(["npm"]) + }) + }) + describe("cloud organization settings handling", () => { beforeEach(() => { vi.resetModules() diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts new file mode 100644 index 0000000000..7784c4a1bd --- /dev/null +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -0,0 +1,247 @@ +import * as vscode from "vscode" + +import { readCommandListScopes, resolveWorkspaceWriteTarget, splitCommandListScopes } from "../commandScope" + +vi.mock("vscode", () => ({ + ConfigurationTarget: { + Global: 1, + Workspace: 2, + WorkspaceFolder: 3, + }, + workspace: { + getConfiguration: vi.fn(), + }, +})) + +interface ConfigDouble { + inspect?: { + key: string + defaultValue?: string[] + globalValue?: string[] + workspaceValue?: string[] + workspaceFolderValue?: string[] + } + effective?: string[] +} + +function mockConfiguration({ inspect, effective = [] }: ConfigDouble = {}) { + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn().mockReturnValue(effective), + inspect: vi.fn().mockReturnValue(inspect), + update: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) +} + +describe("readCommandListScopes", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("reads the workspace layer from the workspace-scoped configuration value", () => { + mockConfiguration({ inspect: { key: "deniedCommands", workspaceValue: ["docker"] } }) + + const scopes = readCommandListScopes("deniedCommands", []) + + expect(scopes.workspace).toEqual(["docker"]) + expect(scopes.merged).toEqual(["docker"]) + }) + + it("prefers the workspace-folder value over the workspace value", () => { + mockConfiguration({ + inspect: { + key: "deniedCommands", + workspaceValue: ["docker"], + workspaceFolderValue: ["pnpm docker"], + }, + }) + + const scopes = readCommandListScopes("deniedCommands", []) + + expect(scopes.workspace).toEqual(["pnpm docker"]) + expect(scopes.merged).toEqual(["pnpm docker"]) + }) + + it("ignores the effective get() value so global-scoped entries are not double-counted", () => { + // A real VS Code get() folds globalValue into the effective result, so + // reading the workspace layer from get() would leak "npm" (a + // user-settings-only entry) into the workspace layer. + mockConfiguration({ + inspect: { key: "allowedCommands", globalValue: ["npm"], workspaceValue: ["docker"] }, + effective: ["npm", "docker"], + }) + + const scopes = readCommandListScopes("allowedCommands", []) + + expect(scopes.workspace).toEqual(["docker"]) + expect(scopes.merged).toEqual(["docker"]) + }) + + it("returns an empty workspace layer when only globalValue is set", () => { + mockConfiguration({ + inspect: { key: "allowedCommands", globalValue: ["npm"] }, + effective: ["npm"], + }) + + const scopes = readCommandListScopes("allowedCommands", []) + + expect(scopes.workspace).toEqual([]) + expect(scopes.merged).toEqual([]) + }) + + it("unions global and workspace layers with deduplication and stable order", () => { + mockConfiguration({ inspect: { key: "deniedCommands", workspaceValue: ["docker", "rm"] } }) + + const scopes = readCommandListScopes("deniedCommands", ["git", "docker"]) + + expect(scopes.global).toEqual(["git", "docker"]) + expect(scopes.workspace).toEqual(["docker", "rm"]) + expect(scopes.merged).toEqual(["git", "docker", "rm"]) + }) + + it("drops blank and non-string entries from both layers", () => { + mockConfiguration({ inspect: { key: "deniedCommands", workspaceValue: ["docker", " "] } }) + + const scopes = readCommandListScopes("deniedCommands", ["git", "", " "] as string[]) + + expect(scopes.global).toEqual(["git"]) + expect(scopes.workspace).toEqual(["docker"]) + expect(scopes.merged).toEqual(["git", "docker"]) + }) + + it("treats a missing inspect result as an empty workspace layer", () => { + mockConfiguration({ inspect: undefined }) + + const scopes = readCommandListScopes("deniedCommands", ["git"]) + + expect(scopes.workspace).toEqual([]) + expect(scopes.merged).toEqual(["git"]) + }) + + it("falls back to an empty workspace layer when the configuration lookup throws", () => { + vi.mocked(vscode.workspace.getConfiguration).mockImplementation(() => { + throw new Error("configuration unavailable") + }) + + const scopes = readCommandListScopes("deniedCommands", ["git"]) + + expect(scopes.workspace).toEqual([]) + expect(scopes.merged).toEqual(["git"]) + }) +}) + +describe("splitCommandListScopes", () => { + it("keeps workspace entries in the workspace layer and routes new entries to global", () => { + // The issue #1939 leak: the dialog sends the merged list back, and the + // workspace-only entry "docker" must not end up in the global write. + const result = splitCommandListScopes(["docker", "aws"], ["docker"], []) + + expect(result.workspaceWrite).toEqual(["docker"]) + expect(result.globalWrite).toEqual(["aws"]) + }) + + it("keeps a global entry in the global layer", () => { + const result = splitCommandListScopes(["git"], [], ["git"]) + + expect(result.workspaceWrite).toEqual([]) + expect(result.globalWrite).toEqual(["git"]) + }) + + it("keeps an entry present in both layers in both layers when retained", () => { + // Semantics: do not silently delete the user's global entry just + // because the current folder happens to define it too; the entry was + // deliberately authored in both scopes and the user kept it. + const result = splitCommandListScopes(["docker"], ["docker"], ["docker"]) + + expect(result.workspaceWrite).toEqual(["docker"]) + expect(result.globalWrite).toEqual(["docker"]) + }) + + it("removes a deleted entry from the workspace layer without touching global", () => { + // The user kept "git" and deleted workspace-only "docker"; "git" must + // survive at its own (global) layer. + const result = splitCommandListScopes(["git"], ["docker"], ["git"]) + + expect(result.workspaceWrite).toEqual([]) + expect(result.globalWrite).toEqual(["git"]) + }) + + it("removes a deleted entry from every layer that contained it", () => { + // "docker" lived in both layers and the user deleted it; kept "rm" + // stays at the workspace layer only. + const result = splitCommandListScopes(["rm"], ["docker", "rm"], ["docker"]) + + expect(result.workspaceWrite).toEqual(["rm"]) + expect(result.globalWrite).toEqual([]) + }) + + it("routes entries the dialog seeded to the layer they came from", () => { + const result = splitCommandListScopes( + ["git", "docker", "pnpm docker", "aws"], + ["docker", "pnpm docker"], + ["git"], + ) + + expect(result.workspaceWrite).toEqual(["docker", "pnpm docker"]) + expect(result.globalWrite).toEqual(["git", "aws"]) + }) + + it("orders the global write as existing global entries then new entries in dialog order", () => { + const result = splitCommandListScopes(["aws", "git", "npm"], ["docker"], ["git"]) + + expect(result.globalWrite).toEqual(["git", "aws", "npm"]) + }) + + it("drops blank and non-string entries from the incoming list", () => { + const result = splitCommandListScopes(["git", "", " ", 42 as unknown as string], [], ["git"]) + + expect(result.globalWrite).toEqual(["git"]) + expect(result.workspaceWrite).toEqual([]) + }) + + it("deduplicates layers so re-writing cannot introduce duplicates", () => { + const result = splitCommandListScopes(["docker", "docker"], ["docker", "docker"], ["docker"]) + + expect(result.workspaceWrite).toEqual(["docker"]) + expect(result.globalWrite).toEqual(["docker"]) + }) +}) + +describe("resolveWorkspaceWriteTarget", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("returns the workspace-folder target when a folder value is set", () => { + mockConfiguration({ + inspect: { key: "deniedCommands", workspaceValue: ["docker"], workspaceFolderValue: ["pnpm docker"] }, + }) + + expect(resolveWorkspaceWriteTarget("deniedCommands")).toBe(vscode.ConfigurationTarget.WorkspaceFolder) + }) + + it("returns the workspace target when only a workspace value is set", () => { + mockConfiguration({ inspect: { key: "deniedCommands", workspaceValue: ["docker"] } }) + + expect(resolveWorkspaceWriteTarget("deniedCommands")).toBe(vscode.ConfigurationTarget.Workspace) + }) + + it("returns undefined when only a global value is set, so no workspace layer is created", () => { + mockConfiguration({ inspect: { key: "deniedCommands", globalValue: ["npm"] } }) + + expect(resolveWorkspaceWriteTarget("deniedCommands")).toBeUndefined() + }) + + it("returns undefined when there is no inspect result", () => { + mockConfiguration({ inspect: undefined }) + + expect(resolveWorkspaceWriteTarget("deniedCommands")).toBeUndefined() + }) + + it("returns undefined when the configuration lookup throws", () => { + vi.mocked(vscode.workspace.getConfiguration).mockImplementation(() => { + throw new Error("configuration unavailable") + }) + + expect(resolveWorkspaceWriteTarget("deniedCommands")).toBeUndefined() + }) +}) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts new file mode 100644 index 0000000000..55c895e8c3 --- /dev/null +++ b/src/core/auto-approval/commandScope.ts @@ -0,0 +1,139 @@ +import * as vscode from "vscode" + +import { Package } from "../../shared/package" + +export type CommandListConfigKey = "allowedCommands" | "deniedCommands" + +export interface CommandListScopes { + global: string[] + workspace: string[] + merged: string[] +} + +/** + * Reads an auto-approval command list from both configuration layers and + * composes the list that should be enforced and displayed. + * + * The workspace layer is read via `inspect()` rather than `get()` on purpose: + * `get()` returns the effective value, which already folds `globalValue` into + * the result. Unioning that with the global layer would double-count entries + * and make removals from global settings unable to shrink the enforced set. + * + * @param configKey - The extension configuration key to read. + * @param globalList - The list persisted in extension global state. + * @returns The per-layer lists and their deduplicated set union. + */ +export function readCommandListScopes( + configKey: CommandListConfigKey, + globalList: string[] | undefined, +): CommandListScopes { + const global = sanitizeCommandList(globalList) + let workspace: string[] = [] + + try { + const inspected = vscode.workspace.getConfiguration(Package.name).inspect(configKey) + // The folder value wins over the workspace value, matching VS Code's own + // resolution precedence for multi-root workspaces. + workspace = sanitizeCommandList(inspected?.workspaceFolderValue ?? inspected?.workspaceValue) + } catch { + // Configuration access can fail (for example before the workspace is + // ready); an absent workspace layer must not break enforcement. + workspace = [] + } + + // Set union: an entry present in both layers collapses to one, so + // composition cannot change prefix-match outcomes. + const merged = [...new Set([...global, ...workspace])] + + return { global, workspace, merged } +} + +export interface CommandListWriteScopes { + globalWrite: string[] + workspaceWrite: string[] +} + +/** + * Splits the merged command list the settings dialog saves back into the two + * configuration layers it was composed from, so saving the dialog cannot + * flatten workspace-scoped entries into the user's global settings. + * + * Semantics: + * - An entry the user kept that exists in the workspace layer stays in the + * workspace layer. If the same entry also exists in the global layer it + * stays there too: dropping it from the global write would silently delete + * a user's global entry just because the current folder happens to define + * it as well. + * - An entry the user removed is dropped from every layer that contained it, + * which makes workspace-scoped entries deletable from the dialog. + * - A brand-new entry (in neither layer) lands in the global layer, matching + * the pre-existing behavior of routing dialog edits to + * `ConfigurationTarget.Global`. + * + * @param incoming - The full merged list sent by the webview on save. + * @param workspaceLayer - The current workspace-scope configuration value. + * @param globalLayer - The list currently persisted in extension global state. + * @returns The per-layer values to write back. + */ +export function splitCommandListScopes( + incoming: string[], + workspaceLayer: string[], + globalLayer: string[], +): CommandListWriteScopes { + const kept = new Set(sanitizeCommandList(incoming)) + const workspace = sanitizeCommandList(workspaceLayer) + const global = sanitizeCommandList(globalLayer) + const known = new Set([...workspace, ...global]) + + // Deduplicated so re-writing a layer cannot introduce duplicates. + const workspaceWrite = [...new Set(workspace.filter((command) => kept.has(command)))] + const globalWrite = [ + ...new Set(global.filter((command) => kept.has(command))), + // Preserve the dialog's ordering for entries the user just added. + ...[...kept].filter((command) => !known.has(command)), + ] + + return { globalWrite, workspaceWrite } +} + +/** + * Picks the configuration target that owns the current workspace-scope layer + * for `configKey`, mirroring how `readCommandListScopes` reads it via an + * unscoped `getConfiguration(Package.name)` (which resolves folder values + * from the first workspace folder). + * + * - `workspaceFolderValue` set -> write at `WorkspaceFolder` scope. + * - Otherwise `workspaceValue` set -> write at `Workspace` scope. + * - Neither set -> `undefined`: no workspace layer exists, so none should be + * created (an empty workspace layer must not materialize in settings.json). + * + * @param configKey - The extension configuration key to inspect. + * @returns The workspace-scoped target to write, or `undefined` when no + * workspace layer exists. + */ +export function resolveWorkspaceWriteTarget( + configKey: CommandListConfigKey, +): vscode.ConfigurationTarget.WorkspaceFolder | vscode.ConfigurationTarget.Workspace | undefined { + try { + const inspected = vscode.workspace.getConfiguration(Package.name).inspect(configKey) + if (inspected?.workspaceFolderValue !== undefined) { + return vscode.ConfigurationTarget.WorkspaceFolder + } + if (inspected?.workspaceValue !== undefined) { + return vscode.ConfigurationTarget.Workspace + } + return undefined + } catch { + // Same defensive posture as readCommandListScopes: configuration + // access failures mean we create no workspace layer. + return undefined + } +} + +function sanitizeCommandList(list: unknown): string[] { + if (!Array.isArray(list)) { + return [] + } + + return list.filter((command): command is string => typeof command === "string" && command.trim().length > 0) +} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 874e2f8f08..78ac7c4870 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -112,6 +112,7 @@ import { forceFullModelDetailsLoad, hasLoadedFullDetails } from "../../api/provi import { ContextProxy } from "../config/ContextProxy" import { ProviderSettingsManager } from "../config/ProviderSettingsManager" import { CustomModesManager } from "../config/CustomModesManager" +import { readCommandListScopes } from "../auto-approval/commandScope" import { PendingActionSettlementError, Task } from "../task/Task" import { webviewMessageHandler } from "./webviewMessageHandler" @@ -2528,62 +2529,6 @@ export class ClineProvider } } - /** - * Merges allowed commands from global state and workspace configuration - * with proper validation and deduplication - */ - private mergeAllowedCommands(globalStateCommands?: string[]): string[] { - return this.mergeCommandLists("allowedCommands", "allowed", globalStateCommands) - } - - /** - * Merges denied commands from global state and workspace configuration - * with proper validation and deduplication - */ - private mergeDeniedCommands(globalStateCommands?: string[]): string[] { - return this.mergeCommandLists("deniedCommands", "denied", globalStateCommands) - } - - /** - * Common utility for merging command lists from global state and workspace configuration. - * Implements the Command Denylist feature's merging strategy with proper validation. - * - * @param configKey - VSCode workspace configuration key - * @param commandType - Type of commands for error logging - * @param globalStateCommands - Commands from global state - * @returns Merged and deduplicated command list - */ - private mergeCommandLists( - configKey: "allowedCommands" | "deniedCommands", - commandType: "allowed" | "denied", - globalStateCommands?: string[], - ): string[] { - try { - // Validate and sanitize global state commands - const validGlobalCommands = Array.isArray(globalStateCommands) - ? globalStateCommands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) - : [] - - // Get workspace configuration commands - const workspaceCommands = vscode.workspace.getConfiguration(Package.name).get(configKey) || [] - - // Validate and sanitize workspace commands - const validWorkspaceCommands = Array.isArray(workspaceCommands) - ? workspaceCommands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) - : [] - - // Combine and deduplicate commands - // Global state takes precedence over workspace configuration - const mergedCommands = [...new Set([...validGlobalCommands, ...validWorkspaceCommands])] - - return mergedCommands - } catch (error) { - console.error(`Error merging ${commandType} commands:`, error) - // Return empty array as fallback to prevent crashes - return [] - } - } - async getStateToPostToWebview({ includeTaskHistory = true }: GetStateOptions = {}): Promise { // Ensure the store is initialized before reading task history await this.taskHistoryStore.initialized @@ -2705,8 +2650,6 @@ export class ClineProvider const telemetryKey = process.env.POSTHOG_API_KEY const machineId = vscode.env.machineId const vscodeTelemetryEnabled = vscode.env.isTelemetryEnabled - const mergedAllowedCommands = this.mergeAllowedCommands(allowedCommands) - const mergedDeniedCommands = this.mergeDeniedCommands(deniedCommands) const cwd = this.cwd const currentTask = this.getCurrentTask() let currentTaskMode: string | undefined @@ -2786,8 +2729,8 @@ export class ClineProvider checkpointTimeout: checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, shouldShowAnnouncement: telemetrySetting !== "unset" && lastShownAnnouncementId !== this.latestAnnouncementId, - allowedCommands: mergedAllowedCommands, - deniedCommands: mergedDeniedCommands, + allowedCommands: allowedCommands ?? [], + deniedCommands: deniedCommands ?? [], soundVolume: soundVolume ?? 0.5, writeDelayMs: writeDelayMs ?? DEFAULT_WRITE_DELAY_MS, diffFuzzyThreshold: diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD, @@ -3016,8 +2959,11 @@ export class ClineProvider autoCondenseContext: stateValues.autoCondenseContext ?? true, autoCondenseContextPercent: stateValues.autoCondenseContextPercent ?? 100, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], - allowedCommands: stateValues.allowedCommands, - deniedCommands: stateValues.deniedCommands, + // Enforce and display the set union of the global-state layer and the + // workspace-scope configuration layer; getStateToPostToWebview shows + // exactly these values, so display cannot drift from enforcement. + allowedCommands: readCommandListScopes("allowedCommands", stateValues.allowedCommands).merged, + deniedCommands: readCommandListScopes("deniedCommands", stateValues.deniedCommands).merged, soundEnabled: stateValues.soundEnabled ?? false, ttsEnabled: stateValues.ttsEnabled ?? false, ttsSpeed: stateValues.ttsSpeed ?? 1.0, @@ -3350,6 +3296,9 @@ export class ClineProvider if (configuration) { await this.setValues(configuration) + // Deliberately Global-targeted: these writes carry "start this task with + // exactly this auto-approval policy" semantics (e.g. from handoff/delegation + // payloads), unlike the scope-split persistence in the settings dialog. if (configuration.allowedCommands) { await vscode.workspace .getConfiguration(Package.name) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b5f304fe56..4a96fadde0 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -1615,6 +1615,75 @@ describe("ClineProvider", () => { expect(state.alwaysDenyUnapprovedCommands).toBe(false) }) + describe("command list scope merging", () => { + // getConfiguration overrides must not leak past these tests: + // clearAllMocks does not remove mockReturnValue defaults. + afterEach(() => { + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn().mockReturnValue([]), + update: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) + }) + + test("getState enforces workspace-scope denied commands even when global state is empty", async () => { + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn().mockReturnValue([]), + inspect: vi + .fn() + .mockImplementation((key: string) => + key === "deniedCommands" ? { key, workspaceValue: ["docker"] } : undefined, + ), + update: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) + + const state = await provider.getState() + + expect(state.deniedCommands).toEqual(["docker"]) + }) + + test("getStateToPostToWebview shows the same merged command lists as getState", async () => { + await provider.resolveWebviewView(mockWebviewView) + await provider.contextProxy.setValue("deniedCommands", ["git"]) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn().mockReturnValue(["git", "docker"]), + inspect: vi + .fn() + .mockImplementation((key: string) => + key === "deniedCommands" ? { key, workspaceValue: ["docker"] } : undefined, + ), + update: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) + + const state = await provider.getStateToPostToWebview() + + // Display is the set union of global state and workspace scope, matching + // what getState() enforces. + expect(state.deniedCommands).toEqual(["git", "docker"]) + expect(state.allowedCommands).toEqual([]) + }) + + test("getState prefers the workspace-folder value for multi-root workspaces", async () => { + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn().mockReturnValue(["docker", "pnpm docker"]), + inspect: vi + .fn() + .mockImplementation((key: string) => + key === "deniedCommands" + ? { key, workspaceValue: ["docker"], workspaceFolderValue: ["pnpm docker"] } + : undefined, + ), + update: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) + + const state = await provider.getState() + + // The folder value replaces (not unions with) the workspace value, and + // the effective get() value is ignored so global-scoped entries do not + // leak into the workspace layer. + expect(state.deniedCommands).toEqual(["pnpm docker"]) + }) + }) + test("getState returns the saved allowed read files", async () => { await provider.contextProxy.setValue("allowedReadFiles", ["notes.md"]) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index dcd70f92f1..3d2f6abc21 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -178,6 +178,11 @@ vi.mock("vscode", () => { const showTextDocument = vi.fn().mockResolvedValue(undefined) return { + ConfigurationTarget: { + Global: 1, + Workspace: 2, + WorkspaceFolder: 3, + }, window: { showInformationMessage, showErrorMessage, @@ -1429,6 +1434,91 @@ describe("webviewMessageHandler - allowlists together", () => { }) }) +describe("webviewMessageHandler - command list scope-aware persistence", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + // Mirrors the real VS Code configuration API: `inspect()` exposes the + // per-scope values, and `update()` records the target it was written to. + // Extension global state is left unset (getValue returns undefined), i.e. + // the global layer starts empty. + function mockCommandConfiguration(inspected: { + globalValue?: string[] + workspaceValue?: string[] + workspaceFolderValue?: string[] + }) { + const update = vi.fn() + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn().mockReturnValue([]), + inspect: vi.fn().mockReturnValue(inspected), + update, + } as never) + return update + } + + it("keeps workspace-scoped denied commands out of the global write when saving the merged list", async () => { + const update = mockCommandConfiguration({ workspaceValue: ["docker"] }) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + // "docker" stays at the workspace scope instead of leaking into the + // user's global settings (issue #1939 leg B). + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + // Extension global state holds only the global layer, so the next save + // cannot double-home the workspace entry. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) + }) + + it("writes the workspace-folder value at the folder target in multi-root workspaces", async () => { + const update = mockCommandConfiguration({ workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.WorkspaceFolder) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) + }) + + it("clears a deleted workspace entry at the workspace scope without adding it to global", async () => { + const update = mockCommandConfiguration({ workspaceValue: ["docker"] }) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + }) + + // Deleting a project entry must clear it where it lives... + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + // ...and must not copy it into global settings. + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) + }) + + it("does not create a workspace layer when none exists", async () => { + const update = mockCommandConfiguration({}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"] }, + }) + + // Only the Global write happens; saving must not materialize an empty + // workspace-scoped value in settings.json. + expect(update).toHaveBeenCalledTimes(1) + expect(update).toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git"]) + }) +}) + describe("webviewMessageHandler - terminalProfile", () => { beforeEach(() => { vi.clearAllMocks() diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 4ba94d454c..374427f966 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -59,6 +59,11 @@ import { } from "./rulesMessageHandler" import { changeLanguage, t } from "../../i18n" import { Package } from "../../shared/package" +import { + readCommandListScopes, + resolveWorkspaceWriteTarget, + splitCommandListScopes, +} from "../auto-approval/commandScope" import { type RouterName, toRouterName } from "../../shared/api" import { MessageEnhancer } from "./messageEnhancer" @@ -751,26 +756,43 @@ export const webviewMessageHandler = async ( if (key === "language") { newValue = value ?? "en" changeLanguage(newValue as Language) - } else if (key === "allowedCommands") { + } else if (key === "allowedCommands" || key === "deniedCommands") { const commands = value ?? [] - newValue = Array.isArray(commands) + const incoming = Array.isArray(commands) ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) : [] - await vscode.workspace - .getConfiguration(Package.name) - .update("allowedCommands", newValue, vscode.ConfigurationTarget.Global) - } else if (key === "deniedCommands") { - const commands = value ?? [] + // The webview always sends the full merged list (it displays + // the union of the global-state and workspace-scope layers). + // Read both layers BEFORE any write and split the incoming + // list by origin scope, so saving the dialog cannot flatten + // workspace-scoped entries into the user's global settings. + const currentScopes = readCommandListScopes(key, getGlobalState(key)) + const { globalWrite, workspaceWrite } = splitCommandListScopes( + incoming, + currentScopes.workspace, + currentScopes.global, + ) + const workspaceTarget = resolveWorkspaceWriteTarget(key) + const config = vscode.workspace.getConfiguration(Package.name) + + // Write the workspace layer first, at the target that owns it. + // When no workspace layer exists the write is skipped entirely + // so saving never materializes one; when entries were deleted + // the `[]` write clears them at that scope. + if (workspaceTarget !== undefined) { + await config.update(key, workspaceWrite, workspaceTarget) + } - newValue = Array.isArray(commands) - ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) - : [] + await config.update(key, globalWrite, vscode.ConfigurationTarget.Global) - await vscode.workspace - .getConfiguration(Package.name) - .update("deniedCommands", newValue, vscode.ConfigurationTarget.Global) + // Extension global state keeps only the global layer: + // enforcement re-adds the workspace layer through + // readCommandListScopes, so storing the merged list here + // would double-home workspace entries and re-leak them on the + // next save. + newValue = globalWrite } else if (key === "allowedReadFiles" || key === "allowedWriteFiles") { const patterns = value ?? [] @@ -1712,38 +1734,6 @@ export const webviewMessageHandler = async ( // Cancel any pending auto-approval timeout for the current task provider.getCurrentTask()?.cancelAutoApprovalTimeout() break - case "allowedCommands": { - // Validate and sanitize the commands array - const commands = message.commands ?? [] - const validCommands = Array.isArray(commands) - ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) - : [] - - await updateGlobalState("allowedCommands", validCommands) - - // Also update workspace settings. - await vscode.workspace - .getConfiguration(Package.name) - .update("allowedCommands", validCommands, vscode.ConfigurationTarget.Global) - - break - } - case "deniedCommands": { - // Validate and sanitize the commands array - const commands = message.commands ?? [] - const validCommands = Array.isArray(commands) - ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) - : [] - - await updateGlobalState("deniedCommands", validCommands) - - // Also update workspace settings. - await vscode.workspace - .getConfiguration(Package.name) - .update("deniedCommands", validCommands, vscode.ConfigurationTarget.Global) - - break - } case "openCustomModesSettings": { const customModesFilePath = await provider.customModesManager.getCustomModesFilePath() diff --git a/src/extension.ts b/src/extension.ts index 1d71f834df..080ca5bae9 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -38,6 +38,7 @@ import { CodeIndexManagerRegistry } from "./services/code-index/code-index-manag import { CodeIndexScope } from "./services/code-index/code-index-scope" import { MdmService } from "./services/mdm/MdmService" import { migrateSettings } from "./utils/migrateSettings" +import { seedAllowedCommands } from "./utils/seedAllowedCommands" import { autoImportSettings } from "./utils/autoImportSettings" import { API } from "./extension/api" @@ -163,13 +164,7 @@ export async function activate(context: vscode.ExtensionContext) { // Initialize Zoo Code auth service for extension session token management. await initZooCodeAuth(context) - // Get default commands from configuration. - const defaultCommands = vscode.workspace.getConfiguration(Package.name).get("allowedCommands") || [] - - // Initialize global state if not already set. - if (!context.globalState.get("allowedCommands")) { - context.globalState.update("allowedCommands", defaultCommands) - } + await seedAllowedCommands(context.globalState) const contextProxy = await ContextProxy.getInstance(context) const updateTelemetryState = () => { diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts new file mode 100644 index 0000000000..19c2623dfb --- /dev/null +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -0,0 +1,121 @@ +// npx vitest run utils/__tests__/seedAllowedCommands.spec.ts + +import * as vscode from "vscode" + +import { seedAllowedCommands } from "../seedAllowedCommands" + +vi.mock("vscode", () => ({ + workspace: { + getConfiguration: vi.fn(), + }, +})) + +interface ConfigDouble { + inspect?: { + key: string + defaultValue?: string[] + globalValue?: string[] + workspaceValue?: string[] + workspaceFolderValue?: string[] + } + effective?: string[] + inspectThrows?: boolean +} + +function mockConfiguration({ inspect, effective = [], inspectThrows = false }: ConfigDouble = {}) { + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn().mockReturnValue(effective), + inspect: vi.fn().mockImplementation(() => { + if (inspectThrows) { + throw new Error("configuration access failed") + } + return inspect + }), + update: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) +} + +function mockMemento(existing: unknown = undefined) { + const store = new Map() + if (existing !== undefined) { + store.set("allowedCommands", existing) + } + + return { + get: vi.fn((key: string) => store.get(key)), + update: vi.fn(async (key: string, value: unknown) => { + store.set(key, value) + }), + } +} + +describe("seedAllowedCommands", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("leaves global state unset when only a workspace-scoped value exists", async () => { + // A real VS Code get() folds the workspace override into the effective + // value, so this is the leak scenario: reading get() would seed + // ["docker"] (from .vscode/settings.json) into global state. + mockConfiguration({ + inspect: { key: "allowedCommands", globalValue: undefined, workspaceValue: ["docker"] }, + effective: ["docker"], + }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState as unknown as vscode.Memento) + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toBeUndefined() + }) + + it("seeds from the global-scope value when global state is empty", async () => { + mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] }, effective: ["git"] }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState as unknown as vscode.Memento) + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", ["git"]) + expect(globalState.get("allowedCommands")).toEqual(["git"]) + }) + + it("does not overwrite global state that is already populated", async () => { + mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] }, effective: ["git"] }) + const globalState = mockMemento(["npm"]) + + await seedAllowedCommands(globalState as unknown as vscode.Memento) + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toEqual(["npm"]) + }) + + it("leaves global state untouched when there is no inspect result at all", async () => { + mockConfiguration({ inspect: undefined, effective: ["git"] }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState as unknown as vscode.Memento) + + expect(globalState.update).not.toHaveBeenCalled() + }) + + it("skips the seed without throwing when configuration access fails", async () => { + mockConfiguration({ inspectThrows: true }) + const globalState = mockMemento() + + await expect(seedAllowedCommands(globalState as unknown as vscode.Memento)).resolves.toBeUndefined() + + expect(globalState.update).not.toHaveBeenCalled() + }) + + it("does not share a reference with the inspected configuration value", async () => { + const globalValue = ["git"] + mockConfiguration({ inspect: { key: "allowedCommands", globalValue } }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState as unknown as vscode.Memento) + + expect(globalState.update).toHaveBeenCalledWith("allowedCommands", expect.arrayContaining(["git"])) + expect(globalState.update.mock.calls[0][1]).not.toBe(globalValue) + }) +}) diff --git a/src/utils/seedAllowedCommands.ts b/src/utils/seedAllowedCommands.ts new file mode 100644 index 0000000000..6a56173e47 --- /dev/null +++ b/src/utils/seedAllowedCommands.ts @@ -0,0 +1,40 @@ +import * as vscode from "vscode" + +import { Package } from "../shared/package" + +/** + * Seeds the extension's global-state allowlist from the `allowedCommands` + * setting, but only when global state holds no list yet (first run). + * + * The seed reads the global-scope value via `inspect()` rather than the + * effective `get()` on purpose: `get()` folds in workspace-scoped overrides, + * so a project's `.vscode/settings.json` would otherwise be copied + * permanently into global state the first time the extension activates inside + * that project — a leak that survives closing the project. + * + * @param globalState - The extension global-state memento to seed. + */ +export async function seedAllowedCommands(globalState: vscode.Memento): Promise { + if (globalState.get("allowedCommands")) { + return + } + + let globalValue: string[] | undefined + try { + globalValue = vscode.workspace.getConfiguration(Package.name).inspect("allowedCommands")?.globalValue + } catch { + // Configuration access can fail (for example before the workspace is + // ready); skipping the seed only defers it to a later activation. + return + } + + // An absent global-scope value leaves global state untouched: seeding the + // package.json default or a workspace override would defeat the point of + // scoping the seed to the user's own settings. + if (!Array.isArray(globalValue)) { + return + } + + // Copy so global state never shares a reference with the configuration object. + await globalState.update("allowedCommands", [...globalValue]) +} From 420cbe80f46de74fb8df54273186eb4ee34c320e Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Wed, 14 Oct 2026 18:29:01 +0200 Subject: [PATCH 02/52] fix: compensate failed command-list saves and scope config access per review (#1939) - Rewind the workspace-layer command-list write when the global-layer write fails: the raw previous value is captured before saving, the failed key skips its extension global-state update while the other keys still save, and a failed rewind is reported alongside the original error. - Read and write the command lists through one configuration object scoped to the first workspace folder, so workspace-folder targets are legal and resolve against the right folder's settings (the VS Code API rejects folder-targeted updates on an unscoped configuration). - Narrow the try/catch around configuration lookups so a failed lookup stays distinct from an absent value; behavior is unchanged, the guarded failure mode is now testable. - Add regression tests for the compensation path, the scoped reads and writes, and the seed guard; tighten comments. --- src/__tests__/extension.spec.ts | 4 + .../__tests__/commandScope.spec.ts | 52 +++++- src/core/auto-approval/commandScope.ts | 66 +++++--- .../__tests__/webviewMessageHandler.spec.ts | 151 ++++++++++++++++-- src/core/webview/webviewMessageHandler.ts | 73 +++++++-- .../__tests__/seedAllowedCommands.spec.ts | 61 ++++--- src/utils/seedAllowedCommands.ts | 12 +- 7 files changed, 349 insertions(+), 70 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index ba8c885c0a..3b52363763 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -424,6 +424,8 @@ describe("extension.ts", () => { workspaceValue, }), update: vi.fn(), + // The double scripts key-scoped get() and per-scope inspect() + // shapes the shared helper cannot express without obscuring them. } as unknown as vscode.WorkspaceConfiguration) } @@ -436,6 +438,8 @@ describe("extension.ts", () => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn().mockReturnValue([]), inspect: vi.fn(), + // Restores the neutral default after the scope fixtures above; + // update is intentionally absent because no test runs after this. } as unknown as vscode.WorkspaceConfiguration) }) diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 7784c4a1bd..58c48fbac3 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -1,7 +1,16 @@ import * as vscode from "vscode" +import { Package } from "../../../shared/package" +import { makeUri, makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { readCommandListScopes, resolveWorkspaceWriteTarget, splitCommandListScopes } from "../commandScope" +// Scriptable stand-in for `vscode.workspace.workspaceFolders`: the module +// mock's getter reads through this object, so a test can change the open +// folders without re-mocking the module. +const workspaceState = vi.hoisted(() => ({ + workspaceFolders: undefined as { uri: unknown }[] | undefined, +})) + vi.mock("vscode", () => ({ ConfigurationTarget: { Global: 1, @@ -9,6 +18,9 @@ vi.mock("vscode", () => ({ WorkspaceFolder: 3, }, workspace: { + get workspaceFolders() { + return workspaceState.workspaceFolders + }, getConfiguration: vi.fn(), }, })) @@ -25,11 +37,12 @@ interface ConfigDouble { } function mockConfiguration({ inspect, effective = [] }: ConfigDouble = {}) { - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ - get: vi.fn().mockReturnValue(effective), - inspect: vi.fn().mockReturnValue(inspect), - update: vi.fn(), - } as unknown as vscode.WorkspaceConfiguration) + const config = makeWorkspaceConfiguration() + // The shared double is scripted after creation so the per-test fixture + // values need no type assertion at the construction site. + vi.mocked(config.get).mockReturnValue(effective) + vi.mocked(config.inspect).mockReturnValue(inspect) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) } describe("readCommandListScopes", () => { @@ -192,6 +205,8 @@ describe("splitCommandListScopes", () => { }) it("drops blank and non-string entries from the incoming list", () => { + // Deliberate wrong runtime type: configuration lists arrive as unknown, + // so the sanitizer must drop non-strings instead of throwing on them. const result = splitCommandListScopes(["git", "", " ", 42 as unknown as string], [], ["git"]) expect(result.globalWrite).toEqual(["git"]) @@ -209,6 +224,7 @@ describe("splitCommandListScopes", () => { describe("resolveWorkspaceWriteTarget", () => { beforeEach(() => { vi.clearAllMocks() + workspaceState.workspaceFolders = undefined }) it("returns the workspace-folder target when a folder value is set", () => { @@ -244,4 +260,30 @@ describe("resolveWorkspaceWriteTarget", () => { expect(resolveWorkspaceWriteTarget("deniedCommands")).toBeUndefined() }) + + it("resolves the target from the configuration scoped to the first workspace folder", () => { + const folderA = makeUri("/mock/folder-a") + const folderB = makeUri("/mock/folder-b") + workspaceState.workspaceFolders = [{ uri: folderA }, { uri: folderB }] + mockConfiguration({ inspect: { key: "deniedCommands", workspaceFolderValue: ["pnpm docker"] } }) + + expect(resolveWorkspaceWriteTarget("deniedCommands")).toBe(vscode.ConfigurationTarget.WorkspaceFolder) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) + // Only the first folder is ever in scope: reading any other folder's + // configuration would silently target the wrong folder's settings file. + expect(vscode.workspace.getConfiguration).not.toHaveBeenCalledWith(Package.name, folderB) + }) + + it.each([undefined, [] as { uri: unknown }[]])( + "falls back to an unscoped configuration when no workspace folder is open (%s)", + (workspaceFolders) => { + workspaceState.workspaceFolders = workspaceFolders + mockConfiguration({ inspect: { key: "deniedCommands", workspaceValue: ["docker"] } }) + + // With no resource to resolve against, no folder value can be + // reported, so the folder target stays unreachable. + expect(resolveWorkspaceWriteTarget("deniedCommands")).toBe(vscode.ConfigurationTarget.Workspace) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, undefined) + }, + ) }) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 55c895e8c3..4778ac1f3e 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -10,6 +10,20 @@ export interface CommandListScopes { merged: string[] } +/** + * The configuration object for every command-list read and write, scoped to + * the first workspace folder. Sharing one scoped access path keeps the two + * sides symmetric: `inspect()` can report `workspaceFolderValue`, and + * `ConfigurationTarget.WorkspaceFolder` updates are legal (the API contract + * throws for that target when the configuration is not scoped to a + * resource). In a multi-root workspace only the first folder's values are in + * scope; with no folder open the configuration is unscoped and reports no + * folder value. + */ +export function commandListConfiguration(): vscode.WorkspaceConfiguration { + return vscode.workspace.getConfiguration(Package.name, vscode.workspace.workspaceFolders?.[0]?.uri) +} + /** * Reads an auto-approval command list from both configuration layers and * composes the list that should be enforced and displayed. @@ -28,19 +42,23 @@ export function readCommandListScopes( globalList: string[] | undefined, ): CommandListScopes { const global = sanitizeCommandList(globalList) - let workspace: string[] = [] + // Only the configuration lookup itself is guarded: it can fail (for example + // before the workspace is ready), and an absent workspace layer must not + // break enforcement. The value reads below have no failure mode of their + // own, so the catch covers exactly the failure it exists to absorb. + let inspected: { workspaceValue?: string[]; workspaceFolderValue?: string[] } | undefined try { - const inspected = vscode.workspace.getConfiguration(Package.name).inspect(configKey) - // The folder value wins over the workspace value, matching VS Code's own - // resolution precedence for multi-root workspaces. - workspace = sanitizeCommandList(inspected?.workspaceFolderValue ?? inspected?.workspaceValue) + inspected = commandListConfiguration().inspect(configKey) } catch { - // Configuration access can fail (for example before the workspace is - // ready); an absent workspace layer must not break enforcement. - workspace = [] + inspected = undefined } + // The folder value wins over the workspace value, matching VS Code's + // folder-over-workspace precedence. An absent inspect result composes to + // an empty workspace layer: enforcement must not break. + const workspace = sanitizeCommandList(inspected?.workspaceFolderValue ?? inspected?.workspaceValue) + // Set union: an entry present in both layers collapses to one, so // composition cannot change prefix-match outcomes. const merged = [...new Set([...global, ...workspace])] @@ -98,9 +116,11 @@ export function splitCommandListScopes( /** * Picks the configuration target that owns the current workspace-scope layer - * for `configKey`, mirroring how `readCommandListScopes` reads it via an - * unscoped `getConfiguration(Package.name)` (which resolves folder values - * from the first workspace folder). + * for `configKey`, inspecting the same `commandListConfiguration()` object + * `readCommandListScopes` reads. Because that configuration is scoped to the + * first workspace folder, folder values resolve against that folder's + * settings; with no folder open the configuration is unscoped and reports no + * folder value, so no folder target can be selected. * * - `workspaceFolderValue` set -> write at `WorkspaceFolder` scope. * - Otherwise `workspaceValue` set -> write at `Workspace` scope. @@ -114,20 +134,22 @@ export function splitCommandListScopes( export function resolveWorkspaceWriteTarget( configKey: CommandListConfigKey, ): vscode.ConfigurationTarget.WorkspaceFolder | vscode.ConfigurationTarget.Workspace | undefined { + // Same defensive posture as readCommandListScopes: only the configuration + // lookup itself may fail, and a failure means we create no workspace layer. + let inspected: { workspaceValue?: string[]; workspaceFolderValue?: string[] } | undefined try { - const inspected = vscode.workspace.getConfiguration(Package.name).inspect(configKey) - if (inspected?.workspaceFolderValue !== undefined) { - return vscode.ConfigurationTarget.WorkspaceFolder - } - if (inspected?.workspaceValue !== undefined) { - return vscode.ConfigurationTarget.Workspace - } - return undefined + inspected = commandListConfiguration().inspect(configKey) } catch { - // Same defensive posture as readCommandListScopes: configuration - // access failures mean we create no workspace layer. - return undefined + inspected = undefined + } + + if (inspected?.workspaceFolderValue !== undefined) { + return vscode.ConfigurationTarget.WorkspaceFolder + } + if (inspected?.workspaceValue !== undefined) { + return vscode.ConfigurationTarget.Workspace } + return undefined } function sanitizeCommandList(list: unknown): string[] { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 3d2f6abc21..ab906d9c45 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -71,6 +71,8 @@ vi.mock("@roo-code/telemetry", () => ({ import type { ModelRecord } from "@roo-code/types" +import { Package } from "../../../shared/package" +import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { webviewMessageHandler } from "../webviewMessageHandler" import type { ClineProvider } from "../ClineProvider" import { flushModels, getModels } from "../../../api/providers/fetchers/modelCache" @@ -1439,21 +1441,44 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { vi.clearAllMocks() }) + // The file-level vscode mock opens one workspace folder, so the command + // list configuration resolves to its uri. + const mockWorkspaceFolderUri = { fsPath: "/mock/workspace" } + // Mirrors the real VS Code configuration API: `inspect()` exposes the // per-scope values, and `update()` records the target it was written to. // Extension global state is left unset (getValue returns undefined), i.e. // the global layer starts empty. - function mockCommandConfiguration(inspected: { - globalValue?: string[] - workspaceValue?: string[] - workspaceFolderValue?: string[] - }) { + // + // `updateSequence` / `inspectSequence` let a failure test script what + // successive `update()` / `inspect()` calls return (each `update()` return + // is awaited by the handler, so a rejected promise fails that write), in + // call order; a plain value resolves like the default mock. + function mockCommandConfiguration( + inspected: { + globalValue?: string[] + workspaceValue?: string[] + workspaceFolderValue?: string[] + }, + updateSequence?: unknown[], + inspectSequence?: unknown[], + ) { const update = vi.fn() - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ - get: vi.fn().mockReturnValue([]), - inspect: vi.fn().mockReturnValue(inspected), - update, - } as never) + if (updateSequence) { + update.mockImplementation(() => updateSequence.shift()) + } + const inspect = vi.fn() + if (inspectSequence) { + inspect.mockImplementation(() => inspectSequence.shift()) + } else { + inspect.mockReturnValue(inspected) + } + // The shared structurally complete double keeps the configuration type + // correct; the scripted members are installed per test. + const config = makeWorkspaceConfiguration() + config.update = update + config.inspect = inspect + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) return update } @@ -1466,7 +1491,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) // "docker" stays at the workspace scope instead of leaking into the - // user's global settings (issue #1939 leg B). + // user's global settings (issue #1939: persist without scope leakage). expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) // Extension global state holds only the global layer, so the next save @@ -1482,6 +1507,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { updatedSettings: { deniedCommands: ["docker", "aws"] }, }) + // Read, target resolution, and write all run on the configuration + // scoped to the first workspace folder — the folder-target update is + // only legal on a resource-scoped configuration. + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, mockWorkspaceFolderUri) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.WorkspaceFolder) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) @@ -1517,6 +1546,106 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(update).toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git"]) }) + + it("restores the previous workspace value when the global write fails", async () => { + // update() call order: workspace write succeeds, global write rejects. + // The raw folder-layer value differs from the sanitized post-split layer + // (and from the workspace-layer value), so the restore call is uniquely + // identifiable and provably reads the folder value for a folder target. + const update = mockCommandConfiguration( + { workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, + [undefined, Promise.reject(new Error("disk on fire"))], + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // A second key pins that only the failed command-list key is skipped. + updatedSettings: { deniedCommands: ["docker", "aws"], alwaysDenyUnapprovedCommands: true }, + }) + + // The capture, the failed write, and the restore all ran on the + // configuration scoped to the first workspace folder. + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, mockWorkspaceFolderUri) + // The raw previous folder value (entries this save dropped included) is + // written back at the target the failed save chose. + expect(update).toHaveBeenCalledWith( + "deniedCommands", + ["pnpm docker", "docker"], + vscode.ConfigurationTarget.WorkspaceFolder, + ) + expect(update).toHaveBeenCalledTimes(3) + // The failed key's extension global-state write is skipped... + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) + // ...while the other key of the same payload still persists. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: disk on fire") + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + + it("does not write global or extension state when the workspace write fails", async () => { + // The first update() call is the workspace write; it rejects, so the + // global write must never be attempted for this key. The rejection is a + // plain string to pin the non-Error rendering of the failure message. + const update = mockCommandConfiguration({ workspaceValue: ["docker"] }, [Promise.reject("workspace locked")]) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + // Nothing was changed yet, so there is nothing to restore: only the + // failed workspace write happened, and no compensation write followed. + expect(update).toHaveBeenCalledTimes(1) + expect(update).not.toHaveBeenCalledWith("deniedCommands", expect.anything(), vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") + }) + + it("saves both layers when the capture of the previous value finds no inspect result", async () => { + // inspect() call order: readCommandListScopes, resolveWorkspaceWriteTarget, + // then the compensation capture — only the capture call sees no result. + // A missing capture result must not abort the save: the writes proceed, + // and only a later failure could find nothing to restore. + const inspected = { workspaceValue: ["docker"] } + const update = mockCommandConfiguration(inspected, undefined, [inspected, inspected, undefined]) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenCalledTimes(2) + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + }) + + it("reports partial failure when the compensating restore also fails", async () => { + // update() call order: workspace write succeeds, global write rejects, + // restore write rejects too. The raw workspace value differs from the + // post-split layer so the restore call is uniquely identifiable. + const update = mockCommandConfiguration({ workspaceValue: ["docker", "old"] }, [ + undefined, + Promise.reject(new Error("disk on fire")), + Promise.reject(new Error("restore also failed")), + ]) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + // The restore was attempted at the owning target even though it failed. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "old"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledTimes(3) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to save deniedCommands: disk on fire. The workspace-scoped restore also failed: Error: restore also failed. Review the command lists in your user and workspace settings.", + ) + // No exception escaped the handler: the state post still ran. + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) }) describe("webviewMessageHandler - terminalProfile", () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 374427f966..92c651d381 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -60,6 +60,7 @@ import { import { changeLanguage, t } from "../../i18n" import { Package } from "../../shared/package" import { + commandListConfiguration, readCommandListScopes, resolveWorkspaceWriteTarget, splitCommandListScopes, @@ -775,17 +776,69 @@ export const webviewMessageHandler = async ( currentScopes.global, ) const workspaceTarget = resolveWorkspaceWriteTarget(key) - const config = vscode.workspace.getConfiguration(Package.name) - - // Write the workspace layer first, at the target that owns it. - // When no workspace layer exists the write is skipped entirely - // so saving never materializes one; when entries were deleted - // the `[]` write clears them at that scope. - if (workspaceTarget !== undefined) { - await config.update(key, workspaceWrite, workspaceTarget) - } + const config = commandListConfiguration() + + // The two configuration writes below are not atomic, so the raw + // previous workspace value is captured before the write: a failed + // global write rewinds the workspace layer to exactly what the + // configuration held beforehand, including the entries this save + // drops. The raw inspected value is used rather than the sanitized + // layer so the rewind reproduces the file contents instead of a + // cleaned-up approximation of them. + let previousWorkspaceValue: string[] | undefined + let workspaceWriteApplied = false + try { + // Capture the raw previous value for the compensation path + // before anything is written, from the target that owns the + // workspace layer, so the rewind reproduces exactly what that + // target held. With no inspect result there is nothing + // trustworthy to rewind to; the layer can only have been + // created or changed by this save's own writes, so the + // compensation write clears it. + const previousInspected = config.inspect(key) + if (previousInspected !== undefined) { + previousWorkspaceValue = + workspaceTarget === vscode.ConfigurationTarget.WorkspaceFolder + ? previousInspected.workspaceFolderValue + : previousInspected.workspaceValue + } - await config.update(key, globalWrite, vscode.ConfigurationTarget.Global) + // Write the workspace layer first, at the target that owns it. + // When no workspace layer exists the write is skipped entirely + // so saving never materializes one; when entries were deleted + // the `[]` write clears them at that scope. + if (workspaceTarget !== undefined) { + await config.update(key, workspaceWrite, workspaceTarget) + workspaceWriteApplied = true + } + + await config.update(key, globalWrite, vscode.ConfigurationTarget.Global) + } catch (error) { + const failure = error instanceof Error ? error.message : String(error) + + // A failed workspace write leaves nothing changed, so only a + // global-write failure has a changed workspace layer to rewind, + // and the rewind goes to the same target the write used. + if (workspaceWriteApplied) { + try { + await config.update(key, previousWorkspaceValue, workspaceTarget) + } catch (restoreError) { + // The rewind itself failed: the configuration keeps the + // partially written values and the extension global-state + // write is skipped, so stored state never reflects a save + // that did not complete. The user hears about both failures. + vscode.window.showErrorMessage( + `Failed to save ${key}: ${failure}. The workspace-scoped restore also failed: ${restoreError}. Review the command lists in your user and workspace settings.`, + ) + continue + } + } + + // Only this key's save is abandoned; the remaining keys of the + // payload persist normally. + vscode.window.showErrorMessage(`Failed to save ${key}: ${failure}`) + continue + } // Extension global state keeps only the global layer: // enforcement re-adds the workspace layer through diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts index 19c2623dfb..6467cb1ef8 100644 --- a/src/utils/__tests__/seedAllowedCommands.spec.ts +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -2,6 +2,7 @@ import * as vscode from "vscode" +import { makeWorkspaceConfiguration } from "../../test-utils/vscode" import { seedAllowedCommands } from "../seedAllowedCommands" vi.mock("vscode", () => ({ @@ -23,16 +24,17 @@ interface ConfigDouble { } function mockConfiguration({ inspect, effective = [], inspectThrows = false }: ConfigDouble = {}) { - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ - get: vi.fn().mockReturnValue(effective), - inspect: vi.fn().mockImplementation(() => { - if (inspectThrows) { - throw new Error("configuration access failed") - } - return inspect - }), - update: vi.fn(), - } as unknown as vscode.WorkspaceConfiguration) + const config = makeWorkspaceConfiguration() + // The shared double is scripted after creation so the per-test fixture + // values need no type assertion at the construction site. + vi.mocked(config.get).mockReturnValue(effective) + vi.mocked(config.inspect).mockImplementation(() => { + if (inspectThrows) { + throw new Error("configuration access failed") + } + return inspect + }) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) } function mockMemento(existing: unknown = undefined) { @@ -41,9 +43,12 @@ function mockMemento(existing: unknown = undefined) { store.set("allowedCommands", existing) } + // Structurally complete Memento double (keys/get/update), so the call + // sites need no type assertion. return { - get: vi.fn((key: string) => store.get(key)), - update: vi.fn(async (key: string, value: unknown) => { + keys: vi.fn((): readonly string[] => [...store.keys()]), + get: vi.fn().mockImplementation((key: string) => store.get(key)), + update: vi.fn().mockImplementation(async (key: string, value: unknown) => { store.set(key, value) }), } @@ -64,7 +69,7 @@ describe("seedAllowedCommands", () => { }) const globalState = mockMemento() - await seedAllowedCommands(globalState as unknown as vscode.Memento) + await seedAllowedCommands(globalState) expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toBeUndefined() @@ -74,7 +79,7 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] }, effective: ["git"] }) const globalState = mockMemento() - await seedAllowedCommands(globalState as unknown as vscode.Memento) + await seedAllowedCommands(globalState) expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", ["git"]) expect(globalState.get("allowedCommands")).toEqual(["git"]) @@ -84,17 +89,37 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] }, effective: ["git"] }) const globalState = mockMemento(["npm"]) - await seedAllowedCommands(globalState as unknown as vscode.Memento) + await seedAllowedCommands(globalState) expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toEqual(["npm"]) }) + it("inspects the global value under the extension's own section key", async () => { + // The seed must read the extension's own section; asking VS Code about + // a different (or empty) section key would silently never find the + // user's global list. + mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] } }) + // Structurally complete Memento double (keys/get/update), so the call + // site needs no type assertion. + const globalState: vscode.Memento = { + keys: () => [], + get: vi.fn(), + update: vi.fn(), + } + + await seedAllowedCommands(globalState) + + const config = vi.mocked(vscode.workspace.getConfiguration).mock.results[0].value + expect(config.inspect).toHaveBeenCalledWith("allowedCommands") + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", ["git"]) + }) + it("leaves global state untouched when there is no inspect result at all", async () => { mockConfiguration({ inspect: undefined, effective: ["git"] }) const globalState = mockMemento() - await seedAllowedCommands(globalState as unknown as vscode.Memento) + await seedAllowedCommands(globalState) expect(globalState.update).not.toHaveBeenCalled() }) @@ -103,7 +128,7 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspectThrows: true }) const globalState = mockMemento() - await expect(seedAllowedCommands(globalState as unknown as vscode.Memento)).resolves.toBeUndefined() + await expect(seedAllowedCommands(globalState)).resolves.toBeUndefined() expect(globalState.update).not.toHaveBeenCalled() }) @@ -113,7 +138,7 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspect: { key: "allowedCommands", globalValue } }) const globalState = mockMemento() - await seedAllowedCommands(globalState as unknown as vscode.Memento) + await seedAllowedCommands(globalState) expect(globalState.update).toHaveBeenCalledWith("allowedCommands", expect.arrayContaining(["git"])) expect(globalState.update.mock.calls[0][1]).not.toBe(globalValue) diff --git a/src/utils/seedAllowedCommands.ts b/src/utils/seedAllowedCommands.ts index 6a56173e47..3deab4897b 100644 --- a/src/utils/seedAllowedCommands.ts +++ b/src/utils/seedAllowedCommands.ts @@ -19,18 +19,22 @@ export async function seedAllowedCommands(globalState: vscode.Memento): Promise< return } - let globalValue: string[] | undefined + // Only the configuration lookup itself is guarded: it can fail (for example + // before the workspace is ready), and skipping the seed then only defers it + // to a later activation. The `?.globalValue` read below stays outside the + // guarded region so a genuine lookup failure stays distinguishable from an + // absent value rather than being swallowed as one. + let inspected: { globalValue?: string[] } | undefined try { - globalValue = vscode.workspace.getConfiguration(Package.name).inspect("allowedCommands")?.globalValue + inspected = vscode.workspace.getConfiguration(Package.name).inspect("allowedCommands") } catch { - // Configuration access can fail (for example before the workspace is - // ready); skipping the seed only defers it to a later activation. return } // An absent global-scope value leaves global state untouched: seeding the // package.json default or a workspace override would defeat the point of // scoping the seed to the user's own settings. + const globalValue = inspected?.globalValue if (!Array.isArray(globalValue)) { return } From 95ed76acf885726b6dd6a67c086dc6163da6621d Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Wed, 14 Oct 2026 21:32:29 +0200 Subject: [PATCH 03/52] fix: derive command-list save scope from a single settings read (#1939) Saving an allowed/denied command list now inspects the configuration once per key and derives the workspace layer, the rollback value and the write target from that one snapshot, instead of three reads that could disagree. When the inspection is unavailable the key is skipped with a visible error and nothing is written for it, which also removes a path where a workspace-only entry could be re-copied into user settings; the other keys of the same save still persist. Regression tests cover the single-read invariant and both abort cases. --- .../__tests__/commandScope.spec.ts | 25 ++++++ src/core/auto-approval/commandScope.ts | 72 +++++++++++----- .../__tests__/webviewMessageHandler.spec.ts | 82 ++++++++++++++----- src/core/webview/webviewMessageHandler.ts | 72 +++++++++------- 4 files changed, 180 insertions(+), 71 deletions(-) diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 58c48fbac3..f09c4ecad2 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -140,6 +140,19 @@ describe("readCommandListScopes", () => { expect(scopes.workspace).toEqual([]) expect(scopes.merged).toEqual(["git"]) }) + + it("takes the workspace layer from a caller-supplied snapshot without reading the configuration", () => { + // The save path threads one captured inspection through every + // derivation, so the snapshot is authoritative: the configuration's own + // value must never be consulted a second time. + mockConfiguration({ inspect: { key: "deniedCommands", workspaceValue: ["stale"] } }) + + const scopes = readCommandListScopes("deniedCommands", [], { workspaceValue: ["docker"] }) + + expect(scopes.workspace).toEqual(["docker"]) + expect(scopes.merged).toEqual(["docker"]) + expect(vscode.workspace.getConfiguration).not.toHaveBeenCalled() + }) }) describe("splitCommandListScopes", () => { @@ -261,6 +274,18 @@ describe("resolveWorkspaceWriteTarget", () => { expect(resolveWorkspaceWriteTarget("deniedCommands")).toBeUndefined() }) + it("resolves the target from a caller-supplied snapshot without reading the configuration", () => { + // The snapshot alone decides the target, so a folder value the live + // configuration does not report still selects the folder target — + // keeping split, write, and rollback on one captured state. + mockConfiguration({ inspect: { key: "deniedCommands", workspaceValue: ["docker"] } }) + + expect(resolveWorkspaceWriteTarget("deniedCommands", { workspaceFolderValue: ["pnpm docker"] })).toBe( + vscode.ConfigurationTarget.WorkspaceFolder, + ) + expect(vscode.workspace.getConfiguration).not.toHaveBeenCalled() + }) + it("resolves the target from the configuration scoped to the first workspace folder", () => { const folderA = makeUri("/mock/folder-a") const folderB = makeUri("/mock/folder-b") diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 4778ac1f3e..d57e77bf7d 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -10,6 +10,17 @@ export interface CommandListScopes { merged: string[] } +/** + * The workspace-scoped layers of a command-list key as reported by + * `WorkspaceConfiguration.inspect()`. Capturing it once lets a save derive + * the read layers, the write target, and a rollback value from a single + * configuration state instead of three independent reads that could disagree. + */ +export interface CommandListInspection { + workspaceValue?: string[] + workspaceFolderValue?: string[] +} + /** * The configuration object for every command-list read and write, scoped to * the first workspace folder. Sharing one scoped access path keeps the two @@ -35,23 +46,33 @@ export function commandListConfiguration(): vscode.WorkspaceConfiguration { * * @param configKey - The extension configuration key to read. * @param globalList - The list persisted in extension global state. + * @param inspectionOverride - A snapshot captured by the caller before any + * write; when present it is used as-is and no fresh lookup happens, so a + * save's reads, target resolution, and rollback stay derived from one + * configuration state. Without it the lookup runs guarded (lenient): this is + * the enforcement/display path, where an unavailable workspace layer must + * degrade to empty rather than fail. * @returns The per-layer lists and their deduplicated set union. */ export function readCommandListScopes( configKey: CommandListConfigKey, globalList: string[] | undefined, + inspectionOverride?: CommandListInspection, ): CommandListScopes { const global = sanitizeCommandList(globalList) - // Only the configuration lookup itself is guarded: it can fail (for example - // before the workspace is ready), and an absent workspace layer must not - // break enforcement. The value reads below have no failure mode of their - // own, so the catch covers exactly the failure it exists to absorb. - let inspected: { workspaceValue?: string[]; workspaceFolderValue?: string[] } | undefined - try { - inspected = commandListConfiguration().inspect(configKey) - } catch { - inspected = undefined + let inspected: CommandListInspection | undefined = inspectionOverride + if (inspected === undefined) { + // Only the configuration lookup itself is guarded: it can fail (for + // example before the workspace is ready), and an absent workspace layer + // must not break enforcement. The value reads below have no failure mode + // of their own, so the catch covers exactly the failure it exists to + // absorb. + try { + inspected = commandListConfiguration().inspect(configKey) + } catch { + inspected = undefined + } } // The folder value wins over the workspace value, matching VS Code's @@ -116,11 +137,12 @@ export function splitCommandListScopes( /** * Picks the configuration target that owns the current workspace-scope layer - * for `configKey`, inspecting the same `commandListConfiguration()` object - * `readCommandListScopes` reads. Because that configuration is scoped to the - * first workspace folder, folder values resolve against that folder's - * settings; with no folder open the configuration is unscoped and reports no - * folder value, so no folder target can be selected. + * for `configKey`. Reading the layers runs through the same + * `commandListConfiguration()` object `readCommandListScopes` uses; because + * that configuration is scoped to the first workspace folder, folder values + * resolve against that folder's settings; with no folder open the + * configuration is unscoped and reports no folder value, so no folder target + * can be selected. * * - `workspaceFolderValue` set -> write at `WorkspaceFolder` scope. * - Otherwise `workspaceValue` set -> write at `Workspace` scope. @@ -128,19 +150,27 @@ export function splitCommandListScopes( * created (an empty workspace layer must not materialize in settings.json). * * @param configKey - The extension configuration key to inspect. + * @param inspectionOverride - A snapshot captured by the caller; when present + * it alone decides the target and no fresh lookup happens, keeping a save's + * split, write, and rollback on one configuration state. Without it the + * lookup is guarded leniently: a failure means no workspace layer exists. * @returns The workspace-scoped target to write, or `undefined` when no * workspace layer exists. */ export function resolveWorkspaceWriteTarget( configKey: CommandListConfigKey, + inspectionOverride?: CommandListInspection, ): vscode.ConfigurationTarget.WorkspaceFolder | vscode.ConfigurationTarget.Workspace | undefined { - // Same defensive posture as readCommandListScopes: only the configuration - // lookup itself may fail, and a failure means we create no workspace layer. - let inspected: { workspaceValue?: string[]; workspaceFolderValue?: string[] } | undefined - try { - inspected = commandListConfiguration().inspect(configKey) - } catch { - inspected = undefined + let inspected: CommandListInspection | undefined = inspectionOverride + if (inspected === undefined) { + // Same defensive posture as readCommandListScopes: only the + // configuration lookup itself may fail, and a failure means we create no + // workspace layer. + try { + inspected = commandListConfiguration().inspect(configKey) + } catch { + inspected = undefined + } } if (inspected?.workspaceFolderValue !== undefined) { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index ab906d9c45..af26431b4c 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1453,7 +1453,8 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // `updateSequence` / `inspectSequence` let a failure test script what // successive `update()` / `inspect()` calls return (each `update()` return // is awaited by the handler, so a rejected promise fails that write), in - // call order; a plain value resolves like the default mock. + // call order; a plain value resolves like the default mock, and an Error + // element makes that call throw. function mockCommandConfiguration( inspected: { globalValue?: string[] @@ -1469,7 +1470,13 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { } const inspect = vi.fn() if (inspectSequence) { - inspect.mockImplementation(() => inspectSequence.shift()) + inspect.mockImplementation(() => { + const next = inspectSequence.shift() + if (next instanceof Error) { + throw next + } + return next + }) } else { inspect.mockReturnValue(inspected) } @@ -1479,11 +1486,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { config.update = update config.inspect = inspect vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - return update + return { update, inspect } } it("keeps workspace-scoped denied commands out of the global write when saving the merged list", async () => { - const update = mockCommandConfiguration({ workspaceValue: ["docker"] }) + const { update, inspect } = mockCommandConfiguration({ workspaceValue: ["docker"] }) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -1497,10 +1504,14 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // Extension global state holds only the global layer, so the next save // cannot double-home the workspace entry. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) + // Exactly one snapshot per key: the scope read, write target, and + // rollback all derive from the same inspect(), so a helper re-reading + // the configuration would raise this count and could diverge. + expect(inspect).toHaveBeenCalledTimes(1) }) it("writes the workspace-folder value at the folder target in multi-root workspaces", async () => { - const update = mockCommandConfiguration({ workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }) + const { update } = mockCommandConfiguration({ workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -1517,7 +1528,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("clears a deleted workspace entry at the workspace scope without adding it to global", async () => { - const update = mockCommandConfiguration({ workspaceValue: ["docker"] }) + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -1533,7 +1544,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("does not create a workspace layer when none exists", async () => { - const update = mockCommandConfiguration({}) + const { update } = mockCommandConfiguration({}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -1552,7 +1563,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The raw folder-layer value differs from the sanitized post-split layer // (and from the workspace-layer value), so the restore call is uniquely // identifiable and provably reads the folder value for a folder target. - const update = mockCommandConfiguration( + const { update } = mockCommandConfiguration( { workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, [undefined, Promise.reject(new Error("disk on fire"))], ) @@ -1586,7 +1597,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The first update() call is the workspace write; it rejects, so the // global write must never be attempted for this key. The rejection is a // plain string to pin the non-Error rendering of the failure message. - const update = mockCommandConfiguration({ workspaceValue: ["docker"] }, [Promise.reject("workspace locked")]) + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, [ + Promise.reject("workspace locked"), + ]) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -1601,31 +1614,56 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) - it("saves both layers when the capture of the previous value finds no inspect result", async () => { - // inspect() call order: readCommandListScopes, resolveWorkspaceWriteTarget, - // then the compensation capture — only the capture call sees no result. - // A missing capture result must not abort the save: the writes proceed, - // and only a later failure could find nothing to restore. - const inspected = { workspaceValue: ["docker"] } - const update = mockCommandConfiguration(inspected, undefined, [inspected, inspected, undefined]) + it("aborts the key without writing when the configuration inspection has no result", async () => { + // The save derives scopes, write target, and rollback from one inspect() + // snapshot, so a missing snapshot means the workspace layer is unknown — + // proceeding would classify the retained workspace entry "docker" as new + // and re-copy it into global settings (issue #1939's leak). The key is + // aborted instead: no configuration write, no extension global state. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, [undefined]) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - expect(update).toHaveBeenCalledTimes(2) - expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) - expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) - expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + expect(update).not.toHaveBeenCalled() + // Leak pin: the workspace entry must not land in the global layer. + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to save deniedCommands: the configuration value could not be read", + ) + // No exception escaped the handler: the state post still ran. + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + + it("aborts the command-list key when the inspection throws, while other keys of the payload still save", async () => { + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, [ + new Error("configuration unavailable"), + ]) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // A second key pins that only the aborted command-list key is skipped. + updatedSettings: { deniedCommands: ["docker", "aws"], alwaysDenyUnapprovedCommands: true }, + }) + + // The aborted key wrote nothing at any scope... + expect(update).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) + // ...while the other key of the same payload still persists. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to save deniedCommands: configuration unavailable", + ) }) it("reports partial failure when the compensating restore also fails", async () => { // update() call order: workspace write succeeds, global write rejects, // restore write rejects too. The raw workspace value differs from the // post-split layer so the restore call is uniquely identifiable. - const update = mockCommandConfiguration({ workspaceValue: ["docker", "old"] }, [ + const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "old"] }, [ undefined, Promise.reject(new Error("disk on fire")), Promise.reject(new Error("restore also failed")), diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 92c651d381..6d198f57fe 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -60,6 +60,7 @@ import { import { changeLanguage, t } from "../../i18n" import { Package } from "../../shared/package" import { + type CommandListInspection, commandListConfiguration, readCommandListScopes, resolveWorkspaceWriteTarget, @@ -766,43 +767,58 @@ export const webviewMessageHandler = async ( // The webview always sends the full merged list (it displays // the union of the global-state and workspace-scope layers). - // Read both layers BEFORE any write and split the incoming - // list by origin scope, so saving the dialog cannot flatten - // workspace-scoped entries into the user's global settings. - const currentScopes = readCommandListScopes(key, getGlobalState(key)) + // Splitting that list by origin scope needs the workspace + // layer, the write target, and the rollback value to describe + // the SAME configuration state, so they are all derived from + // one inspect() snapshot taken before any write. Without a + // snapshot the key's save is aborted rather than guessed at: + // reading the workspace layer as empty would classify a + // workspace-scoped entry as brand new and re-copy it into + // global settings. + // Only the snapshot read is guarded: a failing + // commandListConfiguration() lookup propagates instead of being + // downgraded to a per-key save failure. + const config = commandListConfiguration() + let inspection: CommandListInspection | undefined + let inspectionFailure: string | undefined + try { + inspection = config.inspect(key) + } catch (error) { + inspectionFailure = error instanceof Error ? error.message : String(error) + } + if (inspection === undefined) { + // No snapshot: the workspace layer could only be guessed + // at, and a guessed-empty layer re-copies workspace entries + // into global settings, so this key's save is abandoned + // while the remaining keys of the payload persist normally. + vscode.window.showErrorMessage( + `Failed to save ${key}: ${inspectionFailure ?? "the configuration value could not be read"}`, + ) + continue + } + + const currentScopes = readCommandListScopes(key, getGlobalState(key), inspection) const { globalWrite, workspaceWrite } = splitCommandListScopes( incoming, currentScopes.workspace, currentScopes.global, ) - const workspaceTarget = resolveWorkspaceWriteTarget(key) - const config = commandListConfiguration() + const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) // The two configuration writes below are not atomic, so the raw - // previous workspace value is captured before the write: a failed - // global write rewinds the workspace layer to exactly what the - // configuration held beforehand, including the entries this save - // drops. The raw inspected value is used rather than the sanitized - // layer so the rewind reproduces the file contents instead of a - // cleaned-up approximation of them. - let previousWorkspaceValue: string[] | undefined + // previous workspace value comes from the same snapshot the split + // used, taken from the target that owns the workspace layer: a + // failed global write rewinds that target to exactly what it held + // beforehand, including the entries this save drops. The raw + // inspected value is used rather than the sanitized layer so the + // rewind reproduces the file contents instead of a cleaned-up + // approximation of them. + const previousWorkspaceValue = + workspaceTarget === vscode.ConfigurationTarget.WorkspaceFolder + ? inspection.workspaceFolderValue + : inspection.workspaceValue let workspaceWriteApplied = false try { - // Capture the raw previous value for the compensation path - // before anything is written, from the target that owns the - // workspace layer, so the rewind reproduces exactly what that - // target held. With no inspect result there is nothing - // trustworthy to rewind to; the layer can only have been - // created or changed by this save's own writes, so the - // compensation write clears it. - const previousInspected = config.inspect(key) - if (previousInspected !== undefined) { - previousWorkspaceValue = - workspaceTarget === vscode.ConfigurationTarget.WorkspaceFolder - ? previousInspected.workspaceFolderValue - : previousInspected.workspaceValue - } - // Write the workspace layer first, at the target that owns it. // When no workspace layer exists the write is skipped entirely // so saving never materializes one; when entries were deleted From 7c294cc9ac5d1573d50418eef2eae94350b33549 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 15 Oct 2026 00:16:04 +0200 Subject: [PATCH 04/52] fix: restore default command allowlist on fresh installs (#1939) Fresh installs keep the built-in git command defaults again: with no user, workspace, or folder value set, the declared default list is seeded into global state. A workspace or folder override still wins and nothing is written over it. Scope layers are read through the folder-aware settings lookup shared with the command-list paths. --- src/__tests__/extension.spec.ts | 4 + .../__tests__/seedAllowedCommands.spec.ts | 152 ++++++++++++++++-- src/utils/seedAllowedCommands.ts | 55 +++++-- 3 files changed, 181 insertions(+), 30 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 3b52363763..6a2e2596dd 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -420,6 +420,10 @@ describe("extension.ts", () => { ), inspect: vi.fn().mockReturnValue({ key: "allowedCommands", + // Real inspect() always reports the declared package default; + // including it here lets the workspace-override test prove the + // default stays unseeded beside an override, not just absent. + defaultValue: ["git log", "git diff", "git show"], globalValue, workspaceValue, }), diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts index 6467cb1ef8..a62ce469a9 100644 --- a/src/utils/__tests__/seedAllowedCommands.spec.ts +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -2,11 +2,22 @@ import * as vscode from "vscode" -import { makeWorkspaceConfiguration } from "../../test-utils/vscode" +import { Package } from "../../shared/package" +import { makeUri, makeWorkspaceConfiguration } from "../../test-utils/vscode" import { seedAllowedCommands } from "../seedAllowedCommands" +// Scriptable stand-in for `vscode.workspace.workspaceFolders`: the module +// mock's getter reads through this object, so a test can change the open +// folders without re-mocking the module. +const workspaceState = vi.hoisted(() => ({ + workspaceFolders: undefined as { uri: unknown }[] | undefined, +})) + vi.mock("vscode", () => ({ workspace: { + get workspaceFolders() { + return workspaceState.workspaceFolders + }, getConfiguration: vi.fn(), }, })) @@ -24,17 +35,31 @@ interface ConfigDouble { } function mockConfiguration({ inspect, effective = [], inspectThrows = false }: ConfigDouble = {}) { - const config = makeWorkspaceConfiguration() - // The shared double is scripted after creation so the per-test fixture - // values need no type assertion at the construction site. - vi.mocked(config.get).mockReturnValue(effective) - vi.mocked(config.inspect).mockImplementation(() => { - if (inspectThrows) { - throw new Error("configuration access failed") - } - return inspect - }) - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + // Real VS Code reports `workspaceFolderValue` only for a configuration + // looked up against a resource; an unscoped lookup reports no folder + // layer no matter what any folder's settings contain. Scripting that + // split per call is what lets these tests tell a scoped lookup apart + // from an unscoped one. + vi.mocked(vscode.workspace.getConfiguration).mockImplementation( + (_section?: string, scope?: vscode.ConfigurationScope | null) => { + const config = makeWorkspaceConfiguration() + // The shared double is scripted per call so the per-test fixture + // values need no type assertion at the construction site. + vi.mocked(config.get).mockReturnValue(effective) + vi.mocked(config.inspect).mockImplementation(() => { + if (inspectThrows) { + throw new Error("configuration access failed") + } + if (inspect === undefined) { + return undefined + } + // No resource to resolve against => no folder layer, matching + // the real contract for unscoped (and explicit-null) lookups. + return scope === undefined || scope === null ? { ...inspect, workspaceFolderValue: undefined } : inspect + }) + return config + }, + ) } function mockMemento(existing: unknown = undefined) { @@ -57,14 +82,23 @@ function mockMemento(existing: unknown = undefined) { describe("seedAllowedCommands", () => { beforeEach(() => { vi.clearAllMocks() + workspaceState.workspaceFolders = undefined }) it("leaves global state unset when only a workspace-scoped value exists", async () => { // A real VS Code get() folds the workspace override into the effective // value, so this is the leak scenario: reading get() would seed - // ["docker"] (from .vscode/settings.json) into global state. + // ["docker"] (from .vscode/settings.json) into global state. The + // defaultValue mirrors real VS Code, where the declared default is + // always present: the workspace override replaced it deliberately, so + // re-granting it from global state is also forbidden. mockConfiguration({ - inspect: { key: "allowedCommands", globalValue: undefined, workspaceValue: ["docker"] }, + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + globalValue: undefined, + workspaceValue: ["docker"], + }, effective: ["docker"], }) const globalState = mockMemento() @@ -75,6 +109,92 @@ describe("seedAllowedCommands", () => { expect(globalState.get("allowedCommands")).toBeUndefined() }) + it("leaves global state unset when only a workspace-folder-scoped value exists", async () => { + // A folder override is visible only to a lookup resolved against that + // folder's resource, so this fixture opens a folder and scripts the + // folder layer (which the resource-aware double reports only for the + // scoped call). An unscoped seed would read "no value anywhere" here + // and re-grant the default the folder removed — this test fails on + // that regression. + const folderA = makeUri("/mock/folder-a") + workspaceState.workspaceFolders = [{ uri: folderA }] + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + globalValue: undefined, + workspaceFolderValue: ["docker"], + }, + }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState) + + // The folder layer only reaches the seed through a resource-scoped + // lookup, so the seed must request one (same pin as the save path). + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toBeUndefined() + }) + + it("resolves the folder layer against the first workspace folder only", async () => { + // Reading any other folder's configuration would silently decide the + // seed from the wrong folder's settings file. + const folderA = makeUri("/mock/folder-a") + const folderB = makeUri("/mock/folder-b") + workspaceState.workspaceFolders = [{ uri: folderA }, { uri: folderB }] + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + workspaceFolderValue: ["docker"], + }, + }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState) + + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) + expect(vscode.workspace.getConfiguration).not.toHaveBeenCalledWith(Package.name, folderB) + expect(globalState.update).not.toHaveBeenCalled() + }) + + it("treats an explicitly empty workspace value as an override that suppresses the default", async () => { + // Presence is checked with `undefined`, not truthiness: a workspace that + // set the list to [] opted out of the default as deliberately as one + // that set ["docker"]. + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + globalValue: undefined, + workspaceValue: [], + }, + }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState) + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toBeUndefined() + }) + + it("seeds the declared default on a fresh install with no value set at any scope", async () => { + const defaultValue = ["git log", "git diff", "git show"] + mockConfiguration({ + inspect: { key: "allowedCommands", defaultValue }, + effective: defaultValue, + }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState) + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) + // Copy, like the global-value path: global state must not share a + // reference with the configuration object. + expect(globalState.update.mock.calls[0][1]).not.toBe(defaultValue) + }) + it("seeds from the global-scope value when global state is empty", async () => { mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] }, effective: ["git"] }) const globalState = mockMemento() @@ -98,7 +218,8 @@ describe("seedAllowedCommands", () => { it("inspects the global value under the extension's own section key", async () => { // The seed must read the extension's own section; asking VS Code about // a different (or empty) section key would silently never find the - // user's global list. + // user's global list. With no folder open there is no resource to + // scope against, so the explicit unscoped call is (section, undefined). mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] } }) // Structurally complete Memento double (keys/get/update), so the call // site needs no type assertion. @@ -110,6 +231,7 @@ describe("seedAllowedCommands", () => { await seedAllowedCommands(globalState) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, undefined) const config = vi.mocked(vscode.workspace.getConfiguration).mock.results[0].value expect(config.inspect).toHaveBeenCalledWith("allowedCommands") expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", ["git"]) diff --git a/src/utils/seedAllowedCommands.ts b/src/utils/seedAllowedCommands.ts index 3deab4897b..1afa0bbfcb 100644 --- a/src/utils/seedAllowedCommands.ts +++ b/src/utils/seedAllowedCommands.ts @@ -1,16 +1,30 @@ import * as vscode from "vscode" -import { Package } from "../shared/package" +import { commandListConfiguration } from "../core/auto-approval/commandScope" /** * Seeds the extension's global-state allowlist from the `allowedCommands` * setting, but only when global state holds no list yet (first run). * - * The seed reads the global-scope value via `inspect()` rather than the - * effective `get()` on purpose: `get()` folds in workspace-scoped overrides, - * so a project's `.vscode/settings.json` would otherwise be copied - * permanently into global state the first time the extension activates inside - * that project — a leak that survives closing the project. + * The seed reads scoped values via `inspect()` rather than the effective + * `get()` on purpose: `get()` folds in workspace-scoped overrides, so a + * project's `.vscode/settings.json` would otherwise be copied permanently + * into global state the first time the extension activates inside that + * project — a leak that survives closing the project. The lookup goes + * through `commandListConfiguration()`, the folder-scoped accessor shared + * with the command-list read and write paths: only a configuration resolved + * against a resource reports `workspaceFolderValue` at all, so the folder + * layer is visible here exactly where enforcement can see it. In a + * multi-root workspace only the first folder is in scope; with no folder + * open the configuration is unscoped and reports no folder value. + * + * Selection: the global-scope value wins. With nothing set at any scope (a + * fresh install) the declared package default is seeded, because the + * enforcement path reads only global state plus workspace scopes and never + * falls back to that default on its own. A workspace-scoped value is an + * explicit choice and suppresses the default: array settings replace across + * scopes, so seeding it would re-grant the auto-approvals the override + * removed. * * @param globalState - The extension global-state memento to seed. */ @@ -21,24 +35,35 @@ export async function seedAllowedCommands(globalState: vscode.Memento): Promise< // Only the configuration lookup itself is guarded: it can fail (for example // before the workspace is ready), and skipping the seed then only defers it - // to a later activation. The `?.globalValue` read below stays outside the + // to a later activation. The `inspected` reads below stay outside the // guarded region so a genuine lookup failure stays distinguishable from an // absent value rather than being swallowed as one. - let inspected: { globalValue?: string[] } | undefined + let inspected: + | { + globalValue?: string[] + defaultValue?: string[] + workspaceValue?: string[] + workspaceFolderValue?: string[] + } + | undefined try { - inspected = vscode.workspace.getConfiguration(Package.name).inspect("allowedCommands") + inspected = commandListConfiguration().inspect("allowedCommands") } catch { return } - // An absent global-scope value leaves global state untouched: seeding the - // package.json default or a workspace override would defeat the point of - // scoping the seed to the user's own settings. - const globalValue = inspected?.globalValue - if (!Array.isArray(globalValue)) { + // The `undefined` checks, not truthiness: an explicitly empty array still + // counts as an override. + const seedValue = + inspected?.globalValue ?? + (inspected?.workspaceValue === undefined && inspected?.workspaceFolderValue === undefined + ? inspected?.defaultValue + : undefined) + + if (!Array.isArray(seedValue)) { return } // Copy so global state never shares a reference with the configuration object. - await globalState.update("allowedCommands", [...globalValue]) + await globalState.update("allowedCommands", [...seedValue]) } From 0cf1628953271db530d2d75fbaf59bd5b7ac11e7 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 15 Oct 2026 11:11:32 +0200 Subject: [PATCH 05/52] test: pin command-list seed and settings-lookup edge cases (#1939) Add three tests, no production change: an explicitly empty seeded allowlist is left untouched instead of re-seeded, a settings lookup that cannot return aborts the whole update-settings message instead of partially applying it, and a workspace override added after a fresh-install seed composes as a union with the seeded defaults. --- .../__tests__/webviewMessageHandler.spec.ts | 26 ++++++++++ .../__tests__/seedAllowedCommands.spec.ts | 51 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index af26431b4c..1a3ffaa3ae 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1659,6 +1659,32 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { ) }) + it("propagates a configuration lookup failure instead of degrading it to a per-key abort", async () => { + // The commandListConfiguration() lookup sits outside the guarded + // snapshot read on purpose: a lookup that cannot return a configuration + // object at all is a different failure class than an unreadable value, + // so it aborts the entire message rather than the one key. + vi.mocked(vscode.workspace.getConfiguration).mockImplementation(() => { + throw new Error("workspace not ready") + }) + + await expect( + webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // A second key pins that the whole message aborts, not just the + // command-list key: with the guarded per-key failure paths this + // key would still persist. + updatedSettings: { deniedCommands: ["docker", "aws"], alwaysDenyUnapprovedCommands: true }, + }), + ).rejects.toThrow("workspace not ready") + + // Nothing persisted for any key, no per-key error handling ran, and the + // state post was skipped — the rejection surfaced to the caller instead. + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + expect(mockClineProvider.postStateToWebview).not.toHaveBeenCalled() + }) + it("reports partial failure when the compensating restore also fails", async () => { // update() call order: workspace write succeeds, global write rejects, // restore write rejects too. The raw workspace value differs from the diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts index a62ce469a9..50c1dd5fc6 100644 --- a/src/utils/__tests__/seedAllowedCommands.spec.ts +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -2,6 +2,7 @@ import * as vscode from "vscode" +import { readCommandListScopes } from "../../core/auto-approval/commandScope" import { Package } from "../../shared/package" import { makeUri, makeWorkspaceConfiguration } from "../../test-utils/vscode" import { seedAllowedCommands } from "../seedAllowedCommands" @@ -215,6 +216,56 @@ describe("seedAllowedCommands", () => { expect(globalState.get("allowedCommands")).toEqual(["npm"]) }) + it("leaves an explicitly empty global-state list untouched", async () => { + // The guard treats presence, not emptiness: saving [] is a deliberate + // choice to auto-approve nothing, and re-seeding the package default + // would silently re-grant the approvals the user just revoked. + mockConfiguration({ inspect: { key: "allowedCommands", defaultValue: ["git log", "git diff", "git show"] } }) + const globalState = mockMemento([]) + + await seedAllowedCommands(globalState) + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toEqual([]) + }) + + it("composes a later workspace override as a union with the seeded defaults", async () => { + // Full schedule: a fresh activation seeds the declared default, then a + // workspace override appears in a later activation. The seed + // early-returns because global state already holds a list, so the + // override is never persisted — and the enforcement read composes the + // two layers as a set union. Neither list replaces the other; the + // longest-prefix matcher decides which entry governs a given command. + const defaultValue = ["git log", "git diff", "git show"] + mockConfiguration({ + inspect: { key: "allowedCommands", defaultValue }, + effective: defaultValue, + }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState) + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) + + // A later activation in a workspace whose settings file sets the list: + // the guard early-returns before any inspection, so no second write. + mockConfiguration({ + inspect: { key: "allowedCommands", defaultValue, workspaceValue: ["docker ps"] }, + effective: ["docker ps"], + }) + + await seedAllowedCommands(globalState) + expect(globalState.update).toHaveBeenCalledTimes(1) + expect(globalState.get("allowedCommands")).toEqual(defaultValue) + + // The enforcement view (ClineProvider.getState) keeps both layers and + // merges them: the override adds entries, it does not replace the + // seeded defaults, and vice versa. + const scopes = readCommandListScopes("allowedCommands", globalState.get("allowedCommands")) + expect(scopes.global).toEqual(defaultValue) + expect(scopes.workspace).toEqual(["docker ps"]) + expect(scopes.merged).toEqual([...defaultValue, "docker ps"]) + }) + it("inspects the global value under the extension's own section key", async () => { // The seed must read the extension's own section; asking VS Code about // a different (or empty) section key would silently never find the From 474dfd6936677a68c0debb0f6acb9ca0304b593a Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Sun, 1 Nov 2026 18:21:23 +0100 Subject: [PATCH 06/52] fix: gate workspace command lists and give user-level entries precedence (#1939) A user-level command-list entry now decides any command it matches: an entry from a workspace's .vscode/settings.json applies only where no user-level entry (allow or deny) matches, in both directions. The whole workspace layer sits behind a new setting, zoo-code.workspaceCommandListsEnabled, default off. It is declared with "scope": "application" in the extension manifest, so only user settings resolve it and a repository file cannot enable it; the settings save path also refuses a gate value supplied by the webview. Entries hidden while the gate is off are hidden from the approval dialog as well, and saving from the dialog preserves the workspace entries it does not show. The setting's description resolves from the nls bundles, translated for all 17 locales. Covers allow-side state propagation in tests. Addresses reviewer feedback on #2056. --- packages/types/src/global-settings.ts | 19 ++ packages/types/src/vscode-extension-host.ts | 1 + .../__tests__/commandScope.spec.ts | 131 +++++++++++++- .../auto-approval/__tests__/commands.spec.ts | 87 ++++++++- src/core/auto-approval/commandScope.ts | 75 ++++++++ src/core/auto-approval/commands.ts | 28 +++ src/core/webview/ClineProvider.ts | 33 +++- .../webview/__tests__/ClineProvider.spec.ts | 88 ++++++++- .../__tests__/webviewMessageHandler.spec.ts | 170 ++++++++++++++++-- src/core/webview/webviewMessageHandler.ts | 34 +++- src/package.json | 7 + src/package.nls.ca.json | 3 +- src/package.nls.de.json | 3 +- src/package.nls.es.json | 3 +- src/package.nls.fr.json | 3 +- src/package.nls.hi.json | 3 +- src/package.nls.id.json | 3 +- src/package.nls.it.json | 3 +- src/package.nls.ja.json | 3 +- src/package.nls.json | 3 +- src/package.nls.ko.json | 3 +- src/package.nls.nl.json | 3 +- src/package.nls.pl.json | 3 +- src/package.nls.pt-BR.json | 3 +- src/package.nls.ru.json | 3 +- src/package.nls.tr.json | 3 +- src/package.nls.vi.json | 3 +- src/package.nls.zh-CN.json | 3 +- src/package.nls.zh-TW.json | 3 +- 29 files changed, 681 insertions(+), 46 deletions(-) diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index 54ae7af089..9cca42c877 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -49,6 +49,17 @@ export const DEFAULT_DIFF_FUZZY_THRESHOLD = 1.0 export const DEFAULT_DESTRUCTIVE_COMMAND_GUARD_ENABLED = false +/** + * Whether workspace-scoped command-list layers (`zoo-code.allowedCommands` / + * `zoo-code.deniedCommands` values set in workspace settings) participate in + * command auto-approval at all. Opt-in: while off, workspace-layer entries + * contribute nothing to enforcement or display. The manifest declares the key + * with `scope: "application"`, so only user settings can change it; this + * constant is the single default shared by every consumer reading the + * setting. + */ +export const DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED = false + /** * Whether commands that are not explicitly auto-approved are automatically * denied (with a structured reason sent to the model) instead of prompting the @@ -175,6 +186,14 @@ export const globalSettingsSchema = z.object({ followupAutoApproveTimeoutMs: z.number().optional(), allowedCommands: z.array(z.string()).optional(), deniedCommands: z.array(z.string()).optional(), + /** + * Gate for the workspace-scoped command-list layers. While false (the + * default), workspace-set `allowedCommands`/`deniedCommands` entries + * contribute nothing; when true they are composed under the global layer, + * which outranks them wherever it matches a command. + * @default false + */ + workspaceCommandListsEnabled: z.boolean().optional(), commandExecutionTimeout: z.number().optional(), commandTimeoutAllowlist: z.array(z.string()).optional(), preventCompletionWithOpenTodos: z.boolean().optional(), diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 95316f5e74..689066ccd0 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -287,6 +287,7 @@ export type ExtensionState = Pick< | "followupAutoApproveTimeoutMs" | "allowedCommands" | "deniedCommands" + | "workspaceCommandListsEnabled" | "allowedMaxRequests" | "allowedMaxCost" | "ttsEnabled" diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index f09c4ecad2..4d1064d23d 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -1,8 +1,18 @@ +import * as fs from "fs" +import * as path from "path" + +import { DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, globalSettingsSchema } from "@roo-code/types" import * as vscode from "vscode" import { Package } from "../../../shared/package" import { makeUri, makeWorkspaceConfiguration } from "../../../test-utils/vscode" -import { readCommandListScopes, resolveWorkspaceWriteTarget, splitCommandListScopes } from "../commandScope" +import { + readCommandListScopes, + resolveEffectiveCommandLists, + resolveWorkspaceWriteTarget, + splitCommandListScopes, + workspaceCommandListsEnabled, +} from "../commandScope" // Scriptable stand-in for `vscode.workspace.workspaceFolders`: the module // mock's getter reads through this object, so a test can change the open @@ -312,3 +322,122 @@ describe("resolveWorkspaceWriteTarget", () => { }, ) }) + +function mockGateConfiguration(gate: unknown) { + const config = makeWorkspaceConfiguration() + vi.mocked(config.get).mockReturnValue(gate) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + return config +} + +// Raw per-key layers in the shape readCommandListScopes returns them. +const listScopes = (globalList: string[], workspaceList: string[]) => ({ + global: globalList, + workspace: workspaceList, + merged: [...new Set([...globalList, ...workspaceList])], +}) + +it("workspaceCommandListsEnabled: enables the workspace layers only when the gate configuration reads true", () => { + vi.clearAllMocks() + const config = mockGateConfiguration(true) + + expect(workspaceCommandListsEnabled()).toBe(true) + expect(config.get).toHaveBeenCalledWith("workspaceCommandListsEnabled") +}) + +it("workspaceCommandListsEnabled: keeps the workspace layers disabled when the gate lookup throws", () => { + vi.clearAllMocks() + // Fail-closed: a broken configuration read must never widen what the + // workspace layer can auto-approve. + vi.mocked(vscode.workspace.getConfiguration).mockImplementation(() => { + throw new Error("configuration unavailable") + }) + + expect(workspaceCommandListsEnabled()).toBe(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED) + expect(workspaceCommandListsEnabled()).toBe(false) +}) + +// The manifest declaration is what makes the gate workspace-unsettable; +// VS Code itself refusing a workspace-layer value is platform behavior. +it("manifest: declares the gate as a default-off, application-scoped boolean", () => { + const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, "../../../package.json"), "utf8")) + const gate = manifest.contributes.configuration.properties["zoo-code.workspaceCommandListsEnabled"] + + expect(gate.type).toBe("boolean") + expect(gate.default).toBe(false) + expect(gate.scope).toBe("application") +}) + +it("manifest: keeps the command-list keys workspace-settable so the gated layer can exist", () => { + // The gate scopes the workspace layers' effect; scoping the list keys + // themselves would remove the workspace layer entirely. + const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, "../../../package.json"), "utf8")) + const properties = manifest.contributes.configuration.properties + + expect(properties["zoo-code.allowedCommands"].scope).toBeUndefined() + expect(properties["zoo-code.deniedCommands"].scope).toBeUndefined() +}) + +it("persisted-settings schema: defaults the gate to disabled", () => { + expect(globalSettingsSchema.parse({}).workspaceCommandListsEnabled).toBeUndefined() + expect(globalSettingsSchema.parse({ workspaceCommandListsEnabled: true }).workspaceCommandListsEnabled).toBe(true) + expect(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED).toBe(false) +}) + +it("resolveEffectiveCommandLists: hides every workspace entry, allow and deny alike, while the gate is disabled", () => { + const effective = resolveEffectiveCommandLists(listScopes([], ["docker"]), listScopes([], ["rm"]), false) + + expect(effective.allowed).toEqual([]) + expect(effective.denied).toEqual([]) + expect(effective.hiddenWorkspaceAllow).toEqual(["docker"]) + expect(effective.hiddenWorkspaceDeny).toEqual(["rm"]) +}) + +it("resolveEffectiveCommandLists: treats unshadowed workspace entries as the sole layer when the global layer is empty", () => { + const effective = resolveEffectiveCommandLists(listScopes(["git"], ["docker", "aws"]), listScopes([], ["rm"]), true) + + expect(effective.allowed).toEqual(["git", "docker", "aws"]) + expect(effective.denied).toEqual(["rm"]) + expect(effective.hiddenWorkspaceAllow).toEqual([]) + expect(effective.hiddenWorkspaceDeny).toEqual([]) +}) + +it("resolveEffectiveCommandLists: lets a global allow entry decide a command a longer workspace deny entry also matches", () => { + // Cross-directional shadowing: the workspace deny entry cannot decide + // anything the global allow layer already covers, so it never reaches + // the matcher. + const effective = resolveEffectiveCommandLists(listScopes(["git"], []), listScopes([], ["git push"]), true) + + expect(effective.allowed).toEqual(["git"]) + expect(effective.denied).toEqual([]) + expect(effective.hiddenWorkspaceDeny).toEqual(["git push"]) +}) + +it("resolveEffectiveCommandLists: lets a global deny entry veto a longer workspace allow entry", () => { + const effective = resolveEffectiveCommandLists(listScopes([], ["git push"]), listScopes(["git"], []), true) + + expect(effective.allowed).toEqual([]) + expect(effective.denied).toEqual(["git"]) + expect(effective.hiddenWorkspaceAllow).toEqual(["git push"]) +}) + +it("resolveEffectiveCommandLists: silences every workspace deny entry behind a global wildcard allow entry", () => { + const effective = resolveEffectiveCommandLists(listScopes(["*"], []), listScopes([], ["git push", "rm -rf"]), true) + + expect(effective.allowed).toEqual(["*"]) + expect(effective.denied).toEqual([]) + expect(effective.hiddenWorkspaceDeny).toEqual(["git push", "rm -rf"]) +}) + +it("resolveEffectiveCommandLists: shadows workspace entries case-insensitively, the way the matcher matches", () => { + const effective = resolveEffectiveCommandLists( + listScopes(["Git"], ["git status"]), + listScopes([], ["DOCKER"]), + true, + ) + + expect(effective.allowed).toEqual(["Git"]) + expect(effective.denied).toEqual(["DOCKER"]) + expect(effective.hiddenWorkspaceAllow).toEqual(["git status"]) + expect(effective.hiddenWorkspaceDeny).toEqual([]) +}) diff --git a/src/core/auto-approval/__tests__/commands.spec.ts b/src/core/auto-approval/__tests__/commands.spec.ts index ade53c2b20..87f6f44f5b 100644 --- a/src/core/auto-approval/__tests__/commands.spec.ts +++ b/src/core/auto-approval/__tests__/commands.spec.ts @@ -1,4 +1,10 @@ -import { containsDangerousSubstitution, getCommandDecision, getCommandDecisionDetailed } from "../commands" +import { resolveEffectiveCommandLists } from "../commandScope" +import { + containsDangerousSubstitution, + getCommandDecision, + getCommandDecisionDetailed, + isShadowedByAnyEntry, +} from "../commands" describe("containsDangerousSubstitution", () => { describe("zsh array assignments (should NOT be flagged)", () => { @@ -215,3 +221,82 @@ describe("getCommandDecisionDetailed", () => { } }) }) + +it("isShadowedByAnyEntry: shadows an entry whose every match a prefixing entry also matches", () => { + expect(isShadowedByAnyEntry("git push", ["git"])).toBe(true) + expect(isShadowedByAnyEntry("git push", ["git push"])).toBe(true) +}) + +it("isShadowedByAnyEntry: keeps an entry that decides matches no shadowing entry covers", () => { + expect(isShadowedByAnyEntry("git", ["git push"])).toBe(false) +}) + +it("isShadowedByAnyEntry: shadows every entry behind the universal wildcard", () => { + expect(isShadowedByAnyEntry("git push", ["*"])).toBe(true) + expect(isShadowedByAnyEntry("anything at all", ["*"])).toBe(true) +}) + +it("isShadowedByAnyEntry: compares case-insensitively, the way the matcher matches", () => { + expect(isShadowedByAnyEntry("Git Push", ["git"])).toBe(true) + expect(isShadowedByAnyEntry("git push", ["GIT"])).toBe(true) +}) + +it("isShadowedByAnyEntry: compares entries as stored, the way the matcher compares them", () => { + // The matcher trims commands, never entries, and shadowing mirrors that: + // both sides compare as stored. A trimmed comparison would let an inert + // padded entry erase a decidable one (and the reverse), deciding with a + // rule enforcement never applies. + expect(isShadowedByAnyEntry(" git push ", ["git"])).toBe(false) + expect(isShadowedByAnyEntry("git push", [" git "])).toBe(false) +}) + +it("layered decisions: a padded global deny entry cannot erase a workspace deny entry", () => { + // The padded global entry is inert at enforcement, so it must not shadow + // the workspace entry the matcher does honor: the deny survives. + const scopes = (globalList: string[], workspaceList: string[]) => ({ + global: globalList, + workspace: workspaceList, + merged: [...new Set([...globalList, ...workspaceList])], + }) + const effective = resolveEffectiveCommandLists(scopes([" git"], []), scopes([], ["git push"]), true) + + expect(getCommandDecision("git push origin", effective.allowed, effective.denied)).toBe("auto_deny") +}) + +it("layered decisions: a padded global allow entry cannot erase a workspace allow entry", () => { + // Mirror of the deny side: the inert padded entry leaves the workspace + // allow entry effective, so the command is approved rather than downgraded + // to a prompt for a match no entry can produce. + const scopes = (globalList: string[], workspaceList: string[]) => ({ + global: globalList, + workspace: workspaceList, + merged: [...new Set([...globalList, ...workspaceList])], + }) + const effective = resolveEffectiveCommandLists(scopes([" git"], ["git push"]), scopes([], []), true) + + expect(getCommandDecision("git push origin", effective.allowed, effective.denied)).toBe("auto_approve") +}) + +it("isShadowedByAnyEntry: never treats an empty entry as covered", () => { + // Compared naively, an empty entry prefix-matches every command, so + // against an empty shadow entry it would report itself covered. The + // empty-entry guard keeps such an entry visible instead. Command-list + // layers sanitize blanks before shadowing, so this pins the function's + // contract directly. + expect(isShadowedByAnyEntry("", [""])).toBe(false) + expect(isShadowedByAnyEntry("", ["git"])).toBe(false) +}) + +it("layered decisions: reproduces the global-decides precedence through the scope-blind matcher", () => { + // Global deny "git" vs workspace allow "git push": the composed lists + // drop the shadowed allow entry, so the scope-blind matcher — never told + // about layers — returns the global layer's deny. + const scopes = (globalList: string[], workspaceList: string[]) => ({ + global: globalList, + workspace: workspaceList, + merged: [...new Set([...globalList, ...workspaceList])], + }) + const effective = resolveEffectiveCommandLists(scopes([], ["git push"]), scopes(["git"], []), true) + + expect(getCommandDecision("git push origin", effective.allowed, effective.denied)).toBe("auto_deny") +}) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index d57e77bf7d..03d464559f 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -1,6 +1,8 @@ +import { DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED } from "@roo-code/types" import * as vscode from "vscode" import { Package } from "../../shared/package" +import { isShadowedByAnyEntry } from "./commands" export type CommandListConfigKey = "allowedCommands" | "deniedCommands" @@ -182,6 +184,79 @@ export function resolveWorkspaceWriteTarget( return undefined } +/** + * Reads the `zoo-code.workspaceCommandListsEnabled` gate that decides whether + * the workspace layers of the command-list keys take part in enforcement and + * display at all. The configuration declares the key with `scope: + * "application"`, so only user settings can flip it. The lookup is guarded + * leniently like the command-list reads: a configuration failure keeps the + * workspace layers inert, which cannot widen what auto-approval allows. + */ +export function workspaceCommandListsEnabled(): boolean { + try { + return commandListConfiguration().get("workspaceCommandListsEnabled") === true + } catch { + return DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED + } +} + +export interface EffectiveCommandLists { + allowed: string[] + denied: string[] + /** + * Workspace allow entries absent from the effective allowlist — hidden by + * the gate or shadowed by a global entry — which a dialog save must not be + * able to delete by omission. + */ + hiddenWorkspaceAllow: string[] + /** Deny-side counterpart of {@link hiddenWorkspaceAllow}. */ + hiddenWorkspaceDeny: string[] +} + +/** + * Composes the raw per-key layers into the pair of lists to enforce and + * display, keeping display byte-equal to enforcement. + * + * Gate off: the workspace layers contribute nothing and the global layers are + * effective verbatim. Gate on: a workspace entry survives only when no entry + * of either global list shadows it, so a global entry decides every command it + * matches while workspace entries apply where the global layer is silent. + * Shadowing is cross-directional because a global allow entry silences a + * workspace deny entry (and vice versa) just as much as a same-list shadow. + * + * Composing here — not inside {@link readCommandListScopes} — keeps the raw + * layers intact for the save path, which derives the write split from them and + * must never see entries filtered out of the workspace layer. + * + * @param allowScopes - Raw `allowedCommands` layers from readCommandListScopes. + * @param denyScopes - Raw `deniedCommands` layers from readCommandListScopes. + * @param enabled - The value of the `workspaceCommandListsEnabled` gate. + * @returns The effective allow/deny lists and the workspace entries hidden + * from each. + */ +export function resolveEffectiveCommandLists( + allowScopes: CommandListScopes, + denyScopes: CommandListScopes, + enabled: boolean, +): EffectiveCommandLists { + const globalEntries = [...allowScopes.global, ...denyScopes.global] + + const keptAllow = enabled + ? allowScopes.workspace.filter((entry) => !isShadowedByAnyEntry(entry, globalEntries)) + : [] + const keptDeny = enabled ? denyScopes.workspace.filter((entry) => !isShadowedByAnyEntry(entry, globalEntries)) : [] + + const allowed = [...new Set([...allowScopes.global, ...keptAllow])] + const denied = [...new Set([...denyScopes.global, ...keptDeny])] + + return { + allowed, + denied, + hiddenWorkspaceAllow: allowScopes.workspace.filter((entry) => !allowed.includes(entry)), + hiddenWorkspaceDeny: denyScopes.workspace.filter((entry) => !denied.includes(entry)), + } +} + function sanitizeCommandList(list: unknown): string[] { if (!Array.isArray(list)) { return [] diff --git a/src/core/auto-approval/commands.ts b/src/core/auto-approval/commands.ts index 9d7289c265..8f3020a5f0 100644 --- a/src/core/auto-approval/commands.ts +++ b/src/core/auto-approval/commands.ts @@ -113,6 +113,34 @@ export function findLongestPrefixMatch(command: string, prefixes: string[]): str return longestMatch } +/** + * Whether one command-list entry is covered by any entry of `shadowing`. + * + * "Covered" applies the matcher's comparison — case-insensitive `startsWith` + * with `"*"` as universal prefix — directly to the two stored entries: only + * commands reach the matcher trimmed, entries never are, so an entry whose + * stored form carries leading whitespace matches no command and can shadow + * only other entries that match nothing either. An entry whose every possible + * match is also matched by some `shadowing` entry cannot decide anything on + * its own: that layer's decision stands. Dropping covered entries when + * composing layers reproduces a global-decides precedence without the matcher + * knowing about layers. + * + * @param entry - The entry that may be covered. + * @param shadowing - The entries whose match coverage decides. + * @returns true if some `shadowing` entry covers `entry`. An empty `entry` + * counts as covered only by `"*"`: the guard that stops it prefix-matching + * every command keeps a blank entry visible, as it cannot be enforced. + */ +export function isShadowedByAnyEntry(entry: string, shadowing: string[]): boolean { + const lowerEntry = entry.toLowerCase() + + return shadowing.some((shadow) => { + const lowerShadow = shadow.toLowerCase() + return lowerShadow === "*" || (lowerEntry !== "" && lowerEntry.startsWith(lowerShadow)) + }) +} + /** * Check if a single command should be auto-approved. * Returns true only for commands that explicitly match the allowlist diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 78ac7c4870..ef75a01cc9 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -54,6 +54,7 @@ import { ORGANIZATION_ALLOW_ALL, DEFAULT_MODES, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, + DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, getModelId, isRetiredProvider, providerIdentifiers, @@ -112,7 +113,11 @@ import { forceFullModelDetailsLoad, hasLoadedFullDetails } from "../../api/provi import { ContextProxy } from "../config/ContextProxy" import { ProviderSettingsManager } from "../config/ProviderSettingsManager" import { CustomModesManager } from "../config/CustomModesManager" -import { readCommandListScopes } from "../auto-approval/commandScope" +import { + readCommandListScopes, + resolveEffectiveCommandLists, + workspaceCommandListsEnabled, +} from "../auto-approval/commandScope" import { PendingActionSettlementError, Task } from "../task/Task" import { webviewMessageHandler } from "./webviewMessageHandler" @@ -2549,6 +2554,7 @@ export class ClineProvider alwaysDenyUnapprovedCommands, allowedCommands, deniedCommands, + workspaceCommandListsEnabled: gateEnabled, alwaysAllowMcp, alwaysAllowModeSwitch, alwaysAllowSubtasks, @@ -2729,8 +2735,11 @@ export class ClineProvider checkpointTimeout: checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, shouldShowAnnouncement: telemetrySetting !== "unset" && lastShownAnnouncementId !== this.latestAnnouncementId, - allowedCommands: allowedCommands ?? [], - deniedCommands: deniedCommands ?? [], + // getState() always resolves these to the effective command lists + // (never undefined), so no fallback is needed here. + allowedCommands, + deniedCommands, + workspaceCommandListsEnabled: gateEnabled ?? DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, soundVolume: soundVolume ?? 0.5, writeDelayMs: writeDelayMs ?? DEFAULT_WRITE_DELAY_MS, diffFuzzyThreshold: diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD, @@ -2930,6 +2939,14 @@ export class ClineProvider const taskSyncEnabled: boolean = false + // One gate read and one resolver pass per getState() call, so the + // effective lists and the gate value posted together describe a single + // configuration state. + const gateEnabled = workspaceCommandListsEnabled() + const allowScopes = readCommandListScopes("allowedCommands", stateValues.allowedCommands) + const denyScopes = readCommandListScopes("deniedCommands", stateValues.deniedCommands) + const effectiveCommandLists = resolveEffectiveCommandLists(allowScopes, denyScopes, gateEnabled) + // Return the same structure as before. return { apiConfiguration: providerSettings, @@ -2959,11 +2976,13 @@ export class ClineProvider autoCondenseContext: stateValues.autoCondenseContext ?? true, autoCondenseContextPercent: stateValues.autoCondenseContextPercent ?? 100, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], - // Enforce and display the set union of the global-state layer and the - // workspace-scope configuration layer; getStateToPostToWebview shows + // Enforce and display the effective lists that + // resolveEffectiveCommandLists composes from the global-state and + // workspace-scope configuration layers; getStateToPostToWebview shows // exactly these values, so display cannot drift from enforcement. - allowedCommands: readCommandListScopes("allowedCommands", stateValues.allowedCommands).merged, - deniedCommands: readCommandListScopes("deniedCommands", stateValues.deniedCommands).merged, + allowedCommands: effectiveCommandLists.allowed, + deniedCommands: effectiveCommandLists.denied, + workspaceCommandListsEnabled: gateEnabled, soundEnabled: stateValues.soundEnabled ?? false, ttsEnabled: stateValues.ttsEnabled ?? false, ttsSpeed: stateValues.ttsSpeed ?? 1.0, diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 4a96fadde0..abae55de55 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -18,6 +18,7 @@ import { ORGANIZATION_ALLOW_ALL, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, DEFAULT_DIFF_FUZZY_THRESHOLD, + DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, DEFAULT_WRITE_DELAY_MS, providerIdentifiers, openAiModelInfoSaneDefaults, @@ -27,6 +28,7 @@ import { TelemetryService } from "@roo-code/telemetry" import { defaultModeSlug } from "../../../shared/modes" import { experimentDefault } from "../../../shared/experiments" import { setTtsEnabled } from "../../../utils/tts" +import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { ContextProxy } from "../../config/ContextProxy" import { WorkspaceIndexingEnablementManager } from "../../../services/code-index/workspace-indexing-enablement-manager" import { Task, TaskOptions } from "../../task/Task" @@ -1625,9 +1627,11 @@ describe("ClineProvider", () => { } as unknown as vscode.WorkspaceConfiguration) }) + // The gate is a synchronous configuration read, so the doubles make the + // `get` lookup key-aware: only the gate key reports true here. test("getState enforces workspace-scope denied commands even when global state is empty", async () => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ - get: vi.fn().mockReturnValue([]), + get: vi.fn().mockImplementation((key: string) => key === "workspaceCommandListsEnabled"), inspect: vi .fn() .mockImplementation((key: string) => @@ -1641,11 +1645,11 @@ describe("ClineProvider", () => { expect(state.deniedCommands).toEqual(["docker"]) }) - test("getStateToPostToWebview shows the same merged command lists as getState", async () => { + test("getStateToPostToWebview shows the same effective command lists as getState", async () => { await provider.resolveWebviewView(mockWebviewView) await provider.contextProxy.setValue("deniedCommands", ["git"]) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ - get: vi.fn().mockReturnValue(["git", "docker"]), + get: vi.fn().mockImplementation((key: string) => key === "workspaceCommandListsEnabled"), inspect: vi .fn() .mockImplementation((key: string) => @@ -1656,15 +1660,16 @@ describe("ClineProvider", () => { const state = await provider.getStateToPostToWebview() - // Display is the set union of global state and workspace scope, matching - // what getState() enforces. + // The workspace entry survives because no global entry shadows it, so + // display is the global layer plus that entry — exactly what + // getState() enforces. expect(state.deniedCommands).toEqual(["git", "docker"]) expect(state.allowedCommands).toEqual([]) }) test("getState prefers the workspace-folder value for multi-root workspaces", async () => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ - get: vi.fn().mockReturnValue(["docker", "pnpm docker"]), + get: vi.fn().mockImplementation((key: string) => key === "workspaceCommandListsEnabled"), inspect: vi .fn() .mockImplementation((key: string) => @@ -1682,6 +1687,77 @@ describe("ClineProvider", () => { // leak into the workspace layer. expect(state.deniedCommands).toEqual(["pnpm docker"]) }) + + // A workspace-only allow entry is exactly what the gate decides: enabled + // it joins the effective lists enforcement uses; disabled enforcement ignores it. + function mockGateConfiguration(enabled: boolean) { + // The shared double reports scripted values through `get`, which + // is how the gate reader sees its value; the per-key `inspect` + // override supplies the allow-side workspace layer. + const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: enabled }) + const inspect = vi.fn() + inspect.mockImplementation((key: string) => + key === "allowedCommands" ? { key, workspaceValue: ["docker"] } : undefined, + ) + config.inspect = inspect + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + } + + test("a workspace-only allow entry surfaces through getState and getStateToPostToWebview when the gate is on", async () => { + await provider.resolveWebviewView(mockWebviewView) + mockGateConfiguration(true) + + const state = await provider.getState() + const postedState = await provider.getStateToPostToWebview() + + expect(state.allowedCommands).toEqual(["docker"]) + expect(postedState.allowedCommands).toEqual(["docker"]) + }) + + test("a workspace-only allow entry is absent from getState and getStateToPostToWebview when the gate is off", async () => { + await provider.resolveWebviewView(mockWebviewView) + mockGateConfiguration(false) + + const state = await provider.getState() + const postedState = await provider.getStateToPostToWebview() + + expect(state.allowedCommands).toEqual([]) + expect(postedState.allowedCommands).toEqual([]) + }) + + test("getState returns the saved workspace command-list gate value", async () => { + mockGateConfiguration(true) + + const state = await provider.getState() + + expect(state.workspaceCommandListsEnabled).toBe(true) + }) + + test("getState defaults the workspace command-list gate to the shared constant", async () => { + mockGateConfiguration(false) + + const state = await provider.getState() + + expect(state.workspaceCommandListsEnabled).toBe(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED) + }) + + test("getStateToPostToWebview returns the saved workspace command-list gate value", async () => { + await provider.resolveWebviewView(mockWebviewView) + mockGateConfiguration(true) + + const state = await provider.getStateToPostToWebview() + + expect(state.workspaceCommandListsEnabled).toBe(true) + }) + + test("getStateToPostToWebview defaults the workspace command-list gate to the shared constant", async () => { + await provider.resolveWebviewView(mockWebviewView) + mockGateConfiguration(false) + + const state = await provider.getStateToPostToWebview() + + expect(state.workspaceCommandListsEnabled).toBe(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED) + }) }) test("getState returns the saved allowed read files", async () => { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 1a3ffaa3ae..a4096753c1 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1455,14 +1455,21 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // is awaited by the handler, so a rejected promise fails that write), in // call order; a plain value resolves like the default mock, and an Error // element makes that call throw. + type InspectedCommandList = { + globalValue?: string[] + workspaceValue?: string[] + workspaceFolderValue?: string[] + } + + // `inspected` may be a function of the requested key so a two-key payload + // test can give each list its own layers. `gateEnabled` scripts the + // `workspaceCommandListsEnabled` configuration read; leaving it unset + // keeps the gate off, matching the extension default. function mockCommandConfiguration( - inspected: { - globalValue?: string[] - workspaceValue?: string[] - workspaceFolderValue?: string[] - }, + inspected: InspectedCommandList | ((key: string) => InspectedCommandList), updateSequence?: unknown[], inspectSequence?: unknown[], + gateEnabled?: boolean, ) { const update = vi.fn() if (updateSequence) { @@ -1478,11 +1485,13 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { return next }) } else { - inspect.mockReturnValue(inspected) + inspect.mockImplementation((key: string) => (typeof inspected === "function" ? inspected(key) : inspected)) } // The shared structurally complete double keeps the configuration type // correct; the scripted members are installed per test. - const config = makeWorkspaceConfiguration() + const config = makeWorkspaceConfiguration( + gateEnabled === undefined ? {} : { workspaceCommandListsEnabled: gateEnabled }, + ) config.update = update config.inspect = inspect vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) @@ -1504,10 +1513,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // Extension global state holds only the global layer, so the next save // cannot double-home the workspace entry. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) - // Exactly one snapshot per key: the scope read, write target, and - // rollback all derive from the same inspect(), so a helper re-reading - // the configuration would raise this count and could diverge. - expect(inspect).toHaveBeenCalledTimes(1) + // One snapshot per command-list key: this key's scope read, write + // target, and rollback all derive from the same inspect(), and the + // shadowing check reads the opposite key through its own guarded + // snapshot, so the count is two, never more. + expect(inspect).toHaveBeenCalledTimes(2) }) it("writes the workspace-folder value at the folder target in multi-root workspaces", async () => { @@ -1528,7 +1538,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("clears a deleted workspace entry at the workspace scope without adding it to global", async () => { - const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }) + // Gate on: the entry is visible in the dialog, and only visible entries + // are deletable there (a hidden entry is re-added by the preservation + // rule instead). + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -1558,6 +1571,30 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git"]) }) + it("restores the raw workspace value when a workspace-target global write fails", async () => { + // With no folder layer the rewind must read the workspace value, not + // the absent folder value. The raw value holds the entry this save + // dropped, so the restore call is distinguishable from the workspace + // write itself and provably uses the raw inspected value. + const { update } = mockCommandConfiguration({ workspaceValue: ["npm docker", "docker"] }, [ + undefined, + Promise.reject(new Error("disk on fire")), + ]) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenCalledWith( + "deniedCommands", + ["npm docker", "docker"], + vscode.ConfigurationTarget.Workspace, + ) + expect(update).toHaveBeenCalledTimes(3) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: disk on fire") + }) + it("restores the previous workspace value when the global write fails", async () => { // update() call order: workspace write succeeds, global write rejects. // The raw folder-layer value differs from the sanitized post-split layer @@ -1710,6 +1747,115 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // No exception escaped the handler: the state post still ran. expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) + + // Entries the dialog never displayed — hidden while the gate is off, or + // shadowed by a global entry with it on — cannot be deleted by omission + // from a list the user could not see, so a save re-adds them to the + // workspace layer it rewrites. + it("re-adds gate-hidden workspace entries to the workspace write instead of deleting them", async () => { + const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // The gate is off, so the dialog displayed nothing for this key. + updatedSettings: { deniedCommands: [] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + }) + + it("keeps hidden workspace entries out of the global write", async () => { + const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + }) + + // Preservation is workspace-side only: re-adding hidden entries must + // not leak them into the user's global settings. + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) + }) + + it("re-adds a workspace deny entry shadowed by a global allow entry when the gate is on", async () => { + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git"] : undefined, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // "git push" is shadowed by the global allow "git", so the dialog + // displayed nothing deletable. + updatedSettings: { deniedCommands: [] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + }) + + it("re-adds a shadowed workspace allow entry alongside the user's visible deletions", async () => { + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["git"] : undefined, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "allowedCommands" ? { workspaceValue: ["git", "docker"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // "docker" stayed visible and kept; "git" was hidden by the global + // deny, and a workspace entry the user never saw is not deletable. + updatedSettings: { allowedCommands: ["docker"] }, + }) + + expect(update).toHaveBeenCalledWith("allowedCommands", ["docker", "git"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + }) + + it("does not persist a webview-supplied workspaceCommandListsEnabled value", async () => { + mockCommandConfiguration({}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // A settings payload is not a second source for the gate: the + // synchronous user-scope configuration read is. + updatedSettings: { workspaceCommandListsEnabled: true, alwaysDenyUnapprovedCommands: true }, + }) + + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith( + "workspaceCommandListsEnabled", + expect.anything(), + ) + // Sibling keys of the same payload are unaffected by the refusal. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) + }) + + it("abandons a payload carrying only the gate key without writing configuration", async () => { + const { update } = mockCommandConfiguration({}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { workspaceCommandListsEnabled: true }, + }) + + expect(update).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + // The state post still runs, so the dialog re-reads the effective value + // instead of keeping the refused one. + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) }) describe("webviewMessageHandler - terminalProfile", () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6d198f57fe..9e9e0ef6ea 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -63,8 +63,10 @@ import { type CommandListInspection, commandListConfiguration, readCommandListScopes, + resolveEffectiveCommandLists, resolveWorkspaceWriteTarget, splitCommandListScopes, + workspaceCommandListsEnabled, } from "../auto-approval/commandScope" import { type RouterName, toRouterName } from "../../shared/api" import { MessageEnhancer } from "./messageEnhancer" @@ -758,6 +760,13 @@ export const webviewMessageHandler = async ( if (key === "language") { newValue = value ?? "en" changeLanguage(newValue as Language) + } else if (key === "workspaceCommandListsEnabled") { + // The gate's effective value is the synchronous + // user-scope configuration read that enforcement and + // display already perform; a value arriving in a + // settings payload is not a second source that can flip + // it, so it is never persisted here. + continue } else if (key === "allowedCommands" || key === "deniedCommands") { const commands = value ?? [] @@ -798,11 +807,34 @@ export const webviewMessageHandler = async ( } const currentScopes = readCommandListScopes(key, getGlobalState(key), inspection) - const { globalWrite, workspaceWrite } = splitCommandListScopes( + const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( incoming, currentScopes.workspace, currentScopes.global, ) + + // Shadowing is cross-directional, so the hidden-entry + // set needs the opposite key's global layer as input. + // That opposite-key read is a fresh guarded read: it + // only feeds the additive preservation below and never + // this key's split, target, or rollback, which stay on + // the single snapshot. + const otherKey = key === "allowedCommands" ? "deniedCommands" : "allowedCommands" + const otherScopes = readCommandListScopes(otherKey, getGlobalState(otherKey)) + const { hiddenWorkspaceAllow, hiddenWorkspaceDeny } = resolveEffectiveCommandLists( + key === "allowedCommands" ? currentScopes : otherScopes, + key === "deniedCommands" ? currentScopes : otherScopes, + workspaceCommandListsEnabled(), + ) + // Entries hidden from the dialog — while the gate is off, + // or shadowed by a global entry with it on — cannot be + // deleted through a list that never displayed them, so a + // save re-adds them to the workspace layer it rewrites. + // Users remove those directly in the workspace settings + // file. + const hiddenWorkspaceEntries = + key === "allowedCommands" ? hiddenWorkspaceAllow : hiddenWorkspaceDeny + const workspaceWrite = [...new Set([...keptWorkspaceWrite, ...hiddenWorkspaceEntries])] const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) // The two configuration writes below are not atomic, so the raw diff --git a/src/package.json b/src/package.json index 0931ca779d..c3993fd984 100644 --- a/src/package.json +++ b/src/package.json @@ -317,6 +317,13 @@ "default": [], "description": "%commands.deniedCommands.description%" }, + "zoo-code.workspaceCommandListsEnabled": { + "type": "boolean", + "default": false, + "scope": "application", + "description": "%settings.workspaceCommandListsEnabled.description%", + "markdownDescription": "%settings.workspaceCommandListsEnabled.description%" + }, "zoo-code.commandExecutionTimeout": { "type": "number", "default": 0, diff --git a/src/package.nls.ca.json b/src/package.nls.ca.json index b1397adf71..69da12747e 100644 --- a/src/package.nls.ca.json +++ b/src/package.nls.ca.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Accepta certificats auto-signats del proxy. **Requerit per a la inspecció MITM.** ⚠️ Insegur — utilitza-ho només per a debugging local.", "settings.workspace.rootResolution.description": "Com resol Zoo l'arrel de l'espai de treball en un espai de treball multi-arrel. L'arrel s'utilitza per localitzar `.roomodes`, `.roo/mcp.json`, `.roo/rules/` i altra configuració d'àmbit de projecte. Canviar aquest paràmetre només afecta les cerques futures; les tasques en execució conserven la seva arrel original.", "settings.workspace.rootResolution.activeEditor.description": "Utilitza la carpeta de l'espai de treball que conté l'editor actiu; recorre a la primera carpeta de l'espai de treball. (Per defecte — conserva el comportament heretat.)", - "settings.workspace.rootResolution.firstFolder.description": "Utilitza sempre la primera carpeta de l'espai de treball (workspaceFolders[0]). Determinista — independent del fitxer que tingui el focus en aquest moment." + "settings.workspace.rootResolution.firstFolder.description": "Utilitza sempre la primera carpeta de l'espai de treball (workspaceFolders[0]). Determinista — independent del fitxer que tingui el focus en aquest moment.", + "settings.workspaceCommandListsEnabled.description": "Activa les llistes de comandes aportades pels ajustos de l'espai de treball (els valors de `zoo-code.allowedCommands` i `zoo-code.deniedCommands` als fitxers d'ajustos de l'espai de treball). Mentre estigui desactivada, les llistes de comandes de l'espai de treball no tenen cap efecte. Quan estigui activada, les entrades de nivell d'usuari tenen preferència: una entrada de nivell d'usuari decideix qualsevol comanda que coincideixi, i les entrades de l'espai de treball només s'apliquen a les comandes amb què cap entrada de nivell d'usuari no coincideix. Aquest paràmetre només es pot canviar als [paràmetres d'usuari](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.de.json b/src/package.nls.de.json index b4cd8440ab..59a4f82034 100644 --- a/src/package.nls.de.json +++ b/src/package.nls.de.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Akzeptiere selbstsignierte Zertifikate vom Proxy. **Erforderlich für MITM-Inspektion.** ⚠️ Unsicher – verwende das nur für lokales Debugging.", "settings.workspace.rootResolution.description": "Wie Zoo das Workspace-Stammverzeichnis in einem Multi-Root-Workspace auflöst. Das Stammverzeichnis wird verwendet, um `.roomodes`, `.roo/mcp.json`, `.roo/rules/` und andere projektbezogene Konfiguration zu finden. Eine Änderung dieser Einstellung wirkt sich nur auf zukünftige Suchen aus; laufende Aufgaben behalten ihr ursprüngliches Stammverzeichnis.", "settings.workspace.rootResolution.activeEditor.description": "Verwende den Workspace-Ordner, der den aktiven Editor enthält; greife auf den ersten Workspace-Ordner zurück. (Standard – behält das bisherige Verhalten bei.)", - "settings.workspace.rootResolution.firstFolder.description": "Verwende immer den ersten Workspace-Ordner (workspaceFolders[0]). Deterministisch – unabhängig davon, welche Datei gerade fokussiert ist." + "settings.workspace.rootResolution.firstFolder.description": "Verwende immer den ersten Workspace-Ordner (workspaceFolders[0]). Deterministisch – unabhängig davon, welche Datei gerade fokussiert ist.", + "settings.workspaceCommandListsEnabled.description": "Aktiviert die von Workspace-Einstellungen beigesteuerten Befehlslisten (die Werte von `zoo-code.allowedCommands` und `zoo-code.deniedCommands` in Workspace-Einstellungsdateien). Solange deaktiviert, haben Workspace-Befehlslisten keine Auswirkung. Wenn aktiviert, haben Einträge auf Benutzerebene Vorrang: Ein Eintrag auf Benutzerebene entscheidet über jeden Befehl, mit dem er übereinstimmt, und Workspace-Einträge gelten nur für Befehle, mit denen kein Eintrag auf Benutzerebene übereinstimmt. Diese Einstellung kann nur in den [Benutzereinstellungen](https://code.visualstudio.com/docs/getstarted/settings) geändert werden." } diff --git a/src/package.nls.es.json b/src/package.nls.es.json index 1d86a70980..86ca2c380a 100644 --- a/src/package.nls.es.json +++ b/src/package.nls.es.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Aceptar certificados autofirmados del proxy. **Necesario para la inspección MITM.** ⚠️ Inseguro: úsalo solo para depuración local.", "settings.workspace.rootResolution.description": "Cómo resuelve Zoo la raíz del espacio de trabajo en un espacio de trabajo multi-raíz. La raíz se usa para localizar `.roomodes`, `.roo/mcp.json`, `.roo/rules/` y otra configuración del ámbito del proyecto. Cambiar este ajuste solo afecta a las búsquedas futuras; las tareas en ejecución conservan su raíz original.", "settings.workspace.rootResolution.activeEditor.description": "Usa la carpeta del espacio de trabajo que contiene el editor activo; recurre a la primera carpeta del espacio de trabajo. (Predeterminado: conserva el comportamiento heredado.)", - "settings.workspace.rootResolution.firstFolder.description": "Usa siempre la primera carpeta del espacio de trabajo (workspaceFolders[0]). Determinista: independiente del archivo que tenga el foco en ese momento." + "settings.workspace.rootResolution.firstFolder.description": "Usa siempre la primera carpeta del espacio de trabajo (workspaceFolders[0]). Determinista: independiente del archivo que tenga el foco en ese momento.", + "settings.workspaceCommandListsEnabled.description": "Habilita las listas de comandos aportadas por la configuración del espacio de trabajo (los valores de `zoo-code.allowedCommands` y `zoo-code.deniedCommands` en los archivos de configuración del espacio de trabajo). Mientras esté deshabilitada, las listas de comandos del espacio de trabajo no tienen ningún efecto. Cuando esté habilitada, las entradas de nivel de usuario tienen prioridad: una entrada de nivel de usuario decide cualquier comando que coincida, y las entradas del espacio de trabajo solo se aplican a los comandos con los que ninguna entrada de nivel de usuario coincide. Este ajuste solo se puede cambiar en la [configuración de usuario](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.fr.json b/src/package.nls.fr.json index 85207df975..40b15fd067 100644 --- a/src/package.nls.fr.json +++ b/src/package.nls.fr.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Accepter les certificats auto-signés du proxy. **Requis pour l'inspection MITM.** ⚠️ Non sécurisé — à utiliser uniquement pour le debug local.", "settings.workspace.rootResolution.description": "Comment Zoo résout la racine de l'espace de travail dans un espace de travail multi-racine. La racine sert à localiser `.roomodes`, `.roo/mcp.json`, `.roo/rules/` et d'autres configurations propres au projet. Modifier ce paramètre n'affecte que les recherches futures ; les tâches en cours conservent leur racine d'origine.", "settings.workspace.rootResolution.activeEditor.description": "Utilise le dossier de l'espace de travail contenant l'éditeur actif ; revient au premier dossier de l'espace de travail. (Par défaut — conserve le comportement hérité.)", - "settings.workspace.rootResolution.firstFolder.description": "Utilise toujours le premier dossier de l'espace de travail (workspaceFolders[0]). Déterministe — indépendant du fichier actuellement ciblé." + "settings.workspace.rootResolution.firstFolder.description": "Utilise toujours le premier dossier de l'espace de travail (workspaceFolders[0]). Déterministe — indépendant du fichier actuellement ciblé.", + "settings.workspaceCommandListsEnabled.description": "Active les listes de commandes issues des paramètres de l'espace de travail (les valeurs de `zoo-code.allowedCommands` et `zoo-code.deniedCommands` dans les fichiers de paramètres de l'espace de travail). Lorsqu'elle est désactivée, les listes de commandes de l'espace de travail n'ont aucun effet. Lorsqu'elle est activée, les entrées de niveau utilisateur ont la priorité : une entrée de niveau utilisateur décide de toute commande à laquelle elle correspond, et les entrées de l'espace de travail ne s'appliquent qu'aux commandes pour lesquelles aucune entrée de niveau utilisateur ne correspond. Ce paramètre ne peut être modifié que dans les [paramètres utilisateur](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.hi.json b/src/package.nls.hi.json index f4f283bb65..92bd9f82fb 100644 --- a/src/package.nls.hi.json +++ b/src/package.nls.hi.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Proxy से आने वाले self-signed certificates accept करो। **MITM inspection के लिए ज़रूरी।** ⚠️ Insecure — सिर्फ local debugging के लिए इस्तेमाल करो।", "settings.workspace.rootResolution.description": "Multi-root workspace में Zoo workspace root को कैसे resolve करता है। Root का इस्तेमाल `.roomodes`, `.roo/mcp.json`, `.roo/rules/` और दूसरी project-scoped configuration ढूंढने के लिए होता है। इस setting को बदलने का असर सिर्फ आगे की lookups पर पड़ता है; चल रहे tasks अपना original root बनाए रखते हैं।", "settings.workspace.rootResolution.activeEditor.description": "उस workspace folder का इस्तेमाल करो जिसमें active editor है; पहले workspace folder पर fall back करो। (Default — legacy behavior बनाए रखता है।)", - "settings.workspace.rootResolution.firstFolder.description": "हमेशा पहले workspace folder (workspaceFolders[0]) का इस्तेमाल करो। Deterministic — इस बात से स्वतंत्र कि अभी कौन सी file focused है।" + "settings.workspace.rootResolution.firstFolder.description": "हमेशा पहले workspace folder (workspaceFolders[0]) का इस्तेमाल करो। Deterministic — इस बात से स्वतंत्र कि अभी कौन सी file focused है।", + "settings.workspaceCommandListsEnabled.description": "Workspace settings द्वारा दी गई command lists को सक्रिय करো (workspace settings files में `zoo-code.allowedCommands` और `zoo-code.deniedCommands` के मान)। जब तक इह निष्क्रिय है, workspace command lists का कौनो प्रभाव नाहीं होतै। सक्रिय करतै पर user-level entries कौ प्राथमिकत मिलतै है: हर user-level entry उन सब्ह commands कौ तय करतै है जिनसै वह मेल खातै है, अऊर workspace entries केवल उन commands पर लागू होतै हैं जिनसै कौनो user-level entry मेल नाहीं खातै। इस setting कौ केवल [user settings](https://code.visualstudio.com/docs/getstarted/settings) में बदल जा सकतै है।" } diff --git a/src/package.nls.id.json b/src/package.nls.id.json index c49e54a34e..a7da9e8d62 100644 --- a/src/package.nls.id.json +++ b/src/package.nls.id.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Terima sertifikat self-signed dari proxy. **Diperlukan untuk inspeksi MITM.** ⚠️ Tidak aman — gunakan hanya untuk debugging lokal.", "settings.workspace.rootResolution.description": "Bagaimana Zoo menentukan root workspace di workspace multi-root. Root digunakan untuk menemukan `.roomodes`, `.roo/mcp.json`, `.roo/rules/`, dan konfigurasi lain yang bersifat project-scoped. Mengubah pengaturan ini hanya memengaruhi pencarian berikutnya; task yang sedang berjalan tetap memakai root aslinya.", "settings.workspace.rootResolution.activeEditor.description": "Gunakan folder workspace yang berisi editor aktif; kembali ke folder workspace pertama. (Default — mempertahankan perilaku lama.)", - "settings.workspace.rootResolution.firstFolder.description": "Selalu gunakan folder workspace pertama (workspaceFolders[0]). Deterministik — tidak bergantung pada file mana yang sedang difokuskan." + "settings.workspace.rootResolution.firstFolder.description": "Selalu gunakan folder workspace pertama (workspaceFolders[0]). Deterministik — tidak bergantung pada file mana yang sedang difokuskan.", + "settings.workspaceCommandListsEnabled.description": "Aktifkan daftar perintah yang disediakan oleh pengaturan workspace (nilai `zoo-code.allowedCommands` dan `zoo-code.deniedCommands` di file pengaturan workspace). Saat dinonaktifkan, daftar perintah workspace tidak memiliki efek apa pun. Saat diaktifkan, entri level pengguna lebih diutamakan: entri level pengguna menentukan perintah mana pun yang cocok dengannya, dan entri workspace hanya berlaku untuk perintah yang tidak cocok dengan entri level pengguna mana pun. Pengaturan ini hanya dapat diubah di [pengaturan pengguna](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.it.json b/src/package.nls.it.json index 2a4b95f954..a3b557de7d 100644 --- a/src/package.nls.it.json +++ b/src/package.nls.it.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Accetta certificati autofirmati dal proxy. **Necessario per l'ispezione MITM.** ⚠️ Non sicuro — usalo solo per il debugging locale.", "settings.workspace.rootResolution.description": "Come Zoo determina la radice del workspace in un workspace multi-radice. La radice viene usata per individuare `.roomodes`, `.roo/mcp.json`, `.roo/rules/` e altra configurazione a livello di progetto. Modificare questa impostazione influisce solo sulle ricerche future; i task in esecuzione mantengono la loro radice originale.", "settings.workspace.rootResolution.activeEditor.description": "Usa la cartella del workspace che contiene l'editor attivo; ripiega sulla prima cartella del workspace. (Predefinito — mantiene il comportamento legacy.)", - "settings.workspace.rootResolution.firstFolder.description": "Usa sempre la prima cartella del workspace (workspaceFolders[0]). Deterministico — indipendente dal file attualmente attivo." + "settings.workspace.rootResolution.firstFolder.description": "Usa sempre la prima cartella del workspace (workspaceFolders[0]). Deterministico — indipendente dal file attualmente attivo.", + "settings.workspaceCommandListsEnabled.description": "Abilita gli elenchi di comandi forniti dalle impostazioni del workspace (i valori di `zoo-code.allowedCommands` e `zoo-code.deniedCommands` nei file delle impostazioni del workspace). Finché è disabilitata, gli elenchi di comandi del workspace non hanno alcun effetto. Quando è abilitata, le voci a livello utente hanno la precedenza: una voce a livello utente decide qualsiasi comando con cui corrisponde, e le voci del workspace si applicano solo ai comandi con cui nessuna voce a livello utente corrisponde. Questa impostazione può essere modificata solo nelle [impostazioni utente](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.ja.json b/src/package.nls.ja.json index 0f3f4a3cee..c5592cecb2 100644 --- a/src/package.nls.ja.json +++ b/src/package.nls.ja.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "プロキシからの自己署名証明書を許可します。**MITM インスペクションに必須です。** ⚠️ 危険な設定なので、ローカルでのデバッグにだけ使用してください。", "settings.workspace.rootResolution.description": "マルチルートワークスペースで Zoo がワークスペースルートをどのように解決するか。ルートは `.roomodes`、`.roo/mcp.json`、`.roo/rules/` などのプロジェクト単位の設定を見つけるために使われます。この設定の変更は今後の検索にのみ影響し、実行中のタスクは元のルートを保持します。", "settings.workspace.rootResolution.activeEditor.description": "アクティブなエディタを含むワークスペースフォルダを使用し、最初のワークスペースフォルダにフォールバックします。(デフォルト — 従来の動作を維持します。)", - "settings.workspace.rootResolution.firstFolder.description": "常に最初のワークスペースフォルダ(workspaceFolders[0])を使用します。決定的で、現在フォーカスされているファイルに依存しません。" + "settings.workspace.rootResolution.firstFolder.description": "常に最初のワークスペースフォルダ(workspaceFolders[0])を使用します。決定的で、現在フォーカスされているファイルに依存しません。", + "settings.workspaceCommandListsEnabled.description": "ワークスペース設定が提供するコマンドリスト(ワークスペースの設定ファイル内の `zoo-code.allowedCommands` と `zoo-code.deniedCommands` の値)を有効にします。無効の間は、ワークスペースのコマンドリストは効果を持ちません。有効にすると、ユーザーレベルのエントリが優先されます。ユーザーレベルのエントリは、一致するコマンドをすべて決定し、ワークスペースのエントリはユーザーレベルのエントリが一致しないコマンドにのみ適用されます。この設定は[ユーザー設定](https://code.visualstudio.com/docs/getstarted/settings)でのみ変更できます。" } diff --git a/src/package.nls.json b/src/package.nls.json index fe10839819..bc4b7d15ca 100644 --- a/src/package.nls.json +++ b/src/package.nls.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Accept self-signed certificates from the proxy. **Required for MITM inspection.** ⚠️ Insecure — only use for local debugging.", "settings.workspace.rootResolution.description": "How Zoo resolves the workspace root in a multi-root workspace. The root is used to locate `.roomodes`, `.roo/mcp.json`, `.roo/rules/`, and other project-scoped configuration. Changing this setting only affects future lookups; running tasks keep their original root.", "settings.workspace.rootResolution.activeEditor.description": "Use the workspace folder containing the active editor; fall back to the first workspace folder. (Default — preserves legacy behavior.)", - "settings.workspace.rootResolution.firstFolder.description": "Always use the first workspace folder (workspaceFolders[0]). Deterministic — independent of which file is currently focused." + "settings.workspace.rootResolution.firstFolder.description": "Always use the first workspace folder (workspaceFolders[0]). Deterministic — independent of which file is currently focused.", + "settings.workspaceCommandListsEnabled.description": "Enable command lists contributed by workspace settings (`zoo-code.allowedCommands` and `zoo-code.deniedCommands` values in workspace settings files). While disabled, workspace command lists have no effect. When enabled, user-level entries take precedence: a user-level entry decides any command it matches, and workspace entries only apply to commands no user-level entry matches. This setting can only be changed in [user settings](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.ko.json b/src/package.nls.ko.json index 99a064cd6c..ec6c1a610b 100644 --- a/src/package.nls.ko.json +++ b/src/package.nls.ko.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "프록시의 self-signed 인증서를 허용합니다. **MITM 검사에 필요합니다.** ⚠️ 안전하지 않으므로 로컬 디버깅에만 사용하세요.", "settings.workspace.rootResolution.description": "멀티 루트 워크스페이스에서 Zoo가 워크스페이스 루트를 어떻게 결정하는지 설정합니다. 루트는 `.roomodes`, `.roo/mcp.json`, `.roo/rules/` 및 기타 프로젝트 범위 구성을 찾는 데 사용됩니다. 이 설정을 변경해도 이후의 조회에만 영향을 주며, 실행 중인 작업은 원래 루트를 유지합니다.", "settings.workspace.rootResolution.activeEditor.description": "활성 편집기가 있는 워크스페이스 폴더를 사용하고, 첫 번째 워크스페이스 폴더로 폴백합니다. (기본값 — 기존 동작을 유지합니다.)", - "settings.workspace.rootResolution.firstFolder.description": "항상 첫 번째 워크스페이스 폴더(workspaceFolders[0])를 사용합니다. 결정적이며, 현재 포커스된 파일과 무관합니다." + "settings.workspace.rootResolution.firstFolder.description": "항상 첫 번째 워크스페이스 폴더(workspaceFolders[0])를 사용합니다. 결정적이며, 현재 포커스된 파일과 무관합니다.", + "settings.workspaceCommandListsEnabled.description": "워크스페이스 설정이 제공하는 명령 목록을 활성화합니다(워크스페이스 설정 파일의 `zoo-code.allowedCommands` 및 `zoo-code.deniedCommands` 값). 비활성화된 동안에는 워크스페이스 명령 목록이 효과가 없습니다. 활성화하면 사용자 수준 항목이 우선합니다: 사용자 수준 항목은 자신이 일치시키는 모든 명령을 결정하며, 워크스페이스 항목은 사용자 수준 항목이 일치시키지 않는 명령에만 적용됩니다. 이 설정은 [사용자 설정](https://code.visualstudio.com/docs/getstarted/settings)에서만 변경할 수 있습니다." } diff --git a/src/package.nls.nl.json b/src/package.nls.nl.json index 27948f933a..9704fc084c 100644 --- a/src/package.nls.nl.json +++ b/src/package.nls.nl.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Accepteer zelfondertekende certificaten van de proxy. **Vereist voor MITM-inspectie.** ⚠️ Onveilig — gebruik dit alleen voor lokale debugging.", "settings.workspace.rootResolution.description": "Hoe Zoo de workspace-root bepaalt in een multi-root workspace. De root wordt gebruikt om `.roomodes`, `.roo/mcp.json`, `.roo/rules/` en andere project-scoped configuratie te vinden. Deze instelling wijzigen heeft alleen invloed op toekomstige zoekopdrachten; lopende taken behouden hun oorspronkelijke root.", "settings.workspace.rootResolution.activeEditor.description": "Gebruik de workspace-map die de actieve editor bevat; val terug op de eerste workspace-map. (Standaard — behoudt het oude gedrag.)", - "settings.workspace.rootResolution.firstFolder.description": "Gebruik altijd de eerste workspace-map (workspaceFolders[0]). Deterministisch — onafhankelijk van welk bestand op dit moment de focus heeft." + "settings.workspace.rootResolution.firstFolder.description": "Gebruik altijd de eerste workspace-map (workspaceFolders[0]). Deterministisch — onafhankelijk van welk bestand op dit moment de focus heeft.", + "settings.workspaceCommandListsEnabled.description": "Schakel commandolijsten in die worden bijgedragen door werkruimte-instellingen (de waarden van `zoo-code.allowedCommands` en `zoo-code.deniedCommands` in instellingenbestanden van de werkruimte). Terwijl uitgeschakeld hebben commandolijsten van de werkruimte geen effect. Wanneer ingeschakeld hebben items op gebruikersniveau voorrang: een item op gebruikersniveau beslist elk commando dat ermee overeenkomt, en werkruimte-items zijn alleen van toepassing op commando's waar geen item op gebruikersniveau mee overeenkomt. Deze instelling kan alleen worden gewijzigd in de [gebruikersinstellingen](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.pl.json b/src/package.nls.pl.json index 8fb8b6eb83..73755bdcfd 100644 --- a/src/package.nls.pl.json +++ b/src/package.nls.pl.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Akceptuj certyfikaty self-signed z proxy. **Wymagane do inspekcji MITM.** ⚠️ Niezabezpieczone — używaj tylko do lokalnego debugowania.", "settings.workspace.rootResolution.description": "Jak Zoo ustala katalog główny workspace w workspace z wieloma katalogami głównymi. Katalog główny służy do lokalizowania `.roomodes`, `.roo/mcp.json`, `.roo/rules/` i innej konfiguracji na poziomie projektu. Zmiana tego ustawienia wpływa tylko na przyszłe wyszukiwania; uruchomione zadania zachowują swój pierwotny katalog główny.", "settings.workspace.rootResolution.activeEditor.description": "Użyj folderu workspace zawierającego aktywny edytor; w razie potrzeby wróć do pierwszego folderu workspace. (Domyślnie — zachowuje dotychczasowe zachowanie.)", - "settings.workspace.rootResolution.firstFolder.description": "Zawsze używaj pierwszego folderu workspace (workspaceFolders[0]). Deterministyczne — niezależne od tego, który plik jest aktualnie aktywny." + "settings.workspace.rootResolution.firstFolder.description": "Zawsze używaj pierwszego folderu workspace (workspaceFolders[0]). Deterministyczne — niezależne od tego, który plik jest aktualnie aktywny.", + "settings.workspaceCommandListsEnabled.description": "Włącza listy poleceń dostarczane przez ustawienia workspace (wartości `zoo-code.allowedCommands` i `zoo-code.deniedCommands` w plikach ustawień workspace). Gdy jest wyłączona, listy poleceń workspace nie mają żadnego efektu. Gdy jest włączona, wpisy na poziomie użytkownika mają pierwszeństwo: wpis na poziomie użytkownika rozstrzyga każde polecenie, z którym się dopasuje, a wpisy workspace dotyczą tylko poleceń, z którymi nie dopasuje się żaden wpis na poziomie użytkownika. To ustawienie można zmienić tylko w [ustawieniach użytkownika](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.pt-BR.json b/src/package.nls.pt-BR.json index b4cae4644b..eb5370e919 100644 --- a/src/package.nls.pt-BR.json +++ b/src/package.nls.pt-BR.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Aceitar certificados self-signed do proxy. **Necessário para inspeção MITM.** ⚠️ Inseguro — use apenas para depuração local.", "settings.workspace.rootResolution.description": "Como o Zoo resolve a raiz do workspace em um workspace multi-raiz. A raiz é usada para localizar `.roomodes`, `.roo/mcp.json`, `.roo/rules/` e outras configurações no escopo do projeto. Alterar esta configuração afeta apenas as buscas futuras; as tarefas em execução mantêm sua raiz original.", "settings.workspace.rootResolution.activeEditor.description": "Usa a pasta do workspace que contém o editor ativo; recorre à primeira pasta do workspace. (Padrão — preserva o comportamento legado.)", - "settings.workspace.rootResolution.firstFolder.description": "Usa sempre a primeira pasta do workspace (workspaceFolders[0]). Determinístico — independente de qual arquivo está em foco no momento." + "settings.workspace.rootResolution.firstFolder.description": "Usa sempre a primeira pasta do workspace (workspaceFolders[0]). Determinístico — independente de qual arquivo está em foco no momento.", + "settings.workspaceCommandListsEnabled.description": "Ativa as listas de comandos fornecidas pelas configurações do workspace (os valores de `zoo-code.allowedCommands` e `zoo-code.deniedCommands` nos arquivos de configurações do workspace). Enquanto desativada, as listas de comandos do workspace não têm efeito. Quando ativada, as entradas em nível de usuário têm precedência: uma entrada em nível de usuário decide qualquer comando com o qual corresponda, e as entradas do workspace se aplicam apenas a comandos com os quais nenhuma entrada em nível de usuário corresponde. Essa configuração só pode ser alterada nas [configurações de usuário](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.ru.json b/src/package.nls.ru.json index 0e61002848..141e1cdb0d 100644 --- a/src/package.nls.ru.json +++ b/src/package.nls.ru.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Принимать self-signed сертификаты от прокси. **Требуется для MITM-инспекции.** ⚠️ Небезопасно — используй только для локальной отладки.", "settings.workspace.rootResolution.description": "Как Zoo определяет корень рабочей области в рабочей области с несколькими корнями. Корень используется для поиска `.roomodes`, `.roo/mcp.json`, `.roo/rules/` и другой конфигурации уровня проекта. Изменение этой настройки влияет только на последующие поиски; выполняющиеся задачи сохраняют свой исходный корень.", "settings.workspace.rootResolution.activeEditor.description": "Использовать папку рабочей области, содержащую активный редактор; при необходимости вернуться к первой папке рабочей области. (По умолчанию — сохраняет прежнее поведение.)", - "settings.workspace.rootResolution.firstFolder.description": "Всегда использовать первую папку рабочей области (workspaceFolders[0]). Детерминированно — не зависит от того, какой файл сейчас в фокусе." + "settings.workspace.rootResolution.firstFolder.description": "Всегда использовать первую папку рабочей области (workspaceFolders[0]). Детерминированно — не зависит от того, какой файл сейчас в фокусе.", + "settings.workspaceCommandListsEnabled.description": "Включает списки команд, задаваемые в настройках рабочей области (значения `zoo-code.allowedCommands` и `zoo-code.deniedCommands` в файлах настроек рабочей области). Пока отключено, списки команд рабочей области ни на что не влияют. Когда включено, записи уровня пользователя имеют приоритет: запись уровня пользователя решает любую подошедшую ей команду, а записи рабочей области применяются только к командам, которые не совпали ни с одной записью уровня пользователя. Этот параметр можно изменить только в [настройках пользователя](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.tr.json b/src/package.nls.tr.json index 1842156d75..5c9c06dd9a 100644 --- a/src/package.nls.tr.json +++ b/src/package.nls.tr.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Proxy'den gelen self-signed sertifikaları kabul et. **MITM incelemesi için gerekli.** ⚠️ Güvensiz — yalnızca lokal debugging için kullan.", "settings.workspace.rootResolution.description": "Zoo'nun çok köklü bir çalışma alanında çalışma alanı kökünü nasıl belirlediği. Kök; `.roomodes`, `.roo/mcp.json`, `.roo/rules/` ve diğer proje kapsamındaki yapılandırmayı bulmak için kullanılır. Bu ayarı değiştirmek yalnızca sonraki aramaları etkiler; çalışan görevler özgün köklerini korur.", "settings.workspace.rootResolution.activeEditor.description": "Aktif düzenleyiciyi içeren çalışma alanı klasörünü kullan; ilk çalışma alanı klasörüne geri dön. (Varsayılan — eski davranışı korur.)", - "settings.workspace.rootResolution.firstFolder.description": "Her zaman ilk çalışma alanı klasörünü (workspaceFolders[0]) kullan. Deterministik — o anda hangi dosyanın odakta olduğundan bağımsız." + "settings.workspace.rootResolution.firstFolder.description": "Her zaman ilk çalışma alanı klasörünü (workspaceFolders[0]) kullan. Deterministik — o anda hangi dosyanın odakta olduğundan bağımsız.", + "settings.workspaceCommandListsEnabled.description": "Çalışma alanı ayarlarının sağladığı komut listelerini etkinleştirir (çalışma alanı ayar dosyalarındaki `zoo-code.allowedCommands` ve `zoo-code.deniedCommands` değerleri). Devre dışıyken çalışma alanı komut listelerinin hiçbir etkisi olmaz. Etkinleştirildiğinde kullanıcı düzeyi girdiler önceliklidir: bir kullanıcı düzeyi girdi eşleştiği her komutu kararlaştırır ve çalışma alanı girdileri yalnızca hiçbir kullanıcı düzeyi girdinin eşleşmediği komutlara uygulanır. Bu ayar yalnızca [kullanıcı ayarlarında](https://code.visualstudio.com/docs/getstarted/settings) değiştirilebilir." } diff --git a/src/package.nls.vi.json b/src/package.nls.vi.json index c846978793..73b4be5dee 100644 --- a/src/package.nls.vi.json +++ b/src/package.nls.vi.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "Chấp nhận chứng chỉ self-signed từ proxy. **Bắt buộc cho việc kiểm tra MITM.** ⚠️ Không an toàn — chỉ dùng cho debug cục bộ.", "settings.workspace.rootResolution.description": "Cách Zoo xác định gốc workspace trong một workspace nhiều gốc. Gốc được dùng để tìm `.roomodes`, `.roo/mcp.json`, `.roo/rules/` và các cấu hình khác ở phạm vi dự án. Thay đổi cài đặt này chỉ ảnh hưởng đến các lần tra cứu về sau; các tác vụ đang chạy vẫn giữ gốc ban đầu của chúng.", "settings.workspace.rootResolution.activeEditor.description": "Dùng thư mục workspace chứa trình soạn thảo đang hoạt động; quay lại thư mục workspace đầu tiên. (Mặc định — giữ nguyên hành vi cũ.)", - "settings.workspace.rootResolution.firstFolder.description": "Luôn dùng thư mục workspace đầu tiên (workspaceFolders[0]). Mang tính xác định — không phụ thuộc vào tệp nào đang được focus." + "settings.workspace.rootResolution.firstFolder.description": "Luôn dùng thư mục workspace đầu tiên (workspaceFolders[0]). Mang tính xác định — không phụ thuộc vào tệp nào đang được focus.", + "settings.workspaceCommandListsEnabled.description": "Bật các danh sách lệnh do cài đặt workspace đóng góp (giá trị `zoo-code.allowedCommands` và `zoo-code.deniedCommands` trong các tệp cài đặt workspace). Khi bị tắt, các danh sách lệnh của workspace không có tác dụng. Khi được bật, các mục cấp người dùng được ưu tiên: một mục cấp người dùng quyết định bất kỳ lệnh nào mà nó khớp, và các mục của workspace chỉ áp dụng cho các lệnh không có mục cấp người dùng nào khớp. Cài đặt này chỉ có thể thay đổi trong [cài đặt người dùng](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.zh-CN.json b/src/package.nls.zh-CN.json index e2705e9e2f..b62e8cdb64 100644 --- a/src/package.nls.zh-CN.json +++ b/src/package.nls.zh-CN.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "接受来自代理的 self-signed 证书。**MITM 检查所必需。** ⚠️ 不安全——只在本地调试时使用。", "settings.workspace.rootResolution.description": "Zoo 在多根工作区中如何解析工作区根目录。根目录用于定位 `.roomodes`、`.roo/mcp.json`、`.roo/rules/` 以及其他项目范围的配置。更改此设置仅影响后续查找;正在运行的任务会保留其原始根目录。", "settings.workspace.rootResolution.activeEditor.description": "使用包含活动编辑器的工作区文件夹;回退到第一个工作区文件夹。(默认——保留旧行为。)", - "settings.workspace.rootResolution.firstFolder.description": "始终使用第一个工作区文件夹(workspaceFolders[0])。具有确定性——与当前聚焦的文件无关。" + "settings.workspace.rootResolution.firstFolder.description": "始终使用第一个工作区文件夹(workspaceFolders[0])。具有确定性——与当前聚焦的文件无关。", + "settings.workspaceCommandListsEnabled.description": "启用由工作区设置提供的命令列表(工作区设置文件中的 `zoo-code.allowedCommands` 和 `zoo-code.deniedCommands` 值)。禁用期间,工作区命令列表不产生任何影响。启用后,用户级条目具有优先权:用户级条目决定其匹配的任何命令,工作区条目仅适用于没有任何用户级条目匹配的命令。此设置只能在[用户设置](https://code.visualstudio.com/docs/getstarted/settings)中更改。" } diff --git a/src/package.nls.zh-TW.json b/src/package.nls.zh-TW.json index 723d8d08ad..904867e1b4 100644 --- a/src/package.nls.zh-TW.json +++ b/src/package.nls.zh-TW.json @@ -48,5 +48,6 @@ "settings.debugProxy.tlsInsecure.description": "接受來自代理的 self-signed 憑證。**MITM 檢查所必需。** ⚠️ 不安全——只在本機偵錯時使用。", "settings.workspace.rootResolution.description": "Zoo 在多根工作區中如何解析工作區根目錄。根目錄用於定位 `.roomodes`、`.roo/mcp.json`、`.roo/rules/` 以及其他專案範圍的設定。變更此設定僅影響後續查找;正在執行的工作會保留其原始根目錄。", "settings.workspace.rootResolution.activeEditor.description": "使用包含使用中編輯器的工作區資料夾;回退到第一個工作區資料夾。(預設——保留舊行為。)", - "settings.workspace.rootResolution.firstFolder.description": "一律使用第一個工作區資料夾(workspaceFolders[0])。具決定性——與目前聚焦的檔案無關。" + "settings.workspace.rootResolution.firstFolder.description": "一律使用第一個工作區資料夾(workspaceFolders[0])。具決定性——與目前聚焦的檔案無關。", + "settings.workspaceCommandListsEnabled.description": "啟用由工作區設定所提供的工作區指令清單(工作區設定檔案中的 `zoo-code.allowedCommands` 與 `zoo-code.deniedCommands` 值)。停用時,工作區指令清單不會產生任何影響。啟用後,使用者層級的條目具有優先權:使用者層級的條目會決定其符合的任何指令,工作區條目僅適用於沒有任何使用者層級條目符合的指令。此設定只能在[使用者設定](https://code.visualstudio.com/docs/getstarted/settings)中變更。" } From 10e945669fa4af15ed19cd7d76bc118dd9db9306 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 5 Nov 2026 19:43:40 +0100 Subject: [PATCH 07/52] fix: harden command-list save path and resolve lists per task folder (#1939) Review fixes on the workspace-scoped command-list feature: - The hidden-entry check during a settings save now compares the settings file against a snapshot of each command list's global layer taken before the save loop, so the result no longer depends on which key is processed first. - The final extension-state write at the end of a settings save is guarded: if it is rejected, the error names the layers that did and did not receive the update instead of failing silently, and the save continues. - Workspace command lists for an approval decision now resolve from the workspace folder that contains the task's working directory instead of always the first folder; a working directory that names no folder falls back to the first-folder configuration. The state sent to the webview carries the global layers alongside the window-scoped pair. - An open settings dialog merges external command-list updates into its buffer, holding back a list the user is editing, and a save sends the lists it last displayed as a baseline. Entries the settings file gained while the dialog was open are therefore preserved on save and named in a warning instead of being erased; deletions made in the dialog still apply. - Test coverage added for the unset gate value, both key orders of the save snapshot, the rejected state write, per-folder resolution, and the dialog reseed/baseline behavior. --- packages/types/src/vscode-extension-host.ts | 20 ++ .../__tests__/commandScope.spec.ts | 162 ++++++++- src/core/auto-approval/commandScope.ts | 60 +++- src/core/auto-approval/index.ts | 34 +- src/core/webview/ClineProvider.ts | 17 +- .../__tests__/webviewMessageHandler.spec.ts | 307 +++++++++++++++++- src/core/webview/webviewMessageHandler.ts | 72 +++- .../src/components/settings/SettingsView.tsx | 110 +++++++ .../SettingsView.change-detection.spec.tsx | 125 ++++++- .../settings/__tests__/SettingsView.spec.tsx | 26 ++ .../SettingsView.unsaved-changes.spec.tsx | 132 ++++++++ 11 files changed, 1026 insertions(+), 39 deletions(-) diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index bfe5632af6..e9d94e3e55 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -384,6 +384,18 @@ export type ExtensionState = Pick< toolRequirements?: Record // Map of tool names to their requirements (e.g. {"apply_diff": true}) cwd?: string // Current working directory + + /** + * The user-scope command lists as persisted in extension global state, + * before any workspace-scoped composition. Auto-approval composes the + * pair it enforces from these raw layers plus the folder the task runs + * in, because the merged `allowedCommands`/`deniedCommands` pair follows + * the window's first folder and would judge a task by another root's + * lists. Not user settings: runtime state, written by the provider's + * state bake, never by the settings dialog. + */ + globalAllowedCommands?: string[] + globalDeniedCommands?: string[] telemetrySetting: TelemetrySetting telemetryKey?: string machineId?: string @@ -809,6 +821,14 @@ export interface WebviewMessage { codebaseIndexOpenRouterApiKey?: string } updatedSettings?: RooCodeSettings + /** + * The command lists as the settings dialog last displayed them, sent alongside the + * save that rewrites them. The settings file can gain entries while the dialog is + * open, and without this baseline the save path cannot tell those additions apart + * from list entries the user deleted: both look like "in the file, absent from the + * submitted list". Senders that do not display the lists omit it. + */ + commandListBaseline?: { allowedCommands?: string[]; deniedCommands?: string[] } /** Task configuration applied via `createTask()`. */ taskConfiguration?: RooCodeSettings // Worktree properties diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 4d1064d23d..15598f4caf 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -13,12 +13,17 @@ import { splitCommandListScopes, workspaceCommandListsEnabled, } from "../commandScope" +import { checkAutoApproval } from "../index" +import { baseState, type State } from "./fixtures" // Scriptable stand-in for `vscode.workspace.workspaceFolders`: the module // mock's getter reads through this object, so a test can change the open -// folders without re-mocking the module. +// folders without re-mocking the module. `foldersByPath` backs +// `getWorkspaceFolder`: keys are folder paths, values the folder objects, so +// a test controls which cwds resolve to a root. const workspaceState = vi.hoisted(() => ({ workspaceFolders: undefined as { uri: unknown }[] | undefined, + foldersByPath: new Map(), })) vi.mock("vscode", () => ({ @@ -27,11 +32,25 @@ vi.mock("vscode", () => ({ Workspace: 2, WorkspaceFolder: 3, }, + Uri: { + // Structural local stand-in: the resolver only carries the path + // through to `getWorkspaceFolder`. + file: (fsPath: string) => ({ scheme: "file", authority: "", path: fsPath, fsPath, query: "", fragment: "" }), + }, workspace: { get workspaceFolders() { return workspaceState.workspaceFolders }, getConfiguration: vi.fn(), + getWorkspaceFolder: vi.fn((resource?: { fsPath?: string }) => { + const fsPath = resource?.fsPath ?? "" + for (const [folderPath, uri] of workspaceState.foldersByPath) { + if (fsPath === folderPath || fsPath.startsWith(`${folderPath}/`)) { + return { uri } + } + } + return undefined + }), }, })) @@ -345,6 +364,20 @@ it("workspaceCommandListsEnabled: enables the workspace layers only when the gat expect(config.get).toHaveBeenCalledWith("workspaceCommandListsEnabled") }) +it("workspaceCommandListsEnabled: is off when the gate is unset", () => { + vi.clearAllMocks() + // Unset is the state of every installation that has never opted in, so it + // must read as disabled: treating unset as enabled would widen + // auto-approval by default. The equality against the declared default also + // keeps this expectation attached to the constant that documents the + // shipped default, not to an independently hard-coded boolean. + const config = mockGateConfiguration(undefined) + + expect(workspaceCommandListsEnabled()).toBe(false) + expect(workspaceCommandListsEnabled()).toBe(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED) + expect(config.get).toHaveBeenCalledWith("workspaceCommandListsEnabled") +}) + it("workspaceCommandListsEnabled: keeps the workspace layers disabled when the gate lookup throws", () => { vi.clearAllMocks() // Fail-closed: a broken configuration read must never widen what the @@ -441,3 +474,130 @@ it("resolveEffectiveCommandLists: shadows workspace entries case-insensitively, expect(effective.hiddenWorkspaceAllow).toEqual(["git status"]) expect(effective.hiddenWorkspaceDeny).toEqual([]) }) + +// Command-branch enforcement composes its allow/deny pair from the raw +// global layers at the folder the task's cwd resolves to, so a task in +// another root is judged by that root's lists rather than the window's +// first folder. The window-scoped pair on the state stays what the dialog +// displays. + +function openMultiRootWindow() { + const folderA = makeUri("/mock/folder-a") + const folderB = makeUri("/mock/folder-b") + workspaceState.workspaceFolders = [{ uri: folderA }, { uri: folderB }] + workspaceState.foldersByPath.set(folderA.fsPath, folderA) + workspaceState.foldersByPath.set(folderB.fsPath, folderB) + return { folderA, folderB } +} + +// Scripts each folder's configuration independently so the test can tell +// which folder's settings the enforcement path actually read. +function mockFolderConfigurations(scripts: Record) { + vi.mocked(vscode.workspace.getConfiguration).mockImplementation( + (_section?: string, scope?: vscode.ConfigurationScope | null) => { + const entry = scripts[scope && "fsPath" in scope ? scope.fsPath : ""] + const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: entry?.gate ?? false }) + vi.mocked(config.inspect).mockImplementation((key: string) => + key === "deniedCommands" && entry?.deny ? { key, workspaceFolderValue: entry.deny } : undefined, + ) + return config + }, + ) +} + +// Raw global layers empty: every enforcement decision then comes from the +// folder layer, so a decision can only be right for one folder. The baked +// pair on the state is set to values no folder composes, so a check that +// consumed it instead of re-composing decides differently. +const taskFolderState = (bakedAllowed: string[]): State => ({ + ...baseState, + alwaysAllowExecute: true, + allowedCommands: bakedAllowed, + deniedCommands: [], + globalAllowedCommands: [], + globalDeniedCommands: [], +}) + +it("checkAutoApproval command: enforces the deny entries of the folder the task's cwd resolves to", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + // Folder A denies "echo", folder B denies "rm"; the task runs in B. + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["echo"] }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + // The baked pair would approve exactly what folder B's layer denies. + const result = await checkAutoApproval({ + state: taskFolderState(["rm"]), + cwd: folderB.fsPath, + ask: "command", + text: "rm file", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "rm file", pattern: "rm" } }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderB) +}) + +it("checkAutoApproval command: does not apply another root's deny entries to a task outside it", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["echo"] }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + // "echo" is denied only in the first folder; judging this B-rooted task + // there would auto-deny it. Nothing allows it either, so the correct + // multi-root decision is the plain user prompt. + const result = await checkAutoApproval({ + state: taskFolderState(["echo"]), + cwd: folderB.fsPath, + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + +it("checkAutoApproval command: falls back to the first folder when the cwd resolves to no workspace root", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["echo"] }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + // A removed or relocated folder names no root; enforcement stays on the + // first-folder configuration it used before per-task scoping existed. + const result = await checkAutoApproval({ + state: taskFolderState(["echo"]), + cwd: "/mock/removed-folder", + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) + expect(vscode.workspace.getConfiguration).not.toHaveBeenCalledWith(Package.name, folderB) +}) + +it("checkAutoApproval command: in a single-folder window reads exactly the same configuration as before", async () => { + vi.clearAllMocks() + const { folderA } = openMultiRootWindow() + workspaceState.workspaceFolders = [{ uri: folderA }] + workspaceState.foldersByPath.delete(makeUri("/mock/folder-b").fsPath) + // The one open folder is both the task folder and the first folder, so + // the resolved scope and the no-arg default are the same resource. + mockFolderConfigurations({ [folderA.fsPath]: { gate: true, deny: ["echo"] } }) + + const result = await checkAutoApproval({ + state: taskFolderState(["echo"]), + cwd: folderA.fsPath, + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) +}) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 03d464559f..3ceed09a9f 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -24,17 +24,52 @@ export interface CommandListInspection { } /** - * The configuration object for every command-list read and write, scoped to - * the first workspace folder. Sharing one scoped access path keeps the two - * sides symmetric: `inspect()` can report `workspaceFolderValue`, and - * `ConfigurationTarget.WorkspaceFolder` updates are legal (the API contract - * throws for that target when the configuration is not scoped to a - * resource). In a multi-root workspace only the first folder's values are in - * scope; with no folder open the configuration is unscoped and reports no - * folder value. + * The configuration object for every command-list read and write. Scoped to + * `folderResource` when the caller resolved one — per-task enforcement reads + * the folder that task runs in — and to the first workspace folder otherwise, + * the default the display, save, and seeding callers keep. Sharing one scoped + * access path keeps the two sides symmetric: `inspect()` can report + * `workspaceFolderValue`, and `ConfigurationTarget.WorkspaceFolder` updates + * are legal (the API contract throws for that target when the configuration + * is not scoped to a resource). With no folder open — or when a supplied + * resource resolved to nothing, see {@link commandListFolderForResource} — + * the configuration is unscoped or defaults to the first folder and reports + * only what that lookup can see. */ -export function commandListConfiguration(): vscode.WorkspaceConfiguration { - return vscode.workspace.getConfiguration(Package.name, vscode.workspace.workspaceFolders?.[0]?.uri) +export function commandListConfiguration(folderResource?: vscode.Uri): vscode.WorkspaceConfiguration { + return vscode.workspace.getConfiguration( + Package.name, + folderResource ?? vscode.workspace.workspaceFolders?.[0]?.uri, + ) +} + +/** + * Resolves the workspace folder a task's `cwd` lives in, so command-list + * enforcement scopes its configuration reads to the folder the task belongs + * to instead of the window's first folder. A child task inherits the working + * directory of the task it came from, so it resolves to the same folder + * without separate plumbing. + * + * @param cwd - The task's working directory. A blank cwd, or one that names + * no workspace root (a removed or relocated folder), yields `undefined`, + * which leaves every read on its first-folder default — the behavior such a + * cwd had before per-task scoping existed, never a guess at a different one. + * @returns The containing folder's URI, or `undefined` when cwd resolves to + * no root. + */ +export function commandListFolderForResource(cwd?: string): vscode.Uri | undefined { + if (!cwd) { + return undefined + } + + // Guarded like the configuration reads this feeds: a lookup that cannot + // run stands in for a cwd naming no root, so enforcement degrades to the + // first-folder default instead of failing the approval decision. + try { + return vscode.workspace.getWorkspaceFolder(vscode.Uri.file(cwd))?.uri + } catch { + return undefined + } } /** @@ -54,12 +89,15 @@ export function commandListConfiguration(): vscode.WorkspaceConfiguration { * configuration state. Without it the lookup runs guarded (lenient): this is * the enforcement/display path, where an unavailable workspace layer must * degrade to empty rather than fail. + * @param folderResource - Workspace folder the configuration is scoped to; + * `undefined` keeps the first-folder default. * @returns The per-layer lists and their deduplicated set union. */ export function readCommandListScopes( configKey: CommandListConfigKey, globalList: string[] | undefined, inspectionOverride?: CommandListInspection, + folderResource?: vscode.Uri, ): CommandListScopes { const global = sanitizeCommandList(globalList) @@ -71,7 +109,7 @@ export function readCommandListScopes( // of their own, so the catch covers exactly the failure it exists to // absorb. try { - inspected = commandListConfiguration().inspect(configKey) + inspected = commandListConfiguration(folderResource).inspect(configKey) } catch { inspected = undefined } diff --git a/src/core/auto-approval/index.ts b/src/core/auto-approval/index.ts index 3539eef24d..212f021f2c 100644 --- a/src/core/auto-approval/index.ts +++ b/src/core/auto-approval/index.ts @@ -15,6 +15,12 @@ import { ClineAskResponse } from "../../shared/WebviewMessage" import { isWriteToolAction, isReadOnlyToolAction } from "./tools" import { isMcpToolAlwaysAllowed } from "./mcp" import { containsDangerousSubstitution, getCommandDecisionDetailed } from "./commands" +import { + commandListFolderForResource, + readCommandListScopes, + resolveEffectiveCommandLists, + workspaceCommandListsEnabled, +} from "./commandScope" import { isFileMatchedByPatterns } from "./filePatterns" import { type AutoDenyDetail } from "./autoDenyReason" @@ -40,6 +46,8 @@ export type AutoApprovalStateOptions = | "mcpServers" // For `alwaysAllowMcp`. | "allowedCommands" // For `alwaysAllowExecute`. | "deniedCommands" + | "globalAllowedCommands" // Raw global layer feeding the per-folder command-list composition. + | "globalDeniedCommands" | "destructiveCommandGuardEnabled" | "alwaysDenyUnapprovedCommands" // For `alwaysAllowExecute` (blanket auto-deny). @@ -304,10 +312,32 @@ export async function checkAutoApproval({ return { decision: "approve" } } + // The pair on `state` was composed against the window's first + // folder; a task rooted in another folder must be judged by that + // folder's lists, so enforcement re-composes from the raw global + // layers at the folder the task's `cwd` resolves to (a cwd that + // names no workspace root keeps the first-folder configuration). + // Without the raw layers the pre-composed pair is all the state + // carries, and that pair is what enforcement consumes. + const taskFolder = commandListFolderForResource(cwd) + const effectiveLists = + state.globalAllowedCommands !== undefined && state.globalDeniedCommands !== undefined + ? resolveEffectiveCommandLists( + readCommandListScopes( + "allowedCommands", + state.globalAllowedCommands, + undefined, + taskFolder, + ), + readCommandListScopes("deniedCommands", state.globalDeniedCommands, undefined, taskFolder), + workspaceCommandListsEnabled(), + ) + : { allowed: state.allowedCommands || [], denied: state.deniedCommands || [] } + const { decision, offendingCommand, matchedPattern, parseError } = getCommandDecisionDetailed( text, - state.allowedCommands || [], - state.deniedCommands || [], + effectiveLists.allowed, + effectiveLists.denied, ) if (decision === "auto_approve") { diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 3755aa48b3..dc7f149132 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3445,13 +3445,22 @@ export class ClineProvider autoCondenseContext: stateValues.autoCondenseContext ?? true, autoCondenseContextPercent: stateValues.autoCondenseContextPercent ?? 100, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], - // Enforce and display the effective lists that - // resolveEffectiveCommandLists composes from the global-state and - // workspace-scope configuration layers; getStateToPostToWebview shows - // exactly these values, so display cannot drift from enforcement. + // The effective lists composed from the global-state and + // workspace-scope configuration layers, scoped to the window's + // first folder; getStateToPostToWebview shows exactly these values, + // so the dialog cannot drift from what this state posts. In a + // multi-root window a task in another folder is judged by that + // folder's lists instead — enforcement re-composes the pair from + // the raw global layers below, so the displayed pair describes the + // window, not the task. allowedCommands: effectiveCommandLists.allowed, deniedCommands: effectiveCommandLists.denied, workspaceCommandListsEnabled: gateEnabled, + // The global layers before workspace composition, so command + // enforcement can re-compose the pair against each task's own + // folder; the window-scoped pair above stays what display shows. + globalAllowedCommands: allowScopes.global, + globalDeniedCommands: denyScopes.global, soundEnabled: stateValues.soundEnabled ?? false, ttsEnabled: stateValues.ttsEnabled ?? false, ttsSpeed: stateValues.ttsSpeed ?? 1.0, diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 8a7d0cebc2..725e0131a9 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -77,7 +77,7 @@ vi.mock("@roo-code/telemetry", () => ({ }, })) -import type { ModelRecord } from "@roo-code/types" +import type { ModelRecord, WebviewMessage } from "@roo-code/types" import * as vsCodeLmProvider from "../../../api/providers/vscode-lm" import * as copilotProvider from "../../../api/providers/github-copilot" @@ -776,9 +776,16 @@ describe("webviewMessageHandler - theme fixture probes", () => { import { t } from "../../../i18n" +// Mutable so a test can script a multi-root workspace; every other test sees the +// single folder the command-list configuration resolves against by default. +const mockWorkspaceFolders = vi.hoisted(() => ({ + folders: [{ uri: { fsPath: "/mock/workspace" } }] as { uri: { fsPath: string } }[], +})) + vi.mock("vscode", () => { const showInformationMessage = vi.fn() const showErrorMessage = vi.fn() + const showWarningMessage = vi.fn() const openTextDocument = vi.fn().mockResolvedValue({}) const showTextDocument = vi.fn().mockResolvedValue(undefined) @@ -791,10 +798,13 @@ vi.mock("vscode", () => { window: { showInformationMessage, showErrorMessage, + showWarningMessage, showTextDocument, }, workspace: { - workspaceFolders: [{ uri: { fsPath: "/mock/workspace" } }], + get workspaceFolders() { + return mockWorkspaceFolders.folders + }, openTextDocument, getConfiguration: vi.fn(() => ({ get: vi.fn() })), }, @@ -2104,6 +2114,7 @@ describe("webviewMessageHandler - allowlists together", () => { describe("webviewMessageHandler - command list scope-aware persistence", () => { beforeEach(() => { vi.clearAllMocks() + mockWorkspaceFolders.folders = [{ uri: { fsPath: "/mock/workspace" } }] }) // The file-level vscode mock opens one workspace folder, so the command @@ -2521,6 +2532,298 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // instead of keeping the refused one. expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) + + // A payload can carry both command-list keys; the second-processed key's + // hidden-entry check must judge shadowing against the state as it was when + // the save started, not as the same loop's earlier key left it. The double + // below mirrors ContextProxy: setValue publishes the in-memory copy before + // resolving, so a fresh read after the first key's awaited write would + // observe it and let the never-displayed entry be deleted. + function mockCommandListStateStore(initial: Partial>) { + const store: Partial> = { ...initial } + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" || key === "deniedCommands" ? store[key] : undefined, + ) + vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key: string, value: unknown) => { + if (key === "allowedCommands" || key === "deniedCommands") { + store[key] = value as string[] | undefined + } + }) + return store + } + + it("preserves a workspace deny entry shadowed by a global allow the same save removes", async () => { + mockCommandListStateStore({ allowedCommands: ["git"] }) + const { update } = mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // "allowedCommands" is processed first and drops the shadowing + // global "git"; "git push" was hidden from the dialog, so an empty + // deny list must not delete it. + updatedSettings: { allowedCommands: [], deniedCommands: [] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + + it("preserves a workspace allow entry shadowed by a global deny the same save removes", async () => { + mockCommandListStateStore({ deniedCommands: ["git"] }) + const { update } = mockCommandConfiguration( + (key) => (key === "allowedCommands" ? { workspaceValue: ["git push"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // The mirror order: the deny key is processed first, so this pins + // that preservation does not depend on which key arrives first. + updatedSettings: { deniedCommands: [], allowedCommands: [] }, + }) + + expect(update).toHaveBeenCalledWith("allowedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Workspace) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + + it("reports a rejected extension-state write without aborting the save", async () => { + // The configuration writes succeeded, so silently dropping the state + // write would leave the settings files and the stored list disagreeing + // with nothing shown to the user. The rejection is queued (once) so it + // consumes exactly this key's write and the sibling key still persists. + vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValueOnce(new Error("state store unavailable")) + const { update } = mockCommandConfiguration({}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["aws"], alwaysDenyUnapprovedCommands: true }, + }) + + // The configuration leg did persist... + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + // ...so the message names the leg that failed... + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to save deniedCommands: state store unavailable. The configuration was updated, but the extension's stored copy of the list was not, so the two disagree until a later save succeeds.", + ) + // ...the save continued to the next key... + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) + // ...and the dialog was re-synced instead of keeping an unsaved value. + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + + it("still propagates a rejected state write for non-command-list keys", async () => { + // The partial-failure report is scoped to the command-list keys, whose + // configuration legs succeeded first; other keys have no half-completed + // save to explain, so their failures keep propagating as before. The + // rejection is queued (once) so it stays scoped to this test. + vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValueOnce(new Error("state store unavailable")) + + await expect( + webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { alwaysDenyUnapprovedCommands: true }, + }), + ).rejects.toThrow("state store unavailable") + + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + expect(mockClineProvider.postStateToWebview).not.toHaveBeenCalled() + }) + + it("keeps a settings-file entry the dialog never displayed and warns that it was preserved", async () => { + // An entry the settings file gained while the dialog was open has the same + // shape as a user deletion (in the file, absent from the submitted list); + // the baseline tells them apart, so the new entry is kept in the layer the + // snapshot found it in and the user is told instead of losing it silently. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "rm -rf"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["aws"] }, + commandListBaseline: { deniedCommands: ["aws"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws", "rm -rf"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("rm -rf")) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("1 entry was")) + }) + + it("applies a user deletion of a displayed entry without warning", async () => { + // The counterpart classification: an entry the baseline shows the dialog + // displayed and the submitted list omits is a deliberate deletion and must + // be dropped from every layer that held it, with nothing disclosed. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "rm -rf"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["aws"] }, + commandListBaseline: { deniedCommands: ["aws", "rm -rf"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["rm -rf"], vscode.ConfigurationTarget.Global) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("keeps a file-added entry while applying a displayed deletion in one save, warning once", async () => { + // Both divergence classes in one payload: "git" was displayed and the user + // deleted it (deletion applies), "curl" arrived after the dialog opened + // (preserved). The warning counts only the preserved entry, once per save. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ workspaceValue: ["git", "curl"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: ["git"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalledWith(expect.stringContaining("git")) + }) + + it("saves command lists unchanged when the message carries no baseline", async () => { + // Backward-compatibility witness: senders that omit the baseline keep the + // exact pre-existing behavior - the omitted entry is dropped as a deletion + // and no warning is produced. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "rm -rf"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["aws"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("routes a preserved entry to the layer the save-start snapshot found it in", async () => { + // A preserved entry must land where it lives, not be flattened into the + // global layer: "rm -rf" is in the workspace snapshot, "npm" in the + // extension's stored global layer, and neither was ever displayed. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["npm"] : undefined, + ) + const { update } = mockCommandConfiguration({ workspaceValue: ["rm -rf"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: [] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["rm -rf"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", ["npm"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["npm"]) + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("2 entries were")) + }) + + it("treats a malformed command-list baseline exactly like a missing one", async () => { + // The save message crosses a JSON boundary, so a baseline whose key holds a + // non-array is reachable at runtime even though the declared type forbids it. + // The classification guard treats it as no baseline at all: the submitted list + // is written unclassified and no entry the dialog never displayed is claimed + // as user-deleted, matching the no-baseline witness exactly. + const wireMessage: WebviewMessage = JSON.parse( + JSON.stringify({ + type: "updateSettings", + updatedSettings: { deniedCommands: ["aws"] }, + commandListBaseline: { deniedCommands: "aws" }, + }), + ) + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "rm -rf"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, wireMessage) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("composes and writes only the first workspace folder's layer in a multi-root save", async () => { + // The dialog composes against the first folder, so a save must never read or + // write the second folder's per-folder layer: folder B's entries survive a + // folder A save untouched. + const secondFolderUri = { fsPath: "/mock/second-folder" } + mockWorkspaceFolders.folders = [{ uri: mockWorkspaceFolderUri }, { uri: secondFolderUri }] + const { update } = mockCommandConfiguration( + { workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, mockWorkspaceFolderUri) + expect(vscode.workspace.getConfiguration).not.toHaveBeenCalledWith(Package.name, secondFolderUri) + // The folder-target write the save does make goes to the first folder's layer. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.WorkspaceFolder) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + }) + + it("aggregates preserved entries from both command-list keys into a single save warning", async () => { + // A payload carrying both list keys classifies per key, so two file entries the + // dialog never displayed - one per key - must survive in their own layers and be + // disclosed together in exactly one warning for the save. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + (key) => + key === "allowedCommands" + ? { workspaceValue: ["git", "curl"] } + : { workspaceValue: ["rm -rf", "docker"] }, + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"], deniedCommands: ["rm -rf"] }, + commandListBaseline: { allowedCommands: ["git"], deniedCommands: ["rm -rf"] }, + }) + + // "curl" stays in the workspace allow layer, "docker" in the workspace deny layer. + expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "curl"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith( + "deniedCommands", + ["rm -rf", "docker"], + vscode.ConfigurationTarget.Workspace, + ) + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + // One aggregated warning naming both preserved entries and counting them together. + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("2 entries were")) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("docker")) + }) }) describe("webviewMessageHandler - terminalProfile", () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index dfb7e2e8a0..97ec1f0eb9 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -770,6 +770,17 @@ export const webviewMessageHandler = async ( } } + // Shadowing is cross-directional, and a payload can carry both + // command-list keys, so the second-processed key's hidden-entry + // check would otherwise read the layer the first key's iteration + // just wrote. Both global layers are captured before any write so + // a hidden entry's preservation cannot depend on payload key order. + const commandListGlobalsAtSaveStart = { + allowedCommands: getGlobalState("allowedCommands"), + deniedCommands: getGlobalState("deniedCommands"), + } + const externallyAddedCommandEntries: string[] = [] + for (const [key, value] of Object.entries(message.updatedSettings)) { let newValue = value @@ -823,20 +834,34 @@ export const webviewMessageHandler = async ( } const currentScopes = readCommandListScopes(key, getGlobalState(key), inspection) + // An entry the settings file gained while the dialog was open has + // the same shape as an entry the user deleted: present in the file, + // absent from the submitted list. Only the dialog's last-displayed + // baseline separates the two, so file entries outside that baseline + // are re-admitted before the split (deletions of baseline entries + // still apply). A sender that shows no lists sends no baseline, and + // its submitted list is written unclassified. + const baseline = message.commandListBaseline?.[key] + const externallyAdded = Array.isArray(baseline) + ? [...new Set([...currentScopes.workspace, ...currentScopes.global])].filter( + (entry) => !baseline.includes(entry) && !incoming.includes(entry), + ) + : [] const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( - incoming, + [...incoming, ...externallyAdded], currentScopes.workspace, currentScopes.global, ) - // Shadowing is cross-directional, so the hidden-entry - // set needs the opposite key's global layer as input. - // That opposite-key read is a fresh guarded read: it - // only feeds the additive preservation below and never - // this key's split, target, or rollback, which stay on - // the single snapshot. + // Shadowing is cross-directional, so the hidden-entry set + // needs the opposite key's global layer as input. It comes + // from the save-start snapshot, not a fresh read: an + // earlier iteration of this loop may already have written + // that key. The layer only feeds the additive preservation + // below and never this key's split, target, or rollback, + // which stay on the per-key configuration snapshot. const otherKey = key === "allowedCommands" ? "deniedCommands" : "allowedCommands" - const otherScopes = readCommandListScopes(otherKey, getGlobalState(otherKey)) + const otherScopes = readCommandListScopes(otherKey, commandListGlobalsAtSaveStart[otherKey]) const { hiddenWorkspaceAllow, hiddenWorkspaceDeny } = resolveEffectiveCommandLists( key === "allowedCommands" ? currentScopes : otherScopes, key === "deniedCommands" ? currentScopes : otherScopes, @@ -910,6 +935,10 @@ export const webviewMessageHandler = async ( // would double-home workspace entries and re-leak them on the // next save. newValue = globalWrite + // Accumulated only after both configuration writes succeeded: the + // disclosure must not claim preservation for a key whose save was + // abandoned by a failed write. + externallyAddedCommandEntries.push(...externallyAdded) } else if (key === "allowedReadFiles" || key === "allowedWriteFiles") { const patterns = value ?? [] @@ -994,7 +1023,32 @@ export const webviewMessageHandler = async ( } } - await provider.contextProxy.setValue(key as keyof RooCodeSettings, newValue) + if (key === "allowedCommands" || key === "deniedCommands") { + // The configuration writes above already succeeded, so a + // rejected state write leaves the configuration and the + // extension's stored list disagreeing until a later save + // overwrites it. Letting the rejection escape would also + // skip the state post that re-syncs the dialog, so the key + // reports which leg failed and the save continues. + try { + await provider.contextProxy.setValue(key as keyof RooCodeSettings, newValue) + } catch (error) { + const failure = error instanceof Error ? error.message : String(error) + vscode.window.showErrorMessage( + `Failed to save ${key}: ${failure}. The configuration was updated, but the extension's stored copy of the list was not, so the two disagree until a later save succeeds.`, + ) + continue + } + } else { + await provider.contextProxy.setValue(key as keyof RooCodeSettings, newValue) + } + } + + if (externallyAddedCommandEntries.length > 0) { + const count = externallyAddedCommandEntries.length + vscode.window.showWarningMessage( + `Your settings file changed while the settings dialog was open. ${count} ${count === 1 ? "entry was" : "entries were"} added there during this session and kept by this save: ${externallyAddedCommandEntries.join(", ")}. Reopen the settings dialog to see the current command lists.`, + ) } await provider.postStateToWebview() diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 5f1769a230..492f66512b 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -95,6 +95,25 @@ export const settingsTabTrigger = "whitespace-nowrap overflow-hidden min-w-0 h-12 px-4 py-3 box-border flex items-center border-l-2 border-transparent text-vscode-foreground opacity-70 hover:bg-vscode-list-hoverBackground data-[compact=true]:w-12 data-[compact=true]:p-4" export const settingsTabTriggerActive = "opacity-100 border-vscode-focusBorder bg-vscode-list-activeSelectionBackground" +// Command-list snapshot of a settings state object. Entries are compared by value because every +// state post delivers freshly deserialized arrays; reference identity carries no meaning here. +interface CommandListSnapshot { + allowedCommands?: string[] + deniedCommands?: string[] + workspaceCommandListsEnabled?: boolean +} + +const commandListSnapshot = (state: CommandListSnapshot): string => + JSON.stringify([ + state.allowedCommands ?? [], + state.deniedCommands ?? [], + state.workspaceCommandListsEnabled ?? false, + ]) + +const commandListsEquivalent = (left?: string[], right?: string[]) => + left === right || + (!!left && !!right && left.length === right.length && left.every((entry, index) => entry === right[index])) + export interface SettingsViewRef { checkUnsaveChanges: (then: () => void) => void } @@ -153,6 +172,13 @@ const SettingsView = forwardRef(({ onDone, t const [cachedState, setCachedState] = useState(() => extensionState) + // Command-list values the dialog last displayed, so a later state post can be recognized as + // an external change rather than a restatement of what is already shown. + const lastDisplayedCommandSnapshot = useRef(commandListSnapshot(extensionState)) + // An in-flight user edit of either list claims ownership of the lists until Save, discard, or + // a full reseed; external list updates must not silently overwrite it. + const commandListsTouched = useRef(false) + const { alwaysAllowReadOnly, alwaysAllowReadOnlyOutsideWorkspace, @@ -235,6 +261,8 @@ const SettingsView = forwardRef(({ onDone, t setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) prevApiConfigName.current = currentApiConfigName prevMode.current = mode + lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) + commandListsTouched.current = false setChangeDetected(false) }, [currentApiConfigName, mode, extensionState]) @@ -246,15 +274,79 @@ const SettingsView = forwardRef(({ onDone, t handledSettingsImportedAt.current = settingsImportedAt setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) + lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) + commandListsTouched.current = false setChangeDetected(false) }, [settingsImportedAt, extensionState]) + // The command lists can change in the extension host while this dialog is open (for example, + // a settings-file edit landing mid-session). Fold exactly those fields into the edit buffer on + // every state post that changes them, so a later Save cannot rewrite the configuration layer + // from a list that never showed the new entry. List fields are held back while the user has an + // in-flight list edit (in-flight edits win); every other buffered field is left untouched and + // the dirty flag is never cleared here, keeping the buffer's Save-gated semantics. + useEffect(() => { + const snapshot = commandListSnapshot(extensionState) + if (snapshot === lastDisplayedCommandSnapshot.current) { + return + } + + setCachedState((prevState) => { + const merged: CommandListSnapshot = {} + let changedFields = 0 + + if (!commandListsTouched.current) { + if (!commandListsEquivalent(prevState.allowedCommands, extensionState.allowedCommands)) { + merged.allowedCommands = extensionState.allowedCommands + changedFields++ + } + if (!commandListsEquivalent(prevState.deniedCommands, extensionState.deniedCommands)) { + merged.deniedCommands = extensionState.deniedCommands + changedFields++ + } + } + if (prevState.workspaceCommandListsEnabled !== extensionState.workspaceCommandListsEnabled) { + merged.workspaceCommandListsEnabled = extensionState.workspaceCommandListsEnabled + changedFields++ + } + + // The stamp records the lists this merge leaves on screen, never the posted + // state outright: an entry held back by an in-flight edit was never displayed, + // and a baseline claiming it had been lets the save erase it as a user + // deletion without warning. While the lists are held back the buffered lists + // are themselves unposted, so the stamp keeps its prior lists instead - a + // deletion inside the buffered edit must stay in the baseline for the save to + // apply it rather than resurrect the deleted entry as an external addition. + const [stampAllowed, stampDenied] = commandListsTouched.current + ? (JSON.parse(lastDisplayedCommandSnapshot.current) as [string[], string[], boolean]) + : [ + merged.allowedCommands ?? prevState.allowedCommands, + merged.deniedCommands ?? prevState.deniedCommands, + ] + lastDisplayedCommandSnapshot.current = commandListSnapshot({ + allowedCommands: stampAllowed, + deniedCommands: stampDenied, + workspaceCommandListsEnabled: + merged.workspaceCommandListsEnabled ?? prevState.workspaceCommandListsEnabled, + }) + + if (changedFields === 0) { + return prevState + } + return { ...prevState, ...merged } + }) + }, [extensionState]) + const setCachedStateField: SetCachedStateField = useCallback((field, value) => { setCachedState((prevState) => { if (prevState[field] === value) { return prevState } + if (field === "allowedCommands" || field === "deniedCommands") { + commandListsTouched.current = true + } + setChangeDetected(true) return { ...prevState, [field]: value } }) @@ -382,8 +474,17 @@ const SettingsView = forwardRef(({ onDone, t const handleSubmit = () => { if (isSettingValid) { + const [lastDisplayedAllowed, lastDisplayedDenied] = JSON.parse(lastDisplayedCommandSnapshot.current) as [ + string[], + string[], + boolean, + ] vscode.postMessage({ type: "updateSettings", + commandListBaseline: { + allowedCommands: lastDisplayedAllowed, + deniedCommands: lastDisplayedDenied, + }, updatedSettings: { language, alwaysAllowReadOnly: alwaysAllowReadOnly ?? undefined, @@ -465,6 +566,13 @@ const SettingsView = forwardRef(({ onDone, t vscode.postMessage({ type: "telemetrySetting", text: telemetrySetting }) vscode.postMessage({ type: "debugSetting", bool: cachedState.debug }) + // Saving commits the buffered lists, so they no longer hold off external updates. + commandListsTouched.current = false + lastDisplayedCommandSnapshot.current = commandListSnapshot({ + allowedCommands, + deniedCommands, + workspaceCommandListsEnabled: cachedState.workspaceCommandListsEnabled, + }) setChangeDetected(false) } } @@ -488,6 +596,8 @@ const SettingsView = forwardRef(({ onDone, t if (confirm) { // Discard changes: Reset state and flag setCachedState(extensionState) // Revert to original state + lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) + commandListsTouched.current = false // Buffered edits are gone, so live lists are not held off setChangeDetected(false) // Reset change flag confirmDialogHandler.current?.() // Execute the pending action (e.g., tab switch) } diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx index 6704aa1cf0..f8e4b95737 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx @@ -472,7 +472,7 @@ describe("SettingsView - Change Detection Fix", () => { it("should not show unsaved changes when no changes are made", async () => { const onDone = vi.fn() - ;(useExtensionState as any).mockReturnValue(createExtensionState()) + ;(useExtensionState as ReturnType).mockReturnValue(createExtensionState()) renderWithExtensionState(, { queryClient }) @@ -497,7 +497,7 @@ describe("SettingsView - Change Detection Fix", () => { }, 10000) it("persists a normalized reasoning default through Save", async () => { - ;(useExtensionState as any).mockReturnValue(createExtensionState()) + ;(useExtensionState as ReturnType).mockReturnValue(createExtensionState()) renderWithExtensionState(, { queryClient }) await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) @@ -544,7 +544,7 @@ describe("SettingsView - Change Detection Fix", () => { }, }) - ;(useExtensionState as any).mockImplementation(() => extensionState) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) const { rerender } = renderWithExtensionState(, { queryClient }) @@ -580,7 +580,7 @@ describe("SettingsView - Change Detection Fix", () => { basetenApiKey: "test-baseten-key", }, }) - ;(useExtensionState as any).mockImplementation(() => extensionState) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) rerender() }) @@ -615,7 +615,7 @@ describe("SettingsView - Change Detection Fix", () => { }, }) - ;(useExtensionState as any).mockImplementation(() => extensionState) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) const { rerender } = renderWithExtensionState(, { queryClient }) @@ -635,7 +635,7 @@ describe("SettingsView - Change Detection Fix", () => { basetenApiKey: "imported-baseten-key", }, }) - ;(useExtensionState as any).mockImplementation(() => extensionState) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) rerender() }) @@ -660,7 +660,7 @@ describe("SettingsView - Change Detection Fix", () => { }, }) - ;(useExtensionState as any).mockImplementation(() => extensionState) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) const { rerender } = renderWithExtensionState(, { queryClient }) @@ -720,7 +720,7 @@ describe("SettingsView - Change Detection Fix", () => { apiModelId: "friendli-model", }, }) - ;(useExtensionState as any).mockImplementation(() => extensionState) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) rerender() }) @@ -743,7 +743,7 @@ describe("SettingsView - Change Detection Fix", () => { }, }) - ;(useExtensionState as any).mockImplementation(() => extensionState) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) const { rerender } = renderWithExtensionState(, { queryClient }) @@ -766,7 +766,7 @@ describe("SettingsView - Change Detection Fix", () => { apiModelId: "gpt-4.1", }, }) - ;(useExtensionState as any).mockImplementation(() => extensionState) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) rerender() }) @@ -775,4 +775,109 @@ describe("SettingsView - Change Detection Fix", () => { expect(screen.getByTestId("provider-value")).toHaveTextContent("baseten") }, 20000) }) + + describe("command-list refresh while the dialog is open", () => { + it("merges an externally added deny entry into the buffer before a later save", async () => { + let extensionState = createExtensionState({ deniedCommands: [] }) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) + + const { rerender } = renderWithExtensionState(, { queryClient }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // Buffer an unrelated edit so a Save happens later in this dialog session. + fireEvent.click(screen.getByTestId("set-provider-baseten")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A deny entry lands externally while the dialog is open. + await act(async () => { + extensionState = createExtensionState({ deniedCommands: ["rm -rf"] }) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) + rerender() + }) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + // Save must submit the list that includes the entry the dialog now displays, not the + // stale one captured when the dialog opened. + fireEvent.click(screen.getByTestId("save-button")) + expect(mockPostMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ deniedCommands: ["rm -rf"] }), + }), + ) + }, 10000) + + it("baselines the save on the post-merge lists, not the lists shown when the dialog opened", async () => { + let extensionState = createExtensionState({ deniedCommands: [] }) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) + + const { rerender } = renderWithExtensionState(, { queryClient }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // Buffer an unrelated edit so a Save happens later in this dialog session. + fireEvent.click(screen.getByTestId("set-provider-baseten")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A deny entry lands externally and the merge puts it into the displayed lists. + await act(async () => { + extensionState = createExtensionState({ deniedCommands: ["rm -rf"] }) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) + rerender() + }) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + // The baseline must be the list the dialog NOW displays (post-merge), so the + // merge's entry counts as shown - not the empty list present when the dialog + // opened, which would make the merge's own entry look externally added. + fireEvent.click(screen.getByTestId("save-button")) + expect(mockPostMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { allowedCommands: [], deniedCommands: ["rm -rf"] }, + }), + ) + }, 10000) + + it("merges without clearing unsaved changes when the command-list state flips externally", async () => { + let extensionState = createExtensionState() + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) + + const { rerender } = renderWithExtensionState(, { queryClient }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // Buffer an edit that touches neither command list, so the dialog is dirty. + fireEvent.click(screen.getByTestId("set-provider-baseten")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // One state post flips the workspace command-list gate and adds a deny entry, which is + // what enabling the gate does: workspace entries become part of the displayed lists. + await act(async () => { + extensionState = createExtensionState({ + deniedCommands: ["git push"], + workspaceCommandListsEnabled: true, + }) + ;(useExtensionState as ReturnType).mockImplementation(() => extensionState) + rerender() + }) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + // The merge must not clear the dirty flag or discard the buffered provider edit... + expect(screen.getByTestId("provider-value")).toHaveTextContent("baseten") + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + // ...while the flip's list change still reaches the buffer and the next Save. + fireEvent.click(screen.getByTestId("save-button")) + expect(mockPostMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ deniedCommands: ["git push"] }), + }), + ) + }, 10000) + }) }) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx index 0835f255f9..ae81e16686 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -691,6 +691,32 @@ describe("SettingsView - Allowed Commands", () => { ) }) + it("sends the lists displayed at open as the save baseline, unmoved by an in-flight list edit", () => { + // The save path classifies divergence between "user deleted this" and "the + // settings file gained this" from the baseline, so the payload must carry what + // the dialog displayed BEFORE this save - not the edited list it is submitting, + // and not the committed value the post-save bookkeeping writes back. + renderWithExtensionState(, { + state: { allowedCommands: ["git"], alwaysAllowExecute: true }, + }) + + const content = screen.getByTestId("settings-content") + // An in-flight addition lands in the edit buffer only. + const input = within(content).getByTestId("command-input") + fireEvent.change(input, { target: { value: "npm test" } }) + fireEvent.click(within(content).getByTestId("add-command-button")) + + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { allowedCommands: ["git"], deniedCommands: [] }, + updatedSettings: expect.objectContaining({ allowedCommands: ["git", "npm test"] }), + }), + ) + }) + it("removes command from the list", () => { // Render once and get the activateTab helper const { activateTab, getSettingsContent } = renderSettingsView() diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 1bc4ab1afb..04e0c7e18a 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -249,6 +249,7 @@ vi.mock("../SettingsSearch", () => ({ import { useExtensionState } from "@src/context/ExtensionStateContext" import ApiOptions from "../ApiOptions" +import { AutoApproveSettings } from "../AutoApproveSettings" describe("SettingsView - Unsaved Changes Detection", () => { let queryClient: QueryClient @@ -811,6 +812,137 @@ describe("SettingsView - Unsaved Changes Detection", () => { }) }) + it("keeps an in-flight deny-list edit when an external list update arrives while the dialog is open", async () => { + // Drive the real cached-state setter through a stand-in auto-approve section so the + // buffered list edit is indistinguishable from a user typing in the deny list. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( + + ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("buffer-deny-edit")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // The deny list changes in the extension host while the dialog is open. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + view.rerender() + + // The user's unsaved list edit wins over the external update, and Save submits it. + fireEvent.click(screen.getByTestId("save-button")) + expect(postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ deniedCommands: ["git status"] }), + }), + ) + expect(postMessage).not.toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ deniedCommands: ["rm -rf"] }), + }), + ) + }) + + it("baselines the save on the pre-edit displayed lists when a state post lands during an in-flight list edit", async () => { + // The baseline feeds the save's classification of every entry the submitted + // list omits, so it must hold the lists the dialog displayed BEFORE the + // in-flight edit. Folding the posted state in would claim the never-displayed + // entry had been shown, letting the save erase it as a user deletion; folding + // the edited buffer in would drop an in-flight deletion from the baseline, + // letting the save resurrect it as an external addition. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( + + ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("buffer-deny-edit")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A deny entry lands externally while the list edit holds the merge back. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + + // The submit keeps the in-flight edit, and the baseline stays at the lists + // displayed before the edit - neither the held-back post's list nor the + // edited buffer's. + expect(postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { allowedCommands: [], deniedCommands: [] }, + updatedSettings: expect.objectContaining({ deniedCommands: ["git status"] }), + }), + ) + }) + + it("keeps a deleted displayed entry in the save baseline when a state post lands during the deletion", async () => { + // The deletion counterpart: an entry the dialog displayed and the user then + // deleted must stay in the baseline, so the save classifies it as a user + // deletion and applies it. A baseline folded from the deletion-carrying + // buffer would make the entry look externally added and re-admit it. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( + + ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A coincidental post re-bakes the deny list and adds an entry the dialog + // never displayed; the held merge keeps the buffered deletion. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf", "docker"], + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + + // The baseline retains the deleted (displayed) entry so the save applies the + // deletion, and excludes the never-displayed "docker" so the save keeps that + // entry and warns about it instead. + expect(postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { allowedCommands: [], deniedCommands: ["rm -rf"] }, + updatedSettings: expect.objectContaining({ deniedCommands: [] }), + }), + ) + }) + it("discards IO Intelligence cached edits and restores the extension values", async () => { const onDone = vi.fn() ;(useExtensionState as ReturnType).mockReturnValue({ From 97e5ab1322561c201515332ea660587754596f6d Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 5 Nov 2026 22:16:47 +0100 Subject: [PATCH 08/52] fix: stop false settings-changed warning for hidden command entries Workspace command-list entries hidden from the settings dialog - by the default-off workspace gate or by a shadowing entry in the opposite list - were classified as added outside the dialog, so every save showed a false "settings file changed" warning naming them. Compute the hidden-entry set before classifying external additions and keep those entries out of the warning; the save keeps preserving them in the workspace layer unchanged. --- .../__tests__/webviewMessageHandler.spec.ts | 104 ++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 50 +++++---- 2 files changed, 134 insertions(+), 20 deletions(-) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 61c3d35d75..fbf68ed511 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2828,6 +2828,110 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("docker")) }) + + // A file-side extra the hidden-entry re-add already preserves was never + // displayed, so naming it in the changed-settings warning would repeat that + // warning on every save while the file stays unchanged. + it.each([ + { + name: "hidden while the workspace gate is off", + gateEnabled: false, + hiddenEntry: "docker", + prepare: () => { + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + }, + }, + { + name: "shadowed by a global allow while the gate is on", + gateEnabled: true, + hiddenEntry: "git push", + prepare: () => { + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git"] : undefined, + ) + }, + }, + ])( + "re-adds a $name deny entry without warning that the settings file changed", + async ({ gateEnabled, hiddenEntry, prepare }) => { + prepare() + const { update } = mockCommandConfiguration( + { workspaceValue: [hiddenEntry] }, + undefined, + undefined, + gateEnabled, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + // The dialog displayed the effective deny list, which never + // contained the hidden entry, so the baseline omits it. + commandListBaseline: { deniedCommands: [] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", [hiddenEntry], vscode.ConfigurationTarget.Workspace) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }, + ) + + it("warns only about the genuine file addition when a hidden entry is also present", async () => { + // Mixed divergence in one save: "git push" is hidden by the global allow + // "git" and preserved by the re-add, while "wget" arrived in the visible + // part of the file after the dialog opened. The warning must name only + // the genuine addition. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git"] : undefined, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["git push", "curl", "wget"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["curl"] }, + // The dialog displayed the shadow-filtered deny list: "curl" was + // visible and kept, "git push" was never displayed, and "wget" + // arrived in the settings file after the dialog opened. + commandListBaseline: { deniedCommands: ["curl"] }, + }) + + // "git push" survives through the hidden-entry re-add, "wget" through + // the external-addition re-admission; the global layer stays empty. + expect(update).toHaveBeenCalledWith( + "deniedCommands", + ["curl", "wget", "git push"], + vscode.ConfigurationTarget.Workspace, + ) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("1 entry was")) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("wget")) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalledWith(expect.stringContaining("git push")) + }) + + it("still warns about a visible workspace addition alongside the hidden-entry exclusion", async () => { + // Regression witness for the hidden-entry exclusion: an entry that + // arrived in the displayed part of the file is a genuine external + // addition, is kept in the layer the snapshot found it in, and is named + // in the warning. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ workspaceValue: ["git", "curl"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"] }, + commandListBaseline: { allowedCommands: ["git"] }, + }) + + expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "curl"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) + }) }) describe("webviewMessageHandler - terminalProfile", () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index c20867cd78..52eb8d861b 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -852,32 +852,15 @@ export const webviewMessageHandler = async ( } const currentScopes = readCommandListScopes(key, getGlobalState(key), inspection) - // An entry the settings file gained while the dialog was open has - // the same shape as an entry the user deleted: present in the file, - // absent from the submitted list. Only the dialog's last-displayed - // baseline separates the two, so file entries outside that baseline - // are re-admitted before the split (deletions of baseline entries - // still apply). A sender that shows no lists sends no baseline, and - // its submitted list is written unclassified. - const baseline = message.commandListBaseline?.[key] - const externallyAdded = Array.isArray(baseline) - ? [...new Set([...currentScopes.workspace, ...currentScopes.global])].filter( - (entry) => !baseline.includes(entry) && !incoming.includes(entry), - ) - : [] - const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( - [...incoming, ...externallyAdded], - currentScopes.workspace, - currentScopes.global, - ) // Shadowing is cross-directional, so the hidden-entry set // needs the opposite key's global layer as input. It comes // from the save-start snapshot, not a fresh read: an // earlier iteration of this loop may already have written // that key. The layer only feeds the additive preservation - // below and never this key's split, target, or rollback, - // which stay on the per-key configuration snapshot. + // below and this key's external-addition classification, and + // never this key's split, target, or rollback, which stay on + // the per-key configuration snapshot. const otherKey = key === "allowedCommands" ? "deniedCommands" : "allowedCommands" const otherScopes = readCommandListScopes(otherKey, commandListGlobalsAtSaveStart[otherKey]) const { hiddenWorkspaceAllow, hiddenWorkspaceDeny } = resolveEffectiveCommandLists( @@ -893,6 +876,33 @@ export const webviewMessageHandler = async ( // file. const hiddenWorkspaceEntries = key === "allowedCommands" ? hiddenWorkspaceAllow : hiddenWorkspaceDeny + + // An entry the settings file gained while the dialog was open has + // the same shape as an entry the user deleted: present in the file, + // absent from the submitted list. Only the dialog's last-displayed + // baseline separates the two, so file entries outside that baseline + // are re-admitted before the split (deletions of baseline entries + // still apply). Hidden entries never appear in that baseline, yet + // the workspace-layer re-add below preserves them, so classifying + // them as external additions would repeat a false "settings file + // changed" warning on every save. A sender that shows no lists + // sends no baseline, and its submitted list is written + // unclassified. + const baseline = message.commandListBaseline?.[key] + const externallyAdded = Array.isArray(baseline) + ? [...new Set([...currentScopes.workspace, ...currentScopes.global])].filter( + (entry) => + !baseline.includes(entry) && + !incoming.includes(entry) && + !hiddenWorkspaceEntries.includes(entry), + ) + : [] + const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( + [...incoming, ...externallyAdded], + currentScopes.workspace, + currentScopes.global, + ) + const workspaceWrite = [...new Set([...keptWorkspaceWrite, ...hiddenWorkspaceEntries])] const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) From 9736c1d9b1ca595ca84335541b4b0f338f6f5d1c Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Fri, 6 Nov 2026 13:48:04 +0100 Subject: [PATCH 09/52] fix: promote re-added hidden command entries to the global write When a settings save submitted an entry that sits in the workspace layer but is hidden from the settings dialog - by the default-off workspace gate or by a shadowing entry in the opposite list - the code that splits entries between the global and workspace writes treated it as already known, so the save succeeded while the entry stayed unenforced. The save path now excludes hidden entries from the workspace layer it passes to the split, so a re-added hidden entry is promoted to the global write, while the existing re-add keeps it in the workspace layer. Two save-path tests pin the promotion for both hide reasons. Tests also pin the raw global command lists surfaced to the extension host when the workspace layer differs, and that an explicitly empty stored list seeds empty instead of the defaults. --- .../webview/__tests__/ClineProvider.spec.ts | 25 ++++++++ .../__tests__/webviewMessageHandler.spec.ts | 57 ++++++++++++++++++- src/core/webview/webviewMessageHandler.ts | 16 ++++-- .../__tests__/seedAllowedCommands.spec.ts | 19 +++++++ 4 files changed, 110 insertions(+), 7 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 8c46daf85e..55f9ebf994 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4147,6 +4147,31 @@ describe("ClineProvider", () => { expect(state.allowedCommands).toEqual([]) }) + test("getState returns the raw global command lists when the workspace layer differs", async () => { + await provider.contextProxy.setValue("allowedCommands", ["git"]) + await provider.contextProxy.setValue("deniedCommands", ["curl"]) + const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) + const inspect = vi.fn() + inspect.mockImplementation((key: string) => ({ + key, + workspaceValue: key === "allowedCommands" ? ["docker"] : ["pnpm"], + })) + config.inspect = inspect + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + const state = await provider.getState() + + // The raw global layers are the feed per-folder enforcement + // re-composes from, so they must stay distinguishable from the + // window-composed pair: with the layers diverging here, a dropped + // field or a composed value would silently reroute enforcement to + // the first-folder lists. + expect(state.globalAllowedCommands).toEqual(["git"]) + expect(state.globalDeniedCommands).toEqual(["curl"]) + expect(state.allowedCommands).toEqual(["git", "docker"]) + expect(state.deniedCommands).toEqual(["curl", "pnpm"]) + }) + test("getState prefers the workspace-folder value for multi-root workspaces", async () => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn().mockImplementation((key: string) => key === "workspaceCommandListsEnabled"), diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index fbf68ed511..1fbc13e2dd 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2176,7 +2176,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { } it("keeps workspace-scoped denied commands out of the global write when saving the merged list", async () => { - const { update, inspect } = mockCommandConfiguration({ workspaceValue: ["docker"] }) + // Gate on: the workspace entry is visible in the dialog, so keeping it + // is not a re-add. (With the gate off every submitted workspace entry + // is a re-add and is promoted to the global layer instead.) + const { update, inspect } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -2198,7 +2201,14 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("writes the workspace-folder value at the folder target in multi-root workspaces", async () => { - const { update } = mockCommandConfiguration({ workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }) + // Gate on for the same reason as the merged-list split test: the kept + // folder entry is visible in the dialog, so it stays at its scope. + const { update } = mockCommandConfiguration( + { workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, + undefined, + undefined, + true, + ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -2480,6 +2490,49 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) }) + it("promotes a gate-hidden workspace entry the dialog re-adds to the global write", async () => { + // With the gate off the dialog shows only the global layer, so a + // submitted entry the workspace layer already holds hidden is one the + // user just added: it must reach the enforced global layer instead of + // being treated as existing knowledge, while the re-add below still + // keeps it in the workspace file. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) + }) + + it("promotes a shadowed workspace entry the dialog re-adds to the global write", async () => { + // The global allow "git" shadows the workspace deny "git push", so the + // dialog never displayed the deny entry; a user who re-adds it submits a + // list containing it, and the entry must land in the global layer where + // the gate makes it effective, while the re-add preserves the workspace + // copy. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git"] : undefined, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["git push"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Global) + }) + it("re-adds a shadowed workspace allow entry alongside the user's visible deletions", async () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["git"] : undefined, diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 52eb8d861b..e75df27a16 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -857,10 +857,11 @@ export const webviewMessageHandler = async ( // needs the opposite key's global layer as input. It comes // from the save-start snapshot, not a fresh read: an // earlier iteration of this loop may already have written - // that key. The layer only feeds the additive preservation - // below and this key's external-addition classification, and - // never this key's split, target, or rollback, which stay on - // the per-key configuration snapshot. + // that key. The layer only feeds the hidden-entry mechanism + // below — additive preservation, external-addition + // classification, and the split's promotion filter — + // and never this key's target or rollback, which stay + // on the per-key configuration snapshot. const otherKey = key === "allowedCommands" ? "deniedCommands" : "allowedCommands" const otherScopes = readCommandListScopes(otherKey, commandListGlobalsAtSaveStart[otherKey]) const { hiddenWorkspaceAllow, hiddenWorkspaceDeny } = resolveEffectiveCommandLists( @@ -899,7 +900,12 @@ export const webviewMessageHandler = async ( : [] const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( [...incoming, ...externallyAdded], - currentScopes.workspace, + // Hidden entries are not existing knowledge for promotion + // purposes: the dialog never displayed them, so an entry the + // user just added is new even when the workspace layer + // already holds it hidden. The re-add below restores the + // hidden entries this reduced layer drops. + currentScopes.workspace.filter((entry) => !hiddenWorkspaceEntries.includes(entry)), currentScopes.global, ) diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts index 50c1dd5fc6..c5ddd11767 100644 --- a/src/utils/__tests__/seedAllowedCommands.spec.ts +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -206,6 +206,25 @@ describe("seedAllowedCommands", () => { expect(globalState.get("allowedCommands")).toEqual(["git"]) }) + it("seeds an explicitly empty global value instead of the populated default", async () => { + // An explicitly empty global list is a deliberate opt-out: the seed + // persists [] so global state counts as seeded, rather than treating + // the empty allowlist as unset and re-granting the declared defaults. + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + globalValue: [], + }, + }) + const globalState = mockMemento() + + await seedAllowedCommands(globalState) + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", []) + expect(globalState.get("allowedCommands")).toEqual([]) + }) + it("does not overwrite global state that is already populated", async () => { mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] }, effective: ["git"] }) const globalState = mockMemento(["npm"]) From 8d99f545c1d4b87c027af0dc06ccd9fe5a44612e Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Mon, 9 Nov 2026 23:03:20 +0100 Subject: [PATCH 10/52] fix: judge command approvals by the directory the command runs in The execute tool resolves a command's working directory once and forwards it through the approval context, so the initial approval and the queued re-check judge the same directory the command executes in; a directory no workspace folder claims is judged by the global command lists only. First-run seeding now guards the allow and deny lists per key, so a profile seeded by an earlier version still gets its deny list migrated, and a workspace override suppresses the declared defaults only while the workspace-lists gate is enabled. Tests pin the per-folder configuration lookup, the unset gate in both provider-state paths, and the seed schedule. --- src/__tests__/extension.spec.ts | 56 +++-- .../__tests__/commandScope.spec.ts | 92 ++++++- src/core/auto-approval/index.ts | 39 ++- src/core/task/Task.ts | 18 +- .../task/__tests__/ask-allowlist-cwd.spec.ts | 234 ++++++++++++++++++ src/core/tools/ExecuteCommandTool.ts | 48 +++- .../__tests__/executeCommandTool.spec.ts | 111 ++++++++- .../webview/__tests__/ClineProvider.spec.ts | 78 +++++- .../__tests__/webviewMessageHandler.spec.ts | 52 ++-- src/extension.ts | 8 +- src/shared/tools.ts | 9 + .../__tests__/seedAllowedCommands.spec.ts | 147 +++++++++-- src/utils/seedAllowedCommands.ts | 35 ++- 13 files changed, 812 insertions(+), 115 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 317e1dba6a..1788299572 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -539,26 +539,35 @@ describe("extension.ts", () => { expect(dotenv.config).toHaveBeenCalledTimes(1) }) - describe("allowedCommands activation seeding", () => { + describe("command-list activation seeding", () => { function setConfigScope( vscode: typeof import("vscode"), - scope: { globalValue?: string[]; workspaceValue?: string[] }, + scope: { globalValue?: string[]; workspaceValue?: string[]; deniedGlobalValue?: string[]; gate?: boolean }, ) { - const { globalValue, workspaceValue } = scope + const { globalValue, workspaceValue, deniedGlobalValue, gate = false } = scope vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ // Key-scoped so proxy/other activation reads still see no value. - get: vi.fn((key: string) => - key === "allowedCommands" ? [...(globalValue ?? []), ...(workspaceValue ?? [])] : undefined, - ), - inspect: vi.fn().mockReturnValue({ - key: "allowedCommands", - // Real inspect() always reports the declared package default; - // including it here lets the workspace-override test prove the - // default stays unseeded beside an override, not just absent. - defaultValue: ["git log", "git diff", "git show"], - globalValue, - workspaceValue, + get: vi.fn((key: string) => { + if (key === "workspaceCommandListsEnabled") { + return gate + } + return key === "allowedCommands" ? [...(globalValue ?? []), ...(workspaceValue ?? [])] : undefined }), + // Key-scoped inspect: the deny seed must not read the allow scope's + // values through the same fixture object. + inspect: vi.fn().mockImplementation((key: string) => + key === "deniedCommands" + ? { key, defaultValue: [], globalValue: deniedGlobalValue } + : { + key, + // Real inspect() always reports the declared package default; + // including it here lets the workspace-override test prove the + // default stays unseeded beside an override, not just absent. + defaultValue: ["git log", "git diff", "git show"], + globalValue, + workspaceValue, + }, + ), update: vi.fn(), // The double scripts key-scoped get() and per-scope inspect() // shapes the shared helper cannot express without obscuring them. @@ -579,9 +588,13 @@ describe("extension.ts", () => { } as unknown as vscode.WorkspaceConfiguration) }) - test("does not seed global state from a workspace-scoped override", async () => { + test("does not seed global state from an enforced workspace-scoped override", async () => { const vscode = await import("vscode") - setConfigScope(vscode, { workspaceValue: ["docker"] }) + // The gate is on: an enforced workspace list replaces the default across + // scopes, so the seed must not re-grant the approvals it removed. (With + // the gate off the workspace layer is inert and the default is seeded — + // pinned in the seed module's own spec.) + setConfigScope(vscode, { workspaceValue: ["docker"], gate: true }) const { activate } = await import("../extension") await activate(mockContext) @@ -611,6 +624,17 @@ describe("extension.ts", () => { expect(mockContext.globalState.update).not.toHaveBeenCalledWith("allowedCommands", expect.anything()) expect(globalStateValues.get("allowedCommands")).toEqual(["npm"]) }) + + test("seeds both command-list keys on a fresh profile", async () => { + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + + const { activate } = await import("../extension") + await activate(mockContext) + + expect(mockContext.globalState.update).toHaveBeenCalledWith("allowedCommands", ["git"]) + expect(mockContext.globalState.update).toHaveBeenCalledWith("deniedCommands", ["docker"]) + }) }) describe("cloud organization settings handling", () => { diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 15598f4caf..02d3eb8b37 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -492,14 +492,16 @@ function openMultiRootWindow() { // Scripts each folder's configuration independently so the test can tell // which folder's settings the enforcement path actually read. -function mockFolderConfigurations(scripts: Record) { +function mockFolderConfigurations(scripts: Record) { vi.mocked(vscode.workspace.getConfiguration).mockImplementation( (_section?: string, scope?: vscode.ConfigurationScope | null) => { const entry = scripts[scope && "fsPath" in scope ? scope.fsPath : ""] const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: entry?.gate ?? false }) - vi.mocked(config.inspect).mockImplementation((key: string) => - key === "deniedCommands" && entry?.deny ? { key, workspaceFolderValue: entry.deny } : undefined, - ) + vi.mocked(config.inspect).mockImplementation((key: string) => { + const layer = + key === "deniedCommands" ? entry?.deny : key === "allowedCommands" ? entry?.allow : undefined + return layer ? { key, workspaceFolderValue: layer } : undefined + }) return config }, ) @@ -560,26 +562,94 @@ it("checkAutoApproval command: does not apply another root's deny entries to a t expect(result).toEqual({ decision: "ask" }) }) -it("checkAutoApproval command: falls back to the first folder when the cwd resolves to no workspace root", async () => { +it("checkAutoApproval command: does not apply the first folder's allow list to a cwd naming no workspace root", async () => { vi.clearAllMocks() const { folderA, folderB } = openMultiRootWindow() + // Folder A's layer allows "echo"; the cwd names a removed or relocated + // folder, so no folder's layer may decide the command. Consuming folder A's + // allow entry here would approve a command executing outside every + // workspace folder: a cwd naming no workspace root must not be approvable + // by any folder's allow list — the composition is judged by the (empty) + // global layers only. mockFolderConfigurations({ - [folderA.fsPath]: { gate: true, deny: ["echo"] }, + [folderA.fsPath]: { gate: true, deny: [], allow: ["echo"] }, [folderB.fsPath]: { gate: true, deny: ["rm"] }, }) - // A removed or relocated folder names no root; enforcement stays on the - // first-folder configuration it used before per-task scoping existed. const result = await checkAutoApproval({ - state: taskFolderState(["echo"]), + state: taskFolderState([]), + cwd: "/mock/removed-folder", + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + +it("checkAutoApproval command: still lets a global deny entry veto a command whose cwd names no workspace root", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + // The global-only composition keeps the global layers authoritative: the + // unmatched cwd drops only the workspace layer, never the global deny. + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["rm"] }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + const result = await checkAutoApproval({ + state: { ...taskFolderState([]), globalDeniedCommands: ["echo"] }, cwd: "/mock/removed-folder", ask: "command", text: "echo hi", }) expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) - expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) - expect(vscode.workspace.getConfiguration).not.toHaveBeenCalledWith(Package.name, folderB) +}) + +it("checkAutoApproval command: keeps the first-folder composition for a blank cwd", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + // A blank cwd is the cwd-absent case, not the unmatched case: it stays on + // the first-folder configuration it used before per-folder scoping existed. + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["echo"] }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + const result = await checkAutoApproval({ + state: taskFolderState([]), + cwd: "", + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) +}) + +it("checkAutoApproval command: treats a throwing workspace-folder lookup as a cwd naming no folder", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + // The lookup guard exists so a broken lookup cannot fail the decision; the + // degradation it produces must be the global-only composition, not a + // first-folder guess — the same fail-closed direction as an unmatched cwd. + // Once-only: spies survive between tests in this file, and a leaked throwing + // lookup would change every later test's folder resolution. + vi.mocked(vscode.workspace.getWorkspaceFolder).mockImplementationOnce(() => { + throw new Error("workspace unavailable") + }) + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: [], allow: ["echo"] }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + const result = await checkAutoApproval({ + state: taskFolderState([]), + cwd: folderA.fsPath, + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) }) it("checkAutoApproval command: in a single-folder window reads exactly the same configuration as before", async () => { diff --git a/src/core/auto-approval/index.ts b/src/core/auto-approval/index.ts index 212f021f2c..de9bdcede1 100644 --- a/src/core/auto-approval/index.ts +++ b/src/core/auto-approval/index.ts @@ -178,8 +178,11 @@ export async function checkAutoApproval({ * Workspace root the allowlist patterns and the checked path are resolved * against. * - * Must be the `cwd` of the task this ask belongs to, which is the root the - * path in `text` was made relative to. It is not read from `state`, because + * For every ask but a command, this is the `cwd` of the task the ask belongs + * to — the root the path in `text` was made relative to. A command ask is + * judged against the command's own resolved working directory when the + * caller forwards `commandCwd`, which a custom working directory moves off + * the task folder. It is not read from `state`, because * the provider's `cwd` follows the window (the focused editor in a multi-root * workspace, or a `refreshWorkspace()` while the task runs) and a resumed or * child task can run against another root entirely. Resolving against the @@ -313,13 +316,20 @@ export async function checkAutoApproval({ } // The pair on `state` was composed against the window's first - // folder; a task rooted in another folder must be judged by that - // folder's lists, so enforcement re-composes from the raw global - // layers at the folder the task's `cwd` resolves to (a cwd that - // names no workspace root keeps the first-folder configuration). - // Without the raw layers the pre-composed pair is all the state - // carries, and that pair is what enforcement consumes. - const taskFolder = commandListFolderForResource(cwd) + // folder; a command executing in another folder must be judged by + // that folder's lists, so enforcement re-composes from the raw + // global layers at the folder the command's `cwd` resolves to. A + // non-blank `cwd` that resolves to no workspace root names a + // directory outside every folder, and no folder's layer may decide + // it: the workspace layer is dropped (`enabled=false`) and only the + // global layers apply — fail-closed, so nothing on a folder's + // allow list can approve a command in a directory no folder + // claims. A blank or absent `cwd` keeps the first-folder + // configuration. Without the raw layers the pre-composed pair is + // all the state carries, and that pair is what enforcement + // consumes. + const commandFolder = commandListFolderForResource(cwd) + const cwdNamesNoFolder = Boolean(cwd) && commandFolder === undefined const effectiveLists = state.globalAllowedCommands !== undefined && state.globalDeniedCommands !== undefined ? resolveEffectiveCommandLists( @@ -327,10 +337,15 @@ export async function checkAutoApproval({ "allowedCommands", state.globalAllowedCommands, undefined, - taskFolder, + commandFolder, ), - readCommandListScopes("deniedCommands", state.globalDeniedCommands, undefined, taskFolder), - workspaceCommandListsEnabled(), + readCommandListScopes( + "deniedCommands", + state.globalDeniedCommands, + undefined, + commandFolder, + ), + workspaceCommandListsEnabled() && !cwdNamesNoFolder, ) : { allowed: state.allowedCommands || [], denied: state.deniedCommands || [] } diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index b911479bc6..ab71f40053 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1287,10 +1287,12 @@ export class Task extends EventEmitter implements TaskLike { text, isProtected, dcgDecision, + commandCwd, }: { text?: string isProtected?: boolean dcgDecision?: AutoApprovalContext["dcgDecision"] + commandCwd?: AutoApprovalContext["commandCwd"] }, abortSignal?: AbortSignal, ): Promise { @@ -1319,11 +1321,12 @@ export class Task extends EventEmitter implements TaskLike { // Disengaged: the queued answer is a legitimate approval, as before. return { action: "consume" } } - // Engaged: the full policy decides, with the fresh state. `cwd` and the - // forwarded DCG verdict match the ask-time `checkAutoApproval` call. + // Engaged: the full policy decides, with the fresh state. `cwd`, the + // forwarded DCG verdict, and the command's working directory match the + // ask-time `checkAutoApproval` call. const approval = await checkAutoApproval({ state: freshState, - cwd: this.cwd, + cwd: commandCwd ?? this.cwd, ask: "command", text, isProtected, @@ -1984,12 +1987,15 @@ export class Task extends EventEmitter implements TaskLike { // `this.cwd`, not `provider.cwd`: // The path inside `text` was made relative to this task's workspace, // which for a resumed or child task need not be the one the provider - // currently reports. + // currently reports. A tool that forwards a `commandCwd` overrides that + // for policy purposes: the command lists must judge the directory the + // command will actually run in, which a custom tool `cwd` moves off the + // task folder. const approval = queuedAskResolution ? ({ decision: "ask" } as const) : await checkAutoApproval({ state, - cwd: this.cwd, + cwd: autoApprovalContext?.commandCwd ?? this.cwd, ask: type, text, isProtected, @@ -2262,6 +2268,7 @@ export class Task extends EventEmitter implements TaskLike { text, isProtected, dcgDecision: autoApprovalContext?.dcgDecision, + commandCwd: autoApprovalContext?.commandCwd, }, recheckAbort.signal, ) @@ -2335,6 +2342,7 @@ export class Task extends EventEmitter implements TaskLike { text, isProtected, dcgDecision: autoApprovalContext?.dcgDecision, + commandCwd: autoApprovalContext?.commandCwd, }, recheckAbort.signal, ) diff --git a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts index 3b3682f969..be3f855616 100644 --- a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts +++ b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts @@ -4,6 +4,55 @@ import type { ExtensionState } from "@roo-code/types" import { Task } from "../Task" +// Command-list enforcement resolves the command's cwd to a workspace folder and +// reads that folder's configuration; the shared module mock resolves every +// lookup to nothing, so these scriptable stand-ins (wrapping the real mock) are +// what let a command ask be judged by a named folder's allow/deny entries. +const workspaceState = vi.hoisted(() => ({ + workspaceFolders: [] as { fsPath: string; uri: { fsPath: string } }[], + foldersByPath: new Map(), + configScripts: {} as Record, +})) + +vi.mock("vscode", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + workspace: { + ...actual.workspace, + get workspaceFolders() { + return workspaceState.workspaceFolders + }, + getConfiguration: (_section?: string, scope?: { fsPath?: string } | null) => { + const entry = workspaceState.configScripts[scope?.fsPath ?? ""] + return { + get: (key: string, defaultValue?: unknown) => + key === "workspaceCommandListsEnabled" ? (entry?.gate ?? false) : defaultValue, + inspect: (key: string) => { + const layer = + key === "deniedCommands" + ? entry?.deny + : key === "allowedCommands" + ? entry?.allow + : undefined + return layer ? { key, workspaceFolderValue: layer } : undefined + }, + update: () => Promise.resolve(), + } + }, + getWorkspaceFolder: (resource?: { fsPath?: string }) => { + const fsPath = resource?.fsPath ?? "" + for (const [folderPath, uri] of workspaceState.foldersByPath) { + if (fsPath === folderPath || fsPath.startsWith(`${folderPath}/`)) { + return { uri } + } + } + return undefined + }, + }, + } +}) + // The allowlist patterns are resolved against a workspace root, and the path in // the tool message was made relative by `getReadablePath(task.cwd, ...)`. So the // root used for matching has to be the task's own `cwd`. @@ -103,3 +152,188 @@ describe("Task.ask resolves allowlists against the task's workspace", () => { expect(await askToWriteRelativePath([`${PROVIDER_CWD}/notes.md`])).toBe("ask") }) }) + +// Command asks: the per-folder command lists must judge the directory the +// command will actually run in (`commandCwd` from the tool's approval +// context), not the task folder — a task in folder A must not be able to ride +// folder A's allow entry to run a command in folder B. The raw global layers +// are set empty on the state so every decision below comes from the folder the +// command's cwd resolves to; the baked pair carries values no folder composes, +// so a check that consumed it instead of re-composing decides differently. + +const FOLDER_A = "/mock/folder-a" +const FOLDER_B = "/mock/folder-b" + +function openTwoFolders() { + const folderA = { fsPath: FOLDER_A, uri: { fsPath: FOLDER_A } } + const folderB = { fsPath: FOLDER_B, uri: { fsPath: FOLDER_B } } + workspaceState.workspaceFolders = [folderA, folderB] + workspaceState.foldersByPath.set(FOLDER_A, folderA.uri) + workspaceState.foldersByPath.set(FOLDER_B, folderB.uri) + // Folder A allows "echo" and folder B denies it, so a decision names the + // folder that was read. + workspaceState.configScripts = { + [FOLDER_A]: { gate: true, allow: ["echo"] }, + [FOLDER_B]: { gate: true, deny: ["echo"] }, + } +} + +const commandState = (extra: Partial = {}): Partial => ({ + autoApprovalEnabled: true, + alwaysAllowExecute: true, + allowedCommands: ["echo"], + deniedCommands: [], + globalAllowedCommands: [], + globalDeniedCommands: [], + ...extra, +}) + +/** Ask to run a command with the given approval context and report the policy decision. */ +const askToRunCommand = async (commandCwd: string | undefined, state: Partial) => { + const provider: ProviderStub = { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + cwd: PROVIDER_CWD, + getState: async () => state, + } + // The task runs in folder A (whose allow entry must NOT approve a command + // executing in folder B) — the task cwd equals folder A here. + const task = buildTask(provider, FOLDER_A) + await attachQueue(task) + + const asked = task.ask("command", "echo hi", false, undefined, false, { commandCwd }) + + const addToClineMessages = task["addToClineMessages"] as ReturnType + await vi.waitUntil(() => addToClineMessages.mock.calls.length > 0) + const message = addToClineMessages.mock.calls[0][0] + + task.approveAsk() + await asked + + return message.autoApprovalDecision ?? ("ask" as const) +} + +describe("Task.ask judges command asks by the command's working directory", () => { + beforeEach(() => { + workspaceState.workspaceFolders = [] + workspaceState.foldersByPath.clear() + workspaceState.configScripts = {} + }) + + it("approves a command whose custom cwd resolves to the folder that allows it", async () => { + openTwoFolders() + // Only folder B carries the entry, so approval can only come from the + // folder the command runs in. + workspaceState.configScripts[FOLDER_A] = { gate: true } + workspaceState.configScripts[FOLDER_B] = { gate: true, allow: ["echo"] } + + expect(await askToRunCommand(FOLDER_B, commandState())).toBe("approve") + }) + + it("does not approve a command executing where the same entry is denied, although the task folder allows it", async () => { + openTwoFolders() + + // The task folder (A) allows "echo"; the command runs in B, which denies + // it. The deny layer must decide. + expect(await askToRunCommand(FOLDER_B, commandState())).toBe("deny") + }) + + it("judges a custom cwd that names no workspace folder by the global layers only", async () => { + openTwoFolders() + + // The baked pair would approve, but with the raw layers present the + // command branch re-composes: an unmatched cwd drops the workspace + // layer entirely, so nothing allows or denies "echo" and the user decides. + expect(await askToRunCommand("/mock/removed-folder", commandState())).toBe("ask") + }) + + it("keeps judging a command without a custom cwd by the task folder's policy", async () => { + openTwoFolders() + + // No approval context at all: the task folder's own entry still decides. + expect(await askToRunCommand(undefined, commandState())).toBe("approve") + }) + + it("re-checks a drained queued command against the command's working directory", async () => { + openTwoFolders() + const provider: ProviderStub = { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + cwd: PROVIDER_CWD, + // First read (ask time): blanket deny off, execute auto-approval off, + // so the ask stays pending. Second read (drain re-check): blanket + // deny engaged, so the queued message must re-earn its approval. + getState: vi + .fn() + .mockResolvedValueOnce(commandState({ alwaysAllowExecute: false, alwaysDenyUnapprovedCommands: false })) + .mockResolvedValue(commandState({ alwaysDenyUnapprovedCommands: true })), + } + // The task is rooted in folder B (which denies "echo") while the command + // runs in folder A (which allows it): a re-check that fell back to the + // task folder would deny the queued approval the command's own folder + // grants. + const task = buildTask(provider, FOLDER_B) + await attachQueue(task) + + const asked = task.ask("command", "echo hi", false, undefined, false, { commandCwd: FOLDER_A }) + await vi.waitUntil(() => (task["addToClineMessages"] as ReturnType).mock.calls.length > 0) + task.messageQueueService.addMessage("run it") + + // Folder A allows "echo"; had the re-check judged the task-independent + // defaults or the baked pair, the blanket deny would reject the queued + // approval. The folder the command runs in approves it. + const result = await asked + + expect(result.response).toBe("yesButtonClicked") + expect(result.autoDenyDetail).toBeUndefined() + }) + + it("re-checks a queued command drained at ask entry with no approval context", async () => { + openTwoFolders() + // A message already queued when the ask opens, with the claim gate open + // (blanket deny off): the ENTRY drain (not the later pWaitFor one) + // performs the policy re-check, and folder A's entry approves it. + const provider: ProviderStub = { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + cwd: PROVIDER_CWD, + getState: async () => commandState({ alwaysDenyUnapprovedCommands: false }), + } + const task = buildTask(provider, FOLDER_A) + await attachQueue(task) + task.messageQueueService.addMessage("run it") + + // No approval context at all: the entry re-check must run cleanly + // against the task folder and approve via folder A's entry. A throw + // there is caught and logged (then the pWaitFor drain would paper over + // it), so the log is the witness. + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + const result = await task.ask("command", "echo hi", false) + + expect(result.response).toBe("yesButtonClicked") + expect(result.autoDenyDetail).toBeUndefined() + expect(errorSpy).not.toHaveBeenCalled() + errorSpy.mockRestore() + }) + + it("denies a drained queued command whose working directory the policy denies, although the blanket path would accept it", async () => { + openTwoFolders() + const provider: ProviderStub = { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + cwd: PROVIDER_CWD, + getState: vi + .fn() + .mockResolvedValueOnce(commandState({ alwaysAllowExecute: false, alwaysDenyUnapprovedCommands: false })) + .mockResolvedValue(commandState({ alwaysDenyUnapprovedCommands: true })), + } + // The task folder (A) allows; the command runs in B, which denies. + const task = buildTask(provider, FOLDER_A) + await attachQueue(task) + + const asked = task.ask("command", "echo hi", false, undefined, false, { commandCwd: FOLDER_B }) + await vi.waitUntil(() => (task["addToClineMessages"] as ReturnType).mock.calls.length > 0) + task.messageQueueService.addMessage("run it") + + const result = await asked + + expect(result.response).toBe("noButtonClicked") + expect(result.autoDenyDetail?.kind).toBe("denylist") + }) +}) diff --git a/src/core/tools/ExecuteCommandTool.ts b/src/core/tools/ExecuteCommandTool.ts index 9855e6e417..9acb0c9e85 100644 --- a/src/core/tools/ExecuteCommandTool.ts +++ b/src/core/tools/ExecuteCommandTool.ts @@ -156,13 +156,17 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> { return } const provider = await task.providerRef.deref() + // One canonical working directory, resolved before any approval + // decision: the command-list policy, the DCG run, and the terminal + // spawn must all see the same directory, so a custom `cwd` can never + // be approved against one folder and executed in another. + const workingDirectory = customCwd + ? path.isAbsolute(customCwd) + ? customCwd + : path.resolve(task.cwd, customCwd) + : task.cwd let dcgDecision: DcgDecision | undefined if (provider?.contextProxy.getValue("destructiveCommandGuardEnabled") === true) { - const workingDirectory = customCwd - ? path.isAbsolute(customCwd) - ? customCwd - : path.resolve(task.cwd, customCwd) - : task.cwd const workingDirectoryError = await commandWorkingDirectoryError(workingDirectory) if (workingDirectoryError) { task.didToolFailInCurrentTurn = true @@ -214,13 +218,23 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> { // choose whether to execute it. let didApprove: boolean if (dcgDecision === undefined) { - didApprove = await askApproval("command", canonicalCommand) + didApprove = await askApproval("command", canonicalCommand, undefined, false, { + commandCwd: workingDirectory, + }) } else if (dcgDecision.decision === "allow") { - didApprove = await askApproval("command", canonicalCommand, undefined, false, { dcgDecision }) + didApprove = await askApproval("command", canonicalCommand, undefined, false, { + dcgDecision, + commandCwd: workingDirectory, + }) } else if (blanketAutoDeny) { - didApprove = await askApproval("command", canonicalCommand, undefined, false, { dcgDecision }) + didApprove = await askApproval("command", canonicalCommand, undefined, false, { + dcgDecision, + commandCwd: workingDirectory, + }) } else { - didApprove = await askApproval("command", canonicalCommand, undefined, isProtectedAsk) + didApprove = await askApproval("command", canonicalCommand, undefined, isProtectedAsk, { + commandCwd: workingDirectory, + }) } if (!didApprove) { @@ -257,7 +271,7 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> { // whose own approval was legal, inverting approval semantics. const recheck = await checkAutoApproval({ state: freshState, - cwd: task.cwd, + cwd: workingDirectory, ask: "command", text: canonicalCommand, isProtected: false, @@ -330,6 +344,7 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> { executionId, command: canonicalCommand, customCwd, + workingDirectory, terminalShellIntegrationDisabled, commandExecutionTimeout, agentTimeout, @@ -394,6 +409,14 @@ export type ExecuteCommandOptions = { executionId: string command: string customCwd?: string + /** + * The directory the approval was judged against, resolved once by the + * tool. When present the command spawns there directly, so the executed + * directory cannot drift from the one the command policy approved; + * callers that build options without it fall back to resolving + * `customCwd` against the task's own `cwd` here. + */ + workingDirectory?: string terminalShellIntegrationDisabled?: boolean commandExecutionTimeout?: number agentTimeout?: number @@ -406,6 +429,7 @@ export async function executeCommandInTerminal( executionId, command, customCwd, + workingDirectory, terminalShellIntegrationDisabled = true, commandExecutionTimeout = 0, agentTimeout = 0, @@ -415,7 +439,9 @@ export async function executeCommandInTerminal( // Convert milliseconds back to seconds for display purposes. const commandExecutionTimeoutSeconds = commandExecutionTimeout / 1000 let workingDir: string - if (!customCwd) { + if (workingDirectory !== undefined) { + workingDir = workingDirectory + } else if (!customCwd) { workingDir = task.cwd } else if (path.isAbsolute(customCwd)) { workingDir = customCwd diff --git a/src/core/tools/__tests__/executeCommandTool.spec.ts b/src/core/tools/__tests__/executeCommandTool.spec.ts index c580b55102..1700d676bb 100644 --- a/src/core/tools/__tests__/executeCommandTool.spec.ts +++ b/src/core/tools/__tests__/executeCommandTool.spec.ts @@ -3,6 +3,7 @@ import type { ToolUsage } from "@roo-code/types" import fs from "fs/promises" import { constants as fsConstants, type Stats } from "fs" +import * as path from "path" import * as vscode from "vscode" import { Task } from "../../task/Task" @@ -206,7 +207,9 @@ describe("executeCommandTool", () => { }) // Verify - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test") + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { + commandCwd: "/test/workspace", + }) expect(mockPushToolResult).toHaveBeenCalled() // The exact message depends on the terminal mock's behavior const result = mockPushToolResult.mock.calls[0][0] @@ -228,12 +231,43 @@ describe("executeCommandTool", () => { }) // Verify - command approved, result pushed, and custom cwd passed to terminal - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test") + // The approval context carries the same directory the terminal will + // spawn in, so the folder-scoped command policy judges that folder. + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { + commandCwd: "/custom/path", + }) expect(mockPushToolResult).toHaveBeenCalled() const { TerminalRegistry } = await import("../../../integrations/terminal/TerminalRegistry") const firstArg = (TerminalRegistry.getOrCreateTerminal as ReturnType).mock.calls[0][0] expect(firstArg).toBe("/custom/path") }) + + it("reports a relative custom cwd resolved against the task's workspace", async () => { + // A relative custom cwd runs the command in a subdirectory of the task + // folder, so the approval must name the resolved absolute path: the + // policy lookup resolves against workspace folders, which a relative + // path never names. + mockToolUse.params.command = "echo test" + mockToolUse.params.cwd = "sub/dir" + mockToolUse.nativeArgs = { command: "echo test", cwd: "sub/dir" } + + await executeCommandTool.handle(mockCline as Task, mockToolUse, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockAskApproval).toHaveBeenCalledWith( + "command", + "echo test", + undefined, + false, + expect.objectContaining({ + commandCwd: path.resolve("/test/workspace", "sub/dir"), + }), + ) + }) }) describe("Error handling", () => { @@ -342,7 +376,9 @@ describe("executeCommandTool", () => { "error", "executeCommand.destructiveCommandGuard.blockedWithReasonAndRule", ) - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true) + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true, { + commandCwd: "/test/workspace", + }) }) it("requests normal approval when DCG allows the command", async () => { @@ -366,6 +402,7 @@ describe("executeCommandTool", () => { // the verdict itself rather than inferring it from settings alone. expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { dcgDecision: { decision: "allow" }, + commandCwd: "/test/workspace", }) expect(mockPushToolResult).toHaveBeenCalled() }) @@ -395,6 +432,7 @@ describe("executeCommandTool", () => { // an automatic denial carrying the DCG reason instead of prompting. expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { dcgDecision: { decision: "deny", reason: "matches a destructive pattern" }, + commandCwd: "/test/workspace", }) }) @@ -419,7 +457,9 @@ describe("executeCommandTool", () => { toolCallId: "test-tool-call-id", }) - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true) + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true, { + commandCwd: "/test/workspace", + }) }) it("keeps the protected prompt when blanket auto-deny is on but command auto-approval is off", async () => { @@ -443,7 +483,9 @@ describe("executeCommandTool", () => { toolCallId: "test-tool-call-id", }) - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true) + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true, { + commandCwd: "/test/workspace", + }) }) it("keeps the protected prompt when blanket auto-deny is on but execute auto-approval is off", async () => { @@ -471,7 +513,9 @@ describe("executeCommandTool", () => { toolCallId: "test-tool-call-id", }) - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true) + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true, { + commandCwd: "/test/workspace", + }) }) it("denies an approved command at execute time when blanket deny engages during the approval dwell", async () => { @@ -621,7 +665,9 @@ describe("executeCommandTool", () => { // The prompt shown was the protected one — the blanket setting was off // when the ask was built. - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true) + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true, { + commandCwd: "/test/workspace", + }) // The blanket denial wins over the affirmative approval: the command // never reaches the terminal. The provider-level assertion is the @@ -661,6 +707,53 @@ describe("executeCommandTool", () => { expect(TerminalRegistry.getOrCreateTerminal).not.toHaveBeenCalled() }) + it("re-checks the command policy against the custom working directory", async () => { + // The folder-scoped command policy must judge the directory the command + // actually runs in. Forwarding `task.cwd` here would let folder A's + // allow entry approve a command executing in folder B, so the same + // resolved directory the terminal will spawn in rides the re-check. + await setupProtectedDwellFlip() + mockToolUse.params.cwd = "/custom/path" + mockToolUse.nativeArgs = { command: "echo test", cwd: "/custom/path" } + // Delegates to the import-time real check: re-reading the module + // property here would capture this file's own leaked spy and recurse. + const recheckSpy = vitest + .spyOn(autoApprovalModule, "checkAutoApproval") + .mockImplementation((args) => realCheckAutoApproval(args)) + + await executeCommandTool.handle(mockCline, mockToolUse, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + expect(recheckSpy).toHaveBeenCalledTimes(1) + expect(recheckSpy).toHaveBeenCalledWith(expect.objectContaining({ cwd: "/custom/path" })) + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, true, { + commandCwd: "/custom/path", + }) + }) + + it("spawns in the approval's working directory rather than re-deriving from the raw custom cwd", async () => { + // The executor must honor the directory the tool resolved for + // approval verbatim, even though a different raw `customCwd` rides + // the options. Re-deriving from `customCwd` would spawn the command + // somewhere other than the directory the command policy approved. + vitest.spyOn(executeCommandModule, "executeCommandInTerminal").mockRestore() + + const [rejected] = await executeCommandModule.executeCommandInTerminal(mockCline, { + executionId: "test-exec", + command: "echo test", + customCwd: "sub/dir", + workingDirectory: "/approved/folder", + toolCallId: "test-tool-call-id", + }) + + expect(rejected).toBe(false) + const firstArg = (TerminalRegistry.getOrCreateTerminal as ReturnType).mock.calls[0][0] + expect(firstArg).toBe("/approved/folder") + }) + it("fails closed when the execute-time recheck returns a non-approval other than deny", async () => { await setupProtectedDwellFlip() // The blanket-engaged command policy never answers `ask` today; force a @@ -961,7 +1054,9 @@ describe("executeCommandTool", () => { }) // Verify - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test") + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { + commandCwd: "/test/workspace", + }) // executeCommandInTerminal should not be called since approval was denied expect(mockPushToolResult).not.toHaveBeenCalled() }) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 0d2af06c82..cc45f4d370 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -30,7 +30,7 @@ import { TelemetryService } from "@roo-code/telemetry" import { defaultModeSlug } from "../../../shared/modes" import { experimentDefault } from "../../../shared/experiments" import { setTtsEnabled } from "../../../utils/tts" -import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" +import { makeUri, makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { ContextProxy } from "../../config/ContextProxy" import { WorkspaceIndexingEnablementManager } from "../../../services/code-index/workspace-indexing-enablement-manager" import { Task, TaskOptions } from "../../task/Task" @@ -4105,6 +4105,7 @@ describe("ClineProvider", () => { get: vi.fn().mockReturnValue([]), update: vi.fn(), } as unknown as vscode.WorkspaceConfiguration) + Reflect.deleteProperty(vscode.workspace, "workspaceFolders") }) // The gate is a synchronous configuration read, so the doubles make the @@ -4193,6 +4194,45 @@ describe("ClineProvider", () => { expect(state.deniedCommands).toEqual(["pnpm docker"]) }) + test("getState scopes its command-list lookups to the first workspace folder", async () => { + // Each folder carries its own distinct configuration, keyed by the + // resource the lookup was scoped with: any lookup that resolves to + // the second folder — or to no resource at all — reads the second + // folder's values, so the first folder's list can only come from a + // configuration scoped to the first folder's uri. + const firstFolder = { uri: makeUri("/root/one"), name: "first", index: 0 } + const secondFolder = { uri: makeUri("/root/two"), name: "second", index: 1 } + // The mocked module's workspaceFolders is readonly-typed, so the test + // installs it through defineProperty; the afterEach removes it again. + Reflect.defineProperty(vscode.workspace, "workspaceFolders", { + configurable: true, + value: [firstFolder, secondFolder], + }) + + const firstFolderConfig = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) + firstFolderConfig.inspect = vi + .fn() + .mockImplementation((key: string) => + key === "deniedCommands" + ? { key, workspaceValue: ["workspace docker"], workspaceFolderValue: ["pnpm docker"] } + : undefined, + ) + const secondFolderConfig = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: false }) + secondFolderConfig.inspect = vi + .fn() + .mockImplementation((key: string) => + key === "deniedCommands" ? { key, workspaceFolderValue: ["curl"] } : undefined, + ) + vi.mocked(vscode.workspace.getConfiguration).mockImplementation((_section?: string, scope?: unknown) => + scope === firstFolder.uri ? firstFolderConfig : secondFolderConfig, + ) + + const state = await provider.getState() + + expect(state.deniedCommands).toEqual(["pnpm docker"]) + expect(state.workspaceCommandListsEnabled).toBe(true) + }) + // A workspace-only allow entry is exactly what the gate decides: enabled // it joins the effective lists enforcement uses; disabled enforcement ignores it. function mockGateConfiguration(enabled: boolean) { @@ -4208,6 +4248,21 @@ describe("ClineProvider", () => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) } + // Counterpart for a profile that never set the gate: the configuration + // reports nothing for the gate key, so the provider paths must apply the + // shared default themselves. The allow-side workspace layer is present so + // the asserted default direction (workspace entries stay inert) is + // observable, not just the boolean. + function mockUnsetGateConfiguration() { + const config = makeWorkspaceConfiguration() + const inspect = vi.fn() + inspect.mockImplementation((key: string) => + key === "allowedCommands" ? { key, workspaceValue: ["docker"] } : undefined, + ) + config.inspect = inspect + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + } + test("a workspace-only allow entry surfaces through getState and getStateToPostToWebview when the gate is on", async () => { await provider.resolveWebviewView(mockWebviewView) mockGateConfiguration(true) @@ -4263,6 +4318,27 @@ describe("ClineProvider", () => { expect(state.workspaceCommandListsEnabled).toBe(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED) }) + + test("getState defaults the workspace command-list gate when the configuration is unset", async () => { + mockUnsetGateConfiguration() + + const state = await provider.getState() + + expect(state.workspaceCommandListsEnabled).toBe(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED) + // The default's direction, not just its value: an unset gate keeps the + // workspace entry out of the effective list. + expect(state.allowedCommands).toEqual([]) + }) + + test("getStateToPostToWebview defaults the workspace command-list gate when the configuration is unset", async () => { + await provider.resolveWebviewView(mockWebviewView) + mockUnsetGateConfiguration() + + const state = await provider.getStateToPostToWebview() + + expect(state.workspaceCommandListsEnabled).toBe(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED) + expect(state.allowedCommands).toEqual([]) + }) }) test("getState returns the saved allowed read files", async () => { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 1fbc13e2dd..2a34c42dfc 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2260,20 +2260,28 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { it("restores the raw workspace value when a workspace-target global write fails", async () => { // With no folder layer the rewind must read the workspace value, not - // the absent folder value. The raw value holds the entry this save - // dropped, so the restore call is distinguishable from the workspace - // write itself and provably uses the raw inspected value. - const { update } = mockCommandConfiguration({ workspaceValue: ["npm docker", "docker"] }, [ + // the absent folder value. The gate is on so the kept workspace entry is + // visible and the workspace write (`["docker"]`) differs from the raw + // rollback value (which still holds the entry this save dropped); the + // gate-off alternative would make the first write re-add the hidden + // entries and duplicate the rollback value, letting a call-agnostic + // assertion match a write that is not the rewind. + const { update } = mockCommandConfiguration( + { workspaceValue: ["npm docker", "docker"] }, + [undefined, Promise.reject(new Error("disk on fire"))], undefined, - Promise.reject(new Error("disk on fire")), - ]) + true, + ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - expect(update).toHaveBeenCalledWith( + // Call order: workspace write, failed global write, rewind — so the + // rewind is pinned by position, not just by matching some call. + expect(update).toHaveBeenNthCalledWith( + 3, "deniedCommands", ["npm docker", "docker"], vscode.ConfigurationTarget.Workspace, @@ -2287,9 +2295,14 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The raw folder-layer value differs from the sanitized post-split layer // (and from the workspace-layer value), so the restore call is uniquely // identifiable and provably reads the folder value for a folder target. + // The gate is on so the workspace write keeps only the visible entry and + // cannot match the raw rollback value; the rewind is asserted by call + // position. const { update } = mockCommandConfiguration( { workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, [undefined, Promise.reject(new Error("disk on fire"))], + undefined, + true, ) await webviewMessageHandler(mockClineProvider, { @@ -2302,8 +2315,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // configuration scoped to the first workspace folder. expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, mockWorkspaceFolderUri) // The raw previous folder value (entries this save dropped included) is - // written back at the target the failed save chose. - expect(update).toHaveBeenCalledWith( + // written back at the target the failed save chose, as the third write. + expect(update).toHaveBeenNthCalledWith( + 3, "deniedCommands", ["pnpm docker", "docker"], vscode.ConfigurationTarget.WorkspaceFolder, @@ -2413,12 +2427,15 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { it("reports partial failure when the compensating restore also fails", async () => { // update() call order: workspace write succeeds, global write rejects, // restore write rejects too. The raw workspace value differs from the - // post-split layer so the restore call is uniquely identifiable. - const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "old"] }, [ + // post-split layer so the restore call is uniquely identifiable. The + // gate is on so the workspace write (`["docker"]`) stays distinct from + // the raw rollback value, and the rewind is pinned by call position. + const { update } = mockCommandConfiguration( + { workspaceValue: ["docker", "old"] }, + [undefined, Promise.reject(new Error("disk on fire")), Promise.reject(new Error("restore also failed"))], undefined, - Promise.reject(new Error("disk on fire")), - Promise.reject(new Error("restore also failed")), - ]) + true, + ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -2426,7 +2443,12 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) // The restore was attempted at the owning target even though it failed. - expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "old"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenNthCalledWith( + 3, + "deniedCommands", + ["docker", "old"], + vscode.ConfigurationTarget.Workspace, + ) expect(update).toHaveBeenCalledTimes(3) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( diff --git a/src/extension.ts b/src/extension.ts index dbf38832ce..5e496dac48 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -42,7 +42,7 @@ import { CodeIndexManagerRegistry } from "./services/code-index/code-index-manag import { CodeIndexScope } from "./services/code-index/code-index-scope" import { MdmService } from "./services/mdm/MdmService" import { migrateSettings } from "./utils/migrateSettings" -import { seedAllowedCommands } from "./utils/seedAllowedCommands" +import { seedCommandList } from "./utils/seedAllowedCommands" import { autoImportSettings } from "./utils/autoImportSettings" import { API } from "./extension/api" @@ -173,7 +173,11 @@ export async function activate(context: vscode.ExtensionContext) { // Initialize Zoo Code auth service for extension session token management. await initZooCodeAuth(context) - await seedAllowedCommands(context.globalState) + // Each list key carries its own first-run guard, so a profile whose + // allowlist was seeded by an earlier version still gets the deny-list + // migration on the next activation. + await seedCommandList(context.globalState, "allowedCommands") + await seedCommandList(context.globalState, "deniedCommands") const contextProxy = await ContextProxy.getInstance(context) const updateTelemetryState = () => { diff --git a/src/shared/tools.ts b/src/shared/tools.ts index 6d2e9422ee..e10f24c97c 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -19,6 +19,15 @@ export type AutoApprovalContext = { * produce a verdict — they surface as a retryable tool error beforehand. */ dcgDecision?: DcgDecision + /** + * Directory the command will actually run in (`execute_command` only): + * the tool's resolved working directory, which differs from the task's + * own `cwd` whenever the call carries a custom `cwd`. Command-list + * enforcement judges this directory so a command executing in another + * workspace folder is judged by that folder's policy, never the task + * folder's. + */ + commandCwd?: string } export type AskApproval = ( diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts index c5ddd11767..9a60682952 100644 --- a/src/utils/__tests__/seedAllowedCommands.spec.ts +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -5,7 +5,7 @@ import * as vscode from "vscode" import { readCommandListScopes } from "../../core/auto-approval/commandScope" import { Package } from "../../shared/package" import { makeUri, makeWorkspaceConfiguration } from "../../test-utils/vscode" -import { seedAllowedCommands } from "../seedAllowedCommands" +import { seedCommandList } from "../seedAllowedCommands" // Scriptable stand-in for `vscode.workspace.workspaceFolders`: the module // mock's getter reads through this object, so a test can change the open @@ -33,9 +33,10 @@ interface ConfigDouble { } effective?: string[] inspectThrows?: boolean + gate?: boolean } -function mockConfiguration({ inspect, effective = [], inspectThrows = false }: ConfigDouble = {}) { +function mockConfiguration({ inspect, effective = [], inspectThrows = false, gate = false }: ConfigDouble = {}) { // Real VS Code reports `workspaceFolderValue` only for a configuration // looked up against a resource; an unscoped lookup reports no folder // layer no matter what any folder's settings contain. Scripting that @@ -45,8 +46,13 @@ function mockConfiguration({ inspect, effective = [], inspectThrows = false }: C (_section?: string, scope?: vscode.ConfigurationScope | null) => { const config = makeWorkspaceConfiguration() // The shared double is scripted per call so the per-test fixture - // values need no type assertion at the construction site. - vi.mocked(config.get).mockReturnValue(effective) + // values need no type assertion at the construction site. The gate + // section reads independently of the list values: its shipped + // default is off, so a test only gets an enforced workspace layer + // by asking for one. + vi.mocked(config.get).mockImplementation((section: string) => + section === "workspaceCommandListsEnabled" ? gate : effective, + ) vi.mocked(config.inspect).mockImplementation(() => { if (inspectThrows) { throw new Error("configuration access failed") @@ -63,11 +69,14 @@ function mockConfiguration({ inspect, effective = [], inspectThrows = false }: C ) } -function mockMemento(existing: unknown = undefined) { +function mockMemento(existing: unknown = undefined, deniedExisting: unknown = undefined) { const store = new Map() if (existing !== undefined) { store.set("allowedCommands", existing) } + if (deniedExisting !== undefined) { + store.set("deniedCommands", deniedExisting) + } // Structurally complete Memento double (keys/get/update), so the call // sites need no type assertion. @@ -80,7 +89,7 @@ function mockMemento(existing: unknown = undefined) { } } -describe("seedAllowedCommands", () => { +describe("seedCommandList", () => { beforeEach(() => { vi.clearAllMocks() workspaceState.workspaceFolders = undefined @@ -101,10 +110,13 @@ describe("seedAllowedCommands", () => { workspaceValue: ["docker"], }, effective: ["docker"], + // Suppression only applies while the gate lets the workspace layer + // take effect in enforcement. + gate: true, }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toBeUndefined() @@ -126,10 +138,11 @@ describe("seedAllowedCommands", () => { globalValue: undefined, workspaceFolderValue: ["docker"], }, + gate: true, }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") // The folder layer only reaches the seed through a resource-scoped // lookup, so the seed must request one (same pin as the save path). @@ -150,10 +163,11 @@ describe("seedAllowedCommands", () => { defaultValue: ["git log", "git diff", "git show"], workspaceFolderValue: ["docker"], }, + gate: true, }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) expect(vscode.workspace.getConfiguration).not.toHaveBeenCalledWith(Package.name, folderB) @@ -171,10 +185,11 @@ describe("seedAllowedCommands", () => { globalValue: undefined, workspaceValue: [], }, + gate: true, }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toBeUndefined() @@ -188,19 +203,33 @@ describe("seedAllowedCommands", () => { }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) // Copy, like the global-value path: global state must not share a // reference with the configuration object. expect(globalState.update.mock.calls[0][1]).not.toBe(defaultValue) + + // A later activation with the gate on but still no workspace-scoped + // value: only an actual override suppresses the default, so the gate + // alone must not withhold it. + mockConfiguration({ + inspect: { key: "allowedCommands", defaultValue }, + effective: defaultValue, + gate: true, + }) + const secondGlobalState = mockMemento() + + await seedCommandList(secondGlobalState, "allowedCommands") + + expect(secondGlobalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) }) it("seeds from the global-scope value when global state is empty", async () => { mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] }, effective: ["git"] }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", ["git"]) expect(globalState.get("allowedCommands")).toEqual(["git"]) @@ -219,7 +248,7 @@ describe("seedAllowedCommands", () => { }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", []) expect(globalState.get("allowedCommands")).toEqual([]) @@ -229,7 +258,7 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] }, effective: ["git"] }) const globalState = mockMemento(["npm"]) - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toEqual(["npm"]) @@ -242,7 +271,7 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspect: { key: "allowedCommands", defaultValue: ["git log", "git diff", "git show"] } }) const globalState = mockMemento([]) - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toEqual([]) @@ -262,7 +291,7 @@ describe("seedAllowedCommands", () => { }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) // A later activation in a workspace whose settings file sets the list: @@ -272,7 +301,7 @@ describe("seedAllowedCommands", () => { effective: ["docker ps"], }) - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).toHaveBeenCalledTimes(1) expect(globalState.get("allowedCommands")).toEqual(defaultValue) @@ -299,7 +328,7 @@ describe("seedAllowedCommands", () => { update: vi.fn(), } - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, undefined) const config = vi.mocked(vscode.workspace.getConfiguration).mock.results[0].value @@ -311,7 +340,7 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspect: undefined, effective: ["git"] }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).not.toHaveBeenCalled() }) @@ -320,7 +349,7 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspectThrows: true }) const globalState = mockMemento() - await expect(seedAllowedCommands(globalState)).resolves.toBeUndefined() + await expect(seedCommandList(globalState, "allowedCommands")).resolves.toBeUndefined() expect(globalState.update).not.toHaveBeenCalled() }) @@ -330,9 +359,85 @@ describe("seedAllowedCommands", () => { mockConfiguration({ inspect: { key: "allowedCommands", globalValue } }) const globalState = mockMemento() - await seedAllowedCommands(globalState) + await seedCommandList(globalState, "allowedCommands") expect(globalState.update).toHaveBeenCalledWith("allowedCommands", expect.arrayContaining(["git"])) expect(globalState.update.mock.calls[0][1]).not.toBe(globalValue) }) + + it("seeds the deny list from its settings-file global value on a fresh profile", async () => { + // Symmetric with the allow side: a user-level `deniedCommands` edit in + // settings.json has a one-time migration role, and the enforcement + // global layer reads extension state only, so an unseeded deny list + // silently drops the user's denials. + mockConfiguration({ inspect: { key: "deniedCommands", globalValue: ["docker"] }, effective: ["docker"] }) + const globalState = mockMemento() + + await seedCommandList(globalState, "deniedCommands") + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("deniedCommands", ["docker"]) + expect(globalState.get("deniedCommands")).toEqual(["docker"]) + }) + + it("does not overwrite an existing deniedCommands global state", async () => { + mockConfiguration({ inspect: { key: "deniedCommands", globalValue: ["docker"] }, effective: ["docker"] }) + const globalState = mockMemento(undefined, ["rm"]) + + await seedCommandList(globalState, "deniedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("deniedCommands")).toEqual(["rm"]) + }) + + it("seeds the deny list when only the allow list was already seeded", async () => { + // Per-key guards: an install whose allowlist was seeded by an earlier + // version must still get the deny migration on the next activation. + mockConfiguration({ inspect: { key: "deniedCommands", globalValue: ["docker"] }, effective: ["docker"] }) + const globalState = mockMemento(["npm"]) + + await seedCommandList(globalState, "deniedCommands") + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("deniedCommands", ["docker"]) + expect(globalState.get("allowedCommands")).toEqual(["npm"]) + }) + + it("seeds the declared default when a workspace value exists but the gate is off", async () => { + // With the gate off the workspace layer contributes nothing to + // enforcement, so withholding the default would leave commands + // unapproved that the override never actually governed. + const defaultValue = ["git log", "git diff", "git show"] + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue, + workspaceValue: ["docker"], + }, + effective: ["docker"], + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) + }) + + it("suppresses the declared default for a workspace value while the gate is on", async () => { + // Pins the explicit-override semantics: an enforced workspace list + // replaces the default across scopes, so the seed must not re-grant + // the approvals the override removed. + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + workspaceValue: ["docker"], + }, + effective: ["docker"], + gate: true, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + }) }) diff --git a/src/utils/seedAllowedCommands.ts b/src/utils/seedAllowedCommands.ts index 1afa0bbfcb..be4b930ada 100644 --- a/src/utils/seedAllowedCommands.ts +++ b/src/utils/seedAllowedCommands.ts @@ -1,10 +1,15 @@ import * as vscode from "vscode" -import { commandListConfiguration } from "../core/auto-approval/commandScope" +import { commandListConfiguration, workspaceCommandListsEnabled } from "../core/auto-approval/commandScope" +import type { CommandListConfigKey } from "../core/auto-approval/commandScope" /** - * Seeds the extension's global-state allowlist from the `allowedCommands` - * setting, but only when global state holds no list yet (first run). + * Seeds one auto-approval command-list key (`allowedCommands` or + * `deniedCommands`) from its settings-file value into the extension's + * global state, but only when global state holds no list for that key yet + * (first run). Each key carries its own guard, so a profile whose allowlist + * was already seeded still gets an unseeded deny list migrated on the next + * activation. * * The seed reads scoped values via `inspect()` rather than the effective * `get()` on purpose: `get()` folds in workspace-scoped overrides, so a @@ -22,14 +27,18 @@ import { commandListConfiguration } from "../core/auto-approval/commandScope" * fresh install) the declared package default is seeded, because the * enforcement path reads only global state plus workspace scopes and never * falls back to that default on its own. A workspace-scoped value is an - * explicit choice and suppresses the default: array settings replace across - * scopes, so seeding it would re-grant the auto-approvals the override - * removed. + * explicit choice and suppresses the default — but only while the + * `workspaceCommandListsEnabled` gate lets that value take effect: with the + * gate off the workspace layer contributes nothing to enforcement, so + * withholding the default would leave commands unapproved that the override + * never actually governed. Array settings replace across scopes, so seeding + * past an enforced override would re-grant the approvals it removed. * * @param globalState - The extension global-state memento to seed. + * @param configKey - The command-list configuration key to seed. */ -export async function seedAllowedCommands(globalState: vscode.Memento): Promise { - if (globalState.get("allowedCommands")) { +export async function seedCommandList(globalState: vscode.Memento, configKey: CommandListConfigKey): Promise { + if (globalState.get(configKey)) { return } @@ -47,23 +56,23 @@ export async function seedAllowedCommands(globalState: vscode.Memento): Promise< } | undefined try { - inspected = commandListConfiguration().inspect("allowedCommands") + inspected = commandListConfiguration().inspect(configKey) } catch { return } // The `undefined` checks, not truthiness: an explicitly empty array still // counts as an override. + const workspaceOverride = inspected?.workspaceValue !== undefined || inspected?.workspaceFolderValue !== undefined + const seedValue = inspected?.globalValue ?? - (inspected?.workspaceValue === undefined && inspected?.workspaceFolderValue === undefined - ? inspected?.defaultValue - : undefined) + (workspaceOverride && workspaceCommandListsEnabled() ? undefined : inspected?.defaultValue) if (!Array.isArray(seedValue)) { return } // Copy so global state never shares a reference with the configuration object. - await globalState.update("allowedCommands", [...seedValue]) + await globalState.update(configKey, [...seedValue]) } From 5a43ade440f6e5124a91b31f5b8e5235811993f1 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 10 Nov 2026 07:34:23 +0100 Subject: [PATCH 11/52] fix: cwd resolution now physical: symlink-safe folder-scoped approval The execute tool judged folder command policy by the working directory as spelled, so a symlink could be approved under one folder's policy and run in another's. It now resolves that directory to its real filesystem path before the approval decision, fails the command when resolution is unavailable, and retries workspace-root matching against each root's real path so a folder opened through a symlink keeps its own command lists. Tests cover a symlinked working directory, a broken link, and a symlinked root. --- .../__tests__/commandScope.spec.ts | 222 ++++++++++++++++++ src/core/auto-approval/commandScope.ts | 57 ++++- src/core/tools/ExecuteCommandTool.ts | 30 ++- .../__tests__/executeCommandTool.spec.ts | 177 +++++++++++++- 4 files changed, 481 insertions(+), 5 deletions(-) diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 02d3eb8b37..bcead00215 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -1,4 +1,5 @@ import * as fs from "fs" +import * as os from "os" import * as path from "path" import { DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, globalSettingsSchema } from "@roo-code/types" @@ -7,6 +8,7 @@ import * as vscode from "vscode" import { Package } from "../../../shared/package" import { makeUri, makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { + commandListFolderForResource, readCommandListScopes, resolveEffectiveCommandLists, resolveWorkspaceWriteTarget, @@ -26,6 +28,42 @@ const workspaceState = vi.hoisted(() => ({ foldersByPath: new Map(), })) +// Scriptable stand-in for `fs.realpathSync`, which the root-side containment +// fallback consults. Every other fs binding stays real — the manifest reads +// and the real-filesystem tests run through `importOriginal` — and the double +// resolves paths to themselves by default: the mock roots are fake paths that +// exist on no filesystem, and an unresolvable root is compared by its +// registered path, so identity reproduces exactly what the real call does to +// them. Tests that need other behavior script it explicitly. +const fsState = vi.hoisted(() => ({ + // The unmocked implementation, captured by the module mock so a test can + // delegate through the double to real filesystem behavior. + realRealpathSync: null as null | ((target: string) => string), +})) + +vi.mock("fs", async (importOriginal) => { + const actual = await importOriginal() + fsState.realRealpathSync = (target: string) => String(actual.realpathSync(target)) + const realpathSync = vi.fn((target: string): string => String(target)) + // Interop shape: production code reaches `realpathSync` through the + // default export and this spec through the named one; both must see the + // same double. + const actualDefault = (actual as { default?: typeof import("fs") }).default ?? actual + return { + ...actual, + default: { ...actualDefault, realpathSync }, + realpathSync, + } +}) + +/** The unmocked `fs.realpathSync`, for tests that pin real-filesystem behavior. */ +function realPath(target: string): string { + if (!fsState.realRealpathSync) { + throw new Error("the fs module mock did not capture the unmocked realpathSync") + } + return fsState.realRealpathSync(target) +} + vi.mock("vscode", () => ({ ConfigurationTarget: { Global: 1, @@ -586,6 +624,28 @@ it("checkAutoApproval command: does not apply the first folder's allow list to a expect(result).toEqual({ decision: "ask" }) }) +it("checkAutoApproval command: composes a command without a cwd from the global layers when both raw layers are present", async () => { + vi.clearAllMocks() + // With both raw layers set, the command branch re-composes instead of + // consuming the baked pair; an absent cwd keeps the first-folder + // configuration, which here contributes nothing, so only the raw global + // allow entry can decide. A check that consumed the baked pair instead + // would find no match and fall to the plain prompt. + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + const result = await checkAutoApproval({ + state: { ...taskFolderState(["baked"]), globalAllowedCommands: ["echo"], globalDeniedCommands: ["rm"] }, + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "approve" }) +}) + it("checkAutoApproval command: still lets a global deny entry veto a command whose cwd names no workspace root", async () => { vi.clearAllMocks() const { folderA, folderB } = openMultiRootWindow() @@ -671,3 +731,165 @@ it("checkAutoApproval command: in a single-folder window reads exactly the same expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) }) + +// Creating a directory symlink on Windows needs developer mode or elevation; a +// junction needs neither and is resolved by realpath like a POSIX link, so the +// fixture tries a symlink first and falls back to a junction. Where neither can +// be created the real-filesystem test is skipped; the scripted tests below pin +// the same resolution logic on every platform. +function createDirectoryLink(target: string, linkPath: string): void { + try { + fs.symlinkSync(target, linkPath, "dir") + } catch { + fs.symlinkSync(target, linkPath, "junction") + } +} + +function canCreateDirectoryLink(): boolean { + const probeDir = fs.mkdtempSync(path.join(os.tmpdir(), "command-scope-link-probe-")) + try { + const target = path.join(probeDir, "target") + fs.mkdirSync(target) + createDirectoryLink(target, path.join(probeDir, "link")) + return true + } catch { + return false + } finally { + fs.rmSync(probeDir, { recursive: true, force: true }) + } +} +const directoryLinksAvailable = canCreateDirectoryLink() + +// The root-side fallback runs after the registered paths matched nothing, so +// these tests control resolution through the double (the mock header explains +// the identity default) and keep the registry lists they expect to be read +// independent of resolution. Resetting here also keeps the double's scripted +// behavior from leaking into the manifest reads above and the file's other +// lookup tests. +afterEach(() => { + workspaceState.workspaceFolders = undefined + workspaceState.foldersByPath.clear() + vi.mocked(fs.realpathSync).mockImplementation((target) => String(target)) +}) + +it.skipIf(!directoryLinksAvailable)( + "checkAutoApproval command: applies a symlinked workspace root's folder layer to a cwd in the root's real path", + async () => { + vi.clearAllMocks() + const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "command-scope-link-root-")) + try { + const realRoot = path.join(baseDir, "real-root") + const taskDir = path.join(realRoot, "sub") + fs.mkdirSync(realRoot) + fs.mkdirSync(taskDir) + const link = path.join(baseDir, "link-to-root") + createDirectoryLink(realRoot, link) + const linkUri = makeUri(link) + // The registry holds the link: the folder was opened through it, so + // the registered paths match nothing for a cwd the filesystem has + // already resolved, and only the root's real path connects the two. + workspaceState.workspaceFolders = [{ uri: linkUri }] + workspaceState.foldersByPath.set(link, linkUri) + // One delegate covers every call the lookup makes against this link. + vi.mocked(fs.realpathSync).mockImplementation((target) => realPath(String(target))) + // The configuration is scripted for the registry entry, not the + // real path: folder-scoped settings resolve against what VS Code + // opened. + mockFolderConfigurations({ [link]: { gate: true, allow: ["echo"] } }) + + const result = await checkAutoApproval({ + // Empty raw global layers: only the link folder's layer can + // decide. + state: taskFolderState([]), + cwd: realPath(taskDir), + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "approve" }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, linkUri) + } finally { + fs.rmSync(baseDir, { recursive: true, force: true }) + } + }, +) + +it("commandListFolderForResource: falls back to the registered path for a root whose real path cannot be resolved", () => { + vi.clearAllMocks() + const rootPath = path.join(path.sep + "mock", "broken-root") + const rootUri = makeUri(rootPath) + // A relocated or deleted root has no real path; comparing it by the path the + // registry holds keeps that folder's layer applied instead of silently + // dropping it. + workspaceState.workspaceFolders = [{ uri: rootUri }] + vi.mocked(fs.realpathSync).mockImplementation((target) => { + if (String(target) === rootPath) { + throw new Error("ENOENT: no such file or directory") + } + return String(target) + }) + + expect(commandListFolderForResource(path.join(rootPath, "sub"))).toBe(rootUri) +}) + +it("commandListFolderForResource: a path inside no root stays unmatched after the real-path retry", () => { + vi.clearAllMocks() + const rootPath = path.join(path.sep + "mock", "root") + workspaceState.workspaceFolders = [{ uri: makeUri(rootPath) }] + + // The sibling "root-two" shares "root" as a string prefix; only the + // separator guard between root and remainder keeps it outside the root. + expect(commandListFolderForResource(path.join(path.sep + "mock", "root-two", "x"))).toBeUndefined() + expect(commandListFolderForResource(path.join(path.sep + "mock", "elsewhere"))).toBeUndefined() +}) + +it("commandListFolderForResource: compares the cwd to the root's real path case-sensitively", () => { + vi.clearAllMocks() + workspaceState.workspaceFolders = [{ uri: makeUri(path.join(path.sep + "mock", "Root")) }] + // Both sides arrive canonical, so their case agrees wherever the + // comparison applies; folding case here could match a root the filesystem + // treats as distinct. + expect(commandListFolderForResource(path.join(path.sep + "mock", "root", "sub"))).toBeUndefined() +}) + +it("commandListFolderForResource: returns the registry Uri of the deepest matching root", () => { + vi.clearAllMocks() + const outerRoot = path.sep + "mock" + const innerRegistered = path.join(outerRoot, "inner-real") + const innerReal = path.join(outerRoot, "inner") + const outerUri = makeUri(outerRoot) + const innerUri = makeUri(innerRegistered) + // Order matters: the outer root is seen first, so a lookup that returned + // the first match instead of the deepest one decides differently here. + workspaceState.workspaceFolders = [{ uri: outerUri }, { uri: innerUri }] + vi.mocked(fs.realpathSync).mockImplementation((target) => + String(target) === innerRegistered ? innerReal : String(target), + ) + + const result = commandListFolderForResource(path.join(innerReal, "sub")) + + // Object identity against the registry entry pins both halves: the deepest + // root won, and the value returned is the registered Uri (folder-scoped + // configuration resolves against the registry, not the real path). + expect(result).toBe(innerUri) + expect(result?.fsPath).toBe(innerRegistered) +}) + +it("realpathSync preserves the on-disk case of an existing directory", () => { + vi.clearAllMocks() + const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "command-scope-case-")) + try { + const dirName = "MixedCase-Dir" + const dir = path.join(baseDir, dirName) + fs.mkdirSync(dir) + // The comparison trusts realpath output case, so it is pinned against + // the real filesystem rather than assumed: the final component keeps + // the case it was created with, and a differently-cased spelling of the + // same directory does not sit inside it. + const realBase = realPath(baseDir) + expect(realPath(dir)).toBe(path.join(realBase, dirName)) + expect(path.join(realBase, dirName.toLowerCase()).startsWith(`${realPath(dir)}${path.sep}`)).toBe(false) + } finally { + fs.rmSync(baseDir, { recursive: true, force: true }) + } +}) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 3ceed09a9f..8324f5bfae 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -1,3 +1,6 @@ +import fs from "fs" +import path from "path" + import { DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED } from "@roo-code/types" import * as vscode from "vscode" @@ -50,12 +53,26 @@ export function commandListConfiguration(folderResource?: vscode.Uri): vscode.Wo * directory of the task it came from, so it resolves to the same folder * without separate plumbing. * + * The command path hands this lookup a cwd the filesystem has already + * resolved to its real path, while the workspace registry holds each root as + * it was opened. Containment against the registered paths is tried first; + * when it matches no root, the search is retried against each root's real + * path so a root that is itself a symlink (or a Windows junction) keeps + * matching its own real directory. Among several matches the deepest root + * wins, mirroring how VS Code's own containment picks the innermost folder. + * A root whose real path cannot be resolved is compared by its registered + * path: the cwd is already canonical, so an unresolvable root can only + * narrow which folder layer applies, never widen what a folder's allow list + * may approve — and dropping the layer outright would silently change + * enforcement for a folder the user has open. + * * @param cwd - The task's working directory. A blank cwd, or one that names * no workspace root (a removed or relocated folder), yields `undefined`, * which leaves every read on its first-folder default — the behavior such a * cwd had before per-task scoping existed, never a guess at a different one. - * @returns The containing folder's URI, or `undefined` when cwd resolves to - * no root. + * @returns The containing folder's registry URI — never a canonicalized one, + * because folder-scoped configuration resolves against the registry — or + * `undefined` when cwd resolves to no root. */ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefined { if (!cwd) { @@ -66,12 +83,46 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin // run stands in for a cwd naming no root, so enforcement degrades to the // first-folder default instead of failing the approval decision. try { - return vscode.workspace.getWorkspaceFolder(vscode.Uri.file(cwd))?.uri + const folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(cwd)) + if (folder) { + return folder.uri + } + + // A miss above is expected when a root is a link and the cwd names the + // link's target, so containment is retried root by root against the + // filesystem's real paths. The separator guard keeps a sibling like + // `/root/other` from matching a root `/root`. + let match: vscode.Uri | undefined + let matchedLength = 0 + for (const candidate of vscode.workspace.workspaceFolders ?? []) { + const rootPath = realPathOrRegistered(candidate.uri.fsPath) + if ((cwd === rootPath || cwd.startsWith(rootPath + path.sep)) && rootPath.length > matchedLength) { + match = candidate.uri + matchedLength = rootPath.length + } + } + return match } catch { return undefined } } +/** + * The path a workspace root is compared by: its real filesystem path, or — + * when that cannot be resolved (a relocated or deleted root) — the path the + * registry holds. Root-side lookups stay best-effort because the cwd being + * matched is already canonical; failing the comparison for one unresolvable + * root would drop that folder's command-list layer without widening any + * approval. + */ +function realPathOrRegistered(fsPath: string): string { + try { + return fs.realpathSync(fsPath) + } catch { + return fsPath + } +} + /** * Reads an auto-approval command list from both configuration layers and * composes the list that should be enforced and displayed. diff --git a/src/core/tools/ExecuteCommandTool.ts b/src/core/tools/ExecuteCommandTool.ts index 9acb0c9e85..98c6c0a128 100644 --- a/src/core/tools/ExecuteCommandTool.ts +++ b/src/core/tools/ExecuteCommandTool.ts @@ -160,11 +160,39 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> { // decision: the command-list policy, the DCG run, and the terminal // spawn must all see the same directory, so a custom `cwd` can never // be approved against one folder and executed in another. - const workingDirectory = customCwd + const lexicalWorkingDirectory = customCwd ? path.isAbsolute(customCwd) ? customCwd : path.resolve(task.cwd, customCwd) : task.cwd + // A folder's command lists apply to a command by containment: the + // working directory is matched against the open roots, and against + // each root's real path when the registered paths match nothing, so + // a root that is itself a link still claims its own directory. + // Canonicalizing here keeps both sides of that match physical, so + // the judged folder is the one containing the directory the process + // actually starts in — a symlinked directory would otherwise be + // judged by the folder its path sits in while the process starts in + // the link's target, the same drift in filesystem form (precedent: + // `RooIgnoreController.validateAccess` also resolves symlinks with + // realpath before a policy check). Unlike that file-access posture, + // an unresolvable link here names no directory any policy could + // judge, so the command fails closed through the working-directory + // error channel rather than falling back to the lexical path. A link + // re-pointed between this call and the spawn cannot be closed from + // here; it rides the same accepted race class as a settings flip + // during a pending prompt. + let workingDirectory: string + try { + workingDirectory = await fs.realpath(lexicalWorkingDirectory) + } catch (error) { + const resolutionError = + (await commandWorkingDirectoryError(lexicalWorkingDirectory)) ?? + `Unable to resolve working directory '${lexicalWorkingDirectory}': ${error instanceof Error ? error.message : String(error)}` + task.didToolFailInCurrentTurn = true + pushToolResult(formatResponse.toolError(resolutionError)) + return + } let dcgDecision: DcgDecision | undefined if (provider?.contextProxy.getValue("destructiveCommandGuardEnabled") === true) { const workingDirectoryError = await commandWorkingDirectoryError(workingDirectory) diff --git a/src/core/tools/__tests__/executeCommandTool.spec.ts b/src/core/tools/__tests__/executeCommandTool.spec.ts index 1700d676bb..f14019dcc3 100644 --- a/src/core/tools/__tests__/executeCommandTool.spec.ts +++ b/src/core/tools/__tests__/executeCommandTool.spec.ts @@ -2,7 +2,8 @@ import type { ToolUsage } from "@roo-code/types" import fs from "fs/promises" -import { constants as fsConstants, type Stats } from "fs" +import { constants as fsConstants, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, type Stats } from "fs" +import * as os from "os" import * as path from "path" import * as vscode from "vscode" @@ -24,6 +25,10 @@ vitest.mock("fs/promises", () => ({ default: { access: vitest.fn().mockResolvedValue(undefined), stat: vitest.fn().mockResolvedValue({ isDirectory: () => true }), + // The tool canonicalizes the resolved working directory before any + // approval decision; the default double resolves every path to itself, + // so a test only sees symlink behavior when it scripts this mock. + realpath: vitest.fn().mockImplementation((p: string) => Promise.resolve(p)), }, })) @@ -79,6 +84,34 @@ const { executeCommandTool } = executeCommandModule // capturing inside a test can capture another test's leaked spy and recurse. const realCheckAutoApproval = autoApprovalModule.checkAutoApproval +// Creating a directory symlink on Windows needs developer mode or elevation; a +// junction needs neither and is resolved by `realpath` like a POSIX link, so the +// fixture tries a symlink first and falls back to a junction. Where neither can +// be created the fixture is skipped: the real-filesystem behavior it pins cannot +// be produced by the file-mock module this suite otherwise runs on. +function createDirectoryLink(target: string, linkPath: string): void { + try { + symlinkSync(target, linkPath, "dir") + } catch { + symlinkSync(target, linkPath, "junction") + } +} + +function canCreateDirectoryLink(): boolean { + const probeDir = mkdtempSync(path.join(os.tmpdir(), "execute-command-symlink-probe-")) + try { + const target = path.join(probeDir, "target") + mkdirSync(target) + createDirectoryLink(target, path.join(probeDir, "link")) + return true + } catch { + return false + } finally { + rmSync(probeDir, { recursive: true, force: true }) + } +} +const directoryLinksAvailable = canCreateDirectoryLink() + describe("executeCommandTool", () => { // Setup common test variables let mockCline: any & { consecutiveMistakeCount: number; didRejectTool: boolean } @@ -270,6 +303,148 @@ describe("executeCommandTool", () => { }) }) + // The folder-scoped command policy resolves a directory by string + // containment, so a link would be judged by the folder it sits in while the + // process starts in the link's target. The tool canonicalizes the resolved + // working directory once, before any approval decision, so every consumer + // (ask, DCG, re-checks, spawn) sees the physical directory. + describe("Working directory canonicalization", () => { + it("forwards the physical directory behind a symlinked custom cwd to the approval ask", async () => { + mockToolUse.params.command = "echo test" + mockToolUse.params.cwd = "/mock/link" + mockToolUse.nativeArgs = { command: "echo test", cwd: "/mock/link" } + vi.mocked(fs.realpath).mockResolvedValueOnce("/physical/target") + + await executeCommandTool.handle(mockCline as Task, mockToolUse, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(fs.realpath).toHaveBeenCalledWith("/mock/link") + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { + commandCwd: "/physical/target", + }) + }) + + it("runs the destructive-command guard in the physical directory behind a symlinked custom cwd", async () => { + const provider = await mockCline.providerRef.deref() + provider.context = { globalStorageUri: { fsPath: "/test/storage" } } + provider.contextProxy.getValue.mockReturnValue(true) + mockToolUse.params.cwd = "/mock/link" + mockToolUse.nativeArgs = { command: "echo test", cwd: "/mock/link" } + vi.mocked(fs.realpath).mockResolvedValueOnce("/physical/target") + + await executeCommandTool.handle(mockCline as Task, mockToolUse, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockRunDcg).toHaveBeenCalledWith("/test/storage/dcg", "echo test", "/physical/target") + }) + + it("fails closed on a broken symlink without reaching approval", async () => { + mockToolUse.params.cwd = "/mock/broken-link" + mockToolUse.nativeArgs = { command: "echo test", cwd: "/mock/broken-link" } + vi.mocked(fs.realpath).mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + vi.mocked(fs.stat).mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + vi.mocked(formatResponse.toolError).mockReturnValueOnce("formatted broken-link error") + + await executeCommandTool.handle(mockCline as Task, mockToolUse, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The realpath failure is reported through the working-directory + // error channel, which names the directory by its validated state. + expect(formatResponse.toolError).toHaveBeenCalledExactlyOnceWith( + "Working directory '/mock/broken-link' does not exist.", + ) + expect(mockPushToolResult).toHaveBeenCalledExactlyOnceWith("formatted broken-link error") + expect(mockAskApproval).not.toHaveBeenCalled() + expect(mockCline.didToolFailInCurrentTurn).toBe(true) + }) + + it.each([ + { thrown: Object.assign(new Error("ELOOP: too many symbolic links"), { code: "ELOOP" }) }, + { thrown: "ELOOP: too many symbolic links" }, + ])( + "fails closed when canonicalization fails although the lexical directory validates (%s)", + async ({ thrown }) => { + mockToolUse.params.cwd = "/mock/loop" + mockToolUse.nativeArgs = { command: "echo test", cwd: "/mock/loop" } + vi.mocked(fs.realpath).mockRejectedValueOnce(thrown) + + await executeCommandTool.handle(mockCline as Task, mockToolUse, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // A link that cannot be resolved names no directory any policy + // could judge, even when the lexical `stat` check would pass: the + // fallback message is the witness that the error came from + // canonicalization, and it carries the failure reason whatever + // shape the rejection has. + expect(formatResponse.toolError).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining("Unable to resolve working directory '/mock/loop': ELOOP"), + ) + expect(mockAskApproval).not.toHaveBeenCalled() + expect(mockCline.didToolFailInCurrentTurn).toBe(true) + }, + ) + + // The scripted-realpath tests above pin the tool's contract; this one + // pins it against a real link: the folder policy resolves a path by + // string containment (already covered against the canonical value), so + // the physical path reaching `commandCwd` is what makes a link inside one + // folder judged by the folder of its target. + it.skipIf(!directoryLinksAvailable)( + "forwards the real target of a directory link created on disk", + async () => { + const baseDir = mkdtempSync(path.join(os.tmpdir(), "execute-command-canonicalize-")) + try { + const folderA = path.join(baseDir, "folder-a") + const folderB = path.join(baseDir, "folder-b") + mkdirSync(folderA) + mkdirSync(folderB) + const link = path.join(folderA, "link") + createDirectoryLink(folderB, link) + // The module mock resolves paths through this delegate, so the + // tool sees the same physical path the filesystem reports. + // Once-only: the tool canonicalizes exactly one path per call, + // and a leaked delegate would resolve later tests' fake paths + // against the real filesystem. + vi.mocked(fs.realpath).mockImplementationOnce(async (target) => realpathSync(String(target))) + + mockToolUse.params.cwd = link + mockToolUse.nativeArgs = { command: "echo test", cwd: link } + await executeCommandTool.handle(mockCline as Task, mockToolUse, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // Compared against the independently resolved target rather + // than a literal: temporary-directory paths themselves contain + // links on some platforms. + expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { + commandCwd: realpathSync(folderB), + }) + } finally { + rmSync(baseDir, { recursive: true, force: true }) + } + }, + ) + }) + describe("Error handling", () => { it("reports command parse errors to the webview", async () => { const provider = await mockCline.providerRef.deref() From 4d8f2fde8370f120cccbc4138f60978b20f2c54f Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 10 Nov 2026 13:22:07 +0100 Subject: [PATCH 12/52] fix: match folder command policy by deepest real path An outer workspace root whose registered path lexically contained a command's real directory was matched before the deeper root the directory physically belongs to, skipping that folder's deny entries; all roots are now compared by real path and the deepest match wins. The settings view commits its buffered command-list edits only when the host reports the save succeeded, so a failed save keeps them visible. Activation seeds the command lists before the terminal registry is initialized, so a rejected seed cannot leave registered listeners behind. Tests cover overlapping roots, a working directory equal to a root's real path, no open workspace folder, and a save the host rejects. --- src/__tests__/extension.spec.ts | 44 ++++++ .../__tests__/commandScope.spec.ts | 133 +++++++++++++++--- src/core/auto-approval/commandScope.ts | 41 +++--- src/extension.ts | 10 +- .../src/components/settings/SettingsView.tsx | 23 ++- .../SettingsView.unsaved-changes.spec.tsx | 101 +++++++++++++ 6 files changed, 302 insertions(+), 50 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 1788299572..bfa6821201 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -588,6 +588,50 @@ describe("extension.ts", () => { } as unknown as vscode.WorkspaceConfiguration) }) + test("seeds both command lists before initializing the terminal registry", async () => { + // Invariant: a seed rejection must fail activation before the terminal + // registry is initialized, so no initialized-but-half-activated state is + // reachable (the registry's listeners are released only via deactivate, + // which the host does not guarantee after a failed activation). + const order: string[] = [] + const seedCommandList = vi.fn(async (_globalState: vscode.Memento, configKey: string): Promise => { + order.push(`seed:${configKey}`) + }) + vi.doMock("../utils/seedAllowedCommands", () => ({ seedCommandList })) + try { + const { TerminalRegistry } = await import("../integrations/terminal/TerminalRegistry") + vi.mocked(TerminalRegistry.initialize).mockImplementation(() => void order.push("initialize")) + + const { activate } = await import("../extension") + await activate(mockContext) + + expect(order).toEqual(["seed:allowedCommands", "seed:deniedCommands", "initialize"]) + expect(TerminalRegistry.initialize).toHaveBeenCalledTimes(1) + } finally { + vi.doUnmock("../utils/seedAllowedCommands") + } + }) + + test("aborts activation before the terminal registry is initialized when seeding rejects", async () => { + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), + })) + try { + const { TerminalRegistry } = await import("../integrations/terminal/TerminalRegistry") + const { ClineProvider } = await import("../core/webview/ClineProvider") + + const { activate } = await import("../extension") + await expect(activate(mockContext)).rejects.toThrow("seed state write failed") + + // The seed rejection must reach the host unchanged, with the registry + // never initialized and no downstream activation (sidebar provider) reached. + expect(TerminalRegistry.initialize).not.toHaveBeenCalled() + expect(ClineProvider).not.toHaveBeenCalled() + } finally { + vi.doUnmock("../utils/seedAllowedCommands") + } + }) + test("does not seed global state from an enforced workspace-scoped override", async () => { const vscode = await import("vscode") // The gate is on: an enforced workspace list replaces the default across diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index bcead00215..ee7a6e4104 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -22,10 +22,13 @@ import { baseState, type State } from "./fixtures" // mock's getter reads through this object, so a test can change the open // folders without re-mocking the module. `foldersByPath` backs // `getWorkspaceFolder`: keys are folder paths, values the folder objects, so -// a test controls which cwds resolve to a root. +// a test controls which cwds resolve to a root. `throwsOnFoldersRead` makes +// the getter itself fail once, standing in for a workspace that cannot answer +// the lookup at all. const workspaceState = vi.hoisted(() => ({ workspaceFolders: undefined as { uri: unknown }[] | undefined, foldersByPath: new Map(), + throwsOnFoldersRead: false, })) // Scriptable stand-in for `fs.realpathSync`, which the root-side containment @@ -77,13 +80,27 @@ vi.mock("vscode", () => ({ }, workspace: { get workspaceFolders() { + if (workspaceState.throwsOnFoldersRead) { + // One-shot, like the throwing-lookup test it serves: a leaked + // throw would fail every later read, including the + // first-folder default reads the composition still performs. + workspaceState.throwsOnFoldersRead = false + throw new Error("workspace unavailable") + } return workspaceState.workspaceFolders }, getConfiguration: vi.fn(), + // Mirrors VS Code's lexical containment: a prefix test against the + // registered paths, with the platform separator as the guard between + // root and remainder. The folder lookup does not consult this double — + // it compares roots by their real paths — but the double stays + // faithful so a test can register an outer root that lexically + // contains a symlinked root's target, the containment that must not + // decide the folder match. getWorkspaceFolder: vi.fn((resource?: { fsPath?: string }) => { const fsPath = resource?.fsPath ?? "" for (const [folderPath, uri] of workspaceState.foldersByPath) { - if (fsPath === folderPath || fsPath.startsWith(`${folderPath}/`)) { + if (fsPath === folderPath || fsPath.startsWith(folderPath + path.sep)) { return { uri } } } @@ -624,26 +641,44 @@ it("checkAutoApproval command: does not apply the first folder's allow list to a expect(result).toEqual({ decision: "ask" }) }) -it("checkAutoApproval command: composes a command without a cwd from the global layers when both raw layers are present", async () => { +it("checkAutoApproval command: composes a command without a cwd from the global entries and the first folder's list when both raw layers are present", async () => { vi.clearAllMocks() // With both raw layers set, the command branch re-composes instead of - // consuming the baked pair; an absent cwd keeps the first-folder - // configuration, which here contributes nothing, so only the raw global - // allow entry can decide. A check that consumed the baked pair instead - // would find no match and fall to the plain prompt. + // consuming the baked pair. An absent cwd keeps the first-folder + // configuration, so two independent witnesses apply: the raw global allow + // entry decides "echo hi" (a check that consumed the baked pair instead + // would find no match and fall to the plain prompt), and folder A's deny + // entry — about a command the global layers say nothing of — decides + // "date -u" (a composition that ignored the folder's configuration would + // have only the raw global layers to enforce and would fall to the plain + // prompt). The scope assertions pin which folder's configuration the + // composition read. const { folderA, folderB } = openMultiRootWindow() mockFolderConfigurations({ - [folderA.fsPath]: { gate: true }, + [folderA.fsPath]: { gate: true, deny: ["date"] }, [folderB.fsPath]: { gate: true, deny: ["rm"] }, }) - const result = await checkAutoApproval({ - state: { ...taskFolderState(["baked"]), globalAllowedCommands: ["echo"], globalDeniedCommands: ["rm"] }, - ask: "command", - text: "echo hi", - }) + const state = { + ...taskFolderState(["baked"]), + globalAllowedCommands: ["echo"], + globalDeniedCommands: ["rm"], + } - expect(result).toEqual({ decision: "approve" }) + const globalWitness = await checkAutoApproval({ state, ask: "command", text: "echo hi" }) + expect(globalWitness).toEqual({ decision: "approve" }) + + // "date" is shadowed by neither global layer, so only folder A's list can + // deny it: the outcome names the folder whose configuration decided. + const folderWitness = await checkAutoApproval({ state, ask: "command", text: "date -u" }) + expect(folderWitness).toEqual({ + decision: "deny", + autoDeny: { kind: "denylist", command: "date -u", pattern: "date" }, + }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) + // Reading folder B instead would have judged the command against a folder + // the window never defaults to. + expect(vscode.workspace.getConfiguration).not.toHaveBeenCalledWith(Package.name, folderB) }) it("checkAutoApproval command: still lets a global deny entry veto a command whose cwd names no workspace root", async () => { @@ -692,11 +727,9 @@ it("checkAutoApproval command: treats a throwing workspace-folder lookup as a cw // The lookup guard exists so a broken lookup cannot fail the decision; the // degradation it produces must be the global-only composition, not a // first-folder guess — the same fail-closed direction as an unmatched cwd. - // Once-only: spies survive between tests in this file, and a leaked throwing - // lookup would change every later test's folder resolution. - vi.mocked(vscode.workspace.getWorkspaceFolder).mockImplementationOnce(() => { - throw new Error("workspace unavailable") - }) + // The stand-in throws exactly once, so a leak cannot change later tests' + // folder resolution. + workspaceState.throwsOnFoldersRead = true mockFolderConfigurations({ [folderA.fsPath]: { gate: true, deny: [], allow: ["echo"] }, [folderB.fsPath]: { gate: true, deny: ["rm"] }, @@ -843,6 +876,28 @@ it("commandListFolderForResource: a path inside no root stays unmatched after th expect(commandListFolderForResource(path.join(path.sep + "mock", "elsewhere"))).toBeUndefined() }) +it("commandListFolderForResource: matches a cwd equal to the root's real path", () => { + vi.clearAllMocks() + workspaceState.foldersByPath.clear() + const rootPath = path.join(path.sep + "mock", "root") + const registeredPath = path.join(path.sep + "mock", "root-link") + const rootUri = makeUri(registeredPath) + workspaceState.workspaceFolders = [{ uri: rootUri }] + vi.mocked(fs.realpathSync).mockImplementation((target) => + String(target) === registeredPath ? rootPath : String(target), + ) + + expect(commandListFolderForResource(rootPath)).toBe(rootUri) +}) + +it("commandListFolderForResource: returns undefined when no workspace folder is open", () => { + vi.clearAllMocks() + workspaceState.foldersByPath.clear() + workspaceState.workspaceFolders = undefined + + expect(commandListFolderForResource(path.join(path.sep + "mock", "root"))).toBeUndefined() +}) + it("commandListFolderForResource: compares the cwd to the root's real path case-sensitively", () => { vi.clearAllMocks() workspaceState.workspaceFolders = [{ uri: makeUri(path.join(path.sep + "mock", "Root")) }] @@ -875,6 +930,46 @@ it("commandListFolderForResource: returns the registry Uri of the deepest matchi expect(result?.fsPath).toBe(innerRegistered) }) +it("checkAutoApproval command: judges a cwd inside a symlinked root by that root's layer when an outer root also contains it lexically", async () => { + vi.clearAllMocks() + const outerRoot = path.sep + "mock" + const outerUri = makeUri(outerRoot) + const linkPath = path.join(outerRoot, "link") + const innerReal = path.join(outerRoot, "inner") + const linkUri = makeUri(linkPath) + // The outer root is registered first, and the registry holds the inner + // folder as the link: the command's canonical cwd sits inside the link's + // target. The outer root is also a lexical prefix of the cwd, so + // VS Code-style lexical containment resolves it there — a lookup that + // trusted that first lexical hit would enforce the outer folder's list + // and never consult the folder the command physically runs in. + workspaceState.workspaceFolders = [{ uri: outerUri }, { uri: linkUri }] + workspaceState.foldersByPath.set(outerRoot, outerUri) + vi.mocked(fs.realpathSync).mockImplementation((target) => + String(target) === linkPath ? innerReal : String(target), + ) + // The two folders' lists are deliberately opposite on "echo": the outer + // root allows what the inner root denies, so the decision names the + // folder whose configuration enforcement read. + mockFolderConfigurations({ + [outerRoot]: { gate: true, allow: ["echo"] }, + [linkPath]: { gate: true, deny: ["echo"] }, + }) + + const result = await checkAutoApproval({ + // Empty raw global layers: only the winning folder's layer can decide. + state: taskFolderState([]), + cwd: path.join(innerReal, "sub"), + ask: "command", + text: "echo hi", + }) + + // The deepest canonical match wins over the shallower lexical containment, + // so the symlinked root's deny entry decides the command running inside it. + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, linkUri) +}) + it("realpathSync preserves the on-disk case of an existing directory", () => { vi.clearAllMocks() const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "command-scope-case-")) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 8324f5bfae..365756454c 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -55,10 +55,13 @@ export function commandListConfiguration(folderResource?: vscode.Uri): vscode.Wo * * The command path hands this lookup a cwd the filesystem has already * resolved to its real path, while the workspace registry holds each root as - * it was opened. Containment against the registered paths is tried first; - * when it matches no root, the search is retried against each root's real - * path so a root that is itself a symlink (or a Windows junction) keeps - * matching its own real directory. Among several matches the deepest root + * it was opened. Containment is therefore tested against every root's real + * path, so a root that is itself a symlink (or a Windows junction) keeps + * matching its own real directory. Comparing against the registered paths + * alone could not decide the folder: that comparison is lexical, so an outer + * root lexically contains a directory that physically belongs to a deeper + * root, and enforcing the outer root's lists there would let the deeper + * folder's deny entries be skipped. Among several matches the deepest root * wins, mirroring how VS Code's own containment picks the innermost folder. * A root whose real path cannot be resolved is compared by its registered * path: the cwd is already canonical, so an unresolvable root can only @@ -66,32 +69,28 @@ export function commandListConfiguration(folderResource?: vscode.Uri): vscode.Wo * may approve — and dropping the layer outright would silently change * enforcement for a folder the user has open. * - * @param cwd - The task's working directory. A blank cwd, or one that names - * no workspace root (a removed or relocated folder), yields `undefined`, - * which leaves every read on its first-folder default — the behavior such a - * cwd had before per-task scoping existed, never a guess at a different one. + * @param cwd - The task's working directory. An empty or absent cwd yields + * `undefined` and keeps the first-folder configuration. A nonempty cwd with + * no matching root also yields `undefined`. When both raw global lists are + * available, enforcement then excludes the workspace layer; otherwise, it + * uses the pre-composed state lists. * @returns The containing folder's registry URI — never a canonicalized one, * because folder-scoped configuration resolves against the registry — or - * `undefined` when cwd resolves to no root. + * `undefined` when cwd is empty, resolves to no root, or lookup fails. */ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefined { if (!cwd) { return undefined } - // Guarded like the configuration reads this feeds: a lookup that cannot - // run stands in for a cwd naming no root, so enforcement degrades to the - // first-folder default instead of failing the approval decision. + // A failed lookup returns undefined, like a cwd naming no root. + // With both raw global lists available, enforcement excludes the workspace + // layer; otherwise, it uses the pre-composed state lists. try { - const folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(cwd)) - if (folder) { - return folder.uri - } - - // A miss above is expected when a root is a link and the cwd names the - // link's target, so containment is retried root by root against the - // filesystem's real paths. The separator guard keeps a sibling like - // `/root/other` from matching a root `/root`. + // Comparing by root-path length makes the deepest match win: a root + // registered lexically above a symlinked root must not claim a command + // running in the deeper root's real directory. The separator guard + // keeps a sibling like `/root/other` from matching a root `/root`. let match: vscode.Uri | undefined let matchedLength = 0 for (const candidate of vscode.workspace.workspaceFolders ?? []) { diff --git a/src/extension.ts b/src/extension.ts index 5e496dac48..68742a62dc 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -162,9 +162,6 @@ export async function activate(context: vscode.ExtensionContext) { // Initialize i18n for internationalization support. initializeI18n(context.globalState.get("language") ?? formatLanguage(vscode.env.language)) - // Initialize terminal shell execution handlers. - TerminalRegistry.initialize() - // Initialize OpenAI Codex OAuth manager for ChatGPT subscription-based access. openAiCodexOAuthManager.initialize(context, (message) => outputChannel.appendLine(message)) // Kimi Code OAuth tokens live only in VS Code SecretStorage, outside provider profile JSON/cloud sync. @@ -173,12 +170,19 @@ export async function activate(context: vscode.ExtensionContext) { // Initialize Zoo Code auth service for extension session token management. await initZooCodeAuth(context) + // Seed before the terminal registry is initialized: a rejected seed must + // abort activation while the registry holds no resources, because its + // listeners are released only by `deactivate()`, which the host does not + // guarantee after a failed activation. // Each list key carries its own first-run guard, so a profile whose // allowlist was seeded by an earlier version still gets the deny-list // migration on the next activation. await seedCommandList(context.globalState, "allowedCommands") await seedCommandList(context.globalState, "deniedCommands") + // Initialize terminal shell execution handlers. + TerminalRegistry.initialize() + const contextProxy = await ContextProxy.getInstance(context) const updateTelemetryState = () => { const telemetrySetting = contextProxy.getGlobalState("telemetrySetting") ?? "unset" diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 92d6efcdbc..a0fea12123 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -601,16 +601,20 @@ const SettingsView = forwardRef(({ onDone, t vscode.postMessage({ type: "telemetrySetting", text: telemetrySetting }) vscode.postMessage({ type: "debugSetting", bool: cachedState.debug }) - // Saving commits the buffered lists, so they no longer hold off external updates. - commandListsTouched.current = false lastDisplayedCommandSnapshot.current = commandListSnapshot({ allowedCommands, deniedCommands, workspaceCommandListsEnabled: cachedState.workspaceCommandListsEnabled, }) - // With a time or date edit the flag is cleared when the host reports the save (see below). A failed save - // leaves the user's edits in place to retry. - if (!saveId) setChangeDetected(false) + // The stamp records what is on screen, so it moves at submit regardless of the outcome; the lists' + // ownership of the buffer does not. A save the host answers commits the buffered lists only once the + // host says the write landed (see the settle below) - committing at submit would let the state refresh + // that follows a rejected save overwrite the edit the user is still looking at. A save the host never + // answers has no result to wait for, so it clears the hold at submit. + if (!saveId) { + commandListsTouched.current = false + setChangeDetected(false) + } } } @@ -619,8 +623,13 @@ const SettingsView = forwardRef(({ onDone, t const settle = (success: boolean) => { setPendingSaveId(undefined) - // An edit made while the save was in flight is not in what was sent: it stays unsaved. - if (success && latestCachedState.current === sentState.current) setChangeDetected(false) + // An edit made while the save was in flight is not in what was sent: it stays unsaved. A failed save + // keeps the buffered lists holding off external updates too, so the host's refresh after a rejected + // write cannot replace the edit the user is looking at. + if (success && latestCachedState.current === sentState.current) { + commandListsTouched.current = false + setChangeDetected(false) + } } const onResult = (event: MessageEvent) => { diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 04e0c7e18a..eec8fc01a6 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -9,6 +9,8 @@ import React from "react" import SettingsView from "../SettingsView" import { vscode } from "@src/utils/vscode" +import { answerSave, lastSaveRequestId } from "./saveAcknowledgement" + const postMessage = vi.spyOn(vscode, "postMessage").mockImplementation(() => {}) // Mock the extension state context @@ -943,6 +945,105 @@ describe("SettingsView - Unsaved Changes Detection", () => { ) }) + it("keeps a buffered list edit and its hold on external updates when the save is reported failed", async () => { + // A failed save must leave the dialog exactly as the user left it: still dirty, and with the + // in-flight list still holding back external refreshes. Clearing the hold at submit - before + // the host's answer - would let the post-failure state refresh overwrite the edit on screen. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("buffer-deny-edit")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A display-setting difference between the buffer and the live state puts this save on the + // path that waits for the host's answer, without touching the buffered command lists. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + showRelativeTimes: false, + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + expect(screen.getByTestId("save-button")).toBeDisabled() // waiting for the host's answer + answerSave(saveId, { success: false, error: "storage unavailable" }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) // the failure keeps it dirty + + // The host refreshes state after the rejected write; the edit the user is looking at wins. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + view.rerender() + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["git status"])) + + // Retrying submits the buffered edit, not the refresh that tried to replace it. + fireEvent.click(screen.getByTestId("save-button")) + expect(postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + updatedSettings: expect.objectContaining({ deniedCommands: ["git status"] }), + }), + ) + }) + + it("releases the buffered list to external updates once the host confirms the save", async () => { + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("buffer-deny-edit")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + showRelativeTimes: false, + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + expect(lastSaveRequestId(postMessage)).toBeDefined() // this save waits for the host's answer + answerSave(lastSaveRequestId(postMessage), { success: true }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // The lists committed, so a later host update is no longer an in-flight edit being stomped. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + view.rerender() + await waitFor(() => + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["rm -rf"])), + ) + }) + it("discards IO Intelligence cached edits and restores the extension values", async () => { const onDone = vi.fn() ;(useExtensionState as ReturnType).mockReturnValue({ From 9e7633ea0f47a4a0cf731af0471c2684c9f3ac76 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 10 Nov 2026 17:26:01 +0100 Subject: [PATCH 13/52] fix: reconcile failed-save retry baselines and dispose auth listener After a failed settings save each command list's displayed baseline is reconciled against that list's own write outcome, so a deletion whose write never ran is retried as a deletion instead of re-admitted as an addition. The auth secret-storage listener is now retained and disposed when activation aborts before the seed writes settle. The save-retry test pins the post count, the submitted list, and the retry's baseline. --- src/__tests__/extension.spec.ts | 27 ++++++ src/extension.ts | 17 +++- src/services/zoo-code-auth.ts | 14 +++- .../src/components/settings/SettingsView.tsx | 83 +++++++++++++++++-- .../SettingsView.unsaved-changes.spec.tsx | 83 ++++++++++++++++++- 5 files changed, 206 insertions(+), 18 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index bfa6821201..6ffc8f3708 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -632,6 +632,33 @@ describe("extension.ts", () => { } }) + test("disposes the auth secret-storage listener when seeding rejects activation", async () => { + // A rejected seed aborts activation after the auth initializer has + // registered its secret-storage listener, and the host does not guarantee + // `deactivate()` after a failed activation, so the failure path must + // release the retained listener disposable itself. + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), + })) + const dispose = vi.fn() + const authListener = { dispose } + vi.doMock("../services/zoo-code-auth", () => ({ + initZooCodeAuth: vi.fn().mockResolvedValue(authListener), + })) + try { + const { activate } = await import("../extension") + await expect(activate(mockContext)).rejects.toThrow("seed state write failed") + + // Retained for the success path (deactivate disposes subscriptions) and + // disposed on the failure path, exactly once, with the error propagated. + expect(mockContext.subscriptions).toContain(authListener) + expect(dispose).toHaveBeenCalledExactlyOnceWith() + } finally { + vi.doUnmock("../utils/seedAllowedCommands") + vi.doUnmock("../services/zoo-code-auth") + } + }) + test("does not seed global state from an enforced workspace-scoped override", async () => { const vscode = await import("vscode") // The gate is on: an enforced workspace list replaces the default across diff --git a/src/extension.ts b/src/extension.ts index 68742a62dc..01038adcdb 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -168,7 +168,11 @@ export async function activate(context: vscode.ExtensionContext) { kimiCodeOAuthManager.initialize(context) // Initialize Zoo Code auth service for extension session token management. - await initZooCodeAuth(context) + // The returned disposable unregisters the secret-storage listener the + // initializer acquires; keep it for both the normal deactivate path and the + // failed-activation path below. + const authSecretsListener = await initZooCodeAuth(context) + context.subscriptions.push(authSecretsListener) // Seed before the terminal registry is initialized: a rejected seed must // abort activation while the registry holds no resources, because its @@ -177,8 +181,15 @@ export async function activate(context: vscode.ExtensionContext) { // Each list key carries its own first-run guard, so a profile whose // allowlist was seeded by an earlier version still gets the deny-list // migration on the next activation. - await seedCommandList(context.globalState, "allowedCommands") - await seedCommandList(context.globalState, "deniedCommands") + try { + await seedCommandList(context.globalState, "allowedCommands") + await seedCommandList(context.globalState, "deniedCommands") + } catch (error) { + // Activation aborts here, so `deactivate()` may never run: release the + // secret-storage listener acquired above before propagating. + authSecretsListener.dispose() + throw error + } // Initialize terminal shell execution handlers. TerminalRegistry.initialize() diff --git a/src/services/zoo-code-auth.ts b/src/services/zoo-code-auth.ts index 709cb805c3..0a052c503e 100644 --- a/src/services/zoo-code-auth.ts +++ b/src/services/zoo-code-auth.ts @@ -7,6 +7,9 @@ const ZOO_CODE_USER_NAME_KEY = "zoo-code-user-name" const ZOO_CODE_USER_EMAIL_KEY = "zoo-code-user-email" const ZOO_CODE_USER_IMAGE_KEY = "zoo-code-user-image" +// Returned when no listener was acquired, so callers can dispose unconditionally. +const NOOP_DISPOSABLE: vscode.Disposable = { dispose: () => {} } + let secretStorage: vscode.SecretStorage | undefined // In-memory cache for synchronous access in ZooCodeHandler hot path @@ -16,11 +19,11 @@ let _cachedUserName: string | undefined = undefined let _cachedUserEmail: string | undefined = undefined let _cachedUserImage: string | undefined = undefined -export async function initZooCodeAuth(context: vscode.ExtensionContext): Promise { +export async function initZooCodeAuth(context: vscode.ExtensionContext): Promise { if (!context.secrets) { // Secret storage unavailable (e.g. test environment without secrets mock). // Treat as unauthenticated startup — all cached values remain undefined. - return + return NOOP_DISPOSABLE } secretStorage = context.secrets @@ -42,8 +45,11 @@ export async function initZooCodeAuth(context: vscode.ExtensionContext): Promise } } - // Watch for secret changes and update cache - context.secrets.onDidChange((e) => { + // Watch for secret changes and update cache. The returned disposable unregisters + // the listener: an activation that fails after this point must release it itself, + // because the host does not guarantee `deactivate()` (and with it + // context.subscriptions cleanup) after activation throws. + return context.secrets.onDidChange((e) => { if (e.key === ZOO_CODE_TOKEN_KEY) { secretStorage?.get(ZOO_CODE_TOKEN_KEY).then((token) => { _cachedToken = token diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index a0fea12123..3cd140c7d4 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -185,6 +185,15 @@ const SettingsView = forwardRef(({ onDone, t const sentState = useRef(undefined) const latestCachedState = useRef(cachedState) latestCachedState.current = cachedState + // The live host state, read when a save settles without re-subscribing the result handler on every post. + const latestExtensionState = useRef(extensionState) + latestExtensionState.current = extensionState + // The save the host must answer records the baseline it stamped and the lists it submitted, so a save the + // host reports failed can reconcile each list's baseline against that list's own write outcome (see the + // save-result effect below). + const submittedListSave = useRef<{ baselined: [string[], string[]]; sent: [string[], string[]] } | undefined>( + undefined, + ) // Command-list values the dialog last displayed, so a later state post can be recognized as // an external change rather than a restatement of what is already shown. @@ -507,6 +516,10 @@ const SettingsView = forwardRef(({ onDone, t const saveId = displayChanged ? nextSaveRequestId() : undefined if (saveId) { sentState.current = cachedState + submittedListSave.current = { + baselined: [lastDisplayedAllowed, lastDisplayedDenied], + sent: [allowedCommands ?? [], deniedCommands ?? []], + } setPendingSaveId(saveId) } @@ -606,9 +619,10 @@ const SettingsView = forwardRef(({ onDone, t deniedCommands, workspaceCommandListsEnabled: cachedState.workspaceCommandListsEnabled, }) - // The stamp records what is on screen, so it moves at submit regardless of the outcome; the lists' - // ownership of the buffer does not. A save the host answers commits the buffered lists only once the - // host says the write landed (see the settle below) - committing at submit would let the state refresh + // The stamp records what is on screen, so it moves at submit; a save the host reports failed then + // re-derives each list's entry from whether that list's own write landed (see the settle below). The + // lists' ownership of the buffer does not move at submit. A save the host answers commits the buffered + // lists only once the host says the write landed - committing at submit would let the state refresh // that follows a rejected save overwrite the edit the user is still looking at. A save the host never // answers has no result to wait for, so it clears the hold at submit. if (!saveId) { @@ -623,13 +637,64 @@ const SettingsView = forwardRef(({ onDone, t const settle = (success: boolean) => { setPendingSaveId(undefined) - // An edit made while the save was in flight is not in what was sent: it stays unsaved. A failed save - // keeps the buffered lists holding off external updates too, so the host's refresh after a rejected - // write cannot replace the edit the user is looking at. - if (success && latestCachedState.current === sentState.current) { - commandListsTouched.current = false - setChangeDetected(false) + if (success) { + // Every list's write landed, so the baseline the submit advanced is kept for all of them. + submittedListSave.current = undefined + // An edit made while the save was in flight is not in what was sent: it stays unsaved. A failed save + // keeps the buffered lists holding off external updates too, so the host's refresh after a rejected + // write cannot replace the edit the user is looking at. + if (latestCachedState.current === sentState.current) { + commandListsTouched.current = false + setChangeDetected(false) + } + return + } + // A rejected or timed-out save reports one outcome for the whole payload, yet each command list may + // have reached a different write result before it failed: the save writes setting by setting, so an + // earlier failure (or a timeout) can land after one list was written and before another. The refresh + // the host posts before its answer carries each list's configuration result, so a list equal to what + // was submitted records that its own write landed: for that list the baseline stays advanced, since + // restoring the pre-submit baseline of a written list claims an entry the file no longer holds was + // displayed. Every other edited list's baseline rolls back to what was displayed before the submit, + // so a deletion whose write never ran is still classified as a user deletion on retry instead of an + // external addition to re-admit. Lists the save did not edit keep the stamp's baseline, which the + // external-update merge already maintains. + const save = submittedListSave.current + submittedListSave.current = undefined + if (!save) { + return } + const [stampAllowed, stampDenied, stampGate] = JSON.parse(lastDisplayedCommandSnapshot.current) as [ + string[], + string[], + boolean, + ] + const reconcileList = ( + baselined: string[], + sent: string[], + refreshed: string[] | undefined, + stamped: string[], + ) => + commandListsEquivalent(baselined, sent) + ? stamped + : commandListsEquivalent(refreshed, sent) + ? sent + : baselined + lastDisplayedCommandSnapshot.current = commandListSnapshot({ + allowedCommands: reconcileList( + save.baselined[0], + save.sent[0], + latestExtensionState.current.allowedCommands, + stampAllowed, + ), + deniedCommands: reconcileList( + save.baselined[1], + save.sent[1], + latestExtensionState.current.deniedCommands, + stampDenied, + ), + workspaceCommandListsEnabled: stampGate, + }) } const onResult = (event: MessageEvent) => { diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index eec8fc01a6..fa673ea465 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -13,6 +13,9 @@ import { answerSave, lastSaveRequestId } from "./saveAcknowledgement" const postMessage = vi.spyOn(vscode, "postMessage").mockImplementation(() => {}) +const updateSettingsPosts = () => + postMessage.mock.calls.map(([message]) => message).filter((message) => message.type === "updateSettings") + // Mock the extension state context vi.mock("@src/context/ExtensionStateContext", () => ({ ExtensionStateContextProvider: ({ children }: any) => children, @@ -992,12 +995,88 @@ describe("SettingsView - Unsaved Changes Detection", () => { view.rerender() expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["git status"])) - // Retrying submits the buffered edit, not the refresh that tried to replace it. + // Retrying submits the buffered edit, not the refresh that tried to replace it. The first save posted the + // same list, so only the call count plus the last message's list and baseline prove the retry did it. fireEvent.click(screen.getByTestId("save-button")) - expect(postMessage).toHaveBeenCalledWith( + const saves = updateSettingsPosts() + expect(saves).toHaveLength(2) + expect(saves.at(-1)).toEqual( expect.objectContaining({ type: "updateSettings", updatedSettings: expect.objectContaining({ deniedCommands: ["git status"] }), + commandListBaseline: expect.objectContaining({ deniedCommands: expect.any(Array) }), + }), + ) + }) + + it("reconciles each list's retry baseline with that list's own write outcome after a failed save", async () => { + // A failed save reports one outcome for the whole payload, yet its writes ran setting by setting: the + // refresh the host posts before the answer carries each list's configuration result. A list whose own + // write landed keeps its advanced baseline - its pre-submit baseline no longer describes the file; one + // that was not written rolls back to the pre-submit baseline, so the user's deletion stays a deletion on + // retry instead of looking like an external addition the save must re-admit. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( +
+ + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("edit-allow-list")) + fireEvent.click(screen.getByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A display-setting difference between the buffer and the live state puts this save on the path that + // waits for the host's answer, without touching the buffered command lists. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The host wrote the allow list before the save failed, and never wrote the deny list: the refresh + // carries the allow list's new entry but the deny list's unchanged deletion target, then the answer + // reports the failure. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + }) + view.rerender() + answerSave(saveId, { success: false, error: "storage unavailable" }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + fireEvent.click(screen.getByTestId("save-button")) + const saves = updateSettingsPosts() + expect(saves).toHaveLength(2) + expect(saves.at(-1)).toEqual( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { allowedCommands: ["echo", "ls"], deniedCommands: ["rm -rf"] }, + updatedSettings: expect.objectContaining({ allowedCommands: ["echo", "ls"], deniedCommands: [] }), }), ) }) From 19abefb967275335c4f707e3b3362676b9bb1965 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 10 Nov 2026 19:45:03 +0100 Subject: [PATCH 14/52] fix: keep unsaved edits, shut down telemetry, pin deny precedence A save reported successful can still contain a command-list write the host rejected; each edited list now keeps its unsaved state until the refreshed state shows that list's own write, while an all-landed save still clears the dialog. Activation that aborts on a seed write shuts the telemetry client down before propagating the failure. Equal-length allow/deny matches resolve to deny, and tests pin that precedence and the composition keeping both entries alive. --- src/__tests__/extension.spec.ts | 61 +++++++ .../__tests__/commandScope.spec.ts | 39 +++++ src/extension.ts | 16 +- .../src/components/settings/SettingsView.tsx | 126 +++++++------- .../SettingsView.unsaved-changes.spec.tsx | 159 ++++++++++++++++++ 5 files changed, 336 insertions(+), 65 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 6ffc8f3708..770535512b 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -659,6 +659,67 @@ describe("extension.ts", () => { } }) + test("shuts down the telemetry service before propagating a seed rejection", async () => { + // The telemetry client is created and registered before the seed point, + // so a rejected seed must shut it down on the failure path: without + // `deactivate()` after a failed activation, an unshut-down client keeps + // sending events against an extension the host treats as inactive. + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), + })) + const teardownOrder: string[] = [] + vi.doMock("../services/zoo-code-auth", () => ({ + initZooCodeAuth: vi + .fn() + .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), + })) + const { TelemetryService } = await import("@roo-code/telemetry") + const shutdown = vi.mocked(TelemetryService.instance.shutdown) + // A never-settling shutdown: activation may only reject once the awaited + // teardown settles, pinning that the seed rejection never reaches the + // host ahead of it. + let settleShutdown: () => void = () => {} + shutdown.mockImplementation(() => { + teardownOrder.push("telemetry-shutdown") + return new Promise((resolve) => { + settleShutdown = resolve + }) + }) + try { + const { activate } = await import("../extension") + const activation = activate(mockContext) + let rejected = false + void activation.catch(() => { + rejected = true + }) + + // Both teardown steps run on the failure path, in order, exactly once. + await vi.waitFor(() => expect(teardownOrder).toEqual(["auth-listener-disposed", "telemetry-shutdown"])) + + // Still unrejected while the awaited shutdown is unsettled: the catch + // must not propagate the seed rejection before teardown completes. + expect(rejected).toBe(false) + + settleShutdown() + await expect(activation).rejects.toThrow("seed state write failed") + } finally { + shutdown.mockReset() + vi.doUnmock("../utils/seedAllowedCommands") + vi.doUnmock("../services/zoo-code-auth") + } + }) + + test("does not shut down telemetry when activation completes", async () => { + // Telemetry shutdown is failure-path only: a successfully activated + // extension owns the telemetry client until deactivate() runs. + const { TelemetryService } = await import("@roo-code/telemetry") + + const { activate } = await import("../extension") + await expect(activate(mockContext)).resolves.toBeDefined() + + expect(TelemetryService.instance.shutdown).not.toHaveBeenCalled() + }) + test("does not seed global state from an enforced workspace-scoped override", async () => { const vscode = await import("vscode") // The gate is on: an enforced workspace list replaces the default across diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index ee7a6e4104..fd66d2cfbd 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -15,6 +15,7 @@ import { splitCommandListScopes, workspaceCommandListsEnabled, } from "../commandScope" +import { getCommandDecision, getSingleCommandDecision } from "../commands" import { checkAutoApproval } from "../index" import { baseState, type State } from "./fixtures" @@ -530,6 +531,44 @@ it("resolveEffectiveCommandLists: shadows workspace entries case-insensitively, expect(effective.hiddenWorkspaceDeny).toEqual([]) }) +// When allow and deny entries both match a command with equal specificity, +// the deny decides: an ambiguous case fails closed rather than silently +// widening auto-approval. The direction is a deliberate policy, not an +// accident of the comparison — letting an allow win a tie would approve +// commands a deny entry claims, so reversing it requires an explicit policy +// decision, not a refactor that happens to flip the comparison's direction. +it("getSingleCommandDecision: resolves an equally specific allow/deny match to the deny", () => { + // "*" matches every command but counts as length 1, so it ties the + // one-character allow entry on "git status". + expect(getSingleCommandDecision("git status", ["g"], ["*"])).toBe("auto_deny") + // The same entry present in both lists ties trivially, and still denies. + expect(getSingleCommandDecision("git push", ["git push"], ["git push"])).toBe("auto_deny") +}) + +// Control for the tie: conflicts are decided by specificity, not by a +// blanket deny preference — the longer entry wins whichever side it sits on. +it("getSingleCommandDecision: lets the strictly more specific entry win on either side", () => { + expect(getSingleCommandDecision("git push origin", ["git push"], ["git"])).toBe("auto_approve") + expect(getSingleCommandDecision("git push origin", ["git"], ["git push"])).toBe("auto_deny") +}) + +it("resolveEffectiveCommandLists: keeps a workspace wildcard deny alive beside a global allow entry it only overlaps", () => { + // Composition drops a workspace entry only when a global entry covers + // every command it could match. "*" matches commands "g" cannot, so the + // deny survives into the effective pair and reaches the matcher beside + // the allow entry, where the equal-length tie decides "git status" as a + // deny: a global allow overlaps a wildcard deny's coverage without + // overriding it. + const effective = resolveEffectiveCommandLists(listScopes(["g"], []), listScopes([], ["*"]), true) + + expect(effective.allowed).toEqual(["g"]) + expect(effective.denied).toEqual(["*"]) + // Inside the global allow prefix, yet the equally specific deny decides. + expect(getCommandDecision("git status", effective.allowed, effective.denied)).toBe("auto_deny") + // Outside the global prefix the deny matches alone, so it still decides. + expect(getCommandDecision("docker ps", effective.allowed, effective.denied)).toBe("auto_deny") +}) + // Command-branch enforcement composes its allow/deny pair from the raw // global layers at the folder the task's cwd resolves to, so a task in // another root is judged by that root's lists rather than the window's diff --git a/src/extension.ts b/src/extension.ts index 01038adcdb..37b7c52b0c 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -185,9 +185,21 @@ export async function activate(context: vscode.ExtensionContext) { await seedCommandList(context.globalState, "allowedCommands") await seedCommandList(context.globalState, "deniedCommands") } catch (error) { - // Activation aborts here, so `deactivate()` may never run: release the - // secret-storage listener acquired above before propagating. + // Activation aborts here, and `deactivate()` is not guaranteed to run + // afterward, so this catch is the only teardown for everything + // initialized before the seed point: release the secret-storage + // listener and shut down the telemetry client registered above. + // Shutdown failures are logged rather than rethrown so they cannot mask + // the seed rejection; the service bounds its own drain and client-flush + // phases, so a stuck client cannot hang the host here. authSecretsListener.dispose() + try { + await telemetryService.shutdown() + } catch (shutdownError) { + outputChannel.appendLine( + `Failed to shut down telemetry service: ${shutdownError instanceof Error ? shutdownError.message : String(shutdownError)}`, + ) + } throw error } diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 3cd140c7d4..0ef43b2d39 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -188,9 +188,8 @@ const SettingsView = forwardRef(({ onDone, t // The live host state, read when a save settles without re-subscribing the result handler on every post. const latestExtensionState = useRef(extensionState) latestExtensionState.current = extensionState - // The save the host must answer records the baseline it stamped and the lists it submitted, so a save the - // host reports failed can reconcile each list's baseline against that list's own write outcome (see the - // save-result effect below). + // The save the host must answer records the baseline it stamped and the lists it submitted, so the + // save-result effect can reconcile each list's baseline against that list's own write outcome. const submittedListSave = useRef<{ baselined: [string[], string[]]; sent: [string[], string[]] } | undefined>( undefined, ) @@ -619,11 +618,11 @@ const SettingsView = forwardRef(({ onDone, t deniedCommands, workspaceCommandListsEnabled: cachedState.workspaceCommandListsEnabled, }) - // The stamp records what is on screen, so it moves at submit; a save the host reports failed then - // re-derives each list's entry from whether that list's own write landed (see the settle below). The - // lists' ownership of the buffer does not move at submit. A save the host answers commits the buffered - // lists only once the host says the write landed - committing at submit would let the state refresh - // that follows a rejected save overwrite the edit the user is still looking at. A save the host never + // The stamp records what is on screen, so it moves at submit; the settle below then re-derives each + // edited list's entry from whether that list's own write landed. The lists' ownership of the buffer + // does not move at submit. A save releases that hold - and with it the unsaved flag - only once the + // refresh shows every submitted write landed: releasing earlier would let the state refresh that + // follows a rejected list write overwrite the edit the user is still looking at. A save the host never // answers has no result to wait for, so it clears the hold at submit. if (!saveId) { commandListsTouched.current = false @@ -637,64 +636,65 @@ const SettingsView = forwardRef(({ onDone, t const settle = (success: boolean) => { setPendingSaveId(undefined) - if (success) { - // Every list's write landed, so the baseline the submit advanced is kept for all of them. - submittedListSave.current = undefined - // An edit made while the save was in flight is not in what was sent: it stays unsaved. A failed save - // keeps the buffered lists holding off external updates too, so the host's refresh after a rejected - // write cannot replace the edit the user is looking at. - if (latestCachedState.current === sentState.current) { - commandListsTouched.current = false - setChangeDetected(false) - } - return - } - // A rejected or timed-out save reports one outcome for the whole payload, yet each command list may - // have reached a different write result before it failed: the save writes setting by setting, so an - // earlier failure (or a timeout) can land after one list was written and before another. The refresh - // the host posts before its answer carries each list's configuration result, so a list equal to what - // was submitted records that its own write landed: for that list the baseline stays advanced, since - // restoring the pre-submit baseline of a written list claims an entry the file no longer holds was - // displayed. Every other edited list's baseline rolls back to what was displayed before the submit, - // so a deletion whose write never ran is still classified as a user deletion on retry instead of an - // external addition to re-admit. Lists the save did not edit keep the stamp's baseline, which the - // external-update merge already maintains. + // The answer's flag reports one outcome for the whole payload, but the payload's lists are written + // separately, and a report of success says only that the other settings stored: a rejected + // command-list write is absent from the flag. Each edited list's own write result comes from the + // refresh the host posts before its answer, so every save reconciles each list against what was + // submitted: a list equal to what was submitted records that its own write landed, and its baseline + // stays advanced, since restoring the pre-submit baseline of a written list claims an entry the file + // no longer holds was displayed. Every other edited list's baseline rolls back to what was displayed + // before the submit, so a deletion whose write never ran is still classified as a user deletion on + // retry instead of an external addition to re-admit. Lists the save did not edit keep the stamp's + // baseline, which the external-update merge already maintains. const save = submittedListSave.current submittedListSave.current = undefined - if (!save) { - return + let everyEditedWriteLanded = true + if (save) { + const [stampAllowed, stampDenied, stampGate] = JSON.parse(lastDisplayedCommandSnapshot.current) as [ + string[], + string[], + boolean, + ] + const reconcileList = ( + baselined: string[], + sent: string[], + refreshed: string[] | undefined, + stamped: string[], + ) => + commandListsEquivalent(baselined, sent) + ? stamped + : commandListsEquivalent(refreshed, sent) + ? sent + : baselined + const writeLanded = (baselined: string[], sent: string[], refreshed: string[] | undefined) => + commandListsEquivalent(baselined, sent) || commandListsEquivalent(refreshed, sent) + everyEditedWriteLanded = + writeLanded(save.baselined[0], save.sent[0], latestExtensionState.current.allowedCommands) && + writeLanded(save.baselined[1], save.sent[1], latestExtensionState.current.deniedCommands) + lastDisplayedCommandSnapshot.current = commandListSnapshot({ + allowedCommands: reconcileList( + save.baselined[0], + save.sent[0], + latestExtensionState.current.allowedCommands, + stampAllowed, + ), + deniedCommands: reconcileList( + save.baselined[1], + save.sent[1], + latestExtensionState.current.deniedCommands, + stampDenied, + ), + workspaceCommandListsEnabled: stampGate, + }) + } + // The unsaved flag goes off only when nothing is left unsaved: an edit made while the save was in + // flight is not in what was sent, and an edited list whose write never landed still holds its edit. + // In both cases the buffered lists keep holding off external updates, so a host refresh cannot + // replace the edit the user is looking at. + if (success && everyEditedWriteLanded && latestCachedState.current === sentState.current) { + commandListsTouched.current = false + setChangeDetected(false) } - const [stampAllowed, stampDenied, stampGate] = JSON.parse(lastDisplayedCommandSnapshot.current) as [ - string[], - string[], - boolean, - ] - const reconcileList = ( - baselined: string[], - sent: string[], - refreshed: string[] | undefined, - stamped: string[], - ) => - commandListsEquivalent(baselined, sent) - ? stamped - : commandListsEquivalent(refreshed, sent) - ? sent - : baselined - lastDisplayedCommandSnapshot.current = commandListSnapshot({ - allowedCommands: reconcileList( - save.baselined[0], - save.sent[0], - latestExtensionState.current.allowedCommands, - stampAllowed, - ), - deniedCommands: reconcileList( - save.baselined[1], - save.sent[1], - latestExtensionState.current.deniedCommands, - stampDenied, - ), - workspaceCommandListsEnabled: stampGate, - }) } const onResult = (event: MessageEvent) => { diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index fa673ea465..34c264270e 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -1109,6 +1109,14 @@ describe("SettingsView - Unsaved Changes Detection", () => { fireEvent.click(screen.getByTestId("save-button")) expect(lastSaveRequestId(postMessage)).toBeDefined() // this save waits for the host's answer + // The host writes the list before it answers, so the refresh carries the submitted entry; that + // observation, not the answer alone, is what releases the hold. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["git status"], + showRelativeTimes: false, + }) + view.rerender() answerSave(lastSaveRequestId(postMessage), { success: true }) await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) @@ -1123,6 +1131,157 @@ describe("SettingsView - Unsaved Changes Detection", () => { ) }) + it("keeps a silently rejected list write dirty and rolls back only its baseline when the host reports success", async () => { + // The answer reports one outcome for the whole payload, so a rejected command-list write can arrive + // with success: true. Each edited list's own write result comes from the refresh the host posts before + // its answer: the allow list carries the submitted entry, so its baseline stays advanced; the deny + // list comes back unchanged, so its deletion rolls back to the pre-submit baseline and the flag keeps + // reporting the edit as unsaved instead of silently dropping it. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("edit-allow-list")) + fireEvent.click(screen.getByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A display-setting difference between the buffer and the live state puts this save on the path that + // waits for the host's answer, without touching the buffered command lists. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The host wrote the allow list but silently rejected the deny-list write, and still answers success: + // the refresh carries the allow list's new entry and the deny list's old entry back. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + }) + view.rerender() + answerSave(saveId, { success: true }) + + // The unlanded write keeps the flag on, and the buffered deletion keeps holding external updates back. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + deniedCommands: ["docker"], + showRelativeTimes: false, + }) + view.rerender() + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify([])) + + // Retrying classifies each list by its own write result: the landed allow list keeps its advanced + // baseline, and the rolled-back deny baseline keeps the deletion a user deletion to re-apply. + fireEvent.click(screen.getByTestId("save-button")) + const saves = updateSettingsPosts() + expect(saves).toHaveLength(2) + expect(saves.at(-1)).toEqual( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { allowedCommands: ["echo", "ls"], deniedCommands: ["rm -rf"] }, + updatedSettings: expect.objectContaining({ allowedCommands: ["echo", "ls"], deniedCommands: [] }), + }), + ) + }) + + it("clears the unsaved flag and releases every list when the refresh shows all writes landed", async () => { + // A save whose every edited list appears landed in the host's refresh clears the flag and + // releases the buffered lists to external updates. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("edit-allow-list")) + fireEvent.click(screen.getByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The host wrote both lists before answering: the refresh carries both submitted lists. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + deniedCommands: [], + showRelativeTimes: false, + }) + view.rerender() + answerSave(saveId, { success: true }) + + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // The lists committed, so a later host update is no longer an in-flight edit being stomped. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + deniedCommands: ["curl"], + showRelativeTimes: false, + }) + view.rerender() + await waitFor(() => expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["curl"]))) + expect(screen.getByTestId("save-button")).toBeDisabled() // a folded external update is not a user edit + }) + it("discards IO Intelligence cached edits and restores the extension values", async () => { const onDone = vi.fn() ;(useExtensionState as ReturnType).mockReturnValue({ From a243fee7abcf9fb14340f7defbfd455a316fc213 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 10 Nov 2026 22:55:10 +0100 Subject: [PATCH 15/52] fix(auto-approve): honor user-level command precedence and root paths A matching user-level entry now decides a command before any workspace entry, so a project deny can no longer outrank the user's own allow; deny still wins ties within each layer. Workspace folders registered at a filesystem root (C:\ or /) keep their workspace-layer policy enforced instead of silently dropped. Add a test for a telemetry shutdown that rejects on the seed-failure activation path: the seed error propagates and the shutdown failure is logged. --- src/__tests__/extension.spec.ts | 43 +++ .../__tests__/commandScope.spec.ts | 270 +++++++++++++++++- src/core/auto-approval/commandScope.ts | 94 ++++-- src/core/auto-approval/index.ts | 84 +++++- 4 files changed, 454 insertions(+), 37 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 770535512b..84890249e0 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -709,6 +709,49 @@ describe("extension.ts", () => { } }) + test("logs a rejected telemetry shutdown without masking the seed rejection", async () => { + // The seed-failure catch awaits the shutdown inside its own try/catch, so a + // rejecting shutdown must be logged and the seed error must still reach the + // host as the activation failure. A regression that rethrows the shutdown + // error hides why activation aborted; one that swallows it silently loses + // the only record of the telemetry teardown failure. + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), + })) + const teardownOrder: string[] = [] + vi.doMock("../services/zoo-code-auth", () => ({ + initZooCodeAuth: vi + .fn() + .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), + })) + const { TelemetryService } = await import("@roo-code/telemetry") + const shutdown = vi.mocked(TelemetryService.instance.shutdown) + // Distinct from the seed error so any masking of the seed rejection is visible. + shutdown.mockImplementation(() => { + teardownOrder.push("telemetry-shutdown") + return Promise.reject(new Error("shutdown drain failed")) + }) + try { + const vscode = await import("vscode") + const { activate } = await import("../extension") + + await expect(activate(mockContext)).rejects.toThrow("seed state write failed") + + // The shutdown failure surfaces through the appendLine idiom, with its + // error text, instead of replacing the seed rejection the host receives. + const channel = vi.mocked(vscode.window.createOutputChannel).mock.results.at(-1)?.value + expect(channel?.appendLine).toHaveBeenCalledWith( + "Failed to shut down telemetry service: shutdown drain failed", + ) + // Teardown still runs in order on this path: listener released before the shutdown call. + expect(teardownOrder).toEqual(["auth-listener-disposed", "telemetry-shutdown"]) + } finally { + shutdown.mockReset() + vi.doUnmock("../utils/seedAllowedCommands") + vi.doUnmock("../services/zoo-code-auth") + } + }) + test("does not shut down telemetry when activation completes", async () => { // Telemetry shutdown is failure-path only: a successfully activated // extension owns the telemetry client until deactivate() runs. diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index fd66d2cfbd..337d61c01c 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -9,13 +9,14 @@ import { Package } from "../../../shared/package" import { makeUri, makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { commandListFolderForResource, + getEffectiveCommandDecision, readCommandListScopes, resolveEffectiveCommandLists, resolveWorkspaceWriteTarget, splitCommandListScopes, workspaceCommandListsEnabled, } from "../commandScope" -import { getCommandDecision, getSingleCommandDecision } from "../commands" +import { getSingleCommandDecision } from "../commands" import { checkAutoApproval } from "../index" import { baseState, type State } from "./fixtures" @@ -531,11 +532,14 @@ it("resolveEffectiveCommandLists: shadows workspace entries case-insensitively, expect(effective.hiddenWorkspaceDeny).toEqual([]) }) -// When allow and deny entries both match a command with equal specificity, -// the deny decides: an ambiguous case fails closed rather than silently -// widening auto-approval. The direction is a deliberate policy, not an -// accident of the comparison — letting an allow win a tie would approve -// commands a deny entry claims, so reversing it requires an explicit policy +// A user-level (global) entry decides every command it matches: a workspace +// entry applies only where no global entry matches, so a project file can +// fill gaps in the user's policy but never outrank it. Within a single layer +// the conflict rule is specificity — the longest match wins — and when allow +// and deny entries match with equal specificity, the deny decides: an +// ambiguous case fails closed rather than silently widening auto-approval. +// Letting an allow win a within-layer tie would approve commands a deny entry +// in the same layer claims, so reversing it requires an explicit policy // decision, not a refactor that happens to flip the comparison's direction. it("getSingleCommandDecision: resolves an equally specific allow/deny match to the deny", () => { // "*" matches every command but counts as length 1, so it ties the @@ -552,21 +556,55 @@ it("getSingleCommandDecision: lets the strictly more specific entry win on eithe expect(getSingleCommandDecision("git push origin", ["git"], ["git push"])).toBe("auto_deny") }) -it("resolveEffectiveCommandLists: keeps a workspace wildcard deny alive beside a global allow entry it only overlaps", () => { +it("resolveEffectiveCommandLists: keeps a workspace wildcard deny alive for the commands no global entry matches", () => { // Composition drops a workspace entry only when a global entry covers // every command it could match. "*" matches commands "g" cannot, so the - // deny survives into the effective pair and reaches the matcher beside - // the allow entry, where the equal-length tie decides "git status" as a - // deny: a global allow overlaps a wildcard deny's coverage without - // overriding it. + // deny survives into the effective pair. Deciding then follows the layer + // precedence: the global entry decides every command it matches, and the + // workspace deny applies exactly where the global layer is silent. const effective = resolveEffectiveCommandLists(listScopes(["g"], []), listScopes([], ["*"]), true) expect(effective.allowed).toEqual(["g"]) expect(effective.denied).toEqual(["*"]) - // Inside the global allow prefix, yet the equally specific deny decides. - expect(getCommandDecision("git status", effective.allowed, effective.denied)).toBe("auto_deny") - // Outside the global prefix the deny matches alone, so it still decides. - expect(getCommandDecision("docker ps", effective.allowed, effective.denied)).toBe("auto_deny") + // Inside the global allow prefix the global layer decides: the user's own + // allow outranks a project wildcard deny. + expect(getEffectiveCommandDecision("git status", effective)).toBe("auto_approve") + // Outside the global prefix the deny matches alone, so the workspace + // layer decides. + expect(getEffectiveCommandDecision("docker ps", effective)).toBe("auto_deny") +}) + +it("getEffectiveCommandDecision: lets a global deny decide a command a workspace wildcard allow also matches", () => { + // The precedence is symmetric: a user-level deny outranks a project's + // allow exactly as a user-level allow outranks a project's deny, while + // the workspace allow still decides the commands the user's layer is + // silent about. + const effective = resolveEffectiveCommandLists(listScopes([], ["*"]), listScopes(["g"], []), true) + + expect(getEffectiveCommandDecision("git status", effective)).toBe("auto_deny") + expect(getEffectiveCommandDecision("docker ps", effective)).toBe("auto_approve") +}) + +it("getEffectiveCommandDecision: lets the workspace layer decide when no global entry matches", () => { + // The global layers say nothing about "rm": the kept workspace deny + // decides alone, while the global allow still decides the commands it + // matches. A global entry matching nothing leaves the workspace layer in + // full charge of the commands it covers. + const effective = resolveEffectiveCommandLists(listScopes(["git"], []), listScopes([], ["rm"]), true) + + expect(getEffectiveCommandDecision("git status", effective)).toBe("auto_approve") + expect(getEffectiveCommandDecision("rm -rf tmp", effective)).toBe("auto_deny") +}) + +it("getEffectiveCommandDecision: keeps within-layer conflict resolution in each layer", () => { + // Within the workspace layer an equal-length allow/deny conflict still + // denies: layer precedence orders the layers, not the entries of a layer. + const inWorkspace = resolveEffectiveCommandLists(listScopes([], ["g"]), listScopes([], ["*"]), true) + expect(getEffectiveCommandDecision("git status", inWorkspace)).toBe("auto_deny") + // The same holds within the global layer: the wildcard deny ties the + // one-character allow there too. + const inGlobal = resolveEffectiveCommandLists(listScopes(["g"], []), listScopes(["*"], []), true) + expect(getEffectiveCommandDecision("git status", inGlobal)).toBe("auto_deny") }) // Command-branch enforcement composes its allow/deny pair from the raw @@ -804,6 +842,181 @@ it("checkAutoApproval command: in a single-folder window reads exactly the same expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) }) +it("checkAutoApproval command: enforces the deny entries of a filesystem-root workspace folder", async () => { + vi.clearAllMocks() + // A window opened directly on the filesystem root ("/" or the Windows + // drive root) is a workspace folder whose children must still resolve to + // it: failing containment there would drop the root's deny entries + // silently — the exact fail-open the folder lookup must not have. + const rootPath = path.parse(process.cwd()).root + const rootUri = makeUri(rootPath) + workspaceState.workspaceFolders = [{ uri: rootUri }] + workspaceState.foldersByPath.set(rootPath, rootUri) + mockFolderConfigurations({ [rootPath]: { gate: true, deny: ["echo"] } }) + + const result = await checkAutoApproval({ + // Empty raw global layers: only the root folder's layer can decide. + state: taskFolderState([]), + cwd: path.join(rootPath, "srv"), + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, rootUri) +}) + +// Enforcement decides commands through the layer split the composition +// carries: wherever a global (user-level) entry matches, the global layer +// decides, and the workspace layer decides only the commands no global entry +// matches. A single-character global entry ties a workspace wildcard entry in +// the merged pair's longest-prefix comparison, so a merged-pair matcher alone +// could not reproduce that precedence; these cases pin it through the public +// enforcement boundary. +const layeredState = (globalAllow: string[], globalDeny: string[] = []): State => ({ + ...taskFolderState(["baked"]), + globalAllowedCommands: globalAllow, + globalDeniedCommands: globalDeny, +}) + +it("checkAutoApproval command: lets a global allow entry decide a command a workspace wildcard deny also matches", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["*"] }, + [folderB.fsPath]: { gate: true, deny: ["*"] }, + }) + + const result = await checkAutoApproval({ + state: layeredState(["g"]), + cwd: folderB.fsPath, + ask: "command", + text: "git status", + }) + + // The project's wildcard deny matches "git status" too, but the user's own + // allow entry matches it, so the global layer decides: approve. + expect(result).toEqual({ decision: "approve" }) +}) + +it("checkAutoApproval command: lets the workspace wildcard deny decide the commands no global entry matches", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["*"] }, + [folderB.fsPath]: { gate: true, deny: ["*"] }, + }) + + const result = await checkAutoApproval({ + state: layeredState(["g"]), + cwd: folderB.fsPath, + ask: "command", + text: "docker ps", + }) + + // "docker ps" matches no global entry, so the kept workspace deny decides + // it — the global allow of "g" fills no gap here, and the project fills its + // own. + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "docker ps", pattern: "*" } }) +}) + +it("checkAutoApproval command: lets a global deny entry veto a command a workspace wildcard allow also matches", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, allow: ["*"] }, + [folderB.fsPath]: { gate: true, allow: ["*"] }, + }) + + const state = layeredState([], ["g"]) + + const denied = await checkAutoApproval({ state, cwd: folderB.fsPath, ask: "command", text: "git status" }) + expect(denied).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "git status", pattern: "g" } }) + + // The precedence is symmetric: outside the global deny's prefix the + // project's wildcard allow still decides. + const allowed = await checkAutoApproval({ state, cwd: folderB.fsPath, ask: "command", text: "docker ps" }) + expect(allowed).toEqual({ decision: "approve" }) +}) + +it("checkAutoApproval command: keeps the global-only degradation for a cwd naming no root under the layered composition", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["*"] }, + [folderB.fsPath]: { gate: true, deny: ["*"] }, + }) + + const state = layeredState(["g"]) + + const globalWitness = await checkAutoApproval({ + state, + cwd: "/mock/removed-folder", + ask: "command", + text: "git status", + }) + expect(globalWitness).toEqual({ decision: "approve" }) + + // Dropping the workspace layer for an unmatched cwd must not promote the + // command to an approval: with no global match either, the plain prompt + // stands, exactly as under the pre-composed pair. + const unmatched = await checkAutoApproval({ + state, + cwd: "/mock/removed-folder", + ask: "command", + text: "docker ps", + }) + expect(unmatched).toEqual({ decision: "ask" }) +}) + +it("checkAutoApproval command: decides a command in a filesystem-root workspace folder by both layers", async () => { + vi.clearAllMocks() + // The root folder's deny must still reach enforcement for a child cwd + // (containment keeps the layer), and the global layer must still outrank + // it where it matches — folder containment and layer precedence together. + const rootPath = path.parse(process.cwd()).root + const rootUri = makeUri(rootPath) + workspaceState.workspaceFolders = [{ uri: rootUri }] + workspaceState.foldersByPath.set(rootPath, rootUri) + mockFolderConfigurations({ [rootPath]: { gate: true, deny: ["*"] } }) + + const state = layeredState(["g"]) + const cwd = path.join(rootPath, "srv") + + const globalWitness = await checkAutoApproval({ state, cwd, ask: "command", text: "git status" }) + expect(globalWitness).toEqual({ decision: "approve" }) + + const folderWitness = await checkAutoApproval({ state, cwd, ask: "command", text: "docker ps" }) + expect(folderWitness).toEqual({ + decision: "deny", + autoDeny: { kind: "denylist", command: "docker ps", pattern: "*" }, + }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, rootUri) +}) + +it("checkAutoApproval command: decides each sub-command of a chain by its own matching layer", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["*"] }, + [folderB.fsPath]: { gate: true, deny: ["*"] }, + }) + + const result = await checkAutoApproval({ + state: layeredState(["g"]), + cwd: folderB.fsPath, + ask: "command", + text: "git status && docker ps", + }) + + // Chain aggregation holds across layers — any denial denies the whole + // command — while each sub-command is decided by its own layer: "git + // status" is approved by the global allow while "docker ps" is denied by + // the workspace wildcard, and the denial names the denied sub-command, not + // the approved one. + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "docker ps", pattern: "*" } }) +}) + // Creating a directory symlink on Windows needs developer mode or elevation; a // junction needs neither and is resolved by realpath like a POSIX link, so the // fixture tries a symlink first and falls back to a junction. Where neither can @@ -929,6 +1142,33 @@ it("commandListFolderForResource: matches a cwd equal to the root's real path", expect(commandListFolderForResource(rootPath)).toBe(rootUri) }) +it("commandListFolderForResource: matches a cwd inside a filesystem-root workspace folder", () => { + vi.clearAllMocks() + // A filesystem root — "/" on POSIX, "C:\" on Windows — is a legal + // workspace folder and already ends in a separator. Appending another + // separator would leave no child path able to match the root, dropping + // that folder's command-list layer out of enforcement silently. + const rootPath = path.parse(process.cwd()).root + const rootUri = makeUri(rootPath) + workspaceState.workspaceFolders = [{ uri: rootUri }] + + expect(commandListFolderForResource(path.join(rootPath, "srv", "app"))).toBe(rootUri) + // The root itself remains a match through the equality branch. + expect(commandListFolderForResource(rootPath)).toBe(rootUri) +}) + +it("commandListFolderForResource: matches a child of a folder registered with a trailing separator", () => { + vi.clearAllMocks() + // The real-path fallback passes a registered trailing separator through + // unresolved roots, so containment must treat an already-separated root + // as its own child prefix instead of doubling the separator. + const rootPath = path.join(path.sep + "mock", "root") + path.sep + const rootUri = makeUri(rootPath) + workspaceState.workspaceFolders = [{ uri: rootUri }] + + expect(commandListFolderForResource(path.join(rootPath, "sub"))).toBe(rootUri) +}) + it("commandListFolderForResource: returns undefined when no workspace folder is open", () => { vi.clearAllMocks() workspaceState.foldersByPath.clear() diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 365756454c..fa5736c5f5 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -5,7 +5,12 @@ import { DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED } from "@roo-code/types" import * as vscode from "vscode" import { Package } from "../../shared/package" -import { isShadowedByAnyEntry } from "./commands" +import { + type CommandDecision, + findLongestPrefixMatch, + getSingleCommandDecision, + isShadowedByAnyEntry, +} from "./commands" export type CommandListConfigKey = "allowedCommands" | "deniedCommands" @@ -95,7 +100,12 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin let matchedLength = 0 for (const candidate of vscode.workspace.workspaceFolders ?? []) { const rootPath = realPathOrRegistered(candidate.uri.fsPath) - if ((cwd === rootPath || cwd.startsWith(rootPath + path.sep)) && rootPath.length > matchedLength) { + // A filesystem root (`/`, `C:\`) already ends in a separator; + // appending a second one (`//`, `C:\\`) would leave no child path + // able to match the root, so the separator is added only where the + // root lacks one. + const childPrefix = rootPath.endsWith(path.sep) ? rootPath : rootPath + path.sep + if ((cwd === rootPath || cwd.startsWith(childPrefix)) && rootPath.length > matchedLength) { match = candidate.uri matchedLength = rootPath.length } @@ -291,6 +301,17 @@ export function workspaceCommandListsEnabled(): boolean { export interface EffectiveCommandLists { allowed: string[] denied: string[] + /** The global layer's allow entries: they decide every command they match. */ + globalAllow: string[] + /** Deny-side counterpart of {@link globalAllow}. */ + globalDeny: string[] + /** + * Workspace allow entries the gate and shadowing kept; they decide only + * commands no global entry matches (see {@link getEffectiveCommandDecision}). + */ + keptWorkspaceAllow: string[] + /** Deny-side counterpart of {@link keptWorkspaceAllow}. */ + keptWorkspaceDeny: string[] /** * Workspace allow entries absent from the effective allowlist — hidden by * the gate or shadowed by a global entry — which a dialog save must not be @@ -302,15 +323,23 @@ export interface EffectiveCommandLists { } /** - * Composes the raw per-key layers into the pair of lists to enforce and - * display, keeping display byte-equal to enforcement. + * Composes the raw per-key layers into the pair of lists the settings dialog + * displays, together with the layer split {@link getEffectiveCommandDecision} + * matches commands against, so display and enforcement draw on one composition + * pass and cannot drift. * * Gate off: the workspace layers contribute nothing and the global layers are - * effective verbatim. Gate on: a workspace entry survives only when no entry - * of either global list shadows it, so a global entry decides every command it - * matches while workspace entries apply where the global layer is silent. - * Shadowing is cross-directional because a global allow entry silences a - * workspace deny entry (and vice versa) just as much as a same-list shadow. + * effective verbatim. Gate on: a workspace entry survives in the pair only + * when no entry of either global list shadows it — an entry whose every match + * a global entry also matches can decide nothing on its own, and keeping it + * out of the pair keeps the dialog honest about what the global layer already + * covers. A surviving entry may still overlap a global entry without being + * shadowed by it (a wildcard deny matches commands no global prefix reaches); + * the overlap is harmless because {@link getEffectiveCommandDecision} lets the + * global layer decide every command it matches, so a workspace entry never + * outranks a global match. Shadowing is cross-directional because a global + * allow entry silences a workspace deny entry (and vice versa) just as much as + * a same-list shadow. * * Composing here — not inside {@link readCommandListScopes} — keeps the raw * layers intact for the save path, which derives the write split from them and @@ -319,32 +348,65 @@ export interface EffectiveCommandLists { * @param allowScopes - Raw `allowedCommands` layers from readCommandListScopes. * @param denyScopes - Raw `deniedCommands` layers from readCommandListScopes. * @param enabled - The value of the `workspaceCommandListsEnabled` gate. - * @returns The effective allow/deny lists and the workspace entries hidden - * from each. + * @returns The effective allow/deny lists, the per-layer split behind them, and + * the workspace entries hidden from each. */ export function resolveEffectiveCommandLists( allowScopes: CommandListScopes, denyScopes: CommandListScopes, enabled: boolean, ): EffectiveCommandLists { - const globalEntries = [...allowScopes.global, ...denyScopes.global] + const globalAllow = allowScopes.global + const globalDeny = denyScopes.global + const globalEntries = [...globalAllow, ...globalDeny] - const keptAllow = enabled + const keptWorkspaceAllow = enabled ? allowScopes.workspace.filter((entry) => !isShadowedByAnyEntry(entry, globalEntries)) : [] - const keptDeny = enabled ? denyScopes.workspace.filter((entry) => !isShadowedByAnyEntry(entry, globalEntries)) : [] + const keptWorkspaceDeny = enabled + ? denyScopes.workspace.filter((entry) => !isShadowedByAnyEntry(entry, globalEntries)) + : [] - const allowed = [...new Set([...allowScopes.global, ...keptAllow])] - const denied = [...new Set([...denyScopes.global, ...keptDeny])] + const allowed = [...new Set([...globalAllow, ...keptWorkspaceAllow])] + const denied = [...new Set([...globalDeny, ...keptWorkspaceDeny])] return { allowed, denied, + globalAllow, + globalDeny, + keptWorkspaceAllow, + keptWorkspaceDeny, hiddenWorkspaceAllow: allowScopes.workspace.filter((entry) => !allowed.includes(entry)), hiddenWorkspaceDeny: denyScopes.workspace.filter((entry) => !denied.includes(entry)), } } +/** + * Decides a single command under the precedence the command layers are + * authored with: wherever a global (user-level) entry — allow or deny — + * matches the command, the global layer decides it, so a user's own allow + * outranks a project's deny and a user's own deny outranks a project's allow; + * workspace entries apply only where no global entry matches. Within either + * layer the established matcher semantics stand: the longest matching prefix + * wins and an equal-length allow/deny conflict denies. + * + * The scope is one command: a chained command is decided per sub-command, and + * chain splitting lives with the command matcher. + * + * @param command - The single (unchained) command to decide. + * @param effective - A composition from {@link resolveEffectiveCommandLists}. + * @returns The decision produced by the matching layer. + */ +export function getEffectiveCommandDecision(command: string, effective: EffectiveCommandLists): CommandDecision { + // One longest-prefix probe asks the only question the precedence turns on: + // does the global layer hold any match for this command at all? + if (findLongestPrefixMatch(command, [...effective.globalAllow, ...effective.globalDeny]) !== null) { + return getSingleCommandDecision(command, effective.globalAllow, effective.globalDeny) + } + return getSingleCommandDecision(command, effective.keptWorkspaceAllow, effective.keptWorkspaceDeny) +} + function sanitizeCommandList(list: unknown): string[] { if (!Array.isArray(list)) { return [] diff --git a/src/core/auto-approval/index.ts b/src/core/auto-approval/index.ts index de9bdcede1..6c03454790 100644 --- a/src/core/auto-approval/index.ts +++ b/src/core/auto-approval/index.ts @@ -12,11 +12,20 @@ import type { DcgDecision } from "../../services/destructive-command-guard/runne import { ClineAskResponse } from "../../shared/WebviewMessage" +import { parseCommand } from "../../shared/parse-command" + import { isWriteToolAction, isReadOnlyToolAction } from "./tools" import { isMcpToolAlwaysAllowed } from "./mcp" -import { containsDangerousSubstitution, getCommandDecisionDetailed } from "./commands" import { + type CommandDecisionDetail, + containsDangerousSubstitution, + findLongestPrefixMatch, + getCommandDecisionDetailed, +} from "./commands" +import { + type EffectiveCommandLists, commandListFolderForResource, + getEffectiveCommandDecision, readCommandListScopes, resolveEffectiveCommandLists, workspaceCommandListsEnabled, @@ -146,6 +155,66 @@ function isWriteAllowedByPatterns( ) } +/** + * Same chain aggregation as `getCommandDecisionDetailed` — split into + * sub-commands, any denial denies the whole command, a dangerous substitution + * forces the user prompt, and approval needs every sub-command approved — but + * each sub-command is decided by `getEffectiveCommandDecision`, so the global + * layer decides every command it matches and workspace entries apply only + * where no global entry matches. A flat merged pair cannot express that + * precedence: a workspace wildcard deny ties a global prefix allow in the + * matcher's longest-prefix comparison, so composition would have to drop one + * layer's entries to break the tie and lose its verdicts elsewhere. + * + * The aggregation mirrors `getCommandDecisionDetailed` on purpose: malformed + * parsing, redirection sanitization, the substitution veto, and the + * offending-command/matched-pattern reporting must not drift between the two + * paths — only the per-sub-command leaf decision differs. Where a sub-command + * has no global match at all, both paths reach the same outcome, because the + * flat pair is the union of exactly the layers the split evaluates. + */ +function getLayerScopedCommandDecisionDetailed( + command: string, + effective: EffectiveCommandLists, +): CommandDecisionDetail { + if (!command?.trim()) { + return { decision: "auto_approve" } + } + + const { commands: subCommands, parseError } = parseCommand(command) + if (parseError !== null) { + return { decision: "malformed_command", offendingCommand: command, parseError: parseError.message } + } + + const sanitizedCommands = subCommands.map((cmd) => cmd.replace(/\d*>&\d*/, "").trim()) + + const decisions = sanitizedCommands.map((cmd) => getEffectiveCommandDecision(cmd, effective)) + + const denyIndex = decisions.indexOf("auto_deny") + if (denyIndex !== -1) { + const offendingCommand = sanitizedCommands[denyIndex] + const lowerMatch = findLongestPrefixMatch(offendingCommand, effective.denied) + // Prefer the original-cased pattern the user typed, falling back to the + // case-insensitive match itself. + const matchedPattern = + effective.denied.find((pattern) => pattern.toLowerCase() === lowerMatch) ?? lowerMatch ?? undefined + + return { decision: "auto_deny", offendingCommand, matchedPattern } + } + + if (containsDangerousSubstitution(command)) { + return { decision: "ask_user" } + } + + if (decisions.every((decision) => decision === "auto_approve")) { + return { decision: "auto_approve" } + } + + const askIndex = decisions.indexOf("ask_user") + + return { decision: "ask_user", offendingCommand: askIndex !== -1 ? sanitizedCommands[askIndex] : undefined } +} + export type CheckAutoApprovalResult = | { decision: "approve" } /** @@ -349,11 +418,14 @@ export async function checkAutoApproval({ ) : { allowed: state.allowedCommands || [], denied: state.deniedCommands || [] } - const { decision, offendingCommand, matchedPattern, parseError } = getCommandDecisionDetailed( - text, - effectiveLists.allowed, - effectiveLists.denied, - ) + // The layered composition carries the per-layer split, so each + // sub-command goes through getEffectiveCommandDecision; the + // pre-composed fallback pair carries no layers and keeps the flat + // matcher. + const { decision, offendingCommand, matchedPattern, parseError } = + "globalAllow" in effectiveLists + ? getLayerScopedCommandDecisionDetailed(text, effectiveLists) + : getCommandDecisionDetailed(text, effectiveLists.allowed, effectiveLists.denied) if (decision === "auto_approve") { return { decision: "approve" } From 54f0a6a760b854aa573a1d5c68e85eefa0bc0f13 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Wed, 11 Nov 2026 02:18:05 +0100 Subject: [PATCH 16/52] fix(extension): tear down debug proxy resources on failed activation initializeNetworkProxy returns a disposable over its three debug-mode resources; outside debug mode it is a no-op, and the resources stay on context.subscriptions. Failed-activation teardown disposes auth, telemetry, and proxy resources in reverse acquisition order, then rethrows the seed rejection. Adds layered command-policy coverage via public checkAutoApproval. --- src/__tests__/extension.spec.ts | 85 +++++++++ .../__tests__/commandScope.spec.ts | 163 ++++++++++++++++++ src/extension.ts | 24 ++- src/utils/__tests__/networkProxy.spec.ts | 78 +++++++++ src/utils/networkProxy.ts | 98 +++++++---- 5 files changed, 409 insertions(+), 39 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 84890249e0..37fc085c49 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -45,6 +45,7 @@ vi.mock("vscode", () => ({ }, ExtensionMode: { Production: 1, + Development: 2, }, })) @@ -752,6 +753,90 @@ describe("extension.ts", () => { } }) + test("disposes the network proxy resources when seeding rejects activation", async () => { + // The debug-proxy resources are initialized before the seed point, and the host + // does not guarantee `deactivate()` after a failed activation, so the failure path + // must release them too: a retained configuration listener would let a + // `debugProxy.*` toggle re-apply proxy configuration inside a dead extension. + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), + })) + const teardownOrder: string[] = [] + const proxyDispose = vi.fn(() => void teardownOrder.push("proxy-disposed")) + vi.doMock("../utils/networkProxy", () => ({ + // The initializer resolves to the aggregate disposable covering the + // configuration listener, override cleanup, and fetch-patch restore. + initializeNetworkProxy: vi.fn().mockResolvedValue({ dispose: proxyDispose }), + getSystemProxyUrl: vi.fn().mockReturnValue(undefined), + isProxyEnabled: vi.fn().mockReturnValue(false), + createProxyRoutingRequestHandler: vi.fn().mockReturnValue(undefined), + })) + vi.doMock("../services/zoo-code-auth", () => ({ + initZooCodeAuth: vi + .fn() + .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), + })) + const { TelemetryService } = await import("@roo-code/telemetry") + const shutdown = vi.mocked(TelemetryService.instance.shutdown) + shutdown.mockImplementation(() => { + teardownOrder.push("telemetry-shutdown") + return Promise.resolve() + }) + try { + // Debug mode is the only mode in which the proxy initializer acquires + // resources, so it is the mode the failed-activation teardown applies to. + const vscode = await import("vscode") + const devContext = { ...mockContext, extensionMode: vscode.ExtensionMode.Development } + + const { activate } = await import("../extension") + await expect(activate(devContext)).rejects.toThrow("seed state write failed") + + // Strict reverse acquisition order: the proxy initializes first, telemetry + // second, the auth listener last, so teardown runs auth → telemetry → proxy, + // and the proxy disposable is released exactly once. + expect(teardownOrder).toEqual(["auth-listener-disposed", "telemetry-shutdown", "proxy-disposed"]) + expect(proxyDispose).toHaveBeenCalledExactlyOnceWith() + } finally { + shutdown.mockReset() + vi.doUnmock("../utils/seedAllowedCommands") + vi.doUnmock("../services/zoo-code-auth") + vi.doUnmock("../utils/networkProxy") + } + }) + + test("propagates the seed rejection when the proxy initializer acquired nothing", async () => { + // Outside debug mode the real initializer returns a no-op disposable, so the + // failed-activation teardown on the catch path must stay harmless: auth and + // telemetry still tear down, and the seed error still reaches the host. + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), + })) + const teardownOrder: string[] = [] + vi.doMock("../services/zoo-code-auth", () => ({ + initZooCodeAuth: vi + .fn() + .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), + })) + const { TelemetryService } = await import("@roo-code/telemetry") + const shutdown = vi.mocked(TelemetryService.instance.shutdown) + shutdown.mockImplementation(() => { + teardownOrder.push("telemetry-shutdown") + return Promise.resolve() + }) + try { + // mockContext carries no Development extensionMode, so the unmocked + // initializer takes its early return and acquires nothing. + const { activate } = await import("../extension") + await expect(activate(mockContext)).rejects.toThrow("seed state write failed") + + expect(teardownOrder).toEqual(["auth-listener-disposed", "telemetry-shutdown"]) + } finally { + shutdown.mockReset() + vi.doUnmock("../utils/seedAllowedCommands") + vi.doUnmock("../services/zoo-code-auth") + } + }) + test("does not shut down telemetry when activation completes", async () => { // Telemetry shutdown is failure-path only: a successfully activated // extension owns the telemetry client until deactivate() runs. diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 337d61c01c..8388e7dbd9 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -1017,6 +1017,123 @@ it("checkAutoApproval command: decides each sub-command of a chain by its own ma expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "docker ps", pattern: "*" } }) }) +// The layered aggregator also owns the chain parsing, redirect sanitization, +// substitution veto, and deny reporting of the flat matcher — the enforcement +// path selects it whenever both raw global lists are present, regardless of +// the gate. These cases run through the public boundary with the raw lists +// populated: a fixture without them exercises the pre-composed fallback +// instead, and a regression in the layered copy would pass unnoticed. +it("checkAutoApproval command: approves a blank command under the layered composition", async () => { + vi.clearAllMocks() + // A whitespace-only command parses to zero sub-commands and the layered + // aggregator returns approval for that before any chain logic; pinning it + // on the raw-lists path keeps the blanket branch from reclassifying an + // empty command as unapproved. + const state = layeredState([], []) + + expect(await checkAutoApproval({ state, ask: "command", text: " " })).toEqual({ decision: "approve" }) + expect( + await checkAutoApproval({ + state: { ...state, alwaysDenyUnapprovedCommands: true }, + ask: "command", + text: " ", + }), + ).toEqual({ decision: "approve" }) +}) + +it("checkAutoApproval command: denies a malformed command under blanket and prompts without it", async () => { + vi.clearAllMocks() + // "sh" is allowlisted, so only the layered path's own syntax-error + // detection — not prefix matching — can keep an unterminated quote from + // being auto-approved. + const state = layeredState(["sh"]) + + expect(await checkAutoApproval({ state, ask: "command", text: "sh -c 'echo a" })).toEqual({ decision: "ask" }) + + const result = await checkAutoApproval({ + state: { ...state, alwaysDenyUnapprovedCommands: true }, + ask: "command", + text: "sh -c 'echo a", + }) + expect(result).toEqual({ + decision: "deny", + autoDeny: expect.objectContaining({ + kind: "malformed_command", + command: "sh -c 'echo a", + parseError: expect.stringContaining("unterminated"), + }), + }) +}) + +it("checkAutoApproval command: matches a 2>&1 redirect sub-command on its sanitized form", async () => { + vi.clearAllMocks() + // The redirect token survives command splitting, so the aggregator strips + // it before deciding. The deny witness pins both halves: the verdict as + // if the redirect were absent, and the reported offending sub-command as + // the sanitized text rather than the raw token. + const allowed = await checkAutoApproval({ + state: layeredState(["git"]), + ask: "command", + text: "git status 2>&1", + }) + expect(allowed).toEqual({ decision: "approve" }) + + const denied = await checkAutoApproval({ + state: layeredState([], ["git"]), + ask: "command", + text: "git status 2>&1", + }) + expect(denied).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "git status", pattern: "git" } }) +}) + +it("checkAutoApproval command: never auto-approves an allowed command containing a command substitution", async () => { + vi.clearAllMocks() + // Here-string command substitution: every sub-command is allowlisted, so + // only the chain-wide substitution veto can keep this off the + // auto-approve side. + const state = layeredState(["cat"]) + + expect(await checkAutoApproval({ state, ask: "command", text: "cat <<<$(whoami)" })).toEqual({ decision: "ask" }) + + const result = await checkAutoApproval({ + state: { ...state, alwaysDenyUnapprovedCommands: true }, + ask: "command", + text: "cat <<<$(whoami)", + }) + expect(result).toEqual({ + decision: "deny", + autoDeny: { kind: "dangerous_substitution", command: "cat <<<$(whoami)" }, + }) +}) + +it("checkAutoApproval command: reports the denied pattern in the case the user stored", async () => { + vi.clearAllMocks() + // Matching is case-insensitive, but the reported pattern must be the + // stored entry rather than the lower-cased match, so the denial names + // what the user's list actually contains. + const result = await checkAutoApproval({ + state: layeredState([], ["RM"]), + ask: "command", + text: "rm file", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "rm file", pattern: "RM" } }) +}) + +it("checkAutoApproval command: reports the denied sub-command of a chain in its sanitized form", async () => { + vi.clearAllMocks() + // The denied index selects the reported sub-command from the sanitized + // list: here that is both the second sub-command rather than the approved + // first one, and the redirect-stripped text rather than the raw token. + const result = await checkAutoApproval({ + state: layeredState(["git"], ["RM"]), + ask: "command", + text: "git status && Rm file 2>&1", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "Rm file", pattern: "RM" } }) +}) + // Creating a directory symlink on Windows needs developer mode or elevation; a // junction needs neither and is resolved by realpath like a POSIX link, so the // fixture tries a symlink first and falls back to a junction. Where neither can @@ -1209,6 +1326,52 @@ it("commandListFolderForResource: returns the registry Uri of the deepest matchi expect(result?.fsPath).toBe(innerRegistered) }) +it("commandListFolderForResource: returns the deepest matching root when it is registered before the shallower root", () => { + vi.clearAllMocks() + // The reverse registration order of the test above. The deepest-wins rule + // is a comparison, not a scan order, so it must hold whichever root the + // registry happens to list first; a lookup that simply kept the last + // candidate would return the outer root for this order while still + // passing a shallower-first fixture. + const outerRoot = path.sep + "mock" + const innerReal = path.join(outerRoot, "inner") + const outerUri = makeUri(outerRoot) + const innerUri = makeUri(innerReal) + workspaceState.workspaceFolders = [{ uri: innerUri }, { uri: outerUri }] + + expect(commandListFolderForResource(path.join(innerReal, "sub"))).toBe(innerUri) +}) + +it("checkAutoApproval command: judges a cwd inside a deeper root by that root's layer when the deeper root is registered first", async () => { + vi.clearAllMocks() + // The enforcement consequence of the order-independent deepest-wins rule, + // with the registration order the other symlinked-root test does not use: + // the deeper root comes first, so a lookup that returned the last match + // would enforce the outer folder's list here — the outer entry allows what + // the deeper entry denies, so the decision names the winning folder. + const outerRoot = path.sep + "mock" + const outerUri = makeUri(outerRoot) + const innerReal = path.join(outerRoot, "inner") + const innerUri = makeUri(innerReal) + workspaceState.workspaceFolders = [{ uri: innerUri }, { uri: outerUri }] + workspaceState.foldersByPath.set(outerRoot, outerUri) + mockFolderConfigurations({ + [outerRoot]: { gate: true, allow: ["echo"] }, + [innerReal]: { gate: true, deny: ["echo"] }, + }) + + const result = await checkAutoApproval({ + // Empty raw global layers: only the winning folder's layer can decide. + state: taskFolderState([]), + cwd: path.join(innerReal, "sub"), + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, innerUri) +}) + it("checkAutoApproval command: judges a cwd inside a symlinked root by that root's layer when an outer root also contains it lexically", async () => { vi.clearAllMocks() const outerRoot = path.sep + "mock" diff --git a/src/extension.ts b/src/extension.ts index 37b7c52b0c..4934ad0307 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -135,8 +135,10 @@ export async function activate(context: vscode.ExtensionContext) { // Initialize network proxy configuration early, before any network requests. // When proxyUrl is configured, all HTTP/HTTPS traffic will be routed through it. - // Only applied in debug mode (F5). - await initializeNetworkProxy(context, outputChannel) + // Only applied in debug mode (F5). The returned disposable covers the debug-proxy + // resources; keep it for both the normal deactivate path and the failed-activation + // path below. + const proxyResources = await initializeNetworkProxy(context, outputChannel) // Set extension path for custom tool registry to find bundled esbuild customToolRegistry.setExtensionPath(context.extensionPath) @@ -188,10 +190,13 @@ export async function activate(context: vscode.ExtensionContext) { // Activation aborts here, and `deactivate()` is not guaranteed to run // afterward, so this catch is the only teardown for everything // initialized before the seed point: release the secret-storage - // listener and shut down the telemetry client registered above. - // Shutdown failures are logged rather than rethrown so they cannot mask - // the seed rejection; the service bounds its own drain and client-flush - // phases, so a stuck client cannot hang the host here. + // listener, shut down the telemetry client registered above, and + // release the debug-proxy resources initialized before the seed — in + // strict reverse acquisition order (auth was acquired last, the proxy + // first), each step disposed only after the previous one settles. + // Teardown failures are logged rather than rethrown so they cannot mask + // the seed rejection; the telemetry service bounds its own drain and + // client-flush phases, so a stuck client cannot hang the host here. authSecretsListener.dispose() try { await telemetryService.shutdown() @@ -200,6 +205,13 @@ export async function activate(context: vscode.ExtensionContext) { `Failed to shut down telemetry service: ${shutdownError instanceof Error ? shutdownError.message : String(shutdownError)}`, ) } + try { + proxyResources.dispose() + } catch (disposeError) { + outputChannel.appendLine( + `Failed to dispose network proxy resources: ${disposeError instanceof Error ? disposeError.message : String(disposeError)}`, + ) + } throw error } diff --git a/src/utils/__tests__/networkProxy.spec.ts b/src/utils/__tests__/networkProxy.spec.ts index fc789878c8..7827eff88b 100644 --- a/src/utils/__tests__/networkProxy.spec.ts +++ b/src/utils/__tests__/networkProxy.spec.ts @@ -2,6 +2,7 @@ import * as vscode from "vscode" import { NodeHttpHandler } from "@smithy/node-http-handler" import { HttpProxyAgent } from "http-proxy-agent" import { HttpsProxyAgent } from "https-proxy-agent" +import { makeWorkspaceConfiguration } from "../../test-utils/vscode" import { initializeNetworkProxy, getProxyConfig, @@ -201,6 +202,83 @@ describe("networkProxy", () => { void initializeNetworkProxy(context, mockOutputChannel) }).not.toThrow() }) + + // A failed activation does not guarantee deactivate() runs, so the disposable + // initializeNetworkProxy returns must release every resource that was also registered on + // context.subscriptions - a retained configuration listener could re-apply proxy and TLS + // overrides inside a dead extension. The module is re-imported so the debug-mode resource + // paths (listener, override cleanup, fetch patch) all execute: the latches that keep + // global-agent bootstrap and the fetch patch one-shot would otherwise be tripped by + // earlier tests, leaving a one-sided registration invisible to this equivalence check. + it("should dispose every resource registered on context.subscriptions when the returned disposable is disposed", async () => { + // Other tests in this file call initializeNetworkProxy without awaiting it, and a + // debug-mode run patches global fetch only after its dynamic imports settle. Awaiting + // one debug-mode run and one production-mode run here first: the awaited debug run + // settles the module's one-shot fetch-patch latch, so any still-pending earlier run + // skips its patch instead of racing this test's sentinel, and the trailing + // production-mode run leaves the shared module on the extension context and + // no-patch state the following tests expect. + mockConfig.get.mockImplementation((key: string) => { + if (key === "debugProxy.enabled") return true + if (key === "debugProxy.serverUrl") return "http://localhost:8080" + if (key === "debugProxy.tlsInsecure") return true + return "" + }) + const fetchBefore = globalThis.fetch + try { + await initializeNetworkProxy(createMockContext(vscode.ExtensionMode.Development), mockOutputChannel) + await initializeNetworkProxy(createMockContext(vscode.ExtensionMode.Production), mockOutputChannel) + + vi.resetModules() + // The runs above left the TLS override applied; drop it so the run under test + // captures "unset" as its restore target. + delete process.env.NODE_TLS_REJECT_UNAUTHORIZED + + // A local sentinel function stands in for the pre-patch global fetch: asserting + // the restore comes back to this exact reference is deterministic regardless of + // which fetch implementation is installed at this point. + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + + const freshModule = await import("../networkProxy") + const freshVscode = await import("vscode") + // resetModules re-runs the vscode mock factory, so the re-imported module reads + // its configuration through a fresh getConfiguration spy that needs the stub. + vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( + makeWorkspaceConfiguration({ + "debugProxy.enabled": true, + "debugProxy.serverUrl": "http://localhost:8080", + "debugProxy.tlsInsecure": true, + }), + ) + + const context = createMockContext(vscode.ExtensionMode.Development) + const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + + // Snapshot the registration side, then observe each registered object's own + // dispose: the assertion below holds only if the returned aggregate releases the + // same objects registered on context.subscriptions, which is the invariant. + const registered = [...context.subscriptions] + // Configuration listener, override cleanup, and fetch patch: the scenario must + // register all three for the equivalence to cover every acquisition. + expect(registered.length).toBe(3) + // Both observable overrides are applied before teardown. + expect(globalThis.fetch).not.toBe(fetchSentinel) + expect(process.env.NODE_TLS_REJECT_UNAUTHORIZED).toBe("0") + + const spiedDisposes = registered.map((resource) => vi.spyOn(resource, "dispose")) + returned.dispose() + + for (const dispose of spiedDisposes) { + expect(dispose).toHaveBeenCalledOnce() + } + // Teardown restores both observable overrides: fetch and the TLS setting. + expect(globalThis.fetch).toBe(fetchSentinel) + expect(process.env.NODE_TLS_REJECT_UNAUTHORIZED).toBeUndefined() + } finally { + globalThis.fetch = fetchBefore + } + }) }) describe("getProxyConfig", () => { diff --git a/src/utils/networkProxy.ts b/src/utils/networkProxy.ts index e086908844..cc0c030699 100644 --- a/src/utils/networkProxy.ts +++ b/src/utils/networkProxy.ts @@ -112,20 +112,28 @@ function applyTlsVerificationOverride(config: ProxyConfig): void { * Initialize the network proxy module with the extension context. * Must be called early in extension activation before any network requests. * + * Each resource created here is also registered on `context.subscriptions` for the normal + * deactivate path. The returned disposable covers the same resources so a failed activation + * can tear them down itself: `deactivate()` is not guaranteed to run after activation fails, + * and a retained configuration listener would let a `debugProxy.*` settings toggle re-apply + * proxy configuration (including the TLS verification override) inside a dead extension. + * * @param context The VS Code extension context * @param channel Optional output channel for logging + * @returns A disposable releasing everything initialized here; a no-op outside debug mode, where nothing is created. */ export async function initializeNetworkProxy( context: vscode.ExtensionContext, channel?: vscode.OutputChannel, -): Promise { +): Promise { extensionContext = context // extensionMode is immutable for the process lifetime - exit early if not in debug mode. // This avoids any overhead (listeners, logging, etc.) in production. const isDebugMode = context.extensionMode === vscode.ExtensionMode.Development if (!isDebugMode) { - return + // Nothing was acquired in production, so there is nothing for the caller to tear down. + return { dispose: () => {} } } outputChannel = channel ?? null @@ -139,49 +147,67 @@ export async function initializeNetworkProxy( `Proxy config: enabled=${config.enabled}, serverUrl=${redactProxyUrl(config.serverUrl)}, tlsInsecure=${config.tlsInsecure}`, ) + // Collect every resource created here so the returned disposable can release them when a + // later activation step fails; the same objects also go to context.subscriptions for the + // deactivate path, and both restores below are idempotent, so double disposal is safe. + const resources: vscode.Disposable[] = [] + // Listen for configuration changes to allow toggling proxy during a debug session. // Guard for test environments where onDidChangeConfiguration may not be mocked. if (typeof vscode.workspace.onDidChangeConfiguration === "function") { - context.subscriptions.push( - vscode.workspace.onDidChangeConfiguration((e) => { - if ( - e.affectsConfiguration(`${Package.name}.debugProxy.enabled`) || - e.affectsConfiguration(`${Package.name}.debugProxy.serverUrl`) || - e.affectsConfiguration(`${Package.name}.debugProxy.tlsInsecure`) - ) { - const newConfig = getProxyConfig() - - if (newConfig.enabled) { - applyTlsVerificationOverride(newConfig) - configureGlobalProxy(newConfig) - configureUndiciProxy(newConfig) - } else { - // Proxy disabled - but we can't easily un-bootstrap global-agent or reset undici dispatcher safely. - // We *can* restore any global fetch patch immediately. - restoreGlobalFetchPatch() - restoreTlsVerificationOverride() - log("Debug proxy disabled. Restart VS Code to fully disable proxy routing.") - } + const configListener = vscode.workspace.onDidChangeConfiguration((e) => { + if ( + e.affectsConfiguration(`${Package.name}.debugProxy.enabled`) || + e.affectsConfiguration(`${Package.name}.debugProxy.serverUrl`) || + e.affectsConfiguration(`${Package.name}.debugProxy.tlsInsecure`) + ) { + const newConfig = getProxyConfig() + + if (newConfig.enabled) { + applyTlsVerificationOverride(newConfig) + configureGlobalProxy(newConfig) + configureUndiciProxy(newConfig) + } else { + // Proxy disabled - but we can't easily un-bootstrap global-agent or reset undici dispatcher safely. + // We *can* restore any global fetch patch immediately. + restoreGlobalFetchPatch() + restoreTlsVerificationOverride() + log("Debug proxy disabled. Restart VS Code to fully disable proxy routing.") } - }), - ) + } + }) + context.subscriptions.push(configListener) + resources.push(configListener) } // Ensure we restore any overrides when the extension unloads. - context.subscriptions.push({ + const overrideCleanup: vscode.Disposable = { dispose: () => { restoreGlobalFetchPatch() restoreTlsVerificationOverride() }, - }) + } + context.subscriptions.push(overrideCleanup) + resources.push(overrideCleanup) if (config.enabled) { applyTlsVerificationOverride(config) await configureGlobalProxy(config) - await configureUndiciProxy(config) + const fetchPatch = await configureUndiciProxy(config) + if (fetchPatch) { + resources.push(fetchPatch) + } } else { log(`Debug proxy not enabled.`) } + + return { + dispose: () => { + for (const resource of resources) { + resource.dispose() + } + }, + } } /** @@ -261,17 +287,22 @@ async function configureGlobalProxy(config: ProxyConfig): Promise { /** * Configure undici's global dispatcher so Node's built-in `fetch()` and any undici-based * clients route through the proxy. + * + * @returns A disposable restoring the global fetch patch when one was applied, or undefined + * when no patch was made (nothing to undo). Also registered on `context.subscriptions`. */ -async function configureUndiciProxy(config: ProxyConfig): Promise { +async function configureUndiciProxy(config: ProxyConfig): Promise { if (!config.enabled || !config.serverUrl) { - return + return undefined } if (undiciProxyInitialized) { log(`undici global dispatcher already configured; restart VS Code to change proxy safely`) - return + return undefined } + let fetchPatch: vscode.Disposable | undefined + try { const { ProxyAgent, @@ -307,15 +338,16 @@ async function configureUndiciProxy(config: ProxyConfig): Promise { fetchPatched = true log(`globalThis.fetch patched to undici.fetch (debug proxy mode)`) + fetchPatch = { dispose: () => restoreGlobalFetchPatch() } if (extensionContext) { - extensionContext.subscriptions.push({ - dispose: () => restoreGlobalFetchPatch(), - }) + extensionContext.subscriptions.push(fetchPatch) } } } catch (error) { log(`Failed to configure undici proxy dispatcher: ${error instanceof Error ? error.message : String(error)}`) } + + return fetchPatch } /** * Update environment variables for proxy configuration. From e3d29a6d0bcb3f0dbf1a18bd265d8b1279a646e0 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Wed, 11 Nov 2026 04:29:46 +0100 Subject: [PATCH 17/52] fix(extension): complete failed-activation teardown of channel and sink The seed-failure catch now also clears the persistence trace sink and disposes the output channel, last in strict reverse acquisition order; the sink writes through the channel, so it must go before the dispose to keep later traces out of a dead channel. Tests pin both orders. --- src/__tests__/extension.spec.ts | 139 ++++++++++++++++++++++++++++++++ src/extension.ts | 24 +++++- 2 files changed, 159 insertions(+), 4 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 37fc085c49..bdf5a7f966 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -804,6 +804,145 @@ describe("extension.ts", () => { } }) + test("disposes the output channel last when seeding rejects activation", async () => { + // The output channel is the first resource `activate` acquires, and the + // host does not guarantee `deactivate()` after a failed activation, so + // the failure path must release it too — last, because every earlier + // teardown step logs its own failure through this channel. + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), + })) + const teardownOrder: string[] = [] + const proxyDispose = vi.fn(() => void teardownOrder.push("proxy-disposed")) + vi.doMock("../utils/networkProxy", () => ({ + // The mock returns the aggregate disposable unconditionally; the + // mode-gating of the real initializer is pinned in its own spec. + initializeNetworkProxy: vi.fn().mockResolvedValue({ dispose: proxyDispose }), + getSystemProxyUrl: vi.fn().mockReturnValue(undefined), + isProxyEnabled: vi.fn().mockReturnValue(false), + createProxyRoutingRequestHandler: vi.fn().mockReturnValue(undefined), + })) + vi.doMock("../services/zoo-code-auth", () => ({ + initZooCodeAuth: vi + .fn() + .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), + })) + const { TelemetryService } = await import("@roo-code/telemetry") + const shutdown = vi.mocked(TelemetryService.instance.shutdown) + shutdown.mockImplementation(() => { + teardownOrder.push("telemetry-shutdown") + return Promise.resolve() + }) + try { + const vscode = await import("vscode") + // The factory double is a fixed object, so calling the mock now hands + // back the same channel `activate` will create; arming its dispose + // before activation lets the order assertion observe the step. + const channel = vi.mocked(vscode.window.createOutputChannel)("Test Output") + channel.dispose = vi.fn(() => void teardownOrder.push("channel-disposed")) + + const { activate } = await import("../extension") + await expect(activate(mockContext)).rejects.toThrow("seed state write failed") + + // Strict reverse acquisition: the channel was acquired first, so it is + // disposed after auth, telemetry, and the proxy — every teardown log + // line was still writable when those steps ran. + expect(teardownOrder).toEqual([ + "auth-listener-disposed", + "telemetry-shutdown", + "proxy-disposed", + "channel-disposed", + ]) + expect(channel.dispose).toHaveBeenCalledExactlyOnceWith() + // Still registered for the normal deactivate path; the failure-path + // dispose must not have replaced the subscription push. + expect(mockContext.subscriptions).toContain(channel) + } finally { + shutdown.mockReset() + vi.doUnmock("../utils/seedAllowedCommands") + vi.doUnmock("../services/zoo-code-auth") + vi.doUnmock("../utils/networkProxy") + } + }) + + test("clears the persistence trace sink before disposing the output channel when seeding rejects", async () => { + // The persistence trace sink installed at activation start mirrors + // trace lines through the output channel, so the failure path must + // unregister it before the channel goes away: a later trace — such as + // `deactivate()`'s shutdown event — would otherwise write into a + // disposed channel. + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), + })) + const teardownOrder: string[] = [] + const proxyDispose = vi.fn(() => void teardownOrder.push("proxy-disposed")) + vi.doMock("../utils/networkProxy", () => ({ + // The mock returns the aggregate disposable unconditionally; the + // mode-gating of the real initializer is pinned in its own spec. + initializeNetworkProxy: vi.fn().mockResolvedValue({ dispose: proxyDispose }), + getSystemProxyUrl: vi.fn().mockReturnValue(undefined), + isProxyEnabled: vi.fn().mockReturnValue(false), + createProxyRoutingRequestHandler: vi.fn().mockReturnValue(undefined), + })) + vi.doMock("../services/zoo-code-auth", () => ({ + initZooCodeAuth: vi + .fn() + .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), + })) + // Only the teardown call is an order marker: installation passes the + // channel-logging sink, while clearing passes undefined — the setter's + // documented way to restore the default console sink. + const setPersistenceTraceSink = vi.fn((sink?: unknown) => { + if (sink === undefined) { + teardownOrder.push("trace-sink-cleared") + } + }) + vi.doMock("../core/task-persistence/persistenceTrace", () => ({ + setPersistenceTraceSink, + tracePersistenceEvent: vi.fn(), + })) + const { TelemetryService } = await import("@roo-code/telemetry") + const shutdown = vi.mocked(TelemetryService.instance.shutdown) + shutdown.mockImplementation(() => { + teardownOrder.push("telemetry-shutdown") + return Promise.resolve() + }) + try { + const vscode = await import("vscode") + // The factory double is a fixed object, so calling the mock now hands + // back the same channel `activate` will create; arming its dispose + // before activation lets the order assertion observe the step. + const channel = vi.mocked(vscode.window.createOutputChannel)("Test Output") + channel.dispose = vi.fn(() => void teardownOrder.push("channel-disposed")) + + const { activate } = await import("../extension") + await expect(activate(mockContext)).rejects.toThrow("seed state write failed") + + // Reverse acquisition order pins the clear between the proxy release + // and the channel dispose: the sink was installed after the channel + // it logs through but before the proxy, so it is released after the + // proxy — and before the channel, which goes last. + expect(teardownOrder).toEqual([ + "auth-listener-disposed", + "telemetry-shutdown", + "proxy-disposed", + "trace-sink-cleared", + "channel-disposed", + ]) + // Exactly the install call and the clear: the failure path neither + // skips the clear nor repeats it. + expect(setPersistenceTraceSink).toHaveBeenCalledTimes(2) + expect(setPersistenceTraceSink).toHaveBeenNthCalledWith(1, expect.any(Function)) + expect(setPersistenceTraceSink).toHaveBeenNthCalledWith(2, undefined) + } finally { + shutdown.mockReset() + vi.doUnmock("../utils/seedAllowedCommands") + vi.doUnmock("../services/zoo-code-auth") + vi.doUnmock("../utils/networkProxy") + vi.doUnmock("../core/task-persistence/persistenceTrace") + } + }) + test("propagates the seed rejection when the proxy initializer acquired nothing", async () => { // Outside debug mode the real initializer returns a no-op disposable, so the // failed-activation teardown on the catch path must stay harmless: auth and diff --git a/src/extension.ts b/src/extension.ts index 4934ad0307..b094d22614 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -190,10 +190,11 @@ export async function activate(context: vscode.ExtensionContext) { // Activation aborts here, and `deactivate()` is not guaranteed to run // afterward, so this catch is the only teardown for everything // initialized before the seed point: release the secret-storage - // listener, shut down the telemetry client registered above, and - // release the debug-proxy resources initialized before the seed — in - // strict reverse acquisition order (auth was acquired last, the proxy - // first), each step disposed only after the previous one settles. + // listener, shut down the telemetry client registered above, release + // the debug-proxy resources, clear the persistence trace sink, and + // dispose the output channel — in strict reverse acquisition order + // (auth was acquired last, the output channel first), each step + // disposed only after the previous one settles. // Teardown failures are logged rather than rethrown so they cannot mask // the seed rejection; the telemetry service bounds its own drain and // client-flush phases, so a stuck client cannot hang the host here. @@ -212,6 +213,21 @@ export async function activate(context: vscode.ExtensionContext) { `Failed to dispose network proxy resources: ${disposeError instanceof Error ? disposeError.message : String(disposeError)}`, ) } + // The persistence trace sink installed above writes its lines through + // the output channel, so it is cleared — passing undefined restores the + // default console sink — before the channel is disposed, keeping any + // later trace event (such as a deactivate() shutdown trace) from + // writing into a disposed channel. + setPersistenceTraceSink(undefined) + // The channel is disposed after every step that logs through it, so no + // teardown log is written to an already-dead channel. Once it is gone, + // no extension output sink is left to report a failed dispose to; the + // error is deliberately dropped rather than routed to the console. + try { + outputChannel.dispose() + } catch { + // The extension output sink is itself being torn down. + } throw error } From 224644023e9c841864ffa0d2756a09d0113354d3 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 12 Nov 2026 23:39:32 +0100 Subject: [PATCH 18/52] fix: order command-list writes, undo only this save, close proxy agents Saving the allowed/denied command lists now writes the global layer before the workspace layer, so a mid-save failure can leave a new entry duplicated across both layers but never missing from both; the composed enforcement set is a union, so no approval outcome changes during that window. When a write fails, the rollback re-reads the global layer and undoes only this save's own additions and deletions, so entries added elsewhere mid-save survive; a global layer that was absent before the save is cleared rather than written as an empty list. The settings dialog sends the workspace-command-lists setting it last displayed along with the saved lists. If that setting changed while the dialog was open, entries the user saw and kept are treated as known workspace entries instead of brand-new promotions into the global layer. A failed command-list write now marks the save result as failed, so the settings page keeps the edits unsaved instead of reporting success. The startup proxy setup closes its undici ProxyAgent when disposed and skips installing the dispatcher or the fetch patch when a dynamic import completes after teardown. Tests pin the new write order, the undo delta, the displayed-setting classification, the failed-save result, and the late-install guard. --- packages/types/src/vscode-extension-host.ts | 12 +- .../__tests__/webviewMessageHandler.spec.ts | 508 +++++++++++++++--- src/core/webview/webviewMessageHandler.ts | 141 +++-- src/utils/__tests__/networkProxy.spec.ts | 292 +++++++++- src/utils/networkProxy.ts | 95 +++- .../src/components/settings/SettingsView.tsx | 30 +- .../settings/__tests__/SettingsView.spec.tsx | 130 +++++ .../SettingsView.unsaved-changes.spec.tsx | 47 ++ 8 files changed, 1132 insertions(+), 123 deletions(-) diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index c1cfebdc82..26e36c15f2 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -832,7 +832,17 @@ export interface WebviewMessage { * from list entries the user deleted: both look like "in the file, absent from the * submitted list". Senders that do not display the lists omit it. */ - commandListBaseline?: { allowedCommands?: string[]; deniedCommands?: string[] } + commandListBaseline?: { + allowedCommands?: string[] + deniedCommands?: string[] + /** + * The workspace-command-lists gate as the dialog last displayed it. Flipping the + * gate between display and save hides workspace entries, so this travels with the + * baseline to let the save path classify an entry the baseline already showed as + * existing workspace knowledge rather than a brand-new promotion into the global layer. + */ + workspaceCommandListsEnabled?: boolean + } /** Task configuration applied via `createTask()`. */ taskConfiguration?: RooCodeSettings // Worktree properties diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 7b1454c9d1..8053d461a1 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2286,18 +2286,22 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git"]) }) - it("restores the raw workspace value when a workspace-target global write fails", async () => { - // With no folder layer the rewind must read the workspace value, not - // the absent folder value. The gate is on so the kept workspace entry is - // visible and the workspace write (`["docker"]`) differs from the raw - // rollback value (which still holds the entry this save dropped); the - // gate-off alternative would make the first write re-add the hidden - // entries and duplicate the rollback value, letting a call-agnostic - // assertion match a write that is not the rewind. + it("writes the global layer before the workspace layer and undoes only its own delta when the workspace write fails", async () => { + // update() call order: global write succeeds, workspace write rejects, + // undo write runs. The undo re-reads the global layer and applies only + // this save's delta, so an entry a third party added mid-save + // ("mid-save") survives while the save's own addition ("aws") is + // removed and its deletions ("keep", "drop") are restored. The gate is + // on so the workspace write is a plain keep with no hidden-entry re-add, + // keeping each scripted call distinguishable; the undo is pinned by + // call position. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["keep", "drop"] : undefined, + ) const { update } = mockCommandConfiguration( - { workspaceValue: ["npm docker", "docker"] }, - [undefined, Promise.reject(new Error("disk on fire"))], - undefined, + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ workspaceValue: ["npm docker", "docker"] }, undefined, { globalValue: ["aws", "mid-save"] }], true, ) @@ -2306,50 +2310,59 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - // Call order: workspace write, failed global write, rewind — so the - // rewind is pinned by position, not just by matching some call. + // Global first, workspace second — the ordering itself is the pin. + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + // The undo removes only "aws", restores "keep" and "drop", and keeps the + // mid-save addition — a stale-snapshot rewind would have dropped it. expect(update).toHaveBeenNthCalledWith( 3, "deniedCommands", - ["npm docker", "docker"], - vscode.ConfigurationTarget.Workspace, + ["mid-save", "keep", "drop"], + vscode.ConfigurationTarget.Global, ) expect(update).toHaveBeenCalledTimes(3) - expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: disk on fire") + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) - it("restores the previous workspace value when the global write fails", async () => { - // update() call order: workspace write succeeds, global write rejects. - // The raw folder-layer value differs from the sanitized post-split layer - // (and from the workspace-layer value), so the restore call is uniquely - // identifiable and provably reads the folder value for a folder target. - // The gate is on so the workspace write keeps only the visible entry and - // cannot match the raw rollback value; the rewind is asserted by call - // position. + it("rolls the global layer back on a folder-target save and still persists the payload's other keys", async () => { + // update() call order: global write succeeds, the folder-target + // workspace write rejects, the undo restores the global deletions at + // the Global target (the only layer this save changed). A second key + // pins that only the failed command-list key is skipped. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["drop"] : undefined, + ) const { update } = mockCommandConfiguration( - { workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, - [undefined, Promise.reject(new Error("disk on fire"))], - undefined, + {}, + [undefined, Promise.reject(new Error("disk on fire")), undefined], + [ + { workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, + undefined, + { + globalValue: [], + }, + ], true, ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", - // A second key pins that only the failed command-list key is skipped. updatedSettings: { deniedCommands: ["docker", "aws"], alwaysDenyUnapprovedCommands: true }, }) - // The capture, the failed write, and the restore all ran on the + // The capture, the failed write, and the undo all ran on the // configuration scoped to the first workspace folder. expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, mockWorkspaceFolderUri) - // The raw previous folder value (entries this save dropped included) is - // written back at the target the failed save chose, as the third write. expect(update).toHaveBeenNthCalledWith( - 3, + 2, "deniedCommands", - ["pnpm docker", "docker"], + ["docker"], vscode.ConfigurationTarget.WorkspaceFolder, ) + // This save deleted "drop" from the global layer, so the undo restores it. + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", ["drop"], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) // The failed key's extension global-state write is skipped... expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) @@ -2359,25 +2372,29 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) - it("does not write global or extension state when the workspace write fails", async () => { - // The first update() call is the workspace write; it rejects, so the - // global write must never be attempted for this key. The rejection is a - // plain string to pin the non-Error rendering of the failure message. - const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, [ - Promise.reject("workspace locked"), - ]) + it("aborts the key without compensation when the global write fails", async () => { + // The global layer is written first, so a rejected global write leaves + // nothing changed: no workspace write may follow and no compensation is + // needed. The rejection is a plain string to pin the non-Error + // rendering of the failure message. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, [Promise.reject("global locked")]) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - // Nothing was changed yet, so there is nothing to restore: only the - // failed workspace write happened, and no compensation write followed. + // Only the failed global write happened: the workspace layer is never + // touched and nothing is compensated. expect(update).toHaveBeenCalledTimes(1) - expect(update).not.toHaveBeenCalledWith("deniedCommands", expect.anything(), vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() - expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: global locked") }) it("aborts the key without writing when the configuration inspection has no result", async () => { @@ -2453,15 +2470,21 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("reports partial failure when the compensating restore also fails", async () => { - // update() call order: workspace write succeeds, global write rejects, - // restore write rejects too. The raw workspace value differs from the - // post-split layer so the restore call is uniquely identifiable. The - // gate is on so the workspace write (`["docker"]`) stays distinct from - // the raw rollback value, and the rewind is pinned by call position. + // update() call order: global write succeeds, workspace write rejects, + // the undo write rejects too. The gate is on so the workspace write is + // the plain kept list and every scripted call stays distinguishable; + // the undo is pinned by call position. + // The global layer starts empty here (a mock implementation set by an + // earlier test outlives clearAllMocks), so this save only adds. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( - { workspaceValue: ["docker", "old"] }, - [undefined, Promise.reject(new Error("disk on fire")), Promise.reject(new Error("restore also failed"))], - undefined, + {}, + [ + undefined, + Promise.reject(new Error("workspace locked")), + Promise.reject(new Error("restore also failed")), + ], + [{ workspaceValue: ["docker", "old"] }, undefined, { globalValue: ["aws"] }], true, ) @@ -2470,22 +2493,48 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - // The restore was attempted at the owning target even though it failed. - expect(update).toHaveBeenNthCalledWith( - 3, - "deniedCommands", - ["docker", "old"], - vscode.ConfigurationTarget.Workspace, - ) + // The undo was attempted at the Global target even though it failed; + // this save deleted no global entry, added only "aws", and found no + // global layer at save start, so the undo clears the key rather than + // writing back the fresh read minus "aws". + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( - "Failed to save deniedCommands: disk on fire. The workspace-scoped restore also failed: Error: restore also failed. Review the command lists in your user and workspace settings.", + "Failed to save deniedCommands: workspace locked. The global-scoped restore also failed: Error: restore also failed. Review the command lists in your user and workspace settings.", ) // No exception escaped the handler: the state post still ran. expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) + it("skips the undo without guessing when the global value cannot be re-read to undo it", async () => { + // The compensation re-read is guarded: when even the fresh read fails, + // writing the save-start value would clobber whatever the failed read + // could not show, so nothing is written and the double failure is + // reported instead. update() order: global write succeeds, workspace + // write rejects; the third inspect() call (the undo re-read) throws. + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked"))], + [{ workspaceValue: ["docker"] }, undefined, new Error("inspect unavailable")], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + // The failed workspace write is the last configuration write: a + // stale-snapshot fallback would have written a third value here. + expect(update).toHaveBeenCalledTimes(2) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to save deniedCommands: workspace locked. The global-scoped value could not be re-read to undo this save: Error: inspect unavailable. Review the command lists in your user and workspace settings.", + ) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + // Entries the dialog never displayed — hidden while the gate is off, or // shadowed by a global entry with it on — cannot be deleted by omission // from a list the user could not see, so a save re-adds them to the @@ -2558,6 +2607,316 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) }) + it("keeps a gate-flip-hidden workspace entry the dialog displayed at the workspace scope", async () => { + // The dialog opened with the gate on, so it displayed the workspace + // entry; the gate flipped off before the save, which hides every + // workspace entry. Because the baseline carries the gate as displayed + // and shows the entry, keeping it stays a workspace decision instead of + // becoming a brand-new promotion into the global layer. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + // Only the genuinely new entry is promoted; "docker" stays out of the + // global write. + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) + }) + + it("still promotes a hidden workspace entry when the baseline gate matches the current gate", async () => { + // The equality guard's other side: the dialog displayed with the gate + // off and the gate is still off, so the hidden-entry classification is + // unchanged even though the baseline names the entry — a gate-flipped + // baseline is the only signal that the entry was ever displayed. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: false }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + }) + + // The save result is the dialog's only answer for a per-key command-list + // failure: those paths report through the flags instead of throwing, so + // each one must reach the ack with success:false. + const deniedSaveResults = () => + vi + .mocked(mockClineProvider.postMessageToWebview) + .mock.calls.map(([message]) => message) + .filter((message) => message.type === "settingsSaveResult") + + it("reports a failed save through the result when the configuration inspection has no result", async () => { + // The snapshot-abort leg marks the save failed for the ack: a dialog + // told the save succeeded would discard the user's list edits. + mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, [undefined]) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + requestId: "save-1", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) + }) + + it("promotes a gate-hidden workspace entry named by a baseline without the gate slot", async () => { + // A baseline that predates the gate slot keeps the current + // classification: without the gate as displayed, the entry's presence + // in the baseline is no evidence the dialog showed it, so re-adding it + // promotes to the global layer exactly as it does with no baseline. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + }) + + it("promotes only the hidden entries a gate-flipped baseline did not display", async () => { + // The gate flipped off while the dialog was open; the baseline lists + // "docker" but not "npm". "docker" was displayed, so keeping it stays + // a workspace decision; "npm" was never displayed, so a submitted + // copy of it is classified as new and lands in the global layer. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "npm", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["npm", "aws"], vscode.ConfigurationTarget.Global) + // The re-add still preserves both hidden entries in the workspace file. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Workspace) + }) + + it("keeps an entry the save retained out of the undo's removal set", async () => { + // The compensation removes only what this save added. The global layer + // already held "keep" and this save kept it, so the undo — computed + // against the fresh read — leaves "keep" in place while removing only + // this save's addition ("aws") and restoring its deletion ("drop"). + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["keep", "drop"] : undefined, + ) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["keep", "aws", "mid-save"] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["keep", "docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["keep", "aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenNthCalledWith( + 3, + "deniedCommands", + ["keep", "mid-save", "drop"], + vscode.ConfigurationTarget.Global, + ) + expect(update).toHaveBeenCalledTimes(3) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") + }) + + it("does not restore a global entry a third party removed while undoing", async () => { + // The fresh read during the compensation shows "keep" gone: someone + // else removed it mid-save, so undo-mine must not resurrect an entry + // this save never deleted — only its own deletion ("drop") returns. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["keep", "drop"] : undefined, + ) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws", "mid-save"] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["keep", "docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith( + 3, + "deniedCommands", + ["mid-save", "drop"], + vscode.ConfigurationTarget.Global, + ) + expect(update).toHaveBeenCalledTimes(3) + }) + + it("undoes with only this save's deletions when the re-read reports no global value", async () => { + // A cleared key inspects as no value at all: the compensation reads + // that as an empty layer and writes back just the deletion it must + // restore, rather than treating the absent value as a failed re-read. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["keep", "drop"] : undefined, + ) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ workspaceValue: ["docker"] }, undefined, undefined], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["keep", "docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", ["drop"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(3) + // Only the plain write-failure message: the re-read did not fail. + expect(vscode.window.showErrorMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") + }) + + it("clears the key when the undo finds the layer absent, at save start or cleared mid-save", async () => { + // A rolled-back addition-only save must not materialize an empty global + // layer where none existed: the activation seed treats an explicit `[]` + // as an override, so writing `[]` here would suppress the default command + // lists after a restart. The undo clears the key instead, at the same call + // position the `[]` write would have occupied. The layer can be absent + // either because it was absent when the save started, or because a third + // party cleared it while the save ran and the guarded re-read saw that; + // both absences land in the same clear. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(3) + + // The layer existed when the save started, and the re-read during the + // compensation reports it gone: someone cleared it mid-save, so there is + // nothing present left to restore either and the undo clears the key. + const { update: clearedMidSave } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ globalValue: ["aws"], workspaceValue: ["docker"] }, undefined, undefined], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(clearedMidSave).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(clearedMidSave).toHaveBeenNthCalledWith( + 2, + "deniedCommands", + ["docker"], + vscode.ConfigurationTarget.Workspace, + ) + expect(clearedMidSave).toHaveBeenNthCalledWith( + 3, + "deniedCommands", + undefined, + vscode.ConfigurationTarget.Global, + ) + expect(clearedMidSave).toHaveBeenCalledTimes(3) + }) + + it("still writes an empty undo list when the global layer exists but holds nothing to keep", async () => { + // The guard's other side: a layer that exists stays present after the + // rollback, even when the undo computes an empty list — clearing an + // existing empty layer would silently restore the seeded defaults the + // user had explicitly overridden with an empty list. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ globalValue: [], workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(3) + }) + + it("reports a failed save through the result when the global value cannot be re-read", async () => { + // The guarded re-read leg writes nothing, so the ack is the dialog's + // only notice that the save did not go through. + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked"))], + [{ workspaceValue: ["docker"] }, undefined, new Error("inspect unavailable")], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + requestId: "save-1", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenCalledTimes(2) + expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) + }) + + it("reports a failed save through the result when the compensating restore also fails", async () => { + // The undo-failure leg reports both failures to the user but throws + // nothing, so only its flag can tell the dialog the save was lost. + // The global layer is absent at save start and the save only added, so + // the undo clears the key. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + {}, + [ + undefined, + Promise.reject(new Error("workspace locked")), + Promise.reject(new Error("restore also failed")), + ], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + requestId: "save-1", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) + expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) + }) + it("promotes a shadowed workspace entry the dialog re-adds to the global write", async () => { // The global allow "git" shadows the workspace deny "git push", so the // dialog never displayed the deny entry; a user who re-adds it submits a @@ -4209,6 +4568,35 @@ describe("updateSettings with the display settings", () => { "[updateSettings] Could not refresh the webview state: webview gone", ) }) + + it("reports a failed save when a command-list write fails, without throwing", async () => { + // A command-list key abandons only its own key on a write failure: + // the failure path reports and continues without a throw, so the + // save result must still say the save was not stored — the dialog + // keeps the user's list edits unsaved on this answer. + const config = makeWorkspaceConfiguration({}) + config.inspect = vi.fn().mockReturnValue({}) + config.update = vi.fn().mockRejectedValue(new Error("disk on fire")) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + await expect(saveAs({ deniedCommands: ["aws"] })).resolves.toBeUndefined() + + expect(results()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + }) + + it("still reports a stored save when a command-list write succeeds", async () => { + // The accept-path counterpart: the failure flag must not stick for a + // save whose command-list writes all succeeded. + const config = makeWorkspaceConfiguration({}) + config.inspect = vi.fn().mockReturnValue({}) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + await saveAs({ deniedCommands: ["aws"] }) + + expect(config.update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(results()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: true }]) + }) }) it("completes a partial save when the same values are saved again", async () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6a57f78364..84a1640ea3 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -758,8 +758,11 @@ export const webviewMessageHandler = async ( // times are shown, so a partial save is harmless, and saving again completes it. Either way the webview is // refreshed and, if the request has an id, told whether the save was stored (`settingsSaveResult`): the // settings page keeps the user's edits as unsaved after a failure. The error is then thrown, as it always was. + // A command-list key whose scoped write fails is abandoned for that key only, without a throw, so its + // failure cannot ride the `failed` flag; it is tracked separately to keep the save result honest. let failed = false let failure: unknown + let commandListSaveFailed = false try { if (!message.updatedSettings) break @@ -834,9 +837,16 @@ export const webviewMessageHandler = async ( // downgraded to a per-key save failure. const config = commandListConfiguration() let inspection: CommandListInspection | undefined + // The same save-start snapshot keeps its global layer: the + // rollback below distinguishes an absent Global layer from an + // empty one, and re-reading here would give the rollback a + // configuration state the scope read never saw. + let globalLayerAtSaveStart: string[] | undefined let inspectionFailure: string | undefined try { - inspection = config.inspect(key) + const snapshot = config.inspect(key) + inspection = snapshot + globalLayerAtSaveStart = snapshot?.globalValue } catch (error) { inspectionFailure = error instanceof Error ? error.message : String(error) } @@ -845,9 +855,11 @@ export const webviewMessageHandler = async ( // at, and a guessed-empty layer re-copies workspace entries // into global settings, so this key's save is abandoned // while the remaining keys of the payload persist normally. + // The abandoned key still reports through the save result. vscode.window.showErrorMessage( `Failed to save ${key}: ${inspectionFailure ?? "the configuration value could not be read"}`, ) + commandListSaveFailed = true continue } @@ -898,68 +910,130 @@ export const webviewMessageHandler = async ( !hiddenWorkspaceEntries.includes(entry), ) : [] + // The baseline also carries the gate as the dialog last displayed + // it. When the gate flipped since, the hidden set can hold + // entries the user did see, and an entry the dialog displayed is + // existing workspace knowledge: keeping it must stay a workspace + // decision, not a brand-new promotion into the global layer. + // Entries hidden by shadowing (or by a gate state the baseline + // already reflects) are absent from the baseline, so their + // promotion behavior is unchanged. A baseline without the gate + // slot predates it and keeps the current classification. + const gateAtDisplay = message.commandListBaseline?.workspaceCommandListsEnabled + const promotionHiddenEntries = + gateAtDisplay === undefined || gateAtDisplay === workspaceCommandListsEnabled() + ? hiddenWorkspaceEntries + : hiddenWorkspaceEntries.filter( + (entry) => !Array.isArray(baseline) || !baseline.includes(entry), + ) const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( [...incoming, ...externallyAdded], // Hidden entries are not existing knowledge for promotion // purposes: the dialog never displayed them, so an entry the // user just added is new even when the workspace layer - // already holds it hidden. The re-add below restores the - // hidden entries this reduced layer drops. - currentScopes.workspace.filter((entry) => !hiddenWorkspaceEntries.includes(entry)), + // already holds it hidden — except entries the baseline + // shows the dialog did display. The re-add below restores + // the hidden entries this reduced layer drops. + currentScopes.workspace.filter((entry) => !promotionHiddenEntries.includes(entry)), currentScopes.global, ) const workspaceWrite = [...new Set([...keptWorkspaceWrite, ...hiddenWorkspaceEntries])] const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) - // The two configuration writes below are not atomic, so the raw - // previous workspace value comes from the same snapshot the split - // used, taken from the target that owns the workspace layer: a - // failed global write rewinds that target to exactly what it held - // beforehand, including the entries this save drops. The raw - // inspected value is used rather than the sanitized layer so the - // rewind reproduces the file contents instead of a cleaned-up - // approximation of them. - const previousWorkspaceValue = - workspaceTarget === vscode.ConfigurationTarget.WorkspaceFolder - ? inspection.workspaceFolderValue - : inspection.workspaceValue - let workspaceWriteApplied = false + // The two configuration writes below are not atomic, so their + // order is chosen against the composed enforcement set — the set + // union of the layers: the global layer is written first, so a + // save interrupted between the writes can only leave an entry + // duplicated across the layers (inert under the union, no + // approval outcome differs), never absent from both. A failed + // global write changes nothing and needs no compensation; only a + // failed workspace write leaves the global layer holding this + // save's value, and that half is undone below. + let globalWriteApplied = false try { - // Write the workspace layer first, at the target that owns it. - // When no workspace layer exists the write is skipped entirely - // so saving never materializes one; when entries were deleted + await config.update(key, globalWrite, vscode.ConfigurationTarget.Global) + globalWriteApplied = true + + // Then the workspace layer, at the target that owns it. When + // no workspace layer exists the write is skipped entirely so + // saving never materializes one; when entries were deleted // the `[]` write clears them at that scope. if (workspaceTarget !== undefined) { await config.update(key, workspaceWrite, workspaceTarget) - workspaceWriteApplied = true } - - await config.update(key, globalWrite, vscode.ConfigurationTarget.Global) } catch (error) { const failure = error instanceof Error ? error.message : String(error) - // A failed workspace write leaves nothing changed, so only a - // global-write failure has a changed workspace layer to rewind, - // and the rewind goes to the same target the write used. - if (workspaceWriteApplied) { + // Only a failed workspace write leaves a changed layer, and + // only the global one changed. The compensation undoes + // exactly this save's delta — removing the entries it added + // to the global layer and restoring the ones it deleted — + // against a fresh read, so entries a third party added to + // that layer mid-save survive. A whole-snapshot rewind + // would clobber them, and the configuration API offers no + // compare-and-set to make that safe. + if (globalWriteApplied) { + const addedByThisSave = globalWrite.filter( + (entry) => !currentScopes.global.includes(entry), + ) + const removedByThisSave = currentScopes.global.filter( + (entry) => !globalWrite.includes(entry), + ) + // The re-read is guarded: when even the read fails there + // is nothing safe to write, and falling back to the + // save-start value is the clobber this compensation + // exists to avoid. An undo that would empty a layer that + // is absent clears the key instead: the configuration + // distinguishes `[]` from absent, and the activation seed + // treats `[]` as an override, so writing `[]` where no + // value existed would suppress the default lists after a + // rolled-back save. + let freshGlobalValue: string[] | undefined + try { + freshGlobalValue = config.inspect(key)?.globalValue + } catch (reReadError) { + vscode.window.showErrorMessage( + `Failed to save ${key}: ${failure}. The global-scoped value could not be re-read to undo this save: ${reReadError}. Review the command lists in your user and workspace settings.`, + ) + commandListSaveFailed = true + continue + } + const globalUndo = [ + ...new Set([ + ...(freshGlobalValue ?? []).filter((entry) => !addedByThisSave.includes(entry)), + ...removedByThisSave, + ]), + ] + const hadGlobalLayer = + globalLayerAtSaveStart !== undefined && freshGlobalValue !== undefined try { - await config.update(key, previousWorkspaceValue, workspaceTarget) + if (globalUndo.length === 0 && !hadGlobalLayer) { + // Absent pre-save (or externally cleared mid-save) + // and nothing to restore: clear the key rather than + // materialize an empty layer. + await config.update(key, undefined, vscode.ConfigurationTarget.Global) + } else { + await config.update(key, globalUndo, vscode.ConfigurationTarget.Global) + } } catch (restoreError) { - // The rewind itself failed: the configuration keeps the + // The undo itself failed: the configuration keeps the // partially written values and the extension global-state // write is skipped, so stored state never reflects a save // that did not complete. The user hears about both failures. vscode.window.showErrorMessage( - `Failed to save ${key}: ${failure}. The workspace-scoped restore also failed: ${restoreError}. Review the command lists in your user and workspace settings.`, + `Failed to save ${key}: ${failure}. The global-scoped restore also failed: ${restoreError}. Review the command lists in your user and workspace settings.`, ) + commandListSaveFailed = true continue } } // Only this key's save is abandoned; the remaining keys of the - // payload persist normally. + // payload persist normally, and the abandoned key reports + // through the save result without re-raising the failure. vscode.window.showErrorMessage(`Failed to save ${key}: ${failure}`) + commandListSaveFailed = true continue } @@ -1102,7 +1176,10 @@ export const webviewMessageHandler = async ( await provider.postMessageToWebview({ type: "settingsSaveResult", requestId: message.requestId, - success: !failed, + // A per-key command-list failure does not throw, so it has to + // reach the result through its own flag; the error field stays + // with the thrown-failure path only. + success: !failed && !commandListSaveFailed, ...(failed ? { error: failure instanceof Error ? failure.message : String(failure) } : {}), }) } diff --git a/src/utils/__tests__/networkProxy.spec.ts b/src/utils/__tests__/networkProxy.spec.ts index 7827eff88b..568e9b7a94 100644 --- a/src/utils/__tests__/networkProxy.spec.ts +++ b/src/utils/__tests__/networkProxy.spec.ts @@ -12,9 +12,29 @@ import { createProxyRoutingRequestHandler, } from "../networkProxy" -// Mock global-agent -vi.mock("global-agent", () => ({ - bootstrap: vi.fn(), +// Mock global-agent and undici: the real bootstrap()/setGlobalDispatcher() write +// process-global state every later test would inherit, and the real ProxyAgent owns sockets. +const mocks = vi.hoisted(() => { + const closeSpy = vi.fn().mockResolvedValue(undefined) + return { + bootstrap: vi.fn(), + // mockImplementation with a plain function keeps the double constructible: the + // production path calls `new ProxyAgent(...)`, which an arrow implementation rejects. + proxyAgent: vi.fn().mockImplementation(function () { + return { close: closeSpy } + }), + proxyAgentClose: closeSpy, + setGlobalDispatcher: vi.fn(), + undiciFetch: vi.fn(), + } +}) + +vi.mock("global-agent", () => ({ bootstrap: mocks.bootstrap })) + +vi.mock("undici", () => ({ + ProxyAgent: mocks.proxyAgent, + setGlobalDispatcher: mocks.setGlobalDispatcher, + fetch: mocks.undiciFetch, })) vi.mock("@smithy/node-http-handler", () => ({ @@ -259,8 +279,9 @@ describe("networkProxy", () => { // dispose: the assertion below holds only if the returned aggregate releases the // same objects registered on context.subscriptions, which is the invariant. const registered = [...context.subscriptions] - // Configuration listener, override cleanup, and fetch patch: the scenario must - // register all three for the equivalence to cover every acquisition. + // Configuration listener, override cleanup, and the proxy-agent resource: the + // scenario must register all three for the equivalence to cover every + // acquisition. expect(registered.length).toBe(3) // Both observable overrides are applied before teardown. expect(globalThis.fetch).not.toBe(fetchSentinel) @@ -279,6 +300,267 @@ describe("networkProxy", () => { globalThis.fetch = fetchBefore } }) + + // The proxy agent owns sockets, and both configure* helpers suspend on dynamic imports, + // so teardown must close the agent and the import continuations must refuse to install + // process-global state after disposal. Each test re-imports the module after + // resetModules so the one-shot latches (global-agent bootstrap, fetch patch, dispatcher) + // start untripped, as the aggregate-invariant test above does. + describe("undici disposal and post-dispose import races", () => { + // A dynamic import of a mocked module still resolves asynchronously, so + // initializeNetworkProxy returns at its first await and the configure* continuations + // run only once the test awaits it: disposing synchronously in between lands the + // teardown while both imports are in flight, which is the interleaving the guards + // must reject. + function disposeMidFlight(context: vscode.ExtensionContext): void { + // Only the configuration listener and the override cleanup are registered while + // the imports are pending; disposing them is what VS Code does item-by-item on + // unload, and it latches the module's disposed flag. + expect(context.subscriptions).toHaveLength(2) + context.subscriptions.forEach((subscription) => subscription.dispose()) + } + + // Re-imported module plus a development-mode context with the debug proxy enabled; + // resetModules re-runs the vscode mock factory, so the fresh module's configuration + // spy needs the stub before initializeNetworkProxy reads it. The mock spies are + // shared across the file, so each test starts from a clean call log. + async function freshDebugRunContext(): Promise<{ + freshModule: typeof import("../networkProxy") + context: vscode.ExtensionContext + }> { + vi.clearAllMocks() + mocks.proxyAgent.mockImplementation(function () { + return { close: mocks.proxyAgentClose } + }) + const freshModule = await import("../networkProxy") + const freshVscode = await import("vscode") + vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( + makeWorkspaceConfiguration({ + "debugProxy.enabled": true, + "debugProxy.serverUrl": "http://localhost:8080", + "debugProxy.tlsInsecure": false, + }), + ) + return { freshModule, context: createMockContext(vscode.ExtensionMode.Development) } + } + + it("closes the proxy agent and restores the fetch patch when the returned disposable is disposed", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context } = await freshDebugRunContext() + + const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + + // Accept path: while the extension is alive the disposal guards are + // transparent, and everything this module can install gets installed. + expect(mocks.bootstrap).toHaveBeenCalledOnce() + expect(mocks.setGlobalDispatcher).toHaveBeenCalledWith( + expect.objectContaining({ close: mocks.proxyAgentClose }), + ) + expect(globalThis.fetch).not.toBe(fetchSentinel) + // Configuration listener, override cleanup, and the agent-owning undici + // resource: the agent must be among the registered subscriptions for the + // deactivate path to reach its close. + expect(context.subscriptions).toHaveLength(3) + + returned.dispose() + + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + + it("logs and swallows a rejected agent close during teardown", async () => { + vi.resetModules() + const closeFailure = new Error("close failed") + mocks.proxyAgentClose.mockRejectedValueOnce(closeFailure) + const fetchBefore = globalThis.fetch + globalThis.fetch = () => Promise.reject(new Error("sentinel fetch")) + let returned: vscode.Disposable | undefined + try { + const { freshModule, context } = await freshDebugRunContext() + + returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + + // A rejected close must not throw out of the synchronous dispose or leave an + // unhandled rejection: the teardown logs it and continues releasing resources. + expect(() => returned?.dispose()).not.toThrow() + // The rejection is logged on the microtask the best-effort close awaits. + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( + "Failed to close undici proxy agent: close failed", + ) + } finally { + returned?.dispose() + globalThis.fetch = fetchBefore + } + }) + + it("closes the agent only once when disposal runs through both owners", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context } = await freshDebugRunContext() + + const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + + // The undici resource is registered on context.subscriptions AND collected + // in the aggregate disposable, so an activation-failure teardown can reach + // it again after VS Code (or a re-disposal) already went through the list; + // the close must still happen exactly once. + returned.dispose() + returned.dispose() + context.subscriptions.forEach((subscription) => subscription.dispose()) + + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + expect(mocks.setGlobalDispatcher).toHaveBeenCalledOnce() + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + + it("skips the global-agent bootstrap when disposal runs before the import settles", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context } = await freshDebugRunContext() + + const init = freshModule.initializeNetworkProxy(context, mockOutputChannel) + disposeMidFlight(context) + await init + + // Reject path for the global-agent suspension point: the late continuation + // must not bootstrap global-agent for a disposed extension. + expect(mocks.bootstrap).not.toHaveBeenCalled() + expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( + "global-agent import completed after disposal; skipping bootstrap", + ) + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + + it("closes a late proxy agent without installing it when disposal runs before the undici import settles", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context } = await freshDebugRunContext() + + const init = freshModule.initializeNetworkProxy(context, mockOutputChannel) + disposeMidFlight(context) + await init + + // Reject path for the undici suspension point: the agent is constructed only + // once the import settles - after teardown - so the guard must close it and + // install nothing: no dispatcher swap, no fetch patch for a dead extension. + expect(mocks.proxyAgent).toHaveBeenCalledOnce() + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() + expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( + "undici import completed after disposal; closing the late proxy agent without installing it", + ) + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + }) + + // The configuration-change listener re-runs the configure* helpers when the debug proxy + // is toggled on mid-session. Both helpers are latched (bootstrap and dispatcher are + // one-shot), so after a successful activation the listener path re-enters them and + // returns through their already-configured branches; without this test those call + // sites would never execute. Runs on a reset module instance so the shared latches + // start untripped, as in the disposal tests. + it("re-runs both configure paths without re-installing when the proxy is toggled on again", async () => { + vi.resetModules() + const freshModule = await import("../networkProxy") + const freshVscode = await import("vscode") + vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( + makeWorkspaceConfiguration({ + "debugProxy.enabled": true, + "debugProxy.serverUrl": "http://localhost:8080", + "debugProxy.tlsInsecure": false, + }), + ) + let configListener: ((event: { affectsConfiguration: (section: string) => boolean }) => void) | undefined + vi.mocked(freshVscode.workspace.onDidChangeConfiguration).mockImplementation((listener) => { + configListener = listener as typeof configListener + return { dispose: vi.fn() } + }) + const context = createMockContext(vscode.ExtensionMode.Development) + + await freshModule.initializeNetworkProxy(context, mockOutputChannel) + vi.clearAllMocks() + + expect(configListener).toBeTypeOf("function") + configListener?.({ affectsConfiguration: () => true }) + // The re-entrant calls resolve on their own microtasks. + await new Promise((resolve) => setTimeout(resolve, 0)) + + // Nothing is installed twice: bootstrap and the dispatcher swap stay one-shot, and + // the log records both "already configured" branches rather than a failure. + expect(mocks.bootstrap).not.toHaveBeenCalled() + expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() + const logged = vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n") + expect(logged).toContain("Proxy already initialized, updating env vars only") + expect(logged).toContain("undici global dispatcher already configured") + }) + + // A second initialize on the same module instance reaches configureUndiciProxy through + // the already-configured latch, which returns no resource: the aggregate then collects + // only the listener and the override cleanup, and disposing it must not touch the agent + // owned by the first activation. + it("collects no agent resource on a re-initialization while the dispatcher latch is tripped", async () => { + vi.resetModules() + vi.clearAllMocks() + const fetchBefore = globalThis.fetch + globalThis.fetch = () => Promise.reject(new Error("sentinel fetch")) + try { + const freshModule = await import("../networkProxy") + const freshVscode = await import("vscode") + vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( + makeWorkspaceConfiguration({ + "debugProxy.enabled": true, + "debugProxy.serverUrl": "http://localhost:8080", + "debugProxy.tlsInsecure": false, + }), + ) + + const context = createMockContext(vscode.ExtensionMode.Development) + const first = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + expect(context.subscriptions).toHaveLength(3) + + const secondContext = createMockContext(vscode.ExtensionMode.Development) + const second = await freshModule.initializeNetworkProxy(secondContext, mockOutputChannel) + + // configureUndiciProxy returned undefined for the second run, so only the listener + // and the override cleanup are registered there. + expect(secondContext.subscriptions).toHaveLength(2) + + second.dispose() + // The first activation still owns the agent; the second teardown must not close it. + expect(mocks.proxyAgentClose).not.toHaveBeenCalled() + + first.dispose() + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + } finally { + globalThis.fetch = fetchBefore + } + }) }) describe("getProxyConfig", () => { diff --git a/src/utils/networkProxy.ts b/src/utils/networkProxy.ts index cc0c030699..a54694d1ec 100644 --- a/src/utils/networkProxy.ts +++ b/src/utils/networkProxy.ts @@ -72,6 +72,17 @@ function restoreGlobalFetchPatch(): void { originalFetch = undefined } +/** + * Fire-and-log variant of ProxyAgent.close(): Disposable.dispose() is synchronous while + * close() is async, and neither a teardown sequence nor the late-import abort may block on + * (or reject into) its caller. + */ +function closeProxyAgentBestEffort(proxyAgent: { close(): Promise }): void { + void proxyAgent.close().catch((error) => { + log(`Failed to close undici proxy agent: ${error instanceof Error ? error.message : String(error)}`) + }) +} + function restoreTlsVerificationOverride(): void { if (!tlsVerificationOverridden) { return @@ -152,6 +163,15 @@ export async function initializeNetworkProxy( // deactivate path, and both restores below are idempotent, so double disposal is safe. const resources: vscode.Disposable[] = [] + // The two dynamic imports in the configure* helpers below are suspension points: a teardown + // can run while one is pending, and its continuation would write process-global state + // (dispatcher, fetch patch, global-agent bootstrap) after disposal. Both disposal paths set + // the flag - the aggregate dispose at the end of this function, and overrideCleanup, which + // VS Code also disposes item-by-item through context.subscriptions - and each continuation + // checks it before installing. + let disposed = false + const isDisposed = () => disposed + // Listen for configuration changes to allow toggling proxy during a debug session. // Guard for test environments where onDidChangeConfiguration may not be mocked. if (typeof vscode.workspace.onDidChangeConfiguration === "function") { @@ -165,8 +185,8 @@ export async function initializeNetworkProxy( if (newConfig.enabled) { applyTlsVerificationOverride(newConfig) - configureGlobalProxy(newConfig) - configureUndiciProxy(newConfig) + configureGlobalProxy(newConfig, isDisposed) + configureUndiciProxy(newConfig, context, isDisposed) } else { // Proxy disabled - but we can't easily un-bootstrap global-agent or reset undici dispatcher safely. // We *can* restore any global fetch patch immediately. @@ -183,6 +203,9 @@ export async function initializeNetworkProxy( // Ensure we restore any overrides when the extension unloads. const overrideCleanup: vscode.Disposable = { dispose: () => { + // Latching disposal here covers the path where VS Code disposes context.subscriptions + // item-by-item; the aggregate dispose below sets the same flag itself. + disposed = true restoreGlobalFetchPatch() restoreTlsVerificationOverride() }, @@ -192,10 +215,10 @@ export async function initializeNetworkProxy( if (config.enabled) { applyTlsVerificationOverride(config) - await configureGlobalProxy(config) - const fetchPatch = await configureUndiciProxy(config) - if (fetchPatch) { - resources.push(fetchPatch) + await configureGlobalProxy(config, isDisposed) + const undiciResource = await configureUndiciProxy(config, context, isDisposed) + if (undiciResource) { + resources.push(undiciResource) } } else { log(`Debug proxy not enabled.`) @@ -203,6 +226,8 @@ export async function initializeNetworkProxy( return { dispose: () => { + // Stryker disable next-line BooleanLiteral: the override-cleanup resource disposed by the same loop latches the identical flag, so no interleaving distinguishes this assignment from its mutant. + disposed = true for (const resource of resources) { resource.dispose() } @@ -245,8 +270,11 @@ export function getProxyConfig(): ProxyConfig { /** * Configure global-agent to route all HTTP/HTTPS traffic through the proxy. + * + * @param isDisposed Teardown latch checked after the dynamic import below; bootstrap is + * skipped when the extension was disposed while the import was pending. */ -async function configureGlobalProxy(config: ProxyConfig): Promise { +async function configureGlobalProxy(config: ProxyConfig, isDisposed: () => boolean): Promise { if (proxyInitialized) { // global-agent can only be bootstrapped once // Update environment variables for any new connections @@ -270,6 +298,13 @@ async function configureGlobalProxy(config: ProxyConfig): Promise { return } + // A teardown may have run while the import above was pending; bootstrapping global-agent + // then would intercept this process's HTTP traffic for a dead extension. + if (isDisposed()) { + log("global-agent import completed after disposal; skipping bootstrap") + return + } + // Bootstrap global-agent to intercept all HTTP/HTTPS requests log(`Calling global-agent bootstrap()...`) try { @@ -288,10 +323,17 @@ async function configureGlobalProxy(config: ProxyConfig): Promise { * Configure undici's global dispatcher so Node's built-in `fetch()` and any undici-based * clients route through the proxy. * - * @returns A disposable restoring the global fetch patch when one was applied, or undefined - * when no patch was made (nothing to undo). Also registered on `context.subscriptions`. + * @param context The extension context whose subscriptions register the returned resource. + * @param isDisposed Teardown latch checked after the dynamic import below; a late import + * completion closes the freshly built agent instead of installing it. + * @returns A disposable that closes the created agent, or undefined when no agent was created + * (nothing to close). Also registered on `context.subscriptions`. */ -async function configureUndiciProxy(config: ProxyConfig): Promise { +async function configureUndiciProxy( + config: ProxyConfig, + context: vscode.ExtensionContext, + isDisposed: () => boolean, +): Promise { if (!config.enabled || !config.serverUrl) { return undefined } @@ -301,7 +343,7 @@ async function configureUndiciProxy(config: ProxyConfig): Promise restoreGlobalFetchPatch() } - if (extensionContext) { - extensionContext.subscriptions.push(fetchPatch) - } + // The agent owns sockets, so teardown must close it; restoring the fetch patch is owned + // by the override-cleanup resource, which every disposal path also disposes. Disposal + // reaches this resource from two owners (context.subscriptions and the aggregate + // returned by initializeNetworkProxy), so the once-guard keeps a double dispose to a + // single close of the same agent. + let agentClosed = false + undiciResource = { + dispose: () => { + if (!agentClosed) { + agentClosed = true + closeProxyAgentBestEffort(proxyAgent) + } + }, } + context.subscriptions.push(undiciResource) } catch (error) { log(`Failed to configure undici proxy dispatcher: ${error instanceof Error ? error.message : String(error)}`) } - return fetchPatch + return undiciResource } /** * Update environment variables for proxy configuration. diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 0ef43b2d39..7d0d72467f 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -342,17 +342,21 @@ const SettingsView = forwardRef(({ onDone, t // are themselves unposted, so the stamp keeps its prior lists instead - a // deletion inside the buffered edit must stay in the baseline for the save to // apply it rather than resurrect the deleted entry as an external addition. - const [stampAllowed, stampDenied] = commandListsTouched.current + // The gate slot holds back with those lists because the stamp has to describe + // one displayed state: pairing held-back lists with an externally-flipped gate + // would claim the held-back entries were displayed under a gate they never + // appeared alongside. + const [stampAllowed, stampDenied, stampGate] = commandListsTouched.current ? (JSON.parse(lastDisplayedCommandSnapshot.current) as [string[], string[], boolean]) : [ merged.allowedCommands ?? prevState.allowedCommands, merged.deniedCommands ?? prevState.deniedCommands, + merged.workspaceCommandListsEnabled ?? prevState.workspaceCommandListsEnabled, ] lastDisplayedCommandSnapshot.current = commandListSnapshot({ allowedCommands: stampAllowed, deniedCommands: stampDenied, - workspaceCommandListsEnabled: - merged.workspaceCommandListsEnabled ?? prevState.workspaceCommandListsEnabled, + workspaceCommandListsEnabled: stampGate, }) if (changedFields === 0) { @@ -506,11 +510,9 @@ const SettingsView = forwardRef(({ onDone, t const handleSubmit = () => { if (isSettingValid) { - const [lastDisplayedAllowed, lastDisplayedDenied] = JSON.parse(lastDisplayedCommandSnapshot.current) as [ - string[], - string[], - boolean, - ] + const [lastDisplayedAllowed, lastDisplayedDenied, gateAtSubmit] = JSON.parse( + lastDisplayedCommandSnapshot.current, + ) as [string[], string[], boolean] const saveId = displayChanged ? nextSaveRequestId() : undefined if (saveId) { @@ -528,6 +530,16 @@ const SettingsView = forwardRef(({ onDone, t commandListBaseline: { allowedCommands: lastDisplayedAllowed, deniedCommands: lastDisplayedDenied, + // The gate travels with the lists it was displayed alongside: the stamp + // always carries the gate that was on screen with its lists, so a gate + // flip between display and save cannot pair old-gate entries with a + // new-gate label and reclassify a baseline-shown entry as a brand-new + // promotion into the global layer. A dialog whose host never delivered + // the gate has no displayed gate to accompany the baseline: it posts + // none, and the save path keeps the legacy classification for an + // absent flag. + workspaceCommandListsEnabled: + cachedState.workspaceCommandListsEnabled === undefined ? undefined : gateAtSubmit, }, updatedSettings: { language, @@ -616,7 +628,7 @@ const SettingsView = forwardRef(({ onDone, t lastDisplayedCommandSnapshot.current = commandListSnapshot({ allowedCommands, deniedCommands, - workspaceCommandListsEnabled: cachedState.workspaceCommandListsEnabled, + workspaceCommandListsEnabled: gateAtSubmit, }) // The stamp records what is on screen, so it moves at submit; the settle below then re-derives each // edited list's entry from whether that list's own write landed. The lists' ownership of the buffer diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx index 7251b25738..16608e6363 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -794,6 +794,136 @@ describe("SettingsView - Allowed Commands", () => { ) }) + it("carries the gate displayed as on in the save baseline", () => { + // The save path compares this flag against the gate at write time: with the flag + // on, entries the baseline displayed are existing workspace knowledge, so a gate + // flip between display and save cannot reclassify a kept entry as a brand-new + // promotion into the global layer. + renderWithExtensionState(, { + state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: true }, + }) + + const content = screen.getByTestId("settings-content") + // A dirty list edit so the save button is live, the way a real save would have one. + const input = within(content).getByTestId("command-input") + fireEvent.change(input, { target: { value: "npm test" } }) + fireEvent.click(within(content).getByTestId("add-command-button")) + + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { + allowedCommands: ["git"], + deniedCommands: [], + workspaceCommandListsEnabled: true, + }, + }), + ) + }) + + it("keeps the stamped gate paired with held-back lists when the gate flips during a buffered edit", async () => { + // An external state post flips the gate while a list edit is in flight: the lists are held + // back, so the baseline must keep the gate those entries were displayed under - posting + // the flipped gate alongside the held-back entries would let the save path classify a + // baseline-shown workspace entry as a brand-new promotion into the global layer. + renderWithExtensionState(, { + state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: true }, + }) + + const content = screen.getByTestId("settings-content") + const input = within(content).getByTestId("command-input") + fireEvent.change(input, { target: { value: "npm test" } }) + fireEvent.click(within(content).getByTestId("add-command-button")) + + await act(async () => { + mockPostMessage({ + allowedCommands: ["git", "curl"], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: false, + }) + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { + allowedCommands: ["git"], + deniedCommands: [], + workspaceCommandListsEnabled: true, + }, + }), + ) + }) + + it("sends the merged gate with the merged lists when no list edit is in flight", async () => { + // The same merge's other branch: with no in-flight list edit the merge adopts the posted + // lists AND the gate, so the baseline describes the newly displayed state - the pairing + // guard holds in both directions, and a held stamp must not strand a stale gate. + renderWithExtensionState(, { + state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: false }, + }) + + await act(async () => { + mockPostMessage({ + allowedCommands: ["git", "curl"], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: true, + }) + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + // A non-list edit makes the save button live without claiming ownership of the lists. + const content = screen.getByTestId("settings-content") + fireEvent.click(within(content).getByTestId("always-allow-execute-toggle")) + + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { + allowedCommands: ["git", "curl"], + deniedCommands: [], + workspaceCommandListsEnabled: true, + }, + updatedSettings: expect.objectContaining({ allowedCommands: ["git", "curl"] }), + }), + ) + }) + + it("carries the gate displayed as off in the save baseline without persisting it", () => { + // The gate value reaches the save path through the baseline only: the dialog + // displays the host's gate but never writes it, so the flag must not appear in + // the settings payload the host persists. + renderWithExtensionState(, { + state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: false }, + }) + + const content = screen.getByTestId("settings-content") + const input = within(content).getByTestId("command-input") + fireEvent.change(input, { target: { value: "npm test" } }) + fireEvent.click(within(content).getByTestId("add-command-button")) + + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { + allowedCommands: ["git"], + deniedCommands: [], + workspaceCommandListsEnabled: false, + }, + updatedSettings: expect.not.objectContaining({ workspaceCommandListsEnabled: expect.anything() }), + }), + ) + }) + it("removes command from the list", () => { // Render once and get the activateTab helper const { activateTab, getSettingsContent } = renderSettingsView() diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 34c264270e..b46b8e31bb 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -1009,6 +1009,53 @@ describe("SettingsView - Unsaved Changes Detection", () => { ) }) + it("sends a list-only save with no answer id and releases it at submit", async () => { + // A save that changes only the command lists carries no request id - the answer path needs a + // display-setting change - so the ack-driven failure retention the neighboring tests pin is + // unreachable for it. What the current code can prove for a no-requestId save: the hold and the + // unsaved flag release at submit, and the following state post is classified against the submitted + // lists - showing the submitted entry (write landed) leaves the dialog clean, while a refresh + // without it (a rejected write is indistinguishable from an external edit at this point) folds + // into the dialog without re-dirtying it. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("buffer-deny-edit")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + fireEvent.click(screen.getByTestId("save-button")) + + // The list-only save posted the edit and asked for no answer. + expect(updateSettingsPosts()).toHaveLength(1) + expect(lastSaveRequestId(postMessage)).toBeUndefined() + // With no answer to wait for, the hold releases at submit and the flag goes clean. + expect(screen.getByTestId("save-button")).toBeDisabled() + + // The write did not land: the refresh carries the original list. The submitted entry is absent + // from it, so the merge treats the post as an external change over an already-committed dialog + // and folds it in - the edit is gone and the flag stays off. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: [], + }) + view.rerender() + await waitFor(() => expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify([]))) + expect(screen.getByTestId("save-button")).toBeDisabled() + }) + it("reconciles each list's retry baseline with that list's own write outcome after a failed save", async () => { // A failed save reports one outcome for the whole payload, yet its writes ran setting by setting: the // refresh the host posts before the answer carries each list's configuration result. A list whose own From 4df9ebf1f34a9f42ba0cb9b52e6d7cc5351d2aad Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Fri, 13 Nov 2026 12:28:20 +0100 Subject: [PATCH 19/52] fix: derive command-list rollback from config, restore proxy dispatcher Command-list save rollback now computes what the failed save changed from the configuration layer captured at save start instead of the extension state copy. The two copies can diverge when another writer updates the configuration mid-save, and a delta computed against the stale copy could restore that stale list over entries the failed save had already written. Proxy agents built when a configuration change enables the debug proxy are now registered with the teardown resources like the seed-time agent, so they are closed on deactivation and on failed activation instead of leaking. On disposal, the undici global dispatcher that was active before the extension installed its proxy agent is put back, but only while the global slot still holds that agent; a dispatcher a third party installed since is left alone. A second install that races the first is now aborted and its agent closed instead of overwriting the first dispatcher. Tests cover the config-versus-state divergence in the rollback, the listener-created agent closing through the activation teardown, dispatcher restore ordering and the third-party skip, the raced second install, and a queued command drained while blanket deny engages, approved and denied against the task folder's own policy. --- src/__tests__/extension.spec.ts | 101 +++++- .../task/__tests__/ask-allowlist-cwd.spec.ts | 62 ++++ .../__tests__/webviewMessageHandler.spec.ts | 62 +++- src/core/webview/webviewMessageHandler.ts | 23 +- src/utils/__tests__/networkProxy.spec.ts | 294 +++++++++++++++++- src/utils/networkProxy.ts | 68 ++-- 6 files changed, 575 insertions(+), 35 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index bdf5a7f966..327c38c38d 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -3,7 +3,12 @@ import type * as vscode from "vscode" import type { WebviewMessage } from "@roo-code/types" -import { makeCompositeDisposable, makeEventEmitter, makeExtensionContext } from "../test-utils/vscode" +import { + makeCompositeDisposable, + makeEventEmitter, + makeExtensionContext, + makeWorkspaceConfiguration, +} from "../test-utils/vscode" vi.mock("vscode", () => ({ Disposable: { from: (...subscriptions: vscode.Disposable[]) => makeCompositeDisposable(...subscriptions) }, @@ -24,6 +29,7 @@ vi.mock("vscode", () => ({ get: vi.fn().mockReturnValue([]), inspect: vi.fn(), }), + onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })), createFileSystemWatcher: vi.fn().mockReturnValue({ onDidCreate: vi.fn(), onDidChange: vi.fn(), @@ -804,6 +810,99 @@ describe("extension.ts", () => { } }) + // When activation starts with the debug proxy disabled, only the configuration + // listener can build the undici dispatcher agent, so the failed-activation + // teardown must own that listener-created resource. This runs the real + // initializer with undici/global-agent doubles swapped in and gates the seed + // rejection until the listener-path install has settled, so the close is + // observed through the aggregate dispose rather than the late-import guard. + test("closes the listener-created proxy agent when seeding rejects after a mid-session enable", async () => { + let rejectSeed: () => void = () => {} + vi.doMock("../utils/seedAllowedCommands", () => ({ + seedCommandList: vi.fn( + () => + new Promise((_resolve, reject) => { + rejectSeed = () => reject(new Error("seed state write failed")) + }), + ), + })) + const closeSpy = vi.fn().mockResolvedValue(undefined) + const proxyAgentCtor = vi.fn().mockImplementation(function () { + return { close: closeSpy } + }) + // The slot double mirrors undici's global dispatcher state so the conditional + // restore is observable on this teardown path. + const defaultDispatcher = { close: vi.fn().mockResolvedValue(undefined) } + const dispatcherSlot: { current: unknown } = { current: defaultDispatcher } + const setGlobalDispatcher = vi.fn((dispatcher: unknown) => { + dispatcherSlot.current = dispatcher + }) + const getGlobalDispatcher = vi.fn(() => dispatcherSlot.current) + vi.doMock("undici", () => ({ + ProxyAgent: proxyAgentCtor, + setGlobalDispatcher, + getGlobalDispatcher, + fetch: vi.fn(), + })) + vi.doMock("global-agent", () => ({ bootstrap: vi.fn() })) + try { + const vscode = await import("vscode") + const { Package } = await import("../shared/package") + let configListener: + ((event: { affectsConfiguration: (section: string) => boolean }) => void) | undefined + vi.mocked(vscode.workspace.onDidChangeConfiguration).mockImplementation((listener) => { + configListener = listener as typeof configListener + return { dispose: vi.fn() } + }) + // Mutable so flipping enabled=true re-reads exactly like a live settings + // toggle: the helper's get() reads the record at call time. + const debugProxyValues: Record = { + "debugProxy.enabled": false, + "debugProxy.serverUrl": "http://localhost:8080", + "debugProxy.tlsInsecure": false, + } + const otherSections = makeWorkspaceConfiguration() + vi.mocked(vscode.workspace.getConfiguration).mockImplementation((section?: string) => + section === Package.name ? makeWorkspaceConfiguration(debugProxyValues) : otherSections, + ) + const fetchBefore = globalThis.fetch + try { + const devContext = { ...mockContext, extensionMode: vscode.ExtensionMode.Development } + const { activate } = await import("../extension") + const activation = activate(devContext) + + // Activation has registered the configuration listener and reached the + // gated seed: flip the toggle on, as a mid-session settings change would. + await vi.waitFor(() => expect(configListener).toBeTypeOf("function")) + debugProxyValues["debugProxy.enabled"] = true + configListener?.({ affectsConfiguration: () => true }) + // The listener-path agent is installed before the seed failure arrives, so + // the teardown below closes an installed agent, not a late-import one. + await vi.waitFor(() => expect(setGlobalDispatcher).toHaveBeenCalledOnce()) + + rejectSeed() + await expect(activation).rejects.toThrow("seed state write failed") + + // The aggregate owned the listener-created agent: the dispatcher captured + // at install is back in the slot and the agent closed exactly once. + expect(dispatcherSlot.current).toBe(defaultDispatcher) + expect(setGlobalDispatcher).toHaveBeenLastCalledWith(defaultDispatcher) + expect(closeSpy).toHaveBeenCalledOnce() + // The fetch patch the listener applied is restored by the same teardown. + expect(globalThis.fetch).toBe(fetchBefore) + } finally { + globalThis.fetch = fetchBefore + delete process.env.GLOBAL_AGENT_HTTP_PROXY + delete process.env.GLOBAL_AGENT_HTTPS_PROXY + delete process.env.GLOBAL_AGENT_NO_PROXY + } + } finally { + vi.doUnmock("../utils/seedAllowedCommands") + vi.doUnmock("undici") + vi.doUnmock("global-agent") + } + }) + test("disposes the output channel last when seeding rejects activation", async () => { // The output channel is the first resource `activate` acquires, and the // host does not guarantee `deactivate()` after a failed activation, so diff --git a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts index e82b094d60..f2baa92d22 100644 --- a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts +++ b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts @@ -314,6 +314,68 @@ describe("Task.ask judges command asks by the command's working directory", () = errorSpy.mockRestore() }) + it("re-checks an entry-drained queued command against the task folder's policy once blanket deny engages", async () => { + // Same entry drain as the no-context test above, but blanket deny is + // engaged on the drain read, so the re-check reaches directory + // selection instead of consuming the queued message as a legitimate + // approval. The task's folder is made the SECOND workspace folder + // (folder order swapped) while it allows "echo": a re-check that fell + // back to the first workspace folder — which denies it — would deny, + // so the approval names the task folder's directory. + openTwoFolders() + workspaceState.workspaceFolders = [ + { fsPath: FOLDER_B, uri: { fsPath: FOLDER_B } }, + { fsPath: FOLDER_A, uri: { fsPath: FOLDER_A } }, + ] + const provider: ProviderStub = { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + cwd: PROVIDER_CWD, + // First read (ask time): blanket deny off, so the entry claim gate + // opens. Second read (entry-drain re-check): blanket deny engaged, + // so the queued message must re-earn its approval. + getState: vi + .fn() + .mockResolvedValueOnce(commandState({ alwaysDenyUnapprovedCommands: false })) + .mockResolvedValue(commandState({ alwaysDenyUnapprovedCommands: true })), + } + const task = buildTask(provider, FOLDER_A) + await attachQueue(task) + task.messageQueueService.addMessage("run it") + + // No approval context: the re-check falls back to the task's own + // directory, where folder A's entry grants the queued approval. + const result = await task.ask("command", "echo hi", false) + + expect(result.response).toBe("yesButtonClicked") + expect(result.autoDenyDetail).toBeUndefined() + }) + + it("denies an entry-drained queued command whose task folder denies it, although the first workspace folder allows it", async () => { + // The paired reject path: the task is rooted in folder B (which denies + // "echo") and folder B is NOT the first workspace folder. With blanket + // deny engaged on the drain read, the re-check selects the task + // folder's directory; a fallback to the first workspace folder (which + // allows "echo") would approve, so the denial names the folder the + // task actually runs in. + openTwoFolders() + const provider: ProviderStub = { + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + cwd: PROVIDER_CWD, + getState: vi + .fn() + .mockResolvedValueOnce(commandState({ alwaysDenyUnapprovedCommands: false })) + .mockResolvedValue(commandState({ alwaysDenyUnapprovedCommands: true })), + } + const task = buildTask(provider, FOLDER_B) + await attachQueue(task) + task.messageQueueService.addMessage("run it") + + const result = await task.ask("command", "echo hi", false) + + expect(result.response).toBe("noButtonClicked") + expect(result.autoDenyDetail?.kind).toBe("denylist") + }) + it("denies a drained queued command whose working directory the policy denies, although the blanket path would accept it", async () => { openTwoFolders() const provider: ProviderStub = { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 8053d461a1..d00c99473d 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2301,7 +2301,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["npm docker", "docker"] }, undefined, { globalValue: ["aws", "mid-save"] }], + [ + { globalValue: ["keep", "drop"], workspaceValue: ["npm docker", "docker"] }, + undefined, + { globalValue: ["aws", "mid-save"] }, + ], true, ) @@ -2326,6 +2330,46 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) + it("computes the undo delta against the configuration layer when the extension-state copy is stale", async () => { + // The global write targets the configuration layer, not the extension + // state cache, so that layer's save-start value is the compensation's + // delta baseline. Here the state copy is stale ("old" where the + // configuration holds "manual"): a delta computed against the cache + // would restore the stale list over the value the failed save replaced, + // permanently dropping "manual". The undo follows the configuration + // layer instead. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["old"] : undefined, + ) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ globalValue: ["manual"], workspaceValue: ["docker"] }, undefined, { globalValue: ["aws", "mid-save"] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + // The save wrote ["aws"] over the configuration's ["manual"]. + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + // The undo removes this save's addition, keeps the mid-save addition, and + // restores the configuration-layer entry the save dropped — not the stale + // state copy's "old". + expect(update).toHaveBeenNthCalledWith( + 3, + "deniedCommands", + ["mid-save", "manual"], + vscode.ConfigurationTarget.Global, + ) + expect(update).toHaveBeenCalledTimes(3) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") + }) + it("rolls the global layer back on a folder-target save and still persists the payload's other keys", async () => { // update() call order: global write succeeds, the folder-target // workspace write rejects, the undo restores the global deletions at @@ -2338,7 +2382,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { {}, [undefined, Promise.reject(new Error("disk on fire")), undefined], [ - { workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, + { globalValue: ["drop"], workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, undefined, { globalValue: [], @@ -2715,7 +2759,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["keep", "aws", "mid-save"] }], + [ + { globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, + undefined, + { globalValue: ["keep", "aws", "mid-save"] }, + ], true, ) @@ -2746,7 +2794,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws", "mid-save"] }], + [ + { globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, + undefined, + { globalValue: ["aws", "mid-save"] }, + ], true, ) @@ -2774,7 +2826,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["docker"] }, undefined, undefined], + [{ globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, undefined], true, ) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 84a1640ea3..de17b8fe13 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -839,8 +839,10 @@ export const webviewMessageHandler = async ( let inspection: CommandListInspection | undefined // The same save-start snapshot keeps its global layer: the // rollback below distinguishes an absent Global layer from an - // empty one, and re-reading here would give the rollback a - // configuration state the scope read never saw. + // empty one and computes this save's delta against it — the + // layer the write below actually targets — and re-reading here + // would give the rollback a configuration state the scope read + // never saw. let globalLayerAtSaveStart: string[] | undefined let inspectionFailure: string | undefined try { @@ -865,6 +867,19 @@ export const webviewMessageHandler = async ( const currentScopes = readCommandListScopes(key, getGlobalState(key), inspection) + // The compensation's delta baseline: the global layer of the same + // save-start snapshot — the configuration the global write below + // targets — sanitized the way every command-list read sanitizes it. + // The extension state copy (`currentScopes.global`) is a separate + // cache that can hold a different list, and a delta computed + // against it would restore that stale list over the entries a + // rolled-back save actually wrote over in the configuration. + const configGlobalAtSaveStart = readCommandListScopes( + key, + globalLayerAtSaveStart, + inspection, + ).global + // Shadowing is cross-directional, so the hidden-entry set // needs the opposite key's global layer as input. It comes // from the save-start snapshot, not a fresh read: an @@ -975,9 +990,9 @@ export const webviewMessageHandler = async ( // compare-and-set to make that safe. if (globalWriteApplied) { const addedByThisSave = globalWrite.filter( - (entry) => !currentScopes.global.includes(entry), + (entry) => !configGlobalAtSaveStart.includes(entry), ) - const removedByThisSave = currentScopes.global.filter( + const removedByThisSave = configGlobalAtSaveStart.filter( (entry) => !globalWrite.includes(entry), ) // The re-read is guarded: when even the read fails there diff --git a/src/utils/__tests__/networkProxy.spec.ts b/src/utils/__tests__/networkProxy.spec.ts index 568e9b7a94..6e6d7a849a 100644 --- a/src/utils/__tests__/networkProxy.spec.ts +++ b/src/utils/__tests__/networkProxy.spec.ts @@ -16,6 +16,11 @@ import { // process-global state every later test would inherit, and the real ProxyAgent owns sockets. const mocks = vi.hoisted(() => { const closeSpy = vi.fn().mockResolvedValue(undefined) + // undici's global dispatcher slot always holds a dispatcher (it lazily creates the + // default one), so the double's slot starts with a sentinel object rather than + // undefined: a captured "previous dispatcher" must be a real object, as in undici. + const defaultDispatcher = { close: vi.fn().mockResolvedValue(undefined) } + const dispatcherSlot: { current: unknown } = { current: defaultDispatcher } return { bootstrap: vi.fn(), // mockImplementation with a plain function keeps the double constructible: the @@ -24,7 +29,15 @@ const mocks = vi.hoisted(() => { return { close: closeSpy } }), proxyAgentClose: closeSpy, - setGlobalDispatcher: vi.fn(), + // A scriptable slot mirrors undici's global dispatcher state: get returns what set + // last wrote, so a test can install a third-party dispatcher between install and + // teardown and observe which dispatcher survives. + setGlobalDispatcher: vi.fn((dispatcher: unknown) => { + dispatcherSlot.current = dispatcher + }), + getGlobalDispatcher: vi.fn(() => dispatcherSlot.current), + dispatcherSlot, + defaultDispatcher, undiciFetch: vi.fn(), } }) @@ -34,6 +47,7 @@ vi.mock("global-agent", () => ({ bootstrap: mocks.bootstrap })) vi.mock("undici", () => ({ ProxyAgent: mocks.proxyAgent, setGlobalDispatcher: mocks.setGlobalDispatcher, + getGlobalDispatcher: mocks.getGlobalDispatcher, fetch: mocks.undiciFetch, })) @@ -107,6 +121,9 @@ describe("networkProxy", () => { beforeEach(() => { vi.clearAllMocks() + // Dispatcher-slot state is process-lifetime in undici; reset it per test so each + // run captures the same "previous dispatcher". + mocks.dispatcherSlot.current = mocks.defaultDispatcher // Reset environment variables delete process.env.GLOBAL_AGENT_HTTP_PROXY @@ -420,7 +437,73 @@ describe("networkProxy", () => { context.subscriptions.forEach((subscription) => subscription.dispose()) expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(mocks.setGlobalDispatcher).toHaveBeenCalledOnce() + // Install plus the single conditional restore from the first dispose; the + // once-guard keeps the repeated disposals from restoring or closing again. + expect(mocks.setGlobalDispatcher).toHaveBeenCalledTimes(2) + expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + + // The dispatcher that predates the install must be back in undici's global slot + // after teardown, or every later fetch in a surviving extension host routes + // through the closed proxy agent. + it("restores the dispatcher captured at install time when the returned disposable is disposed", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context } = await freshDebugRunContext() + + const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + + const installed = mocks.dispatcherSlot.current + expect(installed).not.toBe(mocks.defaultDispatcher) + + returned.dispose() + + // The captured pre-install dispatcher is back, not a fresh default or an + // unset slot: this is dispatcher restoration, not fetch-function identity. + expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) + expect(mocks.setGlobalDispatcher).toHaveBeenLastCalledWith(mocks.defaultDispatcher) + // Restore happens before the close, so no fetch started after teardown can + // land on the closing agent. + expect(mocks.setGlobalDispatcher.mock.invocationCallOrder[1]).toBeLessThan( + mocks.proxyAgentClose.mock.invocationCallOrder[0], + ) + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + + it("leaves a third-party dispatcher installed after ours untouched when disposal runs", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context } = await freshDebugRunContext() + + const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + + // Another component replaces the global slot after our install; that slot + // belongs to its installer, so our teardown must leave it alone. + const thirdPartyDispatcher = { close: vi.fn().mockResolvedValue(undefined) } + mocks.setGlobalDispatcher(thirdPartyDispatcher) + + returned.dispose() + + expect(mocks.dispatcherSlot.current).toBe(thirdPartyDispatcher) + // Install + third-party swap only: no restore call on this branch. + expect(mocks.setGlobalDispatcher).toHaveBeenCalledTimes(2) + expect(mocks.setGlobalDispatcher).toHaveBeenLastCalledWith(thirdPartyDispatcher) + // The conditional restore does not skip closing the agent we own. + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() expect(globalThis.fetch).toBe(fetchSentinel) } finally { globalThis.fetch = fetchBefore @@ -479,6 +562,213 @@ describe("networkProxy", () => { }) }) + // When the proxy is disabled at activation, only the configuration-change listener + // can build the dispatcher agent later; the aggregate disposable must own that + // listener-created resource too, or a mid-session enable survives the teardown a + // failed activation performs. Each test runs on a reset module instance so the + // shared latches start untripped, as in the disposal tests. + describe("listener-path agent ownership", () => { + // Fresh module instance whose activation starts with the proxy disabled; the + // configuration record is mutable so a test can flip debugProxy.enabled before + // firing the captured configuration-change listener. + async function freshToggledRunContext(): Promise<{ + freshModule: typeof import("../networkProxy") + context: vscode.ExtensionContext + configValues: Record + fireConfigChange: () => void + }> { + vi.clearAllMocks() + const configValues: Record = { + "debugProxy.enabled": false, + "debugProxy.serverUrl": "http://localhost:8080", + "debugProxy.tlsInsecure": false, + } + const freshModule = await import("../networkProxy") + const freshVscode = await import("vscode") + vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( + makeWorkspaceConfiguration(configValues), + ) + let configListener: + ((event: { affectsConfiguration: (section: string) => boolean }) => void) | undefined + vi.mocked(freshVscode.workspace.onDidChangeConfiguration).mockImplementation((listener) => { + configListener = listener as typeof configListener + return { dispose: vi.fn() } + }) + const context = createMockContext(vscode.ExtensionMode.Development) + return { + freshModule, + context, + configValues, + fireConfigChange: () => configListener?.({ affectsConfiguration: () => true }), + } + } + + it("closes the listener-created agent exactly once when the aggregate disposable is disposed", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context, configValues, fireConfigChange } = await freshToggledRunContext() + + const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + + // Activation with the proxy disabled registers only the listener and the + // override cleanup; no agent is built yet. + expect(context.subscriptions).toHaveLength(2) + expect(mocks.proxyAgent).not.toHaveBeenCalled() + + configValues["debugProxy.enabled"] = true + fireConfigChange() + // The listener's configure* calls resolve on their own microtasks. + await vi.waitFor(() => expect(mocks.proxyAgent).toHaveBeenCalledOnce()) + expect(mocks.setGlobalDispatcher).toHaveBeenCalledOnce() + expect(mocks.dispatcherSlot.current).not.toBe(mocks.defaultDispatcher) + expect(globalThis.fetch).not.toBe(fetchSentinel) + + returned.dispose() + + // The aggregate owns the agent the listener created: its close and the + // dispatcher restore run here, not at toggle time. + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) + expect(globalThis.fetch).toBe(fetchSentinel) + + // Re-disposal through the same owner must not close a second time. + returned.dispose() + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + } finally { + globalThis.fetch = fetchBefore + } + }) + + it("closes an agent created by a post-dispose listener event without installing it", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context, configValues, fireConfigChange } = await freshToggledRunContext() + + await freshModule.initializeNetworkProxy(context, mockOutputChannel) + configValues["debugProxy.enabled"] = true + + // Disposing first, then toggling, is the interleaving that a settings + // event can still deliver after a failed activation tore everything down. + context.subscriptions.forEach((subscription) => subscription.dispose()) + fireConfigChange() + + // The disposal latch rejects the late continuation: the agent is closed + // without ever being installed, so no new agent leaks into the process. + await vi.waitFor(() => expect(mocks.proxyAgent).toHaveBeenCalledOnce()) + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() + expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) + expect(mocks.bootstrap).not.toHaveBeenCalled() + expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( + "undici import completed after disposal; closing the late proxy agent without installing it", + ) + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + + // Two debugProxy config events fired inside the `await import("undici")` window both + // pass the already-configured check ahead of the import. Only the first may install: + // a second install would capture the first agent as its "previous dispatcher", and + // that teardown would then restore a closed agent into undici's global slot. + // doMock keeps the undici factory pending so the first event is verifiably parked + // at its import while the second event passes the latch check; the file-level static + // mock cannot provide that window because its module is already resolved in every + // later test. + it("closes the second of two config events fired inside the undici import window", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + let releaseImport: () => void = () => {} + const importPending = new Promise((resolve) => { + releaseImport = resolve + }) + vi.doMock("undici", () => + importPending.then(() => ({ + ProxyAgent: mocks.proxyAgent, + setGlobalDispatcher: mocks.setGlobalDispatcher, + getGlobalDispatcher: mocks.getGlobalDispatcher, + fetch: mocks.undiciFetch, + })), + ) + try { + const { freshModule, context, configValues, fireConfigChange } = await freshToggledRunContext() + // Once-implementations so the per-agent close spies do not leak past this + // test: the shared file-level spy cannot say *which* of the two agents a + // close came from, and this witness turns on that distinction. Exactly two + // constructions occur, consuming both queued implementations. + const agents: Array<{ close: ReturnType }> = [] + const recordAgent = function (this: unknown) { + const close = vi.fn().mockResolvedValue(undefined) + const agent = { close } + agents.push(agent) + return agent + } + mocks.proxyAgent.mockImplementationOnce(recordAgent).mockImplementationOnce(recordAgent) + + const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) + configValues["debugProxy.enabled"] = true + + fireConfigChange() + // The first event is now parked in configureUndiciProxy's import: the pending + // factory keeps it suspended while the module registration settles, so the + // second event demonstrably passes the latch check mid-flight. + await new Promise((resolve) => setTimeout(resolve, 10)) + expect(mocks.proxyAgent).not.toHaveBeenCalled() + fireConfigChange() + releaseImport() + + await vi.waitFor(() => expect(mocks.proxyAgent).toHaveBeenCalledTimes(2)) + expect(agents).toHaveLength(2) + + // Accept path: the first event installs and owns the global slot. + expect(mocks.dispatcherSlot.current).toBe(agents[0]) + expect(mocks.setGlobalDispatcher).toHaveBeenCalledOnce() + expect(mocks.setGlobalDispatcher).toHaveBeenCalledWith(agents[0]) + + // Reject path: the second event aborts at the post-import latch re-check — + // it never reaches the previous-dispatcher capture (one getGlobalDispatcher + // call: the first capture; dispose below adds the restore check), and its + // agent is closed without ever entering the dispatcher slot. + expect(mocks.getGlobalDispatcher).toHaveBeenCalledTimes(1) + expect(agents[1].close).toHaveBeenCalledOnce() + // The aborted call registers no resource, so the first install's disposable + // remains the only teardown path for the slot. + expect(context.subscriptions).toHaveLength(3) + + returned.dispose() + + // The owning disposable restores the dispatcher it captured (the default), + // not the closed agent a double install would have recorded. + expect(agents[0].close).toHaveBeenCalledOnce() + expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) + expect(mocks.setGlobalDispatcher).toHaveBeenLastCalledWith(mocks.defaultDispatcher) + } finally { + // Re-register a synchronous factory with the same spies and drop the cached + // module: tests running after this one then resolve undici exactly as they + // do through the file-level mock (unmocking instead would expose the real + // package to those tests, and the pending-import factory above is now + // permanently bypassed). + vi.doMock("undici", () => ({ + ProxyAgent: mocks.proxyAgent, + setGlobalDispatcher: mocks.setGlobalDispatcher, + getGlobalDispatcher: mocks.getGlobalDispatcher, + fetch: mocks.undiciFetch, + })) + vi.resetModules() + globalThis.fetch = fetchBefore + } + }) + }) + // The configuration-change listener re-runs the configure* helpers when the debug proxy // is toggled on mid-session. Both helpers are latched (bootstrap and dispatcher are // one-shot), so after a successful activation the listener path re-enters them and diff --git a/src/utils/networkProxy.ts b/src/utils/networkProxy.ts index a54694d1ec..45e0df2a08 100644 --- a/src/utils/networkProxy.ts +++ b/src/utils/networkProxy.ts @@ -186,10 +186,15 @@ export async function initializeNetworkProxy( if (newConfig.enabled) { applyTlsVerificationOverride(newConfig) configureGlobalProxy(newConfig, isDisposed) - configureUndiciProxy(newConfig, context, isDisposed) + // The aggregate owns whatever this enables: without registering the created + // agent resource here, a proxy toggled on mid-session would survive every + // teardown path the returned disposable covers. + configureUndiciProxy(newConfig, context, isDisposed, (resource) => resources.push(resource)) } else { - // Proxy disabled - but we can't easily un-bootstrap global-agent or reset undici dispatcher safely. - // We *can* restore any global fetch patch immediately. + // Proxy disabled mid-session: global-agent can't be un-bootstrapped, and the + // dispatcher stays installed until the resources below are disposed (re-pointing + // live traffic mid-session is not safe). Any global fetch patch *can* be + // restored immediately. restoreGlobalFetchPatch() restoreTlsVerificationOverride() log("Debug proxy disabled. Restart VS Code to fully disable proxy routing.") @@ -216,10 +221,7 @@ export async function initializeNetworkProxy( if (config.enabled) { applyTlsVerificationOverride(config) await configureGlobalProxy(config, isDisposed) - const undiciResource = await configureUndiciProxy(config, context, isDisposed) - if (undiciResource) { - resources.push(undiciResource) - } + await configureUndiciProxy(config, context, isDisposed, (resource) => resources.push(resource)) } else { log(`Debug proxy not enabled.`) } @@ -323,32 +325,36 @@ async function configureGlobalProxy(config: ProxyConfig, isDisposed: () => boole * Configure undici's global dispatcher so Node's built-in `fetch()` and any undici-based * clients route through the proxy. * - * @param context The extension context whose subscriptions register the returned resource. + * The dispatcher active before the install is captured and restored when the created resource + * is disposed — but only while the global slot still holds the agent installed here; a slot a + * third party has since replaced belongs to that installer, not to this teardown. + * + * @param context The extension context whose subscriptions register the created resource. * @param isDisposed Teardown latch checked after the dynamic import below; a late import * completion closes the freshly built agent instead of installing it. - * @returns A disposable that closes the created agent, or undefined when no agent was created - * (nothing to close). Also registered on `context.subscriptions`. + * @param registerResource Called with the created resource synchronously after the last await, + * so a teardown that starts while this function is in flight cannot miss it. */ async function configureUndiciProxy( config: ProxyConfig, context: vscode.ExtensionContext, isDisposed: () => boolean, -): Promise { + registerResource: (resource: vscode.Disposable) => void, +): Promise { if (!config.enabled || !config.serverUrl) { - return undefined + return } if (undiciProxyInitialized) { log(`undici global dispatcher already configured; restart VS Code to change proxy safely`) - return undefined + return } - let undiciResource: vscode.Disposable | undefined - try { const { ProxyAgent, setGlobalDispatcher, + getGlobalDispatcher, fetch: undiciFetch, } = (await import("undici")) as typeof import("undici") @@ -369,9 +375,21 @@ async function configureUndiciProxy( if (isDisposed()) { log("undici import completed after disposal; closing the late proxy agent without installing it") closeProxyAgentBestEffort(proxyAgent) - return undefined + return } + // A concurrent call can pass the already-configured check above while this import is + // pending. Installing after another call has set the dispatcher would capture that + // agent as the previous dispatcher, and its teardown would then restore a closed + // agent globally; the first install owns the slot, so this agent is closed instead. + if (undiciProxyInitialized) { + closeProxyAgentBestEffort(proxyAgent) + return + } + + // undici exposes a getter for its global dispatcher slot, so the dispatcher that + // predates this install can be captured here and put back by the resource below. + const previousDispatcher = getGlobalDispatcher() setGlobalDispatcher(proxyAgent) undiciProxyInitialized = true log(`undici global dispatcher configured for proxy: ${redactProxyUrl(config.serverUrl)}`) @@ -392,25 +410,29 @@ async function configureUndiciProxy( } // The agent owns sockets, so teardown must close it; restoring the fetch patch is owned - // by the override-cleanup resource, which every disposal path also disposes. Disposal - // reaches this resource from two owners (context.subscriptions and the aggregate - // returned by initializeNetworkProxy), so the once-guard keeps a double dispose to a - // single close of the same agent. + // by the override-cleanup resource, which every disposal path also disposes. The + // dispatcher is restored before the close so traffic started after teardown cannot land + // on the closed agent, and only while the slot still holds this agent — a dispatcher + // installed by someone else afterwards is theirs to manage. Disposal reaches this + // resource from two owners (context.subscriptions and the aggregate returned by + // initializeNetworkProxy), so the once-guard keeps a double dispose to a single close. let agentClosed = false - undiciResource = { + const undiciResource: vscode.Disposable = { dispose: () => { if (!agentClosed) { agentClosed = true + if (getGlobalDispatcher() === proxyAgent) { + setGlobalDispatcher(previousDispatcher) + } closeProxyAgentBestEffort(proxyAgent) } }, } + registerResource(undiciResource) context.subscriptions.push(undiciResource) } catch (error) { log(`Failed to configure undici proxy dispatcher: ${error instanceof Error ? error.message : String(error)}`) } - - return undiciResource } /** * Update environment variables for proxy configuration. From 2f0b953f87e8d2196a5df5cdd9b8addde1bc47f3 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Sat, 14 Nov 2026 23:58:08 +0100 Subject: [PATCH 20/52] fix: honor external command-list edits in saves and dialog state Saving the settings dialog no longer resurrects command-list entries that an external edit removed from the workspace layer while the dialog was open: an entry the dialog displayed but no layer still holds was removed in the settings file, and the file wins over the stale dialog buffer. Likewise, an entry the dialog displayed and the user then deleted stays deleted when the workspace command-lists gate flips while the dialog is open; entries the gate hid all along are still preserved by the hidden-entry re-add. A failed command-list save now clears the global layer only when its fresh re-read finds no layer at all. Previously the decision also required a global layer to have existed when the save started, so a global layer another writer created during the save - including one holding an explicit empty list - was cleared by the compensation. Proxy teardown logging goes through a helper that swallows failures from a disposed output channel. A throw from that channel previously aborted the teardown it flanked, skipping the proxy agent close it was meant to report. In the settings dialog, the ref holding the latest extension state is now refreshed in a layout effect so it commits with the render that observed the new state, and the merge of external updates into the unsaved-changes buffer is computed outside the state updater instead of inside it. An equal-valued refresh therefore no longer rewrites the buffer identity, so an external update that changes nothing can no longer clear the pending-save state under an in-flight edit. Tests cover external removal versus retention in both the promotion split and the hidden-entry re-add, the undo's layer-exists decision, teardown logging against a disposed channel, and the dialog's buffer retention across a save and an equal-valued external restatement. --- .../__tests__/webviewMessageHandler.spec.ts | 139 +++++++-- src/core/webview/webviewMessageHandler.ts | 54 +++- src/utils/__tests__/networkProxy.spec.ts | 117 ++++++++ src/utils/networkProxy.ts | 24 +- .../src/components/settings/SettingsView.tsx | 100 +++---- .../SettingsView.unsaved-changes.spec.tsx | 263 ++++++++++++++++++ 6 files changed, 618 insertions(+), 79 deletions(-) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index d00c99473d..917065f653 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2538,10 +2538,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) // The undo was attempted at the Global target even though it failed; - // this save deleted no global entry, added only "aws", and found no - // global layer at save start, so the undo clears the key rather than - // writing back the fresh read minus "aws". - expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) + // this save deleted no global entry and added only "aws", so the undo + // computes an empty list - and because the re-read finds a layer (this + // save's own write still standing), the rollback preserves that + // existence rather than clearing the key. + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( @@ -2687,7 +2688,52 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + // The baseline names the entry, so the hidden-entry re-add honors it as + // displayed: the promoted global copy is this entry's only home after + // the save, and nothing remains to write back at the workspace scope. + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + }) + + it("does not promote a baseline entry an external edit removed from the layers", async () => { + // The dialog displayed "docker" from the workspace layer; while it was + // open the settings file lost it, so the save-start snapshot holds it in + // neither layer. The buffered dialog list still submits it, and + // submitting a displayed entry signals retention rather than newness, so + // it must not be classified as brand-new knowledge and promoted into the + // global layer: external removal wins over the stale dialog buffer, and + // the genuinely new "aws" still promotes. + const { update } = mockCommandConfiguration({ workspaceValue: [] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) + // The removed entry is not re-admitted as an external addition either: + // it was displayed, so no preservation warning names it. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("keeps a retained baseline entry the layers still hold while promoting a new entry", async () => { + // The reconciliation's accept side: the baseline names "docker" and the + // save-start snapshot still finds it in the workspace layer, so the user + // kept existing workspace knowledge - it stays at its scope, not + // promoted - while "aws", absent from the baseline, promotes normally. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) // The save result is the dialog's only answer for a per-key command-list @@ -2727,7 +2773,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) - expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + // The baseline names the entry, so the hidden-entry re-add treats it as + // displayed knowledge whose absence would be a deletion: the promoted + // global copy is this entry's only home after the save. + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) }) it("promotes only the hidden entries a gate-flipped baseline did not display", async () => { @@ -2748,6 +2797,32 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Workspace) }) + it("keeps a displayed entry the user deleted out of the hidden-entry re-add after a gate flip", async () => { + // The dialog displayed "docker" with the gate on — "curl" was hidden all + // along, shadowed by the global allow — and the baseline shows that. The + // user deleted "docker" and the gate flipped off before the save, which + // hides every workspace entry, so the hidden set now holds both. The + // baseline proves "docker" was displayed, so its absence from the + // submission is a deletion the re-add must honor, while "curl" was never + // displayed and the preservation re-add still restores it. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["curl"] : undefined, + ) + const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "curl"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + + // The deletion sticks: "docker" is gone from the workspace layer... + expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + // ...and nothing promoted it into the global layer either. + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + }) + it("keeps an entry the save retained out of the undo's removal set", async () => { // The compensation removes only what this save added. The global layer // already held "keep" and this save kept it, so the undo — computed @@ -2842,20 +2917,21 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) - it("clears the key when the undo finds the layer absent, at save start or cleared mid-save", async () => { - // A rolled-back addition-only save must not materialize an empty global - // layer where none existed: the activation seed treats an explicit `[]` - // as an override, so writing `[]` here would suppress the default command - // lists after a restart. The undo clears the key instead, at the same call - // position the `[]` write would have occupied. The layer can be absent - // either because it was absent when the save started, or because a third - // party cleared it while the save ran and the guarded re-read saw that; - // both absences land in the same clear. + it("clears the key only when the undo's re-read finds no layer", async () => { + // A rolled-back addition-only save must not leave an empty global layer + // where the rollback found none: the activation seed treats an explicit + // `[]` as an override, so writing `[]` over an absent layer would + // suppress the default command lists after a restart. The undo clears the + // key instead, at the same call position the `[]` write would have + // occupied. What decides clear-versus-write is the guarded re-read's + // finding, so both legs land in the same clear: in each, a third party + // cleared the layer while the save ran, leaving even this save's addition + // gone. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], + [{ workspaceValue: ["docker"] }, undefined, undefined], true, ) @@ -2900,6 +2976,33 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(clearedMidSave).toHaveBeenCalledTimes(3) }) + it("preserves an empty global layer another writer created during the save", async () => { + // The global layer was absent when the save started; by undo time a + // third party had created it holding the explicit `[]` list. An explicit + // empty layer is as much the other writer's decision as one that + // predates the save: the compensation reads the current state, finds + // that layer, and writes its empty undo back over it instead of clearing. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: [] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + // A clear here would silently suppress the other writer's override + // through the activation seed. + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(3) + }) + it("still writes an empty undo list when the global layer exists but holds nothing to keep", async () => { // The guard's other side: a layer that exists stays present after the // rollback, even when the undo computes an empty list — clearing an @@ -2945,8 +3048,8 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { it("reports a failed save through the result when the compensating restore also fails", async () => { // The undo-failure leg reports both failures to the user but throws // nothing, so only its flag can tell the dialog the save was lost. - // The global layer is absent at save start and the save only added, so - // the undo clears the key. + // The re-read finds this save's write still in the global layer, so the + // undo writes its empty list back rather than clearing the key. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, @@ -2965,7 +3068,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) }) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index de17b8fe13..4124f3a2e8 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -925,6 +925,25 @@ export const webviewMessageHandler = async ( !hiddenWorkspaceEntries.includes(entry), ) : [] + // An entry the settings file lost while the dialog was open is + // still in the submitted list, and with no layer holding it + // anymore the split below would classify it as brand-new + // knowledge and promote a project entry into the global layer. + // The baseline separates that from a user addition: a baseline + // entry was displayed, so submitting it signals retention, not + // newness — a retained entry that no layer still holds was + // removed in the file, and external removal wins over the stale + // dialog buffer, mirroring how the external-addition re-admit + // above lets the file win over a stale deletion. Entries absent + // from the baseline keep their promotion path untouched. + const splitSourceEntries = Array.isArray(baseline) + ? [...incoming, ...externallyAdded].filter( + (entry) => + !baseline.includes(entry) || + currentScopes.workspace.includes(entry) || + currentScopes.global.includes(entry), + ) + : [...incoming, ...externallyAdded] // The baseline also carries the gate as the dialog last displayed // it. When the gate flipped since, the hidden set can hold // entries the user did see, and an entry the dialog displayed is @@ -942,7 +961,7 @@ export const webviewMessageHandler = async ( (entry) => !Array.isArray(baseline) || !baseline.includes(entry), ) const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( - [...incoming, ...externallyAdded], + splitSourceEntries, // Hidden entries are not existing knowledge for promotion // purposes: the dialog never displayed them, so an entry the // user just added is new even when the workspace layer @@ -953,7 +972,21 @@ export const webviewMessageHandler = async ( currentScopes.global, ) - const workspaceWrite = [...new Set([...keptWorkspaceWrite, ...hiddenWorkspaceEntries])] + // The hidden set holds entries the dialog could not display, + // which is why re-adding them cannot undo a user deletion. A + // gate flip since the dialog displayed its lists breaks that + // premise: an entry the baseline shows displayed became hidden + // afterwards, and its absence from the submitted list is a + // deletion the re-add must honor. Entries hidden all along are + // absent from the baseline, so their preservation is unchanged. + const workspaceWrite = [ + ...new Set([ + ...keptWorkspaceWrite, + ...hiddenWorkspaceEntries.filter( + (entry) => !Array.isArray(baseline) || !baseline.includes(entry), + ), + ]), + ] const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) // The two configuration writes below are not atomic, so their @@ -1003,7 +1036,11 @@ export const webviewMessageHandler = async ( // distinguishes `[]` from absent, and the activation seed // treats `[]` as an override, so writing `[]` where no // value existed would suppress the default lists after a - // rolled-back save. + // rolled-back save. What the rollback must respect is + // whether a layer exists now — one that came into + // existence mid-save is as much another writer's + // decision as one that predates the save, and its + // explicit `[]` override must survive this undo. let freshGlobalValue: string[] | undefined try { freshGlobalValue = config.inspect(key)?.globalValue @@ -1020,13 +1057,12 @@ export const webviewMessageHandler = async ( ...removedByThisSave, ]), ] - const hadGlobalLayer = - globalLayerAtSaveStart !== undefined && freshGlobalValue !== undefined + const globalLayerExistsNow = freshGlobalValue !== undefined try { - if (globalUndo.length === 0 && !hadGlobalLayer) { - // Absent pre-save (or externally cleared mid-save) - // and nothing to restore: clear the key rather than - // materialize an empty layer. + if (globalUndo.length === 0 && !globalLayerExistsNow) { + // The re-read found no layer at all (absent from the + // start, or cleared mid-save) and nothing to restore: + // clear the key rather than materialize an empty layer. await config.update(key, undefined, vscode.ConfigurationTarget.Global) } else { await config.update(key, globalUndo, vscode.ConfigurationTarget.Global) diff --git a/src/utils/__tests__/networkProxy.spec.ts b/src/utils/__tests__/networkProxy.spec.ts index 6e6d7a849a..97cc6c45c3 100644 --- a/src/utils/__tests__/networkProxy.spec.ts +++ b/src/utils/__tests__/networkProxy.spec.ts @@ -560,6 +560,123 @@ describe("networkProxy", () => { globalThis.fetch = fetchBefore } }) + + // A seed-failure teardown also disposes the extension's output channel, and VS + // Code throws "Channel has been closed" from appendLine() afterwards. The + // post-dispose continuation must therefore survive a throwing log sink: a + // propagating throw would skip the late agent's close, and the retry inside the + // outer catch would reject the configureUndiciProxy promise no caller awaits. + it("closes the late agent and resolves when the output channel was disposed during teardown", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + let channelClosed = false + const closedChannel: vscode.OutputChannel = { + name: "Closed in test", + append: vi.fn(), + appendLine: vi.fn(() => { + if (channelClosed) { + throw new Error("Channel has been closed") + } + }), + replace: vi.fn(), + clear: vi.fn(), + show: vi.fn(), + hide: vi.fn(), + dispose: vi.fn(() => { + channelClosed = true + }), + } + try { + const { freshModule, context } = await freshDebugRunContext() + // The late close rejects too, so the deferred close-error log inside the + // best-effort close runs against the same closed channel. + mocks.proxyAgentClose.mockRejectedValueOnce(new Error("close failed")) + + const init = freshModule.initializeNetworkProxy(context, closedChannel) + disposeMidFlight(context) + closedChannel.dispose() + // An init promise that the activation-failure path ignores must resolve, + // not reject, when every teardown log it emits throws. + await expect(init).resolves.toBeDefined() + // Flush the close rejection's catch chain so a handler that rethrows + // surfaces here as an unhandled rejection rather than escaping the test. + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mocks.proxyAgent).toHaveBeenCalledOnce() + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + + // Swallowing is limited to appendLine failures: with a live channel the same + // post-dispose continuation still writes both disposal logs to it. + it("keeps writing the post-dispose teardown logs when the channel is still open", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + try { + const { freshModule, context } = await freshDebugRunContext() + + const init = freshModule.initializeNetworkProxy(context, mockOutputChannel) + disposeMidFlight(context) + await init + + const logged = vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n") + expect(logged).toContain("global-agent import completed after disposal; skipping bootstrap") + expect(logged).toContain( + "undici import completed after disposal; closing the late proxy agent without installing it", + ) + expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + globalThis.fetch = fetchBefore + } + }) + + // The outer catch of configureUndiciProxy logs through the same teardown-safe + // logger, so the import-failure path must surface the failure on the channel and + // still resolve: the configured proxy is best-effort, and activation continues + // without it. + it("logs and swallows an undici import failure without installing anything", async () => { + vi.resetModules() + const fetchBefore = globalThis.fetch + const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) + globalThis.fetch = fetchSentinel + vi.doMock("undici", () => { + throw new Error("undici unavailable") + }) + try { + const { freshModule, context } = await freshDebugRunContext() + + // The ignored configureUndiciProxy path must resolve despite the rejection. + // (The expected error text is only the log prefix: vitest wraps factory + // errors, so the suffix is its own message, not the thrown one.) + await expect(freshModule.initializeNetworkProxy(context, mockOutputChannel)).resolves.toBeDefined() + expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( + "Failed to configure undici proxy dispatcher", + ) + expect(mocks.proxyAgent).not.toHaveBeenCalled() + expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() + expect(globalThis.fetch).toBe(fetchSentinel) + } finally { + // Re-register the resolved factory and drop the cached module so later tests + // resolve undici exactly as through the file-level mock. + vi.doMock("undici", () => ({ + ProxyAgent: mocks.proxyAgent, + setGlobalDispatcher: mocks.setGlobalDispatcher, + getGlobalDispatcher: mocks.getGlobalDispatcher, + fetch: mocks.undiciFetch, + })) + vi.resetModules() + globalThis.fetch = fetchBefore + } + }) }) // When the proxy is disabled at activation, only the configuration-change listener diff --git a/src/utils/networkProxy.ts b/src/utils/networkProxy.ts index 45e0df2a08..e7a307b4b8 100644 --- a/src/utils/networkProxy.ts +++ b/src/utils/networkProxy.ts @@ -72,6 +72,20 @@ function restoreGlobalFetchPatch(): void { originalFetch = undefined } +/** + * Teardown-safe logging. A disposed VS Code output channel throws from appendLine(), and + * teardown paths run exactly when that disposal may already have happened; a throw out of one + * of these log calls would skip the cleanup it flanks or reject a promise no caller handles. + * Losing a late log line is always preferable to losing the close it reports. + */ +function logTeardown(message: string): void { + try { + log(message) + } catch { + // Deliberately empty: the log sink is gone, and every caller here must keep tearing down. + } +} + /** * Fire-and-log variant of ProxyAgent.close(): Disposable.dispose() is synchronous while * close() is async, and neither a teardown sequence nor the late-import abort may block on @@ -79,7 +93,7 @@ function restoreGlobalFetchPatch(): void { */ function closeProxyAgentBestEffort(proxyAgent: { close(): Promise }): void { void proxyAgent.close().catch((error) => { - log(`Failed to close undici proxy agent: ${error instanceof Error ? error.message : String(error)}`) + logTeardown(`Failed to close undici proxy agent: ${error instanceof Error ? error.message : String(error)}`) }) } @@ -303,7 +317,7 @@ async function configureGlobalProxy(config: ProxyConfig, isDisposed: () => boole // A teardown may have run while the import above was pending; bootstrapping global-agent // then would intercept this process's HTTP traffic for a dead extension. if (isDisposed()) { - log("global-agent import completed after disposal; skipping bootstrap") + logTeardown("global-agent import completed after disposal; skipping bootstrap") return } @@ -373,7 +387,7 @@ async function configureUndiciProxy( // or patching fetch then would leave process-global routing active for a dead extension, // so the freshly built agent is closed and nothing is installed. if (isDisposed()) { - log("undici import completed after disposal; closing the late proxy agent without installing it") + logTeardown("undici import completed after disposal; closing the late proxy agent without installing it") closeProxyAgentBestEffort(proxyAgent) return } @@ -431,7 +445,9 @@ async function configureUndiciProxy( registerResource(undiciResource) context.subscriptions.push(undiciResource) } catch (error) { - log(`Failed to configure undici proxy dispatcher: ${error instanceof Error ? error.message : String(error)}`) + logTeardown( + `Failed to configure undici proxy dispatcher: ${error instanceof Error ? error.message : String(error)}`, + ) } } /** diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index ea41601b9f..13e68c8d1a 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -188,7 +188,11 @@ const SettingsView = forwardRef(({ onDone, t latestCachedState.current = cachedState // The live host state, read when a save settles without re-subscribing the result handler on every post. const latestExtensionState = useRef(extensionState) - latestExtensionState.current = extensionState + // Refreshed synchronously at commit: a host state post and the save answer that follows it can arrive as + // back-to-back messages, and the answer's task must observe the post it answers, not the state before it. + useLayoutEffect(() => { + latestExtensionState.current = extensionState + }, [extensionState]) // The save the host must answer records the baseline it stamped and the lists it submitted, so the // save-result effect can reconcile each list's baseline against that list's own write outcome. const submittedListSave = useRef<{ baselined: [string[], string[]]; sent: [string[], string[]] } | undefined>( @@ -319,66 +323,66 @@ const SettingsView = forwardRef(({ onDone, t return } - setCachedState((prevState) => { - const merged: CommandListSnapshot = {} - let changedFields = 0 + // The merge is computed here, outside the state update, from the committed buffer the + // effect's render saw; a state update must stay a pure function of the state it is + // applied to. + const prevState = latestCachedState.current + const merged: CommandListSnapshot = {} - if (!commandListsTouched.current) { - if (!commandListsEquivalent(prevState.allowedCommands, extensionState.allowedCommands)) { - merged.allowedCommands = extensionState.allowedCommands - changedFields++ - } - if (!commandListsEquivalent(prevState.deniedCommands, extensionState.deniedCommands)) { - merged.deniedCommands = extensionState.deniedCommands - changedFields++ - } + if (!commandListsTouched.current) { + if (!commandListsEquivalent(prevState.allowedCommands, extensionState.allowedCommands)) { + merged.allowedCommands = extensionState.allowedCommands } - if (prevState.workspaceCommandListsEnabled !== extensionState.workspaceCommandListsEnabled) { - merged.workspaceCommandListsEnabled = extensionState.workspaceCommandListsEnabled - changedFields++ + if (!commandListsEquivalent(prevState.deniedCommands, extensionState.deniedCommands)) { + merged.deniedCommands = extensionState.deniedCommands } + } + if (prevState.workspaceCommandListsEnabled !== extensionState.workspaceCommandListsEnabled) { + merged.workspaceCommandListsEnabled = extensionState.workspaceCommandListsEnabled + } - // The stamp records the lists this merge leaves on screen, never the posted - // state outright: an entry held back by an in-flight edit was never displayed, - // and a baseline claiming it had been lets the save erase it as a user - // deletion without warning. While the lists are held back the buffered lists - // are themselves unposted, so the stamp keeps its prior lists instead - a - // deletion inside the buffered edit must stay in the baseline for the save to - // apply it rather than resurrect the deleted entry as an external addition. - // The gate slot holds back with those lists because the stamp has to describe - // one displayed state: pairing held-back lists with an externally-flipped gate - // would claim the held-back entries were displayed under a gate they never - // appeared alongside. - const [stampAllowed, stampDenied, stampGate] = commandListsTouched.current - ? (JSON.parse(lastDisplayedCommandSnapshot.current) as [string[], string[], boolean]) - : [ - merged.allowedCommands ?? prevState.allowedCommands, - merged.deniedCommands ?? prevState.deniedCommands, - merged.workspaceCommandListsEnabled ?? prevState.workspaceCommandListsEnabled, - ] - lastDisplayedCommandSnapshot.current = commandListSnapshot({ - allowedCommands: stampAllowed, - deniedCommands: stampDenied, - workspaceCommandListsEnabled: stampGate, - }) - - if (changedFields === 0) { - return prevState - } - return { ...prevState, ...merged } + // The stamp records the lists this merge leaves on screen, never the posted + // state outright: an entry held back by an in-flight edit was never displayed, + // and a baseline claiming it had been lets the save erase it as a user + // deletion without warning. While the lists are held back the buffered lists + // are themselves unposted, so the stamp keeps its prior lists instead - a + // deletion inside the buffered edit must stay in the baseline for the save to + // apply it rather than resurrect the deleted entry as an external addition. + // The gate slot holds back with those lists because the stamp has to describe + // one displayed state: pairing held-back lists with an externally-flipped gate + // would claim the held-back entries were displayed under a gate they never + // appeared alongside. + const [stampAllowed, stampDenied, stampGate] = commandListsTouched.current + ? (JSON.parse(lastDisplayedCommandSnapshot.current) as [string[], string[], boolean]) + : [ + merged.allowedCommands ?? prevState.allowedCommands, + merged.deniedCommands ?? prevState.deniedCommands, + merged.workspaceCommandListsEnabled ?? prevState.workspaceCommandListsEnabled, + ] + lastDisplayedCommandSnapshot.current = commandListSnapshot({ + allowedCommands: stampAllowed, + deniedCommands: stampDenied, + workspaceCommandListsEnabled: stampGate, }) + + if (Object.keys(merged).length > 0) { + setCachedState((prevCachedState) => ({ ...prevCachedState, ...merged })) + } }, [extensionState]) const setCachedStateField: SetCachedStateField = useCallback((field, value) => { + // A list edit claims ownership of the lists only when the value actually changes; the + // equality guard is duplicated here so the marking can sit outside the state update, + // keeping that update pure without giving a no-op set ownership it never had. + if ((field === "allowedCommands" || field === "deniedCommands") && latestCachedState.current[field] !== value) { + commandListsTouched.current = true + } + setCachedState((prevState) => { if (prevState[field] === value) { return prevState } - if (field === "allowedCommands" || field === "deniedCommands") { - commandListsTouched.current = true - } - setChangeDetected(true) return { ...prevState, [field]: value } }) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index b46b8e31bb..507569a380 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -859,6 +859,55 @@ describe("SettingsView - Unsaved Changes Detection", () => { ) }) + it("folds an external list update into the buffer after a no-op list set or a non-list edit", async () => { + // List ownership is claimed only by an edit that actually changes a list: handing back the + // very array already displayed, or editing a field outside the lists, must leave the lists + // open to external updates rather than holding every later post back. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + // An edit outside the lists leaves them unowned: the external deny entry folds into the buffer. + fireEvent.click(await screen.findByTestId("edit-non-list-setting")) + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + view.rerender() + await waitFor(() => + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["rm -rf"])), + ) + + // Re-setting a list to the array it already holds changes nothing, so it claims nothing: + // the next external update still folds in. + fireEvent.click(screen.getByTestId("noop-deny-set")) + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["docker"], + }) + view.rerender() + await waitFor(() => + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["docker"])), + ) + }) + it("baselines the save on the pre-edit displayed lists when a state post lands during an in-flight list edit", async () => { // The baseline feeds the save's classification of every entry the submitted // list omits, so it must hold the lists the dialog displayed BEFORE the @@ -1262,6 +1311,220 @@ describe("SettingsView - Unsaved Changes Detection", () => { ) }) + it("releases the unsaved flag after a save when a refused external update changed nothing", async () => { + // An external post the held-back merge refuses changes nothing, and a merge that changes + // nothing must leave the buffer object itself untouched: the save settles by comparing + // the live buffer against the exact object it submitted, so replacing the buffer with an + // equal-valued copy would read as an edit made during the save and keep the unsaved flag + // on despite the host confirming every write. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A display-setting difference on the next post puts the save on the path that waits for + // the host's answer; its lists restate what the dialog displayed, so the held merge + // refuses them. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The host posts the file's lists before performing this save's write, and they changed + // externally: still refused by the deletion in flight, so the refused post must not + // touch the buffered list or replace the submitted buffer. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf", "docker"], + showRelativeTimes: false, + }) + view.rerender() + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify([])) + + // The write lands and the answer reports success: the buffer is exactly what was + // submitted, so the flag goes off. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: [], + showRelativeTimes: false, + }) + view.rerender() + answerSave(saveId, { success: true }) + + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + }) + + it("settles the save against the refreshed state posted just before the answer", async () => { + // The host posts the state refresh before its save answer, and the answer's handling must observe + // the state that refresh carried - the submitted list seen there is what records the write as + // landed and releases the flag - never the state from before the refresh, which would report the + // landed write as missing: a sticky unsaved flag and a rolled-back baseline after a successful save. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( +
+ + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A display-setting difference puts this save on the path that waits for the host's answer, without + // touching the buffered list. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The refresh (carrying the landed deletion) posts, and the success answer follows it immediately. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: [], + showRelativeTimes: false, + }) + view.rerender() + answerSave(saveId, { success: true }) + + // The settle saw the refreshed list: the write counts as landed and the flag goes off. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // No baseline rollback either: the advanced baseline survives, so a re-edit after this save still + // posts the landed list as the displayed baseline instead of the rolled-back pre-submit one. + fireEvent.click(screen.getByTestId("edit-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const saves = updateSettingsPosts() + expect(saves).toHaveLength(2) + expect(saves.at(-1)).toEqual( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: expect.objectContaining({ deniedCommands: [] }), + }), + ) + }) + + it("keeps the submitted buffer when an equal-valued list restatement arrives during a later pending save", async () => { + // A post whose lists match the buffer value-for-value must leave the buffer object untouched, even + // when the post still differs from the displayed baseline in the gate slot - the slot a flip folded + // into the buffer during an earlier in-flight edit left behind. The save settles by comparing the + // buffer against the exact object it submitted, so folding equal-valued fresh arrays into the buffer + // would read as an edit made during the save and keep the unsaved flag on despite a confirmed write. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( +
+ + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + // An in-flight deletion, then an external gate flip: the flip lands in the buffer while the held-back + // lists keep the displayed baseline at the pre-flip gate - the divergence the restatement posts below + // keep tripping the merge on. + fireEvent.click(await screen.findByTestId("clear-deny-list")) + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + workspaceCommandListsEnabled: true, + showRelativeTimes: false, + }) + view.rerender() + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // The display-setting difference puts this save on the answered path; the refresh shows the deletion + // landed, so the confirmed answer releases the flag and the list's hold, while the baseline keeps the + // gate it was stamped with. + fireEvent.click(screen.getByTestId("save-button")) + const deleteSaveId = lastSaveRequestId(postMessage) + expect(deleteSaveId).toBeDefined() + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: [], + workspaceCommandListsEnabled: true, + showRelativeTimes: false, + }) + view.rerender() + answerSave(deleteSaveId, { success: true }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // A second save goes out - a non-list edit re-dirties the form, and the still-unabsorbed + // display-setting divergence keeps it on the answered path. The host's restatement posts the file + // back with fresh equal-valued list arrays. The lists match the buffer value-for-value, so the + // merge must fold nothing: the buffer has to stay the exact object the save submitted for the + // answer to clear the flag. + fireEvent.click(screen.getByTestId("edit-other-setting")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const formatSaveId = lastSaveRequestId(postMessage) + expect(formatSaveId).toBeDefined() + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: [], + workspaceCommandListsEnabled: true, + showRelativeTimes: false, + timeFormat: "24h", + }) + view.rerender() + answerSave(formatSaveId, { success: true }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + }) + it("clears the unsaved flag and releases every list when the refresh shows all writes landed", async () => { // A save whose every edited list appears landed in the host's refresh clears the flag and // releases the buffered lists to external updates. From a668f4cc53ba0961ecbfd783055928754cdc5805 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Sun, 15 Nov 2026 23:41:13 +0100 Subject: [PATCH 21/52] fix: preserve settings-file-only command entries during saves The command-list save compares the submitted list against a baseline of the entries the settings dialog displayed, and re-admits entries the settings file gained in the meantime so they survive the rewrite. That comparison consulted the workspace layer and the extension-state copy of the global layer, but the state copy is not refreshed when settings.json is edited directly. An entry held only by the configuration's own global value was therefore invisible to the comparison, and the save's Global write dropped it from the user's settings file. The existing-entry set now also includes the configuration global layer read at save start, so such an entry is re-admitted like any other external addition and disclosed with the same warning. Two spec cases pin the behavior: the settings-file-only entry survives the Global write, and a genuinely new entry keeps its promotion path when the configuration global layer already holds a different entry. --- .../__tests__/webviewMessageHandler.spec.ts | 66 +++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 15 ++++- 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 917065f653..1be3fb4dfc 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -3549,6 +3549,72 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) }) + + it("preserves a deny entry only the configuration global layer holds", async () => { + // The user added "curl" to the user-level deny list directly in + // settings.json while the dialog was open. The extension-state copy the + // split consults is never refreshed by such an edit, and neither the + // dialog baseline nor the submitted list names the entry, so the + // save-start configuration global layer is the only source that can + // classify it as an external addition; without that source the save's + // Global write would delete it from the user's settings file. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ globalValue: ["curl"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // The dialog displayed nothing for this key and saved nothing back. + updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: [] }, + }) + + // The Global write re-admits the file-side entry instead of clearing + // the layer that holds it. + expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + // The snapshot found no workspace layer, so the save never creates one. + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // The preserved entry is disclosed like the other external additions, + // and the state copy keeps the layer the save wrote. + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("1 entry was")) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("curl")) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["curl"]) + }) + + it("still promotes a genuinely new entry when the configuration global layer already holds another", async () => { + // The accept side of the external-addition union: "curl" lives in the + // configuration global layer and the state copy the dialog displayed, + // so it is existing knowledge kept in place, while "aws" - held by no + // layer at save start - keeps the brand-new promotion path into the + // global write. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["curl"] : undefined, + ) + const { update } = mockCommandConfiguration({ globalValue: ["curl"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["curl", "aws"] }, + commandListBaseline: { deniedCommands: ["curl"] }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["curl", "aws"], vscode.ConfigurationTarget.Global) + // The kept entry is not dropped by the split either. + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // Nothing was classified as an external addition: no warning. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["curl", "aws"]) + }) }) describe("webviewMessageHandler - terminalProfile", () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 4124f3a2e8..f4c9a3bfab 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -915,10 +915,21 @@ export const webviewMessageHandler = async ( // them as external additions would repeat a false "settings file // changed" warning on every save. A sender that shows no lists // sends no baseline, and its submitted list is written - // unclassified. + // unclassified. The union covers every layer that can hold an + // entry at save start: the extension-state global copy is not + // refreshed when the settings file is edited directly, so an + // entry only the configuration's own global layer holds would be + // invisible to a union of the state copy and the workspace layer, + // and the global write below would delete it from the user file. const baseline = message.commandListBaseline?.[key] const externallyAdded = Array.isArray(baseline) - ? [...new Set([...currentScopes.workspace, ...currentScopes.global])].filter( + ? [ + ...new Set([ + ...currentScopes.workspace, + ...currentScopes.global, + ...configGlobalAtSaveStart, + ]), + ].filter( (entry) => !baseline.includes(entry) && !incoming.includes(entry) && From f3308d9b8aeaafc8679a9bd433e1d7b87cf13fcd Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Mon, 16 Nov 2026 01:34:59 +0100 Subject: [PATCH 22/52] fix: restore absent global command lists after a rolled-back save A command-list save writes the global and workspace layers separately, and when the workspace write fails it compensates by undoing its own global write. That undo consulted only whether a global layer exists now: if the layer was absent before the save and the save had created it, the undo wrote an empty list back instead of removing the key. An explicitly empty global list is a real user choice, honored over the built-in default command lists, so a failed save could leave the user with no default commands and no list they ever created. The rollback now tells the two cases apart. A layer the re-read finds holding something other than this save's own write came about through another writer's decision, or predates the save, and stays as it is; a layer still holding exactly this save's write over an absent start is the half-applied save itself, so the undo clears the key and restores the absence the save started from. Spec cases pin both signatures, including the save's own global write being itself empty, and a third party's explicit empty list created during the save still survives the undo. --- .../__tests__/webviewMessageHandler.spec.ts | 72 +++++++++++++++++-- src/core/webview/webviewMessageHandler.ts | 31 +++++--- 2 files changed, 88 insertions(+), 15 deletions(-) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 1be3fb4dfc..7d236f3166 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2539,10 +2539,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The undo was attempted at the Global target even though it failed; // this save deleted no global entry and added only "aws", so the undo - // computes an empty list - and because the re-read finds a layer (this - // save's own write still standing), the rollback preserves that - // existence rather than clearing the key. - expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) + // computes an empty list - and because the layer was absent when the + // save started and the re-read still holds only this save's own write, + // the rollback restores absence by clearing the key. + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( @@ -2976,6 +2976,64 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(clearedMidSave).toHaveBeenCalledTimes(3) }) + it("clears the key when the undo's re-read finds only this save's own write", async () => { + // The global layer was absent when the save started, and the re-read + // during the compensation finds it holding exactly the list this save + // wrote — the half-applied save itself, not another writer's decision. + // An undo that wrote `[]` back would materialize an explicit empty + // override that the activation seed honors over the default lists, so + // the rollback clears the key and restores the absence the save + // started from. Both legs are that signature: the second when the + // save's own global write was itself empty. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) + // Writing `[]` here instead would read back, after the rolled-back save, + // as the user's explicit empty override of the default command lists. + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(3) + + // The second leg: the save's own global write was itself empty (every + // submitted entry stayed workspace-scoped), and the re-read finds that + // same empty layer — still the save's own write over an absent start, + // so the undo clears rather than writing `[]` back. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update: emptyWrite } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: [] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker"] }, + }) + + expect(emptyWrite).toHaveBeenNthCalledWith(1, "deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(emptyWrite).toHaveBeenNthCalledWith( + 2, + "deniedCommands", + ["docker"], + vscode.ConfigurationTarget.Workspace, + ) + expect(emptyWrite).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) + expect(emptyWrite).toHaveBeenCalledTimes(3) + }) + it("preserves an empty global layer another writer created during the save", async () => { // The global layer was absent when the save started; by undo time a // third party had created it holding the explicit `[]` list. An explicit @@ -3048,8 +3106,8 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { it("reports a failed save through the result when the compensating restore also fails", async () => { // The undo-failure leg reports both failures to the user but throws // nothing, so only its flag can tell the dialog the save was lost. - // The re-read finds this save's write still in the global layer, so the - // undo writes its empty list back rather than clearing the key. + // The global layer was absent at save start and the re-read finds only + // this save's own write, so the undo clears the key to restore absence. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, @@ -3068,7 +3126,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) }) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 4fab846fe4..3bf5b2b1dc 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -1048,11 +1048,14 @@ export const webviewMessageHandler = async ( // distinguishes `[]` from absent, and the activation seed // treats `[]` as an override, so writing `[]` where no // value existed would suppress the default lists after a - // rolled-back save. What the rollback must respect is - // whether a layer exists now — one that came into - // existence mid-save is as much another writer's - // decision as one that predates the save, and its - // explicit `[]` override must survive this undo. + // rolled-back save. What the rollback must respect is whose + // presence the layer holds: a layer the re-read finds holding + // something other than this save's own write came about + // through another writer's decision (or predates the save), + // and its explicit `[]` override must survive this undo; a + // layer still holding exactly this save's write over an + // absent start is the half-applied save itself, so its + // absence is what the rollback restores. let freshGlobalValue: string[] | undefined try { freshGlobalValue = config.inspect(key)?.globalValue @@ -1070,11 +1073,23 @@ export const webviewMessageHandler = async ( ]), ] const globalLayerExistsNow = freshGlobalValue !== undefined + // A layer that started absent only carries another writer's + // decision when it now holds something beyond this save's + // own write: a re-read with the same entries (order aside) + // is the half-applied save itself, so the rollback restores + // absence instead of keeping an empty layer no user created. + const ownWriteIntact = + globalLayerAtSaveStart === undefined && + freshGlobalValue !== undefined && + freshGlobalValue.length === globalWrite.length && + freshGlobalValue.every((entry) => globalWrite.includes(entry)) try { - if (globalUndo.length === 0 && !globalLayerExistsNow) { + if (globalUndo.length === 0 && (!globalLayerExistsNow || ownWriteIntact)) { // The re-read found no layer at all (absent from the - // start, or cleared mid-save) and nothing to restore: - // clear the key rather than materialize an empty layer. + // start, or cleared mid-save), or found only this + // save's own write over an absent start, and nothing + // to restore: clear the key rather than materialize an + // empty layer. await config.update(key, undefined, vscode.ConfigurationTarget.Global) } else { await config.update(key, globalUndo, vscode.ConfigurationTarget.Global) From 5ee3d803643e930a5ac30794a430d7e03b8aecb2 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Mon, 16 Nov 2026 02:51:15 +0100 Subject: [PATCH 23/52] fix: keep settings-file command entries during layered saves A command-list entry that lives only in the global layer of the settings file could still be deleted when the settings dialog was saved. Two parts of the save path classified entries against the extension state's copy of the global layer instead of the configuration itself: the retained-entry check dropped an entry the user had kept in the dialog when only the settings file still held it, and the split that assigns entries to layers treated it as unknown, so the write to the global layer omitted it. Both checks now also consult the configuration global layer captured at the start of the save, so an entry only that layer holds is retained and preserved in the layer that holds it. Two regression tests pin the retained-entry case and the layer-split case with exact values and order. --- .../__tests__/webviewMessageHandler.spec.ts | 67 +++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 19 ++++-- 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 7d236f3166..db8abe27f5 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -3673,6 +3673,73 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["curl", "aws"]) }) + + it("retains a baseline entry only the configuration global layer still holds", async () => { + // The dialog displayed "curl" and the user kept it, but the extension- + // state copy the retained-entry check consults is never refreshed by a + // direct settings-file edit, so only the save-start configuration + // global layer still holds the entry. A check limited to the state copy + // and the workspace layer treats the entry as externally removed and + // drops it, and the Global write then deletes it from the user's + // settings file despite the user having kept it. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ globalValue: ["curl"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["curl"] }, + commandListBaseline: { deniedCommands: ["curl"], workspaceCommandListsEnabled: true }, + }) + + // The retained entry survives the split and the Global write rewrites + // the layer that still holds it, instead of clearing it. + expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + // The snapshot found no workspace layer, so the save never creates one. + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // A kept entry the dialog displayed is retention, not a file-side + // change to disclose. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["curl"]) + }) + + it("preserves a configuration-global entry the dialog displayed at the workspace scope", async () => { + // The user added "docker" to the user-level list in settings.json while + // the dialog was open, and the dialog displayed the same entry from the + // workspace layer. The split classifies kept entries against the global + // origin set; sourced only from the lagging state copy, it misses the + // configuration's own global layer, so "docker" - existing knowledge, + // never routed as new - is dropped from the Global write, deleting it + // from the user's settings file. The unioned origin set keeps it in the + // layer the save-start snapshot found it in, in that layer's order + // ahead of the dialog-ordered new entry "aws". + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + { globalValue: ["docker"], workspaceValue: ["docker"] }, + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + // The workspace layer holds the entry too, and a kept entry present in + // both layers stays in both. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + // The displayed entry was kept, not added by the file: no warning. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) + }) }) describe("webviewMessageHandler - terminalProfile", () => { diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 3bf5b2b1dc..7325bc9614 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -946,14 +946,20 @@ export const webviewMessageHandler = async ( // newness — a retained entry that no layer still holds was // removed in the file, and external removal wins over the stale // dialog buffer, mirroring how the external-addition re-admit - // above lets the file win over a stale deletion. Entries absent - // from the baseline keep their promotion path untouched. + // above lets the file win over a stale deletion. "No layer" + // covers the same layers as that re-admit union, including the + // configuration's own global layer: the extension-state copy is + // not refreshed when the settings file is edited directly, so a + // retained entry only that layer still holds has not been + // removed. Entries absent from the baseline keep their promotion + // path untouched. const splitSourceEntries = Array.isArray(baseline) ? [...incoming, ...externallyAdded].filter( (entry) => !baseline.includes(entry) || currentScopes.workspace.includes(entry) || - currentScopes.global.includes(entry), + currentScopes.global.includes(entry) || + configGlobalAtSaveStart.includes(entry), ) : [...incoming, ...externallyAdded] // The baseline also carries the gate as the dialog last displayed @@ -981,7 +987,12 @@ export const webviewMessageHandler = async ( // shows the dialog did display. The re-add below restores // the hidden entries this reduced layer drops. currentScopes.workspace.filter((entry) => !promotionHiddenEntries.includes(entry)), - currentScopes.global, + // The global origin set decides which kept entries the Global + // write preserves, so it must cover the same layers as the + // retained-entry filter above: an entry only the + // configuration's own global layer holds is existing global + // knowledge even when the extension-state copy lags behind. + [...new Set([...currentScopes.global, ...configGlobalAtSaveStart])], ) // The hidden set holds entries the dialog could not display, From 632cc3a6ca6a384b7c5b7efd5933f596661120e8 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Mon, 16 Nov 2026 08:08:22 +0100 Subject: [PATCH 24/52] fix: report save failure when the stored command list is rejected A settings save writes command lists to the VS Code settings files and to the extension's own stored copy. When that second write was rejected, the error message told the user the two copies now disagree, but the result reported to the settings dialog was still success. The dialog treated the save as complete and discarded edits that a retry could have brought back in line. The result now reports failure when the stored-copy write is rejected, so the dialog keeps the user's edits and a retry stays possible. The result and the error message now tell the same story. Only the result changes: the settings files keep what was written before the rejection and no rollback behavior changes. --- .../__tests__/webviewMessageHandler.spec.ts | 24 +++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 4 ++++ 2 files changed, 28 insertions(+) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index db8abe27f5..ee45db1f8d 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -3297,6 +3297,30 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) + it("reports a failed save through the result when the extension-state write is rejected", async () => { + // The same rejection seen by a sender that awaits an answer: the toast + // names the failed leg, so the answer must agree with it — an ack of + // success would let the dialog discard edits its stored copy never + // received, while a retry would converge. + vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValueOnce(new Error("state store unavailable")) + const { update } = mockCommandConfiguration({}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + requestId: "save-1", + updatedSettings: { deniedCommands: ["aws"], alwaysDenyUnapprovedCommands: true }, + }) + + expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) + // The configuration leg did persist, and the user still hears which leg failed... + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to save deniedCommands: state store unavailable. The configuration was updated, but the extension's stored copy of the list was not, so the two disagree until a later save succeeds.", + ) + // ...and the save continued to the next key. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("alwaysDenyUnapprovedCommands", true) + }) + it("still propagates a rejected state write for non-command-list keys", async () => { // The partial-failure report is scoped to the command-list keys, whose // configuration legs succeeded first; other keys have no half-completed diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 7325bc9614..ce28f3c2e3 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -1234,6 +1234,10 @@ export const webviewMessageHandler = async ( vscode.window.showErrorMessage( `Failed to save ${key}: ${failure}. The configuration was updated, but the extension's stored copy of the list was not, so the two disagree until a later save succeeds.`, ) + // The ack has to agree with the toast the user just saw: treating a + // save whose stored copy diverged as successful would let the + // dialog discard edits that a retry could still converge. + commandListSaveFailed = true continue } } else { From 7a6ce97347d9b2c6660dbc9daf14e871dcc87391 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Mon, 16 Nov 2026 19:35:41 +0100 Subject: [PATCH 25/52] fix: stop dialog saves from deleting command-list entries Saving the command-lists dialog decides, from the list the dialog last displayed, which entries the user added, which changes came from outside the dialog, and which entries must be kept. Two misclassifications in that decision let a save delete entries the user never removed. Entries the workspace layer hides from the dialog were always excluded from the outside-change re-admit, because the workspace-layer re-add preserves them separately. That exclusion only holds while the hidden workspace layer is the entry's only save-start location: when the configuration's own global layer also holds the entry, the entry is global knowledge the dialog shows, and excluding it dropped the user's global file addition on save. The retained-entry check also consulted the cached extension-state copy. That copy is never refreshed when the settings file is edited directly, so an entry the user deleted from the file while the dialog was open was still listed in the copy, was retained, and was re-written over the deletion. Only the configuration layers the writes target can now disprove a deletion; the cached copy counts only when the configuration has no global layer at all. That is the activation-seeded default state before anything has been saved, and without the fallback a first save would wipe the built-in defaults from every layer. The set that tells the Global write which kept entries to preserve was narrowed to the same configuration layer. The added tests cover the shadowed global addition, the settings-file deletion, and the seeded-defaults case, pinning the defaults as declared in package.json. --- .../__tests__/webviewMessageHandler.spec.ts | 123 ++++++++++++++++++ src/core/webview/webviewMessageHandler.ts | 41 +++--- 2 files changed, 149 insertions(+), 15 deletions(-) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index ee45db1f8d..dd634e5471 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2634,6 +2634,44 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) }) + it("keeps a configuration-global deny addition past the hidden-entry exclusion when the workspace copy is shadowed", async () => { + // The global allow "git" shadows the workspace deny "git push", so the + // displayed deny list stays empty; while the dialog was open the user + // added the same "git push" to the user-level deny list in settings.json. + // The hidden-entry exclusion classifies by bare membership, so without a + // provenance proviso the configuration-global addition is excluded from + // the external-addition re-admit, the split source is empty, and the + // Global write deletes the user's file addition instead of keeping it. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git"] : undefined, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"], globalValue: ["git push"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // The dialog displayed nothing deletable: the workspace deny was + // shadowed and the global addition arrived after the display. + updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, + }) + + // The user's new global denial survives the save in the layer it was + // added to, instead of being written away as []. + expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + // The shadowed workspace copy is preserved by the hidden-entry re-add. + expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) + // The genuine file addition is disclosed by the changed-settings warning. + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("git push")) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["git push"]) + }) + it("promotes a gate-hidden workspace entry the dialog re-adds to the global write", async () => { // With the gate off the dialog shows only the global layer, so a // submitted entry the workspace layer already holds hidden is one the @@ -3731,6 +3769,91 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["curl"]) }) + it("drops a baseline entry the user deleted from the configuration global layer while the state copy still holds it", async () => { + // The dialog displayed the global deny "curl" and the submitted list + // still holds it, but the user deleted it from the user-level deny list + // in settings.json while the dialog was open. The extension-state copy + // is never refreshed by a direct file edit, so it still holds "curl" - + // treating that stale copy as proof the entry remains would restore the + // deleted entry over the file. Only the configuration layers can disprove + // a removal, so the retained-entry filter must not consult the state + // copy: external removal wins over the stale buffer, mirroring the + // external-addition re-admit letting the file win over a stale deletion. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["curl"] : undefined, + ) + const { update } = mockCommandConfiguration({ globalValue: [] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["curl"] }, + commandListBaseline: { deniedCommands: ["curl"], workspaceCommandListsEnabled: true }, + }) + + // The deletion sticks: the Global write clears the layer the file now + // shows empty, instead of re-adding "curl" from the stale state copy. + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Global) + // The snapshot found no workspace layer, so the save never creates one. + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // An external removal is not a file-side addition to disclose. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) + }) + + it("preserves activation-seeded default entries whose configuration global layer is absent", async () => { + // A default install holds nothing in the user-level settings: + // activation seeded the built-in defaults into extension state while + // no global configuration layer exists, so the state copy is the only + // evidence the displayed entries have a home. A retained-entry filter + // that ignores the state copy entirely treats those entries as + // externally removed: the split drops them, the Global write clears + // the layer to [], and the emptied state stops activation from ever + // seeding the defaults again. With no configuration layer that could + // contradict the state copy, the retention stands and the defaults + // are written back. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, + ) + const { update } = mockCommandConfiguration({}, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git log", "git diff", "git show"] }, + commandListBaseline: { + allowedCommands: ["git log", "git diff", "git show"], + workspaceCommandListsEnabled: true, + }, + }) + + // The retained entries survive the split and the Global write + // rewrites them, instead of clearing the never-created layer. + expect(update).toHaveBeenCalledWith( + "allowedCommands", + ["git log", "git diff", "git show"], + vscode.ConfigurationTarget.Global, + ) + expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + // The snapshot found no workspace layer, so the save never creates one. + expect(update).not.toHaveBeenCalledWith( + "allowedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // Entries the dialog displayed and the user kept are retention, not a + // file-side change to disclose. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ + "git log", + "git diff", + "git show", + ]) + }) + it("preserves a configuration-global entry the dialog displayed at the workspace scope", async () => { // The user added "docker" to the user-level list in settings.json while // the dialog was open, and the dialog displayed the same entry from the diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index ce28f3c2e3..e3e53678ba 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -914,7 +914,11 @@ export const webviewMessageHandler = async ( // still apply). Hidden entries never appear in that baseline, yet // the workspace-layer re-add below preserves them, so classifying // them as external additions would repeat a false "settings file - // changed" warning on every save. A sender that shows no lists + // changed" warning on every save. That exclusion only speaks for + // entries whose save-start provenance is the hidden workspace + // layer: an entry the configuration's own global layer holds is + // displayed global knowledge, and excluding it would delete the + // user's file addition. A sender that shows no lists // sends no baseline, and its submitted list is written // unclassified. The union covers every layer that can hold an // entry at save start: the extension-state global copy is not @@ -934,7 +938,8 @@ export const webviewMessageHandler = async ( (entry) => !baseline.includes(entry) && !incoming.includes(entry) && - !hiddenWorkspaceEntries.includes(entry), + (!hiddenWorkspaceEntries.includes(entry) || + configGlobalAtSaveStart.includes(entry)), ) : [] // An entry the settings file lost while the dialog was open is @@ -947,19 +952,24 @@ export const webviewMessageHandler = async ( // removed in the file, and external removal wins over the stale // dialog buffer, mirroring how the external-addition re-admit // above lets the file win over a stale deletion. "No layer" - // covers the same layers as that re-admit union, including the - // configuration's own global layer: the extension-state copy is - // not refreshed when the settings file is edited directly, so a - // retained entry only that layer still holds has not been - // removed. Entries absent from the baseline keep their promotion - // path untouched. + // means the configuration layers the writes target: they alone + // can disprove a removal, because the extension-state copy is + // never refreshed when the settings file is edited directly and + // so can hold an entry the file has deleted just as it can miss + // one the file has gained. The state copy is still retention + // evidence where the configuration has no global layer at all: + // an absent layer is no file that could have deleted anything, + // and the entries the copy holds from the activation seed (the + // built-in defaults, before this list was ever saved) would + // otherwise vanish from every layer on the first save. Entries + // absent from the baseline keep their promotion path untouched. const splitSourceEntries = Array.isArray(baseline) ? [...incoming, ...externallyAdded].filter( (entry) => !baseline.includes(entry) || currentScopes.workspace.includes(entry) || - currentScopes.global.includes(entry) || - configGlobalAtSaveStart.includes(entry), + configGlobalAtSaveStart.includes(entry) || + (currentScopes.global.includes(entry) && globalLayerAtSaveStart === undefined), ) : [...incoming, ...externallyAdded] // The baseline also carries the gate as the dialog last displayed @@ -988,11 +998,12 @@ export const webviewMessageHandler = async ( // the hidden entries this reduced layer drops. currentScopes.workspace.filter((entry) => !promotionHiddenEntries.includes(entry)), // The global origin set decides which kept entries the Global - // write preserves, so it must cover the same layers as the - // retained-entry filter above: an entry only the - // configuration's own global layer holds is existing global - // knowledge even when the extension-state copy lags behind. - [...new Set([...currentScopes.global, ...configGlobalAtSaveStart])], + // write preserves, so it covers the same configuration layer + // as the retained-entry filter above: only the + // configuration's own global layer is evidence of existing + // global knowledge, because the extension-state copy is not + // refreshed when the settings file is edited directly. + configGlobalAtSaveStart, ) // The hidden set holds entries the dialog could not display, From 9a60347cd56ac02e4a1bac2c10a4ab7aa3aa55ee Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Mon, 16 Nov 2026 19:38:02 +0100 Subject: [PATCH 26/52] refactor: move proxy and auth teardown to a follow-up PR Command-list scoping, persistence, and seeding do not depend on proxy or auth teardown, and the review's Out-of-Scope check asked for that work as a separate PR referencing its own issue. This commit removes it from this branch; a follow-up PR will land it there. - src/utils/networkProxy.ts and its spec return to their base-branch state: initializeNetworkProxy no longer returns a disposable. - src/services/zoo-code-auth.ts returns to base-branch state: initZooCodeAuth no longer returns its secrets-listener disposable. - src/extension.ts drops the disposal wiring: the proxy resources and the auth listener are no longer retained, and the failed-activation teardown keeps only the steps that belong to this PR - telemetry shutdown, persistence-trace sink clear, output-channel dispose, then rethrow. - src/__tests__/extension.spec.ts drops the tests for the removed teardown and keeps the seed-failure tests scoped to the steps that remain. --- src/__tests__/extension.spec.ts | 290 +-------- src/extension.ts | 39 +- src/services/zoo-code-auth.ts | 14 +- src/utils/__tests__/networkProxy.spec.ts | 773 +---------------------- src/utils/networkProxy.ts | 205 ++---- 5 files changed, 68 insertions(+), 1253 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 327c38c38d..17e89f6cf5 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -3,12 +3,7 @@ import type * as vscode from "vscode" import type { WebviewMessage } from "@roo-code/types" -import { - makeCompositeDisposable, - makeEventEmitter, - makeExtensionContext, - makeWorkspaceConfiguration, -} from "../test-utils/vscode" +import { makeCompositeDisposable, makeEventEmitter, makeExtensionContext } from "../test-utils/vscode" vi.mock("vscode", () => ({ Disposable: { from: (...subscriptions: vscode.Disposable[]) => makeCompositeDisposable(...subscriptions) }, @@ -639,33 +634,6 @@ describe("extension.ts", () => { } }) - test("disposes the auth secret-storage listener when seeding rejects activation", async () => { - // A rejected seed aborts activation after the auth initializer has - // registered its secret-storage listener, and the host does not guarantee - // `deactivate()` after a failed activation, so the failure path must - // release the retained listener disposable itself. - vi.doMock("../utils/seedAllowedCommands", () => ({ - seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), - })) - const dispose = vi.fn() - const authListener = { dispose } - vi.doMock("../services/zoo-code-auth", () => ({ - initZooCodeAuth: vi.fn().mockResolvedValue(authListener), - })) - try { - const { activate } = await import("../extension") - await expect(activate(mockContext)).rejects.toThrow("seed state write failed") - - // Retained for the success path (deactivate disposes subscriptions) and - // disposed on the failure path, exactly once, with the error propagated. - expect(mockContext.subscriptions).toContain(authListener) - expect(dispose).toHaveBeenCalledExactlyOnceWith() - } finally { - vi.doUnmock("../utils/seedAllowedCommands") - vi.doUnmock("../services/zoo-code-auth") - } - }) - test("shuts down the telemetry service before propagating a seed rejection", async () => { // The telemetry client is created and registered before the seed point, // so a rejected seed must shut it down on the failure path: without @@ -675,11 +643,6 @@ describe("extension.ts", () => { seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), })) const teardownOrder: string[] = [] - vi.doMock("../services/zoo-code-auth", () => ({ - initZooCodeAuth: vi - .fn() - .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), - })) const { TelemetryService } = await import("@roo-code/telemetry") const shutdown = vi.mocked(TelemetryService.instance.shutdown) // A never-settling shutdown: activation may only reject once the awaited @@ -700,8 +663,8 @@ describe("extension.ts", () => { rejected = true }) - // Both teardown steps run on the failure path, in order, exactly once. - await vi.waitFor(() => expect(teardownOrder).toEqual(["auth-listener-disposed", "telemetry-shutdown"])) + // The awaited teardown step runs on the failure path, exactly once. + await vi.waitFor(() => expect(teardownOrder).toEqual(["telemetry-shutdown"])) // Still unrejected while the awaited shutdown is unsettled: the catch // must not propagate the seed rejection before teardown completes. @@ -712,7 +675,6 @@ describe("extension.ts", () => { } finally { shutdown.mockReset() vi.doUnmock("../utils/seedAllowedCommands") - vi.doUnmock("../services/zoo-code-auth") } }) @@ -726,11 +688,6 @@ describe("extension.ts", () => { seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), })) const teardownOrder: string[] = [] - vi.doMock("../services/zoo-code-auth", () => ({ - initZooCodeAuth: vi - .fn() - .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), - })) const { TelemetryService } = await import("@roo-code/telemetry") const shutdown = vi.mocked(TelemetryService.instance.shutdown) // Distinct from the seed error so any masking of the seed rejection is visible. @@ -750,156 +707,11 @@ describe("extension.ts", () => { expect(channel?.appendLine).toHaveBeenCalledWith( "Failed to shut down telemetry service: shutdown drain failed", ) - // Teardown still runs in order on this path: listener released before the shutdown call. - expect(teardownOrder).toEqual(["auth-listener-disposed", "telemetry-shutdown"]) - } finally { - shutdown.mockReset() - vi.doUnmock("../utils/seedAllowedCommands") - vi.doUnmock("../services/zoo-code-auth") - } - }) - - test("disposes the network proxy resources when seeding rejects activation", async () => { - // The debug-proxy resources are initialized before the seed point, and the host - // does not guarantee `deactivate()` after a failed activation, so the failure path - // must release them too: a retained configuration listener would let a - // `debugProxy.*` toggle re-apply proxy configuration inside a dead extension. - vi.doMock("../utils/seedAllowedCommands", () => ({ - seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), - })) - const teardownOrder: string[] = [] - const proxyDispose = vi.fn(() => void teardownOrder.push("proxy-disposed")) - vi.doMock("../utils/networkProxy", () => ({ - // The initializer resolves to the aggregate disposable covering the - // configuration listener, override cleanup, and fetch-patch restore. - initializeNetworkProxy: vi.fn().mockResolvedValue({ dispose: proxyDispose }), - getSystemProxyUrl: vi.fn().mockReturnValue(undefined), - isProxyEnabled: vi.fn().mockReturnValue(false), - createProxyRoutingRequestHandler: vi.fn().mockReturnValue(undefined), - })) - vi.doMock("../services/zoo-code-auth", () => ({ - initZooCodeAuth: vi - .fn() - .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), - })) - const { TelemetryService } = await import("@roo-code/telemetry") - const shutdown = vi.mocked(TelemetryService.instance.shutdown) - shutdown.mockImplementation(() => { - teardownOrder.push("telemetry-shutdown") - return Promise.resolve() - }) - try { - // Debug mode is the only mode in which the proxy initializer acquires - // resources, so it is the mode the failed-activation teardown applies to. - const vscode = await import("vscode") - const devContext = { ...mockContext, extensionMode: vscode.ExtensionMode.Development } - - const { activate } = await import("../extension") - await expect(activate(devContext)).rejects.toThrow("seed state write failed") - - // Strict reverse acquisition order: the proxy initializes first, telemetry - // second, the auth listener last, so teardown runs auth → telemetry → proxy, - // and the proxy disposable is released exactly once. - expect(teardownOrder).toEqual(["auth-listener-disposed", "telemetry-shutdown", "proxy-disposed"]) - expect(proxyDispose).toHaveBeenCalledExactlyOnceWith() + // The shutdown step still runs on this path. + expect(teardownOrder).toEqual(["telemetry-shutdown"]) } finally { shutdown.mockReset() vi.doUnmock("../utils/seedAllowedCommands") - vi.doUnmock("../services/zoo-code-auth") - vi.doUnmock("../utils/networkProxy") - } - }) - - // When activation starts with the debug proxy disabled, only the configuration - // listener can build the undici dispatcher agent, so the failed-activation - // teardown must own that listener-created resource. This runs the real - // initializer with undici/global-agent doubles swapped in and gates the seed - // rejection until the listener-path install has settled, so the close is - // observed through the aggregate dispose rather than the late-import guard. - test("closes the listener-created proxy agent when seeding rejects after a mid-session enable", async () => { - let rejectSeed: () => void = () => {} - vi.doMock("../utils/seedAllowedCommands", () => ({ - seedCommandList: vi.fn( - () => - new Promise((_resolve, reject) => { - rejectSeed = () => reject(new Error("seed state write failed")) - }), - ), - })) - const closeSpy = vi.fn().mockResolvedValue(undefined) - const proxyAgentCtor = vi.fn().mockImplementation(function () { - return { close: closeSpy } - }) - // The slot double mirrors undici's global dispatcher state so the conditional - // restore is observable on this teardown path. - const defaultDispatcher = { close: vi.fn().mockResolvedValue(undefined) } - const dispatcherSlot: { current: unknown } = { current: defaultDispatcher } - const setGlobalDispatcher = vi.fn((dispatcher: unknown) => { - dispatcherSlot.current = dispatcher - }) - const getGlobalDispatcher = vi.fn(() => dispatcherSlot.current) - vi.doMock("undici", () => ({ - ProxyAgent: proxyAgentCtor, - setGlobalDispatcher, - getGlobalDispatcher, - fetch: vi.fn(), - })) - vi.doMock("global-agent", () => ({ bootstrap: vi.fn() })) - try { - const vscode = await import("vscode") - const { Package } = await import("../shared/package") - let configListener: - ((event: { affectsConfiguration: (section: string) => boolean }) => void) | undefined - vi.mocked(vscode.workspace.onDidChangeConfiguration).mockImplementation((listener) => { - configListener = listener as typeof configListener - return { dispose: vi.fn() } - }) - // Mutable so flipping enabled=true re-reads exactly like a live settings - // toggle: the helper's get() reads the record at call time. - const debugProxyValues: Record = { - "debugProxy.enabled": false, - "debugProxy.serverUrl": "http://localhost:8080", - "debugProxy.tlsInsecure": false, - } - const otherSections = makeWorkspaceConfiguration() - vi.mocked(vscode.workspace.getConfiguration).mockImplementation((section?: string) => - section === Package.name ? makeWorkspaceConfiguration(debugProxyValues) : otherSections, - ) - const fetchBefore = globalThis.fetch - try { - const devContext = { ...mockContext, extensionMode: vscode.ExtensionMode.Development } - const { activate } = await import("../extension") - const activation = activate(devContext) - - // Activation has registered the configuration listener and reached the - // gated seed: flip the toggle on, as a mid-session settings change would. - await vi.waitFor(() => expect(configListener).toBeTypeOf("function")) - debugProxyValues["debugProxy.enabled"] = true - configListener?.({ affectsConfiguration: () => true }) - // The listener-path agent is installed before the seed failure arrives, so - // the teardown below closes an installed agent, not a late-import one. - await vi.waitFor(() => expect(setGlobalDispatcher).toHaveBeenCalledOnce()) - - rejectSeed() - await expect(activation).rejects.toThrow("seed state write failed") - - // The aggregate owned the listener-created agent: the dispatcher captured - // at install is back in the slot and the agent closed exactly once. - expect(dispatcherSlot.current).toBe(defaultDispatcher) - expect(setGlobalDispatcher).toHaveBeenLastCalledWith(defaultDispatcher) - expect(closeSpy).toHaveBeenCalledOnce() - // The fetch patch the listener applied is restored by the same teardown. - expect(globalThis.fetch).toBe(fetchBefore) - } finally { - globalThis.fetch = fetchBefore - delete process.env.GLOBAL_AGENT_HTTP_PROXY - delete process.env.GLOBAL_AGENT_HTTPS_PROXY - delete process.env.GLOBAL_AGENT_NO_PROXY - } - } finally { - vi.doUnmock("../utils/seedAllowedCommands") - vi.doUnmock("undici") - vi.doUnmock("global-agent") } }) @@ -912,20 +724,6 @@ describe("extension.ts", () => { seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), })) const teardownOrder: string[] = [] - const proxyDispose = vi.fn(() => void teardownOrder.push("proxy-disposed")) - vi.doMock("../utils/networkProxy", () => ({ - // The mock returns the aggregate disposable unconditionally; the - // mode-gating of the real initializer is pinned in its own spec. - initializeNetworkProxy: vi.fn().mockResolvedValue({ dispose: proxyDispose }), - getSystemProxyUrl: vi.fn().mockReturnValue(undefined), - isProxyEnabled: vi.fn().mockReturnValue(false), - createProxyRoutingRequestHandler: vi.fn().mockReturnValue(undefined), - })) - vi.doMock("../services/zoo-code-auth", () => ({ - initZooCodeAuth: vi - .fn() - .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), - })) const { TelemetryService } = await import("@roo-code/telemetry") const shutdown = vi.mocked(TelemetryService.instance.shutdown) shutdown.mockImplementation(() => { @@ -944,14 +742,9 @@ describe("extension.ts", () => { await expect(activate(mockContext)).rejects.toThrow("seed state write failed") // Strict reverse acquisition: the channel was acquired first, so it is - // disposed after auth, telemetry, and the proxy — every teardown log - // line was still writable when those steps ran. - expect(teardownOrder).toEqual([ - "auth-listener-disposed", - "telemetry-shutdown", - "proxy-disposed", - "channel-disposed", - ]) + // disposed after the telemetry shutdown — every teardown log line was + // still writable when that step ran. + expect(teardownOrder).toEqual(["telemetry-shutdown", "channel-disposed"]) expect(channel.dispose).toHaveBeenCalledExactlyOnceWith() // Still registered for the normal deactivate path; the failure-path // dispose must not have replaced the subscription push. @@ -959,8 +752,6 @@ describe("extension.ts", () => { } finally { shutdown.mockReset() vi.doUnmock("../utils/seedAllowedCommands") - vi.doUnmock("../services/zoo-code-auth") - vi.doUnmock("../utils/networkProxy") } }) @@ -974,20 +765,6 @@ describe("extension.ts", () => { seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), })) const teardownOrder: string[] = [] - const proxyDispose = vi.fn(() => void teardownOrder.push("proxy-disposed")) - vi.doMock("../utils/networkProxy", () => ({ - // The mock returns the aggregate disposable unconditionally; the - // mode-gating of the real initializer is pinned in its own spec. - initializeNetworkProxy: vi.fn().mockResolvedValue({ dispose: proxyDispose }), - getSystemProxyUrl: vi.fn().mockReturnValue(undefined), - isProxyEnabled: vi.fn().mockReturnValue(false), - createProxyRoutingRequestHandler: vi.fn().mockReturnValue(undefined), - })) - vi.doMock("../services/zoo-code-auth", () => ({ - initZooCodeAuth: vi - .fn() - .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), - })) // Only the teardown call is an order marker: installation passes the // channel-logging sink, while clearing passes undefined — the setter's // documented way to restore the default console sink. @@ -1017,17 +794,11 @@ describe("extension.ts", () => { const { activate } = await import("../extension") await expect(activate(mockContext)).rejects.toThrow("seed state write failed") - // Reverse acquisition order pins the clear between the proxy release - // and the channel dispose: the sink was installed after the channel - // it logs through but before the proxy, so it is released after the - // proxy — and before the channel, which goes last. - expect(teardownOrder).toEqual([ - "auth-listener-disposed", - "telemetry-shutdown", - "proxy-disposed", - "trace-sink-cleared", - "channel-disposed", - ]) + // Reverse acquisition order: the sink was installed after the channel + // it logs through but before the telemetry client, so it is cleared + // after the telemetry shutdown — and before the channel, which goes + // last. + expect(teardownOrder).toEqual(["telemetry-shutdown", "trace-sink-cleared", "channel-disposed"]) // Exactly the install call and the clear: the failure path neither // skips the clear nor repeats it. expect(setPersistenceTraceSink).toHaveBeenCalledTimes(2) @@ -1036,45 +807,10 @@ describe("extension.ts", () => { } finally { shutdown.mockReset() vi.doUnmock("../utils/seedAllowedCommands") - vi.doUnmock("../services/zoo-code-auth") - vi.doUnmock("../utils/networkProxy") vi.doUnmock("../core/task-persistence/persistenceTrace") } }) - test("propagates the seed rejection when the proxy initializer acquired nothing", async () => { - // Outside debug mode the real initializer returns a no-op disposable, so the - // failed-activation teardown on the catch path must stay harmless: auth and - // telemetry still tear down, and the seed error still reaches the host. - vi.doMock("../utils/seedAllowedCommands", () => ({ - seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), - })) - const teardownOrder: string[] = [] - vi.doMock("../services/zoo-code-auth", () => ({ - initZooCodeAuth: vi - .fn() - .mockResolvedValue({ dispose: () => void teardownOrder.push("auth-listener-disposed") }), - })) - const { TelemetryService } = await import("@roo-code/telemetry") - const shutdown = vi.mocked(TelemetryService.instance.shutdown) - shutdown.mockImplementation(() => { - teardownOrder.push("telemetry-shutdown") - return Promise.resolve() - }) - try { - // mockContext carries no Development extensionMode, so the unmocked - // initializer takes its early return and acquires nothing. - const { activate } = await import("../extension") - await expect(activate(mockContext)).rejects.toThrow("seed state write failed") - - expect(teardownOrder).toEqual(["auth-listener-disposed", "telemetry-shutdown"]) - } finally { - shutdown.mockReset() - vi.doUnmock("../utils/seedAllowedCommands") - vi.doUnmock("../services/zoo-code-auth") - } - }) - test("does not shut down telemetry when activation completes", async () => { // Telemetry shutdown is failure-path only: a successfully activated // extension owns the telemetry client until deactivate() runs. diff --git a/src/extension.ts b/src/extension.ts index b094d22614..3ed27f80cc 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -135,10 +135,8 @@ export async function activate(context: vscode.ExtensionContext) { // Initialize network proxy configuration early, before any network requests. // When proxyUrl is configured, all HTTP/HTTPS traffic will be routed through it. - // Only applied in debug mode (F5). The returned disposable covers the debug-proxy - // resources; keep it for both the normal deactivate path and the failed-activation - // path below. - const proxyResources = await initializeNetworkProxy(context, outputChannel) + // Only applied in debug mode (F5). + await initializeNetworkProxy(context, outputChannel) // Set extension path for custom tool registry to find bundled esbuild customToolRegistry.setExtensionPath(context.extensionPath) @@ -170,11 +168,7 @@ export async function activate(context: vscode.ExtensionContext) { kimiCodeOAuthManager.initialize(context) // Initialize Zoo Code auth service for extension session token management. - // The returned disposable unregisters the secret-storage listener the - // initializer acquires; keep it for both the normal deactivate path and the - // failed-activation path below. - const authSecretsListener = await initZooCodeAuth(context) - context.subscriptions.push(authSecretsListener) + await initZooCodeAuth(context) // Seed before the terminal registry is initialized: a rejected seed must // abort activation while the registry holds no resources, because its @@ -188,17 +182,15 @@ export async function activate(context: vscode.ExtensionContext) { await seedCommandList(context.globalState, "deniedCommands") } catch (error) { // Activation aborts here, and `deactivate()` is not guaranteed to run - // afterward, so this catch is the only teardown for everything - // initialized before the seed point: release the secret-storage - // listener, shut down the telemetry client registered above, release - // the debug-proxy resources, clear the persistence trace sink, and - // dispose the output channel — in strict reverse acquisition order - // (auth was acquired last, the output channel first), each step - // disposed only after the previous one settles. - // Teardown failures are logged rather than rethrown so they cannot mask - // the seed rejection; the telemetry service bounds its own drain and - // client-flush phases, so a stuck client cannot hang the host here. - authSecretsListener.dispose() + // afterward, so this catch performs its own teardown before rethrowing: + // shut down the telemetry client registered above, clear the + // persistence trace sink, and dispose the output channel — in reverse + // of the order those three were acquired (the output channel was + // first), each step run only after the previous one settles. + // Teardown failures are logged or dropped, never rethrown, so they + // cannot mask the seed rejection; the telemetry service bounds its own + // drain and client-flush phases, so a stuck client cannot hang the + // host here. try { await telemetryService.shutdown() } catch (shutdownError) { @@ -206,13 +198,6 @@ export async function activate(context: vscode.ExtensionContext) { `Failed to shut down telemetry service: ${shutdownError instanceof Error ? shutdownError.message : String(shutdownError)}`, ) } - try { - proxyResources.dispose() - } catch (disposeError) { - outputChannel.appendLine( - `Failed to dispose network proxy resources: ${disposeError instanceof Error ? disposeError.message : String(disposeError)}`, - ) - } // The persistence trace sink installed above writes its lines through // the output channel, so it is cleared — passing undefined restores the // default console sink — before the channel is disposed, keeping any diff --git a/src/services/zoo-code-auth.ts b/src/services/zoo-code-auth.ts index 0a052c503e..709cb805c3 100644 --- a/src/services/zoo-code-auth.ts +++ b/src/services/zoo-code-auth.ts @@ -7,9 +7,6 @@ const ZOO_CODE_USER_NAME_KEY = "zoo-code-user-name" const ZOO_CODE_USER_EMAIL_KEY = "zoo-code-user-email" const ZOO_CODE_USER_IMAGE_KEY = "zoo-code-user-image" -// Returned when no listener was acquired, so callers can dispose unconditionally. -const NOOP_DISPOSABLE: vscode.Disposable = { dispose: () => {} } - let secretStorage: vscode.SecretStorage | undefined // In-memory cache for synchronous access in ZooCodeHandler hot path @@ -19,11 +16,11 @@ let _cachedUserName: string | undefined = undefined let _cachedUserEmail: string | undefined = undefined let _cachedUserImage: string | undefined = undefined -export async function initZooCodeAuth(context: vscode.ExtensionContext): Promise { +export async function initZooCodeAuth(context: vscode.ExtensionContext): Promise { if (!context.secrets) { // Secret storage unavailable (e.g. test environment without secrets mock). // Treat as unauthenticated startup — all cached values remain undefined. - return NOOP_DISPOSABLE + return } secretStorage = context.secrets @@ -45,11 +42,8 @@ export async function initZooCodeAuth(context: vscode.ExtensionContext): Promise } } - // Watch for secret changes and update cache. The returned disposable unregisters - // the listener: an activation that fails after this point must release it itself, - // because the host does not guarantee `deactivate()` (and with it - // context.subscriptions cleanup) after activation throws. - return context.secrets.onDidChange((e) => { + // Watch for secret changes and update cache + context.secrets.onDidChange((e) => { if (e.key === ZOO_CODE_TOKEN_KEY) { secretStorage?.get(ZOO_CODE_TOKEN_KEY).then((token) => { _cachedToken = token diff --git a/src/utils/__tests__/networkProxy.spec.ts b/src/utils/__tests__/networkProxy.spec.ts index 97cc6c45c3..fc789878c8 100644 --- a/src/utils/__tests__/networkProxy.spec.ts +++ b/src/utils/__tests__/networkProxy.spec.ts @@ -2,7 +2,6 @@ import * as vscode from "vscode" import { NodeHttpHandler } from "@smithy/node-http-handler" import { HttpProxyAgent } from "http-proxy-agent" import { HttpsProxyAgent } from "https-proxy-agent" -import { makeWorkspaceConfiguration } from "../../test-utils/vscode" import { initializeNetworkProxy, getProxyConfig, @@ -12,43 +11,9 @@ import { createProxyRoutingRequestHandler, } from "../networkProxy" -// Mock global-agent and undici: the real bootstrap()/setGlobalDispatcher() write -// process-global state every later test would inherit, and the real ProxyAgent owns sockets. -const mocks = vi.hoisted(() => { - const closeSpy = vi.fn().mockResolvedValue(undefined) - // undici's global dispatcher slot always holds a dispatcher (it lazily creates the - // default one), so the double's slot starts with a sentinel object rather than - // undefined: a captured "previous dispatcher" must be a real object, as in undici. - const defaultDispatcher = { close: vi.fn().mockResolvedValue(undefined) } - const dispatcherSlot: { current: unknown } = { current: defaultDispatcher } - return { - bootstrap: vi.fn(), - // mockImplementation with a plain function keeps the double constructible: the - // production path calls `new ProxyAgent(...)`, which an arrow implementation rejects. - proxyAgent: vi.fn().mockImplementation(function () { - return { close: closeSpy } - }), - proxyAgentClose: closeSpy, - // A scriptable slot mirrors undici's global dispatcher state: get returns what set - // last wrote, so a test can install a third-party dispatcher between install and - // teardown and observe which dispatcher survives. - setGlobalDispatcher: vi.fn((dispatcher: unknown) => { - dispatcherSlot.current = dispatcher - }), - getGlobalDispatcher: vi.fn(() => dispatcherSlot.current), - dispatcherSlot, - defaultDispatcher, - undiciFetch: vi.fn(), - } -}) - -vi.mock("global-agent", () => ({ bootstrap: mocks.bootstrap })) - -vi.mock("undici", () => ({ - ProxyAgent: mocks.proxyAgent, - setGlobalDispatcher: mocks.setGlobalDispatcher, - getGlobalDispatcher: mocks.getGlobalDispatcher, - fetch: mocks.undiciFetch, +// Mock global-agent +vi.mock("global-agent", () => ({ + bootstrap: vi.fn(), })) vi.mock("@smithy/node-http-handler", () => ({ @@ -121,9 +86,6 @@ describe("networkProxy", () => { beforeEach(() => { vi.clearAllMocks() - // Dispatcher-slot state is process-lifetime in undici; reset it per test so each - // run captures the same "previous dispatcher". - mocks.dispatcherSlot.current = mocks.defaultDispatcher // Reset environment variables delete process.env.GLOBAL_AGENT_HTTP_PROXY @@ -239,735 +201,6 @@ describe("networkProxy", () => { void initializeNetworkProxy(context, mockOutputChannel) }).not.toThrow() }) - - // A failed activation does not guarantee deactivate() runs, so the disposable - // initializeNetworkProxy returns must release every resource that was also registered on - // context.subscriptions - a retained configuration listener could re-apply proxy and TLS - // overrides inside a dead extension. The module is re-imported so the debug-mode resource - // paths (listener, override cleanup, fetch patch) all execute: the latches that keep - // global-agent bootstrap and the fetch patch one-shot would otherwise be tripped by - // earlier tests, leaving a one-sided registration invisible to this equivalence check. - it("should dispose every resource registered on context.subscriptions when the returned disposable is disposed", async () => { - // Other tests in this file call initializeNetworkProxy without awaiting it, and a - // debug-mode run patches global fetch only after its dynamic imports settle. Awaiting - // one debug-mode run and one production-mode run here first: the awaited debug run - // settles the module's one-shot fetch-patch latch, so any still-pending earlier run - // skips its patch instead of racing this test's sentinel, and the trailing - // production-mode run leaves the shared module on the extension context and - // no-patch state the following tests expect. - mockConfig.get.mockImplementation((key: string) => { - if (key === "debugProxy.enabled") return true - if (key === "debugProxy.serverUrl") return "http://localhost:8080" - if (key === "debugProxy.tlsInsecure") return true - return "" - }) - const fetchBefore = globalThis.fetch - try { - await initializeNetworkProxy(createMockContext(vscode.ExtensionMode.Development), mockOutputChannel) - await initializeNetworkProxy(createMockContext(vscode.ExtensionMode.Production), mockOutputChannel) - - vi.resetModules() - // The runs above left the TLS override applied; drop it so the run under test - // captures "unset" as its restore target. - delete process.env.NODE_TLS_REJECT_UNAUTHORIZED - - // A local sentinel function stands in for the pre-patch global fetch: asserting - // the restore comes back to this exact reference is deterministic regardless of - // which fetch implementation is installed at this point. - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - - const freshModule = await import("../networkProxy") - const freshVscode = await import("vscode") - // resetModules re-runs the vscode mock factory, so the re-imported module reads - // its configuration through a fresh getConfiguration spy that needs the stub. - vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( - makeWorkspaceConfiguration({ - "debugProxy.enabled": true, - "debugProxy.serverUrl": "http://localhost:8080", - "debugProxy.tlsInsecure": true, - }), - ) - - const context = createMockContext(vscode.ExtensionMode.Development) - const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - - // Snapshot the registration side, then observe each registered object's own - // dispose: the assertion below holds only if the returned aggregate releases the - // same objects registered on context.subscriptions, which is the invariant. - const registered = [...context.subscriptions] - // Configuration listener, override cleanup, and the proxy-agent resource: the - // scenario must register all three for the equivalence to cover every - // acquisition. - expect(registered.length).toBe(3) - // Both observable overrides are applied before teardown. - expect(globalThis.fetch).not.toBe(fetchSentinel) - expect(process.env.NODE_TLS_REJECT_UNAUTHORIZED).toBe("0") - - const spiedDisposes = registered.map((resource) => vi.spyOn(resource, "dispose")) - returned.dispose() - - for (const dispose of spiedDisposes) { - expect(dispose).toHaveBeenCalledOnce() - } - // Teardown restores both observable overrides: fetch and the TLS setting. - expect(globalThis.fetch).toBe(fetchSentinel) - expect(process.env.NODE_TLS_REJECT_UNAUTHORIZED).toBeUndefined() - } finally { - globalThis.fetch = fetchBefore - } - }) - - // The proxy agent owns sockets, and both configure* helpers suspend on dynamic imports, - // so teardown must close the agent and the import continuations must refuse to install - // process-global state after disposal. Each test re-imports the module after - // resetModules so the one-shot latches (global-agent bootstrap, fetch patch, dispatcher) - // start untripped, as the aggregate-invariant test above does. - describe("undici disposal and post-dispose import races", () => { - // A dynamic import of a mocked module still resolves asynchronously, so - // initializeNetworkProxy returns at its first await and the configure* continuations - // run only once the test awaits it: disposing synchronously in between lands the - // teardown while both imports are in flight, which is the interleaving the guards - // must reject. - function disposeMidFlight(context: vscode.ExtensionContext): void { - // Only the configuration listener and the override cleanup are registered while - // the imports are pending; disposing them is what VS Code does item-by-item on - // unload, and it latches the module's disposed flag. - expect(context.subscriptions).toHaveLength(2) - context.subscriptions.forEach((subscription) => subscription.dispose()) - } - - // Re-imported module plus a development-mode context with the debug proxy enabled; - // resetModules re-runs the vscode mock factory, so the fresh module's configuration - // spy needs the stub before initializeNetworkProxy reads it. The mock spies are - // shared across the file, so each test starts from a clean call log. - async function freshDebugRunContext(): Promise<{ - freshModule: typeof import("../networkProxy") - context: vscode.ExtensionContext - }> { - vi.clearAllMocks() - mocks.proxyAgent.mockImplementation(function () { - return { close: mocks.proxyAgentClose } - }) - const freshModule = await import("../networkProxy") - const freshVscode = await import("vscode") - vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( - makeWorkspaceConfiguration({ - "debugProxy.enabled": true, - "debugProxy.serverUrl": "http://localhost:8080", - "debugProxy.tlsInsecure": false, - }), - ) - return { freshModule, context: createMockContext(vscode.ExtensionMode.Development) } - } - - it("closes the proxy agent and restores the fetch patch when the returned disposable is disposed", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context } = await freshDebugRunContext() - - const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - - // Accept path: while the extension is alive the disposal guards are - // transparent, and everything this module can install gets installed. - expect(mocks.bootstrap).toHaveBeenCalledOnce() - expect(mocks.setGlobalDispatcher).toHaveBeenCalledWith( - expect.objectContaining({ close: mocks.proxyAgentClose }), - ) - expect(globalThis.fetch).not.toBe(fetchSentinel) - // Configuration listener, override cleanup, and the agent-owning undici - // resource: the agent must be among the registered subscriptions for the - // deactivate path to reach its close. - expect(context.subscriptions).toHaveLength(3) - - returned.dispose() - - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - it("logs and swallows a rejected agent close during teardown", async () => { - vi.resetModules() - const closeFailure = new Error("close failed") - mocks.proxyAgentClose.mockRejectedValueOnce(closeFailure) - const fetchBefore = globalThis.fetch - globalThis.fetch = () => Promise.reject(new Error("sentinel fetch")) - let returned: vscode.Disposable | undefined - try { - const { freshModule, context } = await freshDebugRunContext() - - returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - - // A rejected close must not throw out of the synchronous dispose or leave an - // unhandled rejection: the teardown logs it and continues releasing resources. - expect(() => returned?.dispose()).not.toThrow() - // The rejection is logged on the microtask the best-effort close awaits. - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( - "Failed to close undici proxy agent: close failed", - ) - } finally { - returned?.dispose() - globalThis.fetch = fetchBefore - } - }) - - it("closes the agent only once when disposal runs through both owners", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context } = await freshDebugRunContext() - - const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - - // The undici resource is registered on context.subscriptions AND collected - // in the aggregate disposable, so an activation-failure teardown can reach - // it again after VS Code (or a re-disposal) already went through the list; - // the close must still happen exactly once. - returned.dispose() - returned.dispose() - context.subscriptions.forEach((subscription) => subscription.dispose()) - - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - // Install plus the single conditional restore from the first dispose; the - // once-guard keeps the repeated disposals from restoring or closing again. - expect(mocks.setGlobalDispatcher).toHaveBeenCalledTimes(2) - expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - // The dispatcher that predates the install must be back in undici's global slot - // after teardown, or every later fetch in a surviving extension host routes - // through the closed proxy agent. - it("restores the dispatcher captured at install time when the returned disposable is disposed", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context } = await freshDebugRunContext() - - const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - - const installed = mocks.dispatcherSlot.current - expect(installed).not.toBe(mocks.defaultDispatcher) - - returned.dispose() - - // The captured pre-install dispatcher is back, not a fresh default or an - // unset slot: this is dispatcher restoration, not fetch-function identity. - expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) - expect(mocks.setGlobalDispatcher).toHaveBeenLastCalledWith(mocks.defaultDispatcher) - // Restore happens before the close, so no fetch started after teardown can - // land on the closing agent. - expect(mocks.setGlobalDispatcher.mock.invocationCallOrder[1]).toBeLessThan( - mocks.proxyAgentClose.mock.invocationCallOrder[0], - ) - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - it("leaves a third-party dispatcher installed after ours untouched when disposal runs", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context } = await freshDebugRunContext() - - const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - - // Another component replaces the global slot after our install; that slot - // belongs to its installer, so our teardown must leave it alone. - const thirdPartyDispatcher = { close: vi.fn().mockResolvedValue(undefined) } - mocks.setGlobalDispatcher(thirdPartyDispatcher) - - returned.dispose() - - expect(mocks.dispatcherSlot.current).toBe(thirdPartyDispatcher) - // Install + third-party swap only: no restore call on this branch. - expect(mocks.setGlobalDispatcher).toHaveBeenCalledTimes(2) - expect(mocks.setGlobalDispatcher).toHaveBeenLastCalledWith(thirdPartyDispatcher) - // The conditional restore does not skip closing the agent we own. - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - it("skips the global-agent bootstrap when disposal runs before the import settles", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context } = await freshDebugRunContext() - - const init = freshModule.initializeNetworkProxy(context, mockOutputChannel) - disposeMidFlight(context) - await init - - // Reject path for the global-agent suspension point: the late continuation - // must not bootstrap global-agent for a disposed extension. - expect(mocks.bootstrap).not.toHaveBeenCalled() - expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( - "global-agent import completed after disposal; skipping bootstrap", - ) - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - it("closes a late proxy agent without installing it when disposal runs before the undici import settles", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context } = await freshDebugRunContext() - - const init = freshModule.initializeNetworkProxy(context, mockOutputChannel) - disposeMidFlight(context) - await init - - // Reject path for the undici suspension point: the agent is constructed only - // once the import settles - after teardown - so the guard must close it and - // install nothing: no dispatcher swap, no fetch patch for a dead extension. - expect(mocks.proxyAgent).toHaveBeenCalledOnce() - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() - expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( - "undici import completed after disposal; closing the late proxy agent without installing it", - ) - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - // A seed-failure teardown also disposes the extension's output channel, and VS - // Code throws "Channel has been closed" from appendLine() afterwards. The - // post-dispose continuation must therefore survive a throwing log sink: a - // propagating throw would skip the late agent's close, and the retry inside the - // outer catch would reject the configureUndiciProxy promise no caller awaits. - it("closes the late agent and resolves when the output channel was disposed during teardown", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - let channelClosed = false - const closedChannel: vscode.OutputChannel = { - name: "Closed in test", - append: vi.fn(), - appendLine: vi.fn(() => { - if (channelClosed) { - throw new Error("Channel has been closed") - } - }), - replace: vi.fn(), - clear: vi.fn(), - show: vi.fn(), - hide: vi.fn(), - dispose: vi.fn(() => { - channelClosed = true - }), - } - try { - const { freshModule, context } = await freshDebugRunContext() - // The late close rejects too, so the deferred close-error log inside the - // best-effort close runs against the same closed channel. - mocks.proxyAgentClose.mockRejectedValueOnce(new Error("close failed")) - - const init = freshModule.initializeNetworkProxy(context, closedChannel) - disposeMidFlight(context) - closedChannel.dispose() - // An init promise that the activation-failure path ignores must resolve, - // not reject, when every teardown log it emits throws. - await expect(init).resolves.toBeDefined() - // Flush the close rejection's catch chain so a handler that rethrows - // surfaces here as an unhandled rejection rather than escaping the test. - await new Promise((resolve) => setTimeout(resolve, 0)) - - expect(mocks.proxyAgent).toHaveBeenCalledOnce() - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - // Swallowing is limited to appendLine failures: with a live channel the same - // post-dispose continuation still writes both disposal logs to it. - it("keeps writing the post-dispose teardown logs when the channel is still open", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context } = await freshDebugRunContext() - - const init = freshModule.initializeNetworkProxy(context, mockOutputChannel) - disposeMidFlight(context) - await init - - const logged = vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n") - expect(logged).toContain("global-agent import completed after disposal; skipping bootstrap") - expect(logged).toContain( - "undici import completed after disposal; closing the late proxy agent without installing it", - ) - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - // The outer catch of configureUndiciProxy logs through the same teardown-safe - // logger, so the import-failure path must surface the failure on the channel and - // still resolve: the configured proxy is best-effort, and activation continues - // without it. - it("logs and swallows an undici import failure without installing anything", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - vi.doMock("undici", () => { - throw new Error("undici unavailable") - }) - try { - const { freshModule, context } = await freshDebugRunContext() - - // The ignored configureUndiciProxy path must resolve despite the rejection. - // (The expected error text is only the log prefix: vitest wraps factory - // errors, so the suffix is its own message, not the thrown one.) - await expect(freshModule.initializeNetworkProxy(context, mockOutputChannel)).resolves.toBeDefined() - expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( - "Failed to configure undici proxy dispatcher", - ) - expect(mocks.proxyAgent).not.toHaveBeenCalled() - expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - // Re-register the resolved factory and drop the cached module so later tests - // resolve undici exactly as through the file-level mock. - vi.doMock("undici", () => ({ - ProxyAgent: mocks.proxyAgent, - setGlobalDispatcher: mocks.setGlobalDispatcher, - getGlobalDispatcher: mocks.getGlobalDispatcher, - fetch: mocks.undiciFetch, - })) - vi.resetModules() - globalThis.fetch = fetchBefore - } - }) - }) - - // When the proxy is disabled at activation, only the configuration-change listener - // can build the dispatcher agent later; the aggregate disposable must own that - // listener-created resource too, or a mid-session enable survives the teardown a - // failed activation performs. Each test runs on a reset module instance so the - // shared latches start untripped, as in the disposal tests. - describe("listener-path agent ownership", () => { - // Fresh module instance whose activation starts with the proxy disabled; the - // configuration record is mutable so a test can flip debugProxy.enabled before - // firing the captured configuration-change listener. - async function freshToggledRunContext(): Promise<{ - freshModule: typeof import("../networkProxy") - context: vscode.ExtensionContext - configValues: Record - fireConfigChange: () => void - }> { - vi.clearAllMocks() - const configValues: Record = { - "debugProxy.enabled": false, - "debugProxy.serverUrl": "http://localhost:8080", - "debugProxy.tlsInsecure": false, - } - const freshModule = await import("../networkProxy") - const freshVscode = await import("vscode") - vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( - makeWorkspaceConfiguration(configValues), - ) - let configListener: - ((event: { affectsConfiguration: (section: string) => boolean }) => void) | undefined - vi.mocked(freshVscode.workspace.onDidChangeConfiguration).mockImplementation((listener) => { - configListener = listener as typeof configListener - return { dispose: vi.fn() } - }) - const context = createMockContext(vscode.ExtensionMode.Development) - return { - freshModule, - context, - configValues, - fireConfigChange: () => configListener?.({ affectsConfiguration: () => true }), - } - } - - it("closes the listener-created agent exactly once when the aggregate disposable is disposed", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context, configValues, fireConfigChange } = await freshToggledRunContext() - - const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - - // Activation with the proxy disabled registers only the listener and the - // override cleanup; no agent is built yet. - expect(context.subscriptions).toHaveLength(2) - expect(mocks.proxyAgent).not.toHaveBeenCalled() - - configValues["debugProxy.enabled"] = true - fireConfigChange() - // The listener's configure* calls resolve on their own microtasks. - await vi.waitFor(() => expect(mocks.proxyAgent).toHaveBeenCalledOnce()) - expect(mocks.setGlobalDispatcher).toHaveBeenCalledOnce() - expect(mocks.dispatcherSlot.current).not.toBe(mocks.defaultDispatcher) - expect(globalThis.fetch).not.toBe(fetchSentinel) - - returned.dispose() - - // The aggregate owns the agent the listener created: its close and the - // dispatcher restore run here, not at toggle time. - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) - expect(globalThis.fetch).toBe(fetchSentinel) - - // Re-disposal through the same owner must not close a second time. - returned.dispose() - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - } finally { - globalThis.fetch = fetchBefore - } - }) - - it("closes an agent created by a post-dispose listener event without installing it", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - try { - const { freshModule, context, configValues, fireConfigChange } = await freshToggledRunContext() - - await freshModule.initializeNetworkProxy(context, mockOutputChannel) - configValues["debugProxy.enabled"] = true - - // Disposing first, then toggling, is the interleaving that a settings - // event can still deliver after a failed activation tore everything down. - context.subscriptions.forEach((subscription) => subscription.dispose()) - fireConfigChange() - - // The disposal latch rejects the late continuation: the agent is closed - // without ever being installed, so no new agent leaks into the process. - await vi.waitFor(() => expect(mocks.proxyAgent).toHaveBeenCalledOnce()) - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() - expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) - expect(mocks.bootstrap).not.toHaveBeenCalled() - expect(vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n")).toContain( - "undici import completed after disposal; closing the late proxy agent without installing it", - ) - expect(globalThis.fetch).toBe(fetchSentinel) - } finally { - globalThis.fetch = fetchBefore - } - }) - - // Two debugProxy config events fired inside the `await import("undici")` window both - // pass the already-configured check ahead of the import. Only the first may install: - // a second install would capture the first agent as its "previous dispatcher", and - // that teardown would then restore a closed agent into undici's global slot. - // doMock keeps the undici factory pending so the first event is verifiably parked - // at its import while the second event passes the latch check; the file-level static - // mock cannot provide that window because its module is already resolved in every - // later test. - it("closes the second of two config events fired inside the undici import window", async () => { - vi.resetModules() - const fetchBefore = globalThis.fetch - const fetchSentinel: typeof fetch = () => Promise.reject(new Error("sentinel fetch")) - globalThis.fetch = fetchSentinel - let releaseImport: () => void = () => {} - const importPending = new Promise((resolve) => { - releaseImport = resolve - }) - vi.doMock("undici", () => - importPending.then(() => ({ - ProxyAgent: mocks.proxyAgent, - setGlobalDispatcher: mocks.setGlobalDispatcher, - getGlobalDispatcher: mocks.getGlobalDispatcher, - fetch: mocks.undiciFetch, - })), - ) - try { - const { freshModule, context, configValues, fireConfigChange } = await freshToggledRunContext() - // Once-implementations so the per-agent close spies do not leak past this - // test: the shared file-level spy cannot say *which* of the two agents a - // close came from, and this witness turns on that distinction. Exactly two - // constructions occur, consuming both queued implementations. - const agents: Array<{ close: ReturnType }> = [] - const recordAgent = function (this: unknown) { - const close = vi.fn().mockResolvedValue(undefined) - const agent = { close } - agents.push(agent) - return agent - } - mocks.proxyAgent.mockImplementationOnce(recordAgent).mockImplementationOnce(recordAgent) - - const returned = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - configValues["debugProxy.enabled"] = true - - fireConfigChange() - // The first event is now parked in configureUndiciProxy's import: the pending - // factory keeps it suspended while the module registration settles, so the - // second event demonstrably passes the latch check mid-flight. - await new Promise((resolve) => setTimeout(resolve, 10)) - expect(mocks.proxyAgent).not.toHaveBeenCalled() - fireConfigChange() - releaseImport() - - await vi.waitFor(() => expect(mocks.proxyAgent).toHaveBeenCalledTimes(2)) - expect(agents).toHaveLength(2) - - // Accept path: the first event installs and owns the global slot. - expect(mocks.dispatcherSlot.current).toBe(agents[0]) - expect(mocks.setGlobalDispatcher).toHaveBeenCalledOnce() - expect(mocks.setGlobalDispatcher).toHaveBeenCalledWith(agents[0]) - - // Reject path: the second event aborts at the post-import latch re-check — - // it never reaches the previous-dispatcher capture (one getGlobalDispatcher - // call: the first capture; dispose below adds the restore check), and its - // agent is closed without ever entering the dispatcher slot. - expect(mocks.getGlobalDispatcher).toHaveBeenCalledTimes(1) - expect(agents[1].close).toHaveBeenCalledOnce() - // The aborted call registers no resource, so the first install's disposable - // remains the only teardown path for the slot. - expect(context.subscriptions).toHaveLength(3) - - returned.dispose() - - // The owning disposable restores the dispatcher it captured (the default), - // not the closed agent a double install would have recorded. - expect(agents[0].close).toHaveBeenCalledOnce() - expect(mocks.dispatcherSlot.current).toBe(mocks.defaultDispatcher) - expect(mocks.setGlobalDispatcher).toHaveBeenLastCalledWith(mocks.defaultDispatcher) - } finally { - // Re-register a synchronous factory with the same spies and drop the cached - // module: tests running after this one then resolve undici exactly as they - // do through the file-level mock (unmocking instead would expose the real - // package to those tests, and the pending-import factory above is now - // permanently bypassed). - vi.doMock("undici", () => ({ - ProxyAgent: mocks.proxyAgent, - setGlobalDispatcher: mocks.setGlobalDispatcher, - getGlobalDispatcher: mocks.getGlobalDispatcher, - fetch: mocks.undiciFetch, - })) - vi.resetModules() - globalThis.fetch = fetchBefore - } - }) - }) - - // The configuration-change listener re-runs the configure* helpers when the debug proxy - // is toggled on mid-session. Both helpers are latched (bootstrap and dispatcher are - // one-shot), so after a successful activation the listener path re-enters them and - // returns through their already-configured branches; without this test those call - // sites would never execute. Runs on a reset module instance so the shared latches - // start untripped, as in the disposal tests. - it("re-runs both configure paths without re-installing when the proxy is toggled on again", async () => { - vi.resetModules() - const freshModule = await import("../networkProxy") - const freshVscode = await import("vscode") - vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( - makeWorkspaceConfiguration({ - "debugProxy.enabled": true, - "debugProxy.serverUrl": "http://localhost:8080", - "debugProxy.tlsInsecure": false, - }), - ) - let configListener: ((event: { affectsConfiguration: (section: string) => boolean }) => void) | undefined - vi.mocked(freshVscode.workspace.onDidChangeConfiguration).mockImplementation((listener) => { - configListener = listener as typeof configListener - return { dispose: vi.fn() } - }) - const context = createMockContext(vscode.ExtensionMode.Development) - - await freshModule.initializeNetworkProxy(context, mockOutputChannel) - vi.clearAllMocks() - - expect(configListener).toBeTypeOf("function") - configListener?.({ affectsConfiguration: () => true }) - // The re-entrant calls resolve on their own microtasks. - await new Promise((resolve) => setTimeout(resolve, 0)) - - // Nothing is installed twice: bootstrap and the dispatcher swap stay one-shot, and - // the log records both "already configured" branches rather than a failure. - expect(mocks.bootstrap).not.toHaveBeenCalled() - expect(mocks.setGlobalDispatcher).not.toHaveBeenCalled() - const logged = vi.mocked(mockOutputChannel.appendLine).mock.calls.flat().join("\n") - expect(logged).toContain("Proxy already initialized, updating env vars only") - expect(logged).toContain("undici global dispatcher already configured") - }) - - // A second initialize on the same module instance reaches configureUndiciProxy through - // the already-configured latch, which returns no resource: the aggregate then collects - // only the listener and the override cleanup, and disposing it must not touch the agent - // owned by the first activation. - it("collects no agent resource on a re-initialization while the dispatcher latch is tripped", async () => { - vi.resetModules() - vi.clearAllMocks() - const fetchBefore = globalThis.fetch - globalThis.fetch = () => Promise.reject(new Error("sentinel fetch")) - try { - const freshModule = await import("../networkProxy") - const freshVscode = await import("vscode") - vi.mocked(freshVscode.workspace.getConfiguration).mockReturnValue( - makeWorkspaceConfiguration({ - "debugProxy.enabled": true, - "debugProxy.serverUrl": "http://localhost:8080", - "debugProxy.tlsInsecure": false, - }), - ) - - const context = createMockContext(vscode.ExtensionMode.Development) - const first = await freshModule.initializeNetworkProxy(context, mockOutputChannel) - expect(context.subscriptions).toHaveLength(3) - - const secondContext = createMockContext(vscode.ExtensionMode.Development) - const second = await freshModule.initializeNetworkProxy(secondContext, mockOutputChannel) - - // configureUndiciProxy returned undefined for the second run, so only the listener - // and the override cleanup are registered there. - expect(secondContext.subscriptions).toHaveLength(2) - - second.dispose() - // The first activation still owns the agent; the second teardown must not close it. - expect(mocks.proxyAgentClose).not.toHaveBeenCalled() - - first.dispose() - expect(mocks.proxyAgentClose).toHaveBeenCalledOnce() - } finally { - globalThis.fetch = fetchBefore - } - }) }) describe("getProxyConfig", () => { diff --git a/src/utils/networkProxy.ts b/src/utils/networkProxy.ts index e7a307b4b8..e086908844 100644 --- a/src/utils/networkProxy.ts +++ b/src/utils/networkProxy.ts @@ -72,31 +72,6 @@ function restoreGlobalFetchPatch(): void { originalFetch = undefined } -/** - * Teardown-safe logging. A disposed VS Code output channel throws from appendLine(), and - * teardown paths run exactly when that disposal may already have happened; a throw out of one - * of these log calls would skip the cleanup it flanks or reject a promise no caller handles. - * Losing a late log line is always preferable to losing the close it reports. - */ -function logTeardown(message: string): void { - try { - log(message) - } catch { - // Deliberately empty: the log sink is gone, and every caller here must keep tearing down. - } -} - -/** - * Fire-and-log variant of ProxyAgent.close(): Disposable.dispose() is synchronous while - * close() is async, and neither a teardown sequence nor the late-import abort may block on - * (or reject into) its caller. - */ -function closeProxyAgentBestEffort(proxyAgent: { close(): Promise }): void { - void proxyAgent.close().catch((error) => { - logTeardown(`Failed to close undici proxy agent: ${error instanceof Error ? error.message : String(error)}`) - }) -} - function restoreTlsVerificationOverride(): void { if (!tlsVerificationOverridden) { return @@ -137,28 +112,20 @@ function applyTlsVerificationOverride(config: ProxyConfig): void { * Initialize the network proxy module with the extension context. * Must be called early in extension activation before any network requests. * - * Each resource created here is also registered on `context.subscriptions` for the normal - * deactivate path. The returned disposable covers the same resources so a failed activation - * can tear them down itself: `deactivate()` is not guaranteed to run after activation fails, - * and a retained configuration listener would let a `debugProxy.*` settings toggle re-apply - * proxy configuration (including the TLS verification override) inside a dead extension. - * * @param context The VS Code extension context * @param channel Optional output channel for logging - * @returns A disposable releasing everything initialized here; a no-op outside debug mode, where nothing is created. */ export async function initializeNetworkProxy( context: vscode.ExtensionContext, channel?: vscode.OutputChannel, -): Promise { +): Promise { extensionContext = context // extensionMode is immutable for the process lifetime - exit early if not in debug mode. // This avoids any overhead (listeners, logging, etc.) in production. const isDebugMode = context.extensionMode === vscode.ExtensionMode.Development if (!isDebugMode) { - // Nothing was acquired in production, so there is nothing for the caller to tear down. - return { dispose: () => {} } + return } outputChannel = channel ?? null @@ -172,83 +139,49 @@ export async function initializeNetworkProxy( `Proxy config: enabled=${config.enabled}, serverUrl=${redactProxyUrl(config.serverUrl)}, tlsInsecure=${config.tlsInsecure}`, ) - // Collect every resource created here so the returned disposable can release them when a - // later activation step fails; the same objects also go to context.subscriptions for the - // deactivate path, and both restores below are idempotent, so double disposal is safe. - const resources: vscode.Disposable[] = [] - - // The two dynamic imports in the configure* helpers below are suspension points: a teardown - // can run while one is pending, and its continuation would write process-global state - // (dispatcher, fetch patch, global-agent bootstrap) after disposal. Both disposal paths set - // the flag - the aggregate dispose at the end of this function, and overrideCleanup, which - // VS Code also disposes item-by-item through context.subscriptions - and each continuation - // checks it before installing. - let disposed = false - const isDisposed = () => disposed - // Listen for configuration changes to allow toggling proxy during a debug session. // Guard for test environments where onDidChangeConfiguration may not be mocked. if (typeof vscode.workspace.onDidChangeConfiguration === "function") { - const configListener = vscode.workspace.onDidChangeConfiguration((e) => { - if ( - e.affectsConfiguration(`${Package.name}.debugProxy.enabled`) || - e.affectsConfiguration(`${Package.name}.debugProxy.serverUrl`) || - e.affectsConfiguration(`${Package.name}.debugProxy.tlsInsecure`) - ) { - const newConfig = getProxyConfig() - - if (newConfig.enabled) { - applyTlsVerificationOverride(newConfig) - configureGlobalProxy(newConfig, isDisposed) - // The aggregate owns whatever this enables: without registering the created - // agent resource here, a proxy toggled on mid-session would survive every - // teardown path the returned disposable covers. - configureUndiciProxy(newConfig, context, isDisposed, (resource) => resources.push(resource)) - } else { - // Proxy disabled mid-session: global-agent can't be un-bootstrapped, and the - // dispatcher stays installed until the resources below are disposed (re-pointing - // live traffic mid-session is not safe). Any global fetch patch *can* be - // restored immediately. - restoreGlobalFetchPatch() - restoreTlsVerificationOverride() - log("Debug proxy disabled. Restart VS Code to fully disable proxy routing.") + context.subscriptions.push( + vscode.workspace.onDidChangeConfiguration((e) => { + if ( + e.affectsConfiguration(`${Package.name}.debugProxy.enabled`) || + e.affectsConfiguration(`${Package.name}.debugProxy.serverUrl`) || + e.affectsConfiguration(`${Package.name}.debugProxy.tlsInsecure`) + ) { + const newConfig = getProxyConfig() + + if (newConfig.enabled) { + applyTlsVerificationOverride(newConfig) + configureGlobalProxy(newConfig) + configureUndiciProxy(newConfig) + } else { + // Proxy disabled - but we can't easily un-bootstrap global-agent or reset undici dispatcher safely. + // We *can* restore any global fetch patch immediately. + restoreGlobalFetchPatch() + restoreTlsVerificationOverride() + log("Debug proxy disabled. Restart VS Code to fully disable proxy routing.") + } } - } - }) - context.subscriptions.push(configListener) - resources.push(configListener) + }), + ) } // Ensure we restore any overrides when the extension unloads. - const overrideCleanup: vscode.Disposable = { + context.subscriptions.push({ dispose: () => { - // Latching disposal here covers the path where VS Code disposes context.subscriptions - // item-by-item; the aggregate dispose below sets the same flag itself. - disposed = true restoreGlobalFetchPatch() restoreTlsVerificationOverride() }, - } - context.subscriptions.push(overrideCleanup) - resources.push(overrideCleanup) + }) if (config.enabled) { applyTlsVerificationOverride(config) - await configureGlobalProxy(config, isDisposed) - await configureUndiciProxy(config, context, isDisposed, (resource) => resources.push(resource)) + await configureGlobalProxy(config) + await configureUndiciProxy(config) } else { log(`Debug proxy not enabled.`) } - - return { - dispose: () => { - // Stryker disable next-line BooleanLiteral: the override-cleanup resource disposed by the same loop latches the identical flag, so no interleaving distinguishes this assignment from its mutant. - disposed = true - for (const resource of resources) { - resource.dispose() - } - }, - } } /** @@ -286,11 +219,8 @@ export function getProxyConfig(): ProxyConfig { /** * Configure global-agent to route all HTTP/HTTPS traffic through the proxy. - * - * @param isDisposed Teardown latch checked after the dynamic import below; bootstrap is - * skipped when the extension was disposed while the import was pending. */ -async function configureGlobalProxy(config: ProxyConfig, isDisposed: () => boolean): Promise { +async function configureGlobalProxy(config: ProxyConfig): Promise { if (proxyInitialized) { // global-agent can only be bootstrapped once // Update environment variables for any new connections @@ -314,13 +244,6 @@ async function configureGlobalProxy(config: ProxyConfig, isDisposed: () => boole return } - // A teardown may have run while the import above was pending; bootstrapping global-agent - // then would intercept this process's HTTP traffic for a dead extension. - if (isDisposed()) { - logTeardown("global-agent import completed after disposal; skipping bootstrap") - return - } - // Bootstrap global-agent to intercept all HTTP/HTTPS requests log(`Calling global-agent bootstrap()...`) try { @@ -338,23 +261,8 @@ async function configureGlobalProxy(config: ProxyConfig, isDisposed: () => boole /** * Configure undici's global dispatcher so Node's built-in `fetch()` and any undici-based * clients route through the proxy. - * - * The dispatcher active before the install is captured and restored when the created resource - * is disposed — but only while the global slot still holds the agent installed here; a slot a - * third party has since replaced belongs to that installer, not to this teardown. - * - * @param context The extension context whose subscriptions register the created resource. - * @param isDisposed Teardown latch checked after the dynamic import below; a late import - * completion closes the freshly built agent instead of installing it. - * @param registerResource Called with the created resource synchronously after the last await, - * so a teardown that starts while this function is in flight cannot miss it. */ -async function configureUndiciProxy( - config: ProxyConfig, - context: vscode.ExtensionContext, - isDisposed: () => boolean, - registerResource: (resource: vscode.Disposable) => void, -): Promise { +async function configureUndiciProxy(config: ProxyConfig): Promise { if (!config.enabled || !config.serverUrl) { return } @@ -368,7 +276,6 @@ async function configureUndiciProxy( const { ProxyAgent, setGlobalDispatcher, - getGlobalDispatcher, fetch: undiciFetch, } = (await import("undici")) as typeof import("undici") @@ -382,28 +289,6 @@ async function configureUndiciProxy( ? ({ rejectUnauthorized: false } satisfies import("tls").ConnectionOptions) // lgtm[js/disabling-certificate-validation] : undefined, }) - - // A teardown may have run while the import above was pending. Installing the dispatcher - // or patching fetch then would leave process-global routing active for a dead extension, - // so the freshly built agent is closed and nothing is installed. - if (isDisposed()) { - logTeardown("undici import completed after disposal; closing the late proxy agent without installing it") - closeProxyAgentBestEffort(proxyAgent) - return - } - - // A concurrent call can pass the already-configured check above while this import is - // pending. Installing after another call has set the dispatcher would capture that - // agent as the previous dispatcher, and its teardown would then restore a closed - // agent globally; the first install owns the slot, so this agent is closed instead. - if (undiciProxyInitialized) { - closeProxyAgentBestEffort(proxyAgent) - return - } - - // undici exposes a getter for its global dispatcher slot, so the dispatcher that - // predates this install can be captured here and put back by the resource below. - const previousDispatcher = getGlobalDispatcher() setGlobalDispatcher(proxyAgent) undiciProxyInitialized = true log(`undici global dispatcher configured for proxy: ${redactProxyUrl(config.serverUrl)}`) @@ -421,33 +306,15 @@ async function configureUndiciProxy( globalThis.fetch = undiciFetch as unknown as typeof fetch fetchPatched = true log(`globalThis.fetch patched to undici.fetch (debug proxy mode)`) - } - // The agent owns sockets, so teardown must close it; restoring the fetch patch is owned - // by the override-cleanup resource, which every disposal path also disposes. The - // dispatcher is restored before the close so traffic started after teardown cannot land - // on the closed agent, and only while the slot still holds this agent — a dispatcher - // installed by someone else afterwards is theirs to manage. Disposal reaches this - // resource from two owners (context.subscriptions and the aggregate returned by - // initializeNetworkProxy), so the once-guard keeps a double dispose to a single close. - let agentClosed = false - const undiciResource: vscode.Disposable = { - dispose: () => { - if (!agentClosed) { - agentClosed = true - if (getGlobalDispatcher() === proxyAgent) { - setGlobalDispatcher(previousDispatcher) - } - closeProxyAgentBestEffort(proxyAgent) - } - }, + if (extensionContext) { + extensionContext.subscriptions.push({ + dispose: () => restoreGlobalFetchPatch(), + }) + } } - registerResource(undiciResource) - context.subscriptions.push(undiciResource) } catch (error) { - logTeardown( - `Failed to configure undici proxy dispatcher: ${error instanceof Error ? error.message : String(error)}`, - ) + log(`Failed to configure undici proxy dispatcher: ${error instanceof Error ? error.message : String(error)}`) } } /** From 5f549d687729e5c4a58432a5718a497b465c52d8 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 17 Nov 2026 10:38:20 +0100 Subject: [PATCH 27/52] test: pin round-trip scope persistence of seeded command lists Add four round-trip tests to webviewMessageHandler.spec.ts covering how a saved command list is split between the global and workspace layers. The tests pin the behavior raised in review at src/core/webview/webviewMessageHandler.ts:1006. When a workspace layer contains a copy of a seeded default such as "git log", an unchanged save writes that entry only to the workspace layer, not back to the global layer. The default stays enforced regardless, because the effective allow-list is the union of both layers, and a first save materializes the seeded defaults in the global layer anyway. The new tests cover a dialog addition, an explicitly emptied list, a workspace-only edit that materializes the defaults globally, and a workspace duplicate of a default whose removal from the global write still leaves the composed union enforcing it. No production code changes. --- .../__tests__/webviewMessageHandler.spec.ts | 227 ++++++++++++++++++ 1 file changed, 227 insertions(+) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index dd634e5471..49328b1fec 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -82,7 +82,9 @@ import * as vsCodeLmProvider from "../../../api/providers/vscode-lm" import * as copilotProvider from "../../../api/providers/github-copilot" import { Package } from "../../../shared/package" +import { readCommandListScopes } from "../../auto-approval/commandScope" import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" +import { seedCommandList } from "../../../utils/seedAllowedCommands" import { webviewMessageHandler } from "../webviewMessageHandler" import { registerCopilotModelBroadcast } from "../../../services/language-models/copilotModelBroadcast" import type { ClineProvider } from "../ClineProvider" @@ -3887,6 +3889,231 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) }) + + // Post-save probe for the activation seed: `seedCommandList` only skips a + // key whose global state is set, so the saved copy decides whether the + // declared package default can ever be re-granted into that key. + function mockSeededGlobalState(initial: Record) { + const store = new Map(Object.entries(initial)) + + // Structurally complete Memento double (keys/get/update), so the seed + // call site needs no type assertion. + return { + keys: vi.fn((): readonly string[] => [...store.keys()]), + get: vi.fn().mockImplementation((key: string) => store.get(key)), + update: vi.fn().mockImplementation(async (key: string, value: unknown) => { + store.set(key, value) + }), + } + } + + // The fresh-install configuration the seed would act on: the declared + // default with no layer value anywhere, the shape that re-seeds the + // defaults whenever the guard above does not hold. + function mockSeedConfiguration(defaultValue: string[]) { + const config = makeWorkspaceConfiguration() + config.inspect = vi.fn().mockReturnValue({ defaultValue }) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + } + + it("round-trips a dialog addition through the global write and keeps the activation seed blocked", async () => { + // A fresh install holds the defaults only in the extension-state copy; + // an add must rewrite the full list plus the addition into the global + // layer in dialog order, because those seeded entries have no other + // home that survives the save. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, + ) + const { update } = mockCommandConfiguration({}, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git log", "git diff", "git show", "aws"] }, + commandListBaseline: { + allowedCommands: ["git log", "git diff", "git show"], + workspaceCommandListsEnabled: true, + }, + }) + + // Exact array: the seeded defaults keep their state-copy order and the + // brand-new entry lands after them. + expect(update).toHaveBeenCalledWith( + "allowedCommands", + ["git log", "git diff", "git show", "aws"], + vscode.ConfigurationTarget.Global, + ) + expect(update).not.toHaveBeenCalledWith( + "allowedCommands", + ["git log", "git diff", "git show"], + vscode.ConfigurationTarget.Global, + ) + // The snapshot found no workspace layer, so the save never creates one. + expect(update).not.toHaveBeenCalledWith( + "allowedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // A dialog addition is not a settings-file change: no disclosure. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + // The state mirror holds exactly the global layer the save wrote. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ + "git log", + "git diff", + "git show", + "aws", + ]) + expect(update).toHaveBeenCalledTimes(1) + + // A second activation cannot re-grant the defaults: the saved state copy + // is truthy, so the seed guard returns before reading the configuration. + mockSeedConfiguration(["git log", "git diff", "git show"]) + const globalState = mockSeededGlobalState({ + allowedCommands: ["git log", "git diff", "git show", "aws"], + }) + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toEqual(["git log", "git diff", "git show", "aws"]) + }) + + it("persists an explicitly emptied list and keeps the activation seed blocked for it", async () => { + // Clearing every entry must clear the global layer and the state copy, + // and the emptied `[]` must still count as existing state so a later + // activation never re-seeds the default list the user deleted. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, + ) + const { update } = mockCommandConfiguration({}, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: [] }, + commandListBaseline: { + allowedCommands: ["git log", "git diff", "git show"], + workspaceCommandListsEnabled: true, + }, + }) + + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith( + "allowedCommands", + ["git log", "git diff", "git show"], + vscode.ConfigurationTarget.Global, + ) + // The snapshot found no workspace layer, so the save never creates one. + expect(update).not.toHaveBeenCalledWith( + "allowedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", []) + expect(update).toHaveBeenCalledTimes(1) + + // The `[]` state copy is truthy, so the seed guard treats the emptied + // list as existing state even against a configuration that still + // reports the declared default. + mockSeedConfiguration(["git log", "git diff", "git show"]) + const globalState = mockSeededGlobalState({ allowedCommands: [] }) + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toEqual([]) + }) + + it("materializes the seeded defaults in the global layer when the user edited only workspace entries", async () => { + // Current behavior for a workspace-only edit: the user deleted the + // workspace entry "npm test" and touched nothing on the global side, yet + // the global write still materializes the activation-seeded defaults, + // because with the configuration global layer absent the state copy is + // the only home those entries have. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, + ) + const { update } = mockCommandConfiguration( + { workspaceValue: ["npm test", "docker"] }, + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git log", "git diff", "git show", "docker"] }, + commandListBaseline: { + allowedCommands: ["git log", "git diff", "git show", "npm test", "docker"], + workspaceCommandListsEnabled: true, + }, + }) + + // The untouched global side is still written back verbatim. + expect(update).toHaveBeenCalledWith( + "allowedCommands", + ["git log", "git diff", "git show"], + vscode.ConfigurationTarget.Global, + ) + expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + // The kept workspace entry stays at the workspace scope and the deleted + // entry clears it there, never leaking into the global layer. + expect(update).toHaveBeenCalledWith("allowedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ + "git log", + "git diff", + "git show", + ]) + expect(update).toHaveBeenCalledTimes(2) + }) + + it("drops a workspace-duplicate default from the global write while the composed union still enforces it", async () => { + // Current behavior for a seeded default the workspace layer also holds: + // an unchanged save keeps "git log" in the workspace layer only — the + // global write drops the duplicate — and enforcement is unchanged + // because the composed reader unions both layers. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, + ) + const { update } = mockCommandConfiguration({ workspaceValue: ["git log"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git log", "git diff", "git show"] }, + commandListBaseline: { + allowedCommands: ["git log", "git diff", "git show"], + workspaceCommandListsEnabled: true, + }, + }) + + // Exact array: the duplicate is dropped and the survivors keep their + // relative order. + expect(update).toHaveBeenCalledWith( + "allowedCommands", + ["git diff", "git show"], + vscode.ConfigurationTarget.Global, + ) + expect(update).not.toHaveBeenCalledWith( + "allowedCommands", + ["git log", "git diff", "git show"], + vscode.ConfigurationTarget.Global, + ) + expect(update).toHaveBeenCalledWith("allowedCommands", ["git log"], vscode.ConfigurationTarget.Workspace) + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ + "git diff", + "git show", + ]) + expect(update).toHaveBeenCalledTimes(2) + + // The entry the global write dropped is still enforced through the + // workspace layer: the merged set the enforcement path composes covers + // every command either layer holds. + const afterSaveScopes = readCommandListScopes("allowedCommands", ["git diff", "git show"], { + workspaceValue: ["git log"], + }) + expect(afterSaveScopes.merged).toEqual(["git diff", "git show", "git log"]) + }) }) describe("webviewMessageHandler - terminalProfile", () => { From 75d5c2ab1120351ae21b02688aa4d1c9b111c42f Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 17 Nov 2026 16:13:50 +0100 Subject: [PATCH 28/52] fix: wait for the host's answer before releasing buffered command-list edits A save that edited only the command lists carried no save-request id: asking the host for an answer was reserved for saves that changed a display setting. Submitting a list-only save released the buffered edits and the unsaved flag at once, so a rejected write left nothing behind - the state refresh that followed folded the stored list back into the dialog, and a failed list-only save was indistinguishable from a saved one. A save now requests a settingsSaveResult whenever it carries a watched write: a display-setting change or an edited command list. The edited lists hold the incoming state back - and with it the unsaved flag - until the answer settles: a confirmed save releases the hold, a rejected one keeps the edit on screen with Save re-enabled, and the answer timeout now covers list-only saves too. A save that carries neither still asks for no answer and clears the hold at submit, as before. The unsaved-changes tests replace the pin that a list-only save requests no answer. One now proves the scenario raised in review - the host refreshes with the written entry absent, then reports failure - and shows the dialog keeping the buffered edit with the form still dirty. Its counterpart proves a confirmed list-only save releases the hold exactly once and lets a later host update fold in without re-dirtying. --- .../src/components/settings/SettingsView.tsx | 21 +++-- .../SettingsView.unsaved-changes.spec.tsx | 79 +++++++++++++++---- 2 files changed, 77 insertions(+), 23 deletions(-) diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 13e68c8d1a..68879d6474 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -91,9 +91,10 @@ import { useSearchIndexRegistry, SearchIndexProvider } from "./useSettingsSearch import { nextSaveRequestId } from "./saveRequestId" /** - * How long the form waits for the host to answer a save that changes a time or date setting. The host always answers - * (success or failure), but a write that never settles would otherwise leave Save disabled until the webview reloads. - * After this the save is treated as failed: the edits stay unsaved and Save works again. + * How long the form waits for the host to answer a save whose writes it watches: one that changes a time or date + * setting, or one that edits a command list. The host always answers (success or failure), but a write that never + * settles would otherwise leave Save disabled until the webview reloads. After this the save is treated as failed: the + * edits stay unsaved and Save works again. */ export const SAVE_ANSWER_TIMEOUT_MS = 20_000 @@ -509,7 +510,8 @@ const SettingsView = forwardRef(({ onDone, t const isSettingValid = !errorMessage // The time and date values are written one at a time on the host, and a write can fail: a save that changes one of - // them waits for the host's answer. Every other save behaves as it always did. + // them waits for the host's answer, just as a save that edits a command list does. A save that changes neither + // display nor command lists asks for no answer, and behaves as it always did. const displayChanged = (cachedState.timeFormat ?? "auto") !== (extensionState.timeFormat ?? "auto") || (cachedState.dateFormat ?? "auto") !== (extensionState.dateFormat ?? "auto") || @@ -521,7 +523,11 @@ const SettingsView = forwardRef(({ onDone, t lastDisplayedCommandSnapshot.current, ) as [string[], string[], boolean] - const saveId = displayChanged ? nextSaveRequestId() : undefined + // The host reports a rejected command-list write in the same answer it gives a failed display-setting + // write, so a save carrying either waits for it. Reporting nothing for a list-only save would leave + // the dialog unable to tell a stored list from a rejected one, and it would show the rejected edit as + // saved. + const saveId = displayChanged || commandListsTouched.current ? nextSaveRequestId() : undefined if (saveId) { sentState.current = cachedState submittedListSave.current = { @@ -643,8 +649,9 @@ const SettingsView = forwardRef(({ onDone, t // edited list's entry from whether that list's own write landed. The lists' ownership of the buffer // does not move at submit. A save releases that hold - and with it the unsaved flag - only once the // refresh shows every submitted write landed: releasing earlier would let the state refresh that - // follows a rejected list write overwrite the edit the user is still looking at. A save the host never - // answers has no result to wait for, so it clears the hold at submit. + // follows a rejected list write overwrite the edit the user is still looking at. A save that carries + // neither a watched display setting nor an edited list asks for no answer, so it clears the hold at + // submit. if (!saveId) { commandListsTouched.current = false setChangeDetected(false) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 507569a380..7fe1e8494f 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -1058,14 +1058,12 @@ describe("SettingsView - Unsaved Changes Detection", () => { ) }) - it("sends a list-only save with no answer id and releases it at submit", async () => { - // A save that changes only the command lists carries no request id - the answer path needs a - // display-setting change - so the ack-driven failure retention the neighboring tests pin is - // unreachable for it. What the current code can prove for a no-requestId save: the hold and the - // unsaved flag release at submit, and the following state post is classified against the submitted - // lists - showing the submitted entry (write landed) leaves the dialog clean, while a refresh - // without it (a rejected write is indistinguishable from an external edit at this point) folds - // into the dialog without re-dirtying it. + it("requests an answer for a list-only save and keeps the buffered edit when the host reports failure", async () => { + // A rejected command-list write reaches the dialog through the same answer a failed display-setting + // write does: a save that edited a list carries a request id even when no display setting changed, so + // the answer - not the submit - decides whether the edit was stored. Releasing the hold at submit + // would let the post-failure refresh overwrite the edit the user is looking at, showing a rejected + // write as saved. vi.mocked(AutoApproveSettings).mockImplementation( ({ setCachedStateField, deniedCommands }: React.ComponentProps) => (
@@ -1087,21 +1085,70 @@ describe("SettingsView - Unsaved Changes Detection", () => { fireEvent.click(screen.getByTestId("save-button")) - // The list-only save posted the edit and asked for no answer. + // The list-only save posted the edit and asked for an answer. expect(updateSettingsPosts()).toHaveLength(1) - expect(lastSaveRequestId(postMessage)).toBeUndefined() - // With no answer to wait for, the hold releases at submit and the flag goes clean. - expect(screen.getByTestId("save-button")).toBeDisabled() + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + expect(screen.getByTestId("save-button")).toBeDisabled() // waiting for the host's answer - // The write did not land: the refresh carries the original list. The submitted entry is absent - // from it, so the merge treats the post as an external change over an already-committed dialog - // and folds it in - the edit is gone and the flag stays off. + // The host refreshes with the write unlanded - the submitted entry is absent - then reports failure. ;(useExtensionState as ReturnType).mockReturnValue({ ...defaultExtensionState, deniedCommands: [], }) view.rerender() - await waitFor(() => expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify([]))) + answerSave(saveId, { success: false, error: "storage unavailable" }) + + // The failure keeps the edit on screen - still holding the refresh back - and leaves the form dirty. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["git status"])) + }) + + it("clears the unsaved flag for a list-only save the host confirms, releasing the lists to updates", async () => { + // The success counterpart: the refresh shows the submitted list, so the settle releases the hold + // and the unsaved flag exactly once, and a later external change to the now-committed list folds + // into the dialog without re-dirtying it. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("buffer-deny-edit")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The host writes the list before it answers, so the refresh carries the submitted entry. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["git status"], + }) + view.rerender() + answerSave(saveId, { success: true }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // The lists committed, so a later host update is no longer an in-flight edit being stomped. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + view.rerender() + await waitFor(() => + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["rm -rf"])), + ) expect(screen.getByTestId("save-button")).toBeDisabled() }) From d3d0411d97480724c2bade1b3adee829459b5d86 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 17 Nov 2026 17:01:17 +0100 Subject: [PATCH 29/52] test: cover combined command-list write and refresh failure on save A save whose command-list write fails reports the save as not stored, and a state refresh that fails afterward is caught and logged on its own. Each failure had a test of its own; the combination did not. This test makes both fail during the same save and pins that they stay independent: the refresh failure does not mask the write failure - the save result still reports the save as not stored, the write error is shown to the user, the refresh error is logged, and no setting reaches storage. --- .../__tests__/webviewMessageHandler.spec.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 49328b1fec..79ab26d0f5 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -5305,6 +5305,24 @@ describe("updateSettings with the display settings", () => { expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() }) + it("reports a failed save when a command-list write fails and the state refresh fails too", async () => { + // The refresh failure is caught on its own; this pins that it cannot mask the write failure in the ack. + const config = makeWorkspaceConfiguration({}) + config.inspect = vi.fn().mockReturnValue({}) + config.update = vi.fn().mockRejectedValue(new Error("disk on fire")) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + vi.mocked(mockClineProvider.postStateToWebview).mockRejectedValueOnce(new Error("webview gone")) + + await expect(saveAs({ deniedCommands: ["aws"] })).resolves.toBeUndefined() + + expect(results()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: disk on fire") + expect(mockClineProvider.log).toHaveBeenCalledWith( + "[updateSettings] Could not refresh the webview state: webview gone", + ) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + }) + it("still reports a stored save when a command-list write succeeds", async () => { // The accept-path counterpart: the failure flag must not stick for a // save whose command-list writes all succeeded. From 034c0eaea72e8a8b4d1b1827f99c531ff84788f7 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 19 Nov 2026 14:13:33 +0100 Subject: [PATCH 30/52] fix: keep imported command lists after a settings save Importing a settings file stored the command lists only in the extension's state. A later save of the command-list dialog deletes any displayed entry that no configuration layer holds, so that save removed the imported entries from the user settings file. The import now mirrors the imported allowed and denied lists into the global configuration layer, so the next save keeps them. If the mirror fails, the import still succeeds and logs a warning. The workspace command lists setting description now states that while the setting is off, denied commands stored in the repository also have no effect. The text changed in all 18 language files. Tests: new coverage for the import mirror and for the survival of an imported entry across an unrelated save. Two auto-approval tests cover a command chain where one part matches the allow list and another does not, and a workspace allow entry while the workspace setting is off. Comments added by this branch were shortened and simplified. --- packages/types/src/global-settings.ts | 16 +- packages/types/src/vscode-extension-host.ts | 27 +- src/__tests__/extension.spec.ts | 105 +++---- .../__tests__/commandScope.spec.ts | 52 ++++ .../auto-approval/__tests__/commands.spec.ts | 24 +- src/core/auto-approval/commandScope.ts | 240 ++++++---------- src/core/auto-approval/commands.ts | 18 +- src/core/auto-approval/index.ts | 70 ++--- .../config/__tests__/importExport.spec.ts | 142 ++++++++++ src/core/config/importExport.ts | 19 ++ src/core/task/Task.ts | 11 +- .../task/__tests__/ask-allowlist-cwd.spec.ts | 89 +++--- src/core/tools/ExecuteCommandTool.ts | 36 +-- .../__tests__/executeCommandTool.spec.ts | 79 ++---- src/core/webview/ClineProvider.ts | 30 +- .../webview/__tests__/ClineProvider.spec.ts | 58 ++-- .../__tests__/webviewMessageHandler.spec.ts | 128 ++++++--- src/core/webview/webviewMessageHandler.ts | 266 +++++++----------- src/extension.ts | 40 +-- src/package.nls.ca.json | 2 +- src/package.nls.de.json | 2 +- src/package.nls.es.json | 2 +- src/package.nls.fr.json | 2 +- src/package.nls.hi.json | 2 +- src/package.nls.id.json | 2 +- src/package.nls.it.json | 2 +- src/package.nls.ja.json | 2 +- src/package.nls.json | 2 +- src/package.nls.ko.json | 2 +- src/package.nls.nl.json | 2 +- src/package.nls.pl.json | 2 +- src/package.nls.pt-BR.json | 2 +- src/package.nls.ru.json | 2 +- src/package.nls.tr.json | 2 +- src/package.nls.vi.json | 2 +- src/package.nls.zh-CN.json | 2 +- src/package.nls.zh-TW.json | 2 +- src/shared/tools.ts | 9 +- .../__tests__/seedAllowedCommands.spec.ts | 118 +++----- src/utils/seedAllowedCommands.ts | 48 ++-- .../src/components/settings/SettingsView.tsx | 128 ++++----- .../SettingsView.change-detection.spec.tsx | 12 +- .../settings/__tests__/SettingsView.spec.tsx | 32 +-- .../SettingsView.unsaved-changes.spec.tsx | 176 +++++------- 44 files changed, 936 insertions(+), 1073 deletions(-) diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index 6e02507cd1..8b6e5f95c0 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -58,13 +58,9 @@ export const DEFAULT_DESTRUCTIVE_COMMAND_GUARD_ENABLED = false export const DEFAULT_TASK_TITLE_GENERATION_ENABLED = true /** - * Whether workspace-scoped command-list layers (`zoo-code.allowedCommands` / - * `zoo-code.deniedCommands` values set in workspace settings) participate in - * command auto-approval at all. Opt-in: while off, workspace-layer entries - * contribute nothing to enforcement or display. The manifest declares the key - * with `scope: "application"`, so only user settings can change it; this - * constant is the single default shared by every consumer reading the - * setting. + * Opt-in gate for workspace-scoped command lists. While off, those lists are + * inert. The manifest scope is "application", so only user settings change + * it. Every consumer shares this default. */ export const DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED = false @@ -195,10 +191,8 @@ export const globalSettingsSchema = z.object({ allowedCommands: z.array(z.string()).optional(), deniedCommands: z.array(z.string()).optional(), /** - * Gate for the workspace-scoped command-list layers. While false (the - * default), workspace-set `allowedCommands`/`deniedCommands` entries - * contribute nothing; when true they are composed under the global layer, - * which outranks them wherever it matches a command. + * Gate for the workspace command lists. While false, they are inert. When + * true, they apply only where no global entry matches a command. * @default false */ workspaceCommandListsEnabled: z.boolean().optional(), diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 6e31f17c67..4b4699b5ec 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -422,13 +422,10 @@ export type ExtensionState = Pick< cwd?: string // Current working directory /** - * The user-scope command lists as persisted in extension global state, - * before any workspace-scoped composition. Auto-approval composes the - * pair it enforces from these raw layers plus the folder the task runs - * in, because the merged `allowedCommands`/`deniedCommands` pair follows - * the window's first folder and would judge a task by another root's - * lists. Not user settings: runtime state, written by the provider's - * state bake, never by the settings dialog. + * User-scope command lists from extension global state, before workspace + * composition. Auto-approval enforces these raw layers plus the task's + * folder; the merged pair follows only the window's first folder. Runtime + * state, not user settings: the provider writes it, never the dialog. */ globalAllowedCommands?: string[] globalDeniedCommands?: string[] @@ -859,20 +856,18 @@ export interface WebviewMessage { } updatedSettings?: RooCodeSettings /** - * The command lists as the settings dialog last displayed them, sent alongside the - * save that rewrites them. The settings file can gain entries while the dialog is - * open, and without this baseline the save path cannot tell those additions apart - * from list entries the user deleted: both look like "in the file, absent from the - * submitted list". Senders that do not display the lists omit it. + * The lists as the dialog last displayed them, sent with the save that rewrites + * them. Without it the save cannot tell a file-side addition from a user + * deletion: both look like "in the file, absent from the submission". Senders + * that display no lists omit it. */ commandListBaseline?: { allowedCommands?: string[] deniedCommands?: string[] /** - * The workspace-command-lists gate as the dialog last displayed it. Flipping the - * gate between display and save hides workspace entries, so this travels with the - * baseline to let the save path classify an entry the baseline already showed as - * existing workspace knowledge rather than a brand-new promotion into the global layer. + * The gate as the dialog last displayed it. A gate flip between display and + * save hides workspace entries; this lets the save treat an already-shown + * entry as known workspace knowledge, not a new promotion to global. */ workspaceCommandListsEnabled?: boolean } diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 17e89f6cf5..1a40d409ad 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -555,24 +555,21 @@ describe("extension.ts", () => { } return key === "allowedCommands" ? [...(globalValue ?? []), ...(workspaceValue ?? [])] : undefined }), - // Key-scoped inspect: the deny seed must not read the allow scope's - // values through the same fixture object. + // Key-scoped inspect: the deny seed must not read allow-scope values. inspect: vi.fn().mockImplementation((key: string) => key === "deniedCommands" ? { key, defaultValue: [], globalValue: deniedGlobalValue } : { key, - // Real inspect() always reports the declared package default; - // including it here lets the workspace-override test prove the - // default stays unseeded beside an override, not just absent. + // The override test must show the package default stays + // unseeded, not merely absent. defaultValue: ["git log", "git diff", "git show"], globalValue, workspaceValue, }, ), update: vi.fn(), - // The double scripts key-scoped get() and per-scope inspect() - // shapes the shared helper cannot express without obscuring them. + // This double scripts shapes the shared helper cannot express. } as unknown as vscode.WorkspaceConfiguration) } @@ -585,16 +582,14 @@ describe("extension.ts", () => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn().mockReturnValue([]), inspect: vi.fn(), - // Restores the neutral default after the scope fixtures above; - // update is intentionally absent because no test runs after this. + // Restores the neutral default. `update` is absent: no test runs after this. } as unknown as vscode.WorkspaceConfiguration) }) test("seeds both command lists before initializing the terminal registry", async () => { - // Invariant: a seed rejection must fail activation before the terminal - // registry is initialized, so no initialized-but-half-activated state is - // reachable (the registry's listeners are released only via deactivate, - // which the host does not guarantee after a failed activation). + // A seed rejection must fail activation before the registry initializes: + // the host may skip deactivate(), and only it releases the registry's + // listeners. const order: string[] = [] const seedCommandList = vi.fn(async (_globalState: vscode.Memento, configKey: string): Promise => { order.push(`seed:${configKey}`) @@ -625,8 +620,7 @@ describe("extension.ts", () => { const { activate } = await import("../extension") await expect(activate(mockContext)).rejects.toThrow("seed state write failed") - // The seed rejection must reach the host unchanged, with the registry - // never initialized and no downstream activation (sidebar provider) reached. + // The seed rejection reaches the host unchanged; nothing downstream runs. expect(TerminalRegistry.initialize).not.toHaveBeenCalled() expect(ClineProvider).not.toHaveBeenCalled() } finally { @@ -635,19 +629,16 @@ describe("extension.ts", () => { }) test("shuts down the telemetry service before propagating a seed rejection", async () => { - // The telemetry client is created and registered before the seed point, - // so a rejected seed must shut it down on the failure path: without - // `deactivate()` after a failed activation, an unshut-down client keeps - // sending events against an extension the host treats as inactive. + // The seed runs after telemetry registers, and the host may skip + // `deactivate()` after a failed activation, so the failure path must shut + // telemetry down itself. vi.doMock("../utils/seedAllowedCommands", () => ({ seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), })) const teardownOrder: string[] = [] const { TelemetryService } = await import("@roo-code/telemetry") const shutdown = vi.mocked(TelemetryService.instance.shutdown) - // A never-settling shutdown: activation may only reject once the awaited - // teardown settles, pinning that the seed rejection never reaches the - // host ahead of it. + // Activation may reject only after the awaited teardown settles. let settleShutdown: () => void = () => {} shutdown.mockImplementation(() => { teardownOrder.push("telemetry-shutdown") @@ -663,11 +654,10 @@ describe("extension.ts", () => { rejected = true }) - // The awaited teardown step runs on the failure path, exactly once. + // The failure path runs the awaited teardown exactly once. await vi.waitFor(() => expect(teardownOrder).toEqual(["telemetry-shutdown"])) - // Still unrejected while the awaited shutdown is unsettled: the catch - // must not propagate the seed rejection before teardown completes. + // The catch must not propagate before teardown completes. expect(rejected).toBe(false) settleShutdown() @@ -679,11 +669,8 @@ describe("extension.ts", () => { }) test("logs a rejected telemetry shutdown without masking the seed rejection", async () => { - // The seed-failure catch awaits the shutdown inside its own try/catch, so a - // rejecting shutdown must be logged and the seed error must still reach the - // host as the activation failure. A regression that rethrows the shutdown - // error hides why activation aborted; one that swallows it silently loses - // the only record of the telemetry teardown failure. + // A rejecting shutdown must be logged, and the seed error must still + // reach the host as the activation failure. vi.doMock("../utils/seedAllowedCommands", () => ({ seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), })) @@ -701,8 +688,7 @@ describe("extension.ts", () => { await expect(activate(mockContext)).rejects.toThrow("seed state write failed") - // The shutdown failure surfaces through the appendLine idiom, with its - // error text, instead of replacing the seed rejection the host receives. + // The shutdown failure is logged, not swapped for the seed rejection. const channel = vi.mocked(vscode.window.createOutputChannel).mock.results.at(-1)?.value expect(channel?.appendLine).toHaveBeenCalledWith( "Failed to shut down telemetry service: shutdown drain failed", @@ -716,10 +702,9 @@ describe("extension.ts", () => { }) test("disposes the output channel last when seeding rejects activation", async () => { - // The output channel is the first resource `activate` acquires, and the - // host does not guarantee `deactivate()` after a failed activation, so - // the failure path must release it too — last, because every earlier - // teardown step logs its own failure through this channel. + // The host may skip `deactivate()` after a failed activation, so the + // failure path must dispose the channel itself — last, because earlier + // teardown steps log through it. vi.doMock("../utils/seedAllowedCommands", () => ({ seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), })) @@ -732,22 +717,18 @@ describe("extension.ts", () => { }) try { const vscode = await import("vscode") - // The factory double is a fixed object, so calling the mock now hands - // back the same channel `activate` will create; arming its dispose - // before activation lets the order assertion observe the step. + // Calling the fixed-object factory double now returns the same channel + // `activate` will create; arming dispose observes its disposal order. const channel = vi.mocked(vscode.window.createOutputChannel)("Test Output") channel.dispose = vi.fn(() => void teardownOrder.push("channel-disposed")) const { activate } = await import("../extension") await expect(activate(mockContext)).rejects.toThrow("seed state write failed") - // Strict reverse acquisition: the channel was acquired first, so it is - // disposed after the telemetry shutdown — every teardown log line was - // still writable when that step ran. + // Reverse acquisition order: channel first, so disposed last. expect(teardownOrder).toEqual(["telemetry-shutdown", "channel-disposed"]) expect(channel.dispose).toHaveBeenCalledExactlyOnceWith() - // Still registered for the normal deactivate path; the failure-path - // dispose must not have replaced the subscription push. + // The failure-path dispose must not drop the subscriptions entry. expect(mockContext.subscriptions).toContain(channel) } finally { shutdown.mockReset() @@ -756,18 +737,14 @@ describe("extension.ts", () => { }) test("clears the persistence trace sink before disposing the output channel when seeding rejects", async () => { - // The persistence trace sink installed at activation start mirrors - // trace lines through the output channel, so the failure path must - // unregister it before the channel goes away: a later trace — such as - // `deactivate()`'s shutdown event — would otherwise write into a - // disposed channel. + // The trace sink logs through the output channel, so the failure path + // must clear it before disposing the channel. vi.doMock("../utils/seedAllowedCommands", () => ({ seedCommandList: vi.fn().mockRejectedValue(new Error("seed state write failed")), })) const teardownOrder: string[] = [] - // Only the teardown call is an order marker: installation passes the - // channel-logging sink, while clearing passes undefined — the setter's - // documented way to restore the default console sink. + // Clearing passes undefined (restore the default sink); that call marks + // the order assertion. const setPersistenceTraceSink = vi.fn((sink?: unknown) => { if (sink === undefined) { teardownOrder.push("trace-sink-cleared") @@ -785,22 +762,18 @@ describe("extension.ts", () => { }) try { const vscode = await import("vscode") - // The factory double is a fixed object, so calling the mock now hands - // back the same channel `activate` will create; arming its dispose - // before activation lets the order assertion observe the step. + // Calling the fixed-object factory double now returns the same channel + // `activate` will create; arming dispose observes its disposal order. const channel = vi.mocked(vscode.window.createOutputChannel)("Test Output") channel.dispose = vi.fn(() => void teardownOrder.push("channel-disposed")) const { activate } = await import("../extension") await expect(activate(mockContext)).rejects.toThrow("seed state write failed") - // Reverse acquisition order: the sink was installed after the channel - // it logs through but before the telemetry client, so it is cleared - // after the telemetry shutdown — and before the channel, which goes - // last. + // Reverse acquisition order: sink installed after the channel, so it + // clears after telemetry shutdown and before the channel. expect(teardownOrder).toEqual(["telemetry-shutdown", "trace-sink-cleared", "channel-disposed"]) - // Exactly the install call and the clear: the failure path neither - // skips the clear nor repeats it. + // The failure path clears the sink exactly once: install + clear. expect(setPersistenceTraceSink).toHaveBeenCalledTimes(2) expect(setPersistenceTraceSink).toHaveBeenNthCalledWith(1, expect.any(Function)) expect(setPersistenceTraceSink).toHaveBeenNthCalledWith(2, undefined) @@ -812,8 +785,7 @@ describe("extension.ts", () => { }) test("does not shut down telemetry when activation completes", async () => { - // Telemetry shutdown is failure-path only: a successfully activated - // extension owns the telemetry client until deactivate() runs. + // A successful activation owns the telemetry client until deactivate(). const { TelemetryService } = await import("@roo-code/telemetry") const { activate } = await import("../extension") @@ -824,10 +796,9 @@ describe("extension.ts", () => { test("does not seed global state from an enforced workspace-scoped override", async () => { const vscode = await import("vscode") - // The gate is on: an enforced workspace list replaces the default across - // scopes, so the seed must not re-grant the approvals it removed. (With - // the gate off the workspace layer is inert and the default is seeded — - // pinned in the seed module's own spec.) + // Gate on: the workspace list replaces the default, so the seed must not + // re-grant what it removed. (Gate-off seeding is pinned in the seed + // module's own spec.) setConfigScope(vscode, { workspaceValue: ["docker"], gate: true }) const { activate } = await import("../extension") diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 8388e7dbd9..58cce16a94 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -1017,6 +1017,58 @@ it("checkAutoApproval command: decides each sub-command of a chain by its own ma expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "docker ps", pattern: "*" } }) }) +it("checkAutoApproval command: denies a mixed allow/deny chain when one sub-command is unapproved under blanket", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + // The folder layers stay empty: no deny entry may decide the chain, so + // only the all-sub-commands rule can keep it unapproved. + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true }, + [folderB.fsPath]: { gate: true }, + }) + + // One sub-command approved, one not: only that rule denies the chain. An + // any-match rule would approve it on "git status". + const blanket = await checkAutoApproval({ + state: { ...layeredState(["git"]), alwaysDenyUnapprovedCommands: true }, + cwd: folderB.fsPath, + ask: "command", + text: "git status && docker ps", + }) + expect(blanket).toEqual({ decision: "deny", autoDeny: { kind: "not_allowlisted", command: "docker ps" } }) + + // Without blanket the same chain falls to the plain user prompt. + const prompt = await checkAutoApproval({ + state: layeredState(["git"]), + cwd: folderB.fsPath, + ask: "command", + text: "git status && docker ps", + }) + expect(prompt).toEqual({ decision: "ask" }) +}) + +it("checkAutoApproval command: ignores a workspace allow entry while the gate is off", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + // Gate off in both folders: the folder configuration is read, but its + // allow entry must never reach the effective lists. + mockFolderConfigurations({ + [folderA.fsPath]: { gate: false }, + [folderB.fsPath]: { gate: false, allow: ["echo"] }, + }) + + // The raw global layers keep the layered composition selected; it is + // empty, so the gated-off workspace entry is all that could allow "echo". + const result = await checkAutoApproval({ + state: layeredState([], []), + cwd: folderB.fsPath, + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + // The layered aggregator also owns the chain parsing, redirect sanitization, // substitution veto, and deny reporting of the flat matcher — the enforcement // path selects it whenever both raw global lists are present, regardless of diff --git a/src/core/auto-approval/__tests__/commands.spec.ts b/src/core/auto-approval/__tests__/commands.spec.ts index 87f6f44f5b..e3cf140b28 100644 --- a/src/core/auto-approval/__tests__/commands.spec.ts +++ b/src/core/auto-approval/__tests__/commands.spec.ts @@ -242,17 +242,13 @@ it("isShadowedByAnyEntry: compares case-insensitively, the way the matcher match }) it("isShadowedByAnyEntry: compares entries as stored, the way the matcher compares them", () => { - // The matcher trims commands, never entries, and shadowing mirrors that: - // both sides compare as stored. A trimmed comparison would let an inert - // padded entry erase a decidable one (and the reverse), deciding with a - // rule enforcement never applies. + // The matcher trims commands, never entries; shadowing must compare as stored. expect(isShadowedByAnyEntry(" git push ", ["git"])).toBe(false) expect(isShadowedByAnyEntry("git push", [" git "])).toBe(false) }) it("layered decisions: a padded global deny entry cannot erase a workspace deny entry", () => { - // The padded global entry is inert at enforcement, so it must not shadow - // the workspace entry the matcher does honor: the deny survives. + // The inert padded entry must not shadow the workspace deny the matcher honors. const scopes = (globalList: string[], workspaceList: string[]) => ({ global: globalList, workspace: workspaceList, @@ -264,9 +260,7 @@ it("layered decisions: a padded global deny entry cannot erase a workspace deny }) it("layered decisions: a padded global allow entry cannot erase a workspace allow entry", () => { - // Mirror of the deny side: the inert padded entry leaves the workspace - // allow entry effective, so the command is approved rather than downgraded - // to a prompt for a match no entry can produce. + // Mirror of the deny side: the inert padded entry leaves the workspace allow effective. const scopes = (globalList: string[], workspaceList: string[]) => ({ global: globalList, workspace: workspaceList, @@ -278,19 +272,15 @@ it("layered decisions: a padded global allow entry cannot erase a workspace allo }) it("isShadowedByAnyEntry: never treats an empty entry as covered", () => { - // Compared naively, an empty entry prefix-matches every command, so - // against an empty shadow entry it would report itself covered. The - // empty-entry guard keeps such an entry visible instead. Command-list - // layers sanitize blanks before shadowing, so this pins the function's - // contract directly. + // An empty entry prefix-matches everything; the guard keeps it from + // shadowing itself. Layers sanitize blanks first, so this pins the contract. expect(isShadowedByAnyEntry("", [""])).toBe(false) expect(isShadowedByAnyEntry("", ["git"])).toBe(false) }) it("layered decisions: reproduces the global-decides precedence through the scope-blind matcher", () => { - // Global deny "git" vs workspace allow "git push": the composed lists - // drop the shadowed allow entry, so the scope-blind matcher — never told - // about layers — returns the global layer's deny. + // Global deny "git" shadows workspace allow "git push" at composition, so the + // scope-blind matcher returns the deny. const scopes = (globalList: string[], workspaceList: string[]) => ({ global: globalList, workspace: workspaceList, diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index fa5736c5f5..8052e0005f 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -21,10 +21,8 @@ export interface CommandListScopes { } /** - * The workspace-scoped layers of a command-list key as reported by - * `WorkspaceConfiguration.inspect()`. Capturing it once lets a save derive - * the read layers, the write target, and a rollback value from a single - * configuration state instead of three independent reads that could disagree. + * The workspace layers of a command-list key, from `inspect()`. One capture + * gives a save consistent read layers, write target, and rollback value. */ export interface CommandListInspection { workspaceValue?: string[] @@ -32,17 +30,11 @@ export interface CommandListInspection { } /** - * The configuration object for every command-list read and write. Scoped to - * `folderResource` when the caller resolved one — per-task enforcement reads - * the folder that task runs in — and to the first workspace folder otherwise, - * the default the display, save, and seeding callers keep. Sharing one scoped - * access path keeps the two sides symmetric: `inspect()` can report - * `workspaceFolderValue`, and `ConfigurationTarget.WorkspaceFolder` updates - * are legal (the API contract throws for that target when the configuration - * is not scoped to a resource). With no folder open — or when a supplied - * resource resolved to nothing, see {@link commandListFolderForResource} — - * the configuration is unscoped or defaults to the first folder and reports - * only what that lookup can see. + * The configuration for every command-list read and write. Scoped to + * `folderResource` when given, else the first workspace folder. One shared + * scoped path keeps read and write symmetric: `ConfigurationTarget. + * WorkspaceFolder` updates are legal only when the configuration is scoped to + * a resource. */ export function commandListConfiguration(folderResource?: vscode.Uri): vscode.WorkspaceConfiguration { return vscode.workspace.getConfiguration( @@ -53,57 +45,38 @@ export function commandListConfiguration(folderResource?: vscode.Uri): vscode.Wo /** * Resolves the workspace folder a task's `cwd` lives in, so command-list - * enforcement scopes its configuration reads to the folder the task belongs - * to instead of the window's first folder. A child task inherits the working - * directory of the task it came from, so it resolves to the same folder - * without separate plumbing. + * enforcement reads that folder's configuration instead of the window's + * first folder. A child task inherits its parent's cwd and resolves the same + * way. * - * The command path hands this lookup a cwd the filesystem has already - * resolved to its real path, while the workspace registry holds each root as - * it was opened. Containment is therefore tested against every root's real - * path, so a root that is itself a symlink (or a Windows junction) keeps - * matching its own real directory. Comparing against the registered paths - * alone could not decide the folder: that comparison is lexical, so an outer - * root lexically contains a directory that physically belongs to a deeper - * root, and enforcing the outer root's lists there would let the deeper - * folder's deny entries be skipped. Among several matches the deepest root - * wins, mirroring how VS Code's own containment picks the innermost folder. - * A root whose real path cannot be resolved is compared by its registered - * path: the cwd is already canonical, so an unresolvable root can only - * narrow which folder layer applies, never widen what a folder's allow list - * may approve — and dropping the layer outright would silently change - * enforcement for a folder the user has open. + * The cwd arrives canonicalized, but the registry holds roots as opened, so + * containment is tested against each root's real path. A lexical-only compare + * would let an outer root claim a symlinked deeper root's directory and skip + * its deny entries. The deepest match wins, like VS Code's own containment. + * A root whose real path cannot be resolved falls back to its registered + * path: that can only narrow which layer applies, never widen approvals. * - * @param cwd - The task's working directory. An empty or absent cwd yields - * `undefined` and keeps the first-folder configuration. A nonempty cwd with - * no matching root also yields `undefined`. When both raw global lists are - * available, enforcement then excludes the workspace layer; otherwise, it - * uses the pre-composed state lists. - * @returns The containing folder's registry URI — never a canonicalized one, - * because folder-scoped configuration resolves against the registry — or - * `undefined` when cwd is empty, resolves to no root, or lookup fails. + * @param cwd - The task's working directory. Empty, absent, or unmatched + * yields `undefined` and keeps the first-folder configuration. + * @returns The containing folder's registry URI — never canonicalized, since + * folder-scoped configuration resolves against the registry. */ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefined { if (!cwd) { return undefined } - // A failed lookup returns undefined, like a cwd naming no root. - // With both raw global lists available, enforcement excludes the workspace - // layer; otherwise, it uses the pre-composed state lists. + // A failed lookup returns undefined, like a cwd naming no root; the caller + // then falls back to the pre-composed state lists. try { - // Comparing by root-path length makes the deepest match win: a root - // registered lexically above a symlinked root must not claim a command - // running in the deeper root's real directory. The separator guard - // keeps a sibling like `/root/other` from matching a root `/root`. + // Longest match wins so an outer root cannot claim a symlinked deeper + // root's directory. The separator guard keeps `/root/other` out of `/root`. let match: vscode.Uri | undefined let matchedLength = 0 for (const candidate of vscode.workspace.workspaceFolders ?? []) { const rootPath = realPathOrRegistered(candidate.uri.fsPath) // A filesystem root (`/`, `C:\`) already ends in a separator; - // appending a second one (`//`, `C:\\`) would leave no child path - // able to match the root, so the separator is added only where the - // root lacks one. + // doubling it would leave no child path able to match. const childPrefix = rootPath.endsWith(path.sep) ? rootPath : rootPath + path.sep if ((cwd === rootPath || cwd.startsWith(childPrefix)) && rootPath.length > matchedLength) { match = candidate.uri @@ -117,12 +90,9 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin } /** - * The path a workspace root is compared by: its real filesystem path, or — - * when that cannot be resolved (a relocated or deleted root) — the path the - * registry holds. Root-side lookups stay best-effort because the cwd being - * matched is already canonical; failing the comparison for one unresolvable - * root would drop that folder's command-list layer without widening any - * approval. + * The path a workspace root is compared by: its real path, or the registered + * path when the real one cannot be resolved. The cwd is already canonical, so + * a fallback here can only narrow matching, never widen approvals. */ function realPathOrRegistered(fsPath: string): string { try { @@ -136,21 +106,19 @@ function realPathOrRegistered(fsPath: string): string { * Reads an auto-approval command list from both configuration layers and * composes the list that should be enforced and displayed. * - * The workspace layer is read via `inspect()` rather than `get()` on purpose: - * `get()` returns the effective value, which already folds `globalValue` into - * the result. Unioning that with the global layer would double-count entries - * and make removals from global settings unable to shrink the enforced set. + * The workspace layer comes from `inspect()`, not `get()`: `get()` returns the + * effective value, which already folds in `globalValue`. Unioning that with + * the global layer would double-count and keep global removals from shrinking + * the enforced set. * * @param configKey - The extension configuration key to read. * @param globalList - The list persisted in extension global state. - * @param inspectionOverride - A snapshot captured by the caller before any - * write; when present it is used as-is and no fresh lookup happens, so a - * save's reads, target resolution, and rollback stay derived from one - * configuration state. Without it the lookup runs guarded (lenient): this is - * the enforcement/display path, where an unavailable workspace layer must - * degrade to empty rather than fail. - * @param folderResource - Workspace folder the configuration is scoped to; - * `undefined` keeps the first-folder default. + * @param inspectionOverride - A pre-write snapshot; when present it is used + * as-is so a save's reads, target, and rollback share one configuration + * state. Without it the lookup is guarded: enforcement degrades to an empty + * workspace layer rather than failing. + * @param folderResource - Workspace folder to scope to; `undefined` keeps the + * first-folder default. * @returns The per-layer lists and their deduplicated set union. */ export function readCommandListScopes( @@ -163,11 +131,8 @@ export function readCommandListScopes( let inspected: CommandListInspection | undefined = inspectionOverride if (inspected === undefined) { - // Only the configuration lookup itself is guarded: it can fail (for - // example before the workspace is ready), and an absent workspace layer - // must not break enforcement. The value reads below have no failure mode - // of their own, so the catch covers exactly the failure it exists to - // absorb. + // Only the lookup is guarded: it can fail before the workspace is ready. + // The reads below have no failure mode of their own. try { inspected = commandListConfiguration(folderResource).inspect(configKey) } catch { @@ -175,13 +140,10 @@ export function readCommandListScopes( } } - // The folder value wins over the workspace value, matching VS Code's - // folder-over-workspace precedence. An absent inspect result composes to - // an empty workspace layer: enforcement must not break. + // Folder value wins over workspace value, as in VS Code's precedence. const workspace = sanitizeCommandList(inspected?.workspaceFolderValue ?? inspected?.workspaceValue) - // Set union: an entry present in both layers collapses to one, so - // composition cannot change prefix-match outcomes. + // Set union: an entry in both layers collapses to one. const merged = [...new Set([...global, ...workspace])] return { global, workspace, merged } @@ -193,21 +155,14 @@ export interface CommandListWriteScopes { } /** - * Splits the merged command list the settings dialog saves back into the two - * configuration layers it was composed from, so saving the dialog cannot - * flatten workspace-scoped entries into the user's global settings. + * Splits the dialog's merged list back into the two layers it was composed + * from, so saving cannot flatten workspace entries into global settings. * - * Semantics: - * - An entry the user kept that exists in the workspace layer stays in the - * workspace layer. If the same entry also exists in the global layer it - * stays there too: dropping it from the global write would silently delete - * a user's global entry just because the current folder happens to define - * it as well. - * - An entry the user removed is dropped from every layer that contained it, - * which makes workspace-scoped entries deletable from the dialog. - * - A brand-new entry (in neither layer) lands in the global layer, matching - * the pre-existing behavior of routing dialog edits to - * `ConfigurationTarget.Global`. + * - A kept entry stays in every layer that contained it; dropping it from the + * global write would delete a global entry the folder merely mirrors. + * - A removed entry leaves every layer that contained it, so dialog deletes + * work for workspace entries. + * - A new entry lands in the global layer, as dialog edits did before. * * @param incoming - The full merged list sent by the webview on save. * @param workspaceLayer - The current workspace-scope configuration value. @@ -236,26 +191,20 @@ export function splitCommandListScopes( } /** - * Picks the configuration target that owns the current workspace-scope layer - * for `configKey`. Reading the layers runs through the same - * `commandListConfiguration()` object `readCommandListScopes` uses; because - * that configuration is scoped to the first workspace folder, folder values - * resolve against that folder's settings; with no folder open the - * configuration is unscoped and reports no folder value, so no folder target - * can be selected. + * Picks the configuration target that owns the current workspace layer for + * `configKey`, reading through the same scoped configuration as + * `readCommandListScopes`. * - * - `workspaceFolderValue` set -> write at `WorkspaceFolder` scope. - * - Otherwise `workspaceValue` set -> write at `Workspace` scope. - * - Neither set -> `undefined`: no workspace layer exists, so none should be - * created (an empty workspace layer must not materialize in settings.json). + * - `workspaceFolderValue` set -> `WorkspaceFolder`. + * - Else `workspaceValue` set -> `Workspace`. + * - Neither -> `undefined`: an empty workspace layer must not materialize in + * settings.json. * * @param configKey - The extension configuration key to inspect. - * @param inspectionOverride - A snapshot captured by the caller; when present - * it alone decides the target and no fresh lookup happens, keeping a save's - * split, write, and rollback on one configuration state. Without it the - * lookup is guarded leniently: a failure means no workspace layer exists. - * @returns The workspace-scoped target to write, or `undefined` when no - * workspace layer exists. + * @param inspectionOverride - A caller snapshot; when present it alone + * decides the target, keeping a save on one configuration state. Without it + * a failed lookup means no workspace layer exists. + * @returns The workspace-scoped target to write, or `undefined`. */ export function resolveWorkspaceWriteTarget( configKey: CommandListConfigKey, @@ -263,9 +212,7 @@ export function resolveWorkspaceWriteTarget( ): vscode.ConfigurationTarget.WorkspaceFolder | vscode.ConfigurationTarget.Workspace | undefined { let inspected: CommandListInspection | undefined = inspectionOverride if (inspected === undefined) { - // Same defensive posture as readCommandListScopes: only the - // configuration lookup itself may fail, and a failure means we create no - // workspace layer. + // Same guarded posture as readCommandListScopes: failure means no workspace layer. try { inspected = commandListConfiguration().inspect(configKey) } catch { @@ -283,12 +230,10 @@ export function resolveWorkspaceWriteTarget( } /** - * Reads the `zoo-code.workspaceCommandListsEnabled` gate that decides whether - * the workspace layers of the command-list keys take part in enforcement and - * display at all. The configuration declares the key with `scope: - * "application"`, so only user settings can flip it. The lookup is guarded - * leniently like the command-list reads: a configuration failure keeps the - * workspace layers inert, which cannot widen what auto-approval allows. + * Reads the gate that decides whether workspace command lists take part in + * enforcement and display. Its manifest scope is "application", so only user + * settings flip it. A failed lookup keeps the workspace layers inert, which + * cannot widen approvals. */ export function workspaceCommandListsEnabled(): boolean { try { @@ -307,15 +252,14 @@ export interface EffectiveCommandLists { globalDeny: string[] /** * Workspace allow entries the gate and shadowing kept; they decide only - * commands no global entry matches (see {@link getEffectiveCommandDecision}). + * commands no global entry matches. */ keptWorkspaceAllow: string[] /** Deny-side counterpart of {@link keptWorkspaceAllow}. */ keptWorkspaceDeny: string[] /** - * Workspace allow entries absent from the effective allowlist — hidden by - * the gate or shadowed by a global entry — which a dialog save must not be - * able to delete by omission. + * Workspace allow entries hidden from the effective list by the gate or a + * global shadow. A dialog save must not delete these by omission. */ hiddenWorkspaceAllow: string[] /** Deny-side counterpart of {@link hiddenWorkspaceAllow}. */ @@ -323,27 +267,19 @@ export interface EffectiveCommandLists { } /** - * Composes the raw per-key layers into the pair of lists the settings dialog - * displays, together with the layer split {@link getEffectiveCommandDecision} - * matches commands against, so display and enforcement draw on one composition - * pass and cannot drift. + * Composes the raw per-key layers into the pair the dialog displays and the + * layer split {@link getEffectiveCommandDecision} matches against, so display + * and enforcement share one pass and cannot drift. * - * Gate off: the workspace layers contribute nothing and the global layers are - * effective verbatim. Gate on: a workspace entry survives in the pair only - * when no entry of either global list shadows it — an entry whose every match - * a global entry also matches can decide nothing on its own, and keeping it - * out of the pair keeps the dialog honest about what the global layer already - * covers. A surviving entry may still overlap a global entry without being - * shadowed by it (a wildcard deny matches commands no global prefix reaches); - * the overlap is harmless because {@link getEffectiveCommandDecision} lets the - * global layer decide every command it matches, so a workspace entry never - * outranks a global match. Shadowing is cross-directional because a global - * allow entry silences a workspace deny entry (and vice versa) just as much as - * a same-list shadow. + * Gate off: the global layers are effective verbatim. Gate on: a workspace + * entry survives only when no global entry shadows it. Shadowing is + * cross-directional: a global allow silences a workspace deny just as a + * global deny silences a workspace allow. A surviving entry may overlap a + * global entry without being shadowed; the overlap is harmless because the + * global layer decides every command it matches. * - * Composing here — not inside {@link readCommandListScopes} — keeps the raw - * layers intact for the save path, which derives the write split from them and - * must never see entries filtered out of the workspace layer. + * Composing here keeps the raw layers intact for the save path, which derives + * its write split from them. * * @param allowScopes - Raw `allowedCommands` layers from readCommandListScopes. * @param denyScopes - Raw `deniedCommands` layers from readCommandListScopes. @@ -383,24 +319,18 @@ export function resolveEffectiveCommandLists( } /** - * Decides a single command under the precedence the command layers are - * authored with: wherever a global (user-level) entry — allow or deny — - * matches the command, the global layer decides it, so a user's own allow - * outranks a project's deny and a user's own deny outranks a project's allow; - * workspace entries apply only where no global entry matches. Within either - * layer the established matcher semantics stand: the longest matching prefix - * wins and an equal-length allow/deny conflict denies. - * - * The scope is one command: a chained command is decided per sub-command, and - * chain splitting lives with the command matcher. + * Decides one command. Any matching global entry decides it: a user's allow + * outranks a project's deny, and a user's deny outranks a project's allow. + * Workspace entries apply only where no global entry matches. Within a layer + * the matcher semantics stand: longest prefix wins, equal-length conflicts + * deny. Chain splitting lives with the command matcher. * * @param command - The single (unchained) command to decide. * @param effective - A composition from {@link resolveEffectiveCommandLists}. * @returns The decision produced by the matching layer. */ export function getEffectiveCommandDecision(command: string, effective: EffectiveCommandLists): CommandDecision { - // One longest-prefix probe asks the only question the precedence turns on: - // does the global layer hold any match for this command at all? + // One probe asks the precedence question: does the global layer match at all? if (findLongestPrefixMatch(command, [...effective.globalAllow, ...effective.globalDeny]) !== null) { return getSingleCommandDecision(command, effective.globalAllow, effective.globalDeny) } diff --git a/src/core/auto-approval/commands.ts b/src/core/auto-approval/commands.ts index d772bffb12..2839b43b4b 100644 --- a/src/core/auto-approval/commands.ts +++ b/src/core/auto-approval/commands.ts @@ -116,21 +116,17 @@ export function findLongestPrefixMatch(command: string, prefixes: string[]): str /** * Whether one command-list entry is covered by any entry of `shadowing`. * - * "Covered" applies the matcher's comparison — case-insensitive `startsWith` - * with `"*"` as universal prefix — directly to the two stored entries: only - * commands reach the matcher trimmed, entries never are, so an entry whose - * stored form carries leading whitespace matches no command and can shadow - * only other entries that match nothing either. An entry whose every possible - * match is also matched by some `shadowing` entry cannot decide anything on - * its own: that layer's decision stands. Dropping covered entries when - * composing layers reproduces a global-decides precedence without the matcher - * knowing about layers. + * Coverage uses the matcher's own comparison — case-insensitive `startsWith`, + * `"*"` universal — on the stored entries, untrimmed, because the matcher + * trims commands but never entries. Dropping covered entries when composing + * layers reproduces global-decides precedence without the matcher knowing + * about layers. * * @param entry - The entry that may be covered. * @param shadowing - The entries whose match coverage decides. * @returns true if some `shadowing` entry covers `entry`. An empty `entry` - * counts as covered only by `"*"`: the guard that stops it prefix-matching - * every command keeps a blank entry visible, as it cannot be enforced. + * is covered only by `"*"`: it cannot be enforced, so the guard keeps it + * visible. */ export function isShadowedByAnyEntry(entry: string, shadowing: string[]): boolean { const lowerEntry = entry.toLowerCase() diff --git a/src/core/auto-approval/index.ts b/src/core/auto-approval/index.ts index 6c03454790..e1179431a1 100644 --- a/src/core/auto-approval/index.ts +++ b/src/core/auto-approval/index.ts @@ -156,22 +156,14 @@ function isWriteAllowedByPatterns( } /** - * Same chain aggregation as `getCommandDecisionDetailed` — split into - * sub-commands, any denial denies the whole command, a dangerous substitution - * forces the user prompt, and approval needs every sub-command approved — but - * each sub-command is decided by `getEffectiveCommandDecision`, so the global - * layer decides every command it matches and workspace entries apply only - * where no global entry matches. A flat merged pair cannot express that - * precedence: a workspace wildcard deny ties a global prefix allow in the - * matcher's longest-prefix comparison, so composition would have to drop one - * layer's entries to break the tie and lose its verdicts elsewhere. - * - * The aggregation mirrors `getCommandDecisionDetailed` on purpose: malformed - * parsing, redirection sanitization, the substitution veto, and the - * offending-command/matched-pattern reporting must not drift between the two - * paths — only the per-sub-command leaf decision differs. Where a sub-command - * has no global match at all, both paths reach the same outcome, because the - * flat pair is the union of exactly the layers the split evaluates. + * Chain aggregation identical to `getCommandDecisionDetailed` — any denial + * denies, a dangerous substitution prompts, approval needs every sub-command + * approved — except each sub-command goes through + * `getEffectiveCommandDecision`. A flat merged pair cannot express the + * global-decides precedence: a workspace wildcard deny ties a global prefix + * allow in the longest-prefix comparison, and breaking the tie would drop + * one layer's verdicts elsewhere. The aggregation mirrors the flat path so + * parsing, sanitization, and reporting cannot drift between them. */ function getLayerScopedCommandDecisionDetailed( command: string, @@ -194,8 +186,7 @@ function getLayerScopedCommandDecisionDetailed( if (denyIndex !== -1) { const offendingCommand = sanitizedCommands[denyIndex] const lowerMatch = findLongestPrefixMatch(offendingCommand, effective.denied) - // Prefer the original-cased pattern the user typed, falling back to the - // case-insensitive match itself. + // Prefer the user-typed casing; fall back to the case-insensitive match. const matchedPattern = effective.denied.find((pattern) => pattern.toLowerCase() === lowerMatch) ?? lowerMatch ?? undefined @@ -244,19 +235,11 @@ export async function checkAutoApproval({ }: { state?: Pick /** - * Workspace root the allowlist patterns and the checked path are resolved - * against. - * - * For every ask but a command, this is the `cwd` of the task the ask belongs - * to — the root the path in `text` was made relative to. A command ask is - * judged against the command's own resolved working directory when the - * caller forwards `commandCwd`, which a custom working directory moves off - * the task folder. It is not read from `state`, because - * the provider's `cwd` follows the window (the focused editor in a multi-root - * workspace, or a `refreshWorkspace()` while the task runs) and a resumed or - * child task can run against another root entirely. Resolving against the - * wrong one would let a pattern written for one workspace approve a write - * landing in another. + * Workspace root the allowlist patterns and the checked path resolve against. + * For a non-command ask this is the task's `cwd`; for a command ask it is the + * command's own working directory when the caller forwards `commandCwd`. + * Never the provider's `state.cwd`: that follows the window, so a resumed or + * child task could be judged by another root's patterns. */ cwd?: string ask: ClineAsk @@ -384,19 +367,12 @@ export async function checkAutoApproval({ return { decision: "approve" } } - // The pair on `state` was composed against the window's first - // folder; a command executing in another folder must be judged by - // that folder's lists, so enforcement re-composes from the raw - // global layers at the folder the command's `cwd` resolves to. A - // non-blank `cwd` that resolves to no workspace root names a - // directory outside every folder, and no folder's layer may decide - // it: the workspace layer is dropped (`enabled=false`) and only the - // global layers apply — fail-closed, so nothing on a folder's - // allow list can approve a command in a directory no folder - // claims. A blank or absent `cwd` keeps the first-folder - // configuration. Without the raw layers the pre-composed pair is - // all the state carries, and that pair is what enforcement - // consumes. + // The pair on `state` follows the window's first folder, so a command + // in another folder is re-judged from the raw global layers at its own + // folder. A `cwd` outside every workspace root gets no folder layer at + // all — fail-closed: no folder's allow list may approve it. A blank + // `cwd` keeps the first-folder configuration. Without raw layers, the + // pre-composed pair is all the state carries. const commandFolder = commandListFolderForResource(cwd) const cwdNamesNoFolder = Boolean(cwd) && commandFolder === undefined const effectiveLists = @@ -418,10 +394,8 @@ export async function checkAutoApproval({ ) : { allowed: state.allowedCommands || [], denied: state.deniedCommands || [] } - // The layered composition carries the per-layer split, so each - // sub-command goes through getEffectiveCommandDecision; the - // pre-composed fallback pair carries no layers and keeps the flat - // matcher. + // Layered composition takes the per-layer split; the fallback pair + // keeps the flat matcher. const { decision, offendingCommand, matchedPattern, parseError } = "globalAllow" in effectiveLists ? getLayerScopedCommandDecisionDetailed(text, effectiveLists) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 6c66655325..426f907acf 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -20,6 +20,8 @@ import { import { ProviderSettingsManager } from "../ProviderSettingsManager" import { ContextProxy } from "../ContextProxy" import { CustomModesManager } from "../CustomModesManager" +import { Package } from "../../../shared/package" +import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { safeWriteJson } from "../../../utils/safeWriteJson" import type { Mock } from "vitest" @@ -49,6 +51,11 @@ vi.mock("vscode", () => ({ Uri: { file: vi.fn((filePath) => ({ fsPath: filePath })), }, + ConfigurationTarget: { + Global: 1, + Workspace: 2, + WorkspaceFolder: 3, + }, })) vi.mock("fs/promises", () => ({ @@ -663,6 +670,141 @@ describe("importExport", () => { showErrorMessageSpy.mockRestore() }) + // A save classifies a displayed command-list entry as externally + // removed unless a configuration layer holds it, so an import that + // carries command lists must write them into the global layer; + // an import that never runs or never carried a list must not write. + function mockCommandListConfig() { + // The shared structurally complete double keeps the configuration + // type correct; update() records the mirror's calls. + const config = makeWorkspaceConfiguration() + const update = vi.mocked(config.update) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + return update + } + + function stubValidProviderProfiles() { + mockProviderSettingsManager.export.mockResolvedValue({ + currentApiConfigName: "default", + apiConfigs: { default: { apiProvider: providerIdentifiers.anthropic, id: "default-id" } }, + }) + mockProviderSettingsManager.listConfig.mockResolvedValue([ + { name: "valid-profile", id: "valid-id", apiProvider: providerIdentifiers.openai }, + ]) + } + + const validProfileFile = (globalSettings: Record) => + JSON.stringify({ + providerProfiles: { + currentApiConfigName: "valid-profile", + apiConfigs: { + "valid-profile": { + apiProvider: providerIdentifiers.openai, + apiKey: "test-key", + id: "valid-id", + }, + }, + }, + globalSettings, + }) + + const feedbackProvider = () => ({ + settingsImportedAt: 0, + postStateToWebview: vi.fn().mockResolvedValue(undefined), + }) + + const runFeedback = async (filePath?: string) => + importSettingsWithFeedback( + { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider: feedbackProvider(), + }, + filePath, + ) + + it("mirrors the command lists a successful import carried into the global configuration", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue( + validProfileFile({ allowedCommands: ["git", "imported"], deniedCommands: ["rm -rf"] }), + ) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + // The state copy holds the same lists after setValues: the mirror + // and a state-copy source agree here, so this test pins that the + // success path writes both keys at all. + vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git", "imported"] : key === "deniedCommands" ? ["rm -rf"] : undefined, + ) + const update = mockCommandListConfig() + + await runFeedback(filePath) + + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name) + expect(update).toHaveBeenCalledWith( + "allowedCommands", + ["git", "imported"], + vscode.ConfigurationTarget.Global, + ) + expect(update).toHaveBeenCalledWith("deniedCommands", ["rm -rf"], vscode.ConfigurationTarget.Global) + }) + + it("writes no command-list configuration when the file dialog is cancelled", async () => { + ;(vscode.window.showOpenDialog as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + // The state copy holds lists from an earlier session: a mirror that + // runs on the cancel path would write this stale state over the + // user's settings file for an import that never happened. + vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git", "stale"] : key === "deniedCommands" ? ["rm -rf"] : undefined, + ) + const update = mockCommandListConfig() + const showErrorMessageSpy = vi.spyOn(vscode.window, "showErrorMessage").mockResolvedValue(undefined) + + await runFeedback() + + expect(update).not.toHaveBeenCalled() + expect(showErrorMessageSpy).toHaveBeenCalledWith(expect.stringContaining("errors.settings_import_failed")) + showErrorMessageSpy.mockRestore() + }) + + it("writes no command-list configuration when the import fails", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.access as Mock).mockRejectedValue(new Error("ENOENT: no such file or directory")) + // Same stale-state script as the cancel test: a failed import must + // not mirror the state copy either. + vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git", "stale"] : key === "deniedCommands" ? ["rm -rf"] : undefined, + ) + const update = mockCommandListConfig() + const showErrorMessageSpy = vi.spyOn(vscode.window, "showErrorMessage").mockResolvedValue(undefined) + + await runFeedback(filePath) + + expect(update).not.toHaveBeenCalled() + expect(showErrorMessageSpy).toHaveBeenCalledWith(expect.stringContaining("errors.settings_import_failed")) + showErrorMessageSpy.mockRestore() + }) + + it("mirrors only the keys the import file carried, never the state copy's lists", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ mode: "code" })) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + // The state copy holds command lists the file never carried: a + // mirror sourcing the state copy would write them over the user's + // settings file on an import that says nothing about them. + vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git", "stale"] : undefined, + ) + const update = mockCommandListConfig() + + await runFeedback(filePath) + + expect(update).not.toHaveBeenCalled() + }) + it("should handle import when reasoning budget fields are missing from config", async () => { // This test verifies that import works correctly when reasoning budget fields are not present diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 9882039ad3..9861b269ca 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -21,6 +21,7 @@ import { ContextProxy } from "./ContextProxy" import { CustomModesManager } from "./CustomModesManager" import { downgradeLegacyRooConfig, ROUTER_REMOVAL_IMPORT_WARNING } from "./routerRemoval" import { resolveDefaultSaveUri, saveLastExportPath } from "../../utils/export" +import { Package } from "../../shared/package" import { t } from "../../i18n" export type ImportOptions = { @@ -386,6 +387,24 @@ export const importSettingsWithFeedback = async ( } if (result.success) { + // Import writes the command lists only to the extension-state + // copy. A save classifies a displayed entry as externally + // removed unless a configuration layer holds it. Mirror each + // imported list into the global layer so the next save keeps it. + for (const key of ["allowedCommands", "deniedCommands"] as const) { + const imported = result.globalSettings?.[key] + if (Array.isArray(imported)) { + try { + await vscode.workspace + .getConfiguration(Package.name) + .update(key, imported, vscode.ConfigurationTarget.Global) + } catch (error) { + // The import itself succeeded; the lists work until a save rewrites both homes. + console.warn(`Settings import: could not mirror ${key} into the global configuration:`, error) + } + } + } + provider.settingsImportedAt = Date.now() await provider.postStateToWebview() provider.settingsImportedAt = undefined diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 2e12f09ff2..955df93c74 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1329,9 +1329,8 @@ export class Task extends EventEmitter implements TaskLike { // Disengaged: the queued answer is a legitimate approval, as before. return { action: "consume" } } - // Engaged: the full policy decides, with the fresh state. `cwd`, the - // forwarded DCG verdict, and the command's working directory match the - // ask-time `checkAutoApproval` call. + // Engaged: the full policy decides with the fresh state and the same + // inputs as the ask-time `checkAutoApproval` call. const approval = await checkAutoApproval({ state: freshState, cwd: commandCwd ?? this.cwd, @@ -1995,10 +1994,8 @@ export class Task extends EventEmitter implements TaskLike { // `this.cwd`, not `provider.cwd`: // The path inside `text` was made relative to this task's workspace, // which for a resumed or child task need not be the one the provider - // currently reports. A tool that forwards a `commandCwd` overrides that - // for policy purposes: the command lists must judge the directory the - // command will actually run in, which a custom tool `cwd` moves off the - // task folder. + // currently reports. A forwarded `commandCwd` overrides that for policy: + // the command lists judge the directory the command actually runs in. const approval = queuedAskResolution ? ({ decision: "ask" } as const) : await checkAutoApproval({ diff --git a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts index f2baa92d22..27971007bb 100644 --- a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts +++ b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts @@ -5,10 +5,8 @@ import type { ExtensionState } from "@roo-code/types" import { Task } from "../Task" import { setAbortLatch } from "../../../test-utils/run-state" -// Command-list enforcement resolves the command's cwd to a workspace folder and -// reads that folder's configuration; the shared module mock resolves every -// lookup to nothing, so these scriptable stand-ins (wrapping the real mock) are -// what let a command ask be judged by a named folder's allow/deny entries. +// Scriptable workspace stand-ins: the shared vscode mock resolves every lookup +// to nothing, so a command ask could not be judged by a named folder otherwise. const workspaceState = vi.hoisted(() => ({ workspaceFolders: [] as { fsPath: string; uri: { fsPath: string } }[], foldersByPath: new Map(), @@ -154,13 +152,10 @@ describe("Task.ask resolves allowlists against the task's workspace", () => { }) }) -// Command asks: the per-folder command lists must judge the directory the -// command will actually run in (`commandCwd` from the tool's approval -// context), not the task folder — a task in folder A must not be able to ride -// folder A's allow entry to run a command in folder B. The raw global layers -// are set empty on the state so every decision below comes from the folder the -// command's cwd resolves to; the baked pair carries values no folder composes, -// so a check that consumed it instead of re-composing decides differently. +// Command asks are judged by the command's own cwd (commandCwd), not the task +// folder: folder A's allow entry must not approve a command run in folder B. +// The raw global layers are empty, so each decision comes from the command's +// folder. The baked pair carries values no folder composes. const FOLDER_A = "/mock/folder-a" const FOLDER_B = "/mock/folder-b" @@ -171,8 +166,7 @@ function openTwoFolders() { workspaceState.workspaceFolders = [folderA, folderB] workspaceState.foldersByPath.set(FOLDER_A, folderA.uri) workspaceState.foldersByPath.set(FOLDER_B, folderB.uri) - // Folder A allows "echo" and folder B denies it, so a decision names the - // folder that was read. + // Folder A allows "echo" and folder B denies it, so a decision names the folder read. workspaceState.configScripts = { [FOLDER_A]: { gate: true, allow: ["echo"] }, [FOLDER_B]: { gate: true, deny: ["echo"] }, @@ -196,8 +190,7 @@ const askToRunCommand = async (commandCwd: string | undefined, state: Partial state, } - // The task runs in folder A (whose allow entry must NOT approve a command - // executing in folder B) — the task cwd equals folder A here. + // The task runs in folder A; its allow entry must not approve a command in folder B. const task = buildTask(provider, FOLDER_A) await attachQueue(task) @@ -222,8 +215,7 @@ describe("Task.ask judges command asks by the command's working directory", () = it("approves a command whose custom cwd resolves to the folder that allows it", async () => { openTwoFolders() - // Only folder B carries the entry, so approval can only come from the - // folder the command runs in. + // Only folder B carries the entry, so only the command's folder can approve. workspaceState.configScripts[FOLDER_A] = { gate: true } workspaceState.configScripts[FOLDER_B] = { gate: true, allow: ["echo"] } @@ -233,17 +225,15 @@ describe("Task.ask judges command asks by the command's working directory", () = it("does not approve a command executing where the same entry is denied, although the task folder allows it", async () => { openTwoFolders() - // The task folder (A) allows "echo"; the command runs in B, which denies - // it. The deny layer must decide. + // Folder A allows "echo" but the command runs in denying folder B: deny decides. expect(await askToRunCommand(FOLDER_B, commandState())).toBe("deny") }) it("judges a custom cwd that names no workspace folder by the global layers only", async () => { openTwoFolders() - // The baked pair would approve, but with the raw layers present the - // command branch re-composes: an unmatched cwd drops the workspace - // layer entirely, so nothing allows or denies "echo" and the user decides. + // The baked pair would approve. Re-composition drops the workspace layer + // for an unmatched cwd, so nothing matches and the user decides. expect(await askToRunCommand("/mock/removed-folder", commandState())).toBe("ask") }) @@ -259,18 +249,15 @@ describe("Task.ask judges command asks by the command's working directory", () = const provider: ProviderStub = { postMessageToWebview: vi.fn().mockResolvedValue(undefined), cwd: PROVIDER_CWD, - // First read (ask time): blanket deny off, execute auto-approval off, - // so the ask stays pending. Second read (drain re-check): blanket - // deny engaged, so the queued message must re-earn its approval. + // First read (ask time): blanket deny off, so the ask stays pending. + // Second read (drain re-check): blanket deny engaged. getState: vi .fn() .mockResolvedValueOnce(commandState({ alwaysAllowExecute: false, alwaysDenyUnapprovedCommands: false })) .mockResolvedValue(commandState({ alwaysDenyUnapprovedCommands: true })), } - // The task is rooted in folder B (which denies "echo") while the command - // runs in folder A (which allows it): a re-check that fell back to the - // task folder would deny the queued approval the command's own folder - // grants. + // The task is in denying folder B; the command runs in allowing folder A. + // Falling back to the task folder would deny what folder A grants. const task = buildTask(provider, FOLDER_B) await attachQueue(task) @@ -278,9 +265,7 @@ describe("Task.ask judges command asks by the command's working directory", () = await vi.waitUntil(() => (task["addToClineMessages"] as ReturnType).mock.calls.length > 0) task.messageQueueService.addMessage("run it") - // Folder A allows "echo"; had the re-check judged the task-independent - // defaults or the baked pair, the blanket deny would reject the queued - // approval. The folder the command runs in approves it. + // Folder A approves. Judging the defaults or the baked pair would deny instead. const result = await asked expect(result.response).toBe("yesButtonClicked") @@ -289,9 +274,8 @@ describe("Task.ask judges command asks by the command's working directory", () = it("re-checks a queued command drained at ask entry with no approval context", async () => { openTwoFolders() - // A message already queued when the ask opens, with the claim gate open - // (blanket deny off): the ENTRY drain (not the later pWaitFor one) - // performs the policy re-check, and folder A's entry approves it. + // A message is already queued and the claim gate is open: the entry + // drain performs the re-check, and folder A's entry approves. const provider: ProviderStub = { postMessageToWebview: vi.fn().mockResolvedValue(undefined), cwd: PROVIDER_CWD, @@ -301,10 +285,8 @@ describe("Task.ask judges command asks by the command's working directory", () = await attachQueue(task) task.messageQueueService.addMessage("run it") - // No approval context at all: the entry re-check must run cleanly - // against the task folder and approve via folder A's entry. A throw - // there is caught and logged (then the pWaitFor drain would paper over - // it), so the log is the witness. + // Without approval context the entry re-check uses the task folder. + // A throw there is only logged, so the log is the witness. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) const result = await task.ask("command", "echo hi", false) @@ -315,13 +297,10 @@ describe("Task.ask judges command asks by the command's working directory", () = }) it("re-checks an entry-drained queued command against the task folder's policy once blanket deny engages", async () => { - // Same entry drain as the no-context test above, but blanket deny is - // engaged on the drain read, so the re-check reaches directory - // selection instead of consuming the queued message as a legitimate - // approval. The task's folder is made the SECOND workspace folder - // (folder order swapped) while it allows "echo": a re-check that fell - // back to the first workspace folder — which denies it — would deny, - // so the approval names the task folder's directory. + // Same entry drain, but blanket deny is engaged on the drain read. The + // task's folder is now the second workspace folder: a fallback to the + // first folder (which denies "echo") would deny, so the approval names + // the task folder. openTwoFolders() workspaceState.workspaceFolders = [ { fsPath: FOLDER_B, uri: { fsPath: FOLDER_B } }, @@ -330,9 +309,8 @@ describe("Task.ask judges command asks by the command's working directory", () = const provider: ProviderStub = { postMessageToWebview: vi.fn().mockResolvedValue(undefined), cwd: PROVIDER_CWD, - // First read (ask time): blanket deny off, so the entry claim gate - // opens. Second read (entry-drain re-check): blanket deny engaged, - // so the queued message must re-earn its approval. + // First read (ask time): blanket deny off, so the entry claim gate opens. + // Second read (entry-drain re-check): blanket deny engaged. getState: vi .fn() .mockResolvedValueOnce(commandState({ alwaysDenyUnapprovedCommands: false })) @@ -342,8 +320,8 @@ describe("Task.ask judges command asks by the command's working directory", () = await attachQueue(task) task.messageQueueService.addMessage("run it") - // No approval context: the re-check falls back to the task's own - // directory, where folder A's entry grants the queued approval. + // No approval context: the re-check falls back to the task's directory, + // where folder A's entry grants the approval. const result = await task.ask("command", "echo hi", false) expect(result.response).toBe("yesButtonClicked") @@ -351,12 +329,9 @@ describe("Task.ask judges command asks by the command's working directory", () = }) it("denies an entry-drained queued command whose task folder denies it, although the first workspace folder allows it", async () => { - // The paired reject path: the task is rooted in folder B (which denies - // "echo") and folder B is NOT the first workspace folder. With blanket - // deny engaged on the drain read, the re-check selects the task - // folder's directory; a fallback to the first workspace folder (which - // allows "echo") would approve, so the denial names the folder the - // task actually runs in. + // The paired reject path: the task is in denying folder B, which is not + // the first workspace folder. A fallback to the first folder (allow) + // would approve, so the denial names the task's folder. openTwoFolders() const provider: ProviderStub = { postMessageToWebview: vi.fn().mockResolvedValue(undefined), diff --git a/src/core/tools/ExecuteCommandTool.ts b/src/core/tools/ExecuteCommandTool.ts index 98c6c0a128..2dde0ed736 100644 --- a/src/core/tools/ExecuteCommandTool.ts +++ b/src/core/tools/ExecuteCommandTool.ts @@ -156,32 +156,21 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> { return } const provider = await task.providerRef.deref() - // One canonical working directory, resolved before any approval - // decision: the command-list policy, the DCG run, and the terminal - // spawn must all see the same directory, so a custom `cwd` can never + // Resolve one working directory before any approval decision: policy, + // DCG, and spawn all see the same directory, so a custom `cwd` cannot // be approved against one folder and executed in another. const lexicalWorkingDirectory = customCwd ? path.isAbsolute(customCwd) ? customCwd : path.resolve(task.cwd, customCwd) : task.cwd - // A folder's command lists apply to a command by containment: the - // working directory is matched against the open roots, and against - // each root's real path when the registered paths match nothing, so - // a root that is itself a link still claims its own directory. - // Canonicalizing here keeps both sides of that match physical, so - // the judged folder is the one containing the directory the process - // actually starts in — a symlinked directory would otherwise be - // judged by the folder its path sits in while the process starts in - // the link's target, the same drift in filesystem form (precedent: - // `RooIgnoreController.validateAccess` also resolves symlinks with - // realpath before a policy check). Unlike that file-access posture, - // an unresolvable link here names no directory any policy could - // judge, so the command fails closed through the working-directory - // error channel rather than falling back to the lexical path. A link - // re-pointed between this call and the spawn cannot be closed from - // here; it rides the same accepted race class as a settings flip - // during a pending prompt. + // Folder command lists apply by containment. Canonicalizing here keeps + // both sides of that match physical, so a symlinked directory is judged + // where the process actually starts (`RooIgnoreController.validateAccess` + // sets the realpath-before-policy precedent). An unresolvable link names + // no judgeable directory: fail closed via the working-directory error, + // no lexical fallback. A link re-pointed before the spawn is an accepted + // race, like a settings flip during a pending prompt. let workingDirectory: string try { workingDirectory = await fs.realpath(lexicalWorkingDirectory) @@ -439,10 +428,9 @@ export type ExecuteCommandOptions = { customCwd?: string /** * The directory the approval was judged against, resolved once by the - * tool. When present the command spawns there directly, so the executed - * directory cannot drift from the one the command policy approved; - * callers that build options without it fall back to resolving - * `customCwd` against the task's own `cwd` here. + * tool. The command spawns there directly, so execution cannot drift from + * the approved directory. Without it, callers resolve `customCwd` against + * the task `cwd` here. */ workingDirectory?: string terminalShellIntegrationDisabled?: boolean diff --git a/src/core/tools/__tests__/executeCommandTool.spec.ts b/src/core/tools/__tests__/executeCommandTool.spec.ts index f14019dcc3..929114d564 100644 --- a/src/core/tools/__tests__/executeCommandTool.spec.ts +++ b/src/core/tools/__tests__/executeCommandTool.spec.ts @@ -25,9 +25,8 @@ vitest.mock("fs/promises", () => ({ default: { access: vitest.fn().mockResolvedValue(undefined), stat: vitest.fn().mockResolvedValue({ isDirectory: () => true }), - // The tool canonicalizes the resolved working directory before any - // approval decision; the default double resolves every path to itself, - // so a test only sees symlink behavior when it scripts this mock. + // The default double resolves every path to itself, so a test sees + // symlink behavior only when it scripts this mock. realpath: vitest.fn().mockImplementation((p: string) => Promise.resolve(p)), }, })) @@ -84,11 +83,9 @@ const { executeCommandTool } = executeCommandModule // capturing inside a test can capture another test's leaked spy and recurse. const realCheckAutoApproval = autoApprovalModule.checkAutoApproval -// Creating a directory symlink on Windows needs developer mode or elevation; a -// junction needs neither and is resolved by `realpath` like a POSIX link, so the -// fixture tries a symlink first and falls back to a junction. Where neither can -// be created the fixture is skipped: the real-filesystem behavior it pins cannot -// be produced by the file-mock module this suite otherwise runs on. +// A Windows directory symlink needs developer mode or elevation; a junction does +// not, and `realpath` resolves it like a POSIX link. Try a symlink first, then a +// junction. Skip the fixture where neither can be created. function createDirectoryLink(target: string, linkPath: string): void { try { symlinkSync(target, linkPath, "dir") @@ -264,8 +261,7 @@ describe("executeCommandTool", () => { }) // Verify - command approved, result pushed, and custom cwd passed to terminal - // The approval context carries the same directory the terminal will - // spawn in, so the folder-scoped command policy judges that folder. + // The approval context carries the directory the terminal spawns in. expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { commandCwd: "/custom/path", }) @@ -276,10 +272,9 @@ describe("executeCommandTool", () => { }) it("reports a relative custom cwd resolved against the task's workspace", async () => { - // A relative custom cwd runs the command in a subdirectory of the task - // folder, so the approval must name the resolved absolute path: the - // policy lookup resolves against workspace folders, which a relative - // path never names. + // The policy lookup matches against workspace folders, which a + // relative path never names, so the approval must carry the + // resolved absolute path. mockToolUse.params.command = "echo test" mockToolUse.params.cwd = "sub/dir" mockToolUse.nativeArgs = { command: "echo test", cwd: "sub/dir" } @@ -303,11 +298,10 @@ describe("executeCommandTool", () => { }) }) - // The folder-scoped command policy resolves a directory by string - // containment, so a link would be judged by the folder it sits in while the - // process starts in the link's target. The tool canonicalizes the resolved - // working directory once, before any approval decision, so every consumer - // (ask, DCG, re-checks, spawn) sees the physical directory. + // The folder policy matches by string containment, so a link would be judged + // by its own folder while the process starts in the target. The tool + // canonicalizes the working directory before any approval decision, so + // every consumer (ask, DCG, re-checks, spawn) sees the physical directory. describe("Working directory canonicalization", () => { it("forwards the physical directory behind a symlinked custom cwd to the approval ask", async () => { mockToolUse.params.command = "echo test" @@ -360,8 +354,7 @@ describe("executeCommandTool", () => { toolCallId: "test-tool-call-id", }) - // The realpath failure is reported through the working-directory - // error channel, which names the directory by its validated state. + // The failure reports through the working-directory error channel. expect(formatResponse.toolError).toHaveBeenCalledExactlyOnceWith( "Working directory '/mock/broken-link' does not exist.", ) @@ -387,11 +380,9 @@ describe("executeCommandTool", () => { toolCallId: "test-tool-call-id", }) - // A link that cannot be resolved names no directory any policy - // could judge, even when the lexical `stat` check would pass: the - // fallback message is the witness that the error came from - // canonicalization, and it carries the failure reason whatever - // shape the rejection has. + // An unresolvable link names no judgeable directory, even when the + // lexical `stat` check passes. The message names the + // canonicalization failure whatever the rejection's shape. expect(formatResponse.toolError).toHaveBeenCalledExactlyOnceWith( expect.stringContaining("Unable to resolve working directory '/mock/loop': ELOOP"), ) @@ -400,11 +391,9 @@ describe("executeCommandTool", () => { }, ) - // The scripted-realpath tests above pin the tool's contract; this one - // pins it against a real link: the folder policy resolves a path by - // string containment (already covered against the canonical value), so - // the physical path reaching `commandCwd` is what makes a link inside one - // folder judged by the folder of its target. + // The scripted tests above pin the contract; this one uses a real link. + // The physical path reaching `commandCwd` makes a link judged by its + // target's folder. it.skipIf(!directoryLinksAvailable)( "forwards the real target of a directory link created on disk", async () => { @@ -416,11 +405,8 @@ describe("executeCommandTool", () => { mkdirSync(folderB) const link = path.join(folderA, "link") createDirectoryLink(folderB, link) - // The module mock resolves paths through this delegate, so the - // tool sees the same physical path the filesystem reports. - // Once-only: the tool canonicalizes exactly one path per call, - // and a leaked delegate would resolve later tests' fake paths - // against the real filesystem. + // Delegate to the real filesystem. Once-only: a leaked + // delegate would resolve later tests' fake paths for real. vi.mocked(fs.realpath).mockImplementationOnce(async (target) => realpathSync(String(target))) mockToolUse.params.cwd = link @@ -432,9 +418,8 @@ describe("executeCommandTool", () => { toolCallId: "test-tool-call-id", }) - // Compared against the independently resolved target rather - // than a literal: temporary-directory paths themselves contain - // links on some platforms. + // Compare against the independently resolved target: temp paths + // themselves contain links on some platforms. expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test", undefined, false, { commandCwd: realpathSync(folderB), }) @@ -883,15 +868,13 @@ describe("executeCommandTool", () => { }) it("re-checks the command policy against the custom working directory", async () => { - // The folder-scoped command policy must judge the directory the command - // actually runs in. Forwarding `task.cwd` here would let folder A's - // allow entry approve a command executing in folder B, so the same - // resolved directory the terminal will spawn in rides the re-check. + // The policy re-check must judge the command's own directory: folder + // A's allow entry must not approve a command running in folder B. await setupProtectedDwellFlip() mockToolUse.params.cwd = "/custom/path" mockToolUse.nativeArgs = { command: "echo test", cwd: "/custom/path" } - // Delegates to the import-time real check: re-reading the module - // property here would capture this file's own leaked spy and recurse. + // Delegate to the import-time real check; reading the module property + // here would capture this file's leaked spy and recurse. const recheckSpy = vitest .spyOn(autoApprovalModule, "checkAutoApproval") .mockImplementation((args) => realCheckAutoApproval(args)) @@ -910,10 +893,8 @@ describe("executeCommandTool", () => { }) it("spawns in the approval's working directory rather than re-deriving from the raw custom cwd", async () => { - // The executor must honor the directory the tool resolved for - // approval verbatim, even though a different raw `customCwd` rides - // the options. Re-deriving from `customCwd` would spawn the command - // somewhere other than the directory the command policy approved. + // The executor must spawn in the directory the policy approved. + // Re-deriving from the raw `customCwd` could spawn elsewhere. vitest.spyOn(executeCommandModule, "executeCommandInTerminal").mockRestore() const [rejected] = await executeCommandModule.executeCommandInTerminal(mockCline, { diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 05a448c3d0..5a645511c4 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3341,8 +3341,7 @@ export class ClineProvider checkpointTimeout: checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, shouldShowAnnouncement: telemetrySetting !== "unset" && lastShownAnnouncementId !== this.latestAnnouncementId, - // getState() always resolves these to the effective command lists - // (never undefined), so no fallback is needed here. + // These lists are never undefined; getState() resolves them. allowedCommands, deniedCommands, workspaceCommandListsEnabled: gateEnabled ?? DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, @@ -3552,9 +3551,8 @@ export class ClineProvider const taskSyncEnabled: boolean = false - // One gate read and one resolver pass per getState() call, so the - // effective lists and the gate value posted together describe a single - // configuration state. + // One gate read and one resolver pass per call, so the effective lists + // and the gate value always describe one configuration state. const gateEnabled = workspaceCommandListsEnabled() const allowScopes = readCommandListScopes("allowedCommands", stateValues.allowedCommands) const denyScopes = readCommandListScopes("deniedCommands", stateValues.deniedCommands) @@ -3589,20 +3587,15 @@ export class ClineProvider autoCondenseContext: stateValues.autoCondenseContext ?? true, autoCondenseContextPercent: stateValues.autoCondenseContextPercent ?? 100, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], - // The effective lists composed from the global-state and - // workspace-scope configuration layers, scoped to the window's - // first folder; getStateToPostToWebview shows exactly these values, - // so the dialog cannot drift from what this state posts. In a - // multi-root window a task in another folder is judged by that - // folder's lists instead — enforcement re-composes the pair from - // the raw global layers below, so the displayed pair describes the - // window, not the task. + // Composed from the global and workspace layers, scoped to the + // window's first folder. Display shows exactly these values. A + // task in another folder is judged by that folder's lists: + // enforcement re-composes the pair from the raw global layers below. allowedCommands: effectiveCommandLists.allowed, deniedCommands: effectiveCommandLists.denied, workspaceCommandListsEnabled: gateEnabled, - // The global layers before workspace composition, so command - // enforcement can re-compose the pair against each task's own - // folder; the window-scoped pair above stays what display shows. + // Raw global layers, before workspace composition. Enforcement + // re-composes them against each task's folder. globalAllowedCommands: allowScopes.global, globalDeniedCommands: denyScopes.global, soundEnabled: stateValues.soundEnabled ?? false, @@ -4346,9 +4339,8 @@ export class ClineProvider if (configuration) { await this.setValues(configuration) - // Deliberately Global-targeted: these writes carry "start this task with - // exactly this auto-approval policy" semantics (e.g. from handoff/delegation - // payloads), unlike the scope-split persistence in the settings dialog. + // Global target on purpose: these writes mean "start this task with + // exactly this auto-approval policy". The settings dialog splits by scope. if (configuration.allowedCommands) { await vscode.workspace .getConfiguration(Package.name) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 9f26f46fad..a555689205 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4161,8 +4161,8 @@ describe("ClineProvider", () => { }) describe("command list scope merging", () => { - // getConfiguration overrides must not leak past these tests: - // clearAllMocks does not remove mockReturnValue defaults. + // clearAllMocks does not remove mockReturnValue defaults, so reset + // the configuration here. Overrides must not leak to later tests. afterEach(() => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn().mockReturnValue([]), @@ -4171,8 +4171,7 @@ describe("ClineProvider", () => { Reflect.deleteProperty(vscode.workspace, "workspaceFolders") }) - // The gate is a synchronous configuration read, so the doubles make the - // `get` lookup key-aware: only the gate key reports true here. + // The doubles make `get` key-aware so only the gate key reports true. test("getState enforces workspace-scope denied commands even when global state is empty", async () => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn().mockImplementation((key: string) => key === "workspaceCommandListsEnabled"), @@ -4204,9 +4203,8 @@ describe("ClineProvider", () => { const state = await provider.getStateToPostToWebview() - // The workspace entry survives because no global entry shadows it, so - // display is the global layer plus that entry — exactly what - // getState() enforces. + // No global entry shadows the workspace entry, so display shows the + // global layer plus that entry — what getState() enforces. expect(state.deniedCommands).toEqual(["git", "docker"]) expect(state.allowedCommands).toEqual([]) }) @@ -4225,11 +4223,10 @@ describe("ClineProvider", () => { const state = await provider.getState() - // The raw global layers are the feed per-folder enforcement - // re-composes from, so they must stay distinguishable from the - // window-composed pair: with the layers diverging here, a dropped - // field or a composed value would silently reroute enforcement to - // the first-folder lists. + // Per-folder enforcement re-composes from the raw global layers, so + // they must differ from the window-composed pair. If the fields were + // dropped or composed, enforcement would silently use the + // first-folder lists. expect(state.globalAllowedCommands).toEqual(["git"]) expect(state.globalDeniedCommands).toEqual(["curl"]) expect(state.allowedCommands).toEqual(["git", "docker"]) @@ -4251,22 +4248,20 @@ describe("ClineProvider", () => { const state = await provider.getState() - // The folder value replaces (not unions with) the workspace value, and - // the effective get() value is ignored so global-scoped entries do not - // leak into the workspace layer. + // The folder value replaces the workspace value; it does not union. + // The effective get() value is ignored, so global entries cannot leak + // into the workspace layer. expect(state.deniedCommands).toEqual(["pnpm docker"]) }) test("getState scopes its command-list lookups to the first workspace folder", async () => { - // Each folder carries its own distinct configuration, keyed by the - // resource the lookup was scoped with: any lookup that resolves to - // the second folder — or to no resource at all — reads the second - // folder's values, so the first folder's list can only come from a - // configuration scoped to the first folder's uri. + // Each folder gets its own configuration, chosen by the scope resource. + // An unscoped lookup reads the second folder, so the first folder's + // list can only come from a lookup scoped to its uri. const firstFolder = { uri: makeUri("/root/one"), name: "first", index: 0 } const secondFolder = { uri: makeUri("/root/two"), name: "second", index: 1 } - // The mocked module's workspaceFolders is readonly-typed, so the test - // installs it through defineProperty; the afterEach removes it again. + // workspaceFolders is readonly-typed in the mock, so set it through + // defineProperty. The afterEach removes it again. Reflect.defineProperty(vscode.workspace, "workspaceFolders", { configurable: true, value: [firstFolder, secondFolder], @@ -4296,11 +4291,10 @@ describe("ClineProvider", () => { expect(state.workspaceCommandListsEnabled).toBe(true) }) - // A workspace-only allow entry is exactly what the gate decides: enabled - // it joins the effective lists enforcement uses; disabled enforcement ignores it. + // The gate decides a workspace-only allow entry: enabled, it joins the + // effective lists; disabled, enforcement ignores it. function mockGateConfiguration(enabled: boolean) { - // The shared double reports scripted values through `get`, which - // is how the gate reader sees its value; the per-key `inspect` + // The gate reader reads its value through `get`; the `inspect` // override supplies the allow-side workspace layer. const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: enabled }) const inspect = vi.fn() @@ -4311,11 +4305,10 @@ describe("ClineProvider", () => { vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) } - // Counterpart for a profile that never set the gate: the configuration - // reports nothing for the gate key, so the provider paths must apply the - // shared default themselves. The allow-side workspace layer is present so - // the asserted default direction (workspace entries stay inert) is - // observable, not just the boolean. + // For a profile that never set the gate: the configuration reports nothing, + // so the provider must apply the shared default. The workspace layer is + // present so the default direction (workspace entries stay inert) is + // observable. function mockUnsetGateConfiguration() { const config = makeWorkspaceConfiguration() const inspect = vi.fn() @@ -4388,8 +4381,7 @@ describe("ClineProvider", () => { const state = await provider.getState() expect(state.workspaceCommandListsEnabled).toBe(DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED) - // The default's direction, not just its value: an unset gate keeps the - // workspace entry out of the effective list. + // An unset gate keeps the workspace entry out of the effective list. expect(state.allowedCommands).toEqual([]) }) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 79ab26d0f5..93fd8012b0 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -67,6 +67,13 @@ vi.mock("../rulesMessageHandler", () => ({ handleOpenRulesDirectory: vi.fn(), })) +// The import case needs no real import: the shared import function is a +// mock, and the save tests script the configuration state directly. +vi.mock("../../config/importExport", () => ({ + exportSettings: vi.fn(), + importSettingsWithFeedback: vi.fn(), +})) + vi.mock("@roo-code/telemetry", () => ({ TelemetryService: { hasInstance: vi.fn().mockReturnValue(false), @@ -82,6 +89,7 @@ import * as vsCodeLmProvider from "../../../api/providers/vscode-lm" import * as copilotProvider from "../../../api/providers/github-copilot" import { Package } from "../../../shared/package" +import { importSettingsWithFeedback } from "../../config/importExport" import { readCommandListScopes } from "../../auto-approval/commandScope" import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { seedCommandList } from "../../../utils/seedAllowedCommands" @@ -2152,16 +2160,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // list configuration resolves to its uri. const mockWorkspaceFolderUri = { fsPath: "/mock/workspace" } - // Mirrors the real VS Code configuration API: `inspect()` exposes the - // per-scope values, and `update()` records the target it was written to. - // Extension global state is left unset (getValue returns undefined), i.e. - // the global layer starts empty. - // - // `updateSequence` / `inspectSequence` let a failure test script what - // successive `update()` / `inspect()` calls return (each `update()` return - // is awaited by the handler, so a rejected promise fails that write), in - // call order; a plain value resolves like the default mock, and an Error - // element makes that call throw. + // Mirrors the real configuration API: `inspect()` exposes per-scope values, + // `update()` records its target. Extension state stays unset. + // `updateSequence` / `inspectSequence` script successive call outcomes in + // call order: an Error element makes that call throw. type InspectedCommandList = { globalValue?: string[] workspaceValue?: string[] @@ -2289,14 +2291,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("writes the global layer before the workspace layer and undoes only its own delta when the workspace write fails", async () => { - // update() call order: global write succeeds, workspace write rejects, - // undo write runs. The undo re-reads the global layer and applies only - // this save's delta, so an entry a third party added mid-save - // ("mid-save") survives while the save's own addition ("aws") is - // removed and its deletions ("keep", "drop") are restored. The gate is - // on so the workspace write is a plain keep with no hidden-entry re-add, - // keeping each scripted call distinguishable; the undo is pinned by - // call position. + // Call order: global write succeeds, workspace write rejects, undo runs. + // The undo applies only this save's delta, so the third party's + // mid-save addition survives while "aws" is removed and "keep"/"drop" + // are restored. The gate is on to keep each scripted call + // distinguishable; the undo is pinned by call position. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["keep", "drop"] : undefined, ) @@ -2958,15 +2957,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("clears the key only when the undo's re-read finds no layer", async () => { - // A rolled-back addition-only save must not leave an empty global layer - // where the rollback found none: the activation seed treats an explicit - // `[]` as an override, so writing `[]` over an absent layer would - // suppress the default command lists after a restart. The undo clears the - // key instead, at the same call position the `[]` write would have - // occupied. What decides clear-versus-write is the guarded re-read's - // finding, so both legs land in the same clear: in each, a third party - // cleared the layer while the save ran, leaving even this save's addition - // gone. + // The undo must not leave an empty `[]` layer where the re-read found + // none: `[]` is the activation seed's override and would suppress the + // default lists. It clears the key instead. Both legs share the + // scenario: a third party cleared the layer while the save ran. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, @@ -3017,14 +3011,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("clears the key when the undo's re-read finds only this save's own write", async () => { - // The global layer was absent when the save started, and the re-read - // during the compensation finds it holding exactly the list this save - // wrote — the half-applied save itself, not another writer's decision. - // An undo that wrote `[]` back would materialize an explicit empty - // override that the activation seed honors over the default lists, so - // the rollback clears the key and restores the absence the save - // started from. Both legs are that signature: the second when the - // save's own global write was itself empty. + // The re-read finds the layer holding exactly this save's own write + // over an absent start — the half-applied save itself, not another + // writer's decision — so the undo clears the key and restores the + // absence. Both legs share that signature; the second save's own + // global write was empty. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, @@ -3856,6 +3847,73 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { ]) }) + it("preserves a settings-imported entry whose only home is the state copy", async () => { + // A settings import mirrors each command list into the global layer + // (pinned in importExport.spec.ts); this test pins the save side. + // Without that mirrored layer the next unrelated Save would classify + // the displayed entry as externally removed and delete it. The + // scripted configuration is stateful: update() changes what the next + // inspect() reports, as the real API does. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + // The import's state write: "imported" exists here too. + key === "allowedCommands" ? ["git", "imported"] : undefined, + ) + // The import's mirror write holds the full list in the global layer; + // an earlier dialog save had already created that layer, so the + // absent-layer exception cannot carry the case either. + const layers: { globalValue?: string[] } = { globalValue: ["git", "imported"] } + const update = vi.fn() + update.mockImplementation(async (_key: string, value: string[]) => { + layers.globalValue = value + }) + const inspect = vi.fn() + inspect.mockImplementation((key: string) => (key === "allowedCommands" ? layers : {})) + const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) + config.update = update + config.inspect = inspect + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + // The next unrelated Save submits the same list with the baseline the + // import re-posted to the dialog. + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git", "imported"] }, + commandListBaseline: { + allowedCommands: ["git", "imported"], + workspaceCommandListsEnabled: true, + }, + }) + + // The mirrored entry survives the save in both homes instead of + // being dropped as externally removed. + expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "imported"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git", "imported"]) + // Retention, not a file-side change: no disclosure. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("delegates the import case to the shared import function without a configuration write", async () => { + // The command-list mirror lives inside importSettingsWithFeedback + // (pinned in importExport.spec.ts), so the message case must stay a + // thin delegate: it adds no configuration write of its own, even + // with a state copy holding command lists. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git", "imported"] : undefined, + ) + const { update } = mockCommandConfiguration({ globalValue: ["git"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { type: "importSettings" }) + + expect(importSettingsWithFeedback).toHaveBeenCalledWith({ + providerSettingsManager: mockClineProvider.providerSettingsManager, + contextProxy: mockClineProvider.contextProxy, + customModesManager: mockClineProvider.customModesManager, + provider: mockClineProvider, + }) + expect(update).not.toHaveBeenCalled() + }) + it("preserves a configuration-global entry the dialog displayed at the workspace scope", async () => { // The user added "docker" to the user-level list in settings.json while // the dialog was open, and the dialog displayed the same entry from the diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index e3e53678ba..3071d5cd86 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -786,11 +786,9 @@ export const webviewMessageHandler = async ( } } - // Shadowing is cross-directional, and a payload can carry both - // command-list keys, so the second-processed key's hidden-entry - // check would otherwise read the layer the first key's iteration - // just wrote. Both global layers are captured before any write so - // a hidden entry's preservation cannot depend on payload key order. + // Shadowing spans both directions, and one payload can carry both + // command-list keys. Capture both global layers before any write, + // so hidden-entry preservation cannot depend on payload key order. const commandListGlobalsAtSaveStart = { allowedCommands: getGlobalState("allowedCommands"), deniedCommands: getGlobalState("deniedCommands"), @@ -810,11 +808,9 @@ export const webviewMessageHandler = async ( newValue = value ?? "en" changeLanguage(newValue as Language) } else if (key === "workspaceCommandListsEnabled") { - // The gate's effective value is the synchronous - // user-scope configuration read that enforcement and - // display already perform; a value arriving in a - // settings payload is not a second source that can flip - // it, so it is never persisted here. + // The gate's effective value is the synchronous user-scope + // configuration read that enforcement and display already + // perform. A settings payload never flips or persists it. continue } else if (key === "allowedCommands" || key === "deniedCommands") { const commands = value ?? [] @@ -823,27 +819,20 @@ export const webviewMessageHandler = async ( ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) : [] - // The webview always sends the full merged list (it displays - // the union of the global-state and workspace-scope layers). - // Splitting that list by origin scope needs the workspace - // layer, the write target, and the rollback value to describe - // the SAME configuration state, so they are all derived from - // one inspect() snapshot taken before any write. Without a - // snapshot the key's save is aborted rather than guessed at: - // reading the workspace layer as empty would classify a - // workspace-scoped entry as brand new and re-copy it into - // global settings. + // The webview sends the full merged list. Splitting it by + // origin scope needs one inspect() snapshot before any write: + // the workspace layer, write target, and rollback value must + // describe the same configuration state. A guessed-empty + // workspace layer would re-copy workspace entries into global + // settings, so a key without a snapshot aborts instead. // Only the snapshot read is guarded: a failing - // commandListConfiguration() lookup propagates instead of being - // downgraded to a per-key save failure. + // commandListConfiguration() lookup propagates instead of + // becoming a per-key save failure. const config = commandListConfiguration() let inspection: CommandListInspection | undefined - // The same save-start snapshot keeps its global layer: the - // rollback below distinguishes an absent Global layer from an - // empty one and computes this save's delta against it — the - // layer the write below actually targets — and re-reading here - // would give the rollback a configuration state the scope read - // never saw. + // The rollback needs this snapshot's global layer: it + // distinguishes an absent layer from an empty one, and the + // delta is computed against the layer the write targets. let globalLayerAtSaveStart: string[] | undefined let inspectionFailure: string | undefined try { @@ -855,10 +844,8 @@ export const webviewMessageHandler = async ( } if (inspection === undefined) { // No snapshot: the workspace layer could only be guessed - // at, and a guessed-empty layer re-copies workspace entries - // into global settings, so this key's save is abandoned - // while the remaining keys of the payload persist normally. - // The abandoned key still reports through the save result. + // at, so this key's save is abandoned. The other keys + // persist, and this key reports through the save result. vscode.window.showErrorMessage( `Failed to save ${key}: ${inspectionFailure ?? "the configuration value could not be read"}`, ) @@ -868,28 +855,22 @@ export const webviewMessageHandler = async ( const currentScopes = readCommandListScopes(key, getGlobalState(key), inspection) - // The compensation's delta baseline: the global layer of the same - // save-start snapshot — the configuration the global write below - // targets — sanitized the way every command-list read sanitizes it. - // The extension state copy (`currentScopes.global`) is a separate - // cache that can hold a different list, and a delta computed - // against it would restore that stale list over the entries a - // rolled-back save actually wrote over in the configuration. + // The compensation's delta baseline: the snapshot's global layer — + // the configuration the global write targets. The state copy is a + // separate cache; a delta against it would restore a stale list + // over entries the rolled-back save replaced in the configuration. const configGlobalAtSaveStart = readCommandListScopes( key, globalLayerAtSaveStart, inspection, ).global - // Shadowing is cross-directional, so the hidden-entry set - // needs the opposite key's global layer as input. It comes - // from the save-start snapshot, not a fresh read: an - // earlier iteration of this loop may already have written - // that key. The layer only feeds the hidden-entry mechanism - // below — additive preservation, external-addition - // classification, and the split's promotion filter — - // and never this key's target or rollback, which stay - // on the per-key configuration snapshot. + // Shadowing spans both directions, so the hidden-entry set + // needs the opposite key's global layer. Take it from the + // save-start snapshot, not a fresh read: an earlier loop + // iteration may already have written that key. The layer + // feeds only the hidden-entry mechanism, never this key's + // target or rollback. const otherKey = key === "allowedCommands" ? "deniedCommands" : "allowedCommands" const otherScopes = readCommandListScopes(otherKey, commandListGlobalsAtSaveStart[otherKey]) const { hiddenWorkspaceAllow, hiddenWorkspaceDeny } = resolveEffectiveCommandLists( @@ -897,35 +878,27 @@ export const webviewMessageHandler = async ( key === "deniedCommands" ? currentScopes : otherScopes, workspaceCommandListsEnabled(), ) - // Entries hidden from the dialog — while the gate is off, - // or shadowed by a global entry with it on — cannot be - // deleted through a list that never displayed them, so a - // save re-adds them to the workspace layer it rewrites. - // Users remove those directly in the workspace settings - // file. + // Hidden entries — gate off, or shadowed by a global + // entry — were never displayed. A list cannot delete what + // it never showed, so a save re-adds them to the workspace + // layer it rewrites. Remove them in the settings file. const hiddenWorkspaceEntries = key === "allowedCommands" ? hiddenWorkspaceAllow : hiddenWorkspaceDeny - // An entry the settings file gained while the dialog was open has - // the same shape as an entry the user deleted: present in the file, - // absent from the submitted list. Only the dialog's last-displayed - // baseline separates the two, so file entries outside that baseline - // are re-admitted before the split (deletions of baseline entries - // still apply). Hidden entries never appear in that baseline, yet - // the workspace-layer re-add below preserves them, so classifying - // them as external additions would repeat a false "settings file - // changed" warning on every save. That exclusion only speaks for - // entries whose save-start provenance is the hidden workspace - // layer: an entry the configuration's own global layer holds is - // displayed global knowledge, and excluding it would delete the - // user's file addition. A sender that shows no lists - // sends no baseline, and its submitted list is written - // unclassified. The union covers every layer that can hold an - // entry at save start: the extension-state global copy is not - // refreshed when the settings file is edited directly, so an - // entry only the configuration's own global layer holds would be - // invisible to a union of the state copy and the workspace layer, - // and the global write below would delete it from the user file. + // A file entry the dialog never showed looks like a user + // deletion: in the file, absent from the submitted list. The + // last-displayed baseline separates them, so file entries + // outside it are re-admitted before the split; deleting a + // baseline entry still applies. Hidden entries are excluded: + // the workspace re-add below preserves them, so calling them + // external additions would warn on every save. The exclusion + // covers only entries the hidden workspace layer held; an + // entry in the configuration's global layer is displayed, and + // excluding it would delete the user's file addition. A sender + // with no baseline writes its list unclassified. The union + // spans every layer that can hold an entry at save start: the + // state copy lags direct file edits, so a config-only entry + // must still be visible to the classifier. const baseline = message.commandListBaseline?.[key] const externallyAdded = Array.isArray(baseline) ? [ @@ -942,27 +915,18 @@ export const webviewMessageHandler = async ( configGlobalAtSaveStart.includes(entry)), ) : [] - // An entry the settings file lost while the dialog was open is - // still in the submitted list, and with no layer holding it - // anymore the split below would classify it as brand-new - // knowledge and promote a project entry into the global layer. - // The baseline separates that from a user addition: a baseline - // entry was displayed, so submitting it signals retention, not - // newness — a retained entry that no layer still holds was - // removed in the file, and external removal wins over the stale - // dialog buffer, mirroring how the external-addition re-admit - // above lets the file win over a stale deletion. "No layer" - // means the configuration layers the writes target: they alone - // can disprove a removal, because the extension-state copy is - // never refreshed when the settings file is edited directly and - // so can hold an entry the file has deleted just as it can miss - // one the file has gained. The state copy is still retention - // evidence where the configuration has no global layer at all: - // an absent layer is no file that could have deleted anything, - // and the entries the copy holds from the activation seed (the - // built-in defaults, before this list was ever saved) would - // otherwise vanish from every layer on the first save. Entries - // absent from the baseline keep their promotion path untouched. + // A file-deleted entry is still in the submitted list. With + // no layer holding it, the split would treat it as brand-new + // and promote a project entry into the global layer. The + // baseline separates that from a user addition: submitting a + // displayed entry signals retention, and a retained entry no + // configuration layer holds was removed in the file — the + // file wins over the stale dialog buffer. Only the + // configuration layers can disprove a removal: the state + // copy lags direct file edits. The state copy still counts + // where the configuration has no global layer at all — an + // absent layer deleted nothing, and activation-seeded + // defaults would otherwise vanish on the first save. const splitSourceEntries = Array.isArray(baseline) ? [...incoming, ...externallyAdded].filter( (entry) => @@ -972,15 +936,12 @@ export const webviewMessageHandler = async ( (currentScopes.global.includes(entry) && globalLayerAtSaveStart === undefined), ) : [...incoming, ...externallyAdded] - // The baseline also carries the gate as the dialog last displayed - // it. When the gate flipped since, the hidden set can hold - // entries the user did see, and an entry the dialog displayed is - // existing workspace knowledge: keeping it must stay a workspace - // decision, not a brand-new promotion into the global layer. - // Entries hidden by shadowing (or by a gate state the baseline - // already reflects) are absent from the baseline, so their - // promotion behavior is unchanged. A baseline without the gate - // slot predates it and keeps the current classification. + // The baseline carries the gate as the dialog displayed it. + // If the gate flipped since, the hidden set can hold entries + // the user did see; keeping a displayed entry must stay a + // workspace decision, not a promotion into the global layer. + // A baseline without the gate slot keeps the current + // classification. const gateAtDisplay = message.commandListBaseline?.workspaceCommandListsEnabled const promotionHiddenEntries = gateAtDisplay === undefined || gateAtDisplay === workspaceCommandListsEnabled() @@ -990,19 +951,17 @@ export const webviewMessageHandler = async ( ) const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( splitSourceEntries, - // Hidden entries are not existing knowledge for promotion - // purposes: the dialog never displayed them, so an entry the - // user just added is new even when the workspace layer - // already holds it hidden — except entries the baseline - // shows the dialog did display. The re-add below restores - // the hidden entries this reduced layer drops. + // Hidden entries are not existing knowledge: the dialog + // never displayed them, so a submitted entry the user just + // added is new even when the workspace layer holds it + // hidden. Entries the baseline shows displayed are the + // exception; the re-add below restores dropped hidden + // entries. currentScopes.workspace.filter((entry) => !promotionHiddenEntries.includes(entry)), - // The global origin set decides which kept entries the Global - // write preserves, so it covers the same configuration layer - // as the retained-entry filter above: only the - // configuration's own global layer is evidence of existing - // global knowledge, because the extension-state copy is not - // refreshed when the settings file is edited directly. + // The global origin set must match the retained-entry + // filter: only the configuration's own global layer proves + // existing global knowledge, because the state copy lags + // direct file edits. configGlobalAtSaveStart, ) @@ -1023,38 +982,29 @@ export const webviewMessageHandler = async ( ] const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) - // The two configuration writes below are not atomic, so their - // order is chosen against the composed enforcement set — the set - // union of the layers: the global layer is written first, so a - // save interrupted between the writes can only leave an entry - // duplicated across the layers (inert under the union, no - // approval outcome differs), never absent from both. A failed - // global write changes nothing and needs no compensation; only a - // failed workspace write leaves the global layer holding this - // save's value, and that half is undone below. + // The two configuration writes are not atomic. Global is + // written first: an interrupted save can only duplicate an + // entry across layers (inert under the enforcement union), + // never lose it. A failed global write changes nothing; a + // failed workspace write is undone below. let globalWriteApplied = false try { await config.update(key, globalWrite, vscode.ConfigurationTarget.Global) globalWriteApplied = true - // Then the workspace layer, at the target that owns it. When - // no workspace layer exists the write is skipped entirely so - // saving never materializes one; when entries were deleted - // the `[]` write clears them at that scope. + // The workspace layer, at the target that owns it. With no + // workspace layer the write is skipped, so saving never + // materializes one; deletions clear it with `[]`. if (workspaceTarget !== undefined) { await config.update(key, workspaceWrite, workspaceTarget) } } catch (error) { const failure = error instanceof Error ? error.message : String(error) - // Only a failed workspace write leaves a changed layer, and - // only the global one changed. The compensation undoes - // exactly this save's delta — removing the entries it added - // to the global layer and restoring the ones it deleted — - // against a fresh read, so entries a third party added to - // that layer mid-save survive. A whole-snapshot rewind - // would clobber them, and the configuration API offers no - // compare-and-set to make that safe. + // Undo exactly this save's global delta, against a fresh + // read, so entries a third party added mid-save survive. + // A snapshot rewind would clobber them; the configuration + // API offers no compare-and-set. if (globalWriteApplied) { const addedByThisSave = globalWrite.filter( (entry) => !configGlobalAtSaveStart.includes(entry), @@ -1062,22 +1012,14 @@ export const webviewMessageHandler = async ( const removedByThisSave = configGlobalAtSaveStart.filter( (entry) => !globalWrite.includes(entry), ) - // The re-read is guarded: when even the read fails there - // is nothing safe to write, and falling back to the - // save-start value is the clobber this compensation - // exists to avoid. An undo that would empty a layer that - // is absent clears the key instead: the configuration - // distinguishes `[]` from absent, and the activation seed - // treats `[]` as an override, so writing `[]` where no - // value existed would suppress the default lists after a - // rolled-back save. What the rollback must respect is whose - // presence the layer holds: a layer the re-read finds holding - // something other than this save's own write came about - // through another writer's decision (or predates the save), - // and its explicit `[]` override must survive this undo; a - // layer still holding exactly this save's write over an - // absent start is the half-applied save itself, so its - // absence is what the rollback restores. + // A failed re-read means nothing is safe to write: the + // save-start fallback is the clobber this path avoids. + // An undo that would empty an absent layer clears the key + // instead of writing `[]`, which the activation seed + // honors as the user's override. Respect whose decision + // the layer holds: another writer's `[]` survives; a layer + // holding only this save's own write over an absent start + // is the half-applied save, so its absence is restored. let freshGlobalValue: string[] | undefined try { freshGlobalValue = config.inspect(key)?.globalValue @@ -1129,23 +1071,19 @@ export const webviewMessageHandler = async ( } } - // Only this key's save is abandoned; the remaining keys of the - // payload persist normally, and the abandoned key reports - // through the save result without re-raising the failure. + // Abandon only this key; the other keys persist, and this + // key reports through the save result without re-raising. vscode.window.showErrorMessage(`Failed to save ${key}: ${failure}`) commandListSaveFailed = true continue } - // Extension global state keeps only the global layer: - // enforcement re-adds the workspace layer through - // readCommandListScopes, so storing the merged list here - // would double-home workspace entries and re-leak them on the - // next save. + // Extension state keeps only the global layer: enforcement + // re-adds the workspace layer, so storing the merged list here + // would double-home workspace entries and re-leak them. newValue = globalWrite - // Accumulated only after both configuration writes succeeded: the - // disclosure must not claim preservation for a key whose save was - // abandoned by a failed write. + // Accumulate only after both writes succeeded: the disclosure + // must not name a key whose save was abandoned. externallyAddedCommandEntries.push(...externallyAdded) } else if (key === "allowedReadFiles" || key === "allowedWriteFiles") { const patterns = value ?? [] diff --git a/src/extension.ts b/src/extension.ts index 3ed27f80cc..f1bf468eef 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -170,27 +170,20 @@ export async function activate(context: vscode.ExtensionContext) { // Initialize Zoo Code auth service for extension session token management. await initZooCodeAuth(context) - // Seed before the terminal registry is initialized: a rejected seed must - // abort activation while the registry holds no resources, because its - // listeners are released only by `deactivate()`, which the host does not - // guarantee after a failed activation. - // Each list key carries its own first-run guard, so a profile whose - // allowlist was seeded by an earlier version still gets the deny-list - // migration on the next activation. + // Seed before the terminal registry initializes: the host may skip + // `deactivate()` after a failed activation, and only it releases the + // registry's listeners. + // Each key has its own first-run guard, so a profile seeded by an earlier + // version still gets the deny-list migration. try { await seedCommandList(context.globalState, "allowedCommands") await seedCommandList(context.globalState, "deniedCommands") } catch (error) { - // Activation aborts here, and `deactivate()` is not guaranteed to run - // afterward, so this catch performs its own teardown before rethrowing: - // shut down the telemetry client registered above, clear the - // persistence trace sink, and dispose the output channel — in reverse - // of the order those three were acquired (the output channel was - // first), each step run only after the previous one settles. - // Teardown failures are logged or dropped, never rethrown, so they - // cannot mask the seed rejection; the telemetry service bounds its own - // drain and client-flush phases, so a stuck client cannot hang the - // host here. + // The host may skip `deactivate()`, so this catch tears down before + // rethrowing: telemetry shutdown, then trace-sink clear, then channel + // dispose — reverse acquisition order, each step awaited. Teardown + // failures are logged or dropped, never rethrown. Telemetry shutdown + // is bounded, so a stuck client cannot hang activation here. try { await telemetryService.shutdown() } catch (shutdownError) { @@ -198,16 +191,11 @@ export async function activate(context: vscode.ExtensionContext) { `Failed to shut down telemetry service: ${shutdownError instanceof Error ? shutdownError.message : String(shutdownError)}`, ) } - // The persistence trace sink installed above writes its lines through - // the output channel, so it is cleared — passing undefined restores the - // default console sink — before the channel is disposed, keeping any - // later trace event (such as a deactivate() shutdown trace) from - // writing into a disposed channel. + // The trace sink logs through the output channel, so clear it first: + // undefined restores the default console sink. setPersistenceTraceSink(undefined) - // The channel is disposed after every step that logs through it, so no - // teardown log is written to an already-dead channel. Once it is gone, - // no extension output sink is left to report a failed dispose to; the - // error is deliberately dropped rather than routed to the console. + // Dispose the channel last: earlier teardown steps log through it. + // A failed dispose has no sink left to report to, so it is dropped. try { outputChannel.dispose() } catch { diff --git a/src/package.nls.ca.json b/src/package.nls.ca.json index 77f5d530fe..a9eb6ed6bd 100644 --- a/src/package.nls.ca.json +++ b/src/package.nls.ca.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Com resol Zoo l'arrel de l'espai de treball en un espai de treball multi-arrel. L'arrel s'utilitza per localitzar `.roomodes`, `.roo/mcp.json`, `.roo/rules/` i altra configuració d'àmbit de projecte. Canviar aquest paràmetre només afecta les cerques futures; les tasques en execució conserven la seva arrel original.", "settings.workspace.rootResolution.activeEditor.description": "Utilitza la carpeta de l'espai de treball que conté l'editor actiu; recorre a la primera carpeta de l'espai de treball. (Per defecte — conserva el comportament heretat.)", "settings.workspace.rootResolution.firstFolder.description": "Utilitza sempre la primera carpeta de l'espai de treball (workspaceFolders[0]). Determinista — independent del fitxer que tingui el focus en aquest moment.", - "settings.workspaceCommandListsEnabled.description": "Activa les llistes de comandes aportades pels ajustos de l'espai de treball (els valors de `zoo-code.allowedCommands` i `zoo-code.deniedCommands` als fitxers d'ajustos de l'espai de treball). Mentre estigui desactivada, les llistes de comandes de l'espai de treball no tenen cap efecte. Quan estigui activada, les entrades de nivell d'usuari tenen preferència: una entrada de nivell d'usuari decideix qualsevol comanda que coincideixi, i les entrades de l'espai de treball només s'apliquen a les comandes amb què cap entrada de nivell d'usuari no coincideix. Aquest paràmetre només es pot canviar als [paràmetres d'usuari](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Activa les llistes de comandes aportades pels ajustos de l'espai de treball (els valors de `zoo-code.allowedCommands` i `zoo-code.deniedCommands` als fitxers d'ajustos de l'espai de treball). Mentre estigui desactivada, les llistes de comandes de l'espai de treball no tenen cap efecte. Això inclou les comandes denegades desades al repositori. Quan estigui activada, les entrades de nivell d'usuari tenen preferència: una entrada de nivell d'usuari decideix qualsevol comanda que coincideixi, i les entrades de l'espai de treball només s'apliquen a les comandes amb què cap entrada de nivell d'usuari no coincideix. Aquest paràmetre només es pot canviar als [paràmetres d'usuari](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.de.json b/src/package.nls.de.json index d74eed6998..62cd8af031 100644 --- a/src/package.nls.de.json +++ b/src/package.nls.de.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Wie Zoo das Workspace-Stammverzeichnis in einem Multi-Root-Workspace auflöst. Das Stammverzeichnis wird verwendet, um `.roomodes`, `.roo/mcp.json`, `.roo/rules/` und andere projektbezogene Konfiguration zu finden. Eine Änderung dieser Einstellung wirkt sich nur auf zukünftige Suchen aus; laufende Aufgaben behalten ihr ursprüngliches Stammverzeichnis.", "settings.workspace.rootResolution.activeEditor.description": "Verwende den Workspace-Ordner, der den aktiven Editor enthält; greife auf den ersten Workspace-Ordner zurück. (Standard – behält das bisherige Verhalten bei.)", "settings.workspace.rootResolution.firstFolder.description": "Verwende immer den ersten Workspace-Ordner (workspaceFolders[0]). Deterministisch – unabhängig davon, welche Datei gerade fokussiert ist.", - "settings.workspaceCommandListsEnabled.description": "Aktiviert die von Workspace-Einstellungen beigesteuerten Befehlslisten (die Werte von `zoo-code.allowedCommands` und `zoo-code.deniedCommands` in Workspace-Einstellungsdateien). Solange deaktiviert, haben Workspace-Befehlslisten keine Auswirkung. Wenn aktiviert, haben Einträge auf Benutzerebene Vorrang: Ein Eintrag auf Benutzerebene entscheidet über jeden Befehl, mit dem er übereinstimmt, und Workspace-Einträge gelten nur für Befehle, mit denen kein Eintrag auf Benutzerebene übereinstimmt. Diese Einstellung kann nur in den [Benutzereinstellungen](https://code.visualstudio.com/docs/getstarted/settings) geändert werden." + "settings.workspaceCommandListsEnabled.description": "Aktiviert die von Workspace-Einstellungen beigesteuerten Befehlslisten (die Werte von `zoo-code.allowedCommands` und `zoo-code.deniedCommands` in Workspace-Einstellungsdateien). Solange deaktiviert, haben Workspace-Befehlslisten keine Auswirkung. Dies gilt auch für abgelehnte Befehle im Repository. Wenn aktiviert, haben Einträge auf Benutzerebene Vorrang: Ein Eintrag auf Benutzerebene entscheidet über jeden Befehl, mit dem er übereinstimmt, und Workspace-Einträge gelten nur für Befehle, mit denen kein Eintrag auf Benutzerebene übereinstimmt. Diese Einstellung kann nur in den [Benutzereinstellungen](https://code.visualstudio.com/docs/getstarted/settings) geändert werden." } diff --git a/src/package.nls.es.json b/src/package.nls.es.json index e2762d26be..2e5be53518 100644 --- a/src/package.nls.es.json +++ b/src/package.nls.es.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Cómo resuelve Zoo la raíz del espacio de trabajo en un espacio de trabajo multi-raíz. La raíz se usa para localizar `.roomodes`, `.roo/mcp.json`, `.roo/rules/` y otra configuración del ámbito del proyecto. Cambiar este ajuste solo afecta a las búsquedas futuras; las tareas en ejecución conservan su raíz original.", "settings.workspace.rootResolution.activeEditor.description": "Usa la carpeta del espacio de trabajo que contiene el editor activo; recurre a la primera carpeta del espacio de trabajo. (Predeterminado: conserva el comportamiento heredado.)", "settings.workspace.rootResolution.firstFolder.description": "Usa siempre la primera carpeta del espacio de trabajo (workspaceFolders[0]). Determinista: independiente del archivo que tenga el foco en ese momento.", - "settings.workspaceCommandListsEnabled.description": "Habilita las listas de comandos aportadas por la configuración del espacio de trabajo (los valores de `zoo-code.allowedCommands` y `zoo-code.deniedCommands` en los archivos de configuración del espacio de trabajo). Mientras esté deshabilitada, las listas de comandos del espacio de trabajo no tienen ningún efecto. Cuando esté habilitada, las entradas de nivel de usuario tienen prioridad: una entrada de nivel de usuario decide cualquier comando que coincida, y las entradas del espacio de trabajo solo se aplican a los comandos con los que ninguna entrada de nivel de usuario coincide. Este ajuste solo se puede cambiar en la [configuración de usuario](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Habilita las listas de comandos aportadas por la configuración del espacio de trabajo (los valores de `zoo-code.allowedCommands` y `zoo-code.deniedCommands` en los archivos de configuración del espacio de trabajo). Mientras esté deshabilitada, las listas de comandos del espacio de trabajo no tienen ningún efecto. Esto incluye los comandos denegados guardados en el repositorio. Cuando esté habilitada, las entradas de nivel de usuario tienen prioridad: una entrada de nivel de usuario decide cualquier comando que coincida, y las entradas del espacio de trabajo solo se aplican a los comandos con los que ninguna entrada de nivel de usuario coincide. Este ajuste solo se puede cambiar en la [configuración de usuario](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.fr.json b/src/package.nls.fr.json index e3d28cfcd3..61141cce16 100644 --- a/src/package.nls.fr.json +++ b/src/package.nls.fr.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Comment Zoo résout la racine de l'espace de travail dans un espace de travail multi-racine. La racine sert à localiser `.roomodes`, `.roo/mcp.json`, `.roo/rules/` et d'autres configurations propres au projet. Modifier ce paramètre n'affecte que les recherches futures ; les tâches en cours conservent leur racine d'origine.", "settings.workspace.rootResolution.activeEditor.description": "Utilise le dossier de l'espace de travail contenant l'éditeur actif ; revient au premier dossier de l'espace de travail. (Par défaut — conserve le comportement hérité.)", "settings.workspace.rootResolution.firstFolder.description": "Utilise toujours le premier dossier de l'espace de travail (workspaceFolders[0]). Déterministe — indépendant du fichier actuellement ciblé.", - "settings.workspaceCommandListsEnabled.description": "Active les listes de commandes issues des paramètres de l'espace de travail (les valeurs de `zoo-code.allowedCommands` et `zoo-code.deniedCommands` dans les fichiers de paramètres de l'espace de travail). Lorsqu'elle est désactivée, les listes de commandes de l'espace de travail n'ont aucun effet. Lorsqu'elle est activée, les entrées de niveau utilisateur ont la priorité : une entrée de niveau utilisateur décide de toute commande à laquelle elle correspond, et les entrées de l'espace de travail ne s'appliquent qu'aux commandes pour lesquelles aucune entrée de niveau utilisateur ne correspond. Ce paramètre ne peut être modifié que dans les [paramètres utilisateur](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Active les listes de commandes issues des paramètres de l'espace de travail (les valeurs de `zoo-code.allowedCommands` et `zoo-code.deniedCommands` dans les fichiers de paramètres de l'espace de travail). Lorsqu'elle est désactivée, les listes de commandes de l'espace de travail n'ont aucun effet. Cela inclut les commandes refusées enregistrées dans le dépôt. Lorsqu'elle est activée, les entrées de niveau utilisateur ont la priorité : une entrée de niveau utilisateur décide de toute commande à laquelle elle correspond, et les entrées de l'espace de travail ne s'appliquent qu'aux commandes pour lesquelles aucune entrée de niveau utilisateur ne correspond. Ce paramètre ne peut être modifié que dans les [paramètres utilisateur](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.hi.json b/src/package.nls.hi.json index 74ce2fd37a..fbcb85049a 100644 --- a/src/package.nls.hi.json +++ b/src/package.nls.hi.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Multi-root workspace में Zoo workspace root को कैसे resolve करता है। Root का इस्तेमाल `.roomodes`, `.roo/mcp.json`, `.roo/rules/` और दूसरी project-scoped configuration ढूंढने के लिए होता है। इस setting को बदलने का असर सिर्फ आगे की lookups पर पड़ता है; चल रहे tasks अपना original root बनाए रखते हैं।", "settings.workspace.rootResolution.activeEditor.description": "उस workspace folder का इस्तेमाल करो जिसमें active editor है; पहले workspace folder पर fall back करो। (Default — legacy behavior बनाए रखता है।)", "settings.workspace.rootResolution.firstFolder.description": "हमेशा पहले workspace folder (workspaceFolders[0]) का इस्तेमाल करो। Deterministic — इस बात से स्वतंत्र कि अभी कौन सी file focused है।", - "settings.workspaceCommandListsEnabled.description": "Workspace settings द्वारा दी गई command lists को सक्रिय करো (workspace settings files में `zoo-code.allowedCommands` और `zoo-code.deniedCommands` के मान)। जब तक इह निष्क्रिय है, workspace command lists का कौनो प्रभाव नाहीं होतै। सक्रिय करतै पर user-level entries कौ प्राथमिकत मिलतै है: हर user-level entry उन सब्ह commands कौ तय करतै है जिनसै वह मेल खातै है, अऊर workspace entries केवल उन commands पर लागू होतै हैं जिनसै कौनो user-level entry मेल नाहीं खातै। इस setting कौ केवल [user settings](https://code.visualstudio.com/docs/getstarted/settings) में बदल जा सकतै है।" + "settings.workspaceCommandListsEnabled.description": "Workspace settings द्वारा दी गई command lists को सक्रिय करো (workspace settings files में `zoo-code.allowedCommands` और `zoo-code.deniedCommands` के मान)। जब तक इह निष्क्रिय है, workspace command lists का कौनो प्रभाव नाहीं होतै। इसमें repository में रखी गई denied commands भी शामिल हैं। सक्रिय करतै पर user-level entries कौ प्राथमिकत मिलतै है: हर user-level entry उन सब्ह commands कौ तय करतै है जिनसै वह मेल खातै है, अऊर workspace entries केवल उन commands पर लागू होतै हैं जिनसै कौनो user-level entry मेल नाहीं खातै। इस setting कौ केवल [user settings](https://code.visualstudio.com/docs/getstarted/settings) में बदल जा सकतै है।" } diff --git a/src/package.nls.id.json b/src/package.nls.id.json index 2e5d084ae8..a0fd29ce0e 100644 --- a/src/package.nls.id.json +++ b/src/package.nls.id.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Bagaimana Zoo menentukan root workspace di workspace multi-root. Root digunakan untuk menemukan `.roomodes`, `.roo/mcp.json`, `.roo/rules/`, dan konfigurasi lain yang bersifat project-scoped. Mengubah pengaturan ini hanya memengaruhi pencarian berikutnya; task yang sedang berjalan tetap memakai root aslinya.", "settings.workspace.rootResolution.activeEditor.description": "Gunakan folder workspace yang berisi editor aktif; kembali ke folder workspace pertama. (Default — mempertahankan perilaku lama.)", "settings.workspace.rootResolution.firstFolder.description": "Selalu gunakan folder workspace pertama (workspaceFolders[0]). Deterministik — tidak bergantung pada file mana yang sedang difokuskan.", - "settings.workspaceCommandListsEnabled.description": "Aktifkan daftar perintah yang disediakan oleh pengaturan workspace (nilai `zoo-code.allowedCommands` dan `zoo-code.deniedCommands` di file pengaturan workspace). Saat dinonaktifkan, daftar perintah workspace tidak memiliki efek apa pun. Saat diaktifkan, entri level pengguna lebih diutamakan: entri level pengguna menentukan perintah mana pun yang cocok dengannya, dan entri workspace hanya berlaku untuk perintah yang tidak cocok dengan entri level pengguna mana pun. Pengaturan ini hanya dapat diubah di [pengaturan pengguna](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Aktifkan daftar perintah yang disediakan oleh pengaturan workspace (nilai `zoo-code.allowedCommands` dan `zoo-code.deniedCommands` di file pengaturan workspace). Saat dinonaktifkan, daftar perintah workspace tidak memiliki efek apa pun. Ini mencakup perintah yang ditolak yang disimpan di repositori. Saat diaktifkan, entri level pengguna lebih diutamakan: entri level pengguna menentukan perintah mana pun yang cocok dengannya, dan entri workspace hanya berlaku untuk perintah yang tidak cocok dengan entri level pengguna mana pun. Pengaturan ini hanya dapat diubah di [pengaturan pengguna](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.it.json b/src/package.nls.it.json index 6ec6801fc4..ec2f47924b 100644 --- a/src/package.nls.it.json +++ b/src/package.nls.it.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Come Zoo determina la radice del workspace in un workspace multi-radice. La radice viene usata per individuare `.roomodes`, `.roo/mcp.json`, `.roo/rules/` e altra configurazione a livello di progetto. Modificare questa impostazione influisce solo sulle ricerche future; i task in esecuzione mantengono la loro radice originale.", "settings.workspace.rootResolution.activeEditor.description": "Usa la cartella del workspace che contiene l'editor attivo; ripiega sulla prima cartella del workspace. (Predefinito — mantiene il comportamento legacy.)", "settings.workspace.rootResolution.firstFolder.description": "Usa sempre la prima cartella del workspace (workspaceFolders[0]). Deterministico — indipendente dal file attualmente attivo.", - "settings.workspaceCommandListsEnabled.description": "Abilita gli elenchi di comandi forniti dalle impostazioni del workspace (i valori di `zoo-code.allowedCommands` e `zoo-code.deniedCommands` nei file delle impostazioni del workspace). Finché è disabilitata, gli elenchi di comandi del workspace non hanno alcun effetto. Quando è abilitata, le voci a livello utente hanno la precedenza: una voce a livello utente decide qualsiasi comando con cui corrisponde, e le voci del workspace si applicano solo ai comandi con cui nessuna voce a livello utente corrisponde. Questa impostazione può essere modificata solo nelle [impostazioni utente](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Abilita gli elenchi di comandi forniti dalle impostazioni del workspace (i valori di `zoo-code.allowedCommands` e `zoo-code.deniedCommands` nei file delle impostazioni del workspace). Finché è disabilitata, gli elenchi di comandi del workspace non hanno alcun effetto. Ciò include i comandi negati salvati nel repository. Quando è abilitata, le voci a livello utente hanno la precedenza: una voce a livello utente decide qualsiasi comando con cui corrisponde, e le voci del workspace si applicano solo ai comandi con cui nessuna voce a livello utente corrisponde. Questa impostazione può essere modificata solo nelle [impostazioni utente](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.ja.json b/src/package.nls.ja.json index 8c48c277e0..f36a306cf8 100644 --- a/src/package.nls.ja.json +++ b/src/package.nls.ja.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "マルチルートワークスペースで Zoo がワークスペースルートをどのように解決するか。ルートは `.roomodes`、`.roo/mcp.json`、`.roo/rules/` などのプロジェクト単位の設定を見つけるために使われます。この設定の変更は今後の検索にのみ影響し、実行中のタスクは元のルートを保持します。", "settings.workspace.rootResolution.activeEditor.description": "アクティブなエディタを含むワークスペースフォルダを使用し、最初のワークスペースフォルダにフォールバックします。(デフォルト — 従来の動作を維持します。)", "settings.workspace.rootResolution.firstFolder.description": "常に最初のワークスペースフォルダ(workspaceFolders[0])を使用します。決定的で、現在フォーカスされているファイルに依存しません。", - "settings.workspaceCommandListsEnabled.description": "ワークスペース設定が提供するコマンドリスト(ワークスペースの設定ファイル内の `zoo-code.allowedCommands` と `zoo-code.deniedCommands` の値)を有効にします。無効の間は、ワークスペースのコマンドリストは効果を持ちません。有効にすると、ユーザーレベルのエントリが優先されます。ユーザーレベルのエントリは、一致するコマンドをすべて決定し、ワークスペースのエントリはユーザーレベルのエントリが一致しないコマンドにのみ適用されます。この設定は[ユーザー設定](https://code.visualstudio.com/docs/getstarted/settings)でのみ変更できます。" + "settings.workspaceCommandListsEnabled.description": "ワークスペース設定が提供するコマンドリスト(ワークスペースの設定ファイル内の `zoo-code.allowedCommands` と `zoo-code.deniedCommands` の値)を有効にします。無効の間は、ワークスペースのコマンドリストは効果を持ちません。これには、リポジトリに保存された拒否コマンドも含まれます。有効にすると、ユーザーレベルのエントリが優先されます。ユーザーレベルのエントリは、一致するコマンドをすべて決定し、ワークスペースのエントリはユーザーレベルのエントリが一致しないコマンドにのみ適用されます。この設定は[ユーザー設定](https://code.visualstudio.com/docs/getstarted/settings)でのみ変更できます。" } diff --git a/src/package.nls.json b/src/package.nls.json index 3d5a7caa33..07169f6d37 100644 --- a/src/package.nls.json +++ b/src/package.nls.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "How Zoo resolves the workspace root in a multi-root workspace. The root is used to locate `.roomodes`, `.roo/mcp.json`, `.roo/rules/`, and other project-scoped configuration. Changing this setting only affects future lookups; running tasks keep their original root.", "settings.workspace.rootResolution.activeEditor.description": "Use the workspace folder containing the active editor; fall back to the first workspace folder. (Default — preserves legacy behavior.)", "settings.workspace.rootResolution.firstFolder.description": "Always use the first workspace folder (workspaceFolders[0]). Deterministic — independent of which file is currently focused.", - "settings.workspaceCommandListsEnabled.description": "Enable command lists contributed by workspace settings (`zoo-code.allowedCommands` and `zoo-code.deniedCommands` values in workspace settings files). While disabled, workspace command lists have no effect. When enabled, user-level entries take precedence: a user-level entry decides any command it matches, and workspace entries only apply to commands no user-level entry matches. This setting can only be changed in [user settings](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Enable command lists contributed by workspace settings (`zoo-code.allowedCommands` and `zoo-code.deniedCommands` values in workspace settings files). While disabled, workspace command lists have no effect. This includes denied commands stored in the repository. When enabled, user-level entries take precedence: a user-level entry decides any command it matches, and workspace entries only apply to commands no user-level entry matches. This setting can only be changed in [user settings](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.ko.json b/src/package.nls.ko.json index 7546304047..45311d6568 100644 --- a/src/package.nls.ko.json +++ b/src/package.nls.ko.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "멀티 루트 워크스페이스에서 Zoo가 워크스페이스 루트를 어떻게 결정하는지 설정합니다. 루트는 `.roomodes`, `.roo/mcp.json`, `.roo/rules/` 및 기타 프로젝트 범위 구성을 찾는 데 사용됩니다. 이 설정을 변경해도 이후의 조회에만 영향을 주며, 실행 중인 작업은 원래 루트를 유지합니다.", "settings.workspace.rootResolution.activeEditor.description": "활성 편집기가 있는 워크스페이스 폴더를 사용하고, 첫 번째 워크스페이스 폴더로 폴백합니다. (기본값 — 기존 동작을 유지합니다.)", "settings.workspace.rootResolution.firstFolder.description": "항상 첫 번째 워크스페이스 폴더(workspaceFolders[0])를 사용합니다. 결정적이며, 현재 포커스된 파일과 무관합니다.", - "settings.workspaceCommandListsEnabled.description": "워크스페이스 설정이 제공하는 명령 목록을 활성화합니다(워크스페이스 설정 파일의 `zoo-code.allowedCommands` 및 `zoo-code.deniedCommands` 값). 비활성화된 동안에는 워크스페이스 명령 목록이 효과가 없습니다. 활성화하면 사용자 수준 항목이 우선합니다: 사용자 수준 항목은 자신이 일치시키는 모든 명령을 결정하며, 워크스페이스 항목은 사용자 수준 항목이 일치시키지 않는 명령에만 적용됩니다. 이 설정은 [사용자 설정](https://code.visualstudio.com/docs/getstarted/settings)에서만 변경할 수 있습니다." + "settings.workspaceCommandListsEnabled.description": "워크스페이스 설정이 제공하는 명령 목록을 활성화합니다(워크스페이스 설정 파일의 `zoo-code.allowedCommands` 및 `zoo-code.deniedCommands` 값). 비활성화된 동안에는 워크스페이스 명령 목록이 효과가 없습니다. 여기에는 리포지토리에 저장된 거부된 명령도 포함됩니다. 활성화하면 사용자 수준 항목이 우선합니다: 사용자 수준 항목은 자신이 일치시키는 모든 명령을 결정하며, 워크스페이스 항목은 사용자 수준 항목이 일치시키지 않는 명령에만 적용됩니다. 이 설정은 [사용자 설정](https://code.visualstudio.com/docs/getstarted/settings)에서만 변경할 수 있습니다." } diff --git a/src/package.nls.nl.json b/src/package.nls.nl.json index 46f5eab9bd..c08d2278cc 100644 --- a/src/package.nls.nl.json +++ b/src/package.nls.nl.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Hoe Zoo de workspace-root bepaalt in een multi-root workspace. De root wordt gebruikt om `.roomodes`, `.roo/mcp.json`, `.roo/rules/` en andere project-scoped configuratie te vinden. Deze instelling wijzigen heeft alleen invloed op toekomstige zoekopdrachten; lopende taken behouden hun oorspronkelijke root.", "settings.workspace.rootResolution.activeEditor.description": "Gebruik de workspace-map die de actieve editor bevat; val terug op de eerste workspace-map. (Standaard — behoudt het oude gedrag.)", "settings.workspace.rootResolution.firstFolder.description": "Gebruik altijd de eerste workspace-map (workspaceFolders[0]). Deterministisch — onafhankelijk van welk bestand op dit moment de focus heeft.", - "settings.workspaceCommandListsEnabled.description": "Schakel commandolijsten in die worden bijgedragen door werkruimte-instellingen (de waarden van `zoo-code.allowedCommands` en `zoo-code.deniedCommands` in instellingenbestanden van de werkruimte). Terwijl uitgeschakeld hebben commandolijsten van de werkruimte geen effect. Wanneer ingeschakeld hebben items op gebruikersniveau voorrang: een item op gebruikersniveau beslist elk commando dat ermee overeenkomt, en werkruimte-items zijn alleen van toepassing op commando's waar geen item op gebruikersniveau mee overeenkomt. Deze instelling kan alleen worden gewijzigd in de [gebruikersinstellingen](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Schakel commandolijsten in die worden bijgedragen door werkruimte-instellingen (de waarden van `zoo-code.allowedCommands` en `zoo-code.deniedCommands` in instellingenbestanden van de werkruimte). Terwijl uitgeschakeld hebben commandolijsten van de werkruimte geen effect. Dit geldt ook voor geweigerde commando's in de repository. Wanneer ingeschakeld hebben items op gebruikersniveau voorrang: een item op gebruikersniveau beslist elk commando dat ermee overeenkomt, en werkruimte-items zijn alleen van toepassing op commando's waar geen item op gebruikersniveau mee overeenkomt. Deze instelling kan alleen worden gewijzigd in de [gebruikersinstellingen](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.pl.json b/src/package.nls.pl.json index a6378085f1..027fb01f38 100644 --- a/src/package.nls.pl.json +++ b/src/package.nls.pl.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Jak Zoo ustala katalog główny workspace w workspace z wieloma katalogami głównymi. Katalog główny służy do lokalizowania `.roomodes`, `.roo/mcp.json`, `.roo/rules/` i innej konfiguracji na poziomie projektu. Zmiana tego ustawienia wpływa tylko na przyszłe wyszukiwania; uruchomione zadania zachowują swój pierwotny katalog główny.", "settings.workspace.rootResolution.activeEditor.description": "Użyj folderu workspace zawierającego aktywny edytor; w razie potrzeby wróć do pierwszego folderu workspace. (Domyślnie — zachowuje dotychczasowe zachowanie.)", "settings.workspace.rootResolution.firstFolder.description": "Zawsze używaj pierwszego folderu workspace (workspaceFolders[0]). Deterministyczne — niezależne od tego, który plik jest aktualnie aktywny.", - "settings.workspaceCommandListsEnabled.description": "Włącza listy poleceń dostarczane przez ustawienia workspace (wartości `zoo-code.allowedCommands` i `zoo-code.deniedCommands` w plikach ustawień workspace). Gdy jest wyłączona, listy poleceń workspace nie mają żadnego efektu. Gdy jest włączona, wpisy na poziomie użytkownika mają pierwszeństwo: wpis na poziomie użytkownika rozstrzyga każde polecenie, z którym się dopasuje, a wpisy workspace dotyczą tylko poleceń, z którymi nie dopasuje się żaden wpis na poziomie użytkownika. To ustawienie można zmienić tylko w [ustawieniach użytkownika](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Włącza listy poleceń dostarczane przez ustawienia workspace (wartości `zoo-code.allowedCommands` i `zoo-code.deniedCommands` w plikach ustawień workspace). Gdy jest wyłączona, listy poleceń workspace nie mają żadnego efektu. Dotyczy to także odrzuconych poleceń zapisanych w repozytorium. Gdy jest włączona, wpisy na poziomie użytkownika mają pierwszeństwo: wpis na poziomie użytkownika rozstrzyga każde polecenie, z którym się dopasuje, a wpisy workspace dotyczą tylko poleceń, z którymi nie dopasuje się żaden wpis na poziomie użytkownika. To ustawienie można zmienić tylko w [ustawieniach użytkownika](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.pt-BR.json b/src/package.nls.pt-BR.json index 9824a9fd67..63d95da2ac 100644 --- a/src/package.nls.pt-BR.json +++ b/src/package.nls.pt-BR.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Como o Zoo resolve a raiz do workspace em um workspace multi-raiz. A raiz é usada para localizar `.roomodes`, `.roo/mcp.json`, `.roo/rules/` e outras configurações no escopo do projeto. Alterar esta configuração afeta apenas as buscas futuras; as tarefas em execução mantêm sua raiz original.", "settings.workspace.rootResolution.activeEditor.description": "Usa a pasta do workspace que contém o editor ativo; recorre à primeira pasta do workspace. (Padrão — preserva o comportamento legado.)", "settings.workspace.rootResolution.firstFolder.description": "Usa sempre a primeira pasta do workspace (workspaceFolders[0]). Determinístico — independente de qual arquivo está em foco no momento.", - "settings.workspaceCommandListsEnabled.description": "Ativa as listas de comandos fornecidas pelas configurações do workspace (os valores de `zoo-code.allowedCommands` e `zoo-code.deniedCommands` nos arquivos de configurações do workspace). Enquanto desativada, as listas de comandos do workspace não têm efeito. Quando ativada, as entradas em nível de usuário têm precedência: uma entrada em nível de usuário decide qualquer comando com o qual corresponda, e as entradas do workspace se aplicam apenas a comandos com os quais nenhuma entrada em nível de usuário corresponde. Essa configuração só pode ser alterada nas [configurações de usuário](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Ativa as listas de comandos fornecidas pelas configurações do workspace (os valores de `zoo-code.allowedCommands` e `zoo-code.deniedCommands` nos arquivos de configurações do workspace). Enquanto desativada, as listas de comandos do workspace não têm efeito. Isso inclui os comandos negados armazenados no repositório. Quando ativada, as entradas em nível de usuário têm precedência: uma entrada em nível de usuário decide qualquer comando com o qual corresponda, e as entradas do workspace se aplicam apenas a comandos com os quais nenhuma entrada em nível de usuário corresponde. Essa configuração só pode ser alterada nas [configurações de usuário](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.ru.json b/src/package.nls.ru.json index e3231a3bcf..2e01907ed4 100644 --- a/src/package.nls.ru.json +++ b/src/package.nls.ru.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Как Zoo определяет корень рабочей области в рабочей области с несколькими корнями. Корень используется для поиска `.roomodes`, `.roo/mcp.json`, `.roo/rules/` и другой конфигурации уровня проекта. Изменение этой настройки влияет только на последующие поиски; выполняющиеся задачи сохраняют свой исходный корень.", "settings.workspace.rootResolution.activeEditor.description": "Использовать папку рабочей области, содержащую активный редактор; при необходимости вернуться к первой папке рабочей области. (По умолчанию — сохраняет прежнее поведение.)", "settings.workspace.rootResolution.firstFolder.description": "Всегда использовать первую папку рабочей области (workspaceFolders[0]). Детерминированно — не зависит от того, какой файл сейчас в фокусе.", - "settings.workspaceCommandListsEnabled.description": "Включает списки команд, задаваемые в настройках рабочей области (значения `zoo-code.allowedCommands` и `zoo-code.deniedCommands` в файлах настроек рабочей области). Пока отключено, списки команд рабочей области ни на что не влияют. Когда включено, записи уровня пользователя имеют приоритет: запись уровня пользователя решает любую подошедшую ей команду, а записи рабочей области применяются только к командам, которые не совпали ни с одной записью уровня пользователя. Этот параметр можно изменить только в [настройках пользователя](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Включает списки команд, задаваемые в настройках рабочей области (значения `zoo-code.allowedCommands` и `zoo-code.deniedCommands` в файлах настроек рабочей области). Пока отключено, списки команд рабочей области ни на что не влияют. Сюда входят запрещённые команды, сохранённые в репозитории. Когда включено, записи уровня пользователя имеют приоритет: запись уровня пользователя решает любую подошедшую ей команду, а записи рабочей области применяются только к командам, которые не совпали ни с одной записью уровня пользователя. Этот параметр можно изменить только в [настройках пользователя](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.tr.json b/src/package.nls.tr.json index 25f1df2fc8..06fcc53f02 100644 --- a/src/package.nls.tr.json +++ b/src/package.nls.tr.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Zoo'nun çok köklü bir çalışma alanında çalışma alanı kökünü nasıl belirlediği. Kök; `.roomodes`, `.roo/mcp.json`, `.roo/rules/` ve diğer proje kapsamındaki yapılandırmayı bulmak için kullanılır. Bu ayarı değiştirmek yalnızca sonraki aramaları etkiler; çalışan görevler özgün köklerini korur.", "settings.workspace.rootResolution.activeEditor.description": "Aktif düzenleyiciyi içeren çalışma alanı klasörünü kullan; ilk çalışma alanı klasörüne geri dön. (Varsayılan — eski davranışı korur.)", "settings.workspace.rootResolution.firstFolder.description": "Her zaman ilk çalışma alanı klasörünü (workspaceFolders[0]) kullan. Deterministik — o anda hangi dosyanın odakta olduğundan bağımsız.", - "settings.workspaceCommandListsEnabled.description": "Çalışma alanı ayarlarının sağladığı komut listelerini etkinleştirir (çalışma alanı ayar dosyalarındaki `zoo-code.allowedCommands` ve `zoo-code.deniedCommands` değerleri). Devre dışıyken çalışma alanı komut listelerinin hiçbir etkisi olmaz. Etkinleştirildiğinde kullanıcı düzeyi girdiler önceliklidir: bir kullanıcı düzeyi girdi eşleştiği her komutu kararlaştırır ve çalışma alanı girdileri yalnızca hiçbir kullanıcı düzeyi girdinin eşleşmediği komutlara uygulanır. Bu ayar yalnızca [kullanıcı ayarlarında](https://code.visualstudio.com/docs/getstarted/settings) değiştirilebilir." + "settings.workspaceCommandListsEnabled.description": "Çalışma alanı ayarlarının sağladığı komut listelerini etkinleştirir (çalışma alanı ayar dosyalarındaki `zoo-code.allowedCommands` ve `zoo-code.deniedCommands` değerleri). Devre dışıyken çalışma alanı komut listelerinin hiçbir etkisi olmaz. Bu, depoya kaydedilmiş reddedilen komutları da kapsar. Etkinleştirildiğinde kullanıcı düzeyi girdiler önceliklidir: bir kullanıcı düzeyi girdi eşleştiği her komutu kararlaştırır ve çalışma alanı girdileri yalnızca hiçbir kullanıcı düzeyi girdinin eşleşmediği komutlara uygulanır. Bu ayar yalnızca [kullanıcı ayarlarında](https://code.visualstudio.com/docs/getstarted/settings) değiştirilebilir." } diff --git a/src/package.nls.vi.json b/src/package.nls.vi.json index f8913118c1..ca14317231 100644 --- a/src/package.nls.vi.json +++ b/src/package.nls.vi.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Cách Zoo xác định gốc workspace trong một workspace nhiều gốc. Gốc được dùng để tìm `.roomodes`, `.roo/mcp.json`, `.roo/rules/` và các cấu hình khác ở phạm vi dự án. Thay đổi cài đặt này chỉ ảnh hưởng đến các lần tra cứu về sau; các tác vụ đang chạy vẫn giữ gốc ban đầu của chúng.", "settings.workspace.rootResolution.activeEditor.description": "Dùng thư mục workspace chứa trình soạn thảo đang hoạt động; quay lại thư mục workspace đầu tiên. (Mặc định — giữ nguyên hành vi cũ.)", "settings.workspace.rootResolution.firstFolder.description": "Luôn dùng thư mục workspace đầu tiên (workspaceFolders[0]). Mang tính xác định — không phụ thuộc vào tệp nào đang được focus.", - "settings.workspaceCommandListsEnabled.description": "Bật các danh sách lệnh do cài đặt workspace đóng góp (giá trị `zoo-code.allowedCommands` và `zoo-code.deniedCommands` trong các tệp cài đặt workspace). Khi bị tắt, các danh sách lệnh của workspace không có tác dụng. Khi được bật, các mục cấp người dùng được ưu tiên: một mục cấp người dùng quyết định bất kỳ lệnh nào mà nó khớp, và các mục của workspace chỉ áp dụng cho các lệnh không có mục cấp người dùng nào khớp. Cài đặt này chỉ có thể thay đổi trong [cài đặt người dùng](https://code.visualstudio.com/docs/getstarted/settings)." + "settings.workspaceCommandListsEnabled.description": "Bật các danh sách lệnh do cài đặt workspace đóng góp (giá trị `zoo-code.allowedCommands` và `zoo-code.deniedCommands` trong các tệp cài đặt workspace). Khi bị tắt, các danh sách lệnh của workspace không có tác dụng. Bao gồm cả các lệnh bị từ chối được lưu trong repository. Khi được bật, các mục cấp người dùng được ưu tiên: một mục cấp người dùng quyết định bất kỳ lệnh nào mà nó khớp, và các mục của workspace chỉ áp dụng cho các lệnh không có mục cấp người dùng nào khớp. Cài đặt này chỉ có thể thay đổi trong [cài đặt người dùng](https://code.visualstudio.com/docs/getstarted/settings)." } diff --git a/src/package.nls.zh-CN.json b/src/package.nls.zh-CN.json index fe384c7efa..77d09f7ad1 100644 --- a/src/package.nls.zh-CN.json +++ b/src/package.nls.zh-CN.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Zoo 在多根工作区中如何解析工作区根目录。根目录用于定位 `.roomodes`、`.roo/mcp.json`、`.roo/rules/` 以及其他项目范围的配置。更改此设置仅影响后续查找;正在运行的任务会保留其原始根目录。", "settings.workspace.rootResolution.activeEditor.description": "使用包含活动编辑器的工作区文件夹;回退到第一个工作区文件夹。(默认——保留旧行为。)", "settings.workspace.rootResolution.firstFolder.description": "始终使用第一个工作区文件夹(workspaceFolders[0])。具有确定性——与当前聚焦的文件无关。", - "settings.workspaceCommandListsEnabled.description": "启用由工作区设置提供的命令列表(工作区设置文件中的 `zoo-code.allowedCommands` 和 `zoo-code.deniedCommands` 值)。禁用期间,工作区命令列表不产生任何影响。启用后,用户级条目具有优先权:用户级条目决定其匹配的任何命令,工作区条目仅适用于没有任何用户级条目匹配的命令。此设置只能在[用户设置](https://code.visualstudio.com/docs/getstarted/settings)中更改。" + "settings.workspaceCommandListsEnabled.description": "启用由工作区设置提供的命令列表(工作区设置文件中的 `zoo-code.allowedCommands` 和 `zoo-code.deniedCommands` 值)。禁用期间,工作区命令列表不产生任何影响。这包括存储在仓库中的被拒绝命令。启用后,用户级条目具有优先权:用户级条目决定其匹配的任何命令,工作区条目仅适用于没有任何用户级条目匹配的命令。此设置只能在[用户设置](https://code.visualstudio.com/docs/getstarted/settings)中更改。" } diff --git a/src/package.nls.zh-TW.json b/src/package.nls.zh-TW.json index 084e620258..0d6c152820 100644 --- a/src/package.nls.zh-TW.json +++ b/src/package.nls.zh-TW.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Zoo 在多根工作區中如何解析工作區根目錄。根目錄用於定位 `.roomodes`、`.roo/mcp.json`、`.roo/rules/` 以及其他專案範圍的設定。變更此設定僅影響後續查找;正在執行的工作會保留其原始根目錄。", "settings.workspace.rootResolution.activeEditor.description": "使用包含使用中編輯器的工作區資料夾;回退到第一個工作區資料夾。(預設——保留舊行為。)", "settings.workspace.rootResolution.firstFolder.description": "一律使用第一個工作區資料夾(workspaceFolders[0])。具決定性——與目前聚焦的檔案無關。", - "settings.workspaceCommandListsEnabled.description": "啟用由工作區設定所提供的工作區指令清單(工作區設定檔案中的 `zoo-code.allowedCommands` 與 `zoo-code.deniedCommands` 值)。停用時,工作區指令清單不會產生任何影響。啟用後,使用者層級的條目具有優先權:使用者層級的條目會決定其符合的任何指令,工作區條目僅適用於沒有任何使用者層級條目符合的指令。此設定只能在[使用者設定](https://code.visualstudio.com/docs/getstarted/settings)中變更。" + "settings.workspaceCommandListsEnabled.description": "啟用由工作區設定所提供的工作區指令清單(工作區設定檔案中的 `zoo-code.allowedCommands` 與 `zoo-code.deniedCommands` 值)。停用時,工作區指令清單不會產生任何影響。這包括儲存在倉庫中的被拒絕指令。啟用後,使用者層級的條目具有優先權:使用者層級的條目會決定其符合的任何指令,工作區條目僅適用於沒有任何使用者層級條目符合的指令。此設定只能在[使用者設定](https://code.visualstudio.com/docs/getstarted/settings)中變更。" } diff --git a/src/shared/tools.ts b/src/shared/tools.ts index e10f24c97c..3364910915 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -20,12 +20,9 @@ export type AutoApprovalContext = { */ dcgDecision?: DcgDecision /** - * Directory the command will actually run in (`execute_command` only): - * the tool's resolved working directory, which differs from the task's - * own `cwd` whenever the call carries a custom `cwd`. Command-list - * enforcement judges this directory so a command executing in another - * workspace folder is judged by that folder's policy, never the task - * folder's. + * Directory the command actually runs in (`execute_command` only). Command + * lists judge this directory, so a command in another workspace folder is + * judged by that folder's policy, never the task folder's. */ commandCwd?: string } diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts index 9a60682952..a9e1efb93d 100644 --- a/src/utils/__tests__/seedAllowedCommands.spec.ts +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -7,9 +7,8 @@ import { Package } from "../../shared/package" import { makeUri, makeWorkspaceConfiguration } from "../../test-utils/vscode" import { seedCommandList } from "../seedAllowedCommands" -// Scriptable stand-in for `vscode.workspace.workspaceFolders`: the module -// mock's getter reads through this object, so a test can change the open -// folders without re-mocking the module. +// Scriptable `workspaceFolders`: the mock's getter reads this, so tests can +// change open folders without re-mocking. const workspaceState = vi.hoisted(() => ({ workspaceFolders: undefined as { uri: unknown }[] | undefined, })) @@ -37,19 +36,13 @@ interface ConfigDouble { } function mockConfiguration({ inspect, effective = [], inspectThrows = false, gate = false }: ConfigDouble = {}) { - // Real VS Code reports `workspaceFolderValue` only for a configuration - // looked up against a resource; an unscoped lookup reports no folder - // layer no matter what any folder's settings contain. Scripting that - // split per call is what lets these tests tell a scoped lookup apart - // from an unscoped one. + // Real VS Code reports `workspaceFolderValue` only for a resource-scoped + // lookup. Scripting that split lets tests tell scoped calls from unscoped. vi.mocked(vscode.workspace.getConfiguration).mockImplementation( (_section?: string, scope?: vscode.ConfigurationScope | null) => { const config = makeWorkspaceConfiguration() - // The shared double is scripted per call so the per-test fixture - // values need no type assertion at the construction site. The gate - // section reads independently of the list values: its shipped - // default is off, so a test only gets an enforced workspace layer - // by asking for one. + // The gate reads independently of the lists: its default is off, so + // a test gets an enforced workspace layer only by asking. vi.mocked(config.get).mockImplementation((section: string) => section === "workspaceCommandListsEnabled" ? gate : effective, ) @@ -60,8 +53,7 @@ function mockConfiguration({ inspect, effective = [], inspectThrows = false, gat if (inspect === undefined) { return undefined } - // No resource to resolve against => no folder layer, matching - // the real contract for unscoped (and explicit-null) lookups. + // No resource => no folder layer, as in real VS Code. return scope === undefined || scope === null ? { ...inspect, workspaceFolderValue: undefined } : inspect }) return config @@ -78,8 +70,7 @@ function mockMemento(existing: unknown = undefined, deniedExisting: unknown = un store.set("deniedCommands", deniedExisting) } - // Structurally complete Memento double (keys/get/update), so the call - // sites need no type assertion. + // Complete Memento double: no type assertion at call sites. return { keys: vi.fn((): readonly string[] => [...store.keys()]), get: vi.fn().mockImplementation((key: string) => store.get(key)), @@ -96,12 +87,9 @@ describe("seedCommandList", () => { }) it("leaves global state unset when only a workspace-scoped value exists", async () => { - // A real VS Code get() folds the workspace override into the effective - // value, so this is the leak scenario: reading get() would seed - // ["docker"] (from .vscode/settings.json) into global state. The - // defaultValue mirrors real VS Code, where the declared default is - // always present: the workspace override replaced it deliberately, so - // re-granting it from global state is also forbidden. + // The leak scenario: reading get() would seed the workspace override + // into global state. The override also replaced the declared default, + // so re-granting the default is forbidden too. mockConfiguration({ inspect: { key: "allowedCommands", @@ -110,8 +98,7 @@ describe("seedCommandList", () => { workspaceValue: ["docker"], }, effective: ["docker"], - // Suppression only applies while the gate lets the workspace layer - // take effect in enforcement. + // Suppression applies only while the gate enforces the workspace layer. gate: true, }) const globalState = mockMemento() @@ -123,12 +110,9 @@ describe("seedCommandList", () => { }) it("leaves global state unset when only a workspace-folder-scoped value exists", async () => { - // A folder override is visible only to a lookup resolved against that - // folder's resource, so this fixture opens a folder and scripts the - // folder layer (which the resource-aware double reports only for the - // scoped call). An unscoped seed would read "no value anywhere" here - // and re-grant the default the folder removed — this test fails on - // that regression. + // A folder override is visible only to a resource-scoped lookup. An + // unscoped seed would see nothing here and re-grant the suppressed + // default — this test fails on that regression. const folderA = makeUri("/mock/folder-a") workspaceState.workspaceFolders = [{ uri: folderA }] mockConfiguration({ @@ -144,16 +128,14 @@ describe("seedCommandList", () => { await seedCommandList(globalState, "allowedCommands") - // The folder layer only reaches the seed through a resource-scoped - // lookup, so the seed must request one (same pin as the save path). + // The folder layer reaches the seed only through a resource-scoped lookup. expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, folderA) expect(globalState.update).not.toHaveBeenCalled() expect(globalState.get("allowedCommands")).toBeUndefined() }) it("resolves the folder layer against the first workspace folder only", async () => { - // Reading any other folder's configuration would silently decide the - // seed from the wrong folder's settings file. + // Reading another folder's configuration would seed from the wrong settings file. const folderA = makeUri("/mock/folder-a") const folderB = makeUri("/mock/folder-b") workspaceState.workspaceFolders = [{ uri: folderA }, { uri: folderB }] @@ -175,9 +157,8 @@ describe("seedCommandList", () => { }) it("treats an explicitly empty workspace value as an override that suppresses the default", async () => { - // Presence is checked with `undefined`, not truthiness: a workspace that - // set the list to [] opted out of the default as deliberately as one - // that set ["docker"]. + // Presence is checked with `undefined`, not truthiness: an empty list + // opts out of the default as deliberately as a populated one. mockConfiguration({ inspect: { key: "allowedCommands", @@ -206,13 +187,10 @@ describe("seedCommandList", () => { await seedCommandList(globalState, "allowedCommands") expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) - // Copy, like the global-value path: global state must not share a - // reference with the configuration object. + // Copy, like the global-value path: no shared reference with the configuration. expect(globalState.update.mock.calls[0][1]).not.toBe(defaultValue) - // A later activation with the gate on but still no workspace-scoped - // value: only an actual override suppresses the default, so the gate - // alone must not withhold it. + // Gate on with no override: only an actual override suppresses the default. mockConfiguration({ inspect: { key: "allowedCommands", defaultValue }, effective: defaultValue, @@ -236,9 +214,8 @@ describe("seedCommandList", () => { }) it("seeds an explicitly empty global value instead of the populated default", async () => { - // An explicitly empty global list is a deliberate opt-out: the seed - // persists [] so global state counts as seeded, rather than treating - // the empty allowlist as unset and re-granting the declared defaults. + // An empty global list is a deliberate opt-out: persist [] so global + // state counts as seeded and the defaults are not re-granted. mockConfiguration({ inspect: { key: "allowedCommands", @@ -265,9 +242,8 @@ describe("seedCommandList", () => { }) it("leaves an explicitly empty global-state list untouched", async () => { - // The guard treats presence, not emptiness: saving [] is a deliberate - // choice to auto-approve nothing, and re-seeding the package default - // would silently re-grant the approvals the user just revoked. + // The guard checks presence, not emptiness: re-seeding a saved [] would + // re-grant approvals the user revoked. mockConfiguration({ inspect: { key: "allowedCommands", defaultValue: ["git log", "git diff", "git show"] } }) const globalState = mockMemento([]) @@ -278,12 +254,9 @@ describe("seedCommandList", () => { }) it("composes a later workspace override as a union with the seeded defaults", async () => { - // Full schedule: a fresh activation seeds the declared default, then a - // workspace override appears in a later activation. The seed - // early-returns because global state already holds a list, so the - // override is never persisted — and the enforcement read composes the - // two layers as a set union. Neither list replaces the other; the - // longest-prefix matcher decides which entry governs a given command. + // A fresh activation seeds the default; a later workspace override is + // never persisted (the guard early-returns). Enforcement composes the + // two layers as a set union; the matcher picks the governing entry. const defaultValue = ["git log", "git diff", "git show"] mockConfiguration({ inspect: { key: "allowedCommands", defaultValue }, @@ -294,8 +267,7 @@ describe("seedCommandList", () => { await seedCommandList(globalState, "allowedCommands") expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) - // A later activation in a workspace whose settings file sets the list: - // the guard early-returns before any inspection, so no second write. + // Later activation with an override present: the guard early-returns first. mockConfiguration({ inspect: { key: "allowedCommands", defaultValue, workspaceValue: ["docker ps"] }, effective: ["docker ps"], @@ -305,9 +277,8 @@ describe("seedCommandList", () => { expect(globalState.update).toHaveBeenCalledTimes(1) expect(globalState.get("allowedCommands")).toEqual(defaultValue) - // The enforcement view (ClineProvider.getState) keeps both layers and - // merges them: the override adds entries, it does not replace the - // seeded defaults, and vice versa. + // The enforcement view keeps both layers: the override adds entries, + // it does not replace the seeded defaults. const scopes = readCommandListScopes("allowedCommands", globalState.get("allowedCommands")) expect(scopes.global).toEqual(defaultValue) expect(scopes.workspace).toEqual(["docker ps"]) @@ -315,13 +286,10 @@ describe("seedCommandList", () => { }) it("inspects the global value under the extension's own section key", async () => { - // The seed must read the extension's own section; asking VS Code about - // a different (or empty) section key would silently never find the - // user's global list. With no folder open there is no resource to - // scope against, so the explicit unscoped call is (section, undefined). + // The seed must read the extension's own section; a wrong key would + // silently find nothing. No folder open => unscoped (section, undefined). mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] } }) - // Structurally complete Memento double (keys/get/update), so the call - // site needs no type assertion. + // Complete Memento double: no type assertion at the call site. const globalState: vscode.Memento = { keys: () => [], get: vi.fn(), @@ -366,10 +334,8 @@ describe("seedCommandList", () => { }) it("seeds the deny list from its settings-file global value on a fresh profile", async () => { - // Symmetric with the allow side: a user-level `deniedCommands` edit in - // settings.json has a one-time migration role, and the enforcement - // global layer reads extension state only, so an unseeded deny list - // silently drops the user's denials. + // Symmetric with the allow side: enforcement reads extension state only, + // so an unseeded deny list silently drops the user's denials. mockConfiguration({ inspect: { key: "deniedCommands", globalValue: ["docker"] }, effective: ["docker"] }) const globalState = mockMemento() @@ -390,8 +356,7 @@ describe("seedCommandList", () => { }) it("seeds the deny list when only the allow list was already seeded", async () => { - // Per-key guards: an install whose allowlist was seeded by an earlier - // version must still get the deny migration on the next activation. + // Per-key guards: a seeded allowlist must not block the deny migration. mockConfiguration({ inspect: { key: "deniedCommands", globalValue: ["docker"] }, effective: ["docker"] }) const globalState = mockMemento(["npm"]) @@ -402,9 +367,7 @@ describe("seedCommandList", () => { }) it("seeds the declared default when a workspace value exists but the gate is off", async () => { - // With the gate off the workspace layer contributes nothing to - // enforcement, so withholding the default would leave commands - // unapproved that the override never actually governed. + // Gate off: the override governs nothing, so it must not withhold the default. const defaultValue = ["git log", "git diff", "git show"] mockConfiguration({ inspect: { @@ -422,9 +385,8 @@ describe("seedCommandList", () => { }) it("suppresses the declared default for a workspace value while the gate is on", async () => { - // Pins the explicit-override semantics: an enforced workspace list - // replaces the default across scopes, so the seed must not re-grant - // the approvals the override removed. + // An enforced workspace list replaces the default, so the seed must not + // re-grant the approvals it removed. mockConfiguration({ inspect: { key: "allowedCommands", diff --git a/src/utils/seedAllowedCommands.ts b/src/utils/seedAllowedCommands.ts index be4b930ada..4faa0ae6c2 100644 --- a/src/utils/seedAllowedCommands.ts +++ b/src/utils/seedAllowedCommands.ts @@ -4,35 +4,22 @@ import { commandListConfiguration, workspaceCommandListsEnabled } from "../core/ import type { CommandListConfigKey } from "../core/auto-approval/commandScope" /** - * Seeds one auto-approval command-list key (`allowedCommands` or - * `deniedCommands`) from its settings-file value into the extension's - * global state, but only when global state holds no list for that key yet - * (first run). Each key carries its own guard, so a profile whose allowlist - * was already seeded still gets an unseeded deny list migrated on the next - * activation. + * Seeds one command-list key from its settings value into extension global + * state, only when global state holds no list for that key yet. Each key has + * its own guard, so a seeded allowlist does not block a later deny-list + * migration. * - * The seed reads scoped values via `inspect()` rather than the effective - * `get()` on purpose: `get()` folds in workspace-scoped overrides, so a - * project's `.vscode/settings.json` would otherwise be copied permanently - * into global state the first time the extension activates inside that - * project — a leak that survives closing the project. The lookup goes - * through `commandListConfiguration()`, the folder-scoped accessor shared - * with the command-list read and write paths: only a configuration resolved - * against a resource reports `workspaceFolderValue` at all, so the folder - * layer is visible here exactly where enforcement can see it. In a - * multi-root workspace only the first folder is in scope; with no folder - * open the configuration is unscoped and reports no folder value. + * The seed reads `inspect()`, not `get()`: `get()` folds in workspace + * overrides, which would leak a project's `.vscode/settings.json` into global + * state permanently. The lookup shares `commandListConfiguration()` with the + * read/write paths, so the folder layer is visible exactly where enforcement + * sees it. * - * Selection: the global-scope value wins. With nothing set at any scope (a - * fresh install) the declared package default is seeded, because the - * enforcement path reads only global state plus workspace scopes and never - * falls back to that default on its own. A workspace-scoped value is an - * explicit choice and suppresses the default — but only while the - * `workspaceCommandListsEnabled` gate lets that value take effect: with the - * gate off the workspace layer contributes nothing to enforcement, so - * withholding the default would leave commands unapproved that the override - * never actually governed. Array settings replace across scopes, so seeding - * past an enforced override would re-grant the approvals it removed. + * Selection: the global value wins. With nothing set anywhere, the package + * default is seeded — enforcement never falls back to it on its own. An + * enforced workspace override suppresses the default: array settings replace + * across scopes, so seeding past it would re-grant the approvals it removed. + * With the gate off the override is inert, so the default is still seeded. * * @param globalState - The extension global-state memento to seed. * @param configKey - The command-list configuration key to seed. @@ -42,11 +29,8 @@ export async function seedCommandList(globalState: vscode.Memento, configKey: Co return } - // Only the configuration lookup itself is guarded: it can fail (for example - // before the workspace is ready), and skipping the seed then only defers it - // to a later activation. The `inspected` reads below stay outside the - // guarded region so a genuine lookup failure stays distinguishable from an - // absent value rather than being swallowed as one. + // Only the lookup is guarded: it can fail before the workspace is ready, + // and skipping the seed then only defers it to a later activation. let inspected: | { globalValue?: string[] diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 68879d6474..19ac9aa8e5 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -91,10 +91,9 @@ import { useSearchIndexRegistry, SearchIndexProvider } from "./useSettingsSearch import { nextSaveRequestId } from "./saveRequestId" /** - * How long the form waits for the host to answer a save whose writes it watches: one that changes a time or date - * setting, or one that edits a command list. The host always answers (success or failure), but a write that never - * settles would otherwise leave Save disabled until the webview reloads. After this the save is treated as failed: the - * edits stay unsaved and Save works again. + * How long the form waits for the host to answer a watched save. A write + * that never settles would otherwise leave Save disabled until reload. After + * this, treat the save as failed: edits stay unsaved, Save works again. */ export const SAVE_ANSWER_TIMEOUT_MS = 20_000 @@ -105,8 +104,8 @@ export const settingsTabTrigger = "whitespace-nowrap overflow-hidden min-w-0 h-12 px-4 py-3 box-border flex items-center border-l-2 border-transparent text-vscode-foreground opacity-70 hover:bg-vscode-list-hoverBackground data-[compact=true]:w-12 data-[compact=true]:p-4" export const settingsTabTriggerActive = "opacity-100 border-vscode-focusBorder bg-vscode-list-activeSelectionBackground" -// Command-list snapshot of a settings state object. Entries are compared by value because every -// state post delivers freshly deserialized arrays; reference identity carries no meaning here. +// Command-list snapshot of a state object. Compare entries by value: each +// state post delivers freshly deserialized arrays. interface CommandListSnapshot { allowedCommands?: string[] deniedCommands?: string[] @@ -187,24 +186,24 @@ const SettingsView = forwardRef(({ onDone, t const sentState = useRef(undefined) const latestCachedState = useRef(cachedState) latestCachedState.current = cachedState - // The live host state, read when a save settles without re-subscribing the result handler on every post. + // The live host state, read when a save settles. const latestExtensionState = useRef(extensionState) - // Refreshed synchronously at commit: a host state post and the save answer that follows it can arrive as - // back-to-back messages, and the answer's task must observe the post it answers, not the state before it. + // Refresh synchronously at commit: the save answer can follow its state post + // immediately, and must observe that post, not the state before it. useLayoutEffect(() => { latestExtensionState.current = extensionState }, [extensionState]) - // The save the host must answer records the baseline it stamped and the lists it submitted, so the - // save-result effect can reconcile each list's baseline against that list's own write outcome. + // Records the baseline and lists of the save the host must answer, so the + // save-result effect can reconcile each list against its own write outcome. const submittedListSave = useRef<{ baselined: [string[], string[]]; sent: [string[], string[]] } | undefined>( undefined, ) - // Command-list values the dialog last displayed, so a later state post can be recognized as - // an external change rather than a restatement of what is already shown. + // What the dialog last displayed, so a later post reads as an external + // change, not a restatement. const lastDisplayedCommandSnapshot = useRef(commandListSnapshot(extensionState)) - // An in-flight user edit of either list claims ownership of the lists until Save, discard, or - // a full reseed; external list updates must not silently overwrite it. + // An in-flight list edit owns the lists until Save, discard, or reseed; + // external updates must not overwrite it. const commandListsTouched = useRef(false) const { @@ -312,21 +311,19 @@ const SettingsView = forwardRef(({ onDone, t setChangeDetected(false) }, [settingsImportedAt, extensionState]) - // The command lists can change in the extension host while this dialog is open (for example, - // a settings-file edit landing mid-session). Fold exactly those fields into the edit buffer on - // every state post that changes them, so a later Save cannot rewrite the configuration layer - // from a list that never showed the new entry. List fields are held back while the user has an - // in-flight list edit (in-flight edits win); every other buffered field is left untouched and - // the dirty flag is never cleared here, keeping the buffer's Save-gated semantics. + // The host can change the command lists while this dialog is open. Fold the + // changed list fields into the edit buffer on every state post, so a later + // Save cannot rewrite the file from a list that never showed the new entry. + // An in-flight list edit holds the list fields back; other fields are + // untouched and the dirty flag is never cleared here. useEffect(() => { const snapshot = commandListSnapshot(extensionState) if (snapshot === lastDisplayedCommandSnapshot.current) { return } - // The merge is computed here, outside the state update, from the committed buffer the - // effect's render saw; a state update must stay a pure function of the state it is - // applied to. + // Compute the merge here, outside the state update: a state update must + // stay a pure function of the state it applies to. const prevState = latestCachedState.current const merged: CommandListSnapshot = {} @@ -342,17 +339,12 @@ const SettingsView = forwardRef(({ onDone, t merged.workspaceCommandListsEnabled = extensionState.workspaceCommandListsEnabled } - // The stamp records the lists this merge leaves on screen, never the posted - // state outright: an entry held back by an in-flight edit was never displayed, - // and a baseline claiming it had been lets the save erase it as a user - // deletion without warning. While the lists are held back the buffered lists - // are themselves unposted, so the stamp keeps its prior lists instead - a - // deletion inside the buffered edit must stay in the baseline for the save to - // apply it rather than resurrect the deleted entry as an external addition. - // The gate slot holds back with those lists because the stamp has to describe - // one displayed state: pairing held-back lists with an externally-flipped gate - // would claim the held-back entries were displayed under a gate they never - // appeared alongside. + // The stamp records what this merge leaves on screen, never the posted + // state: a held-back entry was never displayed, and claiming it had been + // lets the save erase it as a user deletion. While the lists are held + // back, keep the prior lists: a deletion inside the buffered edit must + // stay in the baseline so the save applies it. The gate holds back with + // the lists so the stamp describes one displayed state. const [stampAllowed, stampDenied, stampGate] = commandListsTouched.current ? (JSON.parse(lastDisplayedCommandSnapshot.current) as [string[], string[], boolean]) : [ @@ -372,9 +364,9 @@ const SettingsView = forwardRef(({ onDone, t }, [extensionState]) const setCachedStateField: SetCachedStateField = useCallback((field, value) => { - // A list edit claims ownership of the lists only when the value actually changes; the - // equality guard is duplicated here so the marking can sit outside the state update, - // keeping that update pure without giving a no-op set ownership it never had. + // Claim ownership only when the value actually changes: a no-op set must + // not own the lists. The guard is duplicated so the marking stays outside + // the (pure) state update. if ((field === "allowedCommands" || field === "deniedCommands") && latestCachedState.current[field] !== value) { commandListsTouched.current = true } @@ -509,9 +501,9 @@ const SettingsView = forwardRef(({ onDone, t const isSettingValid = !errorMessage - // The time and date values are written one at a time on the host, and a write can fail: a save that changes one of - // them waits for the host's answer, just as a save that edits a command list does. A save that changes neither - // display nor command lists asks for no answer, and behaves as it always did. + // The host writes time/date settings one at a time and a write can fail, so + // a save that changes one waits for the host's answer, like a list edit. + // A save that changes neither asks for no answer. const displayChanged = (cachedState.timeFormat ?? "auto") !== (extensionState.timeFormat ?? "auto") || (cachedState.dateFormat ?? "auto") !== (extensionState.dateFormat ?? "auto") || @@ -523,10 +515,9 @@ const SettingsView = forwardRef(({ onDone, t lastDisplayedCommandSnapshot.current, ) as [string[], string[], boolean] - // The host reports a rejected command-list write in the same answer it gives a failed display-setting - // write, so a save carrying either waits for it. Reporting nothing for a list-only save would leave - // the dialog unable to tell a stored list from a rejected one, and it would show the rejected edit as - // saved. + // The host reports a rejected list write in the same answer as a + // failed display write, so a save carrying either waits for it. + // Without an id, a rejected list edit would look saved. const saveId = displayChanged || commandListsTouched.current ? nextSaveRequestId() : undefined if (saveId) { sentState.current = cachedState @@ -543,14 +534,10 @@ const SettingsView = forwardRef(({ onDone, t commandListBaseline: { allowedCommands: lastDisplayedAllowed, deniedCommands: lastDisplayedDenied, - // The gate travels with the lists it was displayed alongside: the stamp - // always carries the gate that was on screen with its lists, so a gate - // flip between display and save cannot pair old-gate entries with a - // new-gate label and reclassify a baseline-shown entry as a brand-new - // promotion into the global layer. A dialog whose host never delivered - // the gate has no displayed gate to accompany the baseline: it posts - // none, and the save path keeps the legacy classification for an - // absent flag. + // The stamp carries the gate its lists were displayed under, so + // a gate flip cannot reclassify a shown entry as a new global + // promotion. If the host never delivered the gate, post none; + // the save path then uses the legacy classification. workspaceCommandListsEnabled: cachedState.workspaceCommandListsEnabled === undefined ? undefined : gateAtSubmit, }, @@ -645,13 +632,11 @@ const SettingsView = forwardRef(({ onDone, t deniedCommands, workspaceCommandListsEnabled: gateAtSubmit, }) - // The stamp records what is on screen, so it moves at submit; the settle below then re-derives each - // edited list's entry from whether that list's own write landed. The lists' ownership of the buffer - // does not move at submit. A save releases that hold - and with it the unsaved flag - only once the - // refresh shows every submitted write landed: releasing earlier would let the state refresh that - // follows a rejected list write overwrite the edit the user is still looking at. A save that carries - // neither a watched display setting nor an edited list asks for no answer, so it clears the hold at - // submit. + // The stamp moves at submit; the settle below re-derives each edited + // list from its own write outcome. The lists' hold does not move at + // submit: releasing early would let the refresh after a rejected write + // overwrite the user's edit. An unwatched save needs no answer, so it + // clears the hold here. if (!saveId) { commandListsTouched.current = false setChangeDetected(false) @@ -664,16 +649,12 @@ const SettingsView = forwardRef(({ onDone, t const settle = (success: boolean) => { setPendingSaveId(undefined) - // The answer's flag reports one outcome for the whole payload, but the payload's lists are written - // separately, and a report of success says only that the other settings stored: a rejected - // command-list write is absent from the flag. Each edited list's own write result comes from the - // refresh the host posts before its answer, so every save reconciles each list against what was - // submitted: a list equal to what was submitted records that its own write landed, and its baseline - // stays advanced, since restoring the pre-submit baseline of a written list claims an entry the file - // no longer holds was displayed. Every other edited list's baseline rolls back to what was displayed - // before the submit, so a deletion whose write never ran is still classified as a user deletion on - // retry instead of an external addition to re-admit. Lists the save did not edit keep the stamp's - // baseline, which the external-update merge already maintains. + // The answer's flag reports the whole payload; each list's own write + // result comes from the refresh the host posts before its answer. + // Reconcile each edited list: one equal to what was submitted landed, + // so its baseline stays advanced. Every other edited list rolls back to + // the pre-submit baseline, so an unwritten deletion stays a user + // deletion on retry. Unedited lists keep the stamp's baseline. const save = submittedListSave.current submittedListSave.current = undefined let everyEditedWriteLanded = true @@ -715,10 +696,9 @@ const SettingsView = forwardRef(({ onDone, t workspaceCommandListsEnabled: stampGate, }) } - // The unsaved flag goes off only when nothing is left unsaved: an edit made while the save was in - // flight is not in what was sent, and an edited list whose write never landed still holds its edit. - // In both cases the buffered lists keep holding off external updates, so a host refresh cannot - // replace the edit the user is looking at. + // Clear the flag only when nothing is left unsaved: an edit made + // during the save, or a list whose write never landed, keeps the hold + // so a host refresh cannot replace the user's edit. if (success && everyEditedWriteLanded && latestCachedState.current === sentState.current) { commandListsTouched.current = false setChangeDetected(false) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx index f8e4b95737..de32dd4f9f 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx @@ -798,8 +798,7 @@ describe("SettingsView - Change Detection Fix", () => { await new Promise((resolve) => setTimeout(resolve, 0)) }) - // Save must submit the list that includes the entry the dialog now displays, not the - // stale one captured when the dialog opened. + // Save must submit the now-displayed list, not the stale one from open time. fireEvent.click(screen.getByTestId("save-button")) expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ @@ -830,9 +829,8 @@ describe("SettingsView - Change Detection Fix", () => { await new Promise((resolve) => setTimeout(resolve, 0)) }) - // The baseline must be the list the dialog NOW displays (post-merge), so the - // merge's entry counts as shown - not the empty list present when the dialog - // opened, which would make the merge's own entry look externally added. + // The baseline must be the post-merge list, so the merge's entry counts + // as shown; the empty open-time list would make it look externally added. fireEvent.click(screen.getByTestId("save-button")) expect(mockPostMessage).toHaveBeenCalledWith( expect.objectContaining({ @@ -853,8 +851,8 @@ describe("SettingsView - Change Detection Fix", () => { fireEvent.click(screen.getByTestId("set-provider-baseten")) await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) - // One state post flips the workspace command-list gate and adds a deny entry, which is - // what enabling the gate does: workspace entries become part of the displayed lists. + // One post flips the gate and adds a deny entry: enabling the gate makes + // workspace entries part of the displayed lists. await act(async () => { extensionState = createExtensionState({ deniedCommands: ["git push"], diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx index 16608e6363..f239768cf0 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -769,10 +769,9 @@ describe("SettingsView - Allowed Commands", () => { }) it("sends the lists displayed at open as the save baseline, unmoved by an in-flight list edit", () => { - // The save path classifies divergence between "user deleted this" and "the - // settings file gained this" from the baseline, so the payload must carry what - // the dialog displayed BEFORE this save - not the edited list it is submitting, - // and not the committed value the post-save bookkeeping writes back. + // The save path tells "user deleted this" from "the file gained this" using + // the baseline, so the payload must carry what the dialog displayed before + // this save - not the submitted list, not the committed value. renderWithExtensionState(, { state: { allowedCommands: ["git"], alwaysAllowExecute: true }, }) @@ -795,10 +794,9 @@ describe("SettingsView - Allowed Commands", () => { }) it("carries the gate displayed as on in the save baseline", () => { - // The save path compares this flag against the gate at write time: with the flag - // on, entries the baseline displayed are existing workspace knowledge, so a gate - // flip between display and save cannot reclassify a kept entry as a brand-new - // promotion into the global layer. + // The save path compares this flag against the gate at write time. With it + // on, baseline entries are known workspace entries, so a gate flip cannot + // reclassify a kept entry as a new global promotion. renderWithExtensionState(, { state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: true }, }) @@ -824,10 +822,10 @@ describe("SettingsView - Allowed Commands", () => { }) it("keeps the stamped gate paired with held-back lists when the gate flips during a buffered edit", async () => { - // An external state post flips the gate while a list edit is in flight: the lists are held - // back, so the baseline must keep the gate those entries were displayed under - posting - // the flipped gate alongside the held-back entries would let the save path classify a - // baseline-shown workspace entry as a brand-new promotion into the global layer. + // An external post flips the gate during a list edit. The lists are held + // back, so the baseline must keep the gate they were displayed under; + // posting the flipped gate would reclassify a shown entry as a new + // global promotion. renderWithExtensionState(, { state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: true }, }) @@ -861,9 +859,8 @@ describe("SettingsView - Allowed Commands", () => { }) it("sends the merged gate with the merged lists when no list edit is in flight", async () => { - // The same merge's other branch: with no in-flight list edit the merge adopts the posted - // lists AND the gate, so the baseline describes the newly displayed state - the pairing - // guard holds in both directions, and a held stamp must not strand a stale gate. + // The other merge branch: with no in-flight edit the merge adopts the + // posted lists and the gate, so the baseline describes the new state. renderWithExtensionState(, { state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: false }, }) @@ -897,9 +894,8 @@ describe("SettingsView - Allowed Commands", () => { }) it("carries the gate displayed as off in the save baseline without persisting it", () => { - // The gate value reaches the save path through the baseline only: the dialog - // displays the host's gate but never writes it, so the flag must not appear in - // the settings payload the host persists. + // The dialog shows the host's gate but never writes it, so the flag must + // reach the save path through the baseline only, not the settings payload. renderWithExtensionState(, { state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: false }, }) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 7fe1e8494f..d0d2574783 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -818,8 +818,8 @@ describe("SettingsView - Unsaved Changes Detection", () => { }) it("keeps an in-flight deny-list edit when an external list update arrives while the dialog is open", async () => { - // Drive the real cached-state setter through a stand-in auto-approve section so the - // buffered list edit is indistinguishable from a user typing in the deny list. + // Drive the real setter through a stand-in section, so the buffered edit + // is indistinguishable from a user typing in the deny list. vi.mocked(AutoApproveSettings).mockImplementation( ({ setCachedStateField }: React.ComponentProps) => ( + +
+ ), + ) + + const submitListEdit = async () => { + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + }) + const view = renderWithExtensionState(, { + queryClient, + }) + fireEvent.click(await screen.findByTestId("edit-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + return view + } + + // First case: the host flips the gate and restates the submitted lists. The + // lists match the submission, so this refresh is an automatic merge. + const mergedView = await submitListEdit() + const mergeSaveId = lastSaveRequestId(postMessage) + expect(mergeSaveId).toBeDefined() + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + workspaceCommandListsEnabled: true, + }) + mergedView.rerender() + answerSave(mergeSaveId, { success: true }) + + // The merge left nothing unsaved, so the form is clean and the lists are open again. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + deniedCommands: ["rm -rf"], + workspaceCommandListsEnabled: true, + }) + mergedView.rerender() + await waitFor(() => + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["rm -rf"])), + ) + expect(screen.getByTestId("save-button")).toBeDisabled() + mergedView.unmount() + + // Second case: the user edits a cached field while the save is pending. The + // refresh still matches the submission, yet the form must stay dirty. + const editedView = await submitListEdit() + const editedSaveId = lastSaveRequestId(postMessage) + expect(editedSaveId).toBeDefined() + fireEvent.click(screen.getByTestId("edit-non-list-setting")) + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + workspaceCommandListsEnabled: true, + }) + editedView.rerender() + answerSave(editedSaveId, { success: true }) + + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + editedView.unmount() + }) + + it("keeps the form dirty when a sibling setter edits a field during a pending save", async () => { + // The settle must recognise a user edit from every setter that can change the + // buffer, not only the generic field setter. Each sibling section below is + // driven in its own render; both run inside this one test so the suite's + // declared test count moves by exactly one. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( +
+ +
+ ), + ) + vi.mocked(ExperimentalSettings).mockImplementation( + ({ setExperimentEnabled }: React.ComponentProps) => ( + + ), + ) + vi.mocked(About).mockImplementation(({ setTelemetrySetting }: React.ComponentProps) => ( + + )) + + const siblingSections = ["experimental", "about"] as const + + for (const siblingSection of siblingSections) { + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + }) + const view = renderWithExtensionState(, { + queryClient, + }) + + // A list edit starts the save, so the settle has a submission to reconcile. + fireEvent.click(await screen.findByTestId("edit-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // While the save is pending, the user edits a field through a sibling setter. + view.rerender() + fireEvent.click(await screen.findByTestId("edit-sibling")) + + // The host's refresh carries the submitted list, so that write landed and only + // the edit made during the save can keep the form dirty. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + }) + view.rerender() + answerSave(saveId, { success: true }) + + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + view.unmount() + } + }) }) From b02d054e9398db59542e88f939154beb775a247c Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 26 Nov 2026 00:35:59 +0100 Subject: [PATCH 37/52] fix: match the Hindi description's own word for "setting" The workspace command-list description spelled the last "setting" in Devanagari, while the same string and its three neighbouring entries use the Latin word. The closing clause now uses the Latin word, so the paragraph reads with one spelling. --- src/package.nls.hi.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/package.nls.hi.json b/src/package.nls.hi.json index 0c7c7c7336..40e7fe3e36 100644 --- a/src/package.nls.hi.json +++ b/src/package.nls.hi.json @@ -51,5 +51,5 @@ "settings.workspace.rootResolution.description": "Multi-root workspace में Zoo workspace root को कैसे resolve करता है। Root का इस्तेमाल `.roomodes`, `.roo/mcp.json`, `.roo/rules/` और दूसरी project-scoped configuration ढूंढने के लिए होता है। इस setting को बदलने का असर सिर्फ आगे की lookups पर पड़ता है; चल रहे tasks अपना original root बनाए रखते हैं।", "settings.workspace.rootResolution.activeEditor.description": "उस workspace folder का इस्तेमाल करो जिसमें active editor है; पहले workspace folder पर fall back करो। (Default — legacy behavior बनाए रखता है।)", "settings.workspace.rootResolution.firstFolder.description": "हमेशा पहले workspace folder (workspaceFolders[0]) का इस्तेमाल करो। Deterministic — इस बात से स्वतंत्र कि अभी कौन सी file focused है।", - "settings.workspaceCommandListsEnabled.description": "Workspace settings द्वारा दी गई command lists को सक्रिय करें (workspace settings files में `zoo-code.allowedCommands` और `zoo-code.deniedCommands` के मान)। जब तक इह निष्क्रिय है, workspace command lists का कौनो प्रभाव नाहीं होतै। इसमें repository में रखी गई denied commands भी शामिल हैं। सक्रिय करतै पर user-level entries कौ प्राथमिकत मिलतै है: हर user-level entry उन सब्ह commands कौ तय करतै है जिनसै वह मेल खातै है, अऊर workspace entries केवल उन commands पर लागू होतै हैं जिनसै कौनो user-level entry मेल नाहीं खातै। यह सेटिंग केवल [user settings](https://code.visualstudio.com/docs/getstarted/settings) में बदली जा सकती है।" + "settings.workspaceCommandListsEnabled.description": "Workspace settings द्वारा दी गई command lists को सक्रिय करें (workspace settings files में `zoo-code.allowedCommands` और `zoo-code.deniedCommands` के मान)। जब तक इह निष्क्रिय है, workspace command lists का कौनो प्रभाव नाहीं होतै। इसमें repository में रखी गई denied commands भी शामिल हैं। सक्रिय करतै पर user-level entries कौ प्राथमिकत मिलतै है: हर user-level entry उन सब्ह commands कौ तय करतै है जिनसै वह मेल खातै है, अऊर workspace entries केवल उन commands पर लागू होतै हैं जिनसै कौनो user-level entry मेल नाहीं खातै। यह setting केवल [user settings](https://code.visualstudio.com/docs/getstarted/settings) में बदली जा सकती है।" } From c694774e38cfcad3dce24b28b5347490f264588f Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 26 Nov 2026 02:00:15 +0100 Subject: [PATCH 38/52] test: create the command-scope fixtures on disk The two folder fixtures in the working-directory suite were constants pointing at /mock/folder-a and /mock/folder-b. The resolver compares each workspace root by its real path, so a root the filesystem cannot resolve drops the folder layer and leaves the global layers deciding alone. Every folder-scoped assertion in that suite then received the weaker answer (ask, noButtonClicked, not_allowlisted) where the stronger one was expected, and both platform unit-test legs failed. The fixtures are now real directories under a temporary root, created in beforeEach and removed in afterEach, and openTwoFolders() registers them by the path the filesystem reports. The registered and resolved spellings therefore agree, and the folder layer survives resolution. One test is added for the case the fixtures cannot cover: a registered folder that has been moved or deleted on disk. Its real path is unknown, so nothing confirms it bounds the command's directory, and matching the command against the registered spelling would let a root that bounds nothing approve it. The test registers such a folder with an allow entry and expects ask, so the drop-the-layer behaviour has a test rather than only a comment. No production file changes. src/core/auto-approval/commandScope.ts is byte-identical to the previous head. --- .../task/__tests__/ask-allowlist-cwd.spec.ts | 50 +++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts index ef59d28a6e..928ae6d822 100644 --- a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts +++ b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts @@ -1,5 +1,9 @@ // npx vitest run core/task/__tests__/ask-allowlist-cwd.spec.ts +import fs from "fs" +import os from "os" +import path from "path" + import type { ExtensionState } from "@roo-code/types" import { Task } from "../Task" @@ -156,9 +160,24 @@ describe("Task.ask resolves allowlists against the task's workspace", () => { // folder, so folder A's allow entry cannot approve a command in folder B. The // raw global layers are empty, so each decision comes from the command's // folder. The baked pair holds values that no folder composes. - -const FOLDER_A = "/mock/folder-a" -const FOLDER_B = "/mock/folder-b" +// +// A root the filesystem cannot resolve drops the folder layer: the resolver +// compares each root by its real path, so a fictional root would leave the +// global layers deciding alone. `beforeEach` creates the two roots on disk and +// `openTwoFolders()` registers them by that real path, so the registered and +// resolved spellings agree on case-insensitive filesystems. The test below for +// a folder that no longer resolves registers one folder by a spelling the +// filesystem cannot resolve, so the two disagree on purpose. + +let fixtureRoot = "" +let FOLDER_A = "" +let FOLDER_B = "" + +function createFolder(parent: string, name: string): string { + const directory = path.join(parent, name) + fs.mkdirSync(directory) + return fs.realpathSync.native(directory) +} function openTwoFolders() { const folderA = { fsPath: FOLDER_A, uri: { fsPath: FOLDER_A } } @@ -211,6 +230,13 @@ describe("Task.ask judges command asks by the command's working directory", () = workspaceState.workspaceFolders = [] workspaceState.foldersByPath.clear() workspaceState.configScripts = {} + fixtureRoot = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), "ask-allowlist-cwd-"))) + FOLDER_A = createFolder(fixtureRoot, "folder-a") + FOLDER_B = createFolder(fixtureRoot, "folder-b") + }) + + afterEach(() => { + fs.rmSync(fixtureRoot, { recursive: true, force: true }) }) it("approves a command whose custom cwd resolves to the folder that allows it", async () => { @@ -237,6 +263,24 @@ describe("Task.ask judges command asks by the command's working directory", () = expect(await askToRunCommand("/mock/removed-folder", commandState())).toBe("ask") }) + it("does not approve a command from a registered folder that no longer resolves on disk", async () => { + // A folder that was moved or deleted keeps its registry entry. Its real + // path is then unknown, so nothing confirms it holds the command's + // directory. Matching the command against the registered spelling would + // let a root that bounds nothing approve it, so the folder layer is + // dropped and only the global layers decide. + const removedFolder = path.join(fixtureRoot, "removed-folder") + fs.mkdirSync(removedFolder) + fs.rmSync(removedFolder, { recursive: true, force: true }) + const removedUri = { fsPath: removedFolder } + workspaceState.workspaceFolders = [{ fsPath: removedFolder, uri: removedUri }] + workspaceState.foldersByPath.set(removedFolder, removedUri) + // The entry would approve the command if the registered spelling decided. + workspaceState.configScripts = { [removedFolder]: { gate: true, allow: ["echo"] } } + + expect(await askToRunCommand(path.join(removedFolder, "sub"), commandState())).toBe("ask") + }) + it("keeps judging a command without a custom cwd by the task folder's policy", async () => { openTwoFolders() From 0492bc894574e37220ae77cac321f928f1fcbb00 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Fri, 27 Nov 2026 00:50:03 +0100 Subject: [PATCH 39/52] fix: one workspace-layer selector, honest save reporting for command lists Command lists can live in two workspace layers, the workspace folder and the workspace, and the code picked the layer two different ways. The enforcement read treated a folder value stored as null as "no folder override"; the write target treated the same null as an override that exists. A save could therefore create a folder layer no read ever saw, and the save path's mid-save re-read could compare the winning layer against the layer it was about to write. One exported selector now answers which layer holds the list, and the enforcement read, the write target, the mid-save re-read and the activation seed all ask it. The save path also changed in five ways: - It waits for an in-flight command-list import to settle before snapshotting the lists, so it cannot read imported state against a settings file the import has not written yet. - It honours an entry another writer removed during the save instead of writing it back, and keeps entries another writer added. - It reports a conflict and skips the write when the layer it was writing has vanished, rather than recreating it. - It keeps a seeded global entry in the global write while workspace command lists are off, so a save no longer drops an entry the user never removed. - It refuses to act on a rollback read that returned no metadata. That read previously cleared the global key instead of restoring the entries the failed save had removed. The settings dialog now reports a save per list instead of per payload. A list counts as written when the refreshed list holds every entry the dialog sent and none of the entries it dropped, so a list the host reorders or extends no longer reads as a failed write. An answer that arrives before the redraw carrying the save's own lists has committed is held until that redraw arrives, with a timeout as the fallback. A profile switch, a settings import or a discard during a pending save now invalidates it, so a late answer cannot restore a baseline the user discarded, and an edit made while a save is pending keeps the form dirty. The activation test now drives the real persistence trace sink against a fresh module registry, and the settings-import mirror warning no longer blocks the state post. --- src/__tests__/extension.spec.ts | 160 ++++++-- .../__tests__/commandScope.spec.ts | 111 ++++-- src/core/auto-approval/commandScope.ts | 172 +++++++-- .../config/__tests__/importExport.spec.ts | 160 ++++++++ src/core/config/importExport.ts | 170 +++++++-- src/core/webview/ClineProvider.ts | 4 +- .../__tests__/webviewMessageHandler.spec.ts | 352 +++++++++++++++++- src/core/webview/webviewMessageHandler.ts | 112 ++++-- .../__tests__/seedAllowedCommands.spec.ts | 29 +- src/utils/seedAllowedCommands.ts | 37 +- .../src/components/settings/SettingsView.tsx | 220 ++++++++--- .../SettingsView.unsaved-changes.spec.tsx | 311 +++++++++++++++- 12 files changed, 1585 insertions(+), 253 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 0e6b075939..07323445a1 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -87,16 +87,60 @@ const mockTelemetryServiceInstance = { updateTelemetryState: vi.fn(), } -vi.mock("@roo-code/telemetry", () => ({ - TelemetryService: { - createInstance: vi.fn().mockReturnValue(mockTelemetryServiceInstance), - hasInstance: vi.fn().mockReturnValue(true), - get instance() { - return mockTelemetryServiceInstance +// Named so a test that installs its own double can restore this one afterwards +// without cancelling the file-level mock for the tests that follow it. +function permissiveTelemetryModule() { + return { + TelemetryService: { + createInstance: vi.fn().mockReturnValue(mockTelemetryServiceInstance), + hasInstance: vi.fn().mockReturnValue(true), + get instance() { + return mockTelemetryServiceInstance + }, }, - }, - PostHogTelemetryClient: vi.fn(), -})) + PostHogTelemetryClient: vi.fn(), + } +} + +// The real `createInstance()` accepts one instance per process and throws after +// that; `shutdown()` does not reset it +// (packages/telemetry/src/TelemetryService.ts:428-435). A test that activates +// twice needs a factory that keeps that rule, so the second activation fails +// unless the test has discarded the module registry in between. +function singletonTelemetryModule() { + let instance: { + register: ReturnType + setProvider: ReturnType + shutdown: ReturnType + updateTelemetryState: ReturnType + } | null = null + return { + TelemetryService: { + createInstance: vi.fn(() => { + if (instance) { + throw new Error("TelemetryService instance already created") + } + instance = { + register: vi.fn(), + setProvider: vi.fn(), + shutdown: vi.fn(), + updateTelemetryState: vi.fn(), + } + return instance + }), + hasInstance: vi.fn(() => instance !== null), + get instance() { + if (!instance) { + throw new Error("TelemetryService not initialized") + } + return instance + }, + }, + PostHogTelemetryClient: vi.fn(), + } +} + +vi.mock("@roo-code/telemetry", () => permissiveTelemetryModule()) vi.mock("../utils/outputChannelLogger", () => ({ createOutputChannelLogger: vi.fn().mockReturnValue(vi.fn()), @@ -736,47 +780,62 @@ describe("extension.ts", () => { }) test("clears the persistence trace sink before disposing the output channel when seeding rejects", async () => { - // The trace sink logs through the output channel, so the failure path - // must clear it before disposing the channel. + // The trace sink logs through the output channel, so the failure path must + // clear it before disposing the channel. The clear is proved by module state, + // not by the call alone: a trace emitted while the sink is installed reaches + // it, and one emitted afterwards falls through to the module's own console + // sink. A double that recorded the call without changing the sink would leave + // the installed sink in place, so the second trace would still reach it. const vscode = await import("vscode") setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) rejectingCommandListKeys.add("deniedCommands") - const teardownOrder: string[] = [] - // Clearing passes undefined, which restores the default sink. That call marks the order assertion. - const setPersistenceTraceSink = vi.fn((sink?: unknown) => { - if (sink === undefined) { - teardownOrder.push("trace-sink-cleared") - } - }) - vi.doMock("../core/task-persistence/persistenceTrace", () => ({ - setPersistenceTraceSink, - tracePersistenceEvent: vi.fn(), - })) + const persistenceTrace = await import("../core/task-persistence/persistenceTrace") + // Pass-through spy: the real setter still performs the transition. + const setPersistenceTraceSink = vi.spyOn(persistenceTrace, "setPersistenceTraceSink") + const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {}) const { TelemetryService } = await import("@roo-code/telemetry") const shutdown = vi.mocked(TelemetryService.instance.shutdown) + // Shutdown runs after the sink is installed and before it is cleared, so a + // trace emitted here lands inside the window the install opened. shutdown.mockImplementation(() => { - teardownOrder.push("telemetry-shutdown") + persistenceTrace.tracePersistenceEvent("shutdown") return Promise.resolve() }) try { // The same channel `activate` creates, from the same factory double. - // Arming dispose observes the disposal order. const channel = vi.mocked(vscode.window.createOutputChannel)("Test Output") - channel.dispose = vi.fn(() => void teardownOrder.push("channel-disposed")) + channel.dispose = vi.fn() const { activate } = await import("../extension") await expect(activate(mockContext)).rejects.toThrow("seed state write failed") // Reverse acquisition order: the sink goes in after the channel, so it clears // after telemetry shutdown and before the channel. - expect(teardownOrder).toEqual(["telemetry-shutdown", "trace-sink-cleared", "channel-disposed"]) + const [installOrder, clearOrder] = setPersistenceTraceSink.mock.invocationCallOrder + expect(installOrder).toBeLessThan(shutdown.mock.invocationCallOrder[0]) + expect(shutdown.mock.invocationCallOrder[0]).toBeLessThan(clearOrder) + expect(clearOrder).toBeLessThan(vi.mocked(channel.dispose).mock.invocationCallOrder[0]) + // The failure path clears the sink exactly once: install + clear. expect(setPersistenceTraceSink).toHaveBeenCalledTimes(2) expect(setPersistenceTraceSink).toHaveBeenNthCalledWith(1, expect.any(Function)) expect(setPersistenceTraceSink).toHaveBeenNthCalledWith(2, undefined) + + // The sink `activate` installed, read back from the real setter's own + // argument. The teardown-time trace reached it, so the install took effect. + const installedSink = vi.mocked(setPersistenceTraceSink.mock.calls[0][0]) + expect(installedSink).toHaveBeenCalledTimes(1) + expect(consoleLog).not.toHaveBeenCalled() + + // A trace after teardown bypasses the sink and falls through to the + // module's default console sink, so the clear took effect too. + persistenceTrace.tracePersistenceEvent("shutdown") + expect(installedSink).toHaveBeenCalledTimes(1) + expect(consoleLog).toHaveBeenCalledTimes(1) } finally { shutdown.mockReset() - vi.doUnmock("../core/task-persistence/persistenceTrace") + consoleLog.mockRestore() + setPersistenceTraceSink.mockRestore() } }) @@ -796,22 +855,45 @@ describe("extension.ts", () => { test("preserves the stored allow list and retries only the failed deny seed", async () => { // The per-key guard makes the retry cheap: the allow key is set, so only the - // denied key is attempted again. - const vscode = await import("vscode") - setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) - rejectingCommandListKeys.add("deniedCommands") + // denied key is attempted again. The retry models a restarted host, because + // `TelemetryService.shutdown()` does not clear the singleton and + // `createInstance()` throws once one exists + // (packages/telemetry/src/TelemetryService.ts:428-435). The double below + // throws exactly as the real singleton does, so the restart between the two + // activations is what lets the seed run again: without it this test fails at + // `createInstance()` instead of silently passing. + vi.doMock("@roo-code/telemetry", () => singletonTelemetryModule()) + try { + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + rejectingCommandListKeys.add("deniedCommands") - const { activate } = await import("../extension") - await expect(activate(mockContext)).rejects.toThrow("seed state write failed") + const { activate } = await import("../extension") + await expect(activate(mockContext)).rejects.toThrow("seed state write failed") - rejectingCommandListKeys.clear() - vi.mocked(mockContext.globalState.update).mockClear() + rejectingCommandListKeys.clear() + vi.mocked(mockContext.globalState.update).mockClear() - await activate(mockContext) + // The restarted host. A process restart discards every module, so both the + // registry and the mock's own factory must be replaced: the registry alone + // would hand back the singleton the previous activation created. The Memento + // double and its stored values live on the test object, so they survive. + vi.resetModules() + vi.doMock("@roo-code/telemetry", () => singletonTelemetryModule()) + const restartedVscode = await import("vscode") + setConfigScope(restartedVscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + const { activate: activateAfterRestart } = await import("../extension") - expect(vi.mocked(mockContext.globalState.update).mock.calls).toEqual([["deniedCommands", ["docker"]]]) - expect(globalStateValues.get("allowedCommands")).toEqual(["git"]) - expect(globalStateValues.get("deniedCommands")).toEqual(["docker"]) + await activateAfterRestart(mockContext) + + expect(vi.mocked(mockContext.globalState.update).mock.calls).toEqual([["deniedCommands", ["docker"]]]) + expect(globalStateValues.get("allowedCommands")).toEqual(["git"]) + expect(globalStateValues.get("deniedCommands")).toEqual(["docker"]) + } finally { + // Restore, not unmock: cancelling the file-level mock would leave the + // tests after this one running against the real singleton module. + vi.doMock("@roo-code/telemetry", () => permissiveTelemetryModule()) + } }) test("does not shut down telemetry when activation completes", async () => { diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index c3db87c3c0..963399f513 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -8,6 +8,7 @@ import * as vscode from "vscode" import { Package } from "../../../shared/package" import { makeUri, makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { + type CommandListInspection, classifyCommandListBaseline, commandListFolderForResource, getEffectiveCommandDecision, @@ -17,6 +18,7 @@ import { rollbackFailedCommandListWrite, splitCommandListScopes, workspaceCommandListsEnabled, + workspaceLayerValue, } from "../commandScope" import { getSingleCommandDecision } from "../commands" import { checkAutoApproval } from "../index" @@ -402,6 +404,55 @@ describe("resolveWorkspaceWriteTarget", () => { ) }) +describe("workspace layer selection parity", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("reads the workspace layer when the folder value is null, matching the target it writes", () => { + // VS Code reports `null` for a key that settings.json sets to null. That is + // no folder override, so the read takes the workspace value and the target + // is the workspace layer. Reading the fallback while writing the folder + // override would save to a layer no read ever saw. + const inspection: CommandListInspection = { workspaceFolderValue: null, workspaceValue: ["docker"] } + + expect(readCommandListScopes("deniedCommands", [], inspection).workspace).toEqual(["docker"]) + expect(resolveWorkspaceWriteTarget("deniedCommands", inspection)).toBe(vscode.ConfigurationTarget.Workspace) + }) + + it("keeps the folder override for an explicitly empty folder value, matching the target it writes", () => { + // An explicit `[]` is a decision to override the workspace list with + // nothing, so both the read and the target stay on the folder layer. A + // predicate that treated emptiness as absence would write the workspace + // layer and leave the user's clear in place. + const inspection: CommandListInspection = { workspaceFolderValue: [], workspaceValue: ["docker"] } + + expect(readCommandListScopes("deniedCommands", [], inspection).workspace).toEqual([]) + expect(resolveWorkspaceWriteTarget("deniedCommands", inspection)).toBe( + vscode.ConfigurationTarget.WorkspaceFolder, + ) + }) + + // The save path's mid-save re-read asks whether the layer it writes still + // holds a value, not which layer wins. These four states pin that per-layer + // read: a folder override arriving is the folder layer's value, never the + // workspace layer's disappearance. + const layerValueCases: [CommandListInspection, string[] | undefined, string[] | undefined][] = [ + [{ workspaceFolderValue: null, workspaceValue: ["docker"] }, undefined, ["docker"]], + [{ workspaceFolderValue: [], workspaceValue: ["docker"] }, [], ["docker"]], + [{ workspaceValue: ["docker"] }, undefined, ["docker"]], + [{}, undefined, undefined], + ] + + it.each(layerValueCases)( + "reads each layer's own value, so a folder override is not a workspace removal (%#)", + (inspection, expectedFolder, expectedWorkspace) => { + expect(workspaceLayerValue(inspection, "workspaceFolder")).toEqual(expectedFolder) + expect(workspaceLayerValue(inspection, "workspace")).toEqual(expectedWorkspace) + }, + ) +}) + function mockGateConfiguration(gate: unknown) { const config = makeWorkspaceConfiguration() vi.mocked(config.get).mockReturnValue(gate) @@ -1731,41 +1782,6 @@ describe("classifyCommandListBaseline", () => { expect(result.promotionHiddenEntries).toEqual(["docker"]) }) - it("keeps a displayed workspace entry out of the global write when an unchanged gate hides it", () => { - // The workspace layer holds "echo", a global entry shadows it, and the - // dialog displayed it before the gate stayed on. The configuration's global - // layer holds no "echo", so a promotion is the only way it could reach the - // user's global list. Reading the promotion set as the whole hidden set - // would drop "echo" from the workspace origin set, the split would read it - // as brand-new, and the global write would gain it. The baseline keeps it a - // workspace decision instead. - const { promotionHiddenEntries } = classifyCommandListBaseline({ - baseline: ["echo"], - incoming: ["echo"], - currentScopes: { global: [], workspace: ["echo"], merged: [] }, - configGlobalAtSaveStart: [], - globalLayerAtSaveStart: undefined, - hiddenWorkspaceEntries: ["echo"], - gateAtDisplay: true, - }) - - // The save path splits, then re-adds the hidden entries the baseline never - // showed. The baseline showed "echo", so the split alone decides here. - const baseline = ["echo"] - const hiddenWorkspaceEntries = ["echo"] - const { globalWrite, workspaceWrite } = splitCommandListScopes( - ["echo"], - hiddenWorkspaceEntries.filter((entry) => !promotionHiddenEntries.includes(entry)), - [], - ) - const workspaceWriteWithHidden = [ - ...new Set([...workspaceWrite, ...hiddenWorkspaceEntries.filter((entry) => !baseline.includes(entry))]), - ] - - expect(globalWrite).toEqual([]) - expect(workspaceWriteWithHidden).toEqual(["echo"]) - }) - it("treats a baseline of the wrong runtime type as no baseline", () => { // A sender can put anything in the baseline slot. A non-array cannot answer // the display-time question, so the guard keeps the current hidden set @@ -2004,6 +2020,31 @@ describe("rollbackFailedCommandListWrite", () => { expect(writeGlobalLayer).toHaveBeenCalledWith([]) }) + it("leaves another writer's clear in place instead of restoring the entries this save removed", async () => { + // The layer held "git", this save replaced it with "new", and the workspace + // write then failed. A later writer cleared the layer to `[]`. Restoring + // "git" would re-add an entry the user just deleted, so the undo keeps the + // clear. The restore still runs, because the failed write leaves the layer + // half-applied otherwise. + const writeGlobalLayer = vi.fn(async () => undefined) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["new"], + configGlobalAtSaveStart: ["git"], + globalLayerAtSaveStart: ["git"], + globalWriteApplied: true, + readGlobalLayer: () => [], + writeGlobalLayer, + }) + + expect(result).toEqual({ status: "rolled-back" }) + expect(writeGlobalLayer).toHaveBeenCalledTimes(1) + expect(writeGlobalLayer).toHaveBeenCalledWith([]) + expect(writeGlobalLayer).not.toHaveBeenCalledWith(["git"]) + }) + it("reports a failed re-read and writes nothing", async () => { const writeGlobalLayer = vi.fn(async () => undefined) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 1dda96b319..ecad704a77 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -26,7 +26,12 @@ export interface CommandListScopes { */ export interface CommandListInspection { workspaceValue?: string[] - workspaceFolderValue?: string[] + /** + * VS Code reports `null` here for a key that settings.json sets to `null`, + * so the type admits it and {@link selectWorkspaceCommandListLayer} decides + * what it means. + */ + workspaceFolderValue?: string[] | null } /** @@ -115,6 +120,79 @@ function realPathOrRegistered(fsPath: string): string | undefined { } } +export type WorkspaceCommandListLayer = "workspaceFolder" | "workspace" + +export interface WorkspaceCommandListSelection { + /** The layer that owns the workspace list, or `undefined` when none is set. */ + layer: WorkspaceCommandListLayer | undefined + /** The layer's value. It is `undefined` only when `layer` is `undefined`. */ + value: string[] | undefined +} + +/** + * The value one named workspace layer holds, or `undefined` when that layer + * holds none. + * + * This answers a different question from + * {@link selectWorkspaceCommandListLayer}, which answers which layer wins. A + * caller that needs to know whether a specific layer still exists must ask + * here: a folder override appearing mid-save makes the selector report the + * folder layer, and that is not the workspace layer vanishing. + * + * @param inspection - The layers from one `inspect()`, or `undefined` when the + * lookup failed. + * @param layer - The layer to read. + * @returns That layer's list, or `undefined` when it holds none. + */ +export function workspaceLayerValue( + inspection: CommandListInspection | undefined, + layer: WorkspaceCommandListLayer, +): string[] | undefined { + // `!= null` covers both an absent folder value and a stored null, which VS + // Code uses to mean the same thing here: no folder override. An explicit `[]` + // is a real override and survives the test. + const folder = inspection?.workspaceFolderValue + if (layer === "workspaceFolder") { + return folder == null ? undefined : folder + } + return inspection?.workspaceValue +} + +/** + * Decides which configuration layer holds the workspace command list, and what + * that layer holds, from one inspection. Every reader of the workspace layer + * resolves it here: the enforcement read, the write target, and the save path's + * re-read. A caller that picks the layer itself can disagree with the others + * about which layer exists, and then write one layer while reading another. + * + * A `null` folder value means "no folder override", not an override that holds + * nothing. VS Code reports `null` when settings.json sets the key to null, and + * a stored null selects no folder layer, so the workspace value serves instead. + * Reading it as an override would write a folder layer that no read ever saw. + * An explicit `[]` is a real override and keeps the folder layer. + * + * The per-layer rule lives in {@link workspaceLayerValue}, so the layer that + * wins and the layer a caller writes cannot disagree about what "set" means. + * + * @param inspection - The layers from one `inspect()`, or `undefined` when the + * lookup failed. + * @returns The owning layer and its value, both `undefined` when neither layer + * is set. + */ +export function selectWorkspaceCommandListLayer( + inspection: CommandListInspection | undefined, +): WorkspaceCommandListSelection { + const folderValue = workspaceLayerValue(inspection, "workspaceFolder") + if (folderValue !== undefined) { + return { layer: "workspaceFolder", value: folderValue } + } + const workspaceList = workspaceLayerValue(inspection, "workspace") + if (workspaceList !== undefined) { + return { layer: "workspace", value: workspaceList } + } + return { layer: undefined, value: undefined } +} + /** * Reads one auto-approval command list from both configuration layers and * composes the list to enforce and display. @@ -122,7 +200,9 @@ function realPathOrRegistered(fsPath: string): string | undefined { * The workspace layer comes from `inspect()`, not `get()`. `get()` returns the * effective value, which already folds in `globalValue`. A union with the * global layer would count an entry twice and would keep a global removal from - * shrinking the enforced set. + * shrinking the enforced set. Which layer supplies the workspace list is + * {@link selectWorkspaceCommandListLayer}'s decision, so a read agrees with the + * target a save writes. * * @param configKey - The extension configuration key to read. * @param globalList - The list persisted in extension global state. @@ -153,8 +233,7 @@ export function readCommandListScopes( } } - // Folder value wins over workspace value, as in VS Code's precedence. - const workspace = sanitizeCommandList(inspected?.workspaceFolderValue ?? inspected?.workspaceValue) + const workspace = sanitizeCommandList(selectWorkspaceCommandListLayer(inspected).value) // Set union: an entry in both layers collapses to one. const merged = [...new Set([...global, ...workspace])] @@ -206,11 +285,13 @@ export function splitCommandListScopes( /** * Picks the configuration target that owns the current workspace layer for * `configKey`. It reads through the same scoped configuration as - * `readCommandListScopes`. + * `readCommandListScopes`, and takes the layer from + * {@link selectWorkspaceCommandListLayer}, so the target is the layer a read + * saw. * - * - A set `workspaceFolderValue` gives `WorkspaceFolder`. - * - Else a set `workspaceValue` gives `Workspace`. - * - Neither gives `undefined`, so an empty workspace layer never appears in + * - The folder layer gives `WorkspaceFolder`. + * - Else the workspace layer gives `Workspace`. + * - No layer gives `undefined`, so an empty workspace layer never appears in * settings.json. * * @param configKey - The extension configuration key to inspect. @@ -233,13 +314,14 @@ export function resolveWorkspaceWriteTarget( } } - if (inspected?.workspaceFolderValue !== undefined) { - return vscode.ConfigurationTarget.WorkspaceFolder + switch (selectWorkspaceCommandListLayer(inspected).layer) { + case "workspaceFolder": + return vscode.ConfigurationTarget.WorkspaceFolder + case "workspace": + return vscode.ConfigurationTarget.Workspace + default: + return undefined } - if (inspected?.workspaceValue !== undefined) { - return vscode.ConfigurationTarget.Workspace - } - return undefined } export interface CommandListBaselineClassification { @@ -393,12 +475,7 @@ export async function rollbackFailedCommandListWrite(input: { const addedByThisSave = globalWrite.filter((entry) => !configGlobalAtSaveStart.includes(entry)) const removedByThisSave = configGlobalAtSaveStart.filter((entry) => !globalWrite.includes(entry)) // A failed re-read means nothing is safe to write. The save-start fallback - // is the clobber this path avoids. An undo that would empty an absent - // layer clears the key instead of writing `[]`. The activation seed honors - // that clear as the user's override. Respect whose decision the layer - // holds. Another writer's `[]` survives. A layer that holds only this - // save's own write over an absent start is the half-applied save. The - // undo restores its absence. No empty layer remains that no user created. + // is the clobber this path avoids. let freshGlobalValue: string[] | undefined try { freshGlobalValue = input.readGlobalLayer() @@ -408,33 +485,48 @@ export async function rollbackFailedCommandListWrite(input: { message: `Failed to save ${key}: ${failure}. The global-scoped value could not be re-read to undo this save: ${reReadError}. Review the command lists in your user and workspace settings.`, } } + // The compensation decides the global layer from four cases, in this order. + // (a) No value now: the layer that existed at save start is gone, so a later + // writer deleted it. Clearing the key is that writer's decision, and the + // entries this save removed must not come back. + // (b) The value now is this save's own write, order aside: the half-applied + // save itself, so the entries this save removed go back. A layer that + // started absent is restored to absence, because an empty layer left + // behind reads back as the user's explicit empty override. + // (c) An empty value now while this save wrote entries: another writer + // cleared the layer. That clear outranks this save's removal, and + // restoring over it would re-add entries the user just deleted. + // (d) Anything else, in particular a value that merely gained entries: the + // difference is not a decision about the entries this save removed, so + // they go back beside the additions. + const globalLayerExistsNow = freshGlobalValue !== undefined + const freshIsThisSavesWrite = + freshGlobalValue !== undefined && + freshGlobalValue.length === globalWrite.length && + freshGlobalValue.every((entry) => globalWrite.includes(entry)) + const freshClearedByAnotherWriter = + freshGlobalValue !== undefined && freshGlobalValue.length === 0 && globalWrite.length > 0 + // Case (c) yields to the clear; cases (b) and (d) restore the removals. Case + // (a) never reaches this list, because it clears the key instead. + const restoreRemovedByThisSave = freshIsThisSavesWrite || !freshClearedByAnotherWriter const globalUndo = [ ...new Set([ ...(freshGlobalValue ?? []).filter((entry) => !addedByThisSave.includes(entry)), - ...removedByThisSave, + ...(restoreRemovedByThisSave ? removedByThisSave : []), ]), ] - const globalLayerExistsNow = freshGlobalValue !== undefined - // A layer that started absent carries another writer's decision only when it - // now holds something beyond this save's own write. A re-read with the same - // entries, order aside, is the half-applied save itself, so the rollback - // restores absence instead of keeping an empty layer. - const ownWriteIntact = - globalLayerAtSaveStart === undefined && - freshGlobalValue !== undefined && - freshGlobalValue.length === globalWrite.length && - freshGlobalValue.every((entry) => globalWrite.includes(entry)) + // Case (b) over a start that held no layer restores the absence itself. An + // empty layer left behind would read back as the user's explicit override. + const ownWriteRestoresAbsence = + globalLayerAtSaveStart === undefined && freshIsThisSavesWrite && globalUndo.length === 0 try { if (!globalLayerExistsNow) { - // The key had a layer at save start, so its absence now is a deletion by a - // later writer. That decision outranks this save's removed delta, exactly as - // another writer's `[]` does. Writing the removed entries back would - // resurrect a layer the user deleted. + // Case (a): the key had a layer at save start, so its absence now is a + // deletion by a later writer. That decision outranks this save's removed + // delta, exactly as another writer's `[]` does. Writing the removed entries + // back would resurrect a layer the user deleted. await input.writeGlobalLayer(undefined) - } else if (globalUndo.length === 0 && ownWriteIntact) { - // The re-read found only this save's own write over an absent start, and - // nothing remains to restore. Clear the key rather than materialize an - // empty layer that no user created. + } else if (ownWriteRestoresAbsence) { await input.writeGlobalLayer(undefined) } else { await input.writeGlobalLayer(globalUndo) @@ -562,7 +654,7 @@ export function getEffectiveCommandDecision(command: string, effective: Effectiv return getSingleCommandDecision(command, effective.keptWorkspaceAllow, effective.keptWorkspaceDeny) } -function sanitizeCommandList(list: unknown): string[] { +export function sanitizeCommandList(list: unknown): string[] { if (!Array.isArray(list)) { return [] } diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 59c390ec8a..c0f347ec69 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -11,6 +11,8 @@ import { clearAllMocks } from "../../../test-utils/reset" import { makeExtensionContext } from "../../../test-utils/vscode" import { + awaitCommandListImportSettled, + beginCommandListImport, importSettings, importSettingsFromFile, importSettingsFromPath, @@ -22,6 +24,7 @@ import { ProviderSettingsManager } from "../ProviderSettingsManager" import { ContextProxy } from "../ContextProxy" import { CustomModesManager } from "../CustomModesManager" import { Package } from "../../../shared/package" +import { flushMacrotasks } from "../../../test-utils/timers" import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { safeWriteJson } from "../../../utils/safeWriteJson" @@ -875,6 +878,163 @@ describe("importExport", () => { showWarningMessageSpy.mockRestore() }) + it("posts the imported state while the mirror warning is still pending", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git"] })) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + mockContextProxy.setValues.mockResolvedValue(undefined) + mockContextProxy.setValue.mockResolvedValue(undefined) + mockContextProxy.setProviderSettings.mockResolvedValue(undefined) + + const config = makeWorkspaceConfiguration() + // Both attempts fail, so the mirror reports the key it could not write. + vi.mocked(config.update).mockRejectedValue(new Error("settings file is locked")) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + // Never resolved: the real promise settles only when the user dismisses the + // warning, so an awaited warning would stall the import here. + const dismissal = createDeferred() + const showWarningMessageSpy = vi + .spyOn(vscode.window, "showWarningMessage") + .mockReturnValue(dismissal.promise) + + const provider = feedbackProvider() + + await importSettingsWithFeedback( + { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider, + }, + filePath, + ) + + expect(provider.postStateToWebview).toHaveBeenCalledTimes(1) + expect(showWarningMessageSpy).toHaveBeenCalledWith(expect.stringContaining("allowedCommands")) + + showWarningMessageSpy.mockRestore() + }) + + it("lets a save dispatched during an import run only against the post-import configuration", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git", "imported"] })) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + mockContextProxy.setValues.mockResolvedValue(undefined) + mockContextProxy.setValue.mockResolvedValue(undefined) + mockContextProxy.setProviderSettings.mockResolvedValue(undefined) + + const mirrorWrite = createDeferred() + // The settings file the save reads. It stays empty until the mirror's write + // lands, which is the half-imported state the save must not observe. + let fileHolds: string[] | undefined + const config = makeWorkspaceConfiguration() + vi.mocked(config.update).mockImplementation(async (key, value) => { + await mirrorWrite.promise + if (key === "allowedCommands") { + fileHolds = value as string[] + } + }) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + const imported = importSettingsWithFeedback( + { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider: feedbackProvider(), + }, + filePath, + ) + + await vi.waitFor(() => + expect(config.update).toHaveBeenCalledWith( + "allowedCommands", + ["git", "imported"], + vscode.ConfigurationTarget.Global, + ), + ) + + // A save that reads the settings file here sees the pre-import one, which is + // why the save path waits for the span to settle first. + let saveObserved: string[] | undefined | "not-yet" = "not-yet" + const save = awaitCommandListImportSettled().then(() => { + saveObserved = fileHolds + }) + + await Promise.resolve() + expect(saveObserved).toBe("not-yet") + + mirrorWrite.resolve() + await imported + await save + + expect(saveObserved).toEqual(["git", "imported"]) + }) + + it("settles the import span when the import throws", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git"] })) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + mockContextProxy.setValues.mockResolvedValue(undefined) + mockContextProxy.setValue.mockResolvedValue(undefined) + mockContextProxy.setProviderSettings.mockResolvedValue(undefined) + + const config = makeWorkspaceConfiguration() + // `mirrorCommandList` catches a failed write, so the span's own `finally` + // is the path under test rather than the retry. + vi.mocked(config.update).mockResolvedValue(undefined) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + const provider = feedbackProvider() + provider.postStateToWebview.mockRejectedValue(new Error("state post failed")) + + await expect( + importSettingsWithFeedback( + { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider, + }, + filePath, + ), + ).rejects.toThrow("state post failed") + + // A save that arrives after the failed import must not wait for a span + // whose owner is gone. + await expect(awaitCommandListImportSettled()).resolves.toBeUndefined() + }) + + it("keeps the span open until every overlapping import releases it", async () => { + const firstRelease = beginCommandListImport() + const secondRelease = beginCommandListImport() + + let settled = false + const save = awaitCommandListImportSettled().then(() => { + settled = true + }) + + // The first import leaving its window does not mean the settings file is + // whole: the second import is still between its state write and its mirror, + // so a save released here would read the file mid-import. + firstRelease() + await flushMacrotasks() + expect(settled).toBe(false) + + secondRelease() + await save + expect(settled).toBe(true) + + // Both handles are safe to call again, and the span they shared settles once. + firstRelease() + secondRelease() + await expect(awaitCommandListImportSettled()).resolves.toBeUndefined() + }) + it("should handle import when reasoning budget fields are missing from config", async () => { // This test verifies that import works correctly when reasoning budget fields are not present diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index d1000f264f..56a0314861 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -365,6 +365,89 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }: } } +/** The open span. `openers` counts the imports still inside the window, so it settles at zero. */ +type CommandListSpan = { + promise: Promise + settle: () => void + openers: number +} + +/** + * The command-list span of the imports that have not settled yet. + * + * An import writes the lists to extension state and then mirrors them into the + * user settings file. A save that runs between those two points reads the + * imported state against the old file, so the save path awaits `promise` before + * it takes its snapshot. `openers` counts the imports still inside that window: + * the span covers all of them and settles when the last one releases. + */ +let inFlightCommandListImport: CommandListSpan | undefined + +/** Opens a span with one owner and makes it the span a save awaits. */ +function openCommandListSpan(): CommandListSpan { + let settle!: () => void + const promise = new Promise((resolve) => { + settle = resolve + }) + const span: CommandListSpan = { promise, settle, openers: 1 } + inFlightCommandListImport = span + return span +} + +/** Builds the release handle one opener holds, so no release can count for another. */ +function releaseOnce(span: CommandListSpan): () => void { + let released = false + + return () => { + if (released) { + return + } + + released = true + span.openers -= 1 + + if (span.openers > 0) { + return + } + + // Cleared before settling, so a save that starts after the last release sees + // no span in flight rather than waiting for one that already ended. + inFlightCommandListImport = undefined + span.settle() + } +} + +/** + * Opens the command-list span of an import. + * + * @returns A release function that settles the span once every opener has called + * it. Calling it more than once is safe. An import that opens while another is + * in flight joins the same span and counts as an owner, so the span settles when + * the last owner releases and a save never waits on a span whose release was + * discarded. + */ +export function beginCommandListImport(): () => void { + const joined = inFlightCommandListImport + + if (joined === undefined) { + return releaseOnce(openCommandListSpan()) + } + + joined.openers += 1 + return releaseOnce(joined) +} + +/** + * Waits for an import's command-list span to settle. + * + * Resolves immediately when no import is in flight. The wait is bounded by the + * import itself: the mirror retries once and then reports, and every caller + * releases in a `finally`, so a throwing import cannot leave a save waiting. + */ +export async function awaitCommandListImportSettled(): Promise { + await inFlightCommandListImport?.promise +} + /** * Writes one imported command list into the user settings file, retrying a * failed write once. @@ -405,24 +488,36 @@ async function mirrorCommandList(key: "allowedCommands" | "deniedCommands", impo * @param globalSettings - The global settings an import produced, or `undefined`. */ export async function mirrorImportedCommandLists(globalSettings: GlobalSettings | undefined): Promise { - const failedKeys: string[] = [] + // The span covers the writes below, so a save cannot read the imported state + // against a settings file this function has not finished writing. An enclosing + // import that already opened a span joins it as a second owner, so neither + // release can settle the span while the other is still writing. + const releaseCommandListImport = beginCommandListImport() - for (const key of ["allowedCommands", "deniedCommands"] as const) { - const imported = globalSettings?.[key] - if (!Array.isArray(imported)) { - continue - } + try { + const failedKeys: string[] = [] + + for (const key of ["allowedCommands", "deniedCommands"] as const) { + const imported = globalSettings?.[key] + if (!Array.isArray(imported)) { + continue + } - if (!(await mirrorCommandList(key, imported))) { - failedKeys.push(key) + if (!(await mirrorCommandList(key, imported))) { + failedKeys.push(key) + } } - } - if (failedKeys.length > 0) { - await vscode.window.showWarningMessage( - `Settings import: the command list(s) ${failedKeys.join(", ")} could not be written to VS Code user settings. ` + - `Set them in user settings, or import the file again. Until they are stored there, a later save can remove the imported entries.`, - ) + if (failedKeys.length > 0) { + // Fire-and-forget: this promise settles only when the user dismisses the + // warning, and the caller's state post must not wait for a human answer. + void vscode.window.showWarningMessage( + `Settings import: the command list(s) ${failedKeys.join(", ")} could not be written to VS Code user settings. ` + + `Set them in user settings, or import the file again. Until they are stored there, a later save can remove the imported entries.`, + ) + } + } finally { + releaseCommandListImport() } } @@ -438,29 +533,40 @@ export const importSettingsWithFeedback = async ( ) => { let result - if (filePath) { - // Validate file path and check if file exists - try { - // Check if file exists and is readable - await fs.access(filePath, fs.constants.F_OK | fs.constants.R_OK) - result = await importSettingsFromPath(filePath, { - providerSettingsManager, - contextProxy, - customModesManager, - }) - } catch (error) { - result = { - success: false, - error: `Cannot access file at path "${filePath}": ${error instanceof Error ? error.message : "Unknown error"}`, + // The span starts before the import, because the command-list state write + // happens inside it, and the mirror joins the same span. The notifications + // below stay outside it: their promises settle only on dismissal. + const releaseCommandListImport = beginCommandListImport() + + try { + if (filePath) { + // Validate file path and check if file exists + try { + // Check if file exists and is readable + await fs.access(filePath, fs.constants.F_OK | fs.constants.R_OK) + result = await importSettingsFromPath(filePath, { + providerSettingsManager, + contextProxy, + customModesManager, + }) + } catch (error) { + result = { + success: false, + error: `Cannot access file at path "${filePath}": ${error instanceof Error ? error.message : "Unknown error"}`, + } } + } else { + result = await importSettings({ providerSettingsManager, contextProxy, customModesManager }) + } + + if (result.success) { + await mirrorImportedCommandLists(result.globalSettings) } - } else { - result = await importSettings({ providerSettingsManager, contextProxy, customModesManager }) + } finally { + releaseCommandListImport() } if (result.success) { - await mirrorImportedCommandLists(result.globalSettings) - provider.settingsImportedAt = Date.now() await provider.postStateToWebview() provider.settingsImportedAt = undefined diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index a3665c4928..223f1fb245 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -4353,8 +4353,8 @@ export class ClineProvider if (configuration) { await this.setValues(configuration) - // Global target on purpose: these writes mean "start this task with - // exactly this auto-approval policy". The settings dialog splits by scope. + // Global target on purpose: these writes set the global layer only. A workspace layer still + // affects the task while the workspace-command-lists gate is on; the settings dialog splits the scopes. if (configuration.allowedCommands) { await vscode.workspace .getConfiguration(Package.name) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index f79bba6b71..7dac19f604 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -70,6 +70,7 @@ vi.mock("../rulesMessageHandler", () => ({ // The import case needs no real import: the shared import function is a mock, // and the save tests script the configuration state directly. vi.mock("../../config/importExport", () => ({ + awaitCommandListImportSettled: vi.fn(), exportSettings: vi.fn(), importSettingsWithFeedback: vi.fn(), })) @@ -89,7 +90,7 @@ import * as vsCodeLmProvider from "../../../api/providers/vscode-lm" import * as copilotProvider from "../../../api/providers/github-copilot" import { Package } from "../../../shared/package" -import { importSettingsWithFeedback } from "../../config/importExport" +import { awaitCommandListImportSettled, importSettingsWithFeedback } from "../../config/importExport" import { readCommandListScopes } from "../../auto-approval/commandScope" import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { seedCommandList } from "../../../utils/seedAllowedCommands" @@ -2204,6 +2205,37 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { return { update, inspect } } + it("holds the save's first configuration read until an in-flight command-list import settles", async () => { + // The import mirrors its lists into the settings file after it writes the state + // copy. A save that read the configuration before the mirror landed would + // snapshot the pre-import file and write that list back. The guard therefore + // has to settle before the save's first inspect(), not merely be called. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { inspect } = mockCommandConfiguration({ globalValue: ["git"] }) + + // A deferred stand-in for the import span, so the test decides when it settles. + let settleImport: () => void = () => {} + vi.mocked(awaitCommandListImportSettled).mockImplementationOnce( + () => new Promise((resolve) => (settleImport = () => resolve())), + ) + + const save = webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"] }, + }) + + // The span is still open, so no snapshot may have been taken yet. A save that + // skipped the wait reaches inspect() synchronously here and fails this. + await Promise.resolve() + expect(inspect).not.toHaveBeenCalled() + + settleImport() + await save + + // The snapshot the save acts on is the post-import one. + expect(inspect).toHaveBeenCalled() + }) + it("keeps workspace-scoped denied commands out of the global write when saving the merged list", async () => { // Gate on: the workspace entry is visible in the dialog, so keeping it is not // a re-add. With the gate off every submitted workspace entry is a re-add, @@ -2408,8 +2440,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { ["docker"], vscode.ConfigurationTarget.WorkspaceFolder, ) - // This save deleted "drop" from the global layer, so the undo restores it. - expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", ["drop"], vscode.ConfigurationTarget.Global) + // This save removed "drop", and another writer then cleared the layer to `[]`. + // That clear outranks this save's removal, so the undo keeps it instead of + // re-adding an entry the user just deleted. + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", [], vscode.ConfigurationTarget.Global) expect(update).toHaveBeenCalledTimes(3) // The failed key skips its extension global-state write... expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) @@ -2727,12 +2761,308 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + // The retained workspace entry survives at its own scope. A save that wrote + // `[]` here would delete it from the settings file while keeping the global + // half, so the workspace write is asserted, not only the global one. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) // The entry the baseline shows is not re-added as hidden, so the workspace // layer is rewritten without it: its submitted copy is retained as workspace // state, not promoted. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) + it("keeps a displayed workspace entry the global layer shadows in the workspace write and out of the global write", async () => { + // The workspace layer holds "echo" and a global entry shadows it, so the + // entry is hidden at save time. The dialog displayed it before, because the + // baseline names it. Reading the promotion set as the whole hidden set would + // drop "echo" from the workspace origin set, the split would then read it as + // brand-new, and the global write would gain it. The baseline keeps it a + // workspace decision instead. + const { update } = mockCommandConfiguration({ workspaceValue: ["echo"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["echo"] }, + commandListBaseline: { deniedCommands: ["echo"], workspaceCommandListsEnabled: true }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + }) + + it("keeps a state-only seeded global entry that also sits in the workspace layer", async () => { + // A fresh profile seeds the extension global state, not the settings file, so + // the configuration has no global layer at save start while the state copy + // holds "aws". The same entry also sits in the workspace layer. + // `classifyCommandListBaseline` keeps the state-only entry in + // `splitSourceEntries` when `globalLayerAtSaveStart` is `undefined`, because + // the activation seed wrote it. The split's origin set must agree, or the + // split reads "aws" + // as new, emits it in neither write, and the state copy loses it. The gate is + // off, so the workspace layer enforces nothing and the global layer is the + // only home the entry has. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) + const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "docker"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["aws", "docker"] }, + // The baseline shows both entries, so neither is a re-add. Without it every + // workspace entry would count as new and the gate-off re-add would promote + // both, which is a different behaviour from the one this case pins. + commandListBaseline: { deniedCommands: ["aws", "docker"], workspaceCommandListsEnabled: false }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws", "docker"], vscode.ConfigurationTarget.Workspace) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) + }) + + it("reports a conflict and compensates the global write when the folder override vanishes mid-save", async () => { + // The save targets the folder layer. While the global write runs, another + // writer removes that override, leaving only the workspace value. Reading the + // fallback would copy the shared entries into the folder layer and recreate + // the override the other writer removed. The save reports the conflict and + // undoes its own global write instead. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + { globalValue: ["aws"], workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, + [undefined, undefined], + // Save start holds the folder override; the second entry answers the + // unguarded read for the opposite key; the third is the merge re-read, which + // finds only the workspace value because the override is gone; the fourth is + // the undo's re-read. + [ + { globalValue: ["aws"], workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, + { workspaceValue: ["npm"] }, + { workspaceValue: ["npm"] }, + { globalValue: [] }, + ], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + // No folder-target write at all: recreating the override is the defect. + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.WorkspaceFolder, + ) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(2) + // The failed key skips its state write, and the conflict is reported. + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.stringContaining("removed during the save")) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + + it("lands both writes when a folder override appears while a workspace-target save runs", async () => { + // The save targets the workspace layer, so that layer is the one it must + // still find at the re-read. A folder override appearing mid-save outranks + // it in enforcement but does not remove it. Reading the selector's winner + // instead would call the workspace layer gone, refuse a valid save, and undo + // its global half. The merge must also take the workspace layer's own value: + // copying the folder override's entries would leak project entries into the + // user's workspace settings. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update, inspect } = mockCommandConfiguration( + { globalValue: ["aws"], workspaceValue: ["docker"] }, + [undefined, undefined], + // Save start holds only the workspace layer. The second entry answers the + // unguarded read for the opposite key. The third is the merge re-read, which + // finds the folder override another writer added and the workspace value + // still in place. + [ + { globalValue: ["aws"], workspaceValue: ["docker"] }, + {}, + { globalValue: ["aws"], workspaceValue: ["docker"], workspaceFolderValue: ["npm"] }, + ], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + // The global half is not rolled back: no second global write undoes it. + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + // The workspace write lands on the layer the save targeted, and it carries the + // workspace layer's entry, never the folder override's. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.arrayContaining(["npm"]), + vscode.ConfigurationTarget.Workspace, + ) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.WorkspaceFolder, + ) + expect(update).toHaveBeenCalledTimes(2) + // The save completes, so the state write happens and no error is reported. + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + // Exactly the three scripted reads: the snapshot, the opposite key, and the + // merge re-read. A fourth would mean the re-read got no inspection object and + // the check under test was skipped. + expect(inspect).toHaveBeenCalledTimes(3) + }) + + it("does not write a blank workspace entry back when the layer holds one at the merge re-read", async () => { + // The workspace layer holds a blank entry, which the schema admits and a hand + // edit or a synced dotfile can produce. The save-start read drops it, so the + // start side never contains it. The merge re-read sees the layer itself, and + // an entry the start side lacks counts as added by another writer. Unsanitised, + // that reading writes the blank entry back and the save can never remove it. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update, inspect } = mockCommandConfiguration( + { globalValue: ["aws"], workspaceValue: ["docker"] }, + [undefined, undefined], + // The second entry answers the unguarded read for the opposite key. The + // third is the merge re-read, which finds the layer still holding the blank + // entry beside the entry the dialog kept. + [ + { globalValue: ["aws"], workspaceValue: ["docker"] }, + {}, + { globalValue: ["aws"], workspaceValue: ["docker", ""] }, + ], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + // The workspace write carries only what the save-start side knew about. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.arrayContaining([""]), + vscode.ConfigurationTarget.Workspace, + ) + expect(update).toHaveBeenCalledTimes(2) + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + expect(inspect).toHaveBeenCalledTimes(3) + }) + + it("does not restore a workspace entry another writer removed during the global write", async () => { + // The dialog submitted "keep" and "drop", and both sat in the workspace layer + // at save start. While the global write runs, another writer removes "drop". + // A pure union of the submission and the fresh read writes "drop" back, which + // undoes that removal. The save applies the submission to the fresh value + // instead: it keeps what both still hold, honors the removal, and preserves + // what the other writer added. + const update = vi.fn() + const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) + let workspaceLayer = ["keep", "drop"] + const inspect: vscode.WorkspaceConfiguration["inspect"] = (section: string) => ({ + key: section, + workspaceValue: workspaceLayer as T, + }) + config.inspect = inspect + config.update = update + update.mockImplementation(async (_key: string, _value: unknown, target?: number) => { + if (target === vscode.ConfigurationTarget.Global) { + workspaceLayer = ["keep", "concurrent"] + } + return undefined + }) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["keep", "drop"] }, + }) + + expect(update).toHaveBeenCalledWith( + "deniedCommands", + ["keep", "concurrent"], + vscode.ConfigurationTarget.Workspace, + ) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + ["keep", "drop", "concurrent"], + vscode.ConfigurationTarget.Workspace, + ) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + ["keep", "drop"], + vscode.ConfigurationTarget.Workspace, + ) + }) + + it("reports a failed re-read and writes nothing when the undo finds no inspection object", async () => { + // An inspection that returns no object is not evidence about the layer, so the + // rollback must refuse it. Treating the missing value as a deleted layer would + // clear the key instead of restoring what this save removed. The key reports + // the failure and skips its state write. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked"))], + // Save start, merge re-read, then the undo's re-read: the last returns no + // inspection object at all, which is the failed read this case pins. + [{ globalValue: ["drop"], workspaceValue: ["docker"] }, undefined, undefined], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + // The undo writes nothing: no clear, no restore. + expect(update).toHaveBeenCalledTimes(2) + expect(update).not.toHaveBeenCalledWith("deniedCommands", undefined, vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["drop"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + expect.stringContaining("could not be re-read to undo this save"), + ) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + + it("still clears the key when the undo's inspection object reports no global value", async () => { + // The other side of the boundary: an inspection object that reports no + // global value is a genuine absent layer, so the rollback keeps taking the + // absent-layer branch and clears the key. Collapsing this case into the + // failed-read path would leave the layer half-applied. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + // Save start, merge re-read, then the undo's re-read, which finds the + // inspection object but no global value. + [{ globalValue: ["drop"], workspaceValue: ["docker"] }, undefined, undefined, {}], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(3) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") + }) + it("does not promote a baseline entry an external edit removed from the layers", async () => { // The dialog displayed "docker" from the workspace layer. While it was open the // settings file lost it, so the save-start snapshot holds it in neither layer. @@ -2943,7 +3273,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, undefined, undefined], + // The layer is present but holds no global value: an absent layer, not a + // failed read. No inspection object at all is the failed read. + [{ globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, undefined, {}], true, ) @@ -3016,7 +3348,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["docker"] }, undefined, undefined, undefined], + // Both legs find an inspection object that reports no global value, which is + // the absent-layer shape. A missing object is a failed read instead. + [{ workspaceValue: ["docker"] }, undefined, undefined, {}], true, ) @@ -3036,7 +3370,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update: clearedMidSave } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ globalValue: ["aws"], workspaceValue: ["docker"] }, undefined, undefined, undefined], + [{ globalValue: ["aws"], workspaceValue: ["docker"] }, undefined, undefined, {}], true, ) @@ -3811,7 +4145,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // while the dialog was open. No direct file edit refreshes the extension-state // copy. Treating that stale copy as proof the entry remains would restore the // deleted entry over the file. Only the configuration layers can disprove a - // removal, so the retained-entry filter must not consult the state copy. + // removal, so `splitSourceEntries` must not consult the state copy. // External removal wins over the stale buffer. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["curl"] : undefined, @@ -3843,8 +4177,8 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // A default install holds nothing in the user-level settings. Activation seeded // the built-in defaults into extension state. No global configuration layer // exists, so the state copy is the only evidence that the displayed entries - // have a home. A retained-entry filter that ignores the state copy treats those - // entries as externally removed. The split drops them, and the Global write + // have a home. A `splitSourceEntries` clause that ignores the state copy treats + // those entries as externally removed. The split drops them, and the Global write // clears the layer to []. The emptied state then stops activation from ever // seeding the defaults again. No configuration layer contradicts the state // copy, so the retention stands and the save writes the defaults back. diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index c2d39586b4..2456dbace8 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -66,14 +66,17 @@ import { changeLanguage, t } from "../../i18n" import { Package } from "../../shared/package" import { type CommandListInspection, + type WorkspaceCommandListLayer, classifyCommandListBaseline, commandListConfiguration, readCommandListScopes, resolveEffectiveCommandLists, resolveWorkspaceWriteTarget, rollbackFailedCommandListWrite, + sanitizeCommandList, splitCommandListScopes, workspaceCommandListsEnabled, + workspaceLayerValue, } from "../auto-approval/commandScope" import { type RouterName, toRouterName } from "../../shared/api" import { MessageEnhancer } from "./messageEnhancer" @@ -92,7 +95,7 @@ import { searchWorkspaceFiles } from "../../services/search/file-search" import { fileExistsAtPath } from "../../utils/fs" import { playTts, setTtsEnabled, setTtsSpeed, stopTts } from "../../utils/tts" import { searchCommits } from "../../utils/git" -import { exportSettings, importSettingsWithFeedback } from "../config/importExport" +import { awaitCommandListImportSettled, exportSettings, importSettingsWithFeedback } from "../config/importExport" import { getOpenAiModels } from "../../api/providers/openai" import { getVsCodeLmModels } from "../../api/providers/vscode-lm" import { getGitHubCopilotViewState } from "../../services/language-models/copilotViewState" @@ -840,6 +843,11 @@ export const webviewMessageHandler = async ( ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) : [] + // An import writes the lists to state and then mirrors them into the + // settings file. Waiting for its span keeps this snapshot from reading + // the imported state against the file the import has not written yet. + await awaitCommandListImportSettled() + // The webview sends the full merged list. The split needs one inspect() // snapshot before any write, so the workspace layer, the write target, and // the rollback value describe the same state. A guessed-empty workspace @@ -886,10 +894,13 @@ export const webviewMessageHandler = async ( // only the hidden-entry mechanism, never this key's target or rollback. const otherKey = key === "allowedCommands" ? "deniedCommands" : "allowedCommands" const otherScopes = readCommandListScopes(otherKey, commandListGlobalsAtSaveStart[otherKey]) + // One read decides both the hidden set and whether the workspace layer can + // carry an entry through this save. + const workspaceListsEnabled = workspaceCommandListsEnabled() const { hiddenWorkspaceAllow, hiddenWorkspaceDeny } = resolveEffectiveCommandLists( key === "allowedCommands" ? currentScopes : otherScopes, key === "deniedCommands" ? currentScopes : otherScopes, - workspaceCommandListsEnabled(), + workspaceListsEnabled, ) // Hidden entries were never displayed. The gate is off, or a global entry // shadows them. A list cannot delete what it never showed, so a save re-adds @@ -911,6 +922,20 @@ export const webviewMessageHandler = async ( hiddenWorkspaceEntries, gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, }) + // The split treats an entry outside its origin set as new, so the origin set + // decides what the global write may hold. `classifyCommandListBaseline` keeps + // a state-only global entry in `splitSourceEntries` when + // `globalLayerAtSaveStart` is `undefined`, because the activation seed wrote + // that copy and not the user. With the gate off the workspace layer enforces + // nothing, so that entry's only home is the global layer and the origin set + // must hold it. With the gate on the workspace layer carries it, and + // re-writing the seeded copy into the user's settings file would duplicate a + // default the user never added. + const seededGlobalEntries = + !workspaceListsEnabled && globalLayerAtSaveStart === undefined + ? currentScopes.global.filter((entry) => !configGlobalAtSaveStart.includes(entry)) + : [] + const globalOriginEntries = [...new Set([...configGlobalAtSaveStart, ...seededGlobalEntries])] const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( splitSourceEntries, // Hidden entries are not known state. The dialog never displayed them, so a @@ -918,10 +943,7 @@ export const webviewMessageHandler = async ( // layer holds it hidden. Entries the baseline shows displayed are the // exception, because the re-add below restores dropped hidden entries. currentScopes.workspace.filter((entry) => !promotionHiddenEntries.includes(entry)), - // The global origin set must match the retained-entry filter. Only the - // configuration's own global layer proves known global state, because - // the state copy lags direct file edits. - configGlobalAtSaveStart, + globalOriginEntries, ) // The hidden set holds entries the dialog could not display, so re-adding @@ -952,33 +974,62 @@ export const webviewMessageHandler = async ( // the save skips the write, so saving never materializes one. Deletions clear // it with `[]`. if (workspaceTarget !== undefined) { - // The layer can gain entries while the global write runs, and the - // configuration API has no compare-and-set. A re-read here narrows that - // window: entries added since save start are merged in, so this save - // does not overwrite another writer's entry. An entry added inside the - // window that remains between this read and the write is still lost. + // The layer can change while the global write runs, and the configuration + // API has no compare-and-set. A re-read here narrows that window: entries + // added since save start are merged in, so this save does not overwrite + // another writer's entry. An entry added inside the window that remains + // between this read and the write is still lost. let workspaceAtWrite = workspaceWrite + let workspaceLayerVanished = false try { const freshInspection = config.inspect(key) + // No inspection object is no evidence about the layer, so the + // precomputed list stands rather than counting as a removal. if (freshInspection !== undefined) { - const workspaceNow = readCommandListScopes( - key, - globalLayerAtSaveStart, - freshInspection, - ).workspace - // `currentScopes.workspace` is this save's start state, sanitized - // the same way, so an entry it never held is a mid-save addition. - // `globalLayerAtSaveStart` is passed only because the signature - // requires it; `.workspace` does not read it. - const addedDuringSave = workspaceNow.filter( - (entry) => !currentScopes.workspace.includes(entry), - ) - workspaceAtWrite = [...new Set([...workspaceWrite, ...addedDuringSave])] + // Read the target layer's own value, not the layer that wins. + // `selectWorkspaceCommandListLayer` answers which layer wins, so a + // folder override appearing mid-save makes it report the folder + // layer while the workspace layer this save writes still exists. + // Comparing the winner to the target would read that appearance as + // a disappearance, refuse a valid save, and undo its global half. + // The question here is narrower: does the target layer still hold + // a value? Only "no" is a conflict. + const targetLayer: WorkspaceCommandListLayer = + workspaceTarget === vscode.ConfigurationTarget.WorkspaceFolder + ? "workspaceFolder" + : "workspace" + const targetValue = workspaceLayerValue(freshInspection, targetLayer) + if (targetValue === undefined) { + workspaceLayerVanished = true + } else { + // The dialog's submission is the intent. An entry it kept and the + // layer still holds stays; an entry the layer lost was removed by + // another writer, so the save honors that removal instead of + // writing it back. Entries another writer added are preserved. + // The start side is sanitised on read, so the fresh side is too. + // Otherwise an entry the layer holds blank or non-string, which + // the read drops, would count as added here and be written back. + const freshWorkspace = sanitizeCommandList(targetValue) + const keptByBoth = workspaceWrite.filter((entry) => + freshWorkspace.includes(entry), + ) + const addedDuringSave = freshWorkspace.filter( + (entry) => !currentScopes.workspace.includes(entry), + ) + workspaceAtWrite = [...new Set([...keptByBoth, ...addedDuringSave])] + } } } catch { // The global write already landed. Keep the precomputed list rather // than abort a half-applied save over a re-read that cannot complete. } + if (workspaceLayerVanished) { + // Writing would recreate an override another writer removed. The + // global half has landed, so it is undone and the key reported. + throw new Error( + `the ${workspaceTarget === vscode.ConfigurationTarget.WorkspaceFolder ? "workspace-folder" : "workspace"} layer was removed during the save`, + ) + } await config.update(key, workspaceAtWrite, workspaceTarget) } } catch (error) { @@ -993,7 +1044,18 @@ export const webviewMessageHandler = async ( configGlobalAtSaveStart, globalLayerAtSaveStart, globalWriteApplied, - readGlobalLayer: () => config.inspect(key)?.globalValue, + readGlobalLayer: () => { + // The rollback treats a missing value as a layer another writer + // deleted, and it then clears the key. That reading is only safe + // when the inspection exists and reports no global value. No + // inspection object at all says nothing about the layer, so it + // throws, which the helper already answers with `re-read-failed`. + const reInspection = config.inspect(key) + if (reInspection === undefined) { + throw new Error("the configuration value could not be read") + } + return reInspection.globalValue + }, writeGlobalLayer: (value) => config.update(key, value, vscode.ConfigurationTarget.Global), }) diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts index 7c8abb9a40..8019c796e3 100644 --- a/src/utils/__tests__/seedAllowedCommands.spec.ts +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -28,7 +28,8 @@ interface ConfigDouble { defaultValue?: string[] globalValue?: string[] workspaceValue?: string[] - workspaceFolderValue?: string[] + // VS Code reports `null` for a key that settings.json sets to null. + workspaceFolderValue?: string[] | null } effective?: string[] inspectThrows?: boolean @@ -174,6 +175,32 @@ describe("seedCommandList", () => { expect(globalState.get("allowedCommands")).toBeUndefined() }) + it("seeds the declared default when the folder value is stored as null", async () => { + // A stored null selects no folder layer, so it is not an override and must + // not withhold the default. Withholding it leaves enforcement reading an + // empty global list plus no workspace layer, which approves nothing. + const folderA = makeUri("/mock/folder-a") + workspaceState.workspaceFolders = [{ uri: folderA }] + const defaultValue = ["git log", "git diff", "git show"] + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue, + globalValue: undefined, + workspaceFolderValue: null, + workspaceValue: undefined, + }, + effective: defaultValue, + gate: true, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) + expect(globalState.get("allowedCommands")).toEqual(defaultValue) + }) + it("seeds the declared default on a fresh install with no value set at any scope", async () => { const defaultValue = ["git log", "git diff", "git show"] mockConfiguration({ diff --git a/src/utils/seedAllowedCommands.ts b/src/utils/seedAllowedCommands.ts index bba8a83779..a99d88789f 100644 --- a/src/utils/seedAllowedCommands.ts +++ b/src/utils/seedAllowedCommands.ts @@ -1,7 +1,20 @@ import * as vscode from "vscode" -import { commandListConfiguration, workspaceCommandListsEnabled } from "../core/auto-approval/commandScope" -import type { CommandListConfigKey } from "../core/auto-approval/commandScope" +import { + commandListConfiguration, + selectWorkspaceCommandListLayer, + workspaceCommandListsEnabled, +} from "../core/auto-approval/commandScope" +import type { CommandListConfigKey, CommandListInspection } from "../core/auto-approval/commandScope" + +/** + * The layers one `inspect()` reports for a command-list key: the selector's + * workspace layers plus the global and default values the seed chooses between. + */ +interface CommandListSeedInspection extends CommandListInspection { + globalValue?: string[] + defaultValue?: string[] +} /** * Seeds one command-list key from its settings value into extension global @@ -19,7 +32,8 @@ import type { CommandListConfigKey } from "../core/auto-approval/commandScope" * workspace override suppresses the default: array settings replace across * scopes, so seeding past the override would re-grant the approvals it * removed. With the gate off the override is inert, so the default is still - * seeded. + * seeded. A folder value stored as `null` selects no layer, so it suppresses + * nothing. * * @param globalState - The extension global-state memento to seed. * @param configKey - The command-list configuration key to seed. @@ -31,23 +45,18 @@ export async function seedCommandList(globalState: vscode.Memento, configKey: Co // Guard only the lookup. It can fail before the workspace is ready, and a skip // then defers the seed to a later activation. - let inspected: - | { - globalValue?: string[] - defaultValue?: string[] - workspaceValue?: string[] - workspaceFolderValue?: string[] - } - | undefined + let inspected: CommandListSeedInspection | undefined try { inspected = commandListConfiguration().inspect(configKey) } catch { return } - // The `undefined` checks, not truthiness: an explicitly empty array still - // counts as an override. - const workspaceOverride = inspected?.workspaceValue !== undefined || inspected?.workspaceFolderValue !== undefined + // Which layer holds a workspace list is the selector's decision, so the seed + // cannot disagree with the read and write paths about which layer exists. A + // stored `null` folder value selects no layer, an explicit `[]` does, and + // either layer is an override even when it holds nothing. + const workspaceOverride = selectWorkspaceCommandListLayer(inspected).layer !== undefined const seedValue = inspected?.globalValue ?? diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index c6299728de..29a087cb8f 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -123,6 +123,29 @@ const commandListsEquivalent = (left?: string[], right?: string[]) => left === right || (!!left && !!right && left.length === right.length && left.every((entry, index) => entry === right[index])) +// A list's write landed when the refreshed list holds every entry the dialog sent and +// none of the entries the dialog dropped. The host orders the list its own way and may +// add entries of its own, so this is containment plus absence rather than equality: +// equality answers whether the dialog's own baseline moved, which is a different +// question and stays on `commandListsEquivalent`. +const commandListWriteLanded = (baselined: string[], sent: string[], refreshed?: string[]) => { + if (commandListsEquivalent(baselined, sent)) { + return true + } + + // Without a refreshed list there is no evidence either way, and a list the dialog + // changed is the case that needs evidence. Treat it as not landed so the user's + // edit stays on screen. + if (!refreshed) { + return false + } + + return ( + sent.every((entry) => refreshed.includes(entry)) && + baselined.filter((entry) => !sent.includes(entry)).every((entry) => !refreshed.includes(entry)) + ) +} + export interface SettingsViewRef { checkUnsaveChanges: (then: () => void) => void } @@ -195,16 +218,40 @@ const SettingsView = forwardRef(({ onDone, t latestCachedState.current = cachedState // The live host state, read when a save settles. const latestExtensionState = useRef(extensionState) - // Refresh synchronously at commit. The save answer can follow its state post - // immediately, so it must see that post, not the state before it. + // The command lists the save was dispatched from. The host posts its state ahead of + // its answer, so a save whose lists changed can tell whether the post it is owed has + // landed by comparing that post's lists with these. A post carrying any other lists + // is the save's own; a post repeating these leaves the answer waiting. A count of + // posts cannot draw that line, because an unrelated post advances it too. + const dispatchedCommandSnapshot = useRef(undefined) + // A save answer handled before the post carrying its own lists committed. + const heldSaveResult = useRef<{ success: boolean } | undefined>(undefined) + // The running save's settle, reachable from the commit effect and from the timer. + const settleSave = useRef<((success: boolean) => void) | undefined>(undefined) + // Counts the resets that take the edit buffer back. A save settled after one of them + // must not write the baseline it captured before, nor adopt host lists into the + // buffer the user discarded. + const baselineGeneration = useRef(0) + // Refresh synchronously at commit, then apply a held answer: the post carrying the + // save's own lists is the state the answer follows, so this is the first moment the + // settlement can judge the write against it. useLayoutEffect(() => { latestExtensionState.current = extensionState + + const held = heldSaveResult.current + if (!held || commandListSnapshot(extensionState) === dispatchedCommandSnapshot.current) { + return + } + + heldSaveResult.current = undefined + settleSave.current?.(held.success) }, [extensionState]) - // Records the baseline and the lists of the save the host must answer. The - // save-result effect reconciles each list against its own write outcome. - const submittedListSave = useRef<{ baselined: [string[], string[]]; sent: [string[], string[]] } | undefined>( - undefined, - ) + // Records the baseline, the lists and the buffer generation of the save the host + // must answer. The save-result effect reconciles each list against its own write + // outcome. + const submittedListSave = useRef< + { baselined: [string[], string[]]; sent: [string[], string[]]; generation: number } | undefined + >(undefined) // What the dialog last displayed, so a later post counts as an external // change, not a repeat. @@ -302,6 +349,9 @@ const SettingsView = forwardRef(({ onDone, t prevMode.current = mode lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) commandListsTouched.current = false + // The buffer this save would have settled is gone, so a late answer must not + // write the baseline it captured from it. + baselineGeneration.current += 1 setChangeDetected(false) }, [currentApiConfigName, mode, extensionState]) @@ -315,6 +365,8 @@ const SettingsView = forwardRef(({ onDone, t setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) commandListsTouched.current = false + // The import replaced the buffer the pending save submitted. + baselineGeneration.current += 1 setChangeDetected(false) }, [settingsImportedAt, extensionState]) @@ -548,7 +600,15 @@ const SettingsView = forwardRef(({ onDone, t submittedListSave.current = { baselined: [lastDisplayedAllowed, lastDisplayedDenied], sent: [allowedCommands ?? [], deniedCommands ?? []], + // The buffer this save owns. A reset after this line invalidates it, so + // the settle writes no baseline for a buffer the user has discarded. + generation: baselineGeneration.current, } + dispatchedCommandSnapshot.current = commandListSnapshot({ + allowedCommands: lastDisplayedAllowed, + deniedCommands: lastDisplayedDenied, + workspaceCommandListsEnabled: gateAtSubmit, + }) setPendingSaveId(saveId) } @@ -674,74 +734,123 @@ const SettingsView = forwardRef(({ onDone, t if (!pendingSaveId) return const settle = (success: boolean) => { + settleSave.current = undefined + heldSaveResult.current = undefined setPendingSaveId(undefined) + // The answer's flag reports the whole payload. Each list's own write result // comes from the refresh the host posts before its answer. Reconcile each - // edited list: one equal to what was submitted landed, so its baseline stays - // advanced. Every other edited list rolls back to the pre-submit baseline, so - // an unwritten deletion stays a user deletion on retry. Unedited lists keep - // the stamp's baseline. + // edited list: one whose write landed keeps its advanced baseline, and every + // other edited list rolls back to the pre-submit baseline, so an unwritten + // deletion stays a user deletion on retry. Unedited lists keep the stamp's + // baseline. const save = submittedListSave.current submittedListSave.current = undefined - let everyEditedWriteLanded = true - if (save) { - const [stampAllowed, stampDenied, stampGate] = JSON.parse(lastDisplayedCommandSnapshot.current) as [ - string[], - string[], - boolean, - ] - const reconcileList = ( - baselined: string[], - sent: string[], - refreshed: string[] | undefined, - stamped: string[], - ) => - commandListsEquivalent(baselined, sent) - ? stamped - : commandListsEquivalent(refreshed, sent) - ? sent - : baselined - const writeLanded = (baselined: string[], sent: string[], refreshed: string[] | undefined) => - commandListsEquivalent(baselined, sent) || commandListsEquivalent(refreshed, sent) - everyEditedWriteLanded = - writeLanded(save.baselined[0], save.sent[0], latestExtensionState.current.allowedCommands) && - writeLanded(save.baselined[1], save.sent[1], latestExtensionState.current.deniedCommands) - lastDisplayedCommandSnapshot.current = commandListSnapshot({ - allowedCommands: reconcileList( - save.baselined[0], - save.sent[0], - latestExtensionState.current.allowedCommands, - stampAllowed, - ), - deniedCommands: reconcileList( - save.baselined[1], - save.sent[1], - latestExtensionState.current.deniedCommands, - stampDenied, - ), - workspaceCommandListsEnabled: stampGate, - }) + // A reset after submit took the buffer this save owned, so its baselines + // describe lists the dialog no longer shows. + if (!save || save.generation !== baselineGeneration.current) { + return } + + const refreshedAllowed = latestExtensionState.current.allowedCommands + const refreshedDenied = latestExtensionState.current.deniedCommands + const [stampAllowed, stampDenied, stampGate] = JSON.parse(lastDisplayedCommandSnapshot.current) as [ + string[], + string[], + boolean, + ] + const reconcileList = ( + baselined: string[], + sent: string[], + refreshed: string[] | undefined, + stamped: string[], + ) => + commandListsEquivalent(baselined, sent) + ? stamped + : commandListWriteLanded(baselined, sent, refreshed) + ? sent + : baselined + const everyEditedWriteLanded = + commandListWriteLanded(save.baselined[0], save.sent[0], refreshedAllowed) && + commandListWriteLanded(save.baselined[1], save.sent[1], refreshedDenied) + lastDisplayedCommandSnapshot.current = commandListSnapshot({ + allowedCommands: reconcileList(save.baselined[0], save.sent[0], refreshedAllowed, stampAllowed), + deniedCommands: reconcileList(save.baselined[1], save.sent[1], refreshedDenied, stampDenied), + workspaceCommandListsEnabled: stampGate, + }) + // Clear the flag only when nothing is left unsaved. An edit made during the // save, or a list whose write never landed, keeps the hold so a host refresh // cannot replace the user's edit. - if (success && everyEditedWriteLanded && !userEditedDuringSave.current) { - commandListsTouched.current = false - setChangeDetected(false) + if (!success || !everyEditedWriteLanded || userEditedDuringSave.current) { + return } + + commandListsTouched.current = false + + // The hold is gone, so the lists the host posted become what the dialog shows. + // An entry posted during the hold would otherwise stay invisible until the + // host's next post. + const adoptedAllowed = latestExtensionState.current.allowedCommands + const adoptedDenied = latestExtensionState.current.deniedCommands + const adoptedGate = latestExtensionState.current.workspaceCommandListsEnabled + lastDisplayedCommandSnapshot.current = commandListSnapshot({ + allowedCommands: adoptedAllowed, + deniedCommands: adoptedDenied, + workspaceCommandListsEnabled: adoptedGate ?? stampGate, + }) + setCachedState((prevCachedState) => ({ + ...prevCachedState, + allowedCommands: adoptedAllowed ?? prevCachedState.allowedCommands, + deniedCommands: adoptedDenied ?? prevCachedState.deniedCommands, + // An absent gate field is not evidence that the gate changed. + ...(adoptedGate === undefined ? {} : { workspaceCommandListsEnabled: adoptedGate }), + })) + setChangeDetected(false) + } + + // A list the dialog changed can only be judged against a state post that has + // replaced the pre-save lists. Without one, the settle would read the lists from + // before the save and report a landed write as failed. A failed answer needs no + // such judgement, so it settles at once. + const awaitingRefreshedLists = () => { + const save = submittedListSave.current + if (!save) { + return false + } + + const changed = + !commandListsEquivalent(save.baselined[0], save.sent[0]) || + !commandListsEquivalent(save.baselined[1], save.sent[1]) + + return changed && commandListSnapshot(latestExtensionState.current) === dispatchedCommandSnapshot.current } const onResult = (event: MessageEvent) => { const message = event.data if (message?.type !== "settingsSaveResult" || message.requestId !== pendingSaveId) return - settle(message.success === true) + + const success = message.success === true + if (!success || !awaitingRefreshedLists()) { + settle(success) + return + } + + // Hold the answer for the post carrying this save's lists. The layout effect + // that writes `latestExtensionState` applies it against the lists that post + // carries, and leaves it held while the lists are still the pre-save ones. + heldSaveResult.current = { success } } + settleSave.current = settle window.addEventListener("message", onResult) - const timer = setTimeout(() => settle(false), SAVE_ANSWER_TIMEOUT_MS) + // Bounds the wait: a held answer is applied here against the lists the ref holds, + // so no result is left unapplied, and a save with no answer is treated as failed. + const timer = setTimeout(() => settle(heldSaveResult.current?.success ?? false), SAVE_ANSWER_TIMEOUT_MS) return () => { clearTimeout(timer) window.removeEventListener("message", onResult) + settleSave.current = undefined } }, [pendingSaveId]) @@ -766,6 +875,9 @@ const SettingsView = forwardRef(({ onDone, t setCachedState(extensionState) // Revert to original state lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) commandListsTouched.current = false // Buffered edits are gone, so live lists are not held off + // A save still in flight owns the buffer this discard replaced, so its + // answer must not write a baseline taken before the discard. + baselineGeneration.current += 1 setChangeDetected(false) // Reset change flag confirmDialogHandler.current?.() // Execute the pending action (e.g., tab switch) } diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index b61e88d6d9..2767968ee3 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -1,12 +1,12 @@ import { providerIdentifiers, openAiModelInfoSaneDefaults, type ProviderSettings } from "@roo-code/types" -import { screen, fireEvent, waitFor } from "@testing-library/react" +import { act, screen, fireEvent, waitFor } from "@testing-library/react" import { renderWithExtensionState } from "@/utils/test-utils" import { vi, describe, it, expect, beforeEach } from "vitest" import { QueryClient } from "@tanstack/react-query" import React from "react" -import SettingsView from "../SettingsView" +import SettingsView, { SAVE_ANSWER_TIMEOUT_MS } from "../SettingsView" import { vscode } from "@src/utils/vscode" import { answerSave, lastSaveRequestId } from "./saveAcknowledgement" @@ -326,6 +326,10 @@ describe("SettingsView - Unsaved Changes Detection", () => { reasoningBlockCollapsed: true, } + afterEach(() => { + vi.useRealTimers() + }) + beforeEach(() => { vi.clearAllMocks() // Reset the ApiOptions mock to its default implementation @@ -1707,4 +1711,307 @@ describe("SettingsView - Unsaved Changes Detection", () => { view.unmount() } }) + + it("re-enables Save for a new edit after the answer settles the previous save", async () => { + // Save is disabled while the answer is outstanding, so only an edit made after + // the answer proves the settlement was applied rather than merely pending. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( + + ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("edit-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + }) + view.rerender() + answerSave(saveId, { success: true }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // The settle ran: the form went clean, and a fresh edit raises it again. + fireEvent.click(screen.getByTestId("edit-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + }) + + it("settles an answer handled before the state post commits, and applies a held answer on the timeout", async () => { + // The host posts the refreshed lists and then the answer, as two separate + // messages. When the answer is handled first, the dialog's copy still holds the + // pre-save lists. Judging the write against them reports a landed write as + // failed, so the answer waits for the post to commit. With no commit at all, the + // existing timeout applies the held answer instead of leaving it unapplied. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + +
+ ), + ) + + // Both cases start from a dialog holding an unsaved deletion. + const openWithPendingDeletion = async () => { + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + const view = renderWithExtensionState(, { + queryClient, + }) + fireEvent.click(await screen.findByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + return view + } + + // First case: the answer arrives before the post commits, and that post then + // releases it. The settlement sees the landed deletion, so the form goes clean. + const committed = await openWithPendingDeletion() + fireEvent.click(screen.getByTestId("save-button")) + const committedId = lastSaveRequestId(postMessage) + expect(committedId).toBeDefined() + answerSave(committedId, { success: true }) + expect(screen.getByTestId("save-button")).toBeDisabled() + + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: [], + }) + committed.rerender() + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify([])) + committed.unmount() + + // Second case: the answer is held and no post ever follows. The timeout applies + // it, so the save stops waiting instead of leaving the result unapplied. Fake + // timers start before Save, because the timeout is armed by the save's own effect. + const uncommitted = await openWithPendingDeletion() + vi.useFakeTimers() + fireEvent.click(screen.getByTestId("save-button")) + const uncommittedId = lastSaveRequestId(postMessage) + expect(uncommittedId).toBeDefined() + answerSave(uncommittedId, { success: true }) + expect(screen.getByTestId("save-button")).toBeDisabled() + + await act(async () => { + await vi.advanceTimersByTimeAsync(SAVE_ANSWER_TIMEOUT_MS) + }) + vi.useRealTimers() + + // The held answer was applied, so the save is no longer pending. The deletion + // never landed in any post, so the edit stays on screen for retry. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify([])) + uncommitted.unmount() + }) + + it("holds a save answer through an unrelated state post until the save's own lists arrive", async () => { + // The host posts its state for reasons unrelated to a save, and such a post + // repeats the command lists the dialog dispatched from. Judging the answer + // against those lists reports a landed write as failed, so the answer must wait + // for the post carrying the save's own lists. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // A post unrelated to this save commits before the answer: the same lists, a + // different payload. It is not the post the answer is owed. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + }) + view.rerender() + answerSave(saveId, { success: true }) + + // Still held, so the save stays pending: settling here would read the pre-save + // lists and leave the form dirty with Save enabled. + expect(screen.getByTestId("save-button")).toBeDisabled() + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify([])) + + // A second unrelated post lands while the answer is held. It still repeats the + // dispatched lists, so it must not apply the answer either. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + showRelativeTimes: false, + maxOpenTabsContext: 11, + }) + view.rerender() + expect(screen.getByTestId("save-button")).toBeDisabled() + + // The post carrying the save's own lists arrives, and the held answer applies + // against it: the deletion landed, so the form goes clean. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: [], + showRelativeTimes: false, + }) + view.rerender() + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + view.unmount() + }) + + it("keeps the discarded baseline when a pending save settles after the user discards", async () => { + // A discard during a pending save replaces the buffer the save submitted. The + // late answer must not write the baseline it captured from that buffer: doing so + // would make the next save apply a list the user already discarded. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( + + ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // Another writer replaces the list while the save is pending. The user then + // discards, so the dialog shows the new list and owns it as its baseline. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["docker"], + }) + view.rerender() + fireEvent.click(screen.getByText("settings:common.done")) + fireEvent.click(await screen.findByText("settings:unsavedChangesDialog.discardButton")) + + // The answer arrives after the discard, describing the buffer that is gone. + answerSave(saveId, { success: false, error: "storage unavailable" }) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // The discarded baseline stands: the next save submits the list the discard + // restored, not the pre-discard baseline the settled save captured. + fireEvent.click(screen.getByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const saves = updateSettingsPosts() + expect(saves.at(-1)).toEqual( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: expect.objectContaining({ deniedCommands: ["docker"] }), + }), + ) + }) + + it("releases a reordered but landed list and disables Save", async () => { + // The host returns the list in its own order. A landed write must be recognised + // from what the list contains, not from where each entry sits, or a successful + // save leaves Save enabled. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( + + ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("edit-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // Both submitted entries landed, in the host's order rather than the dialog's. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["ls", "echo"], + }) + view.rerender() + answerSave(saveId, { success: true }) + + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + }) + + it("adopts a host list that arrived while the lists were held", async () => { + // A deny entry the host posted during the hold is not shown, because the held + // list edit outranks it. Once the save releases the hold, that entry must become + // visible without waiting for another state post. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-deny-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The host posts the landed deletion together with an entry another writer + // added. The held edit keeps that entry off screen for now. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["docker"], + }) + view.rerender() + answerSave(saveId, { success: true }) + + // Releasing the hold adopts the posted list, so the added entry shows. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + await waitFor(() => + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["docker"])), + ) + }) }) From 51f2e0eb36801f33cbeaa3c08b9f04cdd33f59cd Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Fri, 27 Nov 2026 21:30:11 +0100 Subject: [PATCH 40/52] fix: keep command-list saves, imports, and folder scopes consistent The settings dialog writes the command lists to two stores: the VS Code configuration and the extension state copy. An import writes the same two stores in the opposite order. Several paths could leave the two stores holding different lists, or drop entries the user never saw. Saving: - With the gate off, the dialog shows only the user-level list, so a displayed entry also exists in the hidden workspace layer. Deleting it there deleted both copies. Hidden workspace entries now survive the save. With the gate on, an entry that became hidden after display is still treated as a deletion. - A failed re-read of the workspace layer wrote a list computed before the write, which could overwrite an entry another writer added in the meantime. The save now aborts that key, rolls back the global half, and reports the save as failed, so both stores keep their pre-save values. - A seeded global entry was protected only while the gate was off, so turning the gate on and saving could drop it from the user-level layer. The entry is a known global origin in both gate states. - A save that had already passed the import wait could still write its older list after an import finished. A save now holds a span across its writes and an import waits for that span, so the two cannot write the stores in opposite orders at the same time. Importing: - A failed import left the imported lists in extension state while the settings file kept the old ones. The import now restores the prior lists before it reports the failure. - An import whose settings-file mirror failed left its new entries only in extension state, where the next save read them as external deletions. The entries are now recorded in memory for the life of the process until a mirror for that key succeeds, and the save reads them as known global state. Scoping: - One unresolvable workspace root dropped the whole folder layer, so a healthy folder's deny list stopped applying. An unresolvable root that cannot contain the task folder is now skipped. - Deleting the whole command-list key from user settings looked the same as a seeded copy, so the next save wrote the displayed entries back. The state copy now counts as global state only while it equals the shipped default. Exporting: - The export schema did not omit the workspace command-list gate, so a gate value already in extension state came back out through export. The gate is now omitted. The tests cover each path: the gate-off, gate-on, and gate-flip saves; the aborted workspace write; the import restore and the pending mirror; the folder, classifier, ordering, and export cases; and the settings-dialog assertions that a save settles before Save becomes enabled again. --- .../__tests__/commandScope.spec.ts | 121 ++++- src/core/auto-approval/commandScope.ts | 83 +++- src/core/config/ContextProxy.ts | 2 + .../config/__tests__/ContextProxy.spec.ts | 16 + .../config/__tests__/importExport.spec.ts | 365 ++++++++++++++- src/core/config/importExport.ts | 225 +++++++++- .../__tests__/webviewMessageHandler.spec.ts | 423 ++++++++++++++++-- src/core/webview/webviewMessageHandler.ts | 127 ++++-- .../SettingsView.unsaved-changes.spec.tsx | 20 + 9 files changed, 1265 insertions(+), 117 deletions(-) diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 963399f513..50995befd1 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -1290,9 +1290,9 @@ it("commandListFolderForResource: drops the folder layer when a registered root' vi.clearAllMocks() const rootPath = path.join(path.sep + "mock", "broken-root") const rootUri = makeUri(rootPath) - // A relocated or deleted root has no real path, so nothing confirms that it - // holds the cwd. Matching the cwd against the registered path could claim a - // directory the root does not own, so the lookup gives no folder layer. + // A relocated or deleted root has no real path, so its registered path is all + // that is left. That path bounds the cwd, so the root may own it. Nothing + // confirms it does, and no other root may decide instead. workspaceState.workspaceFolders = [{ uri: rootUri }] vi.mocked(fs.realpathSync).mockImplementation((target) => { if (String(target) === rootPath) { @@ -1324,6 +1324,68 @@ it("commandListFolderForResource: an unresolvable root keeps an enclosing root f expect(commandListFolderForResource(path.join(innerRoot, "sub"))).toBeUndefined() }) +it("checkAutoApproval command: keeps a healthy folder's deny when an unrelated registered root cannot be resolved", async () => { + vi.clearAllMocks() + // The root that owns the cwd resolves. The other root cannot, and its + // registered path cannot bound the cwd either, so it cannot own it. One + // failing root therefore says nothing about this cwd, and the folder that + // does own it keeps its deny. + const healthyRoot = path.join(path.sep + "mock", "healthy-root") + const brokenRoot = path.join(path.sep + "mock", "broken-root") + const healthyUri = makeUri(healthyRoot) + workspaceState.workspaceFolders = [{ uri: healthyUri }, { uri: makeUri(brokenRoot) }] + workspaceState.foldersByPath.set(healthyRoot, healthyUri) + vi.mocked(fs.realpathSync).mockImplementation((target) => { + if (String(target) === brokenRoot) { + throw new Error("ENOENT: no such file or directory") + } + return String(target) + }) + mockFolderConfigurations({ [healthyRoot]: { gate: true, deny: ["echo"] } }) + + const result = await checkAutoApproval({ + // The baked pair would approve exactly what the healthy folder denies. + state: taskFolderState(["echo"]), + cwd: path.join(healthyRoot, "sub"), + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "deny", autoDeny: { kind: "denylist", command: "echo hi", pattern: "echo" } }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, healthyUri) +}) + +it("checkAutoApproval command: keeps an unresolvable root that may hold the cwd from falling through to an enclosing root's allow", async () => { + vi.clearAllMocks() + // The inverse of the case above, and the reason an unresolvable root is not + // simply skipped. The inner root's registered path bounds the cwd, so it may + // own it. The enclosing root resolves and allows the command, but it must not + // decide for a directory the inner root may own: that would approve what the + // inner folder's deny would block. + const outerRoot = path.sep + "mock" + const innerRoot = path.join(outerRoot, "inner") + const outerUri = makeUri(outerRoot) + workspaceState.workspaceFolders = [{ uri: outerUri }, { uri: makeUri(innerRoot) }] + workspaceState.foldersByPath.set(outerRoot, outerUri) + vi.mocked(fs.realpathSync).mockImplementation((target) => { + if (String(target) === innerRoot) { + throw new Error("ENOENT: no such file or directory") + } + return String(target) + }) + mockFolderConfigurations({ [outerRoot]: { gate: true, allow: ["echo"] } }) + + const result = await checkAutoApproval({ + // Empty raw global layers: only a folder layer could approve. + state: taskFolderState([]), + cwd: path.join(innerRoot, "sub"), + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + it("commandListFolderForResource: a path inside no root stays unmatched", () => { vi.clearAllMocks() const rootPath = path.join(path.sep + "mock", "root") @@ -1568,6 +1630,9 @@ describe("classifyCommandListBaseline", () => { stateGlobal: string[] configGlobal: string[] globalLayerAtSaveStart: string[] | undefined + stateCopyIsShippedDefault: boolean + /** Entries an import could not mirror yet. Absent means none are pending. */ + pendingGlobalEntries?: string[] survives: boolean } @@ -1580,6 +1645,7 @@ describe("classifyCommandListBaseline", () => { stateGlobal: [], configGlobal: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, survives: true, }, { @@ -1590,6 +1656,7 @@ describe("classifyCommandListBaseline", () => { stateGlobal: [], configGlobal: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, survives: true, }, { @@ -1600,18 +1667,31 @@ describe("classifyCommandListBaseline", () => { stateGlobal: [], configGlobal: ["git"], globalLayerAtSaveStart: ["git"], + stateCopyIsShippedDefault: false, survives: true, }, { - name: "a baseline entry only the state copy holds survives when the configuration has no global layer", + name: "a baseline entry only the state copy holds survives when that copy is the shipped default", baseline: ["git"], incoming: ["git"], workspace: [], stateGlobal: ["git"], configGlobal: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: true, survives: true, }, + { + name: "a baseline entry only the state copy holds is dropped when the copy is not the shipped default", + baseline: ["git"], + incoming: ["git"], + workspace: [], + stateGlobal: ["git"], + configGlobal: [], + globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + survives: false, + }, { name: "a baseline entry only the state copy holds is dropped when a global layer exists", baseline: ["git"], @@ -1620,8 +1700,21 @@ describe("classifyCommandListBaseline", () => { stateGlobal: ["git"], configGlobal: [], globalLayerAtSaveStart: [], + stateCopyIsShippedDefault: true, survives: false, }, + { + name: "a pending imported entry survives even when the state copy is not the shipped default", + baseline: ["aws"], + incoming: ["aws"], + workspace: [], + stateGlobal: ["aws"], + configGlobal: [], + globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + pendingGlobalEntries: ["aws"], + survives: true, + }, ] it.each(rows)("$name", (row) => { @@ -1631,6 +1724,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: row.stateGlobal, workspace: row.workspace, merged: [] }, configGlobalAtSaveStart: row.configGlobal, globalLayerAtSaveStart: row.globalLayerAtSaveStart, + stateCopyIsShippedDefault: row.stateCopyIsShippedDefault, + pendingGlobalEntries: row.pendingGlobalEntries ?? [], hiddenWorkspaceEntries: [], gateAtDisplay: undefined, }) @@ -1699,6 +1794,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: row.stateGlobal, workspace: row.workspace, merged: [] }, configGlobalAtSaveStart: row.configGlobal, globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: [], gateAtDisplay: undefined, }) @@ -1715,6 +1812,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: [], workspace: ["aws"], merged: [] }, configGlobalAtSaveStart: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: [], gateAtDisplay: undefined, }) @@ -1733,6 +1832,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: [], workspace: ["docker"], merged: [] }, configGlobalAtSaveStart: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: ["docker"], gateAtDisplay: undefined, }) @@ -1742,6 +1843,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: [], workspace: ["docker"], merged: [] }, configGlobalAtSaveStart: ["docker"], globalLayerAtSaveStart: ["docker"], + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: ["docker"], gateAtDisplay: undefined, }) @@ -1757,6 +1860,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: ["aws"], workspace: ["docker"], merged: [] }, configGlobalAtSaveStart: ["aws"], globalLayerAtSaveStart: ["aws"], + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: [], gateAtDisplay: undefined, }) @@ -1775,6 +1880,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: [], workspace: ["git"], merged: [] }, configGlobalAtSaveStart: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: ["git", "docker"], gateAtDisplay: true, }) @@ -1793,6 +1900,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: [], workspace: ["git"], merged: [] }, configGlobalAtSaveStart: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: ["git", "docker"], gateAtDisplay: true, }) @@ -1812,6 +1921,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: [], workspace: ["git"], merged: [] }, configGlobalAtSaveStart: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: ["git", "docker"], gateAtDisplay: true, }) @@ -1826,6 +1937,8 @@ describe("classifyCommandListBaseline", () => { currentScopes: { global: [], workspace: ["git"], merged: [] }, configGlobalAtSaveStart: [], globalLayerAtSaveStart: undefined, + stateCopyIsShippedDefault: false, + pendingGlobalEntries: [], hiddenWorkspaceEntries: ["docker"], gateAtDisplay: undefined, }) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index ecad704a77..324e8715e8 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -32,6 +32,11 @@ export interface CommandListInspection { * what it means. */ workspaceFolderValue?: string[] | null + /** + * The key's shipped default, which a save compares against the state copy to + * tell an activation-seeded copy from a key the user deleted. + */ + defaultValue?: string[] } /** @@ -57,15 +62,16 @@ export function commandListConfiguration(folderResource?: vscode.Uri): vscode.Wo * root claim a symlinked deeper root's directory and skip its deny entries. * The deepest match wins, like VS Code's own containment. * - * A root whose real path does not resolve bounds nothing reliable: its real - * path is unknown, so no candidate can be shown to contain the cwd on its - * behalf. The lookup then returns `undefined`, and no enclosing root approves - * a command by standing in for that root. Enforcement reads the global layer - * only, and the folder layer contributes nothing to the decision. + * A root whose real path does not resolve is judged by its registered path. + * One that cannot bound the cwd cannot own it either, so the remaining roots + * still decide. One that may bound the cwd might own it, so no enclosing root + * approves a command by standing in for it: the lookup returns `undefined`, + * enforcement reads the global layer only, and the folder layer contributes + * nothing to the decision. * * @param cwd - The task's working directory. Empty, absent, unmatched, or - * bounded only by an unresolvable root gives `undefined` and keeps the - * first-folder configuration. + * bound by an unresolvable root gives `undefined` and keeps the first-folder + * configuration. * @returns The containing folder's registry URI. It stays uncanonicalized, * because folder-scoped configuration resolves against the registry. */ @@ -74,8 +80,8 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin return undefined } - // A failed lookup gives `undefined`, like a cwd that names no root. The - // caller then falls back to the pre-composed state lists. + // No folder decides the cwd. The caller then falls back to the pre-composed + // state lists. try { // Longest match wins so an outer root cannot claim a symlinked deeper // root's directory. The separator guard keeps `/root/other` out of `/root`. @@ -84,9 +90,15 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin for (const candidate of vscode.workspace.workspaceFolders ?? []) { const rootPath = realPathOrRegistered(candidate.uri.fsPath) if (rootPath === undefined) { - // The root's real path is unknown, so this candidate cannot be - // compared. Matching the cwd against the other roots would let one - // of them decide for a directory this root may own. + // The root's real path is unknown, so only its registered path is + // left to bound the cwd. One that cannot bound the cwd cannot own + // it, and skipping it lets the healthy roots decide. One that may + // bound the cwd may own it, so no other root may decide instead: + // an enclosing root's allow would otherwise stand in for this + // root's deny. + if (!registeredRootContains(candidate.uri.fsPath, cwd)) { + continue + } return undefined } // A filesystem root (`/`, `C:\`) already ends in a separator. A second separator stops child matching. @@ -102,6 +114,22 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin } } +/** + * Whether a registered root's own path can bound the cwd, tested without the + * real path because this root has none. The cwd arrives canonical, so this + * compare can disagree with the real path when a symlink stands between them. + * That is why it decides only whether a root can own the cwd at all: a root + * that fails this test cannot, and a root that passes may still not. + * + * @param registeredPath - The root's path as the registry holds it. + * @param cwd - The task's working directory. + * @returns True when the registered path bounds the cwd. + */ +function registeredRootContains(registeredPath: string, cwd: string): boolean { + const childPrefix = registeredPath.endsWith(path.sep) ? registeredPath : registeredPath + path.sep + return cwd === registeredPath || cwd.startsWith(childPrefix) +} + /** * The path that a workspace root compares by: its real path. The cwd is * already canonical, so the two sides agree only when both are. The native @@ -109,8 +137,8 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin * JavaScript resolver keeps the caller's spelling on Windows, so a root opened * under different casing would never match a canonical cwd. * - * A root that does not resolve gives `undefined`, which drops the folder layer - * rather than comparing the root by a path the filesystem never confirmed. + * A root that does not resolve gives `undefined`. The caller then decides from + * the root's registered path whether that root can own the cwd. */ function realPathOrRegistered(fsPath: string): string | undefined { try { @@ -350,6 +378,12 @@ export interface CommandListBaselineClassification { * save start. * @param input.globalLayerAtSaveStart - The same layer, kept as absent when the * key had no global value. + * @param input.stateCopyIsShippedDefault - Whether the state copy for this key + * equals the key's shipped default. An absent global layer means a seeded copy + * only when this holds, so a key the user deleted is not read as seeded. + * @param input.pendingGlobalEntries - Entries an import wrote to the state copy + * whose settings-file mirror has not succeeded. No configuration layer holds + * them, and they are known global state all the same. * @param input.hiddenWorkspaceEntries - Workspace entries the dialog did not * display. * @param input.gateAtDisplay - The gate as the dialog showed it, if it sent it. @@ -363,6 +397,8 @@ export function classifyCommandListBaseline(input: { currentScopes: CommandListScopes configGlobalAtSaveStart: string[] globalLayerAtSaveStart: string[] | undefined + stateCopyIsShippedDefault: boolean + pendingGlobalEntries: string[] hiddenWorkspaceEntries: string[] gateAtDisplay: boolean | undefined }): CommandListBaselineClassification { @@ -372,6 +408,8 @@ export function classifyCommandListBaseline(input: { currentScopes, configGlobalAtSaveStart, globalLayerAtSaveStart, + stateCopyIsShippedDefault, + pendingGlobalEntries, hiddenWorkspaceEntries, gateAtDisplay, } = input @@ -399,16 +437,25 @@ export function classifyCommandListBaseline(input: { // the global layer. The baseline separates that case from a user addition. // Submitting a displayed entry signals retention. A retained entry that no // configuration layer holds was removed in the file. The file then wins over - // the stale dialog buffer. The state copy still counts where the - // configuration has no global layer. An absent layer deleted nothing, and the - // activation-seeded defaults would otherwise vanish on the first save. + // the stale dialog buffer. + // An absent global layer means either that the activation seed wrote the state + // copy or that the user deleted the key. Only the state copy that still equals + // the shipped default is the seed's, so only that copy counts as known global + // state. Trusting every absent-layer copy would write a deleted key's entries + // back, and the user would see no warning. + const seededStateEntries = + globalLayerAtSaveStart === undefined && stateCopyIsShippedDefault ? currentScopes.global : [] + // A pending entry is a third source of known global state: an import wrote it + // to the state copy, and its mirror has not reached the settings file. Without + // it, the first save after a failed mirror reads the entry as a file deletion. + const knownStateEntries = [...seededStateEntries, ...pendingGlobalEntries] const splitSourceEntries = Array.isArray(baseline) ? [...incoming, ...externallyAdded].filter( (entry) => !baseline.includes(entry) || currentScopes.workspace.includes(entry) || configGlobalAtSaveStart.includes(entry) || - (currentScopes.global.includes(entry) && globalLayerAtSaveStart === undefined), + knownStateEntries.includes(entry), ) : [...incoming, ...externallyAdded] // A hidden entry the baseline shows was displayed, so keeping it stays a diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index e53f60fb83..548153cbb4 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -67,6 +67,8 @@ const globalSettingsExportSchema = globalSettingsSchema.omit({ taskHistory: true, listApiConfigMeta: true, currentApiConfigName: true, + // The gate is read from VS Code user settings only, so an exported copy would be read back by nothing. + workspaceCommandListsEnabled: true, }) export class ContextProxy { diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 4766f87112..e99964d5b2 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -1151,4 +1151,20 @@ Output only the summary of the conversation so far, without any additional comme expect(customSupportPromptsUpdateCalls.length).toBe(0) }) }) + + describe("export", () => { + it("leaves the workspace command-list gate out of the exported settings, which still carry the keys it does export", async () => { + const proxyWithGate = new ContextProxy(mockContext) + await proxyWithGate.initialize() + await proxyWithGate.setValue("workspaceCommandListsEnabled", true) + await proxyWithGate.setValue("allowedCommands", ["echo"]) + + const exported = await proxyWithGate.export() + + // The gate is read from VS Code user settings only, so an exported copy would be read back by nothing. + expect(exported).not.toHaveProperty("workspaceCommandListsEnabled") + // Negative control: a neighbouring key is exported, so the omission above cannot pass on an empty object. + expect(exported).toHaveProperty("allowedCommands", ["echo"]) + }) + }) }) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index c0f347ec69..257b602f14 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -13,12 +13,15 @@ import { makeExtensionContext } from "../../../test-utils/vscode" import { awaitCommandListImportSettled, beginCommandListImport, + beginCommandListSave, + beginOrderedCommandListSave, importSettings, importSettingsFromFile, importSettingsFromPath, importSettingsWithFeedback, exportSettings, mirrorImportedCommandLists, + pendingCommandListMirrors, } from "../importExport" import { ProviderSettingsManager } from "../ProviderSettingsManager" import { ContextProxy } from "../ContextProxy" @@ -260,6 +263,61 @@ describe("importExport", () => { expect(mockContextProxy.setProviderSettings).not.toHaveBeenCalled() expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("listApiConfigMeta", expect.anything()) }) + + it("restores the prior command lists when a failure follows the state write", async () => { + ;(fs.readFile as Mock).mockResolvedValue( + JSON.stringify({ + providerProfiles: { + currentApiConfigName: "test", + apiConfigs: { + test: { apiProvider: providerIdentifiers.openai, apiKey: "test-key", id: "test-id" }, + }, + }, + globalSettings: { mode: "code", allowedCommands: ["imported"], deniedCommands: ["imported-deny"] }, + }), + ) + + // A double of the two keys the import writes. The failure below lands + // after the state write, so only a restore puts these values back. + const state: { allowedCommands?: string[]; deniedCommands?: string[] } = { + allowedCommands: ["prior"], + deniedCommands: ["prior-deny"], + } + vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" + ? state.allowedCommands + : key === "deniedCommands" + ? state.deniedCommands + : undefined, + ) + mockContextProxy.setValues.mockImplementation(async (values) => { + if (values.allowedCommands) state.allowedCommands = values.allowedCommands + if (values.deniedCommands) state.deniedCommands = values.deniedCommands + }) + mockContextProxy.setValue.mockImplementation(async (key, value) => { + if (key === "allowedCommands") state.allowedCommands = value as string[] + if (key === "deniedCommands") state.deniedCommands = value as string[] + }) + mockProviderSettingsManager.listConfig.mockRejectedValueOnce(new Error("config store is locked")) + + const result = await importSettingsFromPath("/mock/path/settings.json", { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + expect(result).toEqual({ success: false, error: "config store is locked" }) + // The imported lists did reach extension state, so the values asserted + // next were written over and had to be put back. + expect(mockContextProxy.setValues).toHaveBeenCalledWith( + expect.objectContaining({ allowedCommands: ["imported"], deniedCommands: ["imported-deny"] }), + ) + // The settings file was never written, and extension state holds the + // lists it held before the import. + expect(vscode.workspace.getConfiguration).not.toHaveBeenCalled() + expect(state.allowedCommands).toEqual(["prior"]) + expect(state.deniedCommands).toEqual(["prior-deny"]) + }) }) describe("importSettings", () => { @@ -878,6 +936,66 @@ describe("importExport", () => { showWarningMessageSpy.mockRestore() }) + // The pending store outlives one call, so each case below clears it before and + // after. A successful mirror for both keys is the documented clear path. + async function clearPendingMirrors() { + const config = makeWorkspaceConfiguration() + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + await mirrorImportedCommandLists({ allowedCommands: [], deniedCommands: [] }) + vi.mocked(vscode.window.showWarningMessage).mockClear() + } + + it("keeps the entries of a failed mirror as pending until a later mirror succeeds", async () => { + await clearPendingMirrors() + + const config = makeWorkspaceConfiguration() + const update = vi.mocked(config.update) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + update.mockRejectedValue(new Error("settings file is locked")) + + await mirrorImportedCommandLists({ allowedCommands: ["git", "aws"], deniedCommands: ["rm -rf"] }) + + // The settings file kept the old list, so neither key has a layer holding + // these entries. The save path reads them here instead. + expect(pendingCommandListMirrors()).toEqual({ + allowedCommands: ["git", "aws"], + deniedCommands: ["rm -rf"], + }) + + update.mockReset() + update.mockResolvedValue(undefined) + await mirrorImportedCommandLists({ allowedCommands: ["git", "aws"], deniedCommands: ["rm -rf"] }) + + // The configuration now carries both lists, so the mark would only + // duplicate a layer the save already reads. + expect(pendingCommandListMirrors()).toEqual({ allowedCommands: [], deniedCommands: [] }) + + await clearPendingMirrors() + }) + + it("leaves no pending entry when the import fails before it can mirror", async () => { + await clearPendingMirrors() + + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git", "aws"] })) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + mockContextProxy.setValues.mockResolvedValue(undefined) + mockContextProxy.setValue.mockResolvedValue(undefined) + // The state write lands, and the failure after it rolls both lists back. + mockProviderSettingsManager.listConfig.mockRejectedValue(new Error("config listing failed")) + const update = mockCommandListConfig() + + await runFeedback(filePath) + + // A failed import reaches no mirror, so it marks nothing. A mark here would + // keep entries the rollback already discarded. + expect(update).not.toHaveBeenCalled() + expect(pendingCommandListMirrors()).toEqual({ allowedCommands: [], deniedCommands: [] }) + + await clearPendingMirrors() + }) + it("posts the imported state while the mirror warning is still pending", async () => { const filePath = "/mock/path/settings.json" ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git"] })) @@ -974,7 +1092,7 @@ describe("importExport", () => { expect(saveObserved).toEqual(["git", "imported"]) }) - it("settles the import span when the import throws", async () => { + it("releases the import span before a state post that fails after a successful import", async () => { const filePath = "/mock/path/settings.json" ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git"] })) ;(fs.access as Mock).mockResolvedValue(undefined) @@ -983,32 +1101,76 @@ describe("importExport", () => { mockContextProxy.setValue.mockResolvedValue(undefined) mockContextProxy.setProviderSettings.mockResolvedValue(undefined) + const mirrorWrite = createDeferred() const config = makeWorkspaceConfiguration() - // `mirrorCommandList` catches a failed write, so the span's own `finally` - // is the path under test rather than the retry. - vi.mocked(config.update).mockResolvedValue(undefined) + vi.mocked(config.update).mockImplementation(() => mirrorWrite.promise) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + // The post stays pending until it is rejected below, so the save waiter + // below settles on the release alone. A span that covered the post would + // leave that waiter pending while the post hangs. + let rejectPost!: (error: Error) => void + const postGate = new Promise((_, reject) => { + rejectPost = reject + }) const provider = feedbackProvider() - provider.postStateToWebview.mockRejectedValue(new Error("state post failed")) + provider.postStateToWebview.mockReturnValue(postGate) - await expect( - importSettingsWithFeedback( - { - providerSettingsManager: mockProviderSettingsManager, - contextProxy: mockContextProxy, - customModesManager: mockCustomModesManager, - provider, - }, - filePath, - ), - ).rejects.toThrow("state post failed") + const imported = importSettingsWithFeedback( + { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider, + }, + filePath, + ) + + // The mirror holds the span open, so the post cannot have started yet. + await vi.waitFor(() => expect(config.update).toHaveBeenCalled()) + expect(provider.postStateToWebview).not.toHaveBeenCalled() + + let saveSettled = false + const save = awaitCommandListImportSettled().then(() => { + saveSettled = true + }) + + mirrorWrite.resolve() + await vi.waitFor(() => expect(provider.postStateToWebview).toHaveBeenCalled()) + await flushMacrotasks() + + // The post is still pending and the waiter has already settled, so the + // span was released before the post rather than by its failure. + expect(saveSettled).toBe(true) + + rejectPost(new Error("state post failed")) + await expect(imported).rejects.toThrow("state post failed") + await save // A save that arrives after the failed import must not wait for a span // whose owner is gone. await expect(awaitCommandListImportSettled()).resolves.toBeUndefined() }) + it("settles the import span when the file dialog throws", async () => { + stubValidProviderProfiles() + // The rejection reaches the import body with no file to read, so the + // span is open when it happens and its release is the only way a save + // can stop waiting. + ;(vscode.window.showOpenDialog as Mock).mockRejectedValueOnce(new Error("dialog unavailable")) + + await expect( + importSettingsWithFeedback({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider: feedbackProvider(), + }), + ).rejects.toThrow("dialog unavailable") + + await expect(awaitCommandListImportSettled()).resolves.toBeUndefined() + }) + it("keeps the span open until every overlapping import releases it", async () => { const firstRelease = beginCommandListImport() const secondRelease = beginCommandListImport() @@ -1035,6 +1197,177 @@ describe("importExport", () => { await expect(awaitCommandListImportSettled()).resolves.toBeUndefined() }) + it("holds an import's configuration writes until a save in flight has landed", async () => { + const config = makeWorkspaceConfiguration() + const update = vi.mocked(config.update) + update.mockResolvedValue(undefined) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + // The save holds its span, so the import has to wait for it. The mirror is + // the import's configuration write, and the settings file it fills is the + // store a save reads. + const releaseSave = beginCommandListSave() + let importDone = false + const imported = mirrorImportedCommandLists({ allowedCommands: ["imported"], deniedCommands: [] }).then( + () => { + importDone = true + }, + ) + + await flushMacrotasks() + // The save still owns the window, so no imported entry may reach the file yet. + expect(update).not.toHaveBeenCalled() + expect(importDone).toBe(false) + + releaseSave() + await imported + + expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) + }) + + it("opens a save's span only after the import it would overtake has settled", async () => { + // The import holds its span from before its configuration read until after + // its mirror, and the mirror waits for a save span. A save that took its + // span before waiting for the import would therefore wait, while holding, + // for an import that waits back: neither side could finish. The save here + // waits on a deferred read instead, so the import is inside its span and + // parked when the save starts. + const filePath = "/mock/path/settings.json" + const readFile = createDeferred() + ;(fs.readFile as Mock).mockReturnValue(readFile.promise) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + + const config = makeWorkspaceConfiguration() + const update = vi.mocked(config.update) + update.mockResolvedValue(undefined) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + const imported = importSettingsWithFeedback( + { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider: feedbackProvider(), + }, + filePath, + ) + + // The import has opened its span and is parked inside its body. + await flushMacrotasks() + + // The save side opens its span through the ordered helper. The helper + // waits for the import span, so the save must not have opened its span. + let saveOpened = false + const save = beginOrderedCommandListSave().then((release) => { + saveOpened = true + return release + }) + + await flushMacrotasks() + expect(saveOpened).toBe(false) + + // The import now reaches its mirror, which waits for a save span. The save + // span is not open, so the import must not park here. Both finish. + readFile.resolve(validProfileFile({ allowedCommands: ["imported"], deniedCommands: [] })) + const [, releaseSave] = await Promise.all([imported, save]) + + expect(saveOpened).toBe(true) + expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) + + releaseSave() + // The import's release settled its span, so a later save opens at once. The + // handle is released again, because an open span would stall every import + // that runs after this case. + const laterRelease = await beginOrderedCommandListSave() + expect(typeof laterRelease).toBe("function") + laterRelease() + }) + + it("holds an import's state write back when a save span opens while the import acquires", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue( + validProfileFile({ allowedCommands: ["imported"], deniedCommands: [] }), + ) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + mockContextProxy.setValues.mockResolvedValue(undefined) + mockContextProxy.setValue.mockResolvedValue(undefined) + mockContextProxy.setProviderSettings.mockResolvedValue(undefined) + + const update = mockCommandListConfig() + update.mockResolvedValue(undefined) + + let saveReleased = false + let saveReleasedAtStateWrite: boolean | undefined + vi.mocked(mockContextProxy.setValues).mockImplementation(async () => { + saveReleasedAtStateWrite = saveReleased + }) + + // Both sides suspend only on their own acquisition wait, so the save's + // continuation opens its span before the import's continuation runs. + const save = beginOrderedCommandListSave() + const imported = runFeedback(filePath) + + const releaseSave = await save + // The import reaches its state write here only if it opened its span without + // observing the save span the line above put in place. + await flushMacrotasks() + + saveReleased = true + releaseSave() + await imported + + // A save reads the state copy back into the settings file, so an import that + // writes it inside a save's span leaves the two stores describing different + // lists. The write must land after the save released instead. + expect(saveReleasedAtStateWrite).toBe(true) + expect(mockContextProxy.setValues).toHaveBeenCalledTimes(1) + expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) + }) + + it("holds a save's span back while an import span that opened first is still writing", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue( + validProfileFile({ allowedCommands: ["imported"], deniedCommands: [] }), + ) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + mockContextProxy.setValues.mockResolvedValue(undefined) + mockContextProxy.setValue.mockResolvedValue(undefined) + mockContextProxy.setProviderSettings.mockResolvedValue(undefined) + + // The mirror write is the import's last write inside its span, so a save span + // that opens before it is a save span that opened inside the import. + let importMirrored = false + const config = makeWorkspaceConfiguration() + const update = vi.mocked(config.update) + update.mockImplementation(async () => { + importMirrored = true + }) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + // The import's continuation runs first and opens the import span, so the + // save's continuation has a span to observe when it runs. + const imported = runFeedback(filePath) + + let saveOpenedBeforeImportRelease: boolean | undefined + const save = beginOrderedCommandListSave().then((release) => { + saveOpenedBeforeImportRelease = !importMirrored + return release + }) + + const releaseSave = await save + releaseSave() + await imported + + // A save that opens inside an import's span reads the settings file before + // the import mirrored into it, so the save must wait the span out instead. + expect(typeof releaseSave).toBe("function") + expect(saveOpenedBeforeImportRelease).toBe(false) + expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) + }) + it("should handle import when reasoning budget fields are missing from config", async () => { // This test verifies that import works correctly when reasoning budget fields are not present diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 56a0314861..57fe072857 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -23,6 +23,7 @@ import { downgradeLegacyRooConfig, ROUTER_REMOVAL_IMPORT_WARNING } from "./route import { resolveDefaultSaveUri, saveLastExportPath } from "../../utils/export" import { Package } from "../../shared/package" import { t } from "../../i18n" +import { sanitizeCommandList, type CommandListConfigKey } from "../auto-approval/commandScope" export type ImportOptions = { providerSettingsManager: ProviderSettingsManager @@ -159,6 +160,11 @@ export async function importSettingsFromPath( globalSettings: z.unknown().optional(), }) + // A failed import leaves both stores as they were. The settings file is only + // written after a successful import, so it needs no restore; extension state + // is written below, and this holds the copy the failure path puts back. + let priorCommandLists: Pick | undefined + try { const previousProviderProfiles = await providerSettingsManager.export() @@ -240,6 +246,15 @@ export async function importSettingsFromPath( // They will be imported automatically with the config - no special handling needed await providerSettingsManager.import(providerProfiles) + + // Read through the same proxy the write below uses, because extension state + // is the store this function writes. Captured before the write so a partial + // `setValues` is restored too, not only a failure that follows it. + priorCommandLists = { + allowedCommands: contextProxy.getValue("allowedCommands"), + deniedCommands: contextProxy.getValue("deniedCommands"), + } + await contextProxy.setValues(sanitizedGlobalSettings) // Set the current provider. @@ -272,6 +287,24 @@ export async function importSettingsFromPath( error = e.message } + if (priorCommandLists) { + const unrestoredKeys: string[] = [] + + for (const key of ["allowedCommands", "deniedCommands"] as const) { + // A restore that rejects is reported in the error text rather than + // thrown, so the caller always learns the import failed. + try { + await contextProxy.setValue(key, priorCommandLists[key]) + } catch { + unrestoredKeys.push(key) + } + } + + if (unrestoredKeys.length > 0) { + error = `${error}\nThe prior ${unrestoredKeys.join(", ")} value(s) could not be restored in extension state.` + } + } + return { success: false, error } } } @@ -380,6 +413,15 @@ type CommandListSpan = { * imported state against the old file, so the save path awaits `promise` before * it takes its snapshot. `openers` counts the imports still inside that window: * the span covers all of them and settles when the last one releases. + * + * The two spans are mutually exclusive, because each side opens its span only when + * the other side's span is absent, and it repeats that check with no suspension + * before the open (`beginOrderedCommandListSave`, `beginOrderedCommandListImport`). + * A save holds its span from its first configuration read to its state write, so an + * import that starts inside that window writes neither half until the save has + * landed both. Without the second span, a save that had already passed the wait + * could write its pre-import list over an import that finished in between, and the + * two stores would end up agreeing with neither order. */ let inFlightCommandListImport: CommandListSpan | undefined @@ -437,6 +479,31 @@ export function beginCommandListImport(): () => void { return releaseOnce(joined) } +/** + * Opens the command-list span of an import after the save it would otherwise + * overtake has settled. + * + * An import writes the state copy and then the configuration, and a save writes + * them in the opposite order, so an import must not write while a save sits + * between its configuration write and its state write. The absence of a save span + * is re-checked with no suspension before the open, so an import that starts + * during a save's span cannot open its own span between the check and the open. + * An enclosing import that already holds the span joins it as a second owner. + * + * @returns The release handle for the span this import opened or joined. + */ +export async function beginOrderedCommandListImport(): Promise<() => void> { + // The check below is repeated with no suspension before the open, because a + // save can open its span during the wait. + for (;;) { + await awaitCommandListSaveSettled() + + if (inFlightCommandListSave === undefined) { + return beginCommandListImport() + } + } +} + /** * Waits for an import's command-list span to settle. * @@ -448,6 +515,135 @@ export async function awaitCommandListImportSettled(): Promise { await inFlightCommandListImport?.promise } +/** + * The command-list span of the saves that have not settled yet. + * + * A save writes the configuration and then the extension-state copy, and an + * import writes the state copy and then the configuration. Either order leaves + * the stores inconsistent if the two interleave, so a save holds this span from + * its first configuration read to its state write, and an import awaits it + * before writing either half. `openers` counts the saves inside that window, so + * overlapping saves settle together rather than at the first release. + */ +let inFlightCommandListSave: CommandListSpan | undefined + +/** Opens a save span with one owner and makes it the span an import awaits. */ +function openCommandListSaveSpan(): CommandListSpan { + let settle!: () => void + const promise = new Promise((resolve) => { + settle = resolve + }) + const span: CommandListSpan = { promise, settle, openers: 1 } + inFlightCommandListSave = span + return span +} + +/** + * Opens the command-list span of a save. + * + * @returns A release function that settles the span once every owner has called + * it. Calling it more than once is safe. A save that opens while another is in + * flight joins the same span and counts as an owner, so the span settles when + * the last one releases. + */ +export function beginCommandListSave(): () => void { + const joined = inFlightCommandListSave + + if (joined === undefined) { + return releaseSaveOnce(openCommandListSaveSpan()) + } + + joined.openers += 1 + return releaseSaveOnce(joined) +} + +/** + * Opens the command-list span of a save after the import it would otherwise + * overtake has settled. + * + * A save writes the configuration and then the state copy, so it must not write + * while an import sits between its state write and its mirror. It must also not + * hold its own span while it waits: the import's mirror waits for this span from + * inside the import span, so a save that held its span across the wait could be + * waited on by the very import it is waiting for. The absence of an import span is + * re-checked with no suspension before the open, so a save never opens its span + * while an import span is open. + * + * @returns The release handle for the span this save opened or joined. + */ +export async function beginOrderedCommandListSave(): Promise<() => void> { + // The check below is repeated with no suspension before the open, because an + // import can open its span during the wait. + for (;;) { + await awaitCommandListImportSettled() + + if (inFlightCommandListImport === undefined) { + return beginCommandListSave() + } + } +} + +/** The save counterpart of `releaseOnce`, over the save span. */ +function releaseSaveOnce(span: CommandListSpan): () => void { + let released = false + + return () => { + if (released) { + return + } + + released = true + span.openers -= 1 + + if (span.openers > 0) { + return + } + + // Cleared before settling, so an import that starts after the last release + // sees no save in flight rather than waiting for one that already ended. + inFlightCommandListSave = undefined + span.settle() + } +} + +/** + * Waits for a save's command-list span to settle. + * + * Resolves immediately when no save is in flight. The wait is bounded by the + * save itself: it releases in a `finally` that covers both of its writes, so a + * throwing save cannot leave an import waiting. + */ +export async function awaitCommandListSaveSettled(): Promise { + await inFlightCommandListSave?.promise +} + +/** + * The command-list entries an import carried that its settings-file mirror could + * not write, per key. + * + * An import writes the lists to extension state and then mirrors them into the + * user settings file. A save reads the configuration, so an entry the mirror + * never wrote has no layer there and the save drops it as a removal. These + * entries stay a known global origin until a mirror for their key succeeds, or + * until they reach the configuration's global layer because the user set them + * there. The store lives for the process: a reload before the next save loses + * it, and that save falls back to reporting the entry as an addition. + */ +const pendingCommandListMirrorEntries = new Map>() + +/** + * The entries an import could not mirror into the user settings file yet. + * + * @returns One list per key. A key with nothing pending gives `[]`, so a caller + * never branches on `undefined`. + */ +export function pendingCommandListMirrors(): Record { + return { + allowedCommands: sanitizeCommandList([...(pendingCommandListMirrorEntries.get("allowedCommands") ?? [])]), + deniedCommands: sanitizeCommandList([...(pendingCommandListMirrorEntries.get("deniedCommands") ?? [])]), + } +} + /** * Writes one imported command list into the user settings file, retrying a * failed write once. @@ -481,21 +677,25 @@ async function mirrorCommandList(key: "allowedCommands" | "deniedCommands", impo * * A key the import did not carry is skipped, so the state copy never becomes * the source. A failed write is retried once and then reported to the user - * with the manual route; the import itself still succeeds. A later save can - * still drop the entries until they are stored in user settings, which is why - * the report names that route. + * with the manual route; the import itself still succeeds. The entries a failed + * write leaves behind stay a known global origin for the next save, which is + * why that save keeps them instead of reading them as removals. * * @param globalSettings - The global settings an import produced, or `undefined`. */ export async function mirrorImportedCommandLists(globalSettings: GlobalSettings | undefined): Promise { + // A save writes the state copy and then the configuration, and this write is + // the import's half of the same pair. Waiting for a save in flight keeps the + // imported list from landing on top of a save that read the pre-import state. + // The span covers the writes below, so a save cannot read the imported state // against a settings file this function has not finished writing. An enclosing // import that already opened a span joins it as a second owner, so neither // release can settle the span while the other is still writing. - const releaseCommandListImport = beginCommandListImport() + const releaseCommandListImport = await beginOrderedCommandListImport() try { - const failedKeys: string[] = [] + const failedKeys: CommandListConfigKey[] = [] for (const key of ["allowedCommands", "deniedCommands"] as const) { const imported = globalSettings?.[key] @@ -503,8 +703,15 @@ export async function mirrorImportedCommandLists(globalSettings: GlobalSettings continue } - if (!(await mirrorCommandList(key, imported))) { + if (await mirrorCommandList(key, imported)) { + // The configuration's global layer now holds these entries, so a save + // reads them from a layer and the mark would only duplicate it. + pendingCommandListMirrorEntries.delete(key) + } else { failedKeys.push(key) + // The replacement is whole, because the mark describes the list this + // import carried, not an accumulation across imports. + pendingCommandListMirrorEntries.set(key, new Set(sanitizeCommandList(imported))) } } @@ -535,8 +742,10 @@ export const importSettingsWithFeedback = async ( // The span starts before the import, because the command-list state write // happens inside it, and the mirror joins the same span. The notifications - // below stay outside it: their promises settle only on dismissal. - const releaseCommandListImport = beginCommandListImport() + // below stay outside it: their promises settle only on dismissal. A save in + // flight settles first, so neither half of this import lands between a save's + // configuration write and its state write. + const releaseCommandListImport = await beginOrderedCommandListImport() try { if (filePath) { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 7dac19f604..d869563847 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -68,11 +68,14 @@ vi.mock("../rulesMessageHandler", () => ({ })) // The import case needs no real import: the shared import function is a mock, -// and the save tests script the configuration state directly. +// and the save tests script the configuration state directly. The save span is a +// no-op release by default, so a case only observes it when it scripts one. vi.mock("../../config/importExport", () => ({ - awaitCommandListImportSettled: vi.fn(), + beginCommandListSave: vi.fn().mockReturnValue(() => {}), + beginOrderedCommandListSave: vi.fn().mockResolvedValue(() => {}), exportSettings: vi.fn(), importSettingsWithFeedback: vi.fn(), + pendingCommandListMirrors: vi.fn().mockReturnValue({ allowedCommands: [], deniedCommands: [] }), })) vi.mock("@roo-code/telemetry", () => ({ @@ -90,7 +93,12 @@ import * as vsCodeLmProvider from "../../../api/providers/vscode-lm" import * as copilotProvider from "../../../api/providers/github-copilot" import { Package } from "../../../shared/package" -import { awaitCommandListImportSettled, importSettingsWithFeedback } from "../../config/importExport" +import { + beginCommandListSave, + beginOrderedCommandListSave, + importSettingsWithFeedback, + pendingCommandListMirrors, +} from "../../config/importExport" import { readCommandListScopes } from "../../auto-approval/commandScope" import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { seedCommandList } from "../../../utils/seedAllowedCommands" @@ -2150,6 +2158,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { beforeEach(() => { vi.clearAllMocks() mockWorkspaceFolders.folders = [{ uri: { fsPath: "/mock/workspace" } }] + // Most cases have no import awaiting its mirror. The cases that do script + // this reader themselves. + vi.mocked(pendingCommandListMirrors).mockReturnValue({ allowedCommands: [], deniedCommands: [] }) }) // The file-level vscode mock opens one workspace folder, so the configuration @@ -2166,6 +2177,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { globalValue?: string[] workspaceValue?: string[] workspaceFolderValue?: string[] + // The package default `inspect()` reports. The save compares it to the state + // copy to tell an activation-seeded copy from a key the user deleted. + defaultValue?: string[] } // `inspected` may be a function of the requested key, so a two-key payload @@ -2208,15 +2222,17 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { it("holds the save's first configuration read until an in-flight command-list import settles", async () => { // The import mirrors its lists into the settings file after it writes the state // copy. A save that read the configuration before the mirror landed would - // snapshot the pre-import file and write that list back. The guard therefore - // has to settle before the save's first inspect(), not merely be called. + // snapshot the pre-import file and write that list back. Opening the save span + // waits for the import span first, so the guard has to settle before the save's + // first inspect(), not merely be called. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { inspect } = mockCommandConfiguration({ globalValue: ["git"] }) - // A deferred stand-in for the import span, so the test decides when it settles. + // A deferred stand-in for the ordered open, so the test decides when the + // import span it waits on settles. let settleImport: () => void = () => {} - vi.mocked(awaitCommandListImportSettled).mockImplementationOnce( - () => new Promise((resolve) => (settleImport = () => resolve())), + vi.mocked(beginOrderedCommandListSave).mockImplementationOnce( + () => new Promise<() => void>((resolve) => (settleImport = () => resolve(() => {}))), ) const save = webviewMessageHandler(mockClineProvider, { @@ -2236,6 +2252,59 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(inspect).toHaveBeenCalled() }) + it("holds the save span across the configuration writes and the state write", async () => { + // The import's wait on the save span is what keeps an import from landing + // between this save's two writes. A span released before the state write + // would let the import write its configuration half while this save still + // holds a pre-import list, so the release has to come after both writes. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ globalValue: ["git"] }) + update.mockResolvedValue(undefined) + + const release = vi.fn() + vi.mocked(beginOrderedCommandListSave).mockResolvedValueOnce(release) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"] }, + }) + + expect(beginOrderedCommandListSave).toHaveBeenCalledTimes(1) + expect(release).toHaveBeenCalledTimes(1) + + const setValue = vi.mocked(mockClineProvider.contextProxy.setValue) + const stateWrite = setValue.mock.calls.findIndex(([key]) => key === "allowedCommands") + expect(stateWrite).toBeGreaterThanOrEqual(0) + expect(release.mock.invocationCallOrder[0]).toBeGreaterThan(update.mock.invocationCallOrder[0]) + expect(release.mock.invocationCallOrder[0]).toBeGreaterThan(setValue.mock.invocationCallOrder[stateWrite]) + + // A payload with no command-list key writes neither store this span orders, + // so it must not open one and stall an import behind an unrelated save. + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { mode: "code" }, + }) + + expect(beginOrderedCommandListSave).toHaveBeenCalledTimes(1) + }) + + it("opens the save span through the ordered helper rather than the bare primitive", async () => { + // The ordered helper waits for an in-flight import before it opens the save + // span. A handler that opened the bare primitive would take the span first and + // reintroduce the wait that an import's mirror performs from inside its own + // span, which is the cycle the ordered open removes. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + mockCommandConfiguration({ globalValue: ["git"] }) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"] }, + }) + + expect(beginOrderedCommandListSave).toHaveBeenCalledTimes(1) + expect(beginCommandListSave).not.toHaveBeenCalled() + }) + it("keeps workspace-scoped denied commands out of the global write when saving the merged list", async () => { // Gate on: the workspace entry is visible in the dialog, so keeping it is not // a re-add. With the gate off every submitted workspace entry is a re-add, @@ -2615,6 +2684,59 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) + it("aborts the workspace write and restores the global layer when the workspace re-read fails", async () => { + // The re-read exists so this save does not overwrite an entry another writer + // added during the global write. A failed re-read cannot rule that out, so the + // key aborts instead of writing the precomputed list: the global half is undone + // and the workspace layer is never written. Both stores then hold their + // save-start values rather than diverging. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["old"] : undefined, + ) + const { update } = mockCommandConfiguration( + { globalValue: ["old"], workspaceValue: ["docker"] }, + [undefined, undefined], + // Save start, the opposite key's snapshot, the merge re-read that throws, + // then the undo's re-read. + [ + { globalValue: ["old"], workspaceValue: ["docker"] }, + undefined, + new Error("workspace unreadable"), + { globalValue: ["old", "aws"] }, + ], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "old", "aws"] }, + }) + + // The global write landed, and the failed re-read came before any workspace write. + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["old", "aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // The undo removes only this save's addition, so the global layer is back to the + // value it held at save start. + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["old"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(2) + // Both stores are read here. The configuration's global layer holds its save-start + // value again, and the extension-state copy was never written, so neither store + // was left ahead of the other. + const globalWrites = update.mock.calls + .filter((call) => call[2] === vscode.ConfigurationTarget.Global) + .map((call) => call[1]) + expect(globalWrites.at(-1)).toEqual(["old"]) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to save deniedCommands: the workspace layer could not be re-read: workspace unreadable", + ) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + // Entries the dialog never displayed cannot be deleted by omission from a // list the user could not see. A save therefore re-adds them to the workspace // layer it rewrites. Such entries are hidden while the gate is off, or shadowed by a @@ -2772,13 +2894,43 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) - it("keeps a displayed workspace entry the global layer shadows in the workspace write and out of the global write", async () => { + it("keeps a displayed workspace entry the global layer shadows in the workspace write without duplicating it into the global write", async () => { // The workspace layer holds "echo" and a global entry shadows it, so the - // entry is hidden at save time. The dialog displayed it before, because the - // baseline names it. Reading the promotion set as the whole hidden set would - // drop "echo" from the workspace origin set, the split would then read it as - // brand-new, and the global write would gain it. The baseline keeps it a - // workspace decision instead. + // composed list no longer carries the entry at save time. The dialog + // displayed it before, because the baseline names it. Reading the composed + // list as the workspace origin set would drop "echo" from the workspace + // write, which deletes a workspace decision the user kept. The baseline + // keeps it a workspace decision, and the global write keeps the user's own + // copy of the entry instead of gaining a second one from the workspace layer. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["echo"]) + const { update } = mockCommandConfiguration( + { globalValue: ["echo"], workspaceValue: ["echo"] }, + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["echo"] }, + commandListBaseline: { deniedCommands: ["echo"], workspaceCommandListsEnabled: true }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + // The shadowed entry is a workspace decision. The global layer holds the + // user's own copy, so the global write neither loses it nor duplicates it + // from the workspace layer. + expect(update).toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["echo"]) + }) + + it("keeps a displayed workspace entry in the workspace write after the gate flips off before the save", async () => { + // The dialog displayed "echo" from the workspace layer with the gate on, and + // the gate was off at save time. The entry is hidden at save time and the + // baseline names it, so the save keeps it a workspace decision and promotes + // nothing into the global layer. const { update } = mockCommandConfiguration({ workspaceValue: ["echo"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { @@ -2805,7 +2957,12 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // off, so the workspace layer enforces nothing and the global layer is the // only home the entry has. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) - const { update } = mockCommandConfiguration({ workspaceValue: ["aws", "docker"] }, undefined, undefined, false) + const { update } = mockCommandConfiguration( + { workspaceValue: ["aws", "docker"], defaultValue: ["aws"] }, + undefined, + undefined, + false, + ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -2821,6 +2978,49 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) + it("keeps an imported entry whose mirror failed in the global write of the next save", async () => { + // The import wrote "aws" to the state copy and could not write it to the + // settings file, so no configuration layer holds it. Without the pending mark + // the save reads the entry as a file deletion and drops it. The mark makes it + // known global state, so the global write keeps it. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) + vi.mocked(pendingCommandListMirrors).mockReturnValue({ allowedCommands: [], deniedCommands: ["aws"] }) + const { update } = mockCommandConfiguration({}, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["aws"] }, + commandListBaseline: { deniedCommands: ["aws"], workspaceCommandListsEnabled: false }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + // The entry is a known origin, not a settings-file addition, so no warning + // names it. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("drops the entries of a key the user deleted from user settings", async () => { + // The user removed the whole key from User Settings, so the snapshot reports + // no global layer and no state copy equals the shipped default. The state copy + // still holds "aws" and the dialog displayed it. The save must honor the + // deletion instead of writing the entry back unwarned. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) + vi.mocked(pendingCommandListMirrors).mockReturnValue({ allowedCommands: [], deniedCommands: [] }) + const { update, inspect } = mockCommandConfiguration({}, undefined, undefined, false) + // The snapshot reports the shipped default, which the state copy does not hold. + vi.mocked(inspect).mockReturnValue({ defaultValue: ["git log"] } as never) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["aws"] }, + commandListBaseline: { deniedCommands: ["aws"], workspaceCommandListsEnabled: false }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + }) + it("reports a conflict and compensates the global write when the folder override vanishes mid-save", async () => { // The save targets the folder layer. While the global write runs, another // writer removes that override, leaving only the workspace value. Reading the @@ -4185,7 +4385,14 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) - const { update } = mockCommandConfiguration({}, undefined, undefined, true) + // The state copy still equals the shipped default, which is what makes the + // absent global layer mean "seeded" rather than "deleted". + const { update } = mockCommandConfiguration( + { defaultValue: ["git log", "git diff", "git show"] }, + undefined, + undefined, + true, + ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -4353,7 +4560,14 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) - const { update } = mockCommandConfiguration({}, undefined, undefined, true) + // The state copy still equals the shipped default, which is what makes the + // absent global layer mean "seeded" rather than "deleted". + const { update } = mockCommandConfiguration( + { defaultValue: ["git log", "git diff", "git show"] }, + undefined, + undefined, + true, + ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -4413,7 +4627,14 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) - const { update } = mockCommandConfiguration({}, undefined, undefined, true) + // The state copy still equals the shipped default, which is what makes the + // absent global layer mean "seeded" rather than "deleted". + const { update } = mockCommandConfiguration( + { defaultValue: ["git log", "git diff", "git show"] }, + undefined, + undefined, + true, + ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -4461,7 +4682,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) const { update } = mockCommandConfiguration( - { workspaceValue: ["npm test", "docker"] }, + { workspaceValue: ["npm test", "docker"], defaultValue: ["git log", "git diff", "git show"] }, undefined, undefined, true, @@ -4495,15 +4716,22 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(update).toHaveBeenCalledTimes(2) }) - it("drops a workspace-duplicate default from the global write while the composed union still enforces it", async () => { - // For a seeded default the workspace layer also holds. An unchanged save keeps - // "git log" in the workspace layer only, and the global write drops the - // duplicate. Enforcement is unchanged, because the composed reader unions both - // layers. + it("keeps a seeded default the workspace layer also holds in the global write with the gate on", async () => { + // For a seeded default the workspace layer also holds, and the gate on. The + // workspace layer carries "git log" only while the gate is on, so the global + // layer is still its home: dropping it there is a loss the user never asked + // for, and a later save with the gate off would have no copy left to keep. An + // unchanged save therefore writes the seeded list back to the global layer and + // clears the workspace duplicate it now holds twice. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) - const { update } = mockCommandConfiguration({ workspaceValue: ["git log"] }, undefined, undefined, true) + const { update } = mockCommandConfiguration( + { workspaceValue: ["git log"], defaultValue: ["git log", "git diff", "git show"] }, + undefined, + undefined, + true, + ) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", @@ -4514,33 +4742,154 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }, }) - // The global write drops the duplicate and keeps the relative order of the - // rest. expect(update).toHaveBeenCalledWith( - "allowedCommands", - ["git diff", "git show"], - vscode.ConfigurationTarget.Global, - ) - expect(update).not.toHaveBeenCalledWith( "allowedCommands", ["git log", "git diff", "git show"], vscode.ConfigurationTarget.Global, ) + expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + // A kept entry stays in every layer that held it, so the workspace copy is + // rewritten too and enforcement still finds it there. expect(update).toHaveBeenCalledWith("allowedCommands", ["git log"], vscode.ConfigurationTarget.Workspace) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", [ + "git log", "git diff", "git show", ]) expect(update).toHaveBeenCalledTimes(2) - // The entry the global write dropped is still enforced through the workspace - // layer. The merged set the enforcement path composes covers every command - // either layer holds. - const afterSaveScopes = readCommandListScopes("allowedCommands", ["git diff", "git show"], { + // Enforcement still covers every entry after the save. The merged set the + // composed reader returns holds the global list the save wrote. + const afterSaveScopes = readCommandListScopes("allowedCommands", ["git log", "git diff", "git show"], { workspaceValue: ["git log"], }) - expect(afterSaveScopes.merged).toEqual(["git diff", "git show", "git log"]) + expect(afterSaveScopes.merged).toEqual(["git log", "git diff", "git show"]) + }) + + it("keeps a gate-hidden workspace copy the user deleted only from the displayed global list", async () => { + // The gate is off, so the dialog displayed only the global layer. "git log" + // sits in both layers, and the baseline names it from the global copy. The user + // deletes it there. That deletion is a decision about the user-level list, not + // about a workspace copy the dialog never showed, so the workspace entry stays + // while the global one goes. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git log"] : undefined, + ) + const { update } = mockCommandConfiguration( + { globalValue: ["git log"], workspaceValue: ["git log"] }, + undefined, + undefined, + false, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: [] }, + commandListBaseline: { allowedCommands: ["git log"], workspaceCommandListsEnabled: false }, + }) + + // The user-level entry the dialog showed is deleted where it lives... + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + // ...and the workspace copy the dialog could not show survives. + expect(update).toHaveBeenCalledWith("allowedCommands", ["git log"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Workspace) + // The workspace copy is not promoted into the user's settings file. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", []) + }) + + it("keeps a gate-hidden workspace copy the user never saw when the baseline names only the global list", async () => { + // The same save with nothing submitted and a baseline that shows only the + // global copy. Both entries go unmentioned by the submission, and the baseline + // proves the dialog displayed the global one alone. The workspace copy is + // preserved, and the global deletion the baseline proves is applied. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["rm -rf"] : undefined, + ) + const { update } = mockCommandConfiguration( + { globalValue: ["rm -rf"], workspaceValue: ["rm -rf", "docker"] }, + undefined, + undefined, + false, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: ["rm -rf"], workspaceCommandListsEnabled: false }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + // Both hidden workspace entries survive the rewrite, including the one the + // global layer also held. + expect(update).toHaveBeenCalledWith( + "deniedCommands", + ["rm -rf", "docker"], + vscode.ConfigurationTarget.Workspace, + ) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) + }) + + it("applies a displayed deletion to both copies when the gate is on", async () => { + // The gate-on counterpart of the case above, with the same fixture. The dialog + // displayed the workspace copy, so deleting the entry there is a deletion of + // that copy too, and the save clears both layers. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git log"] : undefined, + ) + const { update } = mockCommandConfiguration( + { globalValue: ["git log"], workspaceValue: ["git log"] }, + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: [] }, + commandListBaseline: { allowedCommands: ["git log"], workspaceCommandListsEnabled: true }, + }) + + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Workspace) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", []) + }) + + it("keeps a seeded default in the global write with the gate off while the workspace layer duplicates it", async () => { + // The gate-off half of the seeded-default pair. Activation wrote the defaults + // into extension state and the configuration's global layer is absent, so the + // state copy is their only home. The workspace layer duplicates "git log". The + // save keeps the seeded entry in the global write, and the workspace copy stays + // where it is because the gate off means the dialog never showed it. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git log", "git diff"] : undefined, + ) + const { update } = mockCommandConfiguration( + { workspaceValue: ["git log"], defaultValue: ["git log", "git diff"] }, + undefined, + undefined, + false, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git log", "git diff"] }, + commandListBaseline: { + allowedCommands: ["git log", "git diff"], + workspaceCommandListsEnabled: false, + }, + }) + + expect(update).toHaveBeenCalledWith( + "allowedCommands", + ["git log", "git diff"], + vscode.ConfigurationTarget.Global, + ) + expect(update).not.toHaveBeenCalledWith("allowedCommands", ["git diff"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("allowedCommands", ["git log"], vscode.ConfigurationTarget.Workspace) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git log", "git diff"]) }) }) diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 2456dbace8..fa78f8468e 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -95,7 +95,12 @@ import { searchWorkspaceFiles } from "../../services/search/file-search" import { fileExistsAtPath } from "../../utils/fs" import { playTts, setTtsEnabled, setTtsSpeed, stopTts } from "../../utils/tts" import { searchCommits } from "../../utils/git" -import { awaitCommandListImportSettled, exportSettings, importSettingsWithFeedback } from "../config/importExport" +import { + beginOrderedCommandListSave, + exportSettings, + importSettingsWithFeedback, + pendingCommandListMirrors, +} from "../config/importExport" import { getOpenAiModels } from "../../api/providers/openai" import { getVsCodeLmModels } from "../../api/providers/vscode-lm" import { getGitHubCopilotViewState } from "../../services/language-models/copilotViewState" @@ -788,10 +793,29 @@ export const webviewMessageHandler = async ( let failed = false let failure: unknown let commandListSaveFailed = false + // A save and an import write the same two stores in opposite orders: the save + // the configuration then the state copy, the import the state copy then the + // configuration. A save that carries a command-list key therefore holds the + // save span for the whole payload, so an import that starts inside this + // window writes neither half until this save has landed both. The span opens + // only when no import span is in flight, and that check is repeated with no + // suspension before the open, so this save never holds its span while it waits + // and the two spans are never open at the same time. The span bounds the region + // it covers: a write that starts after this release is + // not ordered against this save, and the configuration API offers no + // compare-and-set to close that last gap. + let releaseCommandListSave: (() => void) | undefined try { if (!message.updatedSettings) break + if ("allowedCommands" in message.updatedSettings || "deniedCommands" in message.updatedSettings) { + // The wait comes before the span. An import's mirror waits for this + // span from inside its own span, so a save that held its span across + // the wait could be waited on by the import it is waiting for. + releaseCommandListSave = await beginOrderedCommandListSave() + } + if (message.updatedSettings.destructiveCommandGuardEnabled === true) { try { const { ensureDcgInstalled } = await import("../../services/destructive-command-guard") @@ -838,15 +862,7 @@ export const webviewMessageHandler = async ( continue } else if (key === "allowedCommands" || key === "deniedCommands") { const commands = value ?? [] - - const incoming = Array.isArray(commands) - ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) - : [] - - // An import writes the lists to state and then mirrors them into the - // settings file. Waiting for its span keeps this snapshot from reading - // the imported state against the file the import has not written yet. - await awaitCommandListImportSettled() + const incoming = sanitizeCommandList(commands) // The webview sends the full merged list. The split needs one inspect() // snapshot before any write, so the workspace layer, the write target, and @@ -859,11 +875,16 @@ export const webviewMessageHandler = async ( // The rollback needs this snapshot's global layer. It separates an absent // layer from an empty one, and the delta uses the layer the write targets. let globalLayerAtSaveStart: string[] | undefined + // The package default the same snapshot reports. Comparing it to the state + // copy tells a seeded copy apart from a key the user deleted, and no + // second configuration read is needed for it. + let defaultAtSaveStart: string[] | undefined let inspectionFailure: string | undefined try { const snapshot = config.inspect(key) inspection = snapshot globalLayerAtSaveStart = snapshot?.globalValue + defaultAtSaveStart = snapshot?.defaultValue } catch (error) { inspectionFailure = error instanceof Error ? error.message : String(error) } @@ -910,6 +931,18 @@ export const webviewMessageHandler = async ( key === "allowedCommands" ? hiddenWorkspaceAllow : hiddenWorkspaceDeny const baseline = message.commandListBaseline?.[key] + // An absent global layer means the activation seed wrote the state copy, or + // that the user deleted the key. The copy is the seed's only when it still + // equals the shipped default, which is what separates the two cases. + const shippedDefaultAtSaveStart = sanitizeCommandList(defaultAtSaveStart) + const stateCopyIsShippedDefault = + defaultAtSaveStart !== undefined && + shippedDefaultAtSaveStart.length === currentScopes.global.length && + shippedDefaultAtSaveStart.every((entry) => currentScopes.global.includes(entry)) + // An import that could not write its settings-file mirror leaves its + // entries in the state copy alone. No configuration layer holds them, and + // they are known global state until a mirror for this key succeeds. + const pendingGlobalEntries = pendingCommandListMirrors()[key] // The baseline, the layers, and the gate together decide which submitted // entries survive the save. const { externallyAdded, splitSourceEntries, promotionHiddenEntries } = @@ -919,23 +952,26 @@ export const webviewMessageHandler = async ( currentScopes, configGlobalAtSaveStart, globalLayerAtSaveStart, + stateCopyIsShippedDefault, + pendingGlobalEntries, hiddenWorkspaceEntries, gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, }) // The split treats an entry outside its origin set as new, so the origin set - // decides what the global write may hold. `classifyCommandListBaseline` keeps - // a state-only global entry in `splitSourceEntries` when - // `globalLayerAtSaveStart` is `undefined`, because the activation seed wrote - // that copy and not the user. With the gate off the workspace layer enforces - // nothing, so that entry's only home is the global layer and the origin set - // must hold it. With the gate on the workspace layer carries it, and - // re-writing the seeded copy into the user's settings file would duplicate a - // default the user never added. - const seededGlobalEntries = - !workspaceListsEnabled && globalLayerAtSaveStart === undefined - ? currentScopes.global.filter((entry) => !configGlobalAtSaveStart.includes(entry)) - : [] - const globalOriginEntries = [...new Set([...configGlobalAtSaveStart, ...seededGlobalEntries])] + // decides what the global write may hold. Three contributors are known + // global state: the configuration's own layer, the activation seed's copy, + // and an import's entries whose mirror has not landed. The origin set must + // agree with `classifyCommandListBaseline` in both gate states. The + // workspace layer carries a seeded entry only while the gate is on, so with + // the gate on the global layer is still that entry's home; dropping it there + // is a loss the user never asked for, and a later save with the gate off + // would then have no copy left to keep. + const seededGlobalEntries = stateCopyIsShippedDefault + ? currentScopes.global.filter((entry) => !configGlobalAtSaveStart.includes(entry)) + : [] + const globalOriginEntries = [ + ...new Set([...configGlobalAtSaveStart, ...seededGlobalEntries, ...pendingGlobalEntries]), + ] const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( splitSourceEntries, // Hidden entries are not known state. The dialog never displayed them, so a @@ -946,17 +982,26 @@ export const webviewMessageHandler = async ( globalOriginEntries, ) - // The hidden set holds entries the dialog could not display, so re-adding - // them cannot undo a user deletion. A gate flip since the dialog displayed - // its lists breaks that rule. An entry the baseline shows displayed became - // hidden afterwards. Its absence is then a deletion the re-add must honor. - // Entries hidden all along are absent from the baseline and stay preserved. + // Entries the dialog never displayed cannot be deleted by omission from a + // list the user could not see, so the save re-adds them to the workspace + // layer it rewrites. The baseline's gate says which entries those are. With + // the gate off the dialog showed only the global layer, so no workspace entry + // was displayed, and every one survives. That includes a workspace copy whose + // global twin the user deleted: the deletion was a decision about the + // user-level list, which the save applies to that layer alone. With the gate + // on, or when the sender reported no gate, the workspace layer was displayed, + // and only entries the save still finds hidden are re-added. A baseline entry + // among those became hidden after display, so its absence is a deletion the + // re-add honors. + const gateAtDisplay = message.commandListBaseline?.workspaceCommandListsEnabled const workspaceWrite = [ ...new Set([ ...keptWorkspaceWrite, - ...hiddenWorkspaceEntries.filter( - (entry) => !Array.isArray(baseline) || !baseline.includes(entry), - ), + ...(gateAtDisplay === false + ? currentScopes.workspace + : hiddenWorkspaceEntries.filter( + (entry) => !Array.isArray(baseline) || !baseline.includes(entry), + )), ]), ] const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) @@ -981,6 +1026,7 @@ export const webviewMessageHandler = async ( // between this read and the write is still lost. let workspaceAtWrite = workspaceWrite let workspaceLayerVanished = false + let workspaceReReadFailure: string | undefined try { const freshInspection = config.inspect(key) // No inspection object is no evidence about the layer, so the @@ -1019,9 +1065,13 @@ export const webviewMessageHandler = async ( workspaceAtWrite = [...new Set([...keptByBoth, ...addedDuringSave])] } } - } catch { - // The global write already landed. Keep the precomputed list rather - // than abort a half-applied save over a re-read that cannot complete. + } catch (error) { + // Writing the precomputed list would overwrite an entry another + // writer added during the global write, and the save cannot tell + // the two apart without this read. The key therefore aborts and + // the outer catch undoes the global half, so both stores keep + // their pre-save values instead of diverging. + workspaceReReadFailure = error instanceof Error ? error.message : String(error) } if (workspaceLayerVanished) { // Writing would recreate an override another writer removed. The @@ -1030,6 +1080,11 @@ export const webviewMessageHandler = async ( `the ${workspaceTarget === vscode.ConfigurationTarget.WorkspaceFolder ? "workspace-folder" : "workspace"} layer was removed during the save`, ) } + if (workspaceReReadFailure !== undefined) { + throw new Error( + `the workspace layer could not be re-read: ${workspaceReReadFailure}`, + ) + } await config.update(key, workspaceAtWrite, workspaceTarget) } } catch (error) { @@ -1203,6 +1258,10 @@ export const webviewMessageHandler = async ( } catch (error) { failed = true failure = error + } finally { + // Released after both of this save's writes, and before the state post: + // the post only reflects state the span already covers. + releaseCommandListSave?.() } // A failed refresh must neither undo a stored save nor keep the webview from getting the result. diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 2767968ee3..22873a71a6 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -1308,6 +1308,11 @@ describe("SettingsView - Unsaved Changes Detection", () => { + ), ) @@ -1352,6 +1357,11 @@ describe("SettingsView - Unsaved Changes Detection", () => { answerSave(saveId, { success: true }) await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // Save is disabled while the answer is outstanding, so only an edit made + // after the answer distinguishes a settled form from a still-pending one. + fireEvent.click(screen.getByTestId("edit-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) }) it("settles the save against the refreshed state posted just before the answer", async () => { @@ -1443,6 +1453,11 @@ describe("SettingsView - Unsaved Changes Detection", () => { onClick={() => setCachedStateField("alwaysAllowReadOnly", true)}> Edit a non-list setting + ), ) @@ -1495,6 +1510,11 @@ describe("SettingsView - Unsaved Changes Detection", () => { view.rerender() answerSave(formatSaveId, { success: true }) await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + + // Save is disabled while the answer is outstanding, so only an edit made + // after the answer distinguishes a settled form from a still-pending one. + fireEvent.click(screen.getByTestId("edit-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) }) it("clears the unsaved flag and releases every list when the refresh shows all writes landed", async () => { From 34cd01085fb85f7476ba474b436085782026399b Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Fri, 27 Nov 2026 21:47:03 +0100 Subject: [PATCH 41/52] fix: correct two command-list comments The comment on `mirrorImportedCommandLists` stated that a save writes the extension-state copy and then the configuration. The save writes the configuration first and the state copy second: the settings handler updates the configuration and then calls `contextProxy.setValue`. The comment now states that order, which is the one the save span guards against the import's opposite order. A test comment named the wait between the two spans with a word that reads as internal shorthand. It now names it a circular wait. --- src/core/config/importExport.ts | 2 +- src/core/webview/__tests__/webviewMessageHandler.spec.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 57fe072857..baea7abe3a 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -684,7 +684,7 @@ async function mirrorCommandList(key: "allowedCommands" | "deniedCommands", impo * @param globalSettings - The global settings an import produced, or `undefined`. */ export async function mirrorImportedCommandLists(globalSettings: GlobalSettings | undefined): Promise { - // A save writes the state copy and then the configuration, and this write is + // A save writes the configuration and then the state copy, and this write is // the import's half of the same pair. Waiting for a save in flight keeps the // imported list from landing on top of a save that read the pre-import state. diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index d869563847..afec108088 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2292,7 +2292,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The ordered helper waits for an in-flight import before it opens the save // span. A handler that opened the bare primitive would take the span first and // reintroduce the wait that an import's mirror performs from inside its own - // span, which is the cycle the ordered open removes. + // span, which is the circular wait the ordered open removes. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) mockCommandConfiguration({ globalValue: ["git"] }) From 2a54498e0acdbd6805b105153ac76286f3d5974e Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Fri, 27 Nov 2026 22:17:09 +0100 Subject: [PATCH 42/52] test: add getValue to the auto-import proxy double `importSettingsFromPath` reads the allowed and denied command lists from the context proxy before it writes, so a failed import can put them back. The hand-built proxy double in the auto-import settings spec supplied only the three setters, so that read threw and both success cases in the file failed with "contextProxy.getValue is not a function". The double now answers getValue with undefined, the value the restore path expects when no prior list exists. The two assertions are unchanged, and no production code changed. The misc suite that CI runs under `platform-unit-test` reported 2 failed and 2576 passed before this change. Run locally, it now reports 2590 passed and 0 failed. --- src/utils/__tests__/autoImportSettings.spec.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/utils/__tests__/autoImportSettings.spec.ts b/src/utils/__tests__/autoImportSettings.spec.ts index 84fc16d394..1e08ede3f9 100644 --- a/src/utils/__tests__/autoImportSettings.spec.ts +++ b/src/utils/__tests__/autoImportSettings.spec.ts @@ -110,11 +110,14 @@ describe("autoImportSettings", () => { listConfig: vi.fn().mockResolvedValue([]), } as unknown as MockedManager - // Double provides the ContextProxy members used by auto-import. + // Double provides the ContextProxy members importSettingsFromPath calls: the + // state and provider settings writes, plus the command-list reads it snapshots + // before writing. No prior list exists here, so those reads report undefined. mockContextProxy = { setValues: vi.fn().mockResolvedValue(undefined), setValue: vi.fn().mockResolvedValue(undefined), setProviderSettings: vi.fn().mockResolvedValue(undefined), + getValue: vi.fn(() => undefined), } as unknown as MockedManager // Double provides only updateCustomMode, the CustomModesManager member auto-import calls. From 1e74194017ee627307fc5a57c03408e267ee94bd Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Mon, 30 Nov 2026 14:12:41 +0100 Subject: [PATCH 43/52] Delete only the command-list entries the dialog showed and the user omitted A save used to delete every command-list entry that no layer still held. An entry the dialog never displayed could therefore disappear without a warning, because its absence from the stores was read as a deletion. The save now deletes an entry only when the dialog displayed it and the submission omits it, and it carries every entry the dialog did not display into the write. That rule makes the import's mirror machinery unnecessary, so it is gone. An import no longer copies its result into the state copy to keep a later save from deleting it. The pending-mirror record, the two mirror helpers, the import span and the hidden-entry re-add all existed only to serve the old rule, and all are removed. An import now writes its configuration half and its state half as one pair. One non-reentrant lock now serialises a save against an import. It replaces the two reference-counted spans that each had to await the other. A multi-key import that fails part way now rolls back every key that landed. Previously the rollback read a list that only the failed call could fill, so a key written before the failure stayed behind. --- packages/types/src/vscode-extension-host.ts | 14 +- .../__tests__/commandScope.spec.ts | 425 ++++++------- src/core/auto-approval/commandScope.ts | 271 ++++---- .../config/__tests__/importExport.spec.ts | 586 +++++------------- src/core/config/importExport.ts | 492 +++++---------- .../__tests__/webviewMessageHandler.spec.ts | 510 +++++++-------- src/core/webview/webviewMessageHandler.ts | 201 +++--- src/utils/autoImportSettings.ts | 10 +- 8 files changed, 1008 insertions(+), 1501 deletions(-) diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 1633591e74..556b25d347 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -867,17 +867,19 @@ export interface WebviewMessage { updatedSettings?: RooCodeSettings /** * The lists as the dialog last showed them, sent with the save that rewrites - * them. Without it the save cannot tell a file-side addition from a user - * deletion, because both look like "in the file, absent from the submission". - * A sender that shows no lists omits it. + * them. A save deletes an entry from a layer only when this baseline showed + * that entry for that layer and the submission omits it. A sender that omits + * it gets the compatibility rule: every entry the layers hold counts as + * displayed, so an omission is a deletion. The settings dialog always sends + * one. */ commandListBaseline?: { allowedCommands?: string[] deniedCommands?: string[] /** - * The gate as the dialog last showed it. A gate flip between display and save - * hides workspace entries. This value lets the save treat an already-shown - * entry as known state, not a new promotion to global. + * The gate as the dialog last showed it. With the gate off at display the + * workspace layer was not on screen, so no workspace entry counts as + * displayed and none is deleted by omission. */ workspaceCommandListsEnabled?: boolean } diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 50995befd1..16d653ed35 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -11,6 +11,7 @@ import { type CommandListInspection, classifyCommandListBaseline, commandListFolderForResource, + displayedCommandListScopes, getEffectiveCommandDecision, readCommandListScopes, resolveEffectiveCommandLists, @@ -251,17 +252,21 @@ describe("readCommandListScopes", () => { }) describe("splitCommandListScopes", () => { + // The caller applies the deletions, so each layer argument arrives already + // filtered. The function's remaining job is routing: a layer keeps what it was + // handed, and a submitted entry neither layer holds is new and goes to global. + it("keeps workspace entries in the workspace layer and routes new entries to global", () => { // The dialog sends the merged list back. A workspace-only entry such as // "docker" must not reach the global write. - const result = splitCommandListScopes(["docker", "aws"], ["docker"], []) + const result = splitCommandListScopes(["docker", "aws"], ["docker"], [], ["docker"]) expect(result.workspaceWrite).toEqual(["docker"]) expect(result.globalWrite).toEqual(["aws"]) }) it("keeps a global entry in the global layer", () => { - const result = splitCommandListScopes(["git"], [], ["git"]) + const result = splitCommandListScopes(["git"], [], ["git"], ["git"]) expect(result.workspaceWrite).toEqual([]) expect(result.globalWrite).toEqual(["git"]) @@ -270,33 +275,27 @@ describe("splitCommandListScopes", () => { it("keeps an entry present in both layers in both layers when retained", () => { // Do not delete the user's global entry because the current folder also // defines it. The user authored the entry in both scopes and kept it. - const result = splitCommandListScopes(["docker"], ["docker"], ["docker"]) + const result = splitCommandListScopes(["docker"], ["docker"], ["docker"], ["docker"]) expect(result.workspaceWrite).toEqual(["docker"]) expect(result.globalWrite).toEqual(["docker"]) }) - it("removes a deleted entry from the workspace layer without touching global", () => { - // The user kept "git" and deleted the workspace-only "docker". "git" survives at its own global layer. - const result = splitCommandListScopes(["git"], ["docker"], ["git"]) + it("writes each layer as the caller filtered it", () => { + // A deleted entry never reaches this function: the caller removed it from the + // layer argument, and the function writes what it was handed. + const result = splitCommandListScopes(["git"], [], ["git"], ["git"]) expect(result.workspaceWrite).toEqual([]) expect(result.globalWrite).toEqual(["git"]) }) - it("removes a deleted entry from every layer that contained it", () => { - // "docker" lived in both layers and the user deleted it. The kept "rm" stays at the workspace layer only. - const result = splitCommandListScopes(["rm"], ["docker", "rm"], ["docker"]) - - expect(result.workspaceWrite).toEqual(["rm"]) - expect(result.globalWrite).toEqual([]) - }) - it("routes entries the dialog seeded to the layer they came from", () => { const result = splitCommandListScopes( ["git", "docker", "pnpm docker", "aws"], ["docker", "pnpm docker"], ["git"], + ["docker", "pnpm docker", "git"], ) expect(result.workspaceWrite).toEqual(["docker", "pnpm docker"]) @@ -304,7 +303,7 @@ describe("splitCommandListScopes", () => { }) it("orders the global write as existing global entries then new entries in dialog order", () => { - const result = splitCommandListScopes(["aws", "git", "npm"], ["docker"], ["git"]) + const result = splitCommandListScopes(["aws", "git", "npm"], ["docker"], ["git"], ["docker", "git"]) expect(result.globalWrite).toEqual(["git", "aws", "npm"]) }) @@ -312,18 +311,29 @@ describe("splitCommandListScopes", () => { it("drops blank and non-string entries from the incoming list", () => { // Deliberate wrong runtime type: configuration lists arrive as unknown, // so the sanitizer must drop non-strings instead of throwing on them. - const result = splitCommandListScopes(["git", "", " ", 42 as unknown as string], [], ["git"]) + const result = splitCommandListScopes(["git", "", " ", 42 as unknown as string], [], ["git"], ["git"]) expect(result.globalWrite).toEqual(["git"]) expect(result.workspaceWrite).toEqual([]) }) it("deduplicates layers so re-writing cannot introduce duplicates", () => { - const result = splitCommandListScopes(["docker", "docker"], ["docker", "docker"], ["docker"]) + const result = splitCommandListScopes(["docker", "docker"], ["docker", "docker"], ["docker"], ["docker"]) expect(result.workspaceWrite).toEqual(["docker"]) expect(result.globalWrite).toEqual(["docker"]) }) + + it("does not re-promote an entry the save just deleted from a layer", () => { + // The save deleted "aws" from both writes, so neither layer argument carries + // it, yet the submission still does. "New" must mean held by no layer at save + // start: reading it off the write lists would put the deleted entry straight + // back into the global write and make the deletion unobservable. + const result = splitCommandListScopes(["aws"], [], [], ["aws"]) + + expect(result.globalWrite).toEqual([]) + expect(result.workspaceWrite).toEqual([]) + }) }) describe("resolveWorkspaceWriteTarget", () => { @@ -535,8 +545,8 @@ it("resolveEffectiveCommandLists: hides every workspace entry, allow and deny al expect(effective.allowed).toEqual([]) expect(effective.denied).toEqual([]) - expect(effective.hiddenWorkspaceAllow).toEqual(["docker"]) - expect(effective.hiddenWorkspaceDeny).toEqual(["rm"]) + expect(effective.keptWorkspaceAllow).toEqual([]) + expect(effective.keptWorkspaceDeny).toEqual([]) }) it("resolveEffectiveCommandLists: treats unshadowed workspace entries as the sole layer when the global layer is empty", () => { @@ -544,8 +554,8 @@ it("resolveEffectiveCommandLists: treats unshadowed workspace entries as the sol expect(effective.allowed).toEqual(["git", "docker", "aws"]) expect(effective.denied).toEqual(["rm"]) - expect(effective.hiddenWorkspaceAllow).toEqual([]) - expect(effective.hiddenWorkspaceDeny).toEqual([]) + expect(effective.keptWorkspaceAllow).toEqual(["docker", "aws"]) + expect(effective.keptWorkspaceDeny).toEqual(["rm"]) }) it("resolveEffectiveCommandLists: lets a global allow entry decide a command a longer workspace deny entry also matches", () => { @@ -555,7 +565,7 @@ it("resolveEffectiveCommandLists: lets a global allow entry decide a command a l expect(effective.allowed).toEqual(["git"]) expect(effective.denied).toEqual([]) - expect(effective.hiddenWorkspaceDeny).toEqual(["git push"]) + expect(effective.keptWorkspaceDeny).toEqual([]) }) it("resolveEffectiveCommandLists: lets a global deny entry veto a longer workspace allow entry", () => { @@ -563,7 +573,7 @@ it("resolveEffectiveCommandLists: lets a global deny entry veto a longer workspa expect(effective.allowed).toEqual([]) expect(effective.denied).toEqual(["git"]) - expect(effective.hiddenWorkspaceAllow).toEqual(["git push"]) + expect(effective.keptWorkspaceAllow).toEqual([]) }) it("resolveEffectiveCommandLists: silences every workspace deny entry behind a global wildcard allow entry", () => { @@ -571,7 +581,7 @@ it("resolveEffectiveCommandLists: silences every workspace deny entry behind a g expect(effective.allowed).toEqual(["*"]) expect(effective.denied).toEqual([]) - expect(effective.hiddenWorkspaceDeny).toEqual(["git push", "rm -rf"]) + expect(effective.keptWorkspaceDeny).toEqual([]) }) it("resolveEffectiveCommandLists: shadows workspace entries case-insensitively, the way the matcher matches", () => { @@ -581,10 +591,13 @@ it("resolveEffectiveCommandLists: shadows workspace entries case-insensitively, true, ) + // "git status" is shadowed by the global allow "Git", so it never reaches the + // matcher. "DOCKER" is a deny entry and no global entry matches it, so it is + // kept: shadowing is per entry, and only the allow-side entry is covered. expect(effective.allowed).toEqual(["Git"]) expect(effective.denied).toEqual(["DOCKER"]) - expect(effective.hiddenWorkspaceAllow).toEqual(["git status"]) - expect(effective.hiddenWorkspaceDeny).toEqual([]) + expect(effective.keptWorkspaceAllow).toEqual([]) + expect(effective.keptWorkspaceDeny).toEqual(["DOCKER"]) }) // A global entry decides every command it matches. A workspace entry applies @@ -1619,125 +1632,24 @@ it.skipIf(process.platform !== "win32")( ) describe("classifyCommandListBaseline", () => { - // The four ways a submitted entry survives the baseline filter, plus the - // drop case. Each row names the layer that keeps the entry, so a broken - // predicate fails the row that owns it and no other. - interface SurvivalRow { - name: string - baseline: string[] - incoming: string[] - workspace: string[] - stateGlobal: string[] - configGlobal: string[] - globalLayerAtSaveStart: string[] | undefined - stateCopyIsShippedDefault: boolean - /** Entries an import could not mirror yet. Absent means none are pending. */ - pendingGlobalEntries?: string[] - survives: boolean - } - - const rows: SurvivalRow[] = [ - { - name: "an entry outside the baseline survives as a user addition", - baseline: [], - incoming: ["git"], - workspace: [], - stateGlobal: [], - configGlobal: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - survives: true, - }, - { - name: "a baseline entry the workspace layer holds survives", - baseline: ["docker"], - incoming: ["docker"], - workspace: ["docker"], - stateGlobal: [], - configGlobal: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - survives: true, - }, - { - name: "a baseline entry the configuration global layer holds survives", - baseline: ["git"], - incoming: ["git"], - workspace: [], - stateGlobal: [], - configGlobal: ["git"], - globalLayerAtSaveStart: ["git"], - stateCopyIsShippedDefault: false, - survives: true, - }, - { - name: "a baseline entry only the state copy holds survives when that copy is the shipped default", - baseline: ["git"], - incoming: ["git"], - workspace: [], - stateGlobal: ["git"], - configGlobal: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: true, - survives: true, - }, - { - name: "a baseline entry only the state copy holds is dropped when the copy is not the shipped default", - baseline: ["git"], - incoming: ["git"], - workspace: [], - stateGlobal: ["git"], - configGlobal: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - survives: false, - }, - { - name: "a baseline entry only the state copy holds is dropped when a global layer exists", + it("reports an entry a layer gained after display as externally added", () => { + // The settings file gained "aws" while the dialog was open. The dialog never + // showed it, so the submission omits it, and the save writes it back. + const result = classifyCommandListBaseline({ baseline: ["git"], incoming: ["git"], - workspace: [], - stateGlobal: ["git"], - configGlobal: [], - globalLayerAtSaveStart: [], - stateCopyIsShippedDefault: true, - survives: false, - }, - { - name: "a pending imported entry survives even when the state copy is not the shipped default", - baseline: ["aws"], - incoming: ["aws"], - workspace: [], - stateGlobal: ["aws"], - configGlobal: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - pendingGlobalEntries: ["aws"], - survives: true, - }, - ] - - it.each(rows)("$name", (row) => { - const result = classifyCommandListBaseline({ - baseline: row.baseline, - incoming: row.incoming, - currentScopes: { global: row.stateGlobal, workspace: row.workspace, merged: [] }, - configGlobalAtSaveStart: row.configGlobal, - globalLayerAtSaveStart: row.globalLayerAtSaveStart, - stateCopyIsShippedDefault: row.stateCopyIsShippedDefault, - pendingGlobalEntries: row.pendingGlobalEntries ?? [], - hiddenWorkspaceEntries: [], - gateAtDisplay: undefined, + currentScopes: { global: [], workspace: ["aws"], merged: [] }, + configGlobalAtSaveStart: [], + gateAtDisplay: true, }) - expect(result.splitSourceEntries.includes(row.incoming[0])).toBe(row.survives) + expect(result.externallyAdded).toEqual(["aws"]) }) // The external set spans three layers, and a submitted entry is never - // external. These rows pin four filter terms: the submitted-entry term, the + // external. These rows pin three filter terms: the submitted-entry term, the // baseline term, and the union terms for the state copy's global layer and - // the configuration's global layer at save start. The union's workspace term - // and the hidden-entry term are pinned only by the standalone tests below. + // the configuration's global layer at save start. interface ExternalRow { name: string baseline: string[] @@ -1793,60 +1705,29 @@ describe("classifyCommandListBaseline", () => { incoming: row.incoming, currentScopes: { global: row.stateGlobal, workspace: row.workspace, merged: [] }, configGlobalAtSaveStart: row.configGlobal, - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: [], - gateAtDisplay: undefined, + gateAtDisplay: true, }) expect(result.externallyAdded).toEqual(row.expected) }) - it("classifies a layer entry the submission omits as externally added", () => { - // The settings file gained "aws" while the dialog was open. The dialog never - // showed it, so the submission omits it, and the save must re-admit it. - const result = classifyCommandListBaseline({ - baseline: ["git"], - incoming: ["git"], - currentScopes: { global: [], workspace: ["aws"], merged: [] }, - configGlobalAtSaveStart: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: [], - gateAtDisplay: undefined, - }) - - expect(result.externallyAdded).toEqual(["aws"]) - expect(result.splitSourceEntries).toContain("aws") - }) - - it("keeps a hidden workspace entry out of the external set unless the global layer holds it", () => { - // The workspace re-add preserves a hidden entry, so reporting it as externally - // added would warn on every save. The global layer is displayed, so an entry - // there is a real file addition and does warn. + it("reports a workspace entry the gate hid at display only when the configuration holds it", () => { + // With the gate off no workspace entry was displayed, so the baseline omits + // all of them. Reporting them would warn on every save, so only an entry the + // displayed configuration layer also holds is a real file addition. const hiddenOnly = classifyCommandListBaseline({ baseline: [], incoming: [], currentScopes: { global: [], workspace: ["docker"], merged: [] }, configGlobalAtSaveStart: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: ["docker"], - gateAtDisplay: undefined, + gateAtDisplay: false, }) const alsoGlobal = classifyCommandListBaseline({ baseline: [], incoming: [], currentScopes: { global: [], workspace: ["docker"], merged: [] }, configGlobalAtSaveStart: ["docker"], - globalLayerAtSaveStart: ["docker"], - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: ["docker"], - gateAtDisplay: undefined, + gateAtDisplay: false, }) expect(hiddenOnly.externallyAdded).toEqual([]) @@ -1859,91 +1740,175 @@ describe("classifyCommandListBaseline", () => { incoming: ["git"], currentScopes: { global: ["aws"], workspace: ["docker"], merged: [] }, configGlobalAtSaveStart: ["aws"], - globalLayerAtSaveStart: ["aws"], - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: [], gateAtDisplay: undefined, }) expect(result.externallyAdded).toEqual([]) - expect(result.splitSourceEntries).toEqual(["git"]) - }) - - it("keeps a displayed entry out of the promotion set whether or not the gate moved", () => { - // "git" was displayed and sits in the hidden set, so keeping it stays a - // workspace decision. Only "docker", which the baseline never showed, may - // still be promoted. - const result = classifyCommandListBaseline({ - baseline: ["git"], - incoming: ["git"], - currentScopes: { global: [], workspace: ["git"], merged: [] }, - configGlobalAtSaveStart: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: ["git", "docker"], - gateAtDisplay: true, - }) - - expect(result.promotionHiddenEntries).toEqual(["docker"]) }) it("treats a baseline of the wrong runtime type as no baseline", () => { // A sender can put anything in the baseline slot. A non-array cannot answer - // the display-time question, so the guard keeps the current hidden set - // rather than filtering it against a value that cannot hold entries. + // the display-time question, so the guard reports nothing. const result = classifyCommandListBaseline({ // Deliberately wrong type: the runtime guard, not the type system, decides. baseline: "git" as unknown as string[], incoming: ["git"], currentScopes: { global: [], workspace: ["git"], merged: [] }, configGlobalAtSaveStart: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: ["git", "docker"], gateAtDisplay: true, }) expect(result.externallyAdded).toEqual([]) - expect(result.splitSourceEntries).toEqual(["git"]) - expect(result.promotionHiddenEntries).toEqual(["git", "docker"]) }) +}) - it("drops a displayed entry from the promotion set when the gate flipped since display", () => { - // The dialog showed "git" while the gate was on. The gate is off now, so "git" - // sits in the hidden set, and keeping it must stay a workspace decision rather - // than become a promotion into the global layer. - const result = classifyCommandListBaseline({ +describe("displayedCommandListScopes", () => { + const base = { + baseline: [] as string[] | undefined, + incoming: [] as string[], + stateCopy: [] as string[], + configGlobal: [] as string[], + workspaceNow: [] as string[], + gateAtDisplay: true as boolean | undefined, + seededEntries: [] as string[], + } + + it("deletes a displayed entry the submission omits from every layer that held it", () => { + const result = displayedCommandListScopes({ + ...base, + baseline: ["echo", "git"], + incoming: ["git"], + stateCopy: ["echo", "git"], + configGlobal: ["echo", "git"], + workspaceNow: ["echo"], + }) + + expect(result.displayedGlobal).toEqual(["echo", "git"]) + expect(result.displayedWorkspace).toEqual(["echo", "git"]) + expect(result.writableGlobal).toEqual(["git"]) + expect(result.writableWorkspace).toEqual([]) + }) + + it("keeps an entry the dialog never displayed, so a file edit made while it was open survives", () => { + // "aws" reached the workspace layer after the dialog rendered its list, so the + // baseline omits it and the save has no evidence that the user removed it. + const result = displayedCommandListScopes({ + ...base, baseline: ["git"], incoming: ["git"], - currentScopes: { global: [], workspace: ["git"], merged: [] }, - configGlobalAtSaveStart: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: ["git", "docker"], - gateAtDisplay: true, + workspaceNow: ["git", "aws"], }) - expect(result.promotionHiddenEntries).toEqual(["docker"]) + expect(result.displayedWorkspace).toEqual(["git"]) + expect(result.writableWorkspace).toEqual(["git", "aws"]) }) - it("returns the whole hidden set when the sender reported no display-time value", () => { - const result = classifyCommandListBaseline({ + it("carries a global entry the baseline omits, so a file edit made while the dialog was open survives", () => { + // "npm" reached the global layer after the dialog rendered its list, so the + // baseline omits it. The global write replaces its layer, so the entry is lost + // unless the carry-over clause writes it back. + const result = displayedCommandListScopes({ + ...base, baseline: ["git"], incoming: ["git"], - currentScopes: { global: [], workspace: ["git"], merged: [] }, - configGlobalAtSaveStart: [], - globalLayerAtSaveStart: undefined, - stateCopyIsShippedDefault: false, - pendingGlobalEntries: [], - hiddenWorkspaceEntries: ["docker"], - gateAtDisplay: undefined, + stateCopy: ["git", "npm"], + configGlobal: ["git", "npm"], + }) + + expect(result.displayedGlobal).toEqual(["git"]) + expect(result.writableGlobal).toEqual(["git", "npm"]) + }) + + it("deletes nothing when the gate hid the workspace layer at display", () => { + // The dialog showed only the global layer, so no workspace entry was displayed + // and none may be deleted by omission. A new entry lands in the global write. + const result = displayedCommandListScopes({ + ...base, + baseline: ["git"], + incoming: ["git", "docker"], + // The gate hides the workspace layer only. The global layer was displayed, + // so the state copy that stands in for it holds the entry the dialog showed. + stateCopy: ["git"], + workspaceNow: ["echo"], + gateAtDisplay: false, + }) + + expect(result.displayedWorkspace).toEqual([]) + expect(result.writableWorkspace).toEqual(["echo"]) + expect(result.displayedGlobal).toEqual(["git"]) + }) + + it("applies the omission rule to every layer entry when the sender omits the baseline", () => { + // The compatibility branch: with no displayed list the save treats each layer + // as fully displayed, so an omission is a deletion, exactly as every save + // behaved before the baseline existed. + const result = displayedCommandListScopes({ + ...base, + baseline: undefined, + incoming: ["git"], + stateCopy: ["git", "aws"], + configGlobal: ["git", "aws"], + workspaceNow: ["echo", "docker"], + }) + + expect(result.displayedGlobal).toEqual(["git", "aws"]) + expect(result.displayedWorkspace).toEqual(["echo", "docker"]) + expect(result.writableGlobal).toEqual(["git"]) + expect(result.writableWorkspace).toEqual([]) + }) + + it("deletes a displayed state-copy-only entry the configuration and the shipped default both omit", () => { + // The state copy is a key the user deleted from User Settings: no configuration + // layer holds it and the shipped default does not name it. A submitted entry is + // not evidence that the dialog displayed it, and an omitted one is no better, + // so both delete. Writing either back is the leak this rule exists to remove. + const submitted = displayedCommandListScopes({ + ...base, + baseline: ["git"], + incoming: ["git"], + stateCopy: ["git"], + }) + const omitted = displayedCommandListScopes({ + ...base, + baseline: ["git"], + incoming: [], + stateCopy: ["git"], + }) + + expect(submitted.writableGlobal).toEqual([]) + expect(omitted.writableGlobal).toEqual([]) + }) + + it("keeps a displayed state-copy-only entry the shipped default names", () => { + // The same shape as the deleted key, separated only by the value test: the + // state copy equals the shipped default, so it is the activation seed rather + // than a deletion, and it keeps its global home. + const result = displayedCommandListScopes({ + ...base, + baseline: ["git"], + incoming: ["git"], + stateCopy: ["git"], + seededEntries: ["git"], + }) + + expect(result.writableGlobal).toEqual(["git"]) + }) + + it("does not let a seeded entry vouch for an entry the default does not name", () => { + // The seed is an entry set, not a whole-list flag: a workspace-only entry that + // happens to sit in a seeded save stays out of the global write, so a seeded + // list cannot flatten a workspace entry into global settings. + const result = displayedCommandListScopes({ + ...base, + baseline: ["git", "docker"], + incoming: ["git", "docker"], + stateCopy: ["git"], + seededEntries: ["git"], + workspaceNow: ["docker"], }) - expect(result.promotionHiddenEntries).toEqual(["docker"]) + expect(result.writableGlobal).toEqual(["git"]) + expect(result.writableWorkspace).toEqual(["docker"]) }) }) diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 324e8715e8..9d5e32b59f 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -69,9 +69,9 @@ export function commandListConfiguration(folderResource?: vscode.Uri): vscode.Wo * enforcement reads the global layer only, and the folder layer contributes * nothing to the decision. * - * @param cwd - The task's working directory. Empty, absent, unmatched, or - * bound by an unresolvable root gives `undefined` and keeps the first-folder - * configuration. + * @param cwd - The task's working directory. Absent or empty keeps the + * first-folder configuration. A nonempty cwd that names no folder drops the + * folder layer, so enforcement reads the global layers alone. * @returns The containing folder's registry URI. It stays uncanonicalized, * because folder-scoped configuration resolves against the registry. */ @@ -278,36 +278,123 @@ export interface CommandListWriteScopes { * Splits the dialog's merged list back into the two layers that composed it, * so a save cannot flatten workspace entries into global settings. * - * - A kept entry stays in every layer that held it. Dropping it from the global - * write would delete a global entry that the folder mirrors. - * - A removed entry leaves every layer that held it, so a dialog delete works - * for workspace entries. - * - A new entry lands in the global layer, as dialog edits did before. + * The caller hands already-filtered layers: {@link displayedCommandListScopes} + * applied the deletions, so neither argument loses an entry here. What is left + * is where a new entry lands: an entry the submission carries that no layer held + * at save start is new, and it goes to the global layer, as dialog edits did + * before. * * @param incoming - The full merged list sent by the webview on save. - * @param workspaceLayer - The current workspace-scope configuration value. - * @param globalLayer - The list currently persisted in extension global state. + * @param workspaceLayer - The workspace write's entries, already filtered. + * @param globalLayer - The global write's entries, already filtered. + * @param known - Every entry any layer held at save start. * @returns The per-layer values to write back. */ export function splitCommandListScopes( incoming: string[], workspaceLayer: string[], globalLayer: string[], + known: string[], ): CommandListWriteScopes { const kept = new Set(sanitizeCommandList(incoming)) - const workspace = sanitizeCommandList(workspaceLayer) - const global = sanitizeCommandList(globalLayer) - const known = new Set([...workspace, ...global]) + const knownEntries = new Set(sanitizeCommandList(known)) // Deduplicated so re-writing a layer cannot introduce duplicates. - const workspaceWrite = [...new Set(workspace.filter((command) => kept.has(command)))] - const globalWrite = [ - ...new Set(global.filter((command) => kept.has(command))), - // Preserve the dialog's ordering for entries the user added. - ...[...kept].filter((command) => !known.has(command)), - ] + return { + workspaceWrite: [...new Set(sanitizeCommandList(workspaceLayer))], + globalWrite: [ + ...new Set(sanitizeCommandList(globalLayer)), + // Preserve the dialog's ordering for entries the user added. + ...[...kept].filter((command) => !knownEntries.has(command)), + ], + } +} - return { globalWrite, workspaceWrite } +export interface DisplayedCommandListScopes { + /** Baseline entries the dialog displayed for the global layer. */ + displayedGlobal: string[] + /** Baseline entries the dialog displayed for the workspace layer. */ + displayedWorkspace: string[] + /** The global write's entries: the layer as it stands, less this save's deletions. */ + writableGlobal: string[] + /** The workspace write's entries: the layer as it stands, less this save's deletions. */ + writableWorkspace: string[] +} + +/** + * Decides which entries a save deletes, from what the dialog displayed. + * + * A save deletes an entry from a layer only when the dialog displayed that + * entry for that layer and the submission omits it. An entry the dialog never + * showed is carried into that layer's write unchanged: the save has no evidence + * about it, and it may be an edit another writer made while the dialog was open. + * Deleting it would lose that edit. + * + * The displayed set is the baseline itself, with no store confirming it. On a + * default install no configuration layer exists, so a seeded or file-added entry + * is held by the state copy alone, and requiring a store would disqualify an + * entry the user really did see. Membership is deliberately not a term: it + * answers "which store holds this?", never "did the dialog show it?". + * + * A displayed entry the configuration does not hold is written back only when the + * shipped default names it. Otherwise the state copy is a key the user deleted, + * and writing it back is the leak this rule exists to remove. + * + * A sender that omits the baseline has no displayed list, so every entry its + * layers hold counts as displayed and an omission is a deletion. That is the + * rule every save applied before the baseline existed, and keeping it here is + * what makes such a sender's deletions still land. The settings dialog always + * sends a baseline, so this branch is compatibility for a sender that does not. + * + * @param input.baseline - The merged list the dialog displayed, or `undefined` + * when the sender sent none. + * @param input.incoming - The submitted list. + * @param input.stateCopy - The extension state copy, which display reads as the + * global layer. + * @param input.configGlobal - The configuration's global layer at save start, + * together with any activation-seeded copy the caller counts as global state. + * @param input.workspaceNow - The workspace layer as it stands at save start. + * @param input.gateAtDisplay - The gate as the dialog showed it. `false` means + * the workspace layer was not displayed. + * @param input.seededEntries - The entries the shipped default vouches for, from + * the caller's seeded global copy. A value comparison against the default, never + * a store-membership test. + * @returns The two displayed sets and the two write lists. + */ +export function displayedCommandListScopes(input: { + baseline: string[] | undefined + incoming: string[] + stateCopy: string[] + configGlobal: string[] + workspaceNow: string[] + gateAtDisplay: boolean | undefined + seededEntries: string[] +}): DisplayedCommandListScopes { + const submitted = new Set(sanitizeCommandList(input.incoming)) + const workspace = sanitizeCommandList(input.workspaceNow) + const stateCopy = sanitizeCommandList(input.stateCopy) + const config = sanitizeCommandList(input.configGlobal) + const seededSet = new Set(sanitizeCommandList(input.seededEntries)) + // A baseline of another runtime type cannot answer the display-time question, so + // it is read as absent. The sender then gets the compatibility rule below. + const hasBaseline = Array.isArray(input.baseline) + const baseline = hasBaseline ? sanitizeCommandList(input.baseline) : [] + const heldGlobal = [...new Set([...config, ...stateCopy])] + + const displayedWorkspace = hasBaseline ? (input.gateAtDisplay === false ? [] : baseline) : workspace + const displayedWorkspaceSet = new Set(displayedWorkspace) + const displayedGlobalSet = hasBaseline ? new Set(baseline) : new Set(heldGlobal) + const configSet = new Set(config) + + // Only a displayed entry can be deleted by omission. Everything else is + // carried into the write, which is what makes an unshown file edit survive. + const writableWorkspace = workspace.filter((entry) => !displayedWorkspaceSet.has(entry) || submitted.has(entry)) + const writableGlobal = heldGlobal.filter( + (entry) => + !displayedGlobalSet.has(entry) || (submitted.has(entry) && (configSet.has(entry) || seededSet.has(entry))), + ) + + return { displayedGlobal: [...displayedGlobalSet], displayedWorkspace, writableGlobal, writableWorkspace } } /** @@ -355,19 +442,18 @@ export function resolveWorkspaceWriteTarget( export interface CommandListBaselineClassification { /** Entries a layer held at save start that the baseline and the submission both omit. */ externallyAdded: string[] - /** Entries the split treats as known state, so a file deletion still applies. */ - splitSourceEntries: string[] - /** Hidden workspace entries the split must not read as new promotions. */ - promotionHiddenEntries: string[] } /** - * Classifies the submitted list against the baseline the dialog displayed. + * Reports the entries a layer gained while the settings dialog was open. + * + * An entry a layer holds, that the baseline the dialog rendered omits, and that + * the submission also omits was added by another writer after display. The save + * writes it back and warns the user about it. * - * The three results feed one split. `externallyAdded` holds entries that a - * layer gained while the dialog was open. `splitSourceEntries` holds the - * entries the split may keep. `promotionHiddenEntries` holds hidden entries - * that must not become a promotion into the global layer. + * A workspace entry counts only when the gate was on at display. With the gate + * off the dialog showed no workspace entry at all, so every one of them is + * absent from the baseline, and reporting them would warn on every save. * * @param input.baseline - The lists the dialog displayed for this key, or * `undefined` when the sender shows no lists. @@ -376,99 +462,37 @@ export interface CommandListBaselineClassification { * save-start snapshot. * @param input.configGlobalAtSaveStart - The configuration's global layer at * save start. - * @param input.globalLayerAtSaveStart - The same layer, kept as absent when the - * key had no global value. - * @param input.stateCopyIsShippedDefault - Whether the state copy for this key - * equals the key's shipped default. An absent global layer means a seeded copy - * only when this holds, so a key the user deleted is not read as seeded. - * @param input.pendingGlobalEntries - Entries an import wrote to the state copy - * whose settings-file mirror has not succeeded. No configuration layer holds - * them, and they are known global state all the same. - * @param input.hiddenWorkspaceEntries - Workspace entries the dialog did not - * display. * @param input.gateAtDisplay - The gate as the dialog showed it, if it sent it. - * A sender that sent no value writes its hidden set unclassified. - * @returns The externally added entries, the split source, and the promotion - * hidden entries. + * @returns The externally added entries. */ export function classifyCommandListBaseline(input: { baseline: string[] | undefined incoming: string[] currentScopes: CommandListScopes configGlobalAtSaveStart: string[] - globalLayerAtSaveStart: string[] | undefined - stateCopyIsShippedDefault: boolean - pendingGlobalEntries: string[] - hiddenWorkspaceEntries: string[] gateAtDisplay: boolean | undefined }): CommandListBaselineClassification { - const { - baseline, - incoming, - currentScopes, - configGlobalAtSaveStart, - globalLayerAtSaveStart, - stateCopyIsShippedDefault, - pendingGlobalEntries, - hiddenWorkspaceEntries, - gateAtDisplay, - } = input - - // A file entry the dialog never showed looks like a user deletion: in the file, - // absent from the submitted list. The baseline separates the two, so entries - // outside it are re-admitted before the split, while deleting a baseline entry - // still applies. Hidden entries are excluded because the caller's workspace - // re-add preserves them, so a warning would fire on every save. That - // exclusion covers only entries the hidden workspace layer held. The - // configuration's global layer is displayed, and excluding it would delete - // the user's file addition. - // A sender with no baseline writes its list unclassified. The union spans every - // layer that can hold an entry at save start, because the state copy lags. - const externallyAdded = Array.isArray(baseline) - ? [...new Set([...currentScopes.workspace, ...currentScopes.global, ...configGlobalAtSaveStart])].filter( - (entry) => - !baseline.includes(entry) && - !incoming.includes(entry) && - (!hiddenWorkspaceEntries.includes(entry) || configGlobalAtSaveStart.includes(entry)), - ) - : [] - // A file-deleted entry is still in the submitted list. With no layer holding - // it, the split would treat it as brand-new and promote a project entry into - // the global layer. The baseline separates that case from a user addition. - // Submitting a displayed entry signals retention. A retained entry that no - // configuration layer holds was removed in the file. The file then wins over - // the stale dialog buffer. - // An absent global layer means either that the activation seed wrote the state - // copy or that the user deleted the key. Only the state copy that still equals - // the shipped default is the seed's, so only that copy counts as known global - // state. Trusting every absent-layer copy would write a deleted key's entries - // back, and the user would see no warning. - const seededStateEntries = - globalLayerAtSaveStart === undefined && stateCopyIsShippedDefault ? currentScopes.global : [] - // A pending entry is a third source of known global state: an import wrote it - // to the state copy, and its mirror has not reached the settings file. Without - // it, the first save after a failed mirror reads the entry as a file deletion. - const knownStateEntries = [...seededStateEntries, ...pendingGlobalEntries] - const splitSourceEntries = Array.isArray(baseline) - ? [...incoming, ...externallyAdded].filter( - (entry) => - !baseline.includes(entry) || - currentScopes.workspace.includes(entry) || - configGlobalAtSaveStart.includes(entry) || - knownStateEntries.includes(entry), - ) - : [...incoming, ...externallyAdded] - // A hidden entry the baseline shows was displayed, so keeping it stays a - // workspace decision. It must not become a promotion into the global layer, - // whether or not the gate moved since the dialog read it. An entry absent - // from the baseline was never displayed and may still be promoted. A sender - // with no baseline writes its hidden set unclassified. - const promotionHiddenEntries = - gateAtDisplay === undefined - ? hiddenWorkspaceEntries - : hiddenWorkspaceEntries.filter((entry) => !Array.isArray(baseline) || !baseline.includes(entry)) - - return { externallyAdded, splitSourceEntries, promotionHiddenEntries } + const { baseline, incoming, currentScopes, configGlobalAtSaveStart, gateAtDisplay } = input + + if (!Array.isArray(baseline)) { + return { externallyAdded: [] } + } + + // The union spans every layer that can hold an entry at save start, because + // the state copy lags the configuration. + const heldAtSaveStart = [ + ...new Set([...currentScopes.workspace, ...currentScopes.global, ...configGlobalAtSaveStart]), + ] + const externallyAdded = heldAtSaveStart.filter( + (entry) => + !baseline.includes(entry) && + !incoming.includes(entry) && + // With the gate off no workspace entry was displayed, so only a global + // entry can be a genuine addition. + (gateAtDisplay !== false || configGlobalAtSaveStart.includes(entry)), + ) + + return { externallyAdded } } export type CommandListRollbackOutcome = @@ -621,13 +645,6 @@ export interface EffectiveCommandLists { keptWorkspaceAllow: string[] /** Deny-side counterpart of {@link keptWorkspaceAllow}. */ keptWorkspaceDeny: string[] - /** - * Workspace allow entries that the gate or a global shadow hides. A dialog - * save must not delete them by omission. - */ - hiddenWorkspaceAllow: string[] - /** Deny-side counterpart of {@link hiddenWorkspaceAllow}. */ - hiddenWorkspaceDeny: string[] } /** @@ -648,8 +665,7 @@ export interface EffectiveCommandLists { * @param allowScopes - Raw `allowedCommands` layers from readCommandListScopes. * @param denyScopes - Raw `deniedCommands` layers from readCommandListScopes. * @param enabled - The value of the `workspaceCommandListsEnabled` gate. - * @returns The effective allow/deny lists, the per-layer split behind them, and - * the workspace entries hidden from each. + * @returns The effective allow/deny lists and the per-layer split behind them. */ export function resolveEffectiveCommandLists( allowScopes: CommandListScopes, @@ -670,16 +686,7 @@ export function resolveEffectiveCommandLists( const allowed = [...new Set([...globalAllow, ...keptWorkspaceAllow])] const denied = [...new Set([...globalDeny, ...keptWorkspaceDeny])] - return { - allowed, - denied, - globalAllow, - globalDeny, - keptWorkspaceAllow, - keptWorkspaceDeny, - hiddenWorkspaceAllow: allowScopes.workspace.filter((entry) => !allowed.includes(entry)), - hiddenWorkspaceDeny: denyScopes.workspace.filter((entry) => !denied.includes(entry)), - } + return { allowed, denied, globalAllow, globalDeny, keptWorkspaceAllow, keptWorkspaceDeny } } /** diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 257b602f14..a41992172f 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -11,17 +11,12 @@ import { clearAllMocks } from "../../../test-utils/reset" import { makeExtensionContext } from "../../../test-utils/vscode" import { - awaitCommandListImportSettled, - beginCommandListImport, - beginCommandListSave, - beginOrderedCommandListSave, importSettings, importSettingsFromFile, importSettingsFromPath, importSettingsWithFeedback, exportSettings, - mirrorImportedCommandLists, - pendingCommandListMirrors, + withCommandListLock, } from "../importExport" import { ProviderSettingsManager } from "../ProviderSettingsManager" import { ContextProxy } from "../ContextProxy" @@ -179,6 +174,26 @@ describe("importExport", () => { }) }) + // A configuration double that records what each layer holds, so a case can + // assert the layer an operation left behind instead of the calls it made. A + // call assertion passes when the undo is attempted and its effect is lost; + // only the layer can fail then. `inspect()` reports the recorded layer, so + // the rollback sees its own write, as the real API does. + function mockLayeredCommandListConfig(prior: Record, rejectKey?: string) { + const layers: Record = { ...prior } + const config = makeWorkspaceConfiguration() + const update = vi.mocked(config.update) + update.mockImplementation(async (key: string, value: string[] | undefined) => { + if (key === rejectKey) { + throw new Error(`${key} write failed`) + } + layers[key] = value + }) + vi.mocked(config.inspect).mockImplementation((key: string) => ({ key, globalValue: layers[key] })) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + return { update, layers } + } + describe("importSettingsFromPath persistence", () => { const validFileContent = JSON.stringify({ providerProfiles: { @@ -299,6 +314,14 @@ describe("importExport", () => { if (key === "deniedCommands") state.deniedCommands = value as string[] }) mockProviderSettingsManager.listConfig.mockRejectedValueOnce(new Error("config store is locked")) + // The pair's first half writes the configuration, so this case installs + // its own double rather than inheriting one from an earlier case. It + // records the layer each write leaves behind, so the assertions below read + // the layer the undo restored, not the call that attempted it. + const { update, layers } = mockLayeredCommandListConfig({ + allowedCommands: ["prior"], + deniedCommands: ["prior-deny"], + }) const result = await importSettingsFromPath("/mock/path/settings.json", { providerSettingsManager: mockProviderSettingsManager, @@ -312,9 +335,14 @@ describe("importExport", () => { expect(mockContextProxy.setValues).toHaveBeenCalledWith( expect.objectContaining({ allowedCommands: ["imported"], deniedCommands: ["imported-deny"] }), ) - // The settings file was never written, and extension state holds the - // lists it held before the import. - expect(vscode.workspace.getConfiguration).not.toHaveBeenCalled() + // The pair wrote the configuration first, so the failure has both halves to + // undo: the configuration layer by delta, the state copy from its snapshot. + expect(layers.allowedCommands).toEqual(["prior"]) + expect(layers.deniedCommands).toEqual(["prior-deny"]) + // Secondary pin: the write sequence that produced the layers above. + expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("allowedCommands", ["prior"], vscode.ConfigurationTarget.Global) + // Both stores hold the lists they held before the import. expect(state.allowedCommands).toEqual(["prior"]) expect(state.deniedCommands).toEqual(["prior-deny"]) }) @@ -738,11 +766,12 @@ describe("importExport", () => { // carries no list, must write nothing. function mockCommandListConfig() { // The shared structurally complete double keeps the configuration type - // correct. `update()` records the mirror's calls. + // correct. `update()` records the pair's writes, and the restore cases + // read the double itself to assert the undo. const config = makeWorkspaceConfiguration() const update = vi.mocked(config.update) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - return update + return { update, config } } function stubValidProviderProfiles() { @@ -786,24 +815,29 @@ describe("importExport", () => { filePath, ) - it("mirrors the command lists a successful import carried into the global configuration", async () => { + it("writes the command lists a successful import carried into the global configuration", async () => { const filePath = "/mock/path/settings.json" ;(fs.readFile as Mock).mockResolvedValue( validProfileFile({ allowedCommands: ["git", "imported"], deniedCommands: ["rm -rf"] }), ) ;(fs.access as Mock).mockResolvedValue(undefined) stubValidProviderProfiles() - // After setValues the state copy holds the same lists. The mirror and the - // state copy agree here, so this test pins that the success path writes both - // keys. + // The pair writes the configuration first and the state copy second, so after + // setValues both stores hold the same lists. This pins that the success path + // writes both keys. vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git", "imported"] : key === "deniedCommands" ? ["rm -rf"] : undefined, ) - const update = mockCommandListConfig() + const { update } = mockCommandListConfig() await runFeedback(filePath) - expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name) + // `writeImportedCommandLists` reads the scoped configuration, so the + // lookup names the first workspace folder when one exists. + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith( + Package.name, + vscode.workspace.workspaceFolders?.[0]?.uri, + ) expect(update).toHaveBeenCalledWith( "allowedCommands", ["git", "imported"], @@ -821,7 +855,7 @@ describe("importExport", () => { vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git", "stale"] : key === "deniedCommands" ? ["rm -rf"] : undefined, ) - const update = mockCommandListConfig() + const { update } = mockCommandListConfig() const showErrorMessageSpy = vi.spyOn(vscode.window, "showErrorMessage").mockResolvedValue(undefined) await runFeedback() @@ -839,7 +873,7 @@ describe("importExport", () => { vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git", "stale"] : key === "deniedCommands" ? ["rm -rf"] : undefined, ) - const update = mockCommandListConfig() + const { update } = mockCommandListConfig() const showErrorMessageSpy = vi.spyOn(vscode.window, "showErrorMessage").mockResolvedValue(undefined) await runFeedback(filePath) @@ -849,17 +883,17 @@ describe("importExport", () => { showErrorMessageSpy.mockRestore() }) - it("mirrors only the keys the import file carried, never the state copy's lists", async () => { + it("writes only the keys the import file carried, never the state copy's lists", async () => { const filePath = "/mock/path/settings.json" ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ mode: "code" })) ;(fs.access as Mock).mockResolvedValue(undefined) stubValidProviderProfiles() - // The state copy holds command lists that the file never carried. A mirror - // that read the state copy would write them over the user's settings file. + // The state copy holds command lists that the file never carried. A pair that + // read the state copy would write them over the user's settings file. vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git", "stale"] : undefined, ) - const update = mockCommandListConfig() + const { update } = mockCommandListConfig() await runFeedback(filePath) @@ -900,263 +934,160 @@ describe("importExport", () => { ).toBe(true) }) - it("retries a failed command-list mirror once, then reports the key it could not write", async () => { - const config = makeWorkspaceConfiguration() - const update = vi.mocked(config.update) - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - const showWarningMessageSpy = vi.spyOn(vscode.window, "showWarningMessage").mockResolvedValue(undefined) - - update.mockImplementation(async (key: string) => { - if (key === "deniedCommands") { - throw new Error("settings file is locked") - } - }) - - await mirrorImportedCommandLists({ allowedCommands: ["git"], deniedCommands: ["rm -rf"] }) - - expect(update).toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) - // Two attempts: the first failure is retried, the second is reported. - expect(update.mock.calls.filter(([key]) => key === "deniedCommands")).toHaveLength(2) - expect(showWarningMessageSpy).toHaveBeenCalledTimes(1) - expect(showWarningMessageSpy.mock.calls[0][0]).toContain("deniedCommands") - expect(showWarningMessageSpy.mock.calls[0][0]).not.toContain("allowedCommands") - - update.mockReset() - update.mockRejectedValue(new Error("settings file is locked")) - showWarningMessageSpy.mockClear() - - await mirrorImportedCommandLists({ allowedCommands: ["git"], deniedCommands: ["rm -rf"] }) - - // Both keys fail twice, and one report names both of them. - expect(update).toHaveBeenCalledTimes(4) - expect(showWarningMessageSpy).toHaveBeenCalledTimes(1) - expect(showWarningMessageSpy.mock.calls[0][0]).toContain("allowedCommands") - expect(showWarningMessageSpy.mock.calls[0][0]).toContain("deniedCommands") - - showWarningMessageSpy.mockRestore() - }) - - // The pending store outlives one call, so each case below clears it before and - // after. A successful mirror for both keys is the documented clear path. - async function clearPendingMirrors() { - const config = makeWorkspaceConfiguration() - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - await mirrorImportedCommandLists({ allowedCommands: [], deniedCommands: [] }) - vi.mocked(vscode.window.showWarningMessage).mockClear() - } - - it("keeps the entries of a failed mirror as pending until a later mirror succeeds", async () => { - await clearPendingMirrors() - - const config = makeWorkspaceConfiguration() - const update = vi.mocked(config.update) - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - update.mockRejectedValue(new Error("settings file is locked")) - - await mirrorImportedCommandLists({ allowedCommands: ["git", "aws"], deniedCommands: ["rm -rf"] }) - - // The settings file kept the old list, so neither key has a layer holding - // these entries. The save path reads them here instead. - expect(pendingCommandListMirrors()).toEqual({ - allowedCommands: ["git", "aws"], - deniedCommands: ["rm -rf"], - }) - - update.mockReset() - update.mockResolvedValue(undefined) - await mirrorImportedCommandLists({ allowedCommands: ["git", "aws"], deniedCommands: ["rm -rf"] }) - - // The configuration now carries both lists, so the mark would only - // duplicate a layer the save already reads. - expect(pendingCommandListMirrors()).toEqual({ allowedCommands: [], deniedCommands: [] }) - - await clearPendingMirrors() - }) - - it("leaves no pending entry when the import fails before it can mirror", async () => { - await clearPendingMirrors() - + it("rolls the configuration half back when the state half fails", async () => { const filePath = "/mock/path/settings.json" - ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git", "aws"] })) + ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git", "imported"] })) ;(fs.access as Mock).mockResolvedValue(undefined) stubValidProviderProfiles() - mockContextProxy.setValues.mockResolvedValue(undefined) - mockContextProxy.setValue.mockResolvedValue(undefined) - // The state write lands, and the failure after it rolls both lists back. - mockProviderSettingsManager.listConfig.mockRejectedValue(new Error("config listing failed")) - const update = mockCommandListConfig() - await runFeedback(filePath) + // The configuration holds a pre-import list, so the rollback has a delta to undo. + const { update, layers } = mockLayeredCommandListConfig({ allowedCommands: ["git"] }) - // A failed import reaches no mirror, so it marks nothing. A mark here would - // keep entries the rollback already discarded. - expect(update).not.toHaveBeenCalled() - expect(pendingCommandListMirrors()).toEqual({ allowedCommands: [], deniedCommands: [] }) + // The state half rejects, after the configuration half has landed. + mockContextProxy.setValues.mockRejectedValue(new Error("state write failed")) + + const result = await importSettingsFromPath(filePath, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) - await clearPendingMirrors() + expect(result.success).toBe(false) + // The layer the undo left behind. A rollback that is attempted and whose + // write is lost passes the call assertions below and fails this one. + expect(layers.allowedCommands).toEqual(["git"]) + // The pair writes the configuration first, then undoes exactly that delta. + expect(update).toHaveBeenCalledWith( + "allowedCommands", + ["git", "imported"], + vscode.ConfigurationTarget.Global, + ) + expect(update).toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) }) - it("posts the imported state while the mirror warning is still pending", async () => { + it("keeps both layers pre-import when the second key's write rejects", async () => { const filePath = "/mock/path/settings.json" - ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git"] })) + ;(fs.readFile as Mock).mockResolvedValue( + validProfileFile({ allowedCommands: ["git", "imported"], deniedCommands: ["x"] }), + ) ;(fs.access as Mock).mockResolvedValue(undefined) stubValidProviderProfiles() - mockContextProxy.setValues.mockResolvedValue(undefined) - mockContextProxy.setValue.mockResolvedValue(undefined) - mockContextProxy.setProviderSettings.mockResolvedValue(undefined) - - const config = makeWorkspaceConfiguration() - // Both attempts fail, so the mirror reports the key it could not write. - vi.mocked(config.update).mockRejectedValue(new Error("settings file is locked")) - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - // Never resolved: the real promise settles only when the user dismisses the - // warning, so an awaited warning would stall the import here. - const dismissal = createDeferred() - const showWarningMessageSpy = vi - .spyOn(vscode.window, "showWarningMessage") - .mockReturnValue(dismissal.promise) - - const provider = feedbackProvider() + // Both keys have a prior layer, so the key that lands has a delta to undo. + // `deniedCommands` is the pair's second key by the loop's order, not by a + // fixture choice. Its write rejects after `allowedCommands` landed. + const { layers } = mockLayeredCommandListConfig( + { allowedCommands: ["git"], deniedCommands: ["prior-deny"] }, + "deniedCommands", + ) - await importSettingsWithFeedback( - { - providerSettingsManager: mockProviderSettingsManager, - contextProxy: mockContextProxy, - customModesManager: mockCustomModesManager, - provider, - }, - filePath, + // The failure path restores the state copy from the values it read before the + // write, so the assertion below reads the snapshot, not the imported lists. + const state: { allowedCommands?: string[]; deniedCommands?: string[] } = { + allowedCommands: ["git"], + deniedCommands: ["prior-deny"], + } + vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" + ? state.allowedCommands + : key === "deniedCommands" + ? state.deniedCommands + : undefined, ) + mockContextProxy.setValue.mockImplementation(async (key, value) => { + if (key === "allowedCommands") state.allowedCommands = value as string[] + if (key === "deniedCommands") state.deniedCommands = value as string[] + }) - expect(provider.postStateToWebview).toHaveBeenCalledTimes(1) - expect(showWarningMessageSpy).toHaveBeenCalledWith(expect.stringContaining("allowedCommands")) + const result = await importSettingsFromPath(filePath, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) - showWarningMessageSpy.mockRestore() + expect(result.success).toBe(false) + expect(result.error).toContain("deniedCommands write failed") + // The first key landed and was undone; the second never landed. A rollback + // that cannot see the landed prefix leaves ["git", "imported"] here, and + // the next save resurrects it from the configuration. + expect(layers.allowedCommands).toEqual(["git"]) + expect(layers.deniedCommands).toEqual(["prior-deny"]) + // The state half never ran, so the snapshot is what both keys hold again. + expect(mockContextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git"]) + expect(mockContextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["prior-deny"]) + expect(state.allowedCommands).toEqual(["git"]) + expect(state.deniedCommands).toEqual(["prior-deny"]) }) - it("lets a save dispatched during an import run only against the post-import configuration", async () => { + it("lets a save dispatched during an import run only after the import released the lock", async () => { const filePath = "/mock/path/settings.json" ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git", "imported"] })) ;(fs.access as Mock).mockResolvedValue(undefined) stubValidProviderProfiles() - mockContextProxy.setValues.mockResolvedValue(undefined) - mockContextProxy.setValue.mockResolvedValue(undefined) - mockContextProxy.setProviderSettings.mockResolvedValue(undefined) - const mirrorWrite = createDeferred() - // The settings file the save reads. It stays empty until the mirror's write - // lands, which is the half-imported state the save must not observe. + // The configuration write is the import's first half and it parks here, so + // the import is inside the lock when the save arrives. + const importWrite = createDeferred() let fileHolds: string[] | undefined const config = makeWorkspaceConfiguration() vi.mocked(config.update).mockImplementation(async (key, value) => { - await mirrorWrite.promise + await importWrite.promise if (key === "allowedCommands") { fileHolds = value as string[] } }) vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - const imported = importSettingsWithFeedback( - { - providerSettingsManager: mockProviderSettingsManager, - contextProxy: mockContextProxy, - customModesManager: mockCustomModesManager, - provider: feedbackProvider(), - }, - filePath, - ) - - await vi.waitFor(() => - expect(config.update).toHaveBeenCalledWith( - "allowedCommands", - ["git", "imported"], - vscode.ConfigurationTarget.Global, - ), - ) + const imported = runFeedback(filePath) + await vi.waitFor(() => expect(config.update).toHaveBeenCalled()) - // A save that reads the settings file here sees the pre-import one, which is - // why the save path waits for the span to settle first. + // The save takes the same lock, so it cannot read the configuration until the + // import's pair has landed both halves. let saveObserved: string[] | undefined | "not-yet" = "not-yet" - const save = awaitCommandListImportSettled().then(() => { + const save = withCommandListLock(async () => { saveObserved = fileHolds }) - await Promise.resolve() + await flushMacrotasks() expect(saveObserved).toBe("not-yet") - mirrorWrite.resolve() + importWrite.resolve() await imported await save expect(saveObserved).toEqual(["git", "imported"]) }) - it("releases the import span before a state post that fails after a successful import", async () => { - const filePath = "/mock/path/settings.json" - ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git"] })) - ;(fs.access as Mock).mockResolvedValue(undefined) + it("completes a save dispatched while the file dialog is open, before the dialog is answered", async () => { stubValidProviderProfiles() - mockContextProxy.setValues.mockResolvedValue(undefined) - mockContextProxy.setValue.mockResolvedValue(undefined) - mockContextProxy.setProviderSettings.mockResolvedValue(undefined) - - const mirrorWrite = createDeferred() - const config = makeWorkspaceConfiguration() - vi.mocked(config.update).mockImplementation(() => mirrorWrite.promise) - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - - // The post stays pending until it is rejected below, so the save waiter - // below settles on the release alone. A span that covered the post would - // leave that waiter pending while the post hangs. - let rejectPost!: (error: Error) => void - const postGate = new Promise((_, reject) => { - rejectPost = reject - }) - const provider = feedbackProvider() - provider.postStateToWebview.mockReturnValue(postGate) + // The dialog never resolves until the test answers it, so a lock held across + // it would stall the save for an unbounded time. + const dialog = createDeferred() + ;(vscode.window.showOpenDialog as Mock).mockReturnValue(dialog.promise) - const imported = importSettingsWithFeedback( - { - providerSettingsManager: mockProviderSettingsManager, - contextProxy: mockContextProxy, - customModesManager: mockCustomModesManager, - provider, - }, - filePath, - ) - - // The mirror holds the span open, so the post cannot have started yet. - await vi.waitFor(() => expect(config.update).toHaveBeenCalled()) - expect(provider.postStateToWebview).not.toHaveBeenCalled() - - let saveSettled = false - const save = awaitCommandListImportSettled().then(() => { - saveSettled = true + const imported = importSettingsWithFeedback({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider: feedbackProvider(), }) - mirrorWrite.resolve() - await vi.waitFor(() => expect(provider.postStateToWebview).toHaveBeenCalled()) await flushMacrotasks() - // The post is still pending and the waiter has already settled, so the - // span was released before the post rather than by its failure. - expect(saveSettled).toBe(true) - - rejectPost(new Error("state post failed")) - await expect(imported).rejects.toThrow("state post failed") - await save + // The save runs to completion while the dialog is still unanswered. + let saveCompleted = false + await withCommandListLock(async () => { + saveCompleted = true + }) + expect(saveCompleted).toBe(true) - // A save that arrives after the failed import must not wait for a span - // whose owner is gone. - await expect(awaitCommandListImportSettled()).resolves.toBeUndefined() + // Answering the dialog now lets the import take the lock and proceed. + dialog.resolve(undefined) + await imported }) - it("settles the import span when the file dialog throws", async () => { + it("releases the lock when the file dialog throws", async () => { stubValidProviderProfiles() - // The rejection reaches the import body with no file to read, so the - // span is open when it happens and its release is the only way a save - // can stop waiting. ;(vscode.window.showOpenDialog as Mock).mockRejectedValueOnce(new Error("dialog unavailable")) await expect( @@ -1168,204 +1099,31 @@ describe("importExport", () => { }), ).rejects.toThrow("dialog unavailable") - await expect(awaitCommandListImportSettled()).resolves.toBeUndefined() - }) - - it("keeps the span open until every overlapping import releases it", async () => { - const firstRelease = beginCommandListImport() - const secondRelease = beginCommandListImport() - - let settled = false - const save = awaitCommandListImportSettled().then(() => { - settled = true + // A released lock lets the next writer through immediately. + let nextRan = false + await withCommandListLock(async () => { + nextRan = true }) - - // The first import leaving its window does not mean the settings file is - // whole: the second import is still between its state write and its mirror, - // so a save released here would read the file mid-import. - firstRelease() - await flushMacrotasks() - expect(settled).toBe(false) - - secondRelease() - await save - expect(settled).toBe(true) - - // Both handles are safe to call again, and the span they shared settles once. - firstRelease() - secondRelease() - await expect(awaitCommandListImportSettled()).resolves.toBeUndefined() + expect(nextRan).toBe(true) }) - it("holds an import's configuration writes until a save in flight has landed", async () => { - const config = makeWorkspaceConfiguration() - const update = vi.mocked(config.update) - update.mockResolvedValue(undefined) - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - - // The save holds its span, so the import has to wait for it. The mirror is - // the import's configuration write, and the settings file it fills is the - // store a save reads. - const releaseSave = beginCommandListSave() - let importDone = false - const imported = mirrorImportedCommandLists({ allowedCommands: ["imported"], deniedCommands: [] }).then( - () => { - importDone = true - }, - ) - - await flushMacrotasks() - // The save still owns the window, so no imported entry may reach the file yet. - expect(update).not.toHaveBeenCalled() - expect(importDone).toBe(false) - - releaseSave() - await imported - - expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) - }) - - it("opens a save's span only after the import it would overtake has settled", async () => { - // The import holds its span from before its configuration read until after - // its mirror, and the mirror waits for a save span. A save that took its - // span before waiting for the import would therefore wait, while holding, - // for an import that waits back: neither side could finish. The save here - // waits on a deferred read instead, so the import is inside its span and - // parked when the save starts. - const filePath = "/mock/path/settings.json" - const readFile = createDeferred() - ;(fs.readFile as Mock).mockReturnValue(readFile.promise) - ;(fs.access as Mock).mockResolvedValue(undefined) - stubValidProviderProfiles() - - const config = makeWorkspaceConfiguration() - const update = vi.mocked(config.update) - update.mockResolvedValue(undefined) - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + it("holds a second import back until the first released the lock", async () => { + const first = createDeferred() + let secondRan = false - const imported = importSettingsWithFeedback( - { - providerSettingsManager: mockProviderSettingsManager, - contextProxy: mockContextProxy, - customModesManager: mockCustomModesManager, - provider: feedbackProvider(), - }, - filePath, - ) - - // The import has opened its span and is parked inside its body. - await flushMacrotasks() - - // The save side opens its span through the ordered helper. The helper - // waits for the import span, so the save must not have opened its span. - let saveOpened = false - const save = beginOrderedCommandListSave().then((release) => { - saveOpened = true - return release + const firstImport = withCommandListLock(async () => { + await first.promise }) - - await flushMacrotasks() - expect(saveOpened).toBe(false) - - // The import now reaches its mirror, which waits for a save span. The save - // span is not open, so the import must not park here. Both finish. - readFile.resolve(validProfileFile({ allowedCommands: ["imported"], deniedCommands: [] })) - const [, releaseSave] = await Promise.all([imported, save]) - - expect(saveOpened).toBe(true) - expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) - - releaseSave() - // The import's release settled its span, so a later save opens at once. The - // handle is released again, because an open span would stall every import - // that runs after this case. - const laterRelease = await beginOrderedCommandListSave() - expect(typeof laterRelease).toBe("function") - laterRelease() - }) - - it("holds an import's state write back when a save span opens while the import acquires", async () => { - const filePath = "/mock/path/settings.json" - ;(fs.readFile as Mock).mockResolvedValue( - validProfileFile({ allowedCommands: ["imported"], deniedCommands: [] }), - ) - ;(fs.access as Mock).mockResolvedValue(undefined) - stubValidProviderProfiles() - mockContextProxy.setValues.mockResolvedValue(undefined) - mockContextProxy.setValue.mockResolvedValue(undefined) - mockContextProxy.setProviderSettings.mockResolvedValue(undefined) - - const update = mockCommandListConfig() - update.mockResolvedValue(undefined) - - let saveReleased = false - let saveReleasedAtStateWrite: boolean | undefined - vi.mocked(mockContextProxy.setValues).mockImplementation(async () => { - saveReleasedAtStateWrite = saveReleased + const secondImport = withCommandListLock(async () => { + secondRan = true }) - // Both sides suspend only on their own acquisition wait, so the save's - // continuation opens its span before the import's continuation runs. - const save = beginOrderedCommandListSave() - const imported = runFeedback(filePath) - - const releaseSave = await save - // The import reaches its state write here only if it opened its span without - // observing the save span the line above put in place. await flushMacrotasks() + expect(secondRan).toBe(false) - saveReleased = true - releaseSave() - await imported - - // A save reads the state copy back into the settings file, so an import that - // writes it inside a save's span leaves the two stores describing different - // lists. The write must land after the save released instead. - expect(saveReleasedAtStateWrite).toBe(true) - expect(mockContextProxy.setValues).toHaveBeenCalledTimes(1) - expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) - }) - - it("holds a save's span back while an import span that opened first is still writing", async () => { - const filePath = "/mock/path/settings.json" - ;(fs.readFile as Mock).mockResolvedValue( - validProfileFile({ allowedCommands: ["imported"], deniedCommands: [] }), - ) - ;(fs.access as Mock).mockResolvedValue(undefined) - stubValidProviderProfiles() - mockContextProxy.setValues.mockResolvedValue(undefined) - mockContextProxy.setValue.mockResolvedValue(undefined) - mockContextProxy.setProviderSettings.mockResolvedValue(undefined) - - // The mirror write is the import's last write inside its span, so a save span - // that opens before it is a save span that opened inside the import. - let importMirrored = false - const config = makeWorkspaceConfiguration() - const update = vi.mocked(config.update) - update.mockImplementation(async () => { - importMirrored = true - }) - vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) - - // The import's continuation runs first and opens the import span, so the - // save's continuation has a span to observe when it runs. - const imported = runFeedback(filePath) - - let saveOpenedBeforeImportRelease: boolean | undefined - const save = beginOrderedCommandListSave().then((release) => { - saveOpenedBeforeImportRelease = !importMirrored - return release - }) - - const releaseSave = await save - releaseSave() - await imported - - // A save that opens inside an import's span reads the settings file before - // the import mirrored into it, so the save must wait the span out instead. - expect(typeof releaseSave).toBe("function") - expect(saveOpenedBeforeImportRelease).toBe(false) - expect(update).toHaveBeenCalledWith("allowedCommands", ["imported"], vscode.ConfigurationTarget.Global) + first.resolve() + await Promise.all([firstImport, secondImport]) + expect(secondRan).toBe(true) }) it("should handle import when reasoning budget fields are missing from config", async () => { diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index baea7abe3a..d537810593 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -21,9 +21,13 @@ import { ContextProxy } from "./ContextProxy" import { CustomModesManager } from "./CustomModesManager" import { downgradeLegacyRooConfig, ROUTER_REMOVAL_IMPORT_WARNING } from "./routerRemoval" import { resolveDefaultSaveUri, saveLastExportPath } from "../../utils/export" -import { Package } from "../../shared/package" import { t } from "../../i18n" -import { sanitizeCommandList, type CommandListConfigKey } from "../auto-approval/commandScope" +import { + commandListConfiguration, + rollbackFailedCommandListWrite, + sanitizeCommandList, + type CommandListConfigKey, +} from "../auto-approval/commandScope" export type ImportOptions = { providerSettingsManager: ProviderSettingsManager @@ -137,16 +141,25 @@ function sanitizeGlobalSettings(rawGlobalSettings: unknown): { } /** - * Imports configuration from a specific file path + * Imports configuration from a specific file path. * Shares base functionality for import settings for both the manual * and automatic settings importing. * + * Holds the command-list lock for the whole import. Every caller resolves its + * file path first — the settings dialog runs in `importSettings`, the auto-import + * path checks its configured file — so the lock is never held across a dialog. + * * Uses lenient parsing to handle invalid/removed providers gracefully: * - Invalid apiProvider values are removed (profile is kept but needs reconfiguration) * - Completely invalid profiles are skipped * - Warnings are returned for any issues encountered */ -export async function importSettingsFromPath( +export function importSettingsFromPath(filePath: string, options: ImportOptions) { + return withCommandListLock(() => applySettingsImport(filePath, options)) +} + +/** The import body. It runs inside {@link withCommandListLock}. */ +async function applySettingsImport( filePath: string, { providerSettingsManager, contextProxy, customModesManager }: ImportOptions, ) { @@ -161,9 +174,10 @@ export async function importSettingsFromPath( }) // A failed import leaves both stores as they were. The settings file is only - // written after a successful import, so it needs no restore; extension state - // is written below, and this holds the copy the failure path puts back. - let priorCommandLists: Pick | undefined + // written after a successful import, so it needs no restore; the two command-list + // stores are written below, and these hold the copies the failure path puts back. + let priorStateCopy: Pick | undefined + let importedCommandLists: ImportedCommandListWrite[] = [] try { const previousProviderProfiles = await providerSettingsManager.export() @@ -248,13 +262,20 @@ export async function importSettingsFromPath( await providerSettingsManager.import(providerProfiles) // Read through the same proxy the write below uses, because extension state - // is the store this function writes. Captured before the write so a partial - // `setValues` is restored too, not only a failure that follows it. - priorCommandLists = { + // is the store this function writes. Captured before either write so a + // partial `setValues` is restored too, not only a failure that follows it. + priorStateCopy = { allowedCommands: contextProxy.getValue("allowedCommands"), deniedCommands: contextProxy.getValue("deniedCommands"), } + // The configuration half comes first, matching the save's order. With one + // order, the two writers cannot interleave into stores that disagree, and a + // failure below can undo this half against a fresh read. The helper appends + // to this array as each key lands, so the catch below sees a partial write. + importedCommandLists = [] + await writeImportedCommandLists(sanitizedGlobalSettings, importedCommandLists) + await contextProxy.setValues(sanitizedGlobalSettings) // Set the current provider. @@ -287,14 +308,14 @@ export async function importSettingsFromPath( error = e.message } - if (priorCommandLists) { + if (priorStateCopy) { const unrestoredKeys: string[] = [] for (const key of ["allowedCommands", "deniedCommands"] as const) { // A restore that rejects is reported in the error text rather than // thrown, so the caller always learns the import failed. try { - await contextProxy.setValue(key, priorCommandLists[key]) + await contextProxy.setValue(key, priorStateCopy[key]) } catch { unrestoredKeys.push(key) } @@ -305,6 +326,12 @@ export async function importSettingsFromPath( } } + // The configuration half is undone by delta, so an entry another writer added + // while the import ran survives. Only the keys this import wrote are named. + if (importedCommandLists.length > 0) { + error = `${error}${await rollBackImportedCommandLists(importedCommandLists, error)}` + } + return { success: false, error } } } @@ -398,338 +425,149 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }: } } -/** The open span. `openers` counts the imports still inside the window, so it settles at zero. */ -type CommandListSpan = { - promise: Promise - settle: () => void - openers: number -} - /** - * The command-list span of the imports that have not settled yet. + * Serialises the command-list writes of a save and an import. * - * An import writes the lists to extension state and then mirrors them into the - * user settings file. A save that runs between those two points reads the - * imported state against the old file, so the save path awaits `promise` before - * it takes its snapshot. `openers` counts the imports still inside that window: - * the span covers all of them and settles when the last one releases. + * A save writes the configuration global layer and then the extension state + * copy; an import writes the same two in the same order. With one order, the + * only interleaving that could still diverge the stores is one writer landing + * its second half after the other writer landed both, so mutual exclusion over + * the whole pair closes it. * - * The two spans are mutually exclusive, because each side opens its span only when - * the other side's span is absent, and it repeats that check with no suspension - * before the open (`beginOrderedCommandListSave`, `beginOrderedCommandListImport`). - * A save holds its span from its first configuration read to its state write, so an - * import that starts inside that window writes neither half until the save has - * landed both. Without the second span, a save that had already passed the wait - * could write its pre-import list over an import that finished in between, and the - * two stores would end up agreeing with neither order. - */ -let inFlightCommandListImport: CommandListSpan | undefined - -/** Opens a span with one owner and makes it the span a save awaits. */ -function openCommandListSpan(): CommandListSpan { - let settle!: () => void - const promise = new Promise((resolve) => { - settle = resolve - }) - const span: CommandListSpan = { promise, settle, openers: 1 } - inFlightCommandListImport = span - return span -} - -/** Builds the release handle one opener holds, so no release can count for another. */ -function releaseOnce(span: CommandListSpan): () => void { - let released = false - - return () => { - if (released) { - return - } - - released = true - span.openers -= 1 - - if (span.openers > 0) { - return - } - - // Cleared before settling, so a save that starts after the last release sees - // no span in flight rather than waiting for one that already ended. - inFlightCommandListImport = undefined - span.settle() - } -} - -/** - * Opens the command-list span of an import. + * The lock is not re-entrant. A writer that already holds it must not call this + * function again, and an import acquires it inside `importSettingsFromPath`, + * which every caller reaches only after its file path is resolved. That is what + * keeps the lock off the file dialog: the dialog runs before this function is + * entered, so a save never waits on a human's choice. * - * @returns A release function that settles the span once every opener has called - * it. Calling it more than once is safe. An import that opens while another is - * in flight joins the same span and counts as an owner, so the span settles when - * the last owner releases and a save never waits on a span whose release was - * discarded. + * @param write - The pair to run. It may throw; the lock is released either way. + * @returns Whatever `write` returned. */ -export function beginCommandListImport(): () => void { - const joined = inFlightCommandListImport +export async function withCommandListLock(write: () => Promise): Promise { + const previous = commandListLockTail + let release!: () => void + // The tail the next caller waits on. It resolves when this caller's write + // settles, so waiting callers queue instead of all entering at once. + commandListLockTail = new Promise((resolve) => { + release = resolve + }) - if (joined === undefined) { - return releaseOnce(openCommandListSpan()) + await previous + try { + return await write() + } finally { + release() } - - joined.openers += 1 - return releaseOnce(joined) } -/** - * Opens the command-list span of an import after the save it would otherwise - * overtake has settled. - * - * An import writes the state copy and then the configuration, and a save writes - * them in the opposite order, so an import must not write while a save sits - * between its configuration write and its state write. The absence of a save span - * is re-checked with no suspension before the open, so an import that starts - * during a save's span cannot open its own span between the check and the open. - * An enclosing import that already holds the span joins it as a second owner. - * - * @returns The release handle for the span this import opened or joined. - */ -export async function beginOrderedCommandListImport(): Promise<() => void> { - // The check below is repeated with no suspension before the open, because a - // save can open its span during the wait. - for (;;) { - await awaitCommandListSaveSettled() - - if (inFlightCommandListSave === undefined) { - return beginCommandListImport() - } - } -} +/** The last queued caller's completion, or a settled promise when the lock is free. */ +let commandListLockTail: Promise = Promise.resolve() /** - * Waits for an import's command-list span to settle. - * - * Resolves immediately when no import is in flight. The wait is bounded by the - * import itself: the mirror retries once and then reports, and every caller - * releases in a `finally`, so a throwing import cannot leave a save waiting. + * The keys an import wrote to the configuration, with the layer each held + * before the write, so a failed state half can undo them. */ -export async function awaitCommandListImportSettled(): Promise { - await inFlightCommandListImport?.promise +interface ImportedCommandListWrite { + key: CommandListConfigKey + imported: string[] + priorLayer: string[] | undefined } /** - * The command-list span of the saves that have not settled yet. + * Writes the command lists an import carried into the user settings file. * - * A save writes the configuration and then the extension-state copy, and an - * import writes the state copy and then the configuration. Either order leaves - * the stores inconsistent if the two interleave, so a save holds this span from - * its first configuration read to its state write, and an import awaits it - * before writing either half. `openers` counts the saves inside that window, so - * overlapping saves settle together rather than at the first release. - */ -let inFlightCommandListSave: CommandListSpan | undefined - -/** Opens a save span with one owner and makes it the span an import awaits. */ -function openCommandListSaveSpan(): CommandListSpan { - let settle!: () => void - const promise = new Promise((resolve) => { - settle = resolve - }) - const span: CommandListSpan = { promise, settle, openers: 1 } - inFlightCommandListSave = span - return span -} - -/** - * Opens the command-list span of a save. + * The configuration global layer is the only persisted home for these lists, + * and its absence is what a later save reads as the user having deleted the key. + * An import that skipped this write would leave its entries in the state copy + * alone, and the next save would drop them as removals. So this is the import + * pair's first half, not an optional mirror. * - * @returns A release function that settles the span once every owner has called - * it. Calling it more than once is safe. A save that opens while another is in - * flight joins the same span and counts as an owner, so the span settles when - * the last one releases. - */ -export function beginCommandListSave(): () => void { - const joined = inFlightCommandListSave - - if (joined === undefined) { - return releaseSaveOnce(openCommandListSaveSpan()) - } - - joined.openers += 1 - return releaseSaveOnce(joined) -} - -/** - * Opens the command-list span of a save after the import it would otherwise - * overtake has settled. + * A key the import file did not carry is skipped, so the state copy never + * becomes the source. * - * A save writes the configuration and then the state copy, so it must not write - * while an import sits between its state write and its mirror. It must also not - * hold its own span while it waits: the import's mirror waits for this span from - * inside the import span, so a save that held its span across the wait could be - * waited on by the very import it is waiting for. The absence of an import span is - * re-checked with no suspension before the open, so a save never opens its span - * while an import span is open. + * The caller owns `written`, because a rejection between two keys must reach its + * rollback: each append follows the write it records, so the caller holds exactly + * the keys that landed rather than nothing at all. * - * @returns The release handle for the span this save opened or joined. + * @param globalSettings - The sanitized settings the import file carried. + * @param written - The caller's accumulator. A key is appended after its write resolves. */ -export async function beginOrderedCommandListSave(): Promise<() => void> { - // The check below is repeated with no suspension before the open, because an - // import can open its span during the wait. - for (;;) { - await awaitCommandListImportSettled() - - if (inFlightCommandListImport === undefined) { - return beginCommandListSave() - } - } -} - -/** The save counterpart of `releaseOnce`, over the save span. */ -function releaseSaveOnce(span: CommandListSpan): () => void { - let released = false - - return () => { - if (released) { - return +async function writeImportedCommandLists( + globalSettings: GlobalSettings | undefined, + written: ImportedCommandListWrite[], +): Promise { + const config = commandListConfiguration() + + for (const key of ["allowedCommands", "deniedCommands"] as const) { + const imported = globalSettings?.[key] + if (!Array.isArray(imported)) { + continue } - released = true - span.openers -= 1 - - if (span.openers > 0) { - return + let priorLayer: string[] | undefined + try { + priorLayer = config.inspect(key)?.globalValue + } catch { + // No snapshot is no evidence about the prior layer, so it is passed on as + // unknown. A known baseline lets the rollback put back the entries this + // import replaced. An unknown one leaves it only the fresh read, and a + // fresh read equal to this import's own write is then restored to + // absence: the key is cleared, because an empty layer left behind would + // read as the user's explicit empty override. + priorLayer = undefined } - // Cleared before settling, so an import that starts after the last release - // sees no save in flight rather than waiting for one that already ended. - inFlightCommandListSave = undefined - span.settle() + await config.update(key, sanitizeCommandList(imported), vscode.ConfigurationTarget.Global) + // Appended after the write resolves, so the rollback's baseline and its + // `globalWriteApplied: true` describe a write that landed. + written.push({ key, imported: sanitizeCommandList(imported), priorLayer }) } } /** - * Waits for a save's command-list span to settle. - * - * Resolves immediately when no save is in flight. The wait is bounded by the - * save itself: it releases in a `finally` that covers both of its writes, so a - * throwing save cannot leave an import waiting. - */ -export async function awaitCommandListSaveSettled(): Promise { - await inFlightCommandListSave?.promise -} - -/** - * The command-list entries an import carried that its settings-file mirror could - * not write, per key. - * - * An import writes the lists to extension state and then mirrors them into the - * user settings file. A save reads the configuration, so an entry the mirror - * never wrote has no layer there and the save drops it as a removal. These - * entries stay a known global origin until a mirror for their key succeeds, or - * until they reach the configuration's global layer because the user set them - * there. The store lives for the process: a reload before the next save loses - * it, and that save falls back to reporting the entry as an addition. - */ -const pendingCommandListMirrorEntries = new Map>() - -/** - * The entries an import could not mirror into the user settings file yet. + * Undoes the configuration half of an import whose state half failed. * - * @returns One list per key. A key with nothing pending gives `[]`, so a caller - * never branches on `undefined`. - */ -export function pendingCommandListMirrors(): Record { - return { - allowedCommands: sanitizeCommandList([...(pendingCommandListMirrorEntries.get("allowedCommands") ?? [])]), - deniedCommands: sanitizeCommandList([...(pendingCommandListMirrorEntries.get("deniedCommands") ?? [])]), - } -} - -/** - * Writes one imported command list into the user settings file, retrying a - * failed write once. + * The undo is the save path's own delta rollback, so an entry another writer + * added while the import ran survives. The state copy is restored separately by + * the caller, from the values it captured before the write. * - * @returns `true` when a write succeeded, `false` when both attempts failed. + * @param written - The keys the import's first half wrote. + * @param failure - The failure text of the state write that threw. + * @returns A sentence to append to the error when an undo could not land. */ -async function mirrorCommandList(key: "allowedCommands" | "deniedCommands", imported: string[]): Promise { - // Two attempts: a transient failure retries, a persistent one is reported by - // the caller. - for (let attempt = 0; attempt < 2; attempt++) { - try { - await vscode.workspace - .getConfiguration(Package.name) - .update(key, imported, vscode.ConfigurationTarget.Global) - return true - } catch (error) { - console.warn(`Settings import: could not mirror ${key} into the global configuration:`, error) +async function rollBackImportedCommandLists(written: ImportedCommandListWrite[], failure: string): Promise { + const config = commandListConfiguration() + const unrestored: string[] = [] + + for (const { key, imported, priorLayer } of written) { + const outcome = await rollbackFailedCommandListWrite({ + key, + failure, + globalWrite: imported, + configGlobalAtSaveStart: priorLayer ?? [], + globalLayerAtSaveStart: priorLayer, + globalWriteApplied: true, + readGlobalLayer: () => config.inspect(key)?.globalValue, + writeGlobalLayer: (value) => config.update(key, value, vscode.ConfigurationTarget.Global), + }) + if (outcome.status === "re-read-failed" || outcome.status === "restore-failed") { + unrestored.push(key) } } - return false + return unrestored.length > 0 + ? `\nThe prior ${unrestored.join(", ")} value(s) could not be restored in VS Code user settings.` + : "" } /** - * Writes the command lists an import carried into the user settings file. - * - * An import stores the lists only in extension state. A later save reads the - * user settings file and treats an entry that no configuration layer holds as - * removed there. That save then drops the entry. This write gives the imported - * entries a layer, so the save keeps them. + * Import settings with complete UI feedback and provider state updates * - * A key the import did not carry is skipped, so the state copy never becomes - * the source. A failed write is retried once and then reported to the user - * with the manual route; the import itself still succeeds. The entries a failed - * write leaves behind stay a known global origin for the next save, which is - * why that save keeps them instead of reading them as removals. + * The file path is resolved before `importSettingsFromPath`, which takes the + * command-list lock. A save dispatched while the dialog is open therefore + * completes instead of waiting for the user's answer. The notifications below + * stay outside the lock as well: their promises settle only on dismissal. * - * @param globalSettings - The global settings an import produced, or `undefined`. - */ -export async function mirrorImportedCommandLists(globalSettings: GlobalSettings | undefined): Promise { - // A save writes the configuration and then the state copy, and this write is - // the import's half of the same pair. Waiting for a save in flight keeps the - // imported list from landing on top of a save that read the pre-import state. - - // The span covers the writes below, so a save cannot read the imported state - // against a settings file this function has not finished writing. An enclosing - // import that already opened a span joins it as a second owner, so neither - // release can settle the span while the other is still writing. - const releaseCommandListImport = await beginOrderedCommandListImport() - - try { - const failedKeys: CommandListConfigKey[] = [] - - for (const key of ["allowedCommands", "deniedCommands"] as const) { - const imported = globalSettings?.[key] - if (!Array.isArray(imported)) { - continue - } - - if (await mirrorCommandList(key, imported)) { - // The configuration's global layer now holds these entries, so a save - // reads them from a layer and the mark would only duplicate it. - pendingCommandListMirrorEntries.delete(key) - } else { - failedKeys.push(key) - // The replacement is whole, because the mark describes the list this - // import carried, not an accumulation across imports. - pendingCommandListMirrorEntries.set(key, new Set(sanitizeCommandList(imported))) - } - } - - if (failedKeys.length > 0) { - // Fire-and-forget: this promise settles only when the user dismisses the - // warning, and the caller's state post must not wait for a human answer. - void vscode.window.showWarningMessage( - `Settings import: the command list(s) ${failedKeys.join(", ")} could not be written to VS Code user settings. ` + - `Set them in user settings, or import the file again. Until they are stored there, a later save can remove the imported entries.`, - ) - } - } finally { - releaseCommandListImport() - } -} - -/** - * Import settings with complete UI feedback and provider state updates * @param options - Import options with provider instance * @param filePath - Optional file path to import from. If not provided, a file dialog will be shown. * @returns Promise that resolves when import is complete @@ -738,41 +576,23 @@ export const importSettingsWithFeedback = async ( { providerSettingsManager, contextProxy, customModesManager, provider }: ImportWithProviderOptions, filePath?: string, ) => { + const options = { providerSettingsManager, contextProxy, customModesManager } let result - // The span starts before the import, because the command-list state write - // happens inside it, and the mirror joins the same span. The notifications - // below stay outside it: their promises settle only on dismissal. A save in - // flight settles first, so neither half of this import lands between a save's - // configuration write and its state write. - const releaseCommandListImport = await beginOrderedCommandListImport() - - try { - if (filePath) { - // Validate file path and check if file exists - try { - // Check if file exists and is readable - await fs.access(filePath, fs.constants.F_OK | fs.constants.R_OK) - result = await importSettingsFromPath(filePath, { - providerSettingsManager, - contextProxy, - customModesManager, - }) - } catch (error) { - result = { - success: false, - error: `Cannot access file at path "${filePath}": ${error instanceof Error ? error.message : "Unknown error"}`, - } + if (filePath) { + // Validate file path and check if file exists + try { + // Check if file exists and is readable + await fs.access(filePath, fs.constants.F_OK | fs.constants.R_OK) + result = await importSettingsFromPath(filePath, options) + } catch (error) { + result = { + success: false, + error: `Cannot access file at path "${filePath}": ${error instanceof Error ? error.message : "Unknown error"}`, } - } else { - result = await importSettings({ providerSettingsManager, contextProxy, customModesManager }) - } - - if (result.success) { - await mirrorImportedCommandLists(result.globalSettings) } - } finally { - releaseCommandListImport() + } else { + result = await importSettings(options) } if (result.success) { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index afec108088..cee61038b9 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -68,14 +68,12 @@ vi.mock("../rulesMessageHandler", () => ({ })) // The import case needs no real import: the shared import function is a mock, -// and the save tests script the configuration state directly. The save span is a -// no-op release by default, so a case only observes it when it scripts one. +// and the save tests script the configuration state directly. The lock runs its +// callback by default, so a case only observes it when it scripts one. vi.mock("../../config/importExport", () => ({ - beginCommandListSave: vi.fn().mockReturnValue(() => {}), - beginOrderedCommandListSave: vi.fn().mockResolvedValue(() => {}), + withCommandListLock: vi.fn(async (write: () => Promise) => write()), exportSettings: vi.fn(), importSettingsWithFeedback: vi.fn(), - pendingCommandListMirrors: vi.fn().mockReturnValue({ allowedCommands: [], deniedCommands: [] }), })) vi.mock("@roo-code/telemetry", () => ({ @@ -93,12 +91,7 @@ import * as vsCodeLmProvider from "../../../api/providers/vscode-lm" import * as copilotProvider from "../../../api/providers/github-copilot" import { Package } from "../../../shared/package" -import { - beginCommandListSave, - beginOrderedCommandListSave, - importSettingsWithFeedback, - pendingCommandListMirrors, -} from "../../config/importExport" +import { importSettingsWithFeedback, withCommandListLock } from "../../config/importExport" import { readCommandListScopes } from "../../auto-approval/commandScope" import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { seedCommandList } from "../../../utils/seedAllowedCommands" @@ -2158,9 +2151,8 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { beforeEach(() => { vi.clearAllMocks() mockWorkspaceFolders.folders = [{ uri: { fsPath: "/mock/workspace" } }] - // Most cases have no import awaiting its mirror. The cases that do script - // this reader themselves. - vi.mocked(pendingCommandListMirrors).mockReturnValue({ allowedCommands: [], deniedCommands: [] }) + // The lock runs its callback by default. The cases that observe it script it. + vi.mocked(withCommandListLock).mockImplementation(async (write) => write()) }) // The file-level vscode mock opens one workspace folder, so the configuration @@ -2219,90 +2211,102 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { return { update, inspect } } - it("holds the save's first configuration read until an in-flight command-list import settles", async () => { - // The import mirrors its lists into the settings file after it writes the state - // copy. A save that read the configuration before the mirror landed would - // snapshot the pre-import file and write that list back. Opening the save span - // waits for the import span first, so the guard has to settle before the save's - // first inspect(), not merely be called. + it("takes the command-list lock only for a payload that writes a command list", async () => { + // A payload with no command-list key writes neither store the lock orders, so it + // must not take the lock and stall an import behind an unrelated save. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) - const { inspect } = mockCommandConfiguration({ globalValue: ["git"] }) + mockCommandConfiguration({ globalValue: ["git"] }) - // A deferred stand-in for the ordered open, so the test decides when the - // import span it waits on settles. - let settleImport: () => void = () => {} - vi.mocked(beginOrderedCommandListSave).mockImplementationOnce( - () => new Promise<() => void>((resolve) => (settleImport = () => resolve(() => {}))), - ) + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { mode: "code" }, + }) + expect(withCommandListLock).not.toHaveBeenCalled() - const save = webviewMessageHandler(mockClineProvider, { + await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: ["git"] }, }) - - // The span is still open, so no snapshot may have been taken yet. A save that - // skipped the wait reaches inspect() synchronously here and fails this. - await Promise.resolve() - expect(inspect).not.toHaveBeenCalled() - - settleImport() - await save - - // The snapshot the save acts on is the post-import one. - expect(inspect).toHaveBeenCalled() + expect(withCommandListLock).toHaveBeenCalledTimes(1) }) - it("holds the save span across the configuration writes and the state write", async () => { - // The import's wait on the save span is what keeps an import from landing - // between this save's two writes. A span released before the state write - // would let the import write its configuration half while this save still - // holds a pre-import list, so the release has to come after both writes. + it("holds the lock until the state write has landed", async () => { + // An import that took the lock between the configuration write and the state write + // would leave the two stores describing different lists. The lock's guarantee is + // therefore an ordering one: the callback the save hands it must not resolve until + // the state write has landed. Invocation order is fixed when a call is made, not + // when it completes, so both stores record their write only on completion and the + // assertions read those records. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration({ globalValue: ["git"] }) - update.mockResolvedValue(undefined) - const release = vi.fn() - vi.mocked(beginOrderedCommandListSave).mockResolvedValueOnce(release) + const configuration: Record = {} + update.mockImplementation(async (key: string, value: unknown) => { + configuration[key] = value + }) - await webviewMessageHandler(mockClineProvider, { - type: "updateSettings", - updatedSettings: { allowedCommands: ["git"] }, + let stateCopy: unknown + let stateWriteStarted!: () => void + const stateWriteStart = new Promise((resolve) => { + stateWriteStarted = resolve }) + let settleStateWrite!: () => void + const stateWrite = new Promise((resolve) => { + settleStateWrite = resolve + }) + vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key, value) => { + if (key !== "allowedCommands") { + return + } - expect(beginOrderedCommandListSave).toHaveBeenCalledTimes(1) - expect(release).toHaveBeenCalledTimes(1) + stateWriteStarted() + await stateWrite + stateCopy = value + }) - const setValue = vi.mocked(mockClineProvider.contextProxy.setValue) - const stateWrite = setValue.mock.calls.findIndex(([key]) => key === "allowedCommands") - expect(stateWrite).toBeGreaterThanOrEqual(0) - expect(release.mock.invocationCallOrder[0]).toBeGreaterThan(update.mock.invocationCallOrder[0]) - expect(release.mock.invocationCallOrder[0]).toBeGreaterThan(setValue.mock.invocationCallOrder[stateWrite]) + let releases = 0 + let releasedBeforeStateWriteLanded = false + vi.mocked(withCommandListLock).mockImplementationOnce(async (write) => { + try { + return await write() + } finally { + releases += 1 + releasedBeforeStateWriteLanded = stateCopy === undefined + } + }) - // A payload with no command-list key writes neither store this span orders, - // so it must not open one and stall an import behind an unrelated save. - await webviewMessageHandler(mockClineProvider, { + const save = webviewMessageHandler(mockClineProvider, { type: "updateSettings", - updatedSettings: { mode: "code" }, + updatedSettings: { allowedCommands: ["git"] }, }) - expect(beginOrderedCommandListSave).toHaveBeenCalledTimes(1) - }) + // Reach the pending state write without counting the handler's own awaits. The + // microtask flush keeps a handler that never writes the state copy from stalling + // the case on an unresolved promise. + await Promise.race([ + stateWriteStart, + (async () => { + for (let turn = 0; turn < 20; turn++) { + await Promise.resolve() + } + })(), + ]) - it("opens the save span through the ordered helper rather than the bare primitive", async () => { - // The ordered helper waits for an in-flight import before it opens the save - // span. A handler that opened the bare primitive would take the span first and - // reintroduce the wait that an import's mirror performs from inside its own - // span, which is the circular wait the ordered open removes. - vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) - mockCommandConfiguration({ globalValue: ["git"] }) + // While the state write is pending, the configuration half has already landed — + // the save's fixed order — and the lock is still held. + expect(configuration["allowedCommands"]).toEqual(["git"]) + expect(stateCopy).toBeUndefined() + expect(releases).toBe(0) - await webviewMessageHandler(mockClineProvider, { - type: "updateSettings", - updatedSettings: { allowedCommands: ["git"] }, - }) + settleStateWrite() + await save - expect(beginOrderedCommandListSave).toHaveBeenCalledTimes(1) - expect(beginCommandListSave).not.toHaveBeenCalled() + // Both stores hold the submitted list, and the lock's single release happened only + // after the state copy had landed. + expect(configuration["allowedCommands"]).toEqual(["git"]) + expect(stateCopy).toEqual(["git"]) + expect(releasedBeforeStateWriteLanded).toBe(false) + expect(releases).toBe(1) }) it("keeps workspace-scoped denied commands out of the global write when saving the merged list", async () => { @@ -2324,10 +2328,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // double-home the workspace entry. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) // One snapshot per command-list key. This key's scope read, write target, and - // rollback all derive from the same inspect(). The shadowing check reads the - // opposite key through its own guarded snapshot, and the merge before the - // workspace write re-reads this key once. The count is three, never more. - expect(inspect).toHaveBeenCalledTimes(3) + // rollback all derive from the same inspect(). The merge before the workspace + // write re-reads this key once, so the count is two and never more. + expect(inspect).toHaveBeenCalledTimes(2) }) it("writes the workspace-folder value at the folder target in multi-root workspaces", async () => { @@ -2402,7 +2405,6 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [ { globalValue: ["keep", "drop"], workspaceValue: ["npm docker", "docker"] }, undefined, - undefined, { globalValue: ["aws", "mid-save"] }, ], true, @@ -2442,12 +2444,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [ - { globalValue: ["manual"], workspaceValue: ["docker"] }, - undefined, - undefined, - { globalValue: ["aws", "mid-save"] }, - ], + [{ globalValue: ["manual"], workspaceValue: ["docker"] }, undefined, { globalValue: ["aws", "mid-save"] }], true, ) @@ -2487,7 +2484,6 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [ { globalValue: ["drop"], workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, undefined, - undefined, { globalValue: [], }, @@ -2535,9 +2531,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) // Only the failed global write happened, so the save never touches the - // workspace layer and compensates nothing. + // workspace layer and compensates nothing. The global write carries "aws" + // alone: "docker" is the workspace layer's entry, so it is written at its own + // scope and never promoted into the user's settings. expect(update).toHaveBeenCalledTimes(1) - expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith( "deniedCommands", expect.anything(), @@ -2624,7 +2622,8 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // plain kept list and each scripted call stays distinguishable, and call // position pins the undo. The global layer starts empty here, because a mock // implementation from an earlier test outlives clearAllMocks, so this save - // only adds. + // only adds. Pins the §6.5 clause (iv) divergence: the configuration holds a + // half-applied undo while the state copy holds its pre-operation list. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) const { update } = mockCommandConfiguration( {}, @@ -2633,7 +2632,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { Promise.reject(new Error("workspace locked")), Promise.reject(new Error("restore also failed")), ], - [{ workspaceValue: ["docker", "old"] }, undefined, undefined, { globalValue: ["aws"] }], + [{ workspaceValue: ["docker", "old"] }, undefined, { globalValue: ["aws"] }], true, ) @@ -2661,11 +2660,13 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // the save-start value would clobber whatever the failed read could not show. // Nothing is therefore written, and the code reports the double failure. update() // order: the global write succeeds, the workspace write rejects, and the third - // inspect() call, the undo re-read, throws. + // inspect() call, the undo re-read, throws. Pins the §6.5 clause (iv) divergence: + // the configuration keeps this save's write while the state copy keeps its + // pre-operation list. const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked"))], - [{ workspaceValue: ["docker"] }, undefined, undefined, new Error("inspect unavailable")], + [{ workspaceValue: ["docker"] }, undefined, new Error("inspect unavailable")], true, ) @@ -2700,7 +2701,6 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // then the undo's re-read. [ { globalValue: ["old"], workspaceValue: ["docker"] }, - undefined, new Error("workspace unreadable"), { globalValue: ["old", "aws"] }, ], @@ -2741,17 +2741,21 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // list the user could not see. A save therefore re-adds them to the workspace // layer it rewrites. Such entries are hidden while the gate is off, or shadowed by a // global entry with the gate on. - it("re-adds gate-hidden workspace entries to the workspace write instead of deleting them", async () => { + it("carries gate-hidden workspace entries into the workspace write instead of deleting them", async () => { const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", - // The gate is off, so the dialog displayed nothing for this key. + // The gate was off at display, so the dialog showed no workspace entry. The + // empty baseline is that display, and the two entries are carried unchanged. updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: false }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Workspace) expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + // Neither entry was displayed, so neither is a settings-file addition. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) it("keeps hidden workspace entries out of the global write", async () => { @@ -2769,7 +2773,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", []) }) - it("re-adds a workspace deny entry shadowed by a global allow entry when the gate is on", async () => { + it("carries a workspace deny entry shadowed by a global allow entry when the gate is on", async () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) @@ -2782,9 +2786,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", - // The global allow "git" shadows "git push", so the dialog displayed nothing - // deletable. + // The global allow "git" shadows "git push", so the dialog displayed an empty + // deny list. That display carries the workspace entry instead of deleting it. updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) @@ -2829,21 +2834,23 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["git push"]) }) - it("promotes a gate-hidden workspace entry the dialog re-adds to the global write", async () => { - // With the gate off the dialog shows only the global layer. A submitted entry - // the workspace layer already holds hidden is therefore one the user just added. - // It must reach the enforced global layer instead of counting as known state, - // while the re-add below still keeps it in the workspace file. + it("keeps a gate-hidden workspace entry out of the global write when the baseline omits it", async () => { + // With the gate off the dialog showed only the global layer, so the baseline + // lists no workspace entry. "docker" was never displayed, so the save carries it + // into the workspace write unchanged and never promotes it. Only "aws", which no + // layer held at save start, is new and lands in the global layer. const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, + commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: false }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) - expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) it("keeps a gate-flip-hidden workspace entry the dialog displayed at the workspace scope", async () => { @@ -2949,13 +2956,12 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // A fresh profile seeds the extension global state, not the settings file, so // the configuration has no global layer at save start while the state copy // holds "aws". The same entry also sits in the workspace layer. - // `classifyCommandListBaseline` keeps the state-only entry in - // `splitSourceEntries` when `globalLayerAtSaveStart` is `undefined`, because - // the activation seed wrote it. The split's origin set must agree, or the - // split reads "aws" - // as new, emits it in neither write, and the state copy loses it. The gate is - // off, so the workspace layer enforces nothing and the global layer is the - // only home the entry has. + // `displayedCommandListScopes` carries an entry the baseline omits, and the + // seed disjunct keeps it in the global write when the configuration layer is + // absent. The split's origin set must agree, or it reads "aws" as new, emits + // it in neither write, and the state copy loses it. The gate is off, so the + // workspace layer enforces nothing and the global layer is the only home the + // entry has. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) const { update } = mockCommandConfiguration( { workspaceValue: ["aws", "docker"], defaultValue: ["aws"] }, @@ -2978,35 +2984,12 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) }) - it("keeps an imported entry whose mirror failed in the global write of the next save", async () => { - // The import wrote "aws" to the state copy and could not write it to the - // settings file, so no configuration layer holds it. Without the pending mark - // the save reads the entry as a file deletion and drops it. The mark makes it - // known global state, so the global write keeps it. - vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) - vi.mocked(pendingCommandListMirrors).mockReturnValue({ allowedCommands: [], deniedCommands: ["aws"] }) - const { update } = mockCommandConfiguration({}, undefined, undefined, false) - - await webviewMessageHandler(mockClineProvider, { - type: "updateSettings", - updatedSettings: { deniedCommands: ["aws"] }, - commandListBaseline: { deniedCommands: ["aws"], workspaceCommandListsEnabled: false }, - }) - - expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) - expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) - // The entry is a known origin, not a settings-file addition, so no warning - // names it. - expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() - }) - it("drops the entries of a key the user deleted from user settings", async () => { // The user removed the whole key from User Settings, so the snapshot reports // no global layer and no state copy equals the shipped default. The state copy // still holds "aws" and the dialog displayed it. The save must honor the // deletion instead of writing the entry back unwarned. vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(["aws"]) - vi.mocked(pendingCommandListMirrors).mockReturnValue({ allowedCommands: [], deniedCommands: [] }) const { update, inspect } = mockCommandConfiguration({}, undefined, undefined, false) // The snapshot reports the shipped default, which the state copy does not hold. vi.mocked(inspect).mockReturnValue({ defaultValue: ["git log"] } as never) @@ -3038,7 +3021,6 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [ { globalValue: ["aws"], workspaceValue: ["npm"], workspaceFolderValue: ["docker"] }, { workspaceValue: ["npm"] }, - { workspaceValue: ["npm"] }, { globalValue: [] }, ], true, @@ -3076,13 +3058,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update, inspect } = mockCommandConfiguration( { globalValue: ["aws"], workspaceValue: ["docker"] }, [undefined, undefined], - // Save start holds only the workspace layer. The second entry answers the - // unguarded read for the opposite key. The third is the merge re-read, which - // finds the folder override another writer added and the workspace value - // still in place. + // Save start holds only the workspace layer. The second entry is the merge + // re-read, which finds the folder override another writer added and the + // workspace value still in place. [ { globalValue: ["aws"], workspaceValue: ["docker"] }, - {}, { globalValue: ["aws"], workspaceValue: ["docker"], workspaceFolderValue: ["npm"] }, ], true, @@ -3091,6 +3071,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, + // The dialog displayed both layers' entries, so neither is a deletion and the + // folder override is not mistaken for one. + commandListBaseline: { deniedCommands: ["docker", "aws"], workspaceCommandListsEnabled: true }, }) // The global half is not rolled back: no second global write undoes it. @@ -3112,10 +3095,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The save completes, so the state write happens and no error is reported. expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() - // Exactly the three scripted reads: the snapshot, the opposite key, and the - // merge re-read. A fourth would mean the re-read got no inspection object and - // the check under test was skipped. - expect(inspect).toHaveBeenCalledTimes(3) + // Exactly the two scripted reads: the snapshot and the merge re-read. A third + // would mean the re-read got no inspection object and the check under test was + // skipped. + expect(inspect).toHaveBeenCalledTimes(2) }) it("does not write a blank workspace entry back when the layer holds one at the merge re-read", async () => { @@ -3128,12 +3111,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update, inspect } = mockCommandConfiguration( { globalValue: ["aws"], workspaceValue: ["docker"] }, [undefined, undefined], - // The second entry answers the unguarded read for the opposite key. The - // third is the merge re-read, which finds the layer still holding the blank - // entry beside the entry the dialog kept. + // The second entry is the merge re-read, which finds the layer still holding + // the blank entry beside the entry the dialog kept. [ { globalValue: ["aws"], workspaceValue: ["docker"] }, - {}, { globalValue: ["aws"], workspaceValue: ["docker", ""] }, ], true, @@ -3142,6 +3123,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["docker", "aws"] }, + // The dialog displayed both entries, so the blank entry the re-read finds is + // an addition by another writer, never a displayed entry to write back. + commandListBaseline: { deniedCommands: ["docker", "aws"], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) @@ -3154,7 +3138,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { ) expect(update).toHaveBeenCalledTimes(2) expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() - expect(inspect).toHaveBeenCalledTimes(3) + expect(inspect).toHaveBeenCalledTimes(2) }) it("does not restore a workspace entry another writer removed during the global write", async () => { @@ -3247,7 +3231,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [undefined, Promise.reject(new Error("workspace locked")), undefined], // Save start, merge re-read, then the undo's re-read, which finds the // inspection object but no global value. - [{ globalValue: ["drop"], workspaceValue: ["docker"] }, undefined, undefined, {}], + [{ globalValue: ["drop"], workspaceValue: ["docker"] }, undefined, {}], true, ) @@ -3263,14 +3247,12 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) - it("does not promote a baseline entry an external edit removed from the layers", async () => { - // The dialog displayed "docker" from the workspace layer. While it was open the - // settings file lost it, so the save-start snapshot holds it in neither layer. - // The buffered dialog list still submits it, and submitting a - // displayed entry signals retention rather than newness. The save must not - // classify it as brand-new knowledge or promote it into the global layer. - // External removal wins over the stale dialog buffer. The genuinely new - // "aws" still promotes. + it("promotes a submitted entry no layer holds, even when the baseline still named it", async () => { + // The dialog displayed "docker" from the workspace layer, and while it was open + // the settings file lost it, so no layer holds it at save start. "New" means held + // by no layer at save start, not "absent from the baseline", so the stale dialog + // buffer promotes it beside "aws". Nothing was displayed-and-omitted, so no + // preservation warning fires. const { update } = mockCommandConfiguration({ workspaceValue: [] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { @@ -3279,11 +3261,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) - expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) - expect(update).not.toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) - // The save does not re-admit the removed entry as an external addition - // either: it was displayed, so no preservation warning names it. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) @@ -3341,18 +3321,17 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { commandListBaseline: { deniedCommands: ["docker"] }, }) - expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) - // The baseline names the entry, so the hidden-entry re-add treats it as - // displayed knowledge whose absence would be a deletion. The promoted global - // copy is this entry's only home after the save. - expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + // A baseline without the gate slot cannot say the workspace layer was on + // screen, so the displayed set is empty and the workspace entry is carried. + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) }) - it("promotes only the hidden entries a gate-flipped baseline did not display", async () => { - // The gate flipped off while the dialog was open. The baseline lists - // "docker" but not "npm". "docker" was displayed, so keeping it stays a - // workspace decision. "npm" was never displayed, so a submitted copy counts - // as new and lands in the global layer. + it("promotes only an entry no layer held when a gate-flipped baseline displayed the rest", async () => { + // The gate flipped off while the dialog was open. The baseline lists "docker", + // so it was displayed and keeping it stays a workspace decision. "npm" was never + // displayed, but the workspace layer holds it at save start, so it is carried + // too and is not new. Only "aws", held by no layer, promotes. const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) await webviewMessageHandler(mockClineProvider, { @@ -3361,8 +3340,13 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) - expect(update).toHaveBeenCalledWith("deniedCommands", ["npm", "aws"], vscode.ConfigurationTarget.Global) - // The re-add still preserves both hidden entries in the workspace file. + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.arrayContaining(["npm"]), + vscode.ConfigurationTarget.Global, + ) + // Both workspace entries were never deleted, so both stay in the settings file. expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "npm"], vscode.ConfigurationTarget.Workspace) }) @@ -3405,7 +3389,6 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [ { globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, - undefined, { globalValue: ["keep", "aws", "mid-save"] }, ], true, @@ -3441,7 +3424,6 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [ { globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, - undefined, { globalValue: ["aws", "mid-save"] }, ], true, @@ -3475,7 +3457,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [undefined, Promise.reject(new Error("workspace locked")), undefined], // The layer is present but holds no global value: an absent layer, not a // failed read. No inspection object at all is the failed read. - [{ globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, undefined, {}], + [{ globalValue: ["keep", "drop"], workspaceValue: ["docker"] }, undefined, {}], true, ) @@ -3550,7 +3532,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [undefined, Promise.reject(new Error("workspace locked")), undefined], // Both legs find an inspection object that reports no global value, which is // the absent-layer shape. A missing object is a failed read instead. - [{ workspaceValue: ["docker"] }, undefined, undefined, {}], + [{ workspaceValue: ["docker"] }, undefined, {}], true, ) @@ -3570,7 +3552,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update: clearedMidSave } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ globalValue: ["aws"], workspaceValue: ["docker"] }, undefined, undefined, {}], + [{ globalValue: ["aws"], workspaceValue: ["docker"] }, undefined, {}], true, ) @@ -3604,7 +3586,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["docker"] }, undefined, undefined, { globalValue: ["aws"] }], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], true, ) @@ -3629,7 +3611,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update: emptyWrite } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["docker"] }, undefined, undefined, { globalValue: [] }], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: [] }], true, ) @@ -3659,7 +3641,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ workspaceValue: ["docker"] }, undefined, undefined, { globalValue: [] }], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: [] }], true, ) @@ -3685,7 +3667,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked")), undefined], - [{ globalValue: [], workspaceValue: ["docker"] }, undefined, undefined, { globalValue: ["aws"] }], + [{ globalValue: [], workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], true, ) @@ -3704,7 +3686,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { const { update } = mockCommandConfiguration( {}, [undefined, Promise.reject(new Error("workspace locked"))], - [{ workspaceValue: ["docker"] }, undefined, undefined, new Error("inspect unavailable")], + [{ workspaceValue: ["docker"] }, undefined, new Error("inspect unavailable")], true, ) @@ -3731,7 +3713,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { Promise.reject(new Error("workspace locked")), Promise.reject(new Error("restore also failed")), ], - [{ workspaceValue: ["docker"] }, undefined, undefined, { globalValue: ["aws"] }], + [{ workspaceValue: ["docker"] }, undefined, { globalValue: ["aws"] }], true, ) @@ -3745,11 +3727,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(deniedSaveResults()).toEqual([{ type: "settingsSaveResult", requestId: "save-1", success: false }]) }) - it("promotes a shadowed workspace entry the dialog re-adds to the global write", async () => { + it("carries a shadowed workspace entry without promoting it to the global write", async () => { // The global allow "git" shadows the workspace deny "git push", so the dialog - // never displayed the deny entry. A user who re-adds it submits a list - // containing it. The entry must land in the global layer, where the gate makes - // it effective. The re-add preserves the workspace copy. + // displayed an empty deny list. "git push" was never displayed, so the save + // carries it into the workspace write and never duplicates it into the global + // layer, which would change the scope the user chose. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) @@ -3763,13 +3745,15 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["git push"] }, + commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) - expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) }) - it("re-adds a shadowed workspace allow entry alongside the user's visible deletions", async () => { + it("carries a shadowed workspace allow entry alongside the user's visible deletions", async () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["git"] : undefined, ) @@ -3785,9 +3769,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // "docker" stayed visible and kept. The global deny hid "git", and the user // cannot delete a workspace entry the user never saw. updatedSettings: { allowedCommands: ["docker"] }, + commandListBaseline: { allowedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) - expect(update).toHaveBeenCalledWith("allowedCommands", ["docker", "git"], vscode.ConfigurationTarget.Workspace) + // The carry keeps the workspace layer's own order, so "git" leads the write. + expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "docker"], vscode.ConfigurationTarget.Workspace) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) }) @@ -3843,7 +3829,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { return store } - it("preserves a workspace deny entry shadowed by a global allow the same save removes", async () => { + it("carries a workspace deny entry shadowed by a global allow the same save removes", async () => { mockCommandListStateStore({ allowedCommands: ["git"] }) const { update } = mockCommandConfiguration( (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), @@ -3857,6 +3843,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The handler processes "allowedCommands" first and drops the shadowing global // "git". The dialog hid "git push", so an empty deny list must not delete it. updatedSettings: { allowedCommands: [], deniedCommands: [] }, + commandListBaseline: { + allowedCommands: [], + deniedCommands: [], + workspaceCommandListsEnabled: true, + }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) @@ -3864,7 +3855,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) - it("preserves a workspace allow entry shadowed by a global deny the same save removes", async () => { + it("carries a workspace allow entry shadowed by a global deny the same save removes", async () => { mockCommandListStateStore({ deniedCommands: ["git"] }) const { update } = mockCommandConfiguration( (key) => (key === "allowedCommands" ? { workspaceValue: ["git push"] } : {}), @@ -3878,6 +3869,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The mirror order: the handler processes the deny key first, so this pins // that preservation does not depend on which key arrives first. updatedSettings: { deniedCommands: [], allowedCommands: [] }, + commandListBaseline: { + allowedCommands: [], + deniedCommands: [], + workspaceCommandListsEnabled: true, + }, }) expect(update).toHaveBeenCalledWith("allowedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) @@ -3889,7 +3885,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The configuration writes succeeded. Silently dropping the state write would // therefore leave the settings files and the stored list disagreeing, with // nothing shown to the user. The rejection is queued once, so it consumes exactly this - // key's write and the sibling key still persists. + // key's write and the sibling key still persists. Pins the §6.5 clause (iv) + // divergence: the configuration holds the attempted list while the state copy + // holds its pre-operation list, and the failure names the leg. vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValueOnce(new Error("state store unavailable")) const { update } = mockCommandConfiguration({}) @@ -3914,7 +3912,8 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // The same rejection seen by a sender that awaits an answer: the toast names // the failed leg, so the answer must agree with it. An ack of success would let // the dialog discard edits its stored copy never received, while a retry would - // converge. + // converge. Pins the same §6.5 clause (iv) pair as the case above, through the + // result a sender reads. vi.mocked(mockClineProvider.contextProxy.setValue).mockRejectedValueOnce(new Error("state store unavailable")) const { update } = mockCommandConfiguration({}) @@ -4140,14 +4139,17 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("docker")) }) - // A file-side extra that the hidden-entry re-add already preserves was never - // displayed. Naming it in the changed-settings warning would repeat that warning - // on every save while the file stays unchanged. + // A workspace entry the dialog never displayed is carried into its own layer. + // Whether that carry is also reported as a settings-file addition depends on the + // gate: with the gate off no workspace entry was on screen, so the classifier + // treats the whole workspace layer as hidden and stays silent; with the gate on + // the entry was merely shadowed, which the classifier reports. it.each([ { name: "hidden while the workspace gate is off", gateEnabled: false, hiddenEntry: "docker", + warns: false, prepare: () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) }, @@ -4156,40 +4158,46 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { name: "shadowed by a global allow while the gate is on", gateEnabled: true, hiddenEntry: "git push", + warns: true, prepare: () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) }, }, - ])( - "re-adds a $name deny entry without warning that the settings file changed", - async ({ gateEnabled, hiddenEntry, prepare }) => { - prepare() - const { update } = mockCommandConfiguration( - { workspaceValue: [hiddenEntry] }, - undefined, - undefined, - gateEnabled, - ) + ])("carries a $name deny entry without deleting it", async ({ gateEnabled, hiddenEntry, warns, prepare }) => { + prepare() + const { update } = mockCommandConfiguration( + { workspaceValue: [hiddenEntry] }, + undefined, + undefined, + gateEnabled, + ) - await webviewMessageHandler(mockClineProvider, { - type: "updateSettings", - updatedSettings: { deniedCommands: [] }, - // The dialog displayed the effective deny list, which never - // contained the hidden entry, so the baseline omits it. - commandListBaseline: { deniedCommands: [] }, - }) + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + // The dialog displayed the effective deny list, which never + // contained the hidden entry, so the baseline omits it. The gate + // slot is what tells the classifier this save did not display it. + commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: gateEnabled }, + }) - expect(update).toHaveBeenCalledWith("deniedCommands", [hiddenEntry], vscode.ConfigurationTarget.Workspace) + expect(update).toHaveBeenCalledWith("deniedCommands", [hiddenEntry], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + if (warns) { + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining(hiddenEntry)) + } else { expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() - }, - ) + } + }) - it("warns only about the genuine file addition when a hidden entry is also present", async () => { - // Mixed divergence in one save. The global allow "git" hides "git push", and - // the re-add preserves it. "wget" arrived in the visible part of the file - // after the dialog opened. The warning must name only the genuine addition. + it("warns only about the genuine file addition when a carried entry is also present", async () => { + // Mixed divergence in one save. The baseline omits both "git push" and "wget", + // so both are carried into the workspace write unchanged. Only "wget" is also + // absent from the submission, which is what makes it a settings-file addition + // the user must be told about; "git push" was submitted, so it is silent. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, ) @@ -4202,18 +4210,19 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", - updatedSettings: { deniedCommands: ["curl"] }, + updatedSettings: { deniedCommands: ["curl", "git push"] }, // The dialog displayed the shadow-filtered deny list. "curl" was visible and // kept, and the dialog never displayed "git push". "wget" arrived in the // settings file after the dialog opened. commandListBaseline: { deniedCommands: ["curl"] }, }) - // The hidden-entry re-add keeps "git push", the external-addition re-admit - // keeps "wget", and the global layer stays empty. + // The carry-over clause keeps both hidden entries, and the global layer stays + // empty because neither entry is new. + // The carry keeps the workspace layer's own order. expect(update).toHaveBeenCalledWith( "deniedCommands", - ["curl", "wget", "git push"], + ["git push", "curl", "wget"], vscode.ConfigurationTarget.Workspace, ) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) @@ -4344,8 +4353,8 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // holds it. The user deleted it from the user-level deny list in settings.json // while the dialog was open. No direct file edit refreshes the extension-state // copy. Treating that stale copy as proof the entry remains would restore the - // deleted entry over the file. Only the configuration layers can disprove a - // removal, so `splitSourceEntries` must not consult the state copy. + // deleted entry over the file. The rule consults `configSet` and the seed, + // never the state copy, so the stale copy cannot disprove the removal. // External removal wins over the stale buffer. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "deniedCommands" ? ["curl"] : undefined, @@ -4377,11 +4386,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { // A default install holds nothing in the user-level settings. Activation seeded // the built-in defaults into extension state. No global configuration layer // exists, so the state copy is the only evidence that the displayed entries - // have a home. A `splitSourceEntries` clause that ignores the state copy treats - // those entries as externally removed. The split drops them, and the Global write - // clears the layer to []. The emptied state then stops activation from ever - // seeding the defaults again. No configuration layer contradicts the state - // copy, so the retention stands and the save writes the defaults back. + // have a home. A rule that required a store would drop these entries and empty + // the state copy. The Global write clears the layer to []. The emptied state + // then stops activation from ever seeding the defaults again. The seed + // disjunct names every one of them, so the retention stands and the save + // writes the defaults back. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git log", "git diff", "git show"] : undefined, ) @@ -4427,19 +4436,19 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { ]) }) - it("preserves a settings-imported entry whose only home is the state copy", async () => { - // A settings import mirrors each command list into the global layer, pinned in - // importExport.spec.ts. This test pins the save side. Without that mirrored - // layer the next unrelated Save would classify the displayed entry as - // externally removed and delete it. The scripted configuration is stateful: - // update() changes what the next inspect() reports, as the real API does. + it("preserves a settings-imported entry that sits in the configuration global layer", async () => { + // The import writes the configuration first and the state copy second, pinned in + // importExport.spec.ts. This test pins the save side. Without that configuration + // layer the next unrelated Save would classify the displayed entry as externally + // removed and delete it. The scripted configuration is stateful: update() changes + // what the next inspect() reports, as the real API does. vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => // The import's state write: "imported" exists here too. key === "allowedCommands" ? ["git", "imported"] : undefined, ) - // The import's mirror write holds the full list in the global layer. An - // earlier dialog save had already created that layer. The absent-layer - // exception therefore cannot carry the case either. + // The import's first write holds the full list in the global layer. An earlier + // dialog save had already created that layer. The absent-layer exception + // therefore cannot carry the case either. const layers: { globalValue?: string[] } = { globalValue: ["git", "imported"] } const update = vi.fn() update.mockImplementation(async (_key: string, value: string[]) => { @@ -4463,8 +4472,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }, }) - // The mirrored entry survives the save in both homes instead of being dropped - // as externally removed. + // The entry survives because the configuration layer holds it (`configSet.has`), + // not because anything put it there for the save. Both homes keep it instead of + // the save dropping it as externally removed. expect(update).toHaveBeenCalledWith("allowedCommands", ["git", "imported"], vscode.ConfigurationTarget.Global) expect(update).not.toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git", "imported"]) @@ -4473,7 +4483,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }) it("delegates the import case to the shared import function without a configuration write", async () => { - // The command-list mirror lives inside importSettingsWithFeedback, pinned in + // The import's write pair lives inside importSettingsWithFeedback, pinned in // importExport.spec.ts. The message case must therefore stay a thin delegate. // It adds no configuration write of its own, even with a state copy holding // command lists. diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index fa78f8468e..5ff876fe72 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -69,13 +69,12 @@ import { type WorkspaceCommandListLayer, classifyCommandListBaseline, commandListConfiguration, + displayedCommandListScopes, readCommandListScopes, - resolveEffectiveCommandLists, resolveWorkspaceWriteTarget, rollbackFailedCommandListWrite, sanitizeCommandList, splitCommandListScopes, - workspaceCommandListsEnabled, workspaceLayerValue, } from "../auto-approval/commandScope" import { type RouterName, toRouterName } from "../../shared/api" @@ -95,12 +94,7 @@ import { searchWorkspaceFiles } from "../../services/search/file-search" import { fileExistsAtPath } from "../../utils/fs" import { playTts, setTtsEnabled, setTtsSpeed, stopTts } from "../../utils/tts" import { searchCommits } from "../../utils/git" -import { - beginOrderedCommandListSave, - exportSettings, - importSettingsWithFeedback, - pendingCommandListMirrors, -} from "../config/importExport" +import { withCommandListLock, exportSettings, importSettingsWithFeedback } from "../config/importExport" import { getOpenAiModels } from "../../api/providers/openai" import { getVsCodeLmModels } from "../../api/providers/vscode-lm" import { getGitHubCopilotViewState } from "../../services/language-models/copilotViewState" @@ -793,39 +787,29 @@ export const webviewMessageHandler = async ( let failed = false let failure: unknown let commandListSaveFailed = false - // A save and an import write the same two stores in opposite orders: the save - // the configuration then the state copy, the import the state copy then the - // configuration. A save that carries a command-list key therefore holds the - // save span for the whole payload, so an import that starts inside this - // window writes neither half until this save has landed both. The span opens - // only when no import span is in flight, and that check is repeated with no - // suspension before the open, so this save never holds its span while it waits - // and the two spans are never open at the same time. The span bounds the region - // it covers: a write that starts after this release is - // not ordered against this save, and the configuration API offers no - // compare-and-set to close that last gap. - let releaseCommandListSave: (() => void) | undefined - - try { - if (!message.updatedSettings) break - - if ("allowedCommands" in message.updatedSettings || "deniedCommands" in message.updatedSettings) { - // The wait comes before the span. An import's mirror waits for this - // span from inside its own span, so a save that held its span across - // the wait could be waited on by the import it is waiting for. - releaseCommandListSave = await beginOrderedCommandListSave() - } - - if (message.updatedSettings.destructiveCommandGuardEnabled === true) { + // A save and an import write the same two stores in the same order: the + // configuration global layer and then the extension state copy. One order + // removes the divergence an interleaving could produce, and one lock over + // the whole pair removes the rest. The lock is held only across this + // save's writes — never across the import's file dialog, which resolves + // its path before it takes the lock. A write that starts after this + // release is not ordered against this save, and the configuration API + // offers no compare-and-set to close that last gap. + const writesCommandLists = + message.updatedSettings !== undefined && + ("allowedCommands" in message.updatedSettings || "deniedCommands" in message.updatedSettings) + + const applySettings = async (updatedSettings: RooCodeSettings) => { + if (updatedSettings.destructiveCommandGuardEnabled === true) { try { const { ensureDcgInstalled } = await import("../../services/destructive-command-guard") const binaryPath = await ensureDcgInstalled(provider.context.globalStorageUri.fsPath) if (!binaryPath) { - message.updatedSettings.destructiveCommandGuardEnabled = false + updatedSettings.destructiveCommandGuardEnabled = false vscode.window.showErrorMessage(t("common:errors.destructiveCommandGuard.unavailable")) } } catch (error) { - message.updatedSettings.destructiveCommandGuardEnabled = false + updatedSettings.destructiveCommandGuardEnabled = false vscode.window.showErrorMessage( t("common:errors.destructiveCommandGuard.enableFailed", { error: error instanceof Error ? error.message : String(error), @@ -834,16 +818,9 @@ export const webviewMessageHandler = async ( } } - // One payload can carry both command-list keys, and shadowing works in both - // directions. Capture both global layers before any write, so the order of - // the payload keys cannot change which hidden entries the save preserves. - const commandListGlobalsAtSaveStart = { - allowedCommands: getGlobalState("allowedCommands"), - deniedCommands: getGlobalState("deniedCommands"), - } const externallyAddedCommandEntries: string[] = [] - for (const [key, value] of Object.entries(message.updatedSettings)) { + for (const [key, value] of Object.entries(updatedSettings)) { // An invalid display value is ignored, before anything is done for it. if (isInvalidDisplayValue(key, value)) { provider.log(`[updateSettings] Ignored an invalid value for ${key}`) @@ -909,101 +886,61 @@ export const webviewMessageHandler = async ( inspection, ).global - // Shadowing works in both directions, so the hidden-entry set needs the - // opposite key's global layer. Take it from the save-start snapshot: an - // earlier loop iteration may already have written that key. The layer feeds - // only the hidden-entry mechanism, never this key's target or rollback. - const otherKey = key === "allowedCommands" ? "deniedCommands" : "allowedCommands" - const otherScopes = readCommandListScopes(otherKey, commandListGlobalsAtSaveStart[otherKey]) - // One read decides both the hidden set and whether the workspace layer can - // carry an entry through this save. - const workspaceListsEnabled = workspaceCommandListsEnabled() - const { hiddenWorkspaceAllow, hiddenWorkspaceDeny } = resolveEffectiveCommandLists( - key === "allowedCommands" ? currentScopes : otherScopes, - key === "deniedCommands" ? currentScopes : otherScopes, - workspaceListsEnabled, - ) - // Hidden entries were never displayed. The gate is off, or a global entry - // shadows them. A list cannot delete what it never showed, so a save re-adds - // them to the workspace layer it rewrites. The dialog cannot delete a hidden - // entry. Remove them in the settings file. - const hiddenWorkspaceEntries = - key === "allowedCommands" ? hiddenWorkspaceAllow : hiddenWorkspaceDeny - const baseline = message.commandListBaseline?.[key] // An absent global layer means the activation seed wrote the state copy, or // that the user deleted the key. The copy is the seed's only when it still - // equals the shipped default, which is what separates the two cases. + // equals the shipped default and the user layer is absent, which is what + // separates the two cases. An explicitly present `[]` is the user's + // deletion, and it is honored. const shippedDefaultAtSaveStart = sanitizeCommandList(defaultAtSaveStart) const stateCopyIsShippedDefault = + globalLayerAtSaveStart === undefined && defaultAtSaveStart !== undefined && shippedDefaultAtSaveStart.length === currentScopes.global.length && shippedDefaultAtSaveStart.every((entry) => currentScopes.global.includes(entry)) - // An import that could not write its settings-file mirror leaves its - // entries in the state copy alone. No configuration layer holds them, and - // they are known global state until a mirror for this key succeeds. - const pendingGlobalEntries = pendingCommandListMirrors()[key] - // The baseline, the layers, and the gate together decide which submitted - // entries survive the save. - const { externallyAdded, splitSourceEntries, promotionHiddenEntries } = - classifyCommandListBaseline({ - baseline, - incoming, - currentScopes, - configGlobalAtSaveStart, - globalLayerAtSaveStart, - stateCopyIsShippedDefault, - pendingGlobalEntries, - hiddenWorkspaceEntries, - gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, - }) - // The split treats an entry outside its origin set as new, so the origin set - // decides what the global write may hold. Three contributors are known - // global state: the configuration's own layer, the activation seed's copy, - // and an import's entries whose mirror has not landed. The origin set must - // agree with `classifyCommandListBaseline` in both gate states. The - // workspace layer carries a seeded entry only while the gate is on, so with - // the gate on the global layer is still that entry's home; dropping it there - // is a loss the user never asked for, and a later save with the gate off - // would then have no copy left to keep. + // The configuration's own layer, plus the activation seed's copy, are the + // two contributors of known global state. The seed's copy is the one the + // gate-off display cannot reach: the workspace layer carries a seeded entry + // only while the gate is on, so with the gate on the global layer is still + // that entry's home, and dropping it there is a loss the user never asked + // for. const seededGlobalEntries = stateCopyIsShippedDefault ? currentScopes.global.filter((entry) => !configGlobalAtSaveStart.includes(entry)) : [] - const globalOriginEntries = [ - ...new Set([...configGlobalAtSaveStart, ...seededGlobalEntries, ...pendingGlobalEntries]), - ] - const { globalWrite, workspaceWrite: keptWorkspaceWrite } = splitCommandListScopes( - splitSourceEntries, - // Hidden entries are not known state. The dialog never displayed them, so a - // submitted entry the user just added is new even when the workspace - // layer holds it hidden. Entries the baseline shows displayed are the - // exception, because the re-add below restores dropped hidden entries. - currentScopes.workspace.filter((entry) => !promotionHiddenEntries.includes(entry)), - globalOriginEntries, - ) - - // Entries the dialog never displayed cannot be deleted by omission from a - // list the user could not see, so the save re-adds them to the workspace - // layer it rewrites. The baseline's gate says which entries those are. With - // the gate off the dialog showed only the global layer, so no workspace entry - // was displayed, and every one survives. That includes a workspace copy whose - // global twin the user deleted: the deletion was a decision about the - // user-level list, which the save applies to that layer alone. With the gate - // on, or when the sender reported no gate, the workspace layer was displayed, - // and only entries the save still finds hidden are re-added. A baseline entry - // among those became hidden after display, so its absence is a deletion the - // re-add honors. - const gateAtDisplay = message.commandListBaseline?.workspaceCommandListsEnabled - const workspaceWrite = [ + const globalOriginEntries = [...new Set([...configGlobalAtSaveStart, ...seededGlobalEntries])] + // What the layers held at save start, not the two write lists: a write + // omits what this save deletes, and the split would re-promote that. + const heldAtSaveStart = [ ...new Set([ - ...keptWorkspaceWrite, - ...(gateAtDisplay === false - ? currentScopes.workspace - : hiddenWorkspaceEntries.filter( - (entry) => !Array.isArray(baseline) || !baseline.includes(entry), - )), + ...currentScopes.workspace, + ...currentScopes.global, + ...configGlobalAtSaveStart, ]), ] + // Entries a layer gained after display. The global write replaces its layer, + // so this is what keeps a file edit that landed while the dialog was open. + const { externallyAdded } = classifyCommandListBaseline({ + baseline, + incoming, + currentScopes, + configGlobalAtSaveStart, + gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, + }) + const { writableGlobal, writableWorkspace } = displayedCommandListScopes({ + baseline, + incoming, + stateCopy: currentScopes.global, + configGlobal: globalOriginEntries, + workspaceNow: currentScopes.workspace, + gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, + seededEntries: seededGlobalEntries, + }) + const { globalWrite, workspaceWrite } = splitCommandListScopes( + incoming, + writableWorkspace, + writableGlobal, + heldAtSaveStart, + ) const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) // The two configuration writes are not atomic. Global comes first: an @@ -1255,13 +1192,23 @@ export const webviewMessageHandler = async ( `Your settings file changed while the settings dialog was open. ${count} ${count === 1 ? "entry was" : "entries were"} added there during this session and kept by this save: ${externallyAddedCommandEntries.join(", ")}. Reopen the settings dialog to see the current command lists.`, ) } + } + + try { + const updatedSettings = message.updatedSettings + if (!updatedSettings) break + + // The lock covers this save's whole pair, so an import cannot land between + // the configuration writes and the state write. It is taken only for a + // payload that writes a command list; any other payload runs unlocked. + if (writesCommandLists) { + await withCommandListLock(() => applySettings(updatedSettings)) + } else { + await applySettings(updatedSettings) + } } catch (error) { failed = true failure = error - } finally { - // Released after both of this save's writes, and before the state post: - // the post only reflects state the span already covers. - releaseCommandListSave?.() } // A failed refresh must neither undo a stored save nor keep the webview from getting the result. diff --git a/src/utils/autoImportSettings.ts b/src/utils/autoImportSettings.ts index 61f7afa72a..926408bc21 100644 --- a/src/utils/autoImportSettings.ts +++ b/src/utils/autoImportSettings.ts @@ -6,7 +6,7 @@ import { Package } from "../shared/package" import { fileExistsAtPath } from "./fs" import { t } from "../i18n" -import { importSettingsFromPath, mirrorImportedCommandLists, ImportOptions } from "../core/config/importExport" +import { importSettingsFromPath, ImportOptions } from "../core/config/importExport" /** * Automatically imports RooCode settings from a specified path if it exists. @@ -44,11 +44,9 @@ export async function autoImportSettings( }) if (result.success) { - // The import stores the command lists in extension state only. Without this - // write, a later save reads the user settings file, finds no layer holding an - // imported entry, and drops it as removed there. - await mirrorImportedCommandLists(result.globalSettings) - + // The import writes the command lists to the configuration and then the + // state copy, and rolls the configuration half back if the second fails, + // so a later save reads them from a layer rather than as deletions. outputChannel.appendLine(`[AutoImport] Successfully imported settings from ${resolvedPath}`) if (result.warnings && result.warnings.length > 0) { From 4eaf350fa0443023e2695481b5ff34c8b2641279 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Mon, 30 Nov 2026 20:09:45 +0100 Subject: [PATCH 44/52] fix: distinguish display state from store state on the save path A save promoted a submitted entry to the global layer when no layer held it. That test also matched an entry the dialog had displayed and another writer then removed, so the save granted a workspace entry to every workspace. Promotion now also excludes an entry the dialog displayed, so a stale dialog buffer is dropped from both writes instead of widened to global. An import reads each global command list before it writes, so a failed import can put the list back. When that read threw, the import recorded the list as absent, and the rollback then cleared a list the user had. The import now records the failed read, refuses to clear that key, and names it in the error. The save warns about an entry a layer gained while the dialog was open. A workspace entry that a global entry covers is never displayed, so its absence from the baseline was read as an addition, and the save warned on every save even when nothing changed. The warning now skips an entry that a global entry of the same key covers. The baseline the dialog sent was one flat list, so the save could not tell which layer had displayed an entry. It deleted a workspace entry that the dialog had shown only for the global layer. The baseline now carries the workspace layer's own displayed entries. A sender that omits the field still works: the save then carries every workspace entry instead of deleting one. The test named for the command-list lock drove the file dialog to reject. The dialog runs before the lock is taken, so the test never entered the lock. It now takes the lock, queues a rejecting writer behind the holder, and checks that a third writer runs once the rejection releases it. --- packages/types/src/vscode-extension-host.ts | 10 ++ .../__tests__/commandScope.spec.ts | 149 ++++++++++++++++-- src/core/auto-approval/commandScope.ts | 68 +++++++- .../config/__tests__/importExport.spec.ts | 103 +++++++++++- src/core/config/importExport.ts | 29 +++- .../__tests__/webviewMessageHandler.spec.ts | 104 ++++++++++-- src/core/webview/webviewMessageHandler.ts | 32 ++-- .../src/components/settings/SettingsView.tsx | 126 +++++++++++---- .../settings/__tests__/SettingsView.spec.tsx | 96 ++++++++++- 9 files changed, 635 insertions(+), 82 deletions(-) diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 556b25d347..11d7eb77c4 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -882,6 +882,16 @@ export interface WebviewMessage { * displayed and none is deleted by omission. */ workspaceCommandListsEnabled?: boolean + /** + * The workspace-layer entries the dialog showed, per key: the displayed list + * minus the global layer the host posted at the same moment. The flat + * `allowedCommands`/`deniedCommands` above are the merged pair, so a global + * entry appears there too and cannot say which layer showed it. Absent means + * the sender cannot say, and the save then carries every workspace entry + * rather than deleting one it has no evidence about. + */ + workspaceAllowedCommands?: string[] + workspaceDeniedCommands?: string[] } /** Task configuration applied via `createTask()`. */ taskConfiguration?: RooCodeSettings diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 16d653ed35..72370cf547 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -254,19 +254,20 @@ describe("readCommandListScopes", () => { describe("splitCommandListScopes", () => { // The caller applies the deletions, so each layer argument arrives already // filtered. The function's remaining job is routing: a layer keeps what it was - // handed, and a submitted entry neither layer holds is new and goes to global. + // handed, and a submitted entry that no layer holds and the dialog never + // displayed is new and goes to global. it("keeps workspace entries in the workspace layer and routes new entries to global", () => { // The dialog sends the merged list back. A workspace-only entry such as // "docker" must not reach the global write. - const result = splitCommandListScopes(["docker", "aws"], ["docker"], [], ["docker"]) + const result = splitCommandListScopes(["docker", "aws"], ["docker"], [], ["docker"], ["docker"]) expect(result.workspaceWrite).toEqual(["docker"]) expect(result.globalWrite).toEqual(["aws"]) }) it("keeps a global entry in the global layer", () => { - const result = splitCommandListScopes(["git"], [], ["git"], ["git"]) + const result = splitCommandListScopes(["git"], [], ["git"], ["git"], ["git"]) expect(result.workspaceWrite).toEqual([]) expect(result.globalWrite).toEqual(["git"]) @@ -275,7 +276,7 @@ describe("splitCommandListScopes", () => { it("keeps an entry present in both layers in both layers when retained", () => { // Do not delete the user's global entry because the current folder also // defines it. The user authored the entry in both scopes and kept it. - const result = splitCommandListScopes(["docker"], ["docker"], ["docker"], ["docker"]) + const result = splitCommandListScopes(["docker"], ["docker"], ["docker"], ["docker"], ["docker"]) expect(result.workspaceWrite).toEqual(["docker"]) expect(result.globalWrite).toEqual(["docker"]) @@ -284,7 +285,7 @@ describe("splitCommandListScopes", () => { it("writes each layer as the caller filtered it", () => { // A deleted entry never reaches this function: the caller removed it from the // layer argument, and the function writes what it was handed. - const result = splitCommandListScopes(["git"], [], ["git"], ["git"]) + const result = splitCommandListScopes(["git"], [], ["git"], ["git"], ["git"]) expect(result.workspaceWrite).toEqual([]) expect(result.globalWrite).toEqual(["git"]) @@ -296,6 +297,7 @@ describe("splitCommandListScopes", () => { ["docker", "pnpm docker"], ["git"], ["docker", "pnpm docker", "git"], + ["git", "docker", "pnpm docker"], ) expect(result.workspaceWrite).toEqual(["docker", "pnpm docker"]) @@ -303,7 +305,13 @@ describe("splitCommandListScopes", () => { }) it("orders the global write as existing global entries then new entries in dialog order", () => { - const result = splitCommandListScopes(["aws", "git", "npm"], ["docker"], ["git"], ["docker", "git"]) + const result = splitCommandListScopes( + ["aws", "git", "npm"], + ["docker"], + ["git"], + ["docker", "git"], + ["docker", "git"], + ) expect(result.globalWrite).toEqual(["git", "aws", "npm"]) }) @@ -311,14 +319,26 @@ describe("splitCommandListScopes", () => { it("drops blank and non-string entries from the incoming list", () => { // Deliberate wrong runtime type: configuration lists arrive as unknown, // so the sanitizer must drop non-strings instead of throwing on them. - const result = splitCommandListScopes(["git", "", " ", 42 as unknown as string], [], ["git"], ["git"]) + const result = splitCommandListScopes( + ["git", "", " ", 42 as unknown as string], + [], + ["git"], + ["git"], + ["git"], + ) expect(result.globalWrite).toEqual(["git"]) expect(result.workspaceWrite).toEqual([]) }) it("deduplicates layers so re-writing cannot introduce duplicates", () => { - const result = splitCommandListScopes(["docker", "docker"], ["docker", "docker"], ["docker"], ["docker"]) + const result = splitCommandListScopes( + ["docker", "docker"], + ["docker", "docker"], + ["docker"], + ["docker"], + ["docker"], + ) expect(result.workspaceWrite).toEqual(["docker"]) expect(result.globalWrite).toEqual(["docker"]) @@ -329,11 +349,44 @@ describe("splitCommandListScopes", () => { // it, yet the submission still does. "New" must mean held by no layer at save // start: reading it off the write lists would put the deleted entry straight // back into the global write and make the deletion unobservable. - const result = splitCommandListScopes(["aws"], [], [], ["aws"]) + const result = splitCommandListScopes(["aws"], [], [], ["aws"], ["aws"]) + + expect(result.globalWrite).toEqual([]) + expect(result.workspaceWrite).toEqual([]) + }) + + it("promotes an entry the dialog never displayed and no layer held", () => { + // The user typed "aws" after the dialog opened. No layer held it and the dialog + // never showed it, which is what makes an entry new, so it still reaches the + // global layer. Without this case a filter that promoted nothing would pass. + const result = splitCommandListScopes(["git", "aws"], [], ["git"], ["git"], ["git"]) + + expect(result.globalWrite).toEqual(["git", "aws"]) + }) + + it("drops a displayed entry no layer holds instead of promoting it", () => { + // Gate on, so the dialog displayed "docker" from the workspace layer, and + // another writer removed it before the save. The dialog holds back host + // updates after an edit, so the submission still carries "docker" while no + // layer holds it. Only the displayed set separates that stale entry from one + // the user typed, and promoting it would grant a workspace entry to every + // workspace. + const result = splitCommandListScopes(["docker"], [], [], [], ["docker"]) expect(result.globalWrite).toEqual([]) expect(result.workspaceWrite).toEqual([]) }) + + it("carries a held entry the dialog never displayed into its own layer", () => { + // Gate off at display: the dialog showed no workspace entry, so "docker" is + // absent from the displayed set although the workspace layer holds it. The + // save has no evidence about it, so it is carried in place and never reaches + // the global layer. + const result = splitCommandListScopes(["docker"], ["docker"], [], ["docker"], []) + + expect(result.workspaceWrite).toEqual(["docker"]) + expect(result.globalWrite).toEqual([]) + }) }) describe("resolveWorkspaceWriteTarget", () => { @@ -1760,6 +1813,38 @@ describe("classifyCommandListBaseline", () => { expect(result.externallyAdded).toEqual([]) }) + + it("does not report a workspace entry that a global entry covers", () => { + // Both layers are one key's, here `allowedCommands`: a user-global "git" and a + // workspace "git status". The gate is on and the global entry covers the + // workspace entry, so the composition drops the workspace entry from display. + // Its absence from the baseline is therefore display, not an addition, and the + // save stays silent. + const result = classifyCommandListBaseline({ + baseline: ["git"], + incoming: ["git"], + currentScopes: { global: ["git"], workspace: ["git status"], merged: [] }, + configGlobalAtSaveStart: [], + gateAtDisplay: true, + }) + + expect(result.externallyAdded).toEqual([]) + }) + + it("still reports a workspace entry that no global entry covers", () => { + // The positive control: the same shape as the covered case, without the + // covering global entry. The entry was added after display, so the warning + // must still name it. + const result = classifyCommandListBaseline({ + baseline: ["git"], + incoming: ["git"], + currentScopes: { global: [], workspace: ["git status"], merged: [] }, + configGlobalAtSaveStart: [], + gateAtDisplay: true, + }) + + expect(result.externallyAdded).toEqual(["git status"]) + }) }) describe("displayedCommandListScopes", () => { @@ -1774,6 +1859,9 @@ describe("displayedCommandListScopes", () => { } it("deletes a displayed entry the submission omits from every layer that held it", () => { + // Both layers showed "echo", so its omission is a deletion of both copies. The + // merged baseline cannot say that on its own, which is why the workspace share + // is passed beside it. const result = displayedCommandListScopes({ ...base, baseline: ["echo", "git"], @@ -1781,22 +1869,24 @@ describe("displayedCommandListScopes", () => { stateCopy: ["echo", "git"], configGlobal: ["echo", "git"], workspaceNow: ["echo"], + workspaceDisplayed: ["echo"], }) expect(result.displayedGlobal).toEqual(["echo", "git"]) - expect(result.displayedWorkspace).toEqual(["echo", "git"]) + expect(result.displayedWorkspace).toEqual(["echo"]) expect(result.writableGlobal).toEqual(["git"]) expect(result.writableWorkspace).toEqual([]) }) it("keeps an entry the dialog never displayed, so a file edit made while it was open survives", () => { // "aws" reached the workspace layer after the dialog rendered its list, so the - // baseline omits it and the save has no evidence that the user removed it. + // workspace share omits it and the save has no evidence that the user removed it. const result = displayedCommandListScopes({ ...base, baseline: ["git"], incoming: ["git"], workspaceNow: ["git", "aws"], + workspaceDisplayed: ["git"], }) expect(result.displayedWorkspace).toEqual(["git"]) @@ -1894,6 +1984,43 @@ describe("displayedCommandListScopes", () => { expect(result.writableGlobal).toEqual(["git"]) }) + it("carries a workspace entry the workspace layer did not show, so a displayed global entry does not delete it", () => { + // "echo" is a user-global entry the dialog showed, and it reached the workspace + // layer only after display. The merged baseline names "echo" once, so reading it + // as the workspace layer's displayed set would delete the workspace copy on a + // submission that omits it. The per-layer share proves the workspace layer never + // showed it, so the entry is carried. + const result = displayedCommandListScopes({ + ...base, + baseline: ["echo"], + incoming: [], + stateCopy: ["echo"], + configGlobal: ["echo"], + workspaceNow: ["echo"], + workspaceDisplayed: [], + }) + + expect(result.displayedWorkspace).toEqual([]) + expect(result.writableWorkspace).toEqual(["echo"]) + }) + + it("carries every workspace entry when the sender omits the per-layer field", () => { + // A sender that names the baseline but not the workspace share cannot say which + // layer showed an entry. Carrying is the safe direction: an unshown entry + // survives, and nothing is deleted on evidence the sender never supplied. + const result = displayedCommandListScopes({ + ...base, + baseline: ["echo"], + incoming: [], + stateCopy: ["echo"], + configGlobal: ["echo"], + workspaceNow: ["echo"], + }) + + expect(result.displayedWorkspace).toEqual([]) + expect(result.writableWorkspace).toEqual(["echo"]) + }) + it("does not let a seeded entry vouch for an entry the default does not name", () => { // The seed is an entry set, not a whole-list flag: a workspace-only entry that // happens to sit in a seeded save stays out of the global write, so a seeded diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 9d5e32b59f..ed725b5e47 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -284,10 +284,20 @@ export interface CommandListWriteScopes { * at save start is new, and it goes to the global layer, as dialog edits did * before. * + * Held by no layer is not on its own what makes an entry new. The submission is + * the list the dialog showed, so an entry it displayed and no layer holds any + * more was removed by another writer while the dialog was open: the submission + * is stale about it, and the user's intent was not to add it. Promotion + * therefore also requires that the dialog did not display the entry. A layer + * snapshot cannot answer that question — the stale entry and a freshly typed one + * are equally absent from it — so the display fact is passed separately. + * * @param incoming - The full merged list sent by the webview on save. * @param workspaceLayer - The workspace write's entries, already filtered. * @param globalLayer - The global write's entries, already filtered. * @param known - Every entry any layer held at save start. + * @param displayed - Every entry the dialog displayed. An entry here that no + * layer holds is stale dialog state, so it is dropped rather than promoted. * @returns The per-layer values to write back. */ export function splitCommandListScopes( @@ -295,17 +305,21 @@ export function splitCommandListScopes( workspaceLayer: string[], globalLayer: string[], known: string[], + displayed: string[], ): CommandListWriteScopes { const kept = new Set(sanitizeCommandList(incoming)) const knownEntries = new Set(sanitizeCommandList(known)) + const displayedEntries = new Set(sanitizeCommandList(displayed)) // Deduplicated so re-writing a layer cannot introduce duplicates. return { workspaceWrite: [...new Set(sanitizeCommandList(workspaceLayer))], globalWrite: [ ...new Set(sanitizeCommandList(globalLayer)), - // Preserve the dialog's ordering for entries the user added. - ...[...kept].filter((command) => !knownEntries.has(command)), + // Preserve the dialog's ordering for entries the user added. A displayed + // entry is not one of them: it was on screen, so a layer held it then, and + // its absence from every layer now is another writer's removal. + ...[...kept].filter((command) => !knownEntries.has(command) && !displayedEntries.has(command)), ], } } @@ -336,6 +350,13 @@ export interface DisplayedCommandListScopes { * entry the user really did see. Membership is deliberately not a term: it * answers "which store holds this?", never "did the dialog show it?". * + * The baseline is one merged list, so it cannot say which layer showed an entry: + * a global entry appears there too. The workspace layer's displayed set therefore + * comes from its own field, and the flat baseline only stands in for the global + * layer. Without that field the save carries every workspace entry rather than + * deleting one it has no evidence about — under-deleting costs an edit, while + * deleting an entry the workspace layer never showed destroys data. + * * A displayed entry the configuration does not hold is written back only when the * shipped default names it. Otherwise the state copy is a key the user deleted, * and writing it back is the leak this rule exists to remove. @@ -356,6 +377,9 @@ export interface DisplayedCommandListScopes { * @param input.workspaceNow - The workspace layer as it stands at save start. * @param input.gateAtDisplay - The gate as the dialog showed it. `false` means * the workspace layer was not displayed. + * @param input.workspaceDisplayed - The workspace-layer entries the dialog showed, + * when the sender says. Absent means it cannot, and the save then carries every + * workspace entry rather than deleting one it has no evidence about. * @param input.seededEntries - The entries the shipped default vouches for, from * the caller's seeded global copy. A value comparison against the default, never * a store-membership test. @@ -368,6 +392,7 @@ export function displayedCommandListScopes(input: { configGlobal: string[] workspaceNow: string[] gateAtDisplay: boolean | undefined + workspaceDisplayed?: string[] seededEntries: string[] }): DisplayedCommandListScopes { const submitted = new Set(sanitizeCommandList(input.incoming)) @@ -381,7 +406,14 @@ export function displayedCommandListScopes(input: { const baseline = hasBaseline ? sanitizeCommandList(input.baseline) : [] const heldGlobal = [...new Set([...config, ...stateCopy])] - const displayedWorkspace = hasBaseline ? (input.gateAtDisplay === false ? [] : baseline) : workspace + // With a baseline, only the workspace field can say what the workspace layer + // showed. Its absence is read as "nothing shown for this layer", which carries + // every workspace entry instead of deleting one the dialog never displayed. + const displayedWorkspace = hasBaseline + ? input.gateAtDisplay === false + ? [] + : sanitizeCommandList(input.workspaceDisplayed) + : workspace const displayedWorkspaceSet = new Set(displayedWorkspace) const displayedGlobalSet = hasBaseline ? new Set(baseline) : new Set(heldGlobal) const configSet = new Set(config) @@ -440,7 +472,10 @@ export function resolveWorkspaceWriteTarget( } export interface CommandListBaselineClassification { - /** Entries a layer held at save start that the baseline and the submission both omit. */ + /** + * Entries a layer held at save start that the baseline and the submission both + * omit, and that display did not hide. + */ externallyAdded: string[] } @@ -455,6 +490,15 @@ export interface CommandListBaselineClassification { * off the dialog showed no workspace entry at all, so every one of them is * absent from the baseline, and reporting them would warn on every save. * + * The gate being on is not enough. The composition drops a workspace entry that + * a global entry covers, so the dialog never showed it and its absence from the + * baseline is display, not addition. {@link isShadowedByAnyEntry} is the + * predicate the composition applies. This function reads one key's layers, so a + * global entry of the *other* key that covers this one is not seen here: such an + * entry stays reported, which can raise a warning for an entry the dialog hid. + * The error is one-directional - the shadow term only ever removes a report, so + * the residual can add a spurious warning and never suppress a real one. + * * @param input.baseline - The lists the dialog displayed for this key, or * `undefined` when the sender shows no lists. * @param input.incoming - The submitted list for this key. @@ -483,13 +527,27 @@ export function classifyCommandListBaseline(input: { const heldAtSaveStart = [ ...new Set([...currentScopes.workspace, ...currentScopes.global, ...configGlobalAtSaveStart]), ] + // The global layer the dialog rendered, which decides whether a workspace-only + // entry was shadowed and so never shown. + const globalEntriesAtSaveStart = [...new Set([...currentScopes.global, ...configGlobalAtSaveStart])] + const globalEntrySet = new Set(globalEntriesAtSaveStart) const externallyAdded = heldAtSaveStart.filter( (entry) => !baseline.includes(entry) && !incoming.includes(entry) && // With the gate off no workspace entry was displayed, so only a global // entry can be a genuine addition. - (gateAtDisplay !== false || configGlobalAtSaveStart.includes(entry)), + (gateAtDisplay !== false || configGlobalAtSaveStart.includes(entry)) && + // The gate can hide a workspace entry from display even when it is on: the + // composition drops any workspace entry a global entry already covers. Such + // an entry is absent from the baseline because it was never shown, not + // because it was added, so reporting it would warn on every save. Only an + // entry no global layer holds can be hidden this way: a global entry is + // always displayed, so an entry a global layer holds was shown even when a + // global entry also covers its workspace copy. + (globalEntrySet.has(entry) || + gateAtDisplay === false || + !isShadowedByAnyEntry(entry, globalEntriesAtSaveStart)), ) return { externallyAdded } diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index a41992172f..403c4f7fed 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -1019,6 +1019,50 @@ describe("importExport", () => { expect(state.deniedCommands).toEqual(["prior-deny"]) }) + it("keeps the imported list when the prior global layer could not be read", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git", "imported"] })) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + + // The layer holds a list the import never saw. The import's baseline + // read throws once; every later read sees the layer as it stands, so + // the rollback's own re-read succeeds and the unreadable baseline is + // the only failure left to handle. + const layers: Record = { allowedCommands: ["prior-allow"] } + const config = makeWorkspaceConfiguration() + vi.mocked(config.update).mockImplementation(async (key: string, value: string[] | undefined) => { + layers[key] = value + }) + let threwBaselineRead = false + vi.mocked(config.inspect).mockImplementation((key: string) => { + if (key === "allowedCommands" && !threwBaselineRead) { + threwBaselineRead = true + throw new Error("configuration unavailable") + } + return { key, globalValue: layers[key] } + }) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + // The state half rejects after the configuration half landed. + mockContextProxy.setValues.mockRejectedValue(new Error("state write failed")) + + const result = await importSettingsFromPath(filePath, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + expect(result.success).toBe(false) + // The baseline read failed, so the rollback has no delta to undo against. + // Clearing the key would read the failed read as an absent layer and + // destroy a list this import never saw; the imported list stays and the + // error names the key. + expect(layers.allowedCommands).toEqual(["git", "imported"]) + expect(result.error).toContain("allowedCommands") + expect(result.error).toContain("could not be restored") + }) + it("lets a save dispatched during an import run only after the import released the lock", async () => { const filePath = "/mock/path/settings.json" ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git", "imported"] })) @@ -1086,7 +1130,11 @@ describe("importExport", () => { await imported }) - it("releases the lock when the file dialog throws", async () => { + it("keeps the lock off the file dialog, so a rejected dialog leaves it free", async () => { + // The dialog rejects before `importSettingsFromPath` is reached, and that + // function is the only one that takes the lock. So no writer can be + // waiting on a human's answer to the dialog: the next writer must find + // the lock free even though the import failed. stubValidProviderProfiles() ;(vscode.window.showOpenDialog as Mock).mockRejectedValueOnce(new Error("dialog unavailable")) @@ -1099,7 +1147,6 @@ describe("importExport", () => { }), ).rejects.toThrow("dialog unavailable") - // A released lock lets the next writer through immediately. let nextRan = false await withCommandListLock(async () => { nextRan = true @@ -1107,6 +1154,58 @@ describe("importExport", () => { expect(nextRan).toBe(true) }) + it("releases the lock when the callback rejects, so the queued writer still runs", async () => { + // The holder parks inside the lock, so everything created below it is + // queued behind a lock that is genuinely held. + const gate = createDeferred() + let holderInside = false + const holder = withCommandListLock(async () => { + holderInside = true + await gate.promise + }) + + let rejectingRan = false + const rejecting = withCommandListLock(async () => { + rejectingRan = true + throw new Error("write failed") + }) + + // The rejection is observed from the start, so a lock that fails to queue + // reports a failed assertion here rather than an unhandled rejection. + let rejectionMessage: string | undefined + const rejectionObserved = rejecting.then( + () => undefined, + (error: unknown) => { + rejectionMessage = error instanceof Error ? error.message : String(error) + }, + ) + + let thirdRan = false + const third = withCommandListLock(async () => { + thirdRan = true + }) + + await flushMacrotasks() + expect(holderInside).toBe(true) + // The lock is still held, so nothing behind it has run. This is the + // assertion that fails if the lock stops serialising; without it the + // assertions after the release would pass on a lock that held nothing. + expect(thirdRan).toBe(false) + // The rejecting callback is behind the holder too, so it will run inside + // the lock. That is the fact a case which never takes the lock cannot show. + expect(rejectingRan).toBe(false) + + gate.resolve() + await holder + // The queue is first-in-first-out, so the rejecting callback can only run + // once the holder releases. Its error reaches this caller unswallowed. + await rejectionObserved + expect(rejectionMessage).toBe("write failed") + + await third + expect(thirdRan).toBe(true) + }) + it("holds a second import back until the first released the lock", async () => { const first = createDeferred() let secondRan = false diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index d537810593..2f2eebcb6a 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -471,6 +471,12 @@ interface ImportedCommandListWrite { key: CommandListConfigKey imported: string[] priorLayer: string[] | undefined + /** + * Whether the pre-write layer could not be read. Such a record has no + * baseline to undo against, and its rollback clears nothing rather than + * treat the failed read as an absent layer. + */ + priorLayerUnknown?: boolean } /** @@ -505,22 +511,22 @@ async function writeImportedCommandLists( } let priorLayer: string[] | undefined + let priorLayerUnknown = false try { priorLayer = config.inspect(key)?.globalValue } catch { - // No snapshot is no evidence about the prior layer, so it is passed on as - // unknown. A known baseline lets the rollback put back the entries this - // import replaced. An unknown one leaves it only the fresh read, and a - // fresh read equal to this import's own write is then restored to - // absence: the key is cleared, because an empty layer left behind would - // read as the user's explicit empty override. + // The read threw, so the prior layer is unknown, not absent. Recording + // that lets the rollback leave the key alone: a failed read is no + // evidence that nothing was there, and clearing on it would destroy a + // list this import never saw. priorLayer = undefined + priorLayerUnknown = true } await config.update(key, sanitizeCommandList(imported), vscode.ConfigurationTarget.Global) // Appended after the write resolves, so the rollback's baseline and its // `globalWriteApplied: true` describe a write that landed. - written.push({ key, imported: sanitizeCommandList(imported), priorLayer }) + written.push({ key, imported: sanitizeCommandList(imported), priorLayer, priorLayerUnknown }) } } @@ -539,7 +545,14 @@ async function rollBackImportedCommandLists(written: ImportedCommandListWrite[], const config = commandListConfiguration() const unrestored: string[] = [] - for (const { key, imported, priorLayer } of written) { + for (const { key, imported, priorLayer, priorLayerUnknown } of written) { + if (priorLayerUnknown) { + // There is no baseline to undo against, so any write here would guess. + // The key keeps the imported list and the caller names it as unrestored. + unrestored.push(key) + continue + } + const outcome = await rollbackFailedCommandListWrite({ key, failure, diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index cee61038b9..72fc21c515 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -3247,12 +3247,14 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Failed to save deniedCommands: workspace locked") }) - it("promotes a submitted entry no layer holds, even when the baseline still named it", async () => { + it("does not promote a displayed entry no layer holds", async () => { // The dialog displayed "docker" from the workspace layer, and while it was open - // the settings file lost it, so no layer holds it at save start. "New" means held - // by no layer at save start, not "absent from the baseline", so the stale dialog - // buffer promotes it beside "aws". Nothing was displayed-and-omitted, so no - // preservation warning fires. + // the settings file lost it, so no layer holds it at save start. The dialog holds + // back host updates after an edit, so the submission still carries "docker". An + // entry reaches Global only when the dialog never displayed it, so this one is + // dropped from both writes rather than granted to every workspace. "aws" was + // never displayed, so it still promotes, and nothing was displayed-and-omitted, + // so no preservation warning fires. const { update } = mockCommandConfiguration({ workspaceValue: [] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { @@ -3261,12 +3263,44 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, }) - expect(update).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.arrayContaining(["docker"]), + vscode.ConfigurationTarget.Global, + ) expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["aws"]) expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() }) + it("keeps a workspace allowance out of Global when another writer removed it after display", async () => { + // The allowlist path end to end. Gate on, the dialog displayed allowedCommands + // "docker" from the workspace layer, and another writer removed it before the + // save. Promoting it would auto-approve "docker" in every workspace, so the + // global write must not gain it while the unrelated deny edit still lands. + const { update } = mockCommandConfiguration( + (key: string) => (key === "allowedCommands" ? { workspaceValue: [] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["docker"], deniedCommands: ["aws"] }, + commandListBaseline: { allowedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + + expect(update).not.toHaveBeenCalledWith( + "allowedCommands", + expect.arrayContaining(["docker"]), + vscode.ConfigurationTarget.Global, + ) + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + }) + it("keeps a retained baseline entry the layers still hold while promoting a new entry", async () => { // The reconciliation's accept side: the baseline names "docker" and the // save-start snapshot still finds it in the workspace layer. The user kept it as @@ -3365,7 +3399,11 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, - commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + commandListBaseline: { + deniedCommands: ["docker"], + workspaceCommandListsEnabled: true, + workspaceDeniedCommands: ["docker"], + }, }) // The deletion sticks: "docker" is gone from the workspace layer... @@ -3985,7 +4023,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: ["aws"] }, - commandListBaseline: { deniedCommands: ["aws", "rm -rf"] }, + commandListBaseline: { + deniedCommands: ["aws", "rm -rf"], + workspaceDeniedCommands: ["aws", "rm -rf"], + }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Workspace) @@ -4004,7 +4045,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { deniedCommands: [] }, - commandListBaseline: { deniedCommands: ["git"] }, + commandListBaseline: { deniedCommands: ["git"], workspaceDeniedCommands: ["git"] }, }) expect(update).toHaveBeenCalledWith("deniedCommands", ["curl"], vscode.ConfigurationTarget.Workspace) @@ -4704,6 +4745,9 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { commandListBaseline: { allowedCommands: ["git log", "git diff", "git show", "npm test", "docker"], workspaceCommandListsEnabled: true, + // "npm test" was the only workspace-layer entry on screen; the rest are + // global entries the flat list carries too. + workspaceAllowedCommands: ["npm test", "docker"], }, }) @@ -4859,7 +4903,13 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { await webviewMessageHandler(mockClineProvider, { type: "updateSettings", updatedSettings: { allowedCommands: [] }, - commandListBaseline: { allowedCommands: ["git log"], workspaceCommandListsEnabled: true }, + commandListBaseline: { + allowedCommands: ["git log"], + workspaceCommandListsEnabled: true, + // The workspace layer held a copy the dialog showed, so the omission is a + // deletion of that copy as well as of the global one. + workspaceAllowedCommands: ["git log"], + }, }) expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) @@ -4867,6 +4917,38 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("allowedCommands", []) }) + it("keeps a workspace entry a displayed global entry of the same text did not put on screen", async () => { + // The user-global layer holds "echo", so the dialog showed "echo". The workspace + // layer gained its own "echo" after display, and the user removed "echo" in the + // dialog. The merged baseline names "echo" once, which cannot say which layer + // showed it. The per-layer share says the workspace layer did not, so the + // workspace copy is carried instead of deleted by an omission it never saw. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["echo"] : undefined, + ) + const { update } = mockCommandConfiguration( + { globalValue: ["echo"], workspaceValue: ["echo"] }, + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: [] }, + commandListBaseline: { + allowedCommands: ["echo"], + workspaceCommandListsEnabled: true, + workspaceAllowedCommands: [], + }, + }) + + // The global deletion lands, because that layer did show the entry... + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Global) + // ...and the workspace copy, which was never on screen, survives. + expect(update).toHaveBeenCalledWith("allowedCommands", ["echo"], vscode.ConfigurationTarget.Workspace) + }) + it("keeps a seeded default in the global write with the gate off while the workspace layer duplicates it", async () => { // The gate-off half of the seeded-default pair. Activation wrote the defaults // into extension state and the configuration's global layer is absent, so the diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 5ff876fe72..53018e79ea 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -926,20 +926,34 @@ export const webviewMessageHandler = async ( configGlobalAtSaveStart, gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, }) - const { writableGlobal, writableWorkspace } = displayedCommandListScopes({ - baseline, - incoming, - stateCopy: currentScopes.global, - configGlobal: globalOriginEntries, - workspaceNow: currentScopes.workspace, - gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, - seededEntries: seededGlobalEntries, - }) + // The flat baseline is the merged pair, so it names a global entry the + // workspace layer never showed. The dialog's per-layer field is the only + // evidence of what the workspace layer displayed; without it the save + // carries every workspace entry instead of deleting one it never showed. + const workspaceDisplayed = + key === "allowedCommands" + ? message.commandListBaseline?.workspaceAllowedCommands + : message.commandListBaseline?.workspaceDeniedCommands + const { writableGlobal, writableWorkspace, displayedGlobal, displayedWorkspace } = + displayedCommandListScopes({ + baseline, + incoming, + stateCopy: currentScopes.global, + configGlobal: globalOriginEntries, + workspaceNow: currentScopes.workspace, + gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, + workspaceDisplayed, + seededEntries: seededGlobalEntries, + }) + // Both displayed sets, from the same call that applied the deletions: an + // entry either layer displayed and no layer holds is a removal another + // writer made while the dialog was open, so the split must not promote it. const { globalWrite, workspaceWrite } = splitCommandListScopes( incoming, writableWorkspace, writableGlobal, heldAtSaveStart, + [...new Set([...displayedGlobal, ...displayedWorkspace])], ) const workspaceTarget = resolveWorkspaceWriteTarget(key, inspection) diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 29a087cb8f..51f8e6bc6f 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -112,6 +112,17 @@ interface CommandListSnapshot { workspaceCommandListsEnabled?: boolean } +// The same stamp, plus the global layer the host posted beside the merged lists. +// The merged pair cannot say which layer showed an entry, so the save needs the +// two layers as they stood when the dialog rendered them. +interface DisplayedCommandListStamp { + allowedCommands?: string[] + deniedCommands?: string[] + workspaceCommandListsEnabled?: boolean + globalAllowedCommands?: string[] + globalDeniedCommands?: string[] +} + const commandListSnapshot = (state: CommandListSnapshot): string => JSON.stringify([ state.allowedCommands ?? [], @@ -119,6 +130,38 @@ const commandListSnapshot = (state: CommandListSnapshot): string => state.workspaceCommandListsEnabled ?? false, ]) +const displayedCommandListStamp = (state: DisplayedCommandListStamp): string => + JSON.stringify([ + state.allowedCommands ?? [], + state.deniedCommands ?? [], + state.workspaceCommandListsEnabled ?? false, + // `null` keeps "the host posted no global layer" distinct from "it posted an + // empty one": only the second makes the workspace share derivable. + state.globalAllowedCommands ?? null, + state.globalDeniedCommands ?? null, + ]) + +const readDisplayedCommandListStamp = (stamp: string): DisplayedCommandListStamp => { + const [allowedCommands, deniedCommands, workspaceCommandListsEnabled, globalAllowed, globalDenied] = JSON.parse( + stamp, + ) as [string[], string[], boolean, string[] | null, string[] | null] + return { + allowedCommands, + deniedCommands, + workspaceCommandListsEnabled, + globalAllowedCommands: globalAllowed ?? undefined, + globalDeniedCommands: globalDenied ?? undefined, + } +} + +// The workspace-layer entries the dialog showed: the displayed list less the +// global layer posted with it. A global entry appears in both, so this is the +// only value that can say the workspace layer showed an entry. Without that +// layer the dialog cannot answer, and the field stays absent so the save carries +// every workspace entry rather than guessing. +const workspaceDisplayedEntries = (displayed: string[], globalLayer: string[] | undefined): string[] | undefined => + globalLayer === undefined ? undefined : displayed.filter((entry) => !globalLayer.includes(entry)) + const commandListsEquivalent = (left?: string[], right?: string[]) => left === right || (!!left && !!right && left.length === right.length && left.every((entry, index) => entry === right[index])) @@ -254,8 +297,9 @@ const SettingsView = forwardRef(({ onDone, t >(undefined) // What the dialog last displayed, so a later post counts as an external - // change, not a repeat. - const lastDisplayedCommandSnapshot = useRef(commandListSnapshot(extensionState)) + // change, not a repeat. The stamp also holds the global layer posted beside + // those lists, which is what makes the workspace layer's share derivable. + const lastDisplayedCommandSnapshot = useRef(displayedCommandListStamp(extensionState)) // An in-flight list edit holds the lists until Save, discard, or reseed. // External updates must not overwrite it. const commandListsTouched = useRef(false) @@ -347,7 +391,7 @@ const SettingsView = forwardRef(({ onDone, t setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) prevApiConfigName.current = currentApiConfigName prevMode.current = mode - lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) + lastDisplayedCommandSnapshot.current = displayedCommandListStamp(extensionState) commandListsTouched.current = false // The buffer this save would have settled is gone, so a late answer must not // write the baseline it captured from it. @@ -363,7 +407,7 @@ const SettingsView = forwardRef(({ onDone, t handledSettingsImportedAt.current = settingsImportedAt setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) - lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) + lastDisplayedCommandSnapshot.current = displayedCommandListStamp(extensionState) commandListsTouched.current = false // The import replaced the buffer the pending save submitted. baselineGeneration.current += 1 @@ -377,7 +421,9 @@ const SettingsView = forwardRef(({ onDone, t // untouched, and this effect never clears the dirty flag. useEffect(() => { const snapshot = commandListSnapshot(extensionState) - if (snapshot === lastDisplayedCommandSnapshot.current) { + // The stamp carries the global layer too, and that layer can move on its own. + // Only the list fields decide whether the host posted a new display. + if (snapshot === commandListSnapshot(readDisplayedCommandListStamp(lastDisplayedCommandSnapshot.current))) { return } @@ -403,19 +449,20 @@ const SettingsView = forwardRef(({ onDone, t // erase it as a user deletion. While the lists are held back, keep the prior // lists. A deletion inside the buffered edit must stay in the baseline so the // save applies it. The gate holds back with the lists, so the stamp describes - // one displayed state. - const [stampAllowed, stampDenied, stampGate] = commandListsTouched.current - ? (JSON.parse(lastDisplayedCommandSnapshot.current) as [string[], string[], boolean]) - : [ - merged.allowedCommands ?? prevState.allowedCommands, - merged.deniedCommands ?? prevState.deniedCommands, - merged.workspaceCommandListsEnabled ?? prevState.workspaceCommandListsEnabled, - ] - lastDisplayedCommandSnapshot.current = commandListSnapshot({ - allowedCommands: stampAllowed, - deniedCommands: stampDenied, - workspaceCommandListsEnabled: stampGate, - }) + // one displayed state. The global layer moves with the lists: held back with + // them, because the workspace share is derived from the pair. + const priorStamp = readDisplayedCommandListStamp(lastDisplayedCommandSnapshot.current) + const stamp = commandListsTouched.current + ? priorStamp + : { + allowedCommands: merged.allowedCommands ?? prevState.allowedCommands, + deniedCommands: merged.deniedCommands ?? prevState.deniedCommands, + workspaceCommandListsEnabled: + merged.workspaceCommandListsEnabled ?? prevState.workspaceCommandListsEnabled, + globalAllowedCommands: extensionState.globalAllowedCommands, + globalDeniedCommands: extensionState.globalDeniedCommands, + } + lastDisplayedCommandSnapshot.current = displayedCommandListStamp(stamp) if (Object.keys(merged).length > 0) { setCachedState((prevCachedState) => ({ ...prevCachedState, ...merged })) @@ -588,9 +635,13 @@ const SettingsView = forwardRef(({ onDone, t const handleSubmit = () => { if (isSettingValid) { - const [lastDisplayedAllowed, lastDisplayedDenied, gateAtSubmit] = JSON.parse( - lastDisplayedCommandSnapshot.current, - ) as [string[], string[], boolean] + const { + allowedCommands: lastDisplayedAllowed = [], + deniedCommands: lastDisplayedDenied = [], + workspaceCommandListsEnabled: gateAtSubmit, + globalAllowedCommands: displayedGlobalAllowed, + globalDeniedCommands: displayedGlobalDenied, + } = readDisplayedCommandListStamp(lastDisplayedCommandSnapshot.current) // The host reports a rejected list write in the same answer as a failed // display write, so a save carrying either one waits for it. Without an id, a @@ -627,6 +678,11 @@ const SettingsView = forwardRef(({ onDone, t // classification. workspaceCommandListsEnabled: cachedState.workspaceCommandListsEnabled === undefined ? undefined : gateAtSubmit, + // The merged lists above cannot say which layer showed an entry, so the + // workspace layer's share is posted beside them. It is the displayed list + // less the global layer posted with it: a global entry appears in both. + workspaceAllowedCommands: workspaceDisplayedEntries(lastDisplayedAllowed, displayedGlobalAllowed), + workspaceDeniedCommands: workspaceDisplayedEntries(lastDisplayedDenied, displayedGlobalDenied), }, updatedSettings: { language, @@ -714,10 +770,12 @@ const SettingsView = forwardRef(({ onDone, t vscode.postMessage({ type: "telemetrySetting", text: telemetrySetting }) vscode.postMessage({ type: "debugSetting", bool: cachedState.debug }) - lastDisplayedCommandSnapshot.current = commandListSnapshot({ + lastDisplayedCommandSnapshot.current = displayedCommandListStamp({ allowedCommands, deniedCommands, workspaceCommandListsEnabled: gateAtSubmit, + globalAllowedCommands: displayedGlobalAllowed, + globalDeniedCommands: displayedGlobalDenied, }) // The stamp moves at submit, and the settle below re-derives each edited list // from its own write outcome. The lists' hold does not move at submit: @@ -754,11 +812,13 @@ const SettingsView = forwardRef(({ onDone, t const refreshedAllowed = latestExtensionState.current.allowedCommands const refreshedDenied = latestExtensionState.current.deniedCommands - const [stampAllowed, stampDenied, stampGate] = JSON.parse(lastDisplayedCommandSnapshot.current) as [ - string[], - string[], - boolean, - ] + const { + allowedCommands: stampAllowed = [], + deniedCommands: stampDenied = [], + workspaceCommandListsEnabled: stampGate, + globalAllowedCommands: stampGlobalAllowed, + globalDeniedCommands: stampGlobalDenied, + } = readDisplayedCommandListStamp(lastDisplayedCommandSnapshot.current) const reconcileList = ( baselined: string[], sent: string[], @@ -773,10 +833,14 @@ const SettingsView = forwardRef(({ onDone, t const everyEditedWriteLanded = commandListWriteLanded(save.baselined[0], save.sent[0], refreshedAllowed) && commandListWriteLanded(save.baselined[1], save.sent[1], refreshedDenied) - lastDisplayedCommandSnapshot.current = commandListSnapshot({ + lastDisplayedCommandSnapshot.current = displayedCommandListStamp({ allowedCommands: reconcileList(save.baselined[0], save.sent[0], refreshedAllowed, stampAllowed), deniedCommands: reconcileList(save.baselined[1], save.sent[1], refreshedDenied, stampDenied), workspaceCommandListsEnabled: stampGate, + // The lists reconcile against their own write outcome; the global layer + // they were displayed beside is the one the host posted. + globalAllowedCommands: latestExtensionState.current.globalAllowedCommands ?? stampGlobalAllowed, + globalDeniedCommands: latestExtensionState.current.globalDeniedCommands ?? stampGlobalDenied, }) // Clear the flag only when nothing is left unsaved. An edit made during the @@ -794,10 +858,12 @@ const SettingsView = forwardRef(({ onDone, t const adoptedAllowed = latestExtensionState.current.allowedCommands const adoptedDenied = latestExtensionState.current.deniedCommands const adoptedGate = latestExtensionState.current.workspaceCommandListsEnabled - lastDisplayedCommandSnapshot.current = commandListSnapshot({ + lastDisplayedCommandSnapshot.current = displayedCommandListStamp({ allowedCommands: adoptedAllowed, deniedCommands: adoptedDenied, workspaceCommandListsEnabled: adoptedGate ?? stampGate, + globalAllowedCommands: latestExtensionState.current.globalAllowedCommands, + globalDeniedCommands: latestExtensionState.current.globalDeniedCommands, }) setCachedState((prevCachedState) => ({ ...prevCachedState, @@ -873,7 +939,7 @@ const SettingsView = forwardRef(({ onDone, t if (confirm) { // Discard changes: Reset state and flag setCachedState(extensionState) // Revert to original state - lastDisplayedCommandSnapshot.current = commandListSnapshot(extensionState) + lastDisplayedCommandSnapshot.current = displayedCommandListStamp(extensionState) commandListsTouched.current = false // Buffered edits are gone, so live lists are not held off // A save still in flight owns the buffer this discard replaced, so its // answer must not write a baseline taken before the discard. diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx index bd93a5cb86..e7d9b1e183 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -783,7 +783,12 @@ describe("SettingsView - Allowed Commands", () => { // baseline. The payload therefore carries what the dialog displayed before this // save. It carries neither the submitted list nor the committed value. renderWithExtensionState(, { - state: { allowedCommands: ["git"], alwaysAllowExecute: true }, + state: { + allowedCommands: ["git"], + globalAllowedCommands: [], + globalDeniedCommands: [], + alwaysAllowExecute: true, + }, }) const content = screen.getByTestId("settings-content") @@ -797,18 +802,65 @@ describe("SettingsView - Allowed Commands", () => { expect(vscode.postMessage).toHaveBeenCalledWith( expect.objectContaining({ type: "updateSettings", - commandListBaseline: { allowedCommands: ["git"], deniedCommands: [] }, + commandListBaseline: { + allowedCommands: ["git"], + deniedCommands: [], + workspaceAllowedCommands: ["git"], + workspaceDeniedCommands: [], + }, updatedSettings: expect.objectContaining({ allowedCommands: ["git", "npm test"] }), }), ) }) + it("sends only the workspace layer's share of the displayed lists, not the global entries", () => { + // The dialog shows the merged pair plus the global layer it was composed from. + // A global entry appears in both, so it is not workspace-layer display state. + // The save needs the difference, and the payload carries it per key. + renderWithExtensionState(, { + state: { + allowedCommands: ["git", "docker"], + deniedCommands: ["rm -rf"], + globalAllowedCommands: ["git"], + globalDeniedCommands: ["rm -rf"], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: true, + }, + }) + + const content = screen.getByTestId("settings-content") + const input = within(content).getByTestId("command-input") + fireEvent.change(input, { target: { value: "npm test" } }) + fireEvent.click(within(content).getByTestId("add-command-button")) + + fireEvent.click(screen.getByTestId("save-button")) + + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: expect.objectContaining({ + allowedCommands: ["git", "docker"], + deniedCommands: ["rm -rf"], + // "git" is the global entry the merged list carries too. + workspaceAllowedCommands: ["docker"], + workspaceDeniedCommands: [], + }), + }), + ) + }) + it("carries the gate displayed as on in the save baseline", () => { // The save path compares this flag against the gate at write time. With it on, // baseline entries are known state, so a gate flip cannot // reclassify a shown entry as a new global promotion. renderWithExtensionState(, { - state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: true }, + state: { + allowedCommands: ["git"], + globalAllowedCommands: [], + globalDeniedCommands: [], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: true, + }, }) const content = screen.getByTestId("settings-content") @@ -830,6 +882,8 @@ describe("SettingsView - Allowed Commands", () => { allowedCommands: ["git"], deniedCommands: [], workspaceCommandListsEnabled: true, + workspaceAllowedCommands: ["git"], + workspaceDeniedCommands: [], }, updatedSettings: expect.not.objectContaining({ workspaceCommandListsEnabled: expect.anything(), @@ -843,7 +897,13 @@ describe("SettingsView - Allowed Commands", () => { // so the baseline must keep the gate they were displayed under. Posting the // flipped gate would reclassify a shown entry as a new global promotion. renderWithExtensionState(, { - state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: true }, + state: { + allowedCommands: ["git"], + globalAllowedCommands: [], + globalDeniedCommands: [], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: true, + }, }) const content = screen.getByTestId("settings-content") @@ -854,6 +914,8 @@ describe("SettingsView - Allowed Commands", () => { await act(async () => { mockPostMessage({ allowedCommands: ["git", "curl"], + globalAllowedCommands: [], + globalDeniedCommands: [], alwaysAllowExecute: true, workspaceCommandListsEnabled: false, }) @@ -869,6 +931,8 @@ describe("SettingsView - Allowed Commands", () => { allowedCommands: ["git"], deniedCommands: [], workspaceCommandListsEnabled: true, + workspaceAllowedCommands: ["git"], + workspaceDeniedCommands: [], }, }), ) @@ -878,12 +942,20 @@ describe("SettingsView - Allowed Commands", () => { // With no in-flight edit the merge adopts the posted lists and the gate, so // the baseline describes the new state. renderWithExtensionState(, { - state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: false }, + state: { + allowedCommands: ["git"], + globalAllowedCommands: [], + globalDeniedCommands: [], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: false, + }, }) await act(async () => { mockPostMessage({ allowedCommands: ["git", "curl"], + globalAllowedCommands: [], + globalDeniedCommands: [], alwaysAllowExecute: true, workspaceCommandListsEnabled: true, }) @@ -903,6 +975,8 @@ describe("SettingsView - Allowed Commands", () => { allowedCommands: ["git", "curl"], deniedCommands: [], workspaceCommandListsEnabled: true, + workspaceAllowedCommands: ["git", "curl"], + workspaceDeniedCommands: [], }, updatedSettings: expect.objectContaining({ allowedCommands: ["git", "curl"] }), }), @@ -913,7 +987,13 @@ describe("SettingsView - Allowed Commands", () => { // The dialog shows the host's gate but never writes it, so the flag reaches // the save path through the baseline only, not the settings payload. renderWithExtensionState(, { - state: { allowedCommands: ["git"], alwaysAllowExecute: true, workspaceCommandListsEnabled: false }, + state: { + allowedCommands: ["git"], + globalAllowedCommands: ["git"], + globalDeniedCommands: [], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: false, + }, }) const content = screen.getByTestId("settings-content") @@ -930,6 +1010,10 @@ describe("SettingsView - Allowed Commands", () => { allowedCommands: ["git"], deniedCommands: [], workspaceCommandListsEnabled: false, + // With the gate off the workspace layer was not on screen, and the merged + // list equals the global layer, so the derived share is empty. + workspaceAllowedCommands: [], + workspaceDeniedCommands: [], }, updatedSettings: expect.not.objectContaining({ workspaceCommandListsEnabled: expect.anything() }), }), From 05c3053ddf59e3d9f3f84c95d7255ec61490fbc1 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 1 Dec 2026 10:40:13 +0100 Subject: [PATCH 45/52] fix: bound a broken folder root and pair a restored baseline with its global layer A workspace folder opened at a symlink path lost the folder layer when the link broke. The registered path no longer contained the canonical cwd, so the folder was skipped and the loop fell through to an enclosing folder whose allow list then approved the command. The folder-layer decision now also tests the resolved registered parent, so a broken link stays bounded by the directory it was opened in and cannot fall through to an enclosing allow. A link whose target lay outside its parent stays unknowable, because the registry records where a folder was opened and not where the link pointed. Several unresolvable folders could each claim the cwd, and the last one in folder order replaced the claim recorded before it. A shallower folder listed later could therefore drop the claim below the deepest resolving folder and hand the cwd to it. Both claim accumulators now keep the maximum, so the deepest claim decides and no folder order is more permissive than that claim warrants. A save that restored the original baseline paired it with the global layer the host had just posted, not the one that baseline was displayed beside. On a retry, a workspace entry the dialog never showed was attributed to the global layer and deleted. Settlement now pairs each restored baseline with its own global layer, using the same write-landed test the merged lists already use, so the posted layer is adopted only when that list's write landed and no new protocol field is needed. --- .../__tests__/commandScope.spec.ts | 87 +++++++++++++++++++ src/core/auto-approval/commandScope.ts | 46 ++++++++-- .../src/components/settings/SettingsView.tsx | 18 ++-- .../SettingsView.unsaved-changes.spec.tsx | 78 +++++++++++++++++ 4 files changed, 213 insertions(+), 16 deletions(-) diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 72370cf547..e2ab536c8a 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -1390,6 +1390,93 @@ it("commandListFolderForResource: an unresolvable root keeps an enclosing root f expect(commandListFolderForResource(path.join(innerRoot, "sub"))).toBeUndefined() }) +it("commandListFolderForResource: a broken link's resolved parent keeps an enclosing root from claiming the cwd", () => { + vi.clearAllMocks() + // The inner root was opened at a link's path. The link is gone, so its real + // path cannot be resolved, but its parent still resolves and bounds the cwd + // of the directory the link pointed into. The inner root therefore may own + // the cwd, and the enclosing root must not claim it. + const outerRoot = path.sep + "mock" + const linkRoot = path.join(outerRoot, "link") + const outerUri = makeUri(outerRoot) + workspaceState.workspaceFolders = [{ uri: outerUri }, { uri: makeUri(linkRoot) }] + vi.mocked(fs.realpathSync).mockImplementation((target) => { + if (String(target) === linkRoot) { + throw new Error("ENOENT: no such file or directory") + } + return String(target) + }) + + expect(commandListFolderForResource(path.join(outerRoot, "inner", "sub"))).toBeUndefined() +}) + +it("checkAutoApproval command: a broken link's resolved parent keeps an enclosing root's allow from deciding", async () => { + vi.clearAllMocks() + // The enforcement counterpart of the case above. The link's parent bounds + // the cwd, so the inner root may own it. The enclosing root resolves and + // allows the command, but it must not decide for a directory the inner root + // may own: that would approve what the inner folder's deny would block. + const outerRoot = path.sep + "mock" + const linkRoot = path.join(outerRoot, "link") + const outerUri = makeUri(outerRoot) + workspaceState.workspaceFolders = [{ uri: outerUri }, { uri: makeUri(linkRoot) }] + workspaceState.foldersByPath.set(outerRoot, outerUri) + vi.mocked(fs.realpathSync).mockImplementation((target) => { + if (String(target) === linkRoot) { + throw new Error("ENOENT: no such file or directory") + } + return String(target) + }) + mockFolderConfigurations({ [outerRoot]: { gate: true, allow: ["echo"] } }) + + const result = await checkAutoApproval({ + // Empty raw global layers: only a folder layer could approve. + state: taskFolderState([]), + cwd: path.join(outerRoot, "inner", "sub"), + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + +it("commandListFolderForResource: an unrelated unresolvable root later in folder order cannot weaken a deeper claim", async () => { + vi.clearAllMocks() + // Two roots cannot be resolved and a third, shallower one can. The deep + // dangling root bounds the cwd, so it may own it; the unrelated dangling + // root does not bound the cwd, and only its parent does. Keeping the last + // claim would let that unrelated root hand the cwd to the resolving root, + // whose allow would then approve what the deep root's deny may block. + const healthyRoot = path.join(path.sep + "mock", "healthy-root") + const deepRoot = path.join(healthyRoot, "inner") + const unrelatedRoot = path.join(path.sep + "mock", "other") + const healthyUri = makeUri(healthyRoot) + workspaceState.workspaceFolders = [{ uri: makeUri(deepRoot) }, { uri: makeUri(unrelatedRoot) }, { uri: healthyUri }] + workspaceState.foldersByPath.set(healthyRoot, healthyUri) + vi.mocked(fs.realpathSync).mockImplementation((target) => { + if (String(target) === deepRoot || String(target) === unrelatedRoot) { + throw new Error("ENOENT: no such file or directory") + } + return String(target) + }) + + expect(commandListFolderForResource(path.join(deepRoot, "sub"))).toBeUndefined() + + // The enforcement counterpart: the resolving root allows the command, but a + // directory the deep root may own must not be approved on its word. + mockFolderConfigurations({ [healthyRoot]: { gate: true, allow: ["echo"] } }) + + const result = await checkAutoApproval({ + // Empty raw global layers: only a folder layer could approve. + state: taskFolderState([]), + cwd: path.join(deepRoot, "sub"), + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + it("checkAutoApproval command: keeps a healthy folder's deny when an unrelated registered root cannot be resolved", async () => { vi.clearAllMocks() // The root that owns the cwd resolves. The other root cannot, and its diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index ed725b5e47..d9366c3b44 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -87,19 +87,42 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin // root's directory. The separator guard keeps `/root/other` out of `/root`. let match: vscode.Uri | undefined let matchedLength = 0 + // The deepest claim from a root that may own the cwd but has no real + // path. It is recorded rather than answered at once, because a resolving + // root inside the claim may own the cwd and is the better-supported + // candidate, so it must decide instead. Keeping the deepest claim rather + // than the last one stops a shallower unresolvable root from ceding the + // cwd merely because the registry listed it later. + let unresolvedClaimLength: number | undefined for (const candidate of vscode.workspace.workspaceFolders ?? []) { const rootPath = realPathOrRegistered(candidate.uri.fsPath) if (rootPath === undefined) { - // The root's real path is unknown, so only its registered path is - // left to bound the cwd. One that cannot bound the cwd cannot own - // it, and skipping it lets the healthy roots decide. One that may - // bound the cwd may own it, so no other root may decide instead: - // an enclosing root's allow would otherwise stand in for this - // root's deny. - if (!registeredRootContains(candidate.uri.fsPath, cwd)) { - continue + // The root's real path is unknown, so its registered path is what + // is left to bound the cwd. One that cannot bound the cwd cannot + // own it, and skipping it lets the healthy roots decide. One that + // may bound the cwd may own it, so no enclosing root may decide + // instead: an enclosing root's allow would otherwise stand in for + // this root's deny. + const registeredPath = candidate.uri.fsPath + if (!registeredRootContains(registeredPath, cwd)) { + // A root opened at a link's path keeps a parent that still + // resolves after the link breaks, and that parent bounds the + // cwd of the directory the link pointed into. So the + // registered spelling is not the only path a root can be + // reached by. A link whose target lay outside its parent + // stays unknowable: the registry records where the root was + // opened, not where the link pointed. One whose target lay + // inside a deeper resolving root's subtree is unknowable + // too, and that root decides instead. + const parentReal = realPathOrRegistered(path.dirname(registeredPath)) + if (parentReal === undefined || !registeredRootContains(parentReal, cwd)) { + continue + } + unresolvedClaimLength = Math.max(unresolvedClaimLength ?? 0, parentReal.length) + } else { + unresolvedClaimLength = Math.max(unresolvedClaimLength ?? 0, registeredPath.length) } - return undefined + continue } // A filesystem root (`/`, `C:\`) already ends in a separator. A second separator stops child matching. const childPrefix = rootPath.endsWith(path.sep) ? rootPath : rootPath + path.sep @@ -108,6 +131,11 @@ export function commandListFolderForResource(cwd?: string): vscode.Uri | undefin matchedLength = rootPath.length } } + // A resolving root no deeper than the claim cannot be the one that owns + // the cwd, so the claim stands and the folder layer stays absent. + if (unresolvedClaimLength !== undefined && unresolvedClaimLength >= matchedLength) { + return undefined + } return match } catch { return undefined diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 51f8e6bc6f..91f06faa8d 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -830,17 +830,21 @@ const SettingsView = forwardRef(({ onDone, t : commandListWriteLanded(baselined, sent, refreshed) ? sent : baselined - const everyEditedWriteLanded = - commandListWriteLanded(save.baselined[0], save.sent[0], refreshedAllowed) && - commandListWriteLanded(save.baselined[1], save.sent[1], refreshedDenied) + const allowedWriteLanded = commandListWriteLanded(save.baselined[0], save.sent[0], refreshedAllowed) + const deniedWriteLanded = commandListWriteLanded(save.baselined[1], save.sent[1], refreshedDenied) + const everyEditedWriteLanded = allowedWriteLanded && deniedWriteLanded + // A restored baseline keeps the global layer it was displayed beside. The + // posted layer is that baseline's own only when the write landed, which is + // the same condition that keeps the advanced baseline above. An absent + // stamp layer stays absent rather than becoming an empty one. + const refreshedGlobalAllowed = latestExtensionState.current.globalAllowedCommands + const refreshedGlobalDenied = latestExtensionState.current.globalDeniedCommands lastDisplayedCommandSnapshot.current = displayedCommandListStamp({ allowedCommands: reconcileList(save.baselined[0], save.sent[0], refreshedAllowed, stampAllowed), deniedCommands: reconcileList(save.baselined[1], save.sent[1], refreshedDenied, stampDenied), workspaceCommandListsEnabled: stampGate, - // The lists reconcile against their own write outcome; the global layer - // they were displayed beside is the one the host posted. - globalAllowedCommands: latestExtensionState.current.globalAllowedCommands ?? stampGlobalAllowed, - globalDeniedCommands: latestExtensionState.current.globalDeniedCommands ?? stampGlobalDenied, + globalAllowedCommands: allowedWriteLanded ? refreshedGlobalAllowed : stampGlobalAllowed, + globalDeniedCommands: deniedWriteLanded ? refreshedGlobalDenied : stampGlobalDenied, }) // Clear the flag only when nothing is left unsaved. An edit made during the diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 22873a71a6..2a67be31c2 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -1292,6 +1292,84 @@ describe("SettingsView - Unsaved Changes Detection", () => { ) }) + it("keeps a restored baseline paired with the global layer it was displayed beside", async () => { + // Global and workspace both hold "echo", so the dialog shows one merged entry + // and the stamp pairs it with the global layer it was displayed beside. The + // user deletes it. The global write lands, yet the merged list still holds + // "echo" from the workspace copy, and a third writer adds "ls" to that copy + // during the save. The merged write therefore did not land, and its baseline + // is restored. A restored baseline must keep its own global layer: the posted + // one reflects a deletion the dialog never confirmed. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + globalAllowedCommands: ["echo"], + workspaceCommandListsEnabled: true, + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField }: React.ComponentProps) => ( +
+ +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // A display-setting difference routes this save through the answered path, + // without touching the buffered command lists. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + globalAllowedCommands: ["echo"], + workspaceCommandListsEnabled: true, + showRelativeTimes: false, + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The global write landed, but the merged list still holds "echo" from the + // workspace copy, so the merged list's own write is judged not landed. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + globalAllowedCommands: [], + workspaceCommandListsEnabled: true, + showRelativeTimes: false, + }) + view.rerender() + answerSave(saveId, { success: true }) + + // The restored baseline keeps the hold, so the deletion stays the user's. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // On retry "echo" still belongs to the global layer the baseline was displayed + // beside, so the workspace share is empty and the host carries the workspace + // copy instead of reading it as a deletion. + fireEvent.click(screen.getByTestId("save-button")) + const saves = updateSettingsPosts() + expect(saves).toHaveLength(2) + expect(saves.at(-1)).toEqual( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: expect.objectContaining({ + allowedCommands: ["echo"], + workspaceAllowedCommands: [], + }), + updatedSettings: expect.objectContaining({ allowedCommands: [] }), + }), + ) + }) + it("releases the unsaved flag after a save when a refused external update changed nothing", async () => { // A refused external post changes nothing, so the merge must leave the buffer // object untouched. The save settles by comparing the live buffer against the From 0c7ee1ba8fdd5edbbfa9c03e436ad72e8ca48d91 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Tue, 1 Dec 2026 20:37:48 +0100 Subject: [PATCH 46/52] fix: judge each command-list layer by its own evidence on the save and import paths After the global write, a save re-reads the workspace layer. When that re-read returned nothing, the save kept the list it had computed before the global write, so an entry another writer added in between was dropped. An absent re-read is now the same failure as a thrown one: the key aborts, the outer handler rolls back the global half, and neither store keeps a list built before that write. A failed import now restores only the command-list keys it wrote to extension state. The state write is one call, so the keys it can touch are the ones the settings carry as arrays, which is the same test the write itself uses. A provider-only import therefore rewrites no list and reports no restore error for one. The dialog now sends the global-layer entries it displayed, beside the workspace pair it already sent. Without them the save read the merged list as the global layer, so a global entry another writer added after the dialog opened counted as displayed and its omission deleted it. The merged list still stands in when a sender sends no such field. The classification that warns about entries added outside the dialog now tests them against the global layers of both keys, which is the set the display composition already uses. An entry the other key's global layer hid was never displayed, and it is no longer reported as an addition. Membership stays single-key: an entry this key's global layer holds is always displayed, so it is still reported even when the other key covers it. A global deletion that landed now clears the save hold even when a workspace copy keeps the entry in the merged list. The form stops waiting for the timeout and settling as failed, and the surviving entry is adopted back into the view so the dialog matches the stores. The lock tests now release the parked holder in a finally, so a failed assertion cannot leave the callback pending and strand the lock for a later writer. One case now drives a real save and a real import through the real lock instead of a stubbed one, and asserts both stores end on the imported list. It replaces a case that observed a stub and proved nothing about the serialisation the lock exists to give. --- packages/types/src/vscode-extension-host.ts | 9 + .../__tests__/commandScope.spec.ts | 71 ++++ src/core/auto-approval/commandScope.ts | 60 +++- .../config/__tests__/importExport.spec.ts | 94 +++++- src/core/config/importExport.ts | 13 +- .../__tests__/webviewMessageHandler.spec.ts | 309 +++++++++++++++++- src/core/webview/webviewMessageHandler.ts | 34 +- .../src/components/settings/SettingsView.tsx | 63 +++- .../settings/__tests__/SettingsView.spec.tsx | 14 + .../SettingsView.unsaved-changes.spec.tsx | 67 +++- 10 files changed, 688 insertions(+), 46 deletions(-) diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 11d7eb77c4..9563891dfe 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -892,6 +892,15 @@ export interface WebviewMessage { */ workspaceAllowedCommands?: string[] workspaceDeniedCommands?: string[] + /** + * The global-layer entries the dialog showed, per key: the global counterpart + * of the workspace pair above. Without them the save reads the merged list as + * the global layer too, so a global entry another writer added after the + * dialog opened counts as displayed and its omission deletes it. Absent means + * the sender cannot say, and the save falls back to the merged list. + */ + globalAllowedCommands?: string[] + globalDeniedCommands?: string[] } /** Task configuration applied via `createTask()`. */ taskConfiguration?: RooCodeSettings diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index e2ab536c8a..713defba14 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -1932,6 +1932,77 @@ describe("classifyCommandListBaseline", () => { expect(result.externallyAdded).toEqual(["git status"]) }) + + it("does not report a workspace entry that the other key's global layer covers", () => { + // This key is `deniedCommands` and holds no global entry. The `allowedCommands` + // global layer holds "git", which the composition also applies to this key's + // workspace layer, so the dialog never showed "git status". Its absence from + // the baseline is display, not an addition. + const result = classifyCommandListBaseline({ + baseline: [], + incoming: [], + currentScopes: { global: [], workspace: ["git status"], merged: [] }, + configGlobalAtSaveStart: [], + gateAtDisplay: true, + globalShadowAtSaveStart: ["git"], + }) + + expect(result.externallyAdded).toEqual([]) + }) + + it("still reports a workspace entry the other key's global layer does not cover", () => { + // The positive control for the widened shadow array: the other key's global + // layer holds an entry that covers nothing here, so this workspace entry was + // never hidden and its absence from the baseline is an addition. + const result = classifyCommandListBaseline({ + baseline: [], + incoming: [], + currentScopes: { global: [], workspace: ["git status"], merged: [] }, + configGlobalAtSaveStart: [], + gateAtDisplay: true, + globalShadowAtSaveStart: ["npm"], + }) + + expect(result.externallyAdded).toEqual(["git status"]) + }) + + it("still reports a global entry the other key's global layer happens to cover", () => { + // The entry is in this key's own global layer, so the composition always + // displayed it; its absence from the baseline is an addition even though the + // other key's global layer covers it. Pins that the membership arm exists: + // replacing it with `false` drops this report. It does not pin that the set + // stays single-key, because this entry is reported under a widened set too. + const result = classifyCommandListBaseline({ + baseline: [], + incoming: [], + currentScopes: { global: ["git status"], workspace: [], merged: [] }, + configGlobalAtSaveStart: [], + gateAtDisplay: true, + globalShadowAtSaveStart: ["git"], + }) + + expect(result.externallyAdded).toEqual(["git status"]) + }) + + it("does not report a workspace entry the other key's global layer holds verbatim", () => { + // Membership is single-key: this key's global layer is empty, so the entry is + // absent from the membership set and the shadow test alone decides it. The + // other key's global layer holds "git status" itself, so the composition + // dropped the workspace copy from display and its absence from the baseline + // is display. A membership set that also held the other key's globals would + // match this entry exactly, short-circuit the shadow test, and report an entry + // the dialog never showed. + const result = classifyCommandListBaseline({ + baseline: [], + incoming: [], + currentScopes: { global: [], workspace: ["git status"], merged: [] }, + configGlobalAtSaveStart: [], + gateAtDisplay: true, + globalShadowAtSaveStart: ["git status"], + }) + + expect(result.externallyAdded).toEqual([]) + }) }) describe("displayedCommandListScopes", () => { diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index d9366c3b44..470433753a 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -408,6 +408,9 @@ export interface DisplayedCommandListScopes { * @param input.workspaceDisplayed - The workspace-layer entries the dialog showed, * when the sender says. Absent means it cannot, and the save then carries every * workspace entry rather than deleting one it has no evidence about. + * @param input.globalDisplayed - The global-layer entries the dialog showed, when + * the sender says. Absent means it cannot, and the merged baseline then stands in + * for the global layer. * @param input.seededEntries - The entries the shipped default vouches for, from * the caller's seeded global copy. A value comparison against the default, never * a store-membership test. @@ -421,6 +424,12 @@ export function displayedCommandListScopes(input: { workspaceNow: string[] gateAtDisplay: boolean | undefined workspaceDisplayed?: string[] + /** + * The global-layer entries the dialog showed, when the sender says. Absent means + * the sender cannot say, and the merged baseline then stands in for the global + * layer — which is what treats a global entry added after display as displayed. + */ + globalDisplayed?: string[] seededEntries: string[] }): DisplayedCommandListScopes { const submitted = new Set(sanitizeCommandList(input.incoming)) @@ -443,7 +452,13 @@ export function displayedCommandListScopes(input: { : sanitizeCommandList(input.workspaceDisplayed) : workspace const displayedWorkspaceSet = new Set(displayedWorkspace) - const displayedGlobalSet = hasBaseline ? new Set(baseline) : new Set(heldGlobal) + // The global layer's own field answers this when the sender sends one. The merged + // baseline stands in otherwise: it names every displayed entry, including a global + // one another writer added after the dialog opened, and only this field separates + // the two. + const displayedGlobalSet = hasBaseline + ? new Set(input.globalDisplayed === undefined ? baseline : sanitizeCommandList(input.globalDisplayed)) + : new Set(heldGlobal) const configSet = new Set(config) // Only a displayed entry can be deleted by omission. Everything else is @@ -499,6 +514,23 @@ export function resolveWorkspaceWriteTarget( } } +/** + * The global entries that hide a workspace entry from display. + * + * This is the single construction of that set. {@link resolveEffectiveCommandLists} + * filters both workspace layers against it, so an entry here is one the dialog never + * showed and the save therefore has no display evidence about. The concatenation is + * deliberately not deduplicated: the composition's output order is part of what the + * display and the save both read. + * + * @param allowGlobal - The `allowedCommands` global layer. + * @param denyGlobal - The `deniedCommands` global layer. + * @returns Both layers concatenated, allow first. + */ +export function globalShadowEntries(allowGlobal: string[], denyGlobal: string[]): string[] { + return [...allowGlobal, ...denyGlobal] +} + export interface CommandListBaselineClassification { /** * Entries a layer held at save start that the baseline and the submission both @@ -521,11 +553,11 @@ export interface CommandListBaselineClassification { * The gate being on is not enough. The composition drops a workspace entry that * a global entry covers, so the dialog never showed it and its absence from the * baseline is display, not addition. {@link isShadowedByAnyEntry} is the - * predicate the composition applies. This function reads one key's layers, so a - * global entry of the *other* key that covers this one is not seen here: such an - * entry stays reported, which can raise a warning for an entry the dialog hid. - * The error is one-directional - the shadow term only ever removes a report, so - * the residual can add a spurious warning and never suppress a real one. + * predicate the composition applies, and {@link globalShadowEntries} is the set + * it applies it to. The composition shadows across both keys, so this function + * takes the other key's global layer as an input and widens the shadow array to + * match. Membership stays single-key: an entry this key's own global layer holds + * is always displayed, so it is still reported even when the other key covers it. * * @param input.baseline - The lists the dialog displayed for this key, or * `undefined` when the sender shows no lists. @@ -535,6 +567,11 @@ export interface CommandListBaselineClassification { * @param input.configGlobalAtSaveStart - The configuration's global layer at * save start. * @param input.gateAtDisplay - The gate as the dialog showed it, if it sent it. + * @param input.globalShadowAtSaveStart - The global layers of **both** command + * lists at save start, composed as {@link resolveEffectiveCommandLists} composes + * them. It widens only the shadow test, so an entry the other key's global layer + * hid is not reported as an addition. Absent means only this key's own globals + * are considered, which is the pre-existing behaviour. * @returns The externally added entries. */ export function classifyCommandListBaseline(input: { @@ -543,6 +580,7 @@ export function classifyCommandListBaseline(input: { currentScopes: CommandListScopes configGlobalAtSaveStart: string[] gateAtDisplay: boolean | undefined + globalShadowAtSaveStart?: string[] }): CommandListBaselineClassification { const { baseline, incoming, currentScopes, configGlobalAtSaveStart, gateAtDisplay } = input @@ -558,7 +596,11 @@ export function classifyCommandListBaseline(input: { // The global layer the dialog rendered, which decides whether a workspace-only // entry was shadowed and so never shown. const globalEntriesAtSaveStart = [...new Set([...currentScopes.global, ...configGlobalAtSaveStart])] + // Membership stays on this key's own globals: an entry a global layer holds is + // always displayed, so reporting it is correct even when the other key covers it. + // The shadow test is the one the composition applies, so it sees both keys. const globalEntrySet = new Set(globalEntriesAtSaveStart) + const shadowEntries = globalShadowEntries(globalEntriesAtSaveStart, input.globalShadowAtSaveStart ?? []) const externallyAdded = heldAtSaveStart.filter( (entry) => !baseline.includes(entry) && @@ -573,9 +615,7 @@ export function classifyCommandListBaseline(input: { // entry no global layer holds can be hidden this way: a global entry is // always displayed, so an entry a global layer holds was shown even when a // global entry also covers its workspace copy. - (globalEntrySet.has(entry) || - gateAtDisplay === false || - !isShadowedByAnyEntry(entry, globalEntriesAtSaveStart)), + (globalEntrySet.has(entry) || gateAtDisplay === false || !isShadowedByAnyEntry(entry, shadowEntries)), ) return { externallyAdded } @@ -760,7 +800,7 @@ export function resolveEffectiveCommandLists( ): EffectiveCommandLists { const globalAllow = allowScopes.global const globalDeny = denyScopes.global - const globalEntries = [...globalAllow, ...globalDeny] + const globalEntries = globalShadowEntries(globalAllow, globalDeny) const keptWorkspaceAllow = enabled ? allowScopes.workspace.filter((entry) => !isShadowedByAnyEntry(entry, globalEntries)) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 403c4f7fed..6e4191405e 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -965,6 +965,38 @@ describe("importExport", () => { expect(update).toHaveBeenCalledWith("allowedCommands", ["git"], vscode.ConfigurationTarget.Global) }) + it("restores no command-list key when a provider-only import fails after the snapshot", async () => { + // The import file carries provider profiles and no command lists, so the state + // write touches neither list. Restoring both keys from the snapshot would + // rewrite lists this import never touched, and a rejected restore would report + // a failure for a setting the import did not change. + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({})) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + mockLayeredCommandListConfig({ allowedCommands: ["git"], deniedCommands: ["prior-deny"] }) + + vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git"] : key === "deniedCommands" ? ["prior-deny"] : undefined, + ) + mockContextProxy.setValues.mockRejectedValue(new Error("state write failed")) + // A restore that never runs cannot fail, so an unrestored key here would mean + // the restore named a list the import did not write. + mockContextProxy.setValue.mockRejectedValue(new Error("restore rejected")) + + const result = await importSettingsFromPath(filePath, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + expect(result.success).toBe(false) + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("allowedCommands", expect.anything()) + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) + // No restore error names a command list. + expect(result.error).not.toContain("could not be restored in extension state") + }) + it("keeps both layers pre-import when the second key's write rejects", async () => { const filePath = "/mock/path/settings.json" ;(fs.readFile as Mock).mockResolvedValue( @@ -1185,17 +1217,23 @@ describe("importExport", () => { thirdRan = true }) - await flushMacrotasks() - expect(holderInside).toBe(true) - // The lock is still held, so nothing behind it has run. This is the - // assertion that fails if the lock stops serialising; without it the - // assertions after the release would pass on a lock that held nothing. - expect(thirdRan).toBe(false) - // The rejecting callback is behind the holder too, so it will run inside - // the lock. That is the fact a case which never takes the lock cannot show. - expect(rejectingRan).toBe(false) - - gate.resolve() + try { + await flushMacrotasks() + expect(holderInside).toBe(true) + // The lock is still held, so nothing behind it has run. This is the + // assertion that fails if the lock stops serialising; without it the + // assertions after the release would pass on a lock that held nothing. + expect(thirdRan).toBe(false) + // The rejecting callback is behind the holder too, so it will run inside + // the lock. That is the fact a case which never takes the lock cannot show. + expect(rejectingRan).toBe(false) + } finally { + // The release is unconditional. A failed assertion above must not leave + // the holder parked on the gate, because the lock it holds is shared by + // every later writer in this file and they would all queue behind it. + gate.resolve() + } + await holder // The queue is first-in-first-out, so the rejecting callback can only run // once the holder releases. Its error reaches this caller unswallowed. @@ -1206,6 +1244,40 @@ describe("importExport", () => { expect(thirdRan).toBe(true) }) + it("frees the lock for a later writer when an assertion fails while the holder is parked", async () => { + // The holder parks inside the lock, and the assertion inside the guarded + // region is forced to fail. The release is in a `finally`, so the holder + // still settles and the next writer gets the lock. Without it the lock stays + // held by a test that already failed, and every later writer in this file + // waits on a gate nothing will resolve. + const gate = createDeferred() + void withCommandListLock(async () => { + await gate.promise + }) + await flushMacrotasks() + + let assertionFailure: unknown + try { + expect("the lock is held here").toBe("the lock was not held here") + } catch (error) { + assertionFailure = error + } finally { + gate.resolve() + } + expect(assertionFailure).toBeDefined() + + // Bounded, so a stranded lock reports a named failure instead of hanging the + // case. A free lock lets the queued writer run inside the microtask flush. + const laterWriterRan = await Promise.race([ + withCommandListLock(async () => true), + (async () => { + await flushMacrotasks() + return false + })(), + ]) + expect(laterWriterRan).toBe(true) + }) + it("holds a second import back until the first released the lock", async () => { const first = createDeferred() let secondRan = false diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 2f2eebcb6a..31ceb2a6d4 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -177,6 +177,9 @@ async function applySettingsImport( // written after a successful import, so it needs no restore; the two command-list // stores are written below, and these hold the copies the failure path puts back. let priorStateCopy: Pick | undefined + // The command-list keys this import writes into extension state. Empty until the + // snapshot is taken, because the settings are not parsed before then. + let stateCommandListKeys: readonly (keyof Pick)[] = [] let importedCommandLists: ImportedCommandListWrite[] = [] try { @@ -268,6 +271,14 @@ async function applySettingsImport( allowedCommands: contextProxy.getValue("allowedCommands"), deniedCommands: contextProxy.getValue("deniedCommands"), } + // The state write is one `setValues` call, so the command-list keys it can + // touch are exactly the ones the settings carry as arrays. The same predicate + // gates `writeImportedCommandLists`, so the restore below names the keys the + // import wrote rather than both keys of the snapshot. A provider-only import + // therefore rewrites no list and reports no restore error for one. + stateCommandListKeys = (["allowedCommands", "deniedCommands"] as const).filter((key) => + Array.isArray(sanitizedGlobalSettings[key]), + ) // The configuration half comes first, matching the save's order. With one // order, the two writers cannot interleave into stores that disagree, and a @@ -311,7 +322,7 @@ async function applySettingsImport( if (priorStateCopy) { const unrestoredKeys: string[] = [] - for (const key of ["allowedCommands", "deniedCommands"] as const) { + for (const key of stateCommandListKeys) { // A restore that rejects is reported in the error text rather than // thrown, so the caller always learns the import failed. try { diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 72fc21c515..d376acc54f 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -67,14 +67,19 @@ vi.mock("../rulesMessageHandler", () => ({ handleOpenRulesDirectory: vi.fn(), })) -// The import case needs no real import: the shared import function is a mock, -// and the save tests script the configuration state directly. The lock runs its -// callback by default, so a case only observes it when it scripts one. -vi.mock("../../config/importExport", () => ({ - withCommandListLock: vi.fn(async (write: () => Promise) => write()), - exportSettings: vi.fn(), - importSettingsWithFeedback: vi.fn(), -})) +// The save tests script the configuration state directly, so the import entry +// points stay mocks. The lock is the module's own, delegated through the mock: the +// save and the import are the two writers it serialises, and a case can only show +// that ordering when both take the same lock. +vi.mock("../../config/importExport", async () => { + const actual = await vi.importActual("../../config/importExport") + + return { + withCommandListLock: vi.fn(actual.withCommandListLock), + exportSettings: vi.fn(), + importSettingsWithFeedback: vi.fn(), + } +}) vi.mock("@roo-code/telemetry", () => ({ TelemetryService: { @@ -2190,12 +2195,24 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { } const inspect = vi.fn() if (inspectSequence) { - inspect.mockImplementation(() => { - const next = inspectSequence.shift() + // The most recent snapshot returned for each key. An unscripted read answers + // with it, which is the layer as it stands, so a case that scripts only the + // reads it is about does not have to restate a snapshot to get past the others. + const lastSnapshot = new Map() + inspect.mockImplementation((key: string) => { + const next = inspectSequence.length > 0 ? inspectSequence.shift() : undefined if (next instanceof Error) { throw next } - return next + // `null` scripts the one outcome a snapshot cannot express: no inspection + // object at all. Every other unscripted read repeats the key's latest one. + if (next === null) { + lastSnapshot.set(key, undefined) + return undefined + } + const snapshot = next ?? lastSnapshot.get(key) + lastSnapshot.set(key, snapshot) + return snapshot }) } else { inspect.mockImplementation((key: string) => (typeof inspected === "function" ? inspected(key) : inspected)) @@ -2230,6 +2247,127 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(withCommandListLock).toHaveBeenCalledTimes(1) }) + it("holds a real import behind a parked save, and both stores end on the imported list", async () => { + // The save and the import are the two writers the command-list lock orders. The + // save parks inside the lock before its own state write; the import is started + // behind it and must not reach its state write until the save releases. The save + // then writes its own list first, and the import's list is what both stores hold + // when the queue drains. A stub lock would let the import's state write land + // first, which is the interleaving this case rules out. + const { importSettingsFromPath, withCommandListLock: realCommandListLock } = + await vi.importActual("../../config/importExport") + const { sanitizeCommandList } = await vi.importActual( + "../../auto-approval/commandScope", + ) + + // The block's setup replaces the lock with a direct call, which would let the save + // and the import run concurrently. This case puts the module's own lock back, so + // both writers queue on the one lock the production code installs. + vi.mocked(withCommandListLock).mockImplementation(realCommandListLock) + + const layers: Record = {} + const { update } = mockCommandConfiguration({ globalValue: ["git"] }, undefined, undefined, true) + update.mockImplementation(async (key: string, value: unknown) => { + layers[key] = value as string[] + }) + + // The state copy is the store the import writes, so both writers record into it. + const stateCopy: Record = {} + let stateWriteStarted!: () => void + const stateWriteStart = new Promise((resolve) => { + stateWriteStarted = resolve + }) + let releaseStateWrite!: () => void + const stateWriteGate = new Promise((resolve) => { + releaseStateWrite = resolve + }) + let stateWrites = 0 + vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key, value) => { + stateWrites += 1 + if (stateWrites === 1) { + stateWriteStarted() + await stateWriteGate + } + stateCopy[key] = value as string[] + }) + // The shared double predates the import's own proxy writes, so this case installs + // the members it needs on its own proxy rather than widening the double. + const proxy = mockClineProvider.contextProxy as unknown as { + setValues: (values: Record) => Promise + setProviderSettings: (settings: unknown) => Promise + } + proxy.setValues = vi.fn(async (values) => { + Object.assign(stateCopy, values) + }) + proxy.setProviderSettings = vi.fn(async () => undefined) + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => stateCopy[key]) + + ;(fs.readFile as unknown as Mock).mockResolvedValue( + JSON.stringify({ + providerProfiles: { + currentApiConfigName: "imported-profile", + apiConfigs: { + "imported-profile": { + apiProvider: providerIdentifiers.openai, + apiKey: "test-key", + id: "imported-id", + }, + }, + }, + globalSettings: { allowedCommands: ["imported"] }, + }), + ) + + // The import path, its lock, and its command-list writes are the real ones. The + // provider-profile and custom-mode stores are doubles, because they read VS Code + // secrets and workspace files that this harness does not open — neither touches the + // lock or the command lists, and the file carries no custom modes. + type ImportOptions = Parameters[1] + const providerSettings = { + export: vi.fn(async () => ({ currentApiConfigName: "prior-profile", apiConfigs: {}, modeApiConfigs: {} })), + import: vi.fn(async () => undefined), + listConfig: vi.fn(async () => []), + } + const customModes = { updateCustomMode: vi.fn(async () => undefined) } + + const save = webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"] }, + }) + + await Promise.race([ + stateWriteStart, + (async () => { + for (let turn = 0; turn < 20; turn++) { + await Promise.resolve() + } + })(), + ]) + + const imported = importSettingsFromPath("/mock/path/settings.json", { + // Each double stands in for its real collaborator's public surface only. + providerSettingsManager: providerSettings as unknown as ImportOptions["providerSettingsManager"], + contextProxy: mockClineProvider.contextProxy, + customModesManager: customModes as unknown as ImportOptions["customModesManager"], + }) + + // The save still holds the lock, so the import has not written either store. + for (let turn = 0; turn < 20; turn++) { + await Promise.resolve() + } + expect(layers["allowedCommands"]).toEqual(["git"]) + expect(stateCopy["allowedCommands"]).toBeUndefined() + + releaseStateWrite() + await save + const result = await imported + expect(result.success).toBe(true) + + // Both stores hold the imported list, because the import ran last. + expect(sanitizeCommandList(stateCopy["allowedCommands"])).toEqual(["imported"]) + expect(layers["allowedCommands"]).toEqual(["imported"]) + }) + it("holds the lock until the state write has landed", async () => { // An import that took the lock between the configuration write and the state write // would leave the two stores describing different lists. The lock's guarantee is @@ -2737,6 +2875,48 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) + it("aborts the workspace write and restores the global layer when the merge re-read returns no inspection object", async () => { + // An inspection that returns no object is not evidence about the workspace + // layer, exactly as a thrown re-read is not. Writing the list computed before + // the global write would drop an entry another writer added during it, so the + // key aborts and the global half is undone. Neither store is left ahead of the + // other. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["old"] : undefined, + ) + const { update } = mockCommandConfiguration( + { globalValue: ["old"], workspaceValue: ["docker"] }, + [undefined, undefined], + // Save start, the merge re-read that finds no object, then the undo's + // re-read, which sees this save's own global write. + [{ globalValue: ["old"], workspaceValue: ["docker"] }, null, { globalValue: ["old", "aws"] }], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "old", "aws"] }, + }) + + // The global write landed, and the unreadable re-read came before any workspace + // write, so the workspace layer is never written at all. + expect(update).toHaveBeenNthCalledWith(1, "deniedCommands", ["old", "aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // The undo removes only this save's addition, so the global layer is back to the + // value it held at save start. + expect(update).toHaveBeenNthCalledWith(2, "deniedCommands", ["old"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledTimes(2) + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to save deniedCommands: the workspace layer could not be re-read: the configuration value could not be read", + ) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + // Entries the dialog never displayed cannot be deleted by omission from a // list the user could not see. A save therefore re-adds them to the workspace // layer it rewrites. Such entries are hidden while the gate is off, or shadowed by a @@ -2834,6 +3014,106 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["git push"]) }) + it("does not warn about an allow entry the global deny layer hid", async () => { + // The same cross-key effect in the other direction: the user's global deny layer + // holds "git", so the composition drops the workspace allow "git status" from the + // dialog. The allow key's own global layer is empty, so without the other key's + // layer the classifier reads the entry's absence from the baseline as an addition. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["git"] : undefined, + ) + mockCommandConfiguration( + (key) => (key === "allowedCommands" ? { workspaceValue: ["git status"] } : { globalValue: ["git"] }), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // The dialog never showed the entry, so the submission omits it. + updatedSettings: { allowedCommands: [] }, + commandListBaseline: { allowedCommands: [], workspaceCommandListsEnabled: true }, + }) + + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("warns about a deny entry no global layer covers", async () => { + // The positive control for the caller wiring: the same save with a workspace deny + // that no global entry covers. The entry was never displayed, so it is an + // addition and the warning must name it. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git"] : undefined, + ) + mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["docker"] } : { globalValue: ["git"] }), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // The dialog never showed the entry, so the submission omits it. Nothing + // covers it, so its absence is a genuine addition. + updatedSettings: { deniedCommands: [] }, + commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, + }) + + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("docker")) + }) + + it("keeps a global entry added after display when the dialog deletes the entry it showed", async () => { + // The dialog displayed "echo" from the workspace layer, and the posted global + // layer was empty. While the dialog was open another writer added "echo" to the + // global layer. The merged baseline still names "echo", so treating it as the + // global layer too would count that addition as displayed and the omission would + // delete it. The posted global layer says it was never on screen. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration( + { globalValue: ["echo"], workspaceValue: ["echo"] }, + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + commandListBaseline: { + deniedCommands: ["echo"], + globalDeniedCommands: [], + workspaceDeniedCommands: ["echo"], + workspaceCommandListsEnabled: true, + }, + }) + + // The workspace copy was displayed and omitted, so it goes. The global copy was + // never displayed, so the save carries it instead of deleting it. + expect(update).toHaveBeenCalledWith("deniedCommands", ["echo"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + }) + + it("deletes a global entry the posted global layer showed and the submission omits", async () => { + // The other direction, so the field cannot pass by ignoring the submission: the + // posted global layer names both entries, and the user removed one of them. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + const { update } = mockCommandConfiguration({ globalValue: ["echo", "docker"] }, undefined, undefined, true) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker"] }, + commandListBaseline: { + deniedCommands: ["echo", "docker"], + globalDeniedCommands: ["echo", "docker"], + workspaceCommandListsEnabled: true, + }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["docker"], vscode.ConfigurationTarget.Global) + }) + it("keeps a gate-hidden workspace entry out of the global write when the baseline omits it", async () => { // With the gate off the dialog showed only the global layer, so the baseline // lists no workspace entry. "docker" was never displayed, so the save carries it @@ -3198,7 +3478,7 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { [undefined, Promise.reject(new Error("workspace locked"))], // Save start, merge re-read, then the undo's re-read: the last returns no // inspection object at all, which is the failed read this case pins. - [{ globalValue: ["drop"], workspaceValue: ["docker"] }, undefined, undefined], + [{ globalValue: ["drop"], workspaceValue: ["docker"] }, undefined, null], true, ) @@ -4196,10 +4476,13 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { }, }, { + // The global allow covers the workspace deny, so the composition dropped it + // from the dialog. Its absence from the baseline is display, not an addition, + // so the save carries it silently — the same reading the composition applies. name: "shadowed by a global allow while the gate is on", gateEnabled: true, hiddenEntry: "git push", - warns: true, + warns: false, prepare: () => { vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? ["git"] : undefined, diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 53018e79ea..7173c8efd4 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -76,6 +76,7 @@ import { sanitizeCommandList, splitCommandListScopes, workspaceLayerValue, + globalShadowEntries, } from "../auto-approval/commandScope" import { type RouterName, toRouterName } from "../../shared/api" import { MessageEnhancer } from "./messageEnhancer" @@ -820,6 +821,17 @@ export const webviewMessageHandler = async ( const externallyAddedCommandEntries: string[] = [] + // The composition's own shadow set, built once for the payload from the two + // state copies — the same reads `resolveEffectiveCommandLists` is given. The + // classifier applies it to each key's shadow test so an entry the other key's + // global layer hid is not reported as an addition. The state copy is the + // global layer here, so this reads no configuration and cannot add a snapshot + // to the per-key count below. + const globalShadowAtSaveStart = globalShadowEntries( + sanitizeCommandList(getGlobalState("allowedCommands")), + sanitizeCommandList(getGlobalState("deniedCommands")), + ) + for (const [key, value] of Object.entries(updatedSettings)) { // An invalid display value is ignored, before anything is done for it. if (isInvalidDisplayValue(key, value)) { @@ -925,6 +937,7 @@ export const webviewMessageHandler = async ( currentScopes, configGlobalAtSaveStart, gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, + globalShadowAtSaveStart, }) // The flat baseline is the merged pair, so it names a global entry the // workspace layer never showed. The dialog's per-layer field is the only @@ -934,6 +947,14 @@ export const webviewMessageHandler = async ( key === "allowedCommands" ? message.commandListBaseline?.workspaceAllowedCommands : message.commandListBaseline?.workspaceDeniedCommands + // The global layer's own field, for the same reason: the merged baseline + // cannot say whether a global entry was on screen when the dialog opened. + // Without it an entry another writer added since display counts as shown, + // and the submission's omission deletes it. + const globalDisplayed = + key === "allowedCommands" + ? message.commandListBaseline?.globalAllowedCommands + : message.commandListBaseline?.globalDeniedCommands const { writableGlobal, writableWorkspace, displayedGlobal, displayedWorkspace } = displayedCommandListScopes({ baseline, @@ -943,6 +964,7 @@ export const webviewMessageHandler = async ( workspaceNow: currentScopes.workspace, gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, workspaceDisplayed, + globalDisplayed, seededEntries: seededGlobalEntries, }) // Both displayed sets, from the same call that applied the deletions: an @@ -980,9 +1002,15 @@ export const webviewMessageHandler = async ( let workspaceReReadFailure: string | undefined try { const freshInspection = config.inspect(key) - // No inspection object is no evidence about the layer, so the - // precomputed list stands rather than counting as a removal. - if (freshInspection !== undefined) { + // No inspection object is no evidence about the layer, and the + // save cannot tell an entry another writer added during the + // global write from one it already saw. This is therefore the + // same situation as a thrown re-read: the key aborts and the + // outer catch undoes the global half, so neither store is left + // holding a list computed before that write. + if (freshInspection === undefined) { + workspaceReReadFailure = "the configuration value could not be read" + } else { // Read the target layer's own value, not the layer that wins. // `selectWorkspaceCommandListLayer` answers which layer wins, so a // folder override appearing mid-save makes it report the folder diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index 91f06faa8d..9a95c4df7b 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -189,6 +189,30 @@ const commandListWriteLanded = (baselined: string[], sent: string[], refreshed?: ) } +// A global write landed when the refreshed global layer holds every entry the dialog +// kept on screen there and none of the entries it dropped. The merged judgement above +// cannot answer this on its own: a workspace copy keeps a dropped entry in the merged +// list, so a global deletion that did land reads as failed. Without a posted global +// layer, or with nothing displayed in it, there is no evidence either way and the +// merged judgement stands alone. +const globalLayerWriteLanded = ( + displayedGlobal: string[] | undefined, + sent: string[], + refreshedGlobal: string[] | undefined, +): boolean => { + if (displayedGlobal === undefined || refreshedGlobal === undefined || displayedGlobal.length === 0) { + return false + } + + const keptGlobally = displayedGlobal.filter((entry) => sent.includes(entry)) + const droppedGlobally = displayedGlobal.filter((entry) => !sent.includes(entry)) + + return ( + keptGlobally.every((entry) => refreshedGlobal.includes(entry)) && + droppedGlobally.every((entry) => !refreshedGlobal.includes(entry)) + ) +} + export interface SettingsViewRef { checkUnsaveChanges: (then: () => void) => void } @@ -289,11 +313,19 @@ const SettingsView = forwardRef(({ onDone, t heldSaveResult.current = undefined settleSave.current?.(held.success) }, [extensionState]) - // Records the baseline, the lists and the buffer generation of the save the host - // must answer. The save-result effect reconciles each list against its own write - // outcome. + // Records the baseline, the lists, the global layer they were displayed beside, and + // the buffer generation of the save the host must answer. The save-result effect + // reconciles each list against its own write outcome. const submittedListSave = useRef< - { baselined: [string[], string[]]; sent: [string[], string[]]; generation: number } | undefined + | { + baselined: [string[], string[]] + sent: [string[], string[]] + // The global layer each list was displayed against. A later post or a + // discard rewrites the stamp, so the settle cannot read it from there. + globalBaselined: [string[] | undefined, string[] | undefined] + generation: number + } + | undefined >(undefined) // What the dialog last displayed, so a later post counts as an external @@ -651,6 +683,7 @@ const SettingsView = forwardRef(({ onDone, t submittedListSave.current = { baselined: [lastDisplayedAllowed, lastDisplayedDenied], sent: [allowedCommands ?? [], deniedCommands ?? []], + globalBaselined: [displayedGlobalAllowed, displayedGlobalDenied], // The buffer this save owns. A reset after this line invalidates it, so // the settle writes no baseline for a buffer the user has discarded. generation: baselineGeneration.current, @@ -683,6 +716,12 @@ const SettingsView = forwardRef(({ onDone, t // less the global layer posted with it: a global entry appears in both. workspaceAllowedCommands: workspaceDisplayedEntries(lastDisplayedAllowed, displayedGlobalAllowed), workspaceDeniedCommands: workspaceDisplayedEntries(lastDisplayedDenied, displayedGlobalDenied), + // The global layer itself, so the save can tell a displayed global entry + // from one another writer added after the dialog opened. An absent stamp + // layer stays absent rather than becoming an empty one, which the save + // reads as "the sender cannot say". + globalAllowedCommands: displayedGlobalAllowed, + globalDeniedCommands: displayedGlobalDenied, }, updatedSettings: { language, @@ -832,7 +871,21 @@ const SettingsView = forwardRef(({ onDone, t : baselined const allowedWriteLanded = commandListWriteLanded(save.baselined[0], save.sent[0], refreshedAllowed) const deniedWriteLanded = commandListWriteLanded(save.baselined[1], save.sent[1], refreshedDenied) - const everyEditedWriteLanded = allowedWriteLanded && deniedWriteLanded + // Each list's write landed if the merged list agrees or the global layer does. + // The second reading is what lets a global deletion clear the hold while a + // workspace copy keeps the dropped entry in the merged list. + const allowedGlobalLanded = globalLayerWriteLanded( + save.globalBaselined[0], + save.sent[0], + latestExtensionState.current.globalAllowedCommands, + ) + const deniedGlobalLanded = globalLayerWriteLanded( + save.globalBaselined[1], + save.sent[1], + latestExtensionState.current.globalDeniedCommands, + ) + const everyEditedWriteLanded = + (allowedWriteLanded || allowedGlobalLanded) && (deniedWriteLanded || deniedGlobalLanded) // A restored baseline keeps the global layer it was displayed beside. The // posted layer is that baseline's own only when the write landed, which is // the same condition that keeps the advanced baseline above. An absent diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx index e7d9b1e183..7fd2899eb9 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -807,6 +807,9 @@ describe("SettingsView - Allowed Commands", () => { deniedCommands: [], workspaceAllowedCommands: ["git"], workspaceDeniedCommands: [], + // The global layer the dialog showed beside those lists. + globalAllowedCommands: [], + globalDeniedCommands: [], }, updatedSettings: expect.objectContaining({ allowedCommands: ["git", "npm test"] }), }), @@ -884,6 +887,8 @@ describe("SettingsView - Allowed Commands", () => { workspaceCommandListsEnabled: true, workspaceAllowedCommands: ["git"], workspaceDeniedCommands: [], + globalAllowedCommands: [], + globalDeniedCommands: [], }, updatedSettings: expect.not.objectContaining({ workspaceCommandListsEnabled: expect.anything(), @@ -933,6 +938,10 @@ describe("SettingsView - Allowed Commands", () => { workspaceCommandListsEnabled: true, workspaceAllowedCommands: ["git"], workspaceDeniedCommands: [], + // The gate flipped during the held-back edit, but the lists and the + // global layer they were displayed beside are the stamped ones. + globalAllowedCommands: [], + globalDeniedCommands: [], }, }), ) @@ -977,6 +986,8 @@ describe("SettingsView - Allowed Commands", () => { workspaceCommandListsEnabled: true, workspaceAllowedCommands: ["git", "curl"], workspaceDeniedCommands: [], + globalAllowedCommands: [], + globalDeniedCommands: [], }, updatedSettings: expect.objectContaining({ allowedCommands: ["git", "curl"] }), }), @@ -1014,6 +1025,9 @@ describe("SettingsView - Allowed Commands", () => { // list equals the global layer, so the derived share is empty. workspaceAllowedCommands: [], workspaceDeniedCommands: [], + // The global layer itself is still posted, and it holds the entry. + globalAllowedCommands: ["git"], + globalDeniedCommands: [], }, updatedSettings: expect.not.objectContaining({ workspaceCommandListsEnabled: expect.anything() }), }), diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 2a67be31c2..5b905e9c12 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -1337,12 +1337,12 @@ describe("SettingsView - Unsaved Changes Detection", () => { const saveId = lastSaveRequestId(postMessage) expect(saveId).toBeDefined() - // The global write landed, but the merged list still holds "echo" from the - // workspace copy, so the merged list's own write is judged not landed. + // The merged list still holds "echo" from the workspace copy, so the merged + // write is judged not landed. The refresh posts no global layer, so the save has + // no per-layer evidence and the merged judgement is the only one it can make. ;(useExtensionState as ReturnType).mockReturnValue({ ...defaultExtensionState, allowedCommands: ["echo", "ls"], - globalAllowedCommands: [], workspaceCommandListsEnabled: true, showRelativeTimes: false, }) @@ -2112,4 +2112,65 @@ describe("SettingsView - Unsaved Changes Detection", () => { expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["docker"])), ) }) + + it("clears the hold when a global deletion lands and a workspace copy keeps the entry in the merged list", async () => { + // Global and workspace both hold "echo". The dialog shows one merged entry and + // the user deletes it. The global write lands, so the global layer no longer + // holds "echo" — but the workspace copy keeps it in the merged list, which is + // the pair the host posts. Judging the save on the merged list alone keeps the + // hold up, and the retry then re-sends the deletion from the restored baseline. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + globalAllowedCommands: ["echo"], + workspaceCommandListsEnabled: true, + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, allowedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(allowedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // The buffered list edit is itself what asks the host for an answer, so no + // unrelated display change is needed to route this save through the settle. + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + // The premise: the save's baseline is the list the dialog displayed, so the + // submission's empty list is a deletion the settle has to judge. + expect(updateSettingsPosts()[0].commandListBaseline).toEqual( + expect.objectContaining({ allowedCommands: ["echo"], workspaceAllowedCommands: [] }), + ) + + // The global layer lost "echo" while the workspace copy still holds it, so the + // merged list repeats the entry the dialog deleted and gains one from a third + // writer. The added entry is what distinguishes this post from the dispatched + // lists, so the settle runs against it instead of holding the answer. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + globalAllowedCommands: [], + workspaceCommandListsEnabled: true, + showRelativeTimes: false, + }) + view.rerender() + answerSave(saveId, { success: true }) + + // The hold clears on the global layer's own evidence, so the settle releases the + // lists and leaves the form clean. Judging on the merged list alone keeps the hold, + // which leaves Save enabled until the timeout settles the save as failed. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) + expect(updateSettingsPosts()).toHaveLength(1) + }) }) From 22a9a191a634b867da4a3651b2e25c6913841f74 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Wed, 2 Dec 2026 21:20:26 +0100 Subject: [PATCH 47/52] fix: read the live command lists when deciding command approval The command approval path read the allowed and denied command lists from a copy of the extension global state. That copy is made one time at startup. A user level entry added to deniedCommands after startup did not reach the check, so a denied command could still run. A repository allow entry could also beat a user level deny entry. The check now reads the user level values at decision time. A new function, readLiveGlobalCommandList in src/core/auto-approval/commandScope.ts, reads the global value through inspect(). The composition in src/core/auto-approval/index.ts calls it for both keys. The startup copy is the fallback. If the lookup throws, returns no value, or returns a value that is not an array, the check uses the copy. Approval then behaves as before instead of losing the global layer. The change adds no configuration listener. The read happens inside the decision, so an edit made after startup needs no event to be seen. The save path keeps its own snapshot read, because a save must compare against one configuration state. Three cases in src/core/auto-approval/__tests__/commandScope.spec.ts pin the behavior: a user level deny over a workspace allow, a live allow over a stale copy, and the fallback when the lookup throws. --- .../__tests__/commandScope.spec.ts | 113 ++++++++++++++++++ src/core/auto-approval/commandScope.ts | 36 ++++++ src/core/auto-approval/index.ts | 9 +- 3 files changed, 156 insertions(+), 2 deletions(-) diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index 713defba14..cf385a9bb8 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -751,6 +751,46 @@ function mockFolderConfigurations(scripts: Record, +) { + vi.mocked(vscode.workspace.getConfiguration).mockImplementation( + (_section?: string, scope?: vscode.ConfigurationScope | null) => { + const entry = scripts[scope && "fsPath" in scope ? scope.fsPath : ""] + if (entry?.throws) { + throw new Error("configuration unavailable") + } + const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: entry?.gate ?? false }) + vi.mocked(config.inspect).mockImplementation((key: string) => { + const layer = + key === "deniedCommands" ? entry?.deny : key === "allowedCommands" ? entry?.allow : undefined + const userLayer = + key === "deniedCommands" + ? entry?.userDeny + : key === "allowedCommands" + ? entry?.userAllow + : undefined + return { key, globalValue: userLayer, workspaceFolderValue: layer } + }) + return config + }, + ) +} + // Raw global layers are empty, so every decision comes from the folder layer // and can only be right for one folder. The baked pair on the state holds // values no folder composes, so a check that consumes it decides differently. @@ -1091,6 +1131,79 @@ it("checkAutoApproval command: decides a command in a filesystem-root workspace expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, rootUri) }) +// Enforcement reads the user-level layer live. The state copy is what activation +// seeded, so it is stale the moment the user edits their own settings.json. +// These cases pin both halves: the live value decides when it can be read, and +// the state copy decides when it cannot. + +it("checkAutoApproval command: enforces a user-level deny the state copy does not hold, over a workspace allow", async () => { + vi.clearAllMocks() + const { folderA } = openMultiRootWindow() + workspaceState.workspaceFolders = [{ uri: folderA }] + // The state copy was seeded before the user added "docker" to their own + // deniedCommands, so it holds no deny. The repository's committed allow holds + // "docker". Reading the live layer is what lets the user's deny decide. + mockFolderConfigurationsWithUserLayers({ + [folderA.fsPath]: { gate: true, userDeny: ["docker"], allow: ["docker"] }, + }) + + const result = await checkAutoApproval({ + state: { ...taskFolderState(["docker"]), globalAllowedCommands: [], globalDeniedCommands: [] }, + cwd: folderA.fsPath, + ask: "command", + text: "docker ps", + }) + + expect(result).toEqual({ + decision: "deny", + autoDeny: { kind: "denylist", command: "docker ps", pattern: "docker" }, + }) +}) + +it("checkAutoApproval command: takes the live user-level allow over a stale state copy", async () => { + vi.clearAllMocks() + const { folderA } = openMultiRootWindow() + workspaceState.workspaceFolders = [{ uri: folderA }] + // The state copy still holds an allow the user has since removed, and no deny + // matches. Only the live layer decides, so a check that consumed the copy + // would approve a command the user's current settings leave to the prompt. + mockFolderConfigurationsWithUserLayers({ + [folderA.fsPath]: { gate: true, userAllow: [], deny: [] }, + }) + + const result = await checkAutoApproval({ + state: { ...taskFolderState([]), globalAllowedCommands: ["echo"], globalDeniedCommands: [] }, + cwd: folderA.fsPath, + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + +it("checkAutoApproval command: falls back to the state copy when the user-level lookup throws", async () => { + vi.clearAllMocks() + const { folderA } = openMultiRootWindow() + workspaceState.workspaceFolders = [{ uri: folderA }] + // An unreadable configuration must not widen approvals. The state copy's deny + // is the only rule left, and it decides, exactly as it did before the live read. + mockFolderConfigurationsWithUserLayers({ + [folderA.fsPath]: { gate: true, throws: true }, + }) + + const result = await checkAutoApproval({ + state: { ...taskFolderState([]), globalAllowedCommands: [], globalDeniedCommands: ["docker"] }, + cwd: folderA.fsPath, + ask: "command", + text: "docker ps", + }) + + expect(result).toEqual({ + decision: "deny", + autoDeny: { kind: "denylist", command: "docker ps", pattern: "docker" }, + }) +}) + it("checkAutoApproval command: decides each sub-command of a chain by its own matching layer", async () => { vi.clearAllMocks() const { folderA, folderB } = openMultiRootWindow() diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 470433753a..6cb78173cf 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -297,6 +297,42 @@ export function readCommandListScopes( return { global, workspace, merged } } +/** + * Reads the user-level command list as it stands at decision time. + * + * Enforcement asks here on every decision, because the state copy it also holds + * is baked from extension global state that is seeded once at activation. A + * user who edits the list in their own settings.json afterwards would otherwise + * be judged by the value from startup. The settings save path keeps its + * snapshot instead: it hands {@link readCommandListScopes} a pre-write + * inspection so one save compares against one configuration state, and a live + * read there would judge the save against a layer edited mid-save. + * + * The state copy is the fallback. A lookup that throws, reports no value, or + * reports a non-array cannot be read, and falling back keeps enforcement + * working from the value it already has rather than from an empty layer. + * + * @param configKey - The extension configuration key to read. + * @param stateCopy - The seeded copy to use when the live read is unavailable. + * @param folderResource - Workspace folder to scope to. `undefined` keeps the + * first-folder default. + * @returns The live user-level list, or the state copy when it cannot be read. + */ +export function readLiveGlobalCommandList( + configKey: CommandListConfigKey, + stateCopy: string[] | undefined, + folderResource?: vscode.Uri, +): string[] { + try { + const inspected = commandListConfiguration(folderResource).inspect(configKey) + return Array.isArray(inspected?.globalValue) + ? sanitizeCommandList(inspected.globalValue) + : sanitizeCommandList(stateCopy) + } catch { + return sanitizeCommandList(stateCopy) + } +} + export interface CommandListWriteScopes { globalWrite: string[] workspaceWrite: string[] diff --git a/src/core/auto-approval/index.ts b/src/core/auto-approval/index.ts index 4777d6baf2..decb8d111c 100644 --- a/src/core/auto-approval/index.ts +++ b/src/core/auto-approval/index.ts @@ -30,6 +30,7 @@ import { commandListFolderForResource, getEffectiveCommandDecision, readCommandListScopes, + readLiveGlobalCommandList, resolveEffectiveCommandLists, workspaceCommandListsEnabled, } from "./commandScope" @@ -453,13 +454,17 @@ export async function checkAutoApproval({ ? resolveEffectiveCommandLists( readCommandListScopes( "allowedCommands", - state.globalAllowedCommands, + readLiveGlobalCommandList( + "allowedCommands", + state.globalAllowedCommands, + commandFolder, + ), undefined, commandFolder, ), readCommandListScopes( "deniedCommands", - state.globalDeniedCommands, + readLiveGlobalCommandList("deniedCommands", state.globalDeniedCommands, commandFolder), undefined, commandFolder, ), From abc0f4d2dd307093a540a76b5595623ac030826d Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Wed, 2 Dec 2026 21:21:24 +0100 Subject: [PATCH 48/52] fix: post the raw command layers and normalize an import once Three repairs to the command list paths that surround the approval change. The webview state now carries the raw global command list layers. getStateToPostToWebview in src/core/webview/ClineProvider.ts posted only the composed pair, so the settings dialog had no way to tell a global entry from a workspace entry. It stamps its save baseline from the posted state, and that baseline was therefore always empty. The projection now posts globalAllowedCommands and globalDeniedCommands beside the composed lists, taken from the same getState() value the enforcement path reads. Two cases in src/core/webview/__tests__/ClineProvider.spec.ts pin it: the raw pair differs from the composed pair, and an unset global layer posts as an empty list rather than undefined. The import write path now sanitizes each key once and restores exactly the keys it wrote. In src/core/config/importExport.ts, writeImportedCommandLists sanitizes each imported key into one local and returns the normalized map. The settings file and the extension state copy both receive that same list, so an entry such as ["echo", " "] lands as ["echo"] in both stores and in the returned settings. The rollback key list is now built from that map after the write, not predicted before it, so a failure that stops before the state write restores nothing instead of overwriting a concurrent writer's value with a stale snapshot. Three test integrity repairs. Each replaced an assertion that could not fail for the reason it claimed, so each now can. The lock case in src/core/config/__tests__/importExport.spec.ts queued its later writer only after releasing its deferred promise and failed on a constant string mismatch, which proves nothing about the lock; it now queues the writer before the forced failure, reports that failure by its own token, and asserts the later writer ran on the same lock instance. The lock release case in src/core/webview/__tests__/webviewMessageHandler.spec.ts released the real lock outside a finally, so a failed assertion stranded the holder; it now releases in a finally and has a case that fails on purpose to prove the queued import still settles. The settle case in webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx asserted only a disabled button and a post count, which a timed-out settle also satisfies; it now asserts the adopted list contents, plus a witness case that drives the timeout and shows the buffered deletion stays on screen. --- .../config/__tests__/importExport.spec.ts | 139 +++++++++++++-- src/core/config/importExport.ts | 53 ++++-- src/core/webview/ClineProvider.ts | 7 + .../webview/__tests__/ClineProvider.spec.ts | 37 ++++ .../__tests__/webviewMessageHandler.spec.ts | 163 +++++++++++++++++- .../SettingsView.unsaved-changes.spec.tsx | 84 ++++++++- 6 files changed, 438 insertions(+), 45 deletions(-) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 6e4191405e..60a2a92c3d 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -1044,13 +1044,95 @@ describe("importExport", () => { // the next save resurrects it from the configuration. expect(layers.allowedCommands).toEqual(["git"]) expect(layers.deniedCommands).toEqual(["prior-deny"]) - // The state half never ran, so the snapshot is what both keys hold again. + // The state half never ran, so nothing is restored: a restore here would + // rewrite lists this import never wrote, overwriting a concurrent writer's + // value with the snapshot taken before the configuration half began. + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("allowedCommands", expect.anything()) + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("deniedCommands", expect.anything()) + expect(state.allowedCommands).toEqual(["git"]) + expect(state.deniedCommands).toEqual(["prior-deny"]) + }) + + it("restores exactly the keys the configuration half wrote when the state write rejects", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue( + validProfileFile({ allowedCommands: ["git", "imported"], deniedCommands: ["rm -rf"] }), + ) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + + // Both keys land in the configuration, so the state write runs and rejects + // with both keys already written. + mockLayeredCommandListConfig({ allowedCommands: ["git"], deniedCommands: ["prior-deny"] }) + mockContextProxy.setValues.mockRejectedValue(new Error("state write failed")) + + const state: { allowedCommands?: string[]; deniedCommands?: string[] } = { + allowedCommands: ["git"], + deniedCommands: ["prior-deny"], + } + vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" + ? state.allowedCommands + : key === "deniedCommands" + ? state.deniedCommands + : undefined, + ) + mockContextProxy.setValue.mockImplementation(async (key, value) => { + if (key === "allowedCommands") state.allowedCommands = value as string[] + if (key === "deniedCommands") state.deniedCommands = value as string[] + }) + + const result = await importSettingsFromPath(filePath, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + expect(result.success).toBe(false) + // The restore set is the configuration half's observed keys, so both are + // put back. A derivation that came back empty would leave the imported + // lists in the state copy after a reported failure. expect(mockContextProxy.setValue).toHaveBeenCalledWith("allowedCommands", ["git"]) expect(mockContextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["prior-deny"]) expect(state.allowedCommands).toEqual(["git"]) expect(state.deniedCommands).toEqual(["prior-deny"]) }) + it("lands a normalized list in both stores and in the returned settings", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue( + validProfileFile({ allowedCommands: ["echo", " "], deniedCommands: ["rm -rf", " "] }), + ) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + + const { layers } = mockLayeredCommandListConfig({}) + const state: { allowedCommands?: string[]; deniedCommands?: string[] } = {} + mockContextProxy.setValues.mockImplementation(async (values) => { + if (Array.isArray(values.allowedCommands)) state.allowedCommands = values.allowedCommands + if (Array.isArray(values.deniedCommands)) state.deniedCommands = values.deniedCommands + }) + + const result = await importSettingsFromPath(filePath, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + if (!result.success) { + throw new Error(`import failed: ${result.error}`) + } + + // The blank entry is dropped by `sanitizeCommandList`, and both stores + // receive that one normalized list. A second sanitize pass would leave the + // state copy holding the verbatim `["echo", " "]`. + expect(layers.allowedCommands).toEqual(["echo"]) + expect(state.allowedCommands).toEqual(["echo"]) + expect(result.globalSettings?.allowedCommands).toEqual(["echo"]) + expect(layers.deniedCommands).toEqual(["rm -rf"]) + expect(state.deniedCommands).toEqual(["rm -rf"]) + }) + it("keeps the imported list when the prior global layer could not be read", async () => { const filePath = "/mock/path/settings.json" ;(fs.readFile as Mock).mockResolvedValue(validProfileFile({ allowedCommands: ["git", "imported"] })) @@ -1245,37 +1327,60 @@ describe("importExport", () => { }) it("frees the lock for a later writer when an assertion fails while the holder is parked", async () => { - // The holder parks inside the lock, and the assertion inside the guarded - // region is forced to fail. The release is in a `finally`, so the holder - // still settles and the next writer gets the lock. Without it the lock stays - // held by a test that already failed, and every later writer in this file - // waits on a gate nothing will resolve. + // The holder parks inside the lock, and a second writer is queued before the + // release, so the lock's held state is observed from the queue. const gate = createDeferred() - void withCommandListLock(async () => { + let holderInside = false + const holder = withCommandListLock(async () => { + holderInside = true await gate.promise }) - await flushMacrotasks() - let assertionFailure: unknown + let laterWriterRan = false + let laterWriterSawHolderInside: boolean | undefined + const laterWriter = withCommandListLock(async () => { + laterWriterSawHolderInside = holderInside + laterWriterRan = true + }) + + let assertionFailure: Error | undefined + // An assertion inside the guarded region, forced to fail. The release below + // must run anyway, and this is the failure the case reports. + const deliberateFailureMessage = "the queued writer ran while the holder was parked" try { - expect("the lock is held here").toBe("the lock was not held here") + await flushMacrotasks() + expect(holderInside).toBe(true) + // The probe states the observed fact: the queued writer has not run, so + // the lock is held. Asserting the opposite is the deliberate failure this + // case is built around. + expect(laterWriterRan, deliberateFailureMessage).toBe(true) } catch (error) { - assertionFailure = error + assertionFailure = error instanceof Error ? error : undefined } finally { + // The release is unconditional. A failed assertion above must not leave + // the holder parked, because the lock is shared by every later writer in + // this file and they would all queue behind a gate nothing resolves. gate.resolve() } - expect(assertionFailure).toBeDefined() + // The deliberate failure is reported by its own token, so a different error + // raised inside the held window cannot satisfy this case. + expect(assertionFailure).toBeInstanceOf(Error) + expect(assertionFailure?.message).toContain(deliberateFailureMessage) - // Bounded, so a stranded lock reports a named failure instead of hanging the - // case. A free lock lets the queued writer run inside the microtask flush. - const laterWriterRan = await Promise.race([ - withCommandListLock(async () => true), + await holder + // Bounded, so a stranded lock reports a named failure instead of hanging + // the case. A released lock lets the queued writer run. + const ranAfterRelease = await Promise.race([ + laterWriter.then(() => true), (async () => { await flushMacrotasks() return false })(), ]) - expect(laterWriterRan).toBe(true) + expect(ranAfterRelease).toBe(true) + // The later writer saw the holder inside, so it was serialised behind this + // holder instead of running on a fresh lock beside it. + expect(laterWriterSawHolderInside).toBe(true) }) it("holds a second import back until the first released the lock", async () => { diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 31ceb2a6d4..dd49bd9a2d 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -177,8 +177,9 @@ async function applySettingsImport( // written after a successful import, so it needs no restore; the two command-list // stores are written below, and these hold the copies the failure path puts back. let priorStateCopy: Pick | undefined - // The command-list keys this import writes into extension state. Empty until the - // snapshot is taken, because the settings are not parsed before then. + // The command-list keys this import wrote into extension state. Empty until the + // configuration half records a key, so a failure before that write restores + // nothing rather than a snapshot of keys this import never touched. let stateCommandListKeys: readonly (keyof Pick)[] = [] let importedCommandLists: ImportedCommandListWrite[] = [] @@ -271,23 +272,28 @@ async function applySettingsImport( allowedCommands: contextProxy.getValue("allowedCommands"), deniedCommands: contextProxy.getValue("deniedCommands"), } - // The state write is one `setValues` call, so the command-list keys it can - // touch are exactly the ones the settings carry as arrays. The same predicate - // gates `writeImportedCommandLists`, so the restore below names the keys the - // import wrote rather than both keys of the snapshot. A provider-only import - // therefore rewrites no list and reports no restore error for one. - stateCommandListKeys = (["allowedCommands", "deniedCommands"] as const).filter((key) => - Array.isArray(sanitizedGlobalSettings[key]), - ) - // The configuration half comes first, matching the save's order. With one // order, the two writers cannot interleave into stores that disagree, and a // failure below can undo this half against a fresh read. The helper appends // to this array as each key lands, so the catch below sees a partial write. importedCommandLists = [] - await writeImportedCommandLists(sanitizedGlobalSettings, importedCommandLists) - - await contextProxy.setValues(sanitizedGlobalSettings) + const normalizedCommandLists = await writeImportedCommandLists(sanitizedGlobalSettings, importedCommandLists) + + // The restore set names the keys the configuration half landed, not a pair + // predicted from the settings. A failure before that write leaves this empty, + // so it restores nothing and cannot overwrite a concurrent writer's value with + // a snapshot of keys this import never touched. + stateCommandListKeys = Object.keys(normalizedCommandLists) as (keyof Pick< + GlobalSettings, + "allowedCommands" | "deniedCommands" + >)[] + + // Both stores receive the same normalized list. The helper sanitizes each key + // once and returns the result, so an entry such as `["echo", " "]` lands as + // `["echo"]` in the settings file and in the state copy, instead of the two + // stores holding lists that differ only by the normalization. + const globalSettingsToPersist: GlobalSettings = { ...sanitizedGlobalSettings, ...normalizedCommandLists } + await contextProxy.setValues(globalSettingsToPersist) // Set the current provider. const currentProviderName = providerProfiles.currentApiConfigName @@ -305,7 +311,7 @@ async function applySettingsImport( return { providerProfiles, - globalSettings: sanitizedGlobalSettings, + globalSettings: globalSettingsToPersist, success: true, warnings: warnings.length > 0 ? warnings : undefined, } @@ -508,12 +514,15 @@ interface ImportedCommandListWrite { * * @param globalSettings - The sanitized settings the import file carried. * @param written - The caller's accumulator. A key is appended after its write resolves. + * @returns The normalized list for each key this function wrote, so the caller + * writes the state copy from the same list the settings file received. */ async function writeImportedCommandLists( globalSettings: GlobalSettings | undefined, written: ImportedCommandListWrite[], -): Promise { +): Promise>> { const config = commandListConfiguration() + const normalizedLists: Partial> = {} for (const key of ["allowedCommands", "deniedCommands"] as const) { const imported = globalSettings?.[key] @@ -521,6 +530,11 @@ async function writeImportedCommandLists( continue } + // One sanitize pass feeds both the settings-file write and the state write. + // Sanitizing twice lets the two stores disagree on a value such as + // `["echo", " "]`, which the state copy would keep verbatim. + const importedList = sanitizeCommandList(imported) + let priorLayer: string[] | undefined let priorLayerUnknown = false try { @@ -534,11 +548,14 @@ async function writeImportedCommandLists( priorLayerUnknown = true } - await config.update(key, sanitizeCommandList(imported), vscode.ConfigurationTarget.Global) + await config.update(key, importedList, vscode.ConfigurationTarget.Global) // Appended after the write resolves, so the rollback's baseline and its // `globalWriteApplied: true` describe a write that landed. - written.push({ key, imported: sanitizeCommandList(imported), priorLayer, priorLayerUnknown }) + written.push({ key, imported: importedList, priorLayer, priorLayerUnknown }) + normalizedLists[key] = importedList } + + return normalizedLists } /** diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index cf8ec314ce..bea6cebfd1 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3185,6 +3185,8 @@ export class ClineProvider alwaysDenyUnapprovedCommands, allowedCommands, deniedCommands, + globalAllowedCommands, + globalDeniedCommands, workspaceCommandListsEnabled: gateEnabled, alwaysAllowMcp, alwaysAllowModeSwitch, @@ -3377,6 +3379,11 @@ export class ClineProvider // These lists are never undefined; getState() resolves them. allowedCommands, deniedCommands, + // Raw global layers, before the workspace composition above. The settings + // dialog stamps its save baseline from these, so a save can tell a global + // entry the dialog never showed apart from one it did. + globalAllowedCommands, + globalDeniedCommands, workspaceCommandListsEnabled: gateEnabled ?? DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, soundVolume: soundVolume ?? 0.5, writeDelayMs: writeDelayMs ?? DEFAULT_WRITE_DELAY_MS, diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 7f4b8f5649..64ff0444c2 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4437,6 +4437,43 @@ describe("ClineProvider", () => { expect(state.deniedCommands).toEqual(["curl", "pnpm"]) }) + test("getStateToPostToWebview posts the raw global command lists, not the composed pair", async () => { + await provider.resolveWebviewView(mockWebviewView) + await provider.contextProxy.setValue("allowedCommands", ["git"]) + await provider.contextProxy.setValue("deniedCommands", ["curl"]) + const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) + config.inspect = vi.fn().mockImplementation((key: string) => ({ + key, + workspaceValue: key === "allowedCommands" ? ["docker"] : ["pnpm"], + })) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + const state = await provider.getStateToPostToWebview() + + // The dialog stamps its save baseline from these two fields, so they must carry + // the global layer alone. The "not" half stops the composed pair passing as raw: + // a save fed the composed lists reports a workspace entry as one it displayed. + expect(state.globalAllowedCommands).toEqual(["git"]) + expect(state.globalDeniedCommands).toEqual(["curl"]) + expect(state.globalAllowedCommands).not.toEqual(state.allowedCommands) + expect(state.globalDeniedCommands).not.toEqual(state.deniedCommands) + }) + + test("getStateToPostToWebview posts empty raw global lists when only the workspace layer is set", async () => { + await provider.resolveWebviewView(mockWebviewView) + mockGateConfiguration(true) + + const state = await provider.getStateToPostToWebview() + + // An empty list is an observation, not an absent one: the save path falls back to + // the merged baseline when the field is undefined, so an unset global layer that + // posted undefined would report the workspace entry as shown at display. + expect(state.globalAllowedCommands).toEqual([]) + expect(state.globalDeniedCommands).toEqual([]) + expect(state.allowedCommands).toEqual(["docker"]) + expect(state.allowedCommands).not.toEqual(state.globalAllowedCommands) + }) + test("getState reads the raw global command lists after its awaits, so a save during them is kept", async () => { await provider.contextProxy.setValue("allowedCommands", ["git"]) await provider.contextProxy.setValue("deniedCommands", ["curl"]) diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index d376acc54f..ce34fc097d 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2228,6 +2228,22 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { return { update, inspect } } + // A promise the case needs to settle stays pending forever when the lock that would + // resolve it is never released, and a pending await is reported as a suite timeout + // instead of the assertion that failed. Racing a microtask budget turns that hang + // into a value the case can assert on by name. + async function settlesWithin(work: Promise, turns: number): Promise<"settled" | "still-held"> { + const settled = work.then(() => "settled" as const) + const budget = (async () => { + for (let turn = 0; turn < turns; turn++) { + await Promise.resolve() + } + return "still-held" as const + })() + + return Promise.race([settled, budget]) + } + it("takes the command-list lock only for a payload that writes a command list", async () => { // A payload with no command-list key writes neither store the lock orders, so it // must not take the lock and stall an import behind an unrelated save. @@ -2350,16 +2366,28 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { contextProxy: mockClineProvider.contextProxy, customModesManager: customModes as unknown as ImportOptions["customModesManager"], }) - - // The save still holds the lock, so the import has not written either store. - for (let turn = 0; turn < 20; turn++) { - await Promise.resolve() + // The import can reject once a release lets it run, so a case that fails before + // awaiting this promise must not also report an unhandled rejection. + void imported.catch(() => undefined) + + // The save still holds the lock, so the import has not written either store. The + // release runs in `finally` because a failing assertion would otherwise leave the + // save parked on its state write, and the case would hang until the suite timed + // out instead of reporting the assertion that failed. + try { + for (let turn = 0; turn < 20; turn++) { + await Promise.resolve() + } + expect(layers["allowedCommands"]).toEqual(["git"]) + expect(stateCopy["allowedCommands"]).toBeUndefined() + } finally { + releaseStateWrite() } - expect(layers["allowedCommands"]).toEqual(["git"]) - expect(stateCopy["allowedCommands"]).toBeUndefined() - - releaseStateWrite() await save + + // The release above is what lets the queued import run, so an import that never + // settles means the release did not reach the real lock. + expect(await settlesWithin(imported, 500)).toBe("settled") const result = await imported expect(result.success).toBe(true) @@ -2368,6 +2396,125 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { expect(layers["allowedCommands"]).toEqual(["imported"]) }) + it("releases the real lock when an assertion fails inside the held window", async () => { + // A failing assertion inside the held window must not strand the module's lock. + // The save is parked on its state write and the import queues behind it, so a + // lock left held hangs the queued writer instead of reporting the failure. This + // case throws on purpose and then proves the failure it surfaces is the thrown + // assertion, and that the queued import still drains. + const { importSettingsFromPath, withCommandListLock: realCommandListLock } = + await vi.importActual("../../config/importExport") + + vi.mocked(withCommandListLock).mockImplementation(realCommandListLock) + + const layers: Record = {} + const { update } = mockCommandConfiguration({ globalValue: ["git"] }, undefined, undefined, true) + update.mockImplementation(async (key: string, value: unknown) => { + layers[key] = value as string[] + }) + + const stateCopy: Record = {} + let stateWriteStarted!: () => void + const stateWriteStart = new Promise((resolve) => { + stateWriteStarted = resolve + }) + let releaseStateWrite!: () => void + const stateWriteGate = new Promise((resolve) => { + releaseStateWrite = resolve + }) + let stateWrites = 0 + vi.mocked(mockClineProvider.contextProxy.setValue).mockImplementation(async (key, value) => { + stateWrites += 1 + if (stateWrites === 1) { + stateWriteStarted() + await stateWriteGate + } + stateCopy[key] = value as string[] + }) + vi.mocked(mockClineProvider.contextProxy.setValues).mockImplementation(async (values) => { + Object.assign(stateCopy, values) + }) + vi.mocked(mockClineProvider.contextProxy.setProviderSettings).mockResolvedValue(undefined) + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => stateCopy[key]) + + // `fs` is a module mock whose static type is the real `fs`, so the mock members do + // not survive `vi.mocked`; the cast is the only way to reach `mockResolvedValue`. + ;(fs.readFile as unknown as Mock).mockResolvedValue( + JSON.stringify({ + providerProfiles: { + currentApiConfigName: "imported-profile", + apiConfigs: { + "imported-profile": { + apiProvider: providerIdentifiers.openai, + apiKey: "test-key", + id: "imported-id", + }, + }, + }, + globalSettings: { allowedCommands: ["imported"] }, + }), + ) + + type ImportOptions = Parameters[1] + const providerSettings = { + export: vi.fn(async () => ({ currentApiConfigName: "prior-profile", apiConfigs: {}, modeApiConfigs: {} })), + import: vi.fn(async () => undefined), + listConfig: vi.fn(async () => []), + } + const customModes = { updateCustomMode: vi.fn(async () => undefined) } + + const save = webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"] }, + }) + // A failure below leaves this promise unawaited, so its rejection is handled here + // and surfaces only through the assertions this case makes. + void save.catch(() => undefined) + + await Promise.race([ + stateWriteStart, + (async () => { + for (let turn = 0; turn < 20; turn++) { + await Promise.resolve() + } + })(), + ]) + + // The two doubles stand in for collaborators whose real classes this harness does + // not construct: `providerSettingsManager` supplies only `export`/`import`/`listConfig` + // and `customModesManager` only `updateCustomMode`, which is every member the import + // path reaches. + const imported = importSettingsFromPath("/mock/path/settings.json", { + providerSettingsManager: providerSettings as unknown as ImportOptions["providerSettingsManager"], + contextProxy: mockClineProvider.contextProxy, + customModesManager: customModes as unknown as ImportOptions["customModesManager"], + }) + void imported.catch(() => undefined) + + let failedAssertion: Error | undefined + try { + expect(layers["allowedCommands"]).toEqual(["git"]) + expect(stateCopy["allowedCommands"]).toBeUndefined() + // The deliberate failure. Its token is what the assertion below looks for, so + // a different failure inside the window cannot satisfy this case by accident. + expect(layers["allowedCommands"]).toEqual(["deliberate assertion failure"]) + } catch (error) { + failedAssertion = error instanceof Error ? error : undefined + } finally { + releaseStateWrite() + } + + expect(failedAssertion).toBeInstanceOf(Error) + expect(failedAssertion?.message).toContain("deliberate assertion failure") + + // The release ran even though the block threw. A lock left held leaves the save + // parked on its state write and the import queued behind it, so both are raced + // against a microtask budget and report "still-held" instead of hanging. + expect(await settlesWithin(save, 500)).toBe("settled") + expect(await settlesWithin(imported, 500)).toBe("settled") + await save + }) + it("holds the lock until the state write has landed", async () => { // An import that took the lock between the configuration write and the state write // would leave the two stores describing different lists. The lock's guarantee is diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 5b905e9c12..6a81efc916 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -2165,12 +2165,92 @@ describe("SettingsView - Unsaved Changes Detection", () => { showRelativeTimes: false, }) view.rerender() + + // Before the answer, the buffered deletion still owns the list: the post's added + // entry stays off screen and the pending save keeps Save disabled. + expect(screen.getByTestId("current-allow-list")).toHaveTextContent(JSON.stringify([])) + expect(screen.getByTestId("save-button")).toBeDisabled() + answerSave(saveId, { success: true }) // The hold clears on the global layer's own evidence, so the settle releases the - // lists and leaves the form clean. Judging on the merged list alone keeps the hold, - // which leaves Save enabled until the timeout settles the save as failed. + // lists and adopts the post's list. A failed or timed-out settle keeps the buffered + // deletion on screen instead, which is the pair this assertion separates. + await waitFor(() => + expect(screen.getByTestId("current-allow-list")).toHaveTextContent(JSON.stringify(["echo", "ls"])), + ) await waitFor(() => expect(screen.getByTestId("save-button")).toBeDisabled()) expect(updateSettingsPosts()).toHaveLength(1) + + // A later host post still reaches the dialog, so the list hold is gone rather than + // merely masked by a clean form. A hold left up would keep the new entry off screen. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls", "pwd"], + globalAllowedCommands: [], + workspaceCommandListsEnabled: true, + showRelativeTimes: false, + }) + view.rerender() + await waitFor(() => + expect(screen.getByTestId("current-allow-list")).toHaveTextContent(JSON.stringify(["echo", "ls", "pwd"])), + ) + expect(screen.getByTestId("save-button")).toBeDisabled() + }) + + it("keeps the held deletion on screen when the save times out instead of releasing the post's list", async () => { + // The witness for the settle above: a timed-out settle leaves Save disabled and the + // post count at one, so those two observations alone cannot tell a released hold + // from a timeout. The released hold adopts the post's list; a timeout keeps the + // buffered deletion, so the adopted contents are what separate the two paths. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo"], + globalAllowedCommands: ["echo"], + workspaceCommandListsEnabled: true, + }) + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, allowedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(allowedCommands)} + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + fireEvent.click(await screen.findByTestId("clear-allow-list")) + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + + // Fake timers start before Save, because the timeout is armed by the save's own effect. + vi.useFakeTimers() + fireEvent.click(screen.getByTestId("save-button")) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + + // The post carrying this save's lists lands, but the answer never arrives. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + allowedCommands: ["echo", "ls"], + globalAllowedCommands: [], + workspaceCommandListsEnabled: true, + showRelativeTimes: false, + }) + view.rerender() + + await act(async () => { + await vi.advanceTimersByTimeAsync(SAVE_ANSWER_TIMEOUT_MS) + }) + vi.useRealTimers() + + // The timeout settles the save as failed, so the hold stays and the buffered + // deletion remains on screen rather than adopting the post's ["echo", "ls"]. + await waitFor(() => expect(screen.getByTestId("save-button")).toBeEnabled()) + expect(screen.getByTestId("current-allow-list")).toHaveTextContent(JSON.stringify([])) + expect(updateSettingsPosts()).toHaveLength(1) }) }) From 1d12fc031321777a89100bd57c2988d925b32517 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Wed, 2 Dec 2026 23:12:31 +0100 Subject: [PATCH 49/52] test: release held gates in finally so a failed assertion cannot hang the next test Five tests in four spec files held a gate or a lock open across an assertion and released it on the next line. When the assertion failed, the release never ran. The gate or lock stayed held, and the next test waited on it until the suite timed out. The failure was then reported as a timeout, not as the assertion that failed. Each release now runs in a finally block. A failed assertion still fails the test, and the gate or lock is released before the test ends. Two sites in importExport.spec.ts parked an import inside the real command-list lock. That lock is shared by every later writer in the file, so a stranded release did not only affect the failing test. Sites changed: - extension.spec.ts: one deferred promise now serves every shutdown call, and it is released in finally. The test waits for activation to settle before it resets the mock. - importExport.spec.ts: the import write, the dialog answer, and the first import are released in finally. - ClineProvider.spec.ts: the custom-modes release runs in finally. - webviewMessageHandler.spec.ts: the state write is settled in finally. No test assertion was weakened and no test case was removed. --- src/__tests__/extension.spec.ts | 22 +++++++---- .../config/__tests__/importExport.spec.ts | 39 +++++++++++++------ .../webview/__tests__/ClineProvider.spec.ts | 11 ++++-- .../__tests__/webviewMessageHandler.spec.ts | 17 +++++--- 4 files changed, 62 insertions(+), 27 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index b6ec9b19e9..b10abd457b 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -712,17 +712,21 @@ describe("extension.ts", () => { const teardownOrder: string[] = [] const { TelemetryService } = await import("@roo-code/telemetry") const shutdown = vi.mocked(TelemetryService.instance.shutdown) - // Activation may reject only after the awaited teardown settles. - let settleShutdown: () => void = () => {} + // Activation may reject only after the awaited teardown settles. One deferred + // serves every shutdown call, so the test body and the cleanup path settle the + // same gate; a throw above the explicit release must not leave it pending. + let releaseShutdown: () => void = () => {} + const shutdownGate = new Promise((resolve) => { + releaseShutdown = resolve + }) shutdown.mockImplementation(() => { teardownOrder.push("telemetry-shutdown") - return new Promise((resolve) => { - settleShutdown = resolve - }) + return shutdownGate }) + let activation: Promise | undefined try { const { activate } = await import("../extension") - const activation = activate(mockContext) + activation = activate(mockContext) let rejected = false void activation.catch(() => { rejected = true @@ -734,9 +738,13 @@ describe("extension.ts", () => { // The catch must not propagate before teardown completes. expect(rejected).toBe(false) - settleShutdown() + releaseShutdown() await expect(activation).rejects.toThrow("seed state write failed") } finally { + // Settle the gate before the reset, so activation always finishes and the + // next test never inherits a teardown suspended by a failed assertion. + releaseShutdown() + await activation?.catch(() => {}) shutdown.mockReset() } }) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 60a2a92c3d..f404298acb 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -1206,10 +1206,16 @@ describe("importExport", () => { saveObserved = fileHolds }) - await flushMacrotasks() - expect(saveObserved).toBe("not-yet") + try { + await flushMacrotasks() + expect(saveObserved).toBe("not-yet") + } finally { + // The release is unconditional. A failed assertion above must not leave the + // import parked inside the command-list lock, because that lock is shared by + // every later writer in this file and they would all queue behind it. + importWrite.resolve() + } - importWrite.resolve() await imported await save @@ -1234,13 +1240,18 @@ describe("importExport", () => { // The save runs to completion while the dialog is still unanswered. let saveCompleted = false - await withCommandListLock(async () => { - saveCompleted = true - }) - expect(saveCompleted).toBe(true) + try { + await withCommandListLock(async () => { + saveCompleted = true + }) + expect(saveCompleted).toBe(true) + } finally { + // The release is unconditional. An unanswered dialog would otherwise leave + // the import pending with nothing left to settle it. + dialog.resolve(undefined) + } - // Answering the dialog now lets the import take the lock and proceed. - dialog.resolve(undefined) + // Answering the dialog lets the import take the lock and proceed. await imported }) @@ -1395,9 +1406,15 @@ describe("importExport", () => { }) await flushMacrotasks() - expect(secondRan).toBe(false) + try { + expect(secondRan).toBe(false) + } finally { + // The release is unconditional. A failed assertion above must not leave the + // first import parked inside the command-list lock, because that lock is + // shared by every later writer in this file and they would all queue behind it. + first.resolve() + } - first.resolve() await Promise.all([firstImport, secondImport]) expect(secondRan).toBe(true) }) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 64ff0444c2..1181263f79 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4490,9 +4490,14 @@ describe("ClineProvider", () => { }) const pendingState = provider.getState() - await provider.contextProxy.setValue("allowedCommands", ["docker"]) - await provider.contextProxy.setValue("deniedCommands", ["pnpm"]) - releaseCustomModes() + // The release runs in `finally`: a write that throws above it would otherwise + // leave getState parked on its held await, with nothing left to settle it. + try { + await provider.contextProxy.setValue("allowedCommands", ["docker"]) + await provider.contextProxy.setValue("deniedCommands", ["pnpm"]) + } finally { + releaseCustomModes() + } const state = await pendingState diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index ce34fc097d..52dffca00d 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2578,12 +2578,17 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { ]) // While the state write is pending, the configuration half has already landed — - // the save's fixed order — and the lock is still held. - expect(configuration["allowedCommands"]).toEqual(["git"]) - expect(stateCopy).toBeUndefined() - expect(releases).toBe(0) - - settleStateWrite() + // the save's fixed order — and the lock is still held. The release runs in + // `finally` because a failing assertion here would otherwise leave the save + // parked on its state write, and the case would hang until the suite timed out + // instead of reporting the assertion that failed. + try { + expect(configuration["allowedCommands"]).toEqual(["git"]) + expect(stateCopy).toBeUndefined() + expect(releases).toBe(0) + } finally { + settleStateWrite() + } await save // Both stores hold the submitted list, and the lock's single release happened only From 6e468c78f0589ded2e896fee0dcdbb43fa861ca4 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 3 Dec 2026 09:20:45 +0100 Subject: [PATCH 50/52] fix: treat a deleted user allow list as empty, not as the startup default The enforcement read of the user-level command lists could not tell a list the user never set from a list the user deleted. Both states reach the read as an absent key, so it fell back to the copy taken at activation in both cases. That fallback is right for the first state and wrong for the second. A user who deletes a user-level allow list expects the entries to stop being approved. With the copy still in force, the startup default remained in effect and the removed entries still received automatic approval. Setting the list to an empty array stopped the approvals; deleting the key did not. readLiveGlobalCommandList now compares the activation copy against the inspected default value for the allowedCommands key. The copy stands in only while it still equals that default, which is the shape an activation-seeded copy has and a since-removed list does not. A copy that differs records a list the user no longer holds, so the absent layer decides and no entry approves. The deniedCommands key keeps its existing fallback. An empty deny list is less restrictive than the copy's deny entries, so treating a deletion as empty there would widen approval rather than narrow it. An explicitly null value is not treated as a deletion. It is not an array, so it takes the non-array fallback that was already in place. The code comment records this decision. Three regression cases pin the two sub-cases apart and the deny-key asymmetry: a deleted key, a never-set key, and the deny key left unchanged. --- .../__tests__/commandScope.spec.ts | 86 ++++++++++++++++++- src/core/auto-approval/commandScope.ts | 41 +++++++-- 2 files changed, 118 insertions(+), 9 deletions(-) diff --git a/src/core/auto-approval/__tests__/commandScope.spec.ts b/src/core/auto-approval/__tests__/commandScope.spec.ts index cf385a9bb8..53ed1e8f28 100644 --- a/src/core/auto-approval/__tests__/commandScope.spec.ts +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -754,7 +754,9 @@ function mockFolderConfigurations(scripts: Record, @@ -784,7 +788,13 @@ function mockFolderConfigurationsWithUserLayers( : key === "allowedCommands" ? entry?.userAllow : undefined - return { key, globalValue: userLayer, workspaceFolderValue: layer } + const defaultValue = + key === "deniedCommands" + ? entry?.defaultDeny + : key === "allowedCommands" + ? entry?.defaultAllow + : undefined + return { key, globalValue: userLayer, workspaceFolderValue: layer, defaultValue } }) return config }, @@ -1204,6 +1214,78 @@ it("checkAutoApproval command: falls back to the state copy when the user-level }) }) +it("checkAutoApproval command: stops approving a removed user allow list after the key is deleted", async () => { + vi.clearAllMocks() + const { folderA } = openMultiRootWindow() + workspaceState.workspaceFolders = [{ uri: folderA }] + // The user deleted allowedCommands from their own settings. The layer reports + // no value and the shipped default still does, so the state copy is the only + // record of the removed list. It differs from the default, which is what marks + // it as a removed list rather than a seeded one, so it may not approve. + mockFolderConfigurationsWithUserLayers({ + [folderA.fsPath]: { gate: true, defaultAllow: ["git log", "git diff", "git show"] }, + }) + + const result = await checkAutoApproval({ + state: { ...taskFolderState([]), globalAllowedCommands: ["echo"], globalDeniedCommands: [] }, + cwd: folderA.fsPath, + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + +it("checkAutoApproval command: keeps the state copy's approvals when the user never set the key", async () => { + vi.clearAllMocks() + const { folderA } = openMultiRootWindow() + workspaceState.workspaceFolders = [{ uri: folderA }] + // No user layer, and the copy still equals the shipped default, so the copy is + // the value activation seeded. Equality is the whole difference from a removed + // list, and it keeps the seeded approvals in force. + mockFolderConfigurationsWithUserLayers({ + [folderA.fsPath]: { gate: true, defaultAllow: ["git log", "git diff", "git show"] }, + }) + + const state = { + ...taskFolderState([]), + globalAllowedCommands: ["git log", "git diff", "git show"], + globalDeniedCommands: [], + } + + expect(await checkAutoApproval({ state, cwd: folderA.fsPath, ask: "command", text: "git log" })).toEqual({ + decision: "approve", + }) + expect(await checkAutoApproval({ state, cwd: folderA.fsPath, ask: "command", text: "echo hi" })).toEqual({ + decision: "ask", + }) +}) + +it("checkAutoApproval command: keeps the state copy's deny entries when the user-level deny key is absent", async () => { + vi.clearAllMocks() + const { folderA } = openMultiRootWindow() + workspaceState.workspaceFolders = [{ uri: folderA }] + // The deny key ships empty, so deciding an absent deny key the way an absent + // allow key is decided would approve what the copy still denies. An absent deny + // key is also what a half-failed write leaves behind after its state half + // landed, so the copy stays authoritative. + mockFolderConfigurationsWithUserLayers({ + [folderA.fsPath]: { gate: true, defaultDeny: [] }, + }) + + const result = await checkAutoApproval({ + state: { ...taskFolderState([]), globalAllowedCommands: [], globalDeniedCommands: ["docker"] }, + cwd: folderA.fsPath, + ask: "command", + text: "docker ps", + }) + + expect(result).toEqual({ + decision: "deny", + autoDeny: { kind: "denylist", command: "docker ps", pattern: "docker" }, + }) +}) + it("checkAutoApproval command: decides each sub-command of a chain by its own matching layer", async () => { vi.clearAllMocks() const { folderA, folderB } = openMultiRootWindow() diff --git a/src/core/auto-approval/commandScope.ts b/src/core/auto-approval/commandScope.ts index 6cb78173cf..de3982f446 100644 --- a/src/core/auto-approval/commandScope.ts +++ b/src/core/auto-approval/commandScope.ts @@ -308,15 +308,30 @@ export function readCommandListScopes( * inspection so one save compares against one configuration state, and a live * read there would judge the save against a layer edited mid-save. * - * The state copy is the fallback. A lookup that throws, reports no value, or - * reports a non-array cannot be read, and falling back keeps enforcement - * working from the value it already has rather than from an empty layer. + * The state copy is the fallback for a read that failed: a lookup that throws or + * reports a non-array cannot be read, and the copy keeps enforcement working + * from the value it already holds rather than from an empty layer. + * + * An absent user layer is a successful read of nothing, which for + * `allowedCommands` is not the same event as a failed read. This branch covers + * the `undefined` `globalValue` that `inspect()` reports for a key the user + * deleted and one the user never set, so the state copy is what separates them: + * it stands in only while it still equals the inspected `defaultValue`, because + * that equality is what an activation-seeded copy has and a since-removed list + * does not. A copy that differs records a list the user no longer holds, so the + * absent layer decides and no entry approves. An explicitly `null` value is not + * a deletion here: it is not an array, so it takes the non-array fallback above. + * `deniedCommands` keeps the copy either way: an empty deny list there would + * approve commands the copy still denies, and a copy ahead of an absent deny key + * is also what a half-failed write leaves behind. * * @param configKey - The extension configuration key to read. * @param stateCopy - The seeded copy to use when the live read is unavailable. * @param folderResource - Workspace folder to scope to. `undefined` keeps the * first-folder default. - * @returns The live user-level list, or the state copy when it cannot be read. + * @returns The live user-level list; the state copy when the read failed or the + * copy still equals the shipped default; no entries when the user removed an + * allow list. */ export function readLiveGlobalCommandList( configKey: CommandListConfigKey, @@ -325,9 +340,21 @@ export function readLiveGlobalCommandList( ): string[] { try { const inspected = commandListConfiguration(folderResource).inspect(configKey) - return Array.isArray(inspected?.globalValue) - ? sanitizeCommandList(inspected.globalValue) - : sanitizeCommandList(stateCopy) + if (Array.isArray(inspected?.globalValue)) { + return sanitizeCommandList(inspected.globalValue) + } + if (inspected !== undefined && inspected.globalValue === undefined && configKey === "allowedCommands") { + // Compared sanitized on both sides: the copy leaves here sanitized, so a + // raw default would compare unequal to its own sanitized spelling. + const copy = sanitizeCommandList(stateCopy) + const shippedDefault = sanitizeCommandList(inspected.defaultValue) + const copyIsShippedDefault = + Array.isArray(inspected.defaultValue) && + shippedDefault.length === copy.length && + shippedDefault.every((entry) => copy.includes(entry)) + return copyIsShippedDefault ? copy : [] + } + return sanitizeCommandList(stateCopy) } catch { return sanitizeCommandList(stateCopy) } From 3919093ce48c428b52e40fea51f37b5c637af678 Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 3 Dec 2026 09:21:45 +0100 Subject: [PATCH 51/52] fix: release activation resources when the settings seed fails, and repair three weak tests A failed settings seed now releases the resources that activation registered before the seed step. The seed catch already shut down telemetry, cleared the trace sink and disposed the output channel, then rethrew. It did not release the network-proxy configuration listener, the TLS and fetch restore disposable that the proxy setup pushes, or the fetch-patch restore disposable that the debug proxy path pushes. The host may skip deactivate() after a failed activation, so those entries stayed registered. The catch now disposes them in reverse acquisition order before the rethrow, and the output channel keeps its own entry so the host-driven dispose stays a no-op. Three tests could not catch the regression each one names. The settings import rollback fixture rejected before it changed either list, so both final assertions began at the values they expect to see restored. The production write can commit one key and then fail on the other, which is the case the rollback exists for. The fixture now applies one imported list before it fails, and the test asserts that the import reports failure and that both stores return to their prior lists. The held-window test in the save path asserted the layers and the stored copy after the import had already returned. Without the lock, the import would still finish those writes before the assertions ran, so the test passed whether or not the lock held. It now asserts that the import has not started while the save holds the lock. The save-timeout test in the settings view advanced the timer and then asserted the settled state. A save that failed immediately after dispatch also produced that state, so the test did not show that the timeout caused the settlement. It now asserts the pending state before the timer advance and keeps the settled assertions after it. --- src/__tests__/extension.spec.ts | 34 +++++++++++++++++-- .../config/__tests__/importExport.spec.ts | 11 +++++- .../__tests__/webviewMessageHandler.spec.ts | 4 +++ src/extension.ts | 19 +++++++++++ .../SettingsView.unsaved-changes.spec.tsx | 7 ++++ 5 files changed, 72 insertions(+), 3 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index b10abd457b..5f09596889 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -287,10 +287,12 @@ describe("extension.ts", () => { let rejectingCommandListKeys: Set let settingsUpdatedHandler: ((data: Record) => void | Promise) | undefined - // Partial double: activate() reads only extensionPath, globalState and subscriptions. - const createMockContext = () => + // Partial double: activate() reads only extensionPath, globalState, subscriptions and + // extensionMode. The mode defaults to Production, where the proxy registers nothing. + const createMockContext = (extensionMode: number = 1) => ({ extensionPath: "/test/path", + extensionMode, globalState: { get: vi.fn((key: string) => globalStateValues.get(key)), // Stateful, so a later read sees what an earlier write stored, and @@ -813,6 +815,34 @@ describe("extension.ts", () => { } }) + test("releases the subscriptions registered before the seed when seeding rejects activation", async () => { + // `deactivate()` is the only other disposer, and the host may skip it after a + // failed activation. Development mode makes the proxy register its + // configuration listener and its TLS/fetch restore disposable before the + // seed runs, so both are dangling unless this path releases them. + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + rejectingCommandListKeys.add("deniedCommands") + const { TelemetryService } = await import("@roo-code/telemetry") + const shutdown = vi.mocked(TelemetryService.instance.shutdown) + shutdown.mockImplementation(() => Promise.resolve()) + // Local context, so the list holds only this activation's registrations and + // the assertion below cannot pass on an entry an earlier test pushed. + // ExtensionMode.Development is 2 in the module double above. + const context = createMockContext(2) + try { + const { activate } = await import("../extension") + await expect(activate(context)).rejects.toThrow("seed state write failed") + + // Both proxy entries were registered and then released, and the channel's + // own entry stays for the host, which is what `deactivate()` disposes. + const channel = vi.mocked(vscode.window.createOutputChannel)("Test Output") + expect(context.subscriptions).toEqual([channel]) + } finally { + shutdown.mockReset() + } + }) + test("clears the persistence trace sink before disposing the output channel when seeding rejects", async () => { // The trace sink logs through the output channel, so the failure path must // clear it before disposing the channel. The clear is proved by module state, diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index f404298acb..830612bdb8 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -1064,12 +1064,21 @@ describe("importExport", () => { // Both keys land in the configuration, so the state write runs and rejects // with both keys already written. mockLayeredCommandListConfig({ allowedCommands: ["git"], deniedCommands: ["prior-deny"] }) - mockContextProxy.setValues.mockRejectedValue(new Error("state write failed")) const state: { allowedCommands?: string[]; deniedCommands?: string[] } = { allowedCommands: ["git"], deniedCommands: ["prior-deny"], } + // The state write lands one list before it fails, as a partial write can: + // `setValues` settles each key on its own. The restore below then has a + // landed key to undo, so a restore that does nothing leaves the imported + // list in the state copy and fails this case. + mockContextProxy.setValues.mockImplementation(async (values) => { + if (Array.isArray(values.allowedCommands)) { + state.allowedCommands = values.allowedCommands + } + throw new Error("state write failed") + }) vi.mocked(mockContextProxy.getValue).mockImplementation((key: string) => key === "allowedCommands" ? state.allowedCommands diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index 52dffca00d..3ae696e161 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -2493,6 +2493,10 @@ describe("webviewMessageHandler - command list scope-aware persistence", () => { let failedAssertion: Error | undefined try { + // A queued import does not reach its first await while the lock is held, so + // `export` cannot have run yet. A bypassed lock calls it immediately, which + // is the only way this assertion can fail. + expect(providerSettings.export).not.toHaveBeenCalled() expect(layers["allowedCommands"]).toEqual(["git"]) expect(stateCopy["allowedCommands"]).toBeUndefined() // The deliberate failure. Its token is what the assertion below looks for, so diff --git a/src/extension.ts b/src/extension.ts index c0b55f599f..7f122fe222 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -194,6 +194,25 @@ export async function activate(context: vscode.ExtensionContext) { // The trace sink logs through the output channel, so clear it first: // undefined restores the default console sink. setPersistenceTraceSink(undefined) + // Everything the activation registered before the seed — the network-proxy + // configuration listener and its TLS/fetch restore disposable — is released + // here, because `deactivate()` is the only other disposer and the host may + // skip it after a failed activation. Each entry leaves the list once released, + // so a host-driven dispose that does run is a no-op. Reverse acquisition + // order, so the earliest registration goes last; the output channel's own + // entry stays, because this catch disposes it next. + for (let index = context.subscriptions.length - 1; index >= 0; index -= 1) { + const subscription = context.subscriptions[index] + if (subscription === outputChannel) { + continue + } + try { + subscription.dispose() + } catch { + // A failed teardown step is dropped: activation is already failing. + } + context.subscriptions.splice(index, 1) + } // Dispose the channel last: earlier teardown steps log through it. // A failed dispose has no sink left to report to, so it is dropped. try { diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 6a81efc916..fd306be42c 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -2242,6 +2242,13 @@ describe("SettingsView - Unsaved Changes Detection", () => { }) view.rerender() + // The pending state, observed before the timeout can run: the save is in flight + // and the buffered deletion is still what the dialog shows. A save that fails on + // its own would already be settled here, so this reading separates a timeout + // settle from an immediate failure that only happens to end in the same state. + expect(screen.getByTestId("save-button")).toBeDisabled() + expect(screen.getByTestId("current-allow-list")).toHaveTextContent(JSON.stringify([])) + await act(async () => { await vi.advanceTimersByTimeAsync(SAVE_ANSWER_TIMEOUT_MS) }) From 2d95e192c0526403d5f30e2709b409855466468d Mon Sep 17 00:00:00 2001 From: Franz Daubner Date: Thu, 3 Dec 2026 10:57:48 +0100 Subject: [PATCH 52/52] Correct three comments that named `deactivate()` as the disposer `deactivate()` never touches `context.subscriptions`. The extension host releases those subscriptions. Three comments on the seed-failure path said `deactivate()` disposes them, which sends a reader to a function that does not. They now say the teardown releases what it registered so the host does not have to, and that the host disposes the remaining channel entry when it deactivates the extension. `src/extension.ts` already words the host's role this way at the seed site. Comments only. No logic change, no assertion change, no test count change. --- src/__tests__/extension.spec.ts | 11 ++++++----- src/extension.ts | 11 ++++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 5f09596889..05227cb272 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -816,10 +816,11 @@ describe("extension.ts", () => { }) test("releases the subscriptions registered before the seed when seeding rejects activation", async () => { - // `deactivate()` is the only other disposer, and the host may skip it after a - // failed activation. Development mode makes the proxy register its - // configuration listener and its TLS/fetch restore disposable before the - // seed runs, so both are dangling unless this path releases them. + // The host disposes `context.subscriptions` only through the deactivation + // path, and it may skip that path after a failed activation. Development mode + // makes the proxy register its configuration listener and its TLS/fetch + // restore disposable before the seed runs, so both are dangling unless this + // path releases them. const vscode = await import("vscode") setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) rejectingCommandListKeys.add("deniedCommands") @@ -835,7 +836,7 @@ describe("extension.ts", () => { await expect(activate(context)).rejects.toThrow("seed state write failed") // Both proxy entries were registered and then released, and the channel's - // own entry stays for the host, which is what `deactivate()` disposes. + // own entry stays for the host, which disposes it on deactivation. const channel = vi.mocked(vscode.window.createOutputChannel)("Test Output") expect(context.subscriptions).toEqual([channel]) } finally { diff --git a/src/extension.ts b/src/extension.ts index 7f122fe222..dea085c3b9 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -196,11 +196,12 @@ export async function activate(context: vscode.ExtensionContext) { setPersistenceTraceSink(undefined) // Everything the activation registered before the seed — the network-proxy // configuration listener and its TLS/fetch restore disposable — is released - // here, because `deactivate()` is the only other disposer and the host may - // skip it after a failed activation. Each entry leaves the list once released, - // so a host-driven dispose that does run is a no-op. Reverse acquisition - // order, so the earliest registration goes last; the output channel's own - // entry stays, because this catch disposes it next. + // here so the host does not have to: the host disposes these subscriptions + // only through the deactivation path, and it may skip that path after a + // failed activation. Each entry leaves the list once released, so a + // host-driven dispose that does run is a no-op. Reverse acquisition order, so + // the earliest registration goes last; the output channel's own entry stays, + // because this catch disposes it next. for (let index = context.subscriptions.length - 1; index >= 0; index -= 1) { const subscription = context.subscriptions[index] if (subscription === outputChannel) {