Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@ import { render, screen, waitFor } from '@testing-library/vue'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { nextTick, ref } from 'vue'

import { createI18n } from 'vue-i18n'

import TopbarSubscribeButton from '@/components/topbar/TopbarSubscribeButton.vue'
import enMessages from '@/locales/en/main.json' with { type: 'json' }
import type { BillingStatus } from '@/platform/workspace/api/workspaceApi'
import { useDialogStore } from '@/stores/dialogStore'

import CloudRunButtonWrapper from './CloudRunButtonWrapper.vue'

const mockCanRunWorkflows = ref(true)
const mockIsFreeTier = ref(true)
const mockIsInitialized = ref(true)
const mockBillingStatus = ref<BillingStatus | null>('paid')
const mockSubscriptionTier = ref<string | null>(null)
Expand All @@ -33,6 +38,7 @@ vi.mock<unknown>(
() => mockIsInitialized.value && !mockCanRunWorkflows.value
),
billingStatus: mockBillingStatus,
isFreeTier: mockIsFreeTier,
subscription: computed(() =>
mockSubscriptionTier.value
? { tier: mockSubscriptionTier.value }
Expand All @@ -46,6 +52,17 @@ vi.mock<unknown>(
}
)

vi.mock(import('@/platform/distribution/types'), () => ({
isCloud: true
}))

vi.mock<unknown>(
import('@/platform/cloud/subscription/composables/useSubscriptionDialog'),
() => ({
useSubscriptionDialog: () => ({ showPricingTable: vi.fn() })
})
)

vi.mock<unknown>(import('@/composables/useFeatureFlags'), () => ({
useFeatureFlags: () => ({
flags: {
Expand Down Expand Up @@ -93,12 +110,17 @@ vi.mock<unknown>(

vi.mock<unknown>(
import('@/platform/cloud/subscription/components/SubscribeToRun.vue'),
() => ({
default: {
name: 'SubscribeToRun',
template: '<div data-testid="subscribe-to-run-button" />'
async () => {
const { registerSubscribeToRunPrompt } =
await import('@/platform/cloud/subscription/composables/useSubscribeCtaPresence')
return {
default: {
name: 'SubscribeToRun',
setup: () => registerSubscribeToRunPrompt(),
template: '<div data-testid="subscribe-to-run-button" />'
}
}
})
}
)

function renderWrapper() {
Expand All @@ -113,6 +135,59 @@ describe('CloudRunButtonWrapper', () => {
mockSubscriptionTier.value = null
state.v1PaymentRecovery = true
state.canManageSubscription = true
mockIsFreeTier.value = true
})

describe('one subscribe CTA at a time', () => {
const CtaSurface = {
components: { CloudRunButtonWrapper, TopbarSubscribeButton },
template: '<div><TopbarSubscribeButton /><CloudRunButtonWrapper /></div>'
}

function renderCtaSurface() {
const i18n = createI18n({
legacy: false,
locale: 'en',
messages: { en: enMessages }
})
return render(CtaSurface, { global: { plugins: [i18n] } })
}

it('keeps the topbar CTA on a sales-managed plan, where the prompt never mounts', () => {
mockCanRunWorkflows.value = false
mockSubscriptionTier.value = 'ENTERPRISE'

renderCtaSurface()

expect(
screen.queryByTestId('subscribe-to-run-button')
).not.toBeInTheDocument()
expect(screen.getByTestId('topbar-subscribe-button')).toBeInTheDocument()
})

it('keeps the topbar CTA under payment recovery, where the prompt never mounts', () => {
mockCanRunWorkflows.value = false
mockBillingStatus.value = 'paused'

renderCtaSurface()

expect(
screen.queryByTestId('subscribe-to-run-button')
).not.toBeInTheDocument()
expect(screen.getByTestId('topbar-subscribe-button')).toBeInTheDocument()
})

it('yields the topbar CTA only while the prompt is actually mounted', async () => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): this proves the suppression direction but never the release direction with a real prompt.

The unmount path is only covered in TopbarSubscribeButton.test.ts, where presence is a mocked ref — so the real decrement in useSubscribeCtaPresence is never exercised end to end. That is the failure mode with the worst outcome: a counter that fails to return to 0 hides the Upgrade button permanently, with no test to catch it.

I ran it locally against the real components and it behaves correctly, so this is coverage rather than a defect. It closes cheaply here — flip mockCanRunWorkflows back to true, await nextTick(), and assert the prompt is gone and topbar-subscribe-button is back.

mockCanRunWorkflows.value = false

renderCtaSurface()
await nextTick()

expect(screen.getByTestId('subscribe-to-run-button')).toBeInTheDocument()
expect(
screen.queryByTestId('topbar-subscribe-button')
).not.toBeInTheDocument()
})
})

it('renders the runnable queue button when the subscription is active', () => {
Expand Down
52 changes: 47 additions & 5 deletions src/components/topbar/TopbarSubscribeButton.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { getActivePinia } from 'pinia'
import { nextTick } from 'vue'
import { createI18n } from 'vue-i18n'

import { render, screen } from '@testing-library/vue'
Expand Down Expand Up @@ -27,12 +28,35 @@ vi.mock<unknown>(
})
)

vi.mock<unknown>(import('@/composables/billing/useBillingContext'), () => ({
useBillingContext: vi.fn(() => ({
isFreeTier: { value: true }
}))
const mockState = vi.hoisted(() => ({
holder: null as null | { isFreeTier: boolean; promptMounted: boolean }
}))

vi.mock<unknown>(
import('@/composables/billing/useBillingContext'),
async () => {
const { computed, reactive } = await import('vue')
mockState.holder ??= reactive({ isFreeTier: true, promptMounted: false })
return {
useBillingContext: vi.fn(() => ({
isFreeTier: computed(() => mockState.holder!.isFreeTier)
}))
}
}
)

vi.mock<unknown>(
import('@/platform/cloud/subscription/composables/useSubscribeCtaPresence'),
async () => {
const { computed, reactive } = await import('vue')
mockState.holder ??= reactive({ isFreeTier: true, promptMounted: false })
return {
useSubscribeToRunPromptPresence: () =>
computed(() => mockState.holder!.promptMounted)
}
}
)

vi.mock(import('firebase/app'), () => ({
initializeApp: vi.fn(),
getApp: vi.fn()
Expand Down Expand Up @@ -61,12 +85,30 @@ function renderComponent() {
}

describe('TopbarSubscribeButton', () => {
beforeEach(() => {
mockState.holder!.isFreeTier = true
mockState.holder!.promptMounted = false
})

it('renders on cloud when isFreeTier is true', () => {
mockIsCloud.value = true
renderComponent()
expect(screen.getByTestId('topbar-subscribe-button')).toBeInTheDocument()
})

it('yields while a Run-slot subscribe prompt is mounted, and returns when it unmounts', async () => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: The suite pins the behavior being added but not the invariant being protected.

The three tests cover: renders on cloud when free tier, yields while a prompt is mounted, hides off-cloud. The description makes a stronger promise than that:

modes without the Run slot — builder, Linear without outputs, sales-managed, payment recovery — keep the Upgrade button and never drop to zero CTAs.

Nothing asserts it. And the sales-managed / payment-recovery case is the interesting one, because it's the case where showsSubscribeToRunPrompt is true while CloudRunButtonWrapper deliberately renders the queue button instead — so the prompt never mounts, the counter stays 0, and the topbar must keep showing Upgrade. That's simultaneously the strongest evidence for the mount-presence design and the one path with no test.

The failure mode if it ever regresses is the worst one available here: a free-tier user who can't run and has no subscribe affordance anywhere in the UI. Strictly worse than the duplicate CTA this PR fixes.

Could we add a case that mounts CloudRunButtonWrapper with isSalesManagedPlan (and one with paymentRecoveryLock) and asserts the topbar button is still present? It'd be the executable form of the description's table.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 1c88a84, as a small integration surface rather than wrapper-only tests: TopbarSubscribeButton mounts beside CloudRunButtonWrapper with the real presence composable, and the sales-managed and payment-recovery cases assert the prompt never mounts while the topbar CTA stays — the executable form of the description's table, including the never-zero promise. The yield case runs through real registration too (the SubscribeToRun stub now registers on setup), so the mocked-composable seam you'd otherwise have to trust is gone.

mockIsCloud.value = true
mockState.holder!.promptMounted = true
renderComponent()
expect(
screen.queryByTestId('topbar-subscribe-button')
).not.toBeInTheDocument()

mockState.holder!.promptMounted = false
await nextTick()
expect(screen.getByTestId('topbar-subscribe-button')).toBeInTheDocument()
})

it('hides on non-cloud distribution', () => {
mockIsCloud.value = false
renderComponent()
Expand Down
4 changes: 3 additions & 1 deletion src/components/topbar/TopbarSubscribeButton.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<template>
<Button
v-if="isCloud && isFreeTier"
v-if="isCloud && isFreeTier && !subscribeToRunPromptVisible"
class="mr-2 shrink-0 whitespace-nowrap"
variant="subscribe"
size="sm"
Expand All @@ -14,10 +14,12 @@
<script setup lang="ts">
import Button from '@/components/ui/button/Button.vue'
import { useBillingContext } from '@/composables/billing/useBillingContext'
import { useSubscribeToRunPromptPresence } from '@/platform/cloud/subscription/composables/useSubscribeCtaPresence'
import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog'
import { isCloud } from '@/platform/distribution/types'

const { isFreeTier } = useBillingContext()
const subscribeToRunPromptVisible = useSubscribeToRunPromptPresence()
const subscriptionDialog = useSubscriptionDialog()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low — The two flags settle at different times, so the button can flash. isFreeTier derives from subscription and is populated as soon as fetchStatus() resolves, while showsSubscribeToRunPrompt waits on the context's isInitialized, which only flips after initialize() awaits status/balance/plans together — and resetBillingState() sets isInitialized back to false on every workspace or billing-rail switch. A free-tier user who ultimately cannot run therefore sees the CTA appear and then vanish on load and on each workspace switch; consider also suppressing it while billing is uninitialized.

Raised by 2 of 8 reviewers (claude-opus-5-thinking-max adversarial, claude-opus-5-thinking-max edge-case).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dissolved by the presence fix: the topbar no longer infers from initialization timing at all. Upgrade shows as soon as the tier is known and yields at the moment the prompt mounts — the handoff is a single frame in the same render pass that mounts the prompt, not a window between two async flags settling.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low — This couples topbar visibility to graph contents: showsSubscribeToRunPrompt transitively depends on useFreeTierQuota().freeTierExecutionPermitted, which is false whenever hasInvalidNodes is true (the open graph contains credit-badged API/partner nodes). A free-tier user with full remaining quota loses the topbar CTA merely because the loaded workflow includes an API node, and it toggles as such nodes are added or removed.

Raised by 1 of 8 reviewers (claude-opus-5-thinking-max adversarial).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That coupling is now the rule working as intended rather than a side effect: with credit-badged nodes in the graph, SubscribeToRun genuinely mounts in the Run slot, so the topbar yielding leaves exactly one subscribe CTA — the one adjacent to the blocked action. When the badged nodes leave and the prompt unmounts, Upgrade returns.


function handleClick() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
</template>

<script setup lang="ts">
import { registerSubscribeToRunPrompt } from '@/platform/cloud/subscription/composables/useSubscribeCtaPresence'
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
Expand All @@ -27,6 +28,9 @@ import { isCloud } from '@/platform/distribution/types'
import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI'

const { t } = useI18n()

// Mounting suppresses TopbarSubscribeButton; see useSubscribeCtaPresence
registerSubscribeToRunPrompt()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): this line has an effect outside the component and nothing here says so.

registerSubscribeToRunPrompt() reads as local setup, but mounting this component now suppresses a button in the topbar. A reader of SubscribeToRun.vue has no way to know that, and a reader of TopbarSubscribeButton.vue sees useSubscribeToRunPromptPresence() with no indication of who registers.

The concrete case I'd worry about is Storybook — src/storybook/mocks/useBillingContext.ts exists, so these components are storied, and a story that mounts SubscribeToRun now mutates state shared with the topbar for the rest of that Storybook session. Same for any future surface that renders the prompt outside the Run slot (a preview, an onboarding step, a test harness).

A one-line comment at the call site — something like // Mounting suppresses TopbarSubscribeButton; see useSubscribeCtaPresence — would make the coupling discoverable from the end that causes it, which is the end people refactor from.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the call-site comment in 1c88a84. The Storybook scenario is a fair worry — worth noting the floor from your other comment means a story unmounting cleanly now self-corrects, so the residual risk is a story that keeps the prompt mounted while someone views a topbar story in the same session.

const breakpoints = useBreakpoints(breakpointsTailwind)
const isMdOrLarger = breakpoints.greaterOrEqual('md')

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { computed, onMounted, onUnmounted, ref } from 'vue'

const mountedPrompts = ref(0)

/**
* Registers a mounted Run-slot subscribe prompt for the caller's lifetime.
* The billing flag alone is not evidence a prompt is on screen — builder
* mode unmounts the actionbar, Linear mode needs outputs, and the wrapper
* withholds the prompt for sales-managed and payment-recovery states — so

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit (non-blocking): this docblock's premise does not hold today.

My earlier review checked the three call sites and concluded mounted means on screen. That was true of the call sites and wrong about their ancestors. TopMenuSection.vue:24 hides the whole top-menu-actionbars container with max-h-0 translate-x-8 opacity-0 + inert during agent node selection (agentNodeSelectionStore.ts:91) without unmounting it, while TopbarSubscribeButton sits in the workflow-tabs row (GraphCanvas.vue:17) outside that container.

So for a free-tier workspace that cannot run, entering agent node selection now yields zero subscribe CTAs: the Run-slot prompt is counted but invisible, and the topbar button stands down for it. Before this PR the Upgrade button stayed. I verified this by rendering the topbar button next to a prompt wrapped in opacity-0 max-h-0 inert — the topbar button does not render.

I do not think this blocks: the mode is transient and user-initiated, the user is not being blocked from running at that moment, and everything returns correctly on exit. But the docblock currently argues the mechanism's correctness from an invariant that an ancestor already breaks, so it is worth either narrowing the claim or tracking the gap.

* anything yielding to the prompt must key on real presence.
*/
export function registerSubscribeToRunPrompt() {
onMounted(() => {
mountedPrompts.value += 1
})
onUnmounted(() => {
mountedPrompts.value = Math.max(0, mountedPrompts.value - 1)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit (non-blocking): the floor is unreachable. onUnmounted only fires for a component that mounted, so each decrement is paired with an increment and the counter cannot go negative. The commit subject says the floor is pinned by a test, but there is no test for this composable — the three CTA-surface tests exercise the counter only through the components.

Either drop the Math.max or, if you want it kept as a guard, a direct test of this module would earn it.

})
}

/** Whether any Run-slot subscribe prompt is currently on screen. */
export function useSubscribeToRunPromptPresence() {
return computed(() => mountedPrompts.value > 0)
}
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ describe('CurrentUserPopoverWorkspace', () => {
}
)

it('shows Subscribe instead of Manage plan when payment_failed has no plan', () => {
it('shows the upgrade upsell instead of Manage plan when payment_failed has no plan', () => {
state.billingStatus = 'payment_failed'
state.canAccessSubscriptionFeatures = false
state.canManageSubscription = true
Expand All @@ -340,8 +340,11 @@ describe('CurrentUserPopoverWorkspace', () => {
screen.queryByTestId('manage-plan-menu-item')
).not.toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Subscribe' })
screen.getByTestId('upgrade-to-add-credits-button')
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Subscribe' })
).not.toBeInTheDocument()
})

it('keeps Subscribe hidden on Local after switching to an unsubscribed workspace', async () => {
Expand Down Expand Up @@ -411,7 +414,8 @@ describe('CurrentUserPopoverWorkspace', () => {
expect(screen.getByTestId('add-credits-button')).toBeInTheDocument()
})

it('keeps the upgrade upsell for the Cloud free tier', () => {
it('shows one subscription CTA on the Cloud free tier', () => {
state.canAccessSubscriptionFeatures = false
state.canTopUp = false
state.canSubscribeSelfServe = true

Expand All @@ -421,6 +425,9 @@ describe('CurrentUserPopoverWorkspace', () => {
screen.getByTestId('upgrade-to-add-credits-button')
).toBeInTheDocument()
expect(screen.queryByTestId('add-credits-button')).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Subscribe' })
).not.toBeInTheDocument()
})

it('keeps Resubscribe hidden on Local for a cancelled plan', () => {
Expand All @@ -445,6 +452,7 @@ describe('CurrentUserPopoverWorkspace', () => {
canManageSubscriptionLifecycle: true,
canReactivate: true,
canSubscribeSelfServe: false,
canTopUp: false,
action: 'Resubscribe',
visible: true
},
Expand All @@ -456,6 +464,7 @@ describe('CurrentUserPopoverWorkspace', () => {
canManageSubscriptionLifecycle: false,
canReactivate: false,
canSubscribeSelfServe: false,
canTopUp: false,
action: 'Resubscribe',
visible: false
},
Expand All @@ -467,6 +476,7 @@ describe('CurrentUserPopoverWorkspace', () => {
canManageSubscriptionLifecycle: true,
canReactivate: false,
canSubscribeSelfServe: false,
canTopUp: false,
action: 'Resubscribe',
visible: false
},
Expand All @@ -478,6 +488,7 @@ describe('CurrentUserPopoverWorkspace', () => {
canManageSubscriptionLifecycle: false,
canReactivate: false,
canSubscribeSelfServe: true,
canTopUp: true,
action: 'Subscribe',
visible: true
},
Expand All @@ -489,6 +500,7 @@ describe('CurrentUserPopoverWorkspace', () => {
canManageSubscriptionLifecycle: true,
canReactivate: true,
canSubscribeSelfServe: false,
canTopUp: false,
action: 'Subscribe',
visible: false
}
Expand All @@ -501,6 +513,7 @@ describe('CurrentUserPopoverWorkspace', () => {
canManageSubscriptionLifecycle,
canReactivate,
canSubscribeSelfServe,
canTopUp,
action,
visible
}) => {
Expand All @@ -510,6 +523,7 @@ describe('CurrentUserPopoverWorkspace', () => {
state.canManageSubscriptionLifecycle = canManageSubscriptionLifecycle
state.canReactivatePlan = canReactivate
state.canSubscribeSelfServe = canSubscribeSelfServe
state.canTopUp = canTopUp

renderComponent('team')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,8 @@ const showSubscribeAction = computed(
((isCancelled.value && canReactivatePlan.value) ||
(!canAccessSubscriptionFeatures.value &&
!hasDelinquentSubscription.value &&
canSubscribeSelfServe.value))
canSubscribeSelfServe.value &&
canTopUp.value))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This resolves the reported state correctly, and the gate is safe: both CTAs live inside the same v-if="!accountActionsOnly" block, and when canTopUp is false the upgrade upsell always renders in Subscribe's place, so the count never drops to zero.

Follow-up (not this PR): the cancelled branch is OR'd above this gate, so it still renders two subscription CTAs. With isCancelled && canReactivatePlan plus can_top_up: false and can_subscribe_self_serve: true — a cancelled plan past period end — I get upgrade-to-add-credits and Resubscribe side by side, which is the same duplication class and the same overflow risk. It predates this PR and is not the reported state, so I would rather see it tracked separately than widen this change.

)

const handleOpenUserSettings = () => {
Expand Down
Loading