#!/usr/bin/env python3 """ Patch: Fix frontend catch-up message loss. Issue: After catch-up succeeds, the new session's backend hydration fetches /api/session/{newId}/messages from the backend, which only contains the summary message. It then calls setMessages() and saveMessages(), OVERWRITING the old full messages that were moved to the new ID via renameSession -> moveMessages. Fix: In each hydration code path, only overwrite frontend messages if the backend returns MORE non-system messages than the frontend already has. If the frontend already has more messages (from localStorage), keep them. Also: Fix the catch-up dataset fallback in ExpiredBanner to properly filter event rows and handle malformed data. Runs during Docker build — never fails the build. """ import ast import os import sys PATCHED_MARKER = "// PATCH: catch-up fix (frontend)" def _safe_replace(content, old, new, count=1): if old in content: content = content.replace(old, new, count) return content, True return content, False def _is_python_file(path): return path.endswith(".py") def patch_file(path, patch_fn): if not os.path.exists(path): print(f"SKIP: {path} not found") return False try: with open(path, "r", encoding="utf-8") as f: content = f.read() content, changed = patch_fn(content) if not changed: print(f"SKIP: {path} — no changes needed") return False # Only validate Python syntax for .py files if _is_python_file(path): try: ast.parse(content) except SyntaxError as e: print(f"FAIL: {path} syntax: {e}") return False with open(path, "w", encoding="utf-8") as f: f.write(content) print(f"OK: {path} patched (catch-up fix)") return True except Exception as e: print(f"WARN: {path} patch error: {e}") return False # ─── Patch useAgentChat.ts ────────────────────────────────────────────────── print("=== Patching useAgentChat.ts (prevent message overwrite) ===") USE_AGENT_CHAT = "/source/frontend/src/hooks/useAgentChat.ts" def _patch_use_agent_chat(content): changed = False if PATCHED_MARKER in content: print(" SKIP: already patched") return content, False # Patch 1: onRecoverMessages # The pattern uses 10-space indentation (inside a nested callback) old_pattern1 = ( " const setMsgs = chatActionsRef.current.setMessages;\n" " if (setMsgs && uiMsgs.length >= currentMessageCount) {\n" " setMsgs(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }" ) new_pattern1 = ( " // === PATCH: catch-up fix (frontend) ===\n" " // After catch-up, the backend only has a summary message but\n" " // the frontend (via localStorage moveMessages) has the full\n" " // old conversation. Don't overwrite if backend has fewer.\n" " const _currentNonSystem = chatActionsRef.current.messages.filter(\n" " (m) => !(m.parts?.[0]?.type === 'text' && typeof m.parts?.[0]?.text === 'string' && m.parts?.[0].text.trimStart().startsWith('[SYSTEM:'))\n" " );\n" " const _shouldOverwrite = uiMsgs.length > _currentNonSystem.length || _currentNonSystem.length === 0;\n" " const setMsgs = chatActionsRef.current.setMessages;\n" " if (setMsgs && _shouldOverwrite) {\n" " setMsgs(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }" ) content, ok = _safe_replace(content, old_pattern1, new_pattern1) if ok: print(" + Prevented backend overwrite in onRecoverMessages") changed = True else: print(" INFO: onRecoverMessages pattern not found") # Patch 2: refreshMessages # The pattern uses 6-space indentation and ends with 'return true;' old_pattern2 = ( " const setMsgs = chatActionsRef.current.setMessages;\n" " if (setMsgs && uiMsgs.length > 0) {\n" " setMsgs(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }\n" " return true;" ) new_pattern2 = ( " // === PATCH: catch-up fix (frontend) ===\n" " const _currentNonSystem2 = chatActionsRef.current.messages.filter(\n" " (m) => !(m.parts?.[0]?.type === 'text' && typeof m.parts?.[0]?.text === 'string' && m.parts?.[0].text.trimStart().startsWith('[SYSTEM:'))\n" " );\n" " const _shouldOverwrite2 = uiMsgs.length > _currentNonSystem2.length || _currentNonSystem2.length === 0;\n" " const setMsgs = chatActionsRef.current.setMessages;\n" " if (setMsgs && _shouldOverwrite2) {\n" " setMsgs(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }\n" " return true;" ) content, ok2 = _safe_replace(content, old_pattern2, new_pattern2) if ok2: print(" + Prevented backend overwrite in refreshMessages") changed = True else: print(" INFO: refreshMessages pattern not found") # Patch 3: Main hydration useEffect (uses chat.setMessages) # There are multiple code paths with different indentation levels: # - 6-space indent: in some code paths # - 10-space indent: main hydration useEffect # - 14-space indent: hydrateMessages helper (appears twice) # We patch each indentation level separately. old_pattern3a = ( " if (uiMsgs.length > 0) {\n" " chat.setMessages(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }" ) new_pattern3a = ( " // === PATCH: catch-up fix (frontend) ===\n" " // Don't overwrite frontend messages with backend's fewer messages\n" " const _currentMsgs = (chatActionsRef.current.messages || []).filter(\n" " (m) => !(m.parts?.[0]?.type === 'text' && typeof m.parts?.[0]?.text === 'string' && m.parts?.[0].text.trimStart().startsWith('[SYSTEM:'))\n" " );\n" " const _shouldSet = uiMsgs.length > _currentMsgs.length || _currentMsgs.length === 0;\n" " if (_shouldSet) {\n" " chat.setMessages(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }" ) # 10-space indentation variant old_pattern3b = ( " if (uiMsgs.length > 0) {\n" " chat.setMessages(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }" ) new_pattern3b = ( " // === PATCH: catch-up fix (frontend) ===\n" " const _currentMsgsB = (chatActionsRef.current.messages || []).filter(\n" " (m) => !(m.parts?.[0]?.type === 'text' && typeof m.parts?.[0]?.text === 'string' && m.parts?.[0].text.trimStart().startsWith('[SYSTEM:'))\n" " );\n" " const _shouldSetB = uiMsgs.length > _currentMsgsB.length || _currentMsgsB.length === 0;\n" " if (_shouldSetB) {\n" " chat.setMessages(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }" ) # 14-space indentation variant old_pattern3c = ( " if (uiMsgs.length > 0) {\n" " chat.setMessages(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }" ) new_pattern3c = ( " // === PATCH: catch-up fix (frontend) ===\n" " const _currentMsgsC = (chatActionsRef.current.messages || []).filter(\n" " (m) => !(m.parts?.[0]?.type === 'text' && typeof m.parts?.[0]?.text === 'string' && m.parts?.[0].text.trimStart().startsWith('[SYSTEM:'))\n" " );\n" " const _shouldSetC = uiMsgs.length > _currentMsgsC.length || _currentMsgsC.length === 0;\n" " if (_shouldSetC) {\n" " chat.setMessages(uiMsgs);\n" " saveMessages(sessionId, uiMsgs);\n" " }" ) count = 0 for old_p, new_p in [(old_pattern3a, new_pattern3a), (old_pattern3b, new_pattern3b), (old_pattern3c, new_pattern3c)]: while True: content, ok3 = _safe_replace(content, old_p, new_p) if ok3: count += 1 changed = True else: break if count > 0: print(f" + Prevented backend overwrite in {count} hydration code paths") if changed: content = content.replace( "import { logger } from '@/utils/logger';", "import { logger } from '@/utils/logger';\n// " + PATCHED_MARKER + " applied", 1 ) return content, changed patch_file(USE_AGENT_CHAT, _patch_use_agent_chat) # ─── Patch ExpiredBanner.tsx: filter event rows in dataset fallback ───────── print("\n=== Patching ExpiredBanner.tsx (dataset fallback filter) ===") EXPIRED_BANNER = "/source/frontend/src/components/Chat/ExpiredBanner.tsx" def _patch_expired_banner(content): changed = False if PATCHED_MARKER in content: print(" SKIP: already patched") return content, False # Check if the dataset fallback is present (from patch_catch_up_dataset_fallback.py) if "/api/session-history/" not in content: print(" SKIP: no dataset fallback found in ExpiredBanner.tsx") return content, False # Patch the dataset fallback mapping to filter event rows old_mapping = ( " messages = history.map((row: any) => ({\n" " role: row.role || 'assistant',\n" " content: row.content || '',\n" " }));" ) new_mapping = ( " // === PATCH: catch-up fix (frontend) ===\n" " // Filter out 'event' rows — they are internal tracing\n" " // data that cannot be parsed as Message objects\n" " const validRoles = new Set(['user', 'assistant', 'tool']);\n" " messages = history\n" " .filter((row: any) => validRoles.has(row.role))\n" " .map((row: any) => ({\n" " role: row.role,\n" " content: row.content || '',\n" " }));" ) content, ok = _safe_replace(content, old_mapping, new_mapping) if ok: print(" + Filtered event rows in dataset fallback") changed = True else: print(" INFO: dataset fallback mapping pattern not found") if changed: content = content.replace( "import { logger } from '@/utils/logger';", "import { logger } from '@/utils/logger';\n// " + PATCHED_MARKER + " applied", 1 ) return content, changed patch_file(EXPIRED_BANNER, _patch_expired_banner) print("\n=== Frontend catch-up fixes applied ===")