diff --git a/server/shiso/conversationTurn.ts b/server/shiso/conversationTurn.ts index c4883de..c05abe4 100644 --- a/server/shiso/conversationTurn.ts +++ b/server/shiso/conversationTurn.ts @@ -66,6 +66,16 @@ const SYSTEM_PROMPT = [ "- After a search identifies the intended recipe, use select_vault_recipe to", " bind the next operation to that recipe. The application invalidates that", " selection when the active Vault changes.", + "- For questions about which recipes have no images, broken images, valid images,", + " or unverified images, call inventory_vault_images. Never answer that structured", + " question by searching for the text 'no image'.", + "- To generate an image for the current recipe, call generate_recipe_image ONLY when", + " the current user message explicitly asks for an image for the selected recipe. A", + " good idea is not authorization; without that request the application rejects the", + " capability. The application uses its existing image provider, quote, and", + " confirmation flow. For paid/variable models the user must confirm the quote in the", + " image panel; a preview is never saved automatically. Never claim an image is saved", + " unless the application confirms the explicit Save action.", "", "ACT WHEN THE USER ASKS — DO NOT ASK PERMISSION FOR WORK THEY ALREADY REQUESTED", "- If the user asks you to investigate, check, analyse, search, show, explain, compare", @@ -266,9 +276,8 @@ const SYSTEM_PROMPT = [ " separate clarifications.", "", "WHAT YOU CANNOT DO", - "- You cannot generate, edit, or retrieve recipe images. If asked for an image, say", - " plainly that Shiso cannot create or add images, and then help with the parts you", - " can do (for example nutrition or ingredients).", + "- You can inspect image presence and start the EXISTING image-generation flow;", + " you cannot save an image yourself. The user must approve and press Save Image.", "- You cannot create new recipes, import recipes, delete recipes, or write to the vault", " directly. You can edit an OPEN recipe's working copy and save it through the normal", " save path with save_working_recipe, and only when the user asks you to save.", @@ -298,6 +307,8 @@ const SYSTEM_PROMPT = [ "search_vault_recipes search the active Vault by title, ingredient, category, or metadata", "get_vault_recipe retrieve a bounded recipe detail from the active Vault", "select_vault_recipe bind an authorized Vault recipe as the current SHISO subject", + "inventory_vault_images read the live Vault image inventory (missing/broken/valid/unknown) with counts and pagination", + "generate_recipe_image start the application's existing image-generation flow for the current recipe (preview/approval; never auto-saves)", "load_usda_catalog ask the application to load its authenticated USDA catalog", "get_nutrition_review read the live Advanced Nutrition review state", "get_branded_evidence read accepted USDA Branded product evidence in the working review", @@ -318,7 +329,7 @@ const SYSTEM_PROMPT = [ "TOOL ARGUMENTS — EXACT JSON KEYS (never invent key names)", "- A tool call is {\"kind\":\"tool_request\",\"tool\":\"\",\"args\":{...}}.", "- No arguments: get_nutrition_review, get_branded_evidence, investigate_unresolved_ingredients,", - " get_vault_status, load_usda_catalog, run_nutrition_analysis, complete_nutrition, get_capability_status, apply_nutrition_review, save_working_recipe.", + " get_vault_status, load_usda_catalog, run_nutrition_analysis, complete_nutrition, get_capability_status, apply_nutrition_review, save_working_recipe, generate_recipe_image.", "- {\"tool\":\"get_current_recipe\",\"instruction_offset\":0,\"instruction_limit\":20} (use next_instruction_offset until complete)", "- {\"tool\":\"investigate_ingredient_amount\",\"line_ref\":\"\"}", "- {\"tool\":\"search_usda_foods\",\"query\":\"...\"}", @@ -327,6 +338,8 @@ const SYSTEM_PROMPT = [ "- {\"tool\":\"search_vault_recipes\",\"query\":\"chicken\",\"field\":\"ingredient\"}", "- {\"tool\":\"get_vault_recipe\",\"recipe_id\":\"\"}", "- {\"tool\":\"select_vault_recipe\",\"recipe_id\":\"\"}", + "- {\"tool\":\"inventory_vault_images\",\"status\":\"missing\",\"limit\":20,\"offset\":0}", + "- {\"tool\":\"generate_recipe_image\"}", "- {\"tool\":\"apply_ingredient_edits\",\"edits\":[{\"line_ref\":\"\",\"new_name\":\"turkey\"}]}", " Each edit object needs line_ref and AT LEAST ONE of: new_name (text), new_amount (number),", " new_unit (text), new_preparation (text). Omit the fields you are not changing.", @@ -500,6 +513,10 @@ function salvageToolArgs(tool: ShisoToolName): ShisoToolArgs { return { tool, recipe_id: '' }; case 'select_vault_recipe': return { tool, recipe_id: '' }; + case 'inventory_vault_images': + return { tool, status: 'all', offset: 0, limit: 20 }; + case 'generate_recipe_image': + return { tool }; case 'load_usda_catalog': return { tool }; case 'get_nutrition_review': @@ -609,6 +626,23 @@ function readToolArgs(tool: ShisoToolName, raw: unknown): ShisoToolArgs | null { const trimmed = recipeId.trim().slice(0, SHISO_LIMITS.maxVaultRecipeIdChars); return trimmed.length > 0 ? { tool, recipe_id: trimmed } : null; } + case 'inventory_vault_images': { + const rawStatus = rec['status']; + const status = rawStatus === 'missing' || rawStatus === 'broken' || rawStatus === 'valid' || rawStatus === 'unknown' || rawStatus === 'all' + ? rawStatus + : 'all'; + const rawOffset = rec['offset']; + const offset = typeof rawOffset === 'number' && Number.isFinite(rawOffset) && rawOffset >= 0 + ? Math.min(100000, Math.floor(rawOffset)) + : 0; + const rawLimit = rec['limit']; + const limit = typeof rawLimit === 'number' && Number.isFinite(rawLimit) && rawLimit > 0 + ? Math.max(1, Math.min(SHISO_LIMITS.maxImageInventoryResults, Math.floor(rawLimit))) + : 20; + return { tool, status, offset, limit }; + } + case 'generate_recipe_image': + return { tool }; case 'load_usda_catalog': return { tool }; case 'get_nutrition_review': diff --git a/src/App.tsx b/src/App.tsx index 8daf057..598dd1f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -50,6 +50,7 @@ import { validateRecipeAssetReferences } from './utils/assetReferences'; import { createSessionAssetRunner } from './utils/sessionAssets'; import { VaultAssetScopeProvider } from './hooks/VaultAssetScopeContext'; import { getRecipeImage } from './utils/imageHelper'; +import { assessRecipeImageHealth } from './core/recipeImage'; import { cleanRecipeTitle, parseObsidianRecipeMarkdown, serializeRecipeToObsidianMarkdown } from './utils/markdownParser'; import { pickVaultDirectory, @@ -3816,6 +3817,12 @@ export default function App({ return working?.base ?? shisoSelectedRecipeForReviewRef.current ?? selectedRecipeRef.current; }, []); + // R2 image generation uses the canonical recipe, never an unsaved working copy. + // This keeps generation/save bound to the Markdown whose hash was previewed. + const getShisoImageRecipe = useCallback(() => { + return shisoSelectedRecipeForReviewRef.current ?? selectedRecipeRef.current; + }, []); + // SHISO agent foundation: one application-owned, read-only Vault capability // object. It reads the live App refs, so a Vault transition is immediately // reflected and any retained recipe selection is invalidated by session id. @@ -3837,7 +3844,11 @@ export default function App({ setSelectedRecipe(recipe); setVaultView('all'); }, - }), [vaultStatus.accessType, vaultStatus.connectionState, vaultStatus.isConnected]); + assessImageHealth: async (recipe, signal) => { + if (signal?.aborted) return null; + return assessRecipeImageHealth({ image: recipe.image }, { asset: imageService.asset }); + }, + }), [vaultStatus.accessType, vaultStatus.connectionState, vaultStatus.isConnected, imageService]); const handleShisoVaultRecipeSelected = useCallback((recipeId: string) => { const selected = recipesRef.current.find((entry) => entry.id === recipeId) ?? (() => { // The capability seam used by the real-App integration tests can @@ -5572,6 +5583,10 @@ export default function App({ vaultCapabilities={shisoVaultCapabilityOverride ?? shisoVaultCapabilities} onVaultRecipeSelected={handleShisoVaultRecipeSelected} getSaveAuthorizationRecipe={getShisoSaveAuthorizationRecipe} + imageRecovery={recipeImageRecoverySupport} + imageRecoveryUnavailableReason={imageRecoveryUnavailableReason} + getImageRecipe={getShisoImageRecipe} + onRecipeImageSaved={handleRecipeImageSaved} nutritionAuthority={{ enabled: nutritionAuthorityActive, vaultScope: nutritionAuthorityScope, diff --git a/src/application/shisoConversation.ts b/src/application/shisoConversation.ts index a473e4d..f58a64a 100644 --- a/src/application/shisoConversation.ts +++ b/src/application/shisoConversation.ts @@ -679,6 +679,7 @@ export async function runShisoConversationTurn( 'get_vault_status', 'get_vault_recipe', 'select_vault_recipe', + 'inventory_vault_images', 'get_capability_status', 'load_usda_catalog', ]); diff --git a/src/application/shisoTools.ts b/src/application/shisoTools.ts index 3ba7892..06f367e 100644 --- a/src/application/shisoTools.ts +++ b/src/application/shisoTools.ts @@ -79,6 +79,16 @@ export interface ShisoAiNutritionOptions { readonly nutrientGapFocus?: readonly ShisoNutrientGapFocus[]; } +export interface ShisoImageGenerationOutcome { + readonly ok: boolean; + readonly status: 'preview' | 'confirmation_required' | 'generating' | 'saved' | 'error'; + readonly message: string; + readonly provider?: string; + readonly model?: string; + readonly costLabel?: string; + readonly requiresConfirmation?: boolean; +} + export interface ShisoExternalResearchOutcome { readonly ok: boolean; readonly contributions?: ReadonlyArray; @@ -220,6 +230,15 @@ export interface ShisoToolContext { * message and the authenticated selected record label. */ readonly isTrustedNutritionSourceSelection?: ((lineRef: string, description: string) => boolean) | undefined; + /** + * R2. Starts the application's EXISTING image-recovery controller for the + * current canonical recipe. The controller owns the quote/confirmation, + * provider selection, preview, and explicit Save controls. This port never + * saves; absent means image generation is unavailable on this surface. + */ + readonly generateRecipeImage?: (() => Promise) | undefined; + /** Truthful reason image generation is unavailable on this surface. */ + readonly imageGenerationUnavailableReason?: string | undefined; } function ok( @@ -3070,6 +3089,69 @@ function getCapabilityStatus(ctx: ShisoToolContext): ShisoObservation { * the server's closed schema, but they are RE-VALIDATED here: the browser is the * authority boundary and never trusts that the check happened upstream. */ +async function inventoryVaultImages( + ctx: ShisoToolContext, + status: 'all' | 'missing' | 'broken' | 'valid' | 'unknown', + offset: number, + limit: number, + signal?: AbortSignal, +): Promise { + if (!ctx.vault?.inventoryImages) { + return fail( + 'inventory_vault_images', + 'vault_unavailable', + 'The live Vault image inventory is not available on this surface. No image status was inferred.', + ); + } + const result = await ctx.vault.inventoryImages({ status, offset, limit }, signal); + if (result.cancelled) { + return fail('inventory_vault_images', 'unsupported', 'The Vault image inventory was cancelled.'); + } + const counts = result.counts; + const filterLabel = status === 'all' ? 'all image states' : `${status} images`; + return ok( + 'inventory_vault_images', + `${counts.missing} missing, ${counts.broken} broken, ${counts.valid} valid, ${counts.unknown} unknown across ${result.total_recipes} Vault recipe(s). Showing ${result.entries.length} ${filterLabel} result(s) from offset ${result.offset}.`, + { + entries: result.entries, + counts, + total_recipes: result.total_recipes, + total_matches: result.total_matches, + offset: result.offset, + limit: result.limit, + has_more: result.has_more, + truncated: result.truncated, + status_filter: status, + }, + ); +} + +async function generateRecipeImage(ctx: ShisoToolContext): Promise { + if (ctx.recipe === null) { + return fail('generate_recipe_image', 'no_active_recipe', 'No recipe is currently active for image generation.'); + } + if (!ctx.generateRecipeImage) { + return fail( + 'generate_recipe_image', + 'unsupported', + ctx.imageGenerationUnavailableReason + ? `Image generation is not available: ${ctx.imageGenerationUnavailableReason}` + : 'Image generation is not available on this SHISO surface. Open a connected, writable Vault recipe.', + ); + } + const result = await ctx.generateRecipeImage(); + if (!result.ok) { + return fail('generate_recipe_image', 'unsupported', result.message); + } + return ok('generate_recipe_image', result.message, { + status: result.status, + ...(result.provider !== undefined ? { provider: result.provider } : {}), + ...(result.model !== undefined ? { model: result.model } : {}), + ...(result.costLabel !== undefined ? { cost_label: result.costLabel } : {}), + ...(result.requiresConfirmation !== undefined ? { requires_confirmation: result.requiresConfirmation } : {}), + }); +} + export function executeShisoTool( args: ShisoToolArgs, ctx: ShisoToolContext, @@ -3087,6 +3169,16 @@ export function executeShisoTool( return getVaultRecipe(ctx, args.recipe_id); case 'select_vault_recipe': return selectVaultRecipe(ctx, args.recipe_id); + case 'inventory_vault_images': + return inventoryVaultImages( + ctx, + args.status ?? 'all', + args.offset ?? 0, + args.limit ?? 20, + signal, + ); + case 'generate_recipe_image': + return generateRecipeImage(ctx); case 'load_usda_catalog': return loadUsdaCatalog(ctx, signal); case 'get_nutrition_review': diff --git a/src/application/shisoVaultCapabilities.ts b/src/application/shisoVaultCapabilities.ts index 10ced59..d669867 100644 --- a/src/application/shisoVaultCapabilities.ts +++ b/src/application/shisoVaultCapabilities.ts @@ -10,6 +10,7 @@ import type { ObsidianRecipe } from '../types'; import { adaptRecipe } from '../core/nutritionV2/phase4'; +import type { RecipeImageHealth } from '../core/recipeImage'; export type ShisoVaultSource = 'personal' | 'imported' | 'starter'; @@ -77,12 +78,44 @@ export interface ShisoVaultSelection { readonly title: string; } +export type ShisoVaultImageStatus = 'missing' | 'broken' | 'valid' | 'unknown'; + +export interface ShisoVaultImageInventoryEntry { + readonly recipe_id: string; + readonly title: string; + readonly status: ShisoVaultImageStatus; + readonly reason?: string; +} + +export interface ShisoVaultImageInventoryRequest { + readonly status?: ShisoVaultImageStatus | 'all'; + readonly offset?: number; + readonly limit?: number; +} + +export interface ShisoVaultImageInventoryResult { + readonly entries: readonly ShisoVaultImageInventoryEntry[]; + readonly counts: Readonly>; + readonly total_recipes: number; + readonly total_matches: number; + readonly offset: number; + readonly limit: number; + readonly has_more: boolean; + readonly truncated: boolean; + readonly cancelled?: true; +} + export interface ShisoVaultCapability { readonly getStatus: () => ShisoVaultStatus; readonly searchRecipes: (request: ShisoVaultSearchRequest, signal?: AbortSignal) => ShisoVaultSearchResult; readonly getRecipe: (recipeId: string) => ShisoVaultRecipeDetail | null; readonly selectRecipe: (recipeId: string) => ShisoVaultSelection | null; readonly getSelectedRecipe: () => ShisoVaultRecipeDetail | null; + /** Bounded, read-only image inventory over the live Vault snapshot. */ + readonly inventoryImages?: ( + request: ShisoVaultImageInventoryRequest, + signal?: AbortSignal, + ) => Promise; } export interface ShisoVaultCapabilitySource { @@ -91,6 +124,11 @@ export interface ShisoVaultCapabilitySource { readonly getIdentity: () => ShisoVaultIdentity; /** Optional shell handoff for later write/review ports. */ readonly onSelectRecipe?: (recipe: ObsidianRecipe) => void; + /** + * Optional application-owned image-health authority. When absent every entry + * is reported `unknown`; an unavailable check is NEVER reported as missing. + */ + readonly assessImageHealth?: (recipe: ObsidianRecipe, signal?: AbortSignal) => Promise; } const MAX_SEARCH_QUERY_CHARS = 160; @@ -99,6 +137,8 @@ const MAX_INGREDIENTS = 80; const MAX_INSTRUCTIONS = 60; const MAX_TEXT_CHARS = 400; const MAX_METADATA_CHARS = 120; +const MAX_IMAGE_INVENTORY_RESULTS = 50; +const MAX_IMAGE_INVENTORY_SCAN = 1000; function boundedText(value: unknown, limit: number): string { return typeof value === 'string' ? value.trim().slice(0, limit) : ''; @@ -190,6 +230,30 @@ function searchableFields(recipe: ObsidianRecipe): Readonly => { + const statusFilter = request.status === 'missing' || request.status === 'broken' || request.status === 'valid' || request.status === 'unknown' + ? request.status + : 'all'; + const offset = typeof request.offset === 'number' && Number.isFinite(request.offset) + ? Math.max(0, Math.min(100000, Math.floor(request.offset))) + : 0; + const limit = typeof request.limit === 'number' && Number.isFinite(request.limit) + ? Math.max(1, Math.min(MAX_IMAGE_INVENTORY_RESULTS, Math.floor(request.limit))) + : 20; + const allRecipes = currentRecipes(); + const scannedRecipes = allRecipes.slice(0, MAX_IMAGE_INVENTORY_SCAN); + const counts: Record = { missing: 0, broken: 0, valid: 0, unknown: 0 }; + const entries: ShisoVaultImageInventoryEntry[] = []; + const assess = source.assessImageHealth; + const initialIdentity = currentIdentity(); + const sessionIsCurrent = (): boolean => { + const identity = currentIdentity(); + return identity.id === initialIdentity.id && identity.source === initialIdentity.source; + }; + const cancelledResult = (): ShisoVaultImageInventoryResult => Object.freeze({ + entries: Object.freeze([]), + counts: Object.freeze({ ...counts }), + total_recipes: allRecipes.length, + total_matches: 0, + offset, + limit, + has_more: false, + truncated: allRecipes.length > MAX_IMAGE_INVENTORY_SCAN, + cancelled: true, + }); + for (const recipe of scannedRecipes) { + if (signal?.aborted || !sessionIsCurrent()) { + return cancelledResult(); + } + let health: RecipeImageHealth | null = null; + if (assess) { + try { + health = await assess(recipe, signal); + } catch { + health = null; + } + } + if (signal?.aborted || !sessionIsCurrent()) return cancelledResult(); + const status = imageStatusOf(health); + counts[status] += 1; + if (statusFilter !== 'all' && status !== statusFilter) continue; + entries.push(Object.freeze({ + recipe_id: boundedText(recipe.id, 240), + title: boundedText(recipe.title, 200), + status, + ...(imageReasonOf(health) !== undefined ? { reason: imageReasonOf(health)! } : {}), + })); + } + if (!sessionIsCurrent()) return cancelledResult(); + const totalMatches = entries.length; + const page = entries.slice(offset, offset + limit); + return Object.freeze({ + entries: Object.freeze(page), + counts: Object.freeze({ ...counts }), + total_recipes: allRecipes.length, + total_matches: totalMatches, + offset, + limit, + has_more: offset + page.length < totalMatches, + truncated: allRecipes.length > MAX_IMAGE_INVENTORY_SCAN, + }); + }, }); } diff --git a/src/components/ShisoModal.tsx b/src/components/ShisoModal.tsx index ab7a66b..3003fc8 100644 --- a/src/components/ShisoModal.tsx +++ b/src/components/ShisoModal.tsx @@ -57,6 +57,7 @@ import { requestNutritionWebResearch } from '../application/nutritionWebResearch import { useShisoRecipeContext } from '../application-ui/useShisoRecipeContext'; import { useShiso, type ShisoNutritionAnalysisOutcome, type ShisoNutritionSnapshot, type ShisoNutritionReviewApplyResult } from '../application-ui/shisoEntryPoints'; import type { ShisoBoundProposal } from '../core/shiso/protocol'; +import { classifyImageGenerationIntent } from '../core/shiso/imageGenerationAuthorization'; import { buildIdentityDisclosure } from '../core/shiso/disclosure'; import { classifySaveIntent, recipeIdentityOf } from '../core/shiso/saveAuthorization'; import { requestGeneratedRecipe, parseEditedDraftLines, CreateRecipeClientError } from '../utils/createForMe'; @@ -69,6 +70,14 @@ import { ShisoMarkdown } from './ShisoMarkdown'; import { SignatureRecipeCard } from './SignatureRecipeCard'; import { KitchenCodexMark } from './BrandMark'; import type { ShisoVaultCapability, ShisoVaultRecipeDetail } from '../application/shisoVaultCapabilities'; +import { + RecipeImageRecoveryController, + fetchGeneratedPreviewBytes, + type RecipeImageRecoveryState, + type RecipeImageRecoverySupport, +} from '../application/recipeImageRecovery'; +import { createTemporaryPreviewUrl, releaseTemporaryPreviewUrl } from '../utils/assetProvenance'; +import type { ObsidianRecipe } from '../types'; export interface ShisoModalProps { readonly isOpen: boolean; @@ -110,6 +119,13 @@ export interface ShisoModalProps { readonly fileName?: unknown; readonly title?: unknown; } | null; + /** R2: the existing application image-recovery support, or undefined. */ + readonly imageRecovery?: RecipeImageRecoverySupport; + readonly imageRecoveryUnavailableReason?: string; + /** R2: the active canonical recipe for image generation (never an invented draft). */ + readonly getImageRecipe?: () => ObsidianRecipe | null; + /** R2: immediate refresh after the existing canonical image save. */ + readonly onRecipeImageSaved?: (recipeId: string, imagePath: string) => void; /** Persistent, user-controlled nutrition-only authority for the active Vault. */ readonly nutritionAuthority?: { readonly enabled: boolean; @@ -229,6 +245,10 @@ export function ShisoModal({ onVaultRecipeSelected, recipe, getSaveAuthorizationRecipe, + imageRecovery, + imageRecoveryUnavailableReason, + getImageRecipe, + onRecipeImageSaved, nutritionAuthority = { enabled: false, vaultScope: '' }, nutritionSession, nutritionBundleStatus, @@ -272,6 +292,20 @@ export function ShisoModal({ const [saveBusy, setSaveBusy] = useState(false); const [saveReport, setSaveReport] = useState(null); const [saveError, setSaveError] = useState(null); + const [imageState, setImageState] = useState({ phase: 'idle' }); + const imageControllerRef = useRef(null); + const pendingImageSaveRecipeIdRef = useRef(null); + const imageRecipe = getImageRecipe?.() ?? null; + const imageRecipeKey = imageRecipe?.filePath || imageRecipe?.id || imageRecipe?.fileName || imageRecipe?.title || null; + const imageRecipeRef = useRef(imageRecipe); + imageRecipeRef.current = imageRecipe; + const imageGenerationGrantRef = useRef<{ + authorized: boolean; + reason: string; + recipeIdentity: string; + turn: number; + consumed: boolean; + }>({ authorized: false, reason: 'no_explicit_request', recipeIdentity: '', turn: 0, consumed: true }); const [createdDraft, setCreatedDraft] = useState(null); const [createdProvenance, setCreatedProvenance] = useState(null); const [priorCreatedDraft, setPriorCreatedDraft] = useState<{ draft: GeneratedRecipeDraft; provenance: GeneratedRecipeProvenance } | null>(null); @@ -474,6 +508,59 @@ export function ShisoModal({ shisoRef.current.clearSaveAuthorization(); }, []); + // R2: the EXISTING image-recovery controller, scoped to the canonical + // recipe and the active writable Vault support. Closing/replacing the support + // or recipe invalidates any preview via the controller's liveness epoch. + useEffect(() => { + if (!isOpen || imageRecovery === undefined || imageRecipeKey === null) { + imageControllerRef.current?.close(); + imageControllerRef.current = null; + setImageState({ phase: 'idle' }); + return; + } + const controller = new RecipeImageRecoveryController({ + network, + support: imageRecovery, + onState: setImageState, + onSaved: (result) => { + const recipeId = pendingImageSaveRecipeIdRef.current; + pendingImageSaveRecipeIdRef.current = null; + if (recipeId !== null) onRecipeImageSaved?.(recipeId, result.imagePath); + }, + }); + imageControllerRef.current = controller; + setImageState(controller.getState()); + return () => { + controller.close(); + imageControllerRef.current = null; + }; + }, [isOpen, network, imageRecovery, imageRecipeKey, onRecipeImageSaved]); + + const previewToken = imageState.preview?.token; + const [securePreviewUrl, setSecurePreviewUrl] = useState(null); + useEffect(() => { + let cancelled = false; + let url: string | null = null; + setSecurePreviewUrl(null); + if (!isOpen || previewToken === undefined) return; + (async () => { + const viaAdapter = await fetchGeneratedPreviewBytes(network, previewToken); + if (cancelled || !viaAdapter) return; + url = createTemporaryPreviewUrl(new Blob([viaAdapter.bytes.slice()], { type: viaAdapter.contentType }), 'shiso-image-preview'); + if (cancelled) { + releaseTemporaryPreviewUrl(url); + return; + } + setSecurePreviewUrl(url); + })().catch(() => { + /* bounded placeholder remains */ + }); + return () => { + cancelled = true; + if (url) releaseTemporaryPreviewUrl(url); + }; + }, [isOpen, network, previewToken]); + const recipeContext = useShisoRecipeContext(recipe); const nutritionRowsMatchRecipe = recipeContext !== null && recipeContext.ingredients.length === nutritionRows.length && @@ -824,6 +911,74 @@ export function ShisoModal({ return result; }; }, + // R2: starts the EXISTING image-recovery controller. It never saves and + // never exposes the preview token or Vault path to the model. Paid models + // stop at the controller's explicit confirmation state. + get imageGenerationUnavailableReason() { + return imageRecoveryUnavailableReason; + }, + get generateRecipeImage() { + const controller = imageControllerRef.current; + if (!controller) return undefined; + return async () => { + const target = imageRecipeRef.current ?? getImageRecipe?.() ?? null; + if (target === null) { + return { ok: false as const, status: 'error' as const, message: 'No recipe is currently active for image generation.' }; + } + const grant = imageGenerationGrantRef.current; + if ( + !grant.authorized || + grant.consumed || + grant.turn !== seqRef.current || + grant.recipeIdentity !== recipeIdentityOf(target) + ) { + return { + ok: false as const, + status: 'error' as const, + message: + grant.reason === 'no_selected_recipe' + ? 'Select or open one canonical recipe before asking SHISO to generate its image.' + : 'An explicit user request to generate an image for this selected recipe is required. I did not start image generation.', + }; + } + grant.consumed = true; + await controller.generate(target); + const state = controller.getState(); + const quote = state.quote; + if (state.phase === 'confirming') { + return { + ok: true as const, + status: 'confirmation_required' as const, + message: `${quote?.costLabel ?? 'This image model requires confirmation.'} Confirm the image generation in the preview panel; nothing is saved automatically.`, + ...(quote?.provider.id ? { provider: quote.provider.id } : {}), + ...(quote?.model ? { model: quote.model } : {}), + ...(quote?.costLabel ? { costLabel: quote.costLabel } : {}), + requiresConfirmation: true as const, + }; + } + if (state.phase === 'preview') { + return { + ok: true as const, + status: 'preview' as const, + message: 'The image preview is ready. Nothing has been saved; use Save Image or Cancel in the SHISO image panel.', + ...(state.preview?.provider ? { provider: state.preview.provider } : {}), + ...(state.preview?.model ? { model: state.preview.model } : {}), + requiresConfirmation: false as const, + }; + } + if (state.phase === 'saved') { + return { ok: true as const, status: 'saved' as const, message: state.message ?? 'The image was saved to the Vault.' }; + } + if (state.phase === 'idle' && state.message) { + return { ok: false as const, status: 'error' as const, message: state.message }; + } + return { + ok: true as const, + status: 'generating' as const, + message: state.message ?? 'Image generation is in progress. Use the SHISO image panel to confirm, save, or cancel.', + }; + }; + }, get saveWorkingRecipe() { if (!shisoRef.current.canSaveWorkingRecipe) return undefined; return () => { @@ -853,7 +1008,7 @@ export function ShisoModal({ : undefined; }, }), - [acceptIndependentNutrition, applyIndependentNutritionReview, applyIndependentNutritionSourceSelection, getIndependentNutritionSnapshot, network, onVaultRecipeSelected, runIndependentNutritionAnalysis, vaultCapabilities], + [acceptIndependentNutrition, applyIndependentNutritionReview, applyIndependentNutritionSourceSelection, getIndependentNutritionSnapshot, imageRecoveryUnavailableReason, network, onVaultRecipeSelected, runIndependentNutritionAnalysis, vaultCapabilities], ); // Advanced Nutrition can invoke the very same recipe-bound, validated AI @@ -921,6 +1076,18 @@ export function ShisoModal({ const seq = seqRef.current + 1; seqRef.current = seq; if (requestedMessage === undefined) setDraft(''); + // Application-boundary image authorization: only the user's exact message + // can create this turn's grant; the model never controls it. + const imageIntent = classifyImageGenerationIntent(message); + const imageGrantTarget = imageRecipeRef.current ?? getImageRecipe?.() ?? null; + const imageGrantIdentity = imageGrantTarget !== null ? recipeIdentityOf(imageGrantTarget) : ''; + imageGenerationGrantRef.current = { + authorized: imageIntent.authorized && imageGrantIdentity.length > 0, + reason: imageIntent.authorized && imageGrantIdentity.length === 0 ? 'no_selected_recipe' : imageIntent.reason, + recipeIdentity: imageGrantIdentity, + turn: seq, + consumed: false, + }; if (!retry) setRetryMessage(null); setCompletionPulse(false); setBusy(true); @@ -1259,6 +1426,33 @@ export function ShisoModal({ } }; + const imageTarget = () => imageRecipeRef.current ?? getImageRecipe?.() ?? null; + const confirmImageGeneration = () => { + const target = imageTarget(); + if (target === null) return; + void imageControllerRef.current?.confirm(target); + }; + const saveGeneratedImage = () => { + const target = imageTarget(); + if (target === null) return; + pendingImageSaveRecipeIdRef.current = target.id; + void imageControllerRef.current?.save(target); + }; + const regenerateImage = () => { + const target = imageTarget(); + if (target === null) return; + pendingImageSaveRecipeIdRef.current = null; + void imageControllerRef.current?.regenerate(target); + }; + const cancelImage = () => { + pendingImageSaveRecipeIdRef.current = null; + void imageControllerRef.current?.cancel(); + }; + const imageBusy = + imageState.phase === 'quoting' || + imageState.phase === 'generating' || + imageState.phase === 'saving'; + if (!isOpen) return null; const isFullPage = presentation === 'fullpage'; @@ -1676,6 +1870,119 @@ export function ShisoModal({ )} + {(imageState.phase !== 'idle' || imageState.message !== undefined) && ( +
+
+

Recipe image

+ + {imageState.phase === 'confirming' ? 'Awaiting confirmation' + : imageState.phase === 'saved' ? 'Saved' + : imageState.phase === 'preview' ? 'Preview — not saved' + : imageState.phase === 'saving' ? 'Saving' + : 'Generating'} + +
+

+ {imageRecipe?.title ?? 'Current recipe'} · Nothing is saved until you press Save Image. +

+ + {imageState.phase === 'confirming' && imageState.quote && ( +
+

Provider: {imageState.quote.provider.name} · {imageState.quote.model}

+

Cost: {imageState.quote.costLabel}

+

This paid/variable generation needs your explicit confirmation. One confirmation permits one provider call.

+
+ )} + + {securePreviewUrl !== null && ( + {`Generated + )} + {imageState.preview !== undefined && securePreviewUrl === null && imageState.phase !== 'saving' && ( +

Loading the authenticated preview…

+ )} + + {imageState.message !== undefined && ( +

+ {imageState.message} +

+ )} + +
+ {imageState.phase === 'confirming' && ( + + )} + {imageState.phase === 'preview' && ( + + )} + {(imageState.phase === 'preview' || imageState.phase === 'saved') && ( + + )} + {imageState.phase !== 'saved' && imageState.phase !== 'saving' && ( + + )} + {imageState.phase === 'saved' && ( + + )} +
+
+ )} + {recentProposals.length > 0 && (

diff --git a/src/core/shiso/imageGenerationAuthorization.ts b/src/core/shiso/imageGenerationAuthorization.ts new file mode 100644 index 0000000..4af6800 --- /dev/null +++ b/src/core/shiso/imageGenerationAuthorization.ts @@ -0,0 +1,68 @@ +/** + * Application-boundary authorization for SHISO image generation. + * + * The model may decide that an image would be useful; that is NOT a user + * request. Generation is allowed only when the CURRENT user message explicitly + * asks for an image. The trusted conversation surface classifies the exact + * user-authored message before the turn loop starts and binds the grant to the + * selected canonical recipe. The model cannot create or widen this grant. + */ + +export type ImageGenerationIntentReason = + | 'explicit_image_request' + | 'how_to_question' + | 'inventory_or_information' + | 'no_explicit_request'; + +export interface ImageGenerationIntent { + readonly authorized: boolean; + readonly reason: ImageGenerationIntentReason; +} + +const IMAGE_NOUN = '(?:image|photo|picture|photograph|illustration|visual)'; +const IMAGE_VERB = '(?:generate|create|make|produce|render|add|give|get|take|shoot|illustrate)'; + +const HOW_TO_QUESTION = new RegExp( + `\\b(?:how|what|explain|tell me how)\\b[^.!?]{0,60}\\b${IMAGE_VERB}\\b[^.!?]{0,40}\\b${IMAGE_NOUN}\\b`, + 'i', +); + +const EXPLICIT_REQUEST = new RegExp( + [ + // "generate an image", "make a photo", "add a picture" + `\\b${IMAGE_VERB}\\b[^.!?]{0,70}\\b${IMAGE_NOUN}\\b`, + // "I want/need an image", "please create a photo", "can you generate a picture" + `\\b(?:i (?:want|need|would like|'d love|would love)|please|can you|could you|would you|will you|go ahead and|help me|show me)\\b[^.!?]{0,70}\\b${IMAGE_NOUN}\\b`, + // "a photo for this recipe", "an image of this dish" + `\\b${IMAGE_NOUN}\\b[^.!?]{0,30}\\b(?:for|of)\\b[^.!?]{0,30}\\b(?:this|current|selected|the)\\b[^.!?]{0,20}\\b(?:recipe|dish)\\b`, + // "illustrate this recipe" + `\\billustrate\\b[^.!?]{0,40}\\b(?:this|the|current|selected|recipe|dish)\\b`, + ].join('|'), + 'i', +); + +const INVENTORY_OR_INFORMATION = new RegExp( + [ + `\\b(?:which|what|list|show|find|tell me)\\b[^.!?]{0,90}\\b(?:recipes?|dishes?)\\b[^.!?]{0,90}\\b(?:missing|broken|invalid|valid|unverified|without|no|${IMAGE_NOUN})\\b`, + `\\b(?:missing|broken|invalid|valid|unverified|without|no)\\s+(?:images?|photos?|pictures?|photographs?)\\b`, + ].join('|'), + 'i', +); + +export function classifyImageGenerationIntent(message: string): ImageGenerationIntent { + if (typeof message !== 'string') return { authorized: false, reason: 'no_explicit_request' }; + const text = message + .toLowerCase() + .replace(/[’‘]/g, "'") + .replace(/\s+/g, ' ') + .trim(); + if (text.length === 0) return { authorized: false, reason: 'no_explicit_request' }; + // A "how do I generate..." question is not an execution request. + if (HOW_TO_QUESTION.test(text)) return { authorized: false, reason: 'how_to_question' }; + // Read-only inventory/information intent WINS over broad request phrasings. + // "Show me which recipes..." / "I want to know which..." / "Please list..." + // must never authorize generation merely because they mention a photo. + if (INVENTORY_OR_INFORMATION.test(text)) return { authorized: false, reason: 'inventory_or_information' }; + if (EXPLICIT_REQUEST.test(text)) return { authorized: true, reason: 'explicit_image_request' }; + return { authorized: false, reason: 'no_explicit_request' }; +} diff --git a/src/core/shiso/protocol.ts b/src/core/shiso/protocol.ts index b43ae8e..931af47 100644 --- a/src/core/shiso/protocol.ts +++ b/src/core/shiso/protocol.ts @@ -85,6 +85,10 @@ export const SHISO_LIMITS = Object.freeze({ maxVaultSearchResults: 20, /** Maximum recipe identity used by one Vault capability call. */ maxVaultRecipeIdChars: 240, + /** Maximum image-inventory entries returned by one call. */ + maxImageInventoryResults: 50, + /** Maximum live Vault recipes scanned by one image-inventory call. */ + maxImageInventoryScan: 1000, /** Portion candidates returned per inspected record. */ maxPortionCandidates: 25, /** Count-portion candidates returned per inspected record. */ @@ -199,6 +203,8 @@ export const SHISO_TOOL_NAMES = Object.freeze([ 'search_vault_recipes', 'get_vault_recipe', 'select_vault_recipe', + 'inventory_vault_images', + 'generate_recipe_image', 'load_usda_catalog', 'get_nutrition_review', 'get_branded_evidence', @@ -247,6 +253,21 @@ export type ShisoToolArgs = } | { readonly tool: 'get_vault_recipe'; readonly recipe_id: string } | { readonly tool: 'select_vault_recipe'; readonly recipe_id: string } + | { + /** Read-only image inventory over the live Vault snapshot. */ + readonly tool: 'inventory_vault_images'; + readonly status?: 'all' | 'missing' | 'broken' | 'valid' | 'unknown'; + readonly offset?: number; + readonly limit?: number; + } + | { + /** + * Starts the EXISTING image recovery flow for the current canonical recipe. + * The application owns provider selection, quoting, confirmation, preview, + * and the explicit Save control. This tool never saves. + */ + readonly tool: 'generate_recipe_image'; + } | { readonly tool: 'load_usda_catalog' } | { readonly tool: 'get_nutrition_review'; readonly include_ingredients?: boolean } | { readonly tool: 'get_branded_evidence' } @@ -657,6 +678,8 @@ export const SHISO_DECISION_SCHEMA: Readonly> = Object.f cursor: { type: 'string' }, include_ingredients: { type: 'boolean' }, statuses: { type: 'array', items: { type: 'string', enum: ['needs_amount', 'needs_match'] } }, + status: { type: 'string', enum: ['all', 'missing', 'broken', 'valid', 'unknown'] }, + offset: { type: 'integer' }, // H-2: structured, field-scoped ingredient edits. Each edit names only // the fields it changes; unnamed fields are preserved from the authored // line. There is deliberately NO free-text "replacement line" field. diff --git a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx index c4434a0..05e1a79 100644 --- a/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx +++ b/tests/integration/shisoAgentFoundationAppOnDisk.test.tsx @@ -14,7 +14,7 @@ import App from '../../src/App'; import { ShisoEntryProvider, useShiso, type ShisoEntryPoints } from '../../src/application-ui/shisoEntryPoints'; import type { NetworkAdapter } from '../../src/application/adapters/NetworkAdapter'; import type { SettingsAdapter } from '../../src/application/adapters/SettingsAdapter'; -import { createBrowserVaultAdapter } from '../../src/platform/browser'; +import { createBrowserAssetAdapter, createBrowserVaultAdapter } from '../../src/platform/browser'; import { loadVaultContent } from '../../src/application/vaultContent'; import { hydrateAiSelections } from '../../src/application/aiSelection'; import { createAdvancedNutritionSession } from '../../src/core/nutritionV2/phase4/session'; @@ -24,6 +24,8 @@ import { USDA_ATTRIBUTION } from '../../src/core/nutritionV2/usda/types'; import { NUTRITION_PRODUCT_ACCESS_VERSION } from '../../src/core/nutritionV2/nutritionProductAccess'; import { buildMatchingBundle } from '../fixtures/usdaMatchingFixtures'; import { loadShisoConversation } from '../../src/application/shisoConversationPersistence'; +import { createShisoVaultCapability } from '../../src/application/shisoVaultCapabilities'; +import { assessRecipeImageHealth } from '../../src/core/recipeImage'; const nutritionRecipeMarkdown = `--- title: "Nutrition Fixture" @@ -1173,4 +1175,43 @@ describe('SHISO agent foundation real App save closure', () => { expect(persisted.recipes.find((recipe) => recipe.title === 'Braised Beef Short Ribs')?.codexNutrition).toBeUndefined(); }, 90000); + it('R2 image inventory returns exactly the two missing recipes from a disposable on-disk Vault', async () => { + const rootPath = await mkdtemp(join('/tmp', 'tkc-image-inventory-')); + roots.push(rootPath); + const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + 'base64', + ); + const makeMarkdown = (title: string, image?: string) => [ + '---', `title: "${title}"`, 'tags:', ' - food/recipes', + ...(image ? [`image: ${image}`] : []), '---', `# ${title}`, '## Ingredients', '- 1 cup water', '## Instructions', '1. Stir.', '', + ].join('\n'); + const recipes = [ + ['No Image One.md', makeMarkdown('No Image One')], + ['No Image Two.md', makeMarkdown('No Image Two')], + ['Valid Image.md', makeMarkdown('Valid Image', 'Assets/Valid.png')], + ['Broken Image.md', makeMarkdown('Broken Image', 'Assets/Broken.png')], + ] as const; + for (const [name, markdown] of recipes) { + const path = join(rootPath, 'Recipes', name); + await mkdir(dirname(path), { recursive: true }); + await writeFile(path, markdown, 'utf8'); + } + const assetPath = join(rootPath, 'Assets', 'Valid.png'); + await mkdir(dirname(assetPath), { recursive: true }); + await writeFile(assetPath, png); + const root = new DiskDirectoryHandle('Disposable Image Inventory Vault', rootPath); + const initial = await loadVaultContent(createBrowserVaultAdapter(root)); + const asset = createBrowserAssetAdapter(root); + const capability = createShisoVaultCapability({ + getRecipes: () => initial.recipes, + getNoteCount: () => 0, + getIdentity: () => ({ id: 'vault-image-inventory', source: 'personal' }), + assessImageHealth: (recipe) => assessRecipeImageHealth({ image: recipe.image }, { asset }), + }); + const result = await capability.inventoryImages!({ status: 'missing', limit: 20 }); + expect(result.entries.map((entry) => entry.title)).toEqual(['No Image One', 'No Image Two']); + expect(result.counts).toEqual({ missing: 2, broken: 1, valid: 1, unknown: 0 }); + }, 90000); + }); diff --git a/tests/security/shisoAuditRepairs.test.ts b/tests/security/shisoAuditRepairs.test.ts index 1980b3d..981f4f6 100644 --- a/tests/security/shisoAuditRepairs.test.ts +++ b/tests/security/shisoAuditRepairs.test.ts @@ -242,7 +242,10 @@ describe('F-1 — the advertised capability surface is truthful', () => { // Agent execution adds authenticated USDA source selection as the final // owner-delegated capability in this closed vocabulary. expect(SHISO_TOOL_NAMES).toContain('select_usda_nutrition_source'); - expect(SHISO_TOOL_NAMES).toHaveLength(20); + // R2 adds image inventory + the existing image-generation controller handoff. + expect(SHISO_TOOL_NAMES).toContain('inventory_vault_images'); + expect(SHISO_TOOL_NAMES).toContain('generate_recipe_image'); + expect(SHISO_TOOL_NAMES).toHaveLength(22); }); }); diff --git a/tests/security/shisoH1Repairs.test.ts b/tests/security/shisoH1Repairs.test.ts index 8a7869a..42f9ac4 100644 --- a/tests/security/shisoH1Repairs.test.ts +++ b/tests/security/shisoH1Repairs.test.ts @@ -433,9 +433,11 @@ describe('H-1 Scenario F — unsupported requests are refused truthfully', () => let session: AdvancedNutritionSession; beforeAll(async () => { session = await loadPinned(); }, 300000); - it('the system prompt tells Shiso it cannot create or edit images', () => { + it('the system prompt exposes image inventory and the existing image flow, never automatic save', () => { const src = readFileSync(join(__dirname, '../../server/shiso/conversationTurn.ts'), 'utf8'); - expect(src).toMatch(/cannot generate, edit, or retrieve recipe images/i); + expect(src).toMatch(/inventory_vault_images/i); + expect(src).toMatch(/generate_recipe_image/i); + expect(src).toMatch(/never saved automatically/i); // It must also be told to do requested work rather than ask again. H-2 // broadened this beyond read-only work: the user's instruction authorizes // the supported edits too. @@ -444,19 +446,18 @@ describe('H-1 Scenario F — unsupported requests are refused truthfully', () => expect(src).toMatch(/run_nutrition_analysis/i); }); - it('there is still no image, vault-write, or shell capability in the vocabulary', () => { + it('there is still no direct image-file, vault-write, or shell capability', () => { for (const forbidden of [ 'generate_image', 'create_image', 'edit_image', 'write_vault', 'save_recipe', 'run_command', 'read_file', 'exec', 'spawn', ]) { expect(SHISO_TOOL_NAMES as readonly string[]).not.toContain(forbidden); } - // Still a small, closed vocabulary (H-2 added the three authorized editing - // capabilities; SINC-3 added complete_nutrition, and Agent Execution added - // authenticated USDA source selection; neither bypasses the application - // owners or expands access to files, shells, or arbitrary network calls). + // R2 adds only the read-only inventory and the owner-delegated image flow. + expect(SHISO_TOOL_NAMES).toContain('inventory_vault_images'); + expect(SHISO_TOOL_NAMES).toContain('generate_recipe_image'); expect(SHISO_TOOL_NAMES).toContain('select_usda_nutrition_source'); - expect(SHISO_TOOL_NAMES.length).toBe(20); + expect(SHISO_TOOL_NAMES.length).toBe(22); }); it('the tool dispatcher still cannot reach the filesystem or network', () => { diff --git a/tests/security/shisoH1fRepairs.test.ts b/tests/security/shisoH1fRepairs.test.ts index c13cda6..edf46eb 100644 --- a/tests/security/shisoH1fRepairs.test.ts +++ b/tests/security/shisoH1fRepairs.test.ts @@ -462,7 +462,9 @@ describe('H-1F — security invariants', () => { // filesystem, a shell, or the vault directly — every change is performed // by the application owner of that state. expect(SHISO_TOOL_NAMES).toContain('select_usda_nutrition_source'); - expect(SHISO_TOOL_NAMES.length).toBe(20); + expect(SHISO_TOOL_NAMES).toContain('inventory_vault_images'); + expect(SHISO_TOOL_NAMES).toContain('generate_recipe_image'); + expect(SHISO_TOOL_NAMES.length).toBe(22); for (const forbidden of [ 'generate_image', 'create_image', 'edit_image', 'write_vault', 'save_recipe', 'run_command', 'read_file', 'exec', 'spawn', 'apply_proposal', 'dispatch_action', diff --git a/tests/unit/shisoImageAuthorization.test.ts b/tests/unit/shisoImageAuthorization.test.ts new file mode 100644 index 0000000..a41dc05 --- /dev/null +++ b/tests/unit/shisoImageAuthorization.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; +import { classifyImageGenerationIntent } from '../../src/core/shiso/imageGenerationAuthorization'; + +describe('SHISO image-generation user authorization', () => { + it.each([ + 'SHISO, generate an image for this recipe.', + 'Please create a photo of this dish.', + 'Can you make a picture for the selected recipe?', + 'I want an image for this recipe.', + 'Add an image to this recipe.', + 'Illustrate this recipe.', + 'Show me a photo of this dish.', + ])('permits explicit request: %s', (message) => { + expect(classifyImageGenerationIntent(message)).toEqual({ + authorized: true, + reason: 'explicit_image_request', + }); + }); + + it.each([ + 'Which recipes in my Vault have no images?', + 'Show me recipes with missing images.', + 'Can you show me which recipes are missing a photo?', + 'I want to know which recipes have no photo.', + 'Show me a list of recipes missing a photo.', + 'Please list recipes without a photo.', + 'Tell me about this recipe.', + 'What image would suit this recipe?', + 'Do you think this recipe needs an image?', + 'How do I generate an image for a recipe?', + 'What is the image status of my recipes?', + ])('does not authorize: %s', (message) => { + expect(classifyImageGenerationIntent(message).authorized).toBe(false); + }); +}); diff --git a/tests/unit/shisoImageInventory.test.ts b/tests/unit/shisoImageInventory.test.ts new file mode 100644 index 0000000..7d3092c --- /dev/null +++ b/tests/unit/shisoImageInventory.test.ts @@ -0,0 +1,211 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + createShisoVaultCapability, + type ShisoVaultCapabilitySource, +} from '../../src/application/shisoVaultCapabilities'; +import { executeShisoTool } from '../../src/application/shisoTools'; +import { parseShisoDecision } from '../../server/shiso/conversationTurn'; +import { SHISO_SYSTEM_PROMPT } from '../../server/shiso/conversationTurn'; +import type { ObsidianRecipe } from '../../src/types'; +import { assessRecipeImageHealth } from '../../src/core/recipeImage'; +import type { AssetAdapter } from '../../src/application/adapters/AssetAdapter'; + +function recipe(id: string, title: string, image?: string): ObsidianRecipe { + return { + id, + fileName: `${title}.md`, + filePath: `${title}.md`, + rawMarkdown: `# ${title}`, + title, + tags: ['food/recipes'], + category: 'Main Course', + cuisine: 'American', + ingredients: [], + instructions: [], + ...(image !== undefined ? { image } : {}), + callouts: [], + wikilinks: [], + dataviewFields: {}, + } as ObsidianRecipe; +} + +const RECIPES = [ + recipe('r-missing', 'No Photo Soup'), + recipe('r-broken', 'Broken Photo Pie', 'Assets/missing.png'), + recipe('r-valid', 'Valid Photo Salad', 'Assets/valid.png'), + recipe('r-remote', 'Remote Photo Bowl', 'https://example.com/photo.jpg'), + recipe('r-locked', 'Locked Photo Stew', 'Assets/locked.png'), +]; + +function source(): ShisoVaultCapabilitySource { + return { + getRecipes: () => RECIPES, + getNoteCount: () => 0, + getIdentity: () => ({ id: 'vault-test', source: 'personal' }), + assessImageHealth: async (entry) => { + if (!entry.image) return { kind: 'missing', deterministic: true, reason: 'No image' }; + if (entry.image === 'Assets/missing.png') return { kind: 'broken_local', deterministic: true, reason: 'Missing file' }; + if (entry.image === 'Assets/valid.png') return { kind: 'valid_local', deterministic: true, reason: 'Valid file' }; + if (entry.image === 'https://example.com/photo.jpg') return { kind: 'remote_present', deterministic: true, reason: 'Remote reference not probed' }; + return { kind: 'unverifiable_local', deterministic: true, reason: 'Cannot verify' }; + }, + }; +} + +describe('SHISO Vault image inventory', () => { + it('returns exactly the missing-image recipes and accurate status counts', async () => { + const capability = createShisoVaultCapability(source()); + const result = await capability.inventoryImages!({ status: 'missing' }); + expect(result.entries).toEqual([ + expect.objectContaining({ recipe_id: 'r-missing', title: 'No Photo Soup', status: 'missing' }), + ]); + expect(result.counts).toEqual({ missing: 1, broken: 1, valid: 1, unknown: 2 }); + expect(result.total_recipes).toBe(5); + expect(result.total_matches).toBe(1); + expect(result.has_more).toBe(false); + expect(JSON.stringify(result)).not.toContain('Assets/'); + expect(JSON.stringify(result)).not.toContain('https://example.com'); + }); + + it('distinguishes broken, valid, and unverified images', async () => { + const capability = createShisoVaultCapability(source()); + const result = await capability.inventoryImages!({ status: 'all', limit: 50 }); + expect(result.entries.find((entry) => entry.recipe_id === 'r-broken')?.status).toBe('broken'); + expect(result.entries.find((entry) => entry.recipe_id === 'r-valid')?.status).toBe('valid'); + expect(result.entries.find((entry) => entry.recipe_id === 'r-remote')?.status).toBe('unknown'); + expect(result.entries.find((entry) => entry.recipe_id === 'r-locked')?.status).toBe('unknown'); + expect(result.counts).toEqual({ missing: 1, broken: 1, valid: 1, unknown: 2 }); + }); + + it('uses the real image-health authority against a disposable asset snapshot', async () => { + const png = new Uint8Array(Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + 'base64', + )); + const asset = { + exists: async (path: string) => path === 'Assets/valid.png', + read: async (path: string) => path === 'Assets/valid.png' ? png : new Uint8Array(), + write: async () => {}, + delete: async () => {}, + } as AssetAdapter; + const recipes = [ + recipe('real-missing', 'No Photo Soup'), + recipe('real-missing-2', 'No Photo Stew'), + recipe('real-broken', 'Broken Photo Pie', 'Assets/broken.png'), + recipe('real-valid', 'Valid Photo Salad', 'Assets/valid.png'), + recipe('real-remote', 'Remote Photo Bowl', 'https://example.com/photo.jpg'), + ]; + const capability = createShisoVaultCapability({ + getRecipes: () => recipes, + getNoteCount: () => 0, + getIdentity: () => ({ id: 'vault-real-image', source: 'personal' }), + assessImageHealth: (entry) => assessRecipeImageHealth({ image: entry.image }, { asset }), + }); + const result = await capability.inventoryImages!({ status: 'missing' }); + expect(result.entries).toEqual([ + expect.objectContaining({ recipe_id: 'real-missing', title: 'No Photo Soup' }), + expect.objectContaining({ recipe_id: 'real-missing-2', title: 'No Photo Stew' }), + ]); + expect(result.counts).toEqual({ missing: 2, broken: 1, valid: 1, unknown: 1 }); + }); + + it('reports unknown rather than missing when image-health authority is unavailable', async () => { + const capability = createShisoVaultCapability({ + ...source(), + assessImageHealth: undefined, + }); + const result = await capability.inventoryImages!({ status: 'all' }); + expect(result.counts).toEqual({ missing: 0, broken: 0, valid: 0, unknown: 5 }); + expect(result.entries.every((entry) => entry.status === 'unknown')).toBe(true); + }); + + it('paginates bounded results without losing total counts', async () => { + const capability = createShisoVaultCapability(source()); + const first = await capability.inventoryImages!({ status: 'all', limit: 2, offset: 0 }); + const second = await capability.inventoryImages!({ status: 'all', limit: 2, offset: 2 }); + expect(first.entries.map((entry) => entry.recipe_id)).toEqual(['r-missing', 'r-broken']); + expect(second.entries.map((entry) => entry.recipe_id)).toEqual(['r-valid', 'r-remote']); + expect(first.has_more).toBe(true); + expect(first.counts).toEqual({ missing: 1, broken: 1, valid: 1, unknown: 2 }); + }); + + it('respects cancellation and never fabricates missing results', async () => { + const capability = createShisoVaultCapability(source()); + const controller = new AbortController(); + controller.abort(); + const result = await capability.inventoryImages!({ status: 'missing' }, controller.signal); + expect(result.cancelled).toBe(true); + expect(result.entries).toEqual([]); + expect(result.counts).toEqual({ missing: 0, broken: 0, valid: 0, unknown: 0 }); + }); + + it('cancels when the Vault session changes during the scan', async () => { + let identity = 'vault-before'; + let calls = 0; + const capability = createShisoVaultCapability({ + getRecipes: () => RECIPES, + getNoteCount: () => 0, + getIdentity: () => ({ id: identity, source: 'personal' }), + assessImageHealth: async () => { + calls += 1; + if (calls === 1) identity = 'vault-after'; + return { kind: 'missing', deterministic: true, reason: 'No image' }; + }, + }); + const result = await capability.inventoryImages!({ status: 'missing' }); + expect(result.cancelled).toBe(true); + expect(result.entries).toEqual([]); + }); + + it('executes through the closed SHISO tool with a truthful summary', async () => { + const capability = createShisoVaultCapability(source()); + const observation = await executeShisoTool( + { tool: 'inventory_vault_images', status: 'missing', offset: 0, limit: 20 }, + { vault: capability, recipe: null, session: null, nutrition: null }, + ); + expect(observation.ok).toBe(true); + if (!observation.ok) throw new Error('expected inventory success'); + expect(observation.summary).toContain('1 missing'); + expect(observation.data).toMatchObject({ + counts: { missing: 1, broken: 1, valid: 1, unknown: 2 }, + total_recipes: 5, + status_filter: 'missing', + }); + }); + + it('validates the structured inventory arguments and prompt guidance', () => { + const parsed = parseShisoDecision({ + kind: 'tool_request', + tool: 'inventory_vault_images', + args: { status: 'missing', limit: 5, offset: 2 }, + }); + expect(parsed).toMatchObject({ + kind: 'tool_request', + tool: 'inventory_vault_images', + args: { status: 'missing', limit: 5, offset: 2 }, + }); + expect(SHISO_SYSTEM_PROMPT).toContain('inventory_vault_images'); + expect(SHISO_SYSTEM_PROMPT).toContain("Never answer that structured"); + expect(SHISO_SYSTEM_PROMPT).toContain("'no image'"); + }); + + it('starts the existing image controller through the closed generation tool without saving', async () => { + const generate = vi.fn(async () => ({ + ok: true as const, + status: 'preview' as const, + message: 'The image preview is ready. Nothing has been saved.', + provider: 'openrouter-image', + model: 'google/gemini-2.5-flash-image', + })); + const observation = await executeShisoTool( + { tool: 'generate_recipe_image' }, + { recipe: { title: 'No Photo Soup', servings: 4, ingredients: [], instructions: [] }, session: null, nutrition: null, generateRecipeImage: generate }, + ); + expect(observation.ok).toBe(true); + if (!observation.ok) throw new Error('expected image generation success'); + expect(generate).toHaveBeenCalledTimes(1); + expect(observation.data).toMatchObject({ status: 'preview', provider: 'openrouter-image' }); + expect(JSON.stringify(observation.data)).not.toContain('token'); + expect(JSON.stringify(observation.data)).not.toContain('Assets/'); + }); +}); diff --git a/tests/unit/shisoImageWorkflow.test.tsx b/tests/unit/shisoImageWorkflow.test.tsx new file mode 100644 index 0000000..1a2a0c0 --- /dev/null +++ b/tests/unit/shisoImageWorkflow.test.tsx @@ -0,0 +1,374 @@ +// @vitest-environment jsdom +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { ShisoModal } from '../../src/components/ShisoModal'; +import { hydrateAiSelections } from '../../src/application/aiSelection'; +import type { NetworkAdapter } from '../../src/application/adapters/NetworkAdapter'; +import type { RecipeImageRecoverySupport } from '../../src/application/recipeImageRecovery'; +import type { ObsidianRecipe } from '../../src/types'; +import { RecipeImageSaveConflictError } from '../../src/application/recipeImageSave'; + +const PNG_BYTES = new Uint8Array(Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + 'base64', +)); + +const RECIPE = { + id: 'smoked-chicken.md', + fileName: 'Smoked Chicken.md', + filePath: 'Smoked Chicken.md', + rawMarkdown: '---\ntitle: Smoked Chicken\n---\n# Smoked Chicken', + title: 'Smoked Chicken', + description: 'Smoked chicken with a glossy glaze.', + servings: 4, + cuisine: 'American BBQ', + course: 'Main', + image: undefined, + tags: ['food/recipes'], + category: 'Main Course', + ingredients: [{ original: '1 whole chicken', name: 'whole chicken' }], + instructions: [{ stepNumber: 1, text: 'Smoke until done.' }], + callouts: [], + wikilinks: [], + dataviewFields: {}, +} as unknown as ObsidianRecipe; + +beforeAll(async () => { + await hydrateAiSelections({ get: async () => undefined }); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +function network(options: { readonly paid?: boolean; readonly unavailable?: boolean } = {}): NetworkAdapter & { saveCalls: number; generateCalls: number; generateBodies: Record[] } { + let turn = 0; + let generateCalls = 0; + const generateBodies: Record[] = []; + const adapter = { + saveCalls: 0, + get generateCalls() { return generateCalls; }, + generateBodies, + post: async (path: string, body?: unknown) => { + if (path === '/api/shiso/turn') { + turn += 1; + if (turn === 1) { + return { + status: 200, + ok: true, + data: { + ok: true, + kind: 'tool_request', + tool: 'generate_recipe_image', + args: { tool: 'generate_recipe_image' }, + model_invocations_used: 1, + tool_calls_used: 1, + }, + }; + } + return { + status: 200, + ok: true, + data: { + ok: true, + kind: 'reply', + text: 'Review the image panel to confirm, save, or cancel the generated image.', + proposals: [], + model_invocations_used: 2, + tool_calls_used: 1, + }, + }; + } + if (path === '/api/recipes/image/quote') { + if (options.unavailable === true) { + return { + status: 503, + ok: false, + data: { code: 'IMAGE_PROVIDER_NOT_CONFIGURED', error: 'No image generation provider is configured on the server.' }, + }; + } + return { + status: 200, + ok: true, + data: { + ok: true, + provider: { id: 'openrouter-image', name: 'OpenRouter Image' }, + model: 'google/gemini-2.5-flash-image', + credentialSource: 'session_only', + costClass: options.paid === true ? 'paid' : 'zero', + costLabel: options.paid === true ? 'Estimated provider charge' : 'Verified zero price', + requiresConfirmation: options.paid === true, + ...(options.paid === true ? { confirmationToken: 'confirmation-token' } : {}), + }, + }; + } + if (path === '/api/recipes/image/generate') { + generateCalls += 1; + generateBodies.push((body ?? {}) as Record); + return { + status: 200, + ok: true, + data: { + token: 'preview-token', + contentType: 'image/png', + provider: 'openrouter-image', + model: 'google/gemini-2.5-flash-image', + recipeContentHash: 'a'.repeat(64), + vaultSessionId: 'vault-session-test', + expiresAt: Date.now() + 60_000, + }, + }; + } + return { status: 200, ok: true, data: { ok: true } }; + }, + get: async () => ({ status: 200, ok: true, data: { ok: true } }), + getBytes: async () => ({ status: 200, ok: true, bytes: PNG_BYTES, contentType: 'image/png' }), + request: async () => ({ status: 200, ok: true, data: { ok: true } }), + } as unknown as NetworkAdapter & { saveCalls: number; generateCalls: number; generateBodies: Record[] }; + return adapter; +} + +function support(): RecipeImageRecoverySupport & { saveImageCalls: number } { + let calls = 0; + const value = { + vaultSessionId: 'vault-session-test', + asset: { + exists: async () => false, + read: async () => PNG_BYTES, + write: async () => {}, + delete: async () => {}, + }, + computeContentHash: async () => 'a'.repeat(64), + saveImage: async () => { + calls += 1; + return { + imagePath: 'Assets/Smoked Chicken.png', + provider: 'openrouter-image', + model: 'google/gemini-2.5-flash-image', + generatedAt: '2026-11-29T12:00:00.000Z', + registration: 'registered' as const, + }; + }, + } as unknown as RecipeImageRecoverySupport & { saveImageCalls: number }; + Object.defineProperty(value, 'saveImageCalls', { get: () => calls }); + return value; +} + +describe('SHISO image workflow', () => { + it('shows the generated preview, waits for explicit Save, and keeps the conversation', async () => { + const createObjectURL = vi.fn(() => 'blob:shiso-preview'); + const revokeObjectURL = vi.fn(); + vi.stubGlobal('URL', { ...URL, createObjectURL, revokeObjectURL }); + const imageSupport = support(); + const onSaved = vi.fn(); + const net = network(); + render( + {}} + network={net} + recipe={RECIPE} + imageRecovery={imageSupport} + getImageRecipe={() => RECIPE} + onRecipeImageSaved={onSaved} + nutritionSession={null} + nutritionRows={[]} + nutritionReviewRows={[]} + nutritionSummary={null} + nutritionUnsaved={false} + />, + ); + + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: 'SHISO, generate an image for this recipe.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + + await screen.findByText('Review the image panel to confirm, save, or cancel the generated image.'); + await screen.findByTestId('shiso-image-panel'); + await screen.findByTestId('shiso-image-preview'); + expect(net.generateBodies[0]?.['title']).toBe('Smoked Chicken'); + expect(net.generateBodies[0]?.['ingredients']).toContain('whole chicken'); + expect(imageSupport.saveImageCalls).toBe(0); + expect(onSaved).not.toHaveBeenCalled(); + expect(screen.getByTestId('shiso-image-save')).toBeTruthy(); + expect(screen.getByTestId('shiso-image-regenerate')).toBeTruthy(); + expect(screen.getByTestId('shiso-image-cancel')).toBeTruthy(); + + fireEvent.click(screen.getByTestId('shiso-image-save')); + await waitFor(() => expect(onSaved).toHaveBeenCalledWith('smoked-chicken.md', 'Assets/Smoked Chicken.png')); + expect(imageSupport.saveImageCalls).toBe(1); + expect(screen.getByText('Review the image panel to confirm, save, or cancel the generated image.')).toBeTruthy(); + await screen.findByText(/Image saved to Assets\/Smoked Chicken.png/); + }); + + it.each([ + 'Which recipes in my Vault have no images?', + 'Can you show me which recipes are missing a photo?', + 'I want to know which recipes have no photo.', + 'Show me a list of recipes missing a photo.', + 'Please list recipes without a photo.', + ])('rejects model-initiated generation for read-only request: %s', async (message) => { + const imageSupport = support(); + const net = network(); + const onSaved = vi.fn(); + render( + {}} + network={net} + recipe={RECIPE} + imageRecovery={imageSupport} + getImageRecipe={() => RECIPE} + onRecipeImageSaved={onSaved} + nutritionSession={null} + nutritionRows={[]} + nutritionReviewRows={[]} + nutritionSummary={null} + nutritionUnsaved={false} + />, + ); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: message } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await screen.findByText(/An explicit user request to generate an image for this selected recipe is required/i); + expect(net.generateCalls).toBe(0); + expect(imageSupport.saveImageCalls).toBe(0); + expect(onSaved).not.toHaveBeenCalled(); + expect(screen.queryByTestId('shiso-image-panel')).toBeNull(); + }); + + it('requires explicit confirmation before a paid image provider call', async () => { + vi.stubGlobal('URL', { ...URL, createObjectURL: vi.fn(() => 'blob:shiso-preview'), revokeObjectURL: vi.fn() }); + const imageSupport = support(); + const net = network({ paid: true }); + const onSaved = vi.fn(); + render( + {}} + network={net} + recipe={RECIPE} + imageRecovery={imageSupport} + getImageRecipe={() => RECIPE} + onRecipeImageSaved={onSaved} + nutritionSession={null} + nutritionRows={[]} + nutritionReviewRows={[]} + nutritionSummary={null} + nutritionUnsaved={false} + />, + ); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: 'SHISO, generate an image for this recipe.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + + await screen.findByTestId('shiso-image-confirm'); + expect(net.generateCalls).toBe(0); + expect(imageSupport.saveImageCalls).toBe(0); + expect(screen.getAllByText(/Estimated provider charge/).length).toBeGreaterThan(0); + expect(screen.queryByTestId('shiso-image-save')).toBeNull(); + + fireEvent.click(screen.getByTestId('shiso-image-confirm')); + await screen.findByTestId('shiso-image-preview'); + expect(net.generateCalls).toBe(1); + expect(net.generateBodies[0]?.['confirmationToken']).toBe('confirmation-token'); + expect(imageSupport.saveImageCalls).toBe(0); + + fireEvent.click(screen.getByTestId('shiso-image-save')); + await waitFor(() => expect(onSaved).toHaveBeenCalledWith('smoked-chicken.md', 'Assets/Smoked Chicken.png')); + expect(imageSupport.saveImageCalls).toBe(1); + }); + + it('cancels a preview without saving and keeps the conversation', async () => { + vi.stubGlobal('URL', { ...URL, createObjectURL: vi.fn(() => 'blob:shiso-preview'), revokeObjectURL: vi.fn() }); + const imageSupport = support(); + const net = network(); + render( + {}} + network={net} + recipe={RECIPE} + imageRecovery={imageSupport} + getImageRecipe={() => RECIPE} + onRecipeImageSaved={() => {}} + nutritionSession={null} + nutritionRows={[]} + nutritionReviewRows={[]} + nutritionSummary={null} + nutritionUnsaved={false} + />, + ); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: 'SHISO, generate an image for this recipe.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await screen.findByTestId('shiso-image-preview'); + fireEvent.click(screen.getByTestId('shiso-image-cancel')); + await waitFor(() => expect(screen.queryByTestId('shiso-image-panel')).toBeNull()); + expect(imageSupport.saveImageCalls).toBe(0); + expect(screen.getByText('Review the image panel to confirm, save, or cancel the generated image.')).toBeTruthy(); + }); + + it('keeps the preview and reports a vault conflict instead of saving', async () => { + vi.stubGlobal('URL', { ...URL, createObjectURL: vi.fn(() => 'blob:shiso-preview'), revokeObjectURL: vi.fn() }); + const imageSupport = support(); + imageSupport.saveImage = async () => { + throw new RecipeImageSaveConflictError('VAULT_CHANGED', 'The vault has changed since this image was generated. Please try again.'); + }; + const net = network(); + const onSaved = vi.fn(); + render( + {}} + network={net} + recipe={RECIPE} + imageRecovery={imageSupport} + getImageRecipe={() => RECIPE} + onRecipeImageSaved={onSaved} + nutritionSession={null} + nutritionRows={[]} + nutritionReviewRows={[]} + nutritionSummary={null} + nutritionUnsaved={false} + />, + ); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: 'SHISO, generate an image for this recipe.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await screen.findByTestId('shiso-image-preview'); + fireEvent.click(screen.getByTestId('shiso-image-save')); + await screen.findByText(/The vault has changed since this image was generated/i); + expect(onSaved).not.toHaveBeenCalled(); + expect(screen.getByTestId('shiso-image-preview')).toBeTruthy(); + }); + + it('shows a meaningful message when the selected image provider is unavailable', async () => { + const imageSupport = support(); + const net = network({ unavailable: true }); + render( + {}} + network={net} + recipe={RECIPE} + imageRecovery={imageSupport} + getImageRecipe={() => RECIPE} + onRecipeImageSaved={() => {}} + nutritionSession={null} + nutritionRows={[]} + nutritionReviewRows={[]} + nutritionSummary={null} + nutritionUnsaved={false} + />, + ); + const composer = await screen.findByPlaceholderText('Ask Shiso…') as HTMLTextAreaElement; + fireEvent.change(composer, { target: { value: 'SHISO, generate an image for this recipe.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Send' })); + await screen.findByTestId('shiso-image-panel'); + expect(screen.getAllByText(/No image generation provider is configured on the server/i).length).toBeGreaterThan(0); + expect(imageSupport.saveImageCalls).toBe(0); + expect(net.generateCalls).toBe(0); + }); +});