Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(onboarding): reconcile the active cloud run against the server for all users (#74036)

Fernando Gomes819b3a90f615
diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts
index 23e6016b9e26..3c3d3b43c707 100644
--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts
+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts
@@ -1,15 +1,22 @@
-import { MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'
+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
import { projectLogic } from 'scenes/projectLogic'
-import { userLogic } from 'scenes/userLogic'
import { initKeaTests } from '~/test/init'
+import type { AppContext, OnboardingSkippedReason, TeamType } from '~/types'
import { tasksActiveWizardRunRetrieve, tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'
-import { activeCloudRunLogic, CloudRunHandle, scopedCloudRun } from './activeCloudRunLogic'
+import {
+ activeCloudRunLogic,
+ CloudRunHandle,
+ CloudRunReconciliation,
+ RECONCILE_INTERVAL_MS,
+ reconcileCloudRun,
+ scopedCloudRun,
+} from './activeCloudRunLogic'
jest.mock('products/tasks/frontend/generated/api', () => ({
tasksActiveWizardRunRetrieve: jest.fn(),
@@ -19,6 +26,8 @@ jest.mock('products/tasks/frontend/generated/api', () => ({
const mockActiveWizardRun = tasksActiveWizardRunRetrieve as jest.Mock
const mockRunCancel = tasksRunsCancelCreate as jest.Mock
+const RUN_STARTED_AT = '2026-01-01T00:00:00Z'
+
const handle: CloudRunHandle = {
taskId: 'task-1',
runId: 'run-1',
@@ -26,12 +35,14 @@ const handle: CloudRunHandle = {
projectId: 2,
}
-function setUser(provisioned: boolean): void {
- userLogic.mount()
- userLogic.actions.loadUserSuccess({
- ...MOCK_DEFAULT_USER,
- onboarding_skipped_reason: provisioned ? 'provisioned' : null,
- })
+// userLogic reads the bootstrapped user out of the app context, so seeding it there is how a test
+// picks which kind of account is looking at the run.
+function initAs(onboardingSkippedReason: OnboardingSkippedReason, team: TeamType = MOCK_DEFAULT_TEAM): void {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ current_user: { ...MOCK_DEFAULT_USER, onboarding_skipped_reason: onboardingSkippedReason },
+ } as unknown as AppContext
+ initKeaTests(true, team)
}
describe('activeCloudRunLogic', () => {
@@ -49,13 +60,39 @@ describe('activeCloudRunLogic', () => {
})
})
+ describe('reconcileCloudRun', () => {
+ const serverRun = { run_id: 'run-2' }
+ const cases: [string, CloudRunHandle | null, { run_id: string } | null, boolean, CloudRunReconciliation][] = [
+ // 204: the server drops terminal and stale runs, so whatever the client holds is retired.
+ // Retiring works for every account, adoption does not.
+ ['clears a handle the server no longer reports', handle, null, false, 'clear'],
+ ['clears a handle for an adopting client too', handle, null, true, 'clear'],
+ ['keeps nothing when there is nothing to clear', null, null, false, 'keep'],
+ // The drop-flow signup: the run was started server-side, so this browser never had a handle.
+ ['adopts a server run the client never wrote', null, serverRun, true, 'adopt'],
+ // The endpoint is team-scoped and names no creator, so an answer to a client that cannot
+ // have started a run server-side may well be a teammate's run. Taking it would put their
+ // task titles, event plan and errors on this user's screen, behind this user's Cancel.
+ ['leaves a team run alone for anyone else', null, serverRun, false, 'keep'],
+ // The run's outcome reaches the surfaces through its stream; clearing here would drop the
+ // finished-run handoff before the user dismissed it.
+ ['keeps a terminal answer for the run it already tracks', handle, { run_id: handle.runId }, true, 'keep'],
+ // A held handle is never displaced, not even for the account adoption is open to.
+ ['keeps the local handle against a different run the team is running', handle, serverRun, true, 'keep'],
+ ]
+ it.each(cases)('%s', (_name, local, server, canAdopt, expected) => {
+ expect(reconcileCloudRun(local, server, canAdopt)).toBe(expected)
+ })
+ })
+
describe('hydrateFromServer', () => {
let logic: ReturnType<typeof activeCloudRunLogic.build>
beforeEach(() => {
// The handle is persisted to localStorage, so clear it or a seeded run leaks across tests.
window.localStorage.clear()
- initKeaTests()
+ // The app context survives between tests, so reset the user or a provisioned one leaks.
+ initAs(null)
mockActiveWizardRun.mockReset()
projectLogic.mount()
})
@@ -64,8 +101,10 @@ describe('activeCloudRunLogic', () => {
logic?.unmount()
})
- it('seeds the handle for a provisioned user when the server reports an active run', async () => {
- setUser(true)
+ it('seeds a run started server-side for the drop-flow signup', async () => {
+ // The provisioned signup is the one account whose run is started server-side, so this
+ // browser never wrote a handle for it and the server answer is the only way to find it.
+ initAs('provisioned', { ...MOCK_DEFAULT_TEAM, completed_snippet_onboarding: false })
mockActiveWizardRun.mockResolvedValue({
task_id: 'srv-task',
run_id: 'srv-run',
@@ -84,44 +123,119 @@ describe('activeCloudRunLogic', () => {
})
})
- it('does not call the server for a non-provisioned user', () => {
- setUser(false)
+ it('never seeds a teammate onto the team run', async () => {
+ // The endpoint is team-scoped and names no creator, so a member who joined mid-onboarding
+ // would otherwise take over whatever the team is running: its task titles, event plan and
+ // errors on their screen, and their Cancel button pointed at it.
+ initAs(null, { ...MOCK_DEFAULT_TEAM, completed_snippet_onboarding: false })
+ mockActiveWizardRun.mockResolvedValue({
+ task_id: 'srv-task',
+ run_id: 'srv-run',
+ status: 'in_progress',
+ started_at: '2026-02-02T00:00:00Z',
+ })
logic = activeCloudRunLogic()
logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
- // Gated before the request — a non-provisioned user never reaches server hydration.
- expect(mockActiveWizardRun).not.toHaveBeenCalled()
expect(logic.values.activeCloudRun).toBeNull()
+ // Nothing this member can do with the answer, so it does not cost a request either.
+ expect(mockActiveWizardRun).not.toHaveBeenCalled()
})
- it('hydrates once the provisioned status loads after mount', async () => {
- // The user (and so isProvisionedUser) resolves asynchronously; mounting before it does
- // must not permanently skip the one server lookup — the original one-shot afterMount did.
+ it('spends no request on mount for a finished-onboarding team holding no handle', async () => {
+ // This logic is mounted app-wide, so without the gate every authenticated pageload in the
+ // product would cost one request to an endpoint that can only answer "nothing here".
+ mockActiveWizardRun.mockResolvedValue(undefined)
+ logic = activeCloudRunLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockActiveWizardRun).not.toHaveBeenCalled()
+ })
+
+ it('reconciles a handle held by a team that already finished onboarding', async () => {
+ // The gate is about what a request can achieve, not about who the user is: a handle
+ // always needs checking, whatever the team's onboarding state.
+ mockActiveWizardRun.mockResolvedValue(undefined)
+ logic = activeCloudRunLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockActiveWizardRun).not.toHaveBeenCalled()
+
+ logic.actions.setActiveCloudRun('task-1', 'run-1', RUN_STARTED_AT, MOCK_TEAM_ID)
+
+ await expectLogic(logic).toDispatchActions(['hydrateFromServer', 'clearActiveCloudRun'])
+ })
+
+ it('reconciles again when the tab becomes visible, while a handle is held', async () => {
+ // Confirming the same run keeps the handle in place, so the second trigger has something
+ // to check.
mockActiveWizardRun.mockResolvedValue({
- task_id: 'srv-task',
- run_id: 'srv-run',
+ task_id: 'task-1',
+ run_id: 'run-1',
status: 'in_progress',
- started_at: '2026-02-02T00:00:00Z',
+ started_at: RUN_STARTED_AT,
})
logic = activeCloudRunLogic()
logic.mount()
- expect(mockActiveWizardRun).not.toHaveBeenCalled()
+ logic.actions.setActiveCloudRun('task-1', 'run-1', RUN_STARTED_AT, MOCK_TEAM_ID)
+ await expectLogic(logic).toDispatchActions(['hydrateFromServer'])
+ const callsAfterMount = mockActiveWizardRun.mock.calls.length
- setUser(true)
+ document.dispatchEvent(new Event('visibilitychange'))
- await expectLogic(logic).toDispatchActions(['hydrateFromServer', 'setActiveCloudRun'])
- expect(mockActiveWizardRun).toHaveBeenCalledWith(String(MOCK_TEAM_ID))
- expect(logic.values.activeCloudRun).toMatchObject({ taskId: 'srv-task', runId: 'srv-run' })
+ await expectLogic(logic).toDispatchActions(['hydrateFromServer'])
+ expect(mockActiveWizardRun.mock.calls.length).toBe(callsAfterMount + 1)
+ })
+
+ it('spends no request on tab focus without a handle', async () => {
+ mockActiveWizardRun.mockResolvedValue(undefined)
+ logic = activeCloudRunLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ document.dispatchEvent(new Event('visibilitychange'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockActiveWizardRun).not.toHaveBeenCalled()
})
- it('does not clobber a fresher local handle', async () => {
- setUser(true)
- // Even if the server reports a run, a local handle already present must win.
+ it('reconciles on the interval only while a handle is held', () => {
+ jest.useFakeTimers()
+ try {
+ // Confirming the same run keeps the handle, so the interval has something to check.
+ mockActiveWizardRun.mockResolvedValue({
+ task_id: 'task-1',
+ run_id: 'run-1',
+ status: 'in_progress',
+ started_at: RUN_STARTED_AT,
+ })
+ logic = activeCloudRunLogic()
+ logic.mount()
+ const callsAfterMount = mockActiveWizardRun.mock.calls.length
+
+ // No handle: nothing to retire, so the tick must not spend a request.
+ jest.advanceTimersByTime(RECONCILE_INTERVAL_MS)
+ expect(mockActiveWizardRun.mock.calls.length).toBe(callsAfterMount)
+
+ logic.actions.setActiveCloudRun('task-1', 'run-1', RUN_STARTED_AT, MOCK_TEAM_ID)
+ const callsWithHandle = mockActiveWizardRun.mock.calls.length
+ jest.advanceTimersByTime(RECONCILE_INTERVAL_MS)
+ expect(mockActiveWizardRun.mock.calls.length).toBe(callsWithHandle + 1)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('does not swap a held handle for another run the team is running', async () => {
+ // The endpoint answers with the newest onboarding run in the project, whoever started it,
+ // so a teammate's run must not take over this user's surfaces (or their Cancel button).
mockActiveWizardRun.mockResolvedValue({
task_id: 'srv-task',
run_id: 'srv-run',
status: 'in_progress',
- started_at: null,
+ started_at: '2026-04-04T00:00:00Z',
})
logic = activeCloudRunLogic()
logic.mount()
@@ -133,7 +247,6 @@ describe('activeCloudRunLogic', () => {
})
it('cancels the active run and recovers the button once the request settles', async () => {
- setUser(true)
// Server-side hydration confirms the same run, so it must not clear the local handle mid-test.
mockActiveWizardRun.mockResolvedValue({
task_id: 'task-1',
@@ -159,7 +272,6 @@ describe('activeCloudRunLogic', () => {
})
it('recovers the cancel button when the cancel request fails', async () => {
- setUser(true)
mockActiveWizardRun.mockResolvedValue({
task_id: 'task-1',
run_id: 'run-1',
@@ -182,7 +294,6 @@ describe('activeCloudRunLogic', () => {
it('resets an in-flight cancelling state when a new run handle is set', () => {
// The flag belongs to the run it was set for; a new run (startCloudRun or server
// hydration) must start with a usable Cancel button, not one disabled by the old run.
- setUser(true)
mockActiveWizardRun.mockResolvedValue(undefined)
mockRunCancel.mockReturnValue(new Promise(() => {}))
logic = activeCloudRunLogic()
@@ -197,7 +308,6 @@ describe('activeCloudRunLogic', () => {
})
it('does not call the cancel endpoint without an active handle', async () => {
- setUser(true)
mockActiveWizardRun.mockResolvedValue(undefined)
logic = activeCloudRunLogic()
logic.mount()
@@ -209,20 +319,40 @@ describe('activeCloudRunLogic', () => {
})
it('clears a stale local handle when the server reports no active run', async () => {
- // A returning provisioned user whose run finished/was abandoned still has a handle in
- // localStorage. Hydration must reconcile it away, or the install card and FAB keep
- // claiming setup is in flight forever. Mount before the user loads so the seeded handle
- // is in place before the single hydration runs (no mount-time race to reason about).
+ // A returning user whose run finished or was abandoned still has a handle in localStorage.
+ // Reconciliation must retire it, or the install card and FAB keep claiming setup is in
+ // flight forever.
mockActiveWizardRun.mockResolvedValue(undefined)
logic = activeCloudRunLogic()
logic.mount()
logic.actions.setActiveCloudRun('stale-task', 'stale-run', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)
expect(logic.values.activeCloudRun).not.toBeNull()
- setUser(true)
+ logic.actions.hydrateFromServer()
await expectLogic(logic).toDispatchActions(['hydrateFromServer', 'clearActiveCloudRun'])
expect(logic.values.activeCloudRun).toBeNull()
})
+
+ it('does not let an answer about an older run retire the one just started', async () => {
+ // A kickoff can land while a reconcile is in flight. That answer was computed before the
+ // new run existed, so applying its 204 would clear a run that is only just starting.
+ let answer: (value: unknown) => void = () => {}
+ mockActiveWizardRun.mockReturnValue(
+ new Promise((resolve) => {
+ answer = resolve
+ })
+ )
+ logic = activeCloudRunLogic()
+ logic.mount()
+ logic.actions.setActiveCloudRun('old-task', 'old-run', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)
+ logic.actions.hydrateFromServer()
+
+ logic.actions.setActiveCloudRun('new-task', 'new-run', '2026-01-02T00:00:00Z', MOCK_TEAM_ID)
+ answer(undefined)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.activeCloudRun).toMatchObject({ taskId: 'new-task', runId: 'new-run' })
+ })
})
})
diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts
index 929f0a20f057..0a91001b87b7 100644
--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts
+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts
@@ -1,12 +1,18 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { subscriptions } from 'kea-subscriptions'
import { lemonToast } from '@posthog/lemon-ui'
import { projectLogic } from 'scenes/projectLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
+import type { TeamType } from '~/types'
+
import { tasksActiveWizardRunRetrieve, tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'
+import type { WizardCloudRunDTOApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import type { TeamPublicType } from '../../../../types'
export interface CloudRunHandle {
taskId: string
@@ -25,9 +31,42 @@ export function scopedCloudRun(handle: CloudRunHandle | null, currentProjectId:
return handle?.projectId != null && handle.projectId === currentProjectId ? handle : null
}
+// How often the persisted handle is re-checked against the server while one is held. The run stream
+// is the fast path for a run's outcome; this is the backstop for the cases where it never reports
+// one (stream never opened, tab was asleep, the run was ended from somewhere else).
+export const RECONCILE_INTERVAL_MS = 60 * 1000
+
+export type CloudRunReconciliation = 'keep' | 'clear' | 'adopt'
+
+/**
+ * How a server answer reconciles against the persisted handle. The server owns the "is there an
+ * active run" truth (it drops terminal and stale runs), so a 204 retires whatever the client holds.
+ * A payload naming the run we already track settles it in place: terminal or not, its outcome
+ * reaches the surfaces through the run stream, and clearing it here would drop the finished-run
+ * handoff before the user dismissed it.
+ *
+ * Nothing is ever adopted onto a client that already holds a handle, and adoption at all requires
+ * `canAdopt`. The endpoint is TEAM-scoped: it answers with the newest onboarding cloud run anywhere
+ * in the project, whoever started it, and carries no creator. So an unconditional adopt would point
+ * a user's progress surfaces, the wizard-session stream behind them, and their Cancel button at a
+ * run that is not theirs. `canAdopt` is the drop-flow signup (`isProvisionedUser`), the one account
+ * whose run is started server-side and therefore never had a local handle to adopt from.
+ */
+export function reconcileCloudRun(
+ local: CloudRunHandle | null,
+ server: { run_id: string } | null,
+ canAdopt: boolean
+): CloudRunReconciliation {
+ if (!local) {
+ return server && canAdopt ? 'adopt' : 'keep'
+ }
+ return server ? 'keep' : 'clear'
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface activeCloudRunLogicValues {
currentProjectId: number | null // projectLogic
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
isProvisionedUser: boolean // userLogic
activeCloudRun: CloudRunHandle | null
canHydrateFromServer: boolean
@@ -76,7 +115,12 @@ export interface activeCloudRunLogicMeta {
persistedCloudRun: CloudRunHandle | null,
currentProjectId: number | null
) => CloudRunHandle | null
- canHydrateFromServer: (isProvisionedUser: boolean, currentProjectId: number | null) => boolean
+ canHydrateFromServer: (
+ currentProjectId: number | null,
+ currentTeam: TeamPublicType | TeamType | null,
+ activeCloudRun: CloudRunHandle | null,
+ isProvisionedUser: boolean
+ ) => boolean
}
}
@@ -96,11 +140,17 @@ export type activeCloudRunLogicType = MakeLogicType<
* browser — so `activeCloudRun` only surfaces a handle stamped with the current project. Without that
* gate a fresh account inherits the previous account's run and greets the user with a progress widget
* for a run that isn't theirs.
+ *
+ * localStorage is also the only thing keeping the handle alive: nothing else expires it, so it is
+ * reconciled against the server (`hydrateFromServer`). While a handle is held that happens on mount,
+ * whenever the tab becomes visible, and every RECONCILE_INTERVAL_MS, whoever holds it. With no
+ * handle only the mount reconcile runs, and only for the drop-flow signup on a team still in
+ * onboarding, the one case a server answer can seed from.
*/
export const activeCloudRunLogic = kea<activeCloudRunLogicType>([
path(['scenes', 'onboarding', 'activeCloudRunLogic']),
connect(() => ({
- values: [projectLogic, ['currentProjectId'], userLogic, ['isProvisionedUser']],
+ values: [projectLogic, ['currentProjectId'], teamLogic, ['currentTeam'], userLogic, ['isProvisionedUser']],
})),
actions({
setActiveCloudRun: (taskId: string, runId: string, startedAt: string, projectId: number) => ({
@@ -115,8 +165,9 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([
// Last-writer-wins boolean, not a refcount: at most ONE inline view may be mounted at a time,
// or the first unmount un-hides the FAB while the second view is still on screen.
setPanelMounted: (mounted: boolean) => ({ mounted }),
- // Ask the server whether the current project has an active wizard cloud run, seeding the
- // handle when the drop flow started the run server-side (so no local handle was ever written).
+ // Reconcile the persisted handle against the server's view of the project's active wizard
+ // cloud run: seeds a handle the client never wrote (drop-flow signups start the run
+ // server-side) and retires one the server no longer reports.
hydrateFromServer: true,
// Ask the backend to cancel the active run (terminates the workflow and tears down the
// sandbox). The handle is kept: the run stream delivers the terminal `cancelled` status,
@@ -167,13 +218,24 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([
(persistedCloudRun: CloudRunHandle | null, currentProjectId: number | null): CloudRunHandle | null =>
scopedCloudRun(persistedCloudRun, currentProjectId),
],
- // The two inputs hydrateFromServer needs, both of which load asynchronously after mount.
- // We wait for this to flip true rather than firing once on mount, so a run started for a
- // provisioned user before their user/project loaded still gets hydrated.
+ // Whether a reconcile is worth a request, checked as inputs load rather than once on mount,
+ // so a run whose project resolved late still gets reconciled. This logic is mounted app-wide
+ // (the FAB lives in the authenticated shell), so the gate keeps the unconditional pageload
+ // request off the accounts it can do nothing for. A held handle always needs checking,
+ // whoever holds it. With no handle the only thing a request can do is seed one, which is
+ // only ever offered to the drop-flow signup on a team still in onboarding (see
+ // reconcileCloudRun for why adoption is not open to everyone), so nobody else spends one.
canHydrateFromServer: [
- (s) => [s.isProvisionedUser, s.currentProjectId],
- (isProvisionedUser: boolean, currentProjectId: number | null): boolean =>
- isProvisionedUser && currentProjectId != null,
+ (s) => [s.currentProjectId, s.currentTeam, s.activeCloudRun, s.isProvisionedUser],
+ (
+ currentProjectId: number | null,
+ currentTeam: TeamType | null,
+ activeCloudRun: CloudRunHandle | null,
+ isProvisionedUser: boolean
+ ): boolean =>
+ currentProjectId != null &&
+ currentTeam != null &&
+ (activeCloudRun !== null || (isProvisionedUser && !currentTeam.completed_snippet_onboarding)),
],
}),
listeners(({ actions, values }) => ({
@@ -193,53 +255,76 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([
}
},
hydrateFromServer: async () => {
- // The drop flow starts the run server-side, so a freshly-signed-in provisioned user has
- // no localStorage handle. Only they need the extra request; everyone else already has a
- // client-written handle if a run exists.
- if (!values.isProvisionedUser) {
- return
- }
const projectId = values.currentProjectId
if (projectId == null) {
return
}
+ // The handle the answer will be about. A kickoff (or a dismiss) can land while the
+ // request is in flight, and the server was never asked about that run: applying a 204
+ // computed before it existed would retire a run the user just started.
+ const requestedRunId = values.activeCloudRun?.runId ?? null
try {
- // The server owns the "is there an active run" truth (it drops terminal/stale runs),
- // so we reconcile the persisted handle against it — not just seed when empty. Without
- // this a finished or abandoned run leaves a stale handle in localStorage that keeps
- // the install progress card and FAB claiming setup is still in flight forever.
- const handle = await tasksActiveWizardRunRetrieve(String(projectId))
- if (!handle) {
- // 204 → no active run. Clear any stale local handle so we stop showing progress.
- if (values.activeCloudRun) {
- actions.clearActiveCloudRun()
- }
+ const response = await tasksActiveWizardRunRetrieve(String(projectId))
+ if ((values.activeCloudRun?.runId ?? null) !== requestedRunId) {
return
}
- if (values.activeCloudRun) {
- // Server confirms a run and we already hold a handle — keep the local one, it's at
- // least as fresh (client kickoff writes it before the server round-trip resolves).
- return
+ const server = (response as WizardCloudRunDTOApi | undefined) ?? null
+ const decision = reconcileCloudRun(values.activeCloudRun, server, values.isProvisionedUser)
+ if (decision === 'clear') {
+ actions.clearActiveCloudRun()
+ } else if (decision === 'adopt' && server) {
+ actions.setActiveCloudRun(
+ server.task_id,
+ server.run_id,
+ server.started_at ?? new Date().toISOString(),
+ projectId
+ )
}
- actions.setActiveCloudRun(
- handle.task_id,
- handle.run_id,
- handle.started_at ?? new Date().toISOString(),
- projectId
- )
} catch {
- // Best-effort: a failed hydration just means no FAB, same as before.
+ // Best-effort: a failed reconcile leaves the handle exactly as it was.
}
},
})),
subscriptions(({ actions }) => ({
// Fires once on mount (with the current value) and again whenever readiness changes, so
- // hydration runs as soon as both inputs are available — not just if they happened to be
- // ready at mount. hydrateFromServer is idempotent, so a no-op false value is harmless.
+ // hydration runs as soon as the project is available — not just if it happened to be ready at
+ // mount. hydrateFromServer is idempotent, so a no-op false value is harmless.
canHydrateFromServer: (canHydrate: boolean) => {
if (canHydrate) {
actions.hydrateFromServer()
}
},
})),
+ afterMount(({ actions, values, cache }) => {
+ // A run can finish or be cancelled while this tab sits in the background. Opting out of the
+ // disposables pause is what makes this fire at all: a paused listener is detached, so it
+ // would never hear the tab come back.
+ cache.disposables.add(
+ () => {
+ const onVisibilityChange = (): void => {
+ // Guarded like the interval below: with no handle there is nothing to retire,
+ // and a request per tab focus for every account in the app buys nothing the
+ // mount reconcile has not already covered.
+ if (!document.hidden && values.activeCloudRun) {
+ actions.hydrateFromServer()
+ }
+ }
+ document.addEventListener('visibilitychange', onVisibilityChange)
+ return () => document.removeEventListener('visibilitychange', onVisibilityChange)
+ },
+ 'reconcile-on-visible',
+ { pauseOnPageHidden: false }
+ )
+ // Only while a handle is held: with none there is nothing to retire, and a server-side run
+ // reaches the FAB through the mount reconcile anyway. The interval keeps the disposables
+ // pause, so a background tab does not poll.
+ cache.disposables.add(() => {
+ const timer = window.setInterval(() => {
+ if (values.activeCloudRun) {
+ actions.hydrateFromServer()
+ }
+ }, RECONCILE_INTERVAL_MS)
+ return () => window.clearInterval(timer)
+ }, 'reconcile-interval')
+ }),
])