Логотип Traversing The Semantics Tree

Traversing The Semantics Tree

Сообщество
skydoves
traversing-the-semantics-tree

Use this skill to navigate from one Compose semantics node to its relatives via `onParent`, `onChildren`, `onChild`, `onChildAt`, `onSibling`, `onSiblings`, `onAncestors`, plus the collection helpers `onFirst`, `onLast`, `filter`, `filterToOne`, and the `[index]` operator. Covers when to traverse vs when to add a stable `testTag`, the LazyColumn/LazyRow caveat (only currently composed children appear), the absence of a singular `onAncestor`, and the sticky `useUnmergedTree` flag across navigation. Use when the developer mentions `onChildren`, `onChild`, `onParent`, `onSiblings`, `onAncestors`, `filterToOne`, `onFirst`, `onLast`, brittle child-index chains, or asks how to find the second child of a Row, the parent of a Text, or any sibling of a node. If the developer is dot-chaining navigation through a layout, use this skill.

Обзор

Издательskydoves
Репозиторийandroid-testing-skills
Название навыкаtraversing-the-semantics-tree
Звёзды
338
Форки
14
Файлы в комплекте
Только инструкции
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — skydoves. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Traversing The Semantics Tree в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/skydoves/android-testing-skills/tree/main/compose/finders/traversing-the-semantics-tree
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/skydoves/android-testing-skills.git /tmp/android-testing-skills
mkdir -p .claude/skills
cp -r /tmp/android-testing-skills/compose/finders/traversing-the-semantics-tree .claude/skills/traversing-the-semantics-tree
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Traversing The Semantics Tree в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Traversing The Semantics Tree, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Traversing The Semantics Tree не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Traversing the Semantics Tree — When a Single Finder Won't Reach the Node

The single-finder shortcuts (onNodeWithTag, etc.) cover ~95% of test queries. The remainder need tree navigation: "the parent of this Text", "the third child of this Row", "any sibling that is enabled". This skill maps those navigation operators, calls out the LazyColumn snapshot caveat, and shows when traversal is the wrong tool.

When to use this skill

  • The target node has no stable testTag and one cannot be added to production (third-party composable, dynamically generated children).
  • The test verifies structural relationships ("the second child of the row is the icon").
  • The developer chains .onChildren()[i].onChildAt(j) and wants to know whether that is the right shape.
  • The developer mentions onChildren, onChild, onParent, onSibling, onSiblings, onAncestors, filterToOne, onFirst, onLast, or [index].
  • A LazyColumn test misses items because they are off-screen.

When NOT to use this skill

  • A Modifier.testTag(...) could be added to the target node — adding a tag is almost always cleaner than a traversal chain. See ../finding-nodes-by-tag-text-content/SKILL.md.
  • The relationship is "anywhere above" / "anywhere below" — prefer the matcher-based hasAnyAncestor / hasAnyDescendant (see ../composing-semantics-matchers/SKILL.md).
  • The query is about a LazyColumn item by key — use performScrollToKey instead (see ../../actions/clicking-and-scrolling/SKILL.md, ../../patterns/testing-lazy-lists/SKILL.md).

Prerequisites

  • A working ComposeTestRule / ComposeUiTest. See ../../setup/configuring-test-dependencies/SKILL.md.
  • Familiarity with the merged vs unmerged tree distinction. See ../finding-nodes-by-tag-text-content/SKILL.md.

Workflow

  • 1. Pick the navigator by relationship type. Each operator returns either a SemanticsNodeInteraction (single — fails on 0 or >1) or a SemanticsNodeInteractionCollection (plural — never fails on 0).

    From a single node, go to …APIReturnsFile:line
    parentonParent()singleSelectors.kt:36-42
    exactly one childonChild()singleSelectors.kt:71-77
    child at an indexonChildAt(index)singleSelectors.kt:85
    all currently-composed childrenonChildren()collectionSelectors.kt:53-59
    exactly one siblingonSibling()singleSelectors.kt:119-125
    all siblingsonSiblings()collectionSelectors.kt:101-107
    every ancestor up to rootonAncestors()collectionSelectors.kt:140-146
    From a collection, narrow to …APIReturnsFile:line
    firstonFirst() (= [0])singleSelectors.kt:156-158
    lastonLast()singleSelectors.kt:168-170
    nth[index]singleSemanticsNodeInteraction.kt:261-267
    filter to a sub-collectionfilter(matcher)collectionSelectors.kt:178-186
    filter to exactly onefilterToOne(matcher)singleSelectors.kt:198-206
  • 2. Do not look for onAncestor (singular) — it does not exist. The API surface ships only onAncestors() plural (Selectors.kt:140-146). It returns [parent, grandparent, …, root] in that order. To assert "the immediate parent satisfies X", use onParent().assert(matcherX) or the hasParent(matcherX) predicate.

  • 3. Remember the useUnmergedTree flag is sticky. Every navigator carries the same useUnmergedTree value as the source SemanticsNodeInteraction (SemanticsNodeInteraction.kt:42-49; each Selectors.kt constructor passes useUnmergedTree through unchanged). A finder created with onNodeWithTag(tag, useUnmergedTree = true) keeps the flag on across onChild/onParent/filter. Skydoves hot take #2: default merged, flip to unmerged only when targeting composition detail.

  • 4. onChildren() is a snapshot at invocation time. It returns nodes "currently present in the semantic tree" (Selectors.kt:46-52). For a LazyColumn or LazyRow only the on-screen items appear. To reach an off-screen item, scroll first with performScrollToIndex / performScrollToKey / performScrollToNode (see ../../actions/clicking-and-scrolling/SKILL.md).

  • 5. Re-finding by tag usually beats navigating. If the tree shape might change between Compose versions or under translation rotation, a stable tag on the target node is more durable than a [2].onChildAt(0) chain. Add the tag in production. Skydoves hot take #1.

  • 6. Use filterToOne(matcher) when the count assertion is implicit. filterToOne throws on 0 or >1 matches at fetch time, the same way onNode(matcher) does (Selectors.kt:198-206). It is the collection-narrowing analogue of onNode(matcher).

Patterns

Pattern: prefer a tag over a deep [index] chain

kotlin
// WRONG
@Test
fun second_avatar_isVisible() {
    rule.setContent { ProfileGrid(profiles = profiles) }
    rule.onNodeWithTag("ProfileGrid")
        .onChildren()[2]
        .onChildren()[0]
        .assertIsDisplayed()
}
// WRONG because: layout shuffling (a header inserted, an extra wrapper, a Spacer added)
// silently changes which node is being asserted. The test passes for the wrong reason.
kotlin
// RIGHT
// production:
@Composable
fun ProfileGrid(profiles: List<Profile>) {
    LazyColumn(modifier = Modifier.testTag(ProfileGridTag)) {
        itemsIndexed(profiles) { index, profile ->
            Row(modifier = Modifier.testTag("$AvatarTagPrefix$index")) {
                Avatar(profile, modifier = Modifier.testTag("$AvatarImageTagPrefix$index"))
            }
        }
    }
}

// test:
rule.onNodeWithTag("$AvatarImageTagPrefix${1}").assertIsDisplayed()

Pattern: traversal when no tag is available

kotlin
@Test
fun row_third_child_isIcon() {
    rule.setContent {
        Row(modifier = Modifier.testTag("toolbar")) {
            Text("Title")
            Spacer(Modifier.weight(1f))
            Icon(Icons.Default.Share, contentDescription = "Share")
        }
    }

    rule.onNodeWithTag("toolbar")
        .onChildren()
        .assertCountEquals(3)

    rule.onNodeWithTag("toolbar")
        .onChildAt(2)
        .assertContentDescriptionEquals("Share")
}

onChildAt(index) is exactly onChildren()[index] (Selectors.kt:85). Both fail if the index is out of range or if the resolved node count is not exactly 1 at the leaf.

Pattern: filterToOne instead of [i]

kotlin
// WRONG
rule.onAllNodesWithTag(RowTag).onChildren().filter(hasClickAction())[0]
    .assertHasClickAction()
// WRONG because: indexing into a filtered collection silently passes when the filter returns
// many. The test asserts only "at least one is clickable", not "exactly one".
kotlin
// RIGHT
rule.onAllNodesWithTag(RowTag).onChildren()
    .filterToOne(hasClickAction())
    .assertHasClickAction()

Pattern: assert the parent role from a known child

kotlin
@Test
fun submitText_isInsideEnabledButton() {
    rule.setContent {
        Button(onClick = {}, modifier = Modifier.testTag("submit"), enabled = true) {
            Text("Submit", modifier = Modifier.testTag("submitLabel"))
        }
    }

    rule.onNodeWithTag("submitLabel", useUnmergedTree = true)
        .onParent()                       // sticky: stays unmerged
        .assertIsEnabled()
        .assertHasClickAction()
}

The useUnmergedTree = true set on the inner Text finder propagates to onParent() automatically — no need to repeat it.

Pattern: onAncestors() for the chain to root

kotlin
@Test
fun confirmButton_isInsideDialog() {
    rule.setContent { ConfirmDialog() }

    rule.onNodeWithTag(ConfirmButtonTag)
        .onAncestors()
        .filterToOne(isDialog())
        .assertExists()
}

PREFERRED: rule.onNode(hasTestTag(ConfirmButtonTag) and hasAnyAncestor(isDialog())).assertExists() — same intent in one matcher. See ../composing-semantics-matchers/SKILL.md.

Pattern: LazyColumn — only on-screen children appear

kotlin
// WRONG
rule.onNodeWithTag(ListTag).onChildren().assertCountEquals(1000)
// WRONG because: onChildren() returns a snapshot of currently composed children. A LazyColumn
// only composes the visible viewport plus a small prefetch buffer, so the count is window-sized,
// not data-set-sized.
kotlin
// RIGHT — assert the visible count, OR scroll first then assert by tag
rule.onNodeWithTag(ListTag).performScrollToIndex(999)
rule.onNodeWithTag("$ItemTagPrefix${999}").assertIsDisplayed()

See ../../patterns/testing-lazy-lists/SKILL.md for the full LazyColumn workflow.

Pattern: onSibling() to assert "the row's other half"

kotlin
@Test
fun checkbox_label_isPresent() {
    rule.setContent {
        Row {
            Checkbox(checked = true, onCheckedChange = {},
                modifier = Modifier.testTag("agreeBox"))
            Text("I agree", modifier = Modifier.testTag("agreeLabel"))
        }
    }

    rule.onNodeWithTag("agreeBox")
        .onSibling()
        .assertTextEquals("I agree")
}

onSibling() requires exactly one sibling (Selectors.kt:114-125). For multiple siblings use onSiblings() plus filterToOne(...).

Mandatory rules

  • MUST prefer adding a Modifier.testTag(...) to the target node over a multi-step traversal chain. Skydoves hot take #1.
  • MUST use filterToOne(matcher) over filter(matcher).onFirst() when the contract is "exactly one match"; the former throws on >1, the latter silently picks the first.
  • MUST NOT assume onChildren() returns the full data set for a LazyColumn / LazyRow — it returns the currently-composed snapshot only. Scroll first with performScrollToIndex / performScrollToKey.
  • MUST NOT look up a singular onAncestor — only onAncestors() plural exists. Use onParent() for the immediate parent or hasParent(matcher) / hasAnyAncestor(matcher) as predicates.
  • MUST remember the useUnmergedTree flag is sticky across onChild/onParent/filter. Skydoves hot take #2.
  • PREFERRED: for "anywhere above/below" relationships, replace traversal chains with hasAnyAncestor / hasAnyDescendant from ../composing-semantics-matchers/SKILL.md.

Verification

  • Every traversal chain has at most one navigation step, OR the deeper chain is justified by a comment naming the missing tag.
  • No onChildren()[i] chain spans a LazyColumn / LazyRow boundary without a preceding performScrollTo*.
  • No onAncestor (singular) usage — only onParent, onAncestors, or hasAnyAncestor.
  • filterToOne is used wherever the contract is "exactly one match"; filter().onFirst() is replaced.
  • useUnmergedTree = true on a chain root is intentional — there is a comment or matcher reason for it.
  • ./gradlew :app:connectedDebugAndroidTest or :app:testDebugUnitTest passes.

References

Часто задаваемые вопросы

Что делает навык ИИ Traversing The Semantics Tree?

Use this skill to navigate from one Compose semantics node to its relatives via `onParent`, `onChildren`, `onChild`, `onChildAt`, `onSibling`, `onSiblings`, `onAncestors`, plus the collection helpers `onFirst`, `onLast`, `filter`, `filterToOne`, and the `[index]` operator. Covers when to traverse vs when to add a stable `testTag`, the LazyColumn/LazyRow caveat (only currently composed children appear), the absence of a singular `onAncestor`, and the sticky `useUnmergedTree` flag across navigation. Use when the developer mentions `onChildren`, `onChild`, `onParent`, `onSiblings`, `onAncestor...

Зачем использовать Traversing The Semantics Tree в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Traversing The Semantics Tree — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Traversing The Semantics Tree в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/skydoves/android-testing-skills/tree/main/compose/finders/traversing-the-semantics-tree. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Traversing The Semantics Tree?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Traversing The Semantics Tree?

С любым количеством. В TypingMind вы можете использовать Traversing The Semantics Tree с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Traversing The Semantics Tree?

Да. Навык опубликован на GitHub по лицензии Apache-2.0. Издатель — skydoves. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇