Skip to content

Self-improving AI Employees for everyone

feat(approvals): link a held send to the form whose button started it

trohitg9daeab0391d4
diff --git a/server/services/approvals/tool_calls.py b/server/services/approvals/tool_calls.py
index 2b71df2c..f81d5a1c 100644
--- a/server/services/approvals/tool_calls.py
+++ b/server/services/approvals/tool_calls.py
@@ -220,6 +220,7 @@ async def hold(database: Any, context: Mapping[str, Any], node_cls: Any, spec: A
"""The held call's row: created once, found again on a retry."""
fields = _row_fields(context, node_cls, spec, node_data)
fields["expires_at"] = _utcnow() + timedelta(hours=DEFAULT_TIMEOUT_HOURS)
+ fields["ui_part_id"] = await _ui_part(database, fields.get("run_id"))
row, created = await store.get_or_create(database, idempotency_key=call_key(context), fields=fields)
if created:
logger.info("Held a call for the owner", approval_id=row.id, workflow_id=row.workflow_id, channel=row.channel)
@@ -228,6 +229,20 @@ async def hold(database: Any, context: Mapping[str, Any], node_cls: Any, spec: A
return row
+async def _ui_part(database: Any, run_id: Any) -> Any:
+ """The interface whose button started the run, for "Linked to the form
+ above" on the card."""
+ if not isinstance(run_id, str) or not run_id:
+ return None
+ try:
+ from services.chat.ledger import ui_part_of_run
+
+ return await ui_part_of_run(database, run_id)
+ except Exception: # noqa: BLE001 - the card shows without the link
+ logger.warning("Could not read which interface started a run", run_id=run_id, exc_info=True)
+ return None
+
+
async def _show_in_chat(database: Any, context: Mapping[str, Any], row: Any) -> None:
"""A call made answering the owner shows its card in that answer."""
stream = context.get("chat_stream")
diff --git a/server/services/chat/ledger.py b/server/services/chat/ledger.py
index 2e5843cb..c86c2686 100644
--- a/server/services/chat/ledger.py
+++ b/server/services/chat/ledger.py
@@ -160,6 +160,20 @@ async def runs_by_id(database: Any, run_ids: List[str]) -> Dict[str, ChatRun]:
return {run.run_id: run for run in result.scalars().all()}
+async def ui_part_of_run(database: Any, run_id: str) -> Optional[str]:
+ """The interface whose button started the run (its owner message
+ carries the press, ``meta.ui_event``), if one did."""
+ run = await get_run(database, run_id)
+ if run is None or not run.user_message_uid:
+ return None
+ async with database.get_session() as session:
+ result = await session.execute(select(ChatMessage).where(ChatMessage.uid == run.user_message_uid))
+ message = result.scalar_one_or_none()
+ event = (message.meta or {}).get("ui_event") if message is not None else None
+ part_id = event.get("part_id") if isinstance(event, dict) else None
+ return part_id if isinstance(part_id, str) and part_id else None
+
+
async def session_run_ids(database: Any, session_id: str) -> List[str]:
"""Every run of a session, live or ended."""
async with database.get_session() as session:
@@ -722,5 +736,6 @@ __all__ = [
"runs_by_id",
"session_run_ids",
"start_run",
+ "ui_part_of_run",
"sweep",
]
diff --git a/server/tests/services/approvals/test_tool_calls.py b/server/tests/services/approvals/test_tool_calls.py
index c608a772..9f8002ad 100644
--- a/server/tests/services/approvals/test_tool_calls.py
+++ b/server/tests/services/approvals/test_tool_calls.py
@@ -235,3 +235,24 @@ async def test_clearing_the_chat_cancels_its_drafts(harness, nodes_loaded, monke
async def _async(value):
return value
+
+
+async def test_a_call_made_after_a_button_press_is_linked_to_its_form(harness, nodes_loaded, monkeypatch):
+ from services.chat import ledger, parts
+
+ async def show_approval(database, stream, **_):
+ return None
+
+ monkeypatch.setattr(parts, "show_approval", show_approval)
+ await rules.set_ask_first(harness.database, "wf", True)
+ press = {"part_id": "ui_quote", "element_id": "send", "action": "sendQuote", "params": {}}
+ pressed = await ledger.admit_message(
+ harness.database, session_id="wf", workflow_id="wf", execution_id="gen-1", text="Send the quote",
+ track=True, kind="action", message_kind="action", meta={"ui_event": press},
+ )
+ stream = {"run_id": pressed.run.run_id, "session_id": "wf", "workflow_id": "wf"}
+ await tool_calls.check(call(chat_stream=stream, chat_run_id=pressed.run.run_id), get_node_class("whatsappSend"))
+ (row,) = await store.list_approvals(harness.database, status="pending")
+ assert row.ui_part_id == "ui_quote"
+ # A call in a run the owner's own words started has no form to link.
+ assert await ledger.ui_part_of_run(harness.database, "r_missing") is None