Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Render formatted Copilot responses consistently (SKY-15250) (#8330)
Andrew Neilson644b9461a19c
diff --git a/skyvern-frontend/src/routes/workflows/copilot/CopilotMarkdown.tsx b/skyvern-frontend/src/routes/workflows/copilot/CopilotMarkdown.tsxnew file mode 100644index 000000000..c9fc67724--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/CopilotMarkdown.tsx@@ -0,0 +1,117 @@+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";++interface MarkdownTreeNode {+ type: string;+ value?: string;+ tagName?: string;+ properties?: Record<string, unknown>;+ children?: MarkdownTreeNode[];+}++export interface CopilotMarkdownReveal {+ shown: number;+ gradientStart: number;+ onCharacterCount: (count: number) => void;+}++function markdownRevealPlugin(reveal: CopilotMarkdownReveal) {+ return () => (tree: MarkdownTreeNode) => {+ let offset = 0;+ let lastGradientNode: MarkdownTreeNode | null = null;++ const revealChildren = (node: MarkdownTreeNode) => {+ if (!node.children) return;+ const visibleChildren: MarkdownTreeNode[] = [];++ for (const child of node.children) {+ if (child.type !== "text") {+ const offsetBeforeChild = offset;+ revealChildren(child);+ if (+ (child.children && child.children.length > 0) ||+ (!child.children && offsetBeforeChild < reveal.shown)+ ) {+ visibleChildren.push(child);+ }+ continue;+ }++ const value = child.value ?? "";+ const start = offset;+ offset += value.length;+ const visibleLength = Math.min(+ value.length,+ Math.max(0, reveal.shown - start),+ );+ if (visibleLength === 0) continue;++ const stableLength = Math.min(+ visibleLength,+ Math.max(0, reveal.gradientStart - start),+ );+ if (stableLength > 0) {+ visibleChildren.push({+ type: "text",+ value: value.slice(0, stableLength),+ });+ }++ const gradientLength = visibleLength - stableLength;+ for (let i = 0; i < gradientLength; i += 1) {+ const characterOffset = start + stableLength + i;+ const progress =+ (characterOffset - reveal.gradientStart + 1) /+ Math.max(1, reveal.shown - reveal.gradientStart);+ const opacity = Math.max(0.12, 1 - progress * 0.88);+ const gradientNode: MarkdownTreeNode = {+ type: "element",+ tagName: "span",+ properties: { style: `opacity: ${opacity.toFixed(2)}` },+ children: [+ {+ type: "text",+ value: value[stableLength + i],+ },+ ],+ };+ visibleChildren.push(gradientNode);+ lastGradientNode = gradientNode;+ }+ }++ node.children = visibleChildren;+ };++ revealChildren(tree);+ const gradientEdge = lastGradientNode as MarkdownTreeNode | null;+ if (gradientEdge) {+ gradientEdge.properties = {+ ...gradientEdge.properties,+ "data-testid": "copilot-terminal-prose-gradient",+ };+ }+ reveal.onCharacterCount(offset);+ };+}++export function CopilotMarkdown({+ text,+ reveal,+}: {+ text: string;+ reveal?: CopilotMarkdownReveal;+}) {+ return (+ <div className="whitespace-normal [&_a]:underline [&_a]:underline-offset-2 [&_code]:rounded [&_code]:bg-slate-500/15 [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.92em] [&_li+li]:mt-1 [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:pl-5 [&_p+p]:mt-3 [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:whitespace-pre-wrap [&_pre]:rounded-md [&_pre]:bg-slate-500/15 [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:pl-5">+ <ReactMarkdown+ remarkPlugins={[remarkGfm]}+ rehypePlugins={reveal ? [markdownRevealPlugin(reveal)] : undefined}+ components={{ img: () => null }}+ skipHtml+ >+ {text}+ </ReactMarkdown>+ </div>+ );+}diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsxindex 4206facd9..b227be107 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx@@ -151,7 +151,7 @@ const repairLoopTurn = (): TurnNarrativeState => ({});describe("NarrativeView — activity log", () => {- it("the rollup renders the flat activity rows and drops the phase rail", () => {+ it("renders flat activity rows and drops the phase rail", () => {render(<NarrativeView turn={repairLoopTurn()} />);expect(screen.queryByText("Explore site")).toBeNull();expect(screen.queryByText("Draft code")).toBeNull();@@ -160,29 +160,6 @@ describe("NarrativeView — activity log", () => {expect(screen.getByText("Saved 2 blocks")).toBeTruthy();});- it("moves focus between the terminal rollup and detail disclosures", async () => {- render(<NarrativeView turn={repairLoopTurn()} />);- const rollup = screen.getByRole("button", {- name: /Built the workflow/,- });- expect(rollup.getAttribute("aria-expanded")).toBe("false");- expect(rollup.hasAttribute("aria-controls")).toBe(false);- fireEvent.click(rollup);-- const collapse = screen.getByRole("button", { name: "Collapse turn" });- expect(collapse.getAttribute("aria-expanded")).toBe("true");- expect(- document.getElementById(collapse.getAttribute("aria-controls")!),- ).toBeTruthy();- await waitFor(() => expect(document.activeElement).toBe(collapse));-- fireEvent.click(collapse);- const restored = screen.getByRole("button", {- name: /Built the workflow/,- });- await waitFor(() => expect(document.activeElement).toBe(restored));- });-it("a failed run keeps the server's reason instead of a generic tool label", () => {render(<NarrativeView turn={repairLoopTurn()} />);expect(@@ -209,7 +186,7 @@ describe("NarrativeView — activity log", () => {]);});- it("the rollup gutter reads the row kinds in happened-order", () => {+ it("the terminal gutter reads the row kinds in happened-order", () => {render(<NarrativeView turn={repairLoopTurn()} />);const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);expect(gutter.map((g) => g.textContent)).toEqual(["◎", "▷", "⟨⟩"]);diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsxdeleted file mode 100644index e081a110a..000000000--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx+++ /dev/null@@ -1,618 +0,0 @@-// @vitest-environment jsdom--import {- cleanup,- fireEvent,- render,- screen,- within,-} from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";--import { NarrativeView } from "./NarrativeView";-import {- BlockState,- EMPTY_NARRATIVE,- TurnNarrativeState,- hydrateNarrativeFromPayload,-} from "./narrativeState";--const completedBlock = (- label: string,- workflowRunBlockId = `wrb_${label}`,-): BlockState => ({- workflowRunBlockId,- label,- blockType: "navigation",- state: "completed",- lastSeenIteration: 1,- activity: [],- startedAt: "2026-05-30T00:00:00Z",- endedAt: "2026-05-30T00:00:10Z",-});--const failedBlock = (- label: string,- workflowRunBlockId = `wrb_failed_${label}`,-): BlockState => ({- ...completedBlock(label, workflowRunBlockId),- state: "failed",-});--const terminalBuildTurn = (): TurnNarrativeState => ({- ...EMPTY_NARRATIVE,- turnId: "turn-1",- turnIndex: 0,- designStarted: true,- designEnded: true,- draft: { blockCount: 1, blockLabels: ["block_1"], summary: null },- blocks: [completedBlock("block_1")],- terminal: "response",- narrativeSummary: "Built it.",- startedAt: "2026-05-30T00:00:00Z",- endedAt: "2026-05-30T00:00:12Z",-});--const inFlightTurn = (): TurnNarrativeState => ({- ...EMPTY_NARRATIVE,- turnId: "turn-2",- turnIndex: 1,- terminal: null,-});--const HEADLINE = "Built the workflow";-const REVIEW_HEADLINE = "Draft needs review";-const REVIEW_TESTED_HEADLINE = "Workflow ready for review";-const LONG_OUTCOME_REASON =- "The verification challenge kept reappearing after submit, and each retry landed back on the same gate instead of the requested destination page.";-const SHORT_OUTCOME_REASON = "A verification challenge prevented confirmation";--const interimRunTurn = (): TurnNarrativeState => ({- ...inFlightTurn(),- blocks: [- {- ...completedBlock("block_1"),- outcome: "not_demonstrated",- outcomeRole: "interim_build_test",- outcomeReason: SHORT_OUTCOME_REASON,- },- ],- lastRunOutcome: {- verdict: "not_demonstrated",- role: "interim_build_test",- displayReason: SHORT_OUTCOME_REASON,- },-});--afterEach(() => {- cleanup();-});--describe("NarrativeView collapse default", () => {- it("rolls up a terminal turn to the summary card by default", () => {- render(<NarrativeView turn={terminalBuildTurn()} />);-- expect(screen.getByText(HEADLINE)).toBeTruthy();- expect(- screen- .getByRole("button", { name: new RegExp(HEADLINE) })- .getAttribute("aria-expanded"),- ).toBe("false");- });-- it("does not present an unverified review proposal as built and tested", () => {- render(- <NarrativeView- turn={{- ...terminalBuildTurn(),- proposalDisposition: "review_untested",- terminalMessage:- "I reached the requested browser state, but the reusable workflow still needs a clean verification run before it is ready.",- narrativeSummary:- "I reached the requested browser state, but the reusable workflow still needs a clean verification run before it is ready.",- }}- />,- );-- expect(screen.getByText(REVIEW_HEADLINE)).toBeTruthy();- expect(screen.queryByText(HEADLINE)).toBeNull();- });-- it("does not present a tested review proposal with a success badge", () => {- render(- <NarrativeView- turn={{- ...terminalBuildTurn(),- proposalDisposition: "review_tested",- // One block, run clean on current source — what backs a tested review proposal.- turnFacts: {- factsAvailable: true,- authoredBlockCount: 1,- matchingSourceBlockCount: 1,- evaluationState: null,- runId: "wr_1",- runCompleted: true,- terminalCause: null,- blocksRunThisTurn: 1,- ranCleanOnCurrentSource: true,- },- narrativeSummary: "Workflow ready for review.",- }}- />,- );-- const summaryButton = screen.getByRole("button", {- name: new RegExp(REVIEW_TESTED_HEADLINE),- });- expect(summaryButton.textContent).toContain("!");- expect(summaryButton.textContent).not.toContain("✓");- expect(screen.queryByText(HEADLINE)).toBeNull();- });-- it("keeps the in-flight turn expanded in the detail view", () => {- render(<NarrativeView turn={inFlightTurn()} />);-- expect(screen.queryByText(HEADLINE)).toBeNull();- expect(screen.getByText("Working…")).toBeTruthy();- });-- it("renders an interim completed row as neutral", () => {- render(<NarrativeView turn={interimRunTurn()} />);-- const row = screen.getByTitle("Highlight block_1 on canvas");- expect(row.textContent).toContain("ran");- expect(row.textContent).not.toContain("!");- expect(row.textContent).not.toContain("✓");- expect(screen.queryByText(/Outcome not confirmed/)).toBeNull();- expect(screen.queryByText(SHORT_OUTCOME_REASON)).toBeNull();- });-- it.each([undefined, "adjudicated" as const])(- "keeps role=%s not-demonstrated rows amber",- (outcomeRole) => {- const block: BlockState = {- ...completedBlock("block_1"),- outcome: "not_demonstrated",- outcomeReason: SHORT_OUTCOME_REASON,- ...(outcomeRole ? { outcomeRole } : {}),- };- render(<NarrativeView turn={{ ...inFlightTurn(), blocks: [block] }} />);-- const row = screen.getByTitle("Highlight block_1 on canvas");- expect(row.textContent).toContain("!");- expect(row.textContent).not.toContain("✓");- expect(screen.getByText(/Outcome not confirmed/)).toBeTruthy();- expect(screen.getByText(new RegExp(SHORT_OUTCOME_REASON))).toBeTruthy();- },- );-- it("hydrates an interim outcome into the same neutral row treatment", () => {- const hydrated = hydrateNarrativeFromPayload({- turnId: "turn-hydrated-interim",- turnIndex: 0,- blocks: [- {- ...completedBlock("block_1"),- outcome: "not_demonstrated",- outcomeRole: "interim_build_test",- outcomeReason: SHORT_OUTCOME_REASON,- },- ],- terminal: null,- })!;- render(<NarrativeView turn={hydrated} />);-- const row = screen.getByTitle("Highlight block_1 on canvas");- expect(row.textContent).toContain("ran");- expect(row.textContent).not.toContain("!");- expect(row.textContent).not.toContain("✓");- expect(screen.queryByText(/Outcome not confirmed/)).toBeNull();- expect(screen.queryByText(SHORT_OUTCOME_REASON)).toBeNull();- });-- it("expands via the summary card and re-collapses via the labeled control", () => {- render(<NarrativeView turn={terminalBuildTurn()} />);- const head = () =>- screen.getByRole("button", { name: new RegExp(HEADLINE) });-- expect(head().getAttribute("aria-expanded")).toBe("false");-- fireEvent.click(head());- const collapse = screen.getByRole("button", { name: "Collapse turn" });- expect(screen.queryByText(HEADLINE)).toBeNull();-- fireEvent.click(collapse);- expect(head().getAttribute("aria-expanded")).toBe("false");- });-- it("collapses on the in-flight to terminal transition", () => {- const { rerender } = render(<NarrativeView turn={inFlightTurn()} />);- expect(screen.queryByText(HEADLINE)).toBeNull();-- rerender(<NarrativeView turn={terminalBuildTurn()} />);- expect(screen.getByText(HEADLINE)).toBeTruthy();- });-- it("preserves a user's expand override across re-renders", () => {- const turn = terminalBuildTurn();- const { rerender } = render(<NarrativeView turn={turn} />);-- fireEvent.click(screen.getByRole("button", { name: new RegExp(HEADLINE) }));- expect(screen.getByRole("button", { name: "Collapse turn" })).toBeTruthy();- expect(screen.queryByText(HEADLINE)).toBeNull();-- rerender(<NarrativeView turn={turn} />);- expect(screen.getByRole("button", { name: "Collapse turn" })).toBeTruthy();- expect(screen.queryByText(HEADLINE)).toBeNull();- });-- it("summarizes the latest retry attempt for duplicate block labels", () => {- render(- <NarrativeView- turn={{- ...terminalBuildTurn(),- blocks: [- completedBlock("open_site", "wrb_open_first"),- failedBlock("add_to_cart", "wrb_add_first"),- completedBlock("open_site", "wrb_open_retry"),- completedBlock("add_to_cart", "wrb_add_retry"),- completedBlock("confirm_cart", "wrb_confirm_retry"),- ],- }}- />,- );-- expect(screen.getByText(HEADLINE)).toBeTruthy();- expect(screen.queryByText("Run halted")).toBeNull();- expect(screen.queryByText("Halted")).toBeNull();- const changedSection = screen.getByText("What changed").parentElement!;- expect(within(changedSection).getAllByText("Add To Cart")).toHaveLength(1);- });-- it("appends a truncated not-demonstrated reason to the collapsed subtitle", () => {- render(- <NarrativeView- turn={{- ...terminalBuildTurn(),- lastRunOutcome: {- verdict: "not_demonstrated",- displayReason: LONG_OUTCOME_REASON,- },- }}- />,- );-- const expectedPreview = `${LONG_OUTCOME_REASON.slice(0, 137).trimEnd()}...`;- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.textContent).toContain(- `Outcome not confirmed: ${expectedPreview}`,- );- expect(head.textContent).not.toContain(LONG_OUTCOME_REASON);- });-- it("derives the collapsed subtitle reason from hydrated not-demonstrated block outcomes", () => {- const hydrated = hydrateNarrativeFromPayload({- turnId: "turn-hydrated",- turnIndex: 0,- responseType: "REPLY",- designStarted: true,- designEnded: true,- draft: { blockCount: 1, blockLabels: ["block_1"], summary: null },- blocks: [- {- ...completedBlock("block_1"),- outcome: "not_demonstrated",- outcomeReason: LONG_OUTCOME_REASON,- },- ],- terminal: "response",- terminalMessage: "Built it.",- narrativeSummary: "Built it.",- startedAt: "2026-05-30T00:00:00Z",- endedAt: "2026-05-30T00:00:12Z",- })!;- const expectedPreview = `${LONG_OUTCOME_REASON.slice(0, 137).trimEnd()}...`;- render(<NarrativeView turn={hydrated} />);-- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.textContent).toContain(- `Outcome not confirmed: ${expectedPreview}`,- );- expect(head.textContent).not.toContain(LONG_OUTCOME_REASON);- });-- it("does not append a duplicate not-confirmed reason when closing prose already includes it", () => {- render(- <NarrativeView- turn={{- ...terminalBuildTurn(),- narrativeSummary:- "Could not confirm completion. Reason: a verification challenge prevented confirmation.",- lastRunOutcome: {- verdict: "not_demonstrated",- displayReason: SHORT_OUTCOME_REASON,- },- }}- />,- );-- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.textContent).toContain(- "Reason: a verification challenge prevented confirmation.",- );- expect(head.textContent).not.toContain(- `Outcome not confirmed: ${SHORT_OUTCOME_REASON}`,- );- });-- it("does not append a duplicate when closing prose carries only a truncated preview of the reason", () => {- const truncatedPreview = `${LONG_OUTCOME_REASON.slice(0, 137).trimEnd()}...`;- render(- <NarrativeView- turn={{- ...terminalBuildTurn(),- narrativeSummary: `Could not confirm completion. Reason: ${truncatedPreview}`,- lastRunOutcome: {- verdict: "not_demonstrated",- displayReason: LONG_OUTCOME_REASON,- },- }}- />,- );-- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.textContent).toContain(`Reason: ${truncatedPreview}`);- expect(head.textContent).not.toContain("Outcome not confirmed:");- });-- it("appends not-confirmed reason when closing prose does not include it", () => {- render(- <NarrativeView- turn={{- ...terminalBuildTurn(),- narrativeSummary: "Built it.",- lastRunOutcome: {- verdict: "not_demonstrated",- displayReason: SHORT_OUTCOME_REASON,- },- }}- />,- );-- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.textContent).toContain("Built it.");- expect(head.textContent).toContain(- `Outcome not confirmed: ${SHORT_OUTCOME_REASON}`,- );- });-- it("uses only the not-confirmed segment when there is no closing prose", () => {- render(- <NarrativeView- turn={{- ...terminalBuildTurn(),- narrativeSummary: null,- terminalMessage: null,- lastRunOutcome: {- verdict: "not_demonstrated",- displayReason: SHORT_OUTCOME_REASON,- },- }}- />,- );-- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.textContent).toContain(- `Outcome not confirmed: ${SHORT_OUTCOME_REASON}`,- );- expect(head.textContent).not.toContain("Built it.");- });-- it("does not append a not-demonstrated reason when no verdict signal is present", () => {- render(<NarrativeView turn={terminalBuildTurn()} />);- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.textContent).not.toContain("Outcome not confirmed:");- expect(head.textContent).not.toContain("verification challenge");- });-- it("keeps hydrated turns with neither signal byte-identical to legacy subtitle behavior", () => {- const hydrated = hydrateNarrativeFromPayload({- turnId: "turn-hydrated-legacy",- turnIndex: 0,- responseType: "REPLY",- designStarted: true,- designEnded: true,- draft: { blockCount: 1, blockLabels: ["block_1"], summary: null },- blocks: [{ ...completedBlock("block_1") }],- terminal: "response",- terminalMessage: "Built it.",- narrativeSummary: "Built it.",- startedAt: "2026-05-30T00:00:00Z",- endedAt: "2026-05-30T00:00:12Z",- })!;- render(<NarrativeView turn={hydrated} />);- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.textContent).toContain("Built it.");- expect(head.textContent).not.toContain("Outcome not confirmed:");- });-});--const pureAskTurn = (): TurnNarrativeState => ({- ...EMPTY_NARRATIVE,- turnId: "turn-ask",- turnIndex: 0,- responseType: "ASK_QUESTION",- terminal: "response",- narrativeSummary: "Which login should I use?",-});--const SCOUT_NARRATION = "Checked the login page for SSO options.";--const askAfterScoutingTurn = (): TurnNarrativeState => ({- ...pureAskTurn(),- turnId: "turn-ask-scouted",- designStarted: true,- designActivity: [- { kind: "narration", text: SCOUT_NARRATION, iteration: 0, id: "n-1" },- ],-});--describe("NarrativeView rollup expand affordance", () => {- it("renders a pure needs-input ask as plain, non-expandable prose", () => {- render(<NarrativeView turn={pureAskTurn()} />);-- expect(screen.getByTestId("copilot-terminal-prose")).toBeTruthy();- expect(- screen.getByTestId("copilot-terminal-prose-visual").textContent,- ).toBe("Which login should I use?");- expect(screen.queryByRole("button")).toBeNull();- expect(document.querySelector("[aria-expanded]")).toBeNull();- });-- it("does not box a question just because background scouting was narrated", () => {- render(<NarrativeView turn={askAfterScoutingTurn()} />);-- expect(screen.getByTestId("copilot-terminal-prose")).toBeTruthy();- expect(screen.queryByRole("button")).toBeNull();- expect(screen.queryByText(SCOUT_NARRATION)).toBeNull();- });-- it("still shows the expand chevron for a build turn with blocks", () => {- render(<NarrativeView turn={terminalBuildTurn()} />);-- const head = screen.getByRole("button", { name: new RegExp(HEADLINE) });- expect(head.getAttribute("aria-expanded")).toBe("false");-- fireEvent.click(head);- expect(screen.getByRole("button", { name: "Collapse turn" })).toBeTruthy();- });-- it("makes later block evidence inspectable after a prose-only ask", () => {- const { rerender } = render(<NarrativeView turn={pureAskTurn()} />);- expect(screen.queryByRole("button")).toBeNull();-- rerender(- <NarrativeView- turn={{ ...pureAskTurn(), blocks: [completedBlock("block_1")] }}- />,- );- expect(screen.getByRole("button")).toBeTruthy();- });-});--describe("a stopped block stays inspectable", () => {- const stoppedTurn = (): TurnNarrativeState => ({- ...terminalBuildTurn(),- cancelled: true,- blocks: [- {- ...completedBlock("log_in", "wrb_stopped_log_in"),- state: "stopped",- activity: [- {- kind: "tool_result",- text: "opened the sign-in page",- iteration: 1,- id: "act-1",- success: true,- },- ],- },- ],- });-- // The collapsed rollup is the default view, so a stopped block has to be- // named there too — a failed block gets its own section, and dropping the- // stopped one made it vanish from the summary entirely.- it("names the stopped block in the collapsed rollup", () => {- render(<NarrativeView turn={stoppedTurn()} />);-- const stoppedSection = screen.getByText("Stopped", {- selector: "div",- }).parentElement!;- expect(within(stoppedSection).getByText("Log In")).toBeTruthy();- expect(screen.queryByText("Halted")).toBeNull();- });-- // A non-solo run row keeps its block cards in the collapsed body, so the log- // is not a substitute for the summary list on a finished turn.- it("still names a stopped block on the activity-log surface", () => {- render(<NarrativeView turn={stoppedTurn()} />);-- expect(screen.getByText("Stopped", { selector: "div" })).toBeTruthy();- });-- // A stop is not a failure, so the row must not auto-open and shout — but what- // the block did before the stop still has to be reachable.- it("can be expanded to reveal what ran before the stop", () => {- render(<NarrativeView turn={stoppedTurn()} />);-- fireEvent.click(screen.getByRole("button", { name: /Stopped/ }));-- // Not auto-opened: a stop does not shout the way a failure does.- expect(screen.queryByText("opened the sign-in page")).toBeNull();-- fireEvent.click(screen.getByTitle("Highlight log_in on canvas"));-- expect(screen.getByText("opened the sign-in page")).toBeTruthy();- });-- // A two-block turn is the case a one-block fixture hides: the run row is not a- // solo block, so its cards sit in the collapsed body and name nothing there.- it("names a failed block on a two-block turn, on both surfaces", () => {- const twoBlockTurn = (): TurnNarrativeState => ({- ...terminalBuildTurn(),- designActivity: [- {- kind: "tool_result",- toolName: "update_and_run_blocks",- text: "Ran the blocks",- success: true,- iteration: 0,- id: "tr-run",- },- ],- blocks: [completedBlock("log_in"), failedBlock("download")],- });-- const legacy = render(<NarrativeView turn={twoBlockTurn()} />);- expect(screen.getAllByText(/download/i).length).toBeGreaterThan(0);- legacy.unmount();-- render(<NarrativeView turn={twoBlockTurn()} />);- expect(screen.getAllByText(/download/i).length).toBeGreaterThan(0);- });-- // The write/run row the design shows titled renders as a block card, which- // previously discarded the narrator title entirely.- it("titles a solo block row with the narrator label, without losing the block name", () => {- const narratedRunTurn = (): TurnNarrativeState => ({- ...terminalBuildTurn(),- designActivity: [- {- kind: "tool_result",- toolName: "update_and_run_blocks",- text: "Ran the blocks",- success: true,- iteration: 0,- id: "tr-run",- },- {- kind: "narration",- text: "Checking the saved steps survive a real run",- iteration: 0,- activeLabel: "Running it",- outcomeLabel: "Rewrote the download step",- id: "n-run",- },- ],- blocks: [completedBlock("download_report")],- });-- render(<NarrativeView turn={narratedRunTurn()} />);-- expect(screen.getByText("Rewrote the download step")).toBeTruthy();- // The block itself is still named by the rollup's own list.- expect(screen.getAllByText(/download.report/i).length).toBeGreaterThan(0);- });-});diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsxnew file mode 100644index 000000000..4b0f6ae0f--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx@@ -0,0 +1,65 @@+// @vitest-environment jsdom++import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { NarrativeView } from "./NarrativeView";+import {+ BlockState,+ EMPTY_NARRATIVE,+ TurnNarrativeState,+} from "./narrativeState";++const completedBlock = (): BlockState => ({+ workflowRunBlockId: "wrb_open_site",+ label: "open_site",+ blockType: "navigation",+ state: "completed",+ lastSeenIteration: 1,+ activity: [],+ startedAt: "2026-05-30T00:00:00Z",+ endedAt: "2026-05-30T00:00:10Z",+});++const structuredTurn = (+ overrides: Partial<TurnNarrativeState> = {},+): TurnNarrativeState => ({+ ...EMPTY_NARRATIVE,+ turnId: "turn-1",+ turnIndex: 0,+ designStarted: true,+ designEnded: true,+ draft: { blockCount: 1, blockLabels: ["open_site"], summary: null },+ blocks: [completedBlock()],+ terminal: "response",+ narrativeSummary: "Built the **navigation** block.",+ startedAt: "2026-05-30T00:00:00Z",+ endedAt: "2026-05-30T00:00:12Z",+ ...overrides,+});++afterEach(cleanup);++describe("NarrativeView structured turn presentation", () => {+ it("uses one detailed reading view without the legacy rollup", () => {+ render(<NarrativeView turn={structuredTurn()} />);++ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();+ expect(+ screen.queryByRole("button", { name: /Built the workflow/ }),+ ).toBeNull();+ expect(screen.getByText("navigation", { selector: "strong" })).toBeTruthy();+ expect(screen.getByRole("button", { name: /Open Site/ })).toBeTruthy();+ });++ it("uses the same presentation for an in-flight structured turn", () => {+ render(+ <NarrativeView+ turn={structuredTurn({ terminal: null, endedAt: null })}+ />,+ );++ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();+ expect(screen.getByRole("button", { name: /Open Site/ })).toBeTruthy();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.prose.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.prose.test.tsxindex a927dc0c1..509d69a58 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.prose.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.prose.test.tsx@@ -153,7 +153,7 @@ describe("NarrativeView terminal prose", () => {turn={terminalTurn({responseKind: "answer",terminalMessage:- "Use **records** with `for_loop`.\n\n- One item per iteration\n- Keep the JSON expanded",+ "Use **records** with `for_loop`.\n\n- One item per iteration\n- Keep the JSON expanded\n\n[Docs](https://docs.skyvern.com) [unsafe](javascript:alert(1)) ",})}/>,);@@ -174,6 +174,11 @@ describe("NarrativeView terminal prose", () => {.getByText("records", { selector: ".sr-only strong" }).closest(".whitespace-normal"),).toBeTruthy();+ expect(+ visual.querySelector('a[href="https://docs.skyvern.com"]')?.textContent,+ ).toBe("Docs");+ expect(visual.querySelectorAll("a")[1]?.getAttribute("href")).toBe("");+ expect(visual.querySelector("img")).toBeNull();});it("renders Markdown structure while the response is still revealing", () => {@@ -219,7 +224,7 @@ describe("NarrativeView terminal prose", () => {turn={terminalTurn({responseKind: "clarify",responseType: "REPLY",- terminalMessage: "Which login should I use?",+ terminalMessage: "Which **login** should I use?",lastRunOutcome: {verdict: "not_demonstrated",displayReason: "The sign-in flow did not reach the expected page.",@@ -229,15 +234,50 @@ describe("NarrativeView terminal prose", () => {);expect(screen.queryByTestId("copilot-terminal-prose")).toBeNull();+ expect(screen.getByText("login", { selector: "strong" })).toBeTruthy();+ expect(screen.getByText("Outcome not confirmed")).toBeTruthy();+ expect(container.querySelector(".rounded-xl")).toBeNull();+ });++ it("shows a run-level unconfirmed outcome when completed blocks have no verdict", () => {+ render(+ <NarrativeView+ turn={terminalTurn({+ responseKind: "build",+ terminalMessage: "I built and tested the navigation block.",+ lastRunOutcome: {+ verdict: "not_demonstrated",+ displayReason: "The expected destination was not observed.",+ },+ blocks: [+ {+ workflowRunBlockId: "wrb-open-site",+ label: "open_site",+ blockType: "navigation",+ state: "completed",+ lastSeenIteration: 0,+ activity: [],+ startedAt: null,+ endedAt: null,+ },+ ],+ })}+ />,+ );+expect(screen.getByText("Outcome not confirmed")).toBeTruthy();- expect(container.querySelector(".rounded-xl")).not.toBeNull();+ expect(+ screen.getByText(/The expected destination was not observed/),+ ).toBeTruthy();});- it("keeps a build result in its structured summary card", () => {+ it("keeps a build result in its structured detail view", () => {const { container } = render(<NarrativeViewturn={terminalTurn({responseKind: "build",+ terminalMessage:+ "I built the **navigation** block. [Read the docs](https://docs.skyvern.com)",designStarted: true,draft: {blockCount: 1,@@ -261,6 +301,17 @@ describe("NarrativeView terminal prose", () => {);expect(screen.queryByTestId("copilot-terminal-prose")).toBeNull();- expect(container.querySelector(".rounded-xl")).not.toBeNull();+ const formattedText = screen.getByText("navigation", {+ selector: "strong",+ });+ expect(formattedText).toBeTruthy();+ expect(formattedText.closest(".pl-9")).toBeNull();+ expect(formattedText.closest(".pr-8")).toBeNull();+ expect(screen.getAllByText("Open Site").length).toBeGreaterThan(0);+ expect(container.querySelector(".rounded-xl")).toBeNull();+ const docsLink = screen.getByRole("link", { name: "Read the docs" });+ expect(docsLink.closest("button")).toBeNull();++ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();});});diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsxindex 0769d0636..c07685101 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx@@ -111,39 +111,6 @@ describe("NarrativeView — recorded action reveal", () => {expect(document.querySelectorAll(".animate-spin").length).toBe(0);});- it("survives a real unmount/remount (rollup collapse -> expand) without restarting the schedule", () => {- const actions = [action("a1"), action("a2")];- const failedBlock: BlockState = {- ...verifyingBlockWithActions(actions, NOW),- state: "failed",- outcome: undefined,- };- const terminalTurn: TurnNarrativeState = {- ...inFlightTurnWithBlock(failedBlock),- terminal: "response",- terminalMessage: "Halted.",- endedAt: "2026-06-10T00:00:10Z",- };-- render(<NarrativeView turn={terminalTurn} />);- // A terminal turn defaults to the rolled-up summary card — the block- // row (and its actions) are not mounted at all yet.- expect(screen.queryByText("Action a1")).toBeNull();-- act(() => {- vi.advanceTimersByTime(350);- });-- // Expand into the detail view — FBlockRun mounts for the first time here.- fireEvent.click(screen.getByRole("button", { name: /Run halted/ }));-- // 350ms had already elapsed before this fresh mount: one action already- // done, the second mid-reveal — not restarted from zero.- expect(screen.getByText("Action a1")).toBeTruthy();- expect(screen.getByText("Action a2")).toBeTruthy();- expect(document.querySelectorAll(".animate-spin").length).toBe(1);- });-it("renders no recorded-action rows when the block has none (byte-identical to today)", () => {const block: BlockState = {workflowRunBlockId: "wrb_1",diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsxindex 701e89ebc..22cf9bb64 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx@@ -1,15 +1,4 @@-import {- type Ref,- type ReactNode,- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from "react";-import ReactMarkdown from "react-markdown";-import remarkGfm from "remark-gfm";-+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {REVEAL_MS_PER_CHAR,buildRevealOffsets,@@ -17,6 +6,7 @@ import {revealedCountAt,} from "./actionReveal";import { humanizeBlockLabel } from "./blockLabel";+import { CopilotMarkdown } from "./CopilotMarkdown";import {ACTIVITY_KIND_GLYPH,ACTIVITY_KIND_WORD,@@ -30,13 +20,10 @@ import {BlockState,RecordedActionSummary,TurnNarrativeState,- TurnSummary,- computeTurnSummary,formatElapsed,humanizeJudgeText,isBlockOk,isInterimOutcome,- latestBlocksByLabel,notConfirmedOutcome,parseUtcIsoMs,toolActivityDisplayLabel,@@ -60,18 +47,6 @@ function normalizeOutcomeReason(return humanized.length > 0 ? humanized : null;}-function normalizeOutcomeReasonSearchText(- text: string | null | undefined,-): string {- const normalized = normalizeOutcomeReason(text);- if (!normalized) return "";- return normalized- .toLowerCase()- .replace(/\s+/g, " ")- .replace(/[.,!?;:]+$/g, "")- .trim();-}-function truncateOutcomeReason(reason: string): string {if (reason.length <= OUTCOME_REASON_PREVIEW_LIMIT) return reason;const slice = reason.slice(0, OUTCOME_REASON_PREVIEW_LIMIT - 3).trimEnd();@@ -82,6 +57,15 @@ function notConfirmedDisplayReason(turn: TurnNarrativeState): string | null {return normalizeOutcomeReason(notConfirmedOutcome(turn)?.displayReason);}+function hasBlockOutcomeNotConfirmed(turn: TurnNarrativeState): boolean {+ return turn.blocks.some(+ (block) =>+ block.state === "completed" &&+ block.outcome === "not_demonstrated" &&+ !isInterimOutcome(block.outcomeRole),+ );+}+interface BlockPalette {fg: string;bg: string;@@ -492,9 +476,8 @@ interface FBlockRunProps {turnEnded: boolean;onSelect?: (label: string) => void;outcomeReasonFallback?: string | null;- // Narrator title for the row this card heads. The card's own status text and- // the rollup's block lists still name the block, so the title replaces only- // the label here.+ // Narrator title for the row this card heads. The card's own status text+ // still names the block, so the title replaces only the label here.rowTitle?: string | null;// Inside the activity log the card sheds its puck for the shared row grid,// so a block does not read as a different species from the steps around it.@@ -1493,303 +1476,21 @@ function FActivityLog({);}-function accentBg(accent: TurnSummary["accent"]): string {- if (accent === "fail") {- return "border-rose-400/60 bg-rose-500/15 text-rose-700 dark:text-rose-300";- }- if (accent === "warn") {- return "border-amber-400/60 bg-amber-500/15 text-amber-700 dark:text-amber-300";- }- if (accent === "qa") {- return "border-sky-400/60 bg-sky-500/15 text-sky-700 dark:text-sky-300";- }- return "border-emerald-400/60 bg-emerald-500/15 text-emerald-700 dark:text-emerald-300";-}--interface TurnHeadProps {- summary: TurnSummary;- expanded: boolean;- onClick?: () => void;- subtitle?: ReactNode;- buttonRef?: Ref<HTMLButtonElement>;- controlsId?: string;-}--function TurnHead({- summary,- expanded,- onClick,- subtitle,- buttonRef,- controlsId,-}: TurnHeadProps) {- const expandable = Boolean(onClick);- const headClass = "flex w-full items-start gap-3 px-3.5 py-3 text-left";- const body = (- <>- <span- className={`flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-full border text-[12px] font-bold ${accentBg(- summary.accent,- )}`}- aria-hidden="true"- >- {summary.glyph}- </span>- <div className="min-w-0 flex-1">- <div className="mb-0.5 flex flex-wrap items-baseline gap-x-2 gap-y-0.5">- <span className="text-[14px] font-semibold tracking-tight text-foreground">- {summary.headline}- </span>- {summary.stats.length ? (- <span className="text-[11.5px] text-muted-foreground">- {summary.stats.join(" · ")}- </span>- ) : null}- </div>- {subtitle}- </div>- {expandable ? (- <span- className={`mt-1 shrink-0 text-[14px] text-muted-foreground transition-transform dark:text-slate-500 ${- expanded ? "rotate-90" : ""- }`}- aria-hidden="true"- >- ›- </span>- ) : null}- </>- );-- if (!expandable) {- return <div className={headClass}>{body}</div>;- }-- return (- <button- ref={buttonRef}- type="button"- onClick={onClick}- aria-expanded={expanded}- aria-controls={controlsId}- className={headClass}- >- {body}- </button>- );-}--interface RollupCardProps {- turn: TurnNarrativeState;- summary: TurnSummary;- onExpand: () => void;- onBlockSelect?: (label: string) => void;- activityInteractionRef?: { current: string | null };- headerRef?: Ref<HTMLButtonElement>;-}--function RollupCard({- turn,- summary,- onExpand,- onBlockSelect,- activityInteractionRef,- headerRef,-}: RollupCardProps) {- // The backend appends the judge's verdict to the closing message, so it needs the- // same display-layer rewrite the outcome reason gets.- const closing = humanizeJudgeText(- turn.narrativeSummary?.trim() || turn.terminalMessage?.trim() || "",- );- const collapsedOutcomeReason = notConfirmedDisplayReason(turn);- const truncatedOutcomeReason = collapsedOutcomeReason- ? truncateOutcomeReason(collapsedOutcomeReason)- : null;- const normalizedClosing = normalizeOutcomeReasonSearchText(closing);- // Normalizing the truncated preview (its trailing "..." strips as punctuation)- // makes the containment check a prefix match, so closings carrying either the- // full reason or a truncated form of it both suppress the appended segment.- const normalizedOutcomeReason = normalizeOutcomeReasonSearchText(- truncatedOutcomeReason,- );- const shouldAppendOutcomeReason =- normalizedOutcomeReason.length > 0 &&- !normalizedClosing.includes(normalizedOutcomeReason);- const outcomeReasonSubtitle = shouldAppendOutcomeReason- ? `Outcome not confirmed: ${truncatedOutcomeReason!}`- : "";- const subtitle = [closing, outcomeReasonSubtitle].filter(Boolean).join(" · ");- const rollupBlocks = latestBlocksByLabel(turn.blocks);- const completed = rollupBlocks.filter((b) => isBlockOk(b));- const failed = rollupBlocks.filter((b) => b.state === "failed");- const stopped = rollupBlocks.filter((b) => b.state === "stopped");- const showChecklist = showPhaseChecklist(turn);- // The log holds every block, but a non-solo run row renders its cards in the- // body, which is collapsed once the turn ends — so the log names a block on- // screen only in the one-block case. These lists stay until a run row carries- // its blocks' outcomes in the collapsed line.- const showCommit = !summary.isQA && completed.length > 0;- const showHalted = failed.length > 0;- // Expand only earns a chevron when DetailView adds content beyond the head's- // message — a pure ask (no scouting) re-renders the same text, so no chevron.- const hasExpandableDetail =- showChecklist ||- turn.blocks.length > 0 ||- (turn.designStarted && (turn.draft?.blockCount ?? 0) > 0) ||- turn.designActivity.some((e) => e.kind === "narration");-- return (- <div className="overflow-hidden rounded-xl border border-border/60 bg-slate-elevation2">- <TurnHead- summary={summary}- expanded={false}- onClick={hasExpandableDetail ? onExpand : undefined}- buttonRef={headerRef}- controlsId={undefined}- subtitle={- subtitle ? (- <div- className={`mt-0.5 text-[12.5px] leading-[1.5] ${- summary.isFail && !summary.isStoppedWithDraft- ? "text-rose-700 dark:text-rose-200/90"- : "text-muted-foreground"- }`}- >- {subtitle}- </div>- ) : null- }- />-- {showChecklist ? (- <div className="border-t border-white/5 px-3.5 py-2">- <FActivityLog- key={turn.turnId ?? ""}- turn={turn}- turnEnded- onBlockSelect={onBlockSelect}- interactionRef={activityInteractionRef}- />- </div>- ) : null}-- {showCommit ? (- <div className="border-t border-white/5 pb-3 pl-[52px] pr-3.5 pt-2.5">- <div className="mb-1.5 text-[10px] font-bold uppercase tracking-[.06em] text-muted-foreground dark:text-slate-500">- What changed- </div>- <ul className="m-0 flex list-none flex-col gap-1 p-0">- {completed.map((b) => {- const palette = paletteFor(b.blockType);- return (- <li- key={b.label}- className="flex items-baseline gap-1.5 text-[12px] leading-[1.5] text-foreground dark:text-slate-200"- >- <span- className={`w-3.5 shrink-0 text-center text-[11px] font-bold ${palette.fg}`}- aria-hidden="true"- >- {palette.glyph}- </span>- <span- className="text-[11px] text-muted-foreground"- title={b.label}- >- {humanizeBlockLabel(b.label)}- </span>- <span className="text-slate-600">·</span>- <span className="text-[11.5px] text-foreground dark:text-slate-200">- {b.blockType}- </span>- </li>- );- })}- </ul>- </div>- ) : null}-- {showHalted ? (- <div className="border-t border-white/5 pb-3 pl-[52px] pr-3.5 pt-2.5">- <div className="mb-1.5 text-[10px] font-bold uppercase tracking-[.06em] text-rose-700 dark:text-rose-400">- Halted- </div>- <ul className="m-0 flex list-none flex-col gap-1 p-0">- {failed.map((b) => (- <li- key={b.label}- className="flex items-baseline gap-1.5 text-[12px] leading-[1.5] text-rose-700 dark:text-rose-200"- >- <span- className="w-3.5 shrink-0 text-center text-[11px] font-bold text-rose-700 dark:text-rose-300"- aria-hidden="true"- >- ✕- </span>- <span- className="text-[11px] text-rose-700 dark:text-rose-300/80"- title={b.label}- >- {humanizeBlockLabel(b.label)}- </span>- </li>- ))}- </ul>- </div>- ) : null}-- {stopped.length > 0 ? (- <div className="border-t border-white/5 pb-3 pl-[52px] pr-3.5 pt-2.5">- <div className="mb-1.5 text-[10px] font-bold uppercase tracking-[.06em] text-muted-foreground">- Stopped- </div>- <ul className="m-0 flex list-none flex-col gap-1 p-0">- {stopped.map((b) => (- <li- key={b.label}- className="flex items-baseline gap-1.5 text-[12px] leading-[1.5] text-tertiary-foreground"- >- <span- className="w-3.5 shrink-0 text-center text-[11px] font-bold text-muted-foreground"- aria-hidden="true"- >- ■- </span>- <span- className="text-[11px] text-muted-foreground"- title={b.label}- >- {humanizeBlockLabel(b.label)}- </span>- </li>- ))}- </ul>- </div>- ) : null}- </div>- );-}-interface DetailViewProps {turn: TurnNarrativeState;- onCollapse: (() => void) | null;onBlockSelect?: (label: string) => void;workingRowActive?: boolean;activityInteractionRef?: { current: string | null };- collapseRef?: Ref<HTMLButtonElement>;- detailsId?: string;}function DetailView({turn,- onCollapse,onBlockSelect,workingRowActive,activityInteractionRef,- collapseRef,- detailsId,}: DetailViewProps) {const collapsedOutcomeReason = notConfirmedDisplayReason(turn);+ const blockShowsOutcomeNotConfirmed = hasBlockOutcomeNotConfirmed(turn);const hasBlocks = turn.blocks.length > 0;const designStarted = turn.designStarted;const designOpen = designStarted && !turn.designEnded;@@ -1806,24 +1507,7 @@ function DetailView({return (<div className="flex flex-col gap-2.5">- {onCollapse ? (- <button- ref={collapseRef}- type="button"- onClick={onCollapse}- aria-label="Collapse turn"- aria-expanded={true}- aria-controls={detailsId}- className="flex w-full items-center justify-end gap-1.5 px-3.5 py-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground hover:text-tertiary-foreground dark:text-slate-500"- >- <span>Collapse</span>- <span aria-hidden="true" className="rotate-90 text-[13px]">- ›- </span>- </button>- ) : null}-- <div id={detailsId} className="flex flex-col gap-2.5">+ <div className="flex flex-col gap-2.5">{showChecklist ? (<FActivityLogkey={turn.turnId ?? ""}@@ -1865,12 +1549,21 @@ function DetailView({) : null}{turn.terminal && (turn.narrativeSummary || turn.terminalMessage) ? (- <div className="whitespace-pre-wrap pl-9 pr-8 text-[13px] leading-[1.55] text-foreground dark:text-slate-200">- {humanizeJudgeText(- turn.narrativeSummary?.trim() ||- turn.terminalMessage?.trim() ||- "",- )}+ <div className="text-[13px] leading-[1.55] text-foreground dark:text-slate-200">+ <CopilotMarkdown+ text={humanizeJudgeText(+ turn.narrativeSummary?.trim() ||+ turn.terminalMessage?.trim() ||+ "",+ )}+ />+ </div>+ ) : null}++ {collapsedOutcomeReason && !blockShowsOutcomeNotConfirmed ? (+ <div className="text-[12px] leading-[1.5] text-amber-700 dark:text-amber-300">+ <span className="font-medium">Outcome not confirmed</span>+ {` — ${truncateOutcomeReason(collapsedOutcomeReason)}`}</div>) : null}</div>@@ -1886,125 +1579,6 @@ interface NarrativeViewProps {type TerminalProseTone = "answer" | "question";-interface MarkdownTreeNode {- type: string;- value?: string;- tagName?: string;- properties?: Record<string, unknown>;- children?: MarkdownTreeNode[];-}--interface MarkdownReveal {- shown: number;- gradientStart: number;- onCharacterCount: (count: number) => void;-}--// ReactMarkdown has already parsed the model output into a structured HAST.-// Reveal those text nodes in document order so formatting never depends on-// interpreting a partial Markdown string.-function terminalMarkdownRevealPlugin(reveal: MarkdownReveal) {- return () => (tree: MarkdownTreeNode) => {- let offset = 0;- let lastGradientNode: MarkdownTreeNode | null = null;-- const revealChildren = (node: MarkdownTreeNode) => {- if (!node.children) return;- const visibleChildren: MarkdownTreeNode[] = [];-- for (const child of node.children) {- if (child.type !== "text") {- const offsetBeforeChild = offset;- revealChildren(child);- if (- (child.children && child.children.length > 0) ||- (!child.children && offsetBeforeChild < reveal.shown)- ) {- visibleChildren.push(child);- }- continue;- }-- const value = child.value ?? "";- const start = offset;- offset += value.length;- const visibleLength = Math.min(- value.length,- Math.max(0, reveal.shown - start),- );- if (visibleLength === 0) continue;-- const stableLength = Math.min(- visibleLength,- Math.max(0, reveal.gradientStart - start),- );- if (stableLength > 0) {- visibleChildren.push({- type: "text",- value: value.slice(0, stableLength),- });- }-- const gradientLength = visibleLength - stableLength;- for (let i = 0; i < gradientLength; i += 1) {- const characterOffset = start + stableLength + i;- const progress =- (characterOffset - reveal.gradientStart + 1) /- Math.max(1, reveal.shown - reveal.gradientStart);- const opacity = Math.max(0.12, 1 - progress * 0.88);- const gradientNode: MarkdownTreeNode = {- type: "element",- tagName: "span",- properties: { style: `opacity: ${opacity.toFixed(2)}` },- children: [- {- type: "text",- value: value[stableLength + i],- },- ],- };- visibleChildren.push(gradientNode);- lastGradientNode = gradientNode;- }- }-- node.children = visibleChildren;- };-- revealChildren(tree);- const gradientEdge = lastGradientNode as MarkdownTreeNode | null;- if (gradientEdge) {- gradientEdge.properties = {- ...gradientEdge.properties,- "data-testid": "copilot-terminal-prose-gradient",- };- }- reveal.onCharacterCount(offset);- };-}--function TerminalMarkdown({- text,- reveal,-}: {- text: string;- reveal?: MarkdownReveal;-}) {- return (- <div className="whitespace-normal [&_a]:underline [&_a]:underline-offset-2 [&_code]:rounded [&_code]:bg-slate-500/15 [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.92em] [&_li+li]:mt-1 [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:pl-5 [&_p+p]:mt-3 [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:whitespace-pre-wrap [&_pre]:rounded-md [&_pre]:bg-slate-500/15 [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:pl-5">- <ReactMarkdown- remarkPlugins={[remarkGfm]}- rehypePlugins={- reveal ? [terminalMarkdownRevealPlugin(reveal)] : undefined- }- skipHtml- >- {text}- </ReactMarkdown>- </div>- );-}-function hasRecordedTerminalEvidence(turn: TurnNarrativeState): boolean {return (turn.blocks.length > 0 ||@@ -2106,17 +1680,17 @@ function TerminalProse({<divdata-testid="copilot-terminal-prose"className={[- "whitespace-pre-wrap text-[13px] leading-[1.55]",+ "text-[13px] leading-[1.55]",tone === "question"? "border-l-2 border-sky-500 pl-3 text-sky-700 dark:text-[#a7ccdd]": "text-foreground dark:text-slate-200",].join(" ")}><div className="sr-only">- <TerminalMarkdown text={text} />+ <CopilotMarkdown text={text} /></div><div data-testid="copilot-terminal-prose-visual" aria-hidden="true">- <TerminalMarkdown+ <CopilotMarkdowntext={text}reveal={revealing || settling@@ -2134,28 +1708,11 @@ export function NarrativeView({onBlockSelect,workingRowActive,}: NarrativeViewProps) {- const summary = useMemo(() => computeTurnSummary(turn), [turn]);- const isInFlight = turn.terminal === null;- const isComplete = !isInFlight;const proseTone = terminalProseTone(turn);const proseText = humanizeJudgeText(turn.narrativeSummary?.trim() || turn.terminalMessage?.trim() || "",);- const [userRolled, setUserRolled] = useState<boolean | null>(null);const activityInteractionRef = useRef<string | null>(null);- const rolled = userRolled === null ? isComplete : userRolled;- const rollupButtonRef = useRef<HTMLButtonElement>(null);- const collapseButtonRef = useRef<HTMLButtonElement>(null);- const pendingTurnFocus = useRef<"rollup" | "detail" | null>(null);- const detailsId = `copilot-turn-${turn.turnId ?? turn.turnIndex}-details`;- useEffect(() => {- if (pendingTurnFocus.current === "rollup") {- rollupButtonRef.current?.focus();- } else if (pendingTurnFocus.current === "detail") {- collapseButtonRef.current?.focus();- }- pendingTurnFocus.current = null;- }, [rolled]);if (proseTone !== null && proseText) {return (@@ -2167,40 +1724,12 @@ export function NarrativeView({);}- if (rolled && isComplete) {- return (- <RollupCard- turn={turn}- summary={summary}- onExpand={() => {- activityInteractionRef.current = null;- pendingTurnFocus.current = "detail";- setUserRolled(false);- }}- onBlockSelect={onBlockSelect}- activityInteractionRef={activityInteractionRef}- headerRef={rollupButtonRef}- />- );- }-return (<DetailViewturn={turn}- onCollapse={- isComplete- ? () => {- activityInteractionRef.current = null;- pendingTurnFocus.current = "rollup";- setUserRolled(true);- }- : null- }onBlockSelect={onBlockSelect}workingRowActive={workingRowActive}activityInteractionRef={activityInteractionRef}- collapseRef={collapseButtonRef}- detailsId={detailsId}/>);}diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsxindex b248bcf78..c42fa9d5f 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx@@ -516,13 +516,10 @@ describe("WorkflowCopilotChat — recorded-action live poll wiring", () => {],});- // A settled turn's card defaults to its rolled-up summary; expand it,- // then expand the block row, to reach the replay the fetch just patched- // in — this is the reviewer's "does the verify card ever receive it".+ // The current settled turn remains expanded, so expand the block row to+ // reach the replay the fetch just patched in — this is the reviewer's+ // "does the verify card ever receive it".const statusRegion = await waitFor(() => screen.getByRole("status"));- fireEvent.click(- within(statusRegion).getByRole("button", { expanded: false }),- );// The row's primary text is the humanized label ("block_1" -> "Block 1"),// not the raw block label.fireEvent.click(within(statusRegion).getByText("Block 1"));diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsxindex 1586af907..7448ce371 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx@@ -278,9 +278,9 @@ describe("WorkflowCopilotChat — instant acknowledgement", () => {// Ask turns emit no narrative frames; the placeholder clears when the turn// completes (isLoading falls) as the plain reply lands.- await completeStream(0, "It scrapes headlines.");+ await completeStream(0, "It **scrapes** headlines.");- expect(screen.getByText("It scrapes headlines.")).toBeTruthy();+ expect(screen.getByText("scrapes", { selector: "strong" })).toBeTruthy();expectNoAckLines();});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsxindex 821e61605..3c72420ff 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx@@ -634,7 +634,8 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {call.resolve();});- expect(screen.getByText("Run halted")).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();+ expect(screen.getByText("Copilot hit an internal error.")).toBeTruthy();expect(screen.queryByText("Completed the run")).toBeNull();});@@ -660,7 +661,10 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {call.resolve();});- expect(screen.getByText("Stopped with a draft")).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();+ expect(+ screen.getByText(/Cancelled\. I have a draft workflow/),+ ).toBeTruthy();expect(screen.queryByText("Run halted")).toBeNull();expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();@@ -697,7 +701,8 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {call.resolve();});- expect(screen.getByText("Stopped with a draft")).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();+ expect(screen.getByText(/draft made progress/)).toBeTruthy();expect(screen.queryByText("Run halted")).toBeNull();expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();@@ -785,7 +790,10 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {await renderChat();- expect(screen.getByText("Stopped with a draft")).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();+ expect(+ screen.getByText(/Cancelled\. I have a draft workflow/),+ ).toBeTruthy();expect(screen.queryByText("Run halted")).toBeNull();expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();@@ -982,7 +990,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {const call = streamCalls[0];if (!call) throw new Error("no pending stream to complete");const longInputRequest =- "Please provide the exact BACB lookup/registry URL you want the workflow to use. I will build a general workflow with a person_name input after you provide it.";+ "Please provide the **exact registry URL** you want the workflow to use. I will build a general workflow with a `person_name` input after you provide it.";await act(async () => {call.onMessage({@@ -1007,8 +1015,11 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {call.resolve();});- expect(screen.getByText("Needs your input")).toBeTruthy();- expect(screen.getByText(longInputRequest)).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();+ expect(+ screen.getByText("exact registry URL", { selector: "strong" }),+ ).toBeTruthy();+ expect(screen.getByText("person_name", { selector: "code" })).toBeTruthy();expect(screen.queryByText("Answered")).toBeNull();expect(screen.queryByText("Completed the run")).toBeNull();});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsxindex f55cebd9b..3a75afd6c 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx@@ -523,9 +523,31 @@ describe("WorkflowCopilotChat — g2 review gate", () => {await waitFor(() =>expect(screen.getByText("Different source")).toBeTruthy(),);+ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();expect(- screen.getByText(/3 blocks authored · 0\/3 ran on current source/),- ).toBeTruthy();+ screen.queryByRole("button", { name: /Draft needs review/ }),+ ).toBeNull();expect(screen.queryByText("Built and tested the workflow")).toBeNull();});++ it("keeps the newest structured response in its expanded reading state", async () => {+ await renderChat();++ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(proposalResponse("Draft ready."));+ streamCalls[0]!.resolve();+ });++ await waitFor(() =>+ expect(+ screen.getByText("Here is a draft workflow for you to review."),+ ).toBeTruthy(),+ );+ expect(screen.queryByRole("button", { name: "Collapse turn" })).toBeNull();+ expect(+ screen.queryByRole("button", { name: /Draft needs review/ }),+ ).toBeNull();+ });});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex 8f732cdff..92a6c2014 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -76,6 +76,7 @@ import {import { shouldAutoApplyWorkflowResponse } from "./proposalDisposition";import { shouldArmDraftingGapTimer } from "./copilotPhases";import { InstantAckPlaceholder, NarrativeView } from "./NarrativeView";+import { CopilotMarkdown } from "./CopilotMarkdown";import { CopilotWorkingStatus } from "./CopilotWorkingStatus";import { useRunLifecycleAnnouncements } from "./useRunLifecycleAnnouncements";import { ConfirmCard, shouldShowConfirmCard } from "./cards/ConfirmCard";@@ -540,9 +541,9 @@ const MessageItem = memo(}return (<div className="flex flex-col gap-2">- <p className="whitespace-pre-wrap pl-1 text-[13px] leading-[1.55] text-foreground dark:text-slate-200">- {message.content}- </p>+ <div className="pl-1 text-[13px] leading-[1.55] text-foreground dark:text-slate-200">+ <CopilotMarkdown text={message.content} />+ </div>{footer ? (<div className="flex flex-wrap gap-2 pl-1">{footer}</div>) : null}diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex e9758684f..d1b23679b 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -1346,6 +1346,7 @@ class ForgeAgent:validate_and_fill_extraction_result,)from skyvern.forge.taskv3.auth_tools import VerificationState, build_auth_tools+ from skyvern.forge.taskv3.block_context import render_block_contextfrom skyvern.forge.taskv3.captcha_tools import build_captcha_toolsfrom skyvern.forge.taskv3.engine import (DEFAULT_DEADLINE_SECONDS,@@ -1440,46 +1441,18 @@ class ForgeAgent:page_free_validation = bool(router_result.effective_without_page_information)except Exception:LOG.warning("task_v3 validation evidence router failed; staying page-aware", task_id=task.task_id)- if task_block is not None and not page_free_validation:- # A block resumes mid-workflow: an earlier block may already have satisfied this one's- # criterion (the step engine's per-step goal check gives it this for free).- goal = (- f"{goal}\n\nThis task is one block of a larger workflow and starts mid-flow. First read "- "the full page text (get_html) and check whether the completion criterion is ALREADY "- "satisfied by the page's settled, loaded content - a loading indicator, skeleton, or "- "empty container does NOT satisfy a criterion about visible content."- + (- " When the goal names an action (open/click/submit), perform it unless the page "- "already shows that action's RESULT."- if task.task_type != TaskType.validation- else ""- )- + " If the criterion is genuinely satisfied, finish with status=completed "- "immediately without acting. Stay "- "within this block's goal: never sign out, navigate away from the current flow, or undo "- "prior progress unless the goal explicitly asks for it."- ).strip()- if page_free_validation:- # This mode judges only durable inputs/prior outputs; any perception instruction would- # contradict it, so it replaces (not extends) the read-the-page framing above.- goal = (- f"{goal}\n\nThis is a page-free assessment task: judge ONLY from the information already "- "provided above and prior workflow context. Do not call observe or get_html, and do not "- "modify page state. Evaluate the completion and termination criteria and finish with the "- "matching status."- ).strip()- elif task_block is not None and task.task_type == TaskType.validation:- # ValidationBlock tasks judge, not act; without this the loop can treat the criteria- # above as something to accomplish by interacting with the page.- goal = (- f"{goal}\n\nThis is an assessment task: do not modify page state. Evaluate the completion "- "and termination criteria above and finish with the matching status. Ground the judgment "- "in the page's actual content: read the full page text (get_html) before concluding, and "- "never finish with status=terminated on element summaries alone — absence must be "- "confirmed against the full text."- ).strip()- elif task_block is not None and task.task_type == TaskType.action:- goal = f"{goal}\n\nThis is a single, focused action: perform it and finish.".strip()+ workflow_run_context = (+ app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context(task.workflow_run_id)+ if task.workflow_run_id and app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context(task.workflow_run_id)+ else None+ )+ framing, block_context_section = render_block_context(+ task, task_block, workflow_run_context, page_free_validation=page_free_validation+ )+ if framing:+ goal = f"{goal}\n\n{framing}".strip()+ if block_context_section:+ goal = f"{goal}\n\n{block_context_section}".strip()async def _should_cancel() -> bool:refreshed = await app.DATABASE.tasks.get_task(diff --git a/skyvern/forge/taskv3/block_context.py b/skyvern/forge/taskv3/block_context.pynew file mode 100644index 000000000..b9c540447--- /dev/null+++ b/skyvern/forge/taskv3/block_context.py@@ -0,0 +1,73 @@+"""Cross-block context for a Task V3 block: the framing sentences appended to a block's goal.++Every "block N+1 needs to know X about the workflow" case is meant to become a typed input here,+not another ad-hoc sentence patched onto the goal string in ``ForgeAgent._execute_task_v3``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from skyvern.forge.sdk.schemas.tasks import Task, TaskType++if TYPE_CHECKING:+ from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext+ from skyvern.forge.sdk.workflow.models.block import BaseTaskBlock+++def render_block_context(+ task: Task,+ task_block: BaseTaskBlock | None,+ workflow_run_context: WorkflowRunContext | None,+ *,+ page_free_validation: bool = False,+) -> tuple[str, str]:+ """Return ``(framing, section)`` for a block task; both are ``""`` for a bare task.++ ``framing`` is the block-kind guidance (mid-flow / page-free validation / validation / action).+ ``section`` is the rendered workflow-context data section (position, previous-block handoff);+ it renders only fields that are set, so it is empty when there is nothing to say.+ """+ del workflow_run_context+ pieces: list[str] = []+ if task_block is not None and not page_free_validation:+ # A block resumes mid-workflow: an earlier block may already have satisfied this one's+ # criterion (the step engine's per-step goal check gives it this for free).+ pieces.append(+ "This task is one block of a larger workflow and starts mid-flow. First read "+ "the full page text (get_html) and check whether the completion criterion is ALREADY "+ "satisfied by the page's settled, loaded content - a loading indicator, skeleton, or "+ "empty container does NOT satisfy a criterion about visible content."+ + (+ " When the goal names an action (open/click/submit), perform it unless the page "+ "already shows that action's RESULT."+ if task.task_type != TaskType.validation+ else ""+ )+ + " If the criterion is genuinely satisfied, finish with status=completed "+ "immediately without acting. Stay "+ "within this block's goal: never sign out, navigate away from the current flow, or undo "+ "prior progress unless the goal explicitly asks for it."+ )+ if page_free_validation:+ # This mode judges only durable inputs/prior outputs; any perception instruction would+ # contradict it, so it replaces (not extends) the read-the-page framing above.+ pieces.append(+ "This is a page-free assessment task: judge ONLY from the information already "+ "provided above and prior workflow context. Do not call observe or get_html, and do not "+ "modify page state. Evaluate the completion and termination criteria and finish with the "+ "matching status."+ )+ elif task_block is not None and task.task_type == TaskType.validation:+ # ValidationBlock tasks judge, not act; without this the loop can treat the criteria+ # above as something to accomplish by interacting with the page.+ pieces.append(+ "This is an assessment task: do not modify page state. Evaluate the completion "+ "and termination criteria above and finish with the matching status. Ground the judgment "+ "in the page's actual content: read the full page text (get_html) before concluding, and "+ "never finish with status=terminated on element summaries alone — absence must be "+ "confirmed against the full text."+ )+ elif task_block is not None and task.task_type == TaskType.action:+ pieces.append("This is a single, focused action: perform it and finish.")+ return "\n\n".join(pieces), ""