diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 5cfc15a5..ea051302 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -10,6 +10,7 @@ import type { } from "@milo/adapter-kit"; import type { ChatGptPlanCredential, + ChatGptSignInFlow, ComposioProvider, ConnectorRegistry, DestinationEmulator, @@ -123,6 +124,8 @@ export async function createApp( composio?: ComposioProvider; pipedream?: ManagedConnectorProvider; email?: TransactionalEmailProvider; + /** Replaces the OpenAI sign-in flow, for offline tests. */ + chatgpt?: ChatGptSignInFlow; remoteConnectors?: RemoteConnectorDependencies; logger?: Logger; } = {}, @@ -134,6 +137,7 @@ export async function createApp( composio: composioOverride, pipedream: pipedreamOverride, email: emailOverride, + chatgpt: chatgptOverride, remoteConnectors, logger: loggerOverride, ...envOverrides @@ -305,8 +309,8 @@ export async function createApp( ? ("desktop" as const) : ("browser" as const) : null; - const chatgpt = chatgptCapture - ? new ChatGptSignIn({ hostId: chatGptHostId(env.authSecret) }) + const chatgpt: ChatGptSignInFlow | undefined = chatgptCapture + ? (chatgptOverride ?? new ChatGptSignIn({ hostId: chatGptHostId(env.authSecret) })) : undefined; const auth = createAuth(prisma, { secret: env.authSecret, diff --git a/apps/api/src/onboarding.test.ts b/apps/api/src/onboarding.test.ts index 8452c168..c58d4226 100644 --- a/apps/api/src/onboarding.test.ts +++ b/apps/api/src/onboarding.test.ts @@ -1,6 +1,6 @@ import type * as db from "@milo/db"; import { describe, expect, it, vi } from "vitest"; -import { chooseFocus, markAppConnected } from "./onboarding.js"; +import { chooseFocus, introduce, markAppConnected } from "./onboarding.js"; const posted = vi.hoisted(() => [] as Array<{ blocks: unknown[] }>); vi.mock("@milo/db", async (original) => ({ @@ -92,3 +92,72 @@ it("marks only the authorized connector when provider slugs collide", async () = data: { blocks: [blocks[0], { ...blocks[1], status: "connected" }] }, }); }); + +describe("introduce", () => { + function introFixture(catalog: unknown[], existing = 0) { + const { deps, actor, tx } = fixture(catalog); + let count = existing; + (deps.prisma.bot.findFirst as ReturnType).mockResolvedValue({ + id: "bot", + name: "Chief", + thread: { id: "thread" }, + }); + deps.prisma.message = { count: vi.fn(async () => count) } as never; + Object.assign(tx.message, { + count: vi.fn(async () => count), + }); + return { + deps, + actor, + afterPost: () => { + count = posted.length; + }, + }; + } + + it("posts the intro and three chips, naming connected apps", async () => { + const { deps, actor } = introFixture([ + { slug: "slack", name: "Slack", connected: true }, + { slug: "gmail", name: "Gmail", connected: true }, + { slug: "notion", name: "Notion", connected: false }, + ]); + await introduce(deps, actor, "bot"); + expect(posted).toHaveLength(1); + expect(posted[0]?.blocks).toEqual([ + { + kind: "text", + text: "Hi, I'm Chief. I run on your own subscription and work on my own computer. I can already reach Gmail and Slack. What should I take off your plate first?", + }, + { + kind: "suggestions", + items: ["Summarize my inbox", "Find something for me", "Make another bot"], + }, + ]); + }); + + it("offers to plan the week when Gmail is not connected", async () => { + const { deps, actor } = introFixture([]); + await introduce(deps, actor, "bot"); + expect(posted[0]?.blocks).toEqual([ + { + kind: "text", + text: "Hi, I'm Chief. I run on your own subscription and work on my own computer. What should I take off your plate first?", + }, + { kind: "suggestions", items: ["Plan my week", "Find something for me", "Make another bot"] }, + ]); + }); + + it("posts once when called twice", async () => { + const { deps, actor, afterPost } = introFixture([]); + await introduce(deps, actor, "bot"); + afterPost(); + await introduce(deps, actor, "bot"); + expect(posted).toHaveLength(1); + }); + + it("leaves a thread that already has messages alone", async () => { + const { deps, actor } = introFixture([], 1); + await introduce(deps, actor, "bot"); + expect(posted).toHaveLength(0); + }); +}); diff --git a/apps/api/src/onboarding.ts b/apps/api/src/onboarding.ts index a50747f8..6cf673ef 100644 --- a/apps/api/src/onboarding.ts +++ b/apps/api/src/onboarding.ts @@ -1,6 +1,11 @@ import type { ConnectorRegistry } from "@milo/adapters"; import type { Actor, MessageBlock } from "@milo/contracts"; -import { featuredConnectorProvidersMatch } from "@milo/core"; +import { + FEATURED_CONNECTOR_IDS, + FEATURED_CONNECTOR_LABELS, + featuredConnectorProvidersMatch, + matchFeaturedConnectorId, +} from "@milo/core"; import type { Prisma, PrismaClient, ThreadEvents } from "@milo/db"; import { appendEventInTransaction, @@ -10,9 +15,11 @@ import { import { requireBotThread, updateBlocks } from "./bot-thread.js"; /** - * First-run conversational onboarding, seeded deterministically into the bot's - * thread: greeting, a focus choice, and available app cards the user authorizes - * inline. Focus must not rename the bot. No model tokens are spent. + * A new bot's first message: a fixed intro with idea chips, seeded into its + * thread without spending model tokens. + * + * The focus script below it (greeting, focus choice, app cards) is unused since + * v0 and stays only so old threads keep working. Delete it after v0 ships. */ type OnboardingDeps = { @@ -96,6 +103,85 @@ async function post( return committed.message.id; } +const CATALOG_TIMEOUT_MS = 5_000; + +/** Labels of the featured apps this person already connected, in featured order. */ +async function connectedFeaturedApps( + deps: OnboardingDeps, + actor: Actor, + botId: string, +): Promise { + const items = ( + await Promise.all( + deps.connectors.managedProviders().map((provider) => + provider + .catalog({ + operationId: "onboarding.introduce", + traceId: "onboarding.introduce", + spaceId: actor.spaceId, + userId: actor.userId, + botId, + signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS), + }) + .catch(() => []), + ), + ) + ).flat(); + const connected = new Set( + items.filter((item) => item.connected).map((item) => matchFeaturedConnectorId(item.slug)), + ); + return FEATURED_CONNECTOR_IDS.filter((id) => connected.has(id)).map( + (id) => FEATURED_CONNECTOR_LABELS[id], + ); +} + +function joinNames(names: string[]): string { + return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names.join(""); +} + +export function introBlocks(name: string, apps: string[]): MessageBlock[] { + const reach = apps.length ? ` I can already reach ${joinNames(apps)}.` : ""; + return [ + { + kind: "text", + text: `Hi, I'm ${name}. I run on your own subscription and work on my own computer.${reach} What should I take off your plate first?`, + }, + { + kind: "suggestions", + items: [ + apps.includes(FEATURED_CONNECTOR_LABELS.gmail) ? "Summarize my inbox" : "Plan my week", + "Find something for me", + "Make another bot", + ], + }, + ]; +} + +/** Posts the bot's intro once: a thread that already has any message is left alone. */ +export async function introduce(deps: OnboardingDeps, actor: Actor, botId: string): Promise { + const { bot, thread } = await requireBotThread(deps, actor, botId); + if ((await deps.prisma.message.count({ where: { threadId: thread.id } })) > 0) return; + const blocks = introBlocks(bot.name, await connectedFeaturedApps(deps, actor, bot.id)); + const committed = await deps.prisma.$transaction(async (tx: Prisma.TransactionClient) => { + // Serialize concurrent callers so the intro is posted at most once. + await tx.$executeRaw`SELECT id FROM threads WHERE id = ${thread.id} FOR UPDATE`; + if ((await tx.message.count({ where: { threadId: thread.id } })) > 0) return null; + const message = await createThreadMessageInTransaction(tx, { + threadId: thread.id, + role: "bot", + blocks, + }); + return appendEventInTransaction(tx, { + spaceId: actor.spaceId, + threadId: thread.id, + botId: bot.id, + type: "thread.message.created", + payload: { messageId: message.id, role: "bot", blocks }, + }); + }); + if (committed) await deps.events.notify(thread.id, committed.seq); +} + /** Sentinel answerId for a focus card the user dismissed without choosing. */ export const FOCUS_DISMISSED_ANSWER_ID = "_dismissed"; diff --git a/apps/api/src/router.ts b/apps/api/src/router.ts index 971f3ad2..62df81ea 100644 --- a/apps/api/src/router.ts +++ b/apps/api/src/router.ts @@ -226,6 +226,7 @@ import { buildMcpUpdateMaterial } from "./mcp-material.js"; import { chooseFocus, dismissFocus, + introduce, markAppConnected, promptFocus, startOnboarding, @@ -4019,6 +4020,10 @@ export function createRouter(deps: RouterDeps) { }, }, onboarding: { + introduce: authed.onboarding.introduce.handler(async ({ context, input }) => { + await introduce(onboardingDeps, context.actor, input.botId); + return { ok: true as const }; + }), start: authed.onboarding.start.handler(async ({ context, input }) => { await startOnboarding(onboardingDeps, context.actor, input.botId); return { ok: true as const }; diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/index.tsx index b9df7966..4cf86fc6 100644 --- a/apps/mobile/app/(tabs)/index.tsx +++ b/apps/mobile/app/(tabs)/index.tsx @@ -49,7 +49,6 @@ import { selectSpace, } from "../../lib/api"; import { mobileTokens, resolveMobileAppearance } from "../../lib/appearance"; -import { allowFocusPrompt, scheduleFocusPrompt } from "../../lib/focus-prompt"; import { t, useI18n } from "../../lib/i18n"; import { botTag, filterBots, formatThreadTime } from "../../lib/inbox"; import { @@ -429,25 +428,13 @@ export default function Home() { return; creatingBotRef.current = true; try { - // Authoritative roster so a slow home fetch does not treat later bots as first. - // A failed list is unknown — use the delayed path rather than assuming first. - const existing = await rpc("bots/list").catch(() => null); - const isFirstBot = existing !== null && existing.length === 0; const bot = await rpc("bots/create", { ...normalizeCreateBotProfile({ name: "New Bot", title: "", description: "" }), notifyOnFinish: true, computerMode: "team", }); void refreshBots().catch(() => undefined); - allowFocusPrompt(bot.id); router.push({ pathname: "/thread", params: { botId: bot.id, name: bot.name } }); - void (async () => { - const started = await rpc("onboarding/start", { botId: bot.id }) - .then(() => true) - .catch(() => false); - if (!started) return; - scheduleFocusPrompt(bot.id, isFirstBot); - })(); } catch (err) { setError(err instanceof Error ? err.message : t("Could not create bot")); } finally { diff --git a/apps/mobile/app/new.tsx b/apps/mobile/app/new.tsx index 797484de..44973066 100644 --- a/apps/mobile/app/new.tsx +++ b/apps/mobile/app/new.tsx @@ -10,7 +10,6 @@ import { useState } from "react"; import { Pressable, ScrollView, Text, TextInput } from "react-native"; import { ComputerModePicker } from "../components/computer-mode-picker"; import { type MobileBot, rpc } from "../lib/api"; -import { allowFocusPrompt, scheduleFocusPrompt } from "../lib/focus-prompt"; import { useI18n } from "../lib/i18n"; import { useMobileTokens } from "../lib/native"; @@ -42,23 +41,12 @@ export default function NewBot() { setPending(true); setError(null); try { - // Failed list is unknown — delay focus rather than treating the bot as first. - const existing = await rpc("bots/list").catch(() => null); - const isFirstBot = existing !== null && existing.length === 0; const bot = await rpc("bots/create", { ...normalizeCreateBotProfile({ name, title, description }), notifyOnFinish: true, computerMode, }); - allowFocusPrompt(bot.id); router.replace({ pathname: "/thread", params: { botId: bot.id, name: bot.name } }); - void (async () => { - const started = await rpc("onboarding/start", { botId: bot.id }) - .then(() => true) - .catch(() => false); - if (!started) return; - scheduleFocusPrompt(bot.id, isFirstBot); - })(); } catch (err) { setError(err instanceof Error ? err.message : t("Could not create bot")); } finally { diff --git a/apps/mobile/app/thread.tsx b/apps/mobile/app/thread.tsx index 9acd7c3e..2acc1548 100644 --- a/apps/mobile/app/thread.tsx +++ b/apps/mobile/app/thread.tsx @@ -1,4 +1,4 @@ -import { ChatMarkdown, LinkifiedText } from "@milo/chat-ui/native"; +import { ChatMarkdown, LinkifiedText, SuggestionChips } from "@milo/chat-ui/native"; import type { AgentSkillCatalogEntry, Connection, @@ -109,7 +109,6 @@ import { confirmDeleteBot } from "../lib/bot-lifecycle"; import { setCallProviderTranscribe, startCall, useCallSession } from "../lib/call-session"; import { loadDeviceVoiceEnabled } from "../lib/device-voice"; import { available as dictationAvailable } from "../lib/dictation"; -import { cancelFocusPrompt, focusPromptThreadActive } from "../lib/focus-prompt"; import { dateLocaleForUi, t, useI18n } from "../lib/i18n"; import { saveLastBotId } from "../lib/last-bot"; import { @@ -921,25 +920,10 @@ function Thread() { void dismissThreadNotifications({ threadId: notificationThreadId }).catch(() => undefined); }, [botId, navigation, notificationThreadId]); - // Cancel delayed setup only when leaving this bot's thread (unmount or botId - // change). Blur alone is not leave — settings/computer push must keep the timer. - useEffect(() => { - if (!botId) return; - return () => { - cancelFocusPrompt(botId); - }; - }, [botId]); - // Covers returning from a pushed screen; the AppState listener covers returning from background. useFocusEffect( useCallback(() => { - if (botId) { - focusPromptThreadActive(botId); - void saveLastBotId(botId).catch(() => undefined); - } else { - // Group thread focus: prior bot screen may stay mounted, so clear any delayed setup. - cancelFocusPrompt(); - } + if (botId) void saveLastBotId(botId).catch(() => undefined); if (AppState.currentState === "active" && notificationThreadId) { void setOpenNotificationThread({ botId, @@ -1197,11 +1181,6 @@ function Thread() { const groupTarget = plan.rerouteGroupId ?? initialGroupTarget; const botTarget = reroutedToGroup ? undefined : initialBotTarget; const trimmed = plan.trimmed; - const dropDelayedSetup = () => { - // Only after successful engagement so a failed upload/send keeps the setup card. - // Covers group-mention reroute while the bot thread stays mounted underneath. - if (initialBotTarget) cancelFocusPrompt(initialBotTarget); - }; setSending(true); setError(null); try { @@ -1230,7 +1209,6 @@ function Thread() { setAttachmentNotice(null); }; if (!plan.shouldSend) { - dropDelayedSetup(); clearOriginComposer(); if (reroutedToGroup && groupTarget) { router.push({ @@ -1280,7 +1258,6 @@ function Thread() { replyQuote: replyQuote ?? undefined, }, ); - dropDelayedSetup(); void loadSessionToken() .then((token) => resumeLiveNotifications(currentApiBase(), token, selectedSpaceId() ?? "")) .catch(() => undefined); @@ -3177,6 +3154,7 @@ const MessageBubble = memo(function MessageBubble({ const speaker = message.role === "bot" ? (memberName(members, message.botId) ?? botName) : undefined; const firstContent = segments.findIndex((segment) => segment.kind === "content"); + const suggestions = message.blocks.find((block) => block.kind === "suggestions"); return ( {segments.map((segment, index) => ( @@ -3188,6 +3166,7 @@ const MessageBubble = memo(function MessageBubble({ actionProps={actionProps} /> ))} + {suggestions ? : null} {appConnectBlocks.map((block, index) => ( void pick(item)} + /> + ); +} + function MessageTextCard({ message, speaker, diff --git a/apps/mobile/lib/focus-prompt.ts b/apps/mobile/lib/focus-prompt.ts deleted file mode 100644 index 70441c05..00000000 --- a/apps/mobile/lib/focus-prompt.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { rpc } from "./api"; - -/** Delay before the setup focus card for a non-first bot. */ -export const FOCUS_PROMPT_DELAY_MS = 10_000; - -let pendingTimer: ReturnType | null = null; -let pendingBotId: string | null = null; -/** Bot ids whose delayed prompt must not run after the user left the thread. */ -const cancelledBotIds = new Set(); - -/** Bot id currently allowed to schedule; cleared when another thread is focused. */ -let eligibleBotId: string | null = null; - -/** Allow a freshly created bot to schedule a focus prompt after navigation. */ -export function allowFocusPrompt(botId: string): void { - cancelledBotIds.delete(botId); - eligibleBotId = botId; -} - -/** Cancel a scheduled focus prompt. Pass botId to cancel only that bot. */ -export function cancelFocusPrompt(botId?: string): void { - if (botId) { - cancelledBotIds.add(botId); - if (eligibleBotId === botId) eligibleBotId = null; - } else { - eligibleBotId = null; - } - if (botId && pendingBotId && pendingBotId !== botId) return; - if (pendingTimer) clearTimeout(pendingTimer); - pendingTimer = null; - pendingBotId = null; -} - -/** - * Call when a bot thread gains focus. Cancels another bot's delayed setup when - * the user pushed or switched here while the previous thread stayed mounted. - */ -export function focusPromptThreadActive(botId: string): void { - if (eligibleBotId && eligibleBotId !== botId) { - cancelFocusPrompt(eligibleBotId); - } - if (pendingBotId && pendingBotId !== botId) { - cancelFocusPrompt(pendingBotId); - } -} - -/** - * Schedule posting the focus choice card. Survives leaving the home screen so - * navigating into the new bot's thread does not cancel the delay. Call - * `allowFocusPrompt` before navigating, and `cancelFocusPrompt` when leaving - * that bot's thread (unmount / bot switch — not blur onto settings) so a late - * `onboarding/start` cannot schedule after departure. - */ -export function scheduleFocusPrompt(botId: string, immediate: boolean): void { - if (cancelledBotIds.has(botId) || (eligibleBotId !== null && eligibleBotId !== botId)) return; - if (pendingTimer) clearTimeout(pendingTimer); - pendingTimer = null; - pendingBotId = null; - if (immediate) { - void rpc("onboarding/promptFocus", { botId }).catch(() => undefined); - return; - } - pendingBotId = botId; - pendingTimer = setTimeout(() => { - pendingTimer = null; - pendingBotId = null; - if (cancelledBotIds.has(botId)) return; - void rpc("onboarding/promptFocus", { botId }).catch(() => undefined); - }, FOCUS_PROMPT_DELAY_MS); -} diff --git a/apps/web/e2e/auth-lifecycle.spec.ts b/apps/web/e2e/auth-lifecycle.spec.ts index 9ee9d644..6e022576 100644 --- a/apps/web/e2e/auth-lifecycle.spec.ts +++ b/apps/web/e2e/auth-lifecycle.spec.ts @@ -1,5 +1,5 @@ import { expect, type Page, test } from "@playwright/test"; -import { captureScreenshot, completeOnboarding, signup } from "./helpers"; +import { captureScreenshot, completeOnboarding, signupWithEmail } from "./helpers"; /** The sidebar has no account menu, so sign out through the auth API and reload. */ async function signOut(page: Page) { @@ -48,7 +48,7 @@ test("logout protects bot deep links and sign-in restores the session", async ({ const password = "password12"; const userName = "Auth Lifecycle"; - await page.goto("/sign-up"); + await page.goto("/sign-up?with=email"); await expect(page.getByLabel("Name")).toHaveAttribute("autocomplete", "name"); await expect(page.getByLabel("Email")).toHaveAttribute("autocomplete", "username"); await expect(page.getByLabel("Password", { exact: true })).toHaveAttribute( @@ -56,7 +56,7 @@ test("logout protects bot deep links and sign-in restores the session", async ({ "new-password", ); - await signup(page, email, password, userName); + await signupWithEmail(page, email, password, userName); await completeOnboarding(page); await page.waitForURL(/\/app\/[^/]+$/); @@ -66,21 +66,24 @@ test("logout protects bot deep links and sign-in restores the session", async ({ await expect(page.getByTestId("user-menu-trigger")).toHaveCount(0); await signOut(page); - await expect(page.getByRole("heading", { name: "Sign in to Milo" })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Sign in with ChatGPT" })).toBeVisible(); await page.goto("/"); await expect(page.locator('[data-rakazo-surface="welcome"]')).toBeVisible(); await expect(page.getByText(/Your team of always-on agents/)).toBeVisible(); await page.getByRole("button", { name: /Sign up/ }).click(); await expect(page).toHaveURL(/\/sign-up$/); - await expect(page.getByRole("heading", { name: "Create your Milo" })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Sign in with ChatGPT" })).toBeVisible(); await page.goto("/"); await captureScreenshot(page, testInfo, "37-logged-out-welcome"); await page.goto(protectedBotPath); await page.waitForURL((url) => url.pathname === "/sign-in"); - await expect(page.getByRole("heading", { name: "Sign in to Milo" })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Sign in with ChatGPT" })).toBeVisible(); await expect(page.getByText("Chief", { exact: true })).toHaveCount(0); await expect(page.getByText(userName, { exact: true })).toHaveCount(0); + // Accounts made with a password still sign in by email. + await page.goto("/sign-in?with=email"); + await expect(page.getByRole("heading", { name: "Sign in to Milo" })).toBeVisible(); await expect(page.getByLabel("Email")).toHaveAttribute("autocomplete", "username"); await expect(page.getByLabel("Password", { exact: true })).toHaveAttribute( "autocomplete", @@ -96,7 +99,7 @@ test("logout protects bot deep links and sign-in restores the session", async ({ .locator("form") .getByText(/invalid email or password|invalid credentials|incorrect password/i), ).toBeVisible(); - await expect(page).toHaveURL(/\/sign-in$/); + await expect(page).toHaveURL(/\/sign-in\?with=email$/); await captureScreenshot(page, testInfo, "39-invalid-credentials"); await page.getByLabel("Password", { exact: true }).fill(password); @@ -143,7 +146,7 @@ test("recovers an email password from the sign-in screen", async ({ page }, test const resetPassword = "reset-password12"; const userName = "Password Recovery"; - await signup(page, email, originalPassword, userName); + await signupWithEmail(page, email, originalPassword, userName); await completeOnboarding(page); await page.waitForURL(/\/app\/[^/]+$/); @@ -156,6 +159,7 @@ test("recovers an email password from the sign-in screen", async ({ page }, test await settings.getByRole("button", { name: "Close user settings" }).click(); await signOut(page); + await page.goto("/sign-in?with=email"); await expect(page.getByRole("link", { name: "Forgot password?" })).toBeVisible(); await page.getByRole("link", { name: "Forgot password?" }).click(); await expect(page.getByRole("heading", { name: "Reset your password" })).toBeVisible(); diff --git a/apps/web/e2e/golden.spec.ts b/apps/web/e2e/golden.spec.ts index 16263896..052d2cbc 100644 --- a/apps/web/e2e/golden.spec.ts +++ b/apps/web/e2e/golden.spec.ts @@ -1,5 +1,12 @@ import { expect, type Page, test } from "@playwright/test"; -import { activeBotId, captureScreenshot, completeOnboarding, rpc, signup } from "./helpers"; +import { + activeBotId, + captureScreenshot, + completeOnboarding, + rpc, + signInWithChatGpt, + signup, +} from "./helpers"; function sidebarBotButton(page: Page, name: RegExp | string) { return page.locator("[data-sidebar-group] [data-roster-bot-id]").filter({ @@ -253,9 +260,7 @@ test("sign-in, spawn, and stop work in the shell", async ({ page }, testInfo) => await page.context().clearCookies(); await page.goto("/sign-in"); - await page.getByPlaceholder("Your email address").fill(email); - await page.getByLabel("Password", { exact: true }).fill("password12"); - await page.getByRole("button", { name: "Continue with email" }).click(); + await signInWithChatGpt(page, email, "Shell"); await page.waitForURL(/\/app/, { timeout: 20_000 }); await expect(sidebarBotButton(page, /^Chief/)).toBeVisible(); await expect(sidebarBotButton(page, /Scout/)).toBeVisible(); diff --git a/apps/web/e2e/helpers.ts b/apps/web/e2e/helpers.ts index d6c85839..1dd8201c 100644 --- a/apps/web/e2e/helpers.ts +++ b/apps/web/e2e/helpers.ts @@ -17,60 +17,75 @@ export async function rpc(page: Page, procedure: string, body: unknown): Prom export async function completeOnboarding(page: Page, testInfo?: TestInfo) { await page.waitForURL(/\/(onboarding|app)/, { timeout: 20_000 }); - // Optional Server integrations step (needsSetup). Skip it when shown. - const integrations = page.getByRole("heading", { name: "Server integrations", exact: true }); - const firstRunStep = page - .getByRole("heading", { name: /^(Connect your apps|Meet your first bot)$/ }) - .or(page.getByRole("combobox", { name: /^Message / })); - await integrations.or(firstRunStep).first().waitFor({ timeout: 20_000 }); - if (await integrations.isVisible().catch(() => false)) { - if (testInfo) await captureScreenshot(page, testInfo, "02-connect-apps"); - await page.getByRole("button", { name: "Skip", exact: true }).click(); - } await sayHiToFirstBot(page, testInfo); await expect(page.getByText("Chief").first()).toBeVisible(); if (testInfo) await captureScreenshot(page, testInfo, "06-onboarding-complete"); } -/** Skip the optional apps step, if shown, and wait for the Meet step. */ +/** Wait for the Meet step, the first step after signing in with ChatGPT. */ export async function reachMeetStep(page: Page) { - const apps = page.getByRole("heading", { name: "Connect your apps", exact: true }); - const meet = page.getByRole("heading", { name: "Meet your first bot", exact: true }); - await apps.or(meet).first().waitFor({ timeout: 20_000 }); - if (await apps.isVisible().catch(() => false)) { - await page.getByRole("button", { name: "Skip for now", exact: true }).click(); - } - await expect(meet).toBeVisible(); + await expect(page.getByRole("heading", { name: "Meet your first bot", exact: true })).toBeVisible( + { + timeout: 20_000, + }, + ); } -/** Skip the optional apps step and create the first bot from the Meet step, if shown. */ +/** Meet the first bot, skip the optional apps step, and wait for its chat, when onboarding shows. */ export async function sayHiToFirstBot(page: Page, testInfo?: TestInfo) { - const apps = page.getByRole("heading", { name: "Connect your apps", exact: true }); const meet = page.getByRole("heading", { name: "Meet your first bot", exact: true }); + const apps = page.getByRole("heading", { name: "Connect your apps", exact: true }); const chat = page.getByRole("combobox", { name: /^Message / }); - await apps.or(meet).or(chat).first().waitFor({ timeout: 20_000 }); + await meet.or(chat).first().waitFor({ timeout: 20_000 }); + if (await meet.isVisible().catch(() => false)) { + if (testInfo) await captureScreenshot(page, testInfo, "03-meet-first-bot"); + await page.getByRole("button", { name: /^(Continue|Say hi)$/ }).click(); + await apps.or(chat).first().waitFor({ timeout: 20_000 }); + } if (await apps.isVisible().catch(() => false)) { if (testInfo) await captureScreenshot(page, testInfo, "02-connect-apps"); await page.getByRole("button", { name: "Skip for now", exact: true }).click(); - await meet.or(chat).first().waitFor({ timeout: 20_000 }); - } - if (await meet.isVisible().catch(() => false)) { - if (testInfo) await captureScreenshot(page, testInfo, "03-meet-first-bot"); - await page.getByRole("button", { name: "Say hi", exact: true }).click(); } await page.waitForURL(/\/app\//, { timeout: 20_000 }); } +/** + * Sign in with the offline ChatGPT emulator as this account. The harness stands + * in for the person approving the sign-in in ChatGPT's tab. + */ +export async function signInWithChatGpt( + page: Page, + email: string, + name: string, + testInfo?: TestInfo, +) { + const api = process.env.API_URL ?? "http://127.0.0.1:3110"; + await page.context().route("https://chatgpt.example.test/**", async (route) => { + const state = new URL(route.request().url()).searchParams.get("state"); + await page.request.post(`${api}/__e2e/chatgpt/authorize`, { data: { state, email, name } }); + await route.fulfill({ body: "" }); + }); + await expect(page.getByRole("heading", { name: "Sign in with ChatGPT" })).toBeVisible(); + if (testInfo) await captureScreenshot(page, testInfo, "01-sign-up"); + await page.getByRole("button", { name: "Continue", exact: true }).click(); +} + +/** Create an account through Sign in with ChatGPT. The password is unused there. */ export async function signup( page: Page, email: string, - password: string, + _password: string, name: string, testInfo?: TestInfo, ) { await page.goto("/sign-up"); + await signInWithChatGpt(page, email, name, testInfo); +} + +/** Create an email and password account, for specs about password sign-in. */ +export async function signupWithEmail(page: Page, email: string, password: string, name: string) { + await page.goto("/sign-up?with=email"); await expect(page.getByRole("heading", { name: "Create your Milo" })).toBeVisible(); - if (testInfo) await captureScreenshot(page, testInfo, "01-sign-up"); await page.getByPlaceholder("Your name").fill(name); await page.getByPlaceholder("Your email address").fill(email); await page.getByLabel("Password", { exact: true }).fill(password); diff --git a/apps/web/e2e/integration-setup.spec.ts b/apps/web/e2e/integration-setup.spec.ts index 30c6936e..2ee65ec1 100644 --- a/apps/web/e2e/integration-setup.spec.ts +++ b/apps/web/e2e/integration-setup.spec.ts @@ -1,12 +1,5 @@ import { expect, test } from "@playwright/test"; -import { - captureScreenshot, - completeOnboarding, - openUserSettings, - reachMeetStep, - sayHiToFirstBot, - signup, -} from "./helpers"; +import { captureScreenshot, completeOnboarding, openUserSettings, signup } from "./helpers"; test("setup exposes all integration choices and saves only the selected provider", async ({ page, @@ -32,6 +25,9 @@ test("setup exposes all integration choices and saves only the selected provider return route.fulfill({ json: { json: { ok: true } } }); }); await signup(page, `integration-setup-${Date.now()}@rakazo.test`, "password12", "Setup Test"); + // Onboarding leaves server setup out; owners open it on its own page. + await completeOnboarding(page); + await page.goto("/integrations/setup"); await expect(page.getByRole("heading", { name: "Server integrations" })).toBeVisible(); for (const name of ["Direct MCP", "Composio", "Pipedream", "Executor"]) { await expect(page.getByRole("button", { name, exact: true })).toBeVisible(); @@ -50,89 +46,6 @@ test("setup exposes all integration choices and saves only the selected provider await expect .poll(() => saved) .toEqual([{ json: { provider: "composio", apiKey: "fake-composio-key" } }]); - await sayHiToFirstBot(page); - await expect(page.getByRole("combobox", { name: "Message Chief" })).toBeVisible({ - timeout: 20_000, - }); -}); - -test("direct MCP connects a catalog result without asking for a URL and assigns it to the first bot", async ({ - page, -}, testInfo) => { - await page.route("**/rpc/integrationSetup/get", (route) => - route.fulfill({ - json: { - json: { - canConfigure: true, - needsSetup: true, - webUrl: "https://example.test/integrations/setup", - providers: [], - }, - }, - }), - ); - let serverId = ""; - await page.route("**/rpc/capabilities/catalogSearch", (route) => - route.fulfill({ - json: { - json: { - enabled: true, - results: [ - { - domain: "notion.example.test", - name: "Notion", - description: "", - pageUrl: null, - surfaces: [ - { - kind: "mcp", - slug: "notion", - source: "https://mcp.notion.example.test/mcp", - auth: null, - }, - ], - }, - ], - }, - }, - }), - ); - await page.route("**/rpc/mcp/oauth/begin", (route) => { - serverId = route.request().postDataJSON().json.serverId; - return route.fulfill({ json: { json: { status: "already_connected" } } }); - }); - await signup(page, `direct-mcp-setup-${Date.now()}@rakazo.test`, "password12", "Direct MCP"); - await page.getByRole("textbox", { name: "Search apps", exact: true }).fill("Notion"); - await page.getByRole("button", { name: "Search integrations.sh", exact: true }).click(); - await expect(page.getByText("Notion", { exact: true })).toBeVisible(); - await expect(page.getByRole("textbox", { name: "Server URL" })).toBeHidden(); - await page.getByRole("button", { name: "Connect", exact: true }).click(); - await expect(page.getByRole("button", { name: "Connected", exact: true })).toBeVisible(); - await captureScreenshot(page, testInfo, "integration-setup-direct-connected"); - let createCalls = 0; - let releaseCreate!: () => void; - const createGate = new Promise((resolve) => { - releaseCreate = resolve; - }); - await page.route("**/rpc/bots/create", async (route) => { - createCalls += 1; - await createGate; - await route.continue(); - }); - - const assigned = page.waitForResponse( - (response) => response.url().includes("/rpc/mcp/assignments/approve") && response.ok(), - ); - await page.getByRole("button", { name: "Continue", exact: true }).click(); - await reachMeetStep(page); - await page.getByRole("button", { name: "Say hi", exact: true }).click(); - await expect(page.getByText("Opening chat…")).toBeVisible(); - await expect.poll(() => createCalls).toBe(1); - releaseCreate(); - const response = await assigned; - expect(response.request().postDataJSON().json.serverId).toBe(serverId); - await page.waitForURL(/\/app\//); - await expect(page.getByRole("combobox", { name: "Message Chief" })).toBeVisible(); }); test("Executor reconnect saves a replacement token before authorization", async ({ page }) => { @@ -149,6 +62,8 @@ test("Executor reconnect saves a replacement token before authorization", async }), ); await signup(page, `executor-reconnect-${Date.now()}@rakazo.test`, "password12", "Executor Test"); + await completeOnboarding(page); + await page.goto("/integrations/setup"); await expect(page.getByRole("heading", { name: "Server integrations" })).toBeVisible(); const server = await page.evaluate(async () => { const response = await fetch("/rpc/mcp/servers/create", { diff --git a/apps/web/e2e/message-hover-actions.spec.ts b/apps/web/e2e/message-hover-actions.spec.ts index a9aab114..a684db30 100644 --- a/apps/web/e2e/message-hover-actions.spec.ts +++ b/apps/web/e2e/message-hover-actions.spec.ts @@ -52,17 +52,20 @@ test("message hover shows beside-bubble actions; reply links to parent", async ( await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); const transcript = page.getByTestId("transcript"); + const composer = page.getByRole("combobox", { name: /^Message/ }); + await expect(composer).toBeVisible(); - // Empty start: no Fresh-start greeting. Answer the focus card so a plain - // bot text bubble exists for hover layout checks. - await expect(page.getByText("What do you want me on first?", { exact: true })).toBeVisible({ - timeout: 20_000, - }); - await page.getByRole("button", { name: /Day-to-day work/ }).click(); - const botText = page.getByText(/Got it\./); - await expect(botText).toBeVisible({ timeout: 20_000 }); - const botRow = transcript.locator(`[data-message-id]`).filter({ has: botText }).first(); - await expect(botRow).toBeVisible(); + // Intro chips sit in the same frame the rail centers on, so geometry uses the + // follow-up bot bubble. Scripted replies wrap the prompt ("done. i handled: …"). + const layoutText = `hover-layout-${stamp}`; + await sendComposerMessage(page, composer, layoutText); + const botRow = transcript + .locator(`[data-message-id]`) + .filter({ + has: page.getByTestId("message-bot-bubble").getByText(layoutText), + }) + .first(); + await expect(botRow).toBeVisible({ timeout: 20_000 }); await expectRailAtRest(page, botRow); await captureScreenshot(page, testInfo, "message-actions-rest-desktop"); @@ -102,8 +105,6 @@ test("message hover shows beside-bubble actions; reply links to parent", async ( const parentText = `hover-parent-${stamp}`; const replyText = `hover-reply-${stamp}`; - const composer = page.getByRole("combobox", { name: /^Message/ }); - await expect(composer).toBeVisible(); await sendComposerMessage(page, composer, parentText); const parentRow = transcript.locator(`[data-message-id]`).filter({ hasText: parentText }).first(); @@ -366,17 +367,14 @@ test.describe("touch message actions", () => { expect( await page.evaluate(() => matchMedia("(hover: hover) and (pointer: fine)").matches), ).toBe(false); - await expect(page.getByText("What do you want me on first?", { exact: true })).toBeVisible({ - timeout: 20_000, - }); - await page.getByRole("button", { name: /Day-to-day work/ }).click(); - const botText = page.getByText(/Got it\./); - await expect(botText).toBeVisible({ timeout: 20_000 }); - const row = page - .getByTestId("transcript") + const transcript = page.getByTestId("transcript"); + const row = transcript .locator("[data-message-id]") - .filter({ has: botText }) + .filter({ + has: page.getByTestId("message-bot-bubble").getByText(/Hi, I'm Chief\./), + }) .first(); + await expect(row).toBeVisible({ timeout: 20_000 }); const rail = row.getByTestId("message-hover-rail"); await expect(rail).toHaveCSS("opacity", "1"); await expect(rail.getByRole("button", { name: "Reply", exact: true })).toBeVisible(); diff --git a/apps/web/e2e/new-bot-ux.spec.ts b/apps/web/e2e/new-bot-ux.spec.ts index 83f25b80..1920b07b 100644 --- a/apps/web/e2e/new-bot-ux.spec.ts +++ b/apps/web/e2e/new-bot-ux.spec.ts @@ -75,45 +75,6 @@ test("+ opens the form, then an empty chat; sidebar collapses", async ({ page }, await captureScreenshot(page, testInfo, "bots-sidebar-expanded"); }); -test("later bot waits before showing the focus card; sending cancels it", async ({ page }) => { - const stamp = Date.now(); - await signup(page, `focus-delay-${stamp}@rakazo.test`, "password12", "Focus Delay"); - await completeOnboarding(page); - // First bot from onboarding shows the focus card immediately. - await expect(page.getByText("What do you want me on first?", { exact: true })).toBeVisible(); - - await page.clock.install(); - await createBotFromPicker(page); - await expect(page.getByPlaceholder("Message New Bot")).toBeVisible(); - await expect(page.getByText("What do you want me on first?", { exact: true })).toHaveCount(0); - - await page.clock.fastForward(9_000); - await expect(page.getByText("What do you want me on first?", { exact: true })).toHaveCount(0); - await page.clock.fastForward(1_500); - await expect(page.getByText("What do you want me on first?", { exact: true })).toBeVisible(); - - await createBotFromPicker(page, { name: "Later Bot" }); - await expect(page.getByText("What do you want me on first?", { exact: true })).toHaveCount(0); - const composer = page.getByPlaceholder(/Message/); - await composer.fill("I'll set this up myself"); - // Send must finish before the delay is advanced: cancel runs after a successful - // RPC, and promptFocus will still post if the clock fires while send is in flight. - const sent = page.waitForResponse( - (response) => response.url().includes("/rpc/threads/send") && response.ok(), - ); - await page.keyboard.press("Enter"); - await sent; - // Scope to the user bubble: the assistant reply can echo this phrase as a substring. - await expect( - page - .getByTestId("transcript") - .getByTestId("message-user-bubble") - .getByText("I'll set this up myself", { exact: true }), - ).toBeVisible(); - await page.clock.fastForward(12_000); - await expect(page.getByText("What do you want me on first?", { exact: true })).toHaveCount(0); -}); - test("plus picker can create a Private computer bot", async ({ page }, testInfo) => { const stamp = Date.now(); await signup(page, `new-bot-private-${stamp}@rakazo.test`, "password12", "New Bot Private"); diff --git a/apps/web/e2e/onboarding-agent.spec.ts b/apps/web/e2e/onboarding-agent.spec.ts index 75d72542..0ea23bda 100644 --- a/apps/web/e2e/onboarding-agent.spec.ts +++ b/apps/web/e2e/onboarding-agent.spec.ts @@ -1,59 +1,29 @@ import { expect, test } from "@playwright/test"; -import { captureScreenshot, sayHiToFirstBot, signup } from "./helpers"; +import { captureScreenshot, reachMeetStep, signInWithChatGpt, signupWithEmail } from "./helpers"; -test("onboarding waits for Claude Code before opening Chief", async ({ page }, testInfo) => { - let installed = false; +test("an account without a ChatGPT plan connects it before meeting Chief", async ({ + page, +}, testInfo) => { + // The desktop's local account is made without ChatGPT; an email account stands in for it. await page.route("**/rpc/agent/status", (route) => route.fulfill({ json: { json: { agent: "claude-code", chatgpt: false, - installed, - version: installed ? "2.1.0" : null, - loggedIn: installed, + installed: false, + version: null, + loggedIn: false, platform: "linux", }, }, }), ); - await page.route("**/rpc/integrationSetup/get", (route) => - route.fulfill({ - json: { - json: { - canConfigure: false, - needsSetup: false, - webUrl: "https://example.test/integrations/setup", - providers: [], - }, - }, - }), - ); - const stamp = Date.now(); - await signup(page, `agent-setup-${stamp}@rakazo.test`, "password12", `Agent setup ${stamp}`); - - await expect(page.getByRole("heading", { name: "Connect your agent" })).toBeVisible({ - timeout: 20_000, - }); - await expect(page.getByText("Not installed")).toBeVisible(); - const continueButton = page.getByRole("button", { name: "Continue" }); - await expect(continueButton).toBeDisabled(); - await captureScreenshot(page, testInfo, "onboarding-agent-not-installed"); - - await page.getByRole("button", { name: "Install" }).click(); - await expect(page.getByText("curl -fsSL https://claude.ai/install.sh | bash")).toBeVisible(); - await captureScreenshot(page, testInfo, "onboarding-agent-install-command"); - - installed = true; - await page.getByRole("button", { name: "Check again" }).click(); - await expect(page.getByTestId("onboarding-agent-claude").getByLabel("Ready")).toBeVisible(); - await expect(page.getByRole("button", { name: "Install" })).toHaveCount(0); - await captureScreenshot(page, testInfo, "onboarding-agent-ready"); - - await continueButton.click(); - await sayHiToFirstBot(page); - await expect(page.getByRole("combobox", { name: "Message Chief" })).toBeVisible({ - timeout: 20_000, - }); + await signupWithEmail(page, `agent-chatgpt-${stamp}@rakazo.test`, "password12", "Plan"); + await page.waitForURL(/\/onboarding/, { timeout: 20_000 }); + await expect(page.getByRole("heading", { name: "Connect your agent" })).toHaveCount(0); + await signInWithChatGpt(page, `agent-chatgpt-plan-${stamp}@rakazo.test`, "Plan", testInfo); + await reachMeetStep(page); + await captureScreenshot(page, testInfo, "onboarding-chatgpt-linked"); }); diff --git a/apps/web/e2e/onboarding-auto-skip.spec.ts b/apps/web/e2e/onboarding-auto-skip.spec.ts index 20bdc38b..aea53a8d 100644 --- a/apps/web/e2e/onboarding-auto-skip.spec.ts +++ b/apps/web/e2e/onboarding-auto-skip.spec.ts @@ -1,57 +1,20 @@ import { expect, test } from "@playwright/test"; -import { captureScreenshot, reachMeetStep, signup } from "./helpers"; - -test("onboarding skips agent setup when Claude Code is ready and meets the first bot", async ({ - page, -}, testInfo) => { - await page.route("**/rpc/agent/status", (route) => - route.fulfill({ - json: { - json: { - agent: "claude-code", - chatgpt: false, - installed: true, - version: "2.1.0", - loggedIn: true, - platform: "linux", - }, - }, - }), - ); - - await page.route("**/rpc/integrationSetup/get", (route) => - route.fulfill({ - json: { - json: { - canConfigure: false, - needsSetup: false, - webUrl: "https://example.test/integrations/setup", - providers: [], - }, - }, - }), - ); +import { captureScreenshot, reachMeetStep, sayHiToFirstBot, signup } from "./helpers"; +test("meet the first bot offers six colors and creates Chief", async ({ page }, testInfo) => { const createRequest = page.waitForRequest("**/rpc/bots/create"); const stamp = Date.now(); - await signup( - page, - `agent-auto-skip-${stamp}@rakazo.test`, - "password12", - `Agent auto skip ${stamp}`, - ); + await signup(page, `meet-first-bot-${stamp}@rakazo.test`, "password12", `Meet ${stamp}`); await expect(page.getByRole("heading", { name: "Connect your agent" })).toBeHidden(); await expect(page.getByRole("heading", { name: "Server integrations" })).toBeHidden(); - for (const name of ["Composio", "Pipedream", "Executor"]) { - await expect(page.getByRole("button", { name, exact: true })).toBeHidden(); - } await reachMeetStep(page); const name = page.getByRole("textbox", { name: "Name" }); await expect(name).toHaveValue("Chief"); + await expect(page.getByRole("button", { name: /^Color / })).toHaveCount(6); await page.getByRole("button", { name: "Color #10B981" }).click(); await captureScreenshot(page, testInfo, "onboarding-meet-first-bot"); - await page.getByRole("button", { name: "Say hi", exact: true }).click(); + await sayHiToFirstBot(page); expect((await createRequest).postDataJSON()).toMatchObject({ json: { @@ -69,7 +32,7 @@ test("onboarding skips agent setup when Claude Code is ready and meets the first await captureScreenshot(page, testInfo, "onboarding-auto-skip"); }); -test("connect your apps lists featured apps with their logos and can be skipped", async ({ +test("connect your apps lists featured apps with their logos and opens the chat", async ({ page, }, testInfo) => { const logo = (fill: string) => @@ -107,18 +70,24 @@ test("connect your apps lists featured apps with their logos and can be skipped" const stamp = Date.now(); await signup(page, `onboarding-apps-${stamp}@rakazo.test`, "password12", `Apps ${stamp}`); + await reachMeetStep(page); + await page.getByRole("button", { name: "Continue", exact: true }).click(); await expect(page.getByRole("heading", { name: "Connect your apps" })).toBeVisible({ timeout: 20_000, }); const list = page.getByRole("list"); await expect(list.getByText("Gmail", { exact: true })).toBeVisible(); await expect(list.locator("img")).toHaveCount(2); + // An app without a logo shows its first letter. + await expect(list.getByText("S", { exact: true })).toBeVisible(); + await expect(page.getByRole("img", { name: "Step 3 of 3" })).toBeVisible(); await expect(page.getByRole("button", { name: "Continue" })).toBeDisabled(); await page.getByRole("button", { name: "Connect Gmail" }).click(); await expect(list.getByText("Connected")).toBeVisible(); await expect(page.getByRole("button", { name: "Continue" })).toBeEnabled(); await captureScreenshot(page, testInfo, "onboarding-connect-apps"); - await page.getByRole("button", { name: "Skip for now" }).click(); - await expect(page.getByRole("heading", { name: "Meet your first bot" })).toBeVisible(); + await page.getByRole("button", { name: "Continue" }).click(); + await page.waitForURL(/\/app\//, { timeout: 20_000 }); + await expect(page.getByRole("combobox", { name: "Message Chief" })).toBeVisible(); }); diff --git a/apps/web/e2e/onboarding-conversation.spec.ts b/apps/web/e2e/onboarding-conversation.spec.ts index 74ffe6d0..cc03fd49 100644 --- a/apps/web/e2e/onboarding-conversation.spec.ts +++ b/apps/web/e2e/onboarding-conversation.spec.ts @@ -1,133 +1,42 @@ -import { expect, type Page, test } from "@playwright/test"; -import { captureScreenshot, completeOnboarding, openUserSettings, rpc, signup } from "./helpers"; +import { expect, test } from "@playwright/test"; +import { captureScreenshot, sayHiToFirstBot, signInWithChatGpt } from "./helpers"; -function slackCard(page: Page) { - return page.getByRole("group", { name: "Slack connection" }); -} - -test("focus choice suggests apps and preserves a completed connection", async ({ +test("welcome, ChatGPT sign-in, meet Chief, skip apps, then Chief introduces itself", async ({ page, }, testInfo) => { const stamp = Date.now(); - await signup(page, `onboarding-${stamp}@rakazo.test`, "password12", "Robin"); - await completeOnboarding(page); - + await page.goto("/"); + await expect(page.locator('[data-rakazo-surface="welcome"]')).toBeVisible(); + await captureScreenshot(page, testInfo, "00-welcome"); + await page.getByRole("button", { name: /Sign up/ }).click(); + + await expect(page.getByRole("img", { name: "Step 1 of 3" })).toBeVisible(); + await expect(page.getByPlaceholder("Your email address")).toHaveCount(0); + await signInWithChatGpt(page, `onboarding-${stamp}@rakazo.test`, "Robin", testInfo); + await page.waitForURL(/\/onboarding/, { timeout: 20_000 }); + await expect(page.getByRole("img", { name: "Step 2 of 3" })).toBeVisible(); + await expect(page.getByRole("button", { name: /^Color / })).toHaveCount(6); + await sayHiToFirstBot(page, testInfo); + + const transcript = page.getByTestId("transcript"); await expect( - page.getByText("Hey Robin. Fresh start on my side, so I’ll keep this short."), - ).toHaveCount(0); - await expect(page.getByText("What do you want me on first?", { exact: true })).toBeVisible(); - await expect(page.getByRole("button", { name: /Day-to-day work/ })).toBeVisible(); - await expect(page.getByRole("button", { name: /Research & writing/ })).toBeVisible(); - await expect(page.getByRole("button", { name: /A bit of everything/ })).toBeVisible(); - await page.mouse.move(1, 1); - await captureScreenshot(page, testInfo, "01-focus-choice"); - await captureScreenshot(page, testInfo, "choice-card-onboarding"); - - await page.getByRole("button", { name: /Day-to-day work/ }).click(); - // The focus step suggests apps but must not rename the bot: the name the - // user chose during creation ("Chief") is preserved. - await expect(page.locator("main").getByText("Chief", { exact: true })).toBeVisible(); - await expect(page.getByPlaceholder("Message Chief")).toBeVisible(); - await expect(page.getByText("Slack", { exact: true })).toBeVisible(); - await expect(page.getByText("Gmail", { exact: true })).toBeVisible(); - const connectionCards = page.getByRole("group", { name: / connection$/ }); - await expect(connectionCards).toHaveCount(3); - const cardBoxes = await connectionCards.evaluateAll((cards) => - cards.map((card) => { - const { bottom, top } = card.getBoundingClientRect(); - return { bottom, top }; - }), - ); - expect(cardBoxes[1].top - cardBoxes[0].bottom).toBeGreaterThanOrEqual(8); - expect(cardBoxes[2].top - cardBoxes[1].bottom).toBeGreaterThanOrEqual(8); - await page - .getByTestId("transcript") - .getByText("Hit those three and I’ll start pulling the picture.") - .scrollIntoViewIfNeeded(); + transcript.getByText( + "Hi, I'm Chief. I run on your own subscription and work on my own computer. What should I take off your plate first?", + ), + ).toBeVisible({ timeout: 20_000 }); + const chips = transcript.getByTestId("suggestion-chips"); + for (const chip of ["Plan my week", "Find something for me", "Make another bot"]) { + await expect(chips.getByRole("button", { name: chip, exact: true })).toBeVisible(); + } await page.mouse.move(1, 1); - await captureScreenshot(page, testInfo, "02-app-suggestions"); - const authorizeButton = slackCard(page).getByRole("button", { name: "Authorize" }); - const restingBackground = await authorizeButton.evaluate( - (button) => getComputedStyle(button).backgroundColor, - ); - const accentBackground = await authorizeButton.evaluate((button) => { - const probe = document.createElement("span"); - probe.style.backgroundColor = "var(--accent)"; - button.append(probe); - const backgroundColor = getComputedStyle(probe).backgroundColor; - probe.remove(); - return backgroundColor; - }); - expect(accentBackground).not.toBe(restingBackground); - await authorizeButton.hover(); - await expect - .poll(() => authorizeButton.evaluate((button) => getComputedStyle(button).backgroundColor)) - .toBe(accentBackground); - await captureScreenshot(page, testInfo, "02-app-suggestions-authorize-hover"); + await captureScreenshot(page, testInfo, "04-first-chat-intro"); - await authorizeButton.click(); - await expect(slackCard(page).getByText("Connected", { exact: true })).toBeVisible(); - await expect(slackCard(page).getByText("Connected", { exact: true })).toHaveCSS("opacity", "1"); - await expect - .poll(async () => { - const connections = await rpc>( - page, - "connections/list", - {}, - ); - return connections.some( - (connection) => connection.provider === "SLACK" && connection.status === "connected", - ); - }) - .toBe(true); - await page.mouse.move(1, 1); - await captureScreenshot(page, testInfo, "03-slack-connected"); + await chips.getByRole("button", { name: "Find something for me", exact: true }).click(); + await expect( + transcript.getByTestId("message-user-bubble").filter({ hasText: "Find something for me" }), + ).toBeVisible(); + // Opening the chat again does not post a second intro. await page.reload(); - await expect(slackCard(page).getByText("Connected", { exact: true })).toBeVisible(); - await page.mouse.move(1, 1); - await captureScreenshot(page, testInfo, "04-connected-after-reload"); -}); - -test("focus choice follows Simplified Chinese UI locale", async ({ page }, testInfo) => { - const stamp = Date.now(); - await signup(page, `onboarding-zh-cn-${stamp}@rakazo.test`, "password12", "Robin"); - await completeOnboarding(page); - - await expect(page.getByText("What do you want me on first?", { exact: true })).toBeVisible(); - - const settings = await openUserSettings(page); - const picker = settings.getByTestId("ui-locale-select"); - await picker.click(); - await settings.getByRole("option", { name: "简体中文", exact: true }).click(); - await expect(settings.getByRole("heading", { name: "语言", exact: true })).toBeVisible(); - await settings.getByRole("button", { name: "关闭用户设置" }).click(); - await expect(settings).toHaveCount(0); - - await expect(page.getByText("What do you want me on first?", { exact: true })).toHaveCount(0); - await expect(page.getByText("你想让我先做什么?", { exact: true })).toBeVisible(); - await expect(page.getByRole("button", { name: /日常工作/ })).toBeVisible(); - await expect(page.getByRole("button", { name: /收件箱和邮件/ })).toBeVisible(); - await expect(page.getByRole("button", { name: /调研和写作/ })).toBeVisible(); - await expect(page.getByRole("button", { name: /什么都做一点/ })).toBeVisible(); - await page.mouse.move(1, 1); - await captureScreenshot(page, testInfo, "choice-card-onboarding-zh-cn"); -}); - -test("choice refresh failures leave options available for retry", async ({ page }) => { - await signup(page, `choice-refresh-${Date.now()}@rakazo.test`, "password12", "Choice Retry"); - await completeOnboarding(page); - const choice = page.getByRole("button", { name: /Day-to-day work/ }); - await expect(choice).toBeEnabled(); - // Keep the existing choice rendered while its save succeeds and navigation refresh fails. - await page.route("**/rpc/onboarding/choose", (route) => - route.fulfill({ - status: 200, - contentType: "application/json", - body: JSON.stringify({ json: { ok: true } }), - }), - ); - await page.route("**/rpc/spaces/list", (route) => route.abort()); - await Promise.all([page.waitForRequest("**/rpc/spaces/list"), choice.click()]); - await expect(choice).toBeEnabled(); + await expect(transcript.getByTestId("suggestion-chips")).toHaveCount(1); }); diff --git a/apps/web/e2e/sign-in-chatgpt.spec.ts b/apps/web/e2e/sign-in-chatgpt.spec.ts index 56fab2fb..e9428bb0 100644 --- a/apps/web/e2e/sign-in-chatgpt.spec.ts +++ b/apps/web/e2e/sign-in-chatgpt.spec.ts @@ -1,7 +1,7 @@ import { expect, test } from "@playwright/test"; -import { captureScreenshot, signup } from "./helpers"; +import { captureScreenshot } from "./helpers"; -test("offers Sign in with ChatGPT when the browser shares the server's computer", async ({ +test("signs in only with ChatGPT when the browser shares the server's computer", async ({ page, }, testInfo) => { await page.route("**/api/auth/capabilities", (route) => @@ -17,7 +17,9 @@ test("offers Sign in with ChatGPT when the browser shares the server's computer" await page.route("**/api/auth/get-session", (route) => route.fulfill({ json: null })); await page.goto("/sign-in"); - const button = page.getByRole("button", { name: "Sign in with ChatGPT" }); + await expect(page.getByRole("heading", { name: "Sign in with ChatGPT" })).toBeVisible(); + await expect(page.getByPlaceholder("Your email address")).toHaveCount(0); + const button = page.getByRole("button", { name: "Continue", exact: true }); await expect(button).toBeVisible(); await captureScreenshot(page, testInfo, "sign-in-chatgpt"); @@ -26,7 +28,7 @@ test("offers Sign in with ChatGPT when the browser shares the server's computer" await expect(button).toBeEnabled(); }); -test("hides Sign in with ChatGPT for a server on another computer", async ({ page }) => { +test("falls back to email for a server on another computer", async ({ page }) => { await page.route("**/api/auth/capabilities", (route) => route.fulfill({ json: { passwordReset: false, resetUrl: null, chatgpt: null } }), ); @@ -35,58 +37,3 @@ test("hides Sign in with ChatGPT for a server on another computer", async ({ pag await expect(page.getByRole("button", { name: "Continue with email" })).toBeVisible(); await expect(page.getByRole("button", { name: "Sign in with ChatGPT" })).toHaveCount(0); }); - -test("onboarding accepts ChatGPT in place of Claude Code", async ({ page }, testInfo) => { - let chatgpt = false; - await page.route("**/api/auth/capabilities", (route) => - route.fulfill({ json: { passwordReset: false, resetUrl: null, chatgpt: "browser" } }), - ); - await page.route("**/rpc/agent/status", (route) => - route.fulfill({ - json: { - json: { - agent: "claude-code", - chatgpt, - installed: false, - version: null, - loggedIn: false, - platform: "linux", - }, - }, - }), - ); - await page.route("**/rpc/integrationSetup/get", (route) => - route.fulfill({ - json: { - json: { - canConfigure: false, - needsSetup: false, - webUrl: "https://example.test/integrations/setup", - providers: [], - }, - }, - }), - ); - await page.route("**/api/auth/chatgpt/start", (route) => - route.fulfill({ json: { flowId: "flow-1", url: "https://auth.openai.com/oauth/authorize" } }), - ); - await page.route("**/api/auth/chatgpt/finish", (route) => { - chatgpt = true; - return route.fulfill({ json: { status: "connected", created: false, plan: true } }); - }); - await page.route("https://auth.openai.com/**", (route) => route.fulfill({ body: "" })); - - const stamp = Date.now(); - await signup(page, `agent-chatgpt-${stamp}@rakazo.test`, "password12", `ChatGPT ${stamp}`); - await expect(page.getByRole("heading", { name: "Connect your agent" })).toBeVisible({ - timeout: 20_000, - }); - const continueButton = page.getByRole("button", { name: "Continue" }); - await expect(continueButton).toBeDisabled(); - await page.getByRole("button", { name: "Sign in with ChatGPT" }).click(); - await expect(page.getByTestId("onboarding-agent-chatgpt").getByText("Ready")).toBeVisible({ - timeout: 10_000, - }); - await expect(continueButton).toBeEnabled(); - await captureScreenshot(page, testInfo, "onboarding-agent-chatgpt"); -}); diff --git a/apps/web/src/components/BotAvatarChoices.tsx b/apps/web/src/components/BotAvatarChoices.tsx index 19f59899..402c88d5 100644 --- a/apps/web/src/components/BotAvatarChoices.tsx +++ b/apps/web/src/components/BotAvatarChoices.tsx @@ -34,10 +34,12 @@ export function BotShapeChoices({ } export function BotColorChoices({ + colors = GROK_BOT_COLORS, value, onChange, className, }: { + colors?: readonly string[]; value: string | null; onChange: (color: string) => void; className?: string; @@ -48,7 +50,7 @@ export function BotColorChoices({ aria-label={t`Color`} className={cn("m-0 flex flex-wrap gap-2.5 border-0 p-0", className)} > - {GROK_BOT_COLORS.map((color) => { + {colors.map((color) => { const selected = value?.toLowerCase() === color.toLowerCase(); return ( - + Back to sign in diff --git a/apps/web/src/pages/Onboarding.tsx b/apps/web/src/pages/Onboarding.tsx index fdca9425..590a0c1b 100644 --- a/apps/web/src/pages/Onboarding.tsx +++ b/apps/web/src/pages/Onboarding.tsx @@ -1,15 +1,21 @@ import { Trans, useLingui } from "@lingui/react/macro"; -import type { AgentStatus, ConnectionCatalogItem, IntegrationSetupState } from "@milo/contracts"; +import type { ConnectionCatalogItem } from "@milo/contracts"; import { BOT_NAME_MAX_LENGTH } from "@milo/contracts"; -import { buildFeaturedConnectorTiles } from "@milo/core"; -import { BotAvatar, Button, DEFAULT_GROK_BOT_COLOR, Input } from "@milo/ui-web"; +import { + BOT_PALETTE_COLORS, + buildFeaturedConnectorTiles, + DEFAULT_GROK_BOT_COLOR, +} from "@milo/core"; +import { BotAvatar, Button, Input } from "@milo/ui-web"; import { useEffect, useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; import { BotColorChoices } from "../components/BotAvatarChoices"; -import { IntegrationSetup } from "../components/integrations/IntegrationSetup"; +import type { ChatGptCapture } from "../lib/chatgpt-sign-in"; +import { chatGptAvailable } from "../lib/chatgpt-sign-in"; import { rpc } from "../lib/rpc"; -import { agentReady, OnboardingAgentStep } from "./OnboardingAgent"; +import { agentReady } from "./OnboardingAgent"; import { OnboardingAppsStep } from "./OnboardingApps"; +import { ChatGptStep, OnboardingDots } from "./OnboardingChatGpt"; const FIRST_BOT_NAME = "Chief"; const FIRST_BOT_SPAWN_KEY = "onboarding:first"; @@ -71,54 +77,50 @@ async function ensureFirstBot(first: FirstBot): Promise<{ id: string }> { return firstBotEnsure; } +async function chatGptCapture(): Promise { + const response = await fetch("/api/auth/capabilities"); + if (!response.ok) return null; + const capabilities = (await response.json()) as { chatgpt?: ChatGptCapture }; + return capabilities.chatgpt ?? null; +} + +/** + * Sign in with ChatGPT (when the account has no plan yet), meet the first bot, + * connect apps, then open the bot's chat with its intro. + */ export function OnboardingPage() { const { t } = useLingui(); const navigate = useNavigate(); - const [step, setStep] = useState<"loading" | "agent" | "integrations" | "apps" | "meet">( - "loading", - ); + const [step, setStep] = useState<"loading" | "chatgpt" | "meet" | "apps">("loading"); const [catalog, setCatalog] = useState([]); const [botName, setBotName] = useState(FIRST_BOT_NAME); const [botColor, setBotColor] = useState(DEFAULT_GROK_BOT_COLOR); const [creating, setCreating] = useState(false); - const [agentStatus, setAgentStatus] = useState(null); - const [integrationSetup, setIntegrationSetup] = useState(null); - const [integrationServers, setIntegrationServers] = useState([]); const createStartedRef = useRef(false); const [error, setError] = useState(null); + const hasApps = buildFeaturedConnectorTiles(catalog).some((tile) => tile.item); useEffect(() => { void Promise.all([ rpc.agent.status().catch(() => null), - rpc.integrationSetup.get().catch(() => null), + chatGptCapture().catch(() => null), rpc.connections.catalog({}).catch(() => []), rpc.bots.list().catch(() => []), ]) - .then(([agent, integrations, apps, bots]) => { + .then(([agent, capture, apps, bots]) => { // A stale onboarding URL in a space that already met its first bot goes back to it. const existing = findFirstBot(bots); if (existing) { navigate(`/app/${existing.id}`, { replace: true }); return; } - setAgentStatus(agent); - setIntegrationSetup(integrations); setCatalog(apps); - setStep( - agent && !agentReady(agent) - ? "agent" - : integrations?.needsSetup - ? "integrations" - : afterIntegrations(apps), - ); + // Accounts made without ChatGPT (the desktop's local account) connect it here. + setStep(agent && !agentReady(agent) && chatGptAvailable(capture) ? "chatgpt" : "meet"); }) .catch(() => setStep("meet")); }, []); - function afterIntegrations(apps: ConnectionCatalogItem[]) { - return buildFeaturedConnectorTiles(apps).some((tile) => tile.item) ? "apps" : "meet"; - } - async function createFirstBot() { if (createStartedRef.current || !botName.trim()) return; createStartedRef.current = true; @@ -126,18 +128,7 @@ export function OnboardingPage() { setError(null); try { const bot = await ensureFirstBot({ name: botName.trim(), color: `${botColor}::shape_0` }); - for (const serverId of integrationServers) { - await rpc.mcp.assignments.approve({ botId: bot.id, serverId }); - } - // Onboarding continues conversationally in the thread: greeting first, - // then the focus choice (immediate for the first bot). - const started = await rpc.onboarding - .start({ botId: bot.id }) - .then(() => true) - .catch(() => false); - if (started) { - await rpc.onboarding.promptFocus({ botId: bot.id }).catch(() => undefined); - } + await rpc.onboarding.introduce({ botId: bot.id }).catch(() => undefined); navigate(`/app/${bot.id}`); } catch (err) { createStartedRef.current = false; @@ -154,46 +145,21 @@ export function OnboardingPage() { Loading…

) : null} - {step === "agent" && agentStatus ? ( - - setStep(integrationSetup?.needsSetup ? "integrations" : afterIntegrations(catalog)) - } - /> - ) : null} - {step === "integrations" ? ( -
- { - // Server setup can turn on a catalog that was empty before. - void rpc.connections - .catalog({}) - .catch(() => []) - .then((apps) => { - setCatalog(apps); - setStep(afterIntegrations(apps)); - }); - }} - onServerConnected={(id) => - setIntegrationServers((current) => [...new Set([...current, id])]) - } - /> + {step === "chatgpt" ? ( +
+ setStep("meet")} />
) : null} - {step === "apps" ? ( - setStep("meet")} /> - ) : null} {step === "meet" ? (
{ event.preventDefault(); - void createFirstBot(); + if (hasApps) setStep("apps"); + else void createFirstBot(); }} > +

Meet your first bot @@ -205,7 +171,12 @@ export function OnboardingPage() { onChange={(event) => setBotName(event.target.value)} className="h-12 w-full max-w-[320px] text-center text-[18px] font-medium md:text-[18px]" /> - + {error ? (

{error} @@ -217,10 +188,24 @@ export function OnboardingPage() { className="mt-2 px-6" disabled={!botName.trim() || creating} > - {creating ? Opening chat… : Say hi} + {hasApps ? ( + Continue + ) : creating ? ( + Opening chat… + ) : ( + Say hi + )}

) : null} + {step === "apps" ? ( + void createFirstBot()} + /> + ) : null}

); diff --git a/apps/web/src/pages/OnboardingApps.tsx b/apps/web/src/pages/OnboardingApps.tsx index 6678d5d8..9a35fae6 100644 --- a/apps/web/src/pages/OnboardingApps.tsx +++ b/apps/web/src/pages/OnboardingApps.tsx @@ -2,17 +2,23 @@ import { Trans, useLingui } from "@lingui/react/macro"; import type { ConnectionCatalogItem } from "@milo/contracts"; import { buildFeaturedConnectorTiles } from "@milo/core"; import { Button } from "@milo/ui-web"; -import { Check, Plug } from "lucide-react"; +import { Check } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { Shimmer } from "../components/ai/primitives"; import { connectCatalogApp } from "../lib/connect-app"; +import { OnboardingDots } from "./OnboardingChatGpt"; /** The featured catalog apps, each with Connect. Skipping is always allowed. */ export function OnboardingAppsStep({ catalog, + busy = false, + error: continueError = null, onContinue, }: { catalog: ConnectionCatalogItem[]; + /** Set while continuing, so the step cannot be left twice. */ + busy?: boolean; + error?: string | null; onContinue: () => void; }) { const { t } = useLingui(); @@ -52,6 +58,7 @@ export function OnboardingAppsStep({ return (
+

Connect your apps

@@ -63,12 +70,12 @@ export function OnboardingAppsStep({ > {label} @@ -94,16 +101,21 @@ export function OnboardingAppsStep({ ))} - {error ? ( + {error || continueError ? (

- {error} + {error ?? continueError}

) : null}
- -
diff --git a/apps/web/src/pages/OnboardingChatGpt.tsx b/apps/web/src/pages/OnboardingChatGpt.tsx new file mode 100644 index 00000000..a5e84c1f --- /dev/null +++ b/apps/web/src/pages/OnboardingChatGpt.tsx @@ -0,0 +1,65 @@ +import { Trans, useLingui } from "@lingui/react/macro"; +import { Button, cn } from "@milo/ui-web"; +import { Shimmer } from "../components/ai/primitives"; +import type { ChatGptConnected } from "../lib/chatgpt-sign-in"; +import { useChatGptSignIn } from "../lib/chatgpt-sign-in"; + +const ONBOARDING_STEPS = 3; + +/** Progress through sign-in, meeting the first bot, and connecting apps. */ +export function OnboardingDots({ step }: { step: 1 | 2 | 3 }) { + const { t } = useLingui(); + return ( +
+ {Array.from({ length: ONBOARDING_STEPS }, (_, index) => ( + + ))} +
+ ); +} + +/** + * The only way in: one ChatGPT sign-in. Signed out, it signs in or creates the + * account; signed in, it links the plan the account's bots run on. + */ +export function ChatGptStep({ onConnected }: { onConnected: (result: ChatGptConnected) => void }) { + const chatgpt = useChatGptSignIn(onConnected); + return ( +
+ +

+ Sign in with ChatGPT +

+ {chatgpt.error ? ( +

+ {chatgpt.error} +

+ ) : null} + +
+ ); +} diff --git a/apps/web/src/pages/Shell.tsx b/apps/web/src/pages/Shell.tsx index f8f1e739..eb5e9fd4 100644 --- a/apps/web/src/pages/Shell.tsx +++ b/apps/web/src/pages/Shell.tsx @@ -189,7 +189,6 @@ import { } from "../lib/computer-screen"; import { publishComputerCommand } from "../lib/computer-workspace"; import { desktopBridge } from "../lib/desktop"; -import { scheduleFocusPrompt } from "../lib/focus-prompt"; import { localTimezone } from "../lib/local-timezone"; import { copyableMessageText } from "../lib/message-text"; import { @@ -274,6 +273,7 @@ import { ChartBlockView, ChoiceCard, McpApprovalCard, + SuggestionsCard, } from "./shell/message-cards"; import { WindowChrome } from "./WindowChrome"; @@ -560,8 +560,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { const [draggedBotId, setDraggedBotId] = useState(null); const [createMenuOpen, setCreateMenuOpen] = useState(false); const [botsSidebarCollapsed, setBotsSidebarCollapsed] = useState(false); - const focusPromptAbortRef = useRef(null); - const focusPromptBotIdRef = useRef(null); const botsSidebarEdgeDragRef = useRef<{ startX: number; mode: "expand" | "collapse" } | null>( null, ); @@ -2141,12 +2139,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { sendingRef.current = true; setSending(true); setSendError(null); - const dropDelayedSetup = () => { - // Only after successful engagement so a failed upload/send keeps the setup card. - if (initialBotTarget && focusPromptBotIdRef.current === initialBotTarget) { - cancelFocusPrompt(); - } - }; try { if (plan.shouldRunRoutines) { const sendNonce = newClientNonce(); @@ -2160,7 +2152,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { ); } if (!plan.shouldSend) { - dropDelayedSetup(); clearReply(); revokePendingAttachmentPreviews(attachments); setPendingAttachments((current) => @@ -2227,7 +2218,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { ); } } - dropDelayedSetup(); clearReply(); revokePendingAttachmentPreviews(attachments); setPendingAttachments((current) => @@ -2389,12 +2379,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { await refreshBots().catch(() => undefined); } - function cancelFocusPrompt() { - focusPromptAbortRef.current?.abort(); - focusPromptAbortRef.current = null; - focusPromptBotIdRef.current = null; - } - function setBotsSidebarCollapsedPref(collapsed: boolean) { setBotsSidebarCollapsed(collapsed); writeBotsSidebarCollapsed(userId, collapsed); @@ -2406,7 +2390,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { } async function createBot(input: CreateBotInputDraft) { - const isFirstBot = botsRef.current.length === 0; const bot = await rpc.bots.create({ ...normalizeCreateBotProfile(input), notifyOnFinish: true, @@ -2418,38 +2401,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { ); navigate(`/app/${bot.id}`); setPanel(null); - // Register cancellation before awaiting start so leaving the bot during - // startup cannot miss the abort and still schedule a late focus card. - cancelFocusPrompt(); - const controller = new AbortController(); - focusPromptAbortRef.current = controller; - focusPromptBotIdRef.current = bot.id; - const started = await rpc.onboarding - .start({ botId: bot.id }) - .then(() => true) - .catch(() => false); - if (!started || controller.signal.aborted || focusPromptBotIdRef.current !== bot.id) { - if (focusPromptAbortRef.current === controller) { - focusPromptAbortRef.current = null; - focusPromptBotIdRef.current = null; - } - await refreshBots().catch(() => undefined); - return; - } - void scheduleFocusPrompt({ - immediate: isFirstBot, - signal: controller.signal, - shouldSkip: () => sendingRef.current, - prompt: async () => { - if (focusPromptBotIdRef.current !== bot.id || activeBotId.current !== bot.id) return; - await rpc.onboarding.promptFocus({ botId: bot.id }).catch(() => undefined); - }, - }).finally(() => { - if (focusPromptAbortRef.current === controller) { - focusPromptAbortRef.current = null; - focusPromptBotIdRef.current = null; - } - }); await refreshBots().catch(() => undefined); } @@ -2553,14 +2504,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { setComputerBotId(active?.id); }, [active?.id]); - useEffect(() => { - if (focusPromptBotIdRef.current && focusPromptBotIdRef.current !== active?.id) { - cancelFocusPrompt(); - } - }, [active?.id]); - - useEffect(() => () => cancelFocusPrompt(), []); - useEffect(() => { if (!computer?.busyBotName) { setComputerError(null); @@ -6488,6 +6431,11 @@ const MessageView = memo(function MessageView({ if (!botId) return null; return ; } + if (block.kind === "suggestions") { + const botId = "botId" in artifactTarget ? artifactTarget.botId : message.botId; + if (!botId) return null; + return ; + } if (block.kind === "app_connect") { const botId = "botId" in artifactTarget ? artifactTarget.botId : message.botId; if (!botId) return null; diff --git a/apps/web/src/pages/shell/message-cards.tsx b/apps/web/src/pages/shell/message-cards.tsx index e523db28..11c7c2c9 100644 --- a/apps/web/src/pages/shell/message-cards.tsx +++ b/apps/web/src/pages/shell/message-cards.tsx @@ -1,4 +1,5 @@ import { Trans, useLingui } from "@lingui/react/macro"; +import { SuggestionChips } from "@milo/chat-ui/web"; import type { MessageBlock } from "@milo/contracts"; import { abortableDelay } from "@milo/core"; import { Button, Dialog, DialogClose, DialogContent, DialogTitle } from "@milo/ui-web"; @@ -7,9 +8,50 @@ import { useEffect, useRef, useState } from "react"; import { BuiCard, SuccessPop } from "../../components/ai/primitives"; import { type ArtifactTarget, decodeArtifactBase64 } from "../../lib/artifact-open"; import { chartViewport } from "../../lib/chart-viewport"; +import { newClientId } from "../../lib/client-id"; import { connectMcpOauth } from "../../lib/mcp-connect"; import { rpc } from "../../lib/rpc"; +/** Idea chips under a bot's intro. Picking one sends it to the bot as the user's message. */ +export function SuggestionsCard({ + botId, + block, + onSent, +}: { + botId: string; + block: Extract; + onSent: () => Promise; +}) { + const { t } = useLingui(); + const [pending, setPending] = useState(false); + const [error, setError] = useState(null); + + async function pick(text: string) { + setPending(true); + setError(null); + try { + await rpc.threads.send({ botId, clientNonce: newClientId(), text }); + await onSent(); + } catch (err) { + setError(err instanceof Error ? err.message : t`Failed to send message`); + } finally { + setPending(false); + } + } + + return ( +
+ void pick(item)} /> + {error ? ( +

+ {error} +

+ ) : null} +
+ ); +} + +// The focus card below is from the pre-v0 onboarding script; old threads still show it. export function ChoiceCard({ botId, block, diff --git a/packages/adapters/src/chatgpt-sign-in-emulator.test.ts b/packages/adapters/src/chatgpt-sign-in-emulator.test.ts new file mode 100644 index 00000000..f67af082 --- /dev/null +++ b/packages/adapters/src/chatgpt-sign-in-emulator.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { ChatGptSignInEmulator } from "./chatgpt-sign-in-emulator.js"; + +describe("ChatGptSignInEmulator", () => { + it("stays pending until a test approves the flow, then connects once", async () => { + const emulator = new ChatGptSignInEmulator(); + const { flowId, url } = await emulator.start(); + expect(new URL(url).searchParams.get("state")).toBe(flowId); + expect(await emulator.complete(flowId)).toEqual({ status: "pending" }); + + expect(emulator.approve(flowId, { email: "Ada@Example.test", name: "Ada" })).toBe(true); + expect(await emulator.complete(flowId)).toEqual({ + status: "connected", + clientId: "emulated-client", + identity: { + subject: "emulated:ada@example.test", + email: "ada@example.test", + emailVerified: true, + name: "Ada", + }, + }); + expect(await emulator.complete(flowId)).toMatchObject({ status: "error" }); + }); + + it("refuses to approve an unknown flow", () => { + expect(new ChatGptSignInEmulator().approve("missing", { email: "a@example.test" })).toBe(false); + }); +}); diff --git a/packages/adapters/src/chatgpt-sign-in-emulator.ts b/packages/adapters/src/chatgpt-sign-in-emulator.ts new file mode 100644 index 00000000..42b0515a --- /dev/null +++ b/packages/adapters/src/chatgpt-sign-in-emulator.ts @@ -0,0 +1,55 @@ +import { randomBytes } from "node:crypto"; +import type { ChatGptCallback, ChatGptIdentity, ChatGptSignInResult } from "./chatgpt-plan.js"; + +/** The flow surface the auth endpoints use, shared by `ChatGptSignIn` and the emulator. */ +export interface ChatGptSignInFlow { + start(input: { clientId?: string; listen: boolean }): Promise<{ flowId: string; url: string }>; + complete(flowId: string, callback?: ChatGptCallback): Promise; + cancelAll(): void; +} + +export const CHATGPT_EMULATOR_AUTHORIZE_URL = "https://chatgpt.example.test/authorize"; +const EMULATOR_CLIENT_ID = "emulated-client"; + +/** + * Deterministic, offline Sign in with ChatGPT for tests. The authorize URL never + * loads; a test approves the flow named by its `state` with the identity to sign in as. + */ +export class ChatGptSignInEmulator implements ChatGptSignInFlow { + private readonly flows = new Map(); + + async start(): Promise<{ flowId: string; url: string }> { + const flowId = randomBytes(16).toString("base64url"); + this.flows.set(flowId, null); + const url = new URL(CHATGPT_EMULATOR_AUTHORIZE_URL); + url.searchParams.set("state", flowId); + return { flowId, url: url.href }; + } + + /** Finishes the flow as this ChatGPT account. The subject follows the email, so it signs in again. */ + approve(flowId: string, account: { email: string; name?: string }): boolean { + if (!this.flows.has(flowId)) return false; + const email = account.email.trim().toLowerCase(); + this.flows.set(flowId, { + subject: `emulated:${email}`, + email, + emailVerified: true, + ...(account.name ? { name: account.name } : {}), + }); + return true; + } + + async complete(flowId: string): Promise { + if (!this.flows.has(flowId)) { + return { status: "error", error: "This sign-in expired. Start again." }; + } + const identity = this.flows.get(flowId); + if (!identity) return { status: "pending" }; + this.flows.delete(flowId); + return { status: "connected", identity, clientId: EMULATOR_CLIENT_ID }; + } + + cancelAll(): void { + this.flows.clear(); + } +} diff --git a/packages/adapters/src/index.ts b/packages/adapters/src/index.ts index a51fff55..c1a5a101 100644 --- a/packages/adapters/src/index.ts +++ b/packages/adapters/src/index.ts @@ -21,6 +21,7 @@ export * from "./builtin-skills.js"; export * from "./builtin-tools.js"; export * from "./cartesia-voice.js"; export * from "./chatgpt-plan.js"; +export * from "./chatgpt-sign-in-emulator.js"; export * from "./child-bots.js"; export * from "./claude-code-cli.js"; export * from "./claude-code-runtime.js"; diff --git a/packages/chat-ui/src/markdown.native.tsx b/packages/chat-ui/src/markdown.native.tsx index 5f0d3d77..df200350 100644 --- a/packages/chat-ui/src/markdown.native.tsx +++ b/packages/chat-ui/src/markdown.native.tsx @@ -245,3 +245,5 @@ const layout = StyleSheet.create({ }); export type { ChatMarkdownProps } from "./markdown"; +export type { SuggestionChipsProps } from "./suggestions"; +export { SuggestionChips } from "./suggestions.native"; diff --git a/packages/chat-ui/src/markdown.web.tsx b/packages/chat-ui/src/markdown.web.tsx index a95aae08..328e2611 100644 --- a/packages/chat-ui/src/markdown.web.tsx +++ b/packages/chat-ui/src/markdown.web.tsx @@ -123,3 +123,5 @@ export const ChatMarkdown = memo(function ChatMarkdown({ }); export type { ChatMarkdownProps } from "./markdown"; +export type { SuggestionChipsProps } from "./suggestions"; +export { SuggestionChips } from "./suggestions.web"; diff --git a/packages/chat-ui/src/suggestions.native.tsx b/packages/chat-ui/src/suggestions.native.tsx new file mode 100644 index 00000000..8e237ee5 --- /dev/null +++ b/packages/chat-ui/src/suggestions.native.tsx @@ -0,0 +1,47 @@ +import { type ColorTokens, darkTokens } from "@milo/ui-tokens"; +import { Pressable, StyleSheet, Text, View } from "react-native"; +import type { SuggestionChipsProps } from "./suggestions"; + +/** A bot's idea chips; picking one sends it as the user's message. */ +export function SuggestionChips({ + items, + onPick, + disabled, + palette = darkTokens, +}: SuggestionChipsProps & { palette?: ColorTokens }) { + return ( + + {items.map((item) => ( + onPick(item)} + style={({ pressed }) => [ + styles.chip, + { + borderColor: palette.border, + backgroundColor: pressed ? palette.muted : "transparent", + }, + disabled ? styles.disabled : null, + ]} + > + {item} + + ))} + + ); +} + +const styles = StyleSheet.create({ + row: { flexDirection: "row", flexWrap: "wrap", gap: 8 }, + chip: { + borderWidth: StyleSheet.hairlineWidth, + borderRadius: 999, + paddingHorizontal: 14, + paddingVertical: 8, + }, + label: { fontSize: 15 }, + disabled: { opacity: 0.5 }, +}); diff --git a/packages/chat-ui/src/suggestions.ts b/packages/chat-ui/src/suggestions.ts new file mode 100644 index 00000000..2c905d14 --- /dev/null +++ b/packages/chat-ui/src/suggestions.ts @@ -0,0 +1,5 @@ +export type SuggestionChipsProps = { + items: string[]; + onPick: (item: string) => void; + disabled?: boolean; +}; diff --git a/packages/chat-ui/src/suggestions.web.test.tsx b/packages/chat-ui/src/suggestions.web.test.tsx new file mode 100644 index 00000000..75aeada4 --- /dev/null +++ b/packages/chat-ui/src/suggestions.web.test.tsx @@ -0,0 +1,14 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { SuggestionChips } from "./markdown.web"; + +describe("suggestion chips", () => { + it("renders one button per idea", () => { + const html = renderToStaticMarkup( + {}} />, + ); + expect(html.match(/ + ))} +
+ ); +} diff --git a/packages/contracts/src/events.ts b/packages/contracts/src/events.ts index f3509878..d926665e 100644 --- a/packages/contracts/src/events.ts +++ b/packages/contracts/src/events.ts @@ -133,6 +133,11 @@ export const MessageBlock = z.discriminatedUnion("kind", [ /** Set once the user picks an option; renders the picker as answered. */ answerId: z.string().optional(), }), + z.object({ + /** Idea chips under a bot message; tapping one sends it as the user's message. */ + kind: z.literal("suggestions"), + items: z.array(z.string().min(1).max(200)).min(1).max(6), + }), z.object({ /** Inline app authorization card (Composio-backed): logo, name, one-line description, and an Authorize button that flips to connected. */ diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 3af09450..9fd31873 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -649,6 +649,9 @@ export const appContract = { }, }, onboarding: { + /** Post the bot's intro with idea chips. Does nothing once the thread has a message. */ + introduce: oc.input(z.object({ botId: Id })).output(z.object({ ok: z.literal(true) })), + // The focus script below is unused since v0; delete it after v0 ships. /** Seed the first-run greeting into the bot's thread (focus card is separate). */ start: oc.input(z.object({ botId: Id })).output(z.object({ ok: z.literal(true) })), /** Post the focus choice card when the thread is still idle. */ diff --git a/packages/core/src/bot-avatar-colors.ts b/packages/core/src/bot-avatar-colors.ts index c54b02c0..de2cd539 100644 --- a/packages/core/src/bot-avatar-colors.ts +++ b/packages/core/src/bot-avatar-colors.ts @@ -103,6 +103,11 @@ export const GROK_BOT_COLORS = GROK_COLOR_LIST.map((c) => c.hex); /** Shared identity color for Avatar Studio reset/fallback (Executive Violet). */ export const DEFAULT_GROK_BOT_COLOR = GROK_COLOR_LIST.find((color) => color.id === "violet")!.hex; +/** The six colors offered when creating a bot. Older bots may use any color above. */ +export const BOT_PALETTE_COLORS = ["orange", "violet", "green", "blue", "yellow", "magenta"].map( + (id) => GROK_COLOR_LIST.find((color) => color.id === id)!.hex, +); + export function shippedHash(value: string): number { let hash = 2166136261; for (let index = 0; index < value.length; index += 1) { diff --git a/packages/testkit/src/cli/harness.ts b/packages/testkit/src/cli/harness.ts index ac4e4619..b34868fb 100644 --- a/packages/testkit/src/cli/harness.ts +++ b/packages/testkit/src/cli/harness.ts @@ -130,7 +130,13 @@ async function main() { } const [ - { ComposioEmulator, EmailEmulator, PipedreamConnector, ThirdPartyConnectorEmulator }, + { + ChatGptSignInEmulator, + ComposioEmulator, + EmailEmulator, + PipedreamConnector, + ThirdPartyConnectorEmulator, + }, { createApp }, ] = await Promise.all([import("@milo/adapters"), import("../../../../apps/api/src/app.ts")]); const { serve } = await import("@hono/node-server"); @@ -146,12 +152,14 @@ async function main() { { fetch: thirdParties.fetch, resolveHostname: thirdParties.resolveHostname }, ); const email = new EmailEmulator(); + const chatgpt = new ChatGptSignInEmulator(); const handles = await createApp({ databaseUrl, prisma: undefined, composio: new ComposioEmulator(), pipedream, email, + chatgpt, remoteConnectors: { fetch: thirdParties.fetch, resolveHostname: thirdParties.resolveHostname, @@ -165,6 +173,12 @@ async function main() { if (new URL(request.url).pathname === "/__e2e/emails") { return Response.json(email.sent, { headers: { "cache-control": "no-store" } }); } + if (new URL(request.url).pathname === "/__e2e/chatgpt/authorize") { + // Stands in for the person approving the ChatGPT sign-in in its browser tab. + const body = (await request.json()) as { state: string; email: string; name?: string }; + const approved = chatgpt.approve(body.state, { email: body.email, name: body.name }); + return Response.json({ approved }, { status: approved ? 200 : 404 }); + } activeRequests += 1; try { return await handles.app.fetch(request);