From 1b06bc8a21bd8e29a47387e3a3c1a8faecfbbf78 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 28 Sep 2026 23:19:32 +0000 Subject: [PATCH] fix(agent): defer the consent offer past the first-run screen instead of dropping it (#18966) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Defers the automatic Agent consent offer while Getting Started owns the screen, then re-offers it in the same session after that ownership ends. The template path keeps first-run ownership across the dismissal-to-tour preview gap, so the consent card cannot open underneath the tour. The first-session entry-button/feature-flag timing question is separate and is not changed here. - Arms the consent retry for `first_run_screen` instead of dropping that offer. - Uses live first-run screen ownership, including pending screen-to-tour handoffs, when deciding whether consent can be shown. - Cancels and releases an in-flight handoff when the authenticated identity changes, preventing the previous account tour or hold from crossing sessions. - Removes the obsolete `firstRunTookScreen` latch. - Keeps failed template loads on Getting Started and removes duplicate no-tour coverage. - `dismissIntoFirstRunTour` snapshots the owner, passes an identity-change cancellation predicate to `beginTour`, and invalidates pending holds at the auth boundary. - Per-call symbols keep concurrent handoff ownership distinct, while `authGeneration` separately invalidates stale continuations across authenticated-session changes. - Bare dismissal releases consent; template selection retains ownership until the tour has either started, declined, or failed. At current head `e93ee8410e`, rebased directly on `main` at `4ff3690047` (eleven-file base-to-head diff): - `pnpm test:unit src/extensions/core/agentPanel.test.ts src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.test.ts src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.test.ts src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts --testTimeout=30000` — 4 files, 226 tests passed. - `bash scripts/test-browser-offline.sh --project=cloud browser_tests/tests/agent/agentConsent.spec.ts -g 'defers the offer until Getting Started releases the screen' --workers=1 --repeat-each=5` — 5/5 passed in 43.2 seconds from a freshly restarted cloud-distribution Vite process; the scenario-only 90-second budget covers both application boots. - ESLint, Oxlint, oxfmt, `git diff --check`, pre-push Knip, and changed-line Fallow passed. Fallow excluded 17 inherited dependency findings and reported two inherited styling advisories. The branch retains the test-only changes from #18977 and #18989. Those PRs were merged into this PR's branch (their GitHub base was `fix/agent-consent-defer-first-run-screen`), not into `main`; dropping them during reconciliation would lose their approved coverage. The rebase preserves the eleven-file product/browser patch while removing the stale `main` ancestry. --------- Co-authored-by: Amp --- .../tests/agent/agentConsent.spec.ts | 28 ++- browser_tests/tests/agent/agentPanelMocks.ts | 26 ++- browser_tests/types/globals.d.ts | 1 + src/extensions/core/agentPanel.test.ts | 67 +++++- src/extensions/core/agentPanel.ts | 22 +- .../GettingStartedScreen.test.ts | 34 +-- .../gettingStarted/GettingStartedScreen.vue | 7 +- .../gettingStarted/firstRunEntry.test.ts | 218 +++++++++++++----- .../gettingStarted/firstRunEntry.ts | 129 +++++++++-- .../tour/useFirstRunTourController.ts | 140 ++++++++++- 10 files changed, 540 insertions(+), 132 deletions(-) diff --git a/browser_tests/tests/agent/agentConsent.spec.ts b/browser_tests/tests/agent/agentConsent.spec.ts index a3a407d5624..ee41d1a7461 100644 --- a/browser_tests/tests/agent/agentConsent.spec.ts +++ b/browser_tests/tests/agent/agentConsent.spec.ts @@ -528,6 +528,7 @@ test.describe( { tag: ['@cloud', '@ui'] }, () => { test.use({ + agentAutoShownReadProbe: true, agentConsentAccepted: false, initialSettings: { 'Comfy.TutorialCompleted': false }, initialFeatureFlags: { @@ -535,13 +536,16 @@ test.describe( subscription_required: true } }) + test.describe.configure({ timeout: 90_000 }) - test('stays silent for the session once Getting Started took the screen', async ({ + test('defers the offer until Getting Started releases the screen', async ({ comfyPage, agentPanel, - agentConsentReads + agentConsentWrites }) => { const page = comfyPage.page + const autoShownKey = + 'Comfy.AgentConsent.AutoShown.test-user-e2e.ws-personal' const gettingStarted = page.getByRole('dialog', { name: enMessages.gettingStarted.title }) @@ -553,24 +557,28 @@ test.describe( await expect(gettingStarted).toBeVisible() }) - await test.step('The automatic offer runs and stays silent', async () => { + await test.step('The automatic offer waits without spending its one-time attempt', async () => { await expect - .poll(() => agentConsentReads.length, { + .poll(() => page.evaluate(() => window.__autoShownReads ?? 0), { message: - 'the automatic offer runs once the consent read and the boot decision are both in; the fixture already waited past the decision (the loading overlay clears after it), so the read is the last input and the silence below is a decision, not a race', + 'the held-offer decision reads the unspent one-shot marker', timeout: 15_000 }) .toBeGreaterThan(0) await expect(consent).toHaveCount(0) await expect(agentPanel.root).toHaveCount(0) expect( - await page.evaluate(() => - localStorage.getItem( - 'Comfy.AgentConsent.AutoShown.test-user-e2e.ws-personal' - ) - ) + await page.evaluate((key) => localStorage.getItem(key), autoShownKey) ).toBeNull() }) + + await test.step('Taking the blank canvas presents the deferred offer', async () => { + await page.getByTestId('getting-started-blank').click() + await expect(gettingStarted).toHaveCount(0) + await expect(consent).toBeVisible() + await expect(agentPanel.root).toHaveCount(0) + expect(agentConsentWrites).toHaveLength(0) + }) }) } ) diff --git a/browser_tests/tests/agent/agentPanelMocks.ts b/browser_tests/tests/agent/agentPanelMocks.ts index 996aea189d4..6a87ca36077 100644 --- a/browser_tests/tests/agent/agentPanelMocks.ts +++ b/browser_tests/tests/agent/agentPanelMocks.ts @@ -155,6 +155,7 @@ async function mockAgentBoot( agentConsentReads, agentConsentSave, agentConsentWrites, + agentAutoShownReadProbe, agentFlagEnabled, agentPanelInitiallyOpen, agentOnboardingCompleted, @@ -174,7 +175,23 @@ async function mockAgentBoot( let consentAccepted = agentConsentAccepted await page.addInitScript( - ({ initiallyOpen, onboardingCompleted, debugEnabled }) => { + ({ + initiallyOpen, + onboardingCompleted, + debugEnabled, + autoShownReadProbe + }) => { + if (autoShownReadProbe) { + const autoShownKey = + 'Comfy.AgentConsent.AutoShown.test-user-e2e.ws-personal' + const originalGetItem = Storage.prototype.getItem + window.__autoShownReads = 0 + Storage.prototype.getItem = function (candidate: string) { + if (candidate === autoShownKey) + window.__autoShownReads = (window.__autoShownReads ?? 0) + 1 + return originalGetItem.call(this, candidate) + } + } if (localStorage.getItem('Comfy.AgentPanel.open') === null) { localStorage.setItem('Comfy.AgentPanel.open', String(initiallyOpen)) } @@ -192,7 +209,8 @@ async function mockAgentBoot( { initiallyOpen: agentPanelInitiallyOpen, onboardingCompleted: agentOnboardingCompleted, - debugEnabled: crdtDebugEnabled + debugEnabled: crdtDebugEnabled, + autoShownReadProbe: agentAutoShownReadProbe } ) @@ -388,6 +406,7 @@ async function mockAgentBoot( } type AgentFixtures = { + agentAutoShownReadProbe: boolean agentConsentAccepted: boolean agentConsentReads: boolean[] agentConsentSave: { status: number; pending?: Promise } @@ -404,6 +423,7 @@ type AgentFixtures = { } export const agentTest = comfyPageFixture.extend({ + agentAutoShownReadProbe: [false, { option: true }], agentConsentAccepted: [true, { option: true }], agentConsentReads: async ({ agentFlagEnabled: _agentFlagEnabled }, use) => { await use([]) @@ -425,6 +445,7 @@ export const agentTest = comfyPageFixture.extend({ objectInfo: [undefined, { option: true }], page: async ( { + agentAutoShownReadProbe, agentConsentAccepted, agentConsentReads, agentConsentSave, @@ -444,6 +465,7 @@ export const agentTest = comfyPageFixture.extend({ testInfo ) => { await mockAgentBoot(page, { + agentAutoShownReadProbe, agentConsentAccepted, agentConsentReads, agentConsentSave, diff --git a/browser_tests/types/globals.d.ts b/browser_tests/types/globals.d.ts index 9d79f8e59cb..4c8ca29d316 100644 --- a/browser_tests/types/globals.d.ts +++ b/browser_tests/types/globals.d.ts @@ -49,6 +49,7 @@ declare global { __commandExecutionCounts?: Record // Feature flags test globals + __autoShownReads?: number __capturedMessages?: CapturedMessages __appReadiness?: AppReadiness diff --git a/src/extensions/core/agentPanel.test.ts b/src/extensions/core/agentPanel.test.ts index b818da950db..fa4e7b85b8c 100644 --- a/src/extensions/core/agentPanel.test.ts +++ b/src/extensions/core/agentPanel.test.ts @@ -37,15 +37,41 @@ let consentStore: ReturnType let workspaceStore: ReturnType const currentUser = ref<{ id: string } | null>({ id: 'account-a' }) -const firstRunTookScreen = ref(false) +const isAuthInitialized = ref(true) +type FirstRunScreenState = 'released' | 'visible' | 'handoff' +const firstRunScreenState = ref('released') +const gettingStartedVisible = computed( + () => firstRunScreenState.value === 'visible' +) +const firstRunHoldsScreen = computed( + () => firstRunScreenState.value !== 'released' +) +const firstRunTookScreen = computed({ + get: () => firstRunHoldsScreen.value, + set: (value: boolean) => { + firstRunScreenState.value = value ? 'visible' : 'released' + } +}) const activeTour = ref(null) let startupDecision: Promise = Promise.resolve(true) +function showFirstRunScreen(): void { + firstRunScreenState.value = 'visible' +} + +function releaseFirstRunScreen(): void { + firstRunScreenState.value = 'released' +} + +function beginFirstRunScreenHandoff(): void { + firstRunScreenState.value = 'handoff' +} + vi.mock(import('@/composables/auth/useCurrentUser'), () => ({ useCurrentUser: () => fromPartial>({ resolvedUserInfo: currentUser, - isAuthInitialized: computed(() => true), + isAuthInitialized, isLoggedIn: computed(() => currentUser.value !== null) }) })) @@ -84,7 +110,8 @@ vi.mock( () => ({ useFirstRunEntry: () => fromPartial>({ - firstRunTookScreen, + gettingStartedVisible, + firstRunHoldsScreen, whenStartupDecided: () => startupDecision }) }) @@ -183,7 +210,7 @@ describe('AgentPanel extension flag gate', () => { agentStore.isOpen = true agentFlagEnabled.value = false agentFlagEnabled.value = false - firstRunTookScreen.value = false + releaseFirstRunScreen() activeTour.value = null startupDecision = Promise.resolve(true) vi.spyOn(useOnboardingTourStore(), 'activeTour', 'get').mockImplementation( @@ -345,6 +372,38 @@ describe('AgentPanel extension flag gate', () => { } ) + it('offers in the same session once the Getting Started screen closes', async () => { + agentFlagEnabled.value = true + showFirstRunScreen() + Object.assign(consentStore, { accepted: false, isChecking: false }) + + await loadEntryAndSetup() + await flush() + expect(useAgentConsent().withConsent).not.toHaveBeenCalled() + + releaseFirstRunScreen() + await vi.waitFor(() => + expect(useAgentConsent().withConsent).toHaveBeenCalledOnce() + ) + }) + + it('keeps waiting across the Getting Started to tour handoff', async () => { + agentFlagEnabled.value = true + showFirstRunScreen() + Object.assign(consentStore, { accepted: false, isChecking: false }) + + await loadEntryAndSetup() + await flush() + beginFirstRunScreenHandoff() + await flush() + expect(useAgentConsent().withConsent).not.toHaveBeenCalled() + + activeTour.value = 'firstRun' + releaseFirstRunScreen() + await flush() + expect(useAgentConsent().withConsent).not.toHaveBeenCalled() + }) + it('offers when neither Getting Started took the screen nor a tour is active', async () => { agentFlagEnabled.value = true Object.assign(consentStore, { accepted: false, isChecking: false }) diff --git a/src/extensions/core/agentPanel.ts b/src/extensions/core/agentPanel.ts index fd6fc0663de..77504c1424b 100644 --- a/src/extensions/core/agentPanel.ts +++ b/src/extensions/core/agentPanel.ts @@ -1,5 +1,6 @@ +import { whenever } from '@vueuse/core' import { storeToRefs } from 'pinia' -import { watch } from 'vue' +import { computed, ref, watch } from 'vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useFeatureFlags } from '@/composables/useFeatureFlags' @@ -172,7 +173,7 @@ export function registerAgentPanelExtension(): void { const { resolvedUserInfo, isAuthInitialized, isLoggedIn } = useCurrentUser() const { withConsent } = useAgentConsent() - const { firstRunTookScreen, whenStartupDecided } = useFirstRunEntry() + const { firstRunHoldsScreen, whenStartupDecided } = useFirstRunEntry() const onboardingTourStore = useOnboardingTourStore() registerWorkflowTabActivityTracker(enabled) @@ -185,13 +186,15 @@ export function registerAgentPanelExtension(): void { ) const screenHolder = (): AgentConsentNotOfferedReason | null => - firstRunTookScreen.value + firstRunHoldsScreen.value ? 'first_run_screen' : onboardingTourStore.activeTour !== null ? 'tour_active' : null + const screenIsClear = computed(() => screenHolder() === null) const reportedWithheld = new Set() + const offerHeld = ref(false) const withholdOffer = ( reason: AgentConsentNotOfferedReason, userId = resolvedUserInfo.value?.id, @@ -222,6 +225,7 @@ export function registerAgentPanelExtension(): void { const held = screenHolder() if (held) { withholdOffer(held) + offerHeld.value = true return } @@ -247,7 +251,10 @@ export function registerAgentPanelExtension(): void { }, canShow: () => { const heldAtMount = screenHolder() - if (heldAtMount) withholdOffer(heldAtMount, userId, workspaceId) + if (heldAtMount) { + withholdOffer(heldAtMount, userId, workspaceId) + offerHeld.value = true + } return heldAtMount === null } } @@ -290,6 +297,13 @@ export function registerAgentPanelExtension(): void { loadConsentIfEligible, { immediate: true } ) + whenever( + () => offerHeld.value && screenIsClear.value, + () => { + offerHeld.value = false + loadConsentIfEligible() + } + ) watch( () => onboardingTourStore.activeTour, (tour) => { diff --git a/src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.test.ts b/src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.test.ts index 627ca7963c9..edbfa512832 100644 --- a/src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.test.ts +++ b/src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.test.ts @@ -15,7 +15,7 @@ import { CURATED_TEMPLATE_IDS, FALLBACK_TEMPLATE_IDS } from './tutorialCards' const mocks = vi.hoisted(() => ({ dismiss: vi.fn(), - beginTour: vi.fn(), + dismissIntoTour: vi.fn(), loadTemplate: vi.fn['loadWorkflowTemplate']>(), @@ -23,11 +23,10 @@ const mocks = vi.hoisted(() => ({ })) vi.mock(import('./firstRunEntry'), () => ({ - useFirstRunEntry: () => ({ dismissGettingStarted: mocks.dismiss }) -})) - -vi.mock(import('../tour/useFirstRunTourController'), () => ({ - useFirstRunTourController: () => ({ beginTour: mocks.beginTour }) + useFirstRunEntry: () => ({ + dismissGettingStarted: mocks.dismiss, + dismissIntoFirstRunTour: mocks.dismissIntoTour + }) })) vi.mock( @@ -95,7 +94,7 @@ describe('GettingStartedScreen', () => { vi.mocked( useWorkflowTemplatesStore().loadWorkflowTemplates ).mockResolvedValue(undefined) - mocks.beginTour.mockResolvedValue(true) + mocks.dismissIntoTour.mockResolvedValue(undefined) mocks.loadingTemplateId.value = null }) @@ -116,8 +115,8 @@ describe('GettingStartedScreen', () => { 'default' ) ) - expect(mocks.beginTour).toHaveBeenCalledWith(CURATED_TEMPLATE_IDS[0]) - expect(mocks.dismiss).toHaveBeenCalled() + expect(mocks.dismissIntoTour).toHaveBeenCalledWith(CURATED_TEMPLATE_IDS[0]) + expect(mocks.dismiss).not.toHaveBeenCalled() }) it('ignores a second pick while one is still loading', async () => { @@ -134,21 +133,8 @@ describe('GettingStartedScreen', () => { ).not.toHaveBeenCalled() }) - it('leaves the user on the loaded graph when the template has no tour', async () => { - mocks.beginTour.mockResolvedValue(false) - await renderScreen() - - await pickFirstTemplate() - - await waitFor(() => expect(mocks.beginTour).toHaveBeenCalled()) - expect( - mocks.dismiss, - 'the graph is loaded and usable, so the takeover must not strand the user on it' - ).toHaveBeenCalled() - }) - it('keeps the click handler from rejecting when the tour cannot start', async () => { - mocks.beginTour.mockRejectedValue(new Error('tour unavailable')) + mocks.dismissIntoTour.mockRejectedValue(new Error('tour unavailable')) const rejections: unknown[] = [] const onRejection = (reason: unknown) => rejections.push(reason) process.on('unhandledRejection', onRejection) @@ -157,7 +143,7 @@ describe('GettingStartedScreen', () => { await pickFirstTemplate() - await waitFor(() => expect(mocks.beginTour).toHaveBeenCalled()) + await waitFor(() => expect(mocks.dismissIntoTour).toHaveBeenCalled()) await new Promise((resolve) => setImmediate(resolve)) process.off('unhandledRejection', onRejection) diff --git a/src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.vue b/src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.vue index e43568f2f29..59c0e7768c0 100644 --- a/src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.vue +++ b/src/renderer/extensions/firstRunTour/gettingStarted/GettingStartedScreen.vue @@ -137,7 +137,6 @@ import { useDialogStore } from '@/stores/dialogStore' import GettingStartedCard from './GettingStartedCard.vue' import GettingStartedTemplateCard from './GettingStartedTemplateCard.vue' -import { useFirstRunTourController } from '../tour/useFirstRunTourController' import { useFirstRunEntry } from './firstRunEntry' import type { TutorialCard } from './tutorialCards' import { @@ -164,8 +163,7 @@ const tabs = [ const { t } = useI18n() -const { dismissGettingStarted } = useFirstRunEntry() -const { beginTour } = useFirstRunTourController() +const { dismissGettingStarted, dismissIntoFirstRunTour } = useFirstRunEntry() const templatesStore = useWorkflowTemplatesStore() const dialogStore = useDialogStore() @@ -236,9 +234,8 @@ async function onSelectTemplate(id: string) { const result = await loadWorkflowTemplate(id, 'default') if (result === 'loaded') { - await dismissGettingStarted() try { - await beginTour(id) + await dismissIntoFirstRunTour(id) } catch (error) { console.error('first-run tour failed to start', error) } diff --git a/src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.test.ts b/src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.test.ts index 7763af45da7..4fc2e574879 100644 --- a/src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.test.ts +++ b/src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.test.ts @@ -1,8 +1,9 @@ import { useSettingStore } from '@/platform/settings/settingStore' +import { useAuthStore } from '@/stores/authStore' import { useCommandStore } from '@/stores/commandStore' import { fromAny } from '@total-typescript/shoehorn' import * as VueUse from '@vueuse/core' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import { computed } from 'vue' import { useFeatureFlags } from '@/composables/useFeatureFlags' @@ -16,13 +17,15 @@ const mocks = vi.hoisted<{ subscriptionEnabled: boolean isNewUser: boolean | null beginTour: ReturnType + cancelPendingStart: ReturnType }>(() => ({ isCloud: true, isDesktopWidth: true, subscriptionEnabled: true, isNewUser: true, - beginTour: vi.fn() + beginTour: vi.fn(), + cancelPendingStart: vi.fn(async () => {}) })) const sharedComposable = vi.hoisted(() => { @@ -46,6 +49,19 @@ vi.mock(import('@/platform/distribution/types'), () => ({ })) vi.mock(import('@vueuse/core'), { spy: true }) +vi.mock(import('@comfyorg/account-core/customerRecovery'), () => ({ + fetchWithCustomerRecovery: vi.fn() +})) +vi.mock(import('@comfyorg/account-core/provisioning'), () => ({ + signUpWithProvisioning: vi.fn(), + socialSignInWithProvisioning: vi.fn() +})) +vi.mock(import('@/platform/auth/firebaseIdentity'), () => ({ + firebaseIdentity: { + onUserChanged: vi.fn(), + onTokenChanged: vi.fn() + } +})) vi.mocked(VueUse.createSharedComposable).mockImplementation( sharedComposable.create ) @@ -68,7 +84,10 @@ vi.mock(import('@/platform/telemetry/reportError'), () => ({ reportError: vi.fn() })) vi.mock(import('../tour/useFirstRunTourController'), () => ({ - useFirstRunTourController: () => ({ beginTour: mocks.beginTour }) + useFirstRunTourController: () => ({ + beginTour: mocks.beginTour, + cancelPendingStart: mocks.cancelPendingStart + }) })) const { useFirstRunEntry } = await import('./firstRunEntry') @@ -90,6 +109,10 @@ describe('useFirstRunEntry', () => { mocks.isDesktopWidth = true mocks.subscriptionEnabled = true mocks.isNewUser = true + Object.assign(useAuthStore(), { + currentUser: fromAny({ uid: 'account-a' }) + }) + mocks.cancelPendingStart.mockClear() vi.mocked(useFeatureFlags().flags).onboardingTourEnabled = true useSettingStore().settingValues = {} vi.mocked(useSettingStore().set).mockImplementation(async (key, value) => { @@ -119,52 +142,6 @@ describe('useFirstRunEntry', () => { ] as const describe('what the boot reports to surfaces that must yield to it', () => { - it('records that Getting Started took the screen', async () => { - const entry = useFirstRunEntry() - - await entry.handleStartupOutcome('fresh') - - expect(entry.firstRunTookScreen.value).toBe(true) - }) - - it('records that a url-intent tour took the screen', async () => { - const entry = useFirstRunEntry() - - await entry.handleStartupOutcome('url-intent') - await entry.handleUrlWorkflow('url-intent', 'image_z_image_turbo') - - expect(entry.firstRunTookScreen.value).toBe(true) - }) - - it.for([ - { - label: 'restored work', - boot: async (entry: FirstRunEntry) => - entry.handleStartupOutcome('restored') - }, - { - label: 'a boot that only deferred', - boot: async (entry: FirstRunEntry) => { - mocks.isDesktopWidth = false - await entry.handleStartupOutcome('fresh') - } - }, - { - label: 'a url-intent boot whose tour did not start', - boot: async (entry: FirstRunEntry) => { - mocks.beginTour.mockResolvedValue(false) - await entry.handleStartupOutcome('url-intent') - await entry.handleUrlWorkflow('url-intent', 'image_z_image_turbo') - } - } - ])('reports no first-run screen for $label', async ({ boot }) => { - const entry = useFirstRunEntry() - - await boot(entry) - - expect(entry.firstRunTookScreen.value).toBe(false) - }) - it('settles a url-intent boot only once the url stage has run', async () => { const entry = useFirstRunEntry() let decided: boolean | undefined @@ -243,12 +220,10 @@ describe('useFirstRunEntry', () => { ) await new Promise((resolve) => setTimeout(resolve)) expect(decided).toBeUndefined() - expect(entry.firstRunTookScreen.value).toBe(false) start(true) await urlStage await vi.waitFor(() => expect(decided).toBe(true)) - expect(entry.firstRunTookScreen.value).toBe(true) }) it('settles the startup decision even when the tour fails to start', async () => { @@ -261,7 +236,6 @@ describe('useFirstRunEntry', () => { ).rejects.toThrow('offline') await expect(entry.whenStartupDecided()).resolves.toBe(true) - expect(entry.firstRunTookScreen.value).toBe(false) }) it('gives up with false only once the grace period has fully passed', async () => { @@ -671,4 +645,144 @@ describe('useFirstRunEntry', () => { level: 'warning' }) }) + + describe('handing the screen over to the first-run tour', () => { + it('hides the screen before it asks for the tour', async () => { + const entry = useFirstRunEntry() + mocks.beginTour.mockImplementation(async () => { + expect(entry.gettingStartedVisible.value).toBe(false) + return true + }) + await entry.handleStartupOutcome('fresh') + + await entry.dismissIntoFirstRunTour('image_z_image_turbo') + + expect(mocks.beginTour).toHaveBeenCalledOnce() + }) + + it('holds the screen across the handoff, from the dismissal until the tour opens', async () => { + let finishTour: ((started: boolean) => void) | undefined + mocks.beginTour.mockImplementation( + () => + new Promise((resolve) => { + finishTour = resolve + }) + ) + const entry = useFirstRunEntry() + await entry.handleStartupOutcome('fresh') + + const handoff = entry.dismissIntoFirstRunTour('image_z_image_turbo') + await vi.waitFor(() => expect(finishTour).toBeTypeOf('function')) + + expect(entry.gettingStartedVisible.value).toBe(false) + expect(entry.firstRunHoldsScreen.value).toBe(true) + + assert.exists(finishTour) + finishTour(true) + await handoff + expect(entry.firstRunHoldsScreen.value).toBe(false) + }) + + it('releases the screen when the handoff produces no tour', async () => { + const entry = useFirstRunEntry() + mocks.beginTour.mockResolvedValue(false) + await entry.handleStartupOutcome('fresh') + + await entry.dismissIntoFirstRunTour('image_z_image_turbo') + + expect(entry.firstRunHoldsScreen.value).toBe(false) + }) + + it('releases the screen when the tour throws', async () => { + const entry = useFirstRunEntry() + mocks.beginTour.mockRejectedValue(new Error('tour unavailable')) + await entry.handleStartupOutcome('fresh') + + await expect( + entry.dismissIntoFirstRunTour('image_z_image_turbo') + ).rejects.toThrow('tour unavailable') + + expect(entry.firstRunHoldsScreen.value).toBe(false) + }) + + it('cancels a deferred handoff across an account round trip', async () => { + let finishDismissal: (() => void) | undefined + vi.mocked(useSettingStore().set).mockImplementation( + () => + new Promise((resolve) => { + finishDismissal = resolve + }) + ) + const entry = useFirstRunEntry() + await entry.handleStartupOutcome('fresh') + + const handoff = entry.dismissIntoFirstRunTour('image_z_image_turbo') + await vi.waitFor(() => expect(finishDismissal).toBeTypeOf('function')) + Object.assign(useAuthStore(), { userId: 'account-b' }) + Object.assign(useAuthStore(), { userId: 'account-a' }) + assert.exists(finishDismissal) + finishDismissal() + await handoff + + expect(mocks.beginTour).not.toHaveBeenCalled() + }) + + it('releases a pending handoff hold at the account boundary', async () => { + let finishTour: ((started: boolean) => void) | undefined + mocks.beginTour.mockImplementation( + () => + new Promise((resolve) => { + finishTour = resolve + }) + ) + const entry = useFirstRunEntry() + await entry.handleStartupOutcome('fresh') + + const handoff = entry.dismissIntoFirstRunTour('image_z_image_turbo') + await vi.waitFor(() => expect(mocks.beginTour).toHaveBeenCalled()) + expect(entry.firstRunHoldsScreen.value).toBe(true) + + Object.assign(useAuthStore(), { userId: 'account-b' }) + + expect(entry.firstRunHoldsScreen.value).toBe(false) + expect(mocks.cancelPendingStart).toHaveBeenCalled() + assert.exists(finishTour) + finishTour(false) + await handoff + expect(entry.firstRunHoldsScreen.value).toBe(false) + }) + + it("keeps account B's hold when account A's stale handoff completes", async () => { + const finishTours: Array<(started: boolean) => void> = [] + mocks.beginTour.mockImplementation( + () => + new Promise((resolve) => { + finishTours.push(resolve) + }) + ) + const entry = useFirstRunEntry() + await entry.handleStartupOutcome('fresh') + + const accountAHandoff = entry.dismissIntoFirstRunTour( + 'image_z_image_turbo' + ) + await vi.waitFor(() => expect(finishTours).toHaveLength(1)) + Object.assign(useAuthStore(), { userId: 'account-b' }) + const accountBHandoff = entry.dismissIntoFirstRunTour( + 'image_z_image_turbo' + ) + await vi.waitFor(() => expect(finishTours).toHaveLength(2)) + + const [finishAccountA, finishAccountB] = finishTours + assert.exists(finishAccountA) + finishAccountA(false) + await accountAHandoff + expect(entry.firstRunHoldsScreen.value).toBe(true) + + assert.exists(finishAccountB) + finishAccountB(false) + await accountBHandoff + expect(entry.firstRunHoldsScreen.value).toBe(false) + }) + }) }) diff --git a/src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.ts b/src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.ts index 7b61bb01e26..b4768f9c414 100644 --- a/src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.ts +++ b/src/renderer/extensions/firstRunTour/gettingStarted/firstRunEntry.ts @@ -4,16 +4,18 @@ import { until, useBreakpoints } from '@vueuse/core' -import { readonly, ref } from 'vue' +import { computed, ref, watch } from 'vue' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription' import { isCloud } from '@/platform/distribution/types' +import { useOnboardingTourStore } from '@/platform/onboarding/onboardingTourStore' import { useSettingStore } from '@/platform/settings/settingStore' import { reportError } from '@/platform/telemetry/reportError' import type { StartupOutcome } from '@/platform/workflow/persistence/base/draftTypes' import type { SharedWorkflowUrlLoadStatus } from '@/platform/workflow/sharing/composables/useSharedWorkflowUrlLoader' import { useNewUserService } from '@/services/useNewUserService' +import { useAuthStore } from '@/stores/authStore' import { useCommandStore } from '@/stores/commandStore' import { useFirstRunTourController } from '../tour/useFirstRunTourController' @@ -21,24 +23,94 @@ import { useFirstRunTourController } from '../tour/useFirstRunTourController' /** Waiters give up after this; a healthy boot settles well inside it. */ const STARTUP_DECISION_TIMEOUT_MS = 60_000 -/** - * Decides what a first-time user sees once startup reports its outcome: the - * Getting Started screen for first-run tour candidates, the template browser - * for everyone else. - */ +type FirstRunScreenState = + | { phase: 'released' } + | { phase: 'visible' } + | { phase: 'handoff'; handoffs: ReadonlySet } + +type FirstRunScreenEvent = + | { type: 'shown' } + | { type: 'dismissed' } + | { type: 'released' } + | { type: 'handoffStarted'; ownership: symbol } + | { type: 'handoffFinished'; ownership: symbol } + +function finishFirstRunHandoff( + state: FirstRunScreenState, + ownership: symbol +): FirstRunScreenState { + if (state.phase !== 'handoff' || !state.handoffs.has(ownership)) return state + const handoffs = new Set(state.handoffs) + handoffs.delete(ownership) + return handoffs.size === 0 + ? { phase: 'released' } + : { phase: 'handoff', handoffs } +} + +function transitionFirstRunScreen( + state: FirstRunScreenState, + event: FirstRunScreenEvent +): FirstRunScreenState { + switch (event.type) { + case 'shown': + return { phase: 'visible' } + case 'dismissed': + return state.phase === 'visible' ? { phase: 'released' } : state + case 'released': + return { phase: 'released' } + case 'handoffStarted': + return { + phase: 'handoff', + handoffs: new Set([ + ...(state.phase === 'handoff' ? state.handoffs : []), + event.ownership + ]) + } + case 'handoffFinished': + return finishFirstRunHandoff(state, event.ownership) + } +} + export const useFirstRunEntry = createSharedComposable(() => { + const authStore = useAuthStore() const settingStore = useSettingStore() - const gettingStartedVisible = ref(false) + const firstRunScreen = ref({ phase: 'released' }) const startupDecided = ref(false) - const firstRunTookScreen = ref(false) + let authGeneration = 0 const isDesktopWidth = useBreakpoints(breakpointsTailwind).greaterOrEqual('md') - /** - * `defer` is ineligibility a later boot can lift — the tour flag, the - * viewport, remote config that has not arrived. `Comfy.TutorialCompleted` is - * write-once and server-side, so only `complete` may set it. - */ + const gettingStartedVisible = computed( + () => firstRunScreen.value.phase === 'visible' + ) + const firstRunHoldsScreen = computed( + () => firstRunScreen.value.phase !== 'released' + ) + + function dispatchFirstRunScreen(event: FirstRunScreenEvent): void { + firstRunScreen.value = transitionFirstRunScreen(firstRunScreen.value, event) + } + + watch( + () => authStore.userId, + (userId, previousUserId) => { + if (previousUserId === undefined || userId === previousUserId) return + authGeneration++ + dispatchFirstRunScreen({ type: 'released' }) + void useFirstRunTourController() + .cancelPendingStart() + .catch((error) => + reportError(error, { + errorType: 'failure_restoring_first_run_renderer_setting', + level: 'warning' + }) + ) + const tourStore = useOnboardingTourStore() + if (tourStore.activeTour === 'firstRun') tourStore.postpone() + }, + { flush: 'sync' } + ) + type FirstRunDecision = 'getting-started' | 'defer' | 'complete' function decideFirstRun(): FirstRunDecision { @@ -81,8 +153,7 @@ export const useFirstRunEntry = createSharedComposable(() => { } if (decision === 'getting-started') { - gettingStartedVisible.value = true - firstRunTookScreen.value = true + dispatchFirstRunScreen({ type: 'shown' }) return } @@ -114,7 +185,6 @@ export const useFirstRunEntry = createSharedComposable(() => { shareLoaded ? undefined : templateId ) if (!started) return - firstRunTookScreen.value = true await markTutorialCompleted() } finally { startupDecided.value = true @@ -145,16 +215,35 @@ export const useFirstRunEntry = createSharedComposable(() => { } async function dismissGettingStarted() { - gettingStartedVisible.value = false + dispatchFirstRunScreen({ type: 'dismissed' }) await markTutorialCompleted() } + async function dismissIntoFirstRunTour(templateId: string): Promise { + const ownerId = authStore.userId + const ownerGeneration = authGeneration + const ownership = Symbol('first-run-tour-handoff') + dispatchFirstRunScreen({ type: 'handoffStarted', ownership }) + try { + await dismissGettingStarted() + if (authStore.userId !== ownerId || authGeneration !== ownerGeneration) + return + await useFirstRunTourController().beginTour( + templateId, + () => authStore.userId !== ownerId || authGeneration !== ownerGeneration + ) + } finally { + dispatchFirstRunScreen({ type: 'handoffFinished', ownership }) + } + } + return { - gettingStartedVisible: readonly(gettingStartedVisible), - firstRunTookScreen: readonly(firstRunTookScreen), + gettingStartedVisible, + firstRunHoldsScreen, whenStartupDecided, handleStartupOutcome, handleUrlWorkflow, - dismissGettingStarted + dismissGettingStarted, + dismissIntoFirstRunTour } }) diff --git a/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.ts b/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.ts index e2f5299a703..0599d39feab 100644 --- a/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.ts +++ b/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.ts @@ -35,6 +35,25 @@ const OFFLINE_GRACE_MS = 20_000 /** How long a submitted run has to be accepted before the card stops promising. */ const ACCEPT_DEADLINE_MS = 15_000 +type TourStartState = + | { phase: 'idle' } + | { + phase: 'claimed' + ownership: symbol + restoreRenderer: boolean + } + | { + phase: 'writingRenderer' + ownership: symbol + restoreRenderer: boolean + write: Promise + } + | { + phase: 'previewing' + ownership: symbol + restoreRenderer: boolean + } + function useFirstRunTourControllerInternal() { const engine = useOnboardingTourStore() const billing = useBillingContext() @@ -46,6 +65,7 @@ function useFirstRunTourControllerInternal() { const desktopLayout = useBreakpoints(breakpointsTailwind).greaterOrEqual('md') const tourWorkflow = shallowRef(null) const nudgeArmed = ref(false) + let tourStart: TourStartState = { phase: 'idle' } /** Only a tour walked to the end made a first result to be congratulated for. */ const tourWasCompleted = ref(false) @@ -233,18 +253,114 @@ function useFirstRunTourControllerInternal() { nudgeArmed.value = false } + function ownsTourStart(ownership: symbol): boolean { + return tourStart.phase !== 'idle' && tourStart.ownership === ownership + } + + function releaseTourStart(ownership: symbol): void { + if (ownsTourStart(ownership)) tourStart = { phase: 'idle' } + } + + async function writeRenderer( + ownership: symbol, + enabled: boolean, + restoreRenderer: boolean + ): Promise { + const write = settingStore.set('Comfy.VueNodes.Enabled', enabled) + const writingState: TourStartState = { + phase: 'writingRenderer', + ownership, + restoreRenderer, + write + } + tourStart = writingState + try { + await write + } finally { + if (tourStart === writingState) { + tourStart = { phase: 'claimed', ownership, restoreRenderer } + } + } + } + + async function cleanUpFailedTourStart( + ownership: symbol, + shouldCancel: () => boolean + ) { + const currentStart = tourStart + if (currentStart.phase === 'idle' || currentStart.ownership !== ownership) + return + releaseFirstRunTargets() + tourWorkflow.value = null + const { restoreRenderer } = currentStart + if (restoreRenderer && shouldCancel()) return + if (restoreRenderer) await writeRenderer(ownership, false, restoreRenderer) + releaseTourStart(ownership) + } + + function canBeginTour(shouldCancel: () => boolean): boolean { + return !shouldCancel() && !engine.activeTour && canvasContextHolds.value + } + + async function claimTourStart(ownership: symbol): Promise { + const previousStart = tourStart + const restoreRenderer = + previousStart.phase === 'idle' + ? !settingStore.get('Comfy.VueNodes.Enabled') + : previousStart.restoreRenderer + + if (previousStart.phase === 'writingRenderer') { + tourStart = { ...previousStart, ownership } + await previousStart.write.catch(() => undefined) + if (ownsTourStart(ownership)) + tourStart = { phase: 'claimed', ownership, restoreRenderer } + } else { + tourStart = { phase: 'claimed', ownership, restoreRenderer } + } + return restoreRenderer + } + + async function claimRendererForTour(ownership: symbol): Promise { + const restoreRenderer = await claimTourStart(ownership) + if (!ownsTourStart(ownership)) return restoreRenderer + if (restoreRenderer && !settingStore.get('Comfy.VueNodes.Enabled')) + await writeRenderer(ownership, true, restoreRenderer) + return restoreRenderer + } + + async function cancelPendingStart(): Promise { + const previousStart = tourStart + if (previousStart.phase === 'idle') return + const ownership = Symbol('cancelled-first-run-tour-start') + try { + const restoreRenderer = await claimTourStart(ownership) + if ( + ownsTourStart(ownership) && + restoreRenderer && + settingStore.get('Comfy.VueNodes.Enabled') + ) + await writeRenderer(ownership, false, restoreRenderer) + } finally { + releaseTourStart(ownership) + } + } + /** False when there is no tour to give; any renderer switch is undone. */ - async function beginTour(templateId?: string): Promise { - if (engine.activeTour) return false + async function beginTour( + templateId?: string, + shouldCancel: () => boolean = () => false + ): Promise { + const ownership = Symbol('first-run-tour-start') // Holds only ever end a tour that is already running, and only when they // change — a context lost before the tour opens (`?template=X&mode=linear` // boots straight into linear mode) never produces that change. Refused // here, ahead of the renderer switch below, so nothing is left to undo. - if (!canvasContextHolds.value) return false + if (!canBeginTour(shouldCancel)) return false - const enabledForTour = !settingStore.get('Comfy.VueNodes.Enabled') - if (enabledForTour) await settingStore.set('Comfy.VueNodes.Enabled', true) + const restoreRenderer = await claimRendererForTour(ownership) + if (!ownsTourStart(ownership) || shouldCancel()) return false + tourStart = { phase: 'previewing', ownership, restoreRenderer } tourWorkflow.value = workflowStore.activeWorkflow ?? null runState.value = 'idle' nudgeArmed.value = false @@ -257,18 +373,20 @@ function useFirstRunTourControllerInternal() { // The preview is long enough for the canvas to go away underneath it, and // the holds watcher cannot catch that: there is no active tour to end yet. const contextStillHolds = (): boolean => canvasContextHolds.value - const started = contextStillHolds() && (await engine.startTour('firstRun')) + const started = + ownsTourStart(ownership) && + contextStillHolds() && + !shouldCancel() && + (await engine.startTour('firstRun')) if (!started) { - releaseFirstRunTargets() - tourWorkflow.value = null - if (enabledForTour) - await settingStore.set('Comfy.VueNodes.Enabled', false) - } + await cleanUpFailedTourStart(ownership, shouldCancel) + } else releaseTourStart(ownership) return started } return { beginTour, + cancelPendingStart, nudgeArmed: readonly(nudgeArmed), tourWasCompleted: readonly(tourWasCompleted), dismissNudge