Skip to content
This repository was archived by the owner on Oct 27, 2026. It is now read-only.
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
8 changes: 6 additions & 2 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
} from "@milo/adapter-kit";
import type {
ChatGptPlanCredential,
ChatGptSignInFlow,
ComposioProvider,
ConnectorRegistry,
DestinationEmulator,
Expand Down Expand Up @@ -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;
} = {},
Expand All @@ -134,6 +137,7 @@ export async function createApp(
composio: composioOverride,
pipedream: pipedreamOverride,
email: emailOverride,
chatgpt: chatgptOverride,
remoteConnectors,
logger: loggerOverride,
...envOverrides
Expand Down Expand Up @@ -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,
Expand Down
71 changes: 70 additions & 1 deletion apps/api/src/onboarding.test.ts
Original file line number Diff line number Diff line change
@@ -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) => ({
Expand Down Expand Up @@ -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<typeof vi.fn>).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);
});
});
94 changes: 90 additions & 4 deletions apps/api/src/onboarding.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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 = {
Expand Down Expand Up @@ -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<string[]> {
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<void> {
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";

Expand Down
5 changes: 5 additions & 0 deletions apps/api/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ import { buildMcpUpdateMaterial } from "./mcp-material.js";
import {
chooseFocus,
dismissFocus,
introduce,
markAppConnected,
promptFocus,
startOnboarding,
Expand Down Expand Up @@ -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 };
Expand Down
13 changes: 0 additions & 13 deletions apps/mobile/app/(tabs)/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<MobileBot[]>("bots/list").catch(() => null);
const isFirstBot = existing !== null && existing.length === 0;
const bot = await rpc<MobileBot>("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 {
Expand Down
12 changes: 0 additions & 12 deletions apps/mobile/app/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<MobileBot[]>("bots/list").catch(() => null);
const isFirstBot = existing !== null && existing.length === 0;
const bot = await rpc<MobileBot>("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 {
Expand Down
Loading
Loading