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
18 changes: 11 additions & 7 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
role: demoRole(),
organization_id: 1,
})
setOrganization({
id: 1,
name: 'Demo Organization',
slug: 'demo-org',
member_count: 5,
created_at: new Date().toISOString(),
})
// ?account=new is an account that has never had an organization (see
// mockApi.ts), which onboarding creates.
if (new URLSearchParams(window.location.search).get('account') !== 'new') {
setOrganization({
id: 1,
name: 'Demo Organization',
slug: 'demo-org',
member_count: 5,
created_at: new Date().toISOString(),
})
}
setIsLoading(false)
console.log('[checkAuth] Demo mode setup complete')
return
Expand Down
18 changes: 3 additions & 15 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,6 @@ interface InvitationCheckResponse {
error?: string
}

interface CheckNameAvailabilityResponse {
available: boolean
suggested_slug: string
error?: string
}

interface SignupResponse {
message: string
email: string
Expand Down Expand Up @@ -475,16 +469,11 @@ class ApiClient {
}

// Onboarding
async checkOrganizationName(name: string): Promise<CheckNameAvailabilityResponse> {
return this.fetch<CheckNameAvailabilityResponse>(
`/v1/onboarding/check-name?name=${encodeURIComponent(name)}`
)
}

async createOrganizationOnboarding(name: string): Promise<{ organization: Organization }> {
// The backend names the organization after the user.
async createOrganizationOnboarding(): Promise<{ organization: Organization }> {
return this.fetch<{ organization: Organization }>('/v1/onboarding/organization', {
method: 'POST',
body: JSON.stringify({ name }),
body: JSON.stringify({}),
})
}

Expand Down Expand Up @@ -606,7 +595,6 @@ export type {
OrganizationMember,
UserInvitation,
InvitationCheckResponse,
CheckNameAvailabilityResponse,
SignupResponse,
ConfirmEmailResponse,
}
23 changes: 8 additions & 15 deletions src/lib/mockApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
* The demo account's state, pinned with ?account=<state> (with ?demo=true) so
* tests can reach each one directly:
* orgless - no organization (left it, or never joined)
* new - a new account that has never had an organization
* inactive - an admin deactivated the account
* deleted - the account was deleted (every call refused)
* only-admin - the only admin, so leaving is blocked
Expand All @@ -283,11 +284,11 @@ const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
*/
const demoParam = (name: string) => new URLSearchParams(window.location.search).get(name)

type DemoAccountState = 'member' | 'orgless' | 'inactive' | 'deleted' | 'only-admin' | 'last-member'
type DemoAccountState = 'member' | 'orgless' | 'new' | 'inactive' | 'deleted' | 'only-admin' | 'last-member'

const demoAccountState = (): DemoAccountState => {
const value = new URLSearchParams(window.location.search).get('account')
return (['orgless', 'inactive', 'deleted', 'only-admin', 'last-member'] as const).find((s) => s === value) ?? 'member'
return (['orgless', 'new', 'inactive', 'deleted', 'only-admin', 'last-member'] as const).find((s) => s === value) ?? 'member'
}

// Shaped like the real ApiError (status + code) without importing api.ts,
Expand Down Expand Up @@ -325,7 +326,7 @@ export class MockApiClient {
this.accountDeletedHandler?.()
throw demoApiError('Account deleted', 401, 'account_deleted')
}
const inOrg = state !== 'orgless'
const inOrg = state !== 'orgless' && state !== 'new'
return {
uuid: 'demo-user-uuid',
email: 'demo@getnodea.com',
Expand Down Expand Up @@ -688,19 +689,11 @@ export class MockApiClient {
}

// Onboarding
async checkOrganizationName(name: string): Promise<{ available: boolean; suggested_slug: string; error?: string }> {
await delay(300)
// In mock mode, always return available with a slugified name
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')
return {
available: true,
suggested_slug: slug,
}
}

async createOrganizationOnboarding(name: string): Promise<{ organization: Organization }> {
async createOrganizationOnboarding(): Promise<{ organization: Organization }> {
await delay(500)
// In mock mode, just update the existing organization
// In mock mode, just update the existing organization, named after the
// demo user as the backend would.
const name = "Demo User's Organization"
this.organization.name = name
this.left = false
this.joined = true
Expand Down
4 changes: 2 additions & 2 deletions src/pages/OnboardingModelPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useMemoryBudget } from '@/hooks/useMemoryBudget'
import { apiClient } from '@/lib/api'
import { formatMemory, modelDisplayName, modelTagline, recommend } from '@/lib/recommendedModels'

/* Step 2 of setting up an organization: a new organization has no models,
/* Setting up a new organization: a new organization has no models,
* so its Macs have nothing to serve until an admin adds one. Offer a few that
* fit this Mac and add the chosen one in a click. */
export function OnboardingModelPage() {
Expand Down Expand Up @@ -62,7 +62,7 @@ export function OnboardingModelPage() {
<div className="n-drag fixed inset-x-0 top-0 h-9" data-tauri-drag-region />
<div className="w-full max-w-[560px]">
<div className="text-[13px] font-semibold uppercase tracking-[0.09em] text-[var(--n-accent-400)]">
Step 2 of 2{organization ? ` · ${organization.name}` : ''}
{organization ? organization.name : 'Your organization'}
</div>
<h1 className="mt-3 text-[30px] font-semibold leading-[1.15] tracking-[-0.02em] text-[var(--n-text)]">
Pick a model for your organization
Expand Down
137 changes: 38 additions & 99 deletions src/pages/OnboardingPage.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useRef, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { apiClient } from '../lib/api'
import { Button } from '../components/ui/button'
import { Input } from '../components/ui/input'
import { Card } from '../components/ui/card'
import { toast } from 'sonner'

/* A new user's organization is created without asking for a name: the backend
* names it after them ("{name}'s Organization"), and they can rename it later.
* Someone who just left an organization is asked first, since they may rather
* open an invitation. */
export function OnboardingPage() {
const [organizationName, setOrganizationName] = useState('')
const [isChecking, setIsChecking] = useState(false)
const [isCreating, setIsCreating] = useState(false)
const [suggestedSlug, setSuggestedSlug] = useState('')
const [validationError, setValidationError] = useState('')
const [error, setError] = useState('')
const started = useRef(false)
const { refreshOrganization, leftOrganizationName, organization } = useAuth()
const navigate = useNavigate()

Expand All @@ -26,71 +27,43 @@ export function OnboardingPage() {
}
}, [organization, isCreating, navigate])

// Debounced name availability check
useEffect(() => {
if (!organizationName.trim()) {
setSuggestedSlug('')
setValidationError('')
return
}

const timer = setTimeout(async () => {
setIsChecking(true)
try {
const result = await apiClient.checkOrganizationName(organizationName)
setSuggestedSlug(result.suggested_slug)

if (!result.available) {
setValidationError(result.error || 'Name is not available')
} else {
setValidationError('')
}
} catch (error) {
console.error('Name check failed:', error)
setValidationError('Failed to check name availability')
} finally {
setIsChecking(false)
}
}, 500)

return () => clearTimeout(timer)
}, [organizationName])

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()

if (validationError) {
toast.error('Please fix validation errors')
return
}

if (!organizationName.trim()) {
toast.error('Please enter an organization name')
return
}

const createOrganization = useCallback(async () => {
setError('')
setIsCreating(true)

try {
await apiClient.createOrganizationOnboarding(organizationName)
await apiClient.createOrganizationOnboarding()

// Refresh organization in auth context
await refreshOrganization()

// Clear the "just signed up" flag
sessionStorage.removeItem('just_signed_up')

toast.success('Organization created')
// The creator is the organization's admin, and a new organization has
// no models yet: pick one next, so this Mac has something to serve.
navigate('/onboarding/model')
} catch (error: any) {
console.error('Failed to create organization:', error)
toast.error(error.message || 'Failed to create organization')
} finally {
} catch (err) {
// Already in one: this page showed while the organization was still
// loading. Nothing to set up.
if ((err as { status?: number }).status === 422) {
await refreshOrganization()
navigate('/node', { replace: true })
return
}
console.error('Failed to create organization:', err)
const message = err instanceof Error ? err.message : 'Failed to create organization'
setError(message)
toast.error(message)
setIsCreating(false)
}
}
}, [refreshOrganization, navigate])

useEffect(() => {
if (organization || leftOrganizationName || started.current) return
started.current = true
void createOrganization()
}, [organization, leftOrganizationName, createOrganization])

return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
Expand All @@ -100,63 +73,29 @@ export function OnboardingPage() {
<>
<h1 className="text-2xl font-bold mb-2">You're no longer in {leftOrganizationName}</h1>
<p className="text-muted-foreground">
This device stopped sharing compute. Create an organization below, or open an
This device stopped sharing compute. Create an organization of your own, or open an
invitation link to join one.
</p>
</>
) : (
<>
<h1 className="text-2xl font-bold mb-2">Welcome to Nodea!</h1>
<p className="text-muted-foreground">
Let's set up your organization to get started
{error ? "We couldn't set up your organization" : 'Setting up your organization…'}
</p>
</>
)}
</div>

<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="orgName" className="block text-sm font-medium mb-1">
Organization Name
</label>
<Input
id="orgName"
type="text"
value={organizationName}
onChange={(e) => setOrganizationName(e.target.value)}
placeholder="e.g., Acme Corporation"
disabled={isCreating}
className={validationError ? 'border-destructive' : ''}
maxLength={255}
/>

{isChecking && (
<p className="text-sm text-muted-foreground mt-1">
Checking availability...
</p>
)}

{validationError && (
<p className="text-sm text-destructive mt-1">
{validationError}
</p>
)}

{suggestedSlug && !validationError && (
<p className="text-sm text-muted-foreground mt-1">
URL: <span className="font-mono">{suggestedSlug}</span>
</p>
)}
</div>
{error && (
<p role="alert" className="text-sm text-destructive mb-4">{error}</p>
)}

<Button
type="submit"
className="w-full"
disabled={isCreating || isChecking || !!validationError || !organizationName.trim()}
>
{isCreating ? 'Creating...' : 'Continue'}
{(leftOrganizationName || error) && (
<Button className="w-full" onClick={() => void createOrganization()} disabled={isCreating}>
{isCreating ? 'Creating...' : leftOrganizationName ? 'Create my organization' : 'Try again'}
</Button>
</form>
)}
</Card>
</div>
)
Expand Down
23 changes: 11 additions & 12 deletions tests/onboarding.spec.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import { test, expect } from '@playwright/test'

/**
* First run, in demo mode: an admin names the organization, picks its first
* model, and finishes the setup checklist on the Node page, all without the
* web console. `?setup=fresh` is a brand-new organization (no models, no
* keys, nothing done); `?account=orgless` a user with no organization yet.
* First run, in demo mode: a new admin gets an organization named after them,
* picks its first model, and finishes the setup checklist on the Node page,
* all without the web console. `?setup=fresh` is a brand-new organization (no
* models, no keys, nothing done); `?account=new` an account that never had an
* organization, and `?account=orgless` one that has just left theirs.
*/
test.describe('In-app onboarding (demo mode)', () => {
test('an admin goes from naming the organization to a first model', async ({ page }) => {
await page.goto('/node?demo=true&account=orgless&setup=fresh')
await expect(page).toHaveURL(/\/onboarding$/)

await page.getByLabel('Organization Name').fill('Acme')
await page.getByRole('button', { name: 'Continue' }).click()
test('a new admin gets an organization without naming it, then picks a first model', async ({ page }) => {
await page.goto('/node?demo=true&account=new&setup=fresh')

await expect(page).toHaveURL(/\/onboarding\/model/)
await expect(page.getByRole('heading', { name: 'Pick a model for your organization' })).toBeVisible()
await expect(page.getByText("Demo User's Organization")).toBeVisible()

// Suggestions fit this (mock 16 GB) Mac, and the first is preselected so
// one click is enough.
Expand All @@ -38,8 +36,9 @@ test.describe('In-app onboarding (demo mode)', () => {

await page.goto('/node?demo=true&account=orgless&setup=fresh&phase=serving')
await expect(page).toHaveURL(/\/onboarding$/)
await page.getByLabel('Organization Name').fill('Acme')
await page.getByRole('button', { name: 'Continue' }).click()
// Having just left one, the user is asked before a new one is created.
await expect(page.getByText("You're no longer in Demo Organization")).toBeVisible()
await page.getByRole('button', { name: 'Create my organization' }).click()
await expect(page).toHaveURL(/\/onboarding\/model/)
commands.length = 0

Expand Down
Loading