Skip to content

Automate browser based workflows with AI

Give every question part a field it can be answered in (SKY-15616) (#8447)

Aaron Perez7f131282799c
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.cardAdjacency.test.ts b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.cardAdjacency.test.ts
new file mode 100644
index 000000000..02ebc7ae8
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.cardAdjacency.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vitest";
+
+import { nextAnsweringMessage, questionCardAdjacency } from "./cardAdjacency";
+import type { ChatMessage } from "./WorkflowCopilotChat";
+
+const msg = (
+ id: string,
+ sender: ChatMessage["sender"],
+ overrides: Partial<ChatMessage> = {},
+): ChatMessage =>
+ ({
+ id,
+ sender,
+ content: id,
+ timestamp: "2026-09-04T00:00:00Z",
+ ...overrides,
+ }) as ChatMessage;
+
+const lifecycle = (id: string) =>
+ msg(id, "ai", { kind: "run_lifecycle" } as Partial<ChatMessage>);
+
+describe("nextAnsweringMessage", () => {
+ // The question card treats the following message as the answer: it goes read-only and reads its
+ // receipt from it. A run_lifecycle row is synthetic, so counting it would hide the fields
+ // mid-typing and point the receipt at a line the user never wrote.
+ it("skips a lifecycle row appended after an ask and finds the real answer", () => {
+ const messages = [
+ msg("ask", "ai"),
+ lifecycle("run-started"),
+ msg("answer", "user"),
+ ];
+
+ expect(nextAnsweringMessage(messages, 0)?.id).toBe("answer");
+ });
+
+ it("reports nothing answerable when only lifecycle rows follow the ask", () => {
+ const messages = [msg("ask", "ai"), lifecycle("run-started")];
+
+ expect(nextAnsweringMessage(messages, 0)).toBeUndefined();
+ });
+
+ it("still finds an immediately adjacent answer", () => {
+ const messages = [msg("ask", "ai"), msg("answer", "user")];
+
+ expect(nextAnsweringMessage(messages, 0)?.id).toBe("answer");
+ });
+});
+
+// The card renders BOTH of its adjacency props from questionCardAdjacency. Asserting
+// nextAnsweringMessage alone left either prop free to revert to raw messages[index + 1] with the
+// suite still green — the green-under-mutation shape SKY-15619 was filed for.
+describe("questionCardAdjacency", () => {
+ it("derives both card props across a synthetic row", () => {
+ const messages = [
+ msg("ask", "ai"),
+ lifecycle("run-started"),
+ msg("answer", "user"),
+ ];
+
+ expect(questionCardAdjacency(messages, 0)).toEqual({
+ answeredFrom: "answer",
+ hasFollowingMessage: true,
+ });
+ });
+
+ it("leaves the card live when only a synthetic row follows the ask", () => {
+ const messages = [msg("ask", "ai"), lifecycle("run-started")];
+
+ expect(questionCardAdjacency(messages, 0)).toEqual({
+ answeredFrom: null,
+ hasFollowingMessage: false,
+ });
+ });
+
+ it("reports a following AI turn as consuming without offering it as a receipt", () => {
+ const messages = [msg("ask", "ai"), msg("next-turn", "ai")];
+
+ expect(questionCardAdjacency(messages, 0)).toEqual({
+ answeredFrom: null,
+ hasFollowingMessage: true,
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
index 737920c4e..0dba95bf0 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
@@ -1123,3 +1123,65 @@ describe("WorkflowCopilotChat — recovery poll after a non-terminal stream clos
expect(renderedText()).not.toContain(capturedAiText);
});
});
+
+// A mounted assertion, not a helper one. The adjacency helper has its own unit tests, but those
+// stay green if either QuestionPartsCard prop in the JSX reverts to raw messages[index + 1] —
+// verified by mutation, both reverts passed the whole suite. Only rendering the chat catches it.
+describe("WorkflowCopilotChat — question card survives a synthetic row", () => {
+ it("keeps the answer fields live when a lifecycle row lands after the ask", async () => {
+ await renderChat();
+ await flushHistory(
+ historyData({
+ chat_history: [
+ aiHistoryMessage(
+ narrativePayload({
+ turnId: "turn-ask",
+ responseType: "ASK_QUESTION",
+ terminalMessage: "Which store?",
+ narrativeSummary: "Which store?",
+ terminalEnvelope: {
+ next_state: "awaiting_user_input",
+ rendered_from_envelope: true,
+ question_parts: [
+ { part_id: "p1", prompt: "Which store?", choices: [] },
+ ],
+ },
+ }),
+ "Which store?",
+ ),
+ ],
+ }),
+ );
+
+ // The card's own field, distinct from the composer textarea.
+ await waitFor(() =>
+ expect(screen.getByLabelText("Which store?")).toBeTruthy(),
+ );
+
+ // A run-lifecycle row is synthetic; it is not the user answering.
+ await act(async () => {
+ announceRef.current?.({
+ id: "lifecycle-1",
+ sender: "ai",
+ content: "Run started",
+ kind: "run_lifecycle",
+ });
+ await Promise.resolve();
+ });
+
+ expect(screen.getByLabelText("Which store?")).toBeTruthy();
+
+ // Now the real answer arrives AFTER the synthetic row. With raw adjacency the synthetic row
+ // is what the card reads, so no receipt renders and the user's answer is lost from the card.
+ const composer = screen.getByPlaceholderText("Answer Copilot…");
+ fireEvent.change(composer, {
+ target: { value: "Which store? — acme.example" },
+ });
+ await act(async () => {
+ fireEvent.keyDown(composer, { key: "Enter" });
+ await Promise.resolve();
+ });
+
+ await waitFor(() => expect(screen.getByText("acme.example")).toBeTruthy());
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index f128d4405..750904fea 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -84,6 +84,8 @@ import { useRunLifecycleAnnouncements } from "./useRunLifecycleAnnouncements";
import { ConfirmCard, shouldShowConfirmCard } from "./cards/ConfirmCard";
import { ConnectedAccountChoiceCard } from "./cards/ConnectedAccountChoiceCard";
import { QuestionPartsCard } from "./cards/QuestionPartsCard";
+import { questionCardAdjacency } from "./cardAdjacency";
+import { composerPlaceholder } from "./composerPlaceholder";
import { connectedAccountChoiceLabel } from "./cards/connectedAccountChoiceLabel";
import { shouldShowDiffCard } from "./cards/DiffCard";
import { ReviewGateCard, getReviewGateVerdict } from "./cards/ReviewGateCard";
@@ -3629,6 +3631,12 @@ export function WorkflowCopilotChat({
: "Listening…"
: browserStatusText;
const lastTurnIndex = findLastTurnIndex(messages);
+ // Same tail rule the session pill uses: the ask is live only while it is the end of the
+ // conversation. The composer is the answer path for anything the card cannot take, so while a
+ // question is pending it says so rather than inviting a new request.
+ const latestTurnIsAsk =
+ messages[lastTurnIndex]?.sender === "ai" &&
+ awaitsUserInput(messages[lastTurnIndex]?.narrative);
// A bypassed proposal's gate stays attached to its owning turn (not
// necessarily the last message) so a chip can jump back to it.
const gateOwnerIndex = pendingProposalTurnId
@@ -3902,6 +3910,9 @@ export function WorkflowCopilotChat({
? (message.narrative.terminalEnvelope?.questionParts ?? [])
: [];
const adjacentMessage = messages[index + 1];
+ // The parts card must not treat a synthetic row as an answer; both of its
+ // adjacency props come from one shared function so neither can drift back.
+ const cardAdjacency = questionCardAdjacency(messages, index);
const selectedConnectionId =
adjacentMessage?.sender === "user" &&
choices.some(
@@ -3951,15 +3962,11 @@ export function WorkflowCopilotChat({
{questionParts.length > 0 ? (
<QuestionPartsCard
parts={questionParts}
- answeredFrom={
- adjacentMessage?.sender === "user"
- ? adjacentMessage.content
- : null
- }
+ answeredFrom={cardAdjacency.answeredFrom}
disabled={
!isLastMessage ||
isLoading ||
- adjacentMessage !== undefined
+ cardAdjacency.hasFollowingMessage
}
onAnswer={(answer) => void handleSend(answer)}
/>
@@ -4356,17 +4363,13 @@ export function WorkflowCopilotChat({
)}
<textarea
ref={setTextareaRef}
- placeholder={
- queuedPrompt
- ? "Type to replace the queued message…"
- : isLoading
- ? "Type to queue a message…"
- : isWaitingForLiveBrowser
- ? "Type a prompt to send when ready..."
- : copilotV2Enabled
- ? "Ask Copilot to build or change your workflow…"
- : "Message Skyvern Copilot, or paste recorded steps…"
- }
+ placeholder={composerPlaceholder({
+ queuedPrompt: Boolean(queuedPrompt),
+ isLoading,
+ isWaitingForLiveBrowser,
+ latestTurnIsAsk,
+ copilotV2Enabled,
+ })}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyPress}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cardAdjacency.qaRepro.test.ts b/skyvern-frontend/src/routes/workflows/copilot/cardAdjacency.qaRepro.test.ts
new file mode 100644
index 000000000..36610400b
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/cardAdjacency.qaRepro.test.ts
@@ -0,0 +1,43 @@
+// Pins: no FE-synthetic row may read as the user's answer. `ChatMessage.kind` is a closed set of
+// two — `run_lifecycle` and `status_notice` — and a guard naming only one lets the other through,
+// which sends the question card read-only mid-typing and makes its receipt source a line no user
+// wrote. Origin: QA repro, adopted into #16625.
+
+import { describe, expect, it } from "vitest";
+
+import { nextAnsweringMessage } from "./cardAdjacency";
+import type { ChatMessage } from "./WorkflowCopilotChat";
+
+const msg = (
+ id: string,
+ sender: ChatMessage["sender"],
+ overrides: Partial<ChatMessage> = {},
+): ChatMessage =>
+ ({
+ id,
+ sender,
+ content: id,
+ timestamp: "2026-09-04T00:00:00Z",
+ ...overrides,
+ }) as ChatMessage;
+
+const statusNotice = (id: string) =>
+ msg(id, "ai", { kind: "status_notice" } as Partial<ChatMessage>);
+
+describe("nextAnsweringMessage — QA repro", () => {
+ it("skips a status_notice row the way it skips run_lifecycle", () => {
+ const messages = [
+ msg("ask", "ai"),
+ statusNotice("stop"),
+ msg("answer", "user"),
+ ];
+
+ expect(nextAnsweringMessage(messages, 0)?.id).toBe("answer");
+ });
+
+ it("reports nothing answerable when only a status_notice follows the ask", () => {
+ const messages = [msg("ask", "ai"), statusNotice("stop")];
+
+ expect(nextAnsweringMessage(messages, 0)).toBeUndefined();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cardAdjacency.ts b/skyvern-frontend/src/routes/workflows/copilot/cardAdjacency.ts
new file mode 100644
index 000000000..f1d74a9d2
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/cardAdjacency.ts
@@ -0,0 +1,38 @@
+import type { ChatMessage } from "./WorkflowCopilotChat";
+
+// Rows the FE synthesises for display. They are never persisted and never sent to the LLM, so
+// none of them is an answer — `ChatMessage.kind` is the closed set, and skipping only one of them
+// leaves the other reading as one.
+const SYNTHETIC_KINDS: ReadonlySet<string> = new Set([
+ "run_lifecycle",
+ "status_notice",
+]);
+
+// The next message a user could have answered with. Raw messages[index + 1] would let a synthetic
+// row appended after an ask read as an answer: the card would go read-only, discarding anything
+// half-typed in its fields, and a real answer arriving later would no longer be the receipt
+// source. Its own module so the chat file keeps exporting only components (Fast Refresh).
+export function nextAnsweringMessage(
+ messages: ChatMessage[],
+ index: number,
+): ChatMessage | undefined {
+ for (let next = index + 1; next < messages.length; next += 1) {
+ const candidate = messages[next];
+ if (!SYNTHETIC_KINDS.has(candidate?.kind ?? "")) return candidate;
+ }
+ return undefined;
+}
+
+// The two adjacency-derived props the question card renders from. Exported as one function so the
+// render and the test share a single source: asserting nextAnsweringMessage alone left both props
+// free to revert to raw adjacency while the tests stayed green.
+export function questionCardAdjacency(
+ messages: ChatMessage[],
+ index: number,
+): { answeredFrom: string | null; hasFollowingMessage: boolean } {
+ const answering = nextAnsweringMessage(messages, index);
+ return {
+ answeredFrom: answering?.sender === "user" ? answering.content : null,
+ hasFollowingMessage: answering !== undefined,
+ };
+}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.qaRepro.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.qaRepro.test.tsx
new file mode 100644
index 000000000..f7d7a0732
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.qaRepro.test.tsx
@@ -0,0 +1,131 @@
+// @vitest-environment jsdom
+//
+// Pins the four user-facing guarantees of the question card: it never offers a Send it cannot
+// enable, its counter can always reach its own denominator, an answer is attributed to the part
+// that was answered rather than to a twin, and a multi-line choice stays legible once answered.
+// Each began as a QA repro that failed on the shipped build; adopted into #16625 with the fixes.
+
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { QuestionPartsCard } from "./QuestionPartsCard";
+import { questionAnswerLine } from "./questionAnswerLine";
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("QuestionPartsCard — QA repros", () => {
+ // REPRO 1 (MAJOR): every part is choice-less, so `pending` can never be
+ // non-empty and the Send button can never enable. The card still renders
+ // "0 of N answered" next to a permanently dead Send, and carries no input of
+ // its own, so the affordance reads as broken input.
+ // Observed live on staging: chat wcc_570372112386389568, turn 2.
+ it("does not offer a Send affordance it can never enable", () => {
+ const onAnswer = vi.fn();
+ render(
+ <QuestionPartsCard
+ parts={[
+ { part_id: "p1", prompt: "Which catalog page?", choices: [] },
+ { part_id: "p2", prompt: "Which email?", choices: [] },
+ ]}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={onAnswer}
+ />,
+ );
+
+ const send = screen.queryByRole("button", { name: "Send" });
+ const card = screen.getByRole("group", { name: "Question parts" });
+ const canAnswerInCard =
+ card.querySelectorAll("input, textarea").length > 0 ||
+ screen.queryAllByRole("button", { pressed: false }).length > 0;
+
+ // Either the card offers a way to answer in place, or it must not render a
+ // counter and Send button that nothing the user does can ever satisfy.
+ if (send !== null) {
+ expect(canAnswerInCard).toBe(true);
+ }
+ });
+
+ // REPRO 2 (MAJOR): the mixed case. The counter's denominator is every part,
+ // but only a part with choices can ever become pending, so the count can
+ // never reach its own denominator. Observed live on staging: chat
+ // wcc_570372112386389568 turn 1 (p1 free-form, p2 with three choices) tops
+ // out at "1 of 2 answered".
+ it("does not show a counter whose denominator it can never reach", () => {
+ render(
+ <QuestionPartsCard
+ parts={[
+ { part_id: "p1", prompt: "Which catalog page?", choices: [] },
+ {
+ part_id: "p2",
+ prompt: "Which fields?",
+ choices: ["Name", "Price"],
+ },
+ ]}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ // Answer everything the card lets the user answer.
+ fireEvent.change(screen.getByLabelText("Which catalog page?"), {
+ target: { value: "the catalog page" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Name" }));
+
+ const card = screen.getByRole("group", { name: "Question parts" });
+ const counter = card.textContent?.match(/(\d+) of (\d+) answered/);
+ expect(counter).not.toBeNull();
+ expect(counter![1]).toBe(counter![2]);
+ });
+
+ // REPRO 2 (MINOR): answer attribution is keyed on prompt TEXT, not on the
+ // server-minted part_id. Two parts whose prompts collide are both marked
+ // answered when only one was, and `settled` then freezes the whole card.
+ it("attributes an answer to the part that was answered, not to its twin", () => {
+ render(
+ <QuestionPartsCard
+ parts={[
+ { part_id: "p1", prompt: "Which day?", choices: ["Monday"] },
+ {
+ part_id: "p2",
+ prompt: "Which day?",
+ choices: ["Monday", "Friday"],
+ },
+ ]}
+ answeredFrom={questionAnswerLine("Which day?", "Monday")}
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ const pressed = screen
+ .getAllByRole("button")
+ .filter((b) => b.getAttribute("aria-pressed") === "true");
+ expect(pressed).toHaveLength(1);
+ });
+
+ // REPRO 3 (MINOR): a choice label carrying a newline is admitted by the
+ // server but breaks the client's line-based answer protocol: the sent
+ // message splits across lines, so the answered state can never be read back.
+ it("keeps a multi-line choice legible after it is answered", () => {
+ const choice = "Line one\nLine two";
+ render(
+ <QuestionPartsCard
+ parts={[{ part_id: "p1", prompt: "Pick", choices: [choice] }]}
+ answeredFrom={questionAnswerLine("Pick", choice)}
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ expect(
+ screen
+ .getByRole("button", { name: /Line one/ })
+ .getAttribute("aria-pressed"),
+ ).toBe("true");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.test.tsx
index 4375a1dc2..b823dbdb1 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.test.tsx
@@ -11,18 +11,32 @@ afterEach(() => {
cleanup();
});
-const parts = [
+const mixed = [
{ part_id: "p1", prompt: "Which store?", choices: ["Acme", "Borough"] },
{ part_id: "p2", prompt: "Which email gets the receipt?", choices: [] },
{ part_id: "p3", prompt: "Which day?", choices: ["Monday", "Friday"] },
];
+// 86% of live asks. Never constructed in a test before SKY-15619, which is why SKY-15616 shipped.
+const allChoiceless = [
+ { part_id: "p1", prompt: "Which store?", choices: [] },
+ { part_id: "p2", prompt: "Which email gets the receipt?", choices: [] },
+];
+
+const counterOf = () =>
+ screen
+ .getByRole("group", { name: "Question parts" })
+ .textContent?.match(/(\d+) of (\d+) answered/);
+
+const fieldFor = (prompt: string) =>
+ screen.getByLabelText(prompt) as HTMLInputElement;
+
describe("QuestionPartsCard", () => {
it("sends only the parts the user actually answered", () => {
const onAnswer = vi.fn();
render(
<QuestionPartsCard
- parts={parts}
+ parts={mixed}
answeredFrom={null}
disabled={false}
onAnswer={onAnswer}
@@ -35,17 +49,113 @@ describe("QuestionPartsCard", () => {
expect(onAnswer).toHaveBeenCalledWith(
questionAnswerLine("Which store?", "Borough"),
);
- // A part whose answer is a value only the user holds still shows, so the
- // card never presents a compound ask as though it were a single question.
- expect(
- screen.getByText("Type your answer in the message box."),
- ).toBeTruthy();
});
- it("reads the answered part back off the sent message after a reload", () => {
+ it("gives every choice-less part a field of its own", () => {
+ render(
+ <QuestionPartsCard
+ parts={allChoiceless}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ expect(fieldFor("Which store?")).toBeTruthy();
+ expect(fieldFor("Which email gets the receipt?")).toBeTruthy();
+ });
+
+ // The counter has to be reachable in every shape the model actually produces, or it is telling
+ // the user about work they cannot do. Pins the second half of SKY-15616.
+ it.each([
+ ["all choice-less", allChoiceless],
+ ["mixed", mixed],
+ ["single", [{ part_id: "p1", prompt: "Which store?", choices: [] }]],
+ ])("lets the counter reach its denominator: %s", (_name, parts) => {
render(
<QuestionPartsCard
parts={parts}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ for (const part of parts) {
+ if (part.choices.length) {
+ fireEvent.click(
+ screen.getByRole("button", { name: part.choices[0] as string }),
+ );
+ } else {
+ fireEvent.change(fieldFor(part.prompt), {
+ target: { value: "an answer" },
+ });
+ }
+ }
+
+ const counter = counterOf();
+ expect(counter).not.toBeNull();
+ expect(counter![1]).toBe(String(parts.length));
+ expect(counter![1]).toBe(counter![2]);
+ });
+
+ it("sends what is filled when Enter is pressed in a field", () => {
+ const onAnswer = vi.fn();
+ render(
+ <QuestionPartsCard
+ parts={allChoiceless}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={onAnswer}
+ />,
+ );
+
+ fireEvent.change(fieldFor("Which store?"), {
+ target: { value: "acme.example" },
+ });
+ fireEvent.keyDown(fieldFor("Which store?"), { key: "Enter" });
+
+ expect(onAnswer).toHaveBeenCalledWith(
+ questionAnswerLine("Which store?", "acme.example"),
+ );
+ });
+
+ it("reads a free-form answer back off the label the card itself emitted", () => {
+ render(
+ <QuestionPartsCard
+ parts={allChoiceless}
+ answeredFrom={questionAnswerLine("Which store?", "acme.example")}
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText("acme.example")).toBeTruthy();
+ // The unanswered part keeps its prompt but no longer offers a live field.
+ expect(screen.queryByRole("button", { name: "Send" })).toBeNull();
+ });
+
+ it("shows no per-part receipt when the answer came through the composer", () => {
+ render(
+ <QuestionPartsCard
+ parts={allChoiceless}
+ answeredFrom="it's acme, and send it to me"
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ // Nothing matched the card's own labels, so the chat bubble is the receipt and the card is
+ // read-only rather than claiming an answer it cannot attribute.
+ expect(screen.queryByText("it's acme, and send it to me")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Send" })).toBeNull();
+ expect(screen.queryByRole("textbox")).toBeNull();
+ });
+
+ it("reads the answered part back off the sent message after a reload", () => {
+ render(
+ <QuestionPartsCard
+ parts={mixed}
answeredFrom={questionAnswerLine("Which day?", "Friday")}
disabled
onAnswer={vi.fn()}
@@ -64,6 +174,282 @@ describe("QuestionPartsCard", () => {
).toBe("false");
expect(screen.queryByRole("button", { name: "Send" })).toBeNull();
});
+
+ // QA's twin+gap probe: two parts share a prompt and the user fills only the SECOND. One line
+ // is emitted, and a claim-once-in-order receipt would hand it to the first twin — marking a
+ // part the user never answered and blanking the one they did. Twins are rare; a blank field
+ // beside a filled one is ordinary under D2, so the gap half is common.
+ it("lands a twin's receipt on the part the user actually filled", () => {
+ const twins = [
+ { part_id: "p1", prompt: "Which day?", choices: [] },
+ { part_id: "p2", prompt: "Which day?", choices: [] },
+ ];
+ const onAnswer = vi.fn();
+ const live = render(
+ <QuestionPartsCard
+ parts={twins}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={onAnswer}
+ />,
+ );
+
+ // Only the second twin is filled.
+ fireEvent.change(screen.getAllByRole("textbox")[1] as HTMLInputElement, {
+ target: { value: "Friday" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+ const sent = onAnswer.mock.calls[0]![0] as string;
+ live.unmount();
+
+ render(
+ <QuestionPartsCard
+ parts={twins}
+ answeredFrom={sent}
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ const rows = screen
+ .getByRole("group", { name: "Question parts" })
+ .querySelectorAll(":scope > div > div");
+ expect(rows[0]?.textContent).not.toContain("Friday");
+ expect(rows[1]?.textContent).toContain("Friday");
+ });
+
+ // Under D2 the user types the transport text, so a multi-line paste must not put a newline
+ // into the emitted line — one answer would split across two and be unreadable on reload.
+ it("keeps a multi-line paste on one emitted line, and reads it back", () => {
+ const parts = [{ part_id: "p1", prompt: "Which store?", choices: [] }];
+ const onAnswer = vi.fn();
+ const live = render(
+ <QuestionPartsCard
+ parts={parts}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={onAnswer}
+ />,
+ );
+
+ fireEvent.change(fieldFor("Which store?"), {
+ target: { value: "acme.example\nsecond line" },
+ });
+ // The single-line Input drops the newline on the way in, which is the browser behaviour this
+ // pins rather than assumes. Whatever it kept is what must round-trip.
+ const held = fieldFor("Which store?").value;
+ expect(held).not.toContain("\n");
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+
+ const sent = onAnswer.mock.calls[0]![0] as string;
+ expect(sent).not.toContain("\n");
+ expect(sent).toBe(`Which store? — ${held}`);
+ live.unmount();
+
+ render(
+ <QuestionPartsCard
+ parts={parts}
+ answeredFrom={sent}
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+ expect(screen.getByText(held)).toBeTruthy();
+ });
+
+ // Backward compatibility: a chat written before twins were disambiguated carries the plain
+ // "<prompt> — <answer>" format. Those receipts must still resolve, or every stored chat
+ // silently loses its answered state on the deploy that ships the suffix.
+ it("still reads back a receipt written in the pre-suffix plain format", () => {
+ render(
+ <QuestionPartsCard
+ parts={[{ part_id: "p1", prompt: "Which store?", choices: [] }]}
+ answeredFrom="Which store? — acme.example"
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText("acme.example")).toBeTruthy();
+ });
+
+ // Enter while an IME is composing commits the candidate; sending there would ship a half-typed
+ // answer the user never confirmed.
+ it("does not send on the Enter that commits an IME candidate", () => {
+ const onAnswer = vi.fn();
+ render(
+ <QuestionPartsCard
+ parts={allChoiceless}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={onAnswer}
+ />,
+ );
+
+ fireEvent.change(fieldFor("Which store?"), { target: { value: "アク" } });
+ fireEvent.keyDown(fieldFor("Which store?"), {
+ key: "Enter",
+ isComposing: true,
+ });
+ expect(onAnswer).not.toHaveBeenCalled();
+
+ // The Enter that follows the commit is a real send.
+ fireEvent.keyDown(fieldFor("Which store?"), { key: "Enter" });
+ expect(onAnswer).toHaveBeenCalledTimes(1);
+ });
+
+ // The prompt and the choices are model-authored, and this branch's admission still lets a
+ // newline through either, so the whole emitted line is normalised — not just the typed value.
+ // Round-tripped through a real click/send rather than a prebuilt answeredFrom string.
+ it.each([
+ [
+ "a multi-line prompt",
+ [{ part_id: "p1", prompt: "Which\nstore?", choices: [] }],
+ "acme.example",
+ ],
+ [
+ "a multi-line choice",
+ [
+ {
+ part_id: "p1",
+ prompt: "Which store?",
+ choices: ["Acme\nSupply", "Borough"],
+ },
+ ],
+ "Acme\nSupply",
+ ],
+ ])(
+ "emits one protocol line for %s, and reads it back",
+ (_name, parts, answer) => {
+ const onAnswer = vi.fn();
+ const choiced = parts[0]!.choices.length > 0;
+ const live = render(
+ <QuestionPartsCard
+ parts={parts}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={onAnswer}
+ />,
+ );
+
+ if (choiced) {
+ fireEvent.click(screen.getByRole("button", { name: /Acme/ }));
+ } else {
+ fireEvent.change(screen.getByRole("textbox"), {
+ target: { value: answer },
+ });
+ }
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+
+ const sent = onAnswer.mock.calls[0]![0] as string;
+ expect(sent).not.toContain("\n");
+ live.unmount();
+
+ render(
+ <QuestionPartsCard
+ parts={parts}
+ answeredFrom={sent}
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ // The part reads back as answered rather than reverting to unanswered.
+ if (choiced) {
+ expect(
+ screen
+ .getByRole("button", { name: /Acme/ })
+ .getAttribute("aria-pressed"),
+ ).toBe("true");
+ } else {
+ expect(screen.getByText(answer)).toBeTruthy();
+ expect(screen.queryByRole("textbox")).toBeNull();
+ }
+ },
+ );
+
+ // The emitted line is whitespace-normalised, and that is lossy: these two prompts are different
+ // raw strings that would otherwise persist the same prefix, so answering the second would reload
+ // onto the first. Round-tripped through a real send.
+ it("keeps prompts that differ only by whitespace on their own rows after reload", () => {
+ const parts = [
+ { part_id: "p1", prompt: "Which\nstore?", choices: [] },
+ { part_id: "p2", prompt: "Which store?", choices: [] },
+ ];
+ const onAnswer = vi.fn();
+ const live = render(
+ <QuestionPartsCard
+ parts={parts}
+ answeredFrom={null}
+ disabled={false}
+ onAnswer={onAnswer}
+ />,
+ );
+
+ // Only the SECOND is filled.
+ fireEvent.change(screen.getAllByRole("textbox")[1] as HTMLInputElement, {
+ target: { value: "acme.example" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+ const sent = onAnswer.mock.calls[0]![0] as string;
+ live.unmount();
+
+ render(
+ <QuestionPartsCard
+ parts={parts}
+ answeredFrom={sent}
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ const rows = screen
+ .getByRole("group", { name: "Question parts" })
+ .querySelectorAll(":scope > div > div");
+ expect(rows[0]?.textContent).not.toContain("acme.example");
+ expect(rows[1]?.textContent).toContain("acme.example");
+ });
+
+ // SKY-15619 mutation L: `disabled={disabled || settled}` -> `disabled={false}` on the choice
+ // buttons left the suite green, because the reload test above asserts aria-pressed and the
+ // absence of Send but never that the controls are inert. A historical card that stayed
+ // clickable would have shipped.
+ it("mutation L: a historical card's controls are inert", () => {
+ render(
+ <QuestionPartsCard
+ parts={mixed}
+ answeredFrom={questionAnswerLine("Which day?", "Friday")}
+ disabled
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ for (const button of screen.getAllByRole("button")) {
+ expect((button as HTMLButtonElement).disabled).toBe(true);
+ }
+ // No live field either: a read-only card renders none rather than a disabled empty box.
+ expect(screen.queryByRole("textbox")).toBeNull();
+ });
+
+ // SKY-15619 mutation N: `settled` -> `false` left the suite green, because no test rendered a
+ // LIVE card that already carries an answer. Without the collapse, an answered question keeps
+ // offering to answer itself again.
+ it("mutation N: a live card that already carries an answer stops offering to answer again", () => {
+ render(
+ <QuestionPartsCard
+ parts={mixed}
+ answeredFrom={questionAnswerLine("Which day?", "Friday")}
+ disabled={false}
+ onAnswer={vi.fn()}
+ />,
+ );
+
+ expect(screen.queryByRole("button", { name: "Send" })).toBeNull();
+ expect(screen.queryByRole("textbox")).toBeNull();
+ expect(
+ screen.getByRole("button", { name: "Monday" }).hasAttribute("disabled"),
+ ).toBe(true);
+ });
});
describe("parseTerminalEnvelope question parts", () => {
@@ -83,6 +469,26 @@ describe("parseTerminalEnvelope question parts", () => {
]);
});
+ // The claim-once receipt matches emitted labels against the parts it was handed, so it assumes
+ // the rendered list IS the admitted list. parseQuestionParts drops entries with a non-string
+ // part_id or prompt; if it ever silently shortened the list, answers would land on the wrong
+ // rows. Pins that invariant on an envelope shaped exactly as the server admits.
+ it("renders every part the server admitted, in order", () => {
+ const admitted = [
+ { part_id: "p1", prompt: "Which store?", choices: [] },
+ { part_id: "p2", prompt: "Which items?", choices: ["Recent", "Saved"] },
+ { part_id: "p3", prompt: "Which email?", choices: [] },
+ ];
+
+ const parsed = parseTerminalEnvelope({
+ next_state: "awaiting_user_input",
+ rendered_from_envelope: true,
+ question_parts: admitted,
+ })?.questionParts;
+
+ expect(parsed).toEqual(admitted);
+ });
+
it("is empty on an envelope that carries no parts", () => {
expect(
parseTerminalEnvelope({ next_state: "stopped" })?.questionParts,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.tsx
index 8abdbbf58..75d66096f 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.tsx
@@ -1,14 +1,164 @@
import { CheckIcon, QuestionMarkCircledIcon } from "@radix-ui/react-icons";
-import { useState } from "react";
+import { useId, useState } from "react";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
import type { QuestionPart } from "../workflowCopilotTypes";
-import { questionAnswerLine } from "./questionAnswerLine";
+import {
+ emissionPrompts,
+ questionAnswerLabel,
+ questionAnswerLine,
+} from "./questionAnswerLine";
+
+// Whitespace-insensitive comparison. The answer protocol is line-based, so a label carrying a
+// newline would split across lines in the sent message and never match itself back. The server
+// still admits one today (SKY-15617/15618 follow-up), so the card absorbs it here rather than
+// dropping an answer the user actually gave.
+const flatten = (value: string) => value.replace(/\s+/g, " ").trim();
+
+type PartAnswer = { text: string; fromChoice: boolean };
+
+// Which parts a previous message already answered, read off the card's OWN emitted label rather
+// than off the user's words. Each label is claimed by at most one part, so two parts sharing a
+// prompt cannot both take credit for one answer.
+function resolveAnswers(
+ parts: QuestionPart[],
+ labels: string[],
+ answeredFrom: string | null,
+): Record<string, PartAnswer> {
+ const message = answeredFrom ?? "";
+ if (!message.trim()) return {};
+ const flatMessage = flatten(message);
+ const lines = message.split("\n");
+ // Claim by line POSITION, not by text: two parts that share a prompt can be answered with the
+ // same words, and a text-keyed claim would let the first one swallow both lines and leave its
+ // twin looking unanswered.
+ const takenLines = new Set<number>();
+ const takenSpans = new Set<string>();
+ const answers: Record<string, PartAnswer> = {};
+
+ const takeLine = (matches: (flat: string) => boolean): number | null => {
+ for (let index = 0; index < lines.length; index += 1) {
+ if (takenLines.has(index)) continue;
+ if (matches(flatten(lines[index] ?? ""))) {
+ takenLines.add(index);
+ return index;
+ }
+ }
+ return null;
+ };
+
+ for (const [position, part] of parts.entries()) {
+ // The emitted prompt first, then the plain one: a chat written before twins were
+ // disambiguated still carries plain labels and must not orphan its receipts.
+ const prompts = [labels[position] ?? part.prompt, part.prompt];
+ const choiceOnItsOwnLine = part.choices.find((candidate) =>
+ prompts.some(
+ (prompt) =>
+ takeLine(
+ (flat) => flat === flatten(questionAnswerLine(prompt, candidate)),
+ ) !== null,
+ ),
+ );
+ if (choiceOnItsOwnLine !== undefined) {
+ answers[part.part_id] = { text: choiceOnItsOwnLine, fromChoice: true };
+ continue;
+ }
+ // A label that itself carries a newline spans lines, so it can only be found in the whole
+ // message. Gated on the label actually containing one: without that gate this fallback
+ // bypasses the positional claim above and lets a twin re-claim its sibling's answer.
+ const spanning = part.choices.find((candidate) => {
+ if (!questionAnswerLine(part.prompt, candidate).includes("\n"))
+ return false;
+ const label = flatten(questionAnswerLine(part.prompt, candidate));
+ return !takenSpans.has(label) && flatMessage.includes(label);
+ });
+ if (spanning !== undefined) {
+ takenSpans.add(flatten(questionAnswerLine(part.prompt, spanning)));
+ answers[part.part_id] = { text: spanning, fromChoice: true };
+ continue;
+ }
+ // Free-form receipt belongs only to a part that HAS no choices. A choiced part answered in
+ // prose through the composer gets no per-part receipt — its bubble is the receipt — and
+ // reading one here would settle the card off text it cannot show.
+ if (part.choices.length > 0) continue;
+ // The card emitted "<prompt> — ", so whatever follows that prefix on the first unclaimed
+ // line carrying it is what the user sent for this part.
+ for (const prompt of prompts) {
+ const prefix = flatten(questionAnswerLabel(prompt));
+ const index = takeLine(
+ (flat) => flat.startsWith(prefix) && flat.length > prefix.length,
+ );
+ if (index !== null) {
+ answers[part.part_id] = {
+ text: flatten(lines[index] ?? "")
+ .slice(prefix.length)
+ .trim(),
+ fromChoice: false,
+ };
+ break;
+ }
+ }
+ }
+ return answers;
+}
+
+// One choice-less part's answer slot: the recorded answer, or a field, or — on a read-only card —
+// nothing at all. A read-only card renders no empty disabled box: that is exactly the affordance
+// which cannot be used, which is the whole of SKY-15616. The prompt alone still says what was asked.
+function FreeFormAnswer({
+ inputId,
+ answered,
+ readOnly,
+ value,
+ onChange,
+ onSubmit,
+}: {
+ inputId: string;
+ answered: string | null;
+ readOnly: boolean;
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit: () => void;
+}) {
+ if (answered !== null) {
+ return (
+ <span className="flex items-center gap-1.5 text-[13px] text-foreground">
+ <CheckIcon
+ className="size-3.5 flex-none text-success"
+ aria-hidden="true"
+ />
+ {answered}
+ </span>
+ );
+ }
+ if (readOnly) return null;
+ return (
+ <Input
+ id={inputId}
+ // ponytail: the DS Input has no compact size, so the scale is matched by hand to the
+ // chips beside it. The honest fix is a size="sm" variant.
+ className="h-7 px-2 text-[12px]"
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ onKeyDown={(event) => {
+ // Enter while an IME is composing accepts the candidate; swallowing it here would
+ // send a half-typed answer. Same guard the composer's handleKeyPress uses.
+ if (event.nativeEvent.isComposing) return;
+ if (event.key === "Enter") {
+ event.preventDefault();
+ onSubmit();
+ }
+ }}
+ />
+ );
+}
type QuestionPartsCardProps = {
parts: QuestionPart[];
- // The message that followed this question, when one exists. Its lines are the
- // record of which parts were answered.
+ // The message that followed this question, when one exists. Its lines are the record of which
+ // parts were answered. A user who answered in the composer instead matches nothing here, and
+ // their own chat bubble is the receipt.
answeredFrom: string | null;
disabled: boolean;
onAnswer: (message: string) => void;
@@ -20,25 +170,33 @@ export function QuestionPartsCard({
disabled,
onAnswer,
}: QuestionPartsCardProps) {
- const [selected, setSelected] = useState<Record<string, string>>({});
- const answeredLines = new Set(
- (answeredFrom ?? "")
- .split("\n")
- .map((line) => line.trim())
- .filter(Boolean),
- );
- const answerOf = (part: QuestionPart) =>
- part.choices.find((choice) =>
- answeredLines.has(questionAnswerLine(part.prompt, choice)),
- ) ?? null;
- const settled = parts.some((part) => answerOf(part) !== null);
+ const [typed, setTyped] = useState<Record<string, string>>({});
+ const [picked, setPicked] = useState<Record<string, string>>({});
+ const fieldId = useId();
+
+ const labels = emissionPrompts(parts.map((part) => part.prompt));
+ const answers = resolveAnswers(parts, labels, answeredFrom);
+ const settled = Object.keys(answers).length > 0;
+ const readOnly = disabled || settled;
+
const pending = parts
- .map((part) => {
- const choice = selected[part.part_id];
- return choice ? questionAnswerLine(part.prompt, choice) : null;
+ .map((part, position) => {
+ const value = part.choices.length
+ ? picked[part.part_id]
+ : typed[part.part_id]?.trim();
+ // Flatten the WHOLE line, not just the typed value. The prompt and the choices are
+ // model-authored and this branch's admission still lets a newline through either, so any
+ // of the three could otherwise split one answer into two protocol lines.
+ return value
+ ? flatten(questionAnswerLine(labels[position] ?? part.prompt, value))
+ : null;
})
.filter((line): line is string => line !== null);
+ const send = () => {
+ if (pending.length > 0) onAnswer(pending.join("\n"));
+ };
+
return (
<div
className="overflow-hidden rounded-lg border border-border bg-slate-elevation2"
@@ -55,8 +213,10 @@ export function QuestionPartsCard({
</div>
<div className="flex flex-col p-2">
{parts.map((part, index) => {
- const answered = answerOf(part);
- const active = answered ?? selected[part.part_id] ?? null;
+ const answered = answers[part.part_id];
+ const active = answered?.text ?? picked[part.part_id] ?? null;
+ const inputId = `${fieldId}-${part.part_id}`;
+ const freeForm = part.choices.length === 0;
return (
<div
key={part.part_id}
@@ -65,13 +225,26 @@ export function QuestionPartsCard({
index > 0 ? "border-t border-border" : "",
].join(" ")}
>
- <span className="text-[13px] leading-[1.45] text-foreground">
+ <label
+ htmlFor={freeForm ? inputId : undefined}
+ className="text-[13px] leading-[1.45] text-foreground"
+ >
{part.prompt}
- </span>
- {part.choices.length === 0 ? (
- <span className="text-[11px] text-muted-foreground">
- Type your answer in the message box.
- </span>
+ </label>
+ {freeForm ? (
+ <FreeFormAnswer
+ inputId={inputId}
+ answered={answered?.text ?? null}
+ readOnly={readOnly}
+ value={typed[part.part_id] ?? ""}
+ onChange={(value) =>
+ setTyped((current) => ({
+ ...current,
+ [part.part_id]: value,
+ }))
+ }
+ onSubmit={send}
+ />
) : (
<div className="flex flex-wrap gap-1.5">
{part.choices.map((choice) => {
@@ -80,10 +253,10 @@ export function QuestionPartsCard({
<button
key={choice}
type="button"
- disabled={disabled || settled}
+ disabled={readOnly}
aria-pressed={isActive}
onClick={() =>
- setSelected((current) => ({
+ setPicked((current) => ({
...current,
[part.part_id]: choice,
}))
@@ -112,7 +285,7 @@ export function QuestionPartsCard({
);
})}
</div>
- {settled || disabled ? null : (
+ {readOnly ? null : (
<div className="flex items-center justify-between gap-2 border-t border-border px-3 py-2">
<span className="text-[11px] text-muted-foreground">
{pending.length} of {parts.length} answered
@@ -121,7 +294,7 @@ export function QuestionPartsCard({
size="sm"
variant="secondary"
disabled={pending.length === 0}
- onClick={() => onAnswer(pending.join("\n"))}
+ onClick={send}
>
Send
</Button>
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswerLine.test.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswerLine.test.ts
new file mode 100644
index 000000000..7d2cd2331
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswerLine.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ emissionPrompts,
+ questionAnswerLabel,
+ questionAnswerLine,
+ twinPrompt,
+} from "./questionAnswerLine";
+
+// Pins SKY-15619 mutation O: the separator was changed from " — " to ": " and the whole copilot
+// suite stayed green, because every other call site computed its expectation by calling this
+// function. The expected values here are LITERALS for that reason — a card rendered today reads
+// the answered state out of a message written weeks ago, so this is a persisted format contract
+// and a test that moves with the code cannot hold it still.
+describe("questionAnswerLine", () => {
+ it("emits the exact persisted wire format", () => {
+ expect(questionAnswerLine("Which day?", "Friday")).toBe(
+ "Which day? — Friday",
+ );
+ expect(questionAnswerLabel("Which day?")).toBe("Which day? — ");
+ });
+
+ it("emits the exact persisted twin format", () => {
+ expect(twinPrompt("Which day?", 2)).toBe("Which day? (2)");
+ expect(questionAnswerLine(twinPrompt("Which day?", 2), "Friday")).toBe(
+ "Which day? (2) — Friday",
+ );
+ });
+});
+
+describe("emissionPrompts", () => {
+ it("leaves a unique prompt plain, so no existing chat changes shape", () => {
+ expect(emissionPrompts(["Which day?", "Which store?"])).toEqual([
+ "Which day?",
+ "Which store?",
+ ]);
+ });
+
+ it("keeps the first occurrence plain and numbers the repeats", () => {
+ expect(
+ emissionPrompts(["Which day?", "Which store?", "Which day?"]),
+ ).toEqual(["Which day?", "Which store?", "Which day? (2)"]);
+ });
+
+ // The emitted line is whitespace-normalized, and that is lossy. These two prompts are different
+ // raw strings that would persist the SAME prefix, so uniqueness has to be enforced in normalized
+ // space or answering the second reloads onto the first.
+ it("separates prompts that differ only by whitespace", () => {
+ const labels = emissionPrompts(["Which\nstore?", "Which store?"]);
+ const normalized = labels.map((l) => l.replace(/\s+/g, " ").trim());
+
+ expect(new Set(normalized).size).toBe(2);
+ expect(normalized[1]).toBe("Which store? (2)");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswerLine.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswerLine.ts
index b112fc278..2308c2332 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswerLine.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswerLine.ts
@@ -1,7 +1,46 @@
-// The line one answered part contributes to the reply. Its own file so the card
-// stays component-only (Fast Refresh), matching connectedAccountChoiceLabel.ts.
-// Exported because the answered state a reloaded chat shows is read back off the
-// sent message rather than from component state the reload threw away.
-export function questionAnswerLine(prompt: string, choice: string): string {
- return `${prompt} — ${choice}`;
+// The wire format the card answers in. This is a PERSISTED contract, not an internal detail: a
+// card rendered today reads the answered state back out of a message written weeks ago, so
+// changing any of it silently orphans the answered state of every chat already stored.
+// `questionAnswerLine.test.ts` pins these as LITERAL strings for that reason — assert the text,
+// never a second call to these functions.
+const ANSWER_SEPARATOR = " — ";
+
+// The prefix the card emits before an answer. Matching on this, rather than on the user's words,
+// is what keeps the reload receipt reading the card's own output.
+export function questionAnswerLabel(prompt: string): string {
+ return `${prompt}${ANSWER_SEPARATOR}`;
+}
+
+export function questionAnswerLine(prompt: string, answer: string): string {
+ return `${questionAnswerLabel(prompt)}${answer}`;
+}
+
+// Two parts may carry the same prompt, and the emitted line is all a reloaded card has to go on:
+// one line reading "Which day? — Friday" cannot say which twin the user answered. So a repeat
+// occurrence takes an ordinal and matches its own label.
+export function twinPrompt(prompt: string, ordinal: number): string {
+ return `${prompt} (${ordinal})`;
+}
+
+// Uniqueness has to hold in the space the line is actually WRITTEN in. The emitted line is
+// whitespace-normalized, and that is lossy: "Which\nstore?" and "Which store?" are different
+// prompts that would persist the same prefix, so answering the second would reload onto the
+// first. Labels are therefore reserved by their normalized form, not their raw one.
+const normalizeLabel = (value: string) => value.replace(/\s+/g, " ").trim();
+
+// The prompt each part emits and matches on, in card order. The FIRST occurrence keeps the plain
+// prompt — so a message written before ordinals existed still resolves to it — and only later
+// collisions are suffixed.
+export function emissionPrompts(prompts: string[]): string[] {
+ const taken = new Set<string>();
+ return prompts.map((prompt) => {
+ let label = prompt;
+ let ordinal = 1;
+ while (taken.has(normalizeLabel(label))) {
+ ordinal += 1;
+ label = twinPrompt(prompt, ordinal);
+ }
+ taken.add(normalizeLabel(label));
+ return label;
+ });
}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.test.ts b/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.test.ts
new file mode 100644
index 000000000..4a1aebf84
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+
+import { composerPlaceholder } from "./composerPlaceholder";
+
+const base = {
+ queuedPrompt: false,
+ isLoading: false,
+ isWaitingForLiveBrowser: false,
+ latestTurnIsAsk: false,
+ copilotV2Enabled: true,
+};
+
+describe("composerPlaceholder", () => {
+ it("invites an answer while the latest turn is an ask", () => {
+ expect(composerPlaceholder({ ...base, latestTurnIsAsk: true })).toBe(
+ "Answer Copilot…",
+ );
+ });
+
+ it("returns to the standing invitation once the ask is answered", () => {
+ expect(composerPlaceholder(base)).toBe(
+ "Ask Copilot to build or change your workflow…",
+ );
+ });
+
+ it("lets an in-flight turn outrank the ask state", () => {
+ expect(
+ composerPlaceholder({ ...base, latestTurnIsAsk: true, isLoading: true }),
+ ).toBe("Type to queue a message…");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.ts b/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.ts
new file mode 100644
index 000000000..769ebd9f1
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.ts
@@ -0,0 +1,25 @@
+// The composer's placeholder, as a pure decision so the ask branch is testable without mounting
+// the whole chat. Order is precedence: transient states outrank the standing invitation.
+export function composerPlaceholder({
+ queuedPrompt,
+ isLoading,
+ isWaitingForLiveBrowser,
+ latestTurnIsAsk,
+ copilotV2Enabled,
+}: {
+ queuedPrompt: boolean;
+ isLoading: boolean;
+ isWaitingForLiveBrowser: boolean;
+ latestTurnIsAsk: boolean;
+ copilotV2Enabled: boolean;
+}): string {
+ if (queuedPrompt) return "Type to replace the queued message…";
+ if (isLoading) return "Type to queue a message…";
+ if (isWaitingForLiveBrowser) return "Type a prompt to send when ready...";
+ // While a question is pending the composer is the answer path for anything the card cannot
+ // take, so it says so rather than inviting an unrelated new request.
+ if (latestTurnIsAsk) return "Answer Copilot…";
+ return copilotV2Enabled
+ ? "Ask Copilot to build or change your workflow…"
+ : "Message Skyvern Copilot, or paste recorded steps…";
+}