Skip to content

Automate browser based workflows with AI

Resolve a Google connection named in the request to its stored id (SKY-15324) (#8412)

Andrew Neilsonb1a5c66fdd84
diff --git a/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt b/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
index a3ae73cd0..8e24bb538 100644
--- a/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
+++ b/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
@@ -110,7 +110,7 @@ The interaction blocks differ by how specifically you describe the step — from
For non-interaction steps, use the purpose-built block directly: goto_url (load a known URL), wait, conditional, for_loop/while_loop, http_request, file_url_parser, file_upload, send_email, text_prompt.
-For connected-service outcomes, use the purpose-built integration helper directly rather than automating that service through its browser UI. For Google Sheets, use google_sheets_read to read rows and google_sheets_write to append or update rows. Resolve a compatible connection with list_integrations, then inspect the selected block schema. When the request identifies an active, scope-compatible row, bind its exact connection_id as the native block's credential_id; do not ask the user to repeat an opaque ID already returned by the tool. For a build-and-test request, use the available native workflow update-and-run surface in the same turn; do not stop at a draft.
+For connected-service outcomes, use the purpose-built integration helper directly rather than automating that service through its browser UI. For Google Sheets, use google_sheets_read to read rows and google_sheets_write to append or update rows. Resolve a compatible connection with list_integrations, then inspect the selected block schema. When the request identifies an active, scope-compatible row, bind its exact connection_id as the native block's credential_id; do not ask the user to repeat an opaque ID already returned by the tool. A connection name or account email the user wrote in this turn is also accepted in credential_id: the server resolves it, rewrites the slot to the connection_id, and reports resolved/ambiguous/not_found with the eligible rows. For a build-and-test request, use the available native workflow update-and-run surface in the same turn; do not stop at a draft.
Rule of thumb: if you can name the exact action or purpose, use the specific block; fall back to navigation only when the step is genuinely a goal the agent must work out itself. The specific block also carries the right semantics (login handles 2FA, file_download detects completion, extraction enforces a schema) and runs tighter — a loose navigation_goal re-runs the full browser agent (scrape -> plan -> act) for every step it takes, so it is the block most likely to exhaust the per-tool-call run budget on a heavy page.
diff --git a/skyvern/forge/sdk/copilot/credential_resolution.py b/skyvern/forge/sdk/copilot/credential_resolution.py
index 77c32d7d8..ed25b46ff 100644
--- a/skyvern/forge/sdk/copilot/credential_resolution.py
+++ b/skyvern/forge/sdk/copilot/credential_resolution.py
@@ -7,7 +7,7 @@ the evidence at hand, not a set computed once at turn start.
from __future__ import annotations
-from collections.abc import Sequence
+from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import Literal
from urllib.parse import ParseResult, parse_qsl, urlencode, urlparse
@@ -150,12 +150,12 @@ def credential_reference_spans(message: str, reference: str) -> list[tuple[int,
start = index + 1
-def grounded_credential_references(message: str, credentials: list[Credential]) -> set[str]:
- """Find complete saved names/IDs in a turn, preferring the longest overlap."""
- candidates = {value for credential in credentials for value in (credential.name, credential.credential_id) if value}
+def grounded_references(message: str, candidates: Iterable[str]) -> set[str]:
+ """Find complete candidate literals in a turn, preferring the longest overlap: a shorter
+ candidate that only occurs inside a longer one is not cited on its own."""
occurrences = [
(reference, start, end)
- for reference in candidates
+ for reference in {candidate for candidate in candidates if candidate}
for start, end in credential_reference_spans(message, reference)
]
return {
@@ -168,6 +168,13 @@ def grounded_credential_references(message: str, credentials: list[Credential])
}
+def grounded_credential_references(message: str, credentials: list[Credential]) -> set[str]:
+ """Find complete saved names/IDs in a turn, preferring the longest overlap."""
+ return grounded_references(
+ message, (value for credential in credentials for value in (credential.name, credential.credential_id))
+ )
+
+
def _match_by_url_tiered(
credentials: list[Credential],
urls: list[str],
diff --git a/skyvern/forge/sdk/copilot/google_connection_notice.py b/skyvern/forge/sdk/copilot/google_connection_notice.py
index 7cad8466e..4732b710c 100644
--- a/skyvern/forge/sdk/copilot/google_connection_notice.py
+++ b/skyvern/forge/sdk/copilot/google_connection_notice.py
@@ -52,7 +52,7 @@ def google_sheet_connection_bindings(workflow: Workflow | None) -> tuple[GoogleS
for block in blocks:
if isinstance(block, (GoogleSheetsReadBlock, GoogleSheetsWriteBlock)):
connection_id = block.credential_id
- if connection_id:
+ if connection_id and connection_id.startswith("goac_"):
result.append((block.label, connection_id))
elif isinstance(block, (ForLoopBlock, WhileLoopBlock)):
collect(block.loop_blocks)
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index 4fbe1e343..f41627114 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -822,6 +822,14 @@ async def list_integrations_tool(ctx: RunContextWrapper) -> str:
Never require an opaque ID already present in this tool result to be repeated.
If the requested account remains ambiguous or no compatible active row exists,
use a grounded ordinary-language clarification instead.
+
+ A `credential_id` may instead be the connection `name` or `email_address`
+ exactly as the user wrote it in this turn. The server resolves it and reports
+ the outcome under `google_connection_resolution` in the `update_workflow`
+ result: `resolved` rewrites the slot to the `connection_id`, while `ambiguous`,
+ `not_found`, `ineligible`, and `not_cited` leave it alone and return the
+ eligible rows to clarify against. A slot still holding an unresolved reference
+ cannot run.
"""
copilot_ctx = ctx.context
arguments: dict[str, Any] = {}
diff --git a/skyvern/forge/sdk/copilot/tools/credentials.py b/skyvern/forge/sdk/copilot/tools/credentials.py
index d0c06160c..17bf06e36 100644
--- a/skyvern/forge/sdk/copilot/tools/credentials.py
+++ b/skyvern/forge/sdk/copilot/tools/credentials.py
@@ -12,18 +12,22 @@ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.credential_resolution import (
credential_reference_spans,
grounded_credential_references,
+ grounded_references,
load_credentials,
)
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
from skyvern.forge.sdk.copilot.runtime import AgentContext
+from skyvern.forge.sdk.copilot.secret_scrub import scrub_secrets_from_structure
from skyvern.forge.sdk.copilot.workflow_credential_utils import (
block_credential_ids,
credential_param_ids,
saved_credential_ids,
workflow_blocks,
)
+from skyvern.forge.sdk.copilot.workflow_yaml import dump_workflow_yaml
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ConnectedAccountChoice
from skyvern.forge.sdk.schemas.credentials import Credential, TotpType
+from skyvern.forge.sdk.schemas.google_oauth import GoogleOAuthCredentialBase
from skyvern.forge.sdk.services import google_oauth_service
from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameterType
from skyvern.utils.yaml_loader import safe_load_no_dates
@@ -168,6 +172,185 @@ def _google_sheet_connection_bindings_from_workflow_definition(
]
+_GOOGLE_SHEETS_BLOCK_TYPES = {"google_sheets_read", "google_sheets_write"}
+_GOOGLE_CONNECTION_PREFIX = "goac_"
+
+
+def _is_templated_credential_value(value: str) -> bool:
+ return "{{" in value or "{%" in value
+
+
+_TEMPLATE_KEY_RE = re.compile(r"\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}")
+
+
+def _connection_labels(connections: Sequence[GoogleOAuthCredentialBase]) -> list[str]:
+ return [
+ label.casefold()
+ for connection in connections
+ for label in (connection.credential_name, connection.email_address)
+ if label
+ ]
+
+
+def _google_connection_reference_is_cited(message: str, reference: str, labels: Sequence[str]) -> bool:
+ """Verify a citation; never interpret one. The exact literal must stand as its own token in the
+ current turn, compared the way the resolver matches rows: casefold. A label that only occurs
+ inside a longer sibling label ("Marketing" within "Marketing Archive") is not cited on its own."""
+ if not message or not reference:
+ return False
+ return reference.casefold() in grounded_references(message.casefold(), [reference.casefold(), *labels])
+
+
+def _named_google_sheet_blocks(
+ parsed: dict[str, Any],
+ *,
+ selected_labels: set[str] | None = None,
+) -> list[dict[str, Any]]:
+ """Sheets blocks whose `credential_id` still holds an unresolved connection reference.
+ Saved-credential ids are excluded because they carry the saved-credential approval error instead."""
+ return [
+ block
+ for block in workflow_blocks(parsed, selected_labels=selected_labels)
+ if block.get("block_type") in _GOOGLE_SHEETS_BLOCK_TYPES
+ and isinstance((reference := block.get("credential_id")), str)
+ and reference.strip()
+ and not reference.startswith(_GOOGLE_CONNECTION_PREFIX)
+ and not _is_templated_credential_value(reference)
+ and not _CREDENTIAL_ID_RE.fullmatch(reference.strip())
+ ]
+
+
+def _unbacked_templated_google_sheet_slots(parsed: dict[str, Any], labels: Collection[str]) -> list[str]:
+ """Templated Sheets `credential_id` slots not backed by credential-typed workflow parameters.
+ A slot is backed only when it is a bare `{{ key }}` for such a parameter; a dotted path, a
+ filter, or a `{% %}` expression names no parameter the boundary can vouch for, so it renders at
+ run time with no citation, approval, state, or scope check and carries no authority of its own."""
+ definition = parsed.get("workflow_definition")
+ parameters = definition.get("parameters") if isinstance(definition, dict) else None
+ credential_keys = set(credential_param_ids(parameters))
+ return [
+ reference
+ for block in workflow_blocks(parsed, selected_labels=set(labels))
+ if block.get("block_type") in _GOOGLE_SHEETS_BLOCK_TYPES
+ and isinstance((reference := block.get("credential_id")), str)
+ and _is_templated_credential_value(reference)
+ and not (
+ _TEMPLATE_KEY_RE.fullmatch(reference.strip())
+ and set(_TEMPLATE_KEY_RE.findall(reference)) <= credential_keys
+ )
+ ]
+
+
+def _google_connection_reference_ids(workflow_definition: Any, labels: Collection[str]) -> list[str]:
+ parsed = {"workflow_definition": _workflow_definition_as_dict(workflow_definition)}
+ return list(
+ dict.fromkeys(
+ [
+ *(
+ str(block["credential_id"]).strip()
+ for block in _named_google_sheet_blocks(parsed, selected_labels=set(labels))
+ ),
+ *_unbacked_templated_google_sheet_slots(parsed, labels),
+ ]
+ )
+ )
+
+
+def _connection_row_facts(credential: GoogleOAuthCredentialBase) -> dict[str, Any]:
+ return {
+ "connection_id": credential.id,
+ "name": credential.credential_name,
+ "email_address": credential.email_address,
+ "state": credential.state,
+ "scopes_granted": list(credential.scopes_granted),
+ }
+
+
+async def canonicalize_named_google_sheet_bindings(
+ workflow_yaml: str,
+ ctx: AgentContext,
+) -> tuple[str, list[dict[str, Any]]]:
+ """Rewrite a cited Google connection name in a Sheets `credential_id` slot to its stored id.
+
+ Only a literal the current user turn contains, resolving to exactly one active Sheets-scoped
+ row, is rewritten; every other reference is left in place and reported as facts."""
+ try:
+ parsed = safe_load_no_dates(workflow_yaml)
+ except yaml.YAMLError:
+ return workflow_yaml, []
+ if not isinstance(parsed, dict):
+ return workflow_yaml, []
+ named_blocks = _named_google_sheet_blocks(parsed)
+ if not named_blocks:
+ return workflow_yaml, []
+
+ policy = ctx.request_policy
+ message = policy.canonical_user_message if isinstance(policy, RequestPolicy) else ""
+ try:
+ visible: list[GoogleOAuthCredentialBase] | None = await google_oauth_service.get_visible_credentials_for_org(
+ ctx.organization_id
+ )
+ except Exception:
+ LOG.warning(
+ "copilot_google_connection_canonicalization_lookup_failed",
+ organization_id=ctx.organization_id,
+ exc_info=True,
+ )
+ visible = None
+
+ eligible = [
+ credential
+ for credential in (visible or [])
+ if credential.state == google_oauth_service.STATE_ACTIVE
+ and google_oauth_service.GOOGLE_SHEETS_DATA_SCOPE in credential.scopes_granted
+ ]
+ eligible_ids = {credential.id for credential in eligible}
+
+ facts: list[dict[str, Any]] = []
+ changed = False
+ for block in named_blocks:
+ reference = str(block["credential_id"]).strip()
+ label = block.get("label")
+ fact: dict[str, Any] = {
+ "label": label if isinstance(label, str) else None,
+ "provider": "google",
+ "reference": reference,
+ "canonicalized": False,
+ }
+ if visible is None:
+ fact["status"] = "lookup_failed"
+ elif not _google_connection_reference_is_cited(message, reference, _connection_labels(visible)):
+ fact["status"] = "not_cited"
+ else:
+ resolution = google_oauth_service.resolve_connection_reference(visible, reference)
+ fact["status"] = resolution.status
+ fact["candidates"] = [_connection_row_facts(candidate) for candidate in resolution.candidates]
+ credential = resolution.credential
+ if credential is not None:
+ fact["connection_id"] = credential.id
+ fact["state"] = credential.state
+ fact["scopes_granted"] = list(credential.scopes_granted)
+ if credential.id in eligible_ids:
+ block["credential_id"] = credential.id
+ fact["canonicalized"] = True
+ changed = True
+ else:
+ fact["status"] = "ineligible"
+ if not fact["canonicalized"]:
+ fact["eligible_connections"] = [_connection_row_facts(candidate) for candidate in eligible]
+ facts.append(fact)
+
+ if changed:
+ workflow_yaml = dump_workflow_yaml(parsed)
+ LOG.info(
+ "copilot_google_connection_name_canonicalized",
+ organization_id=ctx.organization_id,
+ connection_ids=[fact["connection_id"] for fact in facts if fact["canonicalized"]],
+ )
+ scrubbed: list[dict[str, Any]] = scrub_secrets_from_structure(ctx, facts)
+ return workflow_yaml, scrubbed
+
+
def _parsed_workflow_definition(workflow_yaml: str | None) -> dict[str, Any] | None:
if not workflow_yaml:
return None
@@ -292,18 +475,58 @@ async def _approve_server_verified_google_sheet_bindings(
organization_id: str,
request_policy: RequestPolicy | None,
) -> list[str]:
- """Admit selected Sheets citations backed by this turn's server-owned listing."""
+ """Admit selected Sheets citations backed by this turn's server-owned listing or user citation."""
if request_policy is None:
return []
- listed_ids: set[str] = set()
+ listed_ids = _same_turn_listed_google_sheet_ids(tool_activity)
+ canonical_message = request_policy.canonical_user_message
+ already_approved = set(request_policy.run_approved_google_connection_ids)
+ candidates = [
+ connection_id
+ for connection_id in dict.fromkeys(connection_id for _, connection_id in bindings)
+ if connection_id not in already_approved
+ ]
+ if not candidates or (not listed_ids and not canonical_message):
+ return []
+ try:
+ visible_connections = await google_oauth_service.get_visible_credentials_for_org(organization_id)
+ except Exception:
+ LOG.warning(
+ "copilot cited Google Sheets binding authority lookup failed",
+ organization_id=organization_id,
+ exc_info=True,
+ )
+ return []
+
+ # Citation is judged against every visible row, the same set author time sees, so a longer
+ # sibling name in the error state still shadows the shorter one; only active rows are eligible.
+ eligible = [
+ connection
+ for connection in visible_connections
+ if connection.state == google_oauth_service.STATE_ACTIVE
+ and google_oauth_service.GOOGLE_SHEETS_DATA_SCOPE in connection.scopes_granted
+ ]
+ eligible_ids = {connection.id for connection in eligible}
+ return [
+ connection_id
+ for connection_id in candidates
+ if connection_id in eligible_ids
+ and (
+ connection_id in listed_ids
+ or _connection_is_cited_by_the_user(connection_id, eligible, visible_connections, canonical_message)
+ )
+ ]
+
+
+def _same_turn_listed_google_sheet_ids(tool_activity: Sequence[dict[str, Any]]) -> set[str]:
for activity in reversed(tool_activity):
if activity.get("tool") != "list_integrations":
continue
integrations = activity.get("integrations")
if not isinstance(integrations, list):
- break
- listed_ids = {
+ return set()
+ return {
connection_id
for integration in integrations
if isinstance(integration, dict)
@@ -313,32 +536,29 @@ async def _approve_server_verified_google_sheet_bindings(
and isinstance(integration.get("scopes_granted"), list)
and google_oauth_service.GOOGLE_SHEETS_DATA_SCOPE in integration["scopes_granted"]
}
- break
- if not listed_ids:
- return []
-
- cited_ids = list(dict.fromkeys(connection_id for _, connection_id in bindings if connection_id in listed_ids))
- already_approved = set(request_policy.run_approved_google_connection_ids)
- candidates = [connection_id for connection_id in cited_ids if connection_id not in already_approved]
- if not candidates:
- return []
- try:
- active_connections = await google_oauth_service.get_credentials_for_org(organization_id)
- except Exception:
- LOG.warning(
- "copilot cited Google Sheets binding authority lookup failed",
- organization_id=organization_id,
- exc_info=True,
- )
- return []
-
- eligible_ids = {
- connection.id
- for connection in active_connections
- if google_oauth_service.GOOGLE_SHEETS_DATA_SCOPE in connection.scopes_granted
- }
- approved = [connection_id for connection_id in candidates if connection_id in eligible_ids]
- return approved
+ return set()
+
+
+def _connection_is_cited_by_the_user(
+ connection_id: str,
+ eligible: Sequence[GoogleOAuthCredentialBase],
+ known: Sequence[GoogleOAuthCredentialBase],
+ canonical_message: str,
+) -> bool:
+ """The user's own verbatim naming of a connection stands in for a same-turn listing, but only
+ when that literal resolves to this one row across every known row: a name shared with a
+ connection that merely lacks the Sheets scope is still ambiguous, and admits nothing."""
+ bound = next((connection for connection in eligible if connection.id == connection_id), None)
+ if bound is None:
+ return False
+ labels = _connection_labels(known)
+ for label in (bound.credential_name, bound.email_address):
+ if not label or not _google_connection_reference_is_cited(canonical_message, label, labels):
+ continue
+ resolution = google_oauth_service.resolve_connection_reference(known, label)
+ if resolution.credential is not None and resolution.credential.id == connection_id:
+ return True
+ return False
def _credential_run_approval_error(
@@ -361,13 +581,14 @@ def _credential_run_approval_blocker_signal(
request_policy: RequestPolicy | None,
*,
additional_approved_ids: Collection[str] = (),
+ google_reference_ids: Collection[str] = (),
) -> CopilotToolBlockerSignal | None:
approved_ids = _approved_run_credential_ids(request_policy) | set(additional_approved_ids)
- unapproved_google_ids = [
- credential_id
- for credential_id in credential_ids
- if credential_id.startswith("goac_") and credential_id not in approved_ids
+ references = [
+ *(credential_id for credential_id in credential_ids if credential_id.startswith(_GOOGLE_CONNECTION_PREFIX)),
+ *google_reference_ids,
]
+ unapproved_google_ids = [reference for reference in dict.fromkeys(references) if reference not in approved_ids]
if not unapproved_google_ids:
return None
return CopilotToolBlockerSignal(
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index c74aa1b9a..2b28b124c 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -225,6 +225,7 @@ from .credentials import (
_extract_credential_ids_for_labels,
_extract_credential_ids_from_tool_value,
_extract_credential_ids_from_workflow_definition,
+ _google_connection_reference_ids,
_google_sheet_connection_bindings_from_workflow_definition,
_server_verified_google_account_choices,
)
@@ -2704,6 +2705,7 @@ async def _run_blocks_and_collect_debug(
approval_credential_ids,
ctx.request_policy,
additional_approved_ids=dispatch_scoped_sheet_ids,
+ google_reference_ids=_google_connection_reference_ids(workflow.workflow_definition, labels_that_may_execute),
)
if google_approval_blocker is not None:
ctx.connected_account_recovery_choices = (
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index 33ba65662..7c982a2a8 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -136,7 +136,11 @@ from .banned_blocks import (
_task_v3_pure_policy_violations,
_task_v3_pure_reject_message,
)
-from .credentials import _credential_id_misbinding_findings, _credential_reference_validation_error
+from .credentials import (
+ _credential_id_misbinding_findings,
+ _credential_reference_validation_error,
+ canonicalize_named_google_sheet_bindings,
+)
from .frontier import (
_get_prior_workflow,
_invalidate_verified_state_on_edit,
@@ -4073,6 +4077,9 @@ async def _update_workflow(
)
try:
+ # Before redaction: a connection name equal to a registered scrub value would otherwise
+ # reach the resolver already replaced by the placeholder.
+ workflow_yaml, google_connection_resolution = await canonicalize_named_google_sheet_bindings(workflow_yaml, ctx)
# Ahead of both persistence and the context assignment below, so the row, the draft the
# model reads back, and the bytes apply_block_edit anchors against are one string. Scrubbing
# the payload alone would leave the model reading redacted code and anchoring on raw code.
@@ -4297,6 +4304,8 @@ async def _update_workflow(
)
if findings:
data["findings"] = findings
+ if google_connection_resolution:
+ data["google_connection_resolution"] = google_connection_resolution
return {
"ok": True,
"data": data,
diff --git a/skyvern/forge/sdk/copilot/workflow_yaml.py b/skyvern/forge/sdk/copilot/workflow_yaml.py
index c2a932e09..2a73570e6 100644
--- a/skyvern/forge/sdk/copilot/workflow_yaml.py
+++ b/skyvern/forge/sdk/copilot/workflow_yaml.py
@@ -82,6 +82,12 @@ def runner_code_block_associations(
return associations
+def dump_workflow_yaml(parsed: dict[str, Any]) -> str:
+ """Serialize a parsed workflow without folding: a wrapped long line reloads as one joined
+ string, which corrupts generated code."""
+ return yaml.safe_dump(parsed, sort_keys=False, allow_unicode=True, width=_YAML_NO_FOLD_WIDTH)
+
+
def reconcile_workflow_completion_contract(
workflow_yaml: str,
contract: dict[str, object] | None,
@@ -110,11 +116,11 @@ def reconcile_workflow_completion_contract(
if definition.get("completion_contract") != previous_contract:
return workflow_yaml, False
definition.pop("completion_contract", None)
- return yaml.safe_dump(parsed, sort_keys=False, allow_unicode=True, width=_YAML_NO_FOLD_WIDTH), True
+ return dump_workflow_yaml(parsed), True
if definition.get("completion_contract") == contract:
return workflow_yaml, False
definition["completion_contract"] = contract
- return yaml.safe_dump(parsed, sort_keys=False, allow_unicode=True, width=_YAML_NO_FOLD_WIDTH), False
+ return dump_workflow_yaml(parsed), False
def _proxy_location_alias_key(value: str) -> str:
diff --git a/skyvern/forge/sdk/services/google_oauth_service.py b/skyvern/forge/sdk/services/google_oauth_service.py
index 15d07d48a..df1004ec7 100644
--- a/skyvern/forge/sdk/services/google_oauth_service.py
+++ b/skyvern/forge/sdk/services/google_oauth_service.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import asyncio
import datetime
import secrets
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from urllib.parse import urlparse
@@ -906,6 +906,47 @@ def _matches_reference(credential: GoogleOAuthCredentialBase, normalized_referen
)
+@dataclass(frozen=True)
+class GoogleConnectionResolution:
+ status: str
+ reference: str
+ credential: GoogleOAuthCredentialBase | None
+ candidates: tuple[GoogleOAuthCredentialBase, ...]
+ matches: tuple[GoogleOAuthCredentialBase, ...]
+
+
+def resolve_connection_reference(
+ credentials: Sequence[GoogleOAuthCredentialBase], reference: str
+) -> GoogleConnectionResolution:
+ """Resolve one connection name, account email, or stored id against the rows given.
+
+ Active rows win outright over same-named non-active ones, so a stale connection sharing a name
+ with a healthy one never makes it ambiguous.
+ """
+ reference = reference.strip()
+ normalized = reference.casefold()
+ matches = [
+ credential
+ for credential in credentials
+ if credential.id == reference or _matches_reference(credential, normalized)
+ ]
+ active = [credential for credential in matches if credential.state == STATE_ACTIVE]
+ candidates = active or matches
+ if not candidates:
+ status = "not_found"
+ elif len({credential.id for credential in candidates}) != 1:
+ status = "ambiguous"
+ else:
+ status = "resolved"
+ return GoogleConnectionResolution(
+ status=status,
+ reference=reference,
+ credential=candidates[0] if status == "resolved" else None,
+ candidates=tuple(candidates),
+ matches=tuple(matches),
+ )
+
+
async def resolve_credential_reference(organization_id: str, reference: str) -> str:
"""Map a caller-supplied Google connection reference onto a stored credential id.
@@ -918,13 +959,8 @@ async def resolve_credential_reference(organization_id: str, reference: str) ->
return reference
credentials = await get_visible_credentials_for_org(organization_id)
- normalized = reference.casefold()
- matches = [credential for credential in credentials if _matches_reference(credential, normalized)]
- active = [credential for credential in matches if credential.state == STATE_ACTIVE]
- candidates = active or matches
- if len({credential.id for credential in candidates}) != 1:
- return reference
- return candidates[0].id
+ resolution = resolve_connection_reference(credentials, reference)
+ return resolution.credential.id if resolution.credential is not None else reference
async def describe_credential_failure(organization_id: str, reference: str) -> str:
@@ -940,8 +976,7 @@ async def describe_credential_failure(organization_id: str, reference: str) -> s
if any(credential.id == reference for credential in credentials):
return reconnect
- normalized = reference.casefold()
- matches = [credential for credential in credentials if _matches_reference(credential, normalized)]
+ matches = resolve_connection_reference(credentials, reference).matches
if len(matches) == 1:
return reconnect
if len(matches) > 1:
diff --git a/tests/unit/google/test_google_oauth.py b/tests/unit/google/test_google_oauth.py
index 64ab247b7..78c9c0878 100644
--- a/tests/unit/google/test_google_oauth.py
+++ b/tests/unit/google/test_google_oauth.py
@@ -4733,3 +4733,46 @@ async def test_google_oauth_callback_rejects_unusable_state(
assert exc_info.value.status_code == 400
exchange_mock.assert_not_awaited()
+
+
+def _connection(connection_id: str, name: str, state: str = "active", email: str | None = None) -> Any:
+ now = datetime.datetime(2026, 9, 1)
+ return GoogleOAuthCredentialBase(
+ id=connection_id,
+ organization_id="org_1",
+ credential_name=name,
+ email_address=email,
+ state=state,
+ scopes_requested=[],
+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ created_at=now,
+ modified_at=now,
+ )
+
+
+ ("reference", "expected_status", "expected_id"),
+ [
+ ("Sheets Writer", "resolved", "goac_active"),
+ ("sheets writer", "resolved", "goac_active"),
+ ("[email protected]", "resolved", "goac_active"),
+ ("Shared Account", "ambiguous", None),
+ ("No Such Connection", "not_found", None),
+ ],
+)
+def test_connection_reference_resolution_prefers_active_rows_and_reports_ambiguity(
+ reference: str,
+ expected_status: str,
+ expected_id: str | None,
+) -> None:
+ rows = [
+ _connection("goac_active", "Sheets Writer", email="[email protected]"),
+ _connection("goac_stale", "sheets writer", state="error"),
+ _connection("goac_twin_a", "Shared Account"),
+ _connection("goac_twin_b", "shared account"),
+ ]
+
+ resolution = google_oauth_service.resolve_connection_reference(rows, reference)
+
+ assert resolution.status == expected_status
+ assert (resolution.credential.id if resolution.credential else None) == expected_id
diff --git a/tests/unit/test_copilot_account_choices.py b/tests/unit/test_copilot_account_choices.py
index 86fdb28d7..38ba9b9fe 100644
--- a/tests/unit/test_copilot_account_choices.py
+++ b/tests/unit/test_copilot_account_choices.py
@@ -10,6 +10,7 @@ from skyvern.forge.sdk.copilot import agent as agent_module
from skyvern.forge.sdk.copilot import request_policy as request_policy_module
from skyvern.forge.sdk.copilot.context import (
ApprovedCredential,
+ CopilotContext,
StructuredContext,
adopt_model_authored_context,
record_approved_credentials_in_global_llm_context,
@@ -26,7 +27,9 @@ from skyvern.forge.sdk.copilot.tools.credentials import (
_credential_run_approval_blocker_signal,
_credential_run_approval_error,
_extract_credential_ids_for_labels,
+ _google_connection_reference_ids,
_parsed_workflow_definition,
+ canonicalize_named_google_sheet_bindings,
)
from skyvern.forge.sdk.copilot.turn_outcome import (
connected_account_choice_context,
@@ -47,6 +50,7 @@ def _google(
name: str,
state: str = "active",
email_address: str | None = None,
+ scopes_granted: list[str] | None = None,
) -> GoogleOAuthCredentialBase:
return GoogleOAuthCredentialBase(
id=connection_id,
@@ -55,7 +59,7 @@ def _google(
email_address=email_address,
state=state,
scopes_requested=["https://www.googleapis.com/auth/spreadsheets"],
- scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ scopes_granted=scopes_granted or ["https://www.googleapis.com/auth/spreadsheets"],
created_at=datetime(2026, 8, 15),
modified_at=datetime(2026, 8, 15),
)
@@ -615,7 +619,7 @@ async def test_inactive_or_unknown_model_bound_account_stays_authority_denied(
active_connections: list[GoogleOAuthCredentialBase],
) -> None:
monkeypatch.setattr(
- "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_credentials_for_org",
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
AsyncMock(return_value=active_connections),
)
policy = request_policy_module.RequestPolicy()
@@ -649,7 +653,7 @@ async def test_model_bound_account_requires_sheets_scope_and_effective_selection
]
)
monkeypatch.setattr(
- "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_credentials_for_org",
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
lookup,
)
policy = request_policy_module.RequestPolicy()
@@ -678,7 +682,7 @@ async def test_model_bound_account_lookup_failure_preserves_authority_denial(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
- "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_credentials_for_org",
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
AsyncMock(side_effect=RuntimeError("database unavailable")),
)
policy = request_policy_module.RequestPolicy()
@@ -700,7 +704,7 @@ async def test_model_bound_account_without_same_turn_list_result_stays_authority
) -> None:
lookup = AsyncMock(return_value=[_google(NAMED_PICK_ACCOUNT_ID, "Sheets Writer")])
monkeypatch.setattr(
- "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_credentials_for_org",
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
lookup,
)
policy = request_policy_module.RequestPolicy()
@@ -804,3 +808,351 @@ def test_terminal_without_a_run_receipt_reports_no_run() -> None:
assert replaced
assert "I ran the workflow" not in message
+
+
+CITED_ACCOUNT_ID = "goac_cited"
+CITED_ACCOUNT_NAME = "Blog Metrics Connection"
+AMBIGUOUS_ACCOUNT_ID = "goac_ambiguous"
+
+
+def _named_sheets_yaml(reference: str) -> str:
+ return (
+ "workflow_definition:\n"
+ " blocks:\n"
+ f" - label: {SHEETS_BLOCK_LABEL}\n"
+ " block_type: google_sheets_write\n"
+ f' credential_id: "{reference}"\n'
+ )
+
+
+def _canonicalization_ctx(workflow_yaml: str, user_message: str) -> CopilotContext:
+ return make_copilot_ctx(
+ workflow_yaml=workflow_yaml,
+ request_policy=request_policy_module.RequestPolicy(canonical_user_message=user_message),
+ )
+
+
+def _patch_visible_credentials(
+ monkeypatch: pytest.MonkeyPatch,
+ credentials: list[GoogleOAuthCredentialBase] | Exception,
+) -> None:
+ mock = (
+ AsyncMock(side_effect=credentials)
+ if isinstance(credentials, Exception)
+ else AsyncMock(return_value=credentials)
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
+ mock,
+ )
+
+
[email protected]("citation", [CITED_ACCOUNT_NAME, CITED_ACCOUNT_NAME.casefold()])
+async def test_cited_connection_name_canonicalizes_and_keeps_run_authority(
+ monkeypatch: pytest.MonkeyPatch,
+ citation: str,
+) -> None:
+ accounts = [_google(CITED_ACCOUNT_ID, CITED_ACCOUNT_NAME, email_address="[email protected]")]
+ _patch_visible_credentials(monkeypatch, accounts)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
+ AsyncMock(return_value=accounts),
+ )
+ draft = _named_sheets_yaml(citation)
+ ctx = _canonicalization_ctx(draft, f'write the rows with the "{citation}" account')
+
+ canonical_yaml, facts = await canonicalize_named_google_sheet_bindings(draft, ctx)
+
+ assert [(fact["status"], fact["canonicalized"], fact["connection_id"]) for fact in facts] == [
+ ("resolved", True, CITED_ACCOUNT_ID)
+ ]
+ dispatched_ids = _dispatch_credential_ids(canonical_yaml)
+ assert dispatched_ids == [CITED_ACCOUNT_ID]
+
+ policy = ctx.request_policy
+ approved = await _approve_server_verified_google_sheet_bindings(
+ [(SHEETS_BLOCK_LABEL, CITED_ACCOUNT_ID)],
+ tool_activity=[],
+ organization_id="org-1",
+ request_policy=policy,
+ )
+
+ assert approved == [CITED_ACCOUNT_ID]
+ assert (
+ _credential_run_approval_blocker_signal(
+ dispatched_ids,
+ policy,
+ additional_approved_ids=approved,
+ google_reference_ids=_google_connection_reference_ids(
+ _parsed_workflow_definition(canonical_yaml), [SHEETS_BLOCK_LABEL]
+ ),
+ )
+ is None
+ )
+
+
+async def test_ambiguous_cited_name_admits_no_account_and_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ accounts = [
+ _google(AMBIGUOUS_ACCOUNT_ID, "Shared Sheets Account", email_address="[email protected]"),
+ _google("goac_ambiguous_twin", "shared sheets account", email_address="[email protected]"),
+ ]
+ _patch_visible_credentials(monkeypatch, accounts)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
+ AsyncMock(return_value=accounts),
+ )
+ draft = _named_sheets_yaml("Shared Sheets Account")
+ ctx = _canonicalization_ctx(draft, 'use the "Shared Sheets Account" connection')
+
+ canonical_yaml, facts = await canonicalize_named_google_sheet_bindings(draft, ctx)
+
+ assert canonical_yaml == draft
+ assert facts[0]["status"] == "ambiguous"
+ assert [candidate["connection_id"] for candidate in facts[0]["candidates"]] == [
+ AMBIGUOUS_ACCOUNT_ID,
+ "goac_ambiguous_twin",
+ ]
+
+ policy = ctx.request_policy
+ model_bound = await _approve_server_verified_google_sheet_bindings(
+ [(SHEETS_BLOCK_LABEL, AMBIGUOUS_ACCOUNT_ID)],
+ tool_activity=[],
+ organization_id="org-1",
+ request_policy=policy,
+ )
+
+ assert model_bound == []
+
+ blocker = _credential_run_approval_blocker_signal(
+ [AMBIGUOUS_ACCOUNT_ID],
+ policy,
+ additional_approved_ids=model_bound,
+ )
+
+ assert blocker is not None
+ assert blocker.blocker_kind == "authority_denied"
+ assert blocker.preserves_workflow_draft
+
+ name_in_slot_blocker = _credential_run_approval_blocker_signal(
+ _dispatch_credential_ids(canonical_yaml),
+ policy,
+ additional_approved_ids=model_bound,
+ google_reference_ids=_google_connection_reference_ids(
+ _parsed_workflow_definition(canonical_yaml), [SHEETS_BLOCK_LABEL]
+ ),
+ )
+
+ assert name_in_slot_blocker is not None
+ assert name_in_slot_blocker.blocker_kind == "authority_denied"
+ assert name_in_slot_blocker.preserves_workflow_draft
+
+
+ ("reference", "user_message", "expected_status"),
+ [
+ ("Missing Reporting Connection", 'bind the "Missing Reporting Connection" account', "not_found"),
+ ("Dead Sheets Account", 'bind the "Dead Sheets Account" account', "ineligible"),
+ ("Blog Metrics Connection", "bind whichever google account works", "not_cited"),
+ ],
+)
+async def test_unresolved_connection_reference_reports_facts_and_fails_closed(
+ monkeypatch: pytest.MonkeyPatch,
+ reference: str,
+ user_message: str,
+ expected_status: str,
+) -> None:
+ accounts = [
+ _google(CITED_ACCOUNT_ID, CITED_ACCOUNT_NAME, email_address="[email protected]"),
+ _google("goac_dead", "Dead Sheets Account", state="error", email_address="[email protected]"),
+ ]
+ _patch_visible_credentials(monkeypatch, accounts)
+ draft = _named_sheets_yaml(reference)
+ ctx = _canonicalization_ctx(draft, user_message)
+
+ canonical_yaml, facts = await canonicalize_named_google_sheet_bindings(draft, ctx)
+
+ assert canonical_yaml == draft
+ assert facts[0]["status"] == expected_status
+ assert facts[0]["canonicalized"] is False
+ assert [row["connection_id"] for row in facts[0]["eligible_connections"]] == [CITED_ACCOUNT_ID]
+
+ blocker = _credential_run_approval_blocker_signal(
+ _dispatch_credential_ids(canonical_yaml),
+ ctx.request_policy,
+ google_reference_ids=_google_connection_reference_ids(
+ _parsed_workflow_definition(canonical_yaml), [SHEETS_BLOCK_LABEL]
+ ),
+ )
+
+ assert blocker is not None
+ assert blocker.blocker_kind == "authority_denied"
+
+
+async def test_saved_credential_slot_is_excluded_from_the_connection_seam(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_visible_credentials(monkeypatch, [_google(CITED_ACCOUNT_ID, CITED_ACCOUNT_NAME)])
+ draft = _named_sheets_yaml("cred_qablogmetrics")
+ ctx = _canonicalization_ctx(draft, "use cred_qablogmetrics for the sheet")
+
+ canonical_yaml, facts = await canonicalize_named_google_sheet_bindings(draft, ctx)
+
+ assert canonical_yaml == draft
+ assert facts == []
+ assert _google_connection_reference_ids(_parsed_workflow_definition(canonical_yaml), [SHEETS_BLOCK_LABEL]) == []
+
+
+ "slot_value",
+ [
+ "{{ sheets_connection }}",
+ "{{ workflow.sheets_connection }}",
+ "{{ sheets_connection | default('goac_x') }}",
+ "{% if x %}goac_a{% else %}goac_b{% endif %}",
+ ],
+)
+async def test_templated_slot_without_a_credential_parameter_fails_closed(
+ monkeypatch: pytest.MonkeyPatch,
+ slot_value: str,
+) -> None:
+ _patch_visible_credentials(monkeypatch, [_google(CITED_ACCOUNT_ID, CITED_ACCOUNT_NAME)])
+ draft = _named_sheets_yaml(slot_value)
+ ctx = _canonicalization_ctx(draft, f"use {slot_value} for the sheet")
+
+ canonical_yaml, facts = await canonicalize_named_google_sheet_bindings(draft, ctx)
+
+ assert canonical_yaml == draft
+ assert facts == []
+ reference_ids = _google_connection_reference_ids(_parsed_workflow_definition(canonical_yaml), [SHEETS_BLOCK_LABEL])
+ assert reference_ids == [slot_value]
+ blocker = _credential_run_approval_blocker_signal(
+ _dispatch_credential_ids(canonical_yaml), ctx.request_policy, google_reference_ids=reference_ids
+ )
+ assert blocker is not None
+ assert blocker.blocker_kind == "authority_denied"
+
+
+ ("slot_value", "expected_reference_ids"),
+ [
+ ("{{ sheets_connection }}", []),
+ ("goac_{{ sheets_connection }}", ["goac_{{ sheets_connection }}"]),
+ ],
+)
+def test_templated_slot_backed_by_a_credential_parameter_carries_its_own_authority(
+ slot_value: str,
+ expected_reference_ids: list[str],
+) -> None:
+ workflow_definition = {
+ "parameters": [{"key": "sheets_connection", "parameter_type": "credential", "credential_id": "cred_sheets"}],
+ "blocks": [
+ {
+ "label": SHEETS_BLOCK_LABEL,
+ "block_type": "google_sheets_write",
+ "credential_id": slot_value,
+ }
+ ],
+ }
+
+ assert _google_connection_reference_ids(workflow_definition, [SHEETS_BLOCK_LABEL]) == expected_reference_ids
+
+
+async def test_connection_lookup_failure_keeps_the_draft_and_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_visible_credentials(monkeypatch, RuntimeError("database unavailable"))
+ draft = _named_sheets_yaml(CITED_ACCOUNT_NAME)
+ ctx = _canonicalization_ctx(draft, f'use the "{CITED_ACCOUNT_NAME}" account')
+
+ canonical_yaml, facts = await canonicalize_named_google_sheet_bindings(draft, ctx)
+
+ assert canonical_yaml == draft
+ assert facts[0]["status"] == "lookup_failed"
+
+ blocker = _credential_run_approval_blocker_signal(
+ _dispatch_credential_ids(canonical_yaml),
+ ctx.request_policy,
+ google_reference_ids=_google_connection_reference_ids(
+ _parsed_workflow_definition(canonical_yaml), [SHEETS_BLOCK_LABEL]
+ ),
+ )
+
+ assert blocker is not None
+ assert blocker.blocker_kind == "authority_denied"
+
+
+async def test_cited_name_shared_with_an_unscoped_connection_admits_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ accounts = [
+ _google(CITED_ACCOUNT_ID, "Reporting Account", email_address="[email protected]"),
+ _google(
+ "goac_no_sheets_scope",
+ "Reporting Account",
+ email_address="[email protected]",
+ scopes_granted=["https://www.googleapis.com/auth/drive.file"],
+ ),
+ ]
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
+ AsyncMock(return_value=accounts),
+ )
+
+ approved = await _approve_server_verified_google_sheet_bindings(
+ [(SHEETS_BLOCK_LABEL, CITED_ACCOUNT_ID)],
+ tool_activity=[],
+ organization_id="org-1",
+ request_policy=request_policy_module.RequestPolicy(
+ canonical_user_message='use the "Reporting Account" connection'
+ ),
+ )
+
+ assert approved == []
+
+
+def _sibling_named_accounts(longer_sibling_state: str = "active") -> list[GoogleOAuthCredentialBase]:
+ return [
+ _google("goac_marketing", "Marketing", email_address="[email protected]"),
+ _google(
+ "goac_marketing_archive",
+ "Marketing Archive",
+ state=longer_sibling_state,
+ email_address="[email protected]",
+ ),
+ ]
+
+
+async def test_name_contained_in_a_longer_sibling_name_is_not_cited(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_visible_credentials(monkeypatch, _sibling_named_accounts())
+ draft = _named_sheets_yaml("Marketing")
+ ctx = _canonicalization_ctx(draft, "please read rows from the Marketing Archive connection")
+
+ canonical_yaml, facts = await canonicalize_named_google_sheet_bindings(draft, ctx)
+
+ assert canonical_yaml == draft
+ assert [(fact["status"], fact["canonicalized"]) for fact in facts] == [("not_cited", False)]
+
+
[email protected]("longer_sibling_state", ["active", "error"])
+async def test_name_contained_in_a_longer_sibling_name_admits_nothing_at_dispatch(
+ monkeypatch: pytest.MonkeyPatch,
+ longer_sibling_state: str,
+) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
+ AsyncMock(return_value=_sibling_named_accounts(longer_sibling_state)),
+ )
+
+ approved = await _approve_server_verified_google_sheet_bindings(
+ [(SHEETS_BLOCK_LABEL, "goac_marketing")],
+ tool_activity=[],
+ organization_id="org-1",
+ request_policy=request_policy_module.RequestPolicy(
+ canonical_user_message="please read rows from the Marketing Archive connection"
+ ),
+ )
+
+ assert approved == []
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 3bdedd66f..a2d436cf0 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -110,6 +110,7 @@ from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerification
from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_blocks, workflow_credential_ids
from skyvern.forge.sdk.routes.workflow_copilot import CHAT_HISTORY_CONTEXT_MESSAGES
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ConnectedAccountChoice, ResponseKind, TurnOutcome
+from skyvern.forge.sdk.schemas.google_oauth import GoogleOAuthCredentialBase
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
@@ -4230,6 +4231,114 @@ workflow_definition:
assert result["ok"] is True, result
get_credentials_by_ids.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_update_workflow_canonicalizes_a_cited_google_connection_name(self, monkeypatch) -> None:
+ connection = GoogleOAuthCredentialBase(
+ id="goac_cited_persist",
+ organization_id="org-1",
+ credential_name="Blog Metrics Connection",
+ state="active",
+ scopes_requested=[],
+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ created_at=datetime(2026, 9, 1),
+ modified_at=datetime(2026, 9, 1),
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
+ AsyncMock(return_value=[connection]),
+ )
+ ctx = _ctx(
+ request_policy=RequestPolicy(
+ canonical_user_message='append the titles with the "Blog Metrics Connection" account'
+ )
+ )
+
+ workflow = MagicMock()
+ workflow.workflow_definition.blocks = []
+ process_workflow_yaml = AsyncMock(return_value=workflow)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",
+ process_workflow_yaml,
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.app.WORKFLOW_SERVICE",
+ SimpleNamespace(update_workflow_definition=AsyncMock()),
+ )
+
+ result = await tools_module._update_workflow(
+ {
+ "workflow_yaml": (
+ "workflow_definition:\n"
+ " blocks:\n"
+ " - label: append_titles\n"
+ " block_type: google_sheets_write\n"
+ ' credential_id: "Blog Metrics Connection"\n'
+ )
+ },
+ ctx,
+ )
+
+ assert result["ok"] is True, result
+ assert result["data"]["google_connection_resolution"][0]["status"] == "resolved"
+ assert "goac_cited_persist" in process_workflow_yaml.await_args.kwargs["workflow_yaml"]
+ assert "goac_cited_persist" in ctx.staged_workflow_yaml
+
+ @pytest.mark.asyncio
+ async def test_update_workflow_reports_an_unmatched_cited_google_connection_name(self, monkeypatch) -> None:
+ connection = GoogleOAuthCredentialBase(
+ id="goac_eligible_row",
+ organization_id="org-1",
+ credential_name="Blog Metrics Connection",
+ state="active",
+ scopes_requested=[],
+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ created_at=datetime(2026, 9, 1),
+ modified_at=datetime(2026, 9, 1),
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_visible_credentials_for_org",
+ AsyncMock(return_value=[connection]),
+ )
+ ctx = _ctx(
+ request_policy=RequestPolicy(
+ canonical_user_message='append the titles with the "Quarterly Revenue Connection" account'
+ )
+ )
+
+ workflow = MagicMock()
+ workflow.workflow_definition.blocks = []
+ process_workflow_yaml = AsyncMock(return_value=workflow)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",
+ process_workflow_yaml,
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools.app.WORKFLOW_SERVICE",
+ SimpleNamespace(update_workflow_definition=AsyncMock()),
+ )
+
+ result = await tools_module._update_workflow(
+ {
+ "workflow_yaml": (
+ "workflow_definition:\n"
+ " blocks:\n"
+ " - label: append_titles\n"
+ " block_type: google_sheets_write\n"
+ ' credential_id: "Quarterly Revenue Connection"\n'
+ )
+ },
+ ctx,
+ )
+
+ assert result["ok"] is True, result
+ assert "block_id" not in result
+ fact = result["data"]["google_connection_resolution"][0]
+ assert fact["status"] == "not_found"
+ assert fact["canonicalized"] is False
+ assert [row["connection_id"] for row in fact["eligible_connections"]] == ["goac_eligible_row"]
+ assert "Quarterly Revenue Connection" in process_workflow_yaml.await_args.kwargs["workflow_yaml"]
+ assert "Quarterly Revenue Connection" in ctx.staged_workflow_yaml
+
class TestRunBlocksCredentialApproval:
@staticmethod
diff --git a/tests/unit/test_copilot_google_connection_notice.py b/tests/unit/test_copilot_google_connection_notice.py
index 7a0e2c84f..498fd3a5c 100644
--- a/tests/unit/test_copilot_google_connection_notice.py
+++ b/tests/unit/test_copilot_google_connection_notice.py
@@ -124,6 +124,12 @@ def test_nested_and_duplicate_bindings_are_flattened_and_deduplicated() -> None:
assert google_sheet_connection_ids(_workflow(loop)) == ("goac_nested",)
+def test_unresolved_connection_name_left_in_the_slot_is_not_a_connection_binding() -> None:
+ workflow = _workflow(_write("named", "Shared Sheets Account"), _write("bound", "goac_active"))
+
+ assert google_sheet_connection_bindings(workflow) == (("bound", "goac_active"),)
+
+
def test_new_block_using_a_preexisting_connection_is_still_a_new_binding() -> None:
notices = collect_google_connection_notices(
turn_start_bindings=(("existing", "goac_error"),),