File size: 3,682 Bytes
dc7c214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Patch frontend: Add dataset fallback to ExpiredBanner handleCatchUp.

When localStorage caches (backend-messages, ui-messages) are empty
(user cleared cache, new browser, Space restarted), the catch-up flow
shows "Nothing to summarize from this chat.". This patch adds a fallback
that fetches messages from /api/session-history/{session_id} — which reads
from the permanent HF dataset (bep40/ml-intern-sessions).

This ensures the "Catch me up" button always works as long as the
session was previously logged to the permanent dataset.
"""

import os
import sys

PATCHED_MARKER = "// === PATCH: catch-up dataset fallback ==="
TARGET_FILE = "/source/frontend/src/components/Chat/ExpiredBanner.tsx"


def patch_expired_banner(content: str) -> tuple[str, bool]:
    changed = False

    if PATCHED_MARKER in content:
        print(f"  SKIP: already patched")
        return content, False

    # Add a fallback to /api/session-history/{session_id} before the error.
    # The old block checks if messages array is empty and bails with error.
    old_block = (
        "      if (!messages || messages.length === 0) {\n"
        "        setError('Nothing to summarize from this chat.');\n"
        "        setBusy(null);\n"
        "        return;\n"
        "      }\n"
    )
    new_block = (
        PATCHED_MARKER + "\n"
        "      // Fallback: when localStorage caches are empty (Space restart,\n"
        "      // new browser, cache cleared), read from the permanent HF dataset\n"
        "      // via /api/session-history/{session_id}.\n"
        "      if (!messages || messages.length === 0) {\n"
        "        try {\n"
        "          const res = await apiFetch(`/api/session-history/${sessionId}`);\n"
        "          if (res.ok) {\n"
        "            const history = await res.json();\n"
        "            if (Array.isArray(history) && history.length > 0) {\n"
        "              messages = history.map((row: any) => ({\n"
        "                role: row.role || 'assistant',\n"
        "                content: row.content || '',\n"
        "              }));\n"
        "            }\n"
        "          }\n"
        "        } catch {\n"
        "          /* dataset fetch failed — continue to error below */\n"
        "        }\n"
        "      }\n"
        "      if (!messages || messages.length === 0) {\n"
        "        setError('Nothing to summarize from this chat.');\n"
        "        setBusy(null);\n"
        "        return;\n"
        "      }\n"
    )
    if old_block in content:
        content = content.replace(old_block, new_block, 1)
        changed = True
        print("  + Added dataset fallback to handleCatchUp")
    else:
        print("  SKIP: target block not found (pattern may have changed)")

    return content, changed


def main():
    if not os.path.exists(TARGET_FILE):
        print(f"SKIP: {TARGET_FILE} not found — frontend source not available")
        return

    with open(TARGET_FILE, "r", encoding="utf-8") as f:
        content = f.read()

    if PATCHED_MARKER in content:
        print(f"SKIP: {TARGET_FILE} already patched")
        return

    content, changed = patch_expired_banner(content)
    if changed:
        with open(TARGET_FILE, "w", encoding="utf-8") as f:
            f.write(content)
        print(f"OK: {TARGET_FILE} patched with dataset fallback")
    else:
        print(f"SKIP: {TARGET_FILE} — no changes applied")


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"WARN: patch_catch_up_dataset_fallback.py error: {e}")
        # Never fail the Docker build
        sys.exit(0)