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.

feat(platform): make the expert hire card short and Typeform-like (#15217)

Ubbe9cbe1a619caa
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_onboarding.py b/autogpt_platform/backend/backend/copilot/tools/expert_onboarding.py
index dcf5e3fc1f..9c04632c01 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_onboarding.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_onboarding.py
@@ -2,6 +2,7 @@
import json
import logging
+import re
from typing import Any
from backend.copilot.model import ChatSession
@@ -19,17 +20,20 @@ logger = logging.getLogger(__name__)
TOOL_NAME = "expert_onboarding"
# The card is a one-question-at-a-time pager, so its length is the user's
-# patience, not a context budget: five steps is already a long walk before
-# anyone has seen the expert do anything.
-MIN_STEPS = 3
-MAX_STEPS = 5
-MAX_OPTIONS = 6
+# patience, not a context budget: every extra step or option is one more
+# chance to close the tab before the expert has done anything.
+MIN_STEPS = 2
+MAX_STEPS = 3
+MAX_OPTIONS = 4
MAX_QUESTION_LENGTH = 200
MAX_OPTION_LENGTH = 120
MAX_GREETING_LENGTH = 600
# Both arrays are model-authored and the model can be steered by an expert's
# own user-supplied identity text, so every scan needs its own bound.
MAX_SCAN = 200
+# Em and en dashes are the tell of machine-written copy, and models reach for
+# them even when told not to, so the greeting loses them either way.
+_DASH = re.compile(r"\s*[\u2013\u2014]+\s*")
class ExpertOnboardingTool(BaseTool):
@@ -49,10 +53,10 @@ class ExpertOnboardingTool(BaseTool):
def description(self) -> str:
return (
"Open your onboarding card on your first turn after being hired: "
- "a short greeting plus 3-5 multiple-choice questions that settle "
- "what the user wants from you and which services you need. Ask "
- "for nothing else on that turn, and do not start work until the "
- "answers come back."
+ f"a one-line greeting plus {MIN_STEPS}-{MAX_STEPS} short "
+ "multiple-choice questions that settle what the user wants from "
+ "you and which services you need. Ask for nothing else on that "
+ "turn, and do not start work until the answers come back."
)
@property
@@ -63,8 +67,9 @@ class ExpertOnboardingTool(BaseTool):
"greeting": {
"type": "string",
"description": (
- "One or two sentences introducing yourself, in your "
- "own voice. Shown above the questions."
+ "One short sentence, under 15 words, introducing "
+ "yourself in your own voice. No dashes. Shown under "
+ "your name."
),
},
"steps": {
@@ -76,19 +81,22 @@ class ExpertOnboardingTool(BaseTool):
"properties": {
"question": {
"type": "string",
- "description": "The question text.",
+ "description": (
+ "The question, under 10 words. No "
+ "preamble or explanation — just the "
+ "question."
+ ),
},
"options": {
"type": "array",
"items": {"type": "string"},
"description": (
- "Up to 6 answers the user can tap. Make "
- "them concrete and specific to your role "
- "— the point is that answering costs no "
- "typing. The user can always write their "
- "own answer instead. Exactly one is "
- "chosen, so split a question that needs "
- "several answers into separate steps."
+ f"2-{MAX_OPTIONS} answers the user can "
+ "tap, 1-5 words each, concrete and "
+ "specific to your role. Exactly one is "
+ "chosen. Leave out "
+ "'not sure', 'later' and 'skip' answers: "
+ "the card already offers Other and Skip."
),
},
"keyword": {
@@ -99,10 +107,9 @@ class ExpertOnboardingTool(BaseTool):
"required": ["question", "options"],
},
"description": (
- "3-5 questions, shown one per step, all about your "
- "own role and the workflows installed on you. Order "
- "them from what you most need to know to what is "
- "merely nice to know."
+ f"{MIN_STEPS}-{MAX_STEPS} questions, shown one per "
+ "step, about your role and installed workflows. Ask "
+ "only what you need before you can start."
),
},
},
@@ -140,7 +147,13 @@ class ExpertOnboardingTool(BaseTool):
)
greeting = kwargs.get("greeting")
- if not isinstance(greeting, str) or not greeting.strip():
+ if not isinstance(greeting, str):
+ raise ValueError("expert_onboarding requires a non-empty 'greeting'")
+ # Cap before the regex: its leading ``\s*`` backtracks quadratically
+ # over a long run of spaces. Checked after the strip, so a greeting
+ # that was nothing but dashes counts as empty too.
+ greeting = _strip_dashes(greeting.strip()[:MAX_GREETING_LENGTH])
+ if not greeting:
raise ValueError("expert_onboarding requires a non-empty 'greeting'")
raw_steps = kwargs.get("steps", [])
@@ -157,7 +170,7 @@ class ExpertOnboardingTool(BaseTool):
message="; ".join(step.question for step in steps),
session_id=session.session_id,
expert_id=expert_id,
- greeting=greeting.strip()[:MAX_GREETING_LENGTH],
+ greeting=greeting,
steps=steps,
)
@@ -190,6 +203,12 @@ def _has_onboarded(session: ChatSession) -> bool:
return False
+def _strip_dashes(text: str) -> str:
+ """Turn every em or en dash into a comma: "I'm Jules — I write" reads
+ "I'm Jules, I write". A dash that ends the text is simply dropped."""
+ return _DASH.sub(", ", text.strip()).strip(", ")
+
+
def _parse_steps(raw: list[Any]) -> list[ExpertOnboardingStep]:
"""Parse raw step dicts, dropping invalid entries and duplicate keywords."""
steps: list[ExpertOnboardingStep] = []
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_onboarding_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_onboarding_test.py
index e5fae97421..caccf6c67b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_onboarding_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_onboarding_test.py
@@ -83,6 +83,30 @@ async def test_returns_greeting_and_steps(
assert result.message == "Which services should I plug into?"
+ "greeting, expected",
+ [
+ (
+ "Hi, I'm Jules — I turn talks into posts.",
+ "Hi, I'm Jules, I turn talks into posts.",
+ ),
+ ("I'm Nadia–competitor teardowns.", "I'm Nadia, competitor teardowns."),
+ ("Hi, I'm Ada —", "Hi, I'm Ada"),
+ ("Day-one ready.", "Day-one ready."),
+ ],
+)
+async def test_greeting_loses_its_dashes(
+ tool: ExpertOnboardingTool, session: ChatSession, greeting: str, expected: str
+):
+ result = await tool._execute(
+ user_id="test-user", session=session, greeting=greeting, steps=steps(2)
+ )
+
+ assert isinstance(result, ExpertOnboardingResponse)
+ assert result.greeting == expected
+
+
@pytest.mark.asyncio
async def test_step_without_options_is_open_ended(
tool: ExpertOnboardingTool, session: ChatSession
@@ -278,10 +302,13 @@ def test_schema_declares_the_step_range(tool: ExpertOnboardingTool):
@pytest.mark.asyncio
-async def test_rejects_empty_greeting(tool: ExpertOnboardingTool, session: ChatSession):
[email protected]("greeting", [" ", " — ", "–, —"])
+async def test_rejects_empty_greeting(
+ tool: ExpertOnboardingTool, session: ChatSession, greeting: str
+):
with pytest.raises(ValueError):
await tool._execute(
- user_id="test-user", session=session, greeting=" ", steps=steps()
+ user_id="test-user", session=session, greeting=greeting, steps=steps()
)
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/ExpertOnboardingCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/ExpertOnboardingCard.tsx
index f390e12141..5c4981d555 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/ExpertOnboardingCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/ExpertOnboardingCard.tsx
@@ -1,7 +1,7 @@
"use client";
import { Icon } from "@/components/atoms/Icon/Icon";
-import { getExpertRoleLabel } from "@/services/experts/expert-role-label";
+import { cn } from "@/lib/utils";
import {
ArrowLeft01Icon,
ArrowRight01Icon,
@@ -13,13 +13,9 @@ import { domAnimation, LazyMotion, m } from "framer-motion";
import { useContext, useId } from "react";
import { useExpertMap } from "../../useExpertMap";
import { ExpertAvatar } from "../ChatMessagesContainer/components/ExpertAvatar/ExpertAvatar";
-import { QuestionAnswerField } from "../ChainActionCard/QuestionAnswerField";
import { MorphingTextAnimation } from "../MorphingTextAnimation/MorphingTextAnimation";
-import {
- parseExpertOnboarding,
- toClarifyingQuestion,
- type ExpertOnboardingOutput,
-} from "./helpers";
+import { OnboardingChoices } from "./components/OnboardingChoices/OnboardingChoices";
+import { parseExpertOnboarding, type ExpertOnboardingOutput } from "./helpers";
import { PendingOnboardingContext } from "./PendingOnboardingContext";
import { useExpertOnboardingCard } from "./useExpertOnboardingCard";
@@ -27,10 +23,10 @@ interface Props {
part: ToolUIPart;
}
-/** The intake card a freshly hired expert opens with: a greeting in its own
- * voice and a few tappable questions, one per step. It stands outside the
- * tool chain because a chain collapses on top of its rows, and this one is
- * the only thing on screen the user is meant to act on. */
+/** The intake card a freshly hired expert opens with: a one-line greeting
+ * and a few tappable questions, one per step, Typeform style. It stands
+ * outside the tool chain because a chain collapses on top of its rows, and
+ * this one is the only thing on screen the user is meant to act on. */
export function ExpertOnboardingCard({ part }: Props) {
const pendingCallId = useContext(PendingOnboardingContext);
const onboarding = parseExpertOnboarding(part);
@@ -81,6 +77,7 @@ function OnboardingForm({ callId, onboarding, isLive }: FormProps) {
isSending,
value,
advance,
+ choose,
goBack,
setAnswer,
skip,
@@ -109,18 +106,35 @@ function OnboardingForm({ callId, onboarding, isLive }: FormProps) {
);
}
+ const total = onboarding.steps.length;
+
return (
<div className="w-full max-w-xl overflow-hidden rounded-3xl border border-zinc-100 bg-white shadow-[0_16px_40px_-24px_rgba(0,0,0,0.25)]">
- <div className="flex items-start justify-between gap-3 border-b border-zinc-100 px-4 py-3">
+ <div
+ role="progressbar"
+ aria-label="Setup progress"
+ aria-valuemin={1}
+ aria-valuemax={total}
+ aria-valuenow={current + 1}
+ aria-valuetext={`Question ${current + 1} of ${total}`}
+ className="h-1 bg-zinc-100"
+ >
+ <div
+ className="h-full bg-zinc-800 transition-[width] duration-300 ease-out"
+ style={{ width: `${((current + 1) / total) * 100}%` }}
+ />
+ </div>
+
+ <div className="flex items-start justify-between gap-3 px-5 pt-4">
<span className="flex min-w-0 items-center gap-3">
<ExpertAvatar name={name} avatarUrl={expert?.avatarUrl ?? null} />
<span className="flex min-w-0 flex-col">
<span className="truncate text-sm font-medium text-zinc-900">
{name}
</span>
- {expert?.role && (
- <span className="truncate text-xs text-zinc-500">
- {getExpertRoleLabel(expert.role)}
+ {onboarding.greeting && (
+ <span className="line-clamp-2 text-xs text-zinc-500">
+ {onboarding.greeting}
</span>
)}
</span>
@@ -135,12 +149,6 @@ function OnboardingForm({ callId, onboarding, isLive }: FormProps) {
</button>
</div>
- {onboarding.greeting && (
- <p className="border-b border-zinc-100 px-5 py-4 text-base leading-relaxed text-zinc-700">
- {onboarding.greeting}
- </p>
- )}
-
{/* Wraps only the pager, not the whole card: ``strict`` rejects any
``motion`` component below it, and the header's ExpertAvatar
animates its face with the full ``motion`` build. */}
@@ -150,76 +158,55 @@ function OnboardingForm({ callId, onboarding, isLive }: FormProps) {
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, ease: [0.23, 1, 0.32, 1] }}
- className="flex flex-col gap-4 px-5 pb-4 pt-5"
+ className="flex flex-col gap-4 px-5 pt-5"
>
- <span
- id={labelId}
- className="text-lg font-medium leading-snug text-zinc-900"
- >
- {currentStep.question}
+ <span className="flex gap-2 text-lg font-medium leading-snug text-zinc-900">
+ <span
+ aria-hidden="true"
+ className="flex shrink-0 items-center gap-0.5 text-sm text-zinc-400"
+ >
+ {current + 1}
+ <Icon icon={ArrowRight01Icon} size={12} />
+ </span>
+ <span id={labelId}>{currentStep.question}</span>
</span>
- <QuestionAnswerField
- // The field owns a typing toggle that must not leak between
- // questions; the key remounts it on every step.
+ <OnboardingChoices
key={currentStep.keyword}
- question={toClarifyingQuestion(currentStep)}
+ options={currentStep.options}
value={value}
labelId={labelId}
autoFocus={current > 0}
+ onChoose={choose}
onChange={setAnswer}
onSubmit={advance}
/>
</m.div>
</LazyMotion>
- <div className="flex items-center justify-between px-5 pb-4 pt-1">
- <span className="flex items-center gap-2">
- <button
- type="button"
- aria-label="Previous question"
- disabled={current === 0}
- onClick={goBack}
- className="flex size-6 items-center justify-center rounded-lg text-zinc-400 transition-colors enabled:hover:bg-zinc-100 enabled:hover:text-zinc-600 disabled:opacity-35"
- >
- <Icon icon={ArrowLeft01Icon} size={14} />
- </button>
- <span
- aria-hidden="true"
- className="flex items-center gap-1.5"
- data-testid="expert-onboarding-progress"
- >
- {onboarding.steps.map((step, index) => (
- <span
- key={step.keyword}
- className={
- "rounded-full transition-all duration-300 " +
- (index === current
- ? "size-2.5 border-2 border-zinc-800"
- : index < current
- ? "size-2 bg-zinc-400"
- : "size-2 border border-zinc-300")
- }
- />
- ))}
- </span>
- <span className="text-xs text-zinc-400">
- {current + 1} of {onboarding.steps.length}
- </span>
- </span>
-
+ <div className="flex items-center justify-between px-5 pb-4 pt-4">
+ <button
+ type="button"
+ aria-label="Previous question"
+ disabled={current === 0}
+ onClick={goBack}
+ className="flex size-8 items-center justify-center rounded-full text-zinc-400 transition-colors enabled:hover:bg-zinc-100 enabled:hover:text-zinc-600 disabled:invisible"
+ >
+ <Icon icon={ArrowLeft01Icon} size={16} />
+ </button>
<button
type="button"
aria-label={isLast ? "Send answers" : "Next question"}
disabled={!isAnswered || isSending}
onClick={advance}
- className={
- "flex size-8 items-center justify-center rounded-full transition-all duration-200 enabled:active:scale-95 " +
- (isAnswered && !isSending
- ? "bg-zinc-800 text-white hover:bg-zinc-900"
- : "bg-zinc-100 text-zinc-400")
- }
+ className={cn(
+ "flex h-8 items-center gap-1.5 rounded-full px-4 text-sm font-medium transition-all duration-200 enabled:active:scale-95",
+ isAnswered && !isSending
+ ? "bg-zinc-900 text-white hover:bg-zinc-800"
+ : "bg-zinc-100 text-zinc-400",
+ )}
>
- <Icon icon={isLast ? SentIcon : ArrowRight01Icon} size={15} />
+ {isLast ? "Send" : "Next"}
+ <Icon icon={isLast ? SentIcon : ArrowRight01Icon} size={14} />
</button>
</div>
</div>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/__tests__/ExpertOnboardingCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/__tests__/ExpertOnboardingCard.test.tsx
index 8193db04d5..8593f1566c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/__tests__/ExpertOnboardingCard.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/__tests__/ExpertOnboardingCard.test.tsx
@@ -103,19 +103,32 @@ function actionButton(label: string): HTMLButtonElement {
return screen.getByLabelText(label) as HTMLButtonElement;
}
+function questionNumber() {
+ return screen.getByRole("progressbar").getAttribute("aria-valuetext");
+}
+
+function isChecked(name: RegExp) {
+ return screen.getByRole("radio", { name }).getAttribute("aria-checked");
+}
+
+// A tap on a non-final step moves on by itself after a short beat.
+async function answerFirstStep() {
+ fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
+ await screen.findByText("Which service should I be connected to?");
+}
+
describe("ExpertOnboardingCard", () => {
- it("greets the user under the expert's identity with the shared area label", () => {
+ it("greets the user under the expert's name, without the role line", () => {
renderCard(onboardingPart());
expect(screen.getByText("Ada")).toBeDefined();
- expect(screen.getByText("Social Media Manager")).toBeDefined();
expect(screen.queryByText("Social & Content Repurposing")).toBeNull();
expect(
screen.getByText("Hi, I'm Ada — good to be working with you."),
).toBeDefined();
});
- it("shows one question at a time with tappable options", () => {
+ it("shows one question at a time with lettered options and Other", () => {
renderCard(onboardingPart());
expect(
@@ -125,60 +138,56 @@ describe("ExpertOnboardingCard", () => {
screen.queryByText("Which service should I be connected to?"),
).toBeNull();
expect(screen.getAllByRole("radio")).toHaveLength(2);
- expect(screen.getByText("1 of 2")).toBeDefined();
+ expect(screen.getByRole("button", { name: "Other" })).toBeDefined();
+ expect(questionNumber()).toBe("Question 1 of 2");
});
- it("waits for Next after an option is tapped", () => {
+ it("moves to the next question once an option is tapped", async () => {
renderCard(onboardingPart());
- expect(actionButton("Next question").disabled).toBe(true);
+ await answerFirstStep();
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
+ expect(questionNumber()).toBe("Question 2 of 2");
+ });
- // The tap only selects, leaving room to change or edit the answer.
- expect(screen.getByText("1 of 2")).toBeDefined();
- expect(actionButton("Next question").disabled).toBe(false);
+ it("picks an option by its letter key", async () => {
+ renderCard(onboardingPart());
- fireEvent.click(actionButton("Next question"));
- expect(
- screen.getByText("Which service should I be connected to?"),
- ).toBeDefined();
+ fireEvent.keyDown(screen.getByRole("radio", { name: /Social listening/ }), {
+ key: "b",
+ });
+
+ expect(isChecked(/Campaign briefs/)).toBe("true");
+ await screen.findByText("Which service should I be connected to?");
});
- it("merges edited options into one typed answer", () => {
+ it("moves the selection with arrow keys without leaving the question", () => {
renderCard(onboardingPart());
- fireEvent.click(
- screen.getByRole("button", { name: "Edit Social listening" }),
- );
- fireEvent.click(
- screen.getByRole("button", { name: "Edit Campaign briefs" }),
- );
+ fireEvent.keyDown(screen.getByRole("radio", { name: /Social listening/ }), {
+ key: "ArrowDown",
+ });
- expect((screen.getByRole("textbox") as HTMLTextAreaElement).value).toBe(
- "Social listening\nCampaign briefs",
- );
- expect(screen.getAllByRole("radio")).toHaveLength(2);
- expect(screen.getByText("1 of 2")).toBeDefined();
+ expect(isChecked(/Campaign briefs/)).toBe("true");
+ expect(questionNumber()).toBe("Question 1 of 2");
});
- it("will not send until the last step is answered", () => {
+ it("will not send until the last step is answered", async () => {
renderCard(onboardingPart());
-
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
- fireEvent.click(actionButton("Next question"));
+ await answerFirstStep();
expect(actionButton("Send answers").disabled).toBe(true);
fireEvent.click(screen.getByRole("radio", { name: /Linear/ }));
+ // The last tap only selects: sending waits for the button.
expect(actionButton("Send answers").disabled).toBe(false);
});
it("keeps the Next button for a typed answer, which cannot auto-advance", () => {
renderCard(onboardingPart());
- fireEvent.click(screen.getByRole("button", { name: /Type something/ }));
+ fireEvent.click(screen.getByRole("button", { name: "Other" }));
const textarea = screen.getByRole("textbox");
expect(actionButton("Next question").disabled).toBe(true);
@@ -186,18 +195,15 @@ describe("ExpertOnboardingCard", () => {
fireEvent.change(textarea, { target: { value: "Competitor tracking" } });
// Still on step one — there is no single moment a typed answer is done.
- expect(screen.getByText("1 of 2")).toBeDefined();
+ expect(questionNumber()).toBe("Question 1 of 2");
fireEvent.click(actionButton("Next question"));
- expect(screen.getByText("2 of 2")).toBeDefined();
+ expect(questionNumber()).toBe("Question 2 of 2");
});
- it("sends every answer as one message on the last step", () => {
+ it("sends every answer as one message on the last step", async () => {
const { onSend } = renderCard(onboardingPart());
+ await answerFirstStep();
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
- fireEvent.click(actionButton("Next question"));
-
- expect(screen.getByText("2 of 2")).toBeDefined();
fireEvent.click(screen.getByRole("radio", { name: /Linear/ }));
fireEvent.click(actionButton("Send answers"));
@@ -209,19 +215,14 @@ describe("ExpertOnboardingCard", () => {
expect(message).toContain("Linear");
});
- it("lets the user step back to change an answer", () => {
+ it("lets the user step back to change an answer", async () => {
renderCard(onboardingPart());
+ await answerFirstStep();
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
- fireEvent.click(actionButton("Next question"));
fireEvent.click(actionButton("Previous question"));
- expect(screen.getByText("1 of 2")).toBeDefined();
- expect(
- screen
- .getByRole("radio", { name: /Social listening/ })
- .getAttribute("aria-checked"),
- ).toBe("true");
+ expect(questionNumber()).toBe("Question 1 of 2");
+ expect(isChecked(/Social listening/)).toBe("true");
});
it("skips the whole card without answering", () => {
@@ -264,54 +265,55 @@ describe("ExpertOnboardingCard", () => {
expect(screen.getByText(/Couldn.t open the setup questions/)).toBeDefined();
});
- it("keeps its place when the settled turn re-keys its message", () => {
+ it("keeps its place when the settled turn re-keys its message", async () => {
const { rekeyRow } = renderCard(onboardingPart());
-
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
- fireEvent.click(actionButton("Next question"));
- expect(screen.getByText("2 of 2")).toBeDefined();
+ await answerFirstStep();
rekeyRow();
- expect(screen.getByText("2 of 2")).toBeDefined();
+ expect(questionNumber()).toBe("Question 2 of 2");
expect(
screen.getByText("Which service should I be connected to?"),
).toBeDefined();
fireEvent.click(actionButton("Previous question"));
+ expect(isChecked(/Social listening/)).toBe("true");
+ });
+
+ it("still moves on when the row re-keys during the auto-advance beat", () => {
+ const { rekeyRow } = renderCard(onboardingPart());
+
+ fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
+ rekeyRow();
+
+ expect(questionNumber()).toBe("Question 2 of 2");
expect(
- screen
- .getByRole("radio", { name: /Social listening/ })
- .getAttribute("aria-checked"),
- ).toBe("true");
+ screen.getByText("Which service should I be connected to?"),
+ ).toBeDefined();
+ fireEvent.click(actionButton("Previous question"));
+ expect(isChecked(/Social listening/)).toBe("true");
});
- it("restores the answers given so far after a reload", () => {
+ it("restores the answers given so far after a reload", async () => {
renderCard(onboardingPart());
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
- fireEvent.click(actionButton("Next question"));
+ await answerFirstStep();
fireEvent.click(screen.getByRole("radio", { name: /Linear/ }));
cleanup();
renderCard(onboardingPart());
- expect(screen.getByText("2 of 2")).toBeDefined();
- expect(
- screen
- .getByRole("radio", { name: /Linear/ })
- .getAttribute("aria-checked"),
- ).toBe("true");
+ expect(questionNumber()).toBe("Question 2 of 2");
+ expect(isChecked(/Linear/)).toBe("true");
});
- it("starts a different card from the beginning", () => {
+ it("starts a different card from the beginning", async () => {
renderCard(onboardingPart());
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
- fireEvent.click(actionButton("Next question"));
+ await answerFirstStep();
cleanup();
const other = { ...onboardingPart(), toolCallId: "call-onboarding-2" };
renderCard(other as ToolUIPart, "call-onboarding-2");
- expect(screen.getByText("1 of 2")).toBeDefined();
+ expect(questionNumber()).toBe("Question 1 of 2");
expect(screen.queryByRole("radio", { checked: true })).toBeNull();
});
@@ -320,8 +322,7 @@ describe("ExpertOnboardingCard", () => {
onSend.mockResolvedValue(undefined);
renderCard(onboardingPart(), CALL_ID, onSend);
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
- fireEvent.click(actionButton("Next question"));
+ await answerFirstStep();
fireEvent.click(screen.getByRole("radio", { name: /Linear/ }));
fireEvent.click(actionButton("Send answers"));
await waitFor(() =>
@@ -331,7 +332,7 @@ describe("ExpertOnboardingCard", () => {
renderCard(onboardingPart());
- expect(screen.getByText("1 of 2")).toBeDefined();
+ expect(questionNumber()).toBe("Question 1 of 2");
expect(screen.queryByRole("radio", { checked: true })).toBeNull();
});
@@ -340,20 +341,13 @@ describe("ExpertOnboardingCard", () => {
onSend.mockRejectedValue(new Error("no session"));
renderCard(onboardingPart(), CALL_ID, onSend);
- fireEvent.click(screen.getByRole("radio", { name: /Social listening/ }));
- fireEvent.click(actionButton("Next question"));
+ await answerFirstStep();
fireEvent.click(screen.getByRole("radio", { name: /Linear/ }));
fireEvent.click(actionButton("Send answers"));
await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
// Still the live form, with the answer intact — not a settled history row.
- await waitFor(() =>
- expect(
- screen
- .getByRole("radio", { name: /Linear/ })
- .getAttribute("aria-checked"),
- ).toBe("true"),
- );
+ await waitFor(() => expect(isChecked(/Linear/)).toBe("true"));
expect(screen.queryByText(/Setup questions from/)).toBeNull();
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/components/OnboardingChoices/OnboardingChoices.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/components/OnboardingChoices/OnboardingChoices.tsx
new file mode 100644
index 0000000000..3f76ac71a3
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/components/OnboardingChoices/OnboardingChoices.tsx
@@ -0,0 +1,131 @@
+"use client";
+
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { cn } from "@/lib/utils";
+import { Tick02Icon } from "@hugeicons/core-free-icons";
+import { getOptionLetter } from "../../helpers";
+import { useOnboardingChoices } from "./useOnboardingChoices";
+
+interface Props {
+ options: string[];
+ value: string;
+ labelId: string;
+ autoFocus: boolean;
+ onChoose: (option: string) => void;
+ onChange: (value: string) => void;
+ onSubmit: () => void;
+}
+
+/** One question's answers as lettered rows: a tap or its letter key picks
+ * the row, and the last row, "Other", opens a text box. Mounted per step,
+ * so the text box toggle starts fresh on every question. */
+export function OnboardingChoices({
+ options,
+ value,
+ labelId,
+ autoFocus,
+ onChoose,
+ onChange,
+ onSubmit,
+}: Props) {
+ const {
+ active,
+ didOpenOther,
+ isTyping,
+ optionRefs,
+ choose,
+ startTyping,
+ handleLetterKey,
+ handleOptionKeyDown,
+ handleTextKeyDown,
+ } = useOnboardingChoices({ options, value, onChoose, onChange, onSubmit });
+
+ return (
+ <div className="flex flex-col gap-2">
+ {options.length > 0 && (
+ <div
+ role="radiogroup"
+ aria-labelledby={labelId}
+ aria-required="true"
+ className="flex flex-col gap-2"
+ >
+ {options.map((option, index) => {
+ const isSelected = option === value.trim();
+ return (
+ <button
+ key={option}
+ ref={(element) => {
+ optionRefs.current[index] = element;
+ }}
+ type="button"
+ role="radio"
+ aria-checked={isSelected}
+ tabIndex={index === active ? 0 : -1}
+ autoFocus={autoFocus && !isTyping && index === active}
+ onClick={() => choose(option)}
+ onKeyDown={(event) => handleOptionKeyDown(event, index)}
+ className={cn(
+ "flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left text-[15px] leading-snug transition-colors",
+ isSelected
+ ? "bg-zinc-900 text-white"
+ : "bg-zinc-50 text-zinc-800 ring-1 ring-zinc-100 hover:bg-zinc-100",
+ )}
+ >
+ <LetterBadge index={index} isSelected={isSelected} />
+ <span className="flex-1">{option}</span>
+ {isSelected && (
+ <Icon icon={Tick02Icon} size={16} className="shrink-0" />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ {isTyping ? (
+ <textarea
+ required
+ rows={2}
+ aria-labelledby={labelId}
+ autoFocus={autoFocus || didOpenOther}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ onKeyDown={handleTextKeyDown}
+ placeholder="Type your answer"
+ className="resize-none rounded-xl bg-zinc-50 px-4 py-3 text-[15px] leading-relaxed text-zinc-800 ring-1 ring-zinc-200 transition-shadow placeholder:text-zinc-400 focus:outline-none focus:ring-zinc-400"
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={startTyping}
+ onKeyDown={handleLetterKey}
+ className="flex w-full items-center gap-3 rounded-xl border border-dashed border-zinc-200 px-3 py-2.5 text-left text-[15px] text-zinc-500 transition-colors hover:bg-zinc-50 hover:text-zinc-700"
+ >
+ <LetterBadge index={options.length} isSelected={false} />
+ Other
+ </button>
+ )}
+ </div>
+ );
+}
+
+interface LetterBadgeProps {
+ index: number;
+ isSelected: boolean;
+}
+
+function LetterBadge({ index, isSelected }: LetterBadgeProps) {
+ return (
+ <span
+ aria-hidden="true"
+ className={cn(
+ "flex size-6 shrink-0 items-center justify-center rounded-md text-xs font-medium",
+ isSelected
+ ? "bg-white/15 text-white"
+ : "bg-white text-zinc-500 ring-1 ring-zinc-200",
+ )}
+ >
+ {getOptionLetter(index)}
+ </span>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/components/OnboardingChoices/useOnboardingChoices.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/components/OnboardingChoices/useOnboardingChoices.ts
new file mode 100644
index 0000000000..925d87db3c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/components/OnboardingChoices/useOnboardingChoices.ts
@@ -0,0 +1,101 @@
+import { isComposingEvent, isKey } from "@/lib/keyboard";
+import { useRef, useState, type KeyboardEvent } from "react";
+import { getLetterIndex } from "../../helpers";
+
+interface Args {
+ options: string[];
+ value: string;
+ onChoose: (option: string) => void;
+ onChange: (value: string) => void;
+ onSubmit: () => void;
+}
+
+export function useOnboardingChoices({
+ options,
+ value,
+ onChoose,
+ onChange,
+ onSubmit,
+}: Args) {
+ const trimmed = value.trim();
+ const isCustom = trimmed.length > 0 && !options.includes(trimmed);
+ const [isTyping, setIsTyping] = useState(isCustom || options.length === 0);
+ // A saved custom answer opens the text box on mount, but only a click on
+ // Other may pull focus into it.
+ const [didOpenOther, setDidOpenOther] = useState(false);
+ const optionRefs = useRef<(HTMLButtonElement | null)[]>([]);
+ const selected = options.indexOf(trimmed);
+ const active = selected === -1 ? 0 : selected;
+
+ function choose(option: string) {
+ setIsTyping(false);
+ onChoose(option);
+ }
+
+ function startTyping() {
+ if (!isCustom) onChange("");
+ setIsTyping(true);
+ setDidOpenOther(true);
+ }
+
+ // Arrows only move the selection: picking with them must not jump to the
+ // next question while the user is still browsing the list.
+ function moveTo(index: number) {
+ onChange(options[index]);
+ optionRefs.current[index]?.focus();
+ }
+
+ // A letter picks its row from anywhere in the list, the last one being
+ // "Other". Returns whether the key was used.
+ function handleLetterKey(event: KeyboardEvent) {
+ if (isComposingEvent(event)) return false;
+ const letter = getLetterIndex(event);
+ if (letter === null || letter > options.length) return false;
+ event.preventDefault();
+ if (letter === options.length) startTyping();
+ else choose(options[letter]);
+ return true;
+ }
+
+ function handleOptionKeyDown(event: KeyboardEvent, index: number) {
+ if (handleLetterKey(event)) return;
+ if (isKey(event, "Enter")) {
+ event.preventDefault();
+ if (options[index] === trimmed) onSubmit();
+ else choose(options[index]);
+ return;
+ }
+ if (isKey(event, " ")) {
+ event.preventDefault();
+ choose(options[index]);
+ return;
+ }
+ const step = isKey(event, "ArrowDown", "ArrowRight")
+ ? 1
+ : isKey(event, "ArrowUp", "ArrowLeft")
+ ? -1
+ : 0;
+ if (step === 0) return;
+ event.preventDefault();
+ moveTo((index + step + options.length) % options.length);
+ }
+
+ // Enter moves on; Shift+Enter is the newline.
+ function handleTextKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
+ if (!isKey(event, "Enter") || event.shiftKey) return;
+ event.preventDefault();
+ onSubmit();
+ }
+
+ return {
+ active,
+ didOpenOther,
+ isTyping,
+ optionRefs,
+ choose,
+ startTyping,
+ handleLetterKey,
+ handleOptionKeyDown,
+ handleTextKeyDown,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/helpers.ts
index 9001086c09..2e08d8af5d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/helpers.ts
@@ -1,7 +1,7 @@
import type { ExpertOnboardingStep as ExpertOnboardingStepPayload } from "@/app/api/__generated__/models/expertOnboardingStep";
import { ResponseType } from "@/app/api/__generated__/models/responseType";
import type { ToolUIPart, UIDataTypes, UIMessage, UITools } from "ai";
-import type { ClarifyingQuestion } from "../../tools/clarifying-questions";
+import type { KeyboardEvent } from "react";
export const EXPERT_ONBOARDING_PART_TYPE = "tool-expert_onboarding";
@@ -64,16 +64,16 @@ export function parseExpertOnboarding(
};
}
-/** The card reuses the tool chain's answer field, which speaks
- * `ClarifyingQuestion`. `example` stays empty: the field only shows it when
- * a question has no options, and an onboarding step without options is an
- * open "anything else?" that reads better with the plain placeholder. */
-export function toClarifyingQuestion(
- step: ExpertOnboardingStep,
-): ClarifyingQuestion {
- return step.options.length > 0
- ? { question: step.question, keyword: step.keyword, options: step.options }
- : { question: step.question, keyword: step.keyword };
+export function getOptionLetter(index: number): string {
+ return String.fromCharCode(65 + index);
+}
+
+/** The option a bare letter key picks, Typeform style: A is the first. */
+export function getLetterIndex(event: KeyboardEvent): number | null {
+ if (event.metaKey || event.ctrlKey || event.altKey) return null;
+ if (event.key.length !== 1) return null;
+ const index = event.key.toUpperCase().charCodeAt(0) - 65;
+ return index >= 0 && index < 26 ? index : null;
}
export function buildOnboardingAnswersMessage(
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/useExpertOnboardingCard.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/useExpertOnboardingCard.ts
index 8e8a0fec26..40a357b886 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/useExpertOnboardingCard.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ExpertOnboardingCard/useExpertOnboardingCard.ts
@@ -1,6 +1,7 @@
"use client";
-import { useEffect, useState } from "react";
+import { useMountEffect } from "@/hooks/useMountEffect";
+import { useEffect, useRef, useState } from "react";
import { useCopilotChatActions } from "../CopilotChatActionsProvider/useCopilotChatActions";
import {
buildOnboardingAnswersMessage,
@@ -13,6 +14,8 @@ import {
} from "./onboardingProgress";
const SKIP_MESSAGE = "Let's skip the setup questions for now.";
+// Long enough to see the tapped row light up before the next question.
+const AUTO_ADVANCE_MS = 300;
interface Args {
callId: string;
@@ -33,6 +36,11 @@ export function useExpertOnboardingCard({ callId, steps, isLive }: Args) {
);
const [isSent, setIsSent] = useState(false);
const [isSending, setIsSending] = useState(false);
+ // The step a tapped option is about to move to. Saved in place of ``step``
+ // so a remount inside the auto-advance beat still lands on the next
+ // question instead of stranding the user on the one they just answered.
+ const [advancingTo, setAdvancingTo] = useState<number | null>(null);
+ const advanceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const current = Math.min(step, steps.length - 1);
const currentStep = steps[current];
@@ -45,14 +53,40 @@ export function useExpertOnboardingCard({ callId, steps, isLive }: Args) {
useEffect(() => {
if (isDone) return;
- writeOnboardingProgress(callId, { step, answers });
- }, [callId, step, answers, isDone]);
+ writeOnboardingProgress(callId, { step: advancingTo ?? step, answers });
+ }, [callId, step, advancingTo, answers, isDone]);
+
+ useMountEffect(() => () => {
+ if (advanceTimer.current) clearTimeout(advanceTimer.current);
+ });
+
+ function cancelAutoAdvance() {
+ if (advanceTimer.current) clearTimeout(advanceTimer.current);
+ advanceTimer.current = null;
+ setAdvancingTo(null);
+ }
function setAnswer(next: string) {
+ cancelAutoAdvance();
setAnswers((previous) => ({ ...previous, [currentStep.keyword]: next }));
}
+ // A tapped option is a whole answer, so it moves on by itself. The last
+ // step waits for Send: sending is the one move the user can't take back.
+ function choose(option: string) {
+ setAnswer(option);
+ if (isLast) return;
+ const next = current + 1;
+ setAdvancingTo(next);
+ advanceTimer.current = setTimeout(() => {
+ advanceTimer.current = null;
+ setAdvancingTo(null);
+ setStep(next);
+ }, AUTO_ADVANCE_MS);
+ }
+
function goBack() {
+ cancelAutoAdvance();
setStep(Math.max(current - 1, 0));
}
@@ -96,6 +130,7 @@ export function useExpertOnboardingCard({ callId, steps, isLive }: Args) {
isSending,
value,
advance,
+ choose,
goBack,
setAnswer,
skip,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts
index d60c88ca75..a4e885e117 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts
@@ -14,8 +14,9 @@ const PENDING_TTL_MS = 2 * 60 * 1000;
// so any redesign of this message, including this one, stays ask-first.
const KICKOFF_PROMPT =
"You were just hired. Call expert_onboarding once, and nothing else, this " +
- "turn: a greeting of 1-2 sentences introducing yourself in your voice, " +
- "then 3-5 questions the user can answer by tapping. Every question and " +
+ "turn: a one-sentence greeting introducing yourself in your voice, with " +
+ "no dashes, then " +
+ "2-3 short questions the user can answer by tapping. Every question and " +
"every option must come from your own role and area of expertise and from " +
"the workflows installed on you — ask which outcome in your area to start " +
"with, and which of the services your work depends on you should be " +