`flow-store.getAllActiveFlows` drops any call made while a fetch is in flight, but its request is parameterised by `filter`: a refetch with a changed filter is discarded with no retry, and `initialize()` then reports the store ready with an empty list
Summary
apps/builder/src/features/flows/provider/flow-store.ts and
apps/builder/src/features/inboxes/provider/inbox-store.ts are the same store written twice β
same initialize() shape, same unconditional finally { set({ initialized: true }) }, same
if (loading || !workspaceId) return guard. #1068 last reshaped both (migrating them onto the
oRPC client) and added a test suite for one of them. One difference makes the shared shape unsound
in the untested one: inbox-store's request takes no parameters, and flow-store's takes
filter.
// flow-store.ts:70-75
getAllActiveFlows: async () => {
const { workspaceId, loading, filter } = get()
if (loading || !workspaceId) {
return
}
For inbox-store this guard is exactly right: a second call would send the identical request, so
dropping it is free. For flow-store it is not, because filter can have changed between the two
calls. "A fetch is already in flight" does not mean "the same question is already being asked" β
and the call that asks the new question is the one that gets dropped, silently, with nothing
scheduling a retry. The store then settles with filter saying one thing and flows holding the
answer to a different query.
The same guard, reached through initialize(), produces the second half:
// flow-store.ts:43-59
initialize: async () => {
const { initialized } = get()
if (initialized) { return }
try {
await get().getAllActiveFlows() // β may return without asking anything
} catch (error: unknown) {
set({ error: getClientErrorMessage(error, "Failed to fetch flows") })
} finally {
set({ initialized: true }) // β unconditional
}
}
When getAllActiveFlows() takes its early return, nothing was requested, nothing failed, and
error stays null β but the finally still reports the store ready, with flows: []. And
because initialize() guards on initialized, the provider never calls it again for the life of
that store; only a consumer that calls getAllActiveFlows() itself can recover, and only one
consumer does (create-broadcast-form.tsx:206/213/216).
Scope, stated honestly up front. We could not find a screen that renders wrong today because
of the second half: none of the six read sites of useFlowStore in this repository reads
initialized, loading or error β all six read state.flows (measured below). So today this
is a store that lies to a reader who does not exist yet, in a store whose public FlowState type
exports the field and whose provider exposes an autoInitialize prop. The first half β the
dropped refetch β is a live correctness trap rather than a latent one, and #1137 (dd6ce4b16,
2026-09-10) added a second filter field to this store, so the surface is growing.
This is the same family as #1158 (inbox-store, still open), one level down: #1158 is "the field
is written and nobody reads it"; this is "the same field is written wrongly, in the sibling store
that has no tests". They should probably be fixed together.
Environment
| Measured against | upstream/main @ 3196f01dd2027279016fb180c48764e128669483 (2026-09-13) |
| How | git grep/git show at that commit, plus vitest against a copy of flow-store.ts extracted with git show upstream/main:β¦ |
| Identity of the code under test | git hash-object of the extracted file = fe563099f570ddc040ab366ee5793cbf8b9d8637 = git rev-parse upstream/main:apps/builder/src/features/flows/provider/flow-store.ts. Byte-for-byte your file, not a paraphrase |
| Node / pnpm / vitest | v24.11.0 / 10.33.2 / 4.1.8 |
| Date | 2026-09-12 |
No deployed instance was involved; everything below is the repository at that commit.
Evidence: red, then green
Three tests state the behaviour we think is correct. Against
upstream/main:apps/builder/src/features/flows/provider/flow-store.ts, all three fail:
β― flow-store-expected.test.ts (3 tests | 3 failed)
Γ a filter change while a fetch is in flight still reaches the server
AssertionError: expected [ Array(1) ] to have a length of 2 but got 1
Γ initialize() does not report the store ready while the list is still on the wire
AssertionError: expected true to be false
Γ initialize() does not latch `initialized` when there is no workspace to ask about
AssertionError: expected true to be false
Test Files 1 failed (1)
Tests 3 failed (3)
The first one, in full β it mirrors what create-broadcast-form.tsx:200-225 does:
test("a filter change while a fetch is in flight still reaches the server", async () => {
const unfiltered = deferred()
setPrivateListFlowsAPI((input) =>
input.startType === undefined
? unfiltered.promise
: Promise.resolve({ data: [{ id: 2, name: "a WA template flow" }] }),
)
const store = createFlowStore({ workspaceId: "workspace-1" })
// Mount: no subaction picked yet, so the effect takes the `else` branch.
const inFlight = store.getState().getAllActiveFlows()
// The operator picks "WhatsApp template message": the same effect re-runs.
store.getState().appendFilter({
startType: "sendWaTemplateMessage",
integrationWhatsappIds: ["integration-wa-1"],
})
await store.getState().getAllActiveFlows()
unfiltered.resolve({ data: [{ id: 1, name: "a flow that starts with sendText" }] })
await inFlight
expect(calls).toHaveLength(2) // β today: 1
expect(calls[1]).toMatchObject({ startType: "sendWaTemplateMessage" })
expect(store.getState().flows).toEqual([{ id: 2, name: "a WA template flow" }])
})
The settled state on today's code, measured rather than described: calls.length === 1 (the
filtered request never left), filter === { startType: "sendWaTemplateMessage", integrationWhatsappIds: [...] }, flows === [{ id: 1, name: "a flow that starts with sendText" }],
loading === false, error === null. Nothing in the store says the two disagree, and nothing will
ask again.
With the patch in "Suggested fix" applied, the same three tests pass:
Test Files 1 passed (1)
Tests 3 passed (3)
Second run: the six behaviours your own inbox-store.test.ts pins, translated
Because the guard is deliberate in the sibling store, we ported every assertion from
apps/builder/src/features/inboxes/provider/__tests__/inbox-store.test.ts onto the flow store and
ran it against both versions:
Behaviour (from inbox-store.test.ts) |
today | with the patch |
|---|---|---|
fetches for the workspace with maxPerPage |
pass | pass |
is a no-op when workspaceId is empty |
pass | pass |
| is a no-op while the same fetch is already in flight (1 request, not 2) | pass | pass |
| sets the error message on a rejected request | pass | pass |
| does not fetch again once already initialized | pass | pass |
| still marks the store initialized when the fetch fails | pass | pass |
###### parity vs the patch ###### Tests 6 passed (6)
###### parity vs today's code ###### Tests 6 passed (6)
The de-duplication you wrote is preserved: two calls with the same filter still produce exactly one request. Only a call with a different filter changes behaviour.
Evidence: six read sites, none reads initialized
$ git grep -n 'useFlowStore' 3196f01dd -- apps/builder/src | grep -v flow-store-context.tsx
β¦/automated-response/automated-response-table.tsx:70: const { flows: allFlows } = useFlowStore((state) => state)
β¦/broadcasts/components/broadcast-flow-targets.tsx:87: const flows = useFlowStore((state) => state.flows)
β¦/broadcasts/create-broadcast-form.tsx:123: const { appendFilter, resetFilter, getAllActiveFlows } = useFlowStore(
β¦/broadcasts/create-broadcast-form.tsx:442: const { flows } = useFlowStore((state) => state)
β¦/flows/provider/flow-hook.ts:7: const flows = useFlowStore((state) => state.flows)
β¦/flows/provider/flow-hook.ts:20: const flows = useFlowStore((state) => state.flows)
β¦/flows/react-flow/steps/start-external-node/editor.tsx:27: const flows = useFlowStore((state) => state.flows)
Six sites read data; every one of them reads flows. The seventh (:123-125, a three-line
destructure trimmed above) takes only the three actions. Nothing anywhere selects initialized,
loading or error. FlowStoreProvider is mounted in 40 files across the app
(git grep -lE '<FlowStoreProvider' 3196f01dd -- apps/builder/src | wc -l β 40), so this is not a
corner of the product.
How to see it in your own pages
/space/[workspaceId]/broadcasts/create (page.tsx:58-89) and
/space/[workspaceId]/broadcasts/[broadcastId]/edit (page.tsx:56-86) nest the providers like
this, outermost first:
FlowStoreProvider β autoInitialize defaults to true (flow-store-context.tsx:27)
β¦ CustomField / Integration / FlowTemplate / WhatsappFlow β¦
InboxStoreProvider
β¦ User / Sequence / Contact β¦
CreateBroadcastForm β calls appendFilter()/resetFilter() + getAllActiveFlows()
in its own effect (create-broadcast-form.tsx:200-225)
React runs a child's effects before its parent's, and getAllActiveFlows sets loading: true
synchronously before its first await (flow-store.ts:77-80). So on every mount of these two
pages the form's effect starts the fetch and FlowStoreProvider's initialize() β which runs
after it β finds loading === true, returns without asking for anything, and its finally marks
initialized: true while the list is still on the wire. That is by construction, not a race.
The refetch path is create-broadcast-form.tsx:200-225, whose deps include
selectedWhatsappIntegrationIds. That value is memoised by value on [inboxes, key]
(:262-275), and inboxes comes from the inbox store mounted inside the flow store β so when
the inbox fetch lands, this effect re-runs and calls getAllActiveFlows() again. If the flow
fetch has not come back yet, that call is the one that gets dropped.
We are being careful about what that costs today, because we checked: of the two filter fields
this effect sets, startType is honoured by flowService.list
(packages/business/src/flow/service.ts:121-137) but only changes on operator interaction, which
is slow relative to a fetch; and integrationWhatsappIds β the one that changes while the fetch is
in flight β never reaches the service at all
(git grep -n integrationWhatsappIds 3196f01dd returns three hits, all client-side). So the
dropped refetch is reachable but, on today's tree, not yet observable as wrong data. It becomes
observable the moment a filter that both varies mid-flight and is honoured server-side exists.
Why we think this is a defect rather than the intended design
Both halves of this mechanism are pinned as intentional in the sibling store, and we want to be explicit that we are not asking for either of those to be reversed:
// inbox-store.test.ts:50-66
test("is a no-op while a fetch is already in flight", β¦)
// inbox-store.test.ts:122-138
test("still marks the store initialized when getAllInboxes fails", async () => {
// β¦its `finally` unconditionally marks `initialized: true` regardless, and
// getAllInboxes's error is still visible on the shared `error` field.
Those are right for inbox-store. getAllInboxes sends one fixed request
(inbox-store.ts:62-66: workspaceId, includes, perPage β no variable parameters), so a
duplicate call really is redundant, and a store that retried forever on a hard failure would be
worse than one that gives up and records error.
What is new here, and what no test in the repository covers, is that flow-store has a filter
in its state and splices it into the request (flow-store.ts:80-85) while carrying a guard whose
correctness depended on there being no parameters. That composition was never pinned either way,
because the flow store has no tests at all:
$ git ls-tree -r --name-only 3196f01dd -- apps/builder/src/features/flows/provider
apps/builder/src/features/flows/provider/flow-hook.ts
apps/builder/src/features/flows/provider/flow-store-context.tsx
apps/builder/src/features/flows/provider/flow-store.ts
$ git ls-tree -r --name-only 3196f01dd -- apps/builder/src/features/inboxes/provider
apps/builder/src/features/inboxes/provider/__tests__/inbox-store.test.ts
apps/builder/src/features/inboxes/provider/inbox-store-context.tsx
apps/builder/src/features/inboxes/provider/inbox-store.ts
The initialize() half is likewise a different case from the one your test documents. That test
covers "the fetch failed", where error is set and a caller has something to look at. The case
here is "the fetch never happened": initialized: true, flows: [], error: null, zero
requests. The comment's own justification β the failure "is still visible on the shared error
field" β does not apply, because there is no failure to be visible.
Suggested fix
De-duplicate by the request rather than by a boolean: an identical query joins the one already on
the wire (your intent, preserved), a different one supersedes it. Built and run against
3196f01dd; biome check clean; 3 red β 3 green, with the six parity behaviours still passing.
--- a/apps/builder/src/features/flows/provider/flow-store.ts
+++ b/apps/builder/src/features/flows/provider/flow-store.ts
@@
-export const createFlowStore = (props: Partial<FlowState>) =>
- createStore<FlowStore>((set, get) => ({
+export const createFlowStore = (props: Partial<FlowState>) => {
+ // Unlike the inbox store, this store's request is parameterised by `filter`,
+ // so "a fetch is already in flight" does NOT mean "the same question is
+ // already being asked". De-duplicate by the request itself: an identical
+ // query joins the one on the wire, a different one supersedes it.
+ let inFlightKey: string | null = null
+ let inFlightRequest: Promise<void> | null = null
+
+ return createStore<FlowStore>((set, get) => ({
loading: false,
@@
initialize: async () => {
- const { initialized } = get()
+ const { initialized, workspaceId } = get()
- if (initialized) {
+ // Without a workspace there is nothing to ask for, and latching
+ // `initialized` here would make every later initialize() a no-op.
+ if (initialized || !workspaceId) {
return
}
@@
getAllActiveFlows: async () => {
- const { workspaceId, loading, filter } = get()
+ const { workspaceId, filter } = get()
- if (loading || !workspaceId) {
+ if (!workspaceId) {
return
}
- try {
- set({ loading: true, error: null })
-
- const { data } = await client.flowsAPI.privateListFlowsAPI({
- workspaceId,
- perPage: maxPerPage,
- active: true,
- ...filter,
- })
-
- set({ flows: data })
- } catch (error: unknown) {
- set({
- error: getClientErrorMessage(error, "Failed to fetch flows"),
- })
- } finally {
- set({ loading: false })
- }
+ const request = {
+ workspaceId,
+ perPage: maxPerPage,
+ active: true,
+ ...filter,
+ }
+ const key = JSON.stringify(request)
+
+ if (inFlightKey === key && inFlightRequest) {
+ // Same query already on the wire: join it, so an awaiting caller
+ // (initialize()) still learns when the list has actually landed.
+ await inFlightRequest
+ return
+ }
+
+ const fetchFlows = async () => {
+ try {
+ const { data } = await client.flowsAPI.privateListFlowsAPI(request)
+
+ if (inFlightKey === key) {
+ set({ flows: data })
+ }
+ } catch (error: unknown) {
+ if (inFlightKey === key) {
+ set({
+ error: getClientErrorMessage(error, "Failed to fetch flows"),
+ })
+ }
+ } finally {
+ if (inFlightKey === key) {
+ inFlightKey = null
+ inFlightRequest = null
+ set({ loading: false })
+ }
+ }
+ }
+
+ set({ loading: true, error: null })
+ inFlightKey = key
+ inFlightRequest = fetchFlows()
+ await inFlightRequest
},
}))
+}
Three things this buys, in order of how much we care:
- A call whose
filterdiffers is no longer dropped, sofilterandflowscannot settle in disagreement, and a stale response cannot overwrite a newer one (inFlightKey === keyguards eachset). initialize()awaits the request that is actually running, soinitialized: truemeans "the list has landed (or failed)" rather than "initialize()finished executing".initialize()no longer latchesinitializedwhen there is noworkspaceIdto ask about, so a provider mounted before the id is known can still load once it arrives. That third one is independent of the other two and is the same two-line change we suggested forinbox-storein #1158 β if you prefer, it can be dropped from this patch and done in both stores at once.
We would rather you take the shape than the diff, and we are glad to open the PR if it is useful.
Whatever shape you land on, a flow-store.test.ts next to inbox-store.test.ts would keep this
from drifting back.
What we did not verify
- We did not observe this in a running browser. We have no deployed instance of this
repository. The store behaviour is measured by test against your exact file; the React effect
ordering that makes the provider's
initialize()lose the race on the two broadcast pages is read from the code and from React's documented child-before-parent effect order β it is reasoned, not observed. - We did not find a user-visible symptom on today's tree, and we say so above rather than implying one. The dropped refetch is reachable but its two current filter fields do not combine into wrong pixels: one is honoured but slow-changing, the other changes mid-flight but never reaches the service.
- We did not audit the other stores built on the same pattern (
flow-template-store,whatsapp-flow-store,contact-store,sequence-store,custom-field-store,integration-store,user-store) for the same parameterised-request-plus-reentrancy-guard shape. That is not checked, not proven absent. - We did not measure how often the drop happens in practice; the report is about the state being unrepresentable, not about frequency.
JSON.stringifyas the request key assumes stable key order, which holds because the object is built literal-first with a spread. If you prefer an explicit key builder, that is a cosmetic change to the patch.
Related issues
- #1158 (open) β same family, sibling store:
inbox-storerecords an error that none of its fourteen consumers reads. That issue is about a field nobody reads; this one is about the same field being set incorrectly in the sibling store that has no tests. #1068 last reshaped both stores and is whereinbox-store.test.tscame from. - Searched
gh search issues --repo ChatbotXIO/ChatbotXforflow-store,useFlowStore,initialized,flow store race,getAllActiveFlows,broadcast flow filter. Only #1158 comes back, on the first and third. The witness query (inbox store) returns results, so the empty ones are genuine absences.
Resolved by #1265 (fdddbf1571), which replaced the Zustand flow-store with TanStack Query hooks in apps/builder/src/features/flows/provider/flow-hook.ts.
useFlows(workspaceId, { filter }) puts the filter in the query key, so a changed filter starts a new query instead of being dropped;
the initialized/loading latch is gone (readiness is isPending, and enabled: Boolean(workspaceId) prevents a premature ready state);
create-broadcast-form.tsx calls useFlows with the derived filter directly;
flow-hook.test.tsx covers the hooks.
Sibling #1158 was closed for the same reason.