File size: 11,472 Bytes
a98a5c3
 
 
 
 
8eeaea7
 
 
 
a98a5c3
8eeaea7
 
a98a5c3
 
 
 
 
 
 
 
 
 
 
 
8eeaea7
 
 
 
 
 
 
 
 
 
 
 
a98a5c3
 
 
 
 
 
 
8eeaea7
a98a5c3
 
 
 
 
8eeaea7
 
 
 
 
 
 
 
a98a5c3
 
 
 
 
 
 
 
8eeaea7
a98a5c3
 
 
 
 
 
 
 
 
 
 
8eeaea7
 
 
a98a5c3
8eeaea7
a98a5c3
 
8eeaea7
a98a5c3
 
8eeaea7
a98a5c3
8eeaea7
 
 
 
 
a98a5c3
8eeaea7
 
 
a98a5c3
 
8eeaea7
a98a5c3
 
8eeaea7
a98a5c3
8eeaea7
a98a5c3
8eeaea7
 
 
 
 
 
 
 
 
 
 
 
 
a98a5c3
8eeaea7
 
 
 
 
 
 
 
 
 
 
 
 
a98a5c3
8eeaea7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a98a5c3
8eeaea7
 
 
 
 
 
 
 
 
 
 
 
a98a5c3
8eeaea7
 
 
 
 
 
 
a98a5c3
8eeaea7
 
 
 
a98a5c3
8eeaea7
 
 
 
 
a98a5c3
 
8eeaea7
 
 
 
 
 
a98a5c3
 
8eeaea7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a98a5c3
 
 
8eeaea7
a98a5c3
 
 
 
 
 
 
 
 
 
 
 
 
8eeaea7
a98a5c3
 
 
 
 
 
8eeaea7
 
 
 
a98a5c3
 
 
8eeaea7
 
 
 
 
 
 
 
 
 
a98a5c3
 
 
 
 
 
 
8eeaea7
a98a5c3
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/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 ===")