К основному содержанию
скилл CX Codex

graph-viewer — скилл для Claude Code: граф CDF в приложении

Скилл помогает встроить интерактивный граф модели данных CDF в приложение на Flows: узлы, связи и обратные связи.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add cognitedata/builder-skills --skill graph-viewer -a claude-code
Открыть на GitHub

Что делает graph-viewer

Скилл проводит агента по шагам: посмотреть структуру целевого приложения, доставить недостающие зависимости, скопировать локальный бандл из skills/graph-viewer/code/ в папку вида src/features/graph-viewer/, импортировать useGraphViewer оттуда и отрисовать GraphCanvas в контейнере с явной высотой. В конце агент гоняет tsc --noEmit и сборку, чтобы поймать ошибки путей после копирования.

Заранее нужно немного: приложение обёрнуто в <DuneProvider> из @cognite/dune, чтобы useDune() возвращал авторизованный SDK, используется React 18+ и TypeScript, а модель данных в CDF уже существует — понадобятся её space, externalId и version. В зависимостях названы @cognite/sdk, @cognite/dune, reagraph и lucide-react; версии в таблице — отправная точка, и скилл советует не трогать React, который уже зафиксирован в проекте.

Разворачивание графа шлёт много запросов в CDF, особенно из-за обратных связей. Поэтому скилл советует ограничить whitelistedRelationProps, уменьшить initialConnectionLimit и maxNodes и объявлять coreReverseQueries только для тех связей, которые реально нужны в интерфейсе: каждая запись добавляет отдельный запрос на разворачивание. Для статических схем и графов не из CDF инструмент не подходит.

Какие задачи решает

  • встроить интерактивный граф модели данных CDF в приложение на Flows
  • показать узлы, прямые и обратные связи между инстансами
  • скопировать бандл useGraphViewer в локальную папку фичи и поправить импорты
  • проставить зависимости @cognite/sdk, @cognite/dune, reagraph и lucide-react
  • сократить число запросов к CDF при разворачивании больших моделей

Примеры запросов агенту

  • Скопируй бандл graph-viewer в src/features/graph-viewer/ и покажи граф для модели my-data-model из пространства my-space
  • Встрой GraphCanvas в панель и оставь высоту контейнера 600px
  • Ограничь coreReverseQueries только нужными связями, чтобы не долбить CDF лишними запросами

Как установить graph-viewer

1Через Skills CLI (Vercel)

npx skills add cognitedata/builder-skills --skill graph-viewer -a claude-code

2Вручную: положить файлы

~/.claude/skills/graph-viewer/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/graph-viewer/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора12

use-topbar Скилл ставит в приложение Flows/Fusion единый топбар из @aura/topbar: хлебные крошки, переключатель темы, кнопка Atlas. CX Codex +1 1 900установок pull-changes-resolve-conflicts Скилл ведёт агента через слияние веток: сначала показывает конфликты и спрашивает, потом правит. Пригодится, когда в проекте несколько контрибьюторов. CX Codex +1 1 900установок setup-python-tools Ставит клиентское выполнение Python-инструментов через Pyodide в приложение с уже готовым useAtlasChat. Нужен, когда агент отдаёт код инструмента, а считать он должен в браузере. CX Codex +1 1 900установок dm-limits-and-best-practices Справочный скилл про лимиты CDF Data Modeling: конкурентность и 429, пагинация, батчи, QueuedTaskRunner. Пригодится, когда код сыпет ошибками на нагрузке. CX Codex +1 1 900установок security Проходит по приложению Flows шаг за шагом: находит утечки секретов, опасный DOM, дыры в авторизации — и сразу правит их. CX Codex +1 1 900установок integrate-atlas-chat Скилл для встраивания чата Atlas прямо в интерфейс приложения Cognite. Нужен, когда сайдбар Fusion/EOS недоступен. CX Codex +1 1 900установок integrate-todo-list Добавляет в приложение инструмент TodoWrite и панель, где видно, как агент Atlas выполняет многошаговую работу. CX Codex +1 1 900установок reveal-3d Встраивает интерактивный 3D-вьюер Cognite Reveal в приложение Flows: CAD-модели, облака точек, панорамы 360° и сцены CDF. CX Codex +1 1 900установок

Похожие

react-flow framara Скилл для работы с React Flow (@xyflow/react): кастомные узлы и рёбра, состояние, лейаут, типизация и отладка графов. CX Codex +1 821установок highlight-graph readwiseio Собирает ваши хайлайты Readwise в интерактивный граф: видно, какие идеи из разных книг и статей перекликаются. CX Codex +1 443установок node-link-and-diagram-layout официальный OpenAI Скилл выбирает алгоритм раскладки для графов, схем и связанных узлов. Пригодится, когда нужно убрать пересечения, наложения и хаотичное размещение. CX Codex GP ChatGPT 16установок convex-realtime waynesutton Скилл объясняет, как связать фронтенд с подписками Convex: useQuery, оптимистичные обновления, живая пагинация и борьба с лишними ререндерами. CX Codex +1 2 900установок modern-web-development Mindrally Набор правил для современного веб-стека: TypeScript, Next.js 14, React Server Components, Supabase, GraphQL и Tailwind CSS. Пригодится, когда агент пишет фронтенд и API в одном проекте. CX Codex +1 1 200установок diagram-viewer официальный Aaron Powell Плагин показывает диаграммы в интерактивном холсте: по узлам можно переходить глубже, а объяснения агента видны рядом. Подойдёт для изучения схемы. ★ 40 418звёзд репо

Рядом в теме «Фронтенд и UI»

Всё по теме «Фронтенд и UI» →

Вопросы о graph-viewer

Как установить graph-viewer в Claude?

Выполните npx skills add cognitedata/builder-skills --skill graph-viewer -a claude-code. Скилл появится в ~/.claude/skills/graph-viewer/SKILL.md.

Что делает graph-viewer?

Проводит агента по встраиванию графа модели данных CDF в приложение: копирует локальный бандл useGraphViewer, подключает зависимости и помогает отрисовать GraphCanvas.

Что нужно для работы скилла?

Приложение с <DuneProvider> из @cognite/dune, React 18+ и TypeScript, а также существующая модель данных в CDF с известными space, externalId и version.

Исходный текст

SKILL.md · Apache-2.0
---
name: graph-viewer
description: Integrate the reusable CDF graph viewer (useGraphViewer) into a Flows app by copying the local code bundle. Use when embedding a graph visualization, adding a knowledge graph, or showing CDF data model relationships and instances.
---

# Graph Viewer

## Use This When

The user wants to embed an interactive graph of a CDF data model — nodes, direct relations, edges, and reverse relations — inside a Flows app.

Do **not** use this skill for static diagrams, pure dataflow visualizations, or non-CDF graphs.

## Prerequisites

- The app is wrapped in `@cognite/dune`'s `<DuneProvider>` so `useDune()` returns an authenticated SDK.
- The target data model exists in CDF and you know its `space`, `externalId`, and `version`.
- The app uses React 18+ and TypeScript.

## Integration Workflow

Follow these steps in order. Adapt to the target repo's conventions instead of inventing new ones.

1. **Inspect the target app.** Read `package.json` and look at the existing folder structure (e.g. `src/features/*`, `src/components/*`, path aliases like `@/*`).
2. **Install missing dependencies** with the app's package manager (`npm`, `pnpm`, `yarn`, …). See the [Dependencies](#dependencies) table below for purposes and suggested versions. Reuse the React version already pinned by the app rather than upgrading it, and prefer any versions the repo already pins over the suggestions here.
3. **Copy the bundle into the app.** Copy every file from `skills/graph-viewer/code/` into an app-local feature folder, for example:

   ```text
   src/features/graph-viewer/
   ```

   If the repo already has a different feature/components layout or alias, mirror it.
4. **Import from the local folder**, never from `@skills/...`. With a typical `@/*` alias:

   ```tsx
   import { useGraphViewer } from "@/features/graph-viewer";
   ```
5. **Render `GraphCanvas` inside a container with explicit dimensions** (height is required — see the minimal example below).
6. **Run typecheck and build** (`tsc --noEmit`, `npm run build`, etc.) and fix any path or type issues introduced by the copy.

## Minimal Example

```tsx
import { useGraphViewer } from "@/features/graph-viewer";

export function GraphPanel() {
  const { GraphCanvas, isLoading, error } = useGraphViewer({
    dataModel: { space: "my-space", externalId: "my-data-model", version: "1" },
    instance: { space: "my-instance-space", externalId: "pump-001" },
  });

  if (isLoading) return <div>Loading graph…</div>;
  if (error) return <div>Error: {error}</div>;

  return <GraphCanvas className="h-[600px] w-full" />;
}
```

## Dependencies

Suggested versions reflect the latest published majors at the time of writing. They are starting points — if the target app already pins different versions, defer to the app.

| Package         | Suggested version | Purpose                                        |
| --------------- | ----------------- | ---------------------------------------------- |
| `react`         | `^18.2.0`         | UI framework (peer; reuse the app's version)   |
| `@cognite/sdk`  | `^10.10.0`        | CDF API client (instances, data models)        |
| `@cognite/dune` | `^2.1.0`          | Provides the authenticated SDK via `useDune()` |
| `reagraph`      | `^4.30.8`         | WebGL graph rendering engine                   |
| `lucide-react`  | `^1.14.0`         | Icon set used by the node-type legend          |

Example install (npm; adapt to the app's package manager):

```bash
npm install @cognite/sdk@^10.10.0 @cognite/dune@^2.1.0 reagraph@^4.30.8 lucide-react@^1.14.0
```

## CDF Cost & Performance

Graph expansion can issue many CDF requests, especially with reverse relations. For large or unfamiliar data models, be conservative:

- Set `whitelistedRelationProps` to the few properties the app actually needs to traverse.
- Lower `initialConnectionLimit` (it is a **hard maximum** of connections fetched per expansion).
- Lower `maxNodes` to bound the in-memory LRU buffer.
- Only declare `coreReverseQueries` for relations the app must surface; each entry adds an extra query per expansion.

Tuples in `coreReverseQueries` are **version-aware**:
`[space, viewExternalId, viewVersion, propertyName, isList]`.

## Advanced Reference

For full configuration tables, return-value docs, layouts, theming, and richer examples, read `code/README.md`.

For implementation details, inspect the source files under `code/`.

## Verification Checklist

- [ ] The app is wrapped in `<DuneProvider>`.
- [ ] All files from `skills/graph-viewer/code/` were copied into an app-local folder.
- [ ] Imports point to the app-local folder (e.g. `@/features/graph-viewer`), not `@skills/...`.
- [ ] `@cognite/dune`, `@cognite/sdk`, `reagraph`, and `lucide-react` are present in `package.json`.
- [ ] The container that renders `<GraphCanvas>` has an explicit height.
- [ ] `tsc --noEmit` and the app's build both pass.
- [ ] No references to `dune-industrial-components` were introduced.

© cognitedata · Apache-2.0 · cognitedata/builder-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой