[GH-ISSUE #5375] [Bug]: shareAddrStrategy silently reverts to 'listen' when opening edit modal due to async node-loading race condition #3762

Closed
opened 2026-10-31 20:34:46 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @jshir700 on GitHub (Jun 16, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/5375

Describe the bug

When an inbound has shareAddrStrategy set to 'node' (saved successfully via the API), opening the edit modal in the UI silently reverts it back to 'listen' without any user interaction. Saving the modal without explicitly re-selecting "Node Address" (node) persists the wrong value to the backend.

The root cause is a race condition in InboundFormModal.tsx introduced in commit c47a905 (fix(inbound): offer node share-address strategy only when a node exists) and partially mitigated in commit 90e6217 (PR #5225, fix(inbound): preserve custom share strategy on edit). The partial fix only protects the 'custom' value but does not resolve the underlying timing issue, so 'node' is still silently overwritten on every modal open.

How to reproduce the problem

Prerequisite: A multi-node setup with at least one online node (e.g., ARM2) and at least one local-only inbound (e.g., ARM1).

  1. Set shareAddrStrategy to 'node' for any inbound via the REST API:
    curl -X POST 'https://panel.example.com/panel/api/inbounds/update/1' \
      -H 'Content-Type: application/json' \
      -H 'X-CSRF-Token: <token>' \
      -d '{"shareAddrStrategy": "node", ...full inbound payload...}'
    
  2. Confirm via GET /panel/api/inbounds/list that the API response contains "shareAddrStrategy": "node" for the updated inbound.
  3. Open the panel web UI and navigate to Inbounds page.
  4. Click the edit (pencil) icon on the inbound that was updated in step 1.
  5. Without touching any field, inspect the "Share Address Strategy" dropdown in the edit modal.
    • Expected: The dropdown should display "Node Address" (node), matching the persisted API value.
    • Actual: The dropdown displays "Listen Address" (listen), even though the API still reports shareAddrStrategy: "node".
  6. Close the modal, re-open it, and observe the same result — the value is 'listen' every time.
  7. Verify via GET /panel/api/inbounds/get/1 that the backend value remains "shareAddrStrategy": "node" — the form has not saved the wrong value to the database, it only displays and will submit the wrong value.

Important: This affects all inbounds, including those deployed to an online node (e.g., ARM2 with nodeId=1). The race condition is not specific to "local" inbounds.

Expected behavior

The UI form should faithfully display the persisted shareAddrStrategy value from the API response when the edit modal opens. Specifically:

  • If the API returns shareAddrStrategy: "node", the dropdown should show "Node Address" (node).
  • If the API returns shareAddrStrategy: "listen", the dropdown should show "Listen Address" (listen).
  • If the API returns shareAddrStrategy: "custom", a text input for shareAddr should appear.

The useEffect that drops the 'node' option should only fire after the node list has fully loaded (or failed to load), and should check the actual availability rather than the transient loading state. The effect should also not silently mutate the form value without user awareness.

Actual behavior

The form silently overwrites shareAddrStrategy from 'node' to 'listen' within milliseconds of the modal opening, due to a useEffect that fires before the async node list API call completes.

The specific code path:

  1. User clicks edit; modal opens; form initializes via rawInboundToFormValues(), which sets shareAddrStrategy to the API's value ('node'). ✅
  2. Almost simultaneously, the node list begins fetching asynchronously. At this instant, availableNodes (or the derived selectableNodes) is an empty array — the fetch has not yet resolved.
  3. nodeShareOptionAvailable is computed as selectableNodes.length > 0 && isNodeEligible. Since selectableNodes is [], this evaluates to false.
  4. The useEffect at lines ~393–400 fires:
    const current = form.getFieldValue('shareAddrStrategy');
    if (!nodeShareOptionAvailable && (current ?? 'node') === 'node') {
      form.setFieldValue('shareAddrStrategy', 'listen');
    }
    
    current is 'node', the condition is true → value immediately set to 'listen'. ❌
  5. A few hundred milliseconds later, the node list API response arrives. selectableNodes is now populated (e.g., 2 nodes). nodeShareOptionAvailable becomes true. The useEffect re-fires due to the dependency change.
  6. Now form.getFieldValue('shareAddrStrategy') returns 'listen' — it was just overwritten in step 4. The condition (current ?? 'node') === 'node' evaluates to false. The value is never restored. ❌

This is a classic race condition between form initialization and async data loading. The useEffect assumes that if nodeShareOptionAvailable is false at the time it runs, there are genuinely no eligible nodes — but it cannot distinguish "no nodes exist" from "nodes have not loaded yet."

Relevant code

File: frontend/src/pages/inbounds/form/InboundFormModal.tsx

Line 191 — eligibility flag:

const nodeShareOptionAvailable = selectableNodes.length > 0 && isNodeEligible;

Lines ~393-400 — the problematic effect:

// When `node` isn't offered (no node, or a protocol that can't deploy to one)
// fall back to `listen`
useEffect(() => {
  const current = form.getFieldValue('shareAddrStrategy') as ShareAddrStrategy | undefined;
  if (!nodeShareOptionAvailable && (current ?? 'node') === 'node') {
    form.setFieldValue('shareAddrStrategy', 'listen');
  }
}, [open, nodeShareOptionAvailable, shareAddrStrategy]);

Relevant commit history:

Commit Date Author Description
c47a905 2026-06-11 MHSanaei Introduced the useEffect and nodeShareOptionAvailable flag; the original code unconditionally overwrote 'node' with 'listen'.
90e6217 (PR #5225) 2026-06-12 yuanzhidao Added the current guard to preserve 'custom' strategy on edit; the fix is incomplete because it does not address the underlying race condition.

Suggested fix

The core problem is that nodeShareOptionAvailable is not a reliable signal during the loading phase. The useEffect should be gated on the node list having completed its initial load, regardless of whether the result is an empty list.

Option A — Track loading state explicitly:

// Add a state variable
const [nodesInitiallyLoaded, setNodesInitiallyLoaded] = useState(false);

// After the first time availableNodes settles (even if empty), mark as loaded
useEffect(() => {
  if (!nodesInitiallyLoaded && availableNodes !== undefined) {
    setNodesInitiallyLoaded(true);
  }
}, [availableNodes]);

// Gate the strategy-fallback effect on this flag
useEffect(() => {
  if (!nodesInitiallyLoaded) return; // still loading — do not touch the value
  const current = form.getFieldValue('shareAddrStrategy');
  if (!nodeShareOptionAvailable && (current ?? 'node') === 'node') {
    form.setFieldValue('shareAddrStrategy', 'listen');
  }
}, [nodesInitiallyLoaded, nodeShareOptionAvailable, shareAddrStrategy]);

Option B — Use the query hook's loading state:

If availableNodes is fetched via a hook that exposes an isLoading or isPending flag, gate the effect on that flag being false:

const { data: availableNodes, isLoading: nodesLoading } = useNodes();

useEffect(() => {
  if (nodesLoading) return;
  // ... existing logic ...
}, [nodesLoading, nodeShareOptionAvailable, ...]);

Option C — Check the actual resolved node count from the real API response:

Inject a short delay or a second-pass check in the effect to allow the async fetch to settle before making the fallback decision.

Relevant logs


Screenshots

No response

3x-ui version

3.3.1

Xray-core version

26.6.1

How did you install 3x-ui?

install.sh script

Operating system

Ubuntu 24.04

Which parts of the panel are affected?

Frontend (UI / panel pages), Multi-node (sub-nodes)

Browser (only if it is a UI bug)

Microsoft Edge 132 (Chromium-based), also reproduced on Chrome 132

Is the panel behind a reverse proxy or CDN?

None

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (or have verified the bug still exists on it).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, client UUIDs).
Originally created by @jshir700 on GitHub (Jun 16, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/5375 ### Describe the bug When an inbound has `shareAddrStrategy` set to `'node'` (saved successfully via the API), opening the edit modal in the UI silently reverts it back to `'listen'` without any user interaction. Saving the modal without explicitly re-selecting "Node Address" (`node`) persists the wrong value to the backend. The root cause is a **race condition in `InboundFormModal.tsx`** introduced in commit `c47a905` (`fix(inbound): offer node share-address strategy only when a node exists`) and partially mitigated in commit `90e6217` (PR #5225, `fix(inbound): preserve custom share strategy on edit`). The partial fix only protects the `'custom'` value but does not resolve the underlying timing issue, so `'node'` is still silently overwritten on every modal open. ### How to reproduce the problem **Prerequisite:** A multi-node setup with at least one online node (e.g., ARM2) and at least one local-only inbound (e.g., ARM1). 1. Set `shareAddrStrategy` to `'node'` for **any** inbound via the REST API: ```bash curl -X POST 'https://panel.example.com/panel/api/inbounds/update/1' \ -H 'Content-Type: application/json' \ -H 'X-CSRF-Token: <token>' \ -d '{"shareAddrStrategy": "node", ...full inbound payload...}' ``` 2. Confirm via `GET /panel/api/inbounds/list` that the API response contains `"shareAddrStrategy": "node"` for the updated inbound. 3. Open the panel web UI and navigate to **Inbounds** page. 4. Click the edit (pencil) icon on the inbound that was updated in step 1. 5. **Without touching any field**, inspect the "Share Address Strategy" dropdown in the edit modal. - **Expected:** The dropdown should display "Node Address" (`node`), matching the persisted API value. - **Actual:** The dropdown displays "Listen Address" (`listen`), even though the API still reports `shareAddrStrategy: "node"`. 6. Close the modal, re-open it, and observe the same result — the value is `'listen'` every time. 7. Verify via `GET /panel/api/inbounds/get/1` that the backend value remains `"shareAddrStrategy": "node"` — the form has **not** saved the wrong value to the database, it only **displays and will submit** the wrong value. **Important:** This affects **all** inbounds, including those deployed to an online node (e.g., ARM2 with `nodeId=1`). The race condition is not specific to "local" inbounds. ### Expected behavior The UI form should faithfully display the persisted `shareAddrStrategy` value from the API response when the edit modal opens. Specifically: - If the API returns `shareAddrStrategy: "node"`, the dropdown should show "Node Address" (`node`). - If the API returns `shareAddrStrategy: "listen"`, the dropdown should show "Listen Address" (`listen`). - If the API returns `shareAddrStrategy: "custom"`, a text input for `shareAddr` should appear. The `useEffect` that drops the `'node'` option should only fire **after** the node list has fully loaded (or failed to load), and should check the actual availability rather than the transient loading state. The effect should also not silently mutate the form value without user awareness. ### Actual behavior The form silently overwrites `shareAddrStrategy` from `'node'` to `'listen'` within milliseconds of the modal opening, due to a `useEffect` that fires **before** the async node list API call completes. The specific code path: 1. User clicks edit; modal opens; form initializes via `rawInboundToFormValues()`, which sets `shareAddrStrategy` to the API's value (`'node'`). ✅ 2. Almost simultaneously, the node list begins fetching asynchronously. At this instant, `availableNodes` (or the derived `selectableNodes`) is an **empty array** — the fetch has not yet resolved. 3. `nodeShareOptionAvailable` is computed as `selectableNodes.length > 0 && isNodeEligible`. Since `selectableNodes` is `[]`, this evaluates to `false`. 4. The `useEffect` at lines ~393–400 fires: ```typescript const current = form.getFieldValue('shareAddrStrategy'); if (!nodeShareOptionAvailable && (current ?? 'node') === 'node') { form.setFieldValue('shareAddrStrategy', 'listen'); } ``` `current` is `'node'`, the condition is `true` → value immediately set to `'listen'`. ❌ 5. A few hundred milliseconds later, the node list API response arrives. `selectableNodes` is now populated (e.g., 2 nodes). `nodeShareOptionAvailable` becomes `true`. The `useEffect` re-fires due to the dependency change. 6. Now `form.getFieldValue('shareAddrStrategy')` returns `'listen'` — it was just overwritten in step 4. The condition `(current ?? 'node') === 'node'` evaluates to `false`. **The value is never restored.** ❌ This is a classic **race condition between form initialization and async data loading**. The `useEffect` assumes that if `nodeShareOptionAvailable` is `false` at the time it runs, there are genuinely no eligible nodes — but it cannot distinguish "no nodes exist" from "nodes have not loaded yet." ### Relevant code **File:** `frontend/src/pages/inbounds/form/InboundFormModal.tsx` **Line 191** — eligibility flag: ```typescript const nodeShareOptionAvailable = selectableNodes.length > 0 && isNodeEligible; ``` **Lines ~393-400** — the problematic effect: ```typescript // When `node` isn't offered (no node, or a protocol that can't deploy to one) // fall back to `listen` useEffect(() => { const current = form.getFieldValue('shareAddrStrategy') as ShareAddrStrategy | undefined; if (!nodeShareOptionAvailable && (current ?? 'node') === 'node') { form.setFieldValue('shareAddrStrategy', 'listen'); } }, [open, nodeShareOptionAvailable, shareAddrStrategy]); ``` **Relevant commit history:** | Commit | Date | Author | Description | |--------|------|--------|-------------| | `c47a905` | 2026-06-11 | MHSanaei | Introduced the `useEffect` and `nodeShareOptionAvailable` flag; the original code unconditionally overwrote `'node'` with `'listen'`. | | `90e6217` (PR #5225) | 2026-06-12 | yuanzhidao | Added the `current` guard to preserve `'custom'` strategy on edit; the fix is incomplete because it does not address the underlying race condition. | ### Suggested fix The core problem is that `nodeShareOptionAvailable` is not a reliable signal during the loading phase. The `useEffect` should be gated on the node list having completed its initial load, regardless of whether the result is an empty list. **Option A — Track loading state explicitly:** ```typescript // Add a state variable const [nodesInitiallyLoaded, setNodesInitiallyLoaded] = useState(false); // After the first time availableNodes settles (even if empty), mark as loaded useEffect(() => { if (!nodesInitiallyLoaded && availableNodes !== undefined) { setNodesInitiallyLoaded(true); } }, [availableNodes]); // Gate the strategy-fallback effect on this flag useEffect(() => { if (!nodesInitiallyLoaded) return; // still loading — do not touch the value const current = form.getFieldValue('shareAddrStrategy'); if (!nodeShareOptionAvailable && (current ?? 'node') === 'node') { form.setFieldValue('shareAddrStrategy', 'listen'); } }, [nodesInitiallyLoaded, nodeShareOptionAvailable, shareAddrStrategy]); ``` **Option B — Use the query hook's loading state:** If `availableNodes` is fetched via a hook that exposes an `isLoading` or `isPending` flag, gate the effect on that flag being `false`: ```typescript const { data: availableNodes, isLoading: nodesLoading } = useNodes(); useEffect(() => { if (nodesLoading) return; // ... existing logic ... }, [nodesLoading, nodeShareOptionAvailable, ...]); ``` **Option C — Check the actual resolved node count from the real API response:** Inject a short delay or a second-pass check in the effect to allow the async fetch to settle before making the fallback decision. ### Relevant logs ```shell ``` ### Screenshots _No response_ ### 3x-ui version 3.3.1 ### Xray-core version 26.6.1 ### How did you install 3x-ui? install.sh script ### Operating system Ubuntu 24.04 ### Which parts of the panel are affected? Frontend (UI / panel pages), Multi-node (sub-nodes) ### Browser (only if it is a UI bug) Microsoft Edge 132 (Chromium-based), also reproduced on Chrome 132 ### Is the panel behind a reverse proxy or CDN? None ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this bug has not been reported. - [x] I am running the latest released version of 3x-ui (or have verified the bug still exists on it). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, client UUIDs).
bsakaguchi 2026-10-31 20:34:46 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@github-actions[bot] commented on GitHub (Jun 16, 2026):

The race condition is confirmed in the current source (v3.3.1). Here is the exact chain:

How the bug occurs

  1. useNodesQuery in frontend/src/api/queries/useNodesQuery.ts (line 36) initializes nodes as query.data ?? []. Before the async /panel/api/nodes/list response arrives, nodes is an empty array.

  2. InboundsPage.tsx (line 104) only destructures nodes from the hook:

    const { nodes: nodesList } = useNodesQuery();
    

    The hook's fetched flag (query.data \!== undefined || query.isError, line 79 of useNodesQuery.ts) is not forwarded to the modal.

  3. InboundFormModal.tsx derives nodeShareOptionAvailable from the still-empty list:

    // line 188
    const selectableNodes = (availableNodes || []).filter((n) => n.enable);
    // line 194
    const nodeShareOptionAvailable = selectableNodes.length > 0 && isNodeEligible;
    

    While the network request is in flight, this is false.

  4. The useEffect at lines 393–400 fires on open becoming true, sees nodeShareOptionAvailable === false and current === 'node', and overwrites the form value to 'listen' before the node list arrives. When the node list does arrive, the same effect re-fires, but by then current is already 'listen', so no restoration occurs.

The partial fix introduced in commit 90e6217 (PR #5225, "fix(inbound): preserve custom share strategy on edit") changed the condition from an unconditional overwrite to:

if (\!nodeShareOptionAvailable && (current ?? 'node') === 'node') {

This correctly protected 'custom' because the condition only triggers when current is 'node' (or undefined). However, it still overwrites 'node' itself, which is exactly the case reported here.

Root cause distinction from #5224

Issue #5224 was specifically about 'custom' being overwritten; PR #5225 fixed that. The present issue concerns 'node' being overwritten, which the same condition still allows. The underlying timing problem (effect fires before the async fetch resolves) was not addressed in that fix.

Minimal fix

useNodesQuery already exposes the information needed. The fix requires three localized changes:

In InboundsPage.tsx, also destructure fetched:

const { nodes: nodesList, fetched: nodesFetched } = useNodesQuery();

Pass it to the modal (around line 652):

<InboundFormModal
  ...
  availableNodes={nodesList}
  nodesLoaded={nodesFetched}
/>

In InboundFormModal.tsx, add the prop to the interface:

interface InboundFormModalProps {
  ...
  availableNodes?: NodeRecord[];
  nodesLoaded?: boolean;
}

Then gate the effect:

useEffect(() => {
  if (\!open) return;
  if (\!nodesLoaded) return; // nodes not yet fetched — do not overwrite
  const current = form.getFieldValue('shareAddrStrategy') as InboundFormValues['shareAddrStrategy'] | undefined;
  if (\!nodeShareOptionAvailable && (current ?? 'node') === 'node') {
    form.setFieldValue('shareAddrStrategy', 'listen');
  }
}, [open, nodesLoaded, nodeShareOptionAvailable, shareAddrStrategy]);

With this gate, the effect is a no-op while the fetch is pending and only enforces the fallback once the actual node list (including an empty one) has been confirmed by the API response.

Affected version: v3.3.1 (latest release). The useNodesQuery.ts fetched flag (query.data \!== undefined || query.isError) is available without any new API surface.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:4715202426 --> @github-actions[bot] commented on GitHub (Jun 16, 2026): The race condition is confirmed in the current source (v3.3.1). Here is the exact chain: **How the bug occurs** 1. `useNodesQuery` in `frontend/src/api/queries/useNodesQuery.ts` (line 36) initializes `nodes` as `query.data ?? []`. Before the async `/panel/api/nodes/list` response arrives, `nodes` is an empty array. 2. `InboundsPage.tsx` (line 104) only destructures `nodes` from the hook: ```typescript const { nodes: nodesList } = useNodesQuery(); ``` The hook's `fetched` flag (`query.data \!== undefined || query.isError`, line 79 of `useNodesQuery.ts`) is not forwarded to the modal. 3. `InboundFormModal.tsx` derives `nodeShareOptionAvailable` from the still-empty list: ```typescript // line 188 const selectableNodes = (availableNodes || []).filter((n) => n.enable); // line 194 const nodeShareOptionAvailable = selectableNodes.length > 0 && isNodeEligible; ``` While the network request is in flight, this is `false`. 4. The `useEffect` at lines 393–400 fires on `open` becoming `true`, sees `nodeShareOptionAvailable === false` and `current === 'node'`, and overwrites the form value to `'listen'` before the node list arrives. When the node list does arrive, the same effect re-fires, but by then `current` is already `'listen'`, so no restoration occurs. The partial fix introduced in commit `90e6217` (PR #5225, "fix(inbound): preserve custom share strategy on edit") changed the condition from an unconditional overwrite to: ```typescript if (\!nodeShareOptionAvailable && (current ?? 'node') === 'node') { ``` This correctly protected `'custom'` because the condition only triggers when `current` is `'node'` (or `undefined`). However, it still overwrites `'node'` itself, which is exactly the case reported here. **Root cause distinction from #5224** Issue #5224 was specifically about `'custom'` being overwritten; PR #5225 fixed that. The present issue concerns `'node'` being overwritten, which the same condition still allows. The underlying timing problem (effect fires before the async fetch resolves) was not addressed in that fix. **Minimal fix** `useNodesQuery` already exposes the information needed. The fix requires three localized changes: In `InboundsPage.tsx`, also destructure `fetched`: ```typescript const { nodes: nodesList, fetched: nodesFetched } = useNodesQuery(); ``` Pass it to the modal (around line 652): ```typescript <InboundFormModal ... availableNodes={nodesList} nodesLoaded={nodesFetched} /> ``` In `InboundFormModal.tsx`, add the prop to the interface: ```typescript interface InboundFormModalProps { ... availableNodes?: NodeRecord[]; nodesLoaded?: boolean; } ``` Then gate the effect: ```typescript useEffect(() => { if (\!open) return; if (\!nodesLoaded) return; // nodes not yet fetched — do not overwrite const current = form.getFieldValue('shareAddrStrategy') as InboundFormValues['shareAddrStrategy'] | undefined; if (\!nodeShareOptionAvailable && (current ?? 'node') === 'node') { form.setFieldValue('shareAddrStrategy', 'listen'); } }, [open, nodesLoaded, nodeShareOptionAvailable, shareAddrStrategy]); ``` With this gate, the effect is a no-op while the fetch is pending and only enforces the fallback once the actual node list (including an empty one) has been confirmed by the API response. **Affected version:** v3.3.1 (latest release). The `useNodesQuery.ts` `fetched` flag (`query.data \!== undefined || query.isError`) is available without any new API surface. *This reply was generated automatically; a maintainer may follow up.*
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#3762
No description provided.