bep40 commited on
Commit
dfd5cb8
·
verified ·
1 Parent(s): 80d646f

Add patch: Restore from dataset button (backend endpoint + frontend button)

Browse files
Files changed (1) hide show
  1. patch_restore_from_dataset.py +315 -0
patch_restore_from_dataset.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Patch: Add "Restore from dataset" button to the expired-session banner.
4
+
5
+ Adds a one-click way to recover a dead session from the permanent HF
6
+ dataset with its FULL conversation, instead of only a lossy summary.
7
+
8
+ Backend:
9
+ - session_manager.seed_from_dataset(session_id): load full history from
10
+ the permanent dataset (backend.session_logger.load_session_history) and
11
+ seed the session's context manager with every valid message. Returns the
12
+ number of messages seeded (0 if the dataset has nothing).
13
+ - routes/agent.py: POST /api/session/restore-from-dataset — creates a new
14
+ session, seeds it from the dataset, returns the new session_id.
15
+
16
+ Frontend:
17
+ - ExpiredBanner.tsx: adds a "Restore from dataset" button that calls the
18
+ new endpoint and renames the session (same flow as Catch me up).
19
+
20
+ Runs during Docker build; never fails the build.
21
+ """
22
+
23
+ import ast
24
+ import os
25
+
26
+ PATCHED_MARKER = "# === PATCH: restore-from-dataset ==="
27
+
28
+
29
+ def _read(path):
30
+ with open(path, encoding="utf-8") as f:
31
+ return f.read()
32
+
33
+
34
+ def _write(path, content):
35
+ with open(path, "w", encoding="utf-8") as f:
36
+ f.write(content)
37
+
38
+
39
+ def _replace(content, old, new):
40
+ if old in content:
41
+ return content.replace(old, new, 1), True
42
+ return content, False
43
+
44
+
45
+ # ---- Backend: session_manager.seed_from_dataset -------------------------
46
+ SM = "/app/backend/session_manager.py"
47
+ if os.path.exists(SM):
48
+ content = _read(SM)
49
+ changed = False
50
+ if PATCHED_MARKER in content:
51
+ print("SKIP: session_manager.py already patched")
52
+ else:
53
+ anchor = " async def record_catchup_done(self, session_id: str) -> None:"
54
+ if anchor in content:
55
+ new_method = (
56
+ " # === PATCH: restore-from-dataset ===\n"
57
+ " async def seed_from_dataset(self, session_id: str) -> int:\n"
58
+ " \"\"\"Rehydrate a session from the permanent HF dataset.\n"
59
+ "\n"
60
+ " Loads the FULL conversation history for ``session_id`` from\n"
61
+ " the permanent sessions dataset and seeds the new session's\n"
62
+ " context manager with every valid message, so the model\n"
63
+ " genuinely remembers the prior conversation (lossless).\n"
64
+ "\n"
65
+ " Returns the number of messages seeded (0 if none found).\n"
66
+ " \"\"\"\n"
67
+ " from litellm import Message\n"
68
+ " from backend.session_logger import load_session_history\n"
69
+ "\n"
70
+ " agent_session = self.sessions.get(session_id)\n"
71
+ " if not agent_session:\n"
72
+ " raise ValueError(f\"Session {session_id} not found\")\n"
73
+ "\n"
74
+ " try:\n"
75
+ " ds_rows = load_session_history(session_id)\n"
76
+ " except Exception as e:\n"
77
+ " logger.error(\"load_session_history failed for %s: %s\", session_id, e)\n"
78
+ " ds_rows = []\n"
79
+ "\n"
80
+ " full_msgs = [\n"
81
+ " r for r in ds_rows\n"
82
+ " if r.get(\"role\") in (\"user\", \"assistant\", \"tool\")\n"
83
+ " ]\n"
84
+ " if not full_msgs:\n"
85
+ " logger.info(\"No dataset messages for session %s\", session_id)\n"
86
+ " return 0\n"
87
+ "\n"
88
+ " session = agent_session.session\n"
89
+ " seeded = 0\n"
90
+ " for raw in full_msgs:\n"
91
+ " try:\n"
92
+ " session.context_manager.items.append(Message.model_validate(raw))\n"
93
+ " seeded += 1\n"
94
+ " except Exception as e:\n"
95
+ " logger.warning(\"Dropping dataset msg during seed: %s\", e)\n"
96
+ "\n"
97
+ " self._touch(agent_session)\n"
98
+ " await self.persist_session_snapshot(agent_session, runtime_state=\"idle\")\n"
99
+ " try:\n"
100
+ " await self.record_catchup_done(session_id)\n"
101
+ " except Exception:\n"
102
+ " pass\n"
103
+ " return seeded\n"
104
+ "\n"
105
+ " async def record_catchup_done(self, session_id: str) -> None:"
106
+ )
107
+ content, ok = _replace(content, anchor, new_method)
108
+ if ok:
109
+ print("+ session_manager.seed_from_dataset added")
110
+ changed = True
111
+ else:
112
+ print("INFO: record_catchup_done anchor not found")
113
+ if changed:
114
+ try:
115
+ ast.parse(content)
116
+ _write(SM, content)
117
+ print("OK: session_manager.py patched (seed_from_dataset)")
118
+ except SyntaxError as e:
119
+ print("FAIL: session_manager.py syntax", e)
120
+
121
+ # ---- Backend: routes/agent.py endpoint ------------------------------------
122
+ RA = "/app/backend/routes/agent.py"
123
+ if os.path.exists(RA):
124
+ content = _read(RA)
125
+ changed = False
126
+ if PATCHED_MARKER in content:
127
+ print("SKIP: routes/agent.py already patched")
128
+ else:
129
+ anchor_start = (
130
+ " logger.info(\n"
131
+ ' f"Seeded session {session_id} for {user.get(\'username\', \'unknown\')} "\n'
132
+ ' f"(summary of {summarized} messages)"\n'
133
+ " )\n"
134
+ " return SessionResponse(\n"
135
+ " session_id=session_id,\n"
136
+ " ready=True,\n"
137
+ " model=model,\n"
138
+ " )\n"
139
+ )
140
+ endpoint = (
141
+ "\n\n@router.post(\"/session/restore-from-dataset\", response_model=SessionResponse)\n"
142
+ "async def restore_session_from_dataset(\n"
143
+ " request: Request, body: dict, user: dict = Depends(get_current_user)\n"
144
+ ") -> SessionResponse:\n"
145
+ " \"\"\"Create a new session seeded with the FULL conversation history read\n"
146
+ " from the permanent HF dataset for the given ``session_id``.\n"
147
+ "\n"
148
+ " Unlike restore-summary, this does not run an LLM summarization — it\n"
149
+ " loads the actual stored messages, so the model genuinely remembers the\n"
150
+ " prior conversation. Body: {\"session_id\": \"...\"}.\n"
151
+ " \"\"\"\n"
152
+ " old_id = body.get(\"session_id\")\n"
153
+ " if not old_id or not isinstance(old_id, str):\n"
154
+ " raise HTTPException(status_code=400, detail=\"Missing 'session_id' string\")\n"
155
+ "\n"
156
+ " hf_token = resolve_hf_request_token(request)\n"
157
+ " model = body.get(\"model\")\n"
158
+ " _validate_model_id(model)\n"
159
+ " model = _model_override_for_new_session(model)\n"
160
+ "\n"
161
+ " try:\n"
162
+ " session_id = await session_manager.create_session(\n"
163
+ " user_id=user[\"user_id\"],\n"
164
+ " hf_username=user.get(\"username\"),\n"
165
+ " hf_token=hf_token,\n"
166
+ " user_plan=user.get(\"plan\"),\n"
167
+ " model=model,\n"
168
+ " is_pro=user.get(\"plan\") == \"pro\",\n"
169
+ " )\n"
170
+ " except SessionCapacityError as e:\n"
171
+ " raise HTTPException(status_code=503, detail=str(e))\n"
172
+ "\n"
173
+ " await _reset_usage_window(session_id)\n"
174
+ " await _check_session_access(\n"
175
+ " session_id,\n"
176
+ " user,\n"
177
+ " request,\n"
178
+ " preload_sandbox=False,\n"
179
+ " )\n"
180
+ " try:\n"
181
+ " seeded = await session_manager.seed_from_dataset(session_id)\n"
182
+ " except Exception as e:\n"
183
+ " logger.exception(\"seed_from_dataset failed\")\n"
184
+ " raise HTTPException(status_code=500, detail=f\"Restore failed: {e}\")\n"
185
+ "\n"
186
+ " logger.info(\n"
187
+ " f\"Restored session {session_id} from dataset for \"\n"
188
+ " f\"{user.get('username', 'unknown')} ({seeded} messages)\"\n"
189
+ " )\n"
190
+ " return SessionResponse(\n"
191
+ " session_id=session_id,\n"
192
+ " ready=True,\n"
193
+ " model=model,\n"
194
+ " )\n"
195
+ )
196
+ if anchor_start in content:
197
+ content = content.replace(anchor_start, anchor_start + endpoint, 1)
198
+ print("+ POST /session/restore-from-dataset endpoint added")
199
+ changed = True
200
+ else:
201
+ print("INFO: exact anchor not found, trying loose anchor")
202
+ loose = " return SessionResponse(\n session_id=session_id,\n ready=True,\n model=model,\n )\n"
203
+ if loose in content:
204
+ idx_last = content.rfind(loose)
205
+ content = content[: idx_last + len(loose)] + endpoint + content[idx_last + len(loose):]
206
+ print("+ endpoint inserted after last SessionResponse return")
207
+ changed = True
208
+ if changed:
209
+ try:
210
+ ast.parse(content)
211
+ _write(RA, content)
212
+ print("OK: routes/agent.py patched (restore-from-dataset)")
213
+ except SyntaxError as e:
214
+ print("FAIL: routes/agent.py syntax", e)
215
+
216
+ # ---- Frontend: ExpiredBanner.tsx button ------------------------------------
217
+ EB = "/source/frontend/src/components/Chat/ExpiredBanner.tsx"
218
+ if os.path.exists(EB):
219
+ content = _read(EB)
220
+ changed = False
221
+ if PATCHED_MARKER in content:
222
+ print("SKIP: ExpiredBanner.tsx already patched")
223
+ else:
224
+ # 1. busy union type
225
+ old_busy = " const [busy, setBusy] = useState<'catch-up' | 'start-over' | null>(null);"
226
+ new_busy = " const [busy, setBusy] = useState<'catch-up' | 'restore-dataset' | 'start-over' | null>(null);"
227
+ content, ok = _replace(content, old_busy, new_busy)
228
+ if ok:
229
+ print("+ busy type widened")
230
+ changed = True
231
+
232
+ # 2. handleRestoreFromDataset callback before handleStartOver
233
+ anchor2 = " const handleStartOver = useCallback(() => {"
234
+ if anchor2 in content:
235
+ cb = (
236
+ " // === PATCH: restore-from-dataset ===\n"
237
+ " const handleRestoreFromDataset = useCallback(async () => {\n"
238
+ " setBusy('restore-dataset');\n"
239
+ " setError(null);\n"
240
+ " try {\n"
241
+ " const res = await apiFetch('/api/session/restore-from-dataset', {\n"
242
+ " method: 'POST',\n"
243
+ " body: JSON.stringify({ session_id: sessionId }),\n"
244
+ " });\n"
245
+ " if (!res.ok) throw new Error(`restore-from-dataset failed: ${res.status}`);\n"
246
+ " const data = await res.json();\n"
247
+ " const newId = data.session_id as string | undefined;\n"
248
+ " if (!newId) throw new Error('no session_id in response');\n"
249
+ "\n"
250
+ " useAgentStore.getState().clearSessionState(sessionId);\n"
251
+ " renameSession(sessionId, newId);\n"
252
+ " if (data.model) updateSessionModel(newId, data.model);\n"
253
+ " // Same catchup-done bookkeeping as Catch me up.\n"
254
+ " try {\n"
255
+ " localStorage.setItem(`ml-intern-catchup-done:${newId}`, 'true');\n"
256
+ " } catch {}\n"
257
+ " try { await apiFetch(`/api/session/${newId}/catchup-done`, { method: 'POST' }); } catch {}\n"
258
+ " } catch (e) {\n"
259
+ " logger.warn('Restore-from-dataset failed:', e);\n"
260
+ " setError(\"Couldn't restore from dataset — try Catch me up or start over.\");\n"
261
+ " setBusy(null);\n"
262
+ " }\n"
263
+ " }, [sessionId, renameSession, updateSessionModel]);\n"
264
+ "\n"
265
+ " const handleStartOver = useCallback(() => {"
266
+ )
267
+ content, ok = _replace(content, anchor2, cb)
268
+ if ok:
269
+ print("+ handleRestoreFromDataset callback added")
270
+ changed = True
271
+
272
+ # 3. Button before Start fresh
273
+ anchor3 = (
274
+ " <Button\n"
275
+ " variant=\"outlined\"\n"
276
+ " onClick={handleStartOver}"
277
+ )
278
+ if anchor3 in content:
279
+ btn = (
280
+ " <Button\n"
281
+ " variant=\"outlined\"\n"
282
+ " onClick={handleRestoreFromDataset}\n"
283
+ " disabled={busy !== null}\n"
284
+ " startIcon={busy === 'restore-dataset' ? <CircularProgress size={16} color=\"inherit\" /> : null}\n"
285
+ " sx={{ textTransform: 'none' }}\n"
286
+ " >\n"
287
+ " {busy === 'restore-dataset' ? 'Restoring…' : 'Restore from dataset'}\n"
288
+ " </Button>\n"
289
+ " <Button\n"
290
+ " variant=\"outlined\"\n"
291
+ " onClick={handleStartOver}"
292
+ )
293
+ content, ok = _replace(content, anchor3, btn)
294
+ if ok:
295
+ print("+ Restore-from-dataset button added")
296
+ changed = True
297
+
298
+ if changed:
299
+ _write(EB, content)
300
+ print("OK: ExpiredBanner.tsx patched")
301
+ else:
302
+ print("SKIP: ExpiredBanner.tsx — no changes")
303
+
304
+ # ---- Verify ---------------------------------------------------------------
305
+ print("\n===== VERIFY =====")
306
+ for f in ["/app/backend/session_manager.py", "/app/backend/routes/agent.py"]:
307
+ if os.path.exists(f):
308
+ ast.parse(_read(f))
309
+ print("PY SYNTAX OK:", f)
310
+ print("routes has endpoint:", "restore-from-dataset" in _read(RA) if os.path.exists(RA) else False)
311
+ print("session_manager has seed_from_dataset:", "def seed_from_dataset" in _read(SM) if os.path.exists(SM) else False)
312
+ if os.path.exists(EB):
313
+ eb = _read(EB)
314
+ print("ExpiredBanner has button:", "Restore from dataset" in eb)
315
+ print("ExpiredBanner has callback:", "handleRestoreFromDataset" in eb)