ui: add com.android.ProcessGraph plugin Add the contextual com.android.ProcessGraph selection-tab plugin rendering Android service and content provider dependencies layered horizontally from CACHED to PERSISTENT, with Direct connections / Directed chains / Full component scoping over active bindings, frozen snowflake markers, priority-waived edge dimming, event/time stepping, and a persistent right-hand node/edge inspector.
diff --git a/ui/src/core/embedder/default_plugins.ts b/ui/src/core/embedder/default_plugins.ts index 295d924..ea4f0dc 100644 --- a/ui/src/core/embedder/default_plugins.ts +++ b/ui/src/core/embedder/default_plugins.ts
@@ -45,6 +45,7 @@ 'com.android.MemoryViz', 'com.android.PinAndroidPerfMetrics', 'com.android.PinSysUITracks', + 'com.android.ProcessGraph', 'com.android.ProcessState', 'com.android.SysUIWorkspace', 'com.android.WearLongBatteryTracing',
diff --git a/ui/src/plugins/com.android.ProcessGraph/OWNERS b/ui/src/plugins/com.android.ProcessGraph/OWNERS new file mode 100644 index 0000000..c533c67 --- /dev/null +++ b/ui/src/plugins/com.android.ProcessGraph/OWNERS
@@ -0,0 +1 @@ +gignat@google.com
diff --git a/ui/src/plugins/com.android.ProcessGraph/chart_option.ts b/ui/src/plugins/com.android.ProcessGraph/chart_option.ts new file mode 100644 index 0000000..88fcb45 --- /dev/null +++ b/ui/src/plugins/com.android.ProcessGraph/chart_option.ts
@@ -0,0 +1,275 @@ +// Copyright (C) 2026 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type { + GraphChartData, + GraphEdge, + GraphEdgeHighlight, + GraphLayer, + GraphNode, + GraphNodeHighlight, + GraphTooltip, +} from '../../components/widgets/charts/graph_chart'; +import { + type CollapsedEdge, + type ContextualSubgraph, + type GraphSnapshot, + type ProcessGraphModel, + type ProcessInfo, + stateStyle, +} from './model'; + +export const SNOWFLAKE_SYMBOL_PATH = + 'path://M 10.68 7.39 L 10.89 5.70 L 8.72 2.98 L 10.93 4.37 L 12.00 0.60 ' + + 'L 13.07 4.37 L 15.28 2.98 L 13.11 5.70 L 13.32 7.39 L 15.33 8.55 ' + + 'L 16.90 7.89 L 18.17 4.65 L 18.07 7.26 L 21.87 6.30 L 19.14 9.12 ' + + 'L 21.45 10.33 L 18.01 9.81 L 16.66 10.84 L 16.66 13.16 L 18.01 14.19 ' + + 'L 21.45 13.67 L 19.14 14.88 L 21.87 17.70 L 18.07 16.74 L 18.17 19.35 ' + + 'L 16.90 16.11 L 15.33 15.45 L 13.32 16.61 L 13.11 18.30 L 15.28 21.02 ' + + 'L 13.07 19.63 L 12.00 23.40 L 10.93 19.63 L 8.72 21.02 L 10.89 18.30 ' + + 'L 10.68 16.61 L 8.67 15.45 L 7.10 16.11 L 5.83 19.35 L 5.93 16.74 ' + + 'L 2.13 17.70 L 4.86 14.88 L 2.55 13.67 L 5.99 14.19 L 7.34 13.16 ' + + 'L 7.34 10.84 L 5.99 9.81 L 2.55 10.33 L 4.86 9.12 L 2.13 6.30 ' + + 'L 5.93 7.26 L 5.83 4.65 L 7.10 7.89 L 8.67 8.55 Z'; + +export type SelectedItem = + | {readonly type: 'node'; readonly upid: number} + | {readonly type: 'edge'; readonly key: string}; + +export function buildProcessInfoFallback( + model: ProcessGraphModel, + upid: number, +): ProcessInfo { + return ( + model.procsByUpid.get(upid) ?? { + upid, + pid: 0, + name: `upid ${upid}`, + } + ); +} + +function buildEdgeTooltip( + model: ProcessGraphModel, + edge: CollapsedEdge, + badge: string, + stepDiff?: string, +): GraphTooltip { + const cn = buildProcessInfoFallback(model, edge.client); + const sn = buildProcessInfoFallback(model, edge.server); + return [ + {value: badge, bold: true}, + `${cn.name} (pid ${cn.pid}) → ${sn.name} (pid ${sn.pid})`, + { + label: 'kind', + value: `${edge.kind} · connections=${edge.count}`, + bold: true, + }, + ...(edge.waivesPriority === true + ? [{label: 'priority', value: 'waived (NOT_FOREGROUND / WAIVE_PRIORITY)'}] + : []), + ...(stepDiff !== undefined + ? [{label: 'step diff', value: stepDiff, bold: true}] + : []), + ...edge.components.slice(0, 3), + ]; +} + +export function buildProcessGraphChartData( + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + snap: GraphSnapshot, + selected: SelectedItem | undefined, + prevSnap?: GraphSnapshot, +): GraphChartData { + const colCounts = new Map<number, number>(); + for (const n of snap.nodes) { + colCounts.set(n.stateRank, (colCounts.get(n.stateRank) ?? 0) + 1); + } + + const rankSet = new Set<number>(subgraph.orderedRanks); + for (const rank of colCounts.keys()) { + rankSet.add(rank); + } + const orderedRanks = + rankSet.size === subgraph.orderedRanks.length + ? subgraph.orderedRanks + : [...rankSet].sort((a, b) => b - a); + + const layers: GraphLayer[] = orderedRanks.map((rank) => { + const stName = + subgraph.rankToState.get(rank) ?? + snap.nodes.find((n) => n.stateRank === rank)?.state ?? + 'UNKNOWN'; + const st = stateStyle(stName); + const cnt = colCounts.get(rank) ?? 0; + return { + id: rank, + label: `${st.short} (${cnt})`, + color: st.fill, + lightTextColor: st.lightText, + dimmed: cnt === 0, + }; + }); + + const prevVisibleUpids = + prevSnap !== undefined + ? new Set(prevSnap.nodes.map((n) => n.upid)) + : undefined; + const visibleUpids = new Set(snap.nodes.map((n) => n.upid)); + + const nodes: GraphNode[] = snap.nodes.map((n) => { + const isSel = selected?.type === 'node' && selected.upid === n.upid; + let highlight: GraphNodeHighlight | undefined; + let diffText: string | undefined; + + if (prevSnap !== undefined && prevVisibleUpids !== undefined) { + if (!prevVisibleUpids.has(n.upid)) { + highlight = 'added'; + diffText = 'appeared in view'; + } else { + const prevNode = prevSnap.allNodesMap.get(n.upid); + if (prevNode !== undefined) { + const diffs: string[] = []; + if (prevNode.state !== n.state) { + diffs.push(`${prevNode.state} → ${n.state}`); + } + if (prevNode.isFrozen !== n.isFrozen) { + diffs.push(n.isFrozen ? 'UNFROZEN → FROZEN' : 'FROZEN → UNFROZEN'); + } + if (diffs.length > 0) { + highlight = 'changed'; + diffText = diffs.join(' · '); + } + } + } + } + + const tooltip: GraphTooltip = [ + {value: `${n.name} (pid ${n.pid})`, bold: true}, + {label: 'state', value: n.state, bold: true}, + ...(n.isFrozen ? [{label: 'freezer', value: 'FROZEN', bold: true}] : []), + ...(diffText !== undefined + ? [{label: 'step diff', value: diffText, bold: true}] + : []), + ...(n.reason ? [{label: 'reason', value: n.reason}] : []), + ...(n.isTarget ? ['Selected on timeline'] : []), + ]; + + return { + id: String(n.upid), + label: n.name || `pid ${n.pid}`, + layer: n.stateRank, + normPosition: subgraph.normYByUpid.get(n.upid) ?? 0.5, + color: stateStyle(n.state).fill, + symbol: n.isFrozen ? SNOWFLAKE_SYMBOL_PATH : undefined, + symbolKeepAspect: n.isFrozen ? true : undefined, + symbolSizeScale: n.isFrozen ? 1.68 : undefined, + borderColor: n.isFrozen ? '#0ea5e9' : undefined, + borderWidth: n.isFrozen ? 1.45 : undefined, + accentRingColor: n.isTarget ? '#f59e0b' : undefined, + labelBold: n.isTarget || isSel, + showLabel: true, + selected: isSel, + highlight, + tooltip, + }; + }); + + const prevEdgeMap = + prevSnap !== undefined + ? new Map(prevSnap.edges.map((pe) => [pe.key, pe])) + : undefined; + const curEdgeKeys = new Set<string>(); + + const edges: GraphEdge[] = snap.edges.map((e) => { + curEdgeKeys.add(e.key); + const isSelf = e.client === e.server; + const clientState = snap.allNodesMap.get(e.client)?.state ?? 'UNKNOWN'; + const prevEdge = prevEdgeMap?.get(e.key); + let highlight: GraphEdgeHighlight | undefined; + let stepDiff: string | undefined; + + if (prevEdgeMap !== undefined) { + if (prevEdge === undefined) { + highlight = 'added'; + stepDiff = 'added at this step'; + } else if (e.count > prevEdge.count) { + highlight = 'added'; + stepDiff = `connections ${prevEdge.count} → ${e.count}`; + } else if (e.count < prevEdge.count) { + stepDiff = `connections ${prevEdge.count} → ${e.count}`; + } + } + + const baseParts = [ + ...(highlight === 'added' ? ['NEW'] : []), + ...(isSelf ? ['SELF-LOOP'] : []), + e.kind.toUpperCase(), + ...(e.waivesPriority === true ? ['PRIORITY WAIVED'] : []), + ]; + const badge = `[${baseParts.join(' · ')}]`; + + return { + id: e.key, + source: String(e.client), + target: String(e.server), + weight: e.count, + color: stateStyle(clientState).fill, + lineType: e.kind === 'provider' ? 'dashed' : 'solid', + width: e.waivesPriority === true ? 0.95 : undefined, + opacity: e.waivesPriority === true ? 0.3 : undefined, + selected: selected?.type === 'edge' && selected.key === e.key, + highlight, + tooltip: buildEdgeTooltip(model, e, badge, stepDiff), + }; + }); + + if (prevSnap !== undefined) { + for (const pe of prevSnap.edges) { + if ( + !curEdgeKeys.has(pe.key) && + visibleUpids.has(pe.client) && + visibleUpids.has(pe.server) + ) { + const isSelf = pe.client === pe.server; + const badgeParts = [ + 'REMOVED', + ...(isSelf ? ['SELF-LOOP'] : []), + pe.kind.toUpperCase(), + ]; + edges.push({ + id: pe.key, + source: String(pe.client), + target: String(pe.server), + weight: pe.count, + selected: selected?.type === 'edge' && selected.key === pe.key, + highlight: 'removed', + tooltip: buildEdgeTooltip( + model, + pe, + `[${badgeParts.join(' · ')}]`, + 'removed at this step', + ), + }); + } + } + } + + return { + layers, + nodes, + edges, + }; +}
diff --git a/ui/src/plugins/com.android.ProcessGraph/index.ts b/ui/src/plugins/com.android.ProcessGraph/index.ts new file mode 100644 index 0000000..cc79089 --- /dev/null +++ b/ui/src/plugins/com.android.ProcessGraph/index.ts
@@ -0,0 +1,206 @@ +// Copyright (C) 2026 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import './styles.scss'; +import m from 'mithril'; +import {Time} from '../../base/time'; +import type {PerfettoPlugin} from '../../public/plugin'; +import type {Selection} from '../../public/selection'; +import type {Trace} from '../../public/trace'; +import {NUM, STR} from '../../trace_processor/query_result'; +import ProcessState from '../com.android.ProcessState'; +import { + TAG_BINDS_TO_TRACK, + TAG_BOUND_BY_TRACK, + TAG_COUNT_TRACK, +} from '../com.android.ProcessState/aggregators'; +import { + type ProcessGraphContext, + ProcessGraphPanel, + ProcessGraphSession, +} from './process_graph_panel'; + +const PLUGIN_ID = 'com.android.ProcessGraph'; +const SELECTION_TAB_ID = `${PLUGIN_ID}#SelectionTab`; + +const PEER_TRACK_URI_RE = + /^com\.android\.ProcessState#process\.\d+\.(?:(?:provider_)?bound_by|(?:provider_)?binds_to)\.(\d+)(?:\.overview)?$/; + +function extractPeerUpid(trackUri: string): number | undefined { + const match = PEER_TRACK_URI_RE.exec(trackUri); + return match !== null ? Number(match[1]) : undefined; +} + +export function resolveProcessGraphContext( + ctx: Trace, + selection: Selection, + bindingEdgeByRowId: ReadonlyMap<number, string>, +): ProcessGraphContext | undefined { + if (selection.kind === 'track_event') { + const track = ctx.tracks.getTrack(selection.trackUri); + const upid = track?.tags?.upid; + if (upid === undefined) return undefined; + + const windowStart = selection.ts; + const rawDur = selection.dur; + const windowEnd = + rawDur === undefined || rawDur === 0n + ? selection.ts + : rawDur < 0n + ? ctx.traceInfo.end + : Time.fromRaw(selection.ts + rawDur); + const isBindingTrack = + track?.tags?.type === TAG_BOUND_BY_TRACK || + track?.tags?.type === TAG_BINDS_TO_TRACK; + const preselectedEdgeKey = isBindingTrack + ? bindingEdgeByRowId.get(selection.eventId) + : undefined; + + return { + selectionKey: `event:${selection.trackUri}:${selection.eventId}:${windowStart}:${windowEnd}`, + windowStart, + windowEnd: windowEnd < windowStart ? windowStart : windowEnd, + targetUpids: [upid], + targetStates: [], + preselectedEdgeKey, + }; + } + + if (selection.kind === 'area') { + const upids = new Set<number>(); + const peerUpids = new Set<number>(); + const states = new Set<string>(); + let allTracksHavePeer = selection.tracks.length > 0; + for (const track of selection.tracks) { + if (typeof track.tags?.upid === 'number') { + upids.add(track.tags.upid); + } + const peerUpid = extractPeerUpid(track.uri); + if (peerUpid !== undefined) { + peerUpids.add(peerUpid); + } else { + allTracksHavePeer = false; + } + if ( + track.tags?.type === TAG_COUNT_TRACK && + typeof track.tags?.state === 'string' + ) { + states.add(track.tags.state); + } + } + // Area drags over a collapsed group include all child tracks; only include + // peerUpids when the user explicitly dragged over peer child track(s). + if (allTracksHavePeer) { + for (const peerUpid of peerUpids) { + upids.add(peerUpid); + } + } + if (upids.size === 0 && states.size === 0) return undefined; + + const targetUpids = [...upids].sort((a, b) => a - b); + const targetStates = [...states].sort(); + return { + selectionKey: `area:${selection.start}:${selection.end}:u=${targetUpids.join(',')}:s=${targetStates.join(',')}`, + windowStart: selection.start, + windowEnd: selection.end, + targetUpids, + targetStates, + }; + } + + if (selection.kind === 'track') { + const tags = ctx.tracks.getTrack(selection.trackUri)?.tags; + const upid = tags?.upid; + if (upid === undefined) return undefined; + const targetSet = new Set<number>([upid]); + const peerUpid = extractPeerUpid(selection.trackUri); + if (peerUpid !== undefined) { + targetSet.add(peerUpid); + } + const targetUpids = [...targetSet].sort((a, b) => a - b); + return { + selectionKey: `track:${selection.trackUri}:${targetUpids.join(',')}`, + windowStart: ctx.traceInfo.start, + windowEnd: ctx.traceInfo.end, + targetUpids, + targetStates: [], + }; + } + + return undefined; +} + +export default class ProcessGraphPlugin implements PerfettoPlugin { + static readonly id = PLUGIN_ID; + static readonly description = + 'Visualizes contextual Android service and content provider process dependencies.'; + static readonly dependencies = [ProcessState]; + + async onTraceLoad(ctx: Trace): Promise<void> { + const res = await ctx.engine.query(` + SELECT + EXISTS(SELECT 1 FROM slice WHERE category = 'service_state') + OR EXISTS(SELECT 1 FROM slice WHERE category = 'provider_state') + AS hasBindings + `); + if (res.firstRow({hasBindings: NUM}).hasBindings === 0) { + return; + } + + await ctx.engine.query(`INCLUDE PERFETTO MODULE android.process_bindings;`); + + const bindingEdgeByRowId = new Map<number, string>(); + const indexRes = await ctx.engine.query(` + SELECT id, binding_kind, client_upid, server_upid + FROM _android_process_bindings + `); + for ( + const it = indexRes.iter({ + id: NUM, + binding_kind: STR, + client_upid: NUM, + server_upid: NUM, + }); + it.valid(); + it.next() + ) { + bindingEdgeByRowId.set( + it.id, + `${it.binding_kind}:${it.client_upid}>${it.server_upid}`, + ); + } + + const session = new ProcessGraphSession(); + ctx.trash.defer(() => session.dispose()); + + ctx.selection.registerSelectionTab({ + id: SELECTION_TAB_ID, + name: 'Process Graph', + render: (selection) => { + const context = resolveProcessGraphContext( + ctx, + selection, + bindingEdgeByRowId, + ); + if (context === undefined) { + return undefined; + } + return { + isLoading: false, + content: m(ProcessGraphPanel, {trace: ctx, session, context}), + }; + }, + }); + } +}
diff --git a/ui/src/plugins/com.android.ProcessGraph/model.ts b/ui/src/plugins/com.android.ProcessGraph/model.ts new file mode 100644 index 0000000..2088821 --- /dev/null +++ b/ui/src/plugins/com.android.ProcessGraph/model.ts
@@ -0,0 +1,1186 @@ +// Copyright (C) 2026 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {type CancellationSignal, TASK_CANCELLED} from '../../base/async_memo'; +import {Time, type time} from '../../base/time'; +import {computeBarycenterOrder} from '../../components/widgets/charts/graph_chart'; +import type {Trace} from '../../public/trace'; +import { + LONG, + NUM, + NUM_NULL, + STR, + STR_NULL, +} from '../../trace_processor/query_result'; + +export type EdgeKind = 'service' | 'provider'; +export type ScopeMode = 'chains' | 'neighbors' | 'component'; +export type StepMode = 'any' | 'edge' | 100 | 1000 | 5000; + +export interface ProcessInfo { + readonly upid: number; + readonly pid: number; + readonly name: string; + readonly uid?: number; + readonly packageName?: string; +} + +export interface StateInterval { + readonly upid: number; + readonly ts: time; + readonly endTs: time; + readonly state: string; + readonly stateRank: number; + readonly reason?: string; +} + +export interface FreezerInterval { + readonly upid: number; + readonly ts: time; + readonly endTs: time; +} + +export interface ConnectionInterval { + readonly kind: EdgeKind; + readonly ts: time; + readonly endTs: time; + readonly clientUpid: number; + readonly serverUpid: number; + readonly label?: string; + readonly detail?: string; + readonly waivesPriority?: boolean; +} + +export interface ProcessGraphFilters { + readonly showServices: boolean; + readonly showProviders: boolean; + readonly showSelfLoops: boolean; + readonly searchQuery: string; +} + +export interface SnapshotNode { + readonly upid: number; + readonly pid: number; + readonly name: string; + readonly uid?: number; + readonly packageName?: string; + readonly state: string; + readonly stateRank: number; + readonly reason?: string; + readonly isFrozen: boolean; + readonly isTarget: boolean; +} + +export interface CollapsedEdge { + readonly key: string; + readonly kind: EdgeKind; + readonly client: number; + readonly server: number; + readonly count: number; + readonly components: ReadonlyArray<string>; + readonly details: ReadonlyArray<string>; + readonly waivesPriority?: boolean; +} + +export interface GraphSnapshot { + readonly ts: time; + readonly allNodesMap: ReadonlyMap<number, SnapshotNode>; + readonly rawEdges: ReadonlyArray<CollapsedEdge>; + readonly nodes: ReadonlyArray<SnapshotNode>; + readonly edges: ReadonlyArray<CollapsedEdge>; +} + +export interface ProcessGraphInput { + readonly traceStart: time; + readonly traceEnd: time; + readonly processes: ReadonlyArray<ProcessInfo>; + readonly stateIntervals: ReadonlyArray<StateInterval>; + readonly connections: ReadonlyArray<ConnectionInterval>; + readonly freezerIntervals?: ReadonlyArray<FreezerInterval>; +} + +export interface ProcessGraphModel { + readonly traceStart: time; + readonly traceEnd: time; + readonly procsByUpid: ReadonlyMap<number, ProcessInfo>; + readonly stateByUpid: ReadonlyMap<number, ReadonlyArray<StateInterval>>; + readonly freezerByUpid: ReadonlyMap<number, ReadonlyArray<FreezerInterval>>; + readonly connections: ReadonlyArray<ConnectionInterval>; + readonly globalRankToState: ReadonlyMap<number, string>; +} + +export interface ContextualSubgraphSpec { + readonly windowStart: time; + readonly windowEnd: time; + readonly targetUpids: ReadonlyArray<number>; + readonly targetStates?: ReadonlyArray<string>; + readonly scopeMode: ScopeMode; + readonly filters: ProcessGraphFilters; +} + +export interface ContextualSubgraph { + readonly windowStart: time; + readonly windowEnd: time; + readonly scopeMode: ScopeMode; + readonly explicitTargetUpids: ReadonlySet<number>; + readonly targetStates: ReadonlySet<string>; + readonly soloExitedFallbackUpid?: number; + readonly targetUpidSet: ReadonlySet<number>; + readonly subgraphUpids: ReadonlySet<number>; + readonly windowConnections: ReadonlyArray<ConnectionInterval>; + readonly orderedRanks: ReadonlyArray<number>; + readonly rankToState: ReadonlyMap<number, string>; + readonly normYByUpid: ReadonlyMap<number, number>; + readonly edgeEvents: ReadonlyArray<time>; + readonly anyEvents: ReadonlyArray<time>; +} + +export interface StateStyle { + readonly fill: string; + readonly lightText: string; + readonly short: string; +} + +const EXITED_RANK = 21; +const UNKNOWN_RANK = 999; + +const STATE_STYLES: Readonly< + Record<string, readonly [fill: string, lightText: string, short?: string]> +> = { + PERSISTENT: ['#ab47bc', '#7b1fa2'], + PERSISTENT_UI: ['#ba68c8', '#8e24aa'], + TOP: ['#ef5350', '#c62828'], + BOUND_TOP: ['#ff7043', '#d84315'], + FOREGROUND_SERVICE: ['#ffa726', '#c25e00', 'FGS'], + BOUND_FOREGROUND_SERVICE: ['#ffca28', '#9e6b00', 'BOUND_FGS'], + IMPORTANT_FOREGROUND: ['#ffee58', '#827717', 'IMP_FG'], + IMPORTANT_BACKGROUND: ['#d4e157', '#558b2f', 'IMP_BG'], + TRANSIENT_BACKGROUND: ['#9ccc65', '#33691e', 'TRANSIENT_BG'], + BACKUP: ['#66bb6a', '#2e7d32'], + SERVICE: ['#26a69a', '#00695c'], + RECEIVER: ['#26c6da', '#00838f'], + TOP_SLEEPING: ['#29b6f6', '#0277bd'], + HEAVY_WEIGHT: ['#42a5f5', '#1565c0'], + HOME: ['#5c6bc0', '#283593'], + LAST_ACTIVITY: ['#7e57c2', '#4527a0'], + CACHED_ACTIVITY: ['#a1887f', '#5d4037', 'CACHED_ACT'], + CACHED_ACTIVITY_CLIENT: ['#bcaaa4', '#6d4c41', 'CACHED_ACT_CLI'], + CACHED_RECENT: ['#90a4ae', '#455a64'], + CACHED_EMPTY: ['#78909c', '#37474f'], + NONEXISTENT: ['#607d8b', '#455a64'], + EXITED: ['#78909c', '#455a64'], + UNKNOWN: ['#9e9e9e', '#616161'], +}; + +export function stateStyle(state: string): StateStyle { + const entry = STATE_STYLES[state]; + return { + fill: entry?.[0] ?? '#9e9e9e', + lightText: entry?.[1] ?? '#475569', + short: entry?.[2] ?? state, + }; +} + +export function hasPriorityWaivingFlag( + flagsOrDetail: string | null | undefined, +): boolean { + if (!flagsOrDetail) return false; + const flagsIdx = flagsOrDetail.indexOf('flags='); + const afterFlags = + flagsIdx >= 0 + ? flagsOrDetail.slice(flagsIdx + 'flags='.length) + : flagsOrDetail; + const sepIdx = afterFlags.indexOf(' · '); + const raw = sepIdx >= 0 ? afterFlags.slice(0, sepIdx) : afterFlags; + for (const token of raw.split(',')) { + const t = token.trim(); + if (t === 'WAIVE_PRIORITY' || t === 'NOT_FOREGROUND') { + return true; + } + } + return false; +} + +export function upperBoundTime(arr: ReadonlyArray<time>, t: time): number { + let lo = 0; + let hi = arr.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + const val = arr[mid]; + if (val !== undefined && val <= t) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} + +function dedupSortedTimes(raw: time[]): ReadonlyArray<time> { + raw.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + const out: time[] = []; + for (const t of raw) { + if (out.length === 0 || out[out.length - 1] !== t) { + out.push(t); + } + } + return out; +} + +export function buildProcessGraphModel( + input: ProcessGraphInput, +): ProcessGraphModel { + const {traceStart, traceEnd} = input; + const procsByUpid = new Map<number, ProcessInfo>(); + for (const p of input.processes) { + procsByUpid.set(p.upid, p); + } + + const globalRankToState = new Map<number, string>(); + const stateByUpidMut = new Map<number, StateInterval[]>(); + for (const s of input.stateIntervals) { + globalRankToState.set(s.stateRank, s.state); + let list = stateByUpidMut.get(s.upid); + if (list === undefined) { + list = []; + stateByUpidMut.set(s.upid, list); + } + list.push(s); + } + for (const list of stateByUpidMut.values()) { + list.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0)); + } + + const freezerByUpidMut = new Map<number, FreezerInterval[]>(); + for (const f of input.freezerIntervals ?? []) { + let list = freezerByUpidMut.get(f.upid); + if (list === undefined) { + list = []; + freezerByUpidMut.set(f.upid, list); + } + list.push(f); + } + for (const list of freezerByUpidMut.values()) { + list.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0)); + } + + for (const c of input.connections) { + for (const u of [c.clientUpid, c.serverUpid]) { + if (!procsByUpid.has(u)) { + procsByUpid.set(u, {upid: u, pid: 0, name: `upid ${u}`}); + } + } + } + + const sortedConnections = [...input.connections].sort((a, b) => + a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0, + ); + + return { + traceStart, + traceEnd, + procsByUpid, + stateByUpid: stateByUpidMut, + freezerByUpid: freezerByUpidMut, + connections: sortedConnections, + globalRankToState, + }; +} + +function findIntervalAt<T extends {readonly ts: time; readonly endTs: time}>( + intervals: ReadonlyArray<T> | undefined, + ts: time, +): T | undefined { + if (intervals === undefined || intervals.length === 0) return undefined; + let lo = 0; + let hi = intervals.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + const iv = intervals[mid]; + if (iv !== undefined && iv.ts <= ts) { + lo = mid + 1; + } else { + hi = mid; + } + } + if (lo === 0) return undefined; + const candidate = intervals[lo - 1]; + return candidate !== undefined && candidate.ts <= ts && ts < candidate.endTs + ? candidate + : undefined; +} + +function pushAdj(map: Map<number, number[]>, from: number, to: number): void { + let list = map.get(from); + if (list === undefined) { + list = []; + map.set(from, list); + } + list.push(to); +} + +function bfsReachable( + seeds: Iterable<number>, + adj: ReadonlyMap<number, ReadonlyArray<number>>, + out: Set<number>, +): void { + const seen = new Set<number>(seeds); + const queue = [...seen]; + for (let head = 0; head < queue.length; head++) { + const u = queue[head]; + if (u === undefined) continue; + for (const v of adj.get(u) ?? []) { + out.add(v); + if (!seen.has(v)) { + seen.add(v); + queue.push(v); + } + } + } +} + +interface TimeSpan { + ts: time; + endTs: time; +} + +function appendMergedSpan( + spansByUpid: Map<number, TimeSpan[]>, + upid: number, + ts: time, + endTs: time, +): void { + if (endTs <= ts) return; + const spans = spansByUpid.get(upid); + if (spans === undefined) { + spansByUpid.set(upid, [{ts, endTs}]); + return; + } + const last = spans[spans.length - 1]; + if (last !== undefined && ts <= last.endTs) { + if (endTs > last.endTs) { + last.endTs = endTs; + } + } else { + spans.push({ts, endTs}); + } +} + +function getStateAt( + model: ProcessGraphModel, + upid: number, + ts: time, +): { + readonly state: string; + readonly stateRank: number; + readonly reason?: string; +} { + const sList = model.stateByUpid.get(upid); + const st = findIntervalAt(sList, ts); + if (st !== undefined) { + return {state: st.state, stateRank: st.stateRank, reason: st.reason}; + } + const hasStateTrack = sList !== undefined && sList.length > 0; + return hasStateTrack + ? {state: 'EXITED', stateRank: EXITED_RANK} + : {state: 'UNKNOWN', stateRank: UNKNOWN_RANK}; +} + +export function buildContextualSubgraph( + model: ProcessGraphModel, + spec: ContextualSubgraphSpec, +): ContextualSubgraph { + const windowStart = Time.clamp( + spec.windowStart, + model.traceStart, + model.traceEnd, + ); + const windowEnd = Time.clamp( + spec.windowEnd < windowStart ? windowStart : spec.windowEnd, + model.traceStart, + model.traceEnd, + ); + const testEnd = + windowEnd > windowStart ? windowEnd : Time.fromRaw(windowStart + 1n); + const inclusiveWindowEnd = Time.fromRaw(windowEnd + 1n); + + const explicitTargetUpids = new Set<number>(spec.targetUpids); + const targetStates = new Set<string>(spec.targetStates ?? []); + const targetUpidSet = new Set<number>(explicitTargetUpids); + if (targetStates.size > 0) { + for (const [upid, list] of model.stateByUpid) { + for (const iv of list) { + if (iv.ts >= inclusiveWindowEnd) break; + if (iv.endTs > windowStart && targetStates.has(iv.state)) { + targetUpidSet.add(upid); + break; + } + } + } + } + + const {filters, scopeMode} = spec; + const subgraphUpids = new Set<number>(targetUpidSet); + let windowConnections: ConnectionInterval[]; + + if (scopeMode === 'neighbors') { + windowConnections = []; + for (const c of model.connections) { + if (c.ts >= testEnd) break; + if (c.endTs <= windowStart) continue; + if (!filters.showServices && c.kind === 'service') continue; + if (!filters.showProviders && c.kind === 'provider') continue; + if (!filters.showSelfLoops && c.clientUpid === c.serverUpid) continue; + if (targetUpidSet.has(c.clientUpid) || targetUpidSet.has(c.serverUpid)) { + subgraphUpids.add(c.clientUpid); + subgraphUpids.add(c.serverUpid); + windowConnections.push(c); + } + } + } else { + const activeConns: ConnectionInterval[] = []; + const undirectedAdj = new Map<number, number[]>(); + const forwardAdj = new Map<number, number[]>(); + const reverseAdj = new Map<number, number[]>(); + + for (const c of model.connections) { + if (c.ts >= testEnd) break; + if (c.endTs <= windowStart) continue; + if (!filters.showServices && c.kind === 'service') continue; + if (!filters.showProviders && c.kind === 'provider') continue; + if (!filters.showSelfLoops && c.clientUpid === c.serverUpid) continue; + activeConns.push(c); + if (c.clientUpid !== c.serverUpid) { + if (scopeMode === 'component') { + pushAdj(undirectedAdj, c.clientUpid, c.serverUpid); + pushAdj(undirectedAdj, c.serverUpid, c.clientUpid); + } else { + pushAdj(forwardAdj, c.clientUpid, c.serverUpid); + pushAdj(reverseAdj, c.serverUpid, c.clientUpid); + } + } + } + + if (scopeMode === 'component') { + bfsReachable(targetUpidSet, undirectedAdj, subgraphUpids); + } else { + bfsReachable(targetUpidSet, forwardAdj, subgraphUpids); + bfsReachable(targetUpidSet, reverseAdj, subgraphUpids); + } + + windowConnections = activeConns.filter( + (c) => subgraphUpids.has(c.clientUpid) && subgraphUpids.has(c.serverUpid), + ); + } + + const soloTargetUpid = + explicitTargetUpids.size === 1 && targetStates.size === 0 + ? [...explicitTargetUpids][0] + : undefined; + let soloExitedFallbackUpid: number | undefined; + if (soloTargetUpid !== undefined) { + const sList = model.stateByUpid.get(soloTargetUpid); + if (sList !== undefined && sList.length > 0) { + const hasLiveInWindow = sList.some( + (s) => s.ts < inclusiveWindowEnd && s.endTs > windowStart, + ); + if (!hasLiveInWindow) { + soloExitedFallbackUpid = soloTargetUpid; + } + } + } + + const connSpansByUpid = new Map<number, TimeSpan[]>(); + for (const c of windowConnections) { + const spStart = c.ts > windowStart ? c.ts : windowStart; + const spEnd = c.endTs < inclusiveWindowEnd ? c.endTs : inclusiveWindowEnd; + appendMergedSpan(connSpansByUpid, c.clientUpid, spStart, spEnd); + if (c.serverUpid !== c.clientUpid) { + appendMergedSpan(connSpansByUpid, c.serverUpid, spStart, spEnd); + } + } + const soloWindowSpans: ReadonlyArray<TimeSpan> = [ + {ts: windowStart, endTs: inclusiveWindowEnd}, + ]; + + const rankToState = new Map<number, string>(model.globalRankToState); + const visitedRanks = new Set<number>(); + const primaryRankByUpid = new Map<number, number>(); + + for (const upid of subgraphUpids) { + const visSpans = + upid === soloTargetUpid ? soloWindowSpans : connSpansByUpid.get(upid); + if (visSpans === undefined || visSpans.length === 0) { + continue; + } + + const sList = model.stateByUpid.get(upid); + if (sList === undefined || sList.length === 0) { + rankToState.set(UNKNOWN_RANK, 'UNKNOWN'); + visitedRanks.add(UNKNOWN_RANK); + primaryRankByUpid.set(upid, UNKNOWN_RANK); + continue; + } + + const rankOverlap = new Map<number, bigint>(); + let bestOverlap = -1n; + let bestRank = UNKNOWN_RANK; + let spanIdx = 0; + for (const s of sList) { + if (s.ts >= inclusiveWindowEnd) break; + if (s.endTs <= windowStart) continue; + while ( + spanIdx < visSpans.length && + (visSpans[spanIdx]?.endTs ?? 0n) <= s.ts + ) { + spanIdx++; + } + for (let j = spanIdx; j < visSpans.length; j++) { + const sp = visSpans[j]; + if (sp === undefined || sp.ts >= s.endTs) break; + const ovStart = s.ts > sp.ts ? s.ts : sp.ts; + const ovEnd = s.endTs < sp.endTs ? s.endTs : sp.endTs; + if (ovEnd > ovStart) { + visitedRanks.add(s.stateRank); + rankToState.set(s.stateRank, s.state); + const totalOv = + (rankOverlap.get(s.stateRank) ?? 0n) + (ovEnd - ovStart); + rankOverlap.set(s.stateRank, totalOv); + if (totalOv > bestOverlap) { + bestOverlap = totalOv; + bestRank = s.stateRank; + } + } + } + } + + if (bestOverlap >= 0n) { + primaryRankByUpid.set(upid, bestRank); + } else if (soloExitedFallbackUpid === upid) { + rankToState.set(EXITED_RANK, 'EXITED'); + visitedRanks.add(EXITED_RANK); + primaryRankByUpid.set(upid, EXITED_RANK); + } + } + + // Order descending so CACHED / EXITED / UNKNOWN sit on the left and + // PERSISTENT (rank 0) sits on the far right. + const orderedRanks = [...visitedRanks].sort((a, b) => b - a); + const colIndexByRank = new Map<number, number>(); + for (let i = 0; i < orderedRanks.length; i++) { + const r = orderedRanks[i]; + if (r !== undefined) { + colIndexByRank.set(r, i); + } + } + + const seenEdgePairs = new Set<string>(); + const unionEdges: Array<{readonly source: string; readonly target: string}> = + []; + for (const c of windowConnections) { + if (c.clientUpid === c.serverUpid) continue; + const pk = `${c.clientUpid}>${c.serverUpid}`; + if (!seenEdgePairs.has(pk)) { + seenEdgePairs.add(pk); + unionEdges.push({ + source: String(c.clientUpid), + target: String(c.serverUpid), + }); + } + } + + const bary = computeBarycenterOrder( + [...subgraphUpids].map((u) => ({ + id: String(u), + layer: colIndexByRank.get(primaryRankByUpid.get(u) ?? UNKNOWN_RANK) ?? 0, + tieBreak: `${model.procsByUpid.get(u)?.name ?? ''}\0${String(u).padStart(10, '0')}`, + })), + unionEdges, + ); + const normYByUpid = new Map<number, number>(); + for (const [id, norm] of bary.normX) { + normYByUpid.set(Number(id), norm); + } + + const openSentinel = Time.fromRaw(model.traceEnd + 1n); + const rawEdgeEvents: time[] = [windowStart, windowEnd]; + for (const c of windowConnections) { + if (c.ts >= windowStart && c.ts <= windowEnd) { + rawEdgeEvents.push(c.ts); + } + if ( + c.endTs < openSentinel && + c.endTs >= windowStart && + c.endTs <= windowEnd + ) { + rawEdgeEvents.push(c.endTs); + } + } + const edgeEvents = dedupSortedTimes(rawEdgeEvents); + + const rawAnyEvents: time[] = [...edgeEvents]; + for (const u of subgraphUpids) { + const visSpans = + u === soloTargetUpid ? soloWindowSpans : connSpansByUpid.get(u); + if (visSpans === undefined || visSpans.length === 0) continue; + + for (const s of model.stateByUpid.get(u) ?? []) { + if (s.ts > windowEnd) break; + if ( + s.ts >= windowStart && + s.ts <= windowEnd && + findIntervalAt(visSpans, s.ts) !== undefined + ) { + rawAnyEvents.push(s.ts); + } + if ( + s.endTs < openSentinel && + s.endTs >= windowStart && + s.endTs <= windowEnd && + findIntervalAt(visSpans, s.endTs) !== undefined + ) { + rawAnyEvents.push(s.endTs); + } + } + for (const f of model.freezerByUpid.get(u) ?? []) { + if (f.ts > windowEnd) break; + if ( + f.ts >= windowStart && + f.ts <= windowEnd && + findIntervalAt(visSpans, f.ts) !== undefined + ) { + rawAnyEvents.push(f.ts); + } + if ( + f.endTs < openSentinel && + f.endTs >= windowStart && + f.endTs <= windowEnd && + findIntervalAt(visSpans, f.endTs) !== undefined + ) { + rawAnyEvents.push(f.endTs); + } + } + } + const anyEvents = dedupSortedTimes(rawAnyEvents); + + return { + windowStart, + windowEnd, + scopeMode, + explicitTargetUpids, + targetStates, + soloExitedFallbackUpid, + targetUpidSet, + subgraphUpids, + windowConnections, + orderedRanks, + rankToState, + normYByUpid, + edgeEvents, + anyEvents, + }; +} + +function nodeMatchesQuery(node: SnapshotNode, qLower: string): boolean { + return ( + node.name.toLowerCase().includes(qLower) || + String(node.pid).includes(qLower) || + node.state.toLowerCase().includes(qLower) || + (node.packageName?.toLowerCase().includes(qLower) ?? false) + ); +} + +export function snapshotAt( + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + ts: time, + filters: ProcessGraphFilters, +): GraphSnapshot { + const seedUpids = new Set<number>(); + for (const u of subgraph.explicitTargetUpids) { + const st = getStateAt(model, u, ts); + if (st.state !== 'EXITED' || subgraph.soloExitedFallbackUpid === u) { + seedUpids.add(u); + } + } + if (subgraph.targetStates.size > 0) { + for (const u of subgraph.targetUpidSet) { + if (seedUpids.has(u)) continue; + if (subgraph.targetStates.has(getStateAt(model, u, ts).state)) { + seedUpids.add(u); + } + } + } + + const candidateConns: ConnectionInterval[] = []; + for (const iv of subgraph.windowConnections) { + if (iv.ts > ts) break; + if (ts >= iv.endTs) continue; + if (!filters.showServices && iv.kind === 'service') continue; + if (!filters.showProviders && iv.kind === 'provider') continue; + if (!filters.showSelfLoops && iv.clientUpid === iv.serverUpid) continue; + candidateConns.push(iv); + } + + let scopedConns: ReadonlyArray<ConnectionInterval>; + if (subgraph.scopeMode === 'neighbors') { + scopedConns = candidateConns.filter( + (iv) => seedUpids.has(iv.clientUpid) || seedUpids.has(iv.serverUpid), + ); + } else if (subgraph.scopeMode === 'component') { + const undirectedAdj = new Map<number, number[]>(); + for (const iv of candidateConns) { + if (iv.clientUpid !== iv.serverUpid) { + pushAdj(undirectedAdj, iv.clientUpid, iv.serverUpid); + pushAdj(undirectedAdj, iv.serverUpid, iv.clientUpid); + } + } + const compSet = new Set<number>(seedUpids); + bfsReachable(seedUpids, undirectedAdj, compSet); + scopedConns = candidateConns.filter( + (iv) => compSet.has(iv.clientUpid) && compSet.has(iv.serverUpid), + ); + } else { + const forwardAdj = new Map<number, number[]>(); + const reverseAdj = new Map<number, number[]>(); + for (const iv of candidateConns) { + if (iv.clientUpid !== iv.serverUpid) { + pushAdj(forwardAdj, iv.clientUpid, iv.serverUpid); + pushAdj(reverseAdj, iv.serverUpid, iv.clientUpid); + } + } + const reachSet = new Set<number>(seedUpids); + bfsReachable(seedUpids, forwardAdj, reachSet); + bfsReachable(seedUpids, reverseAdj, reachSet); + scopedConns = candidateConns.filter( + (iv) => reachSet.has(iv.clientUpid) && reachSet.has(iv.serverUpid), + ); + } + + const edgeMap = new Map< + string, + { + key: string; + kind: EdgeKind; + client: number; + server: number; + count: number; + waivedCount: number; + compSet: Set<string>; + components: string[]; + detailSet: Set<string>; + details: string[]; + } + >(); + + for (const iv of scopedConns) { + const key = `${iv.kind}:${iv.clientUpid}>${iv.serverUpid}`; + let acc = edgeMap.get(key); + if (acc === undefined) { + acc = { + key, + kind: iv.kind, + client: iv.clientUpid, + server: iv.serverUpid, + count: 0, + waivedCount: 0, + compSet: new Set<string>(), + components: [], + detailSet: new Set<string>(), + details: [], + }; + edgeMap.set(key, acc); + } + acc.count += 1; + if ( + iv.kind === 'service' && + (iv.waivesPriority ?? hasPriorityWaivingFlag(iv.detail)) + ) { + acc.waivedCount += 1; + } + if (iv.label && !acc.compSet.has(iv.label)) { + acc.compSet.add(iv.label); + acc.components.push(iv.label); + } + if (iv.detail && !acc.detailSet.has(iv.detail)) { + acc.detailSet.add(iv.detail); + acc.details.push(iv.detail); + } + } + + const rawEdges: CollapsedEdge[] = [...edgeMap.values()].map((e) => ({ + key: e.key, + kind: e.kind, + client: e.client, + server: e.server, + count: e.count, + components: e.components, + details: e.details, + waivesPriority: + e.kind === 'service' && e.count > 0 && e.waivedCount === e.count, + })); + + const visibleAtTsUpids = new Set<number>(); + for (const e of rawEdges) { + visibleAtTsUpids.add(e.client); + visibleAtTsUpids.add(e.server); + } + if ( + subgraph.explicitTargetUpids.size === 1 && + subgraph.targetStates.size === 0 + ) { + for (const u of seedUpids) { + visibleAtTsUpids.add(u); + } + } + + const allNodesMap = new Map<number, SnapshotNode>(); + for (const upid of visibleAtTsUpids) { + const p = model.procsByUpid.get(upid); + const st = getStateAt(model, upid, ts); + const isFrozen = + findIntervalAt(model.freezerByUpid.get(upid), ts) !== undefined; + allNodesMap.set(upid, { + upid, + pid: p?.pid ?? 0, + name: p?.name ?? `upid ${upid}`, + uid: p?.uid, + packageName: p?.packageName, + state: st.state, + stateRank: st.stateRank, + reason: st.reason, + isFrozen, + isTarget: seedUpids.has(upid), + }); + } + + let candidateNodes = [...allNodesMap.values()]; + let finalEdges = rawEdges; + const qLower = filters.searchQuery.trim().toLowerCase(); + + if (qLower !== '') { + const directMatchedUpids = new Set<number>(); + for (const n of candidateNodes) { + if (nodeMatchesQuery(n, qLower)) { + directMatchedUpids.add(n.upid); + } + } + finalEdges = rawEdges.filter( + (e) => + directMatchedUpids.has(e.client) || + directMatchedUpids.has(e.server) || + e.components.some((c) => c.toLowerCase().includes(qLower)) || + e.details.some((d) => d.toLowerCase().includes(qLower)), + ); + const searchKeepUpids = new Set<number>(directMatchedUpids); + for (const e of finalEdges) { + searchKeepUpids.add(e.client); + searchKeepUpids.add(e.server); + } + candidateNodes = candidateNodes.filter((n) => searchKeepUpids.has(n.upid)); + } + + return { + ts, + allNodesMap, + rawEdges, + nodes: candidateNodes, + edges: finalEdges, + }; +} + +function snapshotSignature(snap: GraphSnapshot, mode: StepMode): string { + const edgeSig = snap.edges + .map((e) => `${e.key}:${e.count}:${e.waivesPriority === true ? 1 : 0}`) + .sort() + .join(';'); + if (mode === 'edge') { + return edgeSig; + } + const nodeSig = snap.nodes + .map((n) => `${n.upid}:${n.state}:${n.isFrozen ? 1 : 0}`) + .sort() + .join(';'); + return `${edgeSig}#${nodeSig}`; +} + +export function computeDistinctStepTimes( + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + mode: 'any' | 'edge', + filters: ProcessGraphFilters, +): ReadonlyArray<time> { + const evs = mode === 'edge' ? subgraph.edgeEvents : subgraph.anyEvents; + if (evs.length <= 1 || evs.length > 5_000) { + return evs; + } + const out: time[] = []; + let prevSig: string | undefined; + for (const t of evs) { + const sig = snapshotSignature( + snapshotAt(model, subgraph, t, filters), + mode, + ); + if (sig !== prevSig) { + out.push(t); + prevSig = sig; + } + } + return out; +} + +function nextTimeCandidate( + subgraph: ContextualSubgraph, + curTs: time, + dir: 1 | -1, + mode: StepMode, +): time { + if (typeof mode === 'number') { + const deltaNs = BigInt(mode) * 1_000_000n * BigInt(dir); + return Time.clamp( + Time.fromRaw(curTs + deltaNs), + subgraph.windowStart, + subgraph.windowEnd, + ); + } + const evs = mode === 'edge' ? subgraph.edgeEvents : subgraph.anyEvents; + const idx = upperBoundTime(evs, curTs); + if (dir > 0) { + return idx < evs.length ? (evs[idx] ?? curTs) : curTs; + } + if (idx >= 2) { + return evs[idx - 2] ?? curTs; + } + if (idx === 1 && evs[0] !== undefined && evs[0] < curTs) { + return evs[0]; + } + return curTs; +} + +export function stepTimestamp( + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + curTs: time, + dir: 1 | -1, + mode: StepMode, + filters: ProcessGraphFilters, +): time | undefined { + const isEventStep = mode === 'edge' || mode === 'any'; + const beforeSig = isEventStep + ? snapshotSignature(snapshotAt(model, subgraph, curTs, filters), mode) + : ''; + + let t = curTs; + for (let guard = 0; guard < 400; guard++) { + const nt = nextTimeCandidate(subgraph, t, dir, mode); + if (nt === t) return undefined; + t = nt; + if ( + !isEventStep || + snapshotSignature(snapshotAt(model, subgraph, t, filters), mode) !== + beforeSig + ) { + return t; + } + } + return t === curTs ? undefined : t; +} + +export async function loadProcessGraphModel( + trace: Trace, + signal?: CancellationSignal, +): Promise<ProcessGraphModel | typeof TASK_CANCELLED> { + await trace.engine.query(` + INCLUDE PERFETTO MODULE android.process_metadata; + INCLUDE PERFETTO MODULE android.process_state; + INCLUDE PERFETTO MODULE android.freezer; + INCLUDE PERFETTO MODULE android.process_bindings; + `); + if (signal?.isCancelled) return TASK_CANCELLED; + + const traceStart = trace.traceInfo.start; + const traceEnd = trace.traceInfo.end; + const openEndTs = Time.fromRaw(traceEnd + 1n); + + const procRes = await trace.engine.query(` + SELECT + p.upid, + p.pid, + coalesce(m.process_name, p.name, 'pid ' || p.pid) AS process_name, + m.uid, + m.package_name + FROM process AS p + LEFT JOIN android_process_metadata AS m USING (upid) + `); + if (signal?.isCancelled) return TASK_CANCELLED; + + const processes: ProcessInfo[] = []; + const procIt = procRes.iter({ + upid: NUM, + pid: NUM, + process_name: STR, + uid: NUM_NULL, + package_name: STR_NULL, + }); + for (; procIt.valid(); procIt.next()) { + processes.push({ + upid: procIt.upid, + pid: procIt.pid, + name: procIt.process_name, + uid: procIt.uid ?? undefined, + packageName: procIt.package_name ?? undefined, + }); + } + + const stateRes = await trace.engine.query(` + SELECT + upid, + ts, + dur, + state, + state_rank, + state_change_reason + FROM _android_process_state_intervals + WHERE state != 'EXITED' + AND dur != 0 + `); + if (signal?.isCancelled) return TASK_CANCELLED; + + const stateIntervals: StateInterval[] = []; + const stIt = stateRes.iter({ + upid: NUM, + ts: LONG, + dur: LONG, + state: STR, + state_rank: NUM, + state_change_reason: STR_NULL, + }); + for (; stIt.valid(); stIt.next()) { + const startTs = Time.fromRaw(stIt.ts); + const endTs = stIt.dur < 0n ? openEndTs : Time.fromRaw(stIt.ts + stIt.dur); + if (endTs <= traceStart || startTs > traceEnd) continue; + stateIntervals.push({ + upid: stIt.upid, + ts: startTs, + endTs, + state: stIt.state, + stateRank: stIt.state_rank, + reason: stIt.state_change_reason ?? undefined, + }); + } + + const freezerIntervals: FreezerInterval[] = []; + const freezerRes = await trace.engine.tryQuery(` + SELECT + upid, + ts, + dur + FROM _android_freezer_intervals + WHERE state = 'FROZEN' + AND dur != 0 + `); + if (signal?.isCancelled) return TASK_CANCELLED; + if (freezerRes.ok) { + const frzIt = freezerRes.value.iter({ + upid: NUM, + ts: LONG, + dur: LONG, + }); + for (; frzIt.valid(); frzIt.next()) { + const startTs = Time.fromRaw(frzIt.ts); + const endTs = + frzIt.dur < 0n ? openEndTs : Time.fromRaw(frzIt.ts + frzIt.dur); + if (endTs <= traceStart || startTs > traceEnd) continue; + freezerIntervals.push({ + upid: frzIt.upid, + ts: startTs, + endTs, + }); + } + } + + const connRes = await trace.engine.query(` + SELECT + 'service' AS kind, + ts, + dur, + client_upid, + server_upid, + component_name AS label, + bind_flags, + CASE + WHEN coalesce(intent_action, '') != '' AND coalesce(bind_flags, '') != '' + THEN 'action=' || intent_action || ' · flags=' || bind_flags + WHEN coalesce(intent_action, '') != '' THEN 'action=' || intent_action + WHEN coalesce(bind_flags, '') != '' THEN 'flags=' || bind_flags + ELSE NULL + END AS detail + FROM _android_service_connections + UNION ALL + SELECT + 'provider' AS kind, + ts, + dur, + client_upid, + server_upid, + authority AS label, + CAST(NULL AS STRING) AS bind_flags, + CASE + WHEN is_stable IS NULL THEN NULL + WHEN is_stable != 0 THEN 'stable' + ELSE 'unstable' + END AS detail + FROM _android_content_provider_connections + `); + if (signal?.isCancelled) return TASK_CANCELLED; + + const connections: ConnectionInterval[] = []; + const connIt = connRes.iter({ + kind: STR, + ts: LONG, + dur: LONG, + client_upid: NUM, + server_upid: NUM, + label: STR_NULL, + bind_flags: STR_NULL, + detail: STR_NULL, + }); + for (; connIt.valid(); connIt.next()) { + const startTs = Time.fromRaw(connIt.ts); + const endTs = + connIt.dur < 0n ? openEndTs : Time.fromRaw(connIt.ts + connIt.dur); + if (endTs <= traceStart || startTs > traceEnd) continue; + const edgeKind = connIt.kind === 'provider' ? 'provider' : 'service'; + connections.push({ + kind: edgeKind, + ts: startTs, + endTs, + clientUpid: connIt.client_upid, + serverUpid: connIt.server_upid, + label: connIt.label ?? undefined, + detail: connIt.detail ?? undefined, + waivesPriority: + edgeKind === 'service' && hasPriorityWaivingFlag(connIt.bind_flags), + }); + } + + return buildProcessGraphModel({ + traceStart, + traceEnd, + processes, + stateIntervals, + connections, + freezerIntervals, + }); +}
diff --git a/ui/src/plugins/com.android.ProcessGraph/model_unittest.ts b/ui/src/plugins/com.android.ProcessGraph/model_unittest.ts new file mode 100644 index 0000000..029b947 --- /dev/null +++ b/ui/src/plugins/com.android.ProcessGraph/model_unittest.ts
@@ -0,0 +1,596 @@ +// Copyright (C) 2026 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {Time} from '../../base/time'; +import {buildGraphChartOption} from '../../components/widgets/charts/graph_chart'; +import type {Trace} from '../../public/trace'; +import type {Track} from '../../public/track'; +import { + buildProcessGraphChartData, + SNOWFLAKE_SYMBOL_PATH, +} from './chart_option'; +import {TAG_BOUND_BY_TRACK} from '../com.android.ProcessState/aggregators'; +import {resolveProcessGraphContext} from './index'; +import { + buildContextualSubgraph, + buildProcessGraphModel, + computeDistinctStepTimes, + hasPriorityWaivingFlag, + type ProcessGraphFilters, + snapshotAt, + stepTimestamp, +} from './model'; +import {formatRelTime, ProcessGraphSession} from './process_graph_panel'; + +const DEFAULT_FILTERS: ProcessGraphFilters = { + showServices: true, + showProviders: true, + showSelfLoops: false, + searchQuery: '', +}; + +const TEST_THEME = { + textColor: '#111111', + borderColor: '#cccccc', + backgroundColor: '#ffffff', + accentColor: '#2563eb', + fontFamily: 'sans-serif', + chartColors: ['#2563eb'], +}; + +function makeFixtureModel() { + const t = (ns: bigint) => Time.fromRaw(ns); + return buildProcessGraphModel({ + traceStart: t(1_000n), + traceEnd: t(10_000n), + processes: [ + {upid: 1, pid: 100, name: 'system_server', uid: 1000}, + {upid: 2, pid: 200, name: 'com.example.alpha', uid: 10101}, + {upid: 3, pid: 300, name: 'com.example.beta', uid: 10102}, + {upid: 4, pid: 400, name: 'com.example.sibling', uid: 10103}, + {upid: 5, pid: 500, name: 'com.example.unrelated', uid: 10104}, + ], + stateIntervals: [ + { + upid: 1, + ts: t(1_000n), + endTs: t(10_001n), + state: 'PERSISTENT', + stateRank: 0, + }, + { + upid: 2, + ts: t(1_000n), + endTs: t(5_000n), + state: 'TOP', + stateRank: 2, + }, + { + upid: 2, + ts: t(5_000n), + endTs: t(10_001n), + state: 'CACHED_ACTIVITY', + stateRank: 16, + }, + { + upid: 3, + ts: t(1_000n), + endTs: t(10_001n), + state: 'SERVICE', + stateRank: 10, + }, + { + upid: 4, + ts: t(1_000n), + endTs: t(10_001n), + state: 'CACHED_EMPTY', + stateRank: 19, + }, + { + upid: 5, + ts: t(1_000n), + endTs: t(10_001n), + state: 'CACHED_EMPTY', + stateRank: 19, + }, + ], + freezerIntervals: [ + { + upid: 2, + ts: t(5_500n), + endTs: t(9_000n), + }, + ], + connections: [ + { + kind: 'service', + ts: t(2_000n), + endTs: t(6_000n), + clientUpid: 2, + serverUpid: 3, + label: 'com.example.beta/.WorkService', + }, + { + kind: 'service', + ts: t(2_000n), + endTs: t(8_000n), + clientUpid: 4, + serverUpid: 3, + label: 'com.example.beta/.WorkService', + }, + { + kind: 'provider', + ts: t(3_000n), + endTs: t(10_001n), + clientUpid: 1, + serverUpid: 2, + label: 'com.example.alpha.provider', + }, + ], + }); +} + +describe('ProcessGraph contextual model', () => { + test('orders visited state columns from CACHED on the left to PERSISTENT on the right', () => { + const model = makeFixtureModel(); + const sub = buildContextualSubgraph(model, { + windowStart: Time.fromRaw(2_000n), + windowEnd: Time.fromRaw(8_000n), + targetUpids: [2], + scopeMode: 'component', + filters: DEFAULT_FILTERS, + }); + + // Ranks: 19 (CACHED_EMPTY) > 16 (CACHED_ACTIVITY) > 10 (SERVICE) > 2 (TOP) > 0 (PERSISTENT). + expect(sub.orderedRanks).toEqual([19, 16, 10, 2, 0]); + expect([...sub.subgraphUpids].sort()).toEqual([1, 2, 3, 4]); + }); + + test('distinguishes Full component from Directed chains scope', () => { + const model = makeFixtureModel(); + // Graph: 1 -> 2 -> 3 <- 4 (upid 4 is a co-caller of 3, not on a directed chain through 2). + const fullComp = buildContextualSubgraph(model, { + windowStart: Time.fromRaw(2_000n), + windowEnd: Time.fromRaw(8_000n), + targetUpids: [2], + scopeMode: 'component', + filters: DEFAULT_FILTERS, + }); + const chainsOnly = buildContextualSubgraph(model, { + windowStart: Time.fromRaw(2_000n), + windowEnd: Time.fromRaw(8_000n), + targetUpids: [2], + scopeMode: 'chains', + filters: DEFAULT_FILTERS, + }); + + expect(fullComp.subgraphUpids.has(4)).toBe(true); + expect(chainsOnly.subgraphUpids.has(4)).toBe(false); + expect([...chainsOnly.subgraphUpids].sort()).toEqual([1, 2, 3]); + }); + + test('steps strictly within [windowStart, windowEnd] across edge, state, and freezer changes', () => { + const model = makeFixtureModel(); + const sub = buildContextualSubgraph(model, { + windowStart: Time.fromRaw(2_000n), + windowEnd: Time.fromRaw(7_000n), + targetUpids: [2], + scopeMode: 'chains', + filters: DEFAULT_FILTERS, + }); + + const t1 = stepTimestamp( + model, + sub, + Time.fromRaw(2_000n), + 1, + 'any', + DEFAULT_FILTERS, + ); + expect(t1).toBe(Time.fromRaw(3_000n)); // provider 1->2 acquired + + const t2 = stepTimestamp( + model, + sub, + Time.fromRaw(3_000n), + 1, + 'any', + DEFAULT_FILTERS, + ); + expect(t2).toBe(Time.fromRaw(5_000n)); // upid 2 TOP -> CACHED_ACTIVITY + + const t3 = stepTimestamp( + model, + sub, + Time.fromRaw(5_000n), + 1, + 'any', + DEFAULT_FILTERS, + ); + expect(t3).toBe(Time.fromRaw(5_500n)); // upid 2 enters FROZEN + + const t4 = stepTimestamp( + model, + sub, + Time.fromRaw(5_500n), + 1, + 'any', + DEFAULT_FILTERS, + ); + expect(t4).toBe(Time.fromRaw(6_000n)); // service 2->3 removed + + const tEnd = stepTimestamp( + model, + sub, + Time.fromRaw(6_000n), + 1, + 'any', + DEFAULT_FILTERS, + ); + expect(tEnd).toBeUndefined(); // freezer end @ 9000 is outside [2000, 7000] + }); + + test('formats relative durations cleanly across short and multi-hour traces', () => { + expect(formatRelTime(12_340_000_000n)).toBe('12.34s'); + expect(formatRelTime(65_000_000_000n)).toBe('1m 5s'); + expect(formatRelTime(43_448_000_000_000n)).toBe('12h 4m 8s'); + }); + + test('maps frozen snowflake symbol, target accent ring, and self-loops into horizontal GraphChartData', () => { + const t = (ns: bigint) => Time.fromRaw(ns); + const model = buildProcessGraphModel({ + traceStart: t(1_000n), + traceEnd: t(6_000n), + processes: [{upid: 1, pid: 100, name: 'com.example.self'}], + stateIntervals: [ + { + upid: 1, + ts: t(1_000n), + endTs: t(6_001n), + state: 'CACHED_EMPTY', + stateRank: 19, + }, + ], + freezerIntervals: [{upid: 1, ts: t(2_000n), endTs: t(5_000n)}], + connections: [ + { + kind: 'service', + ts: t(1_000n), + endTs: t(6_001n), + clientUpid: 1, + serverUpid: 1, + label: 'com.example.self/.LoopService', + }, + ], + }); + const filters = {...DEFAULT_FILTERS, showSelfLoops: true}; + const sub = buildContextualSubgraph(model, { + windowStart: t(1_000n), + windowEnd: t(5_000n), + targetUpids: [1], + scopeMode: 'component', + filters, + }); + const snap = snapshotAt(model, sub, t(3_000n), filters); + expect(snap.nodes[0]?.isFrozen).toBe(true); + expect(snap.nodes[0]?.isTarget).toBe(true); + + const data = buildProcessGraphChartData(model, sub, snap, undefined); + expect(data.layers?.map((l) => l.label)).toEqual(['CACHED_EMPTY (1)']); + + const opt = buildGraphChartOption(data, TEST_THEME, { + layout: 'layered', + layerOrientation: 'horizontal', + viewportSize: {width: 760, height: 280}, + }); + const series = ( + opt.series as Array<{data: Array<Record<string, unknown>>}> + )[0]; + const node = series?.data.find((d) => d.id === '1'); + const ring = series?.data.find((d) => d.id === 'accent-ring:1'); + const loopBadge = series?.data.find( + (d) => d.id === 'loop-badge:service:1>1', + ); + expect(node?.symbol).toBe(SNOWFLAKE_SYMBOL_PATH); + expect(ring).toBeDefined(); + expect(loopBadge?.edgeId).toBe('service:1>1'); + }); + + test('defaults to direct connections, omits disconnected/exited peers at ts, and highlights diffs', () => { + expect(new ProcessGraphSession().scopeMode).toBe('neighbors'); + + const t = (ns: bigint) => Time.fromRaw(ns); + // Graph: 1 -> 2 -> 3 -> 5, 1 -> 3 (neighbor-to-neighbor for target 2), + // 4 -> 3, plus transient peer 6 that bound to 2 and exited before t=5000. + const model = buildProcessGraphModel({ + traceStart: t(1_000n), + traceEnd: t(10_000n), + processes: [ + {upid: 1, pid: 100, name: 'system_server'}, + {upid: 2, pid: 200, name: 'com.example.alpha'}, + {upid: 3, pid: 300, name: 'com.example.beta'}, + {upid: 4, pid: 400, name: 'com.example.sibling'}, + {upid: 5, pid: 500, name: 'com.example.leaf'}, + {upid: 6, pid: 600, name: 'com.example.transient'}, + ], + stateIntervals: [ + { + upid: 1, + ts: t(1_000n), + endTs: t(10_001n), + state: 'PERSISTENT', + stateRank: 0, + }, + {upid: 2, ts: t(1_000n), endTs: t(5_000n), state: 'TOP', stateRank: 2}, + { + upid: 2, + ts: t(5_000n), + endTs: t(10_001n), + state: 'CACHED_EMPTY', + stateRank: 19, + }, + { + upid: 3, + ts: t(1_000n), + endTs: t(10_001n), + state: 'SERVICE', + stateRank: 10, + }, + { + upid: 4, + ts: t(1_000n), + endTs: t(10_001n), + state: 'CACHED_EMPTY', + stateRank: 19, + }, + { + upid: 5, + ts: t(1_000n), + endTs: t(10_001n), + state: 'SERVICE', + stateRank: 10, + }, + { + upid: 6, + ts: t(2_000n), + endTs: t(3_000n), + state: 'RECEIVER', + stateRank: 11, + }, + ], + connections: [ + { + kind: 'service', + ts: t(2_000n), + endTs: t(9_000n), + clientUpid: 1, + serverUpid: 2, + detail: 'flags=AUTO_CREATE,NOT_FOREGROUND', + }, + { + kind: 'provider', + ts: t(2_000n), + endTs: t(5_000n), + clientUpid: 1, + serverUpid: 2, + label: 'com.example.alpha.provider', + }, + { + kind: 'service', + ts: t(2_000n), + endTs: t(9_000n), + clientUpid: 1, + serverUpid: 3, + detail: 'flags=AUTO_CREATE', + }, + { + kind: 'service', + ts: t(2_000n), + endTs: t(5_000n), + clientUpid: 2, + serverUpid: 3, + detail: 'flags=AUTO_CREATE', + }, + { + kind: 'service', + ts: t(2_000n), + endTs: t(9_000n), + clientUpid: 3, + serverUpid: 5, + detail: 'flags=AUTO_CREATE,WAIVE_PRIORITY', + }, + { + kind: 'service', + ts: t(2_000n), + endTs: t(9_000n), + clientUpid: 4, + serverUpid: 3, + detail: 'flags=AUTO_CREATE', + }, + { + kind: 'service', + ts: t(2_000n), + endTs: t(3_000n), + clientUpid: 6, + serverUpid: 2, + detail: 'flags=AUTO_CREATE', + }, + ], + }); + + expect(hasPriorityWaivingFlag('AUTO_CREATE,WAIVE_PRIORITY')).toBe(true); + expect(hasPriorityWaivingFlag('flags=AUTO_CREATE,NOT_FOREGROUND')).toBe( + true, + ); + expect(hasPriorityWaivingFlag('AUTO_CREATE,IMPORTANT')).toBe(false); + + const neighborsSub = buildContextualSubgraph(model, { + windowStart: t(2_000n), + windowEnd: t(7_000n), + targetUpids: [2], + scopeMode: 'neighbors', + filters: DEFAULT_FILTERS, + }); + expect([...neighborsSub.subgraphUpids].sort()).toEqual([1, 2, 3, 6]); + expect(neighborsSub.orderedRanks).not.toContain(21); + + const chainsSub = buildContextualSubgraph(model, { + windowStart: t(2_000n), + windowEnd: t(7_000n), + targetUpids: [2], + scopeMode: 'chains', + filters: DEFAULT_FILTERS, + }); + expect([...chainsSub.subgraphUpids].sort()).toEqual([1, 2, 3, 5, 6]); + + const steps = computeDistinctStepTimes( + model, + neighborsSub, + 'any', + DEFAULT_FILTERS, + ); + expect(steps).toEqual([t(2_000n), t(3_000n), t(5_000n)]); + + const snapBefore = snapshotAt( + model, + neighborsSub, + t(2_000n), + DEFAULT_FILTERS, + ); + // Neighbor-to-neighbor edge 1 -> 3 is excluded in 'neighbors' scope. + expect(snapBefore.edges.map((e) => e.key).sort()).toEqual([ + 'provider:1>2', + 'service:1>2', + 'service:2>3', + 'service:6>2', + ]); + + const snapMid = snapshotAt(model, neighborsSub, t(3_000n), DEFAULT_FILTERS); + // Exited transient peer 6 has 0 active edges at t=3000 and is omitted. + expect(snapMid.nodes.map((n) => n.upid).sort()).toEqual([1, 2, 3]); + + const snapAfter = snapshotAt( + model, + neighborsSub, + t(5_000n), + DEFAULT_FILTERS, + ); + // Disconnected peer 3 (still alive in SERVICE) has 0 edges to target 2 at t=5000 and is omitted. + expect(snapAfter.nodes.map((n) => n.upid).sort()).toEqual([1, 2]); + // In 'chains' scope at t=5000, 2 -> 3 is broken so 3 -> 5 is also omitted. + const chainsAfter = snapshotAt( + model, + chainsSub, + t(5_000n), + DEFAULT_FILTERS, + ); + expect(chainsAfter.nodes.map((n) => n.upid).sort()).toEqual([1, 2]); + + const waivedEdge = snapAfter.edges.find((e) => e.key === 'service:1>2'); + expect(waivedEdge?.waivesPriority).toBe(true); + + const chartData = buildProcessGraphChartData( + model, + neighborsSub, + snapAfter, + undefined, + snapMid, + ); + const changedNode = chartData.nodes.find((n) => n.id === '2'); + const dimmedEdge = chartData.edges.find((e) => e.id === 'service:1>2'); + const removedEdge = chartData.edges.find((e) => e.id === 'provider:1>2'); + + expect(changedNode?.highlight).toBe('changed'); + expect(dimmedEdge?.opacity).toBe(0.3); + expect(dimmedEdge?.width).toBe(0.95); + expect(removedEdge?.highlight).toBe('removed'); + }); + + test('resolves service and provider peer child track selections without leaking collapsed-group peers', () => { + const t = (ns: bigint) => Time.fromRaw(ns); + const rootTrack: Track = { + uri: 'com.android.ProcessState#process.162.bound_by', + renderer: {} as Track['renderer'], + tags: {type: TAG_BOUND_BY_TRACK, upid: 162}, + }; + const peerChildTrack: Track = { + uri: 'com.android.ProcessState#process.162.bound_by.109', + renderer: {} as Track['renderer'], + tags: {type: TAG_BOUND_BY_TRACK, upid: 162}, + }; + const providerPeerTrack: Track = { + uri: 'com.android.ProcessState#process.162.provider_bound_by.109', + renderer: {} as Track['renderer'], + tags: {type: TAG_BOUND_BY_TRACK, upid: 162}, + }; + const tracksByUri = new Map<string, Track>([ + [rootTrack.uri, rootTrack], + [peerChildTrack.uri, peerChildTrack], + [providerPeerTrack.uri, providerPeerTrack], + ]); + const fakeTrace = { + traceInfo: {start: t(1_000n), end: t(9_000n)}, + tracks: {getTrack: (uri: string) => tracksByUri.get(uri)}, + } as unknown as Trace; + const edgeMap = new Map<number, string>([ + [7, 'service:109>162'], + [8, 'provider:109>162'], + ]); + + // Area drag over collapsed Bound by (includes root + peer child) keeps only upid 162. + const collapsedArea = resolveProcessGraphContext( + fakeTrace, + { + kind: 'area', + start: t(2_000n), + end: t(5_000n), + trackUris: [rootTrack.uri, peerChildTrack.uri], + tracks: [rootTrack, peerChildTrack], + }, + edgeMap, + ); + expect(collapsedArea?.targetUpids).toEqual([162]); + + // Area drag directly on service or provider peer child track includes both 109 and 162. + for (const track of [peerChildTrack, providerPeerTrack]) { + const peerArea = resolveProcessGraphContext( + fakeTrace, + { + kind: 'area', + start: t(2_000n), + end: t(5_000n), + trackUris: [track.uri], + tracks: [track], + }, + edgeMap, + ); + expect(peerArea?.targetUpids).toEqual([109, 162]); + } + + // Slice click on provider peer child track preselects the provider edge. + const sliceClick = resolveProcessGraphContext( + fakeTrace, + { + kind: 'track_event', + trackUri: providerPeerTrack.uri, + eventId: 8, + ts: t(2_000n), + dur: 1_000n, + }, + edgeMap, + ); + expect(sliceClick?.targetUpids).toEqual([162]); + expect(sliceClick?.preselectedEdgeKey).toBe('provider:109>162'); + }); +});
diff --git a/ui/src/plugins/com.android.ProcessGraph/process_graph_panel.ts b/ui/src/plugins/com.android.ProcessGraph/process_graph_panel.ts new file mode 100644 index 0000000..ca6a6ed --- /dev/null +++ b/ui/src/plugins/com.android.ProcessGraph/process_graph_panel.ts
@@ -0,0 +1,1077 @@ +// Copyright (C) 2026 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import m from 'mithril'; +import {AsyncMemo} from '../../base/async_memo'; +import {GateDetector} from '../../base/mithril_utils'; +import {Icons} from '../../base/semantic_icons'; +import {Duration, type duration, Time, type time} from '../../base/time'; +import {GraphChart} from '../../components/widgets/charts/graph_chart'; +import type {Trace} from '../../public/trace'; +import {Button, ButtonVariant} from '../../widgets/button'; +import {Checkbox} from '../../widgets/checkbox'; +import {EmptyState} from '../../widgets/empty_state'; +import {Section} from '../../widgets/section'; +import {Select} from '../../widgets/select'; +import {Spinner} from '../../widgets/spinner'; +import {SplitPanel} from '../../widgets/split_panel'; +import {TextInput} from '../../widgets/text_input'; +import {Tree, TreeNode} from '../../widgets/tree'; +import { + buildProcessGraphChartData, + buildProcessInfoFallback, + type SelectedItem, +} from './chart_option'; +import { + buildContextualSubgraph, + type CollapsedEdge, + computeDistinctStepTimes, + type ContextualSubgraph, + type GraphSnapshot, + loadProcessGraphModel, + type ProcessGraphFilters, + type ProcessGraphModel, + type ScopeMode, + snapshotAt, + type StepMode, + stepTimestamp, + upperBoundTime, +} from './model'; + +export interface ProcessGraphContext { + readonly selectionKey: string; + readonly windowStart: time; + readonly windowEnd: time; + readonly targetUpids: ReadonlyArray<number>; + readonly targetStates: ReadonlyArray<string>; + readonly preselectedEdgeKey?: string; +} + +export class ProcessGraphSession { + readonly modelMemo = new AsyncMemo<ProcessGraphModel>(); + activeSelectionKey?: string; + curTs?: time; + diffFromTs?: time; + scopeMode: ScopeMode = 'neighbors'; + stepMode: StepMode = 'any'; + playSpeedMs = 350; + inspectorWidthPx = 360; + filters: ProcessGraphFilters = { + showServices: true, + showProviders: true, + showSelfLoops: false, + searchQuery: '', + }; + selected?: SelectedItem; + + dispose(): void { + this.modelMemo.dispose(); + } +} + +export interface ProcessGraphPanelAttrs { + readonly trace: Trace; + readonly session: ProcessGraphSession; + readonly context: ProcessGraphContext; +} + +export function formatRelTime(delta: duration): string { + if (delta <= 0n) return '0s'; + if (delta < 60_000_000_000n) return Duration.humanise(delta); + return Duration.format((delta / 1_000_000_000n) * 1_000_000_000n); +} + +function jumpToTimeline(trace: Trace, ts: time, upid?: number): void { + const trackUri = + upid !== undefined + ? trace.currentWorkspace.flatTracks.find( + (t) => + t.uri !== undefined && + trace.tracks.getTrack(t.uri)?.tags?.upid === upid, + )?.uri + : undefined; + if (trace.getCurrentRoute().page !== '/viewer') { + trace.navigate('#!/viewer'); + } + trace.scrollTo({ + time: {start: ts, behavior: 'pan'}, + track: + trackUri !== undefined ? {uri: trackUri, expandGroup: true} : undefined, + }); +} + +function renderSection(title: string, body: m.Children): m.Children { + return m( + Section, + {title: m('h3.pf-process-graph__section-title', title)}, + body, + ); +} + +export class ProcessGraphPanel implements m.ClassComponent<ProcessGraphPanelAttrs> { + private isPlaying = false; + private isVisible = false; + private playTimer?: ReturnType<typeof setTimeout>; + private resetGeneration = 0; + private cachedSubgraphKey?: string; + private cachedSubgraphModel?: ProcessGraphModel; + private cachedSubgraph?: ContextualSubgraph; + private cachedStepsKey?: string; + private cachedStepsSubgraph?: ContextualSubgraph; + private cachedSteps?: ReadonlyArray<time>; + + onremove({attrs}: m.CVnodeDOM<ProcessGraphPanelAttrs>) { + this.stopPlay(); + this.cachedSubgraph = undefined; + this.cachedSubgraphModel = undefined; + this.cachedSteps = undefined; + this.cachedStepsSubgraph = undefined; + if (this.isVisible) { + attrs.trace.timeline.hoverCursorTimestamp = undefined; + } + this.isVisible = false; + } + + private stopPlay(): void { + this.isPlaying = false; + if (this.playTimer !== undefined) { + clearTimeout(this.playTimer); + this.playTimer = undefined; + } + } + + private advanceTo( + trace: Trace, + session: ProcessGraphSession, + nextTs: time, + ): void { + session.curTs = nextTs; + if (this.isVisible) { + trace.timeline.hoverCursorTimestamp = nextTs; + } + } + + private getSubgraph( + model: ProcessGraphModel, + context: ProcessGraphContext, + session: ProcessGraphSession, + ): ContextualSubgraph { + const {filters} = session; + const key = [ + context.selectionKey, + session.scopeMode, + filters.showServices ? 1 : 0, + filters.showProviders ? 1 : 0, + filters.showSelfLoops ? 1 : 0, + ].join('|'); + if ( + this.cachedSubgraph !== undefined && + this.cachedSubgraphModel === model && + this.cachedSubgraphKey === key + ) { + return this.cachedSubgraph; + } + const sub = buildContextualSubgraph(model, { + windowStart: context.windowStart, + windowEnd: context.windowEnd, + targetUpids: context.targetUpids, + targetStates: context.targetStates, + scopeMode: session.scopeMode, + filters, + }); + this.cachedSubgraphModel = model; + this.cachedSubgraphKey = key; + this.cachedSubgraph = sub; + return sub; + } + + private getDistinctSteps( + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + session: ProcessGraphSession, + ): ReadonlyArray<time> | undefined { + const {stepMode, filters} = session; + if (stepMode !== 'any' && stepMode !== 'edge') { + return undefined; + } + const key = [ + stepMode, + filters.showServices ? 1 : 0, + filters.showProviders ? 1 : 0, + filters.showSelfLoops ? 1 : 0, + filters.searchQuery.trim().toLowerCase(), + ].join('|'); + if ( + this.cachedSteps !== undefined && + this.cachedStepsSubgraph === subgraph && + this.cachedStepsKey === key + ) { + return this.cachedSteps; + } + const steps = computeDistinctStepTimes(model, subgraph, stepMode, filters); + this.cachedStepsSubgraph = subgraph; + this.cachedStepsKey = key; + this.cachedSteps = steps; + return steps; + } + + private step( + trace: Trace, + session: ProcessGraphSession, + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + dir: 1 | -1, + ): boolean { + const cur = session.curTs ?? subgraph.windowStart; + const nextTs = stepTimestamp( + model, + subgraph, + cur, + dir, + session.stepMode, + session.filters, + ); + if (nextTs === undefined) return false; + session.diffFromTs = cur; + this.advanceTo(trace, session, nextTs); + return true; + } + + private togglePlay( + trace: Trace, + session: ProcessGraphSession, + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + ): void { + if (this.isPlaying) { + this.stopPlay(); + return; + } + if (subgraph.windowEnd <= subgraph.windowStart) { + return; + } + const distinctSteps = this.getDistinctSteps(model, subgraph, session); + const lastTs = + distinctSteps !== undefined && distinctSteps.length > 0 + ? (distinctSteps[distinctSteps.length - 1] ?? subgraph.windowEnd) + : subgraph.windowEnd; + const cur = session.curTs ?? subgraph.windowStart; + if (cur >= lastTs) { + session.diffFromTs = undefined; + this.advanceTo(trace, session, subgraph.windowStart); + } + this.isPlaying = true; + const tick = () => { + if (!this.isPlaying) return; + const liveSub = this.cachedSubgraph ?? subgraph; + if (!this.step(trace, session, model, liveSub, 1)) { + this.stopPlay(); + m.redraw(); + return; + } + m.redraw(); + this.playTimer = setTimeout(tick, session.playSpeedMs); + }; + this.playTimer = setTimeout(tick, session.playSpeedMs); + } + + private handleKeyDown( + trace: Trace, + session: ProcessGraphSession, + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + ev: KeyboardEvent, + ): void { + if (ev.ctrlKey || ev.altKey || ev.metaKey) return; + const target = ev.target as HTMLElement | undefined; + const tag = target?.tagName ?? ''; + if ( + tag === 'INPUT' || + tag === 'SELECT' || + tag === 'BUTTON' || + tag === 'TEXTAREA' || + target?.isContentEditable === true + ) { + return; + } + if (ev.key === 'ArrowRight') { + ev.preventDefault(); + this.stopPlay(); + this.step(trace, session, model, subgraph, 1); + } else if (ev.key === 'ArrowLeft') { + ev.preventDefault(); + this.stopPlay(); + this.step(trace, session, model, subgraph, -1); + } else if (ev.key === 'Escape' && session.selected !== undefined) { + session.selected = undefined; + } + } + + view({attrs}: m.CVnode<ProcessGraphPanelAttrs>) { + const {trace, session, context} = attrs; + + const wrapGate = (child: m.Children) => + m( + GateDetector, + { + onVisibilityChanged: (visible: boolean) => { + this.isVisible = visible; + if (visible) { + if (session.curTs !== undefined) { + trace.timeline.hoverCursorTimestamp = session.curTs; + } + m.redraw(); + } else { + this.stopPlay(); + trace.timeline.hoverCursorTimestamp = undefined; + } + }, + }, + child, + ); + + const memoRes = session.modelMemo.use({ + key: {traceStart: trace.traceInfo.start}, + compute: (signal) => loadProcessGraphModel(trace, signal), + }); + + if (memoRes.isPending && memoRes.data === undefined) { + return wrapGate( + m( + '.pf-process-graph', + m( + '.pf-process-graph__loading', + m(Spinner), + 'Loading process graph...', + ), + ), + ); + } + + const model = memoRes.data; + if (model === undefined || model.connections.length === 0) { + return wrapGate( + m( + '.pf-process-graph', + m(EmptyState, { + title: + 'No Android service or content provider connections in trace', + }), + ), + ); + } + + const subgraph = this.getSubgraph(model, context, session); + if (session.activeSelectionKey !== context.selectionKey) { + this.stopPlay(); + session.activeSelectionKey = context.selectionKey; + let initTs = subgraph.windowStart; + if ( + subgraph.windowEnd > subgraph.windowStart && + snapshotAt(model, subgraph, initTs, session.filters).nodes.length === 0 + ) { + const candidates = + this.getDistinctSteps(model, subgraph, session) ?? subgraph.anyEvents; + for (const t of candidates) { + if ( + snapshotAt(model, subgraph, t, session.filters).nodes.length > 0 + ) { + initTs = t; + break; + } + } + } + session.curTs = initTs; + session.diffFromTs = undefined; + this.resetGeneration += 1; + if (context.preselectedEdgeKey !== undefined) { + session.selected = {type: 'edge', key: context.preselectedEdgeKey}; + } else if ( + context.targetUpids.length === 1 && + context.targetUpids[0] !== undefined + ) { + session.selected = {type: 'node', upid: context.targetUpids[0]}; + } else { + session.selected = undefined; + } + if (this.isVisible) { + trace.timeline.hoverCursorTimestamp = initTs; + } + } + + const curTs = Time.clamp( + session.curTs ?? subgraph.windowStart, + subgraph.windowStart, + subgraph.windowEnd, + ); + session.curTs = curTs; + + const snap = snapshotAt(model, subgraph, curTs, session.filters); + const prevTs = + session.diffFromTs !== undefined + ? Time.clamp( + session.diffFromTs, + subgraph.windowStart, + subgraph.windowEnd, + ) + : undefined; + const prevSnap = + prevTs !== undefined && prevTs !== curTs + ? snapshotAt(model, subgraph, prevTs, session.filters) + : undefined; + const distinctSteps = this.getDistinctSteps(model, subgraph, session); + const activeCols = new Set(snap.nodes.map((n) => n.stateRank)).size; + const frozenCount = snap.nodes.filter((n) => n.isFrozen).length; + + const isInstant = subgraph.windowEnd <= subgraph.windowStart; + const firstStepTs = + distinctSteps !== undefined && distinctSteps.length > 0 + ? (distinctSteps[0] ?? subgraph.windowStart) + : subgraph.windowStart; + const lastStepTs = + distinctSteps !== undefined && distinctSteps.length > 0 + ? (distinctSteps[distinctSteps.length - 1] ?? subgraph.windowEnd) + : subgraph.windowEnd; + const canStepPrev = !isInstant && curTs > firstStepTs; + const canStepNext = !isInstant && curTs < lastStepTs; + + const winDurMs = Math.max( + 0, + Number(subgraph.windowEnd - subgraph.windowStart) / 1e6, + ); + const scrubberMax = Math.max(1, winDurMs); + const scrubberVal = isInstant + ? 0 + : Math.max( + 0, + Math.min(winDurMs, Number(curTs - subgraph.windowStart) / 1e6), + ); + + const curFromTraceStart = formatRelTime(curTs - model.traceStart); + const winStartStr = formatRelTime(subgraph.windowStart - model.traceStart); + const winEndStr = formatRelTime(subgraph.windowEnd - model.traceStart); + const stepReadout = + !isInstant && distinctSteps !== undefined && distinctSteps.length > 0 + ? ` · step ${Math.min(distinctSteps.length, Math.max(1, upperBoundTime(distinctSteps, curTs)))}/${distinctSteps.length}` + : ''; + const readoutText = isInstant + ? `+${curFromTraceStart} (instant)` + : `+${curFromTraceStart}${stepReadout} ([+${winStartStr}, +${winEndStr}])`; + + const chartData = buildProcessGraphChartData( + model, + subgraph, + snap, + session.selected, + prevSnap, + ); + + const filterCheckbox = ( + label: string, + key: 'showServices' | 'showProviders' | 'showSelfLoops', + ) => + m(Checkbox, { + label, + checked: session.filters[key], + onchange: () => { + session.filters = { + ...session.filters, + [key]: !session.filters[key], + }; + }, + }); + + return wrapGate( + m( + '.pf-process-graph', + { + tabindex: -1, + onkeydown: (ev: KeyboardEvent) => + this.handleKeyDown(trace, session, model, subgraph, ev), + }, + m( + 'header.pf-process-graph__toolbar', + m( + '.pf-process-graph__toolbar-row', + m(Button, { + 'icon': 'skip_previous', + 'title': 'Previous step in selection', + 'aria-label': 'Previous step in selection', + 'variant': ButtonVariant.Outlined, + 'compact': true, + 'disabled': !canStepPrev, + 'onclick': () => { + this.stopPlay(); + this.step(trace, session, model, subgraph, -1); + }, + }), + m(Button, { + 'label': this.isPlaying ? 'Pause' : 'Play', + 'icon': this.isPlaying ? 'pause' : Icons.Play, + 'variant': ButtonVariant.Filled, + 'compact': true, + 'active': this.isPlaying, + 'disabled': isInstant, + 'aria-label': this.isPlaying + ? 'Pause selection playback' + : 'Play selection window', + 'onclick': () => this.togglePlay(trace, session, model, subgraph), + }), + m(Button, { + 'icon': 'skip_next', + 'title': 'Next step in selection', + 'aria-label': 'Next step in selection', + 'variant': ButtonVariant.Outlined, + 'compact': true, + 'disabled': !canStepNext, + 'onclick': () => { + this.stopPlay(); + this.step(trace, session, model, subgraph, 1); + }, + }), + m('input[type=range].pf-process-graph__scrubber', { + 'min': 0, + 'max': scrubberMax, + 'step': 'any', + 'value': scrubberVal, + 'disabled': isInstant, + 'aria-label': 'Selection time scrubber', + 'oninput': (e: InputEvent) => { + this.stopPlay(); + session.diffFromTs = undefined; + const target = e.target as HTMLInputElement; + const relNs = BigInt(Math.round(Number(target.value) * 1e6)); + const nextTs = Time.clamp( + Time.fromRaw(subgraph.windowStart + relNs), + subgraph.windowStart, + subgraph.windowEnd, + ); + this.advanceTo(trace, session, nextTs); + }, + }), + m( + 'span.pf-process-graph__time-readout', + {'aria-live': 'polite'}, + readoutText, + ), + m( + 'label.pf-process-graph__control-label', + 'Scope:', + m( + Select, + { + 'value': session.scopeMode, + 'aria-label': 'Subgraph scope', + 'onchange': (e: Event) => { + const val = (e.target as HTMLSelectElement).value; + if ( + val === 'chains' || + val === 'neighbors' || + val === 'component' + ) { + session.scopeMode = val; + session.diffFromTs = undefined; + this.resetGeneration += 1; + } + }, + }, + m('option', {value: 'neighbors'}, 'Direct connections'), + m('option', {value: 'chains'}, 'Directed chains'), + m('option', {value: 'component'}, 'Full component'), + ), + ), + m( + 'label.pf-process-graph__control-label', + 'Step:', + m( + Select, + { + 'value': String(session.stepMode), + 'aria-label': 'Step mode', + 'onchange': (e: Event) => { + const val = (e.target as HTMLSelectElement).value; + if (val === 'edge' || val === 'any') { + session.stepMode = val; + } else { + const parsed = Number(val); + if ( + parsed === 100 || + parsed === 1000 || + parsed === 5000 + ) { + session.stepMode = parsed; + } + } + }, + }, + m('option', {value: 'any'}, 'Edges + states + freezer'), + m('option', {value: 'edge'}, 'Edges only'), + m('option', {value: '100'}, '100 ms'), + m('option', {value: '1000'}, '1 s'), + m('option', {value: '5000'}, '5 s'), + ), + ), + m( + 'label.pf-process-graph__control-label', + 'Speed:', + m( + Select, + { + 'value': String(session.playSpeedMs), + 'aria-label': 'Playback speed', + 'onchange': (e: Event) => { + session.playSpeedMs = Number( + (e.target as HTMLSelectElement).value, + ); + }, + }, + m('option', {value: '1000'}, '1×/s'), + m('option', {value: '350'}, '3×/s'), + m('option', {value: '100'}, '10×/s'), + ), + ), + m(Button, { + 'icon': 'fit_screen', + 'title': 'Reset zoom and pan', + 'aria-label': 'Reset zoom and pan', + 'variant': ButtonVariant.Outlined, + 'compact': true, + 'onclick': () => { + this.resetGeneration += 1; + }, + }), + ), + m( + '.pf-process-graph__toolbar-row.pf-process-graph__toolbar-row--meta', + m( + '.pf-process-graph__filters', + m(TextInput, { + 'className': 'pf-process-graph__search', + 'leftIcon': Icons.Search, + 'placeholder': 'Filter...', + 'value': session.filters.searchQuery, + 'aria-label': 'Filter processes or components', + 'onInput': (val: string) => { + session.filters = {...session.filters, searchQuery: val}; + }, + }), + filterCheckbox('Services', 'showServices'), + filterCheckbox('Providers', 'showProviders'), + filterCheckbox('Self-loops', 'showSelfLoops'), + ), + m( + 'span.pf-process-graph__meta', + `${snap.nodes.length} procs (${frozenCount} ❄ frozen · ${activeCols}/${chartData.layers?.length ?? subgraph.orderedRanks.length} cols) · ${snap.edges.length} edges · client → server · — service (dim = waived) · -- provider`, + ), + ), + ), + m( + '.pf-process-graph__body', + subgraph.subgraphUpids.size === 0 + ? m(EmptyState, { + title: 'No processes matched the selected state in this window', + }) + : m(SplitPanel, { + direction: 'horizontal', + controlledPanel: 'second', + split: {pixels: session.inspectorWidthPx}, + minSize: 220, + onResize: (px) => { + session.inspectorWidthPx = Math.round(px); + }, + firstPanel: + snap.nodes.length === 0 + ? m(EmptyState, { + title: + subgraph.windowConnections.length === 0 + ? 'No active bindings for the selected tracks in this window' + : 'No active bindings at this timestamp', + }) + : m(GraphChart, { + data: chartData, + layout: 'layered', + layerOrientation: 'horizontal', + fillParent: true, + resetToken: this.resetGeneration, + ariaLabel: + 'Contextual process dependency graph ordered horizontally from cached processes on the left to persistent processes on the right. Frozen processes appear as snowflakes. Use W, A, S, D to pan and Shift+W or Shift+S to zoom.', + onNodeClick: (nodeId) => { + const upid = Number(nodeId); + if (Number.isFinite(upid)) { + session.selected = {type: 'node', upid}; + } + }, + onEdgeClick: (edgeId) => { + session.selected = {type: 'edge', key: edgeId}; + }, + onCanvasEmptyClick: () => { + session.selected = undefined; + }, + }), + secondPanel: [ + this.renderInspector( + trace, + session, + model, + subgraph, + snap, + prevSnap, + ), + ], + }), + ), + ), + ); + } + + private renderInspectorShell( + trace: Trace, + key: string, + title: string, + ts: time, + upid: number | undefined, + ...body: m.Children[] + ): m.Children { + return m( + 'aside.pf-process-graph__inspector', + { + key, + 'role': 'region', + 'aria-labelledby': 'pf-process-graph-inspector-title', + 'tabindex': 0, + }, + m( + '.pf-process-graph__inspector-header', + m( + 'h2#pf-process-graph-inspector-title.pf-process-graph__inspector-title', + title, + ), + m(Button, { + 'label': 'Show on timeline', + 'aria-label': 'Show on timeline', + 'rightIcon': Icons.GoTo, + 'variant': ButtonVariant.Outlined, + 'compact': true, + 'onclick': () => jumpToTimeline(trace, ts, upid), + }), + ), + ...body, + ); + } + + private renderInspector( + trace: Trace, + session: ProcessGraphSession, + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + snap: GraphSnapshot, + prevSnap?: GraphSnapshot, + ): m.Children { + const sel = session.selected; + if (sel?.type === 'node') { + return this.renderNodeInspector( + trace, + session, + model, + subgraph, + snap, + sel.upid, + ); + } + if (sel?.type === 'edge') { + return this.renderEdgeInspector( + trace, + session, + model, + subgraph, + snap, + prevSnap, + sel.key, + ); + } + return this.renderSummaryInspector(trace, session, model, subgraph, snap); + } + + private renderNodeInspector( + trace: Trace, + session: ProcessGraphSession, + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + snap: GraphSnapshot, + upid: number, + ): m.Children { + const node = snap.allNodesMap.get(upid); + if (node === undefined) { + return this.renderSummaryInspector(trace, session, model, subgraph, snap); + } + const proc = buildProcessInfoFallback(model, upid); + const selfEdges = snap.rawEdges.filter( + (e) => e.client === upid && e.server === upid, + ); + const byPeerRank = + (peerOf: (e: CollapsedEdge) => number) => + (a: CollapsedEdge, b: CollapsedEdge) => + (snap.allNodesMap.get(peerOf(a))?.stateRank ?? 99) - + (snap.allNodesMap.get(peerOf(b))?.stateRank ?? 99) || + b.count - a.count; + const inEdges = snap.rawEdges + .filter((e) => e.server === upid && e.client !== upid) + .sort(byPeerRank((e) => e.client)); + const outEdges = snap.rawEdges + .filter((e) => e.client === upid && e.server !== upid) + .sort(byPeerRank((e) => e.server)); + + const renderPeerList = ( + edges: ReadonlyArray<CollapsedEdge>, + peerOf: (e: CollapsedEdge) => number, + ): m.Children => + edges.length === 0 + ? m('span.pf-process-graph__muted', 'None') + : m( + 'ul.pf-process-graph__list', + edges.map((e) => { + const peerUpid = peerOf(e); + const peerProc = buildProcessInfoFallback(model, peerUpid); + const peerNode = snap.allNodesMap.get(peerUpid); + const peerState = peerNode?.state ?? '—'; + const peerFrozen = peerNode?.isFrozen === true ? ' · FROZEN' : ''; + const peerName = peerProc.name || `pid ${peerProc.pid}`; + return m( + 'li.pf-process-graph__peer-row', + {key: e.key}, + m(Button, { + className: 'pf-process-graph__peer-main', + label: `${peerName} (${peerState}${peerFrozen})`, + title: `Inspect process ${peerProc.name}`, + variant: ButtonVariant.Outlined, + compact: true, + shrink: true, + onclick: () => { + session.selected = {type: 'node', upid: peerUpid}; + }, + }), + m(Button, { + 'label': `${e.kind} ×${e.count} →`, + 'aria-label': `${e.kind} ×${e.count} → with ${peerName}`, + 'title': `Inspect ${e.kind} edge (${e.count} connections)`, + 'variant': ButtonVariant.Outlined, + 'compact': true, + 'onclick': () => { + session.selected = {type: 'edge', key: e.key}; + }, + }), + ); + }), + ); + + return this.renderInspectorShell( + trace, + `node:${upid}`, + 'Process inspector', + snap.ts, + upid, + m( + Tree, + {bordered: true}, + m(TreeNode, {left: 'Process', right: proc.name}), + m(TreeNode, { + left: 'PID / UID', + right: `pid ${proc.pid} · uid ${proc.uid ?? '—'}`, + }), + proc.packageName !== undefined && + m(TreeNode, {left: 'Package', right: proc.packageName}), + m(TreeNode, {left: 'State', right: node.state}), + m(TreeNode, { + left: 'Freezer', + right: node.isFrozen ? 'FROZEN' : 'UNFROZEN', + }), + node.isTarget && + m(TreeNode, {left: 'Selection', right: 'Selected on timeline'}), + node.reason !== undefined && + node.reason !== '' && + m(TreeNode, {left: 'Reason', right: node.reason}), + ), + selfEdges.length > 0 && + renderSection( + `Self-loops (${selfEdges.length})`, + m( + 'ul.pf-process-graph__list', + selfEdges.map((e) => + m( + 'li', + {key: e.key}, + m(Button, { + className: 'pf-process-graph__full-btn', + label: `↻ self (${e.kind} ×${e.count}) — ${e.components[0] ?? 'inspect components'}`, + variant: ButtonVariant.Outlined, + compact: true, + shrink: true, + onclick: () => { + session.selected = {type: 'edge', key: e.key}; + }, + }), + ), + ), + ), + ), + renderSection( + `Incoming — bound by (${inEdges.length})`, + renderPeerList(inEdges, (e) => e.client), + ), + renderSection( + `Outgoing — binds to (${outEdges.length})`, + renderPeerList(outEdges, (e) => e.server), + ), + ); + } + + private renderEdgeInspector( + trace: Trace, + session: ProcessGraphSession, + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + snap: GraphSnapshot, + prevSnap: GraphSnapshot | undefined, + edgeKey: string, + ): m.Children { + const activeEdge = snap.rawEdges.find((e) => e.key === edgeKey); + const removedEdge = + activeEdge === undefined + ? prevSnap?.rawEdges.find((e) => e.key === edgeKey) + : undefined; + const edge = activeEdge ?? removedEdge; + if (edge === undefined) { + return this.renderSummaryInspector(trace, session, model, subgraph, snap); + } + + const clientProc = buildProcessInfoFallback(model, edge.client); + const serverProc = buildProcessInfoFallback(model, edge.server); + const renderMonoList = (items: ReadonlyArray<string>): m.Children => + items.length === 0 + ? m('span.pf-process-graph__muted', 'None recorded') + : m( + 'ul.pf-process-graph__list', + items.map((item) => + m('li.pf-process-graph__mono-item', {key: item}, item), + ), + ); + + return this.renderInspectorShell( + trace, + `edge:${edgeKey}`, + 'Edge inspector', + snap.ts, + edge.client, + renderSection( + 'Client → Server', + m( + '.pf-process-graph__list', + m(Button, { + className: 'pf-process-graph__full-btn', + label: `Client: ${clientProc.name} (pid ${clientProc.pid})`, + variant: ButtonVariant.Outlined, + compact: true, + shrink: true, + onclick: () => { + session.selected = {type: 'node', upid: edge.client}; + }, + }), + m(Button, { + className: 'pf-process-graph__full-btn', + label: `Server: ${serverProc.name} (pid ${serverProc.pid})`, + variant: ButtonVariant.Outlined, + compact: true, + shrink: true, + onclick: () => { + session.selected = {type: 'node', upid: edge.server}; + }, + }), + ), + ), + m( + Tree, + {bordered: true}, + removedEdge !== undefined && + m(TreeNode, {left: 'Status', right: 'Removed at this step'}), + m(TreeNode, {left: 'Kind', right: edge.kind}), + m(TreeNode, {left: 'Connections', right: String(edge.count)}), + edge.kind === 'service' && + m(TreeNode, { + left: 'Priority', + right: + edge.waivesPriority === true + ? 'Waived (NOT_FOREGROUND / WAIVE_PRIORITY)' + : 'Propagates client priority', + }), + ), + renderSection( + `Components / authorities (${edge.components.length})`, + renderMonoList(edge.components), + ), + edge.details.length > 0 && + renderSection('Flags / metadata', renderMonoList(edge.details)), + ); + } + + private renderSummaryInspector( + trace: Trace, + session: ProcessGraphSession, + model: ProcessGraphModel, + subgraph: ContextualSubgraph, + snap: GraphSnapshot, + ): m.Children { + const frozenCount = snap.nodes.filter((n) => n.isFrozen).length; + const targetUpid = + subgraph.explicitTargetUpids.size === 1 + ? [...subgraph.explicitTargetUpids][0] + : undefined; + const scopeLabel = + session.scopeMode === 'component' + ? 'Full component' + : session.scopeMode === 'neighbors' + ? 'Direct connections' + : 'Directed chains'; + return this.renderInspectorShell( + trace, + 'summary', + 'Subgraph summary', + snap.ts, + targetUpid, + m( + Tree, + {bordered: true}, + m(TreeNode, { + left: 'Timestamp', + right: `+${formatRelTime(snap.ts - model.traceStart)}`, + }), + m(TreeNode, { + left: 'Window', + right: `+${formatRelTime(subgraph.windowStart - model.traceStart)} → +${formatRelTime(subgraph.windowEnd - model.traceStart)}`, + }), + m(TreeNode, { + left: 'Scope', + right: scopeLabel, + }), + m(TreeNode, { + left: 'Visible', + right: `${snap.nodes.length} procs (${frozenCount} frozen) · ${snap.edges.length} edges`, + }), + ), + m( + 'p.pf-process-graph__muted', + 'Click a process or edge to inspect its bindings, or press Play / Next to step through changes in the selected window.', + ), + ); + } +}
diff --git a/ui/src/plugins/com.android.ProcessGraph/styles.scss b/ui/src/plugins/com.android.ProcessGraph/styles.scss new file mode 100644 index 0000000..c4e73d6 --- /dev/null +++ b/ui/src/plugins/com.android.ProcessGraph/styles.scss
@@ -0,0 +1,192 @@ +// Copyright (C) 2026 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +.pf-process-graph { + height: 100%; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; + background: var(--pf-color-background); + color: var(--pf-color-text); + + &:focus { + outline: none; + } + + :focus-visible { + outline: 2px solid var(--pf-color-accent); + outline-offset: 2px; + } +} + +.pf-process-graph__toolbar { + flex: none; + display: flex; + flex-direction: column; + gap: 4px; + padding: 5px 8px; + background: var(--pf-color-background-secondary); + border-bottom: 1px solid var(--pf-color-border); + font-size: 11.5px; +} + +.pf-process-graph__toolbar-row { + display: flex; + align-items: center; + gap: 5px 8px; + flex-wrap: wrap; +} + +.pf-process-graph__toolbar-row--meta { + justify-content: space-between; +} + +.pf-process-graph__filters { + display: flex; + align-items: center; + gap: 6px 10px; + flex-wrap: wrap; +} + +.pf-process-graph__meta { + color: var(--pf-color-text-muted); + font-size: 11px; +} + +.pf-process-graph__search { + width: 170px; + min-width: 120px; +} + +.pf-process-graph__control-label { + display: inline-flex; + align-items: center; + gap: 4px; + color: var(--pf-color-text-muted); + font-size: 11.5px; +} + +.pf-process-graph__scrubber { + flex: 1 1 110px; + min-width: 80px; + max-width: 240px; + accent-color: var(--pf-color-primary); + cursor: pointer; + + &:disabled { + opacity: 0.45; + cursor: default; + } +} + +.pf-process-graph__time-readout { + white-space: nowrap; + font-family: var(--pf-font-monospace); + font-size: 11px; + color: var(--pf-color-text-muted); +} + +.pf-process-graph__body { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; +} + +.pf-process-graph__loading { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + color: var(--pf-color-text-muted); + font-size: 13px; +} + +.pf-process-graph__inspector { + width: 100%; + height: 100%; + overflow: auto; + background: var(--pf-color-background-secondary); + padding: 8px 10px; + font-size: 11.5px; + display: flex; + flex-direction: column; + gap: 8px; + border-left: 1px solid var(--pf-color-border); + + > * { + flex-shrink: 0; + } +} + +.pf-process-graph__inspector-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; +} + +.pf-process-graph__inspector-title { + margin: 0; + font-size: 12.5px; + font-weight: 600; +} + +.pf-process-graph__section-title { + margin: 0; + font-size: 11px; + font-weight: 600; + color: var(--pf-color-text-muted); +} + +.pf-process-graph__muted { + margin: 0; + color: var(--pf-color-text-muted); +} + +.pf-process-graph__list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 3px; +} + +.pf-process-graph__peer-row { + display: flex; + align-items: stretch; + gap: 4px; +} + +.pf-process-graph__peer-main { + flex: 1 1 auto; + text-align: left; + font-family: var(--pf-font-monospace); +} + +.pf-process-graph__full-btn { + width: 100%; + text-align: left; + font-family: var(--pf-font-monospace); +} + +.pf-process-graph__mono-item { + font-family: var(--pf-font-monospace); + font-size: 11px; + word-break: break-word; +}