From 7343b6f43276ec45ae10df10d6e591f91edd05e9 Mon Sep 17 00:00:00 2001 From: dorien-koelemeijer <62866702+dorien-koelemeijer@users.noreply.github.com> Date: Wed, 16 Sep 2026 15:08:33 +0000 Subject: [PATCH] fix(desktop): require recipe consent before session/new spawns extensions (#12094) Co-authored-by: Claude Fable 5.1 Co-authored-by: Jasper Hugo --- ui/desktop/src/App.tsx | 10 +- .../src/__tests__/createSession.test.ts | 22 +++ .../createSessionRecipeConsent.test.ts | 139 ++++++++++++++++++ ui/desktop/src/acp/errors.ts | 11 ++ ui/desktop/src/components/BaseChat.tsx | 58 +------- ui/desktop/src/components/ChatInput.tsx | 8 +- .../RecipeConsentModalContainer.tsx | 33 +++++ .../src/components/recipes/RecipesView.tsx | 4 +- ui/desktop/src/recipe/consent.test.ts | 29 ++++ ui/desktop/src/recipe/consent.ts | 55 +++++++ ui/desktop/src/sessions.ts | 41 +++++- 11 files changed, 343 insertions(+), 67 deletions(-) create mode 100644 ui/desktop/src/__tests__/createSessionRecipeConsent.test.ts create mode 100644 ui/desktop/src/components/RecipeConsentModalContainer.tsx create mode 100644 ui/desktop/src/recipe/consent.test.ts create mode 100644 ui/desktop/src/recipe/consent.ts diff --git a/ui/desktop/src/App.tsx b/ui/desktop/src/App.tsx index f5b1d5213..bf4b324a5 100644 --- a/ui/desktop/src/App.tsx +++ b/ui/desktop/src/App.tsx @@ -5,7 +5,12 @@ import { importNostrSessionFromDeepLink } from './sessionLinks'; import { ErrorUI } from './components/ErrorBoundary'; import { ExtensionInstallModal } from './components/ExtensionInstallModal'; import RecipeParamsModalContainer from './components/RecipeParamsModalContainer'; -import { isRecipeParamsCancelled, isRecipeParameterScopesUnsupported } from './acp/errors'; +import RecipeConsentModalContainer from './components/RecipeConsentModalContainer'; +import { + isRecipeDeclined, + isRecipeParamsCancelled, + isRecipeParameterScopesUnsupported, +} from './acp/errors'; import { toast, ToastContainer } from 'react-toastify'; import AnnouncementModal from './components/AnnouncementModal'; import TelemetryConsentPrompt from './components/TelemetryConsentPrompt'; @@ -133,7 +138,7 @@ export const PairRouteWrapper = ({ return prev; }); } catch (error) { - if (isRecipeParamsCancelled(error)) { + if (isRecipeDeclined(error) || isRecipeParamsCancelled(error)) { navigate('/'); return; } @@ -629,6 +634,7 @@ export function AppInner() { pauseOnHover /> +
diff --git a/ui/desktop/src/__tests__/createSession.test.ts b/ui/desktop/src/__tests__/createSession.test.ts index 93ae12571..e4afd59e9 100644 --- a/ui/desktop/src/__tests__/createSession.test.ts +++ b/ui/desktop/src/__tests__/createSession.test.ts @@ -27,10 +27,28 @@ vi.mock('../acp/recipeParamRequests', () => ({ beginConfiguredRecipeParameterScope: vi.fn(), })); +vi.mock('../acp/recipe', () => ({ + decodeRecipe: vi.fn(async () => testRecipe), +})); + +vi.mock('../recipe', () => ({ + scanRecipe: vi.fn(async () => ({ has_security_warnings: false })), +})); + +vi.mock('../recipe/recipe_management', () => ({ + listSavedRecipes: vi.fn(async () => [{ id: 'recipe-1', recipe: testRecipe }]), +})); + +vi.mock('../recipe/consent', () => ({ + requestRecipeConsent: vi.fn(async () => true), +})); + vi.mock('../acp/capabilities', () => ({ getAcpFeatureCapabilities: vi.fn(), })); +const testRecipe = vi.hoisted(() => ({ title: 'Test recipe', description: 'Recipe used in tests' })); + const testSession: Session = { id: 'session-1', name: 'untitled', @@ -71,6 +89,10 @@ const finishConfiguredRecipeParameterScope = vi.fn(); describe('createSession ACP session extensions', () => { beforeEach(() => { + Object.assign(window.electron, { + hasAcceptedRecipeBefore: vi.fn(async () => true), + recordRecipeHash: vi.fn(async () => true), + }); mockedGetConfiguredGooseExtensions.mockReset(); mockedGetConfiguredGooseExtensions.mockResolvedValue([ gooseExtensionEntry('developer'), diff --git a/ui/desktop/src/__tests__/createSessionRecipeConsent.test.ts b/ui/desktop/src/__tests__/createSessionRecipeConsent.test.ts new file mode 100644 index 000000000..319d69b21 --- /dev/null +++ b/ui/desktop/src/__tests__/createSessionRecipeConsent.test.ts @@ -0,0 +1,139 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Recipe } from '../recipe'; + +const mocks = vi.hoisted(() => ({ + controllerCreateSession: vi.fn(), + decodeRecipe: vi.fn(), + scanRecipe: vi.fn(), + listSavedRecipes: vi.fn(), + requestRecipeConsent: vi.fn(), + hasAcceptedRecipeBefore: vi.fn(), + recordRecipeHash: vi.fn(), +})); + +vi.mock('../acp/chatSessionController', () => ({ + acpChatSessionController: { createSession: mocks.controllerCreateSession }, +})); +vi.mock('../acp/extensions', () => ({ + getConfiguredGooseExtensions: vi.fn(async () => []), + gooseExtensionName: vi.fn(), +})); +vi.mock('../acp/capabilities', () => ({ + getAcpFeatureCapabilities: vi.fn(async () => ({ recipeParameterScopes: true })), +})); +vi.mock('../acp/recipeParamRequests', () => ({ + beginConfiguredRecipeParameterScope: vi.fn(() => undefined), +})); +vi.mock('../acp/recipe', () => ({ + decodeRecipe: mocks.decodeRecipe, +})); +vi.mock('../recipe', () => ({ + scanRecipe: mocks.scanRecipe, +})); +vi.mock('../recipe/recipe_management', () => ({ + listSavedRecipes: mocks.listSavedRecipes, +})); +vi.mock('../recipe/consent', () => ({ + requestRecipeConsent: mocks.requestRecipeConsent, +})); + +import { createSession } from '../sessions'; +import { isRecipeDeclined } from '../acp/errors'; + +const recipe: Recipe = { + title: 'Helpful Data Analyzer', + description: 'Shared recipe', + extensions: [{ type: 'stdio', name: 'analyzer', cmd: 'sh', args: ['-c', 'id'] }], +}; +const session = { id: 'session-1' }; + +describe('createSession recipe consent gate', () => { + beforeEach(() => { + vi.clearAllMocks(); + Object.assign(window.electron, { + hasAcceptedRecipeBefore: mocks.hasAcceptedRecipeBefore, + recordRecipeHash: mocks.recordRecipeHash, + }); + mocks.controllerCreateSession.mockResolvedValue(session); + mocks.decodeRecipe.mockResolvedValue(recipe); + mocks.scanRecipe.mockResolvedValue({ has_security_warnings: false }); + mocks.listSavedRecipes.mockResolvedValue([{ id: 'saved-1', recipe }]); + mocks.hasAcceptedRecipeBefore.mockResolvedValue(false); + mocks.recordRecipeHash.mockResolvedValue(true); + }); + + it('shows consent for a deeplink recipe before session/new and records acceptance', async () => { + mocks.requestRecipeConsent.mockResolvedValue(true); + + const result = await createSession('/work', { recipeDeeplink: 'ENCODED' }); + + expect(result).toBe(session); + expect(mocks.decodeRecipe).toHaveBeenCalledWith('ENCODED'); + expect(mocks.requestRecipeConsent).toHaveBeenCalledWith({ + recipe, + hasSecurityWarnings: false, + }); + expect(mocks.recordRecipeHash).toHaveBeenCalledWith(recipe); + expect(mocks.controllerCreateSession).toHaveBeenCalledWith('/work', undefined, { + recipeId: undefined, + recipeDeeplink: 'ENCODED', + recipeParameterScopeId: undefined, + }); + expect(mocks.requestRecipeConsent.mock.invocationCallOrder[0]).toBeLessThan( + mocks.controllerCreateSession.mock.invocationCallOrder[0] + ); + }); + + it('never calls session/new when the user declines', async () => { + mocks.requestRecipeConsent.mockResolvedValue(false); + + await expect(createSession('/work', { recipeDeeplink: 'ENCODED' })).rejects.toSatisfy( + isRecipeDeclined + ); + + expect(mocks.controllerCreateSession).not.toHaveBeenCalled(); + expect(mocks.recordRecipeHash).not.toHaveBeenCalled(); + }); + + it('skips the modal for a recipe accepted before', async () => { + mocks.hasAcceptedRecipeBefore.mockResolvedValue(true); + + await createSession('/work', { recipeDeeplink: 'ENCODED' }); + + expect(mocks.requestRecipeConsent).not.toHaveBeenCalled(); + expect(mocks.scanRecipe).not.toHaveBeenCalled(); + expect(mocks.controllerCreateSession).toHaveBeenCalledTimes(1); + }); + + it('resolves library recipes by id and forwards the existing scan result', async () => { + mocks.scanRecipe.mockResolvedValue({ has_security_warnings: true }); + mocks.requestRecipeConsent.mockResolvedValue(true); + + await createSession('/work', { recipeId: 'saved-1' }); + + expect(mocks.decodeRecipe).not.toHaveBeenCalled(); + expect(mocks.requestRecipeConsent).toHaveBeenCalledWith({ + recipe, + hasSecurityWarnings: true, + }); + expect(mocks.controllerCreateSession).toHaveBeenCalledWith( + '/work', + undefined, + expect.objectContaining({ recipeId: 'saved-1' }) + ); + }); + + it('fails before session/new when a library recipe id is unknown', async () => { + await expect(createSession('/work', { recipeId: 'missing' })).rejects.toThrow(/not found/); + expect(mocks.controllerCreateSession).not.toHaveBeenCalled(); + }); + + it('does not touch recipe machinery for plain sessions', async () => { + await createSession('/work'); + + expect(mocks.decodeRecipe).not.toHaveBeenCalled(); + expect(mocks.listSavedRecipes).not.toHaveBeenCalled(); + expect(mocks.requestRecipeConsent).not.toHaveBeenCalled(); + expect(mocks.controllerCreateSession).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ui/desktop/src/acp/errors.ts b/ui/desktop/src/acp/errors.ts index 67ab0ec77..1c2b4e18c 100644 --- a/ui/desktop/src/acp/errors.ts +++ b/ui/desktop/src/acp/errors.ts @@ -28,6 +28,17 @@ export function isRecipeParameterScopesUnsupported( return error instanceof RecipeParameterScopesUnsupportedError; } +export class RecipeDeclinedError extends Error { + constructor() { + super('Recipe was not trusted by the user'); + this.name = 'RecipeDeclinedError'; + } +} + +export function isRecipeDeclined(error: unknown): error is RecipeDeclinedError { + return error instanceof RecipeDeclinedError; +} + export function isRecipeParamsCancelled(error: unknown): boolean { return asAcpJsonRpcError(error)?.data?.reason === RECIPE_PARAMS_CANCELLED_REASON; } diff --git a/ui/desktop/src/components/BaseChat.tsx b/ui/desktop/src/components/BaseChat.tsx index 48319a3df..98015c7a6 100644 --- a/ui/desktop/src/components/BaseChat.tsx +++ b/ui/desktop/src/components/BaseChat.tsx @@ -17,11 +17,9 @@ import { useIsMobile } from '../hooks/use-mobile'; import { useNavigationContextSafe } from './Layout/NavigationContext'; import { cn } from '../utils'; import { useChatSession } from '../hooks/useChatSession'; -import { acpDeleteSession, acpUpdateWorkingDir } from '../acp/sessions'; +import { acpUpdateWorkingDir } from '../acp/sessions'; import { useNavigation } from '../hooks/useNavigation'; import { RecipeHeader } from './RecipeHeader'; -import { RecipeWarningModal } from './ui/RecipeWarningModal'; -import { scanRecipe } from '../recipe'; import type { Recipe } from '../recipe'; import RecipeActivities from './recipes/RecipeActivities'; import { @@ -90,8 +88,6 @@ export default function BaseChat({ const chatInputRef = useRef(null); const disableAnimation = location.state?.disableAnimation || false; const [hasStartedUsingRecipe, setHasStartedUsingRecipe] = React.useState(false); - const [hasNotAcceptedRecipe, setHasNotAcceptedRecipe] = useState(); - const [hasRecipeSecurityWarnings, setHasRecipeSecurityWarnings] = useState(false); const [acpRecovering, setAcpRecovering] = useState(isAcpRecovering); const isMobile = useIsMobile(); const navContext = useNavigationContextSafe(); @@ -157,10 +153,7 @@ export default function BaseChat({ // (goose://new-session?prompt=...). Once the conversation has messages, later flows // such as forks or resumes should auto-submit normally. const suppressInitialAutoSubmit = noAutoSubmit && messages.length === 0; - const canAutoSubmit = - !acpRecovering && - !suppressInitialAutoSubmit && - (session?.session_type === 'scheduled' || !recipe || hasNotAcceptedRecipe === false); + const canAutoSubmit = !acpRecovering && !suppressInitialAutoSubmit; useAutoSubmit({ sessionId, @@ -236,38 +229,6 @@ export default function BaseChat({ return null; }, [messages]); - useEffect(() => { - if (!recipe || !isActiveSession || session?.session_type === 'scheduled') return; - - (async () => { - const accepted = await window.electron.hasAcceptedRecipeBefore(recipe); - setHasNotAcceptedRecipe(!accepted); - - if (!accepted) { - const scanResult = await scanRecipe(recipe); - setHasRecipeSecurityWarnings(scanResult.has_security_warnings); - } - })(); - }, [recipe, isActiveSession, session?.session_type]); - - const handleRecipeAccept = async (accept: boolean) => { - if (recipe && accept) { - await window.electron.recordRecipeHash(recipe); - setHasNotAcceptedRecipe(false); - return; - } - - if (sessionId) { - try { - await acpDeleteSession(sessionId); - window.dispatchEvent(new CustomEvent(AppEvents.SESSION_DELETED, { detail: { sessionId } })); - } catch (error) { - console.error('Failed to delete declined recipe session:', error); - } - } - setView('chat'); - }; - // Track if this is the initial render for session resuming const initialRenderRef = useRef(true); @@ -539,7 +500,6 @@ export default function BaseChat({ messages={messages} disableAnimation={disableAnimation} recipe={recipe} - recipeAccepted={!hasNotAcceptedRecipe} initialPrompt={initialPrompt} sessionModel={sessionModel} sessionProvider={sessionProvider} @@ -551,20 +511,6 @@ export default function BaseChat({ /> - - {recipe && isActiveSession && session?.session_type !== 'scheduled' && ( - handleRecipeAccept(true)} - onCancel={() => handleRecipeAccept(false)} - recipeDetails={{ - title: recipe.title, - description: recipe.description, - instructions: recipe.instructions || undefined, - }} - hasSecurityWarnings={hasRecipeSecurityWarnings} - /> - )}
); } diff --git a/ui/desktop/src/components/ChatInput.tsx b/ui/desktop/src/components/ChatInput.tsx index c2d99e789..0aae1875b 100644 --- a/ui/desktop/src/components/ChatInput.tsx +++ b/ui/desktop/src/components/ChatInput.tsx @@ -187,7 +187,6 @@ interface ChatInputProps { disableAnimation?: boolean; recipe?: Recipe | null; recipeId?: string | null; - recipeAccepted?: boolean; initialPrompt?: string; append?: (message: Message) => void; onWorkingDirChange?: (newDir: string) => Promise | void; @@ -224,7 +223,6 @@ export default function ChatInput({ disableAnimation = false, recipe: _recipe, recipeId: _recipeId, - recipeAccepted, initialPrompt, append: _append, onWorkingDirChange, @@ -553,17 +551,15 @@ export default function ChatInput({ setHasUserTyped(false); }, [initialValue, draftRef]); - // Handle recipe prompt updates useEffect(() => { - // If recipe is accepted and we have an initial prompt, and no messages yet, and we haven't set it before - if (recipeAccepted && initialPrompt && messages.length === 0) { + if (initialPrompt && messages.length === 0) { setDisplayValue(initialPrompt); setValue(initialPrompt); setTimeout(() => { textAreaRef.current?.focus(); }, 0); } - }, [recipeAccepted, initialPrompt, messages.length, textAreaRef]); + }, [initialPrompt, messages.length, textAreaRef]); const [isComposing, setIsComposing] = useState(false); const [historyIndex, setHistoryIndex] = useState(-1); diff --git a/ui/desktop/src/components/RecipeConsentModalContainer.tsx b/ui/desktop/src/components/RecipeConsentModalContainer.tsx new file mode 100644 index 000000000..c23dcc348 --- /dev/null +++ b/ui/desktop/src/components/RecipeConsentModalContainer.tsx @@ -0,0 +1,33 @@ +import { useSyncExternalStore } from 'react'; +import { + getRecipeConsentRequestsSnapshot, + resolveRecipeConsent, + subscribeRecipeConsentRequests, +} from '../recipe/consent'; +import { RecipeWarningModal } from './ui/RecipeWarningModal'; + +export default function RecipeConsentModalContainer() { + const requests = useSyncExternalStore( + subscribeRecipeConsentRequests, + getRecipeConsentRequestsSnapshot + ); + const request = requests[0]; + if (!request) { + return null; + } + + return ( + resolveRecipeConsent(request.id, true)} + onCancel={() => resolveRecipeConsent(request.id, false)} + /> + ); +} diff --git a/ui/desktop/src/components/recipes/RecipesView.tsx b/ui/desktop/src/components/recipes/RecipesView.tsx index 377ef6894..285317432 100644 --- a/ui/desktop/src/components/recipes/RecipesView.tsx +++ b/ui/desktop/src/components/recipes/RecipesView.tsx @@ -31,7 +31,7 @@ import { MainPanelLayout } from '../Layout/MainPanelLayout'; import { toastSuccess, toastError } from '../../toasts'; import { useEscapeKey } from '../../hooks/useEscapeKey'; import { createSession } from '../../sessions'; -import { isRecipeParamsCancelled } from '../../acp/errors'; +import { isRecipeDeclined, isRecipeParamsCancelled } from '../../acp/errors'; import ImportRecipeForm, { ImportRecipeButton } from './ImportRecipeForm'; import CreateEditRecipeModal from './CreateEditRecipeModal'; import { generateDeepLink } from '../../recipe'; @@ -394,7 +394,7 @@ export default function RecipesView() { : undefined, }); } catch (error) { - if (isRecipeParamsCancelled(error)) { + if (isRecipeDeclined(error) || isRecipeParamsCancelled(error)) { setView('chat'); return; } diff --git a/ui/desktop/src/recipe/consent.test.ts b/ui/desktop/src/recipe/consent.test.ts new file mode 100644 index 000000000..081f39606 --- /dev/null +++ b/ui/desktop/src/recipe/consent.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest'; +import type { Recipe } from '.'; +import { + getRecipeConsentRequestsSnapshot, + requestRecipeConsent, + resolveRecipeConsent, + subscribeRecipeConsentRequests, +} from './consent'; + +const recipe: Recipe = { title: 'Analyzer', description: 'Shared recipe' }; + +describe('recipe consent store', () => { + it('publishes a pending request until it is resolved, then settles the promise', async () => { + const notified: number[] = []; + const unsubscribe = subscribeRecipeConsentRequests(() => + notified.push(getRecipeConsentRequestsSnapshot().length) + ); + + const decision = requestRecipeConsent({ recipe, hasSecurityWarnings: false }); + const [pending] = getRecipeConsentRequestsSnapshot(); + expect(pending.recipe).toBe(recipe); + + resolveRecipeConsent(pending.id, true); + await expect(decision).resolves.toBe(true); + expect(getRecipeConsentRequestsSnapshot()).toEqual([]); + expect(notified).toEqual([1, 0]); + unsubscribe(); + }); +}); diff --git a/ui/desktop/src/recipe/consent.ts b/ui/desktop/src/recipe/consent.ts new file mode 100644 index 000000000..ecdc503fa --- /dev/null +++ b/ui/desktop/src/recipe/consent.ts @@ -0,0 +1,55 @@ +import { v7 as uuidv7 } from 'uuid'; +import type { Recipe } from '.'; + +export interface RecipeConsentRequest { + id: string; + recipe: Recipe; + hasSecurityWarnings: boolean; +} + +interface PendingConsent { + request: RecipeConsentRequest; + resolve: (accepted: boolean) => void; +} + +const pendingRequests = new Map(); +const listeners = new Set<() => void>(); +let snapshot: RecipeConsentRequest[] = []; + +function emit(): void { + snapshot = Array.from(pendingRequests.values(), (pending) => pending.request); + for (const listener of listeners) { + listener(); + } +} + +export function subscribeRecipeConsentRequests(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function getRecipeConsentRequestsSnapshot(): RecipeConsentRequest[] { + return snapshot; +} + +export function requestRecipeConsent( + input: Omit +): Promise { + const request: RecipeConsentRequest = { id: `recipe_consent_${uuidv7()}`, ...input }; + return new Promise((resolve) => { + pendingRequests.set(request.id, { request, resolve }); + emit(); + }); +} + +export function resolveRecipeConsent(id: string, accepted: boolean): void { + const pending = pendingRequests.get(id); + if (!pending) { + return; + } + pendingRequests.delete(id); + emit(); + pending.resolve(accepted); +} diff --git a/ui/desktop/src/sessions.ts b/ui/desktop/src/sessions.ts index e5c796494..9b45d9bbf 100644 --- a/ui/desktop/src/sessions.ts +++ b/ui/desktop/src/sessions.ts @@ -8,7 +8,11 @@ import { acpChatSessionController } from './acp/chatSessionController'; import { getConfiguredGooseExtensions, gooseExtensionName } from './acp/extensions'; import { beginConfiguredRecipeParameterScope } from './acp/recipeParamRequests'; import { getAcpFeatureCapabilities } from './acp/capabilities'; -import { RecipeParameterScopesUnsupportedError } from './acp/errors'; +import { RecipeDeclinedError, RecipeParameterScopesUnsupportedError } from './acp/errors'; +import { decodeRecipe } from './acp/recipe'; +import { scanRecipe, type Recipe } from './recipe'; +import { listSavedRecipes } from './recipe/recipe_management'; +import { requestRecipeConsent } from './recipe/consent'; export function getSessionDisplayName(session: Session): string { if (session.user_set_name) { @@ -67,10 +71,45 @@ async function resolveGooseExtensions( .map((entry) => entry.extension); } +async function resolveRecipe(options?: CreateSessionOptions): Promise { + if (options?.recipeId) { + const entry = (await listSavedRecipes()).find((manifest) => manifest.id === options.recipeId); + if (!entry) { + throw new Error(`Recipe ${options.recipeId} was not found in the recipe library`); + } + return entry.recipe; + } + if (options?.recipeDeeplink) { + return decodeRecipe(options.recipeDeeplink); + } + return undefined; +} + +// Recipes can declare commands, endpoints, and shell checks that run as soon as the +// session exists, so consent has to be settled before session/new is ever sent. +async function ensureRecipeConsent(options?: CreateSessionOptions): Promise { + const recipe = await resolveRecipe(options); + if (!recipe || (await window.electron.hasAcceptedRecipeBefore(recipe))) { + return; + } + + const scan = await scanRecipe(recipe); + const accepted = await requestRecipeConsent({ + recipe, + hasSecurityWarnings: scan.has_security_warnings, + }); + if (!accepted) { + throw new RecipeDeclinedError(); + } + await window.electron.recordRecipeHash(recipe); +} + async function createAcpSession( workingDir: string, options?: CreateSessionOptions ): Promise { + await ensureRecipeConsent(options); + const configuredParameterScope = options?.recipeDeeplink ? beginConfiguredRecipeParameterScope() : undefined;