Spaces:
Running
Running
Download patch_fix_approval_buttons.py from bep40/ml-intern: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/spaces/bep40/ml-intern/resolve/main/patch_fix_approval_buttons.py
- Command line
-
hf download hf://spaces/bep40/ml-intern/patch_fix_approval_buttons.py
-
curl -L -o patch_fix_approval_buttons.py https://huggingface.co/spaces/bep40/ml-intern/resolve/main/patch_fix_approval_buttons.py
17.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| Patch: Fix Approve/Reject buttons doing nothing when 'waiting approval' shows. | |
| Root causes (verified against the built fork): | |
| A) FRONTEND FREEZE (patch_catch_up_fix_v3.py + approval_required SSE handler) | |
| Once a session goes through catch-up, `_catchupDone` forces every | |
| hydration guard to `false`. A NEW approval round (fresh | |
| `approval_required` SSE) therefore never replaces the stale UI parts. | |
| The Approve/Reject buttons then target tool_call_ids the backend already | |
| resolved -> silent no-op, no error, nothing happens. | |
| The css CRITICAL site is the `approval_required` SSE branch in | |
| useAgentChat.ts where a SECOND `_shouldSetC` guard (16-space indent) | |
| sits directly under `sideChannel.onApprovalRequired(...)`. v0 of this | |
| patch only replaced the first (14-space) occurrence; this v2 replaces | |
| ALL occurrences of every guard so the approval branch is covered. | |
| B) BACKEND auto_approval SHAPE | |
| Upstream session.py already declares SCALAR attributes: | |
| session.auto_approval_enabled (default False) | |
| session.auto_approval_cost_cap_usd | |
| session.auto_approval_estimated_spend_usd | |
| patch_agent_backend.py's dict insertion is a no-op on modern upstream | |
| (substring `self.auto_approval` already matches the scalar attrs), so | |
| the scalar stays False on NEW sessions. We explicitly flip the __init__ | |
| default to True so free-model auto-approval actually engages. | |
| C) SILENCE | |
| When an approval arrives for a tool_call_id with no live pending | |
| approval, the backend just ignored it. We answer 409 with a clear | |
| message so the UI surfaces an error instead of appearing frozen. | |
| Fix (runs during Docker build, both stages; never fails the build): | |
| 1. session.py __init__: default auto_approval_enabled to True (with | |
| explicit override path preserved). | |
| 2. session_manager.py seed paths: set scalar + dict so restored sessions | |
| get a coherent policy. | |
| 3. routes/agent.py POST /api/chat/{session_id}: reject approvals whose | |
| ids have no live pending approval (loud 409 instead of silent no-op). | |
| 4. useAgentChat.ts: _hasPendingApproval() bypasses _catchupDone freeze | |
| at EVERY hydration guard (replace_all), so new approval rounds always | |
| reach the UI and stale buttons disappear. | |
| """ | |
| import ast | |
| import os | |
| MARKER = "# === PATCH: fix-approval-buttons ===" | |
| MARKER_TS = "// === PATCH: fix-approval-buttons ===" | |
| def _read(path): | |
| with open(path, encoding="utf-8") as f: | |
| return f.read() | |
| def _write(path, content): | |
| with open(path, "w", encoding="utf-8") as f: | |
| f.write(content) | |
| def _replace_all(content, old, new): | |
| if old in content: | |
| return content.replace(old, new), True | |
| return content, False | |
| def _patch_py(path, fn, label): | |
| if not os.path.exists(path): | |
| print(f"SKIP: {path} not found ({label})") | |
| return | |
| content = _read(path) | |
| if MARKER in content: | |
| print(f"SKIP: {path} already patched ({label})") | |
| return | |
| new_content, changed = fn(content, path) | |
| if not changed: | |
| print(f"SKIP: {path} - no changes needed ({label})") | |
| return | |
| try: | |
| ast.parse(new_content) | |
| except SyntaxError as e: | |
| print(f"FAIL: {path} syntax: {e} ({label})") | |
| return | |
| _write(path, new_content) | |
| print(f"OK: {path} patched ({label})") | |
| # -------------------------------------------------------------------------- | |
| # 1. agent/core/session.py - default scalar auto-approval to True | |
| # -------------------------------------------------------------------------- | |
| SESSION = "/app/agent/core/session.py" | |
| def _patch_session(content, _path): | |
| changed = False | |
| # 1a. Flip the __init__ default: upstream-shipped sessions default to | |
| # auto_approval_enabled=False (the fork wants free models to | |
| # auto-approve; config yolo_mode=True is legacy and does not flip | |
| # the session scalar). | |
| old_init = ( | |
| " self.auto_approval_enabled: bool = False\n" | |
| " self.auto_approval_cost_cap_usd: float | None = None\n" | |
| " self.auto_approval_estimated_spend_usd: float = 0.0\n" | |
| ) | |
| new_init = ( | |
| " # === PATCH: fix-approval-buttons ===\n" | |
| " # Free-model auto-approval must actually engage: the engine\n" | |
| " # reads these scalars (yolo_budget.py), not a dict.\n" | |
| " self.auto_approval_enabled: bool = True\n" | |
| " self.auto_approval_cost_cap_usd: float | None = None\n" | |
| " self.auto_approval_estimated_spend_usd: float = 0.0\n" | |
| " # === PATCH: fix-approval-buttons ===\n" | |
| ) | |
| content, ok = _replace_all(content, old_init, new_init) | |
| if ok: | |
| print(" + __init__ defaults auto_approval_enabled=True (session.py)") | |
| changed = True | |
| else: | |
| print(" INFO: __init__ scalar pattern not found (may differ in fork)") | |
| # 1b. ensure_auto_approval() one-liner -- also flip its scalar default. | |
| old_ensure = ( | |
| " self.auto_approval = {\n" | |
| " 'enabled': True,'cost_cap_usd': None,'estimated_spend_usd': 0.0,'remaining_usd': None,\n" | |
| " }\n" | |
| ) | |
| if old_ensure in content: | |
| # The one-liner dict exists (from patch_fix_approval_waiting); prepend | |
| # the scalar assignments before it. | |
| new_ensure = ( | |
| " self.auto_approval_enabled = True\n" | |
| " self.auto_approval_cost_cap_usd = None\n" | |
| " self.auto_approval_estimated_spend_usd = 0.0\n" | |
| + old_ensure | |
| ) | |
| content, ok = _replace_all(content, old_ensure, new_ensure) | |
| if ok: | |
| print(" + ensure_auto_approval sets scalar attributes") | |
| changed = True | |
| else: | |
| print(" INFO: ensure_auto_approval one-liner not found (may differ)") | |
| return content, changed | |
| _patch_py(SESSION, _patch_session, "session.py scalar auto-approval") | |
| # -------------------------------------------------------------------------- | |
| # 2. backend/session_manager.py - seed paths set scalars on restored sessions | |
| # -------------------------------------------------------------------------- | |
| SM = "/app/backend/session_manager.py" | |
| def _patch_sm(content, _path): | |
| changed = False | |
| old_seed = ( | |
| " agent_session.auto_approval = {\n" | |
| " 'enabled': True,\n" | |
| " 'cost_cap_usd': None,\n" | |
| " 'estimated_spend_usd': 0.0,\n" | |
| " 'remaining_usd': None,\n" | |
| " }\n" | |
| ) | |
| new_seed = ( | |
| " # === PATCH: fix-approval-buttons ===\n" | |
| " if not getattr(agent_session, 'auto_approval_enabled', False):\n" | |
| " agent_session.auto_approval_enabled = True\n" | |
| " agent_session.auto_approval_cost_cap_usd = None\n" | |
| " agent_session.auto_approval_estimated_spend_usd = 0.0\n" | |
| " agent_session.auto_approval = {\n" | |
| " 'enabled': True,\n" | |
| " 'cost_cap_usd': None,\n" | |
| " 'estimated_spend_usd': 0.0,\n" | |
| " 'remaining_usd': None,\n" | |
| " }\n" | |
| ) | |
| n = content.count(old_seed) | |
| if n: | |
| content = content.replace(old_seed, new_seed) | |
| print(f" + seed paths set scalar auto-approval ({n} site(s))") | |
| changed = True | |
| old_meta = ( | |
| " if isinstance(meta, dict):\n" | |
| " meta.setdefault('auto_approval', {\n" | |
| ) | |
| new_meta = ( | |
| " if isinstance(meta, dict):\n" | |
| " # === PATCH: fix-approval-buttons ===\n" | |
| " meta.setdefault('auto_approval_enabled', True)\n" | |
| " meta.setdefault('auto_approval_cost_cap_usd', None)\n" | |
| " meta.setdefault('auto_approval_estimated_spend_usd', 0.0)\n" | |
| " meta.setdefault('auto_approval', {\n" | |
| ) | |
| content, ok = _replace_all(content, old_meta, new_meta) | |
| if ok: | |
| print(" + ensure_session_loaded metadata sets scalar keys") | |
| changed = True | |
| return content, changed | |
| _patch_py(SM, _patch_sm, "session_manager.py seed scalars") | |
| # -------------------------------------------------------------------------- | |
| # 3. backend/routes/agent.py - loud 409 when approval id has no live pending | |
| # -------------------------------------------------------------------------- | |
| RA = "/app/backend/routes/agent.py" | |
| def _patch_ra(content, _path): | |
| changed = False | |
| if MARKER in content: | |
| return content, False | |
| old = ( | |
| " if approvals:\n" | |
| " formatted = [\n" | |
| ) | |
| new = ( | |
| " if approvals:\n" | |
| " # === PATCH: fix-approval-buttons ===\n" | |
| " # Loudly reject approvals whose tool_call_id has no live\n" | |
| " # pending approval instead of silently dropping them.\n" | |
| " try:\n" | |
| " from agent.core.usage_thresholds import is_usage_threshold_pending\n" | |
| " from agent.core.yolo_budget import is_yolo_budget_pending\n" | |
| " _pending = getattr(agent_session.session, 'pending_approval', None) or {}\n" | |
| " if is_usage_threshold_pending(_pending) or is_yolo_budget_pending(_pending):\n" | |
| " _live_ids = {str(_pending.get('tool_call_id') or '')}\n" | |
| " else:\n" | |
| " _live_ids = {\n" | |
| " str(getattr(tc, 'id', '') or '')\n" | |
| " for tc in (_pending.get('tool_calls') or [])\n" | |
| " }\n" | |
| " _submitted = [str(a.get('tool_call_id') or '') for a in approvals]\n" | |
| " _unknown = [i for i in _submitted if i and i not in _live_ids]\n" | |
| " if _unknown:\n" | |
| " broadcaster.unsubscribe(sub_id)\n" | |
| " raise HTTPException(\n" | |
| " status_code=409,\n" | |
| " detail=(\n" | |
| " 'No pending approval for tool call(s): '\n" | |
| " + ', '.join(_unknown)\n" | |
| " + '. The turn already finished or the session was '\n" | |
| " 'restored - send a new message instead.'\n" | |
| " ),\n" | |
| " )\n" | |
| " except HTTPException:\n" | |
| " raise\n" | |
| " except Exception as _e:\n" | |
| " logger.warning('approval mismatch check failed: %s', _e)\n" | |
| " formatted = [\n" | |
| ) | |
| content, ok = _replace_all(content, old, new) | |
| if ok: | |
| print(" + chat_sse rejects unknown approval ids with 409") | |
| changed = True | |
| else: | |
| print(" INFO: chat_sse approval anchor not found") | |
| return content, changed | |
| _patch_py(RA, _patch_ra, "routes/agent.py loud 409") | |
| # -------------------------------------------------------------------------- | |
| # 4. frontend hooks/useAgentChat.ts - let pending approvals bypass freeze | |
| # -------------------------------------------------------------------------- | |
| FSRC = "/source/frontend/src/hooks/useAgentChat.ts" | |
| def _patch_ts(content, _path): | |
| if MARKER_TS in content: | |
| return content, False | |
| changed = False | |
| # 4a. Helper: does this message list contain an approval-requested part? | |
| old_waiting = "function waitingApprovalStatus(items: PendingApprovalItem[] | undefined) {" | |
| helper = ( | |
| "// === PATCH: fix-approval-buttons ===\n" | |
| "/** True if any tool part is currently awaiting approval. */\n" | |
| "function _hasPendingApproval(msgs: UIMessage[]): boolean {\n" | |
| " return msgs.some((m) =>\n" | |
| " m.parts.some(\n" | |
| " (p) => p.type === 'dynamic-tool' && p.state === 'approval-requested',\n" | |
| " ),\n" | |
| " );\n" | |
| "}\n" | |
| "// === PATCH: fix-approval-buttons ===\n" | |
| "\n" | |
| "function waitingApprovalStatus(items: PendingApprovalItem[] | undefined) {" | |
| ) | |
| content, ok = _replace_all(content, old_waiting, helper) | |
| if ok: | |
| print(" + added _hasPendingApproval helper") | |
| changed = True | |
| # 4b. Replace `_catchupDone ? false :` in EVERY hydration guard with | |
| # `_catchupDone ? _hasPendingApproval(uiMsgs) :` so approval rounds | |
| # always hydrate, including the approval_required SSE branch. | |
| # Any indentation variant, replace_all. | |
| variants = [ | |
| ( | |
| " const _shouldOverwrite = _catchupDone\n" | |
| " ? false\n" | |
| " : (uiMsgs.length > _currentNonSystem.length || _currentNonSystem.length === 0);\n", | |
| " const _shouldOverwrite = _catchupDone\n" | |
| " ? _hasPendingApproval(uiMsgs)\n" | |
| " : (uiMsgs.length > _currentNonSystem.length || _currentNonSystem.length === 0);\n", | |
| ), | |
| ( | |
| " const _shouldOverwrite2 = _catchupDone\n" | |
| " ? false\n" | |
| " : (uiMsgs.length > _currentNonSystem2.length || _currentNonSystem2.length === 0);\n", | |
| " const _shouldOverwrite2 = _catchupDone\n" | |
| " ? _hasPendingApproval(uiMsgs)\n" | |
| " : (uiMsgs.length > _currentNonSystem2.length || _currentNonSystem2.length === 0);\n", | |
| ), | |
| ( | |
| " const _shouldSetB = _catchupDone\n" | |
| " ? false\n" | |
| " : (uiMsgs.length > _currentMsgsB.length || _currentMsgsB.length === 0);\n", | |
| " const _shouldSetB = _catchupDone\n" | |
| " ? _hasPendingApproval(uiMsgs)\n" | |
| " : (uiMsgs.length > _currentMsgsB.length || _currentMsgsB.length === 0);\n", | |
| ), | |
| ( | |
| " const _shouldSetC = _catchupDone\n" | |
| " ? false\n" | |
| " : (uiMsgs.length > _currentMsgsC.length || _currentMsgsC.length === 0);\n", | |
| " const _shouldSetC = _catchupDone\n" | |
| " ? _hasPendingApproval(uiMsgs)\n" | |
| " : (uiMsgs.length > _currentMsgsC.length || _currentMsgsC.length === 0);\n", | |
| ), | |
| ( | |
| " const _shouldSet = _catchupDone\n" | |
| " ? false\n" | |
| " : (uiMsgs.length > _currentMsgs.length || _currentMsgs.length === 0);\n", | |
| " const _shouldSet = _catchupDone\n" | |
| " ? _hasPendingApproval(uiMsgs)\n" | |
| " : (uiMsgs.length > _currentMsgs.length || _currentMsgs.length === 0);\n", | |
| ), | |
| # Any other indentation of the same guard (robustness). | |
| ( | |
| "const _shouldSetC = _catchupDone\n" | |
| " ? false\n", | |
| "const _shouldSetC = _catchupDone\n" | |
| " ? _hasPendingApproval(uiMsgs)\n", | |
| ), | |
| ] | |
| for old_g, new_g in variants: | |
| content, ok = _replace_all(content, old_g, new_g) | |
| if ok: | |
| print(f" + hydration guard -> _hasPendingApproval (replace_all)") | |
| changed = True | |
| # 4c. Any remaining generic `_catchupDone ? false` (loose form). | |
| old_loose = "_catchupDone\n ? false\n" | |
| while old_loose in content: | |
| content = content.replace( | |
| old_loose, | |
| "_catchupDone\n ? _hasPendingApproval(uiMsgs)\n", | |
| 1, | |
| ) | |
| changed = True | |
| print(" + loose _catchupDone ? false -> _hasPendingApproval") | |
| # 4d. event-stream consume guard (_c3a) -- add approval bypass. | |
| old3 = ( | |
| " if (uiMsgs.length > 0 && (!_catchupDone || uiMsgs.length > _c3a.length)) {\n" | |
| ) | |
| new3 = ( | |
| " if (uiMsgs.length > 0 && (!_catchupDone || uiMsgs.length > _c3a.length || _hasPendingApproval(uiMsgs))) {\n" | |
| ) | |
| content, ok = _replace_all(content, old3, new3) | |
| if ok: | |
| print(" + event-stream consume guard honors pending approvals") | |
| changed = True | |
| else: | |
| print(" INFO: _c3a consume guard not found (may differ in fork)") | |
| return content, changed | |
| if os.path.exists(FSRC): | |
| content = _read(FSRC) | |
| if MARKER_TS in content: | |
| print(f"SKIP: {FSRC} already patched") | |
| else: | |
| new_content, changed = _patch_ts(content, FSRC) | |
| if changed: | |
| _write(FSRC, new_content) | |
| print(f"OK: {FSRC} patched (frontend approval bypass)") | |
| else: | |
| print(f"SKIP: {FSRC} - no changes needed") | |
| else: | |
| print(f"SKIP: {FSRC} not found (not in this build stage)") | |
| print("\n=== fix-approval-buttons done ===") |