The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(connectors): reconnecting a named account repairs that exact account
Siddharth Balyana36fe1b9260c
diff --git a/tests/tools/test_connector_accounts.py b/tests/tools/test_connector_accounts.pyindex 470aeb86f6e..454b7e49f9a 100644--- a/tests/tools/test_connector_accounts.py+++ b/tests/tools/test_connector_accounts.py@@ -3,7 +3,7 @@Contracts:- the account a call ran under reaches the model on the single-call and the batch path- connect with an alias asks the gateway for that account; reconnect with an alias repairs that- account even when another account of the same connector is healthy+ account by its connection id even when another account of the same connector is healthy- rename resolves the name to the account; an unknown name lists the valid names- an open operation for one account is never reused for another account of the same connector"""@@ -80,8 +80,11 @@ class _Gateway:def list_connectors(self, *, timeout=None):return [{"connector": "gmail", "enabled": True, "connected": "gmail" in self.connected}]- def connections(self, connectors, *, reinitiate=False, alias=None, return_to=None, op=None):- self.mints.append({"connectors": tuple(connectors), "reinitiate": reinitiate, "alias": alias})+ def connections(self, connectors, *, reinitiate=False, alias=None, connection_id=None, return_to=None, op=None):+ mint = {"connectors": tuple(connectors), "reinitiate": reinitiate, "alias": alias}+ if connection_id:+ mint["connection_id"] = connection_id+ self.mints.append(mint)return {"results": [{"connector": c, "status": "initiated", "connection_id": f"ca_{c}_{len(self.mints)}","connect_url": f"https://connect.example/{c}"} for c in connectors]}@@ -115,6 +118,13 @@ def test_reconnect_with_an_alias_repairs_it_even_when_another_account_is_healthygateway = _Gateway(connected={"gmail"})accounts = [_account("home", "[email protected]"), _account("work", "[email protected]", status="expired")]_run({"action": "reconnect", "connectors": [{"name": "gmail", "alias": "work"}]}, gateway, accounts)+ assert gateway.mints == [{"connectors": ("gmail",), "reinitiate": True, "alias": None, "connection_id": "ca_work"}]+++def test_reconnect_of_a_name_no_account_has_yet_sends_the_alias():+ gateway = _Gateway()+ _run({"action": "reconnect", "connectors": [{"name": "gmail", "alias": "work"}]}, gateway,+ [_account("home", "[email protected]")])assert gateway.mints == [{"connectors": ("gmail",), "reinitiate": True, "alias": "work"}]diff --git a/tests/tools/test_connectors_managed.py b/tests/tools/test_connectors_managed.pyindex 7be823b4d3d..9265e4840bf 100644--- a/tests/tools/test_connectors_managed.py+++ b/tests/tools/test_connectors_managed.py@@ -54,7 +54,7 @@ class GatewayFake:self.lists += 1return [{"connector": s, "enabled": True, "connected": s in self.connected} for s in ("gmail", "notion")]- def connections(self, connectors, *, reinitiate=False, alias=None, return_to=None, op=None):+ def connections(self, connectors, *, reinitiate=False, alias=None, connection_id=None, return_to=None, op=None):self.mints.append({"connectors": tuple(connectors), "reinitiate": reinitiate, "alias": alias,"return_to": return_to, "op": op})results = []diff --git a/tools/connectors/gateway/client.py b/tools/connectors/gateway/client.pyindex d2d1569c104..608ad865266 100644--- a/tools/connectors/gateway/client.py+++ b/tools/connectors/gateway/client.py@@ -104,12 +104,14 @@ class ConnectorClient:def connections(self, connectors: Sequence[str], *, reinitiate: bool = False, alias: Optional[str] = None,- return_to: Optional[str] = None, op: Optional[str] = None,+ connection_id: Optional[str] = None, return_to: Optional[str] = None, op: Optional[str] = None,) -> dict[str, Any]:"""Never retry: the gateway cannot deduplicate authorization starts. ``alias`` names the one- account the request connects (or, with ``reinitiate``, repairs)."""+ account the request connects (or, with ``reinitiate``, repairs); ``connection_id`` names an+ existing account to repair, named or not."""body = wire.ConnectorConnectionsRequest(- connectors=list(connectors), reinitiate=reinitiate, alias=alias, return_to=return_to, op=op,+ connectors=list(connectors), reinitiate=reinitiate, alias=alias, connection_id=connection_id,+ return_to=return_to, op=op,).model_dump(by_alias=True, exclude_none=True)payload = self._post(wire.CONNECTOR_CONNECTIONS_PATH, body, retries=0)return wire.ConnectorConnectionsResponse.model_validate(payload).model_dump()diff --git a/tools/connectors/gateway/wire.py b/tools/connectors/gateway/wire.pyindex 3b1f5bb2952..2426fe46c74 100644--- a/tools/connectors/gateway/wire.py+++ b/tools/connectors/gateway/wire.py@@ -140,6 +140,8 @@ class ConnectorConnectionsRequest(_Wire):connectors: list[str]reinitiate: bool = Falsealias: Optional[str] = None+ # The existing account a reinitiate repairs; sent instead of ``alias`` when known.+ connection_id: Optional[str] = Field(default=None, alias="connectionId")return_to: Optional[ConnectorReturnTarget] = Field(default=None, alias="returnTo")# The caller's operation id, echoed on the hermes://connections/done link.op: Optional[str] = Field(default=None, min_length=1, max_length=128)diff --git a/tools/connectors/managed.py b/tools/connectors/managed.pyindex b2ff9da0b5e..359debfa60a 100644--- a/tools/connectors/managed.py+++ b/tools/connectors/managed.py@@ -59,17 +59,20 @@ def _status_by_slug(client: Any) -> dict[str, dict[str, Any]]:return {str(i.get("connector", "")).lower(): i for i in client.list_connectors() if isinstance(i, dict)}-def mint(client: Any, operation: ConnectionOperation, names: list[str], *, reinitiate: bool, actor: Actor) -> None:+def mint(client: Any, operation: ConnectionOperation, names: list[str], *, reinitiate: bool, actor: Actor,+ connection_id: Optional[str] = None) -> None:"""Mint links for ``names`` and apply the gateway's per-app answer to the operation. ``actor`` isthe watcher on the first mint and the user on Try again. The operation id rides along so the- vendor's done page can name it on the way back to the desktop."""+ vendor's done page can name it on the way back to the desktop. ``connection_id`` names the one+ existing account a repair restarts; the gateway then needs no alias to find it."""from tools.connectors.gateway.client import return_to_argsif not names:return# One aliased target per call, so the alias of the first named target is the request's.- alias = next((t.alias for t in operation.targets if t.name in names and t.alias), None)- response = client.connections(names, reinitiate=reinitiate, alias=alias, **return_to_args(op=operation.op_id))+ alias = None if connection_id else next((t.alias for t in operation.targets if t.name in names and t.alias), None)+ response = client.connections(names, reinitiate=reinitiate, alias=alias, connection_id=connection_id,+ **return_to_args(op=operation.op_id))for entry in response.get("results", []):name = str(entry.get("connector") or "").lower()target = operation.target(name)@@ -212,7 +215,9 @@ def _prepare(client: Any, action: str, force: bool) -> Callable[[ConnectionOperaoperation.transition(name, TargetState.connected, Actor.backend_watcher)else:repair.append(name)- mint(client, operation, repair, reinitiate=True, actor=Actor.backend_watcher)+ # A named target is alone in its call, so at most one account id applies.+ account = next((status[n].get("connection_id") for n in repair if status.get(n, {}).get("connection_id")), None)+ mint(client, operation, repair, reinitiate=True, actor=Actor.backend_watcher, connection_id=account)_mark_misrouted(operation)return prepare@@ -225,15 +230,20 @@ def portal_accounts() -> list[dict[str, Any]]:def _alias_status(targets: list[Target]) -> Optional[dict[str, dict[str, Any]]]:- """``{slug: {"connected": bool}}`` for an aliased target, read from that account's own row;- ``None`` when no target is aliased. A failed read raises: guessing "not connected" would send- the user through a new login for an account that may be healthy."""+ """``{slug: {"connected": bool, "connection_id": str | None}}`` for an aliased target, read from+ that account's own row (``connection_id`` is None when no account has that name yet); ``None``+ when no target is aliased. A failed read raises: guessing "not connected" would send the user+ through a new login for an account that may be healthy."""aliased = [t for t in targets if t.alias]if not aliased:return Nonerows = portal_accounts()- return {t.name: {"connected": any(r.get("connector") == t.name and r.get("alias") == t.alias- and r.get("status") == "active" for r in rows)} for t in aliased}+ status: dict[str, dict[str, Any]] = {}+ for t in aliased:+ row = next((r for r in rows if r.get("connector") == t.name and r.get("alias") == t.alias), None)+ status[t.name] = {"connected": bool(row) and row.get("status") == "active",+ "connection_id": row.get("connectionId") if row else None}+ return statusdef _targets(targets: list[HostedTarget], action: str) -> list[Target]: