diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index ef812b01bbd..afa7ceff9a2 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -57,6 +57,13 @@ export const DEFAULT_DESTRUCTIVE_COMMAND_GUARD_ENABLED = false /** Whether new root tasks get a short generated title in the background. */ export const DEFAULT_TASK_TITLE_GENERATION_ENABLED = true +/** + * 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 + /** * Whether commands that are not explicitly auto-approved are automatically * denied (with a structured reason sent to the model) instead of prompting the @@ -183,6 +190,12 @@ 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 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(), 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 4e7efff57fc..c63034a4834 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -336,6 +336,7 @@ export type ExtensionState = Pick< | "followupAutoApproveTimeoutMs" | "allowedCommands" | "deniedCommands" + | "workspaceCommandListsEnabled" | "allowedMaxRequests" | "allowedMaxCost" | "ttsEnabled" @@ -421,6 +422,15 @@ export type ExtensionState = Pick< toolRequirements?: Record // Map of tool names to their requirements (e.g. {"apply_diff": true}) cwd?: string // Current working directory + + /** + * User-scope command lists from extension global state, before the workspace + * layers compose. Auto-approval enforces these raw layers plus the task's + * folder. The merged pair follows only the window's first folder. This is + * runtime state, not a user setting: the provider writes it, never the dialog. + */ + globalAllowedCommands?: string[] + globalDeniedCommands?: string[] telemetrySetting: TelemetrySetting telemetryKey?: string // Salted SHA-256 hash of vscode.env.machineId (see hashDistinctId in @@ -713,9 +723,7 @@ export interface WebviewMessage { | "getDismissedUpsells" | "openMarkdownPreview" | "updateSettings" - | "allowedCommands" | "getTaskWithAggregatedCosts" - | "deniedCommands" | "openDebugApiHistory" | "openDebugUiHistory" | "downloadErrorDiagnostics" @@ -773,7 +781,6 @@ export interface WebviewMessage { stepIndex?: number isLaunchAction?: boolean forceShow?: boolean - commands?: string[] audioType?: AudioType serverName?: string toolName?: string @@ -862,6 +869,43 @@ export interface WebviewMessage { codebaseIndexOpenRouterApiKey?: string } updatedSettings?: RooCodeSettings + /** + * The lists as the dialog last showed them, sent with the save that rewrites + * 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. 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 + /** + * 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[] + /** + * 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 /** Origin of each part of `text`. Absent or not matching `text` means all generated. */ diff --git a/src/__tests__/extension.spec.ts b/src/__tests__/extension.spec.ts index 446b08fff60..05227cb272e 100644 --- a/src/__tests__/extension.spec.ts +++ b/src/__tests__/extension.spec.ts @@ -22,7 +22,9 @@ vi.mock("vscode", () => ({ registerTextDocumentContentProvider: vi.fn(), getConfiguration: vi.fn().mockReturnValue({ get: vi.fn().mockReturnValue([]), + inspect: vi.fn(), }), + onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })), createFileSystemWatcher: vi.fn().mockReturnValue({ onDidCreate: vi.fn(), onDidChange: vi.fn(), @@ -44,6 +46,7 @@ vi.mock("vscode", () => ({ }, ExtensionMode: { Production: 1, + Development: 2, }, })) @@ -84,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()), @@ -234,15 +281,28 @@ describe("extension.ts", () => { const activationTestTimeout = 90_000 let mockContext: vscode.ExtensionContext + let globalStateValues: Map + // Keys whose write must reject, so the real seed helper's failure path runs + // against the Memento boundary rather than a module double. + 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().mockReturnValue(undefined), - update: vi.fn(), + get: vi.fn((key: string) => globalStateValues.get(key)), + // Stateful, so a later read sees what an earlier write stored, and + // rejectable per key, so one seed can fail after the other succeeded. + update: vi.fn(async (key: string, value: unknown) => { + if (rejectingCommandListKeys.has(key)) { + throw new Error("seed state write failed") + } + globalStateValues.set(key, value) + }), }, subscriptions: [], }) as unknown as vscode.ExtensionContext @@ -250,6 +310,8 @@ describe("extension.ts", () => { beforeEach(() => { vi.clearAllMocks() + globalStateValues = new Map() + rejectingCommandListKeys = new Set() mockContext = createMockContext() settingsUpdatedHandler = undefined @@ -562,6 +624,400 @@ describe("extension.ts", () => { expect(dotenv.config).toHaveBeenCalledTimes(1) }) + describe("command-list activation seeding", () => { + function setConfigScope( + vscode: typeof import("vscode"), + scope: { globalValue?: string[]; workspaceValue?: string[]; deniedGlobalValue?: string[]; gate?: boolean }, + ) { + 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) => { + if (key === "workspaceCommandListsEnabled") { + return gate + } + return key === "allowedCommands" ? [...(globalValue ?? []), ...(workspaceValue ?? [])] : undefined + }), + // 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, + // The override test must show the package default stays unseeded, not absent. + defaultValue: ["git log", "git diff", "git show"], + globalValue, + workspaceValue, + }, + ), + update: vi.fn(), + // This double scripts shapes the shared helper cannot express. + } 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(), + // 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 () => { + // A seed rejection must fail activation before the registry initializes. The + // host may skip deactivate(), and only it releases the registry's listeners. + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + const order: string[] = [] + vi.mocked(mockContext.globalState.update).mockImplementation(async (key: string, value: unknown) => { + order.push(`seed:${key}`) + globalStateValues.set(key, value) + }) + + 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) + }) + + test("aborts activation before the terminal registry is initialized when seeding rejects", async () => { + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + rejectingCommandListKeys.add("deniedCommands") + + 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 reaches the host unchanged; nothing downstream runs. + expect(TerminalRegistry.initialize).not.toHaveBeenCalled() + expect(ClineProvider).not.toHaveBeenCalled() + }) + + test("shuts down the telemetry service before propagating a seed rejection", async () => { + // The seed runs after telemetry registers. The host may skip `deactivate()` on + // a failed activation, so this path must shut telemetry down itself. + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + rejectingCommandListKeys.add("deniedCommands") + 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. 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 shutdownGate + }) + let activation: Promise | undefined + try { + const { activate } = await import("../extension") + activation = activate(mockContext) + let rejected = false + void activation.catch(() => { + rejected = true + }) + + // The failure path runs the awaited teardown exactly once. + await vi.waitFor(() => expect(teardownOrder).toEqual(["telemetry-shutdown"])) + + // The catch must not propagate before teardown completes. + expect(rejected).toBe(false) + + 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() + } + }) + + test("logs a rejected telemetry shutdown without masking the seed rejection", async () => { + // A rejecting shutdown must be logged, and the seed error must still + // reach the host as the activation failure. + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + rejectingCommandListKeys.add("deniedCommands") + const teardownOrder: string[] = [] + 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 { activate } = await import("../extension") + + await expect(activate(mockContext)).rejects.toThrow("seed state write failed") + + // 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", + ) + // The shutdown step still runs on this path. + expect(teardownOrder).toEqual(["telemetry-shutdown"]) + } finally { + shutdown.mockReset() + } + }) + + test("disposes the output channel last when seeding rejects activation", async () => { + // The host may skip `deactivate()` on a failed activation, so this path must + // dispose the channel itself. It goes last, because earlier teardown steps log + // through it. + const vscode = await import("vscode") + setConfigScope(vscode, { globalValue: ["git"], deniedGlobalValue: ["docker"] }) + rejectingCommandListKeys.add("deniedCommands") + const teardownOrder: string[] = [] + const { TelemetryService } = await import("@roo-code/telemetry") + const shutdown = vi.mocked(TelemetryService.instance.shutdown) + shutdown.mockImplementation(() => { + teardownOrder.push("telemetry-shutdown") + return Promise.resolve() + }) + try { + // The fixed-object factory double returns the same channel that `activate` + // creates. Arming dispose then observes the 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: channel first, so disposed last. + expect(teardownOrder).toEqual(["telemetry-shutdown", "channel-disposed"]) + expect(channel.dispose).toHaveBeenCalledExactlyOnceWith() + // The failure-path dispose must not drop the subscriptions entry. + expect(mockContext.subscriptions).toContain(channel) + } finally { + shutdown.mockReset() + } + }) + + test("releases the subscriptions registered before the seed when seeding rejects activation", async () => { + // 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") + 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 disposes it on deactivation. + 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, + // 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 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(() => { + persistenceTrace.tracePersistenceEvent("shutdown") + return Promise.resolve() + }) + try { + // The same channel `activate` creates, from the same factory double. + const channel = vi.mocked(vscode.window.createOutputChannel)("Test Output") + 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. + 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() + consoleLog.mockRestore() + setPersistenceTraceSink.mockRestore() + } + }) + + test("keeps a stored allow list when the deny-list seed write fails", async () => { + // The two seeds are separate awaited calls, so the allow write lands before + // the deny write fails. Activation still aborts. + 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") + + expect(globalStateValues.get("allowedCommands")).toEqual(["git"]) + expect(globalStateValues.get("deniedCommands")).toBeUndefined() + }) + + 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. 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") + + rejectingCommandListKeys.clear() + vi.mocked(mockContext.globalState.update).mockClear() + + // 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") + + 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 () => { + // A successful activation owns the telemetry client until deactivate(). + 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") + // Gate on: the workspace list replaces the default, so the seed must not + // re-grant what it removed. The seed module's own spec covers gate-off. + setConfigScope(vscode, { workspaceValue: ["docker"], gate: true }) + + 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"]) + }) + + 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", () => { 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 00000000000..53ed1e8f28c --- /dev/null +++ b/src/core/auto-approval/__tests__/commandScope.spec.ts @@ -0,0 +1,2645 @@ +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" +import * as vscode from "vscode" + +import { Package } from "../../../shared/package" +import { makeUri, makeWorkspaceConfiguration } from "../../../test-utils/vscode" +import { + type CommandListInspection, + classifyCommandListBaseline, + commandListFolderForResource, + displayedCommandListScopes, + getEffectiveCommandDecision, + readCommandListScopes, + resolveEffectiveCommandLists, + resolveWorkspaceWriteTarget, + rollbackFailedCommandListWrite, + splitCommandListScopes, + workspaceCommandListsEnabled, + workspaceLayerValue, +} from "../commandScope" +import { getSingleCommandDecision } from "../commands" +import { checkAutoApproval } from "../index" +import { baseState, type State } from "./fixtures" + +// Double for `vscode.workspace.workspaceFolders`. The module mock reads +// this object, so a test changes the open folders without a new mock. +// `foldersByPath` backs `getWorkspaceFolder`, so a test controls which cwd +// resolves to which root. `throwsOnFoldersRead` makes the getter fail once, +// which stands for a workspace that cannot answer the lookup. +const workspaceState = vi.hoisted(() => ({ + workspaceFolders: undefined as { uri: unknown }[] | undefined, + foldersByPath: new Map(), + throwsOnFoldersRead: false, +})) + +// Double for `fs.realpathSync`. Only this binding is replaced. Every other fs +// call stays real, and the manifest and real-filesystem tests use +// `importOriginal`. The double resolves each path to itself: the mock roots +// exist on no filesystem, and an unresolvable root gives no folder layer. +// Tests that need other behavior script the double. +const fsState = vi.hoisted(() => ({ + // The real implementations, saved by the mock so a test can delegate to them. + realRealpathSync: null as null | ((target: string) => string), + realRealpathSyncNative: null as null | ((target: string) => string), +})) + +vi.mock("fs", async (importOriginal) => { + const actual = await importOriginal() + fsState.realRealpathSync = (target: string) => String(actual.realpathSync(target)) + fsState.realRealpathSyncNative = (target: string) => String(actual.realpathSync.native(target)) + // Production resolves a workspace root with `fs.realpathSync.native`, and + // this spec scripts `fs.realpathSync`. One function object serves both + // spellings, so a scripted behavior reaches the production call. + const realpathSyncBase = vi.fn((target: string): string => String(target)) + const realpathSync: typeof realpathSyncBase & { native: typeof realpathSyncBase } = Object.assign( + realpathSyncBase, + { native: realpathSyncBase }, + ) + // Interop: production code imports the default export, this spec imports 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) +} + +/** The unmocked `fs.realpathSync.native`, which reports the on-disk spelling. */ +function realPathNative(target: string): string { + if (!fsState.realRealpathSyncNative) { + throw new Error("the fs module mock did not capture the unmocked realpathSync.native") + } + return fsState.realRealpathSyncNative(target) +} + +vi.mock("vscode", () => ({ + ConfigurationTarget: { + Global: 1, + 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() { + if (workspaceState.throwsOnFoldersRead) { + // One throw only, like the test it serves. A second throw would fail every + // later read, including the first-folder default the composition performs. + workspaceState.throwsOnFoldersRead = false + throw new Error("workspace unavailable") + } + return workspaceState.workspaceFolders + }, + getConfiguration: vi.fn(), + // Mirrors VS Code's lexical containment: a prefix test on the registered + // paths, guarded by the platform separator. The folder lookup does not use + // this double. It compares roots by real path. The double stays faithful, so + // a test can register an outer root that lexically contains a symlinked + // root's target. That outer root 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 + path.sep)) { + return { uri } + } + } + return undefined + }), + }, +})) + +interface ConfigDouble { + inspect?: { + key: string + defaultValue?: string[] + globalValue?: string[] + workspaceValue?: string[] + workspaceFolderValue?: string[] + } + effective?: string[] +} + +function mockConfiguration({ inspect, effective = [] }: ConfigDouble = {}) { + const config = makeWorkspaceConfiguration() + // The mock scripts the shared double after creation, so the fixture needs no type assertion. + vi.mocked(config.get).mockReturnValue(effective) + vi.mocked(config.inspect).mockReturnValue(inspect) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) +} + +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 get() folds globalValue into the result. Reading the workspace + // layer from get() would leak the user-only entry "npm" into that 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"]) + }) + + it("takes the workspace layer from a caller-supplied snapshot without reading the configuration", () => { + // The save path passes one captured inspection to every derivation. The + // snapshot is authoritative, so the configuration must not be read again. + 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", () => { + // 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 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"], ["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"], ["git"]) + + expect(result.workspaceWrite).toEqual([]) + expect(result.globalWrite).toEqual(["git"]) + }) + + 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"], ["docker"]) + + expect(result.workspaceWrite).toEqual(["docker"]) + expect(result.globalWrite).toEqual(["docker"]) + }) + + 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"], ["git"]) + + expect(result.workspaceWrite).toEqual([]) + expect(result.globalWrite).toEqual(["git"]) + }) + + 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"], + ["git", "docker", "pnpm docker"], + ) + + 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"], + ["docker", "git"], + ["docker", "git"], + ) + + expect(result.globalWrite).toEqual(["git", "aws", "npm"]) + }) + + 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"], + ["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"], + ["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"], ["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", () => { + beforeEach(() => { + vi.clearAllMocks() + workspaceState.workspaceFolders = undefined + }) + + 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() + }) + + it("resolves the target from a caller-supplied snapshot without reading the configuration", () => { + // The snapshot alone picks the target. A folder value the live configuration + // does not report still selects the folder target, so split, write, and + // rollback share 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") + 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"] } }) + + // No resource means no folder value, so the folder target stays unreachable. + expect(resolveWorkspaceWriteTarget("deniedCommands")).toBe(vscode.ConfigurationTarget.Workspace) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, undefined) + }, + ) +}) + +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) + 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: is off when the gate is unset", () => { + vi.clearAllMocks() + // Unset is the state of every installation that never opted in, so unset + // must read as disabled. Treating unset as enabled would widen auto-approval + // by default. The comparison against the declared default also ties this + // expectation to the constant that documents the shipped default. + 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 + // 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 makes the gate workspace-unsettable. VS Code 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: declares the command-list keys at resource scope so a folder value is readable", () => { + // An omitted scope defaults to `window`, and VS Code excludes a `window` + // setting from per-folder configuration in a multi-root workspace. The + // folder layer would then be unreadable at folder level. `resource` is the + // scope that makes a per-folder value readable. The gate stays `application` + // (asserted above), which is what keeps the feature opt-in. + const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, "../../../package.json"), "utf8")) + const properties = manifest.contributes.configuration.properties + + expect(properties["zoo-code.allowedCommands"].scope).toBe("resource") + expect(properties["zoo-code.deniedCommands"].scope).toBe("resource") +}) + +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.keptWorkspaceAllow).toEqual([]) + expect(effective.keptWorkspaceDeny).toEqual([]) +}) + +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.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", () => { + // Shadowing works in both directions. A workspace deny entry cannot decide anything the + // global allow layer 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.keptWorkspaceDeny).toEqual([]) +}) + +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.keptWorkspaceAllow).toEqual([]) +}) + +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.keptWorkspaceDeny).toEqual([]) +}) + +it("resolveEffectiveCommandLists: shadows workspace entries case-insensitively, the way the matcher matches", () => { + const effective = resolveEffectiveCommandLists( + listScopes(["Git"], ["git status"]), + listScopes([], ["DOCKER"]), + 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.keptWorkspaceAllow).toEqual([]) + expect(effective.keptWorkspaceDeny).toEqual(["DOCKER"]) +}) + +// A global entry decides every command it matches. A workspace entry applies +// only where no global entry matches, so a project file fills gaps in the +// user's policy but never outranks it. Inside one layer the longest match +// wins. Equal lengths deny, so an ambiguous case fails closed. It does not +// silently widen auto-approval. An allow win would approve commands a deny +// entry in the same layer claims. Reversing that needs a policy decision. +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: specificity decides the conflict, not a blanket deny preference. +// The longer entry wins on either side. +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 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. The global entry then decides every command it matches, and the + // workspace deny applies 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 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 deny outranks a project allow, and a + // user allow outranks a project deny. The workspace allow still decides the + // commands the user's layer does not match. + 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", so the kept workspace deny + // decides it. The global allow still decides the commands it matches. A + // global entry that matches nothing leaves the workspace layer in charge. + 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 global +// layers at the folder the task cwd resolves to. A task in another root is +// judged by that root's lists, not 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) => { + const layer = + key === "deniedCommands" ? entry?.deny : key === "allowedCommands" ? entry?.allow : undefined + return layer ? { key, workspaceFolderValue: layer } : undefined + }) + return config + }, + ) +} + +// Scripts each folder's user-level layers and workspace layer independently. +// The gate and the folder layers keep the `mockFolderConfigurations` shape, and +// the user-level layers are the values the composition must read live. A +// throwing entry stands for a configuration that cannot be read at all. The +// shipped defaults are scripted separately because an absent user layer and a +// deleted one are told apart only by comparing the state copy against them. +function mockFolderConfigurationsWithUserLayers( + scripts: Record< + string, + { + gate?: boolean + deny?: string[] + allow?: string[] + userDeny?: string[] + userAllow?: string[] + defaultDeny?: string[] + defaultAllow?: string[] + throws?: boolean + } + >, +) { + 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 + const defaultValue = + key === "deniedCommands" + ? entry?.defaultDeny + : key === "allowedCommands" + ? entry?.defaultAllow + : undefined + return { key, globalValue: userLayer, workspaceFolderValue: layer, defaultValue } + }) + 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. +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" and 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, so judging this B-rooted task + // there would deny it. Nothing allows it, so the decision is the plain prompt. + const result = await checkAutoApproval({ + state: taskFolderState(["echo"]), + cwd: folderB.fsPath, + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + +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. Consuming folder A's allow entry + // would approve a command that runs outside every workspace folder. Only the + // empty global layers judge it. The composed list carries "echo", so a check + // that fell back to it would approve the command and fail this test. + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: [], allow: ["echo"] }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + const result = await checkAutoApproval({ + state: taskFolderState(["echo"]), + cwd: "/mock/removed-folder", + ask: "command", + text: "echo hi", + }) + + expect(result).toEqual({ decision: "ask" }) +}) + +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 and ignores the + // baked pair. An absent cwd keeps the first-folder configuration, so two + // witnesses apply. The raw global allow entry decides "echo hi". A check that + // used the baked pair would find no match and fall to the prompt. Folder A's + // deny entry decides "date -u". A composition that skipped the folder + // configuration would fall to the prompt. The scope assertions pin which + // folder's configuration the composition read. + const { folderA, folderB } = openMultiRootWindow() + mockFolderConfigurations({ + [folderA.fsPath]: { gate: true, deny: ["date"] }, + [folderB.fsPath]: { gate: true, deny: ["rm"] }, + }) + + const state = { + ...taskFolderState(["baked"]), + globalAllowedCommands: ["echo"], + globalDeniedCommands: ["rm"], + } + + const globalWitness = await checkAutoApproval({ state, ask: "command", text: "echo hi" }) + expect(globalWitness).toEqual({ decision: "approve" }) + + // Neither global layer shadows "date", 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 judge 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 () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + // The global-only composition keeps the global layers authoritative. An 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" } }) +}) + +it("checkAutoApproval command: keeps the first-folder composition for a blank cwd", async () => { + vi.clearAllMocks() + const { folderA, folderB } = openMultiRootWindow() + // A blank cwd means no cwd, not an unmatched cwd. It keeps the first-folder configuration. + 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 keeps a broken lookup from failing the decision. The + // degradation must be the global-only composition, not a first-folder guess, + // which matches the fail-closed direction of an unmatched cwd. The double + // throws once, so a leak cannot change later tests. + workspaceState.throwsOnFoldersRead = true + 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 () => { + 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 name 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) +}) + +it("checkAutoApproval command: enforces the deny entries of a filesystem-root workspace folder", async () => { + vi.clearAllMocks() + // A window opened on the filesystem root ("/" or the Windows drive root) is + // a workspace folder whose children must still resolve to it. Failed + // containment there would drop the root's deny entries without a warning. + 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 a command through the layer split the composition +// carries. Where a global entry matches, the global layer decides. 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, so a merged-pair matcher cannot 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 wildcard deny matches "git status" too, but the user's allow entry + // matches it, so the global layer approves. + 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. + 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 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" }) + + // An unmatched cwd drops the workspace layer, which must not promote the + // command to an approval. With no global match, the plain prompt stands. + 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 reach enforcement for a child cwd, because + // containment keeps the layer. The global layer still outranks it on a match. + 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) +}) + +// 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: 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() + 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. + // Each sub-command is still decided by its own layer. The global allow + // approves "git status" and the workspace wildcard denies "docker ps", and + // the denial names the denied sub-command. + 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 and one not, so 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 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() + // The gate is off in both folders. The folder configuration is read, but its allow + // entry must not reach the effective lists. + mockFolderConfigurations({ + [folderA.fsPath]: { gate: false }, + [folderB.fsPath]: { gate: false, allow: ["echo"] }, + }) + + // The raw global layers keep the layered composition selected. They are empty, so the + // gated-off workspace entry is the only entry 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. Enforcement +// selects it whenever both raw global lists are present, whatever the gate. +// A fixture without them exercises the fallback, 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 approves it before any chain logic. Pinning that on the + // raw-lists path keeps the blanket branch from marking it 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 syntax-error detection of the layered path can + // stop an auto-approval of the unterminated quote. + 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 case pins both halves: the verdict as if the + // redirect were absent, and the sanitized text as the reported sub-command. + 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() + // Every sub-command is allowlisted, so only the chain-wide substitution veto can keep + // this command 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 ignores case. The reported pattern must be the stored entry, not + // the lower-cased match, so the denial names what the user's list holds. + 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 the second sub-command and the redirect-stripped text. + 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" } }) +}) + +// A directory symlink on Windows needs developer mode or elevation. A junction +// needs neither, and realpath resolves it like a POSIX link, so the fixture +// tries a symlink first and then a junction. Where neither works, the +// real-filesystem test is skipped and the scripted tests still pin the logic. +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 match nothing. These +// tests steer resolution through the double and keep the registry lists +// independent of resolution. The reset here also stops the scripted behavior +// from leaking into the manifest reads and the 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, because the folder was opened through it. The + // registered paths match nothing, so only the root's real path connects them. + 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: drops the folder layer when a registered root's 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, 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) { + throw new Error("ENOENT: no such file or directory") + } + return String(target) + }) + + expect(commandListFolderForResource(path.join(rootPath, "sub"))).toBeUndefined() +}) + +it("commandListFolderForResource: an unresolvable root keeps an enclosing root from claiming the cwd", () => { + vi.clearAllMocks() + // The inner root is registered but cannot be resolved. The outer root + // contains the cwd lexically, so a lookup that skipped the failed candidate + // would hand the cwd to the outer folder and apply its list. + const outerRoot = path.join(path.sep + "mock") + const innerRoot = path.join(outerRoot, "inner") + const outerUri = makeUri(outerRoot) + const innerUri = makeUri(innerRoot) + workspaceState.workspaceFolders = [{ uri: outerUri }, { uri: innerUri }] + vi.mocked(fs.realpathSync).mockImplementation((target) => { + if (String(target) === innerRoot) { + throw new Error("ENOENT: no such file or directory") + } + return String(target) + }) + + 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 + // 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") + workspaceState.workspaceFolders = [{ uri: makeUri(rootPath) }] + + // The sibling "root-two" shares "root" as a string prefix. Only the separator guard 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: 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: 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. A second separator would stop every + // child path from matching, which drops that folder's command-list layer. + 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() + // A registered path can end in a separator. Containment must then treat the + // separated root as its own child prefix instead of adding a second one. + 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() + 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")) }] + // Both sides arrive canonical, so their case agrees wherever the comparison applies. + // Folding case here could match a root the filesystem keeps 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 returns the first match decides differently. + 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 result is the registered Uri. Folder-scoped configuration + // resolves against the registry. The registered Uri is the one that must come + // back, not the canonicalized path. + expect(result).toBe(innerUri) + 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 holds whichever root the registry + // lists first. A lookup that kept the last candidate would return the outer + // root here. + 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 deepest-wins rule, with the other + // registration order. The deeper root comes first, so a lookup that returns + // the last match would enforce the outer folder's list. The outer entry + // allows what the deeper entry denies, so the decision names the winner. + 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" + 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 canonical cwd sits inside the link's target, and the outer + // root is also a lexical prefix of the cwd. A lookup that trusted the first + // lexical hit would enforce the outer folder's list and never read the folder + // the command 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 hold opposite lists for "echo": the outer root allows what the inner + // root denies, so the decision names the folder 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 decides the command that runs 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 reports the on-disk case of a directory created with mixed case", () => { + 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 the case of the realpath output, so this pins it + // against the real filesystem. The final component keeps the case it was + // created with, and a differently-cased spelling 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 }) + } +}) + +it.skipIf(process.platform !== "win32")( + "checkAutoApproval command: routes a differently-cased root and cwd through the production resolvers", + async () => { + vi.clearAllMocks() + const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "command-scope-case-root-")) + try { + const rootName = "MixedCase-Root" + const root = path.join(baseDir, rootName) + const taskDir = path.join(root, "sub") + fs.mkdirSync(root) + fs.mkdirSync(taskDir) + // Windows keeps one directory under any case, so the registry's spelling + // and the cwd's spelling differ while naming the same directory. Both + // resolvers must canonicalize before they compare. + const registeredRoot = root.toUpperCase() + const differentlyCasedCwd = taskDir.toUpperCase() + const rootUri = makeUri(registeredRoot) + workspaceState.workspaceFolders = [{ uri: rootUri }] + workspaceState.foldersByPath.set(registeredRoot, rootUri) + // The production resolver canonicalizes the registry entry with the native + // resolver; the cwd arrives canonical from `fs/promises.realpath`. Both + // report the on-disk spelling, which is what lets the two sides agree. + vi.mocked(fs.realpathSync).mockImplementation((target) => realPathNative(String(target))) + mockFolderConfigurations({ [registeredRoot]: { gate: true, allow: ["echo"] } }) + + const canonicalCwd = await fs.promises.realpath(differentlyCasedCwd) + expect(commandListFolderForResource(canonicalCwd)).toBe(rootUri) + + const result = await checkAutoApproval({ + state: taskFolderState([]), + cwd: canonicalCwd, + ask: "command", + text: "echo hi", + }) + + // The folder list applies, so the cwd's case did not lose the layer. + expect(result).toEqual({ decision: "approve" }) + expect(vscode.workspace.getConfiguration).toHaveBeenCalledWith(Package.name, rootUri) + } finally { + fs.rmSync(baseDir, { recursive: true, force: true }) + } + }, +) + +describe("classifyCommandListBaseline", () => { + 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"], + currentScopes: { global: [], workspace: ["aws"], merged: [] }, + configGlobalAtSaveStart: [], + gateAtDisplay: true, + }) + + expect(result.externallyAdded).toEqual(["aws"]) + }) + + // The external set spans three layers, and a submitted entry is never + // 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. + interface ExternalRow { + name: string + baseline: string[] + incoming: string[] + workspace: string[] + stateGlobal: string[] + configGlobal: string[] + expected: string[] + } + + const externalRows: ExternalRow[] = [ + { + name: "does not report a submitted entry that a workspace layer gained after display", + baseline: ["git"], + incoming: ["docker"], + workspace: ["docker"], + stateGlobal: [], + configGlobal: [], + expected: [], + }, + { + name: "reports an entry that only the state copy's global layer gained after display", + baseline: ["git"], + incoming: ["git"], + workspace: [], + stateGlobal: ["npm"], + configGlobal: [], + expected: ["npm"], + }, + { + name: "reports an entry that only the configuration's global layer held at save start", + baseline: ["git"], + incoming: ["git"], + workspace: [], + stateGlobal: [], + configGlobal: ["npm"], + expected: ["npm"], + }, + { + name: "does not report a displayed entry the submission deleted", + baseline: ["git"], + incoming: [], + workspace: ["git"], + stateGlobal: [], + configGlobal: [], + expected: [], + }, + ] + + it.each(externalRows)("$name", (row) => { + const result = classifyCommandListBaseline({ + baseline: row.baseline, + incoming: row.incoming, + currentScopes: { global: row.stateGlobal, workspace: row.workspace, merged: [] }, + configGlobalAtSaveStart: row.configGlobal, + gateAtDisplay: true, + }) + + expect(result.externallyAdded).toEqual(row.expected) + }) + + 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: [], + gateAtDisplay: false, + }) + const alsoGlobal = classifyCommandListBaseline({ + baseline: [], + incoming: [], + currentScopes: { global: [], workspace: ["docker"], merged: [] }, + configGlobalAtSaveStart: ["docker"], + gateAtDisplay: false, + }) + + expect(hiddenOnly.externallyAdded).toEqual([]) + expect(alsoGlobal.externallyAdded).toEqual(["docker"]) + }) + + it("treats a sender with no baseline as unclassified and reports nothing as externally added", () => { + const result = classifyCommandListBaseline({ + baseline: undefined, + incoming: ["git"], + currentScopes: { global: ["aws"], workspace: ["docker"], merged: [] }, + configGlobalAtSaveStart: ["aws"], + gateAtDisplay: undefined, + }) + + expect(result.externallyAdded).toEqual([]) + }) + + 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 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: [], + gateAtDisplay: true, + }) + + 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"]) + }) + + 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", () => { + 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", () => { + // 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"], + incoming: ["git"], + stateCopy: ["echo", "git"], + configGlobal: ["echo", "git"], + workspaceNow: ["echo"], + workspaceDisplayed: ["echo"], + }) + + expect(result.displayedGlobal).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 + // 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"]) + expect(result.writableWorkspace).toEqual(["git", "aws"]) + }) + + 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"], + 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("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 + // 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.writableGlobal).toEqual(["git"]) + expect(result.writableWorkspace).toEqual(["docker"]) + }) +}) + +describe("rollbackFailedCommandListWrite", () => { + it("reports that nothing needs undoing when the global write never landed", async () => { + const writeGlobalLayer = vi.fn(async () => undefined) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git"], + configGlobalAtSaveStart: [], + globalLayerAtSaveStart: undefined, + globalWriteApplied: false, + readGlobalLayer: () => { + throw new Error("must not be read") + }, + writeGlobalLayer, + }) + + expect(result).toEqual({ status: "not-applied" }) + expect(writeGlobalLayer).not.toHaveBeenCalled() + }) + + it("removes this save's own additions and restores what it removed", async () => { + // The save replaced ["git"] with ["git", "aws"]. The undo must drop "aws" + // and keep "git", and it must not re-add anything the save never removed. + const writeGlobalLayer = vi.fn(async () => undefined) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git", "aws"], + configGlobalAtSaveStart: ["git"], + globalLayerAtSaveStart: ["git"], + globalWriteApplied: true, + readGlobalLayer: () => ["git", "aws"], + writeGlobalLayer, + }) + + expect(result).toEqual({ status: "rolled-back" }) + expect(writeGlobalLayer).toHaveBeenCalledTimes(1) + expect(writeGlobalLayer).toHaveBeenCalledWith(["git"]) + }) + + it("clears the key when a third party deleted the layer mid-save", async () => { + // The layer held "git" at save start and this save removed it, so the delta + // wants to write "git" back. The re-read finds no layer at all: a later + // writer deleted the key, which is the same decision as writing `[]` but + // stated more strongly. Restoring the removed entry would resurrect a layer + // the user deleted, so the rollback clears the key. + const writeGlobalLayer = vi.fn(async () => undefined) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: [], + configGlobalAtSaveStart: ["git"], + globalLayerAtSaveStart: ["git"], + globalWriteApplied: true, + readGlobalLayer: () => undefined, + writeGlobalLayer, + }) + + expect(result).toEqual({ status: "rolled-back" }) + expect(writeGlobalLayer).toHaveBeenCalledTimes(1) + expect(writeGlobalLayer).toHaveBeenCalledWith(undefined) + expect(writeGlobalLayer).not.toHaveBeenCalledWith(["git"]) + }) + + it("restores an entry this save removed", async () => { + // The save replaced ["git", "aws"] with ["git"], so the undo must put "aws" + // back. A delta that only drops its own additions would leave the deletion. + const writeGlobalLayer = vi.fn(async () => undefined) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git"], + configGlobalAtSaveStart: ["git", "aws"], + globalLayerAtSaveStart: ["git", "aws"], + globalWriteApplied: true, + readGlobalLayer: () => ["git"], + writeGlobalLayer, + }) + + expect(result).toEqual({ status: "rolled-back" }) + expect(writeGlobalLayer).toHaveBeenCalledWith(["git", "aws"]) + }) + + it("keeps an entry a third party added mid-save", async () => { + // The re-read holds "npm", which this save never wrote. A snapshot rewind + // would delete it, so the delta must leave it in place. + const writeGlobalLayer = vi.fn(async () => undefined) + + await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git", "aws"], + configGlobalAtSaveStart: ["git"], + globalLayerAtSaveStart: ["git"], + globalWriteApplied: true, + readGlobalLayer: () => ["git", "aws", "npm"], + writeGlobalLayer, + }) + + expect(writeGlobalLayer).toHaveBeenCalledWith(["git", "npm"]) + }) + + it("clears the key when the re-read finds no layer and the undo is empty", async () => { + // The layer held "git" at save start and the save wrote the same list, so + // the delta is empty. A re-read that finds no layer means a third party + // cleared it mid-save. Writing `[]` would materialize a layer no user made. + const writeGlobalLayer = vi.fn(async () => undefined) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git"], + configGlobalAtSaveStart: ["git"], + globalLayerAtSaveStart: ["git"], + globalWriteApplied: true, + readGlobalLayer: () => undefined, + writeGlobalLayer, + }) + + expect(result).toEqual({ status: "rolled-back" }) + expect(writeGlobalLayer).toHaveBeenCalledWith(undefined) + }) + + it("does not duplicate an entry the undo both keeps and restores", async () => { + // The save removed "aws" and the re-read still holds it, so the undo meets + // "aws" twice: once in the kept fresh list and once in the removed set. + const writeGlobalLayer = vi.fn(async () => undefined) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git"], + configGlobalAtSaveStart: ["git", "aws"], + globalLayerAtSaveStart: ["git", "aws"], + globalWriteApplied: true, + readGlobalLayer: () => ["git", "aws"], + writeGlobalLayer, + }) + + expect(result).toEqual({ status: "rolled-back" }) + expect(writeGlobalLayer).toHaveBeenCalledWith(["git", "aws"]) + }) + + it("clears the key instead of materializing an empty layer", async () => { + // The layer was absent at save start and the save wrote only its own entries. + // The undo restores absence, so the activation seed still sees a user override. + const writeGlobalLayer = vi.fn(async () => undefined) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git"], + configGlobalAtSaveStart: [], + globalLayerAtSaveStart: undefined, + globalWriteApplied: true, + readGlobalLayer: () => ["git"], + writeGlobalLayer, + }) + + expect(result).toEqual({ status: "rolled-back" }) + expect(writeGlobalLayer).toHaveBeenCalledWith(undefined) + }) + + it("keeps another writer's empty layer rather than clearing it", async () => { + // The layer started absent, and another writer cleared it to `[]` mid-save. + // That clear is a decision this save must not undo. + const writeGlobalLayer = vi.fn(async () => undefined) + + await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git"], + configGlobalAtSaveStart: [], + globalLayerAtSaveStart: undefined, + globalWriteApplied: true, + readGlobalLayer: () => [], + writeGlobalLayer, + }) + + 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) + + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git"], + configGlobalAtSaveStart: [], + globalLayerAtSaveStart: undefined, + globalWriteApplied: true, + readGlobalLayer: () => { + throw new Error("configuration unavailable") + }, + writeGlobalLayer, + }) + + expect(result.status).toBe("re-read-failed") + expect(result).toMatchObject({ message: expect.stringContaining("could not be re-read to undo this save") }) + expect(writeGlobalLayer).not.toHaveBeenCalled() + }) + + it("reports a failed restore and does not claim the undo landed", async () => { + const result = await rollbackFailedCommandListWrite({ + key: "allowedCommands", + failure: "workspace write failed", + globalWrite: ["git"], + configGlobalAtSaveStart: [], + globalLayerAtSaveStart: undefined, + globalWriteApplied: true, + readGlobalLayer: () => ["git"], + writeGlobalLayer: async () => { + throw new Error("restore rejected") + }, + }) + + expect(result.status).toBe("restore-failed") + expect(result).toMatchObject({ message: expect.stringContaining("global-scoped restore also failed") }) + expect(result).not.toEqual({ status: "rolled-back" }) + }) +}) diff --git a/src/core/auto-approval/__tests__/commands.spec.ts b/src/core/auto-approval/__tests__/commands.spec.ts index bd895aa5ac4..78464c5b970 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)", () => { @@ -958,3 +964,72 @@ 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, so shadowing compares entries 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 inert padded entry must not shadow the workspace deny the matcher honors. + 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 effective. + 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", () => { + // An empty entry prefix-matches everything, so the guard stops it shadowing + // itself. Layers sanitize blanks first. + 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" 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, + 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 new file mode 100644 index 00000000000..de3982f4460 --- /dev/null +++ b/src/core/auto-approval/commandScope.ts @@ -0,0 +1,906 @@ +import fs from "fs" +import path from "path" + +import { DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED } from "@roo-code/types" +import * as vscode from "vscode" + +import { Package } from "../../shared/package" +import { + type CommandDecision, + findLongestPrefixMatch, + getSingleCommandDecision, + isShadowedByAnyEntry, +} from "./commands" + +export type CommandListConfigKey = "allowedCommands" | "deniedCommands" + +export interface CommandListScopes { + global: string[] + workspace: string[] + merged: string[] +} + +/** + * The workspace layers of one command-list key, from `inspect()`. One capture + * gives a save one consistent view for its reads, write target, and rollback. + */ +export interface CommandListInspection { + workspaceValue?: 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 + /** + * 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[] +} + +/** + * The configuration for every command-list read and write. It is scoped to + * `folderResource` when given, else to the first workspace folder. Read and + * write share this scoped path, because a `ConfigurationTarget.WorkspaceFolder` + * update is legal only on a resource-scoped configuration. + */ +export function commandListConfiguration(folderResource?: vscode.Uri): vscode.WorkspaceConfiguration { + return vscode.workspace.getConfiguration( + Package.name, + folderResource ?? vscode.workspace.workspaceFolders?.[0]?.uri, + ) +} + +/** + * Resolves the workspace folder that holds a task's `cwd`, so enforcement + * reads that folder's configuration and not the window's first folder. A child + * task inherits the parent cwd and resolves the same way. + * + * The cwd arrives canonical. The registry holds roots as opened, so the lookup + * compares each root's real path. A lexical compare alone 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 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. 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. + */ +export function commandListFolderForResource(cwd?: string): vscode.Uri | undefined { + if (!cwd) { + return undefined + } + + // 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`. + 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 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) + } + 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 + if ((cwd === rootPath || cwd.startsWith(childPrefix)) && rootPath.length > matchedLength) { + match = candidate.uri + 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 + } +} + +/** + * 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 + * resolver reports the on-disk spelling, which is what the cwd arrives as. The + * 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`. The caller then decides from + * the root's registered path whether that root can own the cwd. + */ +function realPathOrRegistered(fsPath: string): string | undefined { + try { + return fs.realpathSync.native(fsPath) + } catch { + return 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. + * + * 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. 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. + * @param inspectionOverride - A pre-write snapshot. When present the function + * uses it as-is, so a save shares one configuration state across its reads, + * target, and rollback. Without it a failed lookup gives an empty workspace + * layer. + * @param folderResource - Workspace folder to scope to. `undefined` keeps the + * first-folder default. + * @returns The per-layer lists and their deduplicated union. + */ +export function readCommandListScopes( + configKey: CommandListConfigKey, + globalList: string[] | undefined, + inspectionOverride?: CommandListInspection, + folderResource?: vscode.Uri, +): CommandListScopes { + const global = sanitizeCommandList(globalList) + + let inspected: CommandListInspection | undefined = inspectionOverride + if (inspected === undefined) { + // Guard only the lookup. 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 { + inspected = undefined + } + } + + const workspace = sanitizeCommandList(selectWorkspaceCommandListLayer(inspected).value) + + // Set union: an entry in both layers collapses to one. + const merged = [...new Set([...global, ...workspace])] + + 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 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; 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, + stateCopy: string[] | undefined, + folderResource?: vscode.Uri, +): string[] { + try { + const inspected = commandListConfiguration(folderResource).inspect(configKey) + 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) + } +} + +export interface CommandListWriteScopes { + globalWrite: string[] + workspaceWrite: string[] +} + +/** + * Splits the dialog's merged list back into the two layers that composed it, + * so a save cannot flatten workspace entries into global settings. + * + * 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. + * + * 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( + incoming: string[], + 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. 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)), + ], + } +} + +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?". + * + * 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. + * + * 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.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. + * @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 + 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)) + 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])] + + // 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) + // 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 + // 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 } +} + +/** + * Picks the configuration target that owns the current workspace layer for + * `configKey`. It reads through the same scoped configuration as + * `readCommandListScopes`, and takes the layer from + * {@link selectWorkspaceCommandListLayer}, so the target is the layer a read + * saw. + * + * - 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. + * @param inspectionOverride - A caller snapshot. When present it alone picks + * the target, so a save stays 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, + inspectionOverride?: CommandListInspection, +): vscode.ConfigurationTarget.WorkspaceFolder | vscode.ConfigurationTarget.Workspace | undefined { + let inspected: CommandListInspection | undefined = inspectionOverride + if (inspected === undefined) { + // Same guard as `readCommandListScopes`: a failure means no workspace layer. + try { + inspected = commandListConfiguration().inspect(configKey) + } catch { + inspected = undefined + } + } + + switch (selectWorkspaceCommandListLayer(inspected).layer) { + case "workspaceFolder": + return vscode.ConfigurationTarget.WorkspaceFolder + case "workspace": + return vscode.ConfigurationTarget.Workspace + default: + return undefined + } +} + +/** + * 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 + * omit, and that display did not hide. + */ + externallyAdded: string[] +} + +/** + * 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. + * + * 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. + * + * 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, 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. + * @param input.incoming - The submitted list for this key. + * @param input.currentScopes - The layers read from the state copy and the + * save-start snapshot. + * @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: { + baseline: string[] | undefined + incoming: string[] + currentScopes: CommandListScopes + configGlobalAtSaveStart: string[] + gateAtDisplay: boolean | undefined + globalShadowAtSaveStart?: string[] +}): CommandListBaselineClassification { + 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]), + ] + // 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) && + !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)) && + // 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, shadowEntries)), + ) + + return { externallyAdded } +} + +export type CommandListRollbackOutcome = + /** The global write never landed, so nothing needs undoing. */ + | { status: "not-applied" } + /** The global delta is undone, and no entry of another writer was lost. */ + | { status: "rolled-back" } + | { status: "re-read-failed"; message: string } + | { status: "restore-failed"; message: string } + +/** + * Reconciles a failed or half-applied command-list save against its own global + * write. + * + * The undo is a delta against a fresh read, so an entry a third party added + * mid-save survives. It never rewinds to a snapshot, because the configuration + * API offers no compare-and-set. + * + * @param input.key - The command-list key that failed. + * @param input.failure - The failure text of the write that threw. + * @param input.globalWrite - The global list this save attempted. + * @param input.configGlobalAtSaveStart - The configuration's global layer at + * save start, which is the delta baseline. + * @param input.globalLayerAtSaveStart - The same layer, kept as absent when the + * key had no global value. + * @param input.globalWriteApplied - Whether this save's global write landed. + * @param input.readGlobalLayer - Reads the global layer now. It may throw. + * @param input.writeGlobalLayer - Writes the global layer, or clears the key + * with `undefined`. It may reject. + * @returns The outcome. Only `rolled-back` states that the undo landed. + */ +export async function rollbackFailedCommandListWrite(input: { + key: CommandListConfigKey + failure: string + globalWrite: string[] + configGlobalAtSaveStart: string[] + globalLayerAtSaveStart: string[] | undefined + globalWriteApplied: boolean + readGlobalLayer: () => string[] | undefined + writeGlobalLayer: (value: string[] | undefined) => PromiseLike +}): Promise { + if (!input.globalWriteApplied) { + return { status: "not-applied" } + } + + const { key, failure, globalWrite, configGlobalAtSaveStart, globalLayerAtSaveStart } = input + + // 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, + // because the configuration API offers no compare-and-set. + 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. + let freshGlobalValue: string[] | undefined + try { + freshGlobalValue = input.readGlobalLayer() + } catch (reReadError) { + return { + status: "re-read-failed", + 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)), + ...(restoreRemovedByThisSave ? removedByThisSave : []), + ]), + ] + // 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) { + // 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 (ownWriteRestoresAbsence) { + await input.writeGlobalLayer(undefined) + } else { + await input.writeGlobalLayer(globalUndo) + } + } catch (restoreError) { + // The undo itself failed. The configuration keeps the partially written + // values, and the code skips the extension global-state write. Stored + // state therefore never reflects a save that did not complete. The user + // hears about both failures. + return { + status: "restore-failed", + message: `Failed to save ${key}: ${failure}. The global-scoped restore also failed: ${restoreError}. Review the command lists in your user and workspace settings.`, + } + } + + return { status: "rolled-back" } +} + +/** + * Reads the gate that decides whether workspace command lists take part in + * enforcement and display. Its manifest scope is "application", so only user + * settings change it. A failed lookup keeps the workspace layers inert. That + * result can only narrow the layers that apply, and it can never widen + * approvals. + */ +export function workspaceCommandListsEnabled(): boolean { + try { + return commandListConfiguration().get("workspaceCommandListsEnabled") === true + } catch { + return DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED + } +} + +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 that the gate and shadowing kept. They decide + * only commands that no global entry matches. + */ + keptWorkspaceAllow: string[] + /** Deny-side counterpart of {@link keptWorkspaceAllow}. */ + keptWorkspaceDeny: string[] +} + +/** + * Composes the raw per-key layers into the pair that the dialog displays and + * the layer split that {@link getEffectiveCommandDecision} matches against. + * Display and enforcement therefore share one pass. + * + * Gate off: the global layers are effective as they stand. Gate on: a + * workspace entry survives only when no global entry shadows it. Shadowing + * works both ways, so a global allow silences a workspace deny and a global + * deny silences a workspace allow. A surviving entry may overlap a global + * entry without a shadow, and the overlap is harmless because the global + * layer decides every command it matches. + * + * 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. + * @param enabled - The value of the `workspaceCommandListsEnabled` gate. + * @returns The effective allow/deny lists and the per-layer split behind them. + */ +export function resolveEffectiveCommandLists( + allowScopes: CommandListScopes, + denyScopes: CommandListScopes, + enabled: boolean, +): EffectiveCommandLists { + const globalAllow = allowScopes.global + const globalDeny = denyScopes.global + const globalEntries = globalShadowEntries(globalAllow, globalDeny) + + const keptWorkspaceAllow = enabled + ? allowScopes.workspace.filter((entry) => !isShadowedByAnyEntry(entry, globalEntries)) + : [] + const keptWorkspaceDeny = enabled + ? denyScopes.workspace.filter((entry) => !isShadowedByAnyEntry(entry, globalEntries)) + : [] + + const allowed = [...new Set([...globalAllow, ...keptWorkspaceAllow])] + const denied = [...new Set([...globalDeny, ...keptWorkspaceDeny])] + + return { allowed, denied, globalAllow, globalDeny, keptWorkspaceAllow, keptWorkspaceDeny } +} + +/** + * Decides one command. Any matching global entry decides it: a user allow + * outranks a project deny, and a user deny outranks a project allow. Workspace + * entries apply only where no global entry matches. Inside a layer the + * matcher rules hold: the longest prefix wins and an equal-length conflict + * denies. The command matcher splits chains. + * + * @param command - The single (unchained) command to decide. + * @param effective - A composition from {@link resolveEffectiveCommandLists}. + * @returns The decision from the matching layer. + */ +export function getEffectiveCommandDecision(command: string, effective: EffectiveCommandLists): CommandDecision { + // Ask the precedence question first: does the global layer match at all? + if (findLongestPrefixMatch(command, [...effective.globalAllow, ...effective.globalDeny]) !== null) { + return getSingleCommandDecision(command, effective.globalAllow, effective.globalDeny) + } + return getSingleCommandDecision(command, effective.keptWorkspaceAllow, effective.keptWorkspaceDeny) +} + +export 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/auto-approval/commands.ts b/src/core/auto-approval/commands.ts index a0620bd1a8a..221ca862cf2 100644 --- a/src/core/auto-approval/commands.ts +++ b/src/core/auto-approval/commands.ts @@ -113,6 +113,30 @@ export function findLongestPrefixMatch(command: string, prefixes: string[]): str return longestMatch } +/** + * Whether one command-list entry is covered by any entry of `shadowing`. + * + * Coverage uses the matcher's own comparison on the stored entries, with no + * trim: case-insensitive `startsWith`, and `"*"` matches all. The matcher trims + * commands but never entries. Dropping covered entries when the layers compose + * reproduces the global-decides precedence, and the matcher stays unaware of + * 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` is + * covered only by `"*"`, because it cannot be enforced and the guard keeps it + * visible. + */ +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)) + }) +} + /** * Command approval decision types. * diff --git a/src/core/auto-approval/index.ts b/src/core/auto-approval/index.ts index dc2b4fa7a85..decb8d111cc 100644 --- a/src/core/auto-approval/index.ts +++ b/src/core/auto-approval/index.ts @@ -15,9 +15,25 @@ import path from "path" import type { ApprovalFileTarget } from "../../shared/tools" 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, + readLiveGlobalCommandList, + resolveEffectiveCommandLists, + workspaceCommandListsEnabled, +} from "./commandScope" import { isFileMatchedByPatterns } from "./filePatterns" import { type AutoDenyDetail } from "./autoDenyReason" @@ -43,6 +59,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). @@ -204,6 +222,58 @@ function isWriteAllowedByPatterns( ) } +/** + * Chain aggregation, as in `getCommandDecisionDetailed`. Any denial denies. A + * dangerous substitution prompts. Approval needs every sub-command approved. + * The one difference is that 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. A tie-break is not an option here. + * Whichever layer a tie-break favoured would drop the other layer's verdicts + * elsewhere. These rules mirror the flat path. Parsing, sanitization, and + * reporting therefore cannot drift. + */ +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 user-typed casing; fall back to the case-insensitive match. + 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" } /** @@ -234,16 +304,14 @@ export async function checkAutoApproval({ }: { state?: Pick /** - * 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 - * 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 that 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`. It is not the provider's `state.cwd`, which follows the window, + * so a resumed or child task could be judged by another root's patterns. + * Read approval of a tool's file targets also awaits `realpath` on this root, as + * `canonicalCwd`, and matches both spellings. A pattern written against either + * spelling then still matches. An unresolvable root adds no second spelling. */ cwd?: string ask: ClineAsk @@ -373,11 +441,42 @@ export async function checkAutoApproval({ return { decision: "approve" } } - const { decision, offendingCommand, matchedPattern, parseError } = getCommandDecisionDetailed( - text, - state.allowedCommands || [], - state.deniedCommands || [], - ) + // The pair on `state` follows the window's first folder, so enforcement + // re-judges a command in another folder from the raw global layers at that + // folder. A `cwd` outside every workspace root gets no folder layer, which + // fails closed: no folder's allow list may approve it. A blank `cwd` keeps the + // first-folder configuration. Without raw layers the state carries only the + // pre-composed pair. + const commandFolder = commandListFolderForResource(cwd) + const cwdNamesNoFolder = Boolean(cwd) && commandFolder === undefined + const effectiveLists = + state.globalAllowedCommands !== undefined && state.globalDeniedCommands !== undefined + ? resolveEffectiveCommandLists( + readCommandListScopes( + "allowedCommands", + readLiveGlobalCommandList( + "allowedCommands", + state.globalAllowedCommands, + commandFolder, + ), + undefined, + commandFolder, + ), + readCommandListScopes( + "deniedCommands", + readLiveGlobalCommandList("deniedCommands", state.globalDeniedCommands, commandFolder), + undefined, + commandFolder, + ), + workspaceCommandListsEnabled() && !cwdNamesNoFolder, + ) + : { allowed: state.allowedCommands || [], denied: state.deniedCommands || [] } + + // 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) + : getCommandDecisionDetailed(text, effectiveLists.allowed, effectiveLists.denied) if (decision === "auto_approve") { return { decision: "approve" } diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index e53f60fb838..548153cbb40 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 4766f87112f..e99964d5b2f 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 6c66655325b..830612bdb81 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -16,10 +16,14 @@ import { importSettingsFromPath, importSettingsWithFeedback, exportSettings, + withCommandListLock, } from "../importExport" 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" import type { Mock } from "vitest" @@ -49,6 +53,11 @@ vi.mock("vscode", () => ({ Uri: { file: vi.fn((filePath) => ({ fsPath: filePath })), }, + ConfigurationTarget: { + Global: 1, + Workspace: 2, + WorkspaceFolder: 3, + }, })) vi.mock("fs/promises", () => ({ @@ -165,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: { @@ -249,6 +278,74 @@ 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")) + // 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, + 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 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"]) + }) }) describe("importSettings", () => { @@ -663,6 +760,674 @@ describe("importExport", () => { showErrorMessageSpy.mockRestore() }) + // A save treats a displayed entry as removed from outside unless a + // configuration layer holds it. An import that carries command lists must + // therefore write them into the global layer. An import that never runs, or + // carries no list, must write nothing. + function mockCommandListConfig() { + // The shared structurally complete double keeps the configuration type + // 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, config } + } + + 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("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() + // 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() + + await runFeedback(filePath) + + // `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"], + 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 on the cancel + // path would write that 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("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 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() + + await runFeedback(filePath) + + expect(update).not.toHaveBeenCalled() + }) + + it("skips an imported workspace command-list gate value and names where the gate lives", async () => { + const filePath = "/mock/path/settings.json" + ;(fs.readFile as Mock).mockResolvedValue( + validProfileFile({ mode: "code", allowedCommands: ["git"], workspaceCommandListsEnabled: true }), + ) + stubValidProviderProfiles() + mockContextProxy.setValues.mockResolvedValue(undefined) + mockContextProxy.setValue.mockResolvedValue(undefined) + mockContextProxy.setProviderSettings.mockResolvedValue(undefined) + + const result = await importSettingsFromPath(filePath, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + if (!result.success) { + throw new Error(`import failed: ${result.error}`) + } + + // The gate value is refused, so the runtime state never carries a value the + // enforcement path would not read. The settings beside it still land. + const stored = vi.mocked(mockContextProxy.setValues).mock.calls[0][0] as Record + expect(stored).not.toHaveProperty("workspaceCommandListsEnabled") + expect(stored.mode).toBe("code") + expect(stored.allowedCommands).toEqual(["git"]) + + expect( + result.warnings?.some( + (warning) => warning.includes("workspaceCommandListsEnabled") && warning.includes("user settings"), + ), + ).toBe(true) + }) + + 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", "imported"] })) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + + // The configuration holds a pre-import list, so the rollback has a delta to undo. + const { update, layers } = mockLayeredCommandListConfig({ allowedCommands: ["git"] }) + + // 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, + }) + + 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("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( + validProfileFile({ allowedCommands: ["git", "imported"], deniedCommands: ["x"] }), + ) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + + // 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", + ) + + // 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[] + }) + + const result = await importSettingsFromPath(filePath, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + 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 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"] }) + + 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 + : 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"] })) + ;(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"] })) + ;(fs.access as Mock).mockResolvedValue(undefined) + stubValidProviderProfiles() + + // 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 importWrite.promise + if (key === "allowedCommands") { + fileHolds = value as string[] + } + }) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + const imported = runFeedback(filePath) + await vi.waitFor(() => expect(config.update).toHaveBeenCalled()) + + // 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 = withCommandListLock(async () => { + saveObserved = fileHolds + }) + + 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() + } + + await imported + await save + + expect(saveObserved).toEqual(["git", "imported"]) + }) + + it("completes a save dispatched while the file dialog is open, before the dialog is answered", async () => { + stubValidProviderProfiles() + // 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: feedbackProvider(), + }) + + await flushMacrotasks() + + // The save runs to completion while the dialog is still unanswered. + let saveCompleted = false + 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 lets the import take the lock and proceed. + await imported + }) + + 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")) + + await expect( + importSettingsWithFeedback({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + provider: feedbackProvider(), + }), + ).rejects.toThrow("dialog unavailable") + + let nextRan = false + await withCommandListLock(async () => { + nextRan = true + }) + 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 + }) + + 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. + await rejectionObserved + expect(rejectionMessage).toBe("write failed") + + await third + 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 a second writer is queued before the + // release, so the lock's held state is observed from the queue. + const gate = createDeferred() + let holderInside = false + const holder = withCommandListLock(async () => { + holderInside = true + await gate.promise + }) + + 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 { + 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 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() + } + // 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) + + 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(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 () => { + const first = createDeferred() + let secondRan = false + + const firstImport = withCommandListLock(async () => { + await first.promise + }) + const secondImport = withCommandListLock(async () => { + secondRan = true + }) + + await flushMacrotasks() + 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() + } + + await Promise.all([firstImport, secondImport]) + expect(secondRan).toBe(true) + }) + 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 9882039ad38..dd49bd9a2d8 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -22,6 +22,12 @@ import { CustomModesManager } from "./CustomModesManager" import { downgradeLegacyRooConfig, ROUTER_REMOVAL_IMPORT_WARNING } from "./routerRemoval" import { resolveDefaultSaveUri, saveLastExportPath } from "../../utils/export" import { t } from "../../i18n" +import { + commandListConfiguration, + rollbackFailedCommandListWrite, + sanitizeCommandList, + type CommandListConfigKey, +} from "../auto-approval/commandScope" export type ImportOptions = { providerSettingsManager: ProviderSettingsManager @@ -98,6 +104,17 @@ function sanitizeGlobalSettings(rawGlobalSettings: unknown): { for (const [key, rawValue] of Object.entries(rawGlobalSettings)) { const path = `globalSettings.${key}` + + // The schema accepts this key, so without this branch the import reports + // success and stores a value the enforcement path never reads: the gate is + // read from VS Code user settings only. + if (key === "workspaceCommandListsEnabled") { + warnings.push( + `Setting "${path}" was skipped: The workspace command-list gate applies only from VS Code user settings, not from an imported file.`, + ) + continue + } + const schema = globalSettingsShape[key as keyof GlobalSettings] if (!schema) { @@ -124,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, ) { @@ -147,6 +173,16 @@ 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; 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 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[] = [] + try { const previousProviderProfiles = await providerSettingsManager.export() @@ -228,7 +264,36 @@ export async function importSettingsFromPath( // They will be imported automatically with the config - no special handling needed await providerSettingsManager.import(providerProfiles) - await contextProxy.setValues(sanitizedGlobalSettings) + + // Read through the same proxy the write below uses, because extension state + // 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 = [] + 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 @@ -246,7 +311,7 @@ export async function importSettingsFromPath( return { providerProfiles, - globalSettings: sanitizedGlobalSettings, + globalSettings: globalSettingsToPersist, success: true, warnings: warnings.length > 0 ? warnings : undefined, } @@ -260,6 +325,30 @@ export async function importSettingsFromPath( error = e.message } + if (priorStateCopy) { + const unrestoredKeys: string[] = [] + + 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 { + await contextProxy.setValue(key, priorStateCopy[key]) + } catch { + unrestoredKeys.push(key) + } + } + + if (unrestoredKeys.length > 0) { + error = `${error}\nThe prior ${unrestoredKeys.join(", ")} value(s) could not be restored in extension state.` + } + } + + // 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 } } } @@ -353,8 +442,173 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }: } } +/** + * Serialises the command-list writes of a save and an import. + * + * 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 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. + * + * @param write - The pair to run. It may throw; the lock is released either way. + * @returns Whatever `write` returned. + */ +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 + }) + + await previous + try { + return await write() + } finally { + release() + } +} + +/** The last queued caller's completion, or a settled promise when the lock is free. */ +let commandListLockTail: Promise = Promise.resolve() + +/** + * The keys an import wrote to the configuration, with the layer each held + * before the write, so a failed state half can undo them. + */ +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 +} + +/** + * Writes the command lists an import carried into the user settings file. + * + * 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. + * + * A key the import file did not carry is skipped, so the state copy never + * becomes the source. + * + * 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. + * + * @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>> { + const config = commandListConfiguration() + const normalizedLists: Partial> = {} + + for (const key of ["allowedCommands", "deniedCommands"] as const) { + const imported = globalSettings?.[key] + if (!Array.isArray(imported)) { + 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 { + priorLayer = config.inspect(key)?.globalValue + } catch { + // 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, 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: importedList, priorLayer, priorLayerUnknown }) + normalizedLists[key] = importedList + } + + return normalizedLists +} + +/** + * Undoes the configuration half of an import whose state half failed. + * + * 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. + * + * @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 rollBackImportedCommandLists(written: ImportedCommandListWrite[], failure: string): Promise { + const config = commandListConfiguration() + const unrestored: string[] = [] + + 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, + 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 unrestored.length > 0 + ? `\nThe prior ${unrestored.join(", ")} value(s) could not be restored in VS Code user settings.` + : "" +} + /** * Import settings with complete UI feedback and provider state updates + * + * 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 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 @@ -363,6 +617,7 @@ export const importSettingsWithFeedback = async ( { providerSettingsManager, contextProxy, customModesManager, provider }: ImportWithProviderOptions, filePath?: string, ) => { + const options = { providerSettingsManager, contextProxy, customModesManager } let result if (filePath) { @@ -370,11 +625,7 @@ export const importSettingsWithFeedback = async ( 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, - }) + result = await importSettingsFromPath(filePath, options) } catch (error) { result = { success: false, @@ -382,7 +633,7 @@ export const importSettingsWithFeedback = async ( } } } else { - result = await importSettings({ providerSettingsManager, contextProxy, customModesManager }) + result = await importSettings(options) } if (result.success) { diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index e2e25ef93da..2c0cfcb7236 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1318,10 +1318,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 { @@ -1350,11 +1352,11 @@ 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 and the same + // inputs as the ask-time `checkAutoApproval` call. const approval = await checkAutoApproval({ state: freshState, - cwd: this.cwd, + cwd: commandCwd ?? this.cwd, ask: "command", text, isProtected, @@ -1988,12 +1990,13 @@ 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 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({ state, - cwd: this.cwd, + cwd: autoApprovalContext?.commandCwd ?? this.cwd, ask: type, text, isProtected, @@ -2267,6 +2270,7 @@ export class Task extends EventEmitter implements TaskLike { text, isProtected, dcgDecision: autoApprovalContext?.dcgDecision, + commandCwd: autoApprovalContext?.commandCwd, }, recheckAbort.signal, ) @@ -2340,6 +2344,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 563e7e286e0..928ae6d8225 100644 --- a/src/core/task/__tests__/ask-allowlist-cwd.spec.ts +++ b/src/core/task/__tests__/ask-allowlist-cwd.spec.ts @@ -1,10 +1,61 @@ // 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" import { setAbortLatch } from "../../../test-utils/run-state" +// Doubles for the workspace. The shared vscode mock resolves every lookup +// to nothing, so a command ask could not name a folder. +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`. @@ -104,3 +155,266 @@ describe("Task.ask resolves allowlists against the task's workspace", () => { expect(await askToWriteRelativePath([`${PROVIDER_CWD}/notes.md`])).toBe("ask") }) }) + +// Command asks follow the command's own cwd (commandCwd), not the task +// 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. +// +// 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 } } + 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 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; its allow entry must not approve a command in folder B. + 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 = {} + 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 () => { + openTwoFolders() + // 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"] } + + 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() + + // 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. 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") + }) + + 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() + + // 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, 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 in denying folder B and the command runs in allowing folder A. + // A fallback to the task folder would deny what folder A 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 approves. Judging the defaults or the baked pair would deny instead. + 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 is already queued and the claim gate is open, so the entry drain + // performs the re-check. Folder A's entry approves. + 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") + + // 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) + + expect(result.response).toBe("yesButtonClicked") + expect(result.autoDenyDetail).toBeUndefined() + expect(errorSpy).not.toHaveBeenCalled() + errorSpy.mockRestore() + }) + + it("re-checks an entry-drained queued command against the task folder's policy once blanket deny engages", async () => { + // 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 } }, + { 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. + 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 directory, + // where folder A's entry grants the 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 in denying folder B, which is not the + // first workspace folder. A fallback to the first folder would approve, so + // the denial names the task's folder. + 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 = { + 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 9855e6e417e..2a40de59c89 100644 --- a/src/core/tools/ExecuteCommandTool.ts +++ b/src/core/tools/ExecuteCommandTool.ts @@ -156,13 +156,34 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> { return } const provider = await task.providerRef.deref() + // Resolve one working directory before any approval decision. Policy, DCG, and + // spawn then see the same directory, so a custom `cwd` cannot be approved + // against one folder and run in another. + const lexicalWorkingDirectory = customCwd + ? path.isAbsolute(customCwd) + ? customCwd + : path.resolve(task.cwd, customCwd) + : task.cwd + // Folder command lists apply by containment. Canonicalizing here keeps both + // sides of that match physical, so policy judges a symlinked directory where + // the process starts. `RooIgnoreController.validateAccess` sets the + // realpath-before-policy precedent. An unresolvable link names no directory to + // judge: fail closed through the working-directory error, with no lexical + // fallback. A link re-pointed before the spawn is an accepted race, like a + // settings change 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 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 +235,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 +288,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 +361,7 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> { executionId, command: canonicalCommand, customCwd, + workingDirectory, terminalShellIntegrationDisabled, commandExecutionTimeout, agentTimeout, @@ -394,6 +426,13 @@ export type ExecuteCommandOptions = { executionId: string command: string customCwd?: string + /** + * The directory that the approval was judged against, resolved once by the + * 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 commandExecutionTimeout?: number agentTimeout?: number @@ -406,6 +445,7 @@ export async function executeCommandInTerminal( executionId, command, customCwd, + workingDirectory, terminalShellIntegrationDisabled = true, commandExecutionTimeout = 0, agentTimeout = 0, @@ -415,7 +455,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 c580b551025..a336759190a 100644 --- a/src/core/tools/__tests__/executeCommandTool.spec.ts +++ b/src/core/tools/__tests__/executeCommandTool.spec.ts @@ -2,7 +2,9 @@ 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" import { Task } from "../../task/Task" @@ -23,6 +25,9 @@ vitest.mock("fs/promises", () => ({ default: { access: vitest.fn().mockResolvedValue(undefined), stat: vitest.fn().mockResolvedValue({ isDirectory: () => true }), + // 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)), }, })) @@ -78,6 +83,32 @@ const { executeCommandTool } = executeCommandModule // capturing inside a test can capture another test's leaked spy and recurse. const realCheckAutoApproval = autoApprovalModule.checkAutoApproval +// A Windows directory symlink needs developer mode or elevation. A junction +// needs neither, and `realpath` resolves it like a POSIX link. Try a symlink +// first, then a junction. Skip the fixture where neither works. +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 } @@ -206,7 +237,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 +261,169 @@ describe("executeCommandTool", () => { }) // Verify - command approved, result pushed, and custom cwd passed to terminal - expect(mockAskApproval).toHaveBeenCalledWith("command", "echo test") + // The approval context carries the directory the terminal spawns in. + 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 () => { + // The policy lookup matches against workspace folders, and a relative path + // names none. 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" } + + 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"), + }), + ) + }) + }) + + // 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-check, 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", + }) + + 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", + }) + + // An unresolvable link names no directory that policy can judge, even when the + // lexical `stat` check passes. The message names the canonicalization failure. + 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 tests above pin the contract. This one uses a real link, so + // the physical path reaching `commandCwd` puts the link in its target's folder. + 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) + // Delegate to the real filesystem. Once-only: a leaked + // delegate would resolve later tests' non-existent mock paths for real. + 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", + }) + + // 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), + }) + } finally { + rmSync(baseDir, { recursive: true, force: true }) + } + }, + ) }) describe("Error handling", () => { @@ -342,7 +532,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 +558,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 +588,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 +613,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 +639,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 +669,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 +821,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 +863,49 @@ describe("executeCommandTool", () => { expect(TerminalRegistry.getOrCreateTerminal).not.toHaveBeenCalled() }) + it("re-checks the command policy against the custom working directory", async () => { + // 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" } + // 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)) + + 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 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, { + 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 +1206,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/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 32714067fa2..bea6cebfd16 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -71,6 +71,7 @@ import { ORGANIZATION_ALLOW_ALL, DEFAULT_MODES, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, + DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, getModelId, isRetiredProvider, modelIdKeys, @@ -136,6 +137,11 @@ import { ContextProxy } from "../config/ContextProxy" import { withoutInvalidDisplaySettings } from "../config/displaySettings" import { ProviderSettingsManager } from "../config/ProviderSettingsManager" import { CustomModesManager } from "../config/CustomModesManager" +import { + readCommandListScopes, + resolveEffectiveCommandLists, + workspaceCommandListsEnabled, +} from "../auto-approval/commandScope" import { PendingActionSettlementError, Task } from "../task/Task" import { webviewMessageHandler } from "./webviewMessageHandler" @@ -3159,62 +3165,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 @@ -3235,6 +3185,9 @@ export class ClineProvider alwaysDenyUnapprovedCommands, allowedCommands, deniedCommands, + globalAllowedCommands, + globalDeniedCommands, + workspaceCommandListsEnabled: gateEnabled, alwaysAllowMcp, alwaysAllowModeSwitch, alwaysAllowSubtasks, @@ -3344,8 +3297,6 @@ export class ClineProvider // salted hash: the raw machine ID never crosses the webview boundary (issue #830). const machineId = hashDistinctId(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 @@ -3425,8 +3376,15 @@ export class ClineProvider checkpointTimeout: checkpointTimeout ?? DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, shouldShowAnnouncement: telemetrySetting !== "unset" && lastShownAnnouncementId !== this.latestAnnouncementId, - allowedCommands: mergedAllowedCommands, - deniedCommands: mergedDeniedCommands, + // 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, diffFuzzyThreshold: diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD, @@ -3633,6 +3591,18 @@ export class ClineProvider const taskSyncEnabled: boolean = false + // 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() + // The two raw layers are read here, not from `stateValues`: two awaits + // (`getCustomModes`, `getAllowList`) sit between that snapshot and this + // point, and these layers feed `checkAutoApproval`. A save landing during + // either await would otherwise mix a pre-save global layer with a + // post-save workspace layer. + const allowScopes = readCommandListScopes("allowedCommands", this.contextProxy.getValue("allowedCommands")) + const denyScopes = readCommandListScopes("deniedCommands", this.contextProxy.getValue("deniedCommands")) + const effectiveCommandLists = resolveEffectiveCommandLists(allowScopes, denyScopes, gateEnabled) + // Return the same structure as before. return { apiConfiguration: providerSettings, @@ -3662,8 +3632,17 @@ export class ClineProvider autoCondenseContext: stateValues.autoCondenseContext ?? true, autoCondenseContextPercent: stateValues.autoCondenseContextPercent ?? 100, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], - allowedCommands: stateValues.allowedCommands, - deniedCommands: stateValues.deniedCommands, + // Composed from the global and workspace layers, scoped to the window's first + // folder. Display shows exactly these values. Enforcement re-composes the pair + // from the raw global layers below, so a task in another folder is judged by + // that folder's lists. + allowedCommands: effectiveCommandLists.allowed, + deniedCommands: effectiveCommandLists.denied, + workspaceCommandListsEnabled: gateEnabled, + // 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, ttsEnabled: stateValues.ttsEnabled ?? false, ttsSpeed: stateValues.ttsSpeed ?? 1.0, @@ -4408,6 +4387,8 @@ export class ClineProvider if (configuration) { await this.setValues(configuration) + // 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__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b364b5baa79..1181263f795 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -21,6 +21,7 @@ import { ORGANIZATION_ALLOW_ALL, DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, DEFAULT_DIFF_FUZZY_THRESHOLD, + DEFAULT_WORKSPACE_COMMAND_LISTS_ENABLED, DEFAULT_WRITE_DELAY_MS, providerIdentifiers, openAiModelInfoSaneDefaults, @@ -32,6 +33,7 @@ import { joinSegments } from "../../../shared/mentionSegments" import type { MentionSegment } from "@roo-code/types" import { experimentDefault } from "../../../shared/experiments" import { setTtsEnabled } from "../../../utils/tts" +import { makeUri, makeWorkspaceConfiguration } from "../../../test-utils/vscode" import { ContextProxy } from "../../config/ContextProxy" import { ProviderSettingsManager } from "../../config/ProviderSettingsManager" import { importSettingsFromPath } from "../../config/importExport" @@ -4362,6 +4364,313 @@ describe("ClineProvider", () => { expect(state.alwaysDenyUnapprovedCommands).toBe(false) }) + describe("command list scope merging", () => { + // 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([]), + update: vi.fn(), + } as unknown as vscode.WorkspaceConfiguration) + Reflect.deleteProperty(vscode.workspace, "workspaceFolders") + }) + + // The configuration double makes `get` key-aware, so only the gate key + // reports true. The deny-side workspace layer must come from `inspect`. + 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"), + 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 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().mockImplementation((key: string) => key === "workspaceCommandListsEnabled"), + 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() + + // No global entry shadows the workspace entry, so display shows the global + // layer plus that entry, which is what getState() enforces. + expect(state.deniedCommands).toEqual(["git", "docker"]) + 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() + + // Per-folder enforcement re-composes from the raw global layers, so they must + // differ from the window-composed pair. A dropped or composed field would make + // enforcement use 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("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"]) + mockGateConfiguration(true) + + // Hold the first await of getState, so the save below lands inside it. + let releaseCustomModes!: () => void + const customModesPending = new Promise((resolve) => { + releaseCustomModes = () => resolve() + }) + vi.mocked(provider.customModesManager.getCustomModes).mockImplementationOnce(async () => { + await customModesPending + return [] + }) + + const pendingState = provider.getState() + // 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 + + // The lists describe the state at return time, not at call time. A read from + // the call-time snapshot would return the pre-save entries instead. + expect(state.globalAllowedCommands).toEqual(["docker"]) + expect(state.globalDeniedCommands).toEqual(["pnpm"]) + expect(state.allowedCommands).toEqual(["docker"]) + expect(state.deniedCommands).toEqual(["pnpm"]) + expect(state.globalAllowedCommands).not.toContain("git") + expect(state.globalDeniedCommands).not.toContain("curl") + }) + + 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"), + 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 the workspace value. It does not union. The + // effective get() value is ignored, so global entries cannot leak in. + expect(state.deniedCommands).toEqual(["pnpm docker"]) + }) + + test("getState scopes its command-list lookups to the first workspace folder", async () => { + // Each folder gets its own configuration, chosen by the scope resource. An + // unscoped lookup reads the second folder, so only a lookup scoped to the + // first folder's uri returns its list. + const firstFolder = { uri: makeUri("/root/one"), name: "first", index: 0 } + const secondFolder = { uri: makeUri("/root/two"), name: "second", index: 1 } + // 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], + }) + + 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) + }) + + // The gate decides a workspace-only allow entry. Enabled, the entry joins the + // effective lists. Disabled, enforcement ignores it. + function mockGateConfiguration(enabled: boolean) { + // 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() + inspect.mockImplementation((key: string) => + key === "allowedCommands" ? { key, workspaceValue: ["docker"] } : undefined, + ) + config.inspect = inspect + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + } + + // A profile that never set the gate reports nothing, so the provider must + // apply the shared default. The workspace layer is present, so the default + // direction (workspace entries stay inert) is visible. + 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) + + 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 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) + // 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 () => { 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 e1cc7dc8445..3ae696e1616 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -67,6 +67,20 @@ vi.mock("../rulesMessageHandler", () => ({ handleOpenRulesDirectory: 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: { hasInstance: vi.fn().mockReturnValue(false), @@ -77,10 +91,15 @@ 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" +import { Package } from "../../../shared/package" +import { importSettingsWithFeedback, withCommandListLock } from "../../config/importExport" +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" @@ -775,20 +794,35 @@ describe("webviewMessageHandler - theme fixture probes", () => { import { changeLanguage, 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. +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) return { + ConfigurationTarget: { + Global: 1, + Workspace: 2, + WorkspaceFolder: 3, + }, window: { showInformationMessage, showErrorMessage, + showWarningMessage, showTextDocument, }, workspace: { - workspaceFolders: [{ uri: { fsPath: "/mock/workspace" } }], + get workspaceFolders() { + return mockWorkspaceFolders.folders + }, openTextDocument, getConfiguration: vi.fn(() => ({ get: vi.fn() })), }, @@ -2118,152 +2152,3432 @@ describe("webviewMessageHandler - allowlists together", () => { }) }) -describe("webviewMessageHandler - terminalProfile", () => { +describe("webviewMessageHandler - command list scope-aware persistence", () => { beforeEach(() => { vi.clearAllMocks() - Terminal.setTerminalProfile(undefined) - }) + mockWorkspaceFolders.folders = [{ uri: { fsPath: "/mock/workspace" } }] + // 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 + // for the command lists resolves to that uri. + const mockWorkspaceFolderUri = { fsPath: "/mock/workspace" } + + // Mirrors the real configuration API: `inspect()` exposes per-scope values, + // and `update()` records its target. Extension state stays unset. + // `updateSequence` and `inspectSequence` script successive call outcomes in + // call order. An Error element makes that call throw. + // + // One snapshot per key, plus the pre-write merge re-read. + type InspectedCommandList = { + 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[] + } - afterEach(() => { - Terminal.setTerminalProfile(undefined) - vi.restoreAllMocks() - }) + // `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` read. Leaving it unset keeps the gate off, + // which matches the extension default. + function mockCommandConfiguration( + inspected: InspectedCommandList | ((key: string) => InspectedCommandList), + updateSequence?: unknown[], + inspectSequence?: unknown[], + gateEnabled?: boolean, + ) { + const update = vi.fn() + if (updateSequence) { + update.mockImplementation(() => updateSequence.shift()) + } + const inspect = vi.fn() + if (inspectSequence) { + // 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 + } + // `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)) + } + // The shared double keeps the configuration type correct. Each test + // installs the scripted members. + const config = makeWorkspaceConfiguration( + gateEnabled === undefined ? {} : { workspaceCommandListsEnabled: gateEnabled }, + ) + config.update = update + config.inspect = inspect + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + return { update, inspect } + } - it("normalizes and persists a saved terminalProfile, then closes stale idle terminals", async () => { - const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + // 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. + vi.mocked(mockClineProvider.contextProxy.getValue).mockReturnValue(undefined) + mockCommandConfiguration({ globalValue: ["git"] }) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", - updatedSettings: { terminalProfile: " Git Bash " }, + updatedSettings: { mode: "code" }, }) + expect(withCommandListLock).not.toHaveBeenCalled() - expect(Terminal.getTerminalProfile()).toBe("Git Bash") - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", "Git Bash") - expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { allowedCommands: ["git"] }, + }) + 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 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() + } + 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) + + // Both stores hold the imported list, because the import ran last. + expect(sanitizeCommandList(stateCopy["allowedCommands"])).toEqual(["imported"]) + 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 { + // 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 + // 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("does not close idle terminals when hydration sends the unchanged profile", async () => { - Terminal.setTerminalProfile("Git Bash") - const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + 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"] }) - await webviewMessageHandler(mockClineProvider, { + const configuration: Record = {} + update.mockImplementation(async (key: string, value: unknown) => { + configuration[key] = value + }) + + 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 + } + + stateWriteStarted() + await stateWrite + stateCopy = value + }) + + let releases = 0 + let releasedBeforeStateWriteLanded = false + vi.mocked(withCommandListLock).mockImplementationOnce(async (write) => { + try { + return await write() + } finally { + releases += 1 + releasedBeforeStateWriteLanded = stateCopy === undefined + } + }) + + const save = webviewMessageHandler(mockClineProvider, { type: "updateSettings", - updatedSettings: { terminalProfile: " Git Bash " }, + updatedSettings: { allowedCommands: ["git"] }, }) - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", "Git Bash") - expect(closeIdleTerminalsSpy).not.toHaveBeenCalled() + // 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() + } + })(), + ]) + + // While the state write is pending, the configuration half has already landed — + // 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 + // after the state copy had landed. + expect(configuration["allowedCommands"]).toEqual(["git"]) + expect(stateCopy).toEqual(["git"]) + expect(releasedBeforeStateWriteLanded).toBe(false) + expect(releases).toBe(1) }) - it("clears the persisted profile when SettingsView sends the empty-string sentinel", async () => { - Terminal.setTerminalProfile("Git Bash") - const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + 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, + // and the save promotes it to the global layer. + const { update, inspect } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", - updatedSettings: { terminalProfile: "" }, + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + // "docker" stays at the workspace scope instead of leaking into the user's + // global settings. The save persists 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 cannot + // 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 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 () => { + // 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", + updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - expect(Terminal.getTerminalProfile()).toBeUndefined() - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) - expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) + // Read, target resolution, and write all run on the configuration scoped to + // the first workspace folder. The folder-target update is legal only 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"]) }) - it("does not close idle terminals when the empty-string sentinel leaves the profile unset", async () => { - const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + it("clears a deleted workspace entry at the workspace scope without adding it to global", async () => { + // Gate on: the entry is visible in the dialog, and only visible entries are + // deletable there. The preservation rule re-adds a hidden entry instead. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, undefined, true) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", - updatedSettings: { terminalProfile: "" }, + updatedSettings: { deniedCommands: [] }, }) - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) - expect(closeIdleTerminalsSpy).not.toHaveBeenCalled() + // 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("treats non-string terminalProfile values as unset", async () => { - Terminal.setTerminalProfile("Git Bash") - const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + it("does not create a workspace layer when none exists", async () => { + const { update } = mockCommandConfiguration({}) await webviewMessageHandler(mockClineProvider, { type: "updateSettings", - updatedSettings: { terminalProfile: 42 as any }, + updatedSettings: { allowedCommands: ["git"] }, }) - expect(Terminal.getTerminalProfile()).toBeUndefined() - expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) - expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) + // Only the Global write happens, so saving never materializes 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 - requestTerminalProfiles", () => { - beforeEach(() => { - vi.clearAllMocks() - }) + it("writes the global layer before the workspace layer and undoes only its own delta when the workspace write fails", async () => { + // Call order: the global write succeeds, the workspace write rejects, and the + // 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" and "drop" are + // restored. The gate is on so each scripted call stays distinguishable, and + // call position pins the undo. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["keep", "drop"] : undefined, + ) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [ + { globalValue: ["keep", "drop"], workspaceValue: ["npm docker", "docker"] }, + undefined, + { globalValue: ["aws", "mid-save"] }, + ], + true, + ) - afterEach(() => { - vi.restoreAllMocks() + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) + + // 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", + ["mid-save", "keep", "drop"], + 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("posts available profile names", async () => { - vi.spyOn(Terminal, "getAvailableProfileNames").mockReturnValue(["Git Bash", "bash"]) + 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 against the cache would restore the stale list over the + // value the failed save replaced, and it would drop "manual" permanently. 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: "requestTerminalProfiles" }) + 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. It does not restore + // 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") + }) - expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ - type: "terminalProfiles", - profiles: ["Git Bash", "bash"], + it("rolls the global layer back on a folder-target save and still persists the payload's other keys", async () => { + // update() call order. The global write succeeds, the folder-target workspace + // write rejects, and the undo restores the global deletions at the Global + // target. That is the only layer this save changed. A second key pins that the save + // skips only the failed command-list key. + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "deniedCommands" ? ["drop"] : undefined, + ) + const { update } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("disk on fire")), undefined], + [ + { globalValue: ["drop"], workspaceValue: ["npm"], workspaceFolderValue: ["pnpm docker", "docker"] }, + undefined, + { + globalValue: [], + }, + ], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"], alwaysDenyUnapprovedCommands: true }, }) + + // 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) + expect(update).toHaveBeenNthCalledWith( + 2, + "deniedCommands", + ["docker"], + vscode.ConfigurationTarget.WorkspaceFolder, + ) + // 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()) + // ...and 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("posts an empty array when profile discovery throws", async () => { - vi.spyOn(Terminal, "getAvailableProfileNames").mockImplementation(() => { - throw new Error("config error") + it("aborts the key without compensation when the global write fails", async () => { + // The global layer comes first, so a rejected global write leaves nothing + // changed: no workspace write may follow, and the save needs no compensation. + // The rejection is a plain string, which pins 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"] }, }) - await webviewMessageHandler(mockClineProvider, { type: "requestTerminalProfiles" }) + // Only the failed global write happened, so the save never touches the + // 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", ["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: global locked") + }) - expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ - type: "terminalProfiles", - profiles: [], + 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 + // copy it back into global settings. The key aborts instead: no configuration + // write and no extension global state. + const { update } = mockCommandConfiguration({ workspaceValue: ["docker"] }, undefined, [undefined]) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, }) - }) -}) -describe("webviewMessageHandler - openTerminalProfilePicker", () => { - beforeEach(() => { - vi.clearAllMocks() + 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("executes the VS Code selectDefaultShell command", async () => { - await webviewMessageHandler(mockClineProvider, { type: "openTerminalProfilePicker" }) - expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.terminal.selectDefaultShell") + 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 the save skips only the aborted command-list key. + 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", + ) }) -}) -describe("webviewMessageHandler - requestCommands", () => { - beforeEach(() => { - vi.clearAllMocks() + 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 is a + // different failure class than an unreadable value. It therefore 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, and no per-key error handling ran. The + // rejection reached the caller. The webview still gets a state refresh, + // because a failed save always re-posts before it re-throws. + expect(mockClineProvider.contextProxy.setValue).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() }) - it("includes skill slug commands and dedupes duplicate skill names while preserving first skill entry", async () => { - mockGetCommands.mockResolvedValue([]) + it("reports partial failure when the compensating restore also fails", async () => { + // update() call order: the global write succeeds, the workspace write rejects, + // and the undo write rejects too. The gate is on so the workspace write is the + // 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. 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( + {}, + [ + undefined, + Promise.reject(new Error("workspace locked")), + Promise.reject(new Error("restore also failed")), + ], + [{ workspaceValue: ["docker", "old"] }, undefined, { globalValue: ["aws"] }], + true, + ) - const getTaskMode = vi.fn().mockResolvedValue("code") - vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ - cwd: "/mock/workspace", - getTaskMode, - } as unknown as ReturnType) + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + }) - const getSkillsForMode = vi.fn().mockReturnValue([ - { - name: "skill-slug-entry", - description: "Primary skill slug", - path: "/mock/.roo/skills/skill-slug-entry/SKILL.md", - source: "project", - modeSlugs: ["code"], - }, - { + // The undo ran 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. + // The layer was absent at save start, and the re-read still holds only this + // save's own write. The rollback therefore 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( + "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. + // 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. 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, 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() + }) + + 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"] }, + 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() + }) + + 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 + // global entry with the gate on. + 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 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 () => { + const { update } = mockCommandConfiguration({ workspaceValue: ["docker", "npm"] }, undefined, undefined, false) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: [] }, + }) + + // Preservation is workspace-side only, so re-adding hidden entries never + // leaks 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("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, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // 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) + 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 rule for + // provenance it excludes the configuration-global addition from the + // external-addition re-admit. The split source is then 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, because 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 the user added + // it 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 hidden-entry re-add preserves the shadowed workspace copy. + expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) + // The changed-settings warning names the genuine file addition. + expect(vscode.window.showWarningMessage).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(expect.stringContaining("git push")) + 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 + // 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", ["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 () => { + // 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. + // The baseline carries the gate as displayed and shows the entry. Keeping it + // therefore stays a workspace decision. It is not a 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) + // The save promotes only the genuinely new entry, and "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("keeps a displayed workspace entry out of the global write when the baseline gate matches the current gate", async () => { + // The gate is off at display time and still off at save time. The workspace + // layer's "docker" is hidden now, but the baseline names it, so the dialog did + // show it. Keeping it stays a workspace decision: the baseline alone decides, + // whether or not the gate moved. Only the genuinely new "aws" promotes. + 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", ["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 without duplicating it into the global write", async () => { + // The workspace layer holds "echo" and a global entry shadows it, so the + // 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, { + 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. + // `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"] }, + 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("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"]) + 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 + // 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"] }, + { 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 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 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. + 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 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 () => { + // 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 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"] }, + // 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) + // 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(2) + }) + + 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, null], + 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, {}], + 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 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. 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, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + + 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", ["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 + // known state. 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 + // 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, because 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 result. Without + // the gate as displayed, the entry's presence in the baseline does not prove + // the dialog showed it. Re-adding it therefore 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"] }, + }) + + // 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 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, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["docker", "npm", "aws"] }, + commandListBaseline: { deniedCommands: ["docker"], workspaceCommandListsEnabled: true }, + }) + + 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) + }) + + 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, while "curl" was hidden all + // along, shadowed by the global allow. The baseline shows that. The user + // deleted "docker", and the gate flipped off before the save. That 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. The preservation re-add still restores "curl". + 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, + workspaceDeniedCommands: ["docker"], + }, + }) + + // 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. The undo is computed against the fresh + // read, so it leaves "keep" in place. It removes only this save's addition + // ("aws") and restores 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], + [ + { globalValue: ["keep", "drop"], 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. The undo must therefore 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], + [ + { globalValue: ["keep", "drop"], 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("clears the key instead of restoring its deletion when the re-read reports no global value", async () => { + // A cleared key inspects as no value at all. The layer existed at save start, so + // an absent re-read means a later writer deleted it during the save. That + // decision outranks this save's removed delta: writing "drop" back would + // resurrect a layer the other writer removed. The undo clears the key, and it + // does not treat 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], + // 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, {}], + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["keep", "docker", "aws"] }, + }) + + expect(update).toHaveBeenNthCalledWith(3, "deniedCommands", undefined, vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith("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("keeps a workspace entry another writer added during the global write", async () => { + // The global write is not instantaneous, and the configuration API offers no + // compare-and-set. While it runs, a third party adds "concurrent" to the + // workspace layer. The workspace write re-reads that layer and merges the + // addition, so the save does not overwrite it. The entry the user deleted + // ("drop") is in the save-start workspace layer, so it is not a mid-save + // addition and stays deleted. + const update = vi.fn() + const config = makeWorkspaceConfiguration({ workspaceCommandListsEnabled: true }) + let workspaceLayer = ["keep", "drop"] + // The double reports the two layers the save path reads. The list values are + // the string lists the production call asks for. + const inspect: vscode.WorkspaceConfiguration["inspect"] = (section: string) => ({ + key: section, + globalValue: ["keep"] as T, + 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 = [...workspaceLayer, "concurrent"] + } + return undefined + }) + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["keep"] }, + }) + + // The submitted list drops "drop", so the workspace write keeps "keep" and adds + // the entry that arrived mid-save. + expect(update).toHaveBeenCalledWith( + "deniedCommands", + ["keep", "concurrent"], + vscode.ConfigurationTarget.Workspace, + ) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["keep"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + ["keep", "drop", "concurrent"], + vscode.ConfigurationTarget.Workspace, + ) + }) + + it("clears the key only when the undo's re-read finds no layer", async () => { + // 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( + {}, + [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, {}], + 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. Nothing present + // remains to restore either, so the undo clears the key. + const { update: clearedMidSave } = mockCommandConfiguration( + {}, + [undefined, Promise.reject(new Error("workspace locked")), undefined], + [{ globalValue: ["aws"], workspaceValue: ["docker"] }, 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("clears the key when the undo's re-read finds only this save's own write", async () => { + // The re-read finds the layer holding exactly this save's own write over an + // absent start. That is 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( + {}, + [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, because every + // submitted entry stayed workspace-scoped. 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, and 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 other side of the guard: a layer that exists stays present after the + // rollback, even when the undo computes an empty list. Clearing an existing + // empty layer would restore the seeded defaults that 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 was + // absent at save start, and the re-read finds only this save's own write. The + // undo therefore clears the key to restore absence. + 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("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 + // 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, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["git push"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { deniedCommands: ["git push"] }, + commandListBaseline: { deniedCommands: [], workspaceCommandListsEnabled: true }, + }) + + expect(update).toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Workspace) + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["git push"], vscode.ConfigurationTarget.Global) + expect(update).toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Global) + }) + + 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, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "allowedCommands" ? { workspaceValue: ["git", "docker"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // "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 }, + }) + + // 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) + }) + + 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(), + ) + // The refusal does not affect the sibling keys of the same payload. + 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() + }) + + // A payload can carry both command-list keys. The hidden-entry check for the + // second-processed key must judge shadowing against the state as it was when the + // save started. It must not judge against the state the same loop's earlier key + // left behind. The double below mirrors ContextProxy. Its setValue publishes the + // in-memory copy before it resolves, so a fresh read after the first key's awaited + // write would observe it. That read would 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("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"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // 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) + expect(update).not.toHaveBeenCalledWith("deniedCommands", [], vscode.ConfigurationTarget.Workspace) + expect(mockClineProvider.postStateToWebview).toHaveBeenCalled() + }) + + 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"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + // 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) + 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. 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. 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({}) + + 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 re-reads state instead of keeping an unsaved value. + 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. 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({}) + + 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 save + // to explain, so their failures keep propagating. 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() + // The webview still gets a state refresh, because a failed save re-posts + // before the rejection propagates. + expect(mockClineProvider.postStateToWebview).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. It is in the file and absent from the submitted + // list. The baseline tells them apart, so the new entry stays in the layer the + // snapshot found it in. The user hears about it 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: the baseline shows the dialog displayed the + // entry and the submitted list omits it, so the user deleted it on purpose. + // The save drops it from every layer that held it, and discloses nothing. + 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"], + workspaceDeniedCommands: ["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, so the deletion applies. "curl" arrived after the dialog opened, + // so the save preserves it. The warning names only the preserved entry. + 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"], workspaceDeniedCommands: ["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 () => { + // Senders that omit the baseline keep the old behavior: the omitted entry is + // dropped as a deletion, and the save produces no warning. + 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 and "npm" in the + // extension's stored global layer, and the dialog displayed neither. + 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 save writes + // the submitted list unclassified. No entry the dialog never displayed counts + // as user-deleted. + 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. Two file entries the + // dialog never displayed, one per key, must survive in their own layers. The + // save discloses them together in exactly one warning. + 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")) + }) + + // 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) + }, + }, + { + // 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: false, + prepare: () => { + vi.mocked(mockClineProvider.contextProxy.getValue).mockImplementation((key: string) => + key === "allowedCommands" ? ["git"] : undefined, + ) + }, + }, + ])("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. 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).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 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, + ) + const { update } = mockCommandConfiguration( + (key) => (key === "deniedCommands" ? { workspaceValue: ["git push", "curl", "wget"] } : {}), + undefined, + undefined, + true, + ) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + 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 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", + ["git push", "curl", "wget"], + 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. The save keeps + // it in the layer the snapshot found it in and names it 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")) + }) + + 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. No such edit refreshes the extension-state copy + // that the split consults, and neither the dialog baseline nor the submitted + // list names the entry. The save-start configuration global layer is therefore + // 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 save discloses the preserved entry 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. It is + // therefore known state kept in place. "aws", which no layer held 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 split also keeps the entry. + expect(update).not.toHaveBeenCalledWith("deniedCommands", ["aws"], vscode.ConfigurationTarget.Global) + expect(update).not.toHaveBeenCalledWith( + "deniedCommands", + expect.anything(), + vscode.ConfigurationTarget.Workspace, + ) + // No entry counted as an external addition, so no warning fires. + 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. No direct settings-file + // edit refreshes the extension-state copy that the retained-entry check + // consults. 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. The Global write then deletes it + // from the user's settings file. + // Global write then deletes 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", + updatedSettings: { deniedCommands: ["curl"] }, + commandListBaseline: { deniedCommands: ["curl"], workspaceCommandListsEnabled: true }, + }) + + // The split keeps the retained entry, 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("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. 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. 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, + ) + 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. No global configuration layer + // exists, so the state copy is the only evidence that the displayed entries + // 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, + ) + // 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", + 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 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 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[]) => { + 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 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"]) + // 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 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. + 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. 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, that set misses the + // configuration's own global layer. "docker" would therefore count as never + // routed and be dropped from the Global write. That write deletes it from the + // user's settings file. The unioned origin set keeps it in the layer the + // save-start snapshot found it in. It also keeps 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 file did not add this displayed entry. The user kept it, so no warning fires. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("deniedCommands", ["docker", "aws"]) + }) + + // Post-save probe for the activation seed. `seedCommandList` skips only a key + // whose global state is set. The saved copy therefore decides whether the + // declared package default can ever return to that key. + function mockSeededGlobalState(initial: Record) { + const store = new Map(Object.entries(initial)) + + // Structurally complete Memento double with keys, get, and update. The seed + // call site therefore 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. That is 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. 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, + ) + // 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", + 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 it reads 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. 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, + ) + // 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", + 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. The seed guard therefore 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 () => { + // For a workspace-only edit the user deletes the workspace entry "npm test" + // and touches nothing on the global side. 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"], defaultValue: ["git log", "git diff", "git show"] }, + 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, + // "npm test" was the only workspace-layer entry on screen; the rest are + // global entries the flat list carries too. + workspaceAllowedCommands: ["npm test", "docker"], + }, + }) + + // The save writes the untouched global side 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, so nothing leaks 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("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"], defaultValue: ["git log", "git diff", "git show"] }, + 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, + }, + }) + + expect(update).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) + + // 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 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, + // 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) + expect(update).toHaveBeenCalledWith("allowedCommands", [], vscode.ConfigurationTarget.Workspace) + 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 + // 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"]) + }) +}) + +describe("webviewMessageHandler - terminalProfile", () => { + beforeEach(() => { + vi.clearAllMocks() + Terminal.setTerminalProfile(undefined) + }) + + afterEach(() => { + Terminal.setTerminalProfile(undefined) + vi.restoreAllMocks() + }) + + it("normalizes and persists a saved terminalProfile, then closes stale idle terminals", async () => { + const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { terminalProfile: " Git Bash " }, + }) + + expect(Terminal.getTerminalProfile()).toBe("Git Bash") + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", "Git Bash") + expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) + }) + + it("does not close idle terminals when hydration sends the unchanged profile", async () => { + Terminal.setTerminalProfile("Git Bash") + const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { terminalProfile: " Git Bash " }, + }) + + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", "Git Bash") + expect(closeIdleTerminalsSpy).not.toHaveBeenCalled() + }) + + it("clears the persisted profile when SettingsView sends the empty-string sentinel", async () => { + Terminal.setTerminalProfile("Git Bash") + const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { terminalProfile: "" }, + }) + + expect(Terminal.getTerminalProfile()).toBeUndefined() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) + expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) + }) + + it("does not close idle terminals when the empty-string sentinel leaves the profile unset", async () => { + const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { terminalProfile: "" }, + }) + + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) + expect(closeIdleTerminalsSpy).not.toHaveBeenCalled() + }) + + it("treats non-string terminalProfile values as unset", async () => { + Terminal.setTerminalProfile("Git Bash") + const closeIdleTerminalsSpy = vi.spyOn(TerminalRegistry, "closeIdleTerminals").mockImplementation(() => {}) + + await webviewMessageHandler(mockClineProvider, { + type: "updateSettings", + updatedSettings: { terminalProfile: 42 as any }, + }) + + expect(Terminal.getTerminalProfile()).toBeUndefined() + expect(mockClineProvider.contextProxy.setValue).toHaveBeenCalledWith("terminalProfile", undefined) + expect(closeIdleTerminalsSpy).toHaveBeenCalledTimes(1) + }) +}) + +describe("webviewMessageHandler - requestTerminalProfiles", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it("posts available profile names", async () => { + vi.spyOn(Terminal, "getAvailableProfileNames").mockReturnValue(["Git Bash", "bash"]) + + await webviewMessageHandler(mockClineProvider, { type: "requestTerminalProfiles" }) + + expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "terminalProfiles", + profiles: ["Git Bash", "bash"], + }) + }) + + it("posts an empty array when profile discovery throws", async () => { + vi.spyOn(Terminal, "getAvailableProfileNames").mockImplementation(() => { + throw new Error("config error") + }) + + await webviewMessageHandler(mockClineProvider, { type: "requestTerminalProfiles" }) + + expect(mockClineProvider.postMessageToWebview).toHaveBeenCalledWith({ + type: "terminalProfiles", + profiles: [], + }) + }) +}) + +describe("webviewMessageHandler - openTerminalProfilePicker", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("executes the VS Code selectDefaultShell command", async () => { + await webviewMessageHandler(mockClineProvider, { type: "openTerminalProfilePicker" }) + expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.terminal.selectDefaultShell") + }) +}) + +describe("webviewMessageHandler - requestCommands", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("includes skill slug commands and dedupes duplicate skill names while preserving first skill entry", async () => { + mockGetCommands.mockResolvedValue([ + { + name: "deploy", + content: "existing command", + source: "project", + filePath: "/mock/workspace/.roo/commands/deploy.md", + description: "Deploy command", + }, + ]) + + const getTaskMode = vi.fn().mockResolvedValue("code") + vi.mocked(mockClineProvider.getCurrentTask).mockReturnValue({ + cwd: "/mock/workspace", + getTaskMode, + } as unknown as ReturnType) + + const getSkillsForMode = vi.fn().mockReturnValue([ + { + name: "skill-slug-entry", + description: "Primary skill slug", + path: "/mock/.roo/skills/skill-slug-entry/SKILL.md", + source: "project", + modeSlugs: ["code"], + }, + { name: "skill-slug-entry", description: "Duplicate skill slug", path: "/mock/.roo/skills/duplicate-skill/SKILL.md", @@ -2291,24 +5605,29 @@ describe("webviewMessageHandler - requestCommands", () => { expect(commandMessageCall).toBeDefined() const commandMessage = commandMessageCall?.[0] - expect(commandMessage?.commands).toEqual( - expect.arrayContaining([ - { - name: "skill-slug-entry", - source: "project", - filePath: "/mock/.roo/skills/skill-slug-entry/SKILL.md", - description: "Primary skill slug", - }, - { - name: "another-skill-slug", - source: "global", - filePath: "/mock/.roo/skills/another-skill-slug/SKILL.md", - description: "Another skill-generated command", - }, - ]), - ) - - expect(commandMessage?.commands?.filter((command) => command.name === "skill-slug-entry")).toHaveLength(1) + // The complete array in order: the discovered command first, then the skills in + // discovery order. The duplicate skill contributes nothing, and the surviving + // copy is the first one seen. + expect(commandMessage?.commands).toEqual([ + { + name: "deploy", + source: "project", + filePath: "/mock/workspace/.roo/commands/deploy.md", + description: "Deploy command", + }, + { + name: "skill-slug-entry", + source: "project", + filePath: "/mock/.roo/skills/skill-slug-entry/SKILL.md", + description: "Primary skill slug", + }, + { + name: "another-skill-slug", + source: "global", + filePath: "/mock/.roo/skills/another-skill-slug/SKILL.md", + description: "Another skill-generated command", + }, + ]) }) it("adds skill-backed command entries without overriding existing command names", async () => { @@ -3290,6 +6609,53 @@ 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. The save result must therefore + // 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("reports a failed save when a command-list write fails and the state refresh fails too", async () => { + // The code catches the refresh failure on its own, so 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. + 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 6641ff259f1..7173c8efd44 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -64,6 +64,20 @@ import { } from "./rulesMessageHandler" import { changeLanguage, t } from "../../i18n" import { Package } from "../../shared/package" +import { + type CommandListInspection, + type WorkspaceCommandListLayer, + classifyCommandListBaseline, + commandListConfiguration, + displayedCommandListScopes, + readCommandListScopes, + resolveWorkspaceWriteTarget, + rollbackFailedCommandListWrite, + sanitizeCommandList, + splitCommandListScopes, + workspaceLayerValue, + globalShadowEntries, +} from "../auto-approval/commandScope" import { type RouterName, toRouterName } from "../../shared/api" import { MessageEnhancer } from "./messageEnhancer" @@ -81,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 { 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" @@ -769,22 +783,34 @@ 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 failed scoped write abandons only that key and throws nothing. The key + // sets its own flag, so the save result stays honest. let failed = false let failure: unknown - - try { - if (!message.updatedSettings) break - - if (message.updatedSettings.destructiveCommandGuardEnabled === true) { + let commandListSaveFailed = false + // 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), @@ -793,7 +819,20 @@ export const webviewMessageHandler = async ( } } - for (const [key, value] of Object.entries(message.updatedSettings)) { + 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)) { provider.log(`[updateSettings] Ignored an invalid value for ${key}`) @@ -805,26 +844,282 @@ export const webviewMessageHandler = async ( if (key === "language") { newValue = value ?? "en" changeLanguage(newValue as Language) - } else if (key === "allowedCommands") { + } else if (key === "workspaceCommandListsEnabled") { + // The gate value comes from the synchronous user-scope configuration read + // that enforcement and display already do. A settings payload never changes + // or stores it. + continue + } else if (key === "allowedCommands" || key === "deniedCommands") { const commands = value ?? [] + 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 + // the rollback value describe the same state. A guessed-empty workspace + // layer would copy workspace entries back into global settings, so a key + // without a snapshot aborts. Only the snapshot read is guarded: a failed + // commandListConfiguration() lookup propagates for the whole message. + const config = commandListConfiguration() + let inspection: CommandListInspection | undefined + // 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) + } + if (inspection === undefined) { + // No snapshot means the workspace layer is unknown, so this key aborts. 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"}`, + ) + commandListSaveFailed = true + continue + } - newValue = Array.isArray(commands) - ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) + const currentScopes = readCommandListScopes(key, getGlobalState(key), inspection) + + // The compensation's delta baseline is the snapshot's global layer, because + // the global write targets the configuration. A delta against the state copy + // would restore a stale list over entries the rolled-back save replaced. + const configGlobalAtSaveStart = readCommandListScopes( + key, + globalLayerAtSaveStart, + inspection, + ).global + + 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 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)) + // 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])] + // 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([ + ...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, + 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 + // 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 + // 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, + incoming, + stateCopy: currentScopes.global, + configGlobal: globalOriginEntries, + workspaceNow: currentScopes.workspace, + gateAtDisplay: message.commandListBaseline?.workspaceCommandListsEnabled, + workspaceDisplayed, + globalDisplayed, + 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) - await vscode.workspace - .getConfiguration(Package.name) - .update("allowedCommands", newValue, vscode.ConfigurationTarget.Global) - } else if (key === "deniedCommands") { - const commands = value ?? [] + // The two configuration writes are not atomic. Global comes first: an + // interrupted save can only duplicate an entry across layers, which the + // enforcement union makes inert, and never lose it. A failed global write + // changes nothing. The code below undoes a failed workspace write. + let globalWriteApplied = false + try { + await config.update(key, globalWrite, vscode.ConfigurationTarget.Global) + globalWriteApplied = true + + // The workspace layer, at the target that owns it. With no workspace layer + // the save skips the write, so saving never materializes one. Deletions clear + // it with `[]`. + if (workspaceTarget !== undefined) { + // 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 + let workspaceReReadFailure: string | undefined + try { + const freshInspection = config.inspect(key) + // 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 + // 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 (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 + // 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`, + ) + } + if (workspaceReReadFailure !== undefined) { + throw new Error( + `the workspace layer could not be re-read: ${workspaceReReadFailure}`, + ) + } + await config.update(key, workspaceAtWrite, workspaceTarget) + } + } catch (error) { + const failure = error instanceof Error ? error.message : String(error) + + // The helper undoes this save's own global delta. It reports what it achieved + // and never throws, so this key still owns the flag and the loop control. + const outcome = await rollbackFailedCommandListWrite({ + key, + failure, + globalWrite, + configGlobalAtSaveStart, + globalLayerAtSaveStart, + globalWriteApplied, + 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), + }) + if (outcome.status === "re-read-failed") { + // Nothing was safe to write, so the state write is skipped. + vscode.window.showErrorMessage(outcome.message) + commandListSaveFailed = true + continue + } + if (outcome.status === "restore-failed") { + // The undo itself failed, so the state write is skipped. + vscode.window.showErrorMessage(outcome.message) + commandListSaveFailed = true + continue + } - newValue = Array.isArray(commands) - ? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0) - : [] + // 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 + } - await vscode.workspace - .getConfiguration(Package.name) - .update("deniedCommands", newValue, vscode.ConfigurationTarget.Global) + // Extension state keeps only the global layer, because enforcement re-adds the + // workspace layer. Storing the merged list here would double-home workspace + // entries and leak them again. + newValue = globalWrite + // Accumulate only after both writes succeed, so the disclosure never names a + // key whose save was abandoned. + externallyAddedCommandEntries.push(...externallyAdded) } else if (key === "allowedReadFiles" || key === "allowedWriteFiles") { const patterns = value ?? [] @@ -909,7 +1204,49 @@ export const webviewMessageHandler = async ( } } - await provider.contextProxy.setValue(key as keyof RooCodeSettings, newValue) + if (key === "allowedCommands" || key === "deniedCommands") { + // The configuration writes above already succeeded. A rejected state write + // therefore 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. 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.`, + ) + // The ack must agree with the toast the user just saw. A save whose stored + // copy diverged would otherwise let the dialog discard edits that a retry + // could still converge. + commandListSaveFailed = true + 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.`, + ) + } + } + + 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 @@ -929,7 +1266,9 @@ 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 reaches the result + // through its own flag. The error field stays with the thrown-failure path. + success: !failed && !commandListSaveFailed, ...(failed ? { error: failure instanceof Error ? failure.message : String(failure) } : {}), }) } @@ -1928,38 +2267,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 34865230c4d..dea085c3b90 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -42,6 +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 { seedCommandList } from "./utils/seedAllowedCommands" import { autoImportSettings } from "./utils/autoImportSettings" import { API } from "./extension/api" @@ -161,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. @@ -172,14 +170,63 @@ 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) + // Seed before the terminal registry initializes. The host may skip + // `deactivate()` after a failed activation, and only the host releases the + // registry's listeners. + // Each key has its own first-run guard, so a profile seeded by an older + // version still gets the deny-list migration. + try { + await seedCommandList(context.globalState, "allowedCommands") + await seedCommandList(context.globalState, "deniedCommands") + } catch (error) { + // The host may skip `deactivate()`, so this catch tears down before it + // rethrows. The order is reverse acquisition: telemetry shutdown, trace-sink + // clear, then channel dispose, each step awaited. A teardown failure is logged + // or dropped, never rethrown. Telemetry shutdown is bounded, so a stuck client + // cannot hang activation here. + try { + await telemetryService.shutdown() + } catch (shutdownError) { + outputChannel.appendLine( + `Failed to shut down telemetry service: ${shutdownError instanceof Error ? shutdownError.message : String(shutdownError)}`, + ) + } + // 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 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) { + 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 { + outputChannel.dispose() + } catch { + // The extension output sink is itself being torn down. + } + throw error } + // Initialize terminal shell execution handlers. + TerminalRegistry.initialize() + const contextProxy = await ContextProxy.getInstance(context) const updateTelemetryState = () => { const telemetrySetting = contextProxy.getGlobalState("telemetrySetting") ?? "unset" diff --git a/src/package.json b/src/package.json index 9bbb0530656..8631c3832d9 100644 --- a/src/package.json +++ b/src/package.json @@ -317,7 +317,8 @@ "git diff", "git show" ], - "description": "%commands.allowedCommands.description%" + "description": "%commands.allowedCommands.description%", + "scope": "resource" }, "zoo-code.deniedCommands": { "type": "array", @@ -325,7 +326,15 @@ "type": "string" }, "default": [], - "description": "%commands.deniedCommands.description%" + "description": "%commands.deniedCommands.description%", + "scope": "resource" + }, + "zoo-code.workspaceCommandListsEnabled": { + "type": "boolean", + "default": false, + "scope": "application", + "description": "%settings.workspaceCommandListsEnabled.description%", + "markdownDescription": "%settings.workspaceCommandListsEnabled.description%" }, "zoo-code.commandExecutionTimeout": { "type": "number", diff --git a/src/package.nls.ca.json b/src/package.nls.ca.json index d6b40efba32..a9eb6ed6bd5 100644 --- a/src/package.nls.ca.json +++ b/src/package.nls.ca.json @@ -50,5 +50,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. 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 a8bbadbf15e..62cd8af031b 100644 --- a/src/package.nls.de.json +++ b/src/package.nls.de.json @@ -50,5 +50,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. 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 26d9f87e9de..2e5be53518d 100644 --- a/src/package.nls.es.json +++ b/src/package.nls.es.json @@ -50,5 +50,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. 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 364a8878c43..61141cce16f 100644 --- a/src/package.nls.fr.json +++ b/src/package.nls.fr.json @@ -50,5 +50,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. 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 db70bc8417f..40e7fe3e366 100644 --- a/src/package.nls.hi.json +++ b/src/package.nls.hi.json @@ -50,5 +50,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 का कौनो प्रभाव नाहीं होतै। इसमें 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 b7e150ee530..a0fd29ce0e6 100644 --- a/src/package.nls.id.json +++ b/src/package.nls.id.json @@ -50,5 +50,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. 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 6d50b96bc47..ec2f47924bc 100644 --- a/src/package.nls.it.json +++ b/src/package.nls.it.json @@ -50,5 +50,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. 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 22f4f0dfce0..f36a306cf82 100644 --- a/src/package.nls.ja.json +++ b/src/package.nls.ja.json @@ -50,5 +50,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 d1f9afbc395..07169f6d372 100644 --- a/src/package.nls.json +++ b/src/package.nls.json @@ -50,5 +50,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. 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 48d8695a1d2..45311d6568a 100644 --- a/src/package.nls.ko.json +++ b/src/package.nls.ko.json @@ -50,5 +50,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 81113c4b5ac..c08d2278cc3 100644 --- a/src/package.nls.nl.json +++ b/src/package.nls.nl.json @@ -50,5 +50,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. 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 267ddff2775..027fb01f380 100644 --- a/src/package.nls.pl.json +++ b/src/package.nls.pl.json @@ -50,5 +50,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. 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 853832b699c..63d95da2ac5 100644 --- a/src/package.nls.pt-BR.json +++ b/src/package.nls.pt-BR.json @@ -50,5 +50,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. 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 d46ea142451..2e01907ed4c 100644 --- a/src/package.nls.ru.json +++ b/src/package.nls.ru.json @@ -50,5 +50,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 cbc81d959f6..06fcc53f02f 100644 --- a/src/package.nls.tr.json +++ b/src/package.nls.tr.json @@ -50,5 +50,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. 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 1ee4eabd706..ca143172310 100644 --- a/src/package.nls.vi.json +++ b/src/package.nls.vi.json @@ -50,5 +50,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. 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 85dafc3bc70..77d09f7ad18 100644 --- a/src/package.nls.zh-CN.json +++ b/src/package.nls.zh-CN.json @@ -50,5 +50,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 cda075e3069..0d6c152820e 100644 --- a/src/package.nls.zh-TW.json +++ b/src/package.nls.zh-TW.json @@ -50,5 +50,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/shared/tools.ts b/src/shared/tools.ts index ba799efe9c6..0f581a0686e 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -33,6 +33,12 @@ export type AutoApprovalContext = { * produce a verdict — they surface as a retryable tool error beforehand. */ dcgDecision?: DcgDecision + /** + * The directory that the command actually runs in (`execute_command` only). + * Command lists judge this directory, so a command in another workspace folder + * follows that folder's policy, not the task folder's. + */ + commandCwd?: string /** * Every file the tool action will access, one entry per file named in the * ask message (`tool` asks only). When present, auto-approval decides on diff --git a/src/utils/__tests__/autoImportCommandListRetention.spec.ts b/src/utils/__tests__/autoImportCommandListRetention.spec.ts new file mode 100644 index 00000000000..5ed3b2f07d0 --- /dev/null +++ b/src/utils/__tests__/autoImportCommandListRetention.spec.ts @@ -0,0 +1,295 @@ +// npx vitest utils/__tests__/autoImportCommandListRetention.spec.ts + +// Auto-import writes the command lists only into extension state. A save reads +// the user settings file and treats an entry that no configuration layer holds +// as removed there. These tests drive the real auto-import entry point and the +// real save path against one stateful settings file, so the deletion the two +// halves can cause together stays visible. + +vi.mock("vscode", () => ({ + ConfigurationTarget: { Global: 1, Workspace: 2, WorkspaceFolder: 3 }, + workspace: { + workspaceFolders: [{ uri: { fsPath: "/mock/workspace" } }], + getConfiguration: vi.fn(), + }, + window: { + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + showErrorMessage: vi.fn(), + }, +})) + +vi.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + hasInstance: vi.fn().mockReturnValue(false), + instance: { + captureSchemaValidationError: vi.fn(), + updateTelemetryState: vi.fn(), + }, + }, +})) + +vi.mock("../../api", () => ({ + buildApiHandler: vi.fn().mockReturnValue({ getModel: vi.fn() }), +})) + +vi.mock("../../api/providers/fetchers/modelCache") +vi.mock("../../api/providers/fetchers/lmstudio", () => ({ getLMStudioModels: vi.fn() })) +vi.mock("../../services/command/commands", () => ({ getCommands: vi.fn() })) +vi.mock("../../services/destructive-command-guard", () => ({ ensureDcgInstalled: vi.fn() })) +vi.mock("../../integrations/theme/getTheme", () => ({ getTheme: vi.fn().mockResolvedValue({}) })) +vi.mock("../../integrations/openai-codex/oauth", () => ({ + openAiCodexOAuthManager: { getAccessToken: vi.fn(), getAccountId: vi.fn() }, +})) +vi.mock("../../integrations/openai-codex/rate-limits", () => ({ + fetchOpenAiCodexRateLimitInfo: vi.fn(), +})) +vi.mock("../../core/webview/rulesMessageHandler", () => ({ + handleRequestRules: vi.fn(), + handleCreateRule: vi.fn(), + handleDeleteRule: vi.fn(), + handleOpenRuleFile: vi.fn(), + handleOpenRulesDirectory: vi.fn(), +})) +vi.mock("../../core/webview/diagnosticsHandler", () => ({ + generateErrorDiagnostics: vi.fn().mockResolvedValue({ success: true }), +})) + +// The provider modules load native SDKs at import time. The save path never +// builds a handler, so a bare double is enough. +vi.mock("@anthropic-ai/vertex-sdk", () => ({ AnthropicVertex: vi.fn() })) +vi.mock("google-auth-library", () => ({ GoogleAuth: vi.fn() })) +vi.mock("ollama", () => ({ Ollama: vi.fn() })) + +vi.mock("../../i18n", () => ({ + t: vi.fn((key: string) => key), + changeLanguage: vi.fn(), +})) + +vi.mock("fs/promises", () => ({ + __esModule: true, + default: { readFile: vi.fn() }, + readFile: vi.fn(), +})) + +vi.mock("os", async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, default: { ...actual, homedir: vi.fn(() => "/mock/home") }, homedir: vi.fn(() => "/mock/home") } +}) + +vi.mock("../fs", () => ({ fileExistsAtPath: vi.fn() })) + +vi.mock("../../core/config/ProviderSettingsManager", async (importOriginal) => { + const originalModule = await importOriginal() + return { + __esModule: true, + // The import needs the real schemas and a manager whose storage writes stay local. + ...(originalModule || {}), + ProviderSettingsManager: vi.fn().mockImplementation(function () { + return { + export: vi.fn().mockResolvedValue({ + apiConfigs: {}, + modeApiConfigs: {}, + currentApiConfigName: "default", + }), + import: vi.fn().mockResolvedValue({ success: true }), + listConfig: vi.fn().mockResolvedValue([]), + } + }), + } +}) + +vi.mock("../../core/config/ContextProxy") +vi.mock("../../core/config/CustomModesManager") + +import * as vscode from "vscode" +import type { Mock } from "vitest" +import fsPromises from "fs/promises" + +import type { ClineProvider } from "../../core/webview/ClineProvider" +import type { ContextProxy } from "../../core/config/ContextProxy" +import type { CustomModesManager } from "../../core/config/CustomModesManager" +import type { ProviderSettingsManager } from "../../core/config/ProviderSettingsManager" +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" + +import { Package } from "../../shared/package" +import { makeWorkspaceConfiguration } from "../../test-utils/vscode" +import { autoImportSettings } from "../autoImportSettings" +import { fileExistsAtPath } from "../fs" +import { webviewMessageHandler } from "../../core/webview/webviewMessageHandler" + +type CommandLists = { allowedCommands?: string[]; deniedCommands?: string[] } + +describe("auto-imported command lists survive a later save", () => { + // One settings file stands for the user-level layer. The mirror writes into + // it, and the save's snapshot reads it back. + let settingsFile: CommandLists + // The extension-state copy, which the import and the save both write. + let stateCopy: Record + let state: Record + let mockContextProxy: ContextProxy + let mockProviderSettingsManager: ProviderSettingsManager + let mockCustomModesManager: CustomModesManager + let update: Mock + + beforeEach(() => { + vi.clearAllMocks() + + // A user-level list predates the import, so the save has a layer to + // compare against. Without it the absent-layer exception would keep the + // entries for a different reason. + settingsFile = { allowedCommands: ["git"], deniedCommands: ["aws"] } + stateCopy = {} + state = {} + + // The double provides the proxy members the import calls: the bulk and + // single state writes, the provider settings write, and the read that + // backs the save's snapshot. + mockContextProxy = { + setValues: vi.fn(async (values: Record) => { + Object.assign(state, values) + Object.assign(stateCopy, values) + }), + setValue: vi.fn(async (key: string, value: unknown) => { + state[key] = value + stateCopy[key] = value as string[] | undefined + }), + setProviderSettings: vi.fn().mockResolvedValue(undefined), + getValue: vi.fn((key: string) => state[key]), + } as unknown as ContextProxy + + // The double provides the manager members the import calls: the profile + // export and import, and the config listing. + mockProviderSettingsManager = { + export: vi.fn().mockResolvedValue({ + apiConfigs: {}, + modeApiConfigs: {}, + currentApiConfigName: "default", + }), + import: vi.fn().mockResolvedValue({ success: true }), + listConfig: vi.fn().mockResolvedValue([]), + } as unknown as ProviderSettingsManager + + // The double provides updateCustomMode, the one member the import calls. + mockCustomModesManager = { + updateCustomMode: vi.fn().mockResolvedValue(undefined), + } as unknown as CustomModesManager + + // The shared double keeps the configuration type correct. The scripted + // members make the file stateful, as the real API is: a write changes + // what the next read reports. + const config = makeWorkspaceConfiguration({ + workspaceCommandListsEnabled: true, + autoImportSettingsPath: "/mock/auto-import.json", + }) + update = vi.fn(async (key: string, value: unknown) => { + settingsFile[key as keyof CommandLists] = value as string[] + }) + const inspect = vi.fn((key: string) => ({ + key, + globalValue: settingsFile[key as keyof CommandLists], + })) + config.update = update + // The double answers for every key with the stored list. The real member's + // generic return type cannot be expressed by a mock, so the cast stays here + // and names the member this double provides. + config.inspect = inspect as unknown as typeof config.inspect + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config) + + vi.mocked(fileExistsAtPath).mockResolvedValue(true) + ;(fsPromises.readFile as Mock).mockResolvedValue( + JSON.stringify({ + providerProfiles: { + currentApiConfigName: "imported-profile", + apiConfigs: { + "imported-profile": { + apiProvider: providerIdentifiers.anthropic, + anthropicApiKey: "test-key", + }, + }, + }, + globalSettings: { + allowedCommands: ["git", "imported"], + deniedCommands: ["rm -rf"], + }, + }), + ) + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + // Double provides the members these two paths call: the import's state + // writes, and the save's reads and writes. + const provider = () => + ({ + contextProxy: mockContextProxy, + postStateToWebview: vi.fn().mockResolvedValue(undefined), + postMessageToWebview: vi.fn().mockResolvedValue(undefined), + log: vi.fn(), + getCurrentTask: vi.fn().mockReturnValue(undefined), + getSkillsManager: vi.fn().mockReturnValue(undefined), + getMcpHub: vi.fn().mockReturnValue(undefined), + cwd: "/mock/workspace", + context: { globalStorageUri: { fsPath: "/mock/storage" } }, + }) as unknown as ClineProvider + + const runAutoImport = async () => { + // Double provides only appendLine, the sole OutputChannel member the SUT calls. + const outputChannel = { appendLine: vi.fn() } as unknown as vscode.OutputChannel + await autoImportSettings(outputChannel, { + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + } + + // The dialog submits the list it displayed, with the baseline it was posted. + const saveDisplayedLists = async () => + webviewMessageHandler(provider(), { + type: "updateSettings", + updatedSettings: { + allowedCommands: stateCopy.allowedCommands, + deniedCommands: stateCopy.deniedCommands, + }, + commandListBaseline: { + allowedCommands: stateCopy.allowedCommands, + deniedCommands: stateCopy.deniedCommands, + workspaceCommandListsEnabled: true, + }, + }) + + it("writes the imported command lists into the settings file", async () => { + await runAutoImport() + + 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) + // The import's own state write still holds the lists. + expect(stateCopy.allowedCommands).toEqual(["git", "imported"]) + expect(stateCopy.deniedCommands).toEqual(["rm -rf"]) + }) + + it("keeps the imported entries through a later unrelated save", async () => { + await runAutoImport() + + await saveDisplayedLists() + + // Both lists survive in the settings file, not just the state copy. + expect(settingsFile.allowedCommands).toEqual(["git", "imported"]) + expect(settingsFile.deniedCommands).toEqual(["rm -rf"]) + // The save reports retention, so it discloses no file-side change. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("does not mirror the lists when the import fails", async () => { + ;(fsPromises.readFile as Mock).mockResolvedValue("invalid json") + + await runAutoImport() + + // The pre-existing layer stays exactly as it was. + expect(settingsFile).toEqual({ allowedCommands: ["git"], deniedCommands: ["aws"] }) + expect(update).not.toHaveBeenCalled() + }) +}) diff --git a/src/utils/__tests__/autoImportSettings.spec.ts b/src/utils/__tests__/autoImportSettings.spec.ts index 84fc16d3945..1e08ede3f90 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. diff --git a/src/utils/__tests__/seedAllowedCommands.spec.ts b/src/utils/__tests__/seedAllowedCommands.spec.ts new file mode 100644 index 00000000000..8019c796e31 --- /dev/null +++ b/src/utils/__tests__/seedAllowedCommands.spec.ts @@ -0,0 +1,429 @@ +// npx vitest run utils/__tests__/seedAllowedCommands.spec.ts + +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 { seedCommandList } from "../seedAllowedCommands" + +// 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, +})) + +vi.mock("vscode", () => ({ + workspace: { + get workspaceFolders() { + return workspaceState.workspaceFolders + }, + getConfiguration: vi.fn(), + }, +})) + +interface ConfigDouble { + inspect?: { + key: string + defaultValue?: string[] + globalValue?: string[] + workspaceValue?: string[] + // VS Code reports `null` for a key that settings.json sets to null. + workspaceFolderValue?: string[] | null + } + effective?: string[] + inspectThrows?: boolean + gate?: boolean +} + +function mockConfiguration({ inspect, effective = [], inspectThrows = false, gate = false }: ConfigDouble = {}) { + // 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 gate reads on its own: its default is off, so a test must ask for an enforced layer. + vi.mocked(config.get).mockImplementation((section: string) => + section === "workspaceCommandListsEnabled" ? gate : effective, + ) + vi.mocked(config.inspect).mockImplementation(() => { + if (inspectThrows) { + throw new Error("configuration access failed") + } + if (inspect === undefined) { + return undefined + } + // No resource => no folder layer, as in real VS Code. + return scope === undefined || scope === null ? { ...inspect, workspaceFolderValue: undefined } : inspect + }) + return config + }, + ) +} + +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) + } + + // 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)), + update: vi.fn().mockImplementation(async (key: string, value: unknown) => { + store.set(key, value) + }), + } +} + +describe("seedCommandList", () => { + beforeEach(() => { + vi.clearAllMocks() + workspaceState.workspaceFolders = undefined + }) + + it("leaves global state unset when only a workspace-scoped value exists", async () => { + // Reading get() would seed the workspace override into global state. The + // override also replaced the declared default, so the default must not come + // back either. + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + globalValue: undefined, + workspaceValue: ["docker"], + }, + effective: ["docker"], + // Suppression applies only while the gate enforces the workspace layer. + gate: true, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + 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 resource-scoped lookup. An unscoped + // seed would see nothing and re-grant the suppressed default. + 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"], + }, + gate: true, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + // 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 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 }] + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + workspaceFolderValue: ["docker"], + }, + gate: true, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + 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: an empty list + // opts out of the default as deliberately as a populated one. + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + globalValue: undefined, + workspaceValue: [], + }, + gate: true, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + 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({ + inspect: { key: "allowedCommands", defaultValue }, + effective: defaultValue, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) + // Copy, like the global-value path: no shared reference with the configuration. + expect(globalState.update.mock.calls[0][1]).not.toBe(defaultValue) + + // Gate on with no override: only an actual override suppresses the default. + 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 seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", ["git"]) + expect(globalState.get("allowedCommands")).toEqual(["git"]) + }) + + it("seeds an explicitly empty global value instead of the populated default", async () => { + // An empty global list is a deliberate opt-out. Persist [] so global state + // counts as seeded and the defaults stay out. + mockConfiguration({ + inspect: { + key: "allowedCommands", + defaultValue: ["git log", "git diff", "git show"], + globalValue: [], + }, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + 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"]) + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toEqual(["npm"]) + }) + + it("leaves an explicitly empty global-state list untouched", async () => { + // 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([]) + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + expect(globalState.get("allowedCommands")).toEqual([]) + }) + + it("composes a later workspace override as a union with the seeded defaults", async () => { + // A fresh activation seeds the default. A later workspace override is never + // persisted, because the guard returns early. Enforcement unions the two + // layers and the matcher picks the governing entry. + const defaultValue = ["git log", "git diff", "git show"] + mockConfiguration({ + inspect: { key: "allowedCommands", defaultValue }, + effective: defaultValue, + }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + expect(globalState.update).toHaveBeenCalledExactlyOnceWith("allowedCommands", defaultValue) + + // Later activation with an override present: the guard early-returns first. + mockConfiguration({ + inspect: { key: "allowedCommands", defaultValue, workspaceValue: ["docker ps"] }, + effective: ["docker ps"], + }) + + await seedCommandList(globalState, "allowedCommands") + expect(globalState.update).toHaveBeenCalledTimes(1) + expect(globalState.get("allowedCommands")).toEqual(defaultValue) + + // 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"]) + 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. A wrong key would find + // nothing. No folder open means an unscoped (section, undefined) lookup. + mockConfiguration({ inspect: { key: "allowedCommands", globalValue: ["git"] } }) + // Complete Memento double: no type assertion at the call site. + const globalState: vscode.Memento = { + keys: () => [], + get: vi.fn(), + update: vi.fn(), + } + + await seedCommandList(globalState, "allowedCommands") + + 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"]) + }) + + it("leaves global state untouched when there is no inspect result at all", async () => { + mockConfiguration({ inspect: undefined, effective: ["git"] }) + const globalState = mockMemento() + + await seedCommandList(globalState, "allowedCommands") + + expect(globalState.update).not.toHaveBeenCalled() + }) + + it("skips the seed without throwing when configuration access fails", async () => { + mockConfiguration({ inspectThrows: true }) + const globalState = mockMemento() + + await expect(seedCommandList(globalState, "allowedCommands")).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 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: 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() + + 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: a seeded allowlist must not block the deny migration. + 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 () => { + // Gate off: the override governs nothing, so it must not withhold the default. + 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 () => { + // An enforced workspace list replaces the default, so the seed must not + // re-grant the approvals it 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/autoImportSettings.ts b/src/utils/autoImportSettings.ts index 3c8773fb6bd..926408bc214 100644 --- a/src/utils/autoImportSettings.ts +++ b/src/utils/autoImportSettings.ts @@ -44,6 +44,9 @@ export async function autoImportSettings( }) if (result.success) { + // 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) { diff --git a/src/utils/seedAllowedCommands.ts b/src/utils/seedAllowedCommands.ts new file mode 100644 index 00000000000..a99d88789f1 --- /dev/null +++ b/src/utils/seedAllowedCommands.ts @@ -0,0 +1,71 @@ +import * as vscode from "vscode" + +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 + * state, only when global state holds no list for that key. Each key has its + * own guard, so a seeded allowlist does not block a later deny-list migration. + * + * The seed reads `inspect()`, not `get()`. `get()` folds in workspace + * overrides, which would leak a project's `.vscode/settings.json` into global + * state for good. The lookup shares `commandListConfiguration()` with the + * read and write paths, so the folder layer is visible where enforcement sees + * it. + * + * Selection: the global value wins. With no value set anywhere, the package + * default is seeded, because enforcement never falls back to it. An enforced + * 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. 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. + */ +export async function seedCommandList(globalState: vscode.Memento, configKey: CommandListConfigKey): Promise { + if (globalState.get(configKey)) { + return + } + + // 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: CommandListSeedInspection | undefined + try { + inspected = commandListConfiguration().inspect(configKey) + } catch { + return + } + + // 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 ?? + (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(configKey, [...seedValue]) +} diff --git a/webview-ui/src/components/settings/SettingsView.tsx b/webview-ui/src/components/settings/SettingsView.tsx index c7cb8f9f093..9a95c4df7b5 100644 --- a/webview-ui/src/components/settings/SettingsView.tsx +++ b/webview-ui/src/components/settings/SettingsView.tsx @@ -91,9 +91,9 @@ 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 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 @@ -104,6 +104,115 @@ 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" +// Snapshot of the command lists in a state object. Compare entries by value: +// each state post delivers freshly deserialized arrays. +interface CommandListSnapshot { + allowedCommands?: string[] + deniedCommands?: string[] + 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 ?? [], + state.deniedCommands ?? [], + 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])) + +// 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)) + ) +} + +// 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 } @@ -161,12 +270,71 @@ const SettingsView = forwardRef(({ onDone, t const confirmDialogHandler = useRef<() => void>() const [cachedState, setCachedState] = useState(() => extensionState) - // The save waiting for the host's answer, and the form state it sent. The "unsaved changes" flag stays on until the + // The save waiting for the host's answer. The "unsaved changes" flag stays on until the // host says it was stored, and then goes off only if the user has not edited anything since. const [pendingSaveId, setPendingSaveId] = useState(undefined) - const sentState = useRef(undefined) + // Raised by every user edit to a cached field and lowered at each save dispatch. The + // settle reads it instead of comparing the buffer's identity, because the host's own + // refresh replaces the buffer as well, and an identity check cannot tell the two apart. + // It is deliberately not cleared when a save settles or times out: the settle has + // already read it, and the next dispatch resets it. `commandListsTouched` has the other + // lifetime - it is cleared only on a clean settle - so the two flags reset at different + // points by design. + const userEditedDuringSave = useRef(false) const latestCachedState = useRef(cachedState) latestCachedState.current = cachedState + // The live host state, read when a save settles. + const latestExtensionState = useRef(extensionState) + // 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, 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[]] + // 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 + // 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) const { alwaysAllowReadOnly, @@ -255,6 +423,11 @@ const SettingsView = forwardRef(({ onDone, t setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) prevApiConfigName.current = currentApiConfigName prevMode.current = mode + 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. + baselineGeneration.current += 1 setChangeDetected(false) }, [currentApiConfigName, mode, extensionState]) @@ -266,142 +439,227 @@ const SettingsView = forwardRef(({ onDone, t handledSettingsImportedAt.current = settingsImportedAt setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState })) + lastDisplayedCommandSnapshot.current = displayedCommandListStamp(extensionState) + commandListsTouched.current = false + // The import replaced the buffer the pending save submitted. + baselineGeneration.current += 1 setChangeDetected(false) }, [settingsImportedAt, extensionState]) - const setCachedStateField: SetCachedStateField = useCallback((field, value) => { - setCachedState((prevState) => { - if (prevState[field] === value) { - return prevState + // 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 this effect never clears the dirty flag. + useEffect(() => { + const snapshot = commandListSnapshot(extensionState) + // 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 + } + + // Compute the merge here, outside the state update, because a state update + // must stay a pure function of the state it applies to. + const prevState = latestCachedState.current + const merged: CommandListSnapshot = {} + + if (!commandListsTouched.current) { + if (!commandListsEquivalent(prevState.allowedCommands, extensionState.allowedCommands)) { + merged.allowedCommands = extensionState.allowedCommands } + if (!commandListsEquivalent(prevState.deniedCommands, extensionState.deniedCommands)) { + merged.deniedCommands = extensionState.deniedCommands + } + } + if (prevState.workspaceCommandListsEnabled !== extensionState.workspaceCommandListsEnabled) { + merged.workspaceCommandListsEnabled = extensionState.workspaceCommandListsEnabled + } - setChangeDetected(true) - return { ...prevState, [field]: value } - }) + // The stamp records what this merge leaves on screen, never the posted state. + // A held-back entry was never displayed. 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. 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 })) + } + }, [extensionState]) + + // One raising point for the form's dirty signal and the save settle's edit signal, + // so no user-edit path can mark the form dirty without telling the settle that the + // buffer holds work the host's own refresh did not produce. + const markUserEdit = useCallback(() => { + setChangeDetected(true) + userEditedDuringSave.current = true }, []) + const setCachedStateField: SetCachedStateField = useCallback( + (field, value) => { + // A no-op set must own neither the lists nor the edit signal, so the guard runs + // before the update and stays outside the pure updater. + if (latestCachedState.current[field] === value) { + return + } + + // Only a changed command list is an edit the save has to claim ownership of. + if (field === "allowedCommands" || field === "deniedCommands") { + commandListsTouched.current = true + } + + markUserEdit() + setCachedState((prevState) => ({ ...prevState, [field]: value })) + }, + [markUserEdit], + ) + const setApiConfigurationField = useCallback( (field: K, value: ProviderSettings[K], isUserAction: boolean = true) => { - setCachedState((prevState) => { - if (prevState.apiConfiguration[field] === value) { - return prevState - } + const previousValue = latestCachedState.current.apiConfiguration[field] - const previousValue = prevState.apiConfiguration[field] + if (previousValue === value) { + return + } - // Helper to check if two values are semantically equal - const areValuesEqual = (a: any, b: any): boolean => { - if (a === b) return true - if (a == null && b == null) return true - if (typeof a !== typeof b) return false - if (typeof a === "object" && typeof b === "object") { - return JSON.stringify(a) === JSON.stringify(b) - } - return false + // Helper to check if two values are semantically equal + const areValuesEqual = (a: any, b: any): boolean => { + if (a === b) return true + if (a == null && b == null) return true + if (typeof a !== typeof b) return false + if (typeof a === "object" && typeof b === "object") { + return JSON.stringify(a) === JSON.stringify(b) } + return false + } - // Only skip change detection for automatic initialization (not user actions) - // This prevents the dirty state when the component initializes and auto-syncs values - const isInitialSync = - !isUserAction && - (previousValue === undefined || previousValue === "" || previousValue === null) && - value !== undefined && - value !== "" && - value !== null + // Only skip change detection for automatic initialization (not user actions) + // This prevents the dirty state when the component initializes and auto-syncs values + const isInitialSync = + !isUserAction && + (previousValue === undefined || previousValue === "" || previousValue === null) && + value !== undefined && + value !== "" && + value !== null - // Also skip if it's an automatic sync with semantically equal values - const isAutomaticNoOpSync = !isUserAction && areValuesEqual(previousValue, value) + // Also skip if it's an automatic sync with semantically equal values + const isAutomaticNoOpSync = !isUserAction && areValuesEqual(previousValue, value) - if (!isInitialSync && !isAutomaticNoOpSync) { - setChangeDetected(true) - } - return { ...prevState, apiConfiguration: { ...prevState.apiConfiguration, [field]: value } } - }) + if (!isInitialSync && !isAutomaticNoOpSync) { + markUserEdit() + } + + setCachedState((prevState) => ({ + ...prevState, + apiConfiguration: { ...prevState.apiConfiguration, [field]: value }, + })) }, - [], + [markUserEdit], ) - const setExperimentEnabled: SetExperimentEnabled = useCallback((id: ExperimentId, enabled: boolean) => { - setCachedState((prevState) => { - if (prevState.experiments?.[id] === enabled) { - return prevState + const setExperimentEnabled: SetExperimentEnabled = useCallback( + (id: ExperimentId, enabled: boolean) => { + if (latestCachedState.current.experiments?.[id] === enabled) { + return } - setChangeDetected(true) - return { ...prevState, experiments: { ...prevState.experiments, [id]: enabled } } - }) - }, []) + markUserEdit() + setCachedState((prevState) => ({ ...prevState, experiments: { ...prevState.experiments, [id]: enabled } })) + }, + [markUserEdit], + ) - const setTelemetrySetting = useCallback((setting: TelemetrySetting) => { - setCachedState((prevState) => { - if (prevState.telemetrySetting === setting) { - return prevState + const setTelemetrySetting = useCallback( + (setting: TelemetrySetting) => { + if (latestCachedState.current.telemetrySetting === setting) { + return } - setChangeDetected(true) - return { ...prevState, telemetrySetting: setting } - }) - }, []) + markUserEdit() + setCachedState((prevState) => ({ ...prevState, telemetrySetting: setting })) + }, + [markUserEdit], + ) - const setDebug = useCallback((debug: boolean) => { - setCachedState((prevState) => { - if (prevState.debug === debug) { - return prevState + const setDebug = useCallback( + (debug: boolean) => { + if (latestCachedState.current.debug === debug) { + return } - setChangeDetected(true) - return { ...prevState, debug } - }) - }, []) + markUserEdit() + setCachedState((prevState) => ({ ...prevState, debug })) + }, + [markUserEdit], + ) - const setImageGenerationProvider = useCallback((provider: ImageGenerationProvider) => { - setCachedState((prevState) => { - if (prevState.imageGenerationProvider !== provider) { - setChangeDetected(true) + const setImageGenerationProvider = useCallback( + (provider: ImageGenerationProvider) => { + if (latestCachedState.current.imageGenerationProvider === provider) { + return } - return { ...prevState, imageGenerationProvider: provider } - }) - }, []) + markUserEdit() + setCachedState((prevState) => ({ ...prevState, imageGenerationProvider: provider })) + }, + [markUserEdit], + ) - const setOpenRouterImageApiKey = useCallback((apiKey: string) => { - setCachedState((prevState) => { - if (prevState.openRouterImageApiKey !== apiKey) { - setChangeDetected(true) + const setOpenRouterImageApiKey = useCallback( + (apiKey: string) => { + if (latestCachedState.current.openRouterImageApiKey === apiKey) { + return } - return { ...prevState, openRouterImageApiKey: apiKey } - }) - }, []) + markUserEdit() + setCachedState((prevState) => ({ ...prevState, openRouterImageApiKey: apiKey })) + }, + [markUserEdit], + ) - const setImageGenerationSelectedModel = useCallback((model: string) => { - setCachedState((prevState) => { - if (prevState.openRouterImageGenerationSelectedModel !== model) { - setChangeDetected(true) + const setImageGenerationSelectedModel = useCallback( + (model: string) => { + if (latestCachedState.current.openRouterImageGenerationSelectedModel === model) { + return } - return { ...prevState, openRouterImageGenerationSelectedModel: model } - }) - }, []) - - const setCustomSupportPromptsField = useCallback((prompts: Record) => { - setCachedState((prevState) => { - const previousStr = JSON.stringify(prevState.customSupportPrompts) - const newStr = JSON.stringify(prompts) + markUserEdit() + setCachedState((prevState) => ({ ...prevState, openRouterImageGenerationSelectedModel: model })) + }, + [markUserEdit], + ) - if (previousStr === newStr) { - return prevState + const setCustomSupportPromptsField = useCallback( + (prompts: Record) => { + if (JSON.stringify(latestCachedState.current.customSupportPrompts) === JSON.stringify(prompts)) { + return } - setChangeDetected(true) - return { ...prevState, customSupportPrompts: prompts } - }) - }, []) + markUserEdit() + setCachedState((prevState) => ({ ...prevState, customSupportPrompts: prompts })) + }, + [markUserEdit], + ) 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. + // The host writes time and date settings one at a time, and a write can fail. + // 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") || @@ -409,15 +667,62 @@ const SettingsView = forwardRef(({ onDone, t const handleSubmit = () => { if (isSettingValid) { - const saveId = displayChanged ? nextSaveRequestId() : undefined + 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 + // rejected list edit would look saved. + const saveId = displayChanged || commandListsTouched.current ? nextSaveRequestId() : undefined if (saveId) { - sentState.current = cachedState + 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, + } + dispatchedCommandSnapshot.current = commandListSnapshot({ + allowedCommands: lastDisplayedAllowed, + deniedCommands: lastDisplayedDenied, + workspaceCommandListsEnabled: gateAtSubmit, + }) setPendingSaveId(saveId) } + // Lowered at dispatch, so an edit that lands before the post counts as one made + // before the save. No suspension point sits between this line and the post. + userEditedDuringSave.current = false vscode.postMessage({ type: "updateSettings", requestId: saveId, + commandListBaseline: { + allowedCommands: lastDisplayedAllowed, + deniedCommands: lastDisplayedDenied, + // 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 older + // 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), + // 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, alwaysAllowReadOnly: alwaysAllowReadOnly ?? undefined, @@ -504,9 +809,21 @@ const SettingsView = forwardRef(({ onDone, t vscode.postMessage({ type: "telemetrySetting", text: telemetrySetting }) vscode.postMessage({ type: "debugSetting", bool: cachedState.debug }) - // 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) + 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: + // 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) + } } } @@ -514,22 +831,149 @@ const SettingsView = forwardRef(({ onDone, t if (!pendingSaveId) return const settle = (success: boolean) => { + settleSave.current = undefined + heldSaveResult.current = undefined 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) + + // 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 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 + // 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 { + allowedCommands: stampAllowed = [], + deniedCommands: stampDenied = [], + workspaceCommandListsEnabled: stampGate, + globalAllowedCommands: stampGlobalAllowed, + globalDeniedCommands: stampGlobalDenied, + } = readDisplayedCommandListStamp(lastDisplayedCommandSnapshot.current) + const reconcileList = ( + baselined: string[], + sent: string[], + refreshed: string[] | undefined, + stamped: string[], + ) => + commandListsEquivalent(baselined, sent) + ? stamped + : commandListWriteLanded(baselined, sent, refreshed) + ? sent + : baselined + const allowedWriteLanded = commandListWriteLanded(save.baselined[0], save.sent[0], refreshedAllowed) + const deniedWriteLanded = commandListWriteLanded(save.baselined[1], save.sent[1], refreshedDenied) + // 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 + // 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, + globalAllowedCommands: allowedWriteLanded ? refreshedGlobalAllowed : stampGlobalAllowed, + globalDeniedCommands: deniedWriteLanded ? refreshedGlobalDenied : stampGlobalDenied, + }) + + // 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) { + 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 = displayedCommandListStamp({ + allowedCommands: adoptedAllowed, + deniedCommands: adoptedDenied, + workspaceCommandListsEnabled: adoptedGate ?? stampGate, + globalAllowedCommands: latestExtensionState.current.globalAllowedCommands, + globalDeniedCommands: latestExtensionState.current.globalDeniedCommands, + }) + 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]) @@ -552,6 +996,11 @@ const SettingsView = forwardRef(({ onDone, t if (confirm) { // Discard changes: Reset state and flag setCachedState(extensionState) // Revert to original state + 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. + 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.change-detection.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.change-detection.spec.tsx index 6704aa1cf05..e1c141f0601 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,107 @@ 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 now-displayed list, not the stale one from open time. + 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 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({ + 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 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"], + 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 6d76a43d646..7fd2899eb96 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.spec.tsx @@ -778,6 +778,262 @@ 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 tells "user deleted this" from "the file gained this" with the + // 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"], + globalAllowedCommands: [], + globalDeniedCommands: [], + 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: [], + workspaceAllowedCommands: ["git"], + workspaceDeniedCommands: [], + // The global layer the dialog showed beside those lists. + globalAllowedCommands: [], + globalDeniedCommands: [], + }, + 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"], + globalAllowedCommands: [], + globalDeniedCommands: [], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: true, + }, + }) + + const content = screen.getByTestId("settings-content") + // A dirty list edit enables the save button. + 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")) + + // The request id marks the save the host must answer, which is the save whose + // settle reads the edit tracking. The gate reaches the host through the + // baseline's third slot alone. + expect(vscode.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + requestId: expect.any(String), + commandListBaseline: { + allowedCommands: ["git"], + deniedCommands: [], + workspaceCommandListsEnabled: true, + workspaceAllowedCommands: ["git"], + workspaceDeniedCommands: [], + globalAllowedCommands: [], + globalDeniedCommands: [], + }, + updatedSettings: expect.not.objectContaining({ + workspaceCommandListsEnabled: expect.anything(), + }), + }), + ) + }) + + it("keeps the stamped gate paired with held-back lists when the gate flips during a buffered edit", async () => { + // 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"], + globalAllowedCommands: [], + globalDeniedCommands: [], + 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"], + globalAllowedCommands: [], + globalDeniedCommands: [], + 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, + 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: [], + }, + }), + ) + }) + + it("sends the merged gate with the merged lists when no list edit is in flight", async () => { + // 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"], + globalAllowedCommands: [], + globalDeniedCommands: [], + alwaysAllowExecute: true, + workspaceCommandListsEnabled: false, + }, + }) + + await act(async () => { + mockPostMessage({ + allowedCommands: ["git", "curl"], + globalAllowedCommands: [], + globalDeniedCommands: [], + 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, + workspaceAllowedCommands: ["git", "curl"], + workspaceDeniedCommands: [], + globalAllowedCommands: [], + globalDeniedCommands: [], + }, + updatedSettings: expect.objectContaining({ allowedCommands: ["git", "curl"] }), + }), + ) + }) + + it("carries the gate displayed as off in the save baseline without persisting it", () => { + // 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"], + globalAllowedCommands: ["git"], + globalDeniedCommands: [], + 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, + // 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: [], + // The global layer itself is still posted, and it holds the entry. + globalAllowedCommands: ["git"], + globalDeniedCommands: [], + }, + 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 758161c1488..fd306be42cb 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,16 +1,21 @@ 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" + 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, @@ -249,6 +254,9 @@ vi.mock("../SettingsSearch", () => ({ import { useExtensionState } from "@src/context/ExtensionStateContext" import ApiOptions from "../ApiOptions" +import { AutoApproveSettings } from "../AutoApproveSettings" +import { About } from "../About" +import { ExperimentalSettings } from "../ExperimentalSettings" describe("SettingsView - Unsaved Changes Detection", () => { let queryClient: QueryClient @@ -318,6 +326,10 @@ describe("SettingsView - Unsaved Changes Detection", () => { reasoningBlockCollapsed: true, } + afterEach(() => { + vi.useRealTimers() + }) + beforeEach(() => { vi.clearAllMocks() // Reset the ApiOptions mock to its default implementation @@ -757,4 +769,1495 @@ describe("SettingsView - Unsaved Changes Detection", () => { expect(onDone).toHaveBeenCalledOnce() expect(postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "upsertApiConfiguration" })) }) + + it("keeps an in-flight deny-list edit when an external list update arrives while the dialog is open", async () => { + // Drive the real setter through a double section, so the buffered edit looks + // like a user edit. + 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()) + + ;(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("folds an external list update into the buffer after a no-op list set or a non-list edit", async () => { + // Only an edit that changes a list claims ownership. A no-op set or a + // non-list edit must leave the lists open to external updates. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + + +
+ ), + ) + const view = renderWithExtensionState(, { + queryClient, + }) + + // An edit outside the lists leaves them open, so the external deny entry enters 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"])), + ) + + // A re-set to the same array changes nothing, so the next update 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 must hold the lists displayed before the edit. Folding the post + // in would let the save erase a never-displayed entry as a deletion, and + // folding the buffer in would resurrect an in-flight deletion. + 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 pre-edit lists. + 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 reverse case: a displayed entry that the user then deleted must stay in + // the baseline so the save applies the deletion. A buffer-folded baseline + // would re-admit it as an external addition. + ;(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 adds a never-displayed entry, and the held merge keeps the deletion. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf", "docker"], + }) + view.rerender() + + fireEvent.click(screen.getByTestId("save-button")) + + // The baseline keeps the deleted entry so the save applies the deletion. It + // excludes the never-displayed "docker", so the save keeps it and warns. + expect(postMessage).toHaveBeenCalledWith( + expect.objectContaining({ + type: "updateSettings", + commandListBaseline: { allowedCommands: [], deniedCommands: ["rm -rf"] }, + updatedSettings: expect.objectContaining({ deniedCommands: [] }), + }), + ) + }) + + 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 as the user left it. Releasing the hold + // at submit would let the post-failure 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 routes this save through the answered path, + // 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 after the rejected write, and 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"])) + + // The retry submits the buffered edit, not the replacing refresh. The call + // count plus the last baseline prove the retry did it. + fireEvent.click(screen.getByTestId("save-button")) + 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("requests an answer for a list-only save and keeps the buffered edit when the host reports failure", async () => { + // A rejected list write arrives through the same answer as a failed display + // write, so a list-only save carries a request id and the answer decides. + // Releasing the hold at submit would show a rejected write as saved. + 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")) + + expect(updateSettingsPosts()).toHaveLength(1) + const saveId = lastSaveRequestId(postMessage) + expect(saveId).toBeDefined() + expect(screen.getByTestId("save-button")).toBeDisabled() // waiting for the host's answer + + // The host refreshes with the write unlanded, so the submitted entry is absent, then reports failure. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: [], + }) + view.rerender() + answerSave(saveId, { success: false, error: "storage unavailable" }) + + // The failure keeps the edit on screen, still holds 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 case: the refresh shows the submitted list, so the settle releases the + // hold and the flag. A later change enters without setting the flag again. + 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 cannot overwrite an in-flight edit. + ;(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() + }) + + 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, yet each list's write result comes from the refresh + // before the answer. A landed list keeps its advanced baseline, and an unwritten one + // rolls back, so a deletion stays a user deletion on retry. + ;(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 routes this save through the answered path, + // 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 not the deny list, then reported failure, + // so the refresh carries only the allow list's new entry. + ;(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: [] }), + }), + ) + }) + + 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 + // The host writes the list before answering. Observing the submitted entry in + // the refresh, not the answer alone, 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()) + + // The lists committed, so a later host update cannot overwrite an in-flight edit. + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + deniedCommands: ["rm -rf"], + }) + view.rerender() + await waitFor(() => + expect(screen.getByTestId("current-deny-list")).toHaveTextContent(JSON.stringify(["rm -rf"])), + ) + }) + + it("keeps a silently rejected list write dirty and rolls back only its baseline when the host reports success", async () => { + // One answer covers the whole payload, so a rejected list write can arrive + // with success set to true. Each list's own result comes from the refresh. The + // allow list carries the submitted entry and keeps its advanced baseline. The + // deny list comes back unchanged, so its deletion rolls back. The flag stays + // on. + ;(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 routes this save through the answered path, + // 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 write, and + // still answered success. + ;(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 deletion holds 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([])) + + // Retry classifies each list by its own result: the landed allow list keeps + // its advanced baseline, and the rolled-back deny baseline keeps the deletion. + 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("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 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"], + 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 + // exact object it submitted. An equal-valued copy would count as a mid-save + // edit and keep the flag on. + ;(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()) + + // The display difference puts the save on the answered path. Its lists repeat + // what the dialog displayed, so the held merge rejects 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 changed lists before this save's write. The + // in-flight deletion still refuses them, so the post must not touch the 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 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()) + + // 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 () => { + // The host posts the refresh before its answer, and the settle must see that + // refresh: the submitted list there records the write as landed. Using the + // pre-refresh state would report a landed write as missing. + ;(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 routes this save through the answered path, + // without touching the buffered command lists. + ;(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 posts with the landed deletion, 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 rollback either: the advanced baseline survives, so a re-edit posts + // the landed list as the displayed baseline. + 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 with value-equal lists must leave the buffer object untouched, even + // when it differs from the baseline in the gate slot. The save settles by + // comparing the buffer against the exact object it submitted, and fresh + // equal-valued arrays would count as a mid-save edit. + ;(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 enters the + // buffer while the held-back lists keep the baseline at the pre-flip gate. + 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 difference puts this save on the answered path. The refresh + // shows the deletion landed, so the answer releases the flag and the hold. + 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 follows: a non-list edit sets the flag again. The host restates + // the file with fresh equal-valued arrays, and the lists match the buffer. The + // merge therefore folds nothing, and the buffer stays the submitted object. + 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()) + + // 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 () => { + // Every edited list landed in the refresh, so the flag clears and the lists + // accept external updates again. + ;(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 cannot overwrite an in-flight edit. + ;(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("settles a save as clean when the host merges its refresh, and stays dirty for a user edit during the save", async () => { + // A host refresh that lands during a pending save replaces the edit buffer on + // its own, so the settle must not read the replacement as unsaved work. A real + // edit in the same window must still keep the form dirty. + vi.mocked(AutoApproveSettings).mockImplementation( + ({ setCachedStateField, deniedCommands }: React.ComponentProps) => ( +
+ {JSON.stringify(deniedCommands)} + + +
+ ), + ) + + 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() + } + }) + + 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"])), + ) + }) + + 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() + + // 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 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() + + // 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) + }) + 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) + }) })