Build, format, and review Power BI reports (PBIR), with a report pane that follows pbir.

<h1 align="center">Power BI Agentic Dev</h1>
A personalized fork of Kurt Buhler's Power BI & Microsoft Fabric skills marketplace <br></br> <i>Teach AI agents like Claude Code, GitHub Copilot, or OpenAI Codex to work with Power BI and Microsoft Fabric</i>
<img src="https://img.shields.io/badge/version-26.25-blue" alt="Version"> <img src="https://img.shields.io/badge/Power_BI-F2C811?logo=powerbi&logoColor=000" alt="Power BI"> <img src="https://img.shields.io/badge/Microsoft_Fabric-008272" alt="Microsoft Fabric"> <img src="https://img.shields.io/badge/Tabular_Editor-2E7D32" alt="Tabular Editor"> <img src="https://img.shields.io/badge/license-GPL--3.0-green" alt="License">
[!NOTE] This is Tim's personalized fork of
data-goblin/power-bi-agentic-development, renamed topower-bi-agentic-devso it can coexist with the original. It carries the upstream plugins plus additional personal skills, and tracks Kurt's releases selectively rather than following his weekly cadence. Full credit for the original work goes to Kurt Buhler — see Attribution.
Add the marketplace in Claude Code — run this in the terminal:
claude plugin marketplace add InsightfulAnalytics/PBI_Agentic_Dev
This registers the marketplace under the name power-bi-agentic-dev (from the repo's .claude-plugin/marketplace.json). Note that the GitHub repo slug (PBI_Agentic_Dev) differs from the marketplace name (power-bi-agentic-dev) — the slug is used only in the marketplace add command above; the install commands below reference the marketplace name.
After adding the marketplace, install plugins interactively via /plugin → Marketplaces → select power-bi-agentic-dev → install the plugins you want. You can also enable auto-update per marketplace there.
Or install from the command line:
claude plugin install semantic-models@power-bi-agentic-dev
claude plugin install reports@power-bi-agentic-dev
claude plugin install pbip@power-bi-agentic-dev
claude plugin install custom-visuals@power-bi-agentic-dev
claude plugin install tabular-editor@power-bi-agentic-dev
claude plugin install pbi-desktop@power-bi-agentic-dev
claude plugin install fabric-cli@power-bi-agentic-dev
claude plugin install fabric-admin@power-bi-agentic-dev
claude plugin install paginated-reports@power-bi-agentic-dev
claude plugin install etl@power-bi-agentic-dev
claude plugin install fabric-data-app@power-bi-agentic-dev
Verify what's installed with claude plugin list, and inspect a plugin's contents and token cost with claude plugin details <plugin>.
Updates. Every release is listed in CHANGELOG.md and published as a GitHub Release, so to hear about new ones, choose Watch → Custom → Releases on this repository. To update, run claude plugin marketplace update power-bi-agentic-dev, then claude plugin update <plugin>@power-bi-agentic-dev for each plugin you use, or turn on auto-update for the marketplace in /plugin.
The standalone Copilot CLI supports plugin installation from GitHub repos. Copilot CLI reads the same .claude-plugin/marketplace.json manifest this repo uses, so the marketplace and child-plugin layout works without modification.
TMDL files can produce repository-relative paths over 260 characters. Windows' legacy MAX_PATH blocks git clone from writing them unless long path support is enabled at both the OS and git level. Without this, copilot plugin install aborts with Filename too long.
See useful-stuff/agent-scripts/enable-windows-longpaths.ps1 for an example script you can run from an elevated PowerShell session to enable long paths (a reboot is recommended after the registry change). This is a Windows OS limitation, documented at Maximum Path Length Limitation.
Also set the git-level flag:
git config --system core.longpaths true
This repository is an Anthropic-format plugin marketplace (a set of plugins), not a single distributable plugin, so the root .claude-plugin/ contains only marketplace.json. Two documented install paths work:
1. Register the marketplace once, then install named child plugins:
copilot plugin marketplace add InsightfulAnalytics/PBI_Agentic_Dev
copilot plugin install tabular-editor@power-bi-agentic-dev
2. Or install a single plugin directly from its subdirectory, no marketplace registration needed:
copilot plugin install InsightfulAnalytics/PBI_Agentic_Dev:plugins/pbip
Both forms are documented in the Copilot CLI plugin reference and the plugins how-to. Inside an interactive Copilot session, /plugin install PLUGIN-NAME@power-bi-agentic-dev is the equivalent of (1). The bare copilot plugin install InsightfulAnalytics/PBI_Agentic_Dev (no qualifier) will not install anything useful, because the root is a marketplace catalog, not a plugin.
Inside Copilot CLI:
/env # Loaded instructions, MCP servers, skills, agents, plugins, LSPs, extensions
/plugin list # Installed plugins
/skills list # Available skills
/skills info pbip # Details for a specific skill
/agent # Browse installed agents
skills/<name>/SKILL.md.*.agent.md extension required by Copilot CLI's documented convention. Claude Code matches any *.md file in agents/, so the dual extension works in both tools..mcp.json (plugin root) or .github/mcp.json. Two plugins ship MCP declarations: fabric-cli (microsoft-learn, HTTP) and custom-visuals (pbiviz, stdio via npx).hooks/hooks.json (with per-hook if path filters). Copilot CLI reads .github/plugin/plugin.json, which points it at hooks/copilot-hooks.json: the same scripts, wired with explicit bash and powershell commands so a Windows host without Git Bash on PATH gets a clean no-op instead of a failed launch. Copilot has no if filter and denies a tool call on any non-zero PreToolUse exit, so every script also re-applies its own path and command filters and exits 0 on anything unrelated. Requires Copilot CLI >= 1.0.26 (2026-04-14) for CLAUDE_PLUGIN_ROOT (changelog); older builds skip the hooks rather than fail. Native Windows bash users may also hit a separate path-format bug tracked upstream at claude-code#11984.~/.copilot/installed-plugins/ and their hooks run in every session on the machine. There is no per-project install, so the "prefer project scope" advice below applies to Claude Code only; in Copilot, install a plugin only while you need it./plugin rm or copilot plugin uninstall can fail with Access is denied. (os error 5). This is an open Copilot CLI bug, not a plugin problem: the installer swaps the plugin folder by renaming it, and Windows refuses the rename while another process holds a handle on it. VS Code's Copilot extension keeps directory watchers on every installed plugin's hooks/, agents/ and skills/ folders, and a second Copilot CLI session does the same. Tracked at github/copilot-cli#4095 and #4151.
%USERPROFILE%\.copilot\installed-plugins\ (or %COPILOT_HOME%\installed-plugins\) and restart Copilot CLI.hooks folder from that same location.Most of what these skills know is about TMDL, the PBIR JSON schemas, and the Fabric and Power BI REST APIs, none of which care about the operating system. A Codespace on this repository picks the skills up with no setup: .devcontainer/devcontainer.json installs Claude Code and runs the bootstrap.
For a Codespace on a Power BI project repository, which is the usual case, copy the devcontainer.json block from .devcontainer/README.md. To set an existing Linux or macOS machine up by hand:
git clone --depth 1 https://github.com/InsightfulAnalytics/PBI_Agentic_Dev.git ~/.pbi-agentic-dev
bash ~/.pbi-agentic-dev/scripts/bootstrap-agent-env.sh
The bootstrap registers the marketplace, installs the toolchain that exists on the platform, and prints a capability report naming what does not, so an agent learns the limits before its first turn rather than by failing:
| Linux | Windows with Desktop | |
|---|---|---|
fab, te, az, the REST APIs | yes | yes |
TMDL validation (bundled tmdl-validate binary) | yes | yes |
Server-side report render (ExportTo to PDF, then pymupdf to PNG) | yes | yes |
| ADOMD or TOM over XMLA against a published model | yes | yes |
pbir CLI | no, and there is no wheel or sdist to install | yes |
Power BI Desktop, local msmdsrv, DAX Studio, Tabular Editor 2 and 3 | no | yes |
On Linux, author PBIR by hand from the pbip:pbir-format examples, publish with fab import, and verify by rendering server-side. .devcontainer/README.md has the detail.
Codex supports the same open Agent Skills standard these plugins use, so the skills work there too — installed with a small script instead of a plugin marketplace:
git clone https://github.com/InsightfulAnalytics/PBI_Agentic_Dev.git
cd PBI_Agentic_Dev
python codex/install.py --check # dry run: preview what will be installed
python codex/install.py # skills -> ~/.agents/skills, adapter -> ~/.codex/AGENTS.md
python codex/install.py --mcp # optional: also add the MCP servers to ~/.codex/config.toml
Keep the clone — it's the runtime store for bundled scripts and validators that the copies in ~/.agents/skills reference. After a git pull, re-run the installer (idempotent) to refresh. The full guide — project-scoped installs, junction mode, uninstall, and troubleshooting — is in codex/README.md.
Inside a Codex session:
/skills # list available skills (the Power BI skills should appear)
$tmdl # invoke a skill explicitly by name
/mcp # MCP servers (if installed with --mcp)
/status # loaded AGENTS.md, model, config
~/.agents/skills/<name>/SKILL.md and auto-activates from the description, or on $name.~/.codex/AGENTS.md for the agent to run after edits.plugins/*/agents/*.agent.md.$audit-context, $suggest-rule, $migrating-fabric-trial-capacities) since Codex deprecated custom prompts.~/.codex/config.toml with --mcp (microsoft-learn over HTTP, pbiviz over stdio).~/.claude/skills) are not touched by the installer — copy any you want Codex to have into ~/.agents/skills yourself.codex/ layer only reads from plugins/; Claude Code behavior is unchanged.The repo contains skills, agents, and hooks.
/skill-name. In Claude Code, skills and commands have coalesced; commands are simply more prescriptive skill workflows.Hook checks can be individually toggled via config files. Set any check to false to disable it:
plugins/pbip/hooks/config.yaml — PBIR, TMDL, and report-binding validationplugins/pbi-desktop/hooks/config.yaml — DAX references, measure metadata, referential integrity, metadata cacheplugins/paginated-reports/hooks/config.yaml — RDL validation[!WARNING] Don't install every plugin. Each skill competes for the agent's attention and context window, so install a plugin only when you need it and remove it when you don't. Prefer installing plugins scoped to a project rather than to your user, so each project carries only the skills it actually uses.
| Type | Name | Description |
|---|---|---|
| Skill | semantic-model | Design, build, refresh, and review semantic models through a te-first tool cascade |
| Skill | date-table | Drop a ready-made 58-column DimDate (calendar, ISO week, fiscal, to-date flags) plus the Dates Selected title measure into any PBIP model |
| Skill | dax-standard | The house style for authoring measures: table-first DAX, formatting via dynamic format strings, worked recipes |
| Skill | dax-optimisation | Debug and optimize DAX performance (server timings, anti-patterns, tuning) |
| Skill | power-query | Write M expressions, debug query folding, execute M locally or via Fabric API |
| Skill | organize-semantic-model | Organize a model end to end: names, folders, hierarchies, descriptions, formats, UDFs, perspectives, translations, roles |
| Skill | refresh-semantic-model | Trigger or troubleshoot refreshes |
| Skill | lineage-analysis | Trace downstream reports from a semantic model across workspaces |
| Agent | semantic-model-auditor | Audit semantic models for quality, memory, DAX, and design issues |
| Type | Name | Description |
|---|---|---|
| Skill | pbir-cli | Programmatic report manipulation via the pbir CLI, including live Power BI Desktop refresh and page screenshots |
| Skill | create-pbi-report | End-to-end workflow for building a report from scratch with the pbir CLI |
| Skill | pbi-verify-loop | Refresh → settle → screenshot loop to visually verify report edits (optional mockup diff) |
| Skill | power-bi-theme | Browse a preset-theme gallery and apply a chosen theme to a report |
| Skill | modifying-theme-json | Edit, enforce, audit, and re-theme report theme JSON |
| Skill | workout-wednesday | Turn a Workout Wednesday challenge link into a built, verified, published report — see Try it end-to-end |
| Skill | pbi-report-design (WIP) | Power BI report best practices, design, and style |
| Skill | review-report (WIP) | Review Power BI reports for usage metrics and best practices |
| Agent | deneb-reviewer | Review Deneb specs for Vega/Vega-Lite syntax and conventions |
| Agent | svg-reviewer | Review SVG DAX measures for syntax and design quality |
| Agent | r-reviewer | Review R visual scripts (ggplot2) for Power BI conventions |
| Agent | python-reviewer | Review Python visual scripts (matplotlib/seaborn) for Power BI conventions |
| Type | Name | Description |
|---|---|---|
| Skill | deneb-visuals | Author Deneb visuals with Vega and Vega-Lite specs |
| Skill | deneb-pbir | Round-trip tooling: extract/embed a Deneb spec in visual.json and offline-render it |
| Skill | performant-matrix | Diagnose a slow financial matrix, then choose between a bridge model fix, a native restructure, or a Deneb grid |
| Skill | python-visuals | Custom Python visuals (matplotlib/seaborn) in Power BI reports |
| Skill | r-visuals | Custom R visuals (ggplot2) in Power BI reports |
| Skill | svg-visuals | SVG visuals via DAX measures in Power BI reports |
| Skill | powerbi-custom-visuals | Develop, build, and package .pbiviz custom visuals with the pbiviz toolchain |
| Type | Name | Description |
|---|---|---|
| Skill | pbip | Power BI Project (PBIP) format, structure, and file types |
| Skill | tmdl | Author and edit TMDL files directly |
| Skill | pbir-format | Author and edit PBIR metadata files directly (visual.json, report.json, themes, filters, report extensions, visual calculations) |
| Agent | pbip-validator | Validate PBIP project structure, TMDL syntax, and PBIR schemas |
| Hook | PBIR validation | Validates PBIR structure, required fields, naming conventions, and schema URLs |
| Hook | Report binding validation | Validates semantic model binding (byPath directory exists; byConnection model exists via fab exists) |
| Hook | TMDL validation | Validates TMDL structural syntax |
| Type | Name | Description |
|---|---|---|
| Skill | bpa-rules | Create and improve Best Practice Analyzer rules for models |
| Skill | c-sharp-scripting | C# scripting and macros for TE |
| Skill | te-cli | Cross-platform Tabular Editor CLI (te, preview) for semantic models from the terminal |
| Skill | te2-cli | Tabular Editor 2 CLI usage and automation (not TE3) |
| Skill | te-docs | Tabular Editor documentation search, TE3 config files. Uses pbi-search CLI |
| Command | /suggest-rule | Generate BPA rules from descriptions |
| Agent | bpa-expression-helper | Debug and improve BPA rule expressions |
| Type | Name | Description |
|---|---|---|
| Skill | connect-pbid | Explore, query, and modify a model in Power BI Desktop, and reload/screenshot the report canvas via the Desktop Bridge |
| Agent | query-listener | Capture DAX queries from Power BI Desktop visuals in real time |
| Hook | DAX reference validation | Validates table, column, and measure references against the connected model; suggests corrections |
| Hook | Measure metadata enforcement | Blocks adding measures without DisplayFolder, Description, and FormatString |
| Hook | Referential integrity check | Reports unmatched many-side keys after relationship or column changes |
| Hook | Metadata cache refresh | Auto-snapshots model metadata on TOM connect or model modification |
| Hook | Compatibility level check | Reports features available by upgrading; optional auto-upgrade |
| Type | Name | Description |
|---|---|---|
| Skill | fabric-cli | Fabric CLI (fab) for any remote operation in Power BI or Fabric (works fully on Pro/PPU; Fabric not required) |
| Command | /audit-context | Review project context files (CLAUDE.md, agents.md, memory files) |
| Command | [/migrating-fabric-trial-capacities](plugins/fabric-cli/commands/migrating
hooks/register.tsx 1138 lines1import { type EngineInterface, type Register, type Timer, update } from 'claude-code'
2import { LINUX_LAUNCH as LAUNCH, openCommand } from './open'
3
4import type { Explorer, Target, TreeNode } from '../types'
5import { glyph, type Tier, visualLabel } from './icons'
6import type { RowSpec, RowsProps, Seg } from './rows'
7import { FABRIC_SVG } from './svg-data'
8import type { ZoneProps } from './zone'
9import { ancestors, diff, empty, type Row, visible } from './tree'
10import { idOf, reportUrl, workspaceUrl } from './fabric'
11import { binOf, type Invocation, invocations, join, pbirReport, posix, targetLabel, tokenize, useDrives, useHome } from './parse'
12import { loadReport, modelRef, reportDetail } from './report'
13import { pbirTouched } from './touch'
14
15const STATE = { plugin: 'reports', key: 'explorer' } as const
16const TREE = { plugin: 'reports', key: 'tree' } as const
17const PANE = 'report-pane'
18const TITLE = 'Report'
19const TITLE_GLYPH = { fabric: 0xf202a, nerd: '\u{f0127}', plain: '▣' }
20const TITLE_COLOR = '#fbbf24'
21const HINT = 'waiting for a pbir command, or /report-pane <path.Report>'
22const WINDOW = 400
23const DETAIL_ROWS = 12
24const BUSY_MAX_MS = 600_000
25const FLASH_MS = 2700
26const DOUBLE_MS = 450
27const SHIMMER = ['#f97316', '#fb923c', '#fdba74', '#ffedd5']
28const TONES: Record<string, { bright: string[]; dim: string[] }> = {
29 orange: { bright: SHIMMER, dim: ['#8a4316', '#a3562a', '#bd7444', '#d29267'] },
30 teal: { bright: ['#14b8a6', '#2dd4bf', '#5eead4', '#ccfbf1'], dim: ['#0f5e57', '#16786f', '#2a9488', '#4fb3a8'] },
31 pink: { bright: ['#ec4899', '#f472b6', '#f9a8d4', '#fce7f3'], dim: ['#831843', '#9d174d', '#b8406f', '#cf6f93'] },
32 purple: { bright: ['#a855f7', '#c084fc', '#d8b4fe', '#f3e8ff'], dim: ['#581c87', '#6b21a8', '#8b47c4', '#a874d6'] },
33}
34const MUTED = '#6e6e7a'
35const PROPS = 'props:toggle'
36const ROW_PX = 24
37const SVG_NS = 'http://www.w3.org/2000/svg'
38const SVG_KIND: Record<string, string> = { report: 'Report', 'semantic model': 'SemanticModel' }
39const FONT_SCRIPT =
40 'f=; command -v fc-list >/dev/null 2>&1 && f=$(fc-list ":charset=$1" file 2>/dev/null | head -n1 | cut -d: -f1); ' +
41 '[ -n "$f" ] || f=$(ls "$HOME"/Library/Fonts/*"$2"* /Library/Fonts/*"$2"* "$HOME"/.local/share/fonts/*"$2"* 2>/dev/null | head -n1); ' +
42 '[ -n "$f" ] || { echo missing; exit 0; }; m=$(stat -c %Z "$f" 2>/dev/null || stat -f %c "$f"); p=$PPID; ' +
43 'while [ -n "$p" ] && [ "$p" -gt 1 ]; do c=$(ps -o comm= -p "$p" 2>/dev/null); c=$(basename "$c" 2>/dev/null | tr -d " "); case "$c" in ' +
44 'ghostty|kitty|alacritty|Alacritty|foot|footclient|wezterm-gui|konsole|gnome-terminal-|xterm|urxvt|st|Terminal|iTerm2) ' +
45 'e=$(ps -o etime= -p "$p" 2>/dev/null | awk -F\'[-:]\' \'{n=NF; s=$n+60*$(n-1); if (n>2) s+=3600*$(n-2); if (n>3) s+=86400*$(n-3); print s}\'); [ -n "$e" ] && [ $(( $(date +%s) - e )) -lt "$m" ] && echo stale || echo ok; exit 0;; esac; ' +
46 'p=$(ps -o ppid= -p "$p" 2>/dev/null | tr -d " "); done; echo ok'
47
48let lastPress = { key: '', at: 0 }
49const views: Record<string, { from: number; max: number; rows: number; room: number }> = {}
50let detected: Tier = 'nerd'
51let glyphSetting = 'auto'
52let fontHint = true
53let hinted = false
54let fellBack = false
55let follow = true
56let pbirBin = 'pbir'
57let blink: Timer | null = null
58let runs = 0
59let closed = false
60let noDock = false
61let inflight: Promise<void> | null = null
62let queued: Promise<void> | null = null
63let platform: Promise<'linux' | 'darwin' | 'win32'> | null = null
64let reportLinks = 'embed'
65let tenantId = ''
66let propsOpen = false
67let nativeScroll = false
68const modelLinks = new Map<string, { url: string; lines: string[] }>()
69
70function osName($: EngineInterface): Promise<'linux' | 'darwin' | 'win32'> {
71 platform ??= (async () => {
72 if ((await $.env.get('OS')) === 'Windows_NT') return 'win32'
73 try {
74 return (await $.process.run(['uname', '-s'], { timeoutMs: 3_000 })).stdout.trim() === 'Darwin' ? 'darwin' : 'linux'
75 } catch {
76 return 'linux'
77 }
78 })()
79 return platform
80}
81
82async function openPane($: EngineInterface, args: { id: string; title: string; focus?: true }): Promise<void> {
83 if (noDock && !args.focus) return
84 await $.ui.open(args)
85}
86
87async function cwdOf($: EngineInterface): Promise<string> {
88 return posix(await $.session.cwd())
89}
90
91function quiet(p: Promise<unknown>): void {
92 void p.catch(() => undefined)
93}
94
95function jumpTo(ex: Explorer, nodes: TreeNode[], query: string): Partial<Explorer> {
96 const q = query.trim().toLowerCase()
97 const hits = q ? nodes.filter(n => n.name.toLowerCase().includes(q) || n.note.toLowerCase().includes(q)).slice(0, 10) : []
98 const open = new Set(ex.expanded)
99 for (const n of hits) for (const a of ancestors(nodes, n.id)) open.add(a)
100 return { query: '', expanded: [...open], cursor: hits[0]?.id ?? ex.cursor, scroll: {} }
101}
102
103async function copyOf($: EngineInterface, text: string, surface?: string): Promise<void> {
104 const done = await $.ui.copy({ text, ...(surface ? { surface: surface as 'terminal' } : {}) })
105 $.ui.toast(done.isCopied ? `Copied ${text}` : 'Could not copy')
106}
107
108function clean(segs: Seg[]): Seg[] {
109 for (const seg of segs) for (const k of Object.keys(seg) as (keyof Seg)[]) if (seg[k] === undefined) delete seg[k]
110 return segs
111}
112
113async function launch($: EngineInterface, argv: string[]): Promise<void> {
114 try {
115 const run = await $.process.run(['sh', '-c', LAUNCH, 'sh', ...argv], { timeoutMs: 10_000 })
116 if (run.exitCode !== 0) $.ui.toast(`could not start ${argv[0] ?? ''} (exit ${run.exitCode})`)
117 } catch {
118 $.ui.toast(`could not start ${argv[0] ?? ''}`)
119 }
120}
121
122async function openUrl($: EngineInterface, url: string): Promise<void> {
123 const { argv, init } = openCommand(await osName($), url)
124 try {
125 const run = await $.process.run(argv, init)
126 if (run.exitCode !== 0) $.ui.toast(`could not open ${url} with ${argv[0]}: ${run.stderr.trim().split('\n')[0] || `exit ${run.exitCode}`}`)
127 } catch {
128 $.ui.toast(`could not open ${url} with ${argv[0]}`)
129 }
130}
131
132function cmdq(arg: string): string {
133 return /^[\w@%+=:,./\\-]+$/.test(arg) ? arg : `"${arg.replace(/"/g, '""')}"`
134}
135
136function shq(arg: string): string {
137 return `'${arg.replace(/'/g, `'\\''`)}'`
138}
139
140async function terminal($: EngineInterface, linux: string[], cmd: string[], cwd = ''): Promise<void> {
141 const line = cmd.map(shq).join(' ')
142 const os = await osName($)
143 if (os === 'linux') return launch($, ['xdg-terminal-exec', ...linux])
144 const argv =
145 os === 'darwin'
146 ? ['osascript', '-e', `tell application "Terminal" to do script "${(cwd ? `cd ${shq(cwd)} && ${line}` : line).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`, '-e', 'tell application "Terminal" to activate']
147 : ['cmd', '/c', 'start', '', 'cmd', '/k', cwd ? `cd /d "${cwd.replace(/\//g, '\\')}" && ${cmd.map(cmdq).join(' ')}` : cmd.map(cmdq).join(' ')]
148 try {
149 const run = await $.process.run(argv, { timeoutMs: 10_000 })
150 if (run.exitCode !== 0) $.ui.toast(`could not start ${argv[0] ?? ''} (exit ${run.exitCode})`)
151 } catch {
152 $.ui.toast(`could not start ${argv[0] ?? ''}`)
153 }
154}
155
156async function fontState($: EngineInterface, charset: string, name: string): Promise<'ok' | 'stale' | 'missing'> {
157 try {
158 const out = (await $.process.run(['sh', '-c', FONT_SCRIPT, 'sh', charset, name], { timeoutMs: 5_000 })).stdout.trim()
159 return out === 'stale' || out === 'missing' ? out : 'ok'
160 } catch {
161 return 'missing'
162 }
163}
164
165async function detectGlyphs($: EngineInterface): Promise<void> {
166 if ((await $.env.get('SSH_CONNECTION')) || (await $.env.get('SSH_TTY'))) {
167 detected = 'nerd'
168 return
169 }
170 const nerd = (await fontState($, 'f04eb', 'Nerd')) === 'ok'
171 detected = nerd && (await fontState($, 'f2621', 'FabricSymbols')) === 'ok' ? 'fabric' : nerd ? 'nerd' : 'plain'
172}
173
174function fontNote(): string {
175 if (!fontHint || hinted || !fellBack) return ''
176 hinted = true
177 return 'Tell user once: Report pane icons need github.com/data-goblin/fabric-nf plus a Nerd Font. Plugin option fontHint=off disables this.'
178}
179
180function tierFor(surface: string): Tier {
181 if (glyphSetting === 'fabric' || glyphSetting === 'nerd' || glyphSetting === 'plain') return glyphSetting
182 return surface === 'desktop' ? 'plain' : detected
183}
184
185function titleGlyph(tier: Tier): string {
186 return tier === 'fabric' ? String.fromCodePoint(TITLE_GLYPH.fabric) : tier === 'nerd' ? TITLE_GLYPH.nerd : TITLE_GLYPH.plain
187}
188
189function titleFor(target: Target | null): string {
190 return `${titleGlyph(tierFor('terminal'))} ${target ? targetLabel(target) : TITLE}`
191}
192
193async function get($: EngineInterface): Promise<Explorer> {
194 return { ...empty(), ...(await $.state.get(STATE)).value }
195}
196
197async function nodesOf($: EngineInterface, target: Target | null): Promise<TreeNode[]> {
198 const tree = (await $.state.get(TREE)).value
199 return tree && sameTarget(tree.target, target) ? tree.nodes : []
200}
201
202async function setTree($: EngineInterface, target: Target, nodes: TreeNode[]): Promise<TreeNode[] | null> {
203 for (let i = 0; i < 20; i++) {
204 if (!sameTarget((await get($)).target, target)) return null
205 const cur = await $.state.get(TREE)
206 const before = cur.value && sameTarget(cur.value.target, target) ? cur.value.nodes : []
207 const done = await $.state.set(TREE, { target, nodes }, { ifVersion: cur.version })
208 if (done.isSet) return before
209 }
210 return null
211}
212
213async function put($: EngineInterface, fn: (ex: Explorer) => Explorer): Promise<void> {
214 await update($, STATE, cur => fn({ ...empty(), ...cur }))
215}
216
217function patch($: EngineInterface, fn: (ex: Explorer) => Partial<Explorer>) {
218 return put($, ex => ({ ...ex, ...fn(ex) }))
219}
220
221const sameTarget = (a: Target | null, b: Target | null) => JSON.stringify(a) === JSON.stringify(b)
222
223function refresh($: EngineInterface): Promise<void> {
224 if (inflight) {
225 const rerun = () => {
226 queued = null
227 return refresh($)
228 }
229 queued ??= inflight.then(rerun, rerun)
230 return queued
231 }
232 inflight = doRefresh($).finally(() => {
233 inflight = null
234 })
235 return inflight
236}
237
238async function light($: EngineInterface, ids: string[], tone: string, running: boolean, run = ''): Promise<string> {
239 const unique = [...new Set(ids)]
240 const ex = await get($)
241 if (run && ex.work && ex.work.run !== run) return ''
242 if (!running && unique.length === 0) {
243 if (run) await settle($, run)
244 return ''
245 }
246 const mine = run || `${++runs}`
247 blink?.cancel()
248 blink = null
249 const at = await $.clock.now()
250 const nodes = await nodesOf($, ex.target)
251 let kept = false
252 await patch($, cur => {
253 if (run && cur.work && cur.work.run !== run) return {}
254 kept = true
255 const byId = new Map(nodes.map(n => [n.id, n]))
256 const open = new Set(cur.expanded)
257 const dim = new Set<string>()
258 for (const id of unique) {
259 const chain = ancestors(nodes, id, byId)
260 if (!chain.some(a => !open.has(a))) continue
261 for (const a of chain) {
262 if (!open.has(a)) dim.add(a)
263 if (follow) open.add(a)
264 }
265 }
266 for (const id of unique) dim.delete(id)
267 const root = rootOf(cur, nodes)
268 const away = follow && root !== '' && unique.some(id => id !== root && !ancestors(nodes, id, byId).includes(root))
269 const next: Explorer = { ...cur, expanded: [...open], root: away ? '' : cur.root }
270 const scroll = follow ? heldInView(next, nodes, [...unique, ...dim], unique[unique.length - 1] ?? '') : cur.scroll
271 return { work: { run: mine, tone, running, at }, flash: unique, flashDim: [...dim], expanded: next.expanded, scroll, ...(away ? { root: '' } : {}) }
272 })
273 if (!kept) return ''
274 if (!running) {
275 blink = $.clock.after(FLASH_MS, () => {
276 blink = null
277 quiet(settle($, mine))
278 })
279 if (ex.target && !closed) await openPane($, { id: PANE, title: titleFor(ex.target) })
280 }
281 return mine
282}
283
284async function settle($: EngineInterface, run: string): Promise<void> {
285 await patch($, cur => (cur.work?.run === run ? { work: null, flash: [], flashDim: [] } : {}))
286}
287
288function rootOf(ex: Explorer, nodes: TreeNode[]): string {
289 return ex.root && nodes.some(n => n.id === ex.root) ? ex.root : ''
290}
291
292function heldInView(ex: Explorer, nodes: TreeNode[], lit: string[], focus: string): Record<string, number> {
293 const rows = visible(ex, nodes, rootOf(ex, nodes))
294 const where = (id: string) => rows.findIndex(r => r.node.id === id)
295 const first = Math.min(...lit.map(where).filter(i => i >= 0))
296 const at = where(focus)
297 const out: Record<string, number> = {}
298 for (const [surface, from] of Object.entries(ex.scroll)) if (at >= 0 && first >= from && at < from + (views[surface]?.room ?? 0)) out[surface] = from
299 return out
300}
301
302function anchored(ex: Explorer, before: TreeNode[], after: TreeNode[], expanded: string[]): Record<string, number> {
303 const was = visible(ex, before, rootOf(ex, before))
304 const now = visible({ ...ex, expanded }, after, rootOf(ex, after))
305 const out: Record<string, number> = {}
306 for (const [surface, from] of Object.entries(ex.scroll)) {
307 const top = was[from]?.node.id
308 const at = top ? now.findIndex(r => r.node.id === top) : -1
309 out[surface] = at < 0 ? from : at
310 }
311 return out
312}
313
314async function point($: EngineInterface, target: Target | null, opened: 'asked' | 'unasked', fresh = false): Promise<boolean> {
315 const moved = !sameTarget((await get($)).target, target)
316 if (moved) {
317 await put($, cur => ({ ...empty(), target, ...(follow || opened === 'asked' ? {} : { scroll: cur.scroll }) }))
318 await $.state.set(TREE, { target, nodes: [] })
319 } else if (fresh) await patch($, () => ({ expanded: [], query: '', selected: '', detail: [], cursor: '', changed: [] }))
320 if (opened === 'asked' || (moved && target)) {
321 const title = titleFor(target)
322 if (opened === 'asked') {
323 closed = false
324 await openPane($, { id: PANE, title, focus: true })
325 } else if (!closed) await openPane($, { id: PANE, title })
326 }
327 return moved
328}
329
330async function goUp($: EngineInterface): Promise<void> {
331 const nodes = await nodesOf($, (await get($)).target)
332 await patch($, cur => {
333 const n = nodes.find(x => x.id === cur.root)
334 return { root: n?.parent ?? '', cursor: n?.id ?? cur.cursor, scroll: {} }
335 })
336}
337
338async function goHome($: EngineInterface): Promise<void> {
339 await patch($, () => ({ root: '', scroll: {} }))
340}
341
342async function press($: EngineInterface, ex: Explorer, n: TreeNode): Promise<void> {
343 const now = Date.now()
344 const isDouble = lastPress.key === n.id && now - lastPress.at < DOUBLE_MS
345 lastPress = { key: isDouble ? '' : n.id, at: now }
346 if (isDouble) await openNode($, await get($), n)
347 else await select($, ex.target, n)
348}
349
350async function openNode($: EngineInterface, ex: Explorer, n: TreeNode): Promise<void> {
351 if (n.kind === 'semantic model') return openWeb($, ex, n)
352 if (n.file) return openUrl($, n.file)
353 $.ui.toast('no file for this object')
354}
355
356async function openWeb($: EngineInterface, ex: Explorer, n: TreeNode): Promise<void> {
357 if (n.kind === 'semantic model') {
358 const model = await withBusy($, 'Finding the deployed model…', () => resolveModel($, ex.target))
359 if (model.url) await openUrl($, model.url)
360 else $.ui.toast(model.why)
361 return
362 }
363 const url = webUrl(ex, n)
364 if (url) await openUrl($, url)
365 else $.ui.toast('no Fabric link for this report; it opens in Fabric when its folder sits under <workspace>.Workspace')
366}
367
368let pending = ''
369
370async function withBusy<T>($: EngineInterface, text: string, fn: () => Promise<T>): Promise<T> {
371 pending = text
372 $.ui.invalidate('ui.render')
373 try {
374 return await fn()
375 } finally {
376 pending = ''
377 $.ui.invalidate('ui.render')
378 }
379}
380
381async function loadTenant($: EngineInterface): Promise<void> {
382 if (tenantId) return
383 const saved = (await $.store.get('tenant').catch(() => undefined)) as { id?: string } | undefined
384 if (saved?.id) {
385 tenantId = saved.id
386 return
387 }
388 try {
389 const run = await $.process.run(['fab', 'auth', 'status'], { timeoutMs: 30_000 })
390 const id = `${run.stdout}\n${run.stderr}`.match(/Tenant ID:\s*([0-9a-f-]{36})/i)?.[1]?.toLowerCase() ?? ''
391 if (!id) return
392 tenantId = id
393 await $.store.set('tenant', { id }).catch(() => undefined)
394 } catch {
395 return
396 }
397}
398
399function pageOf(n: TreeNode): string {
400 return n.id.match(/^R\/pages\/([^/]+)/)?.[1] ?? ''
401}
402
403function reportLink(portal: string, page: string): string {
404 const id = portal.match(/\/reports\/([0-9a-f-]{36})/i)?.[1] ?? ''
405 if (!id) return portal
406 if (reportLinks !== 'embed') return page ? `${portal}/${encodeURIComponent(page)}` : portal
407 return `https://app.powerbi.com/reportEmbed?reportId=${encodeURIComponent(id)}&autoAuth=true${tenantId ? `&ctid=${encodeURIComponent(tenantId)}` : ''}${page ? `&pageName=${encodeURIComponent(page)}` : ''}`
408}
409
410async function resolveModel($: EngineInterface, target: Target | null): Promise<{ url: string; lines: string[]; why: string }> {
411 if (target?.kind !== 'local') return { url: '', lines: [], why: 'no report is open' }
412 const hit = modelLinks.get(target.path)
413 if (hit) return { ...hit, why: '' }
414 let pbir: Record<string, unknown> | null = null
415 try {
416 pbir = JSON.parse(String(await $.fs.read(`${target.path}/definition.pbir`))) as Record<string, unknown>
417 } catch {
418 pbir = null
419 }
420 const ref = modelRef(pbir)
421 const home = target.path.match(/([^/]+)\.Workspace\/[^/]+\.Report$/)?.[1] ?? ''
422 const ws = ref.workspace || (ref.local ? home : '')
423 if (!ws) return { url: '', lines: [], why: ref.local ? `${ref.name || 'this model'} is a local model with no deployed copy to open` : 'the report connection names no workspace' }
424 const wsGuid = await fabId($, `${ws}.Workspace`)
425 if (!wsGuid) return { url: '', lines: [], why: `fab could not find workspace ${ws}` }
426 const id = /^[0-9a-f-]{36}$/i.test(ref.id) ? ref.id.toLowerCase() : ref.name ? await fabId($, `${ws}.Workspace/${ref.name}.SemanticModel`) : ''
427 if (!id) return { url: '', lines: [`Workspace: ${ws}`], why: `fab could not find ${ref.name || 'the model'} in ${ws}` }
428 const out = { url: `${workspaceUrl(wsGuid)}/datasets/${id}/details`, lines: [`Workspace: ${ws}`, `Model ID: ${id}`] }
429 modelLinks.set(target.path, out)
430 return { ...out, why: '' }
431}
432
433async function fabId($: EngineInterface, path: string): Promise<string> {
434 try {
435 const run = await $.process.run(['fab', 'get', path, '-q', 'id'], { timeoutMs: 30_000 })
436 return run.exitCode === 0 ? idOf(run.stdout) : ''
437 } catch {
438 return ''
439 }
440}
441
442async function targetUrl($: EngineInterface, ws: string, report: string): Promise<string> {
443 const wsId = await fabId($, `${ws}.Workspace`)
444 if (!wsId) return ''
445 const reportId = await fabId($, `${ws}.Workspace/${report}.Report`)
446 return reportId ? reportUrl(wsId, reportId) : workspaceUrl(wsId)
447}
448
449function webUrl(ex: Explorer, n: TreeNode): string {
450 if (n.kind === 'semantic model') return ex.target?.kind === 'local' ? (modelLinks.get(ex.target.path)?.url ?? '') : ''
451 return ex.targetUrl ? reportLink(ex.targetUrl, pageOf(n)) : ''
452}
453
454type Since = { ms: number; mark: string; os: 'linux' | 'darwin' | 'win32' }
455
456let markId = 0
457
458async function sinceNow($: EngineInterface, watch: boolean): Promise<Since> {
459 const ms = await $.clock.now()
460 if (!watch) return { ms, mark: '', os: 'linux' }
461 const os = await osName($)
462 if (os !== 'darwin') return { ms, mark: '', os }
463 const mark = `${((await $.env.get('TMPDIR')) || '/tmp').replace(/\/+$/, '')}/${PANE}-${await $.session.id()}-${++markId}.mark`
464 try {
465 await $.process.run(['touch', mark], { timeoutMs: 3_000 })
466 return { ms, mark, os }
467 } catch {
468 return { ms, mark: '', os }
469 }
470}
471
472async function dropMark($: EngineInterface, since: Since): Promise<void> {
473 if (since.mark) await $.process.run(['rm', '-f', since.mark], { timeoutMs: 3_000 }).catch(() => undefined)
474}
475
476async function changedUnder($: EngineInterface, dirs: string[], since: Since): Promise<string[]> {
477 if (since.os === 'win32') return []
478 const test = since.mark ? ['-newer', since.mark] : ['-newermt', `@${(since.ms / 1000).toFixed(3)}`]
479 try {
480 const run = await $.process.run(['find', '-H', ...dirs, '-name', '.git', '-prune', '-o', '(', '-type', 'f', '-o', '-type', 'd', ')', ...test, '-print'], {
481 timeoutMs: 8_000,
482 })
483 return run.stdout.split('\n').filter(Boolean).slice(0, 500)
484 } catch {
485 return []
486 }
487}
488
489async function directEdit($: EngineInterface, files: string[], run = ''): Promise<void> {
490 const t = (await get($)).target
491 const root = t?.kind === 'local' ? t.path.replace(/\/$/, '') : ''
492 if (!root || !files.some(f => f === root || f.startsWith(root + '/'))) {
493 if (run) await settle($, run)
494 return
495 }
496 await refresh($)
497 await light($, (await get($)).changed, 'orange', false, run)
498}
499
500function toggled(ex: Explorer, nodes: TreeNode[], n: TreeNode): Partial<Explorer> {
501 const open = new Set(ex.expanded)
502 if (nodes.some(c => c.parent === n.id)) open.has(n.id) ? open.delete(n.id) : open.add(n.id)
503 return { expanded: [...open], cursor: n.id, selected: n.id }
504}
505
506const tasks = new Map<string, ((ok: boolean) => Promise<void>)[]>()
507
508function backgroundOf(result: unknown): string {
509 const id = (result as { backgroundTaskId?: unknown } | undefined)?.backgroundTaskId
510 return typeof id === 'string' ? id : ''
511}
512
513function afterTask(id: string, done: (ok: boolean) => Promise<void>): void {
514 tasks.set(id, [...(tasks.get(id) ?? []), done])
515}
516
517async function taskEnded(text: string): Promise<void> {
518 for (const block of text.split('<task-notification>').slice(1)) {
519 const id = block.match(/<task-id>([^<]+)<\/task-id>/)?.[1]
520 const status = block.match(/<status>([^<]+)<\/status>/)?.[1]
521 const waiting = id && status ? tasks.get(id) : undefined
522 if (!id || !waiting) continue
523 tasks.delete(id)
524 for (const done of waiting) await done(status === 'completed')
525 }
526}
527
528const PBIR_READONLY = new Set(['ls', 'list', 'get', 'schema', 'auth', 'validate', 'diff', 'help', 'tree', 'find', 'search', 'info', 'show', 'dump', 'cat', '--help', '-h'])
529
530function readOnlyPbir(inv: Invocation): boolean {
531 return inv.args.filter(a => !a.startsWith('-')).slice(0, 2).some(a => PBIR_READONLY.has(a))
532}
533
534async function doRefresh($: EngineInterface): Promise<void> {
535 const target = (await get($)).target
536 if (!target || target.kind !== 'local') return
537 await patch($, () => ({ status: 'loading' }))
538 try {
539 const nodes = await loadReport(
540 {
541 text: async path => String(await $.fs.read(path)),
542 list: async path => (await $.fs.list(path)).map(e => ({ name: e.name, kind: e.kind })),
543 exists: path => $.fs.exists(path),
544 },
545 target.path,
546 )
547 const before = await setTree($, target, nodes)
548 if (!before) return
549 await patch($, cur => {
550 if (!sameTarget(cur.target, target)) return {}
551 const sel = cur.selected ? nodes.find(n => n.id === cur.selected) : undefined
552 const picked = !cur.selected ? {} : sel ? { detail: [...reportDetail(sel, target.path), ...(sel.kind === 'semantic model' ? cur.detail.filter(l => /^(Workspace|Model ID|Fabric): /.test(l)) : [])] } : { selected: '', detail: [] }
553 const expanded = before.length ? cur.expanded : nodes.filter(n => !n.parent).map(n => n.id)
554 return { changed: diff(before, nodes), expanded, status: '', ...picked, ...(follow ? {} : { scroll: anchored(cur, before, nodes, expanded) }) }
555 })
556 const m = target.path.match(/([^/]+)\.Workspace\/([^/]+)\.Report$/)
557 if (m?.[1] && m[2] && !(await get($)).targetUrl) {
558 const [url] = await Promise.all([targetUrl($, m[1], m[2]), loadTenant($)])
559 await patch($, c => (sameTarget(c.target, target) ? { targetUrl: url } : {}))
560 }
561 } catch (err) {
562 await patch($, cur => (sameTarget(cur.target, target) ? { status: `error: ${err instanceof Error ? err.message : String(err)}` } : {}))
563 }
564}
565
566function toneOf(calls: Invocation[]): string {
567 return calls.some(inv => !readOnlyPbir(inv)) ? 'orange' : 'purple'
568}
569
570async function followPbir($: EngineInterface, calls: Invocation[], run: string): Promise<void> {
571 const ran = calls.filter(inv => !inv.maybe)
572 for (const inv of ran) pbirBin = binOf(inv.bin, inv.cwd, 'pbir')
573 let dirty = false
574 for (const inv of calls) {
575 const path = inv.maybe ? null : pbirReport(inv)
576 if (path && (await point($, { kind: 'local', path }, 'unasked'))) dirty = true
577 if (!readOnlyPbir(inv) && !inv.args.includes('--dry-run')) dirty = true
578 }
579 quiet(
580 (async () => {
581 if (dirty) await refresh($)
582 const cur = await get($)
583 const nodes = await nodesOf($, cur.target)
584 await light($, [...(dirty ? cur.changed : []), ...ran.flatMap(inv => pbirTouched(inv, nodes))], toneOf(calls), false, run)
585 })(),
586 )
587}
588
589async function openShell($: EngineInterface, ex: Explorer): Promise<void> {
590 const t = ex.target
591 if (t?.kind !== 'local') return
592 const parent = t.path.replace(/\/[^/]+$/, '') || '/'
593 await terminal($, ['bash', '-lc', 'cd "$1" && "$2" -i; exec bash', '_', parent, pbirBin], [pbirBin, '-i'], parent)
594}
595
596async function select($: EngineInterface, target: Target | null, n: TreeNode): Promise<void> {
597 const nodes = await nodesOf($, target)
598 const node = nodes.find(x => x.id === n.id)
599 if (!node || target?.kind !== 'local') return
600 const detail = reportDetail(node, target.path)
601 await patch($, cur => (sameTarget(cur.target, target) ? { ...toggled(cur, nodes, node), detail } : {}))
602 if (node.kind !== 'semantic model') return
603 const model = await resolveModel($, target).catch(() => null)
604 const more = model ? (model.lines.length ? model.lines : [`Fabric: ${model.why}`]) : []
605 if (more.length) await patch($, cur => (sameTarget(cur.target, target) && cur.cursor === node.id ? { detail: [...detail, ...more] } : {}))
606}
607
608function contextFor(ex: Explorer, n: TreeNode): string {
609 const t = ex.target
610 return [
611 'The user has this report object selected in the Report pane; "this", "it" or "the selected" in the prompt likely refers to it.',
612 `${n.kind}: ${n.name}`,
613 `pbir report folder: ${t?.kind === 'local' ? t.path : ''}`,
614 ...ex.detail.slice(1),
615 ].join('\n')
616}
617
618function guides(depth: number): string {
619 const lines = Array.from({ length: depth }, (_, i) => `<rect x="${i * 16 + 7.5}" y="0" width="1" height="${ROW_PX}" fill="#34343c"/>`).join('')
620 return `<svg xmlns="${SVG_NS}" width="${depth * 16}" height="${ROW_PX}" viewBox="0 0 ${depth * 16} ${ROW_PX}">${lines}</svg>`
621}
622
623function wholeArg(args: string | undefined): string {
624 const raw = (args ?? '').trim()
625 return /^["']/.test(raw) ? (tokenize(raw)[0] ?? '') : raw
626}
627
628export const register: Register = (on, options) => {
629 glyphSetting = typeof options?.glyphs === 'string' ? options.glyphs : 'auto'
630 follow = options?.follow !== 'off'
631 fontHint = options?.fontHint !== 'off'
632 reportLinks = options?.reportLinks === 'portal' ? 'portal' : 'embed'
633
634 on('session.start', async ($, e, next) => {
635 const windows = (await $.env.get('OS')) === 'Windows_NT'
636 useDrives(windows)
637 useHome(posix((await $.env.get('HOME')) || (windows ? await $.env.get('USERPROFILE') : '') || ''))
638 hinted = false
639 fellBack = false
640 pbirBin = 'pbir'
641 lastPress = { key: '', at: 0 }
642 quiet(detectGlyphs($).then(() => $.ui.invalidate('ui.render')))
643 await patch($, () => ({ flash: [], flashDim: [], work: null }))
644 await $.command.register({ name: PANE, description: 'Open the Report pane; args: <path to .Report>' })
645 const ex = await get($)
646 if (ex.target) quiet(openPane($, { id: PANE, title: titleFor(ex.target) }))
647 return next(e)
648 })
649
650 on('command.run', { command: PANE }, async ($, e) => {
651 const terminalOnly = !(await $.session.surfaces()).includes('desktop')
652 if (terminalOnly && e.presentation && !e.presentation.isFullscreen) return { text: 'The Report pane shows in the sidebar, which needs the fullscreen layout. Run /tui fullscreen, then /report-pane.' }
653 if (terminalOnly && e.presentation && e.presentation.columns < 110) return { text: 'The Report pane shows in the sidebar, which needs a terminal at least 110 columns wide. Widen it, then run /report-pane.' }
654 noDock = false
655 fellBack = false
656 await detectGlyphs($)
657 const cwd = await cwdOf($)
658 let target = (await get($)).target
659 const first = wholeArg(e.args)
660 if (first) target = { kind: 'local', path: join(cwd, first.replace(/\/$/, '')) }
661 await point($, target, 'asked', Boolean(first))
662 quiet(refresh($))
663 return { text: target ? `Report pane on ${targetLabel(target)}.` : 'Report pane open; no report yet.' }
664 })
665
666 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
667 const command = e.tool === 'Bash' ? e.command : ''
668 if (!/\bpbir\b/.test(command)) return next(e)
669 const calls = invocations(command, await cwdOf($))
670 if (calls.length === 0) return next(e)
671 const ex = await get($)
672 const here = calls.filter(inv => {
673 const p = pbirReport(inv)
674 return ex.target && (!p || (ex.target.kind === 'local' && ex.target.path === p))
675 })
676 const nodes = here.length ? await nodesOf($, ex.target) : []
677 const run = here.length ? await light($, here.flatMap(inv => (inv.maybe ? [] : pbirTouched(inv, nodes))), toneOf(calls), true) : ''
678 let result: Awaited<ReturnType<typeof next>>
679 try {
680 result = await next(e)
681 } catch (err) {
682 if (run) await settle($, run)
683 throw err
684 }
685 const task = result.deny || result.isError ? '' : backgroundOf(result.result)
686 if (task) {
687 afterTask(task, async ok => {
688 if (ok) await followPbir($, calls, run)
689 else if (run) await settle($, run)
690 })
691 return result
692 }
693 if (result.deny || result.isError) {
694 if (run) await settle($, run)
695 return result
696 }
697 await followPbir($, calls, run)
698 return result
699 })
700
701 on('tool.call', async ($, e, next) => {
702 if (e.tool !== 'Edit' && e.tool !== 'Write' && e.tool !== 'Bash') return next(e)
703 const command = e.tool === 'Bash' ? e.command : ''
704 const viaCli = e.tool === 'Bash' && invocations(command, await cwdOf($)).length > 0
705 const t = (await get($)).target
706 const watched = e.tool === 'Bash' && !viaCli && t?.kind === 'local' ? [t.path] : []
707 const file = e.tool === 'Bash' ? '' : join(await cwdOf($), e.file_path)
708 const inside = file !== '' && t?.kind === 'local' && file.startsWith(t.path.replace(/\/$/, '') + '/')
709 const run = inside ? await light($, [], 'orange', true) : ''
710 const since = await sinceNow($, watched.length > 0)
711 let result: Awaited<ReturnType<typeof next>>
712 try {
713 result = await next(e)
714 } catch (err) {
715 quiet(dropMark($, since))
716 if (run) await settle($, run)
717 throw err
718 }
719 if (result.deny || result.isError) {
720 quiet(dropMark($, since))
721 if (run) await settle($, run)
722 return result
723 }
724 if (file) {
725 const root = file.match(/^(.*?\.Report)\//)?.[1]
726 if (root && !inside) await point($, { kind: 'local', path: root }, 'unasked')
727 quiet(directEdit($, [file], run))
728 } else if (watched.length) {
729 const scan = async () => {
730 try {
731 await directEdit($, await changedUnder($, watched, since))
732 } finally {
733 await dropMark($, since)
734 }
735 }
736 const task = backgroundOf(result.result)
737 if (task) afterTask(task, ok => (ok ? scan() : dropMark($, since)))
738 else quiet(scan())
739 }
740 return result
741 })
742
743 on('session.append', async ($, e, next) => {
744 if (tasks.size && e.door !== 'tool-result' && e.message.type !== 'assistant') quiet(taskEnded(JSON.stringify(e.message.content)))
745 return next(e)
746 })
747
748 on('ui.close', async ($, e, next) => {
749 const result = await next(e)
750 if (e.id === PANE && e.origin.kind === 'person') closed = true
751 return result
752 })
753
754 on('ui.message', async ($, e, next) => {
755 if (e.requestId === PANE && e.element.startsWith('z:') && e.data && typeof e.data === 'object') {
756 const data = e.data as { zone?: unknown; ctrl?: unknown; shift?: unknown }
757 const id = typeof data.zone === 'string' ? data.zone : ''
758 if (id === PROPS) {
759 propsOpen = !propsOpen
760 $.ui.invalidate('ui.render')
761 return {}
762 }
763 const ex = await get($)
764 const n = (await nodesOf($, ex.target)).find(x => x.id === id)
765 if (n && data.ctrl) quiet(openWeb($, ex, n))
766 else if (n && data.shift) quiet(openShell($, ex))
767 else if (n) quiet(press($, ex, n))
768 return {}
769 }
770 if (e.requestId !== PANE || e.element !== 'rows' || !e.data || typeof e.data !== 'object') return next(e)
771 const data = e.data as { press?: unknown; key?: unknown; ctrl?: unknown; shift?: unknown; scrollTo?: unknown; copy?: unknown }
772 const ex = await get($)
773 if (typeof data.scrollTo === 'number') {
774 const to = Math.round(Math.max(0, Math.min(1, data.scrollTo)) * (views[e.surface]?.max ?? 0))
775 if (to !== ex.scroll[e.surface]) await patch($, cur => ({ scroll: { ...cur.scroll, [e.surface]: to } }))
776 return {}
777 }
778 const nodes = await nodesOf($, ex.target)
779 if (typeof data.copy === 'string') {
780 const n = nodes.find(x => x.id === data.copy)
781 if (n) await copyOf($, n.path || n.name, e.surface)
782 return {}
783 }
784 if (typeof data.press === 'string') {
785 const n = nodes.find(x => x.id === data.press)
786 if (!n) return {}
787 if (ex.scroll[e.surface] === undefined) await patch($, cur => ({ scroll: { ...cur.scroll, [e.surface]: views[e.surface]?.from ?? 0 } }))
788 if (data.ctrl) await openWeb($, ex, n)
789 else if (data.shift) await openShell($, ex)
790 else await press($, ex, n)
791 return {}
792 }
793 if (typeof data.key !== 'string') return {}
794 const rows = visible(ex, nodes, rootOf(ex, nodes))
795 const at = rows.findIndex(r => r.node.id === ex.cursor)
796 const cur = rows[at]
797 const move = (d: number) => {
798 const target = rows[Math.max(0, Math.min(rows.length - 1, (at < 0 ? 0 : at) + d))]
799 return target ? patch($, () => ({ cursor: target.node.id, scroll: {} })) : Promise.resolve()
800 }
801 if (data.key === 'up' || data.key === 'k') await move(-1)
802 else if (data.key === 'down' || data.key === 'j') await move(1)
803 else if (data.key === 'pageup') await move(-10)
804 else if (data.key === 'pagedown') await move(10)
805 else if (data.key === 'home') await move(-rows.length)
806 else if (data.key === 'end') await move(rows.length)
807 else if (cur && (data.key === 'y' || data.key === 'Y')) await copyOf($, cur.node.path || cur.node.name, e.surface)
808 else if (cur && (data.key === 'right' || data.key === 'l') && !cur.leaf && !cur.open) await select($, ex.target, cur.node)
809 else if (cur && (data.key === 'left' || data.key === 'h')) {
810 if (!cur.leaf && cur.open) await patch($, x => ({ expanded: x.expanded.filter(id => id !== cur.node.id) }))
811 else if (cur.node.parent) await patch($, () => ({ cursor: cur.node.parent }))
812 } else if (cur && (data.key === ' ' || data.key === 'return')) await (data.key === 'return' && cur.leaf ? openNode($, ex, cur.node) : select($, ex.target, cur.node))
813 return {}
814 })
815
816 on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
817 if (nativeScroll) return next(e)
818 const ex = await get($)
819 const known = Object.keys(views)
820 const sized = known.filter(s => views[s]?.rows === e.bodyRows)
821 const step = Math.sign(e.by) * Math.max(3, Math.abs(e.by))
822 const moved: Record<string, number> = {}
823 for (const s of sized.length ? sized : known) {
824 const v = views[s]
825 if (v) moved[s] = Math.max(0, Math.min(v.max, (ex.scroll[s] ?? v.from) + step))
826 }
827 if (Object.entries(moved).some(([s, to]) => to !== ex.scroll[s])) await patch($, cur => ({ scroll: { ...cur.scroll, ...moved } }))
828 return {}
829 })
830
831 on('prompt.submit', async ($, e, next) => {
832 const ex = await get($)
833 const n = ex.selected && ex.target ? (await nodesOf($, ex.target)).find(x => x.id === ex.selected) : undefined
834 const hint = fontNote()
835 const context = [...(e.context ?? []), ...(n ? [contextFor(ex, n)] : []), ...(hint ? [hint] : [])]
836 return context.length === (e.context ?? []).length ? next(e) : next({ ...e, context })
837 })
838
839
840 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
841 if (e.surface !== 'terminal' && e.surface !== 'desktop') return next(e)
842 if (e.surface === 'terminal' && e.props.placement === 'inline') {
843 noDock = true
844 quiet($.ui.close({ id: PANE }))
845 const { Box: Empty } = $.ui.resolve(e)
846 return <Empty />
847 }
848 const tier = tierFor(e.surface)
849 if (e.surface === 'terminal' && tier === 'plain' && glyphSetting === 'auto') fellBack = true
850 const table = $.ui.resolve(e)
851 const { Box, Text, Button, Input, Client } = table
852 const Svg = 'Svg' in table ? table.Svg : undefined
853 const native = e.surface === 'desktop' && Boolean(Svg)
854 nativeScroll = native
855 const ex = await get($)
856 const nodes = await nodesOf($, ex.target)
857 const now = await $.clock.now()
858 const work = ex.work && (!ex.work.running || now - ex.work.at < BUSY_MAX_MS) ? ex.work : null
859 const tone = work?.tone ?? ''
860 const brightSet = new Set(work ? ex.flash : [])
861 const dimSet = new Set(work ? ex.flashDim : [])
862 const width = Math.max(20, e.props.bodyColumns)
863 const rootId = rootOf(ex, nodes)
864 const rows = visible(ex, nodes, rootId)
865 const changed = new Set(ex.changed)
866 const detailRows = ex.detail.length ? Math.min(ex.detail.length, DETAIL_ROWS) + 4 : 0
867 const room = Math.max(5, Math.min(WINDOW, (e.props.scroll?.bodyRows ?? 40) - 4 - detailRows - (pending ? 1 : 0) - (nodes.length === 0 ? 1 : 0)))
868 const focusId = follow && work && ex.flash.length ? (ex.flash[ex.flash.length - 1] ?? ex.cursor) : ex.cursor
869 const at = Math.max(0, rows.findIndex(r => r.node.id === focusId))
870 const isLit = (id: string) => brightSet.has(id) || dimSet.has(id)
871 const lit = follow && work ? rows.findIndex(r => isLit(r.node.id)) : -1
872 const fits = lit >= 0 && at - lit < room - 2
873 const base = Math.max(0, Math.min(Math.max(0, rows.findIndex(r => r.node.id === ex.cursor)) - Math.floor(room / 2), rows.length - room))
874 const inView = lit >= base && at < base + room
875 const flashing = lit >= 0 && !inView
876 const nearBottom = (span: number) => Math.max(0, Math.min(fits ? Math.min(Math.max(0, lit - 1), at - span + 3) : at - span + 3, rows.length - span))
877 let from = flashing ? nearBottom(room) : base
878 const cap = Math.max(1, Math.floor(room / 3))
879 const chain = new Set(flashing ? ancestors(nodes, focusId) : [])
880 const keep = (id: string) => chain.has(id) || isLit(id)
881 let pinned = flashing ? rows.slice(0, from).filter(r => keep(r.node.id)).slice(-cap) : []
882 if (pinned.length) {
883 from = nearBottom(Math.max(3, room - pinned.length - 1))
884 pinned = rows.slice(0, from).filter(r => keep(r.node.id)).slice(-cap)
885 }
886 const max = Math.max(0, rows.length - room)
887 const held = ex.scroll[e.surface]
888 if (held !== undefined) {
889 from = Math.max(0, Math.min(held, max))
890 pinned = []
891 }
892 if (!native) views[e.surface] = { from, max, rows: e.props.scroll?.bodyRows ?? 40, room }
893 const shown = rows.slice(from, from + room - pinned.length)
894 const clip = (s: string, max = width) => (s.length > max ? s.slice(0, max - 1) + '…' : s)
895 const noteOf = (n: TreeNode) => (n.note ? (n.kind === 'visual' ? visualLabel(n.note) : n.note) : '')
896 const rowSpec = (r: Row): RowSpec => {
897 const n = r.node
898 const g = glyph(n, tier)
899 const arrow = r.leaf ? ' ' : tier === 'plain' ? (r.open ? '▾ ' : '▸ ') : r.open ? '\u{f47c} ' : '\u{f460} '
900 const note = noteOf(n) ? ` ${noteOf(n)}` : ''
901 const cols = Math.max(4, width - r.depth * 2 - 6 - note.length)
902 const isBright = brightSet.has(n.id)
903 const isDim = !isBright && dimSet.has(n.id)
904 const name = clip(n.name, cols)
905 const faded = n.hidden
906 const left: Seg[] = [
907 { t: changed.has(n.id) ? '*' : ' ', c: '#e5c07b' },
908 { t: ' '.repeat(r.depth) },
909 { t: arrow, c: '#7a7a86' },
910 isBright || isDim ? { t: g.char + ' ', sh: tone, dim: isDim, one: true } : { t: g.char + ' ', c: faded ? MUTED : g.color },
911 isBright || isDim ? { t: name, sh: tone, dim: isDim, b: isBright } : { t: name, c: faded ? MUTED : g.label, b: n.id === ex.selected },
912 ]
913 return { id: n.id, left: clean(left), right: note ? [{ t: note, c: MUTED }] : [] }
914 }
915 const note = (text: string): RowSpec => ({ id: '', left: [{ t: text, c: MUTED }], right: [] })
916 const specs: RowSpec[] = [...pinned.map(rowSpec), ...(pinned.length > 0 ? [note(' ⋮')] : []), ...shown.map(rowSpec)]
917 const barSize = Math.max(1, Math.round((specs.length * shown.length) / Math.max(1, rows.length)))
918 const bar =
919 rows.length > shown.length + pinned.length
920 ? { pos: max ? Math.round((from / max) * (specs.length - barSize)) : 0, size: barSize, thumb: '#5b9bd5', track: '#4a4a56' }
921 : undefined
922 const icon = (nerd: string, fallback: string) => (tier === 'plain' ? fallback : nerd)
923 const rootNode = nodes.find(n => n.id === rootId)
924 const headName = rootNode ? rootNode.name : ex.target ? targetLabel(ex.target) : TITLE
925 const loadingNow = ex.status === 'loading'
926 const statusSegs: Seg[] = loadingNow ? [{ t: ' ' }, { t: '', spin: true }, { t: ' loading', c: MUTED }] : ex.status ? [{ t: ` ${ex.status}`, c: MUTED }] : []
927 const head: RowSpec = {
928 id: '',
929 left: clean([
930 { t: `${titleGlyph(tier)} `, c: TITLE_COLOR },
931 { t: headName, b: true },
932 ...statusSegs,
933 ...(ex.changed.length ? [{ t: ` ${ex.changed.length} changed`, c: '#e5c07b' }] : []),
934 ]),
935 right: [],
936 }
937 const busyRow = (key: string, text: string) => (
938 <Client key={key} module="./rows.tsx" props={{ rows: [{ id: '', left: [{ t: '', spin: true }, { t: ` ${text}`, c: MUTED }], right: [] }], active: '', activeBg: '', hoverBg: '', tones: TONES } satisfies RowsProps} />
939 )
940 const icon16 = (source: string | undefined, alt: string, fallback: Seg, key: string) =>
941 native && Svg && source ? <Svg key={key} source={source} alt={alt} width={16} height={16} /> : <Text key={key} color={fallback.c}>{fallback.t}</Text>
942 const rule = (key: string) => <Text key={key} color="#2e2e34" wrap="truncate-end">{'─'.repeat(width)}</Text>
943 const shownNode = nodes.find(n => n.id === ex.selected)
944 const details = ex.detail.slice(1, DETAIL_ROWS).map(l => {
945 const cut = l.indexOf(': ')
946 const key = cut > 0 ? l.slice(0, cut) : ''
947 return { key: key === 'pbir path' ? 'Path' : key, value: (cut > 0 ? l.slice(cut + 2) : l).replace(/\s+/g, ' ') }
948 })
949 type Action = { key: string; svg: string; nerd: string; plain: string; label: string; run: (surface: string) => void }
950 const actions: Action[] = shownNode
951 ? [
952 ...(shownNode.file && shownNode.kind !== 'semantic model' ? [{ key: 'file', svg: 'ui:open', nerd: '\u{f0214}', plain: '↗', label: 'Open file', run: () => quiet(openUrl($, shownNode.file ?? '')) }] : []),
953 ...(shownNode.kind === 'semantic model' || webUrl(ex, shownNode) ? [{ key: 'web', svg: 'ui:open', nerd: '\u{f0379}', plain: '↗', label: 'Open in Fabric', run: () => quiet(openWeb($, ex, shownNode)) }] : []),
954 ...(shownNode.kind === 'report' ? [{ key: 'pbir', svg: 'ui:open', nerd: '\u{f018d}', plain: '›', label: 'pbir shell', run: () => quiet(openShell($, ex)) }] : []),
955 ...(shownNode.path ? [{ key: 'copy', svg: 'ui:copy', nerd: '\u{f018f}', plain: '⧉', label: 'Copy path', run: (surface: string) => quiet(copyOf($, shownNode.path, surface)) }] : []),
956 ]
957 : []
958 const actionRow = (
959 <Box flexDirection="row" alignItems="center" gap={2}>
960 {actions.map(a => (
961 <Box key={`a:${a.key}`} flexDirection="row" alignItems="center" gap={1}>
962 {native ? icon16(FABRIC_SVG[a.svg], a.label, { t: '', c: MUTED }, `ai:${a.key}`) : null}
963 <Button key={a.key} plain label={native ? a.label : `${icon(a.nerd, a.plain)} ${a.label}`} onPress={p => a.run(p.surface)} />
964 </Box>
965 ))}
966 </Box>
967 )
968 const toggles = (
969 <Box flexDirection="row" alignItems="center" gap={native ? 1 : 2}>
970 {rootNode && <Button key="up" plain dimColor label={icon('\u{f005d}', '↑')} onPress={() => quiet(goUp($))} />}
971 {rootNode && <Button key="home" plain dimColor label={icon('\u{f02dc}', '⌂')} onPress={() => quiet(goHome($))} />}
972 <Button key="refresh" plain dimColor label={icon('\u{f0450}', '↻')} onPress={() => quiet(refresh($))} />
973 <Button key="collapse" plain dimColor label={icon('\u{eac5}', '⊟')} onPress={() => quiet(patch($, () => ({ expanded: [] })))} />
974 <Text> </Text>
975 </Box>
976 )
977 const search = (focus: boolean) => (
978 <Input
979 key="q"
980 placeholder="Filter, or Enter to jump"
981 {...(focus ? { autoFocus: true as const } : {})}
982 value={ex.query}
983 onInput={(v: string) => quiet(patch($, () => ({ query: v })))}
984 onSubmit={(v: string) => quiet(patch($, cur => jumpTo(cur, nodes, v)))}
985 />
986 )
987 const empty = !ex.target ? HINT : nodes.length === 0 && !loadingNow ? 'nothing loaded yet' : ''
988 if (native) {
989 const body = Math.max(10, e.props.scroll?.bodyRows ?? 30)
990 const lead = (d: number, key: string) => (Svg && d > 0 ? <Svg key={key} source={guides(d)} alt={`level ${d}`} width={d * 16} height={ROW_PX} /> : <Box key={key} width={d * 2} />)
991 const nativeRow = (r: Row) => {
992 const n = r.node
993 const g = glyph(n, 'plain')
994 const noteText = noteOf(n)
995 const label = clip(n.name, Math.max(4, width - r.depth * 2 - 8 - noteText.length))
996 const lit = brightSet.has(n.id) || dimSet.has(n.id)
997 return (
998 <Box key={`n:${n.id}`} position="relative" height={1} overflow="hidden" flexDirection="row" alignItems="center" backgroundColor={n.id === ex.cursor ? '#2a2d34' : undefined} hover={{ backgroundColor: '#232529' }}>
999 {lead(r.depth, `g:${n.id}`)}
1000 <Box width={2} flexShrink={0} flexDirection="row" alignItems="center">
1001 {r.leaf ? null : icon16(FABRIC_SVG[r.open ? 'ui:chevron-down' : 'ui:chevron-right'], r.open ? 'collapse' : 'expand', { t: r.open ? '⌄' : '›', c: MUTED }, `c:${n.id}`)}
1002 </Box>
1003 <Box flexDirection="row" alignItems="center" gap={1} flexShrink={1}>
1004 {icon16(FABRIC_SVG[SVG_KIND[n.kind] ?? ''], n.kind, { t: g.char, c: g.color }, `i:${n.id}`)}
1005 <Text color={n.hidden ? MUTED : lit ? TONES[tone]?.bright[1] : undefined} bold={n.id === ex.selected} wrap="truncate-end">{label}</Text>
1006 {changed.has(n.id) ? <Text color="#e5c07b">*</Text> : null}
1007 </Box>
1008 <Box flexGrow={1} />
1009 {noteText ? <Text color={MUTED}>{noteText}</Text> : null}
1010 <Box position="absolute" top={0} left={0} right={0} bottom={0}>
1011 <Client key={`z:${n.id}`} module="./zone.tsx" props={{ id: n.id } satisfies ZoneProps} width="100%" height="100%" />
1012 </Box>
1013 </Box>
1014 )
1015 }
1016 const at = shownNode ? rows.findIndex(r => r.node.id === shownNode.id) : -1
1017 const depth = at >= 0 ? (rows[at]?.depth ?? 0) + 1 : 1
1018 const propRow = (key: string, d: number, child: unknown) => (
1019 <Box key={key} height={1} overflow="hidden" flexDirection="row" alignItems="center" gap={1}>
1020 {lead(d, `${key}:g`)}
1021 {child as never}
1022 </Box>
1023 )
1024 const propLines =
1025 shownNode && ex.detail.length > 0
1026 ? [
1027 <Box key="pr:head" position="relative" height={1} overflow="hidden" flexDirection="row" alignItems="center" gap={1} hover={{ backgroundColor: '#232529' }}>
1028 {lead(depth, 'pr:head:g')}
1029 {icon16(FABRIC_SVG[propsOpen ? 'ui:chevron-down' : 'ui:chevron-right'], propsOpen ? 'collapse' : 'expand', { t: propsOpen ? '⌄' : '›', c: MUTED }, 'pr:chev')}
1030 {icon16(FABRIC_SVG['tenant settings'], 'Properties', { t: '⚙', c: MUTED }, 'pr:icon')}
1031 <Text color={MUTED}>Properties</Text>
1032 <Box position="absolute" top={0} left={0} right={0} bottom={0}>
1033 <Client key={`z:${PROPS}`} module="./zone.tsx" props={{ id: PROPS } satisfies ZoneProps} width="100%" height="100%" />
1034 </Box>
1035 </Box>,
1036 ...(propsOpen
1037 ? [
1038 ...details.map((d, i) =>
1039 propRow(
1040 `pr:p:${i}`,
1041 depth + 1,
1042 <Box flexDirection="row" gap={1} flexGrow={1} flexShrink={1}>
1043 <Box width={12} flexShrink={0}>
1044 <Text color={MUTED}>{d.key}</Text>
1045 </Box>
1046 <Box flexShrink={1}>
1047 <Text wrap="truncate-end">{d.value}</Text>
1048 </Box>
1049 </Box>,
1050 ),
1051 ),
1052 ...(actions.length ? [propRow('pr:actions', depth + 1, actionRow)] : []),
1053 ]
1054 : []),
1055 ]
1056 : []
1057 const headRows = 4 + (pending ? 1 : 0) + (empty ? 1 : 0)
1058 const lines = at >= 0 ? rows.flatMap((r, i) => (i === at ? [nativeRow(r), ...propLines] : [nativeRow(r)])) : rows.map(nativeRow)
1059 const offset = e.props.scroll?.offset ?? 0
1060 const first = Math.max(0, offset - headRows - body)
1061 const last = Math.min(lines.length, offset - headRows + body * 2)
1062 return (
1063 <Box flexDirection="column">
1064 <Box key="desk-head" height={1} flexDirection="row" alignItems="center">
1065 <Box flexGrow={1} flexShrink={1} flexDirection="row" alignItems="center" gap={1}>
1066 {icon16(FABRIC_SVG.Report, 'Power BI report', { t: titleGlyph(tier), c: TITLE_COLOR }, 'logo')}
1067 <Text bold wrap="truncate-end">{headName}</Text>
1068 {loadingNow ? <Box height={1}>{busyRow('loading', 'loading')}</Box> : ex.status ? <Text color={MUTED} wrap="truncate-end">{ex.status}</Text> : null}
1069 {ex.changed.length ? <Text color="#e5c07b">{`${ex.changed.length} changed`}</Text> : null}
1070 </Box>
1071 {toggles}
1072 </Box>
1073 <Box height={3} flexDirection="row" alignItems="center" gap={1} overflow="hidden">
1074 <Box flexGrow={1} flexShrink={1} width="100%">
1075 {search(false)}
1076 </Box>
1077 {ex.query ? <Button key="clearq" plain dimColor label="×" onPress={() => quiet(patch($, () => ({ query: '' })))} /> : null}
1078 </Box>
1079 {pending ? <Box height={1}>{busyRow('pending', pending)}</Box> : null}
1080 {empty ? (
1081 <Box height={1}>
1082 <Text color={MUTED}>{empty}</Text>
1083 </Box>
1084 ) : null}
1085 <Box key="tree" flexDirection="column">
1086 {first > 0 ? <Box key="above" height={first} /> : null}
1087 {lines.slice(first, Math.max(first, last))}
1088 {last < lines.length ? <Box key="below" height={lines.length - Math.max(first, last)} /> : null}
1089 </Box>
1090 </Box>
1091 )
1092 }
1093 return (
1094 <Box flexDirection="column" minHeight={Math.max(1, e.props.scroll?.bodyRows ?? 1)}>
1095 <Client key="head" module="./rows.tsx" props={{ rows: [head], active: '', activeBg: '', hoverBg: '', tones: TONES } satisfies RowsProps} />
1096 <Box flexDirection="row" alignItems="center" marginTop={1} marginBottom={1} gap={1}>
1097 <Box flexGrow={1} flexShrink={1} width="100%">
1098 {work && !ex.query ? (
1099 <Client key="working" module="./rows.tsx" props={{ rows: [{ id: '', left: [{ t: '', spin: true }, { t: ' ' }, { t: tier === 'plain' ? '*' : '\u{ec82}', claude: true }, { t: ' Claude is working in Power BI...', sh: 'orange' }], right: [] }], active: '', activeBg: '', hoverBg: '', tones: TONES } satisfies RowsProps} />
1100 ) : (
1101 search(true)
1102 )}
1103 </Box>
1104 {ex.query ? <Button key="clearq" plain dimColor label={icon('\u{f0156}', '×')} onPress={() => quiet(patch($, () => ({ query: '' })))} /> : null}
1105 {toggles}
1106 </Box>
1107 {pending ? busyRow('pending', pending) : null}
1108 {empty ? <Text color={MUTED}>{empty}</Text> : null}
1109 <Client key="rows" module="./rows.tsx" props={{ rows: specs, active: ex.cursor, activeBg: '#3e4451', hoverBg: '#2d2f33', tones: TONES, ...(bar ? { bar } : {}) } satisfies RowsProps} />
1110 <Box flexGrow={1} />
1111 {shownNode && ex.detail.length > 0 && (
1112 <Box key="details" flexDirection="column">
1113 {rule('rule-top')}
1114 <Box flexDirection="row" alignItems="center" gap={1} marginBottom={1}>
1115 <Text color={glyph(shownNode, tier).color}>{glyph(shownNode, tier).char}</Text>
1116 <Text bold wrap="truncate-end">{shownNode.name}</Text>
1117 <Box flexGrow={1} />
1118 <Button key="clear" plain dimColor label={icon('\u{f0156}', '✕')} onPress={() => quiet(patch($, () => ({ selected: '', detail: [] })))} />
1119 </Box>
1120 {details.map((d, i) => (
1121 <Box key={`p:${i}`} flexDirection="row" gap={1}>
1122 <Box width={12} flexShrink={0}>
1123 <Text color={MUTED}>{d.key}</Text>
1124 </Box>
1125 <Box flexShrink={1}>
1126 <Text wrap="truncate-end">{d.value}</Text>
1127 </Box>
1128 </Box>
1129 ))}
1130 {actions.length > 0 && rule('rule-actions')}
1131 {actions.length > 0 && actionRow}
1132 </Box>
1133 )}
1134 </Box>
1135 )
1136 })
1137}
1138hooks/open.ts 41 lines1export const LINUX_LAUNCH = 'setsid -f -w "$@" </dev/null >/dev/null 2>&1 & p=$!; sleep 1; kill -0 "$p" 2>/dev/null && exit 0; wait "$p"'
2
3export const LINUX_OPEN = [
4 'set -f',
5 'f=$1',
6 'if command -v gio >/dev/null; then',
7 ' if [ -f "$f" ] && command -v file >/dev/null && encoding=$(file -b --mime-encoding -- "$f") && [ -n "$encoding" ] && [ "$encoding" != binary ]; then',
8 ' case $(gio info -a standard::content-type -- "$f" | sed -n \'s/.*standard::content-type: //p\') in',
9 ' video/* | audio/*)',
10 ' app=$(xdg-mime query default text/plain)',
11 ' IFS=:',
12 ' for dir in "${XDG_DATA_HOME:-$HOME/.local/share}" ${XDG_DATA_DIRS:-/usr/local/share:/usr/share}; do',
13 ' [ -n "$app" ] && [ -f "$dir/applications/$app" ] && exec gio launch "$dir/applications/$app" "$f"',
14 ' done',
15 ' echo "No text/plain desktop application found for $f" >&2',
16 ' exit 1',
17 ' ;;',
18 ' esac',
19 ' fi',
20 ' if (exec gio open "$f"); then exit 0; fi',
21 'fi',
22 'exec xdg-open "$f"',
23].join('\n')
24
25const WIN_OPEN = "$ErrorActionPreference = 'Stop'; [Diagnostics.Process]::Start([Diagnostics.ProcessStartInfo]@{ FileName = $env:PANE_OPEN_TARGET; UseShellExecute = $true }) | Out-Null"
26
27export function openCommand(os: 'linux' | 'darwin' | 'win32', target: string) {
28 const argv = os === 'linux'
29 ? ['sh', '-c', LINUX_LAUNCH, 'sh', 'sh', '-c', LINUX_OPEN, 'sh', target]
30 : os === 'darwin'
31 ? ['open', '--', target]
32 : ['powershell', '-NoProfile', '-NonInteractive', '-Command', WIN_OPEN]
33 return {
34 argv,
35 init: {
36 timeoutMs: 10_000,
37 ...(os === 'win32' ? { env: { PANE_OPEN_TARGET: /^[a-z][a-z0-9+.-]*:\/\//i.test(target) ? target : target.replace(/\//g, '\\') } } : {}),
38 },
39 }
40}
41hooks/icons.ts 211 lines1import type { TreeNode } from '../types'
2import { FAB_ITEMS, PBIR_CHILDREN, PBIR_VISUALS } from './icon-data'
3
4type Rgb = [number, number, number]
5type Icon = { fabric: number; nerd: string; rgb: Rgb | null }
6export type Tier = 'fabric' | 'nerd' | 'plain'
7
8const GLYPH_DIM: Rgb = [0x6e, 0x6e, 0x7a]
9const CONTAINER: Icon = { fabric: 0xf2609, nerd: '\u{f024b}', rgb: [197, 197, 197] }
10
11const REPORT_NERD: Record<string, string> = {
12 page: '\u{f0214}',
13 visual: '\u{f154e}',
14 reportfilter: '\u{f0232}',
15 pagefilter: '\u{f0232}',
16 visualfilter: '\u{f0232}',
17 bookmark: '\u{f00c0}',
18 theme: '\u{f03d8}',
19 'data role': '\u{f0d7e}',
20 field: '\u{f0835}',
21 'ext measure': '\u{f00ec}',
22 'theme colors': '\u{f03d8}',
23 'theme data colors': '\u{f08b5}',
24 'theme text': '\u{f06d6}',
25 'text class': '\u{f027f}',
26 'theme styles': '\u{f027c}',
27 'theme state': '\u{f06c4}',
28 'theme card': '\u{f062e}',
29 'theme selector': '\u{f062e}',
30}
31
32const VISUAL_NERD: Record<string, string> = {
33 accessibleTable: '\u{f1094}',
34 actionButton: '\u{f12a8}',
35 advancedSlicerVisual: '\u{f0570}',
36 aiNarratives: '\u{f0674}',
37 animatedNumber: '\u{f0199}',
38 areaChart: '\u{f0e91}',
39 azureMap: '\u{f0352}',
40 barChart: '\u{f066c}',
41 basicShape: '\u{f14fb}',
42 bookmarkNavigator: '\u{f0e15}',
43 card: '\u{f03a0}',
44 cardVisual: '\u{f0b77}',
45 clusteredBarChart: '\u{f066e}',
46 clusteredColumnChart: '\u{f0128}',
47 columnChart: '\u{f076a}',
48 dataQueryVisual: '\u{f0866}',
49 debugVisual: '\u{f00e4}',
50 decompositionTreeVisual: '\u{f04aa}',
51 donutChart: '\u{f07af}',
52 filledMap: '\u{f01e7}',
53 filterSlicer: '\u{f1aa3}',
54 funnel: '\u{f0236}',
55 gauge: '\u{f029a}',
56 group: '\u{f02c3}',
57 groupVisual: '\u{f02c3}',
58 heatMap: '\u{f066d}',
59 hundredPercentStackedAreaChart: '\u{f076b}',
60 hundredPercentStackedBarChart: '\u{f0729}',
61 hundredPercentStackedColumnChart: '\u{f056d}',
62 image: '\u{f02e9}',
63 keyDriversVisual: '\u{f06e8}',
64 keyInfluencers: '\u{f06e8}',
65 kpi: '\u{f0535}',
66 lineChart: '\u{f012a}',
67 lineClusteredColumnComboChart: '\u{f081f}',
68 lineStackedColumnComboChart: '\u{f1213}',
69 listSlicer: '\u{f096a}',
70 map: '\u{f034d}',
71 matrix: '\u{f121d}',
72 multiRowCard: '\u{f0ab7}',
73 pageNavigator: '\u{f0bb0}',
74 pieChart: '\u{f012b}',
75 pivotTable: '\u{f183c}',
76 pythonVisual: '\u{f0320}',
77 qnaVisual: '\u{f0817}',
78 rdlVisual: '\u{f0219}',
79 ribbonChart: '\u{f11df}',
80 scatterChart: '\u{f0e92}',
81 scorecard: '\u{f08c9}',
82 scriptVisual: '\u{f07d4}',
83 shape: '\u{f0831}',
84 shapeMap: '\u{f0560}',
85 slicer: '\u{f10e5}',
86 stackedAreaChart: '\u{f0127}',
87 stackedBarChart: '\u{f066c}',
88 stackedColumnChart: '\u{f076a}',
89 table: '\u{f04f1}',
90 tableEx: '\u{f04eb}',
91 textSlicer: '\u{f0eae}',
92 textbox: '\u{f0d11}',
93 treemap: '\u{f0e94}',
94 waterfallChart: '\u{f1918}',
95}
96
97const VISUAL_PLAIN: Record<string, string> = {
98 accessibleTable: '▧', actionButton: '►', advancedSlicerVisual: '⧉', aiNarratives: '✦', animatedNumber: '№', areaChart: '◢', azureMap: '♁',
99 barChart: '▤', basicShape: '○', bookmarkNavigator: '⚐', card: '#', cardVisual: '▭', clusteredBarChart: '≡', clusteredColumnChart: '▆',
100 columnChart: '▥', dataQueryVisual: '⊜', debugVisual: '✗', decompositionTreeVisual: '⊢', donutChart: '◎', filledMap: '◍', filterSlicer: '⧨',
101 funnel: '▽', gauge: '◠', group: '❐', groupVisual: '❐', heatMap: '▒', hundredPercentStackedAreaChart: '◩', hundredPercentStackedBarChart: '▬',
102 hundredPercentStackedColumnChart: '█', image: '⊡', keyDriversVisual: '☼', keyInfluencers: '☼', kpi: '⬈', lineChart: '∿',
103 lineClusteredColumnComboChart: '╫', lineStackedColumnComboChart: '╪', listSlicer: '⁝', map: '⌖', matrix: '⧆', multiRowCard: '⊟', pageNavigator: '⇥',
104 pieChart: '◔', pivotTable: '⊠', pythonVisual: 'π', qnaVisual: '?', rdlVisual: '⎙', ribbonChart: '≋', scatterChart: '∴', scorecard: '◉',
105 scriptVisual: 'ℛ', shape: '◭', shapeMap: '⬠', slicer: '☐', stackedAreaChart: '◿', stackedBarChart: '▤', stackedColumnChart: '▥', table: '▩',
106 tableEx: '▦', textSlicer: '⌕', textbox: '¶', treemap: '⊞', waterfallChart: '▟',
107}
108
109const ITEM_NERD: Record<string, string> = {
110 SemanticModel: '\u{f01bc}',
111 Report: '\u{f0219}',
112}
113
114const PLAIN: Record<string, string> = {
115 report: '▣', 'semantic model': '◆', group: '■', page: '□', visual: '▢', reportfilter: '▿', pagefilter: '▿',
116 visualfilter: '▿', bookmark: '⚑', theme: '◐', 'data role': '◫', field: '│', 'ext measure': 'Σ',
117 'theme colors': '◐', 'theme data colors': '◐', 'theme text': 'T', 'text class': 'T', 'theme styles': '✎', 'theme state': '*', 'theme card': '◦', 'theme selector': '◦',
118}
119
120export type Glyph = { char: string; color: string | undefined; label?: string }
121
122function hex(rgb: Rgb | null): string | undefined {
123 return rgb ? '#' + rgb.map(v => v.toString(16).padStart(2, '0')).join('') : undefined
124}
125
126function pick(icon: Icon, tier: Tier, plain: string): Glyph {
127 if (tier === 'plain') return { char: plain, color: hex(icon.rgb) }
128 return { char: tier === 'fabric' && icon.fabric ? String.fromCodePoint(icon.fabric) : icon.nerd, color: hex(icon.rgb) }
129}
130
131function hls(rgb: Rgb): [number, number, number] {
132 const [r, g, b] = rgb.map(v => v / 255) as Rgb
133 const max = Math.max(r, g, b)
134 const min = Math.min(r, g, b)
135 const l = (max + min) / 2
136 const range = max - min
137 if (range < 1e-6) return [0, l, 0]
138 const s = l <= 0.5 ? range / (max + min) : range / (2 - max - min)
139 const rc = (max - r) / range
140 const gc = (max - g) / range
141 const bc = (max - b) / range
142 const h = r === max ? bc - gc : g === max ? 2 + rc - bc : 4 + gc - rc
143 return [(((h / 6) % 1) + 1) % 1, l, s]
144}
145
146function component(m1: number, m2: number, hue: number): number {
147 const h = ((hue % 1) + 1) % 1
148 if (h < 1 / 6) return m1 + (m2 - m1) * h * 6
149 if (h < 0.5) return m2
150 if (h < 2 / 3) return m1 + (m2 - m1) * (2 / 3 - h) * 6
151 return m1
152}
153
154function lift(rgb: Rgb): Rgb {
155 const [h, l0, s] = hls(rgb)
156 const l = Math.max(l0, 0.62)
157 if (s < 1e-6) return [Math.round(l * 255), Math.round(l * 255), Math.round(l * 255)]
158 const m2 = l <= 0.5 ? l * (1 + s) : l + s - l * s
159 const m1 = 2 * l - m2
160 return [h + 1 / 3, h, h - 1 / 3].map(x => Math.round(component(m1, m2, x) * 255)) as Rgb
161}
162
163function item(type: string): Icon {
164 const hit = FAB_ITEMS[type]
165 return { fabric: hit?.[0] ?? 0, nerd: ITEM_NERD[type] ?? '\u{f0214}', rgb: hit?.[1] ? lift(hit[1]) : null }
166}
167
168const CUSTOM_VISUAL = /^(.+?)[0-9A-F]{32}$/i
169
170export function visualLabel(type: string): string {
171 const custom = type.match(CUSTOM_VISUAL)?.[1]
172 return custom ? `${custom[0]?.toUpperCase()}${custom.slice(1)}, custom visual` : type
173}
174
175const SWATCH = /^#[0-9a-f]{3,8}$/i
176
177function swatch(hex: string): string {
178 const h = hex.slice(1)
179 return h.length === 3 || h.length === 4 ? `#${[...h.slice(0, 3)].map(c => c + c).join('')}` : `#${h.slice(0, 6)}`
180}
181
182export function glyph(n: TreeNode, tier: Tier): Glyph {
183 if (n.kind === 'theme color' || n.kind === 'theme prop') {
184 const code = n.note.split(' ')[0] ?? ''
185 if (SWATCH.test(code)) return { char: tier === 'plain' ? '■' : '\u{f0764}', color: swatch(code) }
186 return { char: '·', color: hex(GLYPH_DIM) }
187 }
188 if (n.kind === 'text class') {
189 const hexColor = n.note.split(' ').find(w => SWATCH.test(w))
190 const g = pick({ fabric: 0, nerd: REPORT_NERD['text class'] ?? '', rgb: GLYPH_DIM }, tier, PLAIN['text class'] ?? 'T')
191 return hexColor ? { ...g, color: swatch(hexColor) } : g
192 }
193 if (n.kind === 'theme style') {
194 if (n.name === 'All visuals') return pick({ fabric: 0, nerd: '\u{f06c4}', rgb: GLYPH_DIM }, tier, '*')
195 return glyph({ ...n, kind: 'visual', note: n.name }, tier)
196 }
197 const type = n.kind === 'visual' ? n.note || n.name : ''
198 if (n.kind === 'visual' && CUSTOM_VISUAL.test(type)) return pick({ fabric: 0, nerd: '\u{f0431}', rgb: GLYPH_DIM }, tier, '⧈')
199 const plain = VISUAL_PLAIN[type] ?? PLAIN[n.kind] ?? '■'
200 if (n.kind === 'report') return pick(item('Report'), tier, plain)
201 if (n.kind === 'semantic model') {
202 const g = pick(item('SemanticModel'), tier, plain)
203 return { ...g, label: g.color }
204 }
205 if (REPORT_NERD[n.kind]) {
206 const fabric = n.kind === 'visual' ? (PBIR_VISUALS[type] ?? PBIR_CHILDREN.visual) : PBIR_CHILDREN[n.kind]
207 return pick({ fabric: fabric ?? 0, nerd: VISUAL_NERD[type] ?? REPORT_NERD[n.kind] ?? CONTAINER.nerd, rgb: GLYPH_DIM }, tier, plain)
208 }
209 return pick(CONTAINER, tier, plain)
210}
211hooks/rows.tsx 165 lines1import type { ClientModule } from 'claude-code'
2
3export type Seg = { t: string; c?: string; b?: boolean; s?: boolean; i?: boolean; sh?: string; dim?: boolean; one?: boolean; spin?: boolean; claude?: boolean; bg?: string; tab?: string }
4export type RowSpec = { id: string; left: Seg[]; right: Seg[] }
5export type RowsProps = {
6 rows: RowSpec[]
7 active: string
8 activeBg: string
9 hoverBg: string
10 tones: Record<string, { bright: string[]; dim: string[] }>
11 pointer?: boolean
12 bar?: { pos: number; size: number; thumb: string; track: string }
13}
14type Local = { hover: number; phase: number; drag: boolean; ref: { stop?: () => void; unpoint?: () => void } }
15
16const TICK_MS = 90
17const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
18const GRADIENT = ['#5eead4', '#67e8f9', '#7dd3fc', '#93c5fd', '#a5b4fc', '#c4b5fd', '#d8b4fe', '#f0abfc', '#d8b4fe', '#c4b5fd', '#a5b4fc', '#93c5fd', '#7dd3fc', '#67e8f9']
19
20function shimmer(i: number, phase: number, len: number, palette: string[]): string {
21 const band = ((phase * 1.6) % (len + 8)) - 4
22 const d = Math.abs(i - band)
23 return palette[d < 0.8 ? 3 : d < 1.8 ? 2 : d < 2.8 ? 1 : 0] ?? palette[0] ?? '#f97316'
24}
25
26const Rows: ClientModule<RowsProps, Local> = (props, surface) => {
27 const { Box, Text } = surface.elements
28 let state = surface.state
29 if (state === undefined) {
30 state = { hover: -1, phase: 0, drag: false, ref: {} }
31 surface.setState(state)
32 }
33 const lit = props.rows.some(r => r.left.some(s => s.sh || s.spin || s.claude) || r.right.some(s => s.sh || s.spin || s.claude))
34 if (lit && !state.ref.stop) {
35 state.ref.stop = surface.every(TICK_MS, () => {
36 const cur = surface.state
37 if (cur) surface.setState({ ...cur, phase: cur.phase + 1 })
38 })
39 } else if (!lit && state.ref.stop) {
40 state.ref.stop()
41 state.ref.stop = undefined
42 }
43 if (props.pointer === false) {
44 state.ref.unpoint?.()
45 state.ref.unpoint = undefined
46 } else state.ref.unpoint = surface.onPointer(e => {
47 const cur = surface.state ?? state
48 const span = Math.max(1, props.rows.length - 1)
49 const onBar = Boolean(props.bar) && e.x >= surface.columns - 1
50 if (props.bar && (cur.drag || (onBar && e.type === 'down' && (e.button ?? 'left') === 'left'))) {
51 if (e.type === 'up' || e.type === 'leave') {
52 surface.setState({ ...cur, drag: false })
53 return
54 }
55 if (e.type === 'down' || e.type === 'move') {
56 if (!cur.drag) surface.setState({ ...cur, drag: true, hover: -1 })
57 surface.post({ scrollTo: Math.max(0, Math.min(1, e.y / span)) })
58 return
59 }
60 }
61 if (e.type === 'leave' || e.y < 0 || e.y >= props.rows.length) {
62 if (cur.hover !== -1) surface.setState({ ...cur, hover: -1 })
63 return
64 }
65 if (e.type === 'move' && !e.button && cur.hover !== e.y) surface.setState({ ...cur, hover: e.y })
66 const row = props.rows[e.y]
67 if (e.type === 'down' && e.button === 'right' && row?.id) {
68 surface.post({ copy: row.id, shift: Boolean(e.shift) })
69 return
70 }
71 if (e.type !== 'down' || (e.button ?? 'left') !== 'left' || !row) return
72 const wide = (seg: Seg) => [...seg.t].length + (seg.spin ? 1 : 0)
73 let x = 0
74 for (const seg of row.left) {
75 const w = wide(seg)
76 if (seg.tab && e.x >= x && e.x < x + w) {
77 surface.post({ tab: seg.tab })
78 return
79 }
80 x += w
81 }
82 x = surface.columns - (props.bar ? 1 : 0) - row.right.reduce((n, seg) => n + wide(seg), 0)
83 for (const seg of row.right) {
84 const w = wide(seg)
85 if (seg.tab && e.x >= x && e.x < x + w) {
86 surface.post({ tab: seg.tab })
87 return
88 }
89 x += w
90 }
91 if (row.id) surface.post({ press: row.id, ctrl: Boolean(e.ctrl), shift: Boolean(e.shift) })
92 })
93 surface.onKey(e => surface.post({ key: e.key, ctrl: Boolean(e.ctrl), shift: Boolean(e.shift) }))
94 const draw = (s: Seg, k: number) => {
95 if (s.claude) {
96 const shut = Math.floor(state.phase / 3) % 12 === 11
97 return (
98 <Text key={String(k)} color={shut ? '#7a4535' : '#d97757'} bold={!shut}>
99 {s.t}
100 </Text>
101 )
102 }
103 if (s.spin) {
104 const frame = FRAMES[state.phase % FRAMES.length] ?? ''
105 return (
106 <Text key={String(k)} bold={s.b}>
107 {s.t ? <Text color={s.c}>{s.t}</Text> : null}
108 <Text color={GRADIENT[state.phase % GRADIENT.length]} bold>
109 {frame}
110 </Text>
111 </Text>
112 )
113 }
114 const palette = s.sh ? (s.dim ? props.tones[s.sh]?.dim : props.tones[s.sh]?.bright) : undefined
115 if (!palette) {
116 return (
117 <Text key={String(k)} color={s.c} backgroundColor={s.bg} bold={s.b} strikethrough={s.s} italic={s.i}>
118 {s.t}
119 </Text>
120 )
121 }
122 if (s.one) {
123 return (
124 <Text key={String(k)} color={shimmer(-1, state.phase, s.t.length, palette)}>
125 {s.t}
126 </Text>
127 )
128 }
129 const chars = [...s.t]
130 return (
131 <Text key={String(k)} bold={s.b}>
132 {chars.map((ch, i) => (
133 <Text key={String(i)} color={shimmer(i, state.phase, chars.length, palette)}>{ch}</Text>
134 ))}
135 </Text>
136 )
137 }
138 return (
139 <Box flexDirection="column">
140 {props.rows.map((r, i) => (
141 <Box
142 key={r.id || `row-${i}`}
143 flexDirection="row"
144 height={1}
145 overflow="hidden"
146 backgroundColor={r.id && r.id === props.active ? props.activeBg : r.id && i === state.hover ? props.hoverBg : undefined}
147 >
148 <Box flexShrink={1} overflow="hidden">
149 {r.left.map(draw)}
150 </Box>
151 <Box flexGrow={1} />
152 {r.right.map(draw)}
153 {props.bar && (
154 <Text color={i >= props.bar.pos && i < props.bar.pos + props.bar.size ? props.bar.thumb : props.bar.track}>
155 {i >= props.bar.pos && i < props.bar.pos + props.bar.size ? '┃' : '│'}
156 </Text>
157 )}
158 </Box>
159 ))}
160 </Box>
161 )
162}
163
164export default Rows
165hooks/svg-data.ts 2 lines1export const FABRIC_SVG: Record<string, string> = {"SemanticModel":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#fhpaint0_linear_41743_62611)\"/><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#fhpaint1_radial_41743_62611)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M19 3H5C3.89 3 3 3.89 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.89 20.1 3 19 3ZM5 2C3.34 2 2 3.34 2 5V19C2 20.65 3.34 22 5 22H19C20.65 22 22 20.65 22 19V5C22 3.34 20.65 2 19 2H5Z\" fill=\"url(#fhpaint2_linear_41743_62611)\"/><path d=\"M7.25 10.5C7.94 10.5 8.5 9.94 8.5 9.25C8.5 8.55 7.94 8 7.25 8C6.55 8 6 8.55 6 9.25C6 9.94 6.55 10.5 7.25 10.5Z\" fill=\"url(#fhpaint3_linear_41743_62611)\"/><path d=\"M12 10.5C12.69 10.5 13.25 9.94 13.25 9.25C13.25 8.55 12.69 8 12 8C11.3 8 10.75 8.55 10.75 9.25C10.75 9.94 11.3 10.5 12 10.5Z\" fill=\"url(#fhpaint4_linear_41743_62611)\"/><path d=\"M13.25 14.75C13.25 15.44 12.69 16 12 16C11.3 16 10.75 15.44 10.75 14.75C10.75 14.05 11.3 13.5 12 13.5C12.69 13.5 13.25 14.05 13.25 14.75Z\" fill=\"url(#fhpaint5_linear_41743_62611)\"/><path d=\"M7.25 16C7.94 16 8.5 15.44 8.5 14.75C8.5 14.05 7.94 13.5 7.25 13.5C6.55 13.5 6 14.05 6 14.75C6 15.44 6.55 16 7.25 16Z\" fill=\"url(#fhpaint6_linear_41743_62611)\"/><path d=\"M18 9.25C18 9.94 17.44 10.5 16.75 10.5C16.05 10.5 15.5 9.94 15.5 9.25C15.5 8.55 16.05 8 16.75 8C17.44 8 18 8.55 18 9.25Z\" fill=\"url(#fhpaint7_linear_41743_62611)\"/><defs><linearGradient id=\"fhpaint0_linear_41743_62611\" x1=\"7.55\" y1=\"2\" x2=\"10.08\" y2=\"22.23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"fhpaint1_radial_41743_62611\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(8.38 7.2) rotate(56.3) scale(19.02 16.46)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"fhpaint2_linear_41743_62611\" x1=\"8.45\" y1=\"2\" x2=\"11.15\" y2=\"22.19\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"fhpaint3_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient><linearGradient id=\"fhpaint4_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient><linearGradient id=\"fhpaint5_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient><linearGradient id=\"fhpaint6_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient><linearGradient id=\"fhpaint7_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient></defs></svg>","Report":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#rupaint0_linear_41743_63108)\"/><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#rupaint1_radial_41743_63108)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M19 3H5C3.89 3 3 3.89 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.89 20.1 3 19 3ZM5 2C3.34 2 2 3.34 2 5V19C2 20.65 3.34 22 5 22H19C20.65 22 22 20.65 22 19V5C22 3.34 20.65 2 19 2H5Z\" fill=\"url(#rupaint2_linear_41743_63108)\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M7.5 17.24V6.75C7.5 6.33 7.83 6 8.25 6C8.66 6 9 6.33 9 6.75L9 17.24C9 17.66 8.66 17.99 8.25 17.99C7.83 17.99 7.5 17.66 7.5 17.24ZM11.25 17.25V9.75C11.25 9.33 11.58 9 12 9C12.41 9 12.75 9.33 12.75 9.75V17.25C12.75 17.66 12.41 18 12 18C11.58 18 11.25 17.66 11.25 17.25ZM16.5 13C16.5 12.58 16.16 12.25 15.75 12.25C15.33 12.25 15 12.58 15 13L15 17.25C15 17.66 15.33 18 15.75 18C16.16 18 16.5 17.66 16.5 17.25L16.5 13Z\" fill=\"url(#rupaint3_linear_41743_63108)\"/><defs><linearGradient id=\"rupaint0_linear_41743_63108\" x1=\"7.55\" y1=\"2\" x2=\"10.08\" y2=\"22.23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"rupaint1_radial_41743_63108\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(8.38 7.2) rotate(56.3) scale(19.02 16.46)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"rupaint2_linear_41743_63108\" x1=\"8.45\" y1=\"2\" x2=\"11.15\" y2=\"22.19\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"rupaint3_linear_41743_63108\" x1=\"7.5\" y1=\"6\" x2=\"19.02\" y2=\"14.64\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#C28400\"/><stop offset=\"1\" stop-color=\"#A86500\"/></linearGradient></defs></svg>","ui:open":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"20\" height=\"20\" fill=\"#c5c5d0\"><path d=\"M6 4a2 2 0 0 0-2 2v8c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2v-2.5a.5.5 0 0 1 1 0V14a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3h2.5a.5.5 0 0 1 0 1H6Zm5-.5c0-.28.22-.5.5-.5h5c.28 0 .5.22.5.5v5a.5.5 0 0 1-1 0V4.7l-4.15 4.15a.5.5 0 0 1-.7-.7L15.29 4H11.5a.5.5 0 0 1-.5-.5Z\"/></svg>","ui:copy":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"20\" height=\"20\" fill=\"#c5c5d0\"><path d=\"M8 2a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h6a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8ZM7 4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V4ZM4 6a2 2 0 0 1 1-1.73V14.5A2.5 2.5 0 0 0 7.5 17h6.23A2 2 0 0 1 12 18H7.5A3.5 3.5 0 0 1 4 14.5V6Z\"/></svg>","ui:chevron-right":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"16\" height=\"16\" fill=\"#8b8b96\"><path d=\"M7.65 4.15c.2-.2.5-.2.7 0l5.49 5.46c.21.22.21.57 0 .78l-5.49 5.46a.5.5 0 0 1-.7-.7L12.8 10 7.65 4.85a.5.5 0 0 1 0-.7Z\"/></svg>","ui:chevron-down":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"16\" height=\"16\" fill=\"#8b8b96\"><path d=\"M15.85 7.65c.2.2.2.5 0 .7l-5.46 5.49a.55.55 0 0 1-.78 0L4.15 8.35a.5.5 0 1 1 .7-.7L10 12.8l5.15-5.16c.2-.2.5-.2.7 0Z\"/></svg>","tenant settings":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"20\" height=\"20\" fill=\"#c5c5d0\"><path d=\"M1.91 7.38A8.5 8.5 0 0 1 3.7 4.3a.5.5 0 0 1 .54-.13l1.92.68a1 1 0 0 0 1.32-.76l.36-2a.5.5 0 0 1 .4-.4 8.53 8.53 0 0 1 3.55 0c.2.04.35.2.38.4l.37 2a1 1 0 0 0 1.32.76l1.92-.68a.5.5 0 0 1 .54.13 8.5 8.5 0 0 1 1.78 3.08c.06.2 0 .4-.15.54l-1.56 1.32a1 1 0 0 0 0 1.52l1.56 1.32a.5.5 0 0 1 .15.54 8.5 8.5 0 0 1-1.78 3.08.5.5 0 0 1-.54.13l-1.92-.68a1 1 0 0 0-1.32.76l-.37 2a.5.5 0 0 1-.38.4 8.53 8.53 0 0 1-3.56 0 .5.5 0 0 1-.39-.4l-.36-2a1 1 0 0 0-1.32-.76l-1.92.68a.5.5 0 0 1-.54-.13 8.5 8.5 0 0 1-1.78-3.08.5.5 0 0 1 .15-.54l1.56-1.32a1 1 0 0 0 0-1.52L2.06 7.92a.5.5 0 0 1-.15-.54Zm1.06 0 1.3 1.1a2 2 0 0 1 0 3.04l-1.3 1.1c.3.79.72 1.51 1.25 2.16l1.6-.58a2 2 0 0 1 2.63 1.53l.3 1.67a7.56 7.56 0 0 0 2.5 0l.3-1.67a2 2 0 0 1 2.64-1.53l1.6.58a7.5 7.5 0 0 0 1.24-2.16l-1.3-1.1a2 2 0 0 1 0-3.04l1.3-1.1a7.5 7.5 0 0 0-1.25-2.16l-1.6.58a2 2 0 0 1-2.63-1.53l-.3-1.67a7.55 7.55 0 0 0-2.5 0l-.3 1.67A2 2 0 0 1 5.81 5.8l-1.6-.58a7.5 7.5 0 0 0-1.24 2.16ZM7.5 10a2.5 2.5 0 1 1 5 0 2.5 2.5 0 0 1-5 0Zm1 0a1.5 1.5 0 1 0 3 0 1.5 1.5 0 0 0-3 0Z\"/></svg>"}
2hooks/zone.tsx 22 lines1import type { ClientModule } from 'claude-code'
2
3export type ZoneProps = { id: string }
4type Local = { ref: { unpoint?: () => void; id: string } }
5
6const Zone: ClientModule<ZoneProps, Local> = (props, surface) => {
7 const { Box } = surface.elements
8 let state = surface.state
9 if (state === undefined) {
10 state = { ref: { id: props.id } }
11 surface.setState(state)
12 }
13 const ref = state.ref
14 ref.id = props.id
15 ref.unpoint ??= surface.onPointer(e => {
16 if (e.type === 'up' && (e.button ?? 'left') === 'left') surface.post({ zone: ref.id, shift: Boolean(e.shift), ctrl: Boolean(e.ctrl) })
17 })
18 return <Box width="100%" height="100%" />
19}
20
21export default Zone
22hooks/tree.ts 90 lines1import type { Explorer, TreeNode } from '../types'
2
3export type Row = { node: TreeNode; depth: number; open: boolean; leaf: boolean }
4
5export function empty(): Explorer {
6 return {
7 target: null,
8 changed: [],
9 expanded: [],
10 query: '',
11 cursor: '',
12 selected: '',
13 detail: [],
14 status: '',
15 flash: [],
16 flashDim: [],
17 work: null,
18 targetUrl: '',
19 scroll: {},
20 root: '',
21 }
22}
23
24export function diff(before: TreeNode[], after: TreeNode[]): string[] {
25 if (before.length === 0) return []
26 const old = new Map(before.map(n => [n.id, n.sig + '|' + n.hidden]))
27 const out = new Set(after.filter(n => old.get(n.id) !== n.sig + '|' + n.hidden).map(n => n.id))
28 const was = new Map(before.map(n => [n.id, n]))
29 const now = new Map(after.map(n => [n.id, n]))
30 for (const n of before) {
31 if (now.has(n.id)) continue
32 let up = was.get(n.parent)
33 while (up && !now.has(up.id)) up = was.get(up.parent)
34 if (up) out.add(up.id)
35 }
36 return [...out]
37}
38
39function childrenOf(nodes: TreeNode[]): Map<string, TreeNode[]> {
40 const kids = new Map<string, TreeNode[]>()
41 for (const n of nodes) {
42 const list = kids.get(n.parent)
43 if (list) list.push(n)
44 else kids.set(n.parent, [n])
45 }
46 return kids
47}
48
49export function ancestors(nodes: TreeNode[], id: string, byId?: Map<string, TreeNode>): string[] {
50 const map = byId ?? new Map(nodes.map(n => [n.id, n]))
51 const out: string[] = []
52 let cur = map.get(id)
53 while (cur && cur.parent) {
54 out.push(cur.parent)
55 cur = map.get(cur.parent)
56 }
57 return out
58}
59
60export function visible(ex: Explorer, nodes: TreeNode[], root = ''): Row[] {
61 const kids = childrenOf(nodes)
62 const q = ex.query.trim().toLowerCase()
63 let keep: Set<string> | null = null
64 if (q) {
65 keep = new Set()
66 const byId = new Map(nodes.map(n => [n.id, n]))
67 for (const n of nodes) {
68 if (!n.name.toLowerCase().includes(q) && !n.note.toLowerCase().includes(q)) continue
69 let cur: TreeNode | undefined = n
70 while (cur && !keep.has(cur.id)) {
71 keep.add(cur.id)
72 cur = byId.get(cur.parent)
73 }
74 }
75 }
76 const open = new Set(ex.expanded)
77 const rows: Row[] = []
78 const walk = (parent: string, depth: number) => {
79 for (const n of kids.get(parent) ?? []) {
80 if (keep && !keep.has(n.id)) continue
81 const leaf = !kids.has(n.id)
82 const isOpen = !leaf && (keep ? true : open.has(n.id))
83 rows.push({ node: n, depth, open: isOpen, leaf })
84 if (isOpen) walk(n.id, depth + 1)
85 }
86 }
87 walk(root, 0)
88 return rows
89}
90hooks/fabric.ts 17 lines1const PORTAL = 'https://app.powerbi.com'
2const GUID = /^[0-9a-f-]{36}$/i
3
4export function workspaceUrl(wsId: string): string {
5 return GUID.test(wsId) ? `${PORTAL}/groups/${wsId}` : ''
6}
7
8export function reportUrl(wsId: string, reportId: string): string {
9 const ws = workspaceUrl(wsId)
10 return ws && GUID.test(reportId) ? `${ws}/reports/${reportId}` : ws
11}
12
13export function idOf(stdout: string): string {
14 const m = stdout.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)
15 return m?.[0] ?? ''
16}
17hooks/parse.ts 214 lines1import type { Target } from '../types'
2
3export type Invocation = { bin: string; args: string[]; cwd: string; maybe: boolean }
4
5const SEPARATORS = new Set(['&&', '||', ';', '|', '&', '\n'])
6const REDIRECT = /^(\d*>>?|\d*<|\d*>&\d*|&>>?)$/
7
8let drives = false
9let home = ''
10
11export function useDrives(on: boolean): void {
12 drives = on
13}
14
15export function useHome(path: string): void {
16 home = path.replace(/\/+$/, '')
17}
18
19export function posix(path: string): string {
20 if (!drives) return path
21 return path.replace(/\\/g, '/').replace(/^\/([A-Za-z])(\/|$)/, (_, d: string) => `${d.toUpperCase()}:/`)
22}
23
24export function isAbsolute(path: string): boolean {
25 return path.startsWith('/') || (drives && /^[A-Za-z]:\//.test(path))
26}
27
28export function tokenize(command: string): string[] {
29 const out: string[] = []
30 let cur = ''
31 let quote = ''
32 let has = false
33 for (let i = 0; i < command.length; i++) {
34 const ch = command[i] ?? ''
35 if (!quote && ch === '#' && !has && !cur) {
36 while (i + 1 < command.length && command[i + 1] !== '\n') i++
37 continue
38 }
39 if (quote) {
40 if (ch === quote) quote = ''
41 else if (ch === '\\' && quote === '"' && /[$`"\\\n]/.test(command[i + 1] ?? '')) cur += (command[++i] ?? '').replace('\n', '')
42 else cur += ch
43 continue
44 }
45 if (ch === '"' || ch === "'") {
46 quote = ch
47 has = true
48 } else if (ch === '\\' && i + 1 < command.length) {
49 cur += command[++i] ?? ''
50 has = true
51 } else if (ch === '\n') {
52 if (has || cur) out.push(cur)
53 cur = ''
54 has = false
55 out.push('\n')
56 } else if (/\s/.test(ch)) {
57 if (has || cur) out.push(cur)
58 cur = ''
59 has = false
60 } else if (ch === '>' || ch === '<') {
61 let op = /^\d+$/.test(cur) || (cur === '&' && !has) ? cur : ''
62 if (!op && (has || cur)) out.push(cur)
63 op += ch
64 while (command[i + 1] === '>' || command[i + 1] === '&' || /\d/.test(command[i + 1] ?? '')) {
65 if (command[i + 1] === '&' && op.endsWith('&')) break
66 op += command[++i]
67 }
68 out.push(op)
69 cur = ''
70 has = false
71 } else if (ch === ';' || ch === '|' || ch === '&') {
72 if (ch === '&' && command[i + 1] === '>') {
73 if (has || cur) out.push(cur)
74 cur = '&'
75 has = false
76 continue
77 }
78 if (has || cur) out.push(cur)
79 cur = ''
80 has = false
81 const two = command.slice(i, i + 2)
82 if (two === '&&' || two === '||') {
83 out.push(two)
84 i++
85 } else out.push(ch)
86 } else {
87 cur += ch
88 has = true
89 }
90 }
91 if (has || cur) out.push(cur)
92 if (!quote) return out
93 return command
94 .split(/(&&|\|\||[;|\n])/)
95 .flatMap(part => (/^(&&|\|\||[;|\n])$/.test(part) ? [part] : part.trim().split(/\s+/).filter(Boolean)))
96}
97
98export function join(base: string, raw: string): string {
99 let path = posix(raw)
100 if (path === '~' || path.startsWith('~/')) {
101 if (!home) return path
102 path = home + path.slice(1)
103 }
104 const drive = isAbsolute(path) && !path.startsWith('/') ? path.slice(0, 2) : ''
105 const parts = isAbsolute(path) ? [drive] : base.split('/')
106 for (const seg of path.slice(drive.length).split('/')) {
107 if (seg === '' || seg === '.') continue
108 if (seg === '..') {
109 if (parts.length > 1) parts.pop()
110 } else parts.push(seg)
111 }
112 return parts.length > 1 ? parts.join('/') : `${parts[0] ?? ''}/`
113}
114
115export function binOf(bin: string, cwd: string, name: string): string {
116 const path = posix(bin)
117 if (!path.includes('/') || /[~$`]/.test(path)) return name
118 if (isAbsolute(path)) return join('/', path)
119 return isAbsolute(cwd) && !/[~$`]/.test(cwd) ? join(cwd, path) : name
120}
121
122export function invocations(command: string, sessionCwd: string): Invocation[] {
123 const toks = tokenize(command)
124 const found: Invocation[] = []
125 let cwd = sessionCwd
126 let start = true
127 let maybe = false
128 let gate = -1
129 for (let i = 0; i < toks.length; i++) {
130 const t = toks[i] ?? ''
131 if (SEPARATORS.has(t)) {
132 if (t === '&&' && gate < 0) gate = found.length
133 if (t === '||' && gate >= 0) for (const inv of found.slice(gate)) inv.maybe = true
134 if (t !== '|' && t !== '&&' && t !== '||') gate = -1
135 if (t !== '|') maybe = t === '||'
136 start = true
137 continue
138 }
139 if (!start) continue
140 start = false
141 let j = i
142 while (j < toks.length && /^[A-Z_][A-Z0-9_]*=/.test(toks[j] ?? '')) j++
143 const bin = toks[j] ?? ''
144 const head = bin.split('/').pop()
145 const dir = toks[j + 1]
146 if (head === 'cd' && dir && !SEPARATORS.has(dir)) {
147 cwd = join(cwd, dir)
148 continue
149 }
150 if (head !== 'pbir') continue
151 const args: string[] = []
152 let k = j + 1
153 while (k < toks.length && !SEPARATORS.has(toks[k] ?? '')) {
154 const tok = toks[k++] ?? ''
155 if (REDIRECT.test(tok)) {
156 if (!/&\d*$/.test(tok) || tok.startsWith('&')) k++
157 continue
158 }
159 args.push(tok)
160 }
161 found.push({ bin, args, cwd, maybe })
162 i = k - 1
163 }
164 return found
165}
166
167function flag(args: string[], names: string[]): string | undefined {
168 for (let i = 0; i < args.length; i++) {
169 const a = args[i] ?? ''
170 for (const n of names) {
171 if (a === n) return args[i + 1]
172 if (a.startsWith(n + '=')) return a.slice(n.length + 1)
173 }
174 }
175 return undefined
176}
177
178function positionals(args: string[], valued: string[]): string[] {
179 const out: string[] = []
180 for (let i = 1; i < args.length; i++) {
181 const a = args[i] ?? ''
182 if (a.startsWith('-')) {
183 if (valued.includes(a)) i++
184 continue
185 }
186 out.push(a)
187 }
188 return out
189}
190
191export function pbirReport(inv: Invocation): string | null {
192 const { args, cwd } = inv
193 if (args[0] === 'connect') {
194 const pos = positionals(args, ['-o', '--output', '-p', '--profile'])
195 const [first, second] = pos
196 if (first && !second) return join(cwd, first.replace(/\/$/, ''))
197 if (first && second) {
198 const ws = first.replace(/\.Workspace$/, '')
199 const rpt = second.replace(/\.Report$/, '')
200 const out = flag(args, ['-o', '--output'])
201 return join(out ? join(cwd, out) : cwd, `${ws}.Workspace/${rpt}.Report`)
202 }
203 }
204 for (const a of args.slice(1)) {
205 const m = a.match(/^(.*?\.Report)(\/|$)/)
206 if (m?.[1]) return join(cwd, m[1])
207 }
208 return null
209}
210
211export function targetLabel(t: Target | null): string {
212 return t ? t.path.split('/').filter(Boolean).slice(-2).join('/') : 'no target'
213}
214hooks/report.ts 338 lines1import type { TreeNode } from '../types'
2import { visualLabel } from './icons'
3
4type Json = Record<string, any>
5
6const READS = 16
7
8export type Io = {
9 text: (path: string) => Promise<string>
10 list: (path: string) => Promise<{ name: string; kind: string }[]>
11 exists: (path: string) => Promise<boolean>
12}
13
14function node(id: string, parent: string, kind: string, name: string, path: string, sig = '', note = '', file = ''): TreeNode {
15 return { id, parent, kind, name, path, hidden: false, sig, note, ...(file ? { file } : {}) }
16}
17
18function reason(err: unknown): string {
19 return err instanceof Error ? err.message : String(err)
20}
21
22function rel(base: string, path: string): string {
23 return path.startsWith(base + '/') ? path.slice(base.length + 1) : path
24}
25
26async function json(io: Io, base: string, path: string): Promise<Json | null> {
27 let text: string
28 try {
29 text = await io.text(path)
30 } catch (err) {
31 if (!(await io.exists(path))) return null
32 throw new Error(`cannot read ${rel(base, path)}: ${reason(err)}`)
33 }
34 try {
35 return JSON.parse(text) as Json
36 } catch (err) {
37 throw new Error(`invalid JSON in ${rel(base, path)}: ${reason(err)}`)
38 }
39}
40
41async function entries(io: Io, base: string, path: string): Promise<{ name: string; kind: string }[]> {
42 try {
43 return await io.list(path)
44 } catch (err) {
45 if (!(await io.exists(path))) return []
46 throw new Error(`cannot list ${rel(base, path)}: ${reason(err)}`)
47 }
48}
49
50async function dirs(io: Io, base: string, path: string): Promise<string[]> {
51 return (await entries(io, base, path)).filter(e => e.kind === 'dir').map(e => e.name)
52}
53
54async function each<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
55 const out: R[] = []
56 let next = 0
57 const work = async () => {
58 while (next < items.length) {
59 const i = next++
60 out[i] = await fn(items[i] as T)
61 }
62 }
63 await Promise.all(Array.from({ length: Math.min(limit, items.length) }, work))
64 return out
65}
66
67function hash(s: string): string {
68 let x = 5381
69 for (let i = 0; i < s.length; i++) x = (x * 33 + s.charCodeAt(i)) >>> 0
70 return x.toString(16)
71}
72
73function fieldName(field: Json | undefined): string {
74 if (!field) return '?'
75 const inner = field.Column ?? field.Measure ?? field.Aggregation?.Expression?.Column ?? field.HierarchyLevel ?? {}
76 const entity = inner.Expression?.SourceRef?.Entity ?? inner.Expression?.Hierarchy?.Expression?.SourceRef?.Entity ?? ''
77 const prop = inner.Property ?? inner.Level ?? ''
78 return entity ? `${entity}.${prop}` : prop || '?'
79}
80
81function filters(list: Json[] | undefined, parent: string, base: string, kind: string, file: string): TreeNode[] {
82 if (!list?.length) return []
83 const gid = `${parent}/filters`
84 const out = [node(gid, parent, 'group', `Filters (${list.length})`, '', '', '', file)]
85 for (const f of list) {
86 const name = fieldName(f.field)
87 out.push(node(`${gid}/${f.name}`, gid, kind, name, `${base}/${name}.Filter`, hash(JSON.stringify(f)), f.type ?? '', file))
88 }
89 return out
90}
91
92function literal(v: Json | undefined): string {
93 const s = v?.expr?.Literal?.Value
94 return typeof s === 'string' ? s.replace(/^'|'$/g, '') : ''
95}
96
97export async function loadReport(io: Io, dir: string): Promise<TreeNode[]> {
98 const def = `${dir}/definition`
99 const report = await json(io, dir, `${def}/report.json`)
100 if (!report) throw new Error(`not a PBIR report: ${dir}`)
101 const rname = dir.split('/').pop() ?? 'Report'
102 const root = 'R'
103 const out: TreeNode[] = [node(root, '', 'report', rname, rname, hash(JSON.stringify(report)), '', `${def}/report.json`)]
104
105 const pbir = await json(io, dir, `${dir}/definition.pbir`)
106 const ref = pbir?.datasetReference ?? {}
107 const byPath: string = ref.byPath?.path ?? ''
108 const mref = modelRef(pbir)
109 const modelName = mref.name || mref.id
110 if (modelName) {
111 out.push(node(`${root}/model`, root, 'semantic model', modelName, '', hash(JSON.stringify(ref)), byPath ? 'local model' : 'live connection', `${dir}/definition.pbir`))
112 }
113 const theme = report.themeCollection?.customTheme?.name ?? report.themeCollection?.baseTheme?.name
114 if (theme) {
115 const tfile = themeFile(dir, report)
116 const tid = `${root}/theme`
117 out.push(node(tid, root, 'theme', theme, `${rname}/${theme}.Theme`, hash(JSON.stringify(report.themeCollection)), report.themeCollection?.customTheme?.name ? 'custom theme' : 'base theme', tfile))
118 out.push(...themeNodes(await json(io, dir, tfile).catch(() => null), tid, tfile))
119 }
120 out.push(...filters(report.filterConfig?.filters, root, rname, 'reportfilter', `${def}/report.json`))
121
122 const meta = await json(io, dir, `${def}/pages/pages.json`)
123 const folders = await dirs(io, dir, `${def}/pages`)
124 const order: string[] = meta?.pageOrder ?? folders
125 const pagesId = `${root}/pages`
126 out.push(node(pagesId, root, 'group', `Pages (${order.length})`, '', '', '', meta ? `${def}/pages/pages.json` : `${def}/pages`))
127 for (const pf of order) {
128 const page = await json(io, dir, `${def}/pages/${pf}/page.json`)
129 if (!page) continue
130 const pid = `${pagesId}/${pf}`
131 const ppath = `${rname}/${page.displayName ?? pf}.Page`
132 const active = meta?.activePageName === pf ? 'active' : ''
133 const hidden = page.visibility === 'HiddenInViewMode'
134 const pfile = `${def}/pages/${pf}/page.json`
135 out.push({ ...node(pid, pagesId, 'page', page.displayName ?? pf, ppath, hash(JSON.stringify(page)), active, pfile), hidden })
136 out.push(...filters(page.filterConfig?.filters, pid, ppath, 'pagefilter', pfile))
137 const vdir = `${def}/pages/${pf}/visuals`
138 const vfolders = await dirs(io, dir, vdir)
139 const visuals = await each(vfolders, READS, async vf => ({ vf, v: await json(io, dir, `${vdir}/${vf}/visual.json`) }))
140 const vis: { z: number; n: TreeNode[] }[] = []
141 for (const { vf, v } of visuals) {
142 if (!v) continue
143 const vid = `${pid}/${vf}`
144 const type = v.visual?.visualType ?? (v.visualGroup ? 'group' : 'visual')
145 const title = literal(v.visual?.visualContainerObjects?.title?.[0]?.properties?.text) || v.visualGroup?.displayName || ''
146 const vpath = `${ppath}/${v.name ?? vf}.Visual`
147 const vfile = `${vdir}/${vf}/visual.json`
148 const nodes: TreeNode[] = [
149 {
150 ...node(vid, pid, 'visual', title ? `${title}` : type, vpath, hash(JSON.stringify(v)), title ? type : '', vfile),
151 hidden: v.isHidden === true,
152 },
153 ]
154 for (const [role, st] of Object.entries((v.visual?.query?.queryState ?? {}) as Json)) {
155 const rid = `${vid}/${role}`
156 nodes.push(node(rid, vid, 'data role', role, '', '', '', vfile))
157 for (const p of (st as Json).projections ?? []) {
158 const ref = p.queryRef ?? fieldName(p.field)
159 nodes.push(node(`${rid}/${ref}`, rid, 'field', p.displayName ?? ref, vpath, '', p.displayName ? ref : '', vfile))
160 }
161 }
162 nodes.push(...filters(v.filterConfig?.filters, vid, vpath, 'visualfilter', vfile))
163 vis.push({ z: v.position?.z ?? 0, n: nodes })
164 }
165 vis.sort((a, b) => b.z - a.z)
166 for (const one of vis) out.push(...one.n)
167 }
168
169 const bdir = `${def}/bookmarks`
170 const files = (await entries(io, dir, bdir)).filter(e => e.name.endsWith('.bookmark.json'))
171 if (files.length) {
172 const bid = `${root}/bookmarks`
173 out.push(node(bid, root, 'group', `Bookmarks (${files.length})`, '', '', '', bdir))
174 for (const f of files) {
175 const b = await json(io, dir, `${bdir}/${f.name}`)
176 out.push(node(`${bid}/${f.name}`, bid, 'bookmark', b?.displayName ?? f.name, `${rname}/bookmark:${b?.name ?? f.name.replace(/\.bookmark\.json$/, '')}`, hash(JSON.stringify(b)), '', `${bdir}/${f.name}`))
177 }
178 }
179
180 const ext = await json(io, dir, `${def}/reportExtensions.json`)
181 const measures = (ext?.entities ?? []).flatMap((e: Json) =>
182 (e.measures ?? []).map((m: Json) => ({ table: e.name, m })),
183 )
184 if (measures.length) {
185 const xid = `${root}/ext`
186 out.push(node(xid, root, 'group', `Report measures (${measures.length})`, '', '', '', `${def}/reportExtensions.json`))
187 for (const { table, m } of measures)
188 out.push(node(`${xid}/${table}.${m.name}`, xid, 'ext measure', m.name, rname, hash(m.expression ?? ''), table, `${def}/reportExtensions.json`))
189 }
190 return out
191}
192
193const HEX = /^#[0-9a-f]{3,8}$/i
194
195export function colorOf(v: unknown): string {
196 if (typeof v === 'string') return HEX.test(v.trim()) ? v.trim() : ''
197 const c = (v as Json | null | undefined)?.solid?.color
198 return typeof c === 'string' && HEX.test(c.trim()) ? c.trim() : ''
199}
200
201function shown(v: unknown): string {
202 const c = colorOf(v)
203 if (c) return c
204 if (v === null || v === undefined) return 'null'
205 if (typeof v !== 'object') return String(v)
206 const text = JSON.stringify(v)
207 return text.length > 60 ? text.slice(0, 59) + '…' : text
208}
209
210const PLURAL: Record<string, string> = { property: 'properties', class: 'classes' }
211
212function plural(n: number, word: string): string {
213 return `${n} ${n === 1 ? word : (PLURAL[word] ?? `${word}s`)}`
214}
215
216function themeProps(el: Json, parent: string, file: string): TreeNode[] {
217 return Object.entries(el)
218 .filter(([k]) => k !== '$id')
219 .map(([k, v]) => node(`${parent}/${k}`, parent, 'theme prop', k, '', hash(JSON.stringify(v)), shown(v), file))
220}
221
222function themeNodes(t: Json | null, tid: string, file: string): TreeNode[] {
223 if (!t || typeof t !== 'object') return []
224 const out: TreeNode[] = []
225 const data = (Array.isArray(t.dataColors) ? t.dataColors : []).filter((c: unknown): c is string => typeof c === 'string')
226 const named = Object.entries(t).filter((e): e is [string, string] => e[0] !== 'name' && typeof e[1] === 'string' && HEX.test(e[1].trim()))
227 if (data.length || named.length) {
228 const cid = `${tid}/colors`
229 out.push(node(cid, tid, 'theme colors', 'Colors', '', '', plural(data.length + named.length, 'color'), file))
230 if (data.length) {
231 const did = `${cid}/data`
232 out.push(node(did, cid, 'theme data colors', 'Data colors', '', hash(JSON.stringify(data)), plural(data.length, 'color'), file))
233 data.forEach((c: string, i: number) => out.push(node(`${did}/${i}`, did, 'theme color', `Color ${i + 1}`, '', hash(c), c, file)))
234 }
235 for (const [k, v] of named) out.push(node(`${cid}/${k}`, cid, 'theme color', k, '', hash(v), v.trim(), file))
236 }
237 const classes = t.textClasses && typeof t.textClasses === 'object' ? Object.entries(t.textClasses as Json) : []
238 if (classes.length) {
239 const xid = `${tid}/text`
240 out.push(node(xid, tid, 'theme text', 'Text classes', '', '', plural(classes.length, 'class'), file))
241 for (const [k, v] of classes) {
242 const style = (v ?? {}) as Json
243 const font = typeof style.fontFace === 'string' ? (style.fontFace.split(',')[0] ?? '').replace(/['"]/g, '').trim() : ''
244 const note = [font, style.fontSize !== undefined ? `${style.fontSize}pt` : '', colorOf(style.color)].filter(Boolean).join(' ')
245 out.push(node(`${xid}/${k}`, xid, 'text class', k, '', hash(JSON.stringify(v)), note, file))
246 }
247 }
248 const styles = t.visualStyles && typeof t.visualStyles === 'object' ? Object.entries(t.visualStyles as Json) : []
249 if (styles.length) {
250 const sid = `${tid}/styles`
251 out.push(node(sid, tid, 'theme styles', 'Visual styles', '', '', plural(styles.length, 'target'), file))
252 for (const [vtype, states] of styles) {
253 const vid = `${sid}/${vtype}`
254 const byState = states && typeof states === 'object' ? Object.entries(states as Json) : []
255 const cardsOf = (cards: unknown) => (cards && typeof cards === 'object' ? Object.entries(cards as Json) : [])
256 const count = byState.reduce((n, [, cards]) => n + cardsOf(cards).length, 0)
257 out.push(node(vid, sid, 'theme style', vtype === '*' ? 'All visuals' : vtype, '', hash(JSON.stringify(states)), vtype === '*' ? `* wildcard, ${plural(count, 'card')}` : plural(count, 'card'), file))
258 for (const [state, cards] of byState) {
259 const at = byState.length > 1 || state !== '*' ? `${vid}/${state}` : vid
260 if (at !== vid) out.push(node(at, vid, 'theme state', state === '*' ? 'All states' : state, '', hash(JSON.stringify(cards)), state === '*' ? '* wildcard' : '', file))
261 for (const [card, list] of cardsOf(cards)) {
262 const kid = `${at}/${card}`
263 const items = (Array.isArray(list) ? list : [list]).filter((x: unknown): x is Json => Boolean(x) && typeof x === 'object')
264 const props = items.reduce((n: number, el: Json) => n + Object.keys(el).filter(k => k !== '$id').length, 0)
265 out.push(node(kid, at, 'theme card', card === '*' ? 'All cards' : card, '', hash(JSON.stringify(list)), card === '*' ? `* wildcard, ${plural(props, 'property')}` : plural(props, 'property'), file))
266 if (items.length === 1 && items[0] && !items[0].$id) out.push(...themeProps(items[0], kid, file))
267 else
268 items.forEach((el: Json, i: number) => {
269 const eid = `${kid}/${i}`
270 out.push(node(eid, kid, 'theme selector', typeof el.$id === 'string' ? el.$id : `#${i + 1}`, '', hash(JSON.stringify(el)), plural(Object.keys(el).filter(k => k !== '$id').length, 'property'), file))
271 out.push(...themeProps(el, eid, file))
272 })
273 }
274 }
275 }
276 }
277 return out
278}
279
280const NOTE_LABEL: Record<string, string> = {
281 theme: 'Type',
282 'theme color': 'Color',
283 'theme prop': 'Value',
284 'text class': 'Style',
285 'theme colors': 'Count',
286 'theme data colors': 'Count',
287 'theme text': 'Count',
288 'theme styles': 'Count',
289 'theme style': 'Cards',
290 'theme state': 'State',
291 'theme card': 'Properties',
292 'theme selector': 'Properties',
293 page: 'State',
294 'semantic model': 'Connection',
295 field: 'Field',
296 reportfilter: 'Filter type',
297 pagefilter: 'Filter type',
298 visualfilter: 'Filter type',
299 'ext measure': 'Table',
300}
301
302function themeFile(dir: string, report: Json): string {
303 const custom = report.themeCollection?.customTheme
304 const base = report.themeCollection?.baseTheme
305 if (custom?.name) return `${dir}/StaticResources/${custom.type === 'SharedResources' ? 'SharedResources' : 'RegisteredResources'}/${custom.name}`
306 if (base?.name) return `${dir}/StaticResources/SharedResources/BaseThemes/${base.name}.json`
307 return `${dir}/definition/report.json`
308}
309
310export type ModelRef = { workspace: string; id: string; name: string; local: string }
311
312export function modelRef(pbir: Json | null): ModelRef {
313 const ref = pbir?.datasetReference ?? {}
314 const local: string = ref.byPath?.path ?? ''
315 const conn: string = ref.byConnection?.connectionString ?? ''
316 const field = (key: string) => {
317 const m = conn.match(new RegExp(`${key}=("([^"]*)"|[^;]*)`, 'i'))
318 return (m?.[2] ?? m?.[1] ?? '').trim()
319 }
320 return {
321 workspace: (field('data source').match(/\/myorg\/(.+)$/i)?.[1] ?? '').trim(),
322 id: field('semanticmodelid') || (ref.byConnection?.pbiModelDatabaseName ?? ''),
323 name: local ? (local.split(/[\\/]/).pop() ?? local).replace(/\.SemanticModel$/i, '') : field('initial catalog'),
324 local,
325 }
326}
327
328export function reportDetail(n: TreeNode, dir: string): string[] {
329 const label = NOTE_LABEL[n.kind] ?? 'Note'
330 return [
331 `${n.kind} ${n.name}`,
332 ...(n.kind === 'visual' ? [`Visual type: ${visualLabel(n.note || n.name)}`] : n.note ? [`${label}: ${n.note}`] : []),
333 ...(n.path ? [`pbir path: ${n.path}`] : []),
334 ...(n.file ? [`File: ${rel(dir, n.file)}`] : []),
335 ...(n.hidden ? ['Hidden: yes'] : []),
336 ]
337}
338hooks/touch.ts 54 lines1import type { TreeNode } from '../types'
2import type { Invocation } from './parse'
3
4function glob(pattern: string): RegExp {
5 const esc = pattern
6 .split(/(\*\*|\*|\?)/)
7 .map(p => (p === '**' ? '.*' : p === '*' ? '[^/]*' : p === '?' ? '.' : p.replace(/[.+^${}()|[\]\\]/g, '\\$&')))
8 .join('')
9 return new RegExp(`(^|/)${esc}$`, 'i')
10}
11
12function pbirParts(arg: string): { page?: string; visual?: string; glob: boolean } | null {
13 const trimmed = arg.replace(/(\.(Page|Visual))\.[A-Za-z].*$/, '$1')
14 const segs = trimmed.split('/')
15 const page = segs.find(s => s.endsWith('.Page'))?.replace(/\.Page$/, '')
16 const visual = segs.find(s => s.endsWith('.Visual'))?.replace(/\.Visual$/, '')
17 if (!page && !visual) return null
18 return { page, visual, glob: /[*?]/.test(trimmed) }
19}
20
21function matches(name: string, pattern: string, isGlob: boolean): boolean {
22 if (!isGlob) return name.toLowerCase() === pattern.toLowerCase()
23 return glob(pattern.replace(/^\*\*\/?/, '')).test(name)
24}
25
26export function pbirTouched(inv: Invocation, nodes: TreeNode[]): string[] {
27 const out = new Set<string>()
28 const pages = nodes.filter(n => n.kind === 'page')
29 const visuals = nodes.filter(n => n.kind === 'visual')
30 for (const arg of inv.args.slice(1)) {
31 const p = pbirParts(arg)
32 if (!p) continue
33 const hitPages = p.page
34 ? pages.filter(n => {
35 const folder = n.id.split('/').pop() ?? ''
36 return matches(n.name, p.page ?? '', p.glob) || matches(folder, p.page ?? '', p.glob)
37 })
38 : []
39 if (!p.visual) {
40 for (const n of hitPages) out.add(n.id)
41 continue
42 }
43 for (const v of visuals) {
44 const vname = v.path.split('/').pop()?.replace(/\.Visual$/, '') ?? ''
45 const folder = (v.id.split('/').pop() ?? '').replace(/-Visual$/, '')
46 const type = v.note || v.name
47 const inPage = !p.page || p.page === '**' || hitPages.some(pg => v.parent === pg.id)
48 const named = matches(vname, p.visual, p.glob) || matches(folder, p.visual, p.glob)
49 if (inPage && (named || (p.glob && matches(type, p.visual, true)))) out.add(v.id)
50 }
51 }
52 return [...out]
53}
54hooks/icon-data.ts 6 lines1export const FAB_ITEMS: Record<string, [number, [number, number, number] | null]> = {"SemanticModel": [991234, [90, 64, 156]], "Report": [991274, [194, 132, 0]]}
2
3export const PBIR_VISUALS: Record<string, number> = {"accessibleTable": 993311, "actionButton": 993316, "advancedSlicerVisual": 993309, "aiNarratives": 991875, "animatedNumber": 993305, "areaChart": 993287, "azureMap": 993301, "barChart": 993280, "basicShape": 991978, "bookmarkNavigator": 993318, "card": 992044, "cardVisual": 993303, "clusteredBarChart": 993281, "clusteredColumnChart": 993284, "columnChart": 993283, "dataQueryVisual": 992065, "debugVisual": 993322, "decompositionTreeVisual": 991825, "donutChart": 993297, "filledMap": 993300, "filterSlicer": 991891, "funnel": 993294, "gauge": 993302, "group": 993323, "groupVisual": 993323, "heatMap": 993313, "hundredPercentStackedAreaChart": 993289, "hundredPercentStackedBarChart": 993282, "hundredPercentStackedColumnChart": 993285, "image": 993315, "keyDriversVisual": 993319, "keyInfluencers": 993319, "kpi": 993306, "lineChart": 993286, "lineClusteredColumnComboChart": 993291, "lineStackedColumnComboChart": 993290, "listSlicer": 993307, "map": 993299, "matrix": 992035, "multiRowCard": 993304, "pageNavigator": 993317, "pieChart": 993296, "pivotTable": 993312, "pythonVisual": 992051, "qnaVisual": 993320, "rdlVisual": 991878, "ribbonChart": 993292, "scatterChart": 993295, "scorecard": 992054, "scriptVisual": 993321, "shape": 991979, "shapeMap": 991948, "slicer": 992062, "stackedAreaChart": 993288, "stackedBarChart": 993280, "stackedColumnChart": 993283, "table": 993310, "tableEx": 992023, "textSlicer": 993308, "textbox": 993314, "treemap": 993298, "waterfallChart": 993293}
4
5export const PBIR_CHILDREN: Record<string, number> = {"page": 991989, "visual": 991983, "field": 991803, "reportfilter": 991891, "pagefilter": 992062, "visualfilter": 991898, "bookmark": 991764, "ext measure": 992019, "data role": 991982}
6