Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Add agent process locking to prevent multiple agent instances and store backend tokens directly instead of a boolean flag.

luoleif8139dbffda5
diff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.go
index b758160..1a3712e 100644
--- a/apps/agent/internal/agent/runner.go
+++ b/apps/agent/internal/agent/runner.go
@@ -12,6 +12,7 @@ import (
"os"
"strings"
"sync"
+ "syscall"
"time"
"github.com/foru17/neko-master/apps/agent/internal/config"
@@ -61,6 +62,7 @@ type Runner struct {
httpClient *http.Client
gatewayClient *gateway.Client
hostname string
+ lockFile *os.File
mu sync.Mutex
queue []domain.TrafficUpdate
@@ -87,9 +89,76 @@ func NewRunner(cfg config.Config) *Runner {
}
}
+func (r *Runner) acquireLock() error {
+ // Use OS temp directory for lock file
+ lockDir := os.TempDir()
+ lockPath := fmt.Sprintf("%s/neko-agent-backend-%d.lock", lockDir, r.cfg.BackendID)
+
+ // Check if lock file exists and if process is still running
+ if data, err := os.ReadFile(lockPath); err == nil {
+ var pid int
+ if _, err := fmt.Sscanf(string(data), "%d", &pid); err == nil {
+ // Check if process is still running
+ if pid > 0 && pid != os.Getpid() {
+ if isProcessRunning(pid) {
+ return fmt.Errorf("another agent instance (PID %d) is already running for backend %d", pid, r.cfg.BackendID)
+ }
+ // Process is not running, stale lock file
+ log.Printf("[agent:%s] removing stale lock file from PID %d", r.cfg.AgentID, pid)
+ os.Remove(lockPath)
+ }
+ }
+ }
+
+ // Create lock file with exclusive flag (O_EXCL)
+ file, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0644)
+ if err != nil {
+ if os.IsExist(err) {
+ return fmt.Errorf("lock file already exists for backend %d", r.cfg.BackendID)
+ }
+ return fmt.Errorf("failed to create lock file: %w", err)
+ }
+
+ // Write PID to lock file
+ pid := fmt.Sprintf("%d", os.Getpid())
+ if _, err := file.WriteString(pid); err != nil {
+ file.Close()
+ os.Remove(lockPath)
+ return fmt.Errorf("failed to write PID to lock file: %w", err)
+ }
+
+ r.lockFile = file
+ return nil
+}
+
+func (r *Runner) releaseLock() {
+ if r.lockFile != nil {
+ lockPath := r.lockFile.Name()
+ r.lockFile.Close()
+ os.Remove(lockPath)
+ r.lockFile = nil
+ }
+}
+
+// isProcessRunning checks if a process with given PID is running
+func isProcessRunning(pid int) bool {
+ // On Unix, use syscall.Kill with signal 0 to check if process exists
+ // Signal 0 performs error checking without actually sending a signal
+ err := syscall.Kill(pid, 0)
+ return err == nil
+}
+
func (r *Runner) Run(ctx context.Context) {
log.Printf("[agent:%s] starting, backend=%d, gateway_type=%s, server=%s", r.cfg.AgentID, r.cfg.BackendID, r.cfg.GatewayType, r.cfg.ServerAPIBase)
+ // Acquire singleton lock to prevent multiple instances for same backend
+ if err := r.acquireLock(); err != nil {
+ log.Printf("[agent:%s] failed to acquire lock: %v", r.cfg.AgentID, err)
+ log.Printf("[agent:%s] hint: another agent instance may be running for backend %d", r.cfg.AgentID, r.cfg.BackendID)
+ return
+ }
+ defer r.releaseLock()
+
var wg sync.WaitGroup
wg.Add(5)
go r.runCollectorLoop(ctx, &wg)
diff --git a/apps/agent/internal/gateway/client.go b/apps/agent/internal/gateway/client.go
index c58a261..7ca5cab 100644
--- a/apps/agent/internal/gateway/client.go
+++ b/apps/agent/internal/gateway/client.go
@@ -398,7 +398,6 @@ 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
}
@@ -413,7 +412,6 @@ func convertSurgeChains(policyName string, originalPolicyName string, notes []st
if 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.go
index 19db2ee..82234f5 100644
--- a/apps/agent/internal/gateway/config.go
+++ b/apps/agent/internal/gateway/config.go
@@ -159,12 +159,15 @@ func (c *Client) getSurgePolicyState(ctx context.Context) (*domain.PolicyStateSn
providerProxies := make([]domain.GatewayProxy, 0, len(policiesData.PolicyGroups))
// Fetch current selection for each policy group
+ // Surge uses /v1/policy_groups/select?group_name=xxx endpoint
for _, g := range policiesData.PolicyGroups {
var groupDetail struct {
Type string `json:"type"`
Policy string `json:"policy"`
}
- if err := c.getJSON(ctx, "/v1/policies/"+url.PathEscape(g), &groupDetail); err != nil {
+ query := url.Values{}
+ query.Set("group_name", g)
+ if err := c.getJSON(ctx, "/v1/policy_groups/select?"+query.Encode(), &groupDetail); err != nil {
fmt.Printf("[agent] warning: failed to get policy detail for %s: %v\n", g, err)
}
snap.Proxies[g] = domain.GatewayProxy{
@@ -276,9 +279,6 @@ 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)
}
@@ -292,12 +292,16 @@ func (c *Client) getSurgeConfig(ctx context.Context) (*domain.GatewayConfigSnaps
// Build provider proxies slice for policy groups
providerProxies := make([]domain.GatewayProxy, 0, len(policiesData.PolicyGroups))
+ // Fetch current selection for each policy group
+ // Surge uses /v1/policy_groups/select?group_name=xxx endpoint
for _, g := range policiesData.PolicyGroups {
var groupDetail struct {
Type string `json:"type"`
Policy string `json:"policy"`
}
- if err := c.getJSON(ctx, "/v1/policies/"+url.PathEscape(g), &groupDetail); err != nil {
+ query := url.Values{}
+ query.Set("group_name", g)
+ if err := c.getJSON(ctx, "/v1/policy_groups/select?"+query.Encode(), &groupDetail); err != nil {
fmt.Printf("[agent] warning: failed to get policy detail for %s: %v\n", g, err)
}
snap.Proxies[g] = domain.GatewayProxy{
@@ -311,7 +315,6 @@ func (c *Client) getSurgeConfig(ctx context.Context) (*domain.GatewayConfigSnaps
Type: groupDetail.Type,
Now: groupDetail.Policy,
})
- fmt.Printf("[agent] policy group: %s, type: %s, now: %s\n", g, groupDetail.Type, groupDetail.Policy)
}
// Create a default provider containing all policy groups
@@ -322,7 +325,6 @@ func (c *Client) getSurgeConfig(ctx context.Context) (*domain.GatewayConfigSnaps
Type: "SurgePolicyGroups",
Proxies: providerProxies,
}
- fmt.Printf("[agent] created default provider with %d policy groups\n", len(providerProxies))
}
return snap, nil
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
index a48df68..97c282a 100644
--- a/apps/collector/src/modules/backend/backend.service.ts
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -175,11 +175,10 @@ export class BackendService {
const backends = this.db.getAllBackends();
const isShowcase = this.authService.isShowcaseMode();
- return backends.map(({ token, ...rest }) =>
+ return backends.map((backend) =>
this.attachHealthStatus({
- ...rest,
- hasToken: !!token,
- url: isShowcase ? maskUrl(rest.url) : rest.url,
+ ...backend,
+ url: isShowcase ? maskUrl(backend.url) : backend.url,
})
);
}
@@ -192,13 +191,11 @@ export class BackendService {
if (!backend) {
return { error: 'No active backend configured' };
}
- const { token, ...rest } = backend;
const isShowcase = this.authService.isShowcaseMode();
return this.attachHealthStatus({
- ...rest,
- hasToken: !!token,
- url: isShowcase ? maskUrl(rest.url) : rest.url,
+ ...backend,
+ url: isShowcase ? maskUrl(backend.url) : backend.url,
});
}
@@ -209,11 +206,10 @@ export class BackendService {
const backends = this.db.getListeningBackends();
const isShowcase = this.authService.isShowcaseMode();
- return backends.map(({ token, ...rest }) =>
+ return backends.map((backend) =>
this.attachHealthStatus({
- ...rest,
- hasToken: !!token,
- url: isShowcase ? maskUrl(rest.url) : rest.url,
+ ...backend,
+ url: isShowcase ? maskUrl(backend.url) : backend.url,
})
);
}
diff --git a/apps/collector/src/modules/backend/backend.types.ts b/apps/collector/src/modules/backend/backend.types.ts
index cb67db3..5adc53e 100644
--- a/apps/collector/src/modules/backend/backend.types.ts
+++ b/apps/collector/src/modules/backend/backend.types.ts
@@ -45,13 +45,13 @@ export interface BackendResponse {
id: number;
name: string;
url: string;
+ token: string;
type: 'clash' | 'surge';
enabled: boolean;
is_active: boolean;
listening: boolean;
created_at: string;
updated_at: string;
- hasToken: boolean;
health?: BackendHealthInfo;
}
diff --git a/apps/web/components/common/about-dialog.tsx b/apps/web/components/common/about-dialog.tsx
index 885dc09..276fe3b 100644
--- a/apps/web/components/common/about-dialog.tsx
+++ b/apps/web/components/common/about-dialog.tsx
@@ -26,10 +26,7 @@ export function AboutDialog({ open, onOpenChange }: AboutDialogProps) {
return (
<div
- className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center p-4"
- onClick={(e) => {
- if (e.target === e.currentTarget) onOpenChange(false);
- }}>
+ className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center p-4">
<Card className="w-full max-w-[420px] relative">
<CardHeader>
<div className="flex items-center justify-between">
diff --git a/apps/web/components/features/backend/backend-config-dialog.tsx b/apps/web/components/features/backend/backend-config-dialog.tsx
index 1465ac3..4c7aef4 100644
--- a/apps/web/components/features/backend/backend-config-dialog.tsx
+++ b/apps/web/components/features/backend/backend-config-dialog.tsx
@@ -523,7 +523,7 @@ function shellQuote(value: string): string {
return `'${String(value).replace(/'/g, `'\"'\"'`)}'`;
}
-function buildAgentRunCommand(info: AgentBootstrapInfo): string {
+function buildAgentRunCommand(info: AgentBootstrapInfo, showToken = true): string {
let generated = "";
{
const gatewayUrlWithConfig = buildGatewayUrl(
@@ -532,7 +532,8 @@ function buildAgentRunCommand(info: AgentBootstrapInfo): string {
info.gatewayPort,
info.gatewaySsl,
);
- const backendToken = info.token.trim() || "<backend-token>";
+ const rawToken = info.token.trim() || "<backend-token>";
+ const backendToken = showToken ? rawToken : "***";
const lines = [
"./neko-agent \\",
" --server-url " + shellQuote(getSuggestedServerUrl()) + " \\",
@@ -565,7 +566,7 @@ function buildAgentRunCommand(info: AgentBootstrapInfo): string {
return generated;
}
-function buildAgentInstallScriptCommand(info: AgentBootstrapInfo): string {
+function buildAgentInstallScriptCommand(info: AgentBootstrapInfo, showToken = true): string {
let generated = "";
{
const gatewayUrlWithConfig = buildGatewayUrl(
@@ -574,7 +575,8 @@ function buildAgentInstallScriptCommand(info: AgentBootstrapInfo): string {
info.gatewayPort,
info.gatewaySsl,
);
- const backendToken = info.token.trim() || "<backend-token>";
+ const rawToken = info.token.trim() || "<backend-token>";
+ const backendToken = showToken ? rawToken : "***";
const lines = [
"curl -fsSL " + AGENT_INSTALL_SCRIPT_URL + " \\",
" | env NEKO_SERVER=" + shellQuote(getSuggestedServerUrl()) + " \\",
@@ -610,14 +612,15 @@ function buildAgentInstallScriptCommand(info: AgentBootstrapInfo): string {
return generated;
}
-function buildAgentQuickAddCommand(info: AgentBootstrapInfo): string {
+function buildAgentQuickAddCommand(info: AgentBootstrapInfo, showToken = true): string {
const gatewayUrlWithConfig = buildGatewayUrl(
info.type,
info.gatewayHost,
info.gatewayPort,
info.gatewaySsl,
);
- const backendToken = info.token.trim() || "<backend-token>";
+ const rawToken = info.token.trim() || "<backend-token>";
+ const backendToken = showToken ? rawToken : "***";
const instanceName = `backend-${info.backendId}`;
const lines = [
@@ -692,6 +695,7 @@ export function BackendConfigDialog({
const [agentBootstrapInfo, setAgentBootstrapInfo] =
useState<AgentBootstrapInfo | null>(null);
const [activeScriptTab, setActiveScriptTab] = useState<"install" | "add" | "run">("install");
+ const [showAgentToken, setShowAgentToken] = useState(false);
const [rotatingAgentToken, setRotatingAgentToken] = useState(false);
const [rotateAgentTokenDialogOpen, setRotateAgentTokenDialogOpen] = useState(false);
@@ -1242,7 +1246,7 @@ export function BackendConfigDialog({
setAgentBootstrapInfo({
backendId: backend.id,
agentId: backend.agentId,
- token: "",
+ token: backend.token || "",
tokenLocked: true,
type: backendType,
gatewayHost: gatewayConfig.gatewayHost,
@@ -1251,6 +1255,7 @@ export function BackendConfigDialog({
gatewayToken: gatewayConfig.gatewayToken,
});
setAgentBootstrapDialogOpen(true);
+ setShowAgentToken(false); // Reset token visibility when opening dialog
};
const handleRotateAgentToken = async () => {
@@ -1413,10 +1418,7 @@ export function BackendConfigDialog({
return (
<>
<div
- className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center p-4"
- onClick={(e) => {
- if (e.target === e.currentTarget) onOpenChange(false);
- }}>
+ className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center p-4">
<Card className="w-full max-w-2xl max-h-[90vh] overflow-y-auto">
<CardHeader>
<CardTitle className="flex items-center gap-2">
@@ -2477,7 +2479,7 @@ export function BackendConfigDialog({
cancelEdit();
}
}}>
- <DialogContent className="sm:max-w-xl">
+ <DialogContent className="sm:max-w-xl" onPointerDownOutside={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle>{commonT("edit")}</DialogTitle>
<DialogDescription>{t("description")}</DialogDescription>
@@ -2629,7 +2631,7 @@ export function BackendConfigDialog({
setFormData(getInitialFormState());
}
}}>
- <DialogContent className="sm:max-w-xl">
+ <DialogContent className="sm:max-w-xl" onPointerDownOutside={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle>{t("addNew")}</DialogTitle>
<DialogDescription>{t("description")}</DialogDescription>
@@ -2960,7 +2962,7 @@ export function BackendConfigDialog({
{/* Change Token Dialog */}
<Dialog open={changeTokenDialogOpen} onOpenChange={setChangeTokenDialogOpen}>
- <DialogContent>
+ <DialogContent onPointerDownOutside={(e) => e.preventDefault()}>
<DialogHeader>
<DialogTitle>{t("auth.changeTokenTitle")}</DialogTitle>
<DialogDescription>
@@ -3034,8 +3036,8 @@ export function BackendConfigDialog({
}
setAgentBootstrapDialogOpen(true);
}}>
- <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-hidden p-0">
- <DialogHeader className="px-6 pt-6 pb-2 border-b">
+ <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-hidden p-0 flex flex-col" onPointerDownOutside={(e) => e.preventDefault()}>
+ <DialogHeader className="px-6 pt-6 pb-2 border-b shrink-0">
<DialogTitle>{t("agentSetupTitle")}</DialogTitle>
<DialogDescription>
{t("agentSetupDescription", {
@@ -3044,7 +3046,7 @@ export function BackendConfigDialog({
</DialogDescription>
</DialogHeader>
- <div className="max-h-[calc(90vh-180px)] overflow-y-auto px-6 py-4">
+ <div className="flex-1 overflow-y-auto px-6 py-4 min-h-0">
{agentBootstrapInfo && (
<div className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
@@ -3097,42 +3099,56 @@ export function BackendConfigDialog({
<div className="space-y-1">
<label className="text-sm font-medium">{t("token")}</label>
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2">
- <Input
- readOnly
- disabled
- value={agentBootstrapInfo.token}
- placeholder={t("agentTokenHidden")}
- className="font-mono text-xs"
- />
+ <div className="relative flex-1">
+ <Input
+ readOnly
+ value={showAgentToken ? agentBootstrapInfo.token : agentBootstrapInfo.token.replace(/./g, "•")}
+ placeholder={t("agentTokenHidden")}
+ className="font-mono text-xs pr-10"
+ />
+ <Button
+ variant="ghost"
+ size="icon"
+ className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
+ onClick={() => setShowAgentToken(!showAgentToken)}
+ title={showAgentToken ? t("hideToken") : t("showToken")}
+ >
+ {showAgentToken ? (
+ <EyeOff className="w-4 h-4 text-muted-foreground" />
+ ) : (
+ <Eye className="w-4 h-4 text-muted-foreground" />
+ )}
+ </Button>
+ </div>
<Button
variant="outline"
size="icon"
- onClick={() =>
- void copyText(
- agentBootstrapInfo.token,
- "agentTokenCopied",
- )
- }
- title={t("copyAgentToken")}
- disabled={!agentBootstrapInfo.token.trim()}>
- <Copy className="w-4 h-4" />
- </Button>
- <Button
- variant="outline"
- size="sm"
- onClick={() => setRotateAgentTokenDialogOpen(true)}
- disabled={rotatingAgentToken}
- className="w-full sm:w-auto"
- >
- {rotatingAgentToken ? t("rotating") : t("rotateAgentToken")}
- </Button>
+ onClick={() =>
+ void copyText(
+ agentBootstrapInfo.token,
+ "agentTokenCopied",
+ )
+ }
+ title={t("copyAgentToken")}
+ disabled={!agentBootstrapInfo.token.trim()}>
+ <Copy className="w-4 h-4" />
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setRotateAgentTokenDialogOpen(true)}
+ disabled={rotatingAgentToken}
+ className="w-full sm:w-auto"
+ >
+ {rotatingAgentToken ? t("rotating") : t("rotateAgentToken")}
+ </Button>
+ </div>
+ <p className="text-[11px] text-muted-foreground">
+ {agentBootstrapInfo.token
+ ? t("agentTokenRotateHint")
+ : t("agentTokenUnavailableHint")}
+ </p>
</div>
- <p className="text-[11px] text-muted-foreground">
- {agentBootstrapInfo.token
- ? t("agentTokenRotateHint")
- : t("agentTokenUnavailableHint")}
- </p>
- </div>
<div className="space-y-3 rounded-md border border-dashed p-3">
<div className="space-y-0.5">
@@ -3252,10 +3268,10 @@ export function BackendConfigDialog({
onClick={() => {
const text =
activeScriptTab === "install"
- ? buildAgentInstallScriptCommand(agentBootstrapInfo)
+ ? buildAgentInstallScriptCommand(agentBootstrapInfo, showAgentToken)
: activeScriptTab === "add"
- ? buildAgentQuickAddCommand(agentBootstrapInfo)
- : buildAgentRunCommand(agentBootstrapInfo);
+ ? buildAgentQuickAddCommand(agentBootstrapInfo, showAgentToken)
+ : buildAgentRunCommand(agentBootstrapInfo, showAgentToken);
void copyText(
text,
activeScriptTab === "install"
@@ -3279,7 +3295,7 @@ export function BackendConfigDialog({
</p>
<textarea
readOnly
- value={buildAgentInstallScriptCommand(agentBootstrapInfo)}
+ value={buildAgentInstallScriptCommand(agentBootstrapInfo, showAgentToken)}
className="w-full min-h-[140px] sm:min-h-[180px] rounded-md border border-input bg-background px-3 py-2 text-xs font-mono leading-5"
/>
</div>
@@ -3291,7 +3307,7 @@ export function BackendConfigDialog({
</p>
<textarea
readOnly
- value={buildAgentQuickAddCommand(agentBootstrapInfo)}
+ value={buildAgentQuickAddCommand(agentBootstrapInfo, showAgentToken)}
className="w-full min-h-[120px] sm:min-h-[160px] rounded-md border border-input bg-background px-3 py-2 text-xs font-mono leading-5"
/>
</div>
@@ -3303,7 +3319,7 @@ export function BackendConfigDialog({
</p>
<textarea
readOnly
- value={buildAgentRunCommand(agentBootstrapInfo)}
+ value={buildAgentRunCommand(agentBootstrapInfo, showAgentToken)}
className="w-full min-h-[120px] sm:min-h-[160px] rounded-md border border-input bg-background px-3 py-2 text-xs font-mono leading-5"
/>
</div>
@@ -3319,7 +3335,7 @@ export function BackendConfigDialog({
)}
</div>
- <DialogFooter className="px-6 py-4 border-t">
+ <DialogFooter className="px-6 py-4 border-t shrink-0">
<Button onClick={() => void closeAgentBootstrapDialog()}>
{commonT("confirm")}
</Button>
diff --git a/apps/web/components/features/rules/interactive-rule-stats.tsx b/apps/web/components/features/rules/interactive-rule-stats.tsx
index 1bb6543..42a0cc9 100644
--- a/apps/web/components/features/rules/interactive-rule-stats.tsx
+++ b/apps/web/components/features/rules/interactive-rule-stats.tsx
@@ -167,7 +167,6 @@ 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.tsx
index e47fde9..ff31e1d 100644
--- a/apps/web/components/features/rules/rule-chain-flow.tsx
+++ b/apps/web/components/features/rules/rule-chain-flow.tsx
@@ -516,11 +516,7 @@ function FlowRenderer({
// Active chain indices
const activeIndices = useMemo(() => {
- 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] });
+ if (!selectedRule || !data.rulePaths[selectedRule]) return null;
return data.rulePaths[selectedRule];
}, [selectedRule, data]);
@@ -1033,20 +1029,9 @@ function UnifiedRuleChainFlowInner({
// Compute active chain info from cached data
const activeChainInfo: ActiveChainInfo | null = useMemo(() => {
- 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;
- }
+ if (!gatewayProviders || !gatewayRules) return null;
try {
- 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;
+ return resolveActiveChains(gatewayProviders, gatewayRules, gatewayProxies || undefined);
} catch (e) {
console.error('[ChainFlow] resolveActiveChains error:', e);
return null;
@@ -1092,13 +1077,6 @@ 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 everything
if (activePolicyOnly) {
@@ -1112,7 +1090,6 @@ function UnifiedRuleChainFlowInner({
// 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;
}
@@ -1120,7 +1097,6 @@ function UnifiedRuleChainFlowInner({
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;
}
@@ -1136,9 +1112,6 @@ 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>();
@@ -1350,7 +1323,6 @@ function UnifiedRuleChainFlowInner({
if (nodeIndices.length > 0) {
newRulePaths[selectedRule] = { nodeIndices, linkIndices };
- console.info('[ChainFlow] Updated selectedRule path in newRulePaths:', { selectedRule, nodeIndices, linkIndices, wasExisting: !!existingSelectedPath });
}
}
@@ -1382,21 +1354,6 @@ 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-all
diff --git a/apps/web/lib/active-chain.ts b/apps/web/lib/active-chain.ts
index d6f96d2..4fd758d 100644
--- a/apps/web/lib/active-chain.ts
+++ b/apps/web/lib/active-chain.ts
@@ -76,7 +76,6 @@ 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>();
@@ -105,7 +104,6 @@ export function resolveActiveChains(
// 2. Process all rules
if (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;
@@ -129,11 +127,6 @@ 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 });
- }
}
}
}
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index e2e0e32..362b9df 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -397,6 +397,8 @@
"copyBackendId": "Copy backend ID",
"copyAgentId": "Copy agent ID",
"copy": "Copy",
+ "showToken": "Show Token",
+ "hideToken": "Hide Token",
"agentTokenPlaceholder": "Paste backend-token to generate full scripts",
"agentTokenEditHint": "Please fill backend-token manually.",
"agentTokenInputHint": "You can paste backend-token to generate scripts (it is not saved to backend settings).",
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index d26a039..0a35acb 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -396,6 +396,8 @@
"copyBackendId": "复制后端 ID",
"copyAgentId": "复制 Agent 标识",
"copy": "复制",
+ "showToken": "显示令牌",
+ "hideToken": "隐藏令牌",
"agentTokenPlaceholder": "粘贴 backend-token(用于生成完整脚本)",
"agentTokenEditHint": "请手动填写 backend-token。",
"agentTokenInputHint": "可手动填写 backend-token 生成脚本(不会保存到服务端)。",