File size: 17,162 Bytes
de536ff
 
 
 
5afa055
de536ff
5afa055
de536ff
 
 
 
 
5afa055
 
 
 
 
 
 
 
 
de536ff
 
5afa055
 
 
 
de536ff
 
5afa055
 
 
 
 
 
 
 
 
 
 
 
 
 
de536ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5afa055
de536ff
5afa055
de536ff
 
 
 
 
 
 
 
 
 
 
 
 
5afa055
de536ff
 
 
 
 
 
 
 
 
 
5afa055
 
 
de536ff
 
 
 
 
 
5afa055
 
 
 
de536ff
5afa055
 
 
de536ff
 
 
5afa055
 
 
 
 
de536ff
 
5afa055
de536ff
5afa055
de536ff
5afa055
 
de536ff
5afa055
de536ff
 
 
 
 
5afa055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de536ff
 
 
 
 
 
5afa055
 
 
de536ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5afa055
de536ff
 
 
 
 
 
 
 
 
5afa055
 
 
de536ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5afa055
de536ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5afa055
de536ff
 
 
 
5afa055
de536ff
 
 
 
 
 
5afa055
 
 
de536ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5afa055
de536ff
 
 
 
5afa055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de536ff
 
 
 
5afa055
 
 
de536ff
 
 
 
 
5afa055
 
 
de536ff
 
 
 
 
5afa055
 
 
 
 
 
 
 
 
 
de536ff
5afa055
 
 
de536ff
5afa055
de536ff
 
5afa055
 
 
 
 
 
 
 
 
 
 
 
de536ff
 
 
 
 
 
5afa055
de536ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5afa055
de536ff
 
 
 
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/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 ===")