fix(desktop): require recipe consent before session/new spawns extensions (#12094)

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Jasper Hugo <jasper@jasperhugo.com>
This commit is contained in:
dorien-koelemeijer
2026-09-16 15:08:33 +00:00
committed by GitHub
parent 5a21df18c5
commit 7343b6f432
11 changed files with 343 additions and 67 deletions
+8 -2
View File
@@ -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
/>
<ExtensionInstallModal addExtension={addExtension} setView={setView} />
<RecipeConsentModalContainer />
<RecipeParamsModalContainer />
<div className="relative w-screen h-screen overflow-hidden bg-background-secondary flex flex-col">
<div className="titlebar-drag-region" />
@@ -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'),
@@ -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);
});
});
+11
View File
@@ -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;
}
+2 -56
View File
@@ -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<HTMLTextAreaElement>(null);
const disableAnimation = location.state?.disableAnimation || false;
const [hasStartedUsingRecipe, setHasStartedUsingRecipe] = React.useState(false);
const [hasNotAcceptedRecipe, setHasNotAcceptedRecipe] = useState<boolean>();
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({
/>
</ChatInputCard>
</MainPanelLayout>
{recipe && isActiveSession && session?.session_type !== 'scheduled' && (
<RecipeWarningModal
isOpen={!!hasNotAcceptedRecipe}
onConfirm={() => handleRecipeAccept(true)}
onCancel={() => handleRecipeAccept(false)}
recipeDetails={{
title: recipe.title,
description: recipe.description,
instructions: recipe.instructions || undefined,
}}
hasSecurityWarnings={hasRecipeSecurityWarnings}
/>
)}
</div>
);
}
+2 -6
View File
@@ -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> | 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);
@@ -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 (
<RecipeWarningModal
key={request.id}
isOpen
recipeDetails={{
title: request.recipe.title,
description: request.recipe.description,
instructions: request.recipe.instructions || undefined,
}}
hasSecurityWarnings={request.hasSecurityWarnings}
onConfirm={() => resolveRecipeConsent(request.id, true)}
onCancel={() => resolveRecipeConsent(request.id, false)}
/>
);
}
@@ -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;
}
+29
View File
@@ -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();
});
});
+55
View File
@@ -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<string, PendingConsent>();
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<RecipeConsentRequest, 'id'>
): Promise<boolean> {
const request: RecipeConsentRequest = { id: `recipe_consent_${uuidv7()}`, ...input };
return new Promise<boolean>((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);
}
+40 -1
View File
@@ -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<Recipe | undefined> {
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<void> {
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<Session> {
await ensureRecipeConsent(options);
const configuredParameterScope = options?.recipeDeeplink
? beginConfiguredRecipeParameterScope()
: undefined;