Skip to content

Automate browser based workflows with AI

fix: auto-expand iterations/conditionals containing active item (#4923)

Suchintan5317e9c72f9a
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
index 39187121d..6ff9702b3 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
@@ -6,7 +6,7 @@ import {
CubeIcon,
ExternalLinkIcon,
} from "@radix-ui/react-icons";
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Status } from "@/api/types";
@@ -124,6 +124,50 @@ function getLoopIterationGroups(
});
}
+/**
+ * Check whether any block, action, or thought within `items` (recursively)
+ * matches the currently-active element. Uses an iterative stack to avoid
+ * deep nesting — same pattern as `findActiveItem` in workflowTimelineUtils.
+ */
+function timelineItemsContainActiveElement(
+ items: Array<WorkflowRunTimelineItem>,
+ activeItem: WorkflowRunOverviewActiveElement,
+): boolean {
+ if (activeItem === null || activeItem === "stream") return false;
+
+ const stack = [...items];
+ while (stack.length > 0) {
+ const item = stack.pop()!;
+
+ if (
+ isBlockItem(item) &&
+ isWorkflowRunBlock(activeItem) &&
+ item.block.workflow_run_block_id === activeItem.workflow_run_block_id
+ ) {
+ return true;
+ }
+
+ if (
+ isBlockItem(item) &&
+ isAction(activeItem) &&
+ item.block.actions?.some((a) => a.action_id === activeItem.action_id)
+ ) {
+ return true;
+ }
+
+ if (
+ isThoughtItem(item) &&
+ isObserverThought(activeItem) &&
+ item.thought.thought_id === activeItem.thought_id
+ ) {
+ return true;
+ }
+
+ stack.push(...item.children);
+ }
+ return false;
+}
+
type TimelineSubItemsProps = {
items: Array<WorkflowRunTimelineItem>;
activeItem: WorkflowRunOverviewActiveElement;
@@ -248,6 +292,63 @@ function WorkflowRunTimelineBlockItem({
[subItems],
);
+ // Track which loop iteration groups are expanded (controlled state).
+ // Initialise with the most-recent group (index 0) plus any group that
+ // contains the currently-active element so it is visible on first render.
+ const [openLoopGroups, setOpenLoopGroups] = useState<Set<number>>(() => {
+ const initial = new Set<number>();
+ if (loopIterationGroups.length > 0) {
+ initial.add(0);
+ }
+ loopIterationGroups.forEach((group, idx) => {
+ if (timelineItemsContainActiveElement(group.items, activeItem)) {
+ initial.add(idx);
+ }
+ });
+ return initial;
+ });
+
+ // When the active element changes (or loop groups load for the first time),
+ // auto-expand the group that contains it. Also ensure the most-recent group
+ // (index 0) is open — this covers the edge case where subItems loads after
+ // the initial mount so the useState initializer missed it.
+ useEffect(() => {
+ setOpenLoopGroups((prev) => {
+ let next = prev;
+ // Ensure most-recent group is open (covers late-loading data).
+ if (loopIterationGroups.length > 0 && !prev.has(0)) {
+ next = new Set(next);
+ next.add(0);
+ }
+ // Find and expand the group containing the active item.
+ for (let idx = 0; idx < loopIterationGroups.length; idx++) {
+ const group = loopIterationGroups[idx];
+ if (
+ group &&
+ timelineItemsContainActiveElement(group.items, activeItem)
+ ) {
+ if (!next.has(idx)) {
+ if (next === prev) next = new Set(next);
+ next.add(idx);
+ }
+ break; // active item can only be in one group
+ }
+ }
+ return next;
+ });
+ }, [activeItem, loopIterationGroups]);
+
+ // Auto-expand conditional children when the active element is inside them.
+ useEffect(() => {
+ if (
+ isConditionalBlock &&
+ hasNestedChildren &&
+ timelineItemsContainActiveElement(subItems, activeItem)
+ ) {
+ setChildrenOpen(true);
+ }
+ }, [activeItem, isConditionalBlock, hasNestedChildren, subItems]);
+
const loopValues = Array.isArray(block.loop_values) ? block.loop_values : [];
return (
@@ -504,7 +605,18 @@ function WorkflowRunTimelineBlockItem({
return (
<Collapsible
key={`${group.index ?? "unknown"}-${groupIndex}`}
- defaultOpen={groupIndex === 0}
+ open={openLoopGroups.has(groupIndex)}
+ onOpenChange={(open) => {
+ setOpenLoopGroups((prev) => {
+ const next = new Set(prev);
+ if (open) {
+ next.add(groupIndex);
+ } else {
+ next.delete(groupIndex);
+ }
+ return next;
+ });
+ }}
>
<div className="rounded border border-slate-700 bg-slate-elevation4">
<CollapsibleTrigger asChild>
diff --git a/tests/unit/workflow/test_cache_key_domain.py b/tests/unit/workflow/test_cache_key_domain.py
new file mode 100644
index 000000000..b0300a568
--- /dev/null
+++ b/tests/unit/workflow/test_cache_key_domain.py
@@ -0,0 +1,96 @@
+"""Tests for automatic domain-based cache key enrichment."""
+
+from datetime import datetime, timezone
+
+from skyvern.forge.sdk.workflow.models.block import BlockType, TaskBlock
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
+from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinition
+from skyvern.services.workflow_script_service import _extract_first_block_domain, _jinja_domain_filter
+
+
+def _output_param(key: str = "out") -> OutputParameter:
+ return OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key=key,
+ description="",
+ output_parameter_id="op_test",
+ workflow_id="w_test",
+ created_at=datetime.now(timezone.utc),
+ modified_at=datetime.now(timezone.utc),
+ )
+
+
+def _task_block(label: str, url: str | None = None) -> TaskBlock:
+ return TaskBlock(
+ label=label,
+ block_type=BlockType.TASK,
+ output_parameter=_output_param(f"{label}_out"),
+ url=url,
+ title="Test",
+ navigation_goal="Do something",
+ )
+
+
+def _workflow(blocks: list, cache_key: str = "default") -> Workflow:
+ return Workflow(
+ workflow_id="w_test",
+ organization_id="o_test",
+ title="Test Workflow",
+ workflow_permanent_id="wpid_test",
+ version=1,
+ is_saved_task=False,
+ workflow_definition=WorkflowDefinition(blocks=blocks, parameters=[]),
+ cache_key=cache_key,
+ created_at=datetime.now(timezone.utc),
+ modified_at=datetime.now(timezone.utc),
+ )
+
+
+class TestJinjaDomainFilter:
+ def test_extracts_domain_from_url(self) -> None:
+ assert _jinja_domain_filter("https://www.fanr.gov.ae/en/Documents") == "www.fanr.gov.ae"
+
+ def test_extracts_domain_with_port(self) -> None:
+ assert _jinja_domain_filter("https://example.com:8080/path") == "example.com:8080"
+
+ def test_returns_input_for_non_url(self) -> None:
+ assert _jinja_domain_filter("not-a-url") == "not-a-url"
+
+ def test_returns_input_for_empty_string(self) -> None:
+ assert _jinja_domain_filter("") == ""
+
+
+class TestExtractFirstBlockDomain:
+ def test_extracts_domain_from_first_block_with_url(self) -> None:
+ blocks = [_task_block("step1", url="https://www.fanr.gov.ae/documents")]
+ wf = _workflow(blocks)
+ assert _extract_first_block_domain(wf, {}) == "www.fanr.gov.ae"
+
+ def test_skips_blocks_without_url(self) -> None:
+ blocks = [
+ _task_block("step1", url=None),
+ _task_block("step2", url="https://search.gov.hk/results"),
+ ]
+ wf = _workflow(blocks)
+ assert _extract_first_block_domain(wf, {}) == "search.gov.hk"
+
+ def test_renders_jinja_template_url(self) -> None:
+ blocks = [_task_block("step1", url="{{ target_url }}")]
+ wf = _workflow(blocks)
+ params = {"target_url": "https://www.irs.gov/apply-ein"}
+ assert _extract_first_block_domain(wf, params) == "www.irs.gov"
+
+ def test_returns_empty_when_no_blocks_have_url(self) -> None:
+ blocks = [_task_block("step1", url=None)]
+ wf = _workflow(blocks)
+ assert _extract_first_block_domain(wf, {}) == ""
+
+ def test_returns_empty_for_empty_blocks(self) -> None:
+ wf = _workflow([])
+ assert _extract_first_block_domain(wf, {}) == ""
+
+ def test_handles_unresolvable_template_gracefully(self) -> None:
+ blocks = [_task_block("step1", url="{{ missing_param }}")]
+ wf = _workflow(blocks)
+ # Jinja renders undefined variables as empty string in SandboxedEnvironment
+ assert _extract_first_block_domain(wf, {}) == ""