kaxil commented on code in PR #76309:
URL: https://github.com/apache/airflow/pull/76309#discussion_r4473322338


##########
providers/common/ai/src/airflow/providers/common/ai/toolsets/skills.py:
##########
@@ -50,9 +58,53 @@
     from collections.abc import Callable, Sequence
 
     from pydantic_ai._run_context import RunContext
-    from pydantic_ai.messages import InstructionPart
+    from pydantic_ai.messages import InstructionPart, ModelMessage
     from pydantic_ai.toolsets.abstract import ToolsetTool
 
+log = logging.getLogger(__name__)
+
+# The pydantic-ai-skills tools that act on one skill, named by their 
``skill_name`` argument.
+_PER_SKILL_TOOLS = frozenset({"load_skill", "read_skill_resource", 
"run_skill_script"})
+
+
+def _describe_skill_source(skill_uri: str, locations: list[_SkillsLocation]) 
-> dict[str, Any]:
+    """Name where a discovered skill came from: its local path, or its 
repository, path and commit."""
+    skill_dir = os.path.realpath(skill_uri)
+    # Nested sources can both contain the skill; the deepest one is where it 
came from.
+    owner, owner_root = None, ""
+    for location in locations:
+        root = os.path.realpath(location.directory)
+        if os.path.commonpath([skill_dir, root]) == root and len(root) > 
len(owner_root):
+            owner, owner_root = location, root
+    if owner is None or owner.git is None:
+        return {"path": skill_dir}
+    return {
+        # GitSkills rejects a repo_url carrying credentials, so it is safe to 
publish.
+        "repo_url": owner.git.repo_url,
+        "path": PurePosixPath(owner.git.path, 
Path(skill_dir).relative_to(owner_root).as_posix()).as_posix(),
+        "branch": owner.git.branch,
+        "commit": owner.commit,
+    }
+
+
+def _count_skill_calls(messages: Sequence[ModelMessage]) -> defaultdict[str, 
Counter[str]]:
+    """Count, per skill, the calls to each per-skill tool that returned a 
result."""
+    calls: dict[str, ToolCallPart] = {}
+    counts: defaultdict[str, Counter[str]] = defaultdict(Counter)
+    for message in messages:
+        for part in message.parts:
+            if isinstance(part, ToolCallPart):
+                calls[part.tool_call_id] = part
+            elif isinstance(part, ToolReturnPart) and (call := 
calls.get(part.tool_call_id)):

Review Comment:
   This counts every `ToolReturnPart`, but its `outcome` can also be 
`'denied'`, `'failed'` or `'interrupted'`. A reviewer who denies a 
`run_skill_script` still gets `run_skill_script ×1` in the tab for a script 
that never ran, and a durable retry after a crash mid-script counts it twice. 
Should this only count `outcome == "success"`?



##########
providers/common/ai/src/airflow/providers/common/ai/plugins/www/src/components/ModelPanel.tsx:
##########
@@ -141,6 +142,8 @@ export const ModelPanel: FC<ModelPanelProps> = ({ dagId, 
runId, taskId, mapIndex
           <StatBox label="Cost" tooltip={COST_TOOLTIP} 
value={formatCost(usage.cost)} />
         </SimpleGrid>
       )}
+
+      {skills && skills.length > 0 && <SkillsSection skills={skills} />}

Review Comment:
   When the toolset finds no skills (a typo in `GitSkills.path`, for example) 
it pushes `[]`, and this hides the section, so the tab looks the same as a run 
without the toolset. Could an empty list render the section with a "no skills 
found" line instead? That's the run someone opens this tab to debug.



##########
providers/common/ai/src/airflow/providers/common/ai/toolsets/skills.py:
##########
@@ -164,6 +222,36 @@ async def __aexit__(self, *args: Any) -> bool | None:
             self._inner = None
             self._cleanup = None
 
+    def _push_skills_xcom(self) -> None:
+        """Publish the skills offered to the agent and the skill tools it 
called, for the AI Model tab."""
+        try:
+            context = get_current_context()
+        except RuntimeError:
+            # Used outside an Airflow task: there is no task instance to 
publish on.
+            return
+        if not context["ti"].task.do_xcom_push:
+            return
+        # Telemetry only: a failure here must not fail the run or skip the 
clean-up after it.
+        try:
+            counts = _count_skill_calls(self._messages)

Review Comment:
   `self._messages` also includes a `message_history` seeded from an earlier 
task, so a skill that task loaded shows as loaded here, next to this task's 
clone commit. Same after an approval pause if the branch moved before the 
resumed run cloned again. Is that intended? It cuts against tracing a behaviour 
change to a specific commit.



##########
providers/common/ai/src/airflow/providers/common/ai/toolsets/skills.py:
##########
@@ -156,6 +213,7 @@ async def __aenter__(self) -> AgentSkillsToolset:
     async def __aexit__(self, *args: Any) -> bool | None:
         try:
             if self._inner is not None:
+                self._push_skills_xcom()

Review Comment:
   When the run is wrapped in `async with agent:` (say a plain `@task` keeping 
MCP servers open), the agent also enters this original instance, not just the 
`for_run` copy. It never sees `get_tools`, so it exits last with `_messages == 
()` and its push overwrites the real counts with `calls: {}`. Could this only 
push from an instance that actually served a run, e.g. a flag set in 
`get_tools`?



##########
providers/common/ai/src/airflow/providers/common/ai/plugins/www/src/skill-source.ts:
##########
@@ -0,0 +1,54 @@
+/*!
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { SkillSource } from "src/types/model";
+
+/** An HTTPS or SSH Git remote, split into its host and repository path. */
+const GIT_REMOTE = 
/^(?:https:\/\/|ssh:\/\/git@|git@)([^/:]+)[/:](.+?)(?:\.git)?\/?$/;

Review Comment:
   `[/:]` takes a port's colon as the path separator, so 
`https://gitlab.corp.com:8443/team/skills.git` shows as 
`gitlab.corp.com/8443/team/skills` and the link 404s. Also, `GitSkills` rejects 
a URL with a username, so the `ssh://git@` branch never matches a published 
URL, while `ssh://gitlab.corp.com/team/skills.git` gets no link. Parsing 
`https://` and `ssh://` with `new URL()` (keeping `url.host`) and using the 
regex only for `git@host:path` would cover both and drop the `host!` assertions.



##########
providers/common/ai/docs/observability.rst:
##########
@@ -105,7 +109,8 @@ How it works
 
   **Model tab.** Separately from tracing, the provider adds an "AI Model" tab 
to the
   task-instance page showing the resolved model name and the ``usage`` XCom 
above as a
-  readable table, including an estimated cost. It needs Airflow >= 3.4, since 
it relies on
+  readable table, including an estimated cost, and the skills XCom above as 
the list of

Review Comment:
   The external XCom storage caveat further down covers the model badge and 
`usage` but not this. With an offloaded value `fetchSkills` gets a string and 
the skills section just disappears. Worth adding a clause there?



##########
providers/common/ai/src/airflow/providers/common/ai/plugins/www/src/components/SkillsSection.tsx:
##########
@@ -0,0 +1,94 @@
+/*!
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { Badge, Box, HStack, Heading, Link, Stack, Text } from 
"@chakra-ui/react";
+import type { FC } from "react";
+
+import { Tooltip } from "src/components/Tooltip";
+import { describeSkillSource, isLoaded } from "src/skill-source";
+import type { SkillInfo } from "src/types/model";
+
+const SkillSourceText: FC<{ skill: SkillInfo }> = ({ skill }) => {
+  const { location, path, commit, href } = describeSkillSource(skill.source);
+  const text = [location, path, commit].filter((part) => part !== 
undefined).join(" · ");
+
+  return href === undefined ? (
+    <Text color="fg.muted" fontFamily="mono" fontSize="xs" 
wordBreak="break-all">
+      {text}
+    </Text>
+  ) : (
+    <Link color="fg.muted" fontFamily="mono" fontSize="xs" href={href} 
rel="noreferrer" target="_blank">
+      {text}
+    </Link>
+  );
+};
+
+export const SkillsSection: FC<{ skills: SkillInfo[] }> = ({ skills }) => {
+  // Loaded skills first: they are what the run actually used.
+  const ordered = [...skills].sort((a, b) => Number(isLoaded(b.calls)) - 
Number(isLoaded(a.calls)));
+  const loadedCount = skills.filter((skill) => isLoaded(skill.calls)).length;
+
+  return (
+    <Box data-testid="skills-section" maxW="960px" mt={6}>
+      <HStack gap={2} mb={3}>
+        <Heading size="sm">Skills</Heading>
+        <Text color="fg.muted" fontSize="sm">
+          {loadedCount} of {skills.length} loaded
+        </Text>
+      </HStack>
+      <Stack gap={2}>
+        {ordered.map((skill) => {
+          const loaded = isLoaded(skill.calls);
+          const calls = Object.entries(skill.calls);
+
+          return (
+            <HStack align="center" gap={3} key={skill.name}>
+              <Tooltip
+                content={
+                  <Stack gap={1}>
+                    {skill.description ? <Text>{skill.description}</Text> : 
undefined}
+                    <Text>
+                      {calls.length === 0
+                        ? "Available, not used"
+                        : calls.map(([tool, count]) => `${tool} 
×${count}`).join(" · ")}
+                    </Text>
+                  </Stack>
+                }
+                portalled
+              >
+                <Badge

Review Comment:
   The `Badge` is a `span` that can't take focus, so the description and call 
counts are mouse-only. `StatBox` in `ModelPanel.tsx` wraps its tooltip trigger 
in `as="button"` with an `aria-label`; can this do the same?



##########
providers/common/ai/src/airflow/providers/common/ai/skills.py:
##########
@@ -162,6 +171,7 @@ def _clone_git(source: GitSkills) -> tuple[str, str]:
         # Strip any embedded credential from .git/config so a skill script in 
the
         # checkout cannot read it back out of the temporary clone.
         repo.remote("origin").set_url(source.repo_url)
+        commit = repo.head.commit.hexsha

Review Comment:
   On a repo with no commits yet, `repo.head.commit` raises `ValueError`, and 
the `except` below reports it as `Failed to clone ...` even though the clone 
worked. `repo.head.commit.hexsha if repo.head.is_valid() else None` would keep 
that case from failing the task.



##########
providers/common/ai/tests/unit/common/ai/toolsets/test_skills.py:
##########
@@ -250,3 +253,195 @@ def 
test_unsupported_installed_version_names_version_and_range(self, tmp_path):
 async def _enter_exit(toolset):
     await toolset.__aenter__()
     await toolset.__aexit__(None, None, None)
+
+
+def _calling(*tool_calls):
+    """A model that makes each (tool, args) call in turn, then answers 
"done"."""
+    calls = iter(tool_calls)
+
+    def model(messages, info):
+        if (call := next(calls, None)) is None:
+            return ModelResponse(parts=[TextPart("done")])
+        return ModelResponse(parts=[ToolCallPart(*call)])
+
+    return FunctionModel(model)
+
+
+_GET_CONTEXT = 
"airflow.providers.common.ai.toolsets.skills.get_current_context"
+
+
+class _FakeTaskInstance:
+    """Keeps what is pushed, so a later pull in the same task instance reads 
it back."""
+
+    task_id = "agent"
+    map_index = -1
+
+    def __init__(self, stored=None):
+        self.task = types.SimpleNamespace(do_xcom_push=True)
+        self.xcoms = {} if stored is None else {SKILLS_XCOM_KEY: stored}
+
+    def xcom_pull(self, key, task_ids, map_indexes):
+        assert (task_ids, map_indexes) == (self.task_id, self.map_index)
+        return self.xcoms.get(key)
+
+    def xcom_push(self, key, value):
+        self.xcoms[key] = value
+
+
+def _skill_entry(name, path, calls):
+    return {
+        "name": name,
+        "description": f"A {name} skill for tests.",
+        "source": {"path": os.path.realpath(path)},
+        "calls": calls,
+    }
+
+
+class TestSkillsXCom:
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_pushes_available_skills_and_the_calls_made_for_each(self, 
mock_get_context, tmp_path):
+        alpha = _write_skill(tmp_path, "alpha")
+        (alpha / "notes.md").write_text("notes")
+        beta = _write_skill(tmp_path, "beta")
+        ti = _FakeTaskInstance()
+        mock_get_context.return_value = {"ti": ti}
+        model = _calling(
+            ("load_skill", {"skill_name": "alpha"}),
+            ("read_skill_resource", {"skill_name": "alpha", "resource_name": 
"notes.md"}),
+            # Not a skill: the failed lookup is not counted against any skill.
+            ("load_skill", {"skill_name": "missing"}),
+        )
+
+        Agent(model, 
toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])]).run_sync("go")
+
+        assert ti.xcoms[SKILLS_XCOM_KEY] == [
+            _skill_entry("alpha", alpha, {"load_skill": 1, 
"read_skill_resource": 1}),
+            _skill_entry("beta", beta, {}),
+        ]
+
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_counts_calls_from_the_message_history(self, mock_get_context, 
tmp_path):
+        # A run resumed after an approval pause or replayed on a durable retry 
starts in a new
+        # process, with its earlier calls given back as history rather than 
run again.
+        alpha = _write_skill(tmp_path, "alpha")
+        ti = _FakeTaskInstance()
+        mock_get_context.return_value = {"ti": ti}
+        earlier = Agent(
+            _calling(("load_skill", {"skill_name": "alpha"})),
+            toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])],
+        ).run_sync("go")
+
+        Agent(
+            _calling(("load_skill", {"skill_name": "alpha"})),
+            toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])],
+        ).run_sync("go on", message_history=earlier.all_messages())
+
+        assert ti.xcoms[SKILLS_XCOM_KEY] == [_skill_entry("alpha", alpha, 
{"load_skill": 2})]
+
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_replaces_its_own_stored_skills_and_keeps_the_others(self, 
mock_get_context, tmp_path):
+        alpha = _write_skill(tmp_path, "alpha")
+        other = _skill_entry("other", tmp_path / "elsewhere", {"load_skill": 
3})
+        ti = _FakeTaskInstance(stored=[_skill_entry("alpha", alpha, 
{"load_skill": 1}), other])
+        mock_get_context.return_value = {"ti": ti}
+
+        Agent(_calling(), 
toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])]).run_sync("go")
+
+        assert ti.xcoms[SKILLS_XCOM_KEY] == [_skill_entry("alpha", alpha, {}), 
other]
+
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_two_prefixed_toolsets_each_count_their_own_skills(self, 
mock_get_context, tmp_path):
+        alpha = _write_skill(tmp_path / "one", "alpha")
+        beta = _write_skill(tmp_path / "two", "beta")
+        ti = _FakeTaskInstance()
+        mock_get_context.return_value = {"ti": ti}
+        toolsets = [
+            AgentSkillsToolset(sources=[str(tmp_path / 
"one")]).prefixed("one"),
+            AgentSkillsToolset(sources=[str(tmp_path / 
"two")]).prefixed("two"),
+        ]
+        model = _calling(
+            ("one_load_skill", {"skill_name": "alpha"}),
+            ("two_load_skill", {"skill_name": "beta"}),
+        )
+
+        Agent(model, toolsets=toolsets).run_sync("go")
+
+        assert ti.xcoms[SKILLS_XCOM_KEY] == [
+            _skill_entry("alpha", alpha, {"load_skill": 1}),
+            _skill_entry("beta", beta, {"load_skill": 1}),
+        ]
+
+    @pytest.mark.parametrize(
+        "context",
+        [
+            pytest.param(RuntimeError("no task"), id="outside_a_task"),
+            pytest.param({"ti": MagicMock(**{"task.do_xcom_push": False})}, 
id="do_xcom_push_off"),
+        ],
+    )
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_nothing_pushed_without_a_task_that_pushes_xcom(self, 
mock_get_context, tmp_path, context):
+        _write_skill(tmp_path, "alpha")
+        if isinstance(context, Exception):
+            mock_get_context.side_effect = context
+        else:
+            mock_get_context.return_value = context
+        model = _calling(("load_skill", {"skill_name": "alpha"}))
+
+        assert (
+            Agent(model, 
toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])]).run_sync("go").output
+            == "done"
+        )
+        if not isinstance(context, Exception):
+            context["ti"].xcom_push.assert_not_called()
+
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_failed_push_does_not_fail_the_run_or_skip_cleanup(self, 
mock_get_context, tmp_path):
+        _write_skill(tmp_path, "alpha")
+        ti = MagicMock()
+        ti.task.do_xcom_push = True
+        ti.xcom_pull.return_value = None
+        ti.xcom_push.side_effect = RuntimeError("xcom backend down")
+        mock_get_context.return_value = {"ti": ti}
+        cleanup = MagicMock()
+        toolset = AgentSkillsToolset(sources=[str(tmp_path)])
+
+        with patch(
+            "airflow.providers.common.ai.toolsets.skills._materialize_skills",
+            return_value=([_SkillsLocation(str(tmp_path))], cleanup),
+        ):
+            result = Agent(_calling(), toolsets=[toolset]).run_sync("go")
+
+        assert result.output == "done"
+        cleanup.assert_called_once()
+
+
+class TestDescribeSkillSource:
+    @pytest.mark.parametrize(
+        ("repo_path", "expected_path"),
+        [
+            pytest.param("skills", "skills/alpha", id="sub_path"),
+            pytest.param("", "alpha", id="repo_root"),
+        ],
+    )
+    def test_git_skill_names_repository_path_and_commit(self, tmp_path, 
repo_path, expected_path):
+        skills_dir = tmp_path / "clone" / repo_path
+        skill_dir = _write_skill(skills_dir, "alpha")
+        source = GitSkills(repo_url="https://github.com/org/repo";, 
path=repo_path, branch="main")
+        locations = [_SkillsLocation(str(skills_dir), git=source, 
commit="0123abc")]
+
+        assert _describe_skill_source(str(skill_dir), locations) == {
+            "repo_url": "https://github.com/org/repo";,
+            "path": expected_path,
+            "branch": "main",
+            "commit": "0123abc",
+        }
+
+    def test_nested_source_wins_over_the_one_containing_it(self, tmp_path):
+        skill_dir = _write_skill(tmp_path / "clone", "alpha")
+        source = GitSkills(repo_url="https://github.com/org/repo";)
+        locations = [
+            _SkillsLocation(str(tmp_path)),

Review Comment:
   With the containing location listed first, "last match wins" passes too, so 
dropping the `len(root) > len(owner_root)` check keeps this green. Can it also 
cover the reverse order?



##########
providers/common/ai/tests/unit/common/ai/toolsets/test_skills.py:
##########
@@ -250,3 +253,195 @@ def 
test_unsupported_installed_version_names_version_and_range(self, tmp_path):
 async def _enter_exit(toolset):
     await toolset.__aenter__()
     await toolset.__aexit__(None, None, None)
+
+
+def _calling(*tool_calls):
+    """A model that makes each (tool, args) call in turn, then answers 
"done"."""
+    calls = iter(tool_calls)
+
+    def model(messages, info):
+        if (call := next(calls, None)) is None:
+            return ModelResponse(parts=[TextPart("done")])
+        return ModelResponse(parts=[ToolCallPart(*call)])
+
+    return FunctionModel(model)
+
+
+_GET_CONTEXT = 
"airflow.providers.common.ai.toolsets.skills.get_current_context"
+
+
+class _FakeTaskInstance:
+    """Keeps what is pushed, so a later pull in the same task instance reads 
it back."""
+
+    task_id = "agent"
+    map_index = -1
+
+    def __init__(self, stored=None):
+        self.task = types.SimpleNamespace(do_xcom_push=True)
+        self.xcoms = {} if stored is None else {SKILLS_XCOM_KEY: stored}
+
+    def xcom_pull(self, key, task_ids, map_indexes):
+        assert (task_ids, map_indexes) == (self.task_id, self.map_index)
+        return self.xcoms.get(key)
+
+    def xcom_push(self, key, value):
+        self.xcoms[key] = value
+
+
+def _skill_entry(name, path, calls):
+    return {
+        "name": name,
+        "description": f"A {name} skill for tests.",
+        "source": {"path": os.path.realpath(path)},
+        "calls": calls,
+    }
+
+
+class TestSkillsXCom:
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_pushes_available_skills_and_the_calls_made_for_each(self, 
mock_get_context, tmp_path):
+        alpha = _write_skill(tmp_path, "alpha")
+        (alpha / "notes.md").write_text("notes")
+        beta = _write_skill(tmp_path, "beta")
+        ti = _FakeTaskInstance()
+        mock_get_context.return_value = {"ti": ti}
+        model = _calling(
+            ("load_skill", {"skill_name": "alpha"}),
+            ("read_skill_resource", {"skill_name": "alpha", "resource_name": 
"notes.md"}),
+            # Not a skill: the failed lookup is not counted against any skill.
+            ("load_skill", {"skill_name": "missing"}),
+        )
+
+        Agent(model, 
toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])]).run_sync("go")
+
+        assert ti.xcoms[SKILLS_XCOM_KEY] == [
+            _skill_entry("alpha", alpha, {"load_skill": 1, 
"read_skill_resource": 1}),
+            _skill_entry("beta", beta, {}),
+        ]
+
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_counts_calls_from_the_message_history(self, mock_get_context, 
tmp_path):
+        # A run resumed after an approval pause or replayed on a durable retry 
starts in a new
+        # process, with its earlier calls given back as history rather than 
run again.
+        alpha = _write_skill(tmp_path, "alpha")
+        ti = _FakeTaskInstance()
+        mock_get_context.return_value = {"ti": ti}
+        earlier = Agent(
+            _calling(("load_skill", {"skill_name": "alpha"})),
+            toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])],
+        ).run_sync("go")
+
+        Agent(
+            _calling(("load_skill", {"skill_name": "alpha"})),
+            toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])],
+        ).run_sync("go on", message_history=earlier.all_messages())
+
+        assert ti.xcoms[SKILLS_XCOM_KEY] == [_skill_entry("alpha", alpha, 
{"load_skill": 2})]
+
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_replaces_its_own_stored_skills_and_keeps_the_others(self, 
mock_get_context, tmp_path):
+        alpha = _write_skill(tmp_path, "alpha")
+        other = _skill_entry("other", tmp_path / "elsewhere", {"load_skill": 
3})
+        ti = _FakeTaskInstance(stored=[_skill_entry("alpha", alpha, 
{"load_skill": 1}), other])
+        mock_get_context.return_value = {"ti": ti}
+
+        Agent(_calling(), 
toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])]).run_sync("go")
+
+        assert ti.xcoms[SKILLS_XCOM_KEY] == [_skill_entry("alpha", alpha, {}), 
other]
+
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_two_prefixed_toolsets_each_count_their_own_skills(self, 
mock_get_context, tmp_path):
+        alpha = _write_skill(tmp_path / "one", "alpha")
+        beta = _write_skill(tmp_path / "two", "beta")
+        ti = _FakeTaskInstance()
+        mock_get_context.return_value = {"ti": ti}
+        toolsets = [
+            AgentSkillsToolset(sources=[str(tmp_path / 
"one")]).prefixed("one"),
+            AgentSkillsToolset(sources=[str(tmp_path / 
"two")]).prefixed("two"),
+        ]
+        model = _calling(
+            ("one_load_skill", {"skill_name": "alpha"}),
+            ("two_load_skill", {"skill_name": "beta"}),
+        )
+
+        Agent(model, toolsets=toolsets).run_sync("go")
+
+        assert ti.xcoms[SKILLS_XCOM_KEY] == [
+            _skill_entry("alpha", alpha, {"load_skill": 1}),
+            _skill_entry("beta", beta, {"load_skill": 1}),
+        ]
+
+    @pytest.mark.parametrize(
+        "context",
+        [
+            pytest.param(RuntimeError("no task"), id="outside_a_task"),
+            pytest.param({"ti": MagicMock(**{"task.do_xcom_push": False})}, 
id="do_xcom_push_off"),
+        ],
+    )
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_nothing_pushed_without_a_task_that_pushes_xcom(self, 
mock_get_context, tmp_path, context):
+        _write_skill(tmp_path, "alpha")
+        if isinstance(context, Exception):
+            mock_get_context.side_effect = context
+        else:
+            mock_get_context.return_value = context
+        model = _calling(("load_skill", {"skill_name": "alpha"}))
+
+        assert (
+            Agent(model, 
toolsets=[AgentSkillsToolset(sources=[str(tmp_path)])]).run_sync("go").output
+            == "done"
+        )
+        if not isinstance(context, Exception):
+            context["ti"].xcom_push.assert_not_called()
+
+    @patch(_GET_CONTEXT, autospec=True)
+    def test_failed_push_does_not_fail_the_run_or_skip_cleanup(self, 
mock_get_context, tmp_path):
+        _write_skill(tmp_path, "alpha")
+        ti = MagicMock()

Review Comment:
   This passes even if the push is skipped entirely, so 
`ti.xcom_push.assert_called_once()` would make it test the swallowed failure. 
Could it also use `_FakeTaskInstance` from above instead of a bare 
`MagicMock()` (same for the `do_xcom_push_off` case)?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to