diff --git a/app/api/morph-chat/route.ts b/app/api/morph-chat/route.ts index 83f97f11..c2042ebb 100644 --- a/app/api/morph-chat/route.ts +++ b/app/api/morph-chat/route.ts @@ -30,6 +30,14 @@ export async function POST(req: Request) { currentFragment: FragmentSchema } = await req.json() + // Validate that currentFragment exists (required for morph edits) + if (!currentFragment?.file_path || !currentFragment?.code) { + return new Response( + JSON.stringify({ error: 'currentFragment with file_path and code is required for morph edits' }), + { status: 400, headers: { 'Content-Type': 'application/json' } } + ) + } + // Rate limiting (same as chat route) const limit = !config.apiKey ? await ratelimit( diff --git a/app/page.tsx b/app/page.tsx index 05817e6d..261f6be5 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -79,10 +79,8 @@ export default function Home() { : { [selectedTemplate]: templates[selectedTemplate] } const lastMessage = messages[messages.length - 1] - // Determine which API to use based on morph toggle and existing fragment - const shouldUseMorph = - useMorphApply && fragment && fragment.code && fragment.file_path - const apiEndpoint = shouldUseMorph ? '/api/morph-chat' : '/api/chat' + // Determine which API to use based on morph toggle AND whether we have a fragment to edit + const apiEndpoint = useMorphApply && fragment?.code ? '/api/morph-chat' : '/api/chat' const { object, submit, isLoading, stop, error } = useObject({ api: apiEndpoint, @@ -128,7 +126,8 @@ export default function Home() { }) useEffect(() => { - if (object) { + // Only update messages during active streaming, not when toggling settings + if (object && isLoading) { setFragment(object) const content: Message['content'] = [ { type: 'text', text: object.commentary || '' }, @@ -150,7 +149,7 @@ export default function Home() { }) } } - }, [object]) + }, [object, isLoading]) useEffect(() => { if (error) stop() @@ -200,7 +199,7 @@ export default function Home() { template: currentTemplate, model: currentModel, config: languageModel, - ...(shouldUseMorph && fragment ? { currentFragment: fragment } : {}), + ...(useMorphApply && fragment?.code ? { currentFragment: fragment } : {}), }) setChatInput('') @@ -221,7 +220,7 @@ export default function Home() { template: currentTemplate, model: currentModel, config: languageModel, - ...(shouldUseMorph && fragment ? { currentFragment: fragment } : {}), + ...(useMorphApply && fragment?.code ? { currentFragment: fragment } : {}), }) }