"""Undo windows on approved sends (Phase 7). A T2 send queues its message with ``send_after = now + undo window``. When such a call ran on a human approval, the tool result tells the gateway how to undo it:: {"send_after": "", "undo_url": "/packs/.../cancel", "undo": {"tool": ".cancel_message", "args": {...}}} and the gateway copies those onto the approval row, so the inbox shows a countdown and an Undo button. Undo is itself a gateway call (``undo.tool``), executed as the operator. """ from __future__ import annotations import uuid from datetime import datetime from typing import Any from sqlalchemy import update from sqlalchemy.ext.asyncio import AsyncSession from core.approvals.models import Approval def _when(v: Any) -> datetime | None: if isinstance(v, datetime): return v if isinstance(v, str): try: return datetime.fromisoformat(v) except ValueError: return None return None async def attach_undo(s: AsyncSession, approval_id: uuid.UUID, data: dict[str, Any]) -> bool: when = _when(data.get("send_after")) undo = data.get("undo") if when is None or not isinstance(undo, dict) or not isinstance(undo.get("tool"), str): return False url = data.get("undo_url") await s.execute( update(Approval) .where(Approval.id == approval_id) .values( send_after=when, undo={"tool": undo["tool"], "args": dict(undo.get("args") or {})}, undo_url=url if isinstance(url, str) and len(url) <= 300 else None, ) ) return True