Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend): start expert onboarding after raise and from the team chat panel (#15034)

Ubbeb3785e35d80c
diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/raise/__tests__/main.test.tsx
index d594ec5860..d7527a542e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/raise/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/raise/__tests__/main.test.tsx
@@ -49,6 +49,14 @@ const { pushMock, notFoundMock } = vi.hoisted(() => ({
notFoundMock: vi.fn(),
}));
+const { invalidateRosterMock } = vi.hoisted(() => ({
+ invalidateRosterMock: vi.fn(() => Promise.resolve([])),
+}));
+
+vi.mock("@/services/experts/invalidate-experts", () => ({
+ invalidateExpertRosterQueries: invalidateRosterMock,
+}));
+
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: pushMock }),
usePathname: () => "/raise",
@@ -254,6 +262,26 @@ test("skips remaining kit steps, posts null budget and empty attachments, and op
);
});
+test("refreshes the expert roster before opening the kickoff thread", async () => {
+ server.use(getCreateRaisedExpertMockHandler(raiseResult()));
+ seedAtSkills();
+ renderRaise();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Skip" }, { timeout: 5000 }),
+ );
+
+ await waitFor(() =>
+ expect(pushMock).toHaveBeenCalledWith(
+ "/copilot?expertId=raised-1&kickoff=1",
+ ),
+ );
+ expect(invalidateRosterMock).toHaveBeenCalledTimes(1);
+ expect(invalidateRosterMock.mock.invocationCallOrder[0]).toBeLessThan(
+ pushMock.mock.invocationCallOrder[0],
+ );
+});
+
test("posts null when the job title was skipped", async () => {
let captured: unknown = null;
server.use(
diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/useRaiseSubmission.ts b/autogpt_platform/frontend/src/app/(platform)/raise/useRaiseSubmission.ts
index fc873f007f..6e971f17f4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/raise/useRaiseSubmission.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/raise/useRaiseSubmission.ts
@@ -2,6 +2,8 @@ import { useCreateRaisedExpert } from "@/app/api/__generated__/endpoints/experts
import type { RaiseResult } from "@/app/api/__generated__/models/raiseResult";
import { toast } from "@/components/molecules/Toast/use-toast";
import { ApiError } from "@/lib/autogpt-server-api/helpers";
+import { invalidateExpertRosterQueries } from "@/services/experts/invalidate-experts";
+import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useRef, useState } from "react";
import { roleFor } from "./components/CategoryStep/helpers";
@@ -17,6 +19,7 @@ import {
} from "./helpers";
export function useRaiseSubmission() {
+ const queryClient = useQueryClient();
const router = useRouter();
const { mutateAsync: createRaisedExpert, isPending } =
useCreateRaisedExpert();
@@ -55,6 +58,11 @@ export function useRaiseSubmission() {
});
}
clearDraft();
+ // The copilot page only fires the kickoff for an expert it finds in the
+ // roster, and the sidebar keeps that roster cached, so refresh it before
+ // handing over or the new expert is treated as unknown and the kickoff
+ // param is dropped.
+ await invalidateExpertRosterQueries(queryClient);
// kickoff=1 has the expert open the thread itself: introduce who it is,
// say what it can take on, and start or ask for its first job.
router.push(
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/__tests__/ExpertChatDrawer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/__tests__/ExpertChatDrawer.test.tsx
index 396309bebf..3d71a81ed8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/__tests__/ExpertChatDrawer.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/__tests__/ExpertChatDrawer.test.tsx
@@ -1,24 +1,479 @@
+import { TEST_BACKEND_BASE_URL } from "@/app/(platform)/copilot/__tests__/sse-helpers";
+import { useCopilotStreamStore } from "@/app/(platform)/copilot/copilotStreamStore";
+import {
+ getKickoffStatus,
+ markKickoffDone,
+ markKickoffPending,
+} from "@/app/(platform)/copilot/expertKickoff";
import {
getGetV2GetSessionMockHandler200,
+ getGetV2GetSessionResponseMock200,
getGetV2ListSessionsMockHandler200,
+ getPostV2CreateSessionMockHandler200,
+ getPostV2CreateSessionResponseMock200,
} from "@/app/api/__generated__/endpoints/chat/chat.msw";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
import { server } from "@/mocks/mock-server";
+import {
+ assistantTextChunks,
+ streamSseResponse,
+} from "@/tests/integrations/copilot-sse";
import {
fireEvent,
render,
screen,
waitFor,
} from "@/tests/integrations/test-utils";
-import { describe, expect, test, vi } from "vitest";
-import { http, HttpResponse } from "msw";
+import userEvent from "@testing-library/user-event";
+import { http, HttpResponse, ws } from "msw";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { onboardingCard, onboardingTurn } from "./onboardingFixtures";
import { ExpertChatDrawer } from "../ExpertChatDrawer";
-const EXPERT_ID = "expert-zara";
+const USER_ID = "user-1";
+const EXPERT_ID = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";
const SESSION_ID = "session-zara";
+const FRESH_SESSION_ID = "session-zara-fresh";
+const RETRY_SESSION_ID = "session-zara-retry";
+const ERROR_SESSION_ID = "session-zara-error";
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
+vi.mock("@/lib/auth/actions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/auth/actions")>()),
+ getWebSocketToken: async () => ({ token: "test-token" }),
+}));
+
+vi.mock("@/services/environment", async (importActual) => {
+ const actual = await importActual<typeof import("@/services/environment")>();
+ return {
+ ...actual,
+ environment: {
+ ...actual.environment,
+ getAGPTServerBaseUrl: () => TEST_BACKEND_BASE_URL,
+ },
+ };
+});
+
+vi.mock("@/app/(platform)/copilot/helpers", async (importActual) => {
+ const actual =
+ await importActual<typeof import("@/app/(platform)/copilot/helpers")>();
+ return {
+ ...actual,
+ getCopilotAuthHeaders: async () => ({ "x-test-auth": "yes" }),
+ };
+});
+
+const backendSocket = ws.link("ws://localhost:8001/ws");
+
+const ZARA = {
+ expertId: EXPERT_ID,
+ name: "Zara",
+ role: "GTM Strategist",
+ avatarUrl: null,
+};
+
+function freshThreadHandlers(
+ createBodies: unknown[],
+ streamBodies: string[],
+ sessionId = FRESH_SESSION_ID,
+) {
+ return [
+ getGetV2ListSessionsMockHandler200({ sessions: [], total: 0 }),
+ getPostV2CreateSessionMockHandler200(async (info) => {
+ createBodies.push(await info.request.clone().json());
+ return getPostV2CreateSessionResponseMock200({ id: sessionId });
+ }),
+ getGetV2GetSessionMockHandler200(
+ getGetV2GetSessionResponseMock200({
+ id: sessionId,
+ expert_id: EXPERT_ID,
+ messages: [],
+ active_stream: null,
+ }),
+ ),
+ http.post(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${sessionId}/stream`,
+ async ({ request }) => {
+ streamBodies.push(await request.clone().text());
+ return streamSseResponse(assistantTextChunks("Hi, I'm Zara."), {
+ abortSignal: request.signal,
+ });
+ },
+ ),
+ ];
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ useCopilotStreamStore.getState().resetAll();
+ server.use(backendSocket.addEventListener("connection", () => {}));
+ useAuthStore.setState({
+ user: { id: USER_ID, email: "[email protected]", user_metadata: {} },
+ isUserLoading: false,
+ hasLoadedUser: true,
+ });
+});
+
+afterEach(() => {
+ useAuthStore.setState({ user: null, hasLoadedUser: false });
+});
describe("ExpertChatDrawer", () => {
+ test("keeps chat disabled while it checks for an existing thread", async () => {
+ const sessionsRequest = deferred();
+ const createBodies: unknown[] = [];
+ server.use(
+ getGetV2ListSessionsMockHandler200(async () => {
+ await sessionsRequest.promise;
+ return { sessions: [], total: 0 };
+ }),
+ ...freshThreadHandlers(createBodies, []),
+ );
+
+ render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ />,
+ );
+
+ expect(
+ (await screen.findByPlaceholderText(
+ "Message Zara…",
+ )) as HTMLTextAreaElement,
+ ).toHaveProperty("disabled", true);
+ expect(createBodies).toEqual([]);
+
+ sessionsRequest.resolve();
+ await waitFor(() => expect(createBodies.length).toBe(1));
+ expect(await screen.findByText("Hi, I'm Zara.")).toBeDefined();
+ });
+
+ test("waits for a fresh session list before starting onboarding", async () => {
+ const createBodies: unknown[] = [];
+ server.use(...freshThreadHandlers(createBodies, []));
+ const { rerender } = render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ threadKey={0}
+ />,
+ );
+
+ await waitFor(() => expect(createBodies.length).toBe(1));
+ expect(await screen.findByText("Hi, I'm Zara.")).toBeDefined();
+
+ rerender(
+ <ExpertChatDrawer
+ target={null}
+ onClose={() => {}}
+ resumeLatest={false}
+ threadKey={1}
+ />,
+ );
+ await waitFor(() => expect(screen.queryByText("Hi, I'm Zara.")).toBeNull());
+ window.localStorage.clear();
+
+ const sessionsRequest = deferred();
+ server.use(
+ getGetV2ListSessionsMockHandler200(async () => {
+ await sessionsRequest.promise;
+ return {
+ sessions: [
+ {
+ id: SESSION_ID,
+ created_at: "2026-09-27T18:00:00Z",
+ updated_at: "2026-09-27T18:01:00Z",
+ is_processing: false,
+ expert_id: EXPERT_ID,
+ },
+ ],
+ total: 1,
+ };
+ }),
+ );
+ rerender(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ threadKey={2}
+ />,
+ );
+
+ expect(
+ (await screen.findByPlaceholderText(
+ "Message Zara…",
+ )) as HTMLTextAreaElement,
+ ).toHaveProperty("disabled", true);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(createBodies.length).toBe(1);
+
+ sessionsRequest.resolve();
+ await waitFor(() =>
+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done"),
+ );
+ expect(createBodies.length).toBe(1);
+ });
+
+ test("retries a failed kickoff before sending the user's message", async () => {
+ const user = userEvent.setup();
+ const createBodies: unknown[] = [];
+ const streamBodies: string[] = [];
+ let createAttempts = 0;
+ server.use(
+ http.post("/api/proxy/api/chat/sessions", async ({ request }) => {
+ createBodies.push(await request.clone().json());
+ createAttempts += 1;
+ if (createAttempts === 1) {
+ return HttpResponse.json(
+ { detail: "Could not create session" },
+ { status: 500 },
+ );
+ }
+ return HttpResponse.json(
+ getPostV2CreateSessionResponseMock200({ id: RETRY_SESSION_ID }),
+ );
+ }),
+ ...freshThreadHandlers([], streamBodies, RETRY_SESSION_ID),
+ );
+
+ render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ />,
+ );
+
+ await waitFor(() => expect(createAttempts).toBe(1));
+ const input = await screen.findByPlaceholderText("Message Zara…");
+ await waitFor(() =>
+ expect(input as HTMLTextAreaElement).toHaveProperty("disabled", false),
+ );
+ await user.type(input, "Plan my launch{Enter}");
+
+ await waitFor(() => expect(createAttempts).toBe(2));
+ await waitFor(() => expect(streamBodies.length).toBe(2));
+ expect(JSON.parse(streamBodies[0]).expert_kickoff).toBe(true);
+ expect(JSON.parse(streamBodies[1])).toMatchObject({
+ expert_kickoff: false,
+ message: "Plan my launch",
+ });
+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done");
+ expect(createBodies).toEqual([
+ { expert_id: EXPERT_ID, expert_kickoff: true },
+ { expert_id: EXPERT_ID, expert_kickoff: true },
+ ]);
+ });
+
+ test("releases the kickoff after its stream fails", async () => {
+ let streamStarted = false;
+ server.use(
+ http.post(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${ERROR_SESSION_ID}/stream`,
+ () => {
+ streamStarted = true;
+ return HttpResponse.json(
+ { detail: "Could not start stream" },
+ { status: 500 },
+ );
+ },
+ ),
+ ...freshThreadHandlers([], [], ERROR_SESSION_ID),
+ );
+
+ render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ />,
+ );
+
+ await waitFor(() => expect(streamStarted).toBe(true));
+ await waitFor(() =>
+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle"),
+ );
+ });
+
+ test("returns a prompt queued behind the kickoff when its stream fails", async () => {
+ const user = userEvent.setup();
+ const streamBodies: string[] = [];
+ let createAttempts = 0;
+ server.use(
+ http.post("/api/proxy/api/chat/sessions", () => {
+ createAttempts += 1;
+ if (createAttempts === 1) {
+ return HttpResponse.json(
+ { detail: "Could not create session" },
+ { status: 500 },
+ );
+ }
+ return HttpResponse.json(
+ getPostV2CreateSessionResponseMock200({ id: ERROR_SESSION_ID }),
+ );
+ }),
+ http.post(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${ERROR_SESSION_ID}/stream`,
+ async ({ request }) => {
+ streamBodies.push(await request.clone().text());
+ return HttpResponse.json(
+ { detail: "Could not start stream" },
+ { status: 500 },
+ );
+ },
+ ),
+ ...freshThreadHandlers([], [], ERROR_SESSION_ID),
+ );
+
+ render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ />,
+ );
+
+ await waitFor(() => expect(createAttempts).toBe(1));
+ const input = (await screen.findByPlaceholderText(
+ "Message Zara…",
+ )) as HTMLTextAreaElement;
+ await waitFor(() => expect(input).toHaveProperty("disabled", false));
+ await user.type(input, "Plan my launch{Enter}");
+
+ await waitFor(() => expect(streamBodies.length).toBe(1));
+ expect(JSON.parse(streamBodies[0]).expert_kickoff).toBe(true);
+ await waitFor(() => expect(input.value).toBe("Plan my launch"));
+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle");
+ });
+
+ test("opens a plain thread when the kickoff check fails", async () => {
+ const user = userEvent.setup();
+ const createBodies: unknown[] = [];
+ const streamBodies: string[] = [];
+ server.use(
+ http.get("/api/proxy/api/chat/sessions", () =>
+ HttpResponse.json({ detail: "Unavailable" }, { status: 503 }),
+ ),
+ ...freshThreadHandlers(createBodies, streamBodies),
+ );
+
+ render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ />,
+ );
+
+ expect(await screen.findByText("What can I do for you?")).toBeDefined();
+ const input = await screen.findByPlaceholderText("Message Zara…");
+ await waitFor(() =>
+ expect(input as HTMLTextAreaElement).toHaveProperty("disabled", false),
+ );
+ await user.type(input, "Plan my launch{Enter}");
+
+ await waitFor(() =>
+ expect(createBodies).toEqual([{ expert_id: EXPERT_ID }]),
+ );
+ await waitFor(() => expect(streamBodies.length).toBe(1));
+ expect(JSON.parse(streamBodies[0])).toMatchObject({
+ expert_kickoff: false,
+ message: "Plan my launch",
+ });
+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle");
+ });
+
+ test("kicks off onboarding the first time an expert's thread opens", async () => {
+ const createBodies: unknown[] = [];
+ const streamBodies: string[] = [];
+ server.use(...freshThreadHandlers(createBodies, streamBodies));
+
+ render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(createBodies).toEqual([
+ { expert_id: EXPERT_ID, expert_kickoff: true },
+ ]),
+ );
+ await waitFor(() => expect(streamBodies.length).toBe(1));
+ const body = JSON.parse(streamBodies[0]);
+ expect(body.expert_kickoff).toBe(true);
+ expect(body.message).toContain("expert_onboarding");
+ expect(await screen.findByText("Hi, I'm Zara.")).toBeDefined();
+ expect(screen.queryByText(/You were just hired/)).toBeNull();
+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done");
+ });
+
+ test("opens a plain thread once the expert has been onboarded", async () => {
+ markKickoffDone(USER_ID, EXPERT_ID, markKickoffPending(USER_ID, EXPERT_ID));
+ const createBodies: unknown[] = [];
+ server.use(...freshThreadHandlers(createBodies, []));
+
+ render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ />,
+ );
+
+ expect(await screen.findByText("What can I do for you?")).toBeDefined();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(createBodies).toEqual([]);
+ });
+
+ test("treats an existing thread as already onboarded", async () => {
+ const createBodies: unknown[] = [];
+ server.use(
+ getGetV2ListSessionsMockHandler200({
+ sessions: [
+ {
+ id: SESSION_ID,
+ created_at: "2026-09-27T18:00:00Z",
+ updated_at: "2026-09-27T18:01:00Z",
+ is_processing: false,
+ expert_id: EXPERT_ID,
+ },
+ ],
+ total: 1,
+ }),
+ ...freshThreadHandlers(createBodies, []),
+ );
+
+ render(
+ <ExpertChatDrawer
+ target={ZARA}
+ onClose={() => {}}
+ resumeLatest={false}
+ />,
+ );
+
+ expect(await screen.findByText("What can I do for you?")).toBeDefined();
+ await waitFor(() =>
+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done"),
+ );
+ expect(createBodies).toEqual([]);
+ });
+
test("keeps answers if creating the new chat fails", async () => {
+ markKickoffDone(USER_ID, EXPERT_ID, markKickoffPending(USER_ID, EXPERT_ID));
const createSession = vi.fn(() =>
HttpResponse.json({ detail: "Unavailable" }, { status: 503 }),
);
@@ -30,12 +485,7 @@ describe("ExpertChatDrawer", () => {
);
render(
<ExpertChatDrawer
- target={{
- expertId: EXPERT_ID,
- name: "Zara",
- role: "GTM Strategist",
- avatarUrl: null,
- }}
+ target={ZARA}
resumeLatest={false}
onClose={() => {}}
/>,
@@ -60,18 +510,14 @@ describe("ExpertChatDrawer", () => {
});
test("keeps settled setup out of new chats", async () => {
+ markKickoffDone(USER_ID, EXPERT_ID, markKickoffPending(USER_ID, EXPERT_ID));
const request = vi.fn(() => HttpResponse.json(null));
server.use(
http.get("/api/proxy/api/experts/:expertId/onboarding", request),
);
render(
<ExpertChatDrawer
- target={{
- expertId: EXPERT_ID,
- name: "Zara",
- role: "GTM Strategist",
- avatarUrl: null,
- }}
+ target={ZARA}
resumeLatest={false}
onClose={() => {}}
/>,
@@ -82,18 +528,14 @@ describe("ExpertChatDrawer", () => {
});
test("does not request setup when the new chat has a prompt", async () => {
+ markKickoffDone(USER_ID, EXPERT_ID, markKickoffPending(USER_ID, EXPERT_ID));
const request = vi.fn(() => HttpResponse.json(onboardingCard()));
server.use(
http.get("/api/proxy/api/experts/:expertId/onboarding", request),
);
render(
<ExpertChatDrawer
- target={{
- expertId: EXPERT_ID,
- name: "Zara",
- role: "GTM Strategist",
- avatarUrl: null,
- }}
+ target={ZARA}
resumeLatest={false}
seedPrompt="Research this company"
onClose={() => {}}
@@ -104,6 +546,7 @@ describe("ExpertChatDrawer", () => {
});
test("shows unanswered setup questions in a new chat", async () => {
+ markKickoffDone(USER_ID, EXPERT_ID, markKickoffPending(USER_ID, EXPERT_ID));
server.use(
http.get("/api/proxy/api/experts/:expertId/onboarding", () =>
HttpResponse.json(onboardingCard()),
@@ -111,12 +554,7 @@ describe("ExpertChatDrawer", () => {
);
render(
<ExpertChatDrawer
- target={{
- expertId: EXPERT_ID,
- name: "Zara",
- role: "GTM Strategist",
- avatarUrl: null,
- }}
+ target={ZARA}
resumeLatest={false}
onClose={() => {}}
/>,
@@ -151,17 +589,7 @@ describe("ExpertChatDrawer", () => {
}),
);
- render(
- <ExpertChatDrawer
- target={{
- expertId: EXPERT_ID,
- name: "Zara",
- role: "GTM Strategist",
- avatarUrl: null,
- }}
- onClose={() => {}}
- />,
- );
+ render(<ExpertChatDrawer target={ZARA} onClose={() => {}} />);
expect(
await screen.findByText("Which outcome should I start with?"),
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/useExpertChatDrawer.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/useExpertChatDrawer.ts
index 1acac4eaf2..19b2ec0f69 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/useExpertChatDrawer.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/useExpertChatDrawer.ts
@@ -1,3 +1,13 @@
+import {
+ buildKickoffMessage,
+ clearKickoffPending,
+ type ExpertKickoffMetadata,
+ getKickoffStatus,
+ type KickoffAttemptToken,
+ markKickoffDone,
+ markKickoffPending,
+ withKickoffLock,
+} from "@/app/(platform)/copilot/expertKickoff";
import { convertChatSessionMessagesToUiMessages } from "@/app/(platform)/copilot/helpers/convertChatSessionToUiMessages";
import { queueFollowUpMessage } from "@/app/(platform)/copilot/helpers/queueFollowUpMessage";
import { latestExpertSessionParams } from "@/app/(platform)/copilot/expertSessionQuery";
@@ -9,6 +19,7 @@ import {
usePostV2CreateSession,
} from "@/app/api/__generated__/endpoints/chat/chat";
import { toast } from "@/components/molecules/Toast/use-toast";
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
import * as Sentry from "@sentry/nextjs";
import type { UIDataTypes, UIMessage, UITools } from "ai";
import { useEffect, useMemo, useRef, useState } from "react";
@@ -26,6 +37,26 @@ function notifyStartFailed() {
});
}
+interface PendingSend {
+ text: string;
+ metadata?: ExpertKickoffMetadata;
+}
+
+interface KickoffAttempt {
+ userId: string;
+ expertId: string;
+ token: KickoffAttemptToken;
+}
+
+/** A prompt sent while the kickoff is being decided. Its send settles only
+ * once the prompt went out, so a failed kickoff hands the failure back to
+ * the composer or card that sent it instead of dropping the words. */
+interface QueuedSend {
+ text: string;
+ resolve: () => void;
+ reject: (err: unknown) => void;
+}
+
interface Args {
target: ChatTarget | null;
isOpen: boolean;
@@ -46,11 +77,17 @@ export function useExpertChatDrawer({
seedPrompt,
}: Args) {
const expertId = target?.expertId ?? null;
+ const userId = useAuthStore((state) => state.user?.id) ?? null;
const [sessionId, setSessionId] = useState<string | null>(null);
const [isCreating, setIsCreating] = useState(false);
const [skipLatest, setSkipLatest] = useState(false);
const [suppressOnboarding, setSuppressOnboarding] = useState(!!seedPrompt);
- const pendingPromptRef = useRef<string | null>(null);
+ const [kickoffCheckedFor, setKickoffCheckedFor] = useState<string | null>(
+ null,
+ );
+ const pendingPromptRef = useRef<PendingSend | null>(null);
+ const queuedBehindKickoffRef = useRef<QueuedSend | null>(null);
+ const kickoffAttemptRef = useRef<KickoffAttempt | null>(null);
// Every thread reset bumps the generation; a session create that resolves
// for an older generation is ignored so its prompt never lands in the new
// thread, and the new thread is free to create its own session.
@@ -74,6 +111,65 @@ export function useExpertChatDrawer({
if (latest) setSessionId(latest.id);
}, [latestQuery.data, wantsLatest]);
+ // An expert that has never been kicked off opens the thread itself with its
+ // onboarding card, as it does on the copilot page after a hire. Any existing
+ // thread means that already happened somewhere else, so only remember it.
+ const wantsKickoff =
+ isOpen &&
+ !!expertId &&
+ !!userId &&
+ !sessionId &&
+ !isCreating &&
+ kickoffCheckedFor !== expertId &&
+ getKickoffStatus(userId, expertId) === "idle";
+ const kickoffCheckQuery = useGetV2ListSessions(
+ latestExpertSessionParams(expertId),
+ { query: { enabled: wantsKickoff, refetchOnWindowFocus: false } },
+ );
+
+ const startKickoffRef = useRef(startKickoff);
+ startKickoffRef.current = startKickoff;
+ const startSessionRef = useRef(startSession);
+ startSessionRef.current = startSession;
+ const sendQueuedInNewThreadRef = useRef(sendQueuedInNewThread);
+ sendQueuedInNewThreadRef.current = sendQueuedInNewThread;
+ useEffect(() => {
+ if (!wantsKickoff || !userId || !expertId) return;
+ if (kickoffCheckQuery.isFetching) return;
+ const settled = kickoffCheckQuery.data;
+ if (!settled && !kickoffCheckQuery.isError) return;
+ if (!settled || settled.status !== 200) {
+ // Without the list there is no telling whether the expert was onboarded
+ // elsewhere, so this open skips the kickoff rather than risk asking
+ // twice; a prompt queued behind it opens a plain thread instead.
+ void sendQueuedInNewThreadRef.current();
+ return;
+ }
+ setKickoffCheckedFor(expertId);
+ if (settled.data.sessions.length > 0) {
+ void withKickoffLock(userId, expertId, async () => {
+ if (getKickoffStatus(userId, expertId) === "idle") {
+ markKickoffDone(
+ userId,
+ expertId,
+ markKickoffPending(userId, expertId),
+ );
+ }
+ })
+ .catch(() => undefined)
+ .then(() => sendQueuedInNewThreadRef.current());
+ return;
+ }
+ void startKickoffRef.current(userId, expertId).catch(notifyStartFailed);
+ }, [
+ expertId,
+ kickoffCheckQuery.data,
+ kickoffCheckQuery.isError,
+ kickoffCheckQuery.isFetching,
+ userId,
+ wantsKickoff,
+ ]);
+
const sessionQuery = useGetV2GetSession(sessionId ?? "", undefined, {
query: {
enabled: !!sessionId,
@@ -98,6 +194,7 @@ export function useExpertChatDrawer({
const { messages, setMessages, sendMessage, stop, status, error } =
useCopilotStream({
+ userId,
sessionId,
hydratedMessages,
hasActiveStream,
@@ -105,6 +202,39 @@ export function useExpertChatDrawer({
copilotModel: undefined,
});
+ const hasAssistantReply = messages.some(
+ (message) => message.role === "assistant",
+ );
+ useEffect(() => {
+ const attempt = kickoffAttemptRef.current;
+ if (!attempt || status !== "ready" || !hasAssistantReply) return;
+ kickoffAttemptRef.current = null;
+ void withKickoffLock(attempt.userId, attempt.expertId, async () => {
+ markKickoffDone(attempt.userId, attempt.expertId, attempt.token);
+ })
+ .catch(() => undefined)
+ .then(async () => {
+ const queued = takeQueued();
+ if (!queued) return;
+ try {
+ await sendMessage({ text: queued.text });
+ queued.resolve();
+ } catch (err) {
+ queued.reject(err);
+ }
+ });
+ }, [hasAssistantReply, sendMessage, status]);
+
+ useEffect(() => {
+ const attempt = kickoffAttemptRef.current;
+ if (!error || !attempt) return;
+ kickoffAttemptRef.current = null;
+ takeQueued()?.reject(error);
+ void withKickoffLock(attempt.userId, attempt.expertId, async () => {
+ clearKickoffPending(attempt.userId, attempt.expertId, attempt.token);
+ }).catch(() => undefined);
+ }, [error]);
+
const { queuedMessages, queueMessage } = useCopilotPendingChips({
sessionId,
status,
@@ -123,24 +253,25 @@ export function useExpertChatDrawer({
setSkipLatest(true);
setSessionId(null);
setMessages([]);
+ setKickoffCheckedFor(null);
pendingPromptRef.current = null;
+ takeQueued()?.reject(new Error("The chat was reset"));
+ kickoffAttemptRef.current = null;
setSeedToSend(seedPrompt);
setSuppressOnboarding(!!seedPrompt);
}, [threadKey, seedPrompt, setMessages]);
- const startSessionRef = useRef(startSession);
- startSessionRef.current = startSession;
useEffect(() => {
if (!seedToSend) return;
setSeedToSend(null);
- void startSessionRef.current(seedToSend).catch(notifyStartFailed);
+ void startSessionRef.current({ text: seedToSend }).catch(notifyStartFailed);
}, [seedToSend]);
useEffect(() => {
if (!sessionId || !pendingPromptRef.current) return;
- const prompt = pendingPromptRef.current;
+ const pending = pendingPromptRef.current;
pendingPromptRef.current = null;
- sendMessage({ text: prompt });
+ sendMessage({ text: pending.text, metadata: pending.metadata });
}, [sessionId, sendMessage]);
function startNewThread() {
@@ -151,12 +282,87 @@ export function useExpertChatDrawer({
setSkipLatest(true);
setSessionId(null);
setMessages([]);
+ setKickoffCheckedFor(null);
pendingPromptRef.current = null;
+ takeQueued()?.reject(new Error("The chat was reset"));
+ kickoffAttemptRef.current = null;
+ }
+
+ function queueBehindKickoff(text: string): Promise<void> {
+ if (queuedBehindKickoffRef.current) throw new SessionStartingError();
+ const settled = new Promise<void>((resolve, reject) => {
+ queuedBehindKickoffRef.current = { text, resolve, reject };
+ });
+ // The sender awaits `settled`; this handler only keeps a rejection that
+ // lands before it does from surfacing as unhandled.
+ settled.catch(() => undefined);
+ return settled;
+ }
+
+ function takeQueued(): QueuedSend | null {
+ const queued = queuedBehindKickoffRef.current;
+ queuedBehindKickoffRef.current = null;
+ return queued;
}
- async function startSession(firstMessage: string) {
+ async function sendQueuedInNewThread() {
+ const queued = takeQueued();
+ if (!queued) return;
+ try {
+ const started = await startSession({ text: queued.text });
+ if (started) queued.resolve();
+ else queued.reject(new Error("The chat was reset"));
+ } catch (err) {
+ queued.reject(err);
+ }
+ }
+
+ async function startKickoff(ownerId: string, id: string): Promise<boolean> {
+ let attemptToken: KickoffAttemptToken | null = null;
+ function clearAttempt() {
+ if (!attemptToken) return;
+ if (kickoffAttemptRef.current?.token === attemptToken) {
+ kickoffAttemptRef.current = null;
+ }
+ clearKickoffPending(ownerId, id, attemptToken);
+ }
+ let started: boolean | undefined;
+ try {
+ started = await withKickoffLock(ownerId, id, async () => {
+ if (getKickoffStatus(ownerId, id) !== "idle") return false;
+ const token = markKickoffPending(ownerId, id);
+ attemptToken = token;
+ kickoffAttemptRef.current = { userId: ownerId, expertId: id, token };
+ if (sessionId) {
+ await sendMessage(buildKickoffMessage(id, token));
+ return true;
+ }
+ return startSession(buildKickoffMessage(id, token), {
+ expertKickoff: true,
+ });
+ });
+ } catch (err) {
+ clearAttempt();
+ const queued = takeQueued();
+ if (!queued) throw err;
+ // The queued sender surfaces the failure and gets its words back.
+ queued.reject(err);
+ return false;
+ }
+ if (started) return true;
+ // Another tab onboarded this expert first, or the thread was reset
+ // mid-create: nothing to wait for, so a queued prompt goes out plainly.
+ clearAttempt();
+ await sendQueuedInNewThread();
+ return false;
+ }
+
+ async function startSession(
+ firstMessage: PendingSend,
+ options?: { expertKickoff?: boolean },
+ ): Promise<boolean> {
const generation = generationRef.current;
- if (!target) return;
+ if (!target) return false;
// A card answered while a typed prompt is still creating the session must
// not settle on a message that never went out, so the second send rejects.
if (creatingGenerationRef.current === generation) {
@@ -166,17 +372,25 @@ export function useExpertChatDrawer({
setIsCreating(true);
try {
const response = await createSession(
- expertId ? { data: { expert_id: expertId } } : { data: null },
+ expertId
+ ? {
+ data: {
+ expert_id: expertId,
+ ...(options?.expertKickoff ? { expert_kickoff: true } : {}),
+ },
+ }
+ : { data: null },
);
- if (generation !== generationRef.current) return;
+ if (generation !== generationRef.current) return false;
if (response.status !== 200) {
throw new Error("Failed to create expert chat session");
}
pendingPromptRef.current = firstMessage;
setSuppressOnboarding(true);
setSessionId(response.data.id);
+ return true;
} catch (err) {
- if (generation !== generationRef.current) return;
+ if (generation !== generationRef.current) return false;
Sentry.captureException(err);
setSuppressOnboarding(false);
throw err;
@@ -191,8 +405,23 @@ export function useExpertChatDrawer({
async function onSend(message: string) {
const trimmed = message.trim();
if (!trimmed) return;
+ if (!sessionId && isCheckingKickoff) {
+ await queueBehindKickoff(trimmed);
+ return;
+ }
+ if (
+ userId &&
+ expertId &&
+ kickoffCheckedFor === expertId &&
+ getKickoffStatus(userId, expertId) === "idle"
+ ) {
+ const sent = queueBehindKickoff(trimmed);
+ await startKickoff(userId, expertId);
+ await sent;
+ return;
+ }
if (!sessionId) {
- await startSession(trimmed);
+ await startSession({ text: trimmed });
return;
}
const isInFlight = status === "streaming" || status === "submitted";
@@ -231,7 +460,12 @@ export function useExpertChatDrawer({
}
}
- const isResolvingSession = !sessionId && wantsLatest && latestQuery.isLoading;
+ const isCheckingKickoff =
+ wantsKickoff &&
+ (kickoffCheckQuery.isFetching ||
+ (!kickoffCheckQuery.isError && !kickoffCheckQuery.data));
+ const isResolvingSession =
+ (!sessionId && wantsLatest && latestQuery.isLoading) || isCheckingKickoff;
return {
sessionId,