Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Resolve the Sheets tab from a URL gid at Copilot save, and show Range in append mode (SKY-16797) (#8696)
Andrew Neilson9f7036ed22cd
diff --git a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts b/skyvern-frontend/src/routes/workflows/editor/helpContent.tsindex 54fad3de3..795943cba 100644--- a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts+++ b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts@@ -148,7 +148,7 @@ export const helpTooltips = {writeMode:"Append adds new rows below existing data. Update Range overwrites the exact cells in the range you specify.",range:- "Only used for Update Range. A1 notation (e.g. A2:D5) or a named range. The data shape must match the range dimensions.",+ "Update Range: the cells to overwrite, in A1 notation (e.g. A2:D5) or a named range; the data shape must match. Append: optional start column (e.g. D:D); rows are added below existing data from that column.",values:"Jinja2 template that resolves to a JSON array. Arrays of lists write left-to-right; arrays of objects require column mappings below.",columnMapping:diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/GoogleSheetsWriteNode/GoogleSheetsWriteEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/GoogleSheetsWriteNode/GoogleSheetsWriteEditor.tsxindex 967b637f6..87d94640f 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/GoogleSheetsWriteNode/GoogleSheetsWriteEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/GoogleSheetsWriteNode/GoogleSheetsWriteEditor.tsx@@ -287,13 +287,7 @@ function GoogleSheetsWriteEditorBody({<buttonkey={opt.key}type="button"- onClick={() =>- update(- opt.key === "append"- ? { writeMode: opt.key, range: "" }- : { writeMode: opt.key },- )- }+ onClick={() => update({ writeMode: opt.key })}className={cn("nopan flex flex-col gap-1 rounded-md border px-3 py-2 text-left text-xs transition-colors",selected@@ -395,29 +389,31 @@ function GoogleSheetsWriteEditorBody({) : null}</div>- {data.writeMode === "update" ? (- <div className="space-y-2">- <div className="flex gap-2">- <Label className="text-xs text-tertiary-foreground">- Range- </Label>- <HelpTooltip- content={- helpTooltips["google_sheets_write"]?.["range"] ??- "The exact cells to overwrite. Data shape must match the range."- }- />- </div>- <WorkflowBlockInputTextarea- name="range"- nodeId={blockId}- onChange={(next) => update({ range: next })}- value={data.range}- placeholder="A2:D5 or MyNamedRange"- className="nopan text-xs"+ <div className="space-y-2">+ <div className="flex gap-2">+ <Label className="text-xs text-tertiary-foreground">+ Range+ </Label>+ <HelpTooltip+ content={+ helpTooltips["google_sheets_write"]?.["range"] ??+ "The exact cells to overwrite. Data shape must match the range."+ }/></div>- ) : null}+ <WorkflowBlockInputTextarea+ name="range"+ nodeId={blockId}+ onChange={(next) => update({ range: next })}+ value={data.range}+ placeholder={+ data.writeMode === "append"+ ? "D:D, the column to append into (optional)"+ : "A2:D5 or MyNamedRange"+ }+ className="nopan text-xs"+ />+ </div><div className="space-y-2"><div className="flex gap-2">diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/GoogleSheetsWriteBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/GoogleSheetsWriteBlockForm.test.tsxindex 07c951ed2..1ccfe14ff 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/GoogleSheetsWriteBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/GoogleSheetsWriteBlockForm.test.tsx@@ -573,27 +573,27 @@ describe("GoogleSheetsWriteBlockForm (SKY-9361)", () => {expect(updateNodeData).toHaveBeenCalledWith("g1", { writeMode: "update" });});- test("switching writeMode to append clears range", () => {- setGoogleSheetsWriteNode("g1", { writeMode: "update", range: "A1:B2" });+ test("append mode shows the configured range and switching to append keeps it", () => {+ setGoogleSheetsWriteNode("g1", { writeMode: "append", range: "D:D" });render(<GoogleSheetsWriteBlockForm blockId="g1" />);+ expect(+ screen.getByTestId<HTMLTextAreaElement>(/the column to append into/)+ .value,+ ).toBe("D:D");+fireEvent.click(screen.getByText("Append rows"));- expect(updateNodeData).toHaveBeenCalledWith("g1", {- writeMode: "append",- range: "",- });+ expect(updateNodeData).toHaveBeenCalledWith("g1", { writeMode: "append" });});test("editing values propagates", () => {setGoogleSheetsWriteNode("g1");- const { container } = render(<GoogleSheetsWriteBlockForm blockId="g1" />);+ render(<GoogleSheetsWriteBlockForm blockId="g1" />);- // Append mode hides the Range textarea, so the only visible- // WorkflowBlockInputTextarea is Values.- const textareas = container.querySelectorAll("textarea");- expect(textareas).toHaveLength(1);- fireEvent.change(textareas[0]!, { target: { value: "[[1,2,3]]" } });+ fireEvent.change(screen.getByTestId(/full fidelity/), {+ target: { value: "[[1,2,3]]" },+ });expect(updateNodeData).toHaveBeenCalledWith("g1", { values: "[[1,2,3]]" });});diff --git a/skyvern/forge/sdk/copilot/tools/credentials.py b/skyvern/forge/sdk/copilot/tools/credentials.pyindex 25158ecda..fe6cd836f 100644--- a/skyvern/forge/sdk/copilot/tools/credentials.py+++ b/skyvern/forge/sdk/copilot/tools/credentials.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport refrom collections.abc import Collection, Sequencefrom typing import Any@@ -33,8 +34,9 @@ from skyvern.forge.sdk.copilot.workflow_yaml import dump_workflow_yamlfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import ConnectedAccountChoicefrom skyvern.forge.sdk.schemas.credentials import Credential, CredentialType, TotpTypefrom skyvern.forge.sdk.schemas.google_oauth import GoogleOAuthCredentialBase-from skyvern.forge.sdk.services import google_oauth_service+from skyvern.forge.sdk.services import google_oauth_service, google_sheets_servicefrom skyvern.forge.sdk.workflow.models.parameter import WorkflowParameterType+from skyvern.schemas.google_sheets import extract_sheet_gid, extract_spreadsheet_id, is_plain_cell_rangefrom skyvern.utils.yaml_loader import safe_load_no_datesfrom ._shared import _iter_yaml_blocks, _workflow_definition_as_dict@@ -275,6 +277,17 @@ def _connection_row_facts(credential: GoogleOAuthCredentialBase) -> dict[str, An}+def _eligible_sheets_connections(+ connections: Sequence[GoogleOAuthCredentialBase],+) -> list[GoogleOAuthCredentialBase]:+ return [+ credential+ for credential in connections+ if credential.state == google_oauth_service.STATE_ACTIVE+ and google_oauth_service.GOOGLE_SHEETS_DATA_SCOPE in credential.scopes_granted+ ]++async def canonicalize_named_google_sheet_bindings(workflow_yaml: str,ctx: AgentContext,@@ -307,12 +320,7 @@ async def canonicalize_named_google_sheet_bindings()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 = _eligible_sheets_connections(visible or [])eligible_ids = {credential.id for credential in eligible}facts: list[dict[str, Any]] = []@@ -360,6 +368,132 @@ async def canonicalize_named_google_sheet_bindings(return workflow_yaml, scrubbed+_GID_TAB_LOOKUP_TIMEOUT_SECONDS = 5.0+++async def _fetch_sheet_tabs(organization_id: str, credential_id: str, url: str) -> list[google_sheets_service.SheetTab]:+ token = await app.AGENT_FUNCTION.get_google_sheets_credentials(organization_id, credential_id)+ if token is None:+ raise RuntimeError("no Google Sheets access token")+ return await google_sheets_service.get_spreadsheet_tabs(token, url)+++async def resolve_google_sheet_tabs_from_gid(+ workflow_yaml: str,+ ctx: AgentContext,+) -> tuple[str, list[dict[str, Any]]]:+ """Fill an empty Sheets `sheet_name` with the title of the tab whose id is the `gid` in the block's+ literal `spreadsheet_url`, read through the block's bound connection. Never falls back to another tab."""+ try:+ parsed = safe_load_no_dates(workflow_yaml)+ except yaml.YAMLError:+ return workflow_yaml, []+ if not isinstance(parsed, dict):+ return workflow_yaml, []+ candidates = [+ (block, url, gid)+ for block in workflow_blocks(parsed)+ if block.get("block_type") in _GOOGLE_SHEETS_BLOCK_TYPES+ and not str(block.get("sheet_name") or "").strip()+ and isinstance((url := block.get("spreadsheet_url")), str)+ and not _is_templated_credential_value(url)+ and (gid := extract_sheet_gid(url)) is not None+ ]+ if not candidates:+ return workflow_yaml, []++ try:+ eligible_ids: set[str] | None = {+ credential.id+ for credential in _eligible_sheets_connections(+ await google_oauth_service.get_visible_credentials_for_org(ctx.organization_id)+ )+ }+ except Exception:+ LOG.warning("copilot_google_sheet_tab_lookup_failed", organization_id=ctx.organization_id, exc_info=True)+ eligible_ids = None++ # Reading tab titles discloses spreadsheet metadata, so it needs the same turn approval dispatch requires.+ policy = ctx.request_policy if isinstance(ctx.request_policy, RequestPolicy) else None+ approved_ids = set(policy.run_approved_google_connection_ids) if policy is not None else set()+ approved_ids.update(+ await _approve_server_verified_google_sheet_bindings(+ [(str(block.get("label")), str(block.get("credential_id"))) for block, _, _ in candidates],+ tool_activity=ctx.tool_activity,+ organization_id=ctx.organization_id,+ request_policy=policy,+ )+ )++ # A slow Sheets API must not stall the save: one bounded lookup per spreadsheet, failures included.+ tabs_by_spreadsheet: dict[tuple[str, str], list[google_sheets_service.SheetTab] | None] = {}+ facts: list[dict[str, Any]] = []+ changed = False+ for block, url, gid in candidates:+ label = block.get("label")+ credential_id = block.get("credential_id")+ cell_range = block.get("range")+ fact: dict[str, Any] = {"label": label if isinstance(label, str) else None, "gid": gid, "resolved": False}+ facts.append(fact)+ has_range = cell_range is not None and str(cell_range).strip() != ""+ if has_range and not (isinstance(cell_range, str) and is_plain_cell_range(cell_range)):+ fact.update(status="ineligible", reason="range_not_plain_cells")+ continue+ if not isinstance(credential_id, str) or not credential_id.strip():+ fact["status"] = "no_connection"+ continue+ if _is_templated_credential_value(credential_id):+ fact.update(status="ineligible", reason="templated_credential")+ continue+ if eligible_ids is None:+ fact["status"] = "lookup_failed"+ continue+ if credential_id not in eligible_ids:+ fact.update(status="ineligible", reason="not_eligible_connection")+ continue+ if credential_id not in approved_ids:+ fact.update(status="ineligible", reason="connection_not_approved")+ continue+ try:+ lookup_key = (credential_id, extract_spreadsheet_id(url))+ if lookup_key not in tabs_by_spreadsheet:+ tabs_by_spreadsheet[lookup_key] = None+ tabs_by_spreadsheet[lookup_key] = await asyncio.wait_for(+ _fetch_sheet_tabs(ctx.organization_id, credential_id, url),+ timeout=_GID_TAB_LOOKUP_TIMEOUT_SECONDS,+ )+ tabs = tabs_by_spreadsheet[lookup_key]+ if tabs is None:+ raise RuntimeError("tab lookup already failed for this spreadsheet")+ except Exception:+ LOG.warning(+ "copilot_google_sheet_tab_lookup_failed",+ organization_id=ctx.organization_id,+ connection_id=credential_id,+ exc_info=True,+ )+ fact["status"] = "lookup_failed"+ continue+ fact["available_tabs"] = [tab.title for tab in tabs]+ match = next((tab for tab in tabs if tab.sheet_id == gid), None)+ if match is None:+ fact["status"] = "gid_not_found"+ continue+ block["sheet_name"] = match.title+ fact.update(status="resolved", resolved=True, sheet_name=match.title)+ changed = True++ if changed:+ workflow_yaml = dump_workflow_yaml(parsed)+ LOG.info(+ "copilot_google_sheet_tab_resolved_from_gid",+ organization_id=ctx.organization_id,+ labels=[fact["label"] for fact in facts if fact["resolved"]],+ )+ 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 Nonediff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 02d2f8bbe..29722f701 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -163,6 +163,7 @@ from .credentials import (_credential_id_misbinding_findings,_credential_reference_validation_error,canonicalize_named_google_sheet_bindings,+ resolve_google_sheet_tabs_from_gid,)from .frontier import (_get_prior_workflow,@@ -3879,6 +3880,7 @@ def carry_author_time_findings(update_result: dict[str, Any], result: dict[str,"block_type_changes","persistence","persistence_message",+ "google_sheet_tab_resolution",)if update_data.get(key)}@@ -4496,6 +4498,7 @@ async def _update_workflow(# 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)+ workflow_yaml, google_sheet_tab_resolution = await resolve_google_sheet_tabs_from_gid(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.@@ -4776,6 +4779,8 @@ async def _update_workflow(data["legacy_engine_blocks"] = list(authoring_validation.legacy_engine_blocks)if google_connection_resolution:data["google_connection_resolution"] = google_connection_resolution+ if google_sheet_tab_resolution:+ data["google_sheet_tab_resolution"] = google_sheet_tab_resolutionif isinstance(ctx, CopilotContext) and ctx.google_connection_notices:data["google_connection_notices"] = [notice.to_payload() for notice in ctx.google_connection_notices]return {diff --git a/skyvern/schemas/google_sheets.py b/skyvern/schemas/google_sheets.pyindex a82cdb52a..687967709 100644--- a/skyvern/schemas/google_sheets.py+++ b/skyvern/schemas/google_sheets.py@@ -1,5 +1,6 @@import refrom typing import Any+from urllib.parse import parse_qs, urlsplit_SPREADSHEET_URL_RE = re.compile(r"/spreadsheets(?:/u/\d+)?/d/([a-zA-Z0-9-_]+)")_BARE_ID_RE = re.compile(r"^[a-zA-Z0-9-_]{20,}$")@@ -30,6 +31,33 @@ def extract_spreadsheet_id(url_or_id: str) -> str:raise ValueError(f"Could not extract spreadsheet id from: {url_or_id}")+def extract_sheet_gid(url: str) -> int | None:+ try:+ parts = urlsplit(url)+ except ValueError:+ return None+ for component in (parts.fragment, parts.query):+ values = parse_qs(component).get("gid")+ if values:+ try:+ return int(values[0])+ except ValueError:+ return None+ return None+++def is_plain_cell_range(cell_range: str) -> bool:+ """True for cell or column A1 with no sheet title (``D8``, ``D:D``, ``A2:D5``); a named range is not."""+ parts = cell_range.strip().split(":")+ if len(parts) > 2 or (len(parts) == 1 and not _A1_CELL_RE.match(parts[0])):+ return False+ for part in parts:+ match = _A1_CELL_RE.match(part) or _A1_COLUMN_ONLY_RE.match(part)+ if match is None or column_letters_to_index(match.group(1)) > MAX_COLUMN_INDEX:+ return False+ return True++def quote_sheet_name(name: str) -> str:return "'" + name.replace("'", "''") + "'"diff --git a/tests/unit/conftest.py b/tests/unit/conftest.pyindex e2646d43e..c62c741d4 100644--- a/tests/unit/conftest.py+++ b/tests/unit/conftest.py@@ -44,6 +44,7 @@ from skyvern.webeye.utils import page as page_modulefrom skyvern.webeye.utils.page import ScreenshotModefrom tests.unit._fingerprint_expectations import FINGERPRINT_TEST_SECRET_KEYfrom tests.unit.force_stub_app import start_forge_stub_app+from tests.unit.google.conftest import mock_sheets_transport # noqa: F401# Four distinct ways to leave the legacy downloads root; each defeats a different weak check.LEGACY_DOWNLOAD_ESCAPE_CASES = ("parent_traversal", "encoded_dot_dot", "sibling_prefix", "symlink_escape")diff --git a/tests/unit/test_copilot_account_choices.py b/tests/unit/test_copilot_account_choices.pyindex 3910874a5..16c290bce 100644--- a/tests/unit/test_copilot_account_choices.py+++ b/tests/unit/test_copilot_account_choices.py@@ -1,13 +1,18 @@from __future__ import annotations+import asyncio+from collections.abc import Callablefrom datetime import datetimefrom types import SimpleNamespace-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, MagicMock+import httpximport pytest+from skyvern.forge import appfrom skyvern.forge.sdk.copilot import agent as agent_modulefrom skyvern.forge.sdk.copilot import request_policy as request_policy_module+from skyvern.forge.sdk.copilot import tools as tools_modulefrom skyvern.forge.sdk.copilot.context import (ApprovedCredential,CopilotContext,@@ -25,6 +30,7 @@ from skyvern.forge.sdk.copilot.tools.credentials import (_parsed_workflow_definition,_retire_stale_google_connection_denial,canonicalize_named_google_sheet_bindings,+ resolve_google_sheet_tabs_from_gid,)from skyvern.forge.sdk.copilot.turn_outcome import (connected_account_choice_context,@@ -42,6 +48,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (WorkflowCopilotChatRequest,WorkflowCopilotChatSender,)+from skyvern.utils.yaml_loader import safe_load_no_datesfrom tests.unit.copilot_test_helpers import make_copilot_ctx@@ -1569,3 +1576,206 @@ def test_retiring_a_stale_google_denial_never_widens_the_run_approved_ids() -> Nassert ctx.connected_account_recovery_choices == []assert policy.run_approved_google_connection_ids == []assert _approved_run_credential_ids(policy) == set()+++SPREADSHEET_ID = "1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"+ENGINEERING_GID = 1226505961+RECORDED_TABS_PAYLOAD = {+ "sheets": [+ {"properties": {"sheetId": 0, "title": "Sheet1", "index": 0}},+ {"properties": {"sheetId": ENGINEERING_GID, "title": "Engineering", "index": 1}},+ ]+}+++def _gid_sheets_yaml(block_type: str, url: str, extra: str = "") -> str:+ return (+ "workflow_definition:\n"+ " blocks:\n"+ " - label: engineering_rows\n"+ f" block_type: {block_type}\n"+ f" spreadsheet_url: {url}\n"+ f" credential_id: {CITED_ACCOUNT_ID}\n"+ f"{extra}"+ )+++def _gid_turn_policy() -> request_policy_module.RequestPolicy:+ return request_policy_module.RequestPolicy(+ canonical_user_message=f"append the total to the sheet using the {CITED_ACCOUNT_NAME}"+ )+++def _saved_sheets_block(workflow_yaml: str) -> dict[str, object]:+ return safe_load_no_dates(workflow_yaml)["workflow_definition"]["blocks"][0]+++def recorded_sheets_tabs(+ monkeypatch: pytest.MonkeyPatch,+ mock_sheets_transport: Callable[[Callable[[httpx.Request], httpx.Response]], None],+) -> list[httpx.Request]:+ requests: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return httpx.Response(200, json=RECORDED_TABS_PAYLOAD)++ mock_sheets_transport(handler)+ connections = [_google(CITED_ACCOUNT_ID, CITED_ACCOUNT_NAME)]+ _patch_visible_credentials(monkeypatch, connections)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools.credentials.google_oauth_service.get_credentials_for_org",+ AsyncMock(return_value=connections),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_google_sheets_credentials", AsyncMock(return_value="sheets-token"))+ return requests++[email protected]("block_type", ["google_sheets_read", "google_sheets_write"])[email protected]("gid_suffix", [f"/edit#gid={ENGINEERING_GID}", f"/edit?gid={ENGINEERING_GID}"])+async def test_update_workflow_saves_the_tab_named_by_the_url_gid(+ monkeypatch: pytest.MonkeyPatch,+ recorded_sheets_tabs: list[httpx.Request],+ block_type: str,+ gid_suffix: str,+) -> None:+ ctx = make_copilot_ctx(request_policy=_gid_turn_policy())+ process_workflow_yaml = AsyncMock(return_value=MagicMock())+ 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()),+ )+ url = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}{gid_suffix}"++ result = await tools_module._update_workflow(+ {"workflow_yaml": _gid_sheets_yaml(block_type, url, " range: D:D\n")}, ctx+ )++ assert result["ok"] is True, result+ assert [(fact["status"], fact.get("sheet_name")) for fact in result["data"]["google_sheet_tab_resolution"]] == [+ ("resolved", "Engineering")+ ]+ saved = _saved_sheets_block(process_workflow_yaml.await_args.kwargs["workflow_yaml"])+ assert (saved["sheet_name"], saved["range"], saved["spreadsheet_url"]) == ("Engineering", "D:D", url)+ assert _saved_sheets_block(ctx.staged_workflow_yaml)["sheet_name"] == "Engineering"+ assert [request.url.path for request in recorded_sheets_tabs] == [f"/v4/spreadsheets/{SPREADSHEET_ID}"]+++ ("gid", "extra", "expected_fact", "expected_sheet_name"),+ [+ (ENGINEERING_GID, " sheet_name: Summary\n", None, "Summary"),+ (+ 987654321,+ "",+ {"status": "gid_not_found", "available_tabs": ["Sheet1", "Engineering"]},+ None,+ ),+ (+ ENGINEERING_GID,+ " range: \"'Sheet1'!D:D\"\n",+ {"status": "ineligible", "reason": "range_not_plain_cells"},+ None,+ ),+ (+ ENGINEERING_GID,+ ' range: "{{ destination_range }}"\n',+ {"status": "ineligible", "reason": "range_not_plain_cells"},+ None,+ ),+ (+ ENGINEERING_GID,+ " range: MyNamedRange\n",+ {"status": "ineligible", "reason": "range_not_plain_cells"},+ None,+ ),+ (+ ENGINEERING_GID,+ " range: TAX\n",+ {"status": "ineligible", "reason": "range_not_plain_cells"},+ None,+ ),+ ],+ ids=[+ "explicit_sheet_name",+ "gid_absent_from_tabs",+ "range_names_a_sheet",+ "templated_range",+ "named_range",+ "short_uppercase_named_range",+ ],+)+async def test_gid_resolution_never_overwrites_or_guesses_a_tab(+ recorded_sheets_tabs: list[httpx.Request],+ gid: int,+ extra: str,+ expected_fact: dict[str, object] | None,+ expected_sheet_name: str | None,+) -> None:+ url = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit#gid={gid}"+ draft = _gid_sheets_yaml("google_sheets_write", url, extra)++ resolved_yaml, facts = await resolve_google_sheet_tabs_from_gid(+ draft, make_copilot_ctx(workflow_yaml=draft, request_policy=_gid_turn_policy())+ )++ assert resolved_yaml == draft+ assert _saved_sheets_block(resolved_yaml).get("sheet_name") == expected_sheet_name+ if expected_fact is None:+ assert facts == []+ else:+ assert [{key: fact.get(key) for key in expected_fact} for fact in facts] == [expected_fact]+ assert facts[0]["resolved"] is False+++async def test_gid_resolution_reads_no_tabs_through_a_connection_this_turn_did_not_approve(+ recorded_sheets_tabs: list[httpx.Request],+) -> None:+ url = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit#gid={ENGINEERING_GID}"+ draft = _gid_sheets_yaml("google_sheets_write", url)+ ctx = make_copilot_ctx(+ workflow_yaml=draft,+ request_policy=request_policy_module.RequestPolicy(canonical_user_message="append the total to the sheet"),+ )++ resolved_yaml, facts = await resolve_google_sheet_tabs_from_gid(draft, ctx)++ assert resolved_yaml == draft+ assert [(fact["status"], fact.get("reason"), "available_tabs" in fact) for fact in facts] == [+ ("ineligible", "connection_not_approved", False)+ ]+ assert recorded_sheets_tabs == []+++async def test_gid_resolution_bounds_a_hung_tab_lookup_once_per_spreadsheet(+ monkeypatch: pytest.MonkeyPatch,+ recorded_sheets_tabs: list[httpx.Request],+) -> None:+ lookups: list[str] = []++ async def hung_token(organization_id: str, credential_id: str) -> str:+ lookups.append(credential_id)+ await asyncio.Event().wait()+ return "never"++ monkeypatch.setattr(app.AGENT_FUNCTION, "get_google_sheets_credentials", hung_token)+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.credentials._GID_TAB_LOOKUP_TIMEOUT_SECONDS", 0.05)+ url = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit#gid={ENGINEERING_GID}"+ block = _gid_sheets_yaml("google_sheets_write", url).split(" blocks:\n", 1)[1]+ draft = "workflow_definition:\n blocks:\n" + block + block.replace("engineering_rows", "engineering_copy")++ _, facts = await asyncio.wait_for(+ resolve_google_sheet_tabs_from_gid(+ draft, make_copilot_ctx(workflow_yaml=draft, request_policy=_gid_turn_policy())+ ),+ timeout=2,+ )++ assert [fact["status"] for fact in facts] == ["lookup_failed", "lookup_failed"]+ assert lookups == [CITED_ACCOUNT_ID]diff --git a/tests/unit/test_copilot_workflow_update.py b/tests/unit/test_copilot_workflow_update.pyindex 057d3354f..eb2aaf10e 100644--- a/tests/unit/test_copilot_workflow_update.py+++ b/tests/unit/test_copilot_workflow_update.py@@ -350,6 +350,15 @@ async def test_combined_tool_result_carries_staging_without_overwriting_its_run_assert skipped["persistence_message"] == update_result["data"]["persistence_message"]+def test_combined_tool_result_carries_sheet_tab_resolution() -> None:+ fact = {"label": "append", "gid": 7, "resolved": False, "status": "gid_not_found", "available_tabs": ["Sheet1"]}+ update_result = {"ok": True, "data": {"google_sheet_tab_resolution": [fact]}}++ carried = carry_author_time_findings(update_result, {"ok": True, "data": {"message": "Ran 1 block."}})++ assert carried["data"]["google_sheet_tab_resolution"] == [fact]++_SAVE_CLAIM_PHRASES = ("updated successfully", "has been saved", "saved the workflow", "workflow was saved")