A modern and elegant dashboard for network traffic visualization and analysis.
feat: Enrich rule flow paths in collector using agent proxy configuration's 'now' field to resolve full policy chains.
luolei4be23f93d6ae
diff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.goindex d308b55..bd68598 100644--- a/apps/agent/internal/agent/runner.go+++ b/apps/agent/internal/agent/runner.go@@ -176,12 +176,32 @@ func (r *Runner) runHeartbeatLoop(ctx context.Context, wg *sync.WaitGroup) {func (r *Runner) runConfigSyncLoop(ctx context.Context, wg *sync.WaitGroup) {defer wg.Done()- // Initial sync immediately- if err := r.syncConfig(ctx); err != nil {- log.Printf("[agent:%s] init config sync error: %v", r.cfg.AgentID, err)+ // Initial sync with retry for binding conflicts+ // If server returns 409 (already bound), retry with backoff+ maxRetries := 5+ for i := 0; i < maxRetries; i++ {+ err := r.syncConfig(ctx)+ if err == nil {+ log.Printf("[agent:%s] config synced successfully", r.cfg.AgentID)+ break+ }+ if i == maxRetries-1 {+ log.Printf("[agent:%s] init config sync failed after %d retries: %v", r.cfg.AgentID, maxRetries, err)+ } else {+ // Check if it's a binding conflict (409)+ if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "AGENT_TOKEN_ALREADY_BOUND") {+ backoff := time.Duration(i+1) * 5 * time.Second+ log.Printf("[agent:%s] config sync binding conflict, retrying in %v... (%d/%d)", r.cfg.AgentID, backoff, i+1, maxRetries)+ time.Sleep(backoff)+ } else {+ // Non-binding error, log and continue with ticker+ log.Printf("[agent:%s] init config sync error: %v", r.cfg.AgentID, err)+ break+ }+ }}- // Then every 5 minutes (or reuse heartbeat interval)+ // Then every 2 minutesticker := time.NewTicker(2 * time.Minute)defer ticker.Stop()diff --git a/apps/agent/internal/gateway/client.go b/apps/agent/internal/gateway/client.goindex 7ca5cab..c58a261 100644--- a/apps/agent/internal/gateway/client.go+++ b/apps/agent/internal/gateway/client.go@@ -398,6 +398,7 @@ func isDomainName(host string) bool {func convertSurgeChains(policyName string, originalPolicyName string, notes []string) []string {if fromNotes := extractPolicyPathFromNotes(notes); len(fromNotes) >= 2 {+ fmt.Printf("[agent] convertSurgeChains from notes: %v -> %v\n", notes, fromNotes)return fromNotes}@@ -412,6 +413,7 @@ func convertSurgeChains(policyName string, originalPolicyName string, notes []stif len(chains) == 0 {return []string{"DIRECT"}}+ fmt.Printf("[agent] convertSurgeChains fallback: policy=%s, original=%s, notes=%v -> %v\n", policyName, originalPolicyName, notes, chains)return chains}diff --git a/apps/agent/internal/gateway/config.go b/apps/agent/internal/gateway/config.goindex 54b84ad..7322715 100644--- a/apps/agent/internal/gateway/config.go+++ b/apps/agent/internal/gateway/config.go@@ -165,6 +165,9 @@ func (c *Client) getSurgeConfig(ctx context.Context) (*domain.GatewayConfigSnaps}for i, raw := range rulesData.Rules {+ if i < 3 {+ fmt.Printf("[agent] rule %d: %s\n", i, raw)+ }snap.Rules[i] = parseSurgeRuleForAgent(raw)}@@ -180,12 +183,15 @@ func (c *Client) getSurgeConfig(ctx context.Context) (*domain.GatewayConfigSnapsType string `json:"type"`Policy string `json:"policy"`}- _ = c.getJSON(ctx, "/v1/policies/"+url.PathEscape(g), &groupDetail)+ if err := c.getJSON(ctx, "/v1/policies/"+url.PathEscape(g), &groupDetail); err != nil {+ fmt.Printf("[agent] warning: failed to get policy detail for %s: %v\n", g, err)+ }snap.Proxies[g] = domain.GatewayProxy{Name: g,Type: groupDetail.Type,Now: groupDetail.Policy,}+ fmt.Printf("[agent] policy group: %s, type: %s, now: %s\n", g, groupDetail.Type, groupDetail.Policy)}return snap, nildiff --git a/apps/collector/src/database/repositories/base.repository.ts b/apps/collector/src/database/repositories/base.repository.tsindex 7915e3c..72ce335 100644--- a/apps/collector/src/database/repositories/base.repository.ts+++ b/apps/collector/src/database/repositories/base.repository.ts@@ -246,20 +246,63 @@ export abstract class BaseRepository {* Build a normalized rule flow path in "rule -> ... -> proxy" order*/protected buildRuleFlowPath(rule: string, chain: string): string[] {+ return this.buildRuleFlowPathWithConfig(rule, chain, undefined);+ }++ /**+ * Build a normalized rule flow path with proxy config enrichment.+ * For Agent mode, uses proxy config (with 'now' field) to complete short chains.+ */+ protected buildRuleFlowPathWithConfig(+ rule: string,+ chain: string,+ proxyConfig: Record<string, { now?: string }> | undefined,+ ): string[] {const chainParts = this.splitChainParts(chain);if (chainParts.length === 0) {return [];}- const ruleIndex = this.findRuleIndexInChain(chainParts, rule);+ // Debug logging for Agent mode chain enrichment+ if (proxyConfig && chainParts.length < 3) {+ console.info(`[buildRuleFlowPath] Rule: ${rule}, Chain: ${chain}, Parts: ${JSON.stringify(chainParts)}, ProxyConfig keys: ${Object.keys(proxyConfig).length}`);+ }++ // Enrich chain with proxy config if available and chain is short+ let enrichedParts = chainParts;+ if (proxyConfig && chainParts.length < 3) {+ enrichedParts = this.enrichChainWithProxyConfig(chainParts, proxyConfig);+ if (enrichedParts.length > chainParts.length) {+ console.info(`[buildRuleFlowPath] Enriched: ${JSON.stringify(chainParts)} -> ${JSON.stringify(enrichedParts)}`);+ }+ }++ // Try to find rule in enriched chain+ const ruleIndex = this.findRuleIndexInChain(enrichedParts, rule);if (ruleIndex !== -1) {// Full chain stored as proxy > ... > rule, reverse to rule > ... > proxy.- return chainParts.slice(0, ruleIndex + 1).reverse();+ return enrichedParts.slice(0, ruleIndex + 1).reverse();+ }++ // If rule not in chain but we enriched it, build path: rule -> ... -> proxy+ // enrichedParts is already in order: [ruleGroup, middleGroup, finalProxy]+ if (enrichedParts.length > chainParts.length) {+ // Check if first element could be the rule target+ const normalizedRule = this.normalizeFlowLabel(rule);+ const normalizedFirst = this.normalizeFlowLabel(enrichedParts[0] || "");++ // If rule matches first element or rule is parent of first element+ if (normalizedRule === normalizedFirst) {+ return enrichedParts;+ }++ // Otherwise prepend rule: rule -> enrichedParts+ return [rule, ...enrichedParts];}// Fallback for mismatched labels or minute_dim rows:// normalize direction to rule/group -> ... -> proxy.- const reversed = [...chainParts].reverse();+ const reversed = [...enrichedParts].reverse();const normalizedRule = this.normalizeFlowLabel(rule);const normalizedHead = this.normalizeFlowLabel(reversed[0] || "");if (normalizedRule && normalizedRule === normalizedHead) {@@ -269,6 +312,70 @@ export abstract class BaseRepository {return [rule, ...reversed];}+ /**+ * Enrich a short chain using proxy config to build complete policy path.+ * For Surge Agent mode: traces back from final proxy through policy groups using 'now' field.+ */+ private enrichChainWithProxyConfig(+ chainParts: string[],+ proxyConfig: Record<string, { now?: string }>,+ ): string[] {+ if (chainParts.length === 0) {+ return chainParts;+ }++ // Debug: log proxyConfig sample+ const sampleEntries = Object.entries(proxyConfig).slice(0, 3);+ console.info(`[enrichChain] chainParts: ${JSON.stringify(chainParts)}, proxyConfig sample: ${JSON.stringify(sampleEntries)}`);++ // Build complete path by tracing backwards through proxy config+ const completePath = [...chainParts];+ const visited = new Set<string>(chainParts);++ // Start from the last element and trace back using 'now' references+ let current = chainParts[chainParts.length - 1];+ let iterations = 0;+ const maxIterations = 10; // Prevent infinite loops++ while (current && iterations < maxIterations) {+ // Find which policy group points to current as its 'now' selection+ let foundParent = false;+ for (const [name, config] of Object.entries(proxyConfig)) {+ if (config.now === current && !visited.has(name)) {+ console.info(`[enrichChain] Found parent: ${name}.now = ${config.now} (current: ${current})`);+ completePath.push(name);+ visited.add(name);+ current = name;+ foundParent = true;+ break;+ }+ }+ if (!foundParent) {+ console.info(`[enrichChain] No parent found for current: ${current}`);+ break;+ }+ iterations++;+ }++ // If we enriched the chain, reverse to get correct order (rule -> ... -> proxy)+ if (completePath.length > chainParts.length) {+ // The chain is stored as [finalProxy, ...], we need to reverse to get [..., rule]+ // But actually we want: rule -> group -> finalProxy+ // Proxy config gives us: group -> finalProxy (via now field)+ // So we reverse to get: finalProxy -> group+ // Then the caller will reverse again... let's return in correct order++ // Current completePath: [finalProxy, group1, group2] (where group2.now = group1, group1.now = finalProxy)+ // We want: [group2, group1, finalProxy] for proper flow path+ const result = completePath.reverse();+ console.info(`[enrichChain] Result: ${JSON.stringify(result)}`);+ return result;+ }++ console.info(`[enrichChain] No enrichment possible, returning original`);+ return chainParts;+ }+/*** Get unique non-empty values from an array*/diff --git a/apps/collector/src/database/repositories/rule.repository.ts b/apps/collector/src/database/repositories/rule.repository.tsindex 061926a..f0cb272 100644--- a/apps/collector/src/database/repositories/rule.repository.ts+++ b/apps/collector/src/database/repositories/rule.repository.ts@@ -306,6 +306,7 @@ export class RuleRepository extends BaseRepository {getRuleChainFlow(backendId: number, rule: string, start?: string, end?: string,realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>,+ proxyConfig?: Record<string, { now?: string }>,): { nodes: Array<{ name: string; totalUpload: number; totalDownload: number; totalConnections: number }>; links: Array<{ source: number; target: number }> } {const range = this.parseMinuteRange(start, end);let rows: Array<{ chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>;@@ -363,7 +364,7 @@ export class RuleRepository extends BaseRepository {const linkSet = new Set<string>();for (const row of rows) {- const flowPath = this.buildRuleFlowPath(rule, row.chain);+ const flowPath = this.buildRuleFlowPathWithConfig(rule, row.chain, proxyConfig);if (flowPath.length < 2) continue;for (let i = 0; i < flowPath.length; i++) {const nodeName = flowPath[i];@@ -400,6 +401,7 @@ export class RuleRepository extends BaseRepository {getAllRuleChainFlows(backendId: number, start?: string, end?: string,realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>,+ proxyConfig?: Record<string, { now?: string }>,): {nodes: Array<{ name: string; layer: number; nodeType: 'rule' | 'group' | 'proxy'; totalUpload: number; totalDownload: number; totalConnections: number; rules: string[] }>;links: Array<{ source: number; target: number; rules: string[] }>;@@ -431,9 +433,11 @@ export class RuleRepository extends BaseRepository {FROM rule_chain_traffic WHERE backend_id = ? ORDER BY rule, chain`);rows = stmt.all(backendId) as typeof rows;+ console.info(`[getAllRuleChainFlows] DB rows count: ${rows.length}, sample: ${JSON.stringify(rows.slice(0, 2))}`);}if (realtimeRows) {+ console.info(`[getAllRuleChainFlows] realtimeRows count: ${realtimeRows.length}, sample: ${JSON.stringify(realtimeRows.slice(0, 2))}`);for (const rt of realtimeRows) {const index = rows.findIndex((r) => r.rule === rt.rule && r.chain === rt.chain);if (index >= 0) {@@ -469,7 +473,11 @@ export class RuleRepository extends BaseRepository {rulePathLinks.set(rule, new Set());}- const flowPath = this.buildRuleFlowPath(rule, row.chain);+ const flowPath = this.buildRuleFlowPathWithConfig(rule, row.chain, proxyConfig);+ // Debug: log first few rows+ if (rows.indexOf(row) < 3) {+ console.info(`[getAllRuleChainFlows] Row ${rows.indexOf(row)}: rule=${rule}, chain=${row.chain}, flowPath=${JSON.stringify(flowPath)}`);+ }if (flowPath.length < 2) continue;for (let i = 0; i < flowPath.length; i++) {diff --git a/apps/collector/src/modules/app/app.ts b/apps/collector/src/modules/app/app.tsindex d346af9..933fa77 100644--- a/apps/collector/src/modules/app/app.ts+++ b/apps/collector/src/modules/app/app.ts@@ -381,6 +381,17 @@ export async function createApp(options: AppOptions) {return true;}+ // Allow rebinding if the existing agent has been offline for a while+ // Use a longer timeout (60s) than the health check to avoid race conditions+ const AGENT_BINDING_TIMEOUT_MS = 60000;+ const lastSeenMs = new Date(heartbeat.lastSeen).getTime();+ const ageMs = Number.isFinite(lastSeenMs) ? Math.max(0, Date.now() - lastSeenMs) : Number.POSITIVE_INFINITY;++ if (Number.isFinite(ageMs) && ageMs > AGENT_BINDING_TIMEOUT_MS) {+ console.info(`[Agent] Allowing rebinding for backend ${backendId}: previous agent '${heartbeat.agentId}' offline for ${Math.round(ageMs / 1000)}s`);+ return true;+ }+reply.status(409).send({error: `Agent token is already bound to '${heartbeat.agentId}'. Rotate token before binding '${agentId}'.`,code: 'AGENT_TOKEN_ALREADY_BOUND',@@ -508,6 +519,9 @@ export async function createApp(options: AppOptions) {}}+ // Debug log for chain data+ console.info(`[Agent Report] Chain data: chains=${JSON.stringify(update.chains)}, rule=${update.rule}, domain=${update.domain}`);+realtimeStore.recordTraffic(backendId,{@@ -595,10 +609,12 @@ export async function createApp(options: AppOptions) {app.post('/api/agent/config', async (request, reply) => {const body = request.body as AgentConfigPayload;const backendId = parseBackendId(body?.backendId);+ console.info(`[Agent Config] Received config for backendId: ${backendId}, agentId: ${body?.agentId}`);if (backendId === null) {return reply.status(400).send({ error: 'Invalid backendId' });}if (!isAgentBackendAuthorized(backendId, request, reply)) {+ console.info(`[Agent Config] Backend not authorized: ${backendId}`);return;}const agentId = parseAgentId(body.agentId);@@ -606,6 +622,7 @@ export async function createApp(options: AppOptions) {return reply.status(400).send({ error: 'Invalid agentId' });}if (!isAgentBindingAllowed(backendId, agentId, reply)) {+ console.info(`[Agent Config] Binding not allowed for agent: ${agentId}`);return;}@@ -613,6 +630,7 @@ export async function createApp(options: AppOptions) {return reply.status(400).send({ error: 'Missing config payload' });}+ console.info(`[Agent Config] Storing config for backendId: ${backendId}, proxies count: ${Object.keys(body.config?.proxies || {}).length}`);realtimeStore.setAgentConfig(backendId, body.config);return { success: true, backendId, hash: body.config.hash };@@ -621,6 +639,7 @@ export async function createApp(options: AppOptions) {// Compatibility routes: Gateway APIsapp.get('/api/gateway/proxies', async (request, reply) => {const backendId = getBackendIdFromQuery(request.query as Record<string, unknown>);+ console.info(`[Gateway API /proxies] backendId: ${backendId}`);if (backendId === null) {return reply.status(404).send({ error: 'No backend specified or active' });}@@ -631,6 +650,7 @@ export async function createApp(options: AppOptions) {}if (isAgentBackendUrl(backend.url)) {const cached = realtimeStore.getAgentConfig(backendId);+ console.info(`[Gateway API /proxies] Agent mode, cached exists: ${!!cached}`);if (!cached) {return reply.status(503).send({ error: 'Agent config not yet synced' });}@@ -906,6 +926,7 @@ export async function createApp(options: AppOptions) {.map(r => r.raw ? parseSurgeRule(r.raw) : null).filter((r): r is NonNullable<typeof r> => r !== null).map(r => ({ type: r.type, payload: r.payload, proxy: r.policy, size: 0 }));+ console.info(`[Gateway API /rules] Agent mode Surge rules count: ${parsedRules.length}, sample:`, parsedRules.slice(0, 3));return { rules: parsedRules, _source: 'agent-cache' };}diff --git a/apps/collector/src/modules/db/db.ts b/apps/collector/src/modules/db/db.tsindex 888c7da..3aff61d 100644--- a/apps/collector/src/modules/db/db.ts+++ b/apps/collector/src/modules/db/db.ts@@ -754,8 +754,8 @@ export class StatsDatabase {}getRuleIPProxyStats(backendId: number, rule: string, ip: string, start?: string, end?: string) { return this.repos.rule.getRuleIPProxyStats(backendId, rule, ip, start, end); }getRuleIPDomainDetails(backendId: number, rule: string, ip: string, start?: string, end?: string, limit?: number) { return this.repos.rule.getRuleIPDomainDetails(backendId, rule, ip, start, end, limit); }- getRuleChainFlow(backendId: number, rule: string, start?: string, end?: string, realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>) { return this.repos.rule.getRuleChainFlow(backendId, rule, start, end, realtimeRows); }- getAllRuleChainFlows(backendId: number, start?: string, end?: string, realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>) { return this.repos.rule.getAllRuleChainFlows(backendId, start, end, realtimeRows); }+ getRuleChainFlow(backendId: number, rule: string, start?: string, end?: string, realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>, proxyConfig?: Record<string, { now?: string }>) { return this.repos.rule.getRuleChainFlow(backendId, rule, start, end, realtimeRows, proxyConfig); }+ getAllRuleChainFlows(backendId: number, start?: string, end?: string, realtimeRows?: Array<{ rule: string; chain: string; totalUpload: number; totalDownload: number; totalConnections: number }>, proxyConfig?: Record<string, { now?: string }>) { return this.repos.rule.getAllRuleChainFlows(backendId, start, end, realtimeRows, proxyConfig); }// ==================== Private helpers (kept for getSummary) ====================private toMinuteKey(date: Date): string {diff --git a/apps/collector/src/modules/stats/stats.controller.ts b/apps/collector/src/modules/stats/stats.controller.tsindex 7fa4ddf..05706b2 100644--- a/apps/collector/src/modules/stats/stats.controller.ts+++ b/apps/collector/src/modules/stats/stats.controller.ts@@ -390,7 +390,9 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(404).send({ error: 'No backend specified or active' });}- return await service.getRuleStatsWithRouting(backendId, timeRange);+ const result = await service.getRuleStatsWithRouting(backendId, timeRange);+ console.info(`[Stats API /rules] backendId: ${backendId}, rules count: ${result.length}, sample:`, result.slice(0, 3));+ return result;});// Get domains for a specific rulediff --git a/apps/collector/src/modules/stats/stats.service.ts b/apps/collector/src/modules/stats/stats.service.tsindex 3b9bfef..b39aa47 100644--- a/apps/collector/src/modules/stats/stats.service.ts+++ b/apps/collector/src/modules/stats/stats.service.ts@@ -1133,7 +1133,11 @@ export class StatsService {*/getRuleChainFlow(backendId: number, rule: string, timeRange: TimeRange): any {const realtimeRows = this.shouldIncludeRealtime(timeRange) ? this.realtimeStore.getRuleChainRows(backendId) : undefined;- return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end, realtimeRows);+ // Get proxy config for Agent mode to enrich short chains+ const agentConfig = this.realtimeStore.getAgentConfig(backendId);+ const proxyConfig = agentConfig?.proxies;+ console.info(`[StatsService.getRuleChainFlow] backendId: ${backendId}, rule: ${rule}, agentConfig exists: ${!!agentConfig}, proxyConfig keys: ${proxyConfig ? Object.keys(proxyConfig).length : 0}`);+ return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end, realtimeRows, proxyConfig);}async getRuleChainFlowWithRouting(@@ -1143,6 +1147,9 @@ export class StatsService {): Promise<any> {const shouldUseCH = this.shouldUseClickHouseForOptionalRange(timeRange);const realtimeRows = this.shouldIncludeRealtime(timeRange) ? this.realtimeStore.getRuleChainRows(backendId) : undefined;+ // Get proxy config for Agent mode to enrich short chains+ const agentConfig = this.realtimeStore.getAgentConfig(backendId);+ const proxyConfig = agentConfig?.proxies;if (shouldUseCH) {const ch = await this.clickHouseReader.getRuleChainFlow(@@ -1160,7 +1167,7 @@ export class StatsService {this.failIfStrictFallback('rules.chain-flow');this.recordRoute('rules.chain-flow', 'sqlite');- return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end, realtimeRows);+ return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end, realtimeRows, proxyConfig);}/**@@ -1168,7 +1175,11 @@ export class StatsService {*/getAllRuleChainFlows(backendId: number, timeRange: TimeRange): any {const realtimeRows = this.shouldIncludeRealtime(timeRange) ? this.realtimeStore.getRuleChainRows(backendId) : undefined;- return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end, realtimeRows);+ // Get proxy config for Agent mode to enrich short chains+ const agentConfig = this.realtimeStore.getAgentConfig(backendId);+ const proxyConfig = agentConfig?.proxies;+ console.info(`[StatsService.getAllRuleChainFlows] backendId: ${backendId}, agentConfig exists: ${!!agentConfig}, proxyConfig keys: ${proxyConfig ? Object.keys(proxyConfig).length : 0}`);+ return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end, realtimeRows, proxyConfig);}async getAllRuleChainFlowsWithRouting(@@ -1177,6 +1188,9 @@ export class StatsService {): Promise<any> {const shouldUseCH = this.shouldUseClickHouseForOptionalRange(timeRange);const realtimeRows = this.shouldIncludeRealtime(timeRange) ? this.realtimeStore.getRuleChainRows(backendId) : undefined;+ // Get proxy config for Agent mode to enrich short chains+ const agentConfig = this.realtimeStore.getAgentConfig(backendId);+ const proxyConfig = agentConfig?.proxies;if (shouldUseCH) {const ch = await this.clickHouseReader.getAllRuleChainFlows(@@ -1193,7 +1207,7 @@ export class StatsService {this.failIfStrictFallback('rules.chain-flow-all');this.recordRoute('rules.chain-flow-all', 'sqlite');- return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end, realtimeRows);+ return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end, realtimeRows, proxyConfig);}/**diff --git a/apps/web/components/features/rules/interactive-rule-stats.tsx b/apps/web/components/features/rules/interactive-rule-stats.tsxindex 42a0cc9..1bb6543 100644--- a/apps/web/components/features/rules/interactive-rule-stats.tsx+++ b/apps/web/components/features/rules/interactive-rule-stats.tsx@@ -167,6 +167,7 @@ export function InteractiveRuleStats({// Ruleset metadata changes infrequently, so load on mount/backend switch only.const chartData = useMemo<RuleChartItem[]>(() => {+ console.info('[RuleStats] rulesData:', rulesData);if (!rulesData) return [];// Normalize rule names for deduplication (trim whitespace)diff --git a/apps/web/components/features/rules/rule-chain-flow.tsx b/apps/web/components/features/rules/rule-chain-flow.tsxindex 36ba5cf..e47fde9 100644--- a/apps/web/components/features/rules/rule-chain-flow.tsx+++ b/apps/web/components/features/rules/rule-chain-flow.tsx@@ -516,7 +516,11 @@ function FlowRenderer({// Active chain indicesconst activeIndices = useMemo(() => {- if (!selectedRule || !data.rulePaths[selectedRule]) return null;+ if (!selectedRule || !data.rulePaths[selectedRule]) {+ console.info('[FlowRenderer] activeIndices is null:', { selectedRule, hasPath: selectedRule ? !!data.rulePaths[selectedRule] : false, rulePathKeys: Object.keys(data.rulePaths) });+ return null;+ }+ console.info('[FlowRenderer] activeIndices:', { selectedRule, activeIndices: data.rulePaths[selectedRule] });return data.rulePaths[selectedRule];}, [selectedRule, data]);@@ -1029,13 +1033,25 @@ function UnifiedRuleChainFlowInner({// Compute active chain info from cached dataconst activeChainInfo: ActiveChainInfo | null = useMemo(() => {- if (!gatewayProviders || !gatewayRules) return null;+ console.info('[ChainFlow] gatewayProviders:', !!gatewayProviders, 'gatewayRules:', !!gatewayRules, 'gatewayProxies:', !!gatewayProxies, 'backendId:', activeBackendId);+ if (!gatewayProviders || !gatewayRules) {+ console.info('[ChainFlow] Missing providers or rules, returning null');+ return null;+ }try {- return resolveActiveChains(gatewayProviders, gatewayRules, gatewayProxies || undefined);- } catch {+ const result = resolveActiveChains(gatewayProviders, gatewayRules, gatewayProxies || undefined);+ console.info('[ChainFlow] activeChainInfo:', {+ backendId: activeBackendId,+ activeNodeNames: Array.from(result.activeNodeNames).slice(0, 5),+ activeChainsCount: result.activeChains.size,+ sampleChain: result.activeChains.size > 0 ? Array.from(result.activeChains.entries())[0] : null+ });+ return result;+ } catch (e) {+ console.error('[ChainFlow] resolveActiveChains error:', e);return null;}- }, [gatewayProviders, gatewayRules, gatewayProxies]);+ }, [gatewayProviders, gatewayRules, gatewayProxies, activeBackendId]);// When user selects a different rule, auto-disable showAlluseEffect(() => {@@ -1076,6 +1092,13 @@ function UnifiedRuleChainFlowInner({normalizedRulePaths.set(key.trim(), value);}+ // Debug: log selectedRule and rulePaths keys+ if (selectedRule) {+ console.info('[ChainFlow] Filtering for selectedRule:', selectedRule, 'rulePaths keys:', Object.keys(data.rulePaths));+ const exactMatch = normalizedRulePaths.get(selectedRule);+ console.info('[ChainFlow] exactMatch for selectedRule:', exactMatch);+ }+data.nodes.forEach((node, idx) => {// 1. If "All Policies" is checked, keep everythingif (activePolicyOnly) {@@ -1085,9 +1108,24 @@ function UnifiedRuleChainFlowInner({// 2. If a specific rule is selected, always keep nodes in its path// Use normalized lookup- if (selectedRule && normalizedRulePaths.get(selectedRule)?.nodeIndices.includes(idx)) {- keepNodeIndices.add(idx);- return;+ if (selectedRule) {+ // Try exact match first+ const exactMatch = normalizedRulePaths.get(selectedRule);+ if (exactMatch?.nodeIndices.includes(idx)) {+ console.info('[ChainFlow] Exact match for node:', node.name, 'idx:', idx);+ keepNodeIndices.add(idx);+ return;+ }+ // Try emoji-normalized match (e.g., "GitHub" matches "👨💻 GitHub")+ for (const [key, value] of normalizedRulePaths.entries()) {+ if (key.includes(selectedRule) || selectedRule.includes(key)) {+ if (value.nodeIndices.includes(idx)) {+ console.info('[ChainFlow] Fuzzy match for node:', node.name, 'idx:', idx, 'key:', key);+ keepNodeIndices.add(idx);+ return;+ }+ }+ }}// 3. Otherwise, only keep nodes with active traffic or relevant to active chains@@ -1098,6 +1136,9 @@ function UnifiedRuleChainFlowInner({}});+ // Debug: log keepNodeIndices size before building new nodes+ console.info('[ChainFlow] keepNodeIndices size before inject:', keepNodeIndices.size, 'selectedRule:', selectedRule);+// Build new nodes array (existing kept + zero-traffic for missing active)const newNodes: MergedChainNode[] = [];const nameToNewIdx = new Map<string, number>();@@ -1181,8 +1222,22 @@ function UnifiedRuleChainFlowInner({// Check if the server-side analysis knows this link for the selected rule// This is crucial for Surge backend where client-side chain resolution might miss some links// Use normalized lookup here too- const isServerKnownLink = selectedRule &&- normalizedRulePaths.get(selectedRule)?.linkIndices?.includes(idx);+ let isServerKnownLink = false;+ if (selectedRule) {+ // Try exact match first+ isServerKnownLink = normalizedRulePaths.get(selectedRule)?.linkIndices?.includes(idx) ?? false;+ // Try fuzzy match+ if (!isServerKnownLink) {+ for (const [key, value] of normalizedRulePaths.entries()) {+ if (key.includes(selectedRule) || selectedRule.includes(key)) {+ if (value.linkIndices?.includes(idx)) {+ isServerKnownLink = true;+ break;+ }+ }+ }+ }+ }const shouldKeepLink =activePolicyOnly ||@@ -1255,6 +1310,50 @@ function UnifiedRuleChainFlowInner({}}+ // Also add selectedRule's path if it exists in original data but not in activeChains+ // OR if the existing path is incomplete (single node) but original has full chain+ // This ensures FlowRenderer can get activeIndices for the selected rule+ const existingSelectedPath = selectedRule ? newRulePaths[selectedRule] : null;+ const originalPath = selectedRule ? data.rulePaths[selectedRule] : null;+ const needsFullPath = selectedRule && originalPath &&+ (!existingSelectedPath || existingSelectedPath.nodeIndices.length < originalPath.nodeIndices.length);++ if (needsFullPath) {+ const nodeIndices: number[] = [];+ const linkIndices: number[] = [];++ // Map original indices to new indices+ for (const oldIdx of originalPath.nodeIndices) {+ const nodeName = data.nodes[oldIdx]?.name;+ if (nodeName) {+ const newIdx = nameToNewIdx.get(nodeName);+ if (newIdx !== undefined) nodeIndices.push(newIdx);+ }+ }++ // Map original link indices to new links+ for (const oldLinkIdx of originalPath.linkIndices) {+ const oldLink = data.links[oldLinkIdx];+ if (oldLink) {+ const sourceName = data.nodes[oldLink.source]?.name;+ const targetName = data.nodes[oldLink.target]?.name;+ if (sourceName && targetName) {+ const newSrcIdx = nameToNewIdx.get(sourceName);+ const newTgtIdx = nameToNewIdx.get(targetName);+ if (newSrcIdx !== undefined && newTgtIdx !== undefined) {+ const linkIdx = newLinks.findIndex(l => l.source === newSrcIdx && l.target === newTgtIdx);+ if (linkIdx !== -1) linkIndices.push(linkIdx);+ }+ }+ }+ }++ if (nodeIndices.length > 0) {+ newRulePaths[selectedRule] = { nodeIndices, linkIndices };+ console.info('[ChainFlow] Updated selectedRule path in newRulePaths:', { selectedRule, nodeIndices, linkIndices, wasExisting: !!existingSelectedPath });+ }+ }+// Compute maxLayer// const maxLayer = newNodes.reduce((max, n) => Math.max(max, n.layer), 0);@@ -1283,6 +1382,21 @@ function UnifiedRuleChainFlowInner({};}, [data, activePolicyOnly, activeChainInfo, selectedRule, visibleRuleNames]);+ // Debug: log filtered data+ useEffect(() => {+ if (filteredData) {+ console.info('[ChainFlow] filteredData:', {+ backendId: activeBackendId,+ nodesCount: filteredData.nodes.length,+ linksCount: filteredData.links.length,+ nodeNames: filteredData.nodes.map(n => n.name),+ rulePathKeys: Object.keys(filteredData.rulePaths),+ selectedRulePath: selectedRule ? filteredData.rulePaths[selectedRule] : null,+ selectedRule+ });+ }+ }, [filteredData, selectedRule, activeBackendId]);+const renderData = filteredData;// Container height: compact for focused mode, taller for show-alldiff --git a/apps/web/lib/active-chain.ts b/apps/web/lib/active-chain.tsindex 4fd758d..d6f96d2 100644--- a/apps/web/lib/active-chain.ts+++ b/apps/web/lib/active-chain.ts@@ -76,6 +76,7 @@ export function resolveActiveChains(// Use the global proxy list (from /gateway/proxies) as the primary source for 'now'// because it contains the accurate 'now' field we fetched from the backend.const groupNowMap = buildGroupNowMap(providers, proxies);+ console.info('[active-chain] groupNowMap size:', groupNowMap.size, 'entries:', Array.from(groupNowMap.entries()).slice(0, 10));const activeNodeNames = new Set<string>();const activeLinkKeys = new Set<string>();@@ -104,6 +105,7 @@ export function resolveActiveChains(// 2. Process all rulesif (rules && rules.rules) {+ console.info('[active-chain] Processing', rules.rules.length, 'rules');for (const rawRule of rules.rules) {const parsed = parseGatewayRule(rawRule);if (!parsed || !parsed.proxy) continue;@@ -127,6 +129,11 @@ export function resolveActiveChains(if (groupChain.length > 0) {activeLinkKeys.add(encodeActiveLinkKey(ruleName, groupChain[0]));}++ // Debug log for GitHub rule+ if (ruleName.includes('GitHub') || targetGroup.includes('GitHub') || targetGroup.includes('国外')) {+ console.info('[active-chain] GitHub-related rule:', { ruleName, targetGroup, groupChain, ruleChain });+ }}}}