bep40 commited on
Commit
b5a8153
Β·
verified Β·
1 Parent(s): 295b8d6

Upload patch_catch_up_fix_v3.py

Browse files
Files changed (1) hide show
  1. patch_catch_up_fix_v3.py +252 -14
patch_catch_up_fix_v3.py CHANGED
@@ -27,14 +27,18 @@ v3 fixes (runs AFTER all other patches, idempotent):
27
  chat.sendMessage (kills TS7006).
28
  2. AppLayout.tsx
29
  a. Render the missing Share button in the header (kills TS6133 for
30
- ShareIcon) β€” copy current URL (incl. ?chat=<sessionId>).
31
- 3. session_logger.py (backend)
32
- a. Fix v2's indent bug (insert filter correctly so no SyntaxError):
33
- event rows are filtered at source in load_session_history.
34
- 4. Defensive: remove any leftover unused-var traps by checking comments.
35
-
36
- Never fails the build (all writes are guarded by ast.parse / marker checks,
37
- and the Dockerfile already appends `|| true`).
 
 
 
 
38
  """
39
 
40
  import ast
@@ -216,12 +220,28 @@ def patch_use_agent_chat(content, _path):
216
 
217
 
218
  def patch_app_layout(content, _path):
219
- """Render the Share button (kills TS6133 for ShareIcon import)."""
220
  changed = False
221
  if MARKER3 in content:
222
  print(" SKIP: already patched")
223
  return content, False
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  old_theme_btn = (
226
  " <IconButton\n"
227
  " onClick={toggleTheme}\n"
@@ -247,12 +267,17 @@ def patch_app_layout(content, _path):
247
  " </IconButton>\n"
248
  "\n"
249
  " {activeSessionId && (\n"
250
- " <Tooltip title=\"Share this chat\">\n"
251
  " <IconButton\n"
252
  " size=\"small\"\n"
253
  " onClick={(e: React.MouseEvent) => {\n"
254
  " e.stopPropagation();\n"
255
- " const url = window.location.href;\n"
 
 
 
 
 
256
  " if (navigator.clipboard?.writeText) {\n"
257
  " navigator.clipboard.writeText(url).catch(() => {\n"
258
  " prompt('Copy this link:', url);\n"
@@ -274,7 +299,7 @@ def patch_app_layout(content, _path):
274
  content, ok = _replace(content, old_theme_btn, new_theme_btn)
275
  if ok:
276
  changed = True
277
- print(" + Added Share button before theme toggle (kills TS6133)")
278
  else:
279
  print(" INFO: theme toggle pattern not found (may already be v3)")
280
 
@@ -295,9 +320,161 @@ def patch_app_layout(content, _path):
295
  else:
296
  print(" INFO: could not add Tooltip import (Avatar import not found)")
297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  return content, changed
299
 
300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  def patch_session_sidebar(content, _path):
302
  changed = False
303
  if MARKER3 in content:
@@ -319,11 +496,56 @@ def patch_welcome_screen(content, _path):
319
  return content, changed
320
 
321
 
322
- # ─── Backend session_logger.py ──────────────────────────────────────────────
323
 
 
324
  BACKEND_SESSION_LOGGER = "/app/backend/session_logger.py"
325
 
326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  def patch_session_logger(content):
328
  """Fix v2's broken insertion that caused a SyntaxError.
329
 
@@ -400,8 +622,9 @@ patch_frontend_file(
400
  patch_frontend_file(
401
  "components/Layout/AppLayout.tsx",
402
  patch_app_layout,
403
- "share button + Tooltip import",
404
  )
 
405
  patch_frontend_file(
406
  "components/SessionSidebar/SessionSidebar.tsx",
407
  patch_session_sidebar,
@@ -419,6 +642,21 @@ patch_frontend_file(
419
  )
420
 
421
  print("\n=== v3: Backend ===")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
  if os.path.exists(BACKEND_SESSION_LOGGER):
423
  content = _read(BACKEND_SESSION_LOGGER)
424
  content, changed = patch_session_logger(content)
 
27
  chat.sendMessage (kills TS7006).
28
  2. AppLayout.tsx
29
  a. Render the missing Share button in the header (kills TS6133 for
30
+ ShareIcon). The button copies a PUBLIC share URL (?share=<id>).
31
+ b. If the URL has ?share=<sessionId>, render a read-only ShareView
32
+ instead of the chat (auth-free, works for anyone with the link).
33
+ 3. ShareView.tsx (new file): read-only transcript viewer.
34
+ 4. Backend routes/agent.py: add public GET /api/public/session/{id}
35
+ (no auth) that serves sanitized conversation rows from the permanent
36
+ public sessions dataset.
37
+ 5. Backend session_logger.py: fix v2's indent bug (insert filter
38
+ correctly so no SyntaxError) β€” event rows filtered at source.
39
+
40
+ Never fails the build (all writes guarded by markers / ast.parse, and the
41
+ Dockerfile already appends `|| true`).
42
  """
43
 
44
  import ast
 
220
 
221
 
222
  def patch_app_layout(content, _path):
223
+ """Share button (public ?share= URL) + read-only ShareView mode."""
224
  changed = False
225
  if MARKER3 in content:
226
  print(" SKIP: already patched")
227
  return content, False
228
 
229
+ # (2a) Import ShareView (new component in the same folder).
230
+ if "import ShareView" not in content:
231
+ anchor = "import ShareIcon from '@mui/icons-material/Share';"
232
+ if anchor in content:
233
+ content = content.replace(
234
+ anchor,
235
+ anchor + "\nimport ShareView from '@/components/ShareView';\n" + MARKER3,
236
+ 1,
237
+ )
238
+ changed = True
239
+ print(" + Imported ShareView")
240
+ else:
241
+ print(" INFO: ShareIcon import not found for ShareView import")
242
+
243
+ # (2b) Share button before theme toggle. Builds a PUBLIC share URL
244
+ # (?share=<sessionId>) instead of the owner-only ?chat= URL.
245
  old_theme_btn = (
246
  " <IconButton\n"
247
  " onClick={toggleTheme}\n"
 
267
  " </IconButton>\n"
268
  "\n"
269
  " {activeSessionId && (\n"
270
+ " <Tooltip title=\"Copy public share link\">\n"
271
  " <IconButton\n"
272
  " size=\"small\"\n"
273
  " onClick={(e: React.MouseEvent) => {\n"
274
  " e.stopPropagation();\n"
275
+ " const _p = new URLSearchParams(window.location.search);\n"
276
+ " const _sid = _p.get('chat') || activeSessionId || '';\n"
277
+ " const _sp = new URLSearchParams();\n"
278
+ " if (_sid) _sp.set('share', _sid);\n"
279
+ " const _qs = _sp.toString();\n"
280
+ " const url = `${window.location.origin}${window.location.pathname}${_qs ? `?${_qs}` : ''}`;\n"
281
  " if (navigator.clipboard?.writeText) {\n"
282
  " navigator.clipboard.writeText(url).catch(() => {\n"
283
  " prompt('Copy this link:', url);\n"
 
299
  content, ok = _replace(content, old_theme_btn, new_theme_btn)
300
  if ok:
301
  changed = True
302
+ print(" + Added Share button before theme toggle (public ?share= URL)")
303
  else:
304
  print(" INFO: theme toggle pattern not found (may already be v3)")
305
 
 
320
  else:
321
  print(" INFO: could not add Tooltip import (Avatar import not found)")
322
 
323
+ # (2c) Read-only share mode: if ?share=<id> is present, render ShareView.
324
+ # Must come AFTER all hooks (it is β€” right before the WelcomeScreen return).
325
+ old_welcome = " // -- Welcome screen: no sessions at all ---------------------------------\n"
326
+ new_welcome = (
327
+ " // === PATCH: catch-up-v3 ===\n"
328
+ " // Public read-only share mode (?share=<sessionId>). Works without\n"
329
+ " // login for anyone who has the link; data comes from the public\n"
330
+ " // sessions dataset via GET /api/public/session/{id}.\n"
331
+ " const _shareParam = new URLSearchParams(window.location.search).get('share');\n"
332
+ " if (_shareParam) {\n"
333
+ " return <ShareView sessionId={_shareParam} />;\n"
334
+ " }\n"
335
+ "\n"
336
+ " // -- Welcome screen: no sessions at all ---------------------------------\n"
337
+ )
338
+ content, ok = _replace(content, old_welcome, new_welcome)
339
+ if ok:
340
+ changed = True
341
+ print(" + ?share= renders read-only ShareView")
342
+ else:
343
+ print(" INFO: welcome-screen anchor not found for share mode")
344
+
345
  return content, changed
346
 
347
 
348
+ def patch_share_view(path):
349
+ """Create the read-only ShareView component (new file)."""
350
+ if os.path.exists(path):
351
+ print(" SKIP: ShareView.tsx already exists")
352
+ return
353
+ content = (
354
+ "/**\n"
355
+ " * Read-only public session viewer (no auth required).\n"
356
+ " *\n"
357
+ " * Rendered by AppLayout when the URL contains ?share=<sessionId>.\n"
358
+ " * Fetches sanitized conversation rows from the public endpoint\n"
359
+ " * GET /api/public/session/{id}, which reads the permanent public\n"
360
+ " * sessions dataset. Anyone with the link can view the transcript.\n"
361
+ " */\n"
362
+ "// === PATCH: catch-up-v3 ===\n"
363
+ "import { useEffect, useState } from 'react';\n"
364
+ "import {\n"
365
+ " Alert,\n"
366
+ " Box,\n"
367
+ " Button,\n"
368
+ " CircularProgress,\n"
369
+ " Paper,\n"
370
+ " Typography,\n"
371
+ "} from '@mui/material';\n"
372
+ "\n"
373
+ "interface ShareRow {\n"
374
+ " role: string;\n"
375
+ " content: string;\n"
376
+ " timestamp?: string;\n"
377
+ "}\n"
378
+ "\n"
379
+ "interface ShareViewProps {\n"
380
+ " sessionId: string;\n"
381
+ "}\n"
382
+ "\n"
383
+ "export default function ShareView({ sessionId }: ShareViewProps) {\n"
384
+ " const [rows, setRows] = useState<ShareRow[]>([]);\n"
385
+ " const [loading, setLoading] = useState(true);\n"
386
+ " const [error, setError] = useState<string | null>(null);\n"
387
+ "\n"
388
+ " useEffect(() => {\n"
389
+ " let cancelled = false;\n"
390
+ " (async () => {\n"
391
+ " try {\n"
392
+ " const res = await fetch(\n"
393
+ " `/api/public/session/${encodeURIComponent(sessionId)}`,\n"
394
+ " { credentials: 'include' },\n"
395
+ " );\n"
396
+ " if (res.status === 404) {\n"
397
+ " if (!cancelled) setError('Session not found.');\n"
398
+ " } else if (!res.ok) {\n"
399
+ " if (!cancelled) setError('Failed to load this session.');\n"
400
+ " } else {\n"
401
+ " const data = await res.json();\n"
402
+ " if (!cancelled && Array.isArray(data)) setRows(data);\n"
403
+ " }\n"
404
+ " } catch {\n"
405
+ " if (!cancelled) setError('Network error while loading this session.');\n"
406
+ " } finally {\n"
407
+ " if (!cancelled) setLoading(false);\n"
408
+ " }\n"
409
+ " })();\n"
410
+ " return () => {\n"
411
+ " cancelled = true;\n"
412
+ " };\n"
413
+ " }, [sessionId]);\n"
414
+ "\n"
415
+ " return (\n"
416
+ " <Box\n"
417
+ " sx={{\n"
418
+ " minHeight: '100vh',\n"
419
+ " bgcolor: 'var(--body-gradient)' as string,\n"
420
+ " py: 4,\n"
421
+ " px: { xs: 2, md: 6 },\n"
422
+ " }}\n"
423
+ " >\n"
424
+ " <Box sx={{ maxWidth: 860, mx: 'auto' }}>\n"
425
+ " <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 2 }}>\n"
426
+ " <Typography variant=\"h6\" sx={{ fontSize: '1rem', fontWeight: 700 }}>\n"
427
+ " Shared session\n"
428
+ " </Typography>\n"
429
+ " <Button component=\"a\" href=\"/\" size=\"small\" sx={{ textTransform: 'none', ml: 'auto' }}>\n"
430
+ " Open ML Intern\n"
431
+ " </Button>\n"
432
+ " </Box>\n"
433
+ "\n"
434
+ " {loading && <CircularProgress size={20} />}\n"
435
+ " {error && (\n"
436
+ " <Alert severity=\"warning\" variant=\"outlined\">\n"
437
+ " {error}\n"
438
+ " </Alert>\n"
439
+ " )}\n"
440
+ " {!loading && !error && rows.length === 0 && (\n"
441
+ " <Typography color=\"text.secondary\" variant=\"body2\">\n"
442
+ " No messages in this session.\n"
443
+ " </Typography>\n"
444
+ " )}\n"
445
+ " {rows.map((row, i) => (\n"
446
+ " <Paper\n"
447
+ " key={i}\n"
448
+ " sx={{\n"
449
+ " mb: 1,\n"
450
+ " p: 1.5,\n"
451
+ " bgcolor: row.role === 'user' ? 'var(--hover-bg)' : 'var(--panel)',\n"
452
+ " borderRadius: 2,\n"
453
+ " }}\n"
454
+ " >\n"
455
+ " <Typography\n"
456
+ " variant=\"caption\"\n"
457
+ " sx={{ color: 'var(--muted-text)', fontWeight: 700, textTransform: 'uppercase' }}\n"
458
+ " >\n"
459
+ " {row.role}\n"
460
+ " </Typography>\n"
461
+ " <Typography\n"
462
+ " variant=\"body2\"\n"
463
+ " sx={{ whiteSpace: 'pre-wrap', mt: 0.5, wordBreak: 'break-word' }}\n"
464
+ " >\n"
465
+ " {row.content}\n"
466
+ " </Typography>\n"
467
+ " </Paper>\n"
468
+ " ))}\n"
469
+ " </Box>\n"
470
+ " </Box>\n"
471
+ " );\n"
472
+ "}\n"
473
+ )
474
+ _write(path, content)
475
+ print(" + Created ShareView.tsx")
476
+
477
+
478
  def patch_session_sidebar(content, _path):
479
  changed = False
480
  if MARKER3 in content:
 
496
  return content, changed
497
 
498
 
499
+ # ─── Backend routes/agent.py: public share endpoint ───────────────────────
500
 
501
+ BACKEND_ROUTES_AGENT = "/app/backend/routes/agent.py"
502
  BACKEND_SESSION_LOGGER = "/app/backend/session_logger.py"
503
 
504
 
505
+ def patch_routes_agent(content):
506
+ """Add public GET /api/public/session/{id} (no auth)."""
507
+ changed = False
508
+ if "public/session/" in content:
509
+ print(" SKIP: public endpoint already present")
510
+ return content, False
511
+
512
+ endpoint = '''
513
+
514
+ @router.get("/public/session/{session_id}")
515
+ async def public_session_transcript(session_id: str) -> list[dict]:
516
+ """Public read-only transcript for a session (no auth required).
517
+
518
+ Reads sanitized conversation rows from the permanent public sessions
519
+ dataset (bep40/ml-intern-sessions). Returns only user/assistant/tool
520
+ messages β€” never internal event/system rows. Useful for sharing a
521
+ session transcript with anyone via a link.
522
+ """
523
+ from backend.session_logger import load_session_history
524
+
525
+ rows = load_session_history(session_id)
526
+ valid_roles = {"user", "assistant", "tool"}
527
+ messages = [r for r in rows if r.get("role") in valid_roles]
528
+ # Cap payload size: last 300 messages, each content truncated to 20k chars.
529
+ truncated = []
530
+ for r in messages[-300:]:
531
+ content = r.get("content") or ""
532
+ if isinstance(content, str) and len(content) > 20000:
533
+ content = content[:20000] + "\\n...[truncated]"
534
+ truncated.append(
535
+ {
536
+ "role": r.get("role", "assistant"),
537
+ "content": content,
538
+ "timestamp": r.get("timestamp"),
539
+ }
540
+ )
541
+ return truncated
542
+ '''
543
+ content = content.rstrip() + "\n" + endpoint
544
+ print(" + Added public /api/public/session/{id} endpoint")
545
+ changed = True
546
+ return content, changed
547
+
548
+
549
  def patch_session_logger(content):
550
  """Fix v2's broken insertion that caused a SyntaxError.
551
 
 
622
  patch_frontend_file(
623
  "components/Layout/AppLayout.tsx",
624
  patch_app_layout,
625
+ "share button + share mode",
626
  )
627
+ patch_share_view(os.path.join(FRONTEND_DIR, "components/ShareView.tsx"))
628
  patch_frontend_file(
629
  "components/SessionSidebar/SessionSidebar.tsx",
630
  patch_session_sidebar,
 
642
  )
643
 
644
  print("\n=== v3: Backend ===")
645
+ if os.path.exists(BACKEND_ROUTES_AGENT):
646
+ content = _read(BACKEND_ROUTES_AGENT)
647
+ content, changed = patch_routes_agent(content)
648
+ if changed:
649
+ try:
650
+ ast.parse(content)
651
+ _write(BACKEND_ROUTES_AGENT, content)
652
+ print("OK: routes/agent.py patched")
653
+ except SyntaxError as e:
654
+ print(f"FAIL: routes/agent.py syntax: {e}")
655
+ else:
656
+ print("SKIP: routes/agent.py β€” no changes needed")
657
+ else:
658
+ print("SKIP: routes/agent.py not found")
659
+
660
  if os.path.exists(BACKEND_SESSION_LOGGER):
661
  content = _read(BACKEND_SESSION_LOGGER)
662
  content, changed = patch_session_logger(content)