Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Make Copilot's activity log read in the order it happened, and redesign answered question cards (SKY-17394) (#8718)
Shuchang Zheng6b11959ab2c4
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsxindex 1d902c52e..0bc9a143a 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx@@ -110,7 +110,19 @@ describe("NarrativeView — narrator content condensing (SKY-11971)", () => {});});-const KIND_GLYPH_PATTERN = /^(◎|⟨⟩|▷)$/;+// A finished turn with more than one step folds them under one header.+const openFold = () =>+ fireEvent.click(screen.getByRole("button", { name: /^Worked through/ }));++const stepLines = (): HTMLElement[] =>+ Array.from(document.querySelectorAll<HTMLElement>("[data-activity-line]"));++// What a sighted reader sees on a line, without the screen-reader words.+const visibleText = (el: Element): string => {+ const clone = el.cloneNode(true) as HTMLElement;+ clone.querySelectorAll(".sr-only").forEach((n) => n.remove());+ return (clone.textContent ?? "").replace(/\u00a0/g, " ");+};const repairLoopTurn = (): TurnNarrativeState => ({...EMPTY_NARRATIVE,@@ -151,112 +163,72 @@ const repairLoopTurn = (): TurnNarrativeState => ({});describe("NarrativeView — activity log", () => {- it("renders flat activity rows and drops the phase rail", () => {+ it("folds a finished turn under one header that counts its failed tests", () => {render(<NarrativeView turn={repairLoopTurn()} />);expect(screen.queryByText("Explore site")).toBeNull();- expect(screen.queryByText("Draft code")).toBeNull();- expect(screen.queryByText("Test-run")).toBeNull();- expect(screen.getByText("Opened the sign-in page")).toBeTruthy();- expect(screen.getByText("Saved 2 blocks")).toBeTruthy();- });+ const fold = screen.getByRole("button", { name: /^Worked through/ });+ expect(fold.textContent).toBe("Worked through 3 steps · 1 failed test");+ expect(fold.getAttribute("aria-expanded")).toBe("false");+ expect(stepLines()).toHaveLength(0);- it("a failed run keeps the server's reason instead of a generic tool label", () => {- render(<NarrativeView turn={repairLoopTurn()} />);- expect(- screen.queryByText(- "The submit button stayed disabled after filling the form",- ),- ).toBeNull();+ openFold();+ expect(stepLines()).toHaveLength(3);+ });- fireEvent.click(screen.getByRole("button", { name: /Block 1/ }));- expect(- screen.getByText(- "The submit button stayed disabled after filling the form",- ),- ).toBeTruthy();+ it("keeps a block's unconfirmed outcome visible while its turn is folded", () => {+ const turn = repairLoopTurn();+ render(+ <NarrativeView+ turn={{+ ...turn,+ blocks: [+ {+ ...turn.blocks[0]!,+ outcome: "not_demonstrated",+ outcomeReason: "No confirmation page appeared",+ },+ ],+ }}+ />,+ );+ expect(stepLines()).toHaveLength(0);+ expect(screen.getByText(/No confirmation page appeared/)).toBeTruthy();});- it("an in-flight turn renders the same flat rows in happened-order", () => {+ it("names a step the narrator never titled by what its calls did", () => {render(<NarrativeView turn={{ ...repairLoopTurn(), terminal: null }} />);- expect(screen.queryByText("Explore site")).toBeNull();- const rows = screen.getAllByText(/Opened the sign-in page|Saved 2 blocks/);- expect(rows.map((r) => r.textContent)).toEqual([- "Opened the sign-in page",- "Saved 2 blocks",+ expect(stepLines().map(visibleText)).toEqual([+ "1 browser action",+ "Tested the workflow · attempt failed",+ "Updated the workflow",]);});- it("the terminal gutter reads the row kinds in happened-order", () => {+ it("a failed run keeps the server's reason one click deep", () => {render(<NarrativeView turn={repairLoopTurn()} />);- const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);- expect(gutter.map((g) => g.textContent)).toEqual(["◎", "▷", "⟨⟩"]);- });+ openFold();+ const error = "The submit button stayed disabled after filling the form";+ expect(screen.queryByText(error)).toBeNull();- it("the in-flight detail gutter reads the same row kinds", () => {- render(<NarrativeView turn={{ ...repairLoopTurn(), terminal: null }} />);- const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);- expect(gutter.map((g) => g.textContent)).toEqual(["◎", "▷", "⟨⟩"]);- });-- it("the block card is the run row itself, ahead of the re-authoring row that follows it", () => {- render(<NarrativeView turn={repairLoopTurn()} />);- const reauthoringRow = screen.getByText("Saved 2 blocks");- const cards = screen.getAllByRole("button", { name: /Block 1/ });- expect(cards.length).toBeGreaterThan(0);- for (const card of cards) {- expect(- reauthoringRow.compareDocumentPosition(card) &- Node.DOCUMENT_POSITION_PRECEDING,- ).toBeTruthy();- }+ fireEvent.click(stepLines()[1]!);+ expect(screen.getByText(error).className).toContain("rose");});- it("a block row wears the same row treatment as a step row", () => {+ it("a block inside a step wears the shared row treatment", () => {render(<NarrativeView turn={repairLoopTurn()} />);- const blockRow = screen- .getAllByRole("button", { name: /Block 1/ })- .find((b) => b.className.includes("grid-cols-"));+ openFold();+ fireEvent.click(stepLines()[1]!);+ const blockRow = screen.getByTitle(/Highlight block_1/);// The block used to lead with a 24px status puck and a bold label while// the steps beside it led with a 16px glyph, so the column never lined up.- expect(blockRow).toBeTruthy();- expect(blockRow!.querySelector(".rounded-full")).toBeNull();- expect(blockRow!.className).toContain("grid-cols-[18px_1fr_auto]");-- // State is the inline mark and the elapsed column now, not a trailing- // "· done · code" the canvas rows never carry. The state still reaches a- // screen reader as a word, so read what is on screen rather than the- // sr-only text alongside it.- const onScreen = blockRow!.cloneNode(true) as HTMLElement;- onScreen.querySelectorAll(".sr-only").forEach((n) => n.remove());- expect(onScreen.textContent).not.toContain("code");- expect(onScreen.textContent).not.toContain("done");+ expect(blockRow.querySelector(".rounded-full")).toBeNull();+ expect(blockRow.className).toContain("grid-cols-[18px_1fr_auto]");+ expect(visibleText(blockRow)).not.toContain("code");+ expect(visibleText(blockRow)).not.toContain("done");});- it("a live row's clock reads wall time, not the span of its entries", () => {- const startedAt = new Date(Date.now() - 90_000).toISOString();- const turn = repairLoopTurn();- turn.terminal = null;- turn.blocks = [];- turn.designActivity = [- activityEntry({- id: "tc-live",- kind: "tool_call",- toolName: "navigate_browser",- text: "Opening the page",- iteration: 0,- timestamp: startedAt,- }),- ];- render(<NarrativeView turn={turn} />);-- // One entry means first stamp === last stamp, so the recorded span is zero- // and the column sat at 0:00 for as long as the step took.- expect(screen.getByText("1:30")).toBeTruthy();- expect(screen.queryByText("0:00")).toBeNull();- });-- it("a run row still calling carries no success mark", () => {+ it("a run row still calling claims no result", () => {const turn = repairLoopTurn();turn.terminal = null;turn.designActivity = [@@ -271,21 +243,13 @@ describe("NarrativeView — activity log", () => {turn.blocks = [];render(<NarrativeView turn={turn} />);- // A mark reports an outcome. The row is mid-call, so it has none yet —- // before this, "not failed" was rendered as "succeeded".- const row = screen- .getAllByText(/calling…/)- .map((n) => n.closest("[class*='grid-cols-']"))- .find(Boolean);- expect(row).toBeTruthy();- expect(row!.textContent).toContain("calling…");- expect(row!.textContent).not.toContain("✓");+ const [line] = stepLines();+ expect(visibleText(line!)).toBe("Testing the workflow");});- it("the kind reaches a screen reader as a word, not only as the glyph", () => {+ it("the kind reaches a screen reader as a word", () => {render(<NarrativeView turn={repairLoopTurn()} />);- // The glyph is aria-hidden, so without this the kind is invisible to a- // screen reader — the phase rail pairs its puck with an sr-only word too.+ openFold();expect(screen.getAllByText(/Looked at the page ·/).length).toBeGreaterThan(0,);@@ -293,22 +257,6 @@ describe("NarrativeView — activity log", () => {expect(screen.getAllByText(/Wrote code ·/).length).toBeGreaterThan(0);});- it("a block-authoring row carries the authoring glyph", () => {- const turn = repairLoopTurn();- turn.designActivity = [- activityEntry({- id: "tr-9",- kind: "tool_result",- toolName: "edit_block",- text: "Reworked the login block",- success: true,- }),- ];- render(<NarrativeView turn={turn} />);- const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);- expect(gutter.map((g) => g.textContent)).toEqual(["⟨⟩", "▷"]);- });-const browseEntry = (i: number, toolName: string, text: string) =>activityEntry({id: `tr-b${i}`,@@ -327,8 +275,9 @@ describe("NarrativeView — activity log", () => {terminal: null,designActivity: [browseEntry(0, "navigate_browser", "Opened the sign-in page"),- browseEntry(1, "get_page_evidence", "Read the form state"),- browseEntry(2, "click_element", "Found the invoice list"),+ browseEntry(1, "fill_credential_field", "Filled the saved login"),+ browseEntry(2, "click", "Clicked 'text=Invoices'"),+ browseEntry(3, "set_work_plan", "Planned three steps"),],});@@ -359,40 +308,63 @@ describe("NarrativeView — activity log", () => {],});- it("three consecutive browse steps fold into one row carrying the step count", () => {+ it("an open step lists its calls, and a call opens to its saved result", () => {render(<NarrativeView turn={groupedBrowseTurn()} />);- const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);- expect(gutter.map((g) => g.textContent)).toEqual(["◎"]);- expect(screen.getByText("Found the invoice list")).toBeTruthy();-- // The turn has not ended, so the newest row is the one being worked on and- // stays open through the gap between calls.- expect(screen.getByText("Opened the sign-in page")).toBeTruthy();- expect(screen.getByText("Read the form state")).toBeTruthy();-- fireEvent.click(screen.getByRole("button", { expanded: true }));- expect(screen.getByText(/3 steps/)).toBeTruthy();- expect(screen.queryByText("Opened the sign-in page")).toBeNull();+ expect(visibleText(stepLines()[0]!)).toBe(+ "2 browser actions, used a saved login, updated its plan",+ );++ // The newest row stays open through the gap between calls, each call's+ // result reading beside it on one line until the call is opened.+ const result = screen.getByText("Opened the sign-in page");+ expect(result.className).toContain("truncate");++ fireEvent.click(screen.getByRole("button", { name: /Opening page/ }));+ expect(screen.getByText("Opened the sign-in page").className).toContain(+ "whitespace-pre-wrap",+ );+ });++ it("repeated identical calls read as one line with a count", () => {+ const turn = groupedBrowseTurn();+ turn.designActivity = [+ browseEntry(0, "evaluate", "Evaluated JavaScript: returned 3 items"),+ browseEntry(1, "evaluate", "Evaluated JavaScript: returned 3 items"),+ browseEntry(2, "evaluate", "Evaluated JavaScript: returned 5 items"),+ ].map((entry) => ({ ...entry, displayLabel: "Inspecting page" }));+ render(<NarrativeView turn={turn} />);++ const calls = screen.getAllByRole("button", { name: /Inspecting page/ });+ expect(+ calls.map((call) => {+ const result = call.querySelector(".font-mono");+ return [+ visibleText(call).replace(result?.textContent ?? "", ""),+ result?.textContent,+ ];+ }),+ ).toEqual([+ ["Inspecting page ×2", "Evaluated JavaScript: returned 3 items"],+ ["Inspecting page", "Evaluated JavaScript: returned 5 items"],+ ]);});it("only the last unresolved call is expanded while two are in flight", () => {render(<NarrativeView turn={twoInFlightTurn()} />);-- expect(screen.getAllByRole("button", { expanded: true })).toHaveLength(1);- expect(screen.getByText("Checked the cart")).toBeTruthy();- expect(screen.queryByText("Opened the sign-in page")).toBeNull();- expect(screen.getByRole("button", { expanded: false })).toBeTruthy();+ expect(+ stepLines().map((line) => line.getAttribute("aria-expanded")),+ ).toEqual(["false", "false", "true"]);});- it("a finished browse row re-opens on click and folds again on the next", () => {+ it("a live step folds on click and opens again on the next", () => {render(<NarrativeView turn={groupedBrowseTurn()} />);- const row = screen.getByRole("button", { expanded: true });+ const row = stepLines()[0]!;fireEvent.click(row);- expect(screen.queryByText("Opened the sign-in page")).toBeNull();+ expect(screen.queryByRole("button", { name: /Opening page/ })).toBeNull();fireEvent.click(row);- expect(screen.getByText("Opened the sign-in page")).toBeTruthy();+ expect(screen.getByRole("button", { name: /Opening page/ })).toBeTruthy();});const REASON = "Checking whether the invoices sit behind a login";@@ -416,23 +388,82 @@ describe("NarrativeView — activity log", () => {],});- it.each([0, 7])(- "narration tagged iteration=%s renders inside the browse step, never as its own row",- (narrationIteration) => {- render(<NarrativeView turn={narratedBrowseTurn(narrationIteration)} />);+ it("keeps every step's sentence where it was spoken as the turn grows", () => {+ const at = (second: number) => `2026-06-10T00:00:0${second}Z`;+ const said = (n: number, iteration: number) =>+ activityEntry({+ id: `n-${n}`,+ kind: "narration",+ text: `Reason ${n}`,+ iteration,+ timestamp: at(n * 2),+ });+ const activity = [+ {+ ...browseEntry(0, "navigate_browser", "Opened the page"),+ timestamp: at(1),+ },+ said(1, 0),+ activityEntry({+ id: "tr-w1",+ kind: "tool_result",+ toolName: "update_workflow",+ text: "Saved 1 block",+ success: true,+ iteration: 1,+ timestamp: at(3),+ }),+ said(2, 1),+ ];+ const turn = (entries: typeof activity): TurnNarrativeState => ({+ ...narratedBrowseTurn(0),+ designActivity: entries,+ });+ const reasons = () =>+ screen.queryAllByTestId("copilot-reason").map((node) => node.textContent);++ const { rerender } = render(<NarrativeView turn={turn(activity)} />);+ expect(reasons()).toEqual([+ expect.stringContaining("Reason 1"),+ expect.stringContaining("Reason 2"),+ ]);++ rerender(<NarrativeView turn={turn([...activity, said(3, 1)])} />);+ expect(reasons()).toEqual([+ expect.stringContaining("Reason 1"),+ expect.stringContaining("Reason 2"),+ expect.stringContaining("Reason 3"),+ ]);+ });++ it("a narration about its step reads above it and stays when the step folds", () => {+ render(<NarrativeView turn={narratedBrowseTurn(0)} />);- expect(- screen.getAllByText(KIND_GLYPH_PATTERN).map((g) => g.textContent),- ).toEqual(["◎"]);- // Inside the step, not beside it: one glyph means one row.- expect(screen.getByText(REASON)).toBeTruthy();+ expect(document.querySelectorAll("[data-activity-row-id]")).toHaveLength(1);+ const reason = screen.getByTestId("copilot-reason");+ expect(reason.textContent).toContain(REASON);+ expect(+ reason.compareDocumentPosition(stepLines()[0]!) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();++ fireEvent.click(stepLines()[0]!);+ expect(screen.getByTestId("copilot-reason").textContent).toContain(REASON);+ });- fireEvent.click(screen.getByRole("button", { expanded: true }));- expect(screen.queryByText(REASON)).toBeNull();- },- );+ it("a narration spoken after its step settled reads below it, leaving the step untouched", () => {+ render(<NarrativeView turn={narratedBrowseTurn(7)} />);++ expect(document.querySelectorAll("[data-activity-row-id]")).toHaveLength(2);+ const reason = screen.getByTestId("copilot-reason");+ expect(reason.textContent).toContain(REASON);+ expect(+ reason.compareDocumentPosition(stepLines()[0]!) &+ Node.DOCUMENT_POSITION_PRECEDING,+ ).toBeTruthy();+ });- it("a finished run row re-opens to the block's step list", () => {+ it("a finished run step opens to its block, and the block to its steps", () => {const turn = repairLoopTurn();turn.blocks = [runningBlock({@@ -458,30 +489,14 @@ describe("NarrativeView — activity log", () => {}),];render(<NarrativeView turn={turn} />);+ openFold();+ fireEvent.click(stepLines()[1]!);expect(screen.queryByText("Submitted the form")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: /Block 1/ }));+ fireEvent.click(screen.getByTitle(/Highlight block_1/));expect(screen.getByText("Submitted the form")).toBeTruthy();});- it("a run row with no block renders a plain line and no block card", () => {- const turn = repairLoopTurn();- turn.blocks = [];- render(<NarrativeView turn={turn} />);- expect(screen.queryByText("Block 1")).toBeNull();- expect(- screen.queryByText(- "The submit button stayed disabled after filling the form",- ),- ).toBeNull();- fireEvent.click(screen.getByRole("button", { name: /Testing workflow/ }));- expect(- screen.getByText(- "The submit button stayed disabled after filling the form",- ),- ).toBeTruthy();- });-it("a run row with two blocks holds both cards behind one toggle", () => {const turn = repairLoopTurn();turn.blocks = [@@ -494,20 +509,100 @@ describe("NarrativeView — activity log", () => {}),];render(<NarrativeView turn={turn} />);+ openFold();expect(screen.queryAllByRole("button", { name: /Block 1/ })).toHaveLength(0,);- expect(screen.queryAllByRole("button", { name: /Block 2/ })).toHaveLength(- 0,- );- fireEvent.click(screen.getByRole("button", { name: /Testing workflow/ }));+ fireEvent.click(stepLines()[1]!);+ expect(screen.getAllByRole("button", { name: /Block 1/ })).toHaveLength(1);+ expect(screen.getAllByRole("button", { name: /Block 2/ })).toHaveLength(1);+ });++ const titledFailedRun = (): TurnNarrativeState => ({+ ...EMPTY_NARRATIVE,+ turnId: "turn-1",+ turnIndex: 0,+ designStarted: true,+ designEnded: true,+ terminal: "response",+ blocks: [+ runningBlock({+ workflowRunBlockId: "wrb_a",+ label: "sign_in",+ state: "completed",+ startedAt: null,+ }),+ runningBlock({+ workflowRunBlockId: "wrb_b",+ label: "download_latest_pdf",+ state: "failed",+ startedAt: null,+ }),+ ],+ designActivity: [+ activityEntry({+ id: "tr-look",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "Opened the portal",+ success: true,+ }),+ activityEntry({+ id: "tr-run",+ kind: "tool_result",+ toolName: "run_blocks_and_collect_debug",+ text: "download_latest_pdf timed out",+ success: false,+ iteration: 1,+ }),+ activityEntry({+ id: "n-run",+ kind: "narration",+ text: "Running both blocks against the live portal.",+ iteration: 1,+ activeLabel: "Testing the workflow end to end",+ }),+ ],+ });++ it("a failed block stays named on the collapsed step and on the folded turn", () => {+ render(<NarrativeView turn={titledFailedRun()} />);+ // The turn's fold says which block the newest test left failing.expect(- screen.getAllByRole("button", { name: /Block 1/ }).length,- ).toBeGreaterThan(0);+ visibleText(screen.getByRole("button", { name: /^Worked through/ })),+ ).toBe(+ "Worked through 2 steps · 1 failed test · Download Latest Pdf failed",+ );++ openFold();+ const runLine = stepLines()[1]!;+ expect(runLine.getAttribute("aria-expanded")).toBe("false");+ expect(visibleText(runLine)).toBe(+ "Tested the workflow · attempt failed · Download Latest Pdf failed",+ );+ // Attempt failures keep the neutral timeline palette on the line.+ expect(runLine.innerHTML).not.toContain("rose");+ expect(screen.queryByText("Test passed")).toBeNull();+ });++ it("a fixed turn says so and names nothing it no longer fails", () => {+ const turn = titledFailedRun();+ turn.turnFacts = {+ factsAvailable: true,+ authoredBlockCount: 2,+ matchingSourceBlockCount: 2,+ evaluationState: "demonstrated",+ runId: "wr_1",+ runCompleted: true,+ terminalCause: null,+ blocksRunThisTurn: 2,+ ranCleanOnCurrentSource: true,+ };+ render(<NarrativeView turn={turn} />);expect(- screen.getAllByRole("button", { name: /Block 2/ }).length,- ).toBeGreaterThan(0);+ visibleText(screen.getByRole("button", { name: /^Worked through/ })),+ ).toBe("Worked through 2 steps · 1 failed test, fixed");});it("an evidence-free drafted block never renders", () => {@@ -521,8 +616,9 @@ describe("NarrativeView — activity log", () => {}),];render(<NarrativeView turn={turn} />);+ openFold();expect(screen.queryByText("Block 2")).toBeNull();- expect(screen.getByText("Testing workflow")).toBeTruthy();+ expect(stepLines()).toHaveLength(3);});it("filters evidence-free blocks from the fallback projection", () => {@@ -583,19 +679,12 @@ describe("NarrativeView — activity log", () => {],};- const { container, rerender } = render(<NarrativeView turn={turn} />);- const liveRow = screen.getByRole("button", {- name: /Searching the catalogue/,- expanded: true,- });- expect(liveRow).toBeTruthy();+ const { rerender } = render(<NarrativeView turn={turn} />);+ expect(stepLines()).toHaveLength(1);expect(screen.queryByRole("button", { name: /Add First Result/ }),).toBeNull();- expect(container.querySelectorAll(".border-l")).toHaveLength(1);- // The newest row still owns focus during a real between-call gap, but a- // contentless draft remains a plain row rather than an empty disclosure.rerender(<NarrativeViewturn={{@@ -613,16 +702,16 @@ describe("NarrativeView — activity log", () => {}}/>,);+ expect(stepLines()).toHaveLength(1);expect(screen.queryByRole("button", { name: /Add First Result/ }),).toBeNull();- expect(container.querySelectorAll(".border-l")).toHaveLength(0);});it("a hand-opened row stays open when a new row goes live, and resets next turn", () => {const { rerender } = render(<NarrativeView turn={twoInFlightTurn()} />);- fireEvent.click(screen.getByRole("button", { expanded: false }));- expect(screen.getByText("Opened the sign-in page")).toBeTruthy();+ fireEvent.click(stepLines()[0]!);+ expect(stepLines()[0]!.getAttribute("aria-expanded")).toBe("true");// Liveness has to actually move, or this cannot tell a surviving click from// one the auto-rule never had a chance to stomp: resolve both open calls so@@ -656,15 +745,16 @@ describe("NarrativeView — activity log", () => {];rerender(<NarrativeView turn={advanced} />);- // The hand-opened row survives the advance...- expect(screen.getByText("Opened the sign-in page")).toBeTruthy();- // ...and the row that just went live is the one the rule opened.- expect(screen.getByText(/Testing workflow/)).toBeTruthy();+ // The hand-opened row survives the advance, and the row that just went+ // live is the newest one.+ const lines = stepLines();+ expect(lines[0]!.getAttribute("aria-expanded")).toBe("true");+ expect(visibleText(lines[lines.length - 1]!)).toBe("Testing the workflow");rerender(<NarrativeView turn={{ ...twoInFlightTurn(), turnId: "turn-2" }} />,);- expect(screen.queryByText("Opened the sign-in page")).toBeNull();+ expect(stepLines()[0]!.getAttribute("aria-expanded")).toBe("false");});it("a still-calling run row is headed by its live line, not a finished block's verdict", () => {@@ -704,21 +794,13 @@ describe("NarrativeView — activity log", () => {};render(<NarrativeView turn={turn} />);- const header = screen.getByRole("button", { expanded: true });- expect(header.textContent).toContain("Testing workflow");- expect(header.textContent).toContain("calling…");- expect(header.textContent).not.toContain("done");- });-- it("the step count folds away while the row is expanded", () => {- render(<NarrativeView turn={groupedBrowseTurn()} />);- expect(screen.queryByText(/3 steps/)).toBeNull();-- fireEvent.click(screen.getByRole("button", { expanded: true }));- expect(screen.getByText(/3 steps/)).toBeTruthy();+ const lines = stepLines();+ const header = lines[lines.length - 1]!;+ expect(header.getAttribute("aria-expanded")).toBe("true");+ expect(visibleText(header)).toBe("Testing the workflow");});- it("a collapsed run row says how many blocks are folded inside it", () => {+ it("a run whose every block passed says so on its line", () => {const finished = (id: string, label: string): BlockState =>runningBlock({workflowRunBlockId: id,@@ -762,18 +844,46 @@ describe("NarrativeView — activity log", () => {],};render(<NarrativeView turn={turn} />);+ openFold();- const rowHolding = screen- .getAllByRole("button")- .find((b) => b.textContent?.includes("Reached the confirmation page"));+ expect(stepLines().map(visibleText)).toEqual([+ "Tested the workflow · attempt failed",+ "1 browser action",+ "Tested the workflow · 2 of 2 passed",+ ]);+ });- // Only the row actually holding cards claims a count; the earlier run row- // stays silent rather than reading as "there might be something here".- expect(rowHolding?.textContent).toContain("· 2 blocks");- expect(screen.getAllByText(/· \d+ blocks?$/)).toHaveLength(1);+ it("does not call a run passed when a block went unevaluated", () => {+ const turn: TurnNarrativeState = {+ ...EMPTY_NARRATIVE,+ turnId: "turn-1",+ turnIndex: 0,+ designStarted: true,+ designEnded: true,+ terminal: "response",+ blocks: [+ runningBlock({+ workflowRunBlockId: "wrb_a",+ label: "open_statement",+ state: "completed",+ startedAt: null,+ outcome: "not_evaluated",+ }),+ ],+ designActivity: [+ activityEntry({+ id: "tr-1",+ kind: "tool_result",+ toolName: "update_and_run_blocks",+ text: "Ran the draft",+ success: true,+ }),+ ],+ };+ render(<NarrativeView turn={turn} />);- fireEvent.click(rowHolding!);- expect(screen.queryByText(/· \d+ blocks?$/)).toBeNull();+ const lines = stepLines().map(visibleText);+ expect(lines).toEqual(["Tested the workflow"]);});it("a block whose run row was evicted still renders inside a row at Done", () => {@@ -798,10 +908,13 @@ describe("NarrativeView — activity log", () => {],};render(<NarrativeView turn={turn} />);+ openFold();- const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);- expect(gutter.map((g) => g.textContent)).toEqual(["⟨⟩", "▷"]);- expect(screen.queryAllByRole("button", { expanded: true })).toHaveLength(0);+ expect(document.querySelectorAll("[data-activity-row-id]")).toHaveLength(2);+ expect(screen.getByTitle(/Highlight block_1/)).toBeTruthy();+ expect(+ stepLines().map((line) => line.getAttribute("aria-expanded")),+ ).toEqual(["false"]);});const failedRunTurn = (): TurnNarrativeState => ({@@ -834,13 +947,13 @@ describe("NarrativeView — activity log", () => {it("clicking the live row folds it instead of pinning it open", () => {render(<NarrativeView turn={twoInFlightTurn()} />);- const live = screen.getByRole("button", { expanded: true });+ const live = stepLines()[2]!;fireEvent.click(live);- expect(screen.queryAllByRole("button", { expanded: true })).toHaveLength(0);+ expect(live.getAttribute("aria-expanded")).toBe("false");});- it("a finished run row is one line, not a line plus a summary", () => {+ it("a one-step finished turn is not folded, and its block opens to its steps", () => {const turn = failedRunTurn();turn.blocks = [runningBlock({@@ -860,14 +973,17 @@ describe("NarrativeView — activity log", () => {}),];render(<NarrativeView turn={turn} />);+ expect(+ screen.queryByRole("button", { name: /^Worked through/ }),+ ).toBeNull();expect(screen.queryByText("Clicked the download link")).toBeNull();+ fireEvent.click(stepLines()[0]!);fireEvent.click(screen.getByTitle(/Highlight download_block/));expect(screen.getByText("Clicked the download link")).toBeTruthy();});it("the live run row is already open when its block lands", () => {- // The in-flight call has nothing to show yet, so the row is a plain line.const inFlight: TurnNarrativeState = {...EMPTY_NARRATIVE,turnId: "turn-1",@@ -885,8 +1001,7 @@ describe("NarrativeView — activity log", () => {],};const { rerender } = render(<NarrativeView turn={inFlight} />);- expect(screen.queryAllByRole("button")).toHaveLength(0);- expect(screen.getByText(/Testing workflow/)).toBeTruthy();+ expect(stepLines()[0]!.getAttribute("aria-expanded")).toBe("true");// Once the block dispatches it anchors to that same row, and the row must// already be open — no click — or the running block card renders folded.@@ -897,7 +1012,8 @@ describe("NarrativeView — activity log", () => {],};rerender(<NarrativeView turn={withBlock} />);- expect(screen.getByRole("button", { expanded: true })).toBeTruthy();+ expect(stepLines()[0]!.getAttribute("aria-expanded")).toBe("true");+ expect(screen.getByTitle(/Highlight download_block/)).toBeTruthy();});it("a live row with one step renders that step once", () => {@@ -917,10 +1033,11 @@ describe("NarrativeView — activity log", () => {],};render(<NarrativeView turn={turn} />);+ expect(stepLines().map(visibleText)).toEqual(["1 browser action"]);expect(screen.queryAllByText(/Opening page/)).toHaveLength(1);});- it("uses the narrator's intent for a failed row and keeps the exact error in its detail", () => {+ it("names a failed row by its calls and keeps the exact error in its detail", () => {render(<NarrativeViewturn={{@@ -945,7 +1062,6 @@ describe("NarrativeView — activity log", () => {text: REASON,iteration: 0,activeLabel: "Running it",- outcomeLabel: "Ran it - everything passed",}),activityEntry({id: "tr-next",@@ -963,8 +1079,11 @@ describe("NarrativeView — activity log", () => {// The outcome label is a stale prediction on failure. The collapsed row// keeps the trustworthy intent, while the exact server error remains// available one level deeper instead of becoming the primary headline.- expect(screen.getByText("Running it")).toBeTruthy();- expect(screen.getByText(/attempt failed/).className).not.toContain("rose");+ const failedLine = stepLines()[0]!;+ expect(visibleText(failedLine)).toBe(+ "Tested the workflow · attempt failed",+ );+ expect(failedLine.innerHTML).not.toContain("rose");expect(screen.queryByText("The submit button stayed disabled after filling the form",@@ -972,7 +1091,7 @@ describe("NarrativeView — activity log", () => {).toBeNull();expect(screen.queryByText("Ran it - everything passed")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: /Running it/ }));+ fireEvent.click(failedLine);expect(screen.getByText("The submit button stayed disabled after filling the form",@@ -1005,12 +1124,11 @@ describe("NarrativeView — activity log", () => {/>,);- expect(- screen.getByText("Restoring access to the certification results")- .className,- ).not.toContain("rose");- expect(screen.getByText(/attempt failed/).className).not.toContain("rose");- expect(screen.getAllByText(/2 attempts/).length).toBeGreaterThan(0);+ const line = stepLines()[0]!;+ expect(visibleText(line)).toBe(+ "1 browser action · attempt failed · ↻ 2 attempts",+ );+ expect(line.innerHTML).not.toContain("rose");});});@@ -1232,9 +1350,10 @@ describe("NarrativeView — code write diffs", () => {expect(container.querySelector('[aria-expanded="true"]')).toBeNull();expect(screen.queryByRole("button", { name: "hide diff" })).toBeNull();expect(screen.queryByText("+await page.wait_for_timeout(500)")).toBeNull();+ // The row the reader was on folds with the turn, so focus lands on the fold.await waitFor(() =>expect(document.activeElement).toBe(- screen.getByRole("button", { name: /Repaired the download step/ }),+ screen.getByRole("button", { name: /^Worked through/ }),),);});@@ -1252,7 +1371,7 @@ describe("NarrativeView — code write diffs", () => {await waitFor(() =>expect(document.activeElement).toBe(- screen.getByRole("button", { name: /Repaired the download step/ }),+ screen.getByRole("button", { name: /^Worked through/ }),),);});@@ -1405,9 +1524,7 @@ describe("NarrativeView — code write diffs", () => {it("does not show the faded peek when the user manually re-opens a row", () => {const { container } = render(<NarrativeView turn={twoWriteTurn()} />);- const currentRow = screen.getByRole("button", {- name: /Repaired the download step/,- });+ const currentRow = stepLines()[1]!;expect(container.querySelector("[data-code-diff-peek]")).toBeTruthy();fireEvent.click(currentRow);@@ -1420,9 +1537,7 @@ describe("NarrativeView — code write diffs", () => {it("a historical write reveals its patch only after the row and diff are opened", () => {render(<NarrativeView turn={twoWriteTurn()} />);- fireEvent.click(- screen.getAllByRole("button", { name: /Saved and ran/ })[0]!,- );+ fireEvent.click(stepLines()[0]!);expect(screen.queryByText("-await page.click('#a')")).toBeNull();expect(screen.getAllByRole("button", { name: "view diff" }).length).toBe(1);@@ -1433,15 +1548,14 @@ describe("NarrativeView — code write diffs", () => {it("keeps collapsed diff counts quiet while preserving patch syntax colors", () => {render(<NarrativeView turn={twoWriteTurn({ terminal: "response" })} />);+ openFold();const addedCount = screen.getByText("+4");const removedCount = screen.getByText("−2");expect(addedCount.className).not.toContain("emerald");expect(removedCount.className).not.toContain("rose");- fireEvent.click(- screen.getAllByRole("button", { name: /Saved and ran/ })[0]!,- );+ fireEvent.click(stepLines()[0]!);fireEvent.click(screen.getAllByRole("button", { name: "view diff" })[0]!);expect(screen.getByText("-await page.click('#a')").className).toContain("rose",@@ -1455,6 +1569,7 @@ describe("NarrativeView — code write diffs", () => {const { container } = render(<NarrativeView turn={twoWriteTurn({ terminal: "response" })} />,);+ openFold();expect(container.querySelector("[data-code-diff-peek]")).toBeNull();expect(screen.queryByText("+await page.wait_for_timeout(500)")).toBeNull();@@ -1462,14 +1577,12 @@ describe("NarrativeView — code write diffs", () => {expect(screen.getByText("+4")).toBeTruthy();expect(screen.queryByRole("button", { name: "view diff" })).toBeNull();- fireEvent.click(- screen.getAllByRole("button", { name: /Saved and ran/ })[0]!,- );+ fireEvent.click(stepLines()[0]!);fireEvent.click(screen.getAllByRole("button", { name: "view diff" })[0]!);expect(screen.getByText("-await page.click('#a')")).toBeTruthy();});- it("a payload without the new keys renders today's label card", () => {+ it("a payload without the new keys renders its steps without counts", () => {const turn = twoWriteTurn({ terminal: "response" });const legacy = {...turn,@@ -1479,8 +1592,12 @@ describe("NarrativeView — code write diffs", () => {}),};render(<NarrativeView turn={legacy} />);+ openFold();- expect(screen.getByText("Saved and ran the download step")).toBeTruthy();+ expect(stepLines().map(visibleText)).toEqual([+ "Tested the workflow",+ "Tested the workflow",+ ]);expect(screen.queryByText("+4")).toBeNull();expect(screen.queryByText(/view diff/)).toBeNull();expect(screen.queryByText("-await page.click('#a')")).toBeNull();@@ -1509,9 +1626,7 @@ describe("NarrativeView — code write diffs", () => {expect(screen.getByText("+4")).toBeTruthy();expect(screen.getByText("−2")).toBeTruthy();- fireEvent.click(- screen.getAllByRole("button", { name: /Saved and ran/ })[0]!,- );+ fireEvent.click(stepLines()[0]!);const toggle = screen.getByRole("button", { name: "view diff" });expect(toggle.hasAttribute("disabled")).toBe(true);expect(screen.queryByText("-await page.click('#a')")).toBeNull();@@ -1548,9 +1663,7 @@ describe("NarrativeView — code write diffs", () => {expect(screen.getByText("+4")).toBeTruthy();expect(screen.getByText("−2")).toBeTruthy();- fireEvent.click(- screen.getAllByRole("button", { name: /Saved and ran/ })[0]!,- );+ fireEvent.click(stepLines()[0]!);fireEvent.click(screen.getByRole("button", { name: "view diff" }));expect(screen.getByText("-await page.click('#a')")).toBeTruthy();});diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.instantAck.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.instantAck.test.tsxdeleted file mode 100644index e4f4ed2ff..000000000--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.instantAck.test.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { act, cleanup, render, screen } from "@testing-library/react";-import { afterEach, expect, it, vi } from "vitest";--import {- ACK_ROTATE_INTERVAL_MS,- COPILOT_ACK_LINES,- InstantAckPlaceholder,-} from "./NarrativeView";--afterEach(() => {- cleanup();- vi.useRealTimers();- vi.restoreAllMocks();-});--it("renders and rotates the instant acknowledgement", () => {- vi.useFakeTimers();- vi.spyOn(Math, "random").mockReturnValue(0); // deterministic start = line 0- render(<InstantAckPlaceholder />);-- expect(screen.getByRole("status")).toBeTruthy();- expect(screen.getByText(COPILOT_ACK_LINES[0])).toBeTruthy();-- act(() => vi.advanceTimersByTime(ACK_ROTATE_INTERVAL_MS));-- expect(screen.getByText(COPILOT_ACK_LINES[1])).toBeTruthy();- expect(screen.queryByText(COPILOT_ACK_LINES[0])).toBeNull();-});diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsxindex 052dd6f5e..604958766 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx@@ -312,6 +312,6 @@ describe("NarrativeView drafting row (codegen_progress)", () => {});rerender(<NarrativeView turn={reloaded!} />);expect(draftingRow()).toBeNull();- expect(screen.getByText("Wrote the workflow code")).toBeTruthy();+ expect(screen.getByText("Tested the workflow")).toBeTruthy();});});diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsxindex c07685101..080352769 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx@@ -1,12 +1,6 @@// @vitest-environment jsdom-import {- act,- cleanup,- fireEvent,- render,- screen,-} from "@testing-library/react";+import { act, cleanup, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { NarrativeView } from "./NarrativeView";@@ -183,7 +177,7 @@ const narrationTurn = (startedAt: "2026-06-10T00:00:00Z",});-const clamped = () => document.querySelector('[data-testid="copilot-reason"]');+const reason = () => document.querySelector('[data-testid="copilot-reason"]');const caret = () =>document.querySelector('[data-testid="copilot-reason"] > span[aria-hidden="true"]',@@ -209,7 +203,7 @@ describe("NarrativeView — narration reveal", () => {expect(hidden()!.textContent).toBe("");expect(caret()!.className).toContain("opacity-0");- expect(clamped()!.textContent).toContain(REASON);+ expect(reason()!.textContent).toContain(REASON);});it("renders a narration with no arrival stamp complete on first render", () => {@@ -221,37 +215,10 @@ describe("NarrativeView — narration reveal", () => {expect(hidden()!.textContent).toBe("");expect(caret()!.className).toContain("opacity-0");- expect(clamped()!.textContent).toContain(REASON);- });-- it("clamps the narration to four lines rather than growing the row", () => {- render(- <NarrativeView- turn={narrationTurn([toolCall("1", 1), narration(1, undefined)])}- />,- );-- expect(clamped()).toBeTruthy();- expect(clamped()!.textContent).toContain(REASON);+ expect(reason()!.textContent).toContain(REASON);});- it("holds the truncation ellipsis until the reveal finishes", () => {- render(- <NarrativeView- turn={narrationTurn([toolCall("1", 1), narration(1, NOW - 500)])}- />,- );-- expect(clamped()!.className).not.toContain("line-clamp-4");-- act(() => {- vi.advanceTimersByTime(60_000);- });-- expect(clamped()!.className).toContain("line-clamp-4");- });-- it("loses nothing when its owner row is closed and opened after the reveal window", () => {+ it("keeps a step's sentence above it once a later step starts", () => {render(<NarrativeViewturn={narrationTurn([@@ -263,15 +230,14 @@ describe("NarrativeView — narration reveal", () => {/>,);- expect(clamped()).toBeNull();-act(() => {vi.advanceTimersByTime(60_000);});- fireEvent.click(screen.getByRole("button", { name: /Tool 1 finished/ }));expect(hidden()!.textContent).toBe("");expect(caret()!.className).toContain("opacity-0");- expect(clamped()!.textContent).toContain(REASON);+ expect(reason()!.textContent).toContain(REASON);+ // The whole sentence wraps; nothing cuts it to an ellipsis.+ expect(reason()!.className).not.toContain("line-clamp");});});diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsxindex 971dae4f5..9aff3a33f 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx@@ -1,4 +1,16 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ ChevronRightIcon,+ CodeIcon,+ Cross2Icon,+ DotsHorizontalIcon,+ GlobeIcon,+ ListBulletIcon,+ LockClosedIcon,+ PlayIcon,+ ReaderIcon,+ StopIcon,+} from "@radix-ui/react-icons";import {REVEAL_MS_PER_CHAR,buildRevealOffsets,@@ -8,12 +20,18 @@ import {import { humanizeBlockLabel } from "./blockLabel";import { CopilotMarkdown } from "./CopilotMarkdown";import {- ACTIVITY_KIND_GLYPH,ACTIVITY_KIND_WORD,ActivityLog,ActivityRow as ActivityRowModel,+ FinishedTurnSummary,+ callLabel,+ callRollup,+ condenseCalls,deriveActivityLog,+ failedRowBlocks,+ passedBlockCount,rowIndexOfToolCall,+ summarizeFinishedTurn,} from "./copilotActivityLog";import { TURN_ROW_INSET, TURN_ROW_OUTSET } from "./cards/cardLayout";import { showPhaseChecklist } from "./copilotPhases";@@ -21,7 +39,9 @@ import { CodeWriteDiff } from "./workflowCopilotTypes";import {ActivityEntry,BlockState,+ BudgetExpiryState,RecordedActionSummary,+ ToolCallKind,TurnNarrativeState,formatElapsed,humanizeJudgeText,@@ -30,11 +50,12 @@ import {isInterimOutcome,notConfirmedOutcome,parseUtcIsoMs,+ toolCallIdOf,terminalNarrativeText,toolActivityDisplayLabel,+ toolCallKind,} from "./narrativeState";import { useShimmerText } from "../workflowRun/useShimmerText";-import { useThemeAsDarkOrLight } from "../../../components/useThemeAsDarkOrLight";// Row flashes green/red for 600ms once revealed — must match the tailwind// copilot-row-flash-* animation duration.@@ -63,6 +84,33 @@ function truncateOutcomeReason(reason: string): string {return `${slice}...`;}+// What a collapsed line says about a block whose run did not confirm its+// outcome, or null when there is nothing to say.+function collapsedOutcomeNote(+ block: BlockState,+ ownsOutcomeNotConfirmed: boolean,+ outcomeReasonFallback: string | null | undefined,+): string | null {+ const completed = block.state === "completed";+ const notShown =+ completed &&+ block.outcome === "not_demonstrated" &&+ !isInterimOutcome(block.outcomeRole);+ const reason =+ notShown || ownsOutcomeNotConfirmed+ ? normalizeOutcomeReason(block.outcomeReason ?? outcomeReasonFallback)+ : null;+ if (notShown) {+ return `Outcome not confirmed — ${OUTCOME_NOT_CONFIRMED_REASON}${+ reason ? `: ${truncateOutcomeReason(reason)}` : "."+ }`;+ }+ if (ownsOutcomeNotConfirmed && reason !== null) {+ return `Outcome not confirmed — ${truncateOutcomeReason(reason)}`;+ }+ return null;+}+function notConfirmedDisplayReason(turn: TurnNarrativeState): string | null {return normalizeOutcomeReason(notConfirmedOutcome(turn)?.displayReason);}@@ -257,13 +305,10 @@ function AttemptsBadge({ attempts }: { attempts?: number }) {);}-// The activity log's row, one grid for every kind of work: a single gutter-// glyph, the sentence, and the elapsed column. Status rides inline at the end-// of the sentence rather than as a second glyph column, so a block row and a-// step row sit on the same rails.+// A block's line inside the activity log: a gutter glyph, the block's name, and+// a trailing disclosure. Status rides inline at the end of the name.function FLogLine({glyph,- kindWord,children,trailing,onClick,@@ -271,7 +316,6 @@ function FLogLine({title,}: {glyph: React.ReactNode;- kindWord?: string;children: React.ReactNode;trailing?: React.ReactNode;onClick?: () => void;@@ -293,9 +337,6 @@ function FLogLine({{glyph}</span><span className="min-w-0 text-left text-[12.5px] leading-[1.5] text-muted-foreground dark:text-slate-400">- {kindWord === undefined ? null : (- <span className="sr-only">{kindWord} · </span>- )}{children}</span><span className="whitespace-nowrap font-mono text-[10.5px] tabular-nums text-muted-foreground dark:text-slate-500">@@ -320,62 +361,7 @@ function FLogLine({);}-// The sentence an entry contributes, without the glyph column. The log's row-// renders it inline so status can ride at the end; a nested sub-row wraps the-// same content in its own glyph gutter.-function entryLine(- entry: ActivityEntry,- title?: string | null,-): { content: React.ReactNode } {- if (entry.kind === "narration") {- return { content: <span className="italic">{entry.text}</span> };- }- if (entry.kind === "tool_call") {- return {- content: (- <>- <span>- {title ??- entry.displayLabel ??- toolActivityDisplayLabel(entry.toolName)}- </span>- <span className="text-muted-foreground dark:text-slate-500">- {" "}- · calling…- </span>- <AttemptsBadge attempts={entry.attempts} />- </>- ),- };- }- const ok = entry.success !== false;- const label =- title ?? entry.displayLabel ?? toolActivityDisplayLabel(entry.toolName);- return {- content: (- <>- <span>{ok ? (title ?? entry.text) : label}</span>- {!ok ? (- <span className="text-muted-foreground dark:text-slate-500">- {" "}- · attempt failed- </span>- ) : null}- <AttemptsBadge attempts={entry.attempts} />- </>- ),- };-}--function ActivityRow({- entry,- title,-}: {- entry: ActivityEntry;- // Narrator-authored title for the row this entry heads. Falls through to the- // tool-derived label when the narrator never spoke for the step.- title?: string | null;-}) {+function ActivityRow({ entry }: { entry: ActivityEntry }) {if (entry.kind === "narration") {return (<FSubRow@@ -390,7 +376,7 @@ function ActivityRow({}if (entry.kind === "tool_call") {const label =- title ?? entry.displayLabel ?? toolActivityDisplayLabel(entry.toolName);+ entry.displayLabel ?? toolActivityDisplayLabel(entry.toolName);return (<FSubRow glyph="▸" glyphClass="text-muted-foreground"><span className="text-foreground dark:text-slate-200">{label}</span>@@ -419,7 +405,7 @@ function ActivityRow({: "text-rose-700 dark:text-rose-200"}>- {ok ? (title ?? entry.text) : entry.text}+ {entry.text}</span><AttemptsBadge attempts={entry.attempts} /></FSubRow>@@ -513,27 +499,15 @@ interface FBlockRunProps {onSelect?: (label: string) => void;outcomeReasonFallback?: string | null;ownsOutcomeNotConfirmed?: boolean;- // 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.flat?: boolean;- // Supplied when the log's row already names the kind of work. The block's- // own state then rides inline as a mark instead of taking the gutter.- rowGlyph?: React.ReactNode;- rowKindWord?: string;- rowTrailing?: React.ReactNode;- rowDiffCounts?: { added: number; removed: number };// When the activity log owns this card's row, open/closed comes from there// so the row and the card never disagree about a single click.expansion?: { open: boolean; onToggle: () => void };// Historical failed attempts stay quiet in the collapsed timeline. Their// full failure treatment remains available in the expanded evidence.quietFailure?: boolean;- // Activity-log context that should lead the block's own run evidence.- detailBeforeBlock?: React.ReactNode;- detailAfterBlock?: React.ReactNode;}function FBlockRun({@@ -542,18 +516,11 @@ function FBlockRun({onSelect,outcomeReasonFallback,ownsOutcomeNotConfirmed,- rowTitle,flat,- rowGlyph,- rowKindWord,- rowTrailing,- rowDiffCounts,expansion,quietFailure,- detailBeforeBlock,- detailAfterBlock,}: FBlockRunProps) {- const displayLabel = rowTitle ?? humanizeBlockLabel(block.label);+ const displayLabel = humanizeBlockLabel(block.label);const palette = paletteFor(block.blockType);const isRunning = block.state === "running";const isCompleted = block.state === "completed";@@ -653,15 +620,12 @@ function FBlockRun({// the activity log `expansion` supplies the open state and none of this// applies — there, every finished row folds, a failure included.const hasExpandableDetail =- detailBeforeBlock !== null && detailBeforeBlock !== undefined- ? true- : isRunning ||- block.activity.length > 0 ||- hasActions ||- isFail ||- isOutcomeNotShown ||- ownsOutcomeReason ||- (detailAfterBlock !== null && detailAfterBlock !== undefined);+ isRunning ||+ block.activity.length > 0 ||+ hasActions ||+ isFail ||+ isOutcomeNotShown ||+ ownsOutcomeReason;const toggleable =hasExpandableDetail &&(expansion !== undefined ||@@ -768,7 +732,6 @@ function FBlockRun({const blockDetail = (<div className="flex flex-col gap-1.5 border-l border-border/60 py-1.5 pl-3">- {detailBeforeBlock}{isRunning ? (<span className="inline-flex w-fit items-center gap-1.5 rounded-full border border-blue-400/40 bg-blue-500/10 px-2 py-0.5 text-[11px] font-semibold text-blue-700 dark:text-blue-300"><span className="h-[5px] w-[5px] animate-pulse rounded-full bg-blue-400" />@@ -825,7 +788,6 @@ function FBlockRun({</div></div>) : null}- {detailAfterBlock}</div>);@@ -833,33 +795,14 @@ function FBlockRun({return (<div className="flex flex-col"><FLogLine- glyph={rowGlyph ?? <span className={accentText}>{stateGlyph}</span>}- kindWord={rowKindWord}- trailing={- <>- {elapsed ?? rowTrailing}- {toggleable ? (open ? " ⌄" : " ›") : null}- </>- }+ glyph={<span className={accentText}>{stateGlyph}</span>}+ trailing={toggleable ? <Chevron open={open} /> : null}onClick={onHeaderClick}expanded={toggleable && expansion ? open : undefined}title={`Highlight ${block.label} on canvas`}>{displayLabel}- {rowGlyph === undefined ? null : (- <span className={accentText} aria-hidden="true">- {" "}- {stateGlyph}- </span>- )}<span className="sr-only">{` · ${stateWord}`}</span>- {rowDiffCounts === undefined ? null : (- <span className="font-mono tabular-nums text-muted-foreground dark:text-slate-500">- <span>{" · "}</span>- <span>{`+${rowDiffCounts.added}`}</span>- <span className="pl-1">{`−${rowDiffCounts.removed}`}</span>- </span>- )}</FLogLine><div className="pl-[28px]">{collapsedExtras}</div>{open && hasExpandableDetail ? (@@ -1007,54 +950,16 @@ function FDesignRow({ done, blockLabels, activity }: FDesignRowProps) {);}-export const COPILOT_ACK_LINES = [- "Reading your request…",- "Getting oriented…",- "Sketching a plan…",- "Lining up the steps…",- "Thinking it through…",-] as const;--export const ACK_ROTATE_INTERVAL_MS = 3000;--// Fills the send→first-frame gap with a rotating shimmer so the build never starts on dead air.-// The first real narrative replaces it immediately; it never persists to history.+// Fills the send→first-event gap with one quiet line; the first step replaces it.export function InstantAckPlaceholder() {- // Random start so quick repeated sends (a gap near the rotation cadence)- // don't always open on the same line.- const [index, setIndex] = useState(() =>- Math.floor(Math.random() * COPILOT_ACK_LINES.length),- );- useEffect(() => {- const id = setInterval(- () => setIndex((i) => (i + 1) % COPILOT_ACK_LINES.length),- ACK_ROTATE_INTERVAL_MS,- );- return () => clearInterval(id);- }, []);- // Shimmer paints the text with a white gradient, which vanishes on the- // near-white light surface — restrict it to dark, where the base- // text-muted-foreground stays readable on its own.- const isDark = useThemeAsDarkOrLight() === "dark";- const shimmerRef = useShimmerText<HTMLSpanElement>(isDark);- const line = COPILOT_ACK_LINES[index];return (- <div className="flex items-center gap-3 px-1 py-1" role="status">+ <p+ role="status"+ className="mt-2 text-[13px] leading-[1.55] text-muted-foreground"+ ><span className="sr-only">Copilot is working on your request…</span>- <span- className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-sky-400/60 bg-sky-500/15"- aria-hidden="true"- >- <Spinner />- </span>- <span- ref={shimmerRef}- aria-hidden="true"- className="text-[12.5px] font-medium text-muted-foreground"- >- {line}- </span>- </div>+ <span aria-hidden="true">Working…</span>+ </p>);}@@ -1065,6 +970,7 @@ interface FActivityLogProps {onBlockSelect?: (label: string) => void;interactionRef?: { current: string | null };anchoredAfterRow?: ReadonlyMap<string, AnchoredTurnItem[]>;+ anchoredBeforeRows?: AnchoredTurnItem[];}// The kind gutter sits to the left of ActivityRow's own status column, so a@@ -1172,6 +1078,160 @@ function FCodeWriteDiff({);}+const CALL_KIND_ICON: Record<ToolCallKind, typeof GlobeIcon> = {+ browser: GlobeIcon,+ credential: LockClosedIcon,+ plan: ListBulletIcon,+ guidance: ReaderIcon,+ write: CodeIcon,+ run: PlayIcon,+ other: DotsHorizontalIcon,+};++const STEP_TEXT = "text-foreground/75";+// The no-break space binds each "·" to the item before it, so a wrapped tail never starts a line with one.+const SEP = "\u00a0· ";++function Chevron({ open }: { open: boolean }) {+ return (+ <ChevronRightIcon+ aria-hidden="true"+ className={`size-3 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none ${+ open ? "rotate-90" : ""+ }`}+ />+ );+}++function FDetailBox({ children }: { children: React.ReactNode }) {+ return (+ <div className="mb-1.5 ml-[18px] mt-[3px] flex flex-col gap-1 rounded-lg border border-border bg-muted/40 px-[9px] py-[7px]">+ {children}+ </div>+ );+}++function DiffCounts({ added, removed }: { added: number; removed: number }) {+ return (+ <span className="whitespace-nowrap font-mono text-[11px] tabular-nums text-muted-foreground">+ {`+${added}`}+ <span className="pl-1">{`−${removed}`}</span>+ </span>+ );+}++// A failed block stays named on the collapsed line, in the neutral timeline+// palette; its exact error keeps the rose treatment inside the expansion.+function FFailurePin({ block }: { block: BlockState }) {+ return (+ <span+ className={`inline-flex items-center gap-1 whitespace-nowrap ${STEP_TEXT}`}+ >+ <Cross2Icon aria-hidden="true" className="size-3 text-muted-foreground" />+ <span title={block.label}>{humanizeBlockLabel(block.label)}</span>+ {/* A flex gap is not text, so copied or spoken text needs the space. */}{" "}+ <span className="text-muted-foreground">failed</span>+ </span>+ );+}++// One call in an expanded step. A result reads inline beside the call and+// opens to its full text; an error opens as its own box.+function FCallItem({+ entry,+ count,+ detail,+ inlineResult,+ defaultOpen,+ evidence,+ turnEnded,+}: {+ entry: ActivityEntry;+ count: number;+ detail: React.ReactNode | null;+ inlineResult: string | null;+ defaultOpen: boolean;+ evidence?: React.ReactNode;+ turnEnded: boolean;+}) {+ const [userOpen, setUserOpen] = useState<boolean | null>(null);+ const expandable = detail !== null || inlineResult !== null;+ const open = expandable && (userOpen ?? defaultOpen);+ const Icon =+ CALL_KIND_ICON[+ entry.toolName === undefined ? "other" : toolCallKind(entry.toolName)+ ];+ const failed = entry.kind === "tool_result" && entry.success === false;+ // A cancelled turn can end with a call that never got its result.+ const pending = entry.kind === "tool_call" && !turnEnded;+ const diffs = entry.codeDiffs ?? [];+ const lineClass = `flex w-full min-w-0 items-center gap-1.5 py-px text-left text-[12px] leading-[1.5] ${STEP_TEXT}`;+ const inner = (+ <>+ {expandable ? <Chevron open={open} /> : null}+ <Icon+ aria-hidden="true"+ className="size-3 shrink-0 text-muted-foreground"+ />+ <span className="min-w-0 break-words">+ {callLabel(entry)}+ {count > 1 ? (+ <span className="text-muted-foreground">{` ×${count}`}</span>+ ) : null}+ {failed ? (+ <span className="text-muted-foreground"> · attempt failed</span>+ ) : null}+ <AttemptsBadge attempts={entry.attempts} />+ </span>+ {/* Shown beside the label until opened, then in full below it; the+ button's name stays the call, not its result. */}+ {inlineResult === null || open ? null : (+ <span+ aria-hidden="true"+ className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground"+ >+ {inlineResult}+ </span>+ )}+ {diffs.length === 0 ? null : (+ <DiffCounts+ added={diffs.reduce((n, d) => n + d.added, 0)}+ removed={diffs.reduce((n, d) => n + d.removed, 0)}+ />+ )}+ {pending ? (+ <>+ <Spinner small />+ <span className="sr-only">calling</span>+ </>+ ) : null}+ </>+ );+ return (+ <li>+ {!expandable ? (+ <div className={`${lineClass} pl-[18px]`}>{inner}</div>+ ) : (+ <button+ type="button"+ aria-expanded={open}+ className={`${lineClass} hover:text-foreground`}+ onClick={() => setUserOpen(!open)}+ >+ {inner}+ </button>+ )}+ {open && inlineResult !== null ? (+ <p className="mb-0.5 ml-[36px] whitespace-pre-wrap break-words font-mono text-[11px] leading-[1.5] text-muted-foreground">+ {inlineResult}+ </p>+ ) : null}+ {evidence}+ {open && detail !== null ? <FDetailBox>{detail}</FDetailBox> : null}+ </li>+ );+}+function FActivityLogRow({row,open,@@ -1196,48 +1256,6 @@ function FActivityLogRow({outcomeOwnerKey?: string | null;}) {const last = row.entries[row.entries.length - 1];- // A lone run card becomes the row itself, so the collapsed line keeps the- // block's own verdict rather than the run tool's flag, which can disagree.- // Unless the row is still calling and that block already finished: it is an- // earlier run's card, and its verdict would read as this row's status.- const only = row.blocks.length === 1 ? row.blocks[0] : undefined;- const soloBlock =- row.pending && only !== undefined && only.state !== "running"- ? undefined- : only;- const exactFailure =- last?.kind === "tool_result" && last.success === false ? last : null;- const hasDetail =- row.blocks.length > 0 ||- row.entries.length > 1 ||- row.codeDiffs.length > 0 ||- row.reason !== null ||- exactFailure !== null;- // Body content is whatever the line does not already show: a solo block's- // line is the card, so its tool entries stay represented by the block's own- // evidence; otherwise the line is the last entry and the body carries the- // ones before it.- const bodyEntries = soloBlock ? [] : row.entries.slice(0, -1);- const bodyFailures = bodyEntries.filter(- (entry) => entry.kind === "tool_result" && entry.success === false,- );- const bodySteps = bodyEntries.filter(- (entry) => entry.kind !== "tool_result" || entry.success !== false,- );- // The reason is a body child too: a row whose only detail is its reason- // would otherwise render an empty container and hide the prose entirely.- const bodyChildren = soloBlock- ? 0- : bodyEntries.length +- row.blocks.length +- row.codeDiffs.length +- (row.reason === null ? 0 : 1) +- (exactFailure === null ? 0 : 1);- // The collapsed row carries the whole write's delta; per-block identity and- // the patch itself live in the detail. A row folding two writes sums them,- // since one line cannot name both blocks without becoming two.- const rowAdded = row.codeDiffs.reduce((n, d) => n + d.added, 0);- const rowRemoved = row.codeDiffs.reduce((n, d) => n + d.removed, 0);// Time-derived like the recorded-action reveal, so a hydrated row (no// arrival stamp) falls straight through to the full string on first render.const reasonShown =@@ -1246,98 +1264,28 @@ function FActivityLogRow({: revealedCharsAt(row.reason.length, Date.now() - (row.reasonAt ?? 0));const reasonRevealing =row.reason !== null && reasonShown < row.reason.length;- useFrameTick(open && reasonRevealing);-- // A combined write/test row can carry both entries and blocks; prefer the- // step count when there are several tool transitions to summarize.- const foldedSummary =- row.entries.length > 1 && (last?.attempts ?? 1) <= 1- ? `\u00b7 ${row.entries.length} steps`- : row.blocks.length > 0- ? `\u00b7 ${row.blocks.length} ${row.blocks.length === 1 ? "block" : "blocks"}`- : null;-- // While the work is still happening the trailing column is wall time since it- // began; the row's own entry stamps only span what has been recorded, so a- // row with one entry would read 0:00 for as long as the step took. Once the- // row settles it reports the recorded span, and the tick stops with it.- useTick(row.live);- const rowElapsed = row.live- ? liveElapsed(row.startedAt)- : formatElapsed(row.startedAt, row.endedAt);-- const kindGlyph = row.kind === null ? null : ACTIVITY_KIND_GLYPH[row.kind];- const kindWord = row.kind === null ? undefined : ACTIVITY_KIND_WORD[row.kind];-- const lineContent =- soloBlock || last === undefined ? null : entryLine(last, row.label);- // These arrive as the raw authored identifiers (`open_page`), so they get the- // same humanizing every other surface applies — otherwise a block reads- // `open_page` here and "Open Page" in its own card a second later. The- // backend caps its own list at 50; a chat pane this narrow reads about three- // labels to a line, so capping the head keeps already-read text still while- // only the tail counts up.- const draftingLine =- row.draftingLabels === undefined ? null : (- <>- <span>Writing the workflow code</span>- {row.draftingLabels.length === 0 ? null : (- <span className="text-muted-foreground dark:text-slate-500">- {` · ${row.draftingLabels- .slice(0, MAX_DRAFTING_LABELS)- .map(humanizeBlockLabel)- .join(", ")}`}- {row.draftingLabels.length > MAX_DRAFTING_LABELS- ? ` +${row.draftingLabels.length - MAX_DRAFTING_LABELS} more`- : ""}- </span>- )}- </>- );- // A mark reports an outcome, so only a step that returned can carry one — a- // call still in flight has no outcome yet. Beyond that, a browse or write- // step that worked says so in its own sentence, so only a run's result and- // any failure earn a mark of their own.- const settled = last !== undefined && last.kind === "tool_result";- const mark =- soloBlock || !settled- ? null- : last.success !== false && row.kind === "run"- ? "✓"- : null;-+ useFrameTick(reasonRevealing);+ // Every step keeps its whole sentence where it was spoken. While it types out, the rest of+ // the string stays in flow, transparent, so the line never grows and later evidence stays put.const reasonNode =row.reason === null ? null : (- <FSubRow- glyph="✦"- glyphClass="text-sky-700 dark:text-sky-300"- italic- muted+ <p+ data-testid="copilot-reason"+ className="mb-px mt-2 break-words text-[13px] leading-[1.55] text-foreground [overflow-wrap:anywhere] dark:text-slate-200">+ {row.reason.slice(0, reasonShown)}<span- data-testid="copilot-reason"- className={[- "break-words [overflow-wrap:anywhere]",- // The tail keeps the full string in flow so the row never grows,- // while the cap prevents the reveal from moving later evidence.- reasonRevealing- ? "overflow-hidden [max-height:calc(4*1.55em)]"- : "line-clamp-4",- ].join(" ")}+ aria-hidden="true"+ className={reasonRevealing ? "animate-pulse" : "opacity-0"}>- {row.reason.slice(0, reasonShown)}- <span- aria-hidden="true"- className={reasonRevealing ? "animate-pulse" : "opacity-0"}- >- {"\u258c"}- </span>- <span className="text-transparent">- {row.reason.slice(reasonShown)}- </span>+ {"▌"}</span>- </FSubRow>+ <span className="text-transparent">+ {row.reason.slice(reasonShown)}+ </span>+ </p>);+const diffNodes = row.codeDiffs.map((diff) => (<FCodeWriteDiffkey={diff.label}@@ -1347,122 +1295,290 @@ function FActivityLogRow({onToggle={() => onDiffToggle(diff.label)}/>));- const rowFailures = row.entries.filter(- (entry) => entry.kind === "tool_result" && entry.success === false,- );-- const lineNode = soloBlock ? (+ const blockNodes = row.blocks.map((b) => (<FBlockRun- block={soloBlock}+ key={b.workflowRunBlockId || b.label}+ block={b}turnEnded={turnEnded}onSelect={onBlockSelect}outcomeReasonFallback={outcomeReasonFallback}- ownsOutcomeNotConfirmed={blockIdentity(soloBlock) === outcomeOwnerKey}- rowTitle={row.label}+ ownsOutcomeNotConfirmed={blockIdentity(b) === outcomeOwnerKey}flat- rowGlyph={kindGlyph}- rowKindWord={kindWord}- rowTrailing={rowElapsed}- rowDiffCounts={- row.codeDiffs.length === 0- ? undefined- : { added: rowAdded, removed: rowRemoved }- }- expansion={{ open, onToggle }}quietFailure- detailBeforeBlock={- row.reason !== null || diffNodes.length > 0 ? (- <>- {reasonNode}- {diffNodes}- </>- ) : undefined- }- detailAfterBlock={- rowFailures.length > 0 ? (- <>- {rowFailures.map((entry) => (- <ActivityRow key={entry.id} entry={entry} />- ))}- </>- ) : undefined+ expansion={+ row.entries.length === 0 && row.blocks.length === 1+ ? { open, onToggle }+ : undefined}/>- ) : (- <FLogLine- glyph={kindGlyph}- kindWord={kindWord}- trailing={+ ));++ const diffEvidence = (+ <div className="mb-1 ml-[18px] mt-0.5 flex flex-col gap-1">{diffNodes}</div>+ );++ // A block observed with no step of its own keeps its card as the line.+ if (row.entries.length === 0 && row.draftingLabels === undefined) {+ return (+ <div className="flex flex-col">+ {reasonNode}+ {blockNodes}+ {open && diffNodes.length > 0 ? diffEvidence : null}+ </div>+ );+ }++ const failedLast = last?.kind === "tool_result" && last.success === false;+ // The sentence above says why; the line says what the calls were.+ const title = callRollup(row.entries, turnEnded) ?? "Working";+ const failedBlocks = failedRowBlocks(row);+ const passed = passedBlockCount(row);+ const rowAdded = row.codeDiffs.reduce((n, d) => n + d.added, 0);+ const rowRemoved = row.codeDiffs.reduce((n, d) => n + d.removed, 0);+ const kindWord = row.kind === null ? undefined : ACTIVITY_KIND_WORD[row.kind];+ const calls = condenseCalls(row.entries);+ const resultShown = (entry: ActivityEntry) =>+ entry.kind === "tool_result" && entry.text !== callLabel(entry);+ const hasDetail =+ calls.length > 0 || row.blocks.length > 0 || row.codeDiffs.length > 0;++ const lineText = (+ <span+ className={`min-w-0 flex-1 ${row.live ? STEP_TEXT : "text-muted-foreground"}`}+ >+ {kindWord === undefined ? null : (+ <span className="sr-only">{kindWord} · </span>+ )}+ {row.draftingLabels === undefined ? (+ title+ ) : (+ // Raw authored identifiers, humanized like every other surface. Capping+ // the head keeps already-read text still while only the tail counts up.<>- {rowElapsed}- {hasDetail ? (open ? " ⌄" : " ›") : null}+ <span>Writing the workflow code</span>+ {row.draftingLabels.length === 0 ? null : (+ <span className="font-normal text-muted-foreground">+ {` · ${row.draftingLabels+ .slice(0, MAX_DRAFTING_LABELS)+ .map(humanizeBlockLabel)+ .join(", ")}`}+ {row.draftingLabels.length > MAX_DRAFTING_LABELS+ ? ` +${row.draftingLabels.length - MAX_DRAFTING_LABELS} more`+ : ""}+ </span>+ )}</>- }- onClick={hasDetail ? onToggle : undefined}- expanded={hasDetail ? open : undefined}- >- {draftingLine ?? lineContent?.content}- {mark === null ? null : (- <span- className={- mark === "✓"- ? "text-emerald-700 dark:text-emerald-300"- : "text-rose-700 dark:text-rose-300"- }- aria-hidden="true"- >- {" "}- {mark}- </span>)}- {!open && foldedSummary !== null ? (- <span className="text-muted-foreground dark:text-slate-500">- {" "}- {foldedSummary}+ {failedLast ? (+ <span className="font-normal text-muted-foreground">+ {SEP}attempt failed</span>) : null}+ <AttemptsBadge attempts={last?.attempts} />{row.codeDiffs.length === 0 ? null : (- <span className="font-mono tabular-nums text-muted-foreground dark:text-slate-500">- <span>{" \u00b7 "}</span>- <span>{`+${rowAdded}`}</span>- <span className="pl-1">{`\u2212${rowRemoved}`}</span>+ <>+ <span className="font-normal text-muted-foreground">{SEP}</span>+ <DiffCounts added={rowAdded} removed={rowRemoved} />+ </>+ )}+ {passed === null ? null : (+ <span className="font-normal text-muted-foreground">{`${SEP}${passed} of ${passed} passed`}</span>+ )}+ {failedBlocks.length === 0 ? null : (+ <span className="font-normal">+ <span className="text-muted-foreground">{SEP}</span>+ {failedBlocks.map((block, i) => (+ <span key={block.workflowRunBlockId || block.label}>+ {i === 0 ? null : " "}+ <FFailurePin block={block} />+ </span>+ ))}</span>)}- </FLogLine>+ </span>+ );+ const line = (+ <>+ <span className="flex h-[19px] w-3 shrink-0 items-center">+ {hasDetail ? <Chevron open={open} /> : null}+ </span>+ {row.live ? (+ <span className="flex h-[19px] shrink-0 items-center">+ <Spinner small />+ <span className="sr-only">in progress</span>+ </span>+ ) : null}+ {lineText}+ </>+ );+ const lineClass =+ "flex w-full min-w-0 items-start gap-1.5 py-px text-left text-[12.5px] leading-[1.5]";++ // Collapsing a row must not hide that its run's outcome went unconfirmed.+ const outcomeNotes = open+ ? []+ : blockOutcomeNotes(+ row.blocks,+ outcomeOwnerKey,+ outcomeReasonFallback,+ row.blocks.length > 1,+ );++ const lastIndexWhere = (predicate: (entry: ActivityEntry) => boolean) => {+ for (let i = calls.length - 1; i >= 0; i -= 1) {+ if (predicate(calls[i]!.entry)) return i;+ }+ return -1;+ };+ const diffHost =+ diffNodes.length === 0+ ? -1+ : lastIndexWhere((entry) => (entry.codeDiffs?.length ?? 0) > 0);+ const blockHost =+ blockNodes.length === 0+ ? -1+ : lastIndexWhere(+ (entry) =>+ entry.toolName !== undefined &&+ toolCallKind(entry.toolName) === "run",+ );+ const blockEvidence = <FDetailBox>{blockNodes}</FDetailBox>;++ const body = (+ <ul className="mb-1 ml-[18px] mt-0.5 flex list-none flex-col gap-px border-l border-border pl-2">+ {diffNodes.length > 0 && diffHost === -1 ? <li>{diffEvidence}</li> : null}+ {calls.map(({ entry, count }, i) => {+ const failed = entry.kind === "tool_result" && entry.success === false;+ const result =+ failed && resultShown(entry) ? (+ <pre className="whitespace-pre-wrap break-words font-mono text-[11.5px] leading-[1.5] text-rose-700 dark:text-rose-300">+ {entry.text}+ </pre>+ ) : null;+ return (+ <FCallItem+ key={toolCallIdOf(entry) ?? entry.id}+ entry={entry}+ turnEnded={turnEnded}+ count={count}+ detail={result}+ inlineResult={!failed && resultShown(entry) ? entry.text : null}+ // The exact server error is the evidence a failed step owes.+ defaultOpen={failed}+ evidence={+ <>+ {i === diffHost ? diffEvidence : null}+ {i === blockHost ? blockEvidence : null}+ </>+ }+ />+ );+ })}+ {blockNodes.length > 0 && blockHost === -1 ? (+ <li>{blockEvidence}</li>+ ) : null}+ </ul>);return (<div className="flex flex-col">- {lineNode}- {open && bodyChildren > 0 ? (- <div className="ml-[28px] flex flex-col gap-1 border-l border-border/60 py-1 pl-3">- {reasonNode}- {diffNodes}- {bodySteps.map((entry) => (- <ActivityRow key={entry.id} entry={entry} />- ))}- {(soloBlock ? [] : row.blocks).map((b) => (- <FBlockRun- key={b.workflowRunBlockId || b.label}- block={b}- turnEnded={turnEnded}- onSelect={onBlockSelect}- outcomeReasonFallback={outcomeReasonFallback}- ownsOutcomeNotConfirmed={blockIdentity(b) === outcomeOwnerKey}- flat- quietFailure- />- ))}- {bodyFailures.map((entry) => (- <ActivityRow key={entry.id} entry={entry} />- ))}- {exactFailure === null ? null : <ActivityRow entry={exactFailure} />}+ {reasonNode}+ {hasDetail ? (+ <button+ type="button"+ data-activity-line="true"+ aria-expanded={open}+ onClick={onToggle}+ className={`${lineClass} cursor-pointer`}+ >+ {line}+ </button>+ ) : (+ <div data-activity-line="true" className={lineClass}>+ {line}</div>- ) : null}+ )}+ {outcomeNotes.map(({ key, note }) => (+ <FOutcomeNote key={key} note={note} />+ ))}+ {open && hasDetail ? body : null}+ </div>+ );+}++function blockOutcomeNotes(+ blocks: BlockState[],+ outcomeOwnerKey: string | null | undefined,+ outcomeReasonFallback: string | null | undefined,+ named: boolean,+): { key: string; note: string }[] {+ return blocks.flatMap((b) => {+ const note = collapsedOutcomeNote(+ b,+ blockIdentity(b) === outcomeOwnerKey,+ outcomeReasonFallback,+ );+ if (note === null) return [];+ return [+ {+ key: blockIdentity(b),+ note: named ? `${humanizeBlockLabel(b.label)}: ${note}` : note,+ },+ ];+ });+}++function FOutcomeNote({ note }: { note: string }) {+ return (+ <div className="ml-[18px] mt-0.5 text-[12px] leading-[1.5] text-amber-700 dark:text-amber-200/80">+ {note}</div>);}+function FTurnFoldHeader({+ summary,+ open,+ onToggle,+}: {+ summary: FinishedTurnSummary;+ open: boolean;+ onToggle: () => void;+}) {+ const failures =+ summary.failedTests === 0+ ? ""+ : ` · ${summary.failedTests} failed ${summary.failedTests === 1 ? "test" : "tests"}${summary.fixed ? ", fixed" : ""}`;+ return (+ <button+ type="button"+ data-activity-fold="true"+ aria-expanded={open}+ onClick={onToggle}+ className="flex w-full min-w-0 items-start gap-1.5 pb-1.5 pt-0.5 text-left text-[12.5px] leading-[1.5] text-muted-foreground hover:text-foreground"+ >+ <span className="flex h-[19px] shrink-0 items-center">+ <Chevron open={open} />+ </span>+ <span className="min-w-0">+ {`Worked through ${summary.steps} steps${failures}`}+ {summary.stillFailing.map((block) => (+ <span key={block.workflowRunBlockId || block.label}>+ {SEP}+ <FFailurePin block={block} />+ </span>+ ))}+ </span>+ {summary.stillFailing.length > 0 ? null : (+ <span+ aria-hidden="true"+ className="ml-1 mt-[9px] h-px min-w-4 flex-1 bg-border"+ />+ )}+ </button>+ );+}+function FActivityLog({turn,log,@@ -1470,6 +1586,7 @@ function FActivityLog({onBlockSelect,interactionRef,anchoredAfterRow,+ anchoredBeforeRows = NO_ANCHORED_ITEMS,}: FActivityLogProps) {const outcomeReasonFallback = notConfirmedDisplayReason(turn);const outcomeOwnerKey = outcomeNotConfirmedOwnerKey(turn);@@ -1479,6 +1596,7 @@ function FActivityLog({const [override, setOverride] = useState<ReadonlyMap<string, boolean>>(() => new Map(),);+ const [foldOpen, setFoldOpen] = useState(false);const logRef = useRef<HTMLDivElement>(null);const ownInteractionRef = useRef<string | null>(null);const lastInteractedRow = interactionRef ?? ownInteractionRef;@@ -1492,7 +1610,11 @@ function FActivityLog({"[data-activity-row-id]",) ?? [],).find((candidate) => candidate.dataset.activityRowId === rowId);- row?.querySelector<HTMLButtonElement>("button")?.focus();+ // A finished turn folds its rows, so focus falls back to the fold.+ (+ row?.querySelector<HTMLButtonElement>("button") ??+ logRef.current?.querySelector<HTMLButtonElement>("[data-activity-fold]")+ )?.focus();lastInteractedRow.current = null;}, 0);return () => window.clearTimeout(timer);@@ -1523,64 +1645,179 @@ function FActivityLog({return <InstantAckPlaceholder />;}+ // One row already reads as one line, so only a longer finished turn folds.+ const finished = turnEnded+ ? summarizeFinishedTurn(rows, turn.turnFacts)+ : null;+ const summary = finished !== null && finished.steps > 1 ? finished : null;++ // Folded, a card from before or during the first step still reads first.+ const folded = summary !== null && !foldOpen;+ const leadingCards = [+ ...anchoredBeforeRows,+ ...(rows[0] ? (anchoredAfterRow?.get(rows[0].id) ?? []) : []),+ ];return (<div ref={logRef} className="flex flex-col gap-1.5">- {rows.map((row, i) => {- const focused = i === focusIndex;- const rowOverride = override.get(row.id);- const autoFocused = rowOverride === undefined && focused;- const open = rowOverride ?? focused;- const diffOpen = (label: string) =>- override.get(`diff:${row.id}:${label}`) ?? false;- const diffPeek = (label: string) =>- autoFocused &&- !diffOpen(label) &&- row.codeDiffs.some(- (candidate) =>- candidate.label === label && candidate.patch !== undefined,- );- return [- <div- key={row.id}- data-activity-row-id={row.id}- onFocusCapture={() => {- lastInteractedRow.current = row.id;- }}- >- <FActivityLogRow- row={row}- open={open}- onToggle={() => toggle(row.id, open)}- diffOpen={diffOpen}- diffPeek={diffPeek}- onDiffToggle={(label) =>- toggleDiff(row.id, label, diffOpen(label))- }- turnEnded={turnEnded}- onBlockSelect={onBlockSelect}- outcomeReasonFallback={outcomeReasonFallback}- outcomeOwnerKey={outcomeOwnerKey}- />- </div>,- ...(anchoredAfterRow?.get(row.id) ?? []).map((item) => (- <div key={item.key} className={`${TURN_ROW_OUTSET} py-0.5`}>- {item.node}- </div>- )),- ];- })}+ {folded ? leadingCards.map(anchoredNode) : null}+ {summary === null ? null : (+ <FTurnFoldHeader+ summary={summary}+ open={foldOpen}+ onToggle={() => setFoldOpen((v) => !v)}+ />+ )}+ {/* A block that owns the turn's unconfirmed verdict suppresses the turn+ card, so the fold has to keep that note visible itself. */}+ {summary === null || foldOpen+ ? null+ : blockOutcomeNotes(+ rows+ .flatMap((row) => row.blocks)+ .filter((b) => blockIdentity(b) === outcomeOwnerKey)+ .slice(-1),+ outcomeOwnerKey,+ outcomeReasonFallback,+ true,+ ).map(({ key, note }) => <FOutcomeNote key={key} note={note} />)}+ {/* Folding the steps must not hide the cards that happened among them. */}+ {folded+ ? rows+ .slice(1)+ .flatMap((row) => anchoredAfterRow?.get(row.id) ?? [])+ .map(anchoredNode)+ : anchoredBeforeRows.map(anchoredNode)}+ {summary !== null && !foldOpen+ ? null+ : rows.map((row, i) => {+ const focused = i === focusIndex;+ const rowOverride = override.get(row.id);+ const autoFocused = rowOverride === undefined && focused;+ const open = rowOverride ?? focused;+ const diffOpen = (label: string) =>+ override.get(`diff:${row.id}:${label}`) ?? false;+ const diffPeek = (label: string) =>+ autoFocused &&+ !diffOpen(label) &&+ row.codeDiffs.some(+ (candidate) =>+ candidate.label === label && candidate.patch !== undefined,+ );+ return [+ <div+ key={row.id}+ data-activity-row-id={row.id}+ onFocusCapture={() => {+ lastInteractedRow.current = row.id;+ }}+ >+ <FActivityLogRow+ row={row}+ open={open}+ onToggle={() => toggle(row.id, open)}+ diffOpen={diffOpen}+ diffPeek={diffPeek}+ onDiffToggle={(label) =>+ toggleDiff(row.id, label, diffOpen(label))+ }+ turnEnded={turnEnded}+ onBlockSelect={onBlockSelect}+ outcomeReasonFallback={outcomeReasonFallback}+ outcomeOwnerKey={outcomeOwnerKey}+ />+ </div>,+ ...(anchoredAfterRow?.get(row.id) ?? []).map(anchoredNode),+ ];+ })}+ </div>+ );+}++// The typed budget-expiry record, as its own line so a folded turn still says+// why it stopped. When no report was produced the terminal prose says so.+function FBudgetLimitNote({ budget }: { budget: BudgetExpiryState }) {+ const limit = budget.source === "deadline" ? "time" : "model-call";+ return (+ <div+ data-testid="copilot-budget-limit"+ className={`flex items-start gap-[7px] text-[12px] leading-[1.5] ${STEP_TEXT}`}+ >+ <StopIcon+ aria-hidden="true"+ className="mt-[3px] size-3 shrink-0 text-muted-foreground"+ />+ <span>+ {`Reached this turn's ${limit} limit. Copilot stopped starting new work${+ budget.reportProduced === true ? " and reported what it found" : ""+ }.`}+ </span></div>);}// Something that happened during a turn and renders where it happened: after the activity row-// holding its tool call, or above the turn's reply when that row is not on screen.+// holding its tool call. When that row is not on screen (a long turn keeps only its newest+// activity), `at` places it among the rows by time; without it, it sits above the reply.export interface AnchoredTurnItem {key: string;toolCallId: string | null;+ at?: string | null;node: React.ReactNode;}+function placeAnchoredItems(+ rows: ActivityRowModel[],+ anchored: AnchoredTurnItem[],+): {+ anchoredAfterRow: Map<string, AnchoredTurnItem[]>;+ anchoredBeforeRows: AnchoredTurnItem[];+ unanchored: AnchoredTurnItem[];+} {+ const anchoredAfterRow = new Map<string, AnchoredTurnItem[]>();+ const anchoredBeforeRows: AnchoredTurnItem[] = [];+ const unanchored: AnchoredTurnItem[] = [];+ for (const item of anchored) {+ let row =+ item.toolCallId === null+ ? undefined+ : rows[rowIndexOfToolCall(rows, item.toolCallId)];+ const atMs = row === undefined ? parseUtcIsoMs(item.at) : null;+ if (atMs !== null && rows.length > 0) {+ // Rows can sit out of start order when parallel calls settle out of order, so pick the+ // latest start, not the last row shown.+ let latestMs = -Infinity;+ for (const candidate of rows) {+ const startedMs = parseUtcIsoMs(candidate.startedAt);+ if (startedMs !== null && startedMs <= atMs && startedMs >= latestMs) {+ latestMs = startedMs;+ row = candidate;+ }+ }+ if (row === undefined) {+ anchoredBeforeRows.push(item);+ continue;+ }+ }+ if (row === undefined) {+ unanchored.push(item);+ } else {+ anchoredAfterRow.set(row.id, [+ ...(anchoredAfterRow.get(row.id) ?? []),+ item,+ ]);+ }+ }+ return { anchoredAfterRow, anchoredBeforeRows, unanchored };+}++function anchoredNode(item: AnchoredTurnItem) {+ return (+ <div key={item.key} className={`${TURN_ROW_OUTSET} py-0.5`}>+ {item.node}+ </div>+ );+}+function AnchoredFallback({ items }: { items: AnchoredTurnItem[] }) {return (<>@@ -1596,7 +1833,6 @@ interface DetailViewProps {onBlockSelect?: (label: string) => void;workingRowActive?: boolean;activityInteractionRef?: { current: string | null };- beforeProse?: React.ReactNode;anchored: AnchoredTurnItem[];}@@ -1605,7 +1841,6 @@ function DetailView({onBlockSelect,workingRowActive,activityInteractionRef,- beforeProse,anchored,}: DetailViewProps) {const collapsedOutcomeReason = notConfirmedDisplayReason(turn);@@ -1628,26 +1863,15 @@ function DetailView({() => (showChecklist ? deriveActivityLog(turn) : null),[showChecklist, turn],);- const { anchoredAfterRow, unanchored } = useMemo(() => {- const byRow = new Map<string, AnchoredTurnItem[]>();- const rest: AnchoredTurnItem[] = [];- // The log shows a placeholder instead of rows until a live turn has one.- const rows =- log && (turn.terminal !== null || log.rows.length > 0) ? log.rows : [];- for (const item of anchored) {- const index =- item.toolCallId === null- ? -1- : rowIndexOfToolCall(rows, item.toolCallId);- const row = rows[index];- if (row === undefined) {- rest.push(item);- } else {- byRow.set(row.id, [...(byRow.get(row.id) ?? []), item]);- }- }- return { anchoredAfterRow: byRow, unanchored: rest };- }, [anchored, log, turn.terminal]);+ const { anchoredAfterRow, anchoredBeforeRows, unanchored } = useMemo(+ () =>+ placeAnchoredItems(+ // The log shows a placeholder instead of rows until a live turn has one.+ log && (turn.terminal !== null || log.rows.length > 0) ? log.rows : [],+ anchored,+ ),+ [anchored, log, turn.terminal],+ );return (<div className="flex flex-col gap-2.5">@@ -1662,6 +1886,7 @@ function DetailView({onBlockSelect={onBlockSelect}interactionRef={activityInteractionRef}anchoredAfterRow={anchoredAfterRow}+ anchoredBeforeRows={anchoredBeforeRows}/></div>) : showDesign ? (@@ -1724,7 +1949,11 @@ function DetailView({<AnchoredFallback items={unanchored} />- {beforeProse}+ {turn.terminal !== null &&+ turn.budgetExpiry !== null &&+ turn.budgetExpiry.reportProduced !== false ? (+ <FBudgetLimitNote budget={turn.budgetExpiry} />+ ) : null}{/* terminalProseTone's question branch without its evidence gate: anask that followed a run keeps the rail here, beside the evidence,@@ -1757,9 +1986,6 @@ interface NarrativeViewProps {turn: TurnNarrativeState;onBlockSelect?: (blockLabel: string) => void;workingRowActive?: boolean;- // What the user did mid-turn (answered a question). It happened after the turn's activity and- // before the reply, so it renders between them to keep the transcript chronological.- beforeProse?: React.ReactNode;anchored?: AnchoredTurnItem[];}@@ -1896,12 +2122,22 @@ export function NarrativeView({turn,onBlockSelect,workingRowActive,- beforeProse,anchored = NO_ANCHORED_ITEMS,}: NarrativeViewProps) {const proseTone = terminalProseTone(turn);const proseText = humanizeJudgeText(terminalNarrativeText(turn));const activityInteractionRef = useRef<string | null>(null);+ const answerLog = useMemo(+ () =>+ proseTone !== null && proseText && turn.designActivity.length > 0+ ? deriveActivityLog(turn)+ : null,+ [proseTone, proseText, turn],+ );+ const answerAnchored = useMemo(+ () => placeAnchoredItems(answerLog?.rows ?? [], anchored),+ [answerLog, anchored],+ );if (proseTone !== null && proseText) {const prose = (@@ -1911,14 +2147,28 @@ export function NarrativeView({arrivedAt={turn.endedAt}/>);- return beforeProse || anchored.length > 0 ? (+ if (answerLog === null && anchored.length === 0) {+ return prose;+ }+ // An answer that took work still says what that work was, folded above it.+ return (<div className="flex flex-col gap-2.5">- <AnchoredFallback items={anchored} />- {beforeProse}+ {answerLog === null ? null : (+ <div className={TURN_ROW_INSET}>+ <FActivityLog+ turn={turn}+ log={answerLog}+ turnEnded+ onBlockSelect={onBlockSelect}+ interactionRef={activityInteractionRef}+ anchoredAfterRow={answerAnchored.anchoredAfterRow}+ anchoredBeforeRows={answerAnchored.anchoredBeforeRows}+ />+ </div>+ )}+ <AnchoredFallback items={answerAnchored.unanchored} />{prose}</div>- ) : (- prose);}@@ -1928,7 +2178,6 @@ export function NarrativeView({onBlockSelect={onBlockSelect}workingRowActive={workingRowActive}activityInteractionRef={activityInteractionRef}- beforeProse={beforeProse}anchored={anchored}/>);diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.workingLine.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.workingLine.test.tsxindex 030313a83..97f7cbd83 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.workingLine.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.workingLine.test.tsx@@ -21,7 +21,7 @@ describe("NarrativeView — transcript working line", () => {it("replaces the active-turn working header with the acknowledgement", () => {render(<NarrativeView turn={exploringTurn()} />);- expect(screen.queryByText("Working…")).toBeNull();+ expect(screen.getAllByText("Working…")).toHaveLength(1);expect(screen.queryByText("· building your workflow")).toBeNull();expect(screen.getByRole("status").textContent).toContain("Copilot is working on your request…",diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsxindex 4e39474fb..3f8729bb4 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx@@ -574,7 +574,7 @@ const streamScoutTurn = async () => {describe("WorkflowCopilotChat — activity log", () => {it("renders the flat log, not the retired phase rail", async () => {await streamScoutTurn();- expect(screen.getByText("Opened the sign-in page")).toBeTruthy();+ expect(screen.getByText("1 browser action")).toBeTruthy();expect(screen.queryByText("Explore site")).toBeNull();});});@@ -680,11 +680,408 @@ describe("WorkflowCopilotChat — credential receipt placement", () => {});const receipt = await screen.findByText("Credential 'HN Login' added");expect(screen.getAllByText("Credential 'HN Login' added")).toHaveLength(1);- expect(precedes(row("tc-1"), receipt)).toBe(true);- expect(precedes(receipt, row("tc-2"))).toBe(true);expect(precedes(receipt, screen.getByText("Signed in and saved the draft.")),).toBe(true);++ // The finished turn folds its steps; the card stays visible, and opening+ // the fold puts it back after the row it was raised on.+ fireEvent.click(+ document.querySelector<HTMLButtonElement>("[data-activity-fold]")!,+ );+ const unfolded = screen.getByText("Credential 'HN Login' added");+ expect(screen.getAllByText("Credential 'HN Login' added")).toHaveLength(1);+ expect(precedes(row("tc-1"), unfolded)).toBe(true);+ expect(precedes(unfolded, row("tc-2"))).toBe(true);+ });+});++describe("WorkflowCopilotChat — question receipt placement", () => {+ it("keeps an answered question after the step that asked it while later steps run", async () => {+ await streamScoutTurn();+ const ask = {+ tool_name: "ask_user",+ display_label: "Asking you",+ iteration: 1,+ tool_call_id: "tc-ask",+ };+ const said = (iteration: number, narration: string, second: number) => ({+ type: "narration",+ narration,+ iteration,+ timestamp: `2026-07-13T00:00:0${second}Z`,+ });+ const question = {+ interaction_id: "qi-1",+ turn_id: "turn-1",+ tool_call_id: "tc-ask",+ parts: [+ {+ part_id: "p1",+ prompt: "Which structure?",+ choices: [{ choice_id: "c-llc", text: "LLC" }],+ },+ ],+ status: "pending" as const,+ response: null,+ created_at: "2026-07-13T00:00:02Z",+ resolved_at: null,+ };+ const later = {+ tool_name: "get_block_schema",+ display_label: "Checking workflow block options",+ iteration: 2,+ tool_call_id: "tc-later",+ };+ await act(async () => {+ streamCalls[0]!.onMessage(said(1, "Checking what the form needs.", 1));+ streamCalls[0]!.onMessage({+ type: "tool_call",+ tool_input: {},+ timestamp: "2026-07-13T00:00:02Z",+ ...ask,+ });+ streamCalls[0]!.onMessage({+ type: "question_required",+ turn_id: "turn-1",+ workflow_copilot_chat_id: "chat-1",+ cancel_token: null,+ interactions: [question],+ });+ streamCalls[0]!.onMessage({+ type: "question_resolved",+ continued: true,+ interaction: {+ ...question,+ status: "resolved",+ response: {+ answers: [{ part_id: "p1", choice_id: "c-llc", text: null }],+ text: null,+ skipped: false,+ },+ resolved_at: "2026-07-13T00:00:03Z",+ },+ });+ streamCalls[0]!.onMessage({+ type: "tool_result",+ success: true,+ summary: "Answered",+ timestamp: "2026-07-13T00:00:04Z",+ ...ask,+ });+ streamCalls[0]!.onMessage(said(2, "Choosing the blocks.", 5));+ streamCalls[0]!.onMessage({+ type: "tool_call",+ tool_input: {},+ timestamp: "2026-07-13T00:00:06Z",+ ...later,+ });+ });+ // The full suite runs this file under load; the default 1s wait flakes.+ const receipt = await screen.findByText(+ "You answered 1 question",+ undefined,+ {+ timeout: 5000,+ },+ );+ const step = (reason: string) =>+ [...document.querySelectorAll("[data-activity-row-id]")].find((row) =>+ row.textContent?.includes(reason),+ );+ const precedes = (a: Node | undefined, b: Node | undefined) =>+ Boolean(+ a &&+ b &&+ a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING,+ );+ // The receipt renders before later steps finish revealing, so wait for the steps too.+ await waitFor(+ () => {+ expect(precedes(step("Checking what the form needs."), receipt)).toBe(+ true,+ );+ expect(precedes(receipt, step("Choosing the blocks."))).toBe(true);+ },+ { timeout: 5000 },+ );+ });+});++describe("WorkflowCopilotChat — saved turn placement", () => {+ it("places a plan and a question whose rows the saved turn no longer keeps by their call and time", async () => {+ const at = (s: number) => `2026-07-13T00:00:${String(s).padStart(2, "0")}Z`;+ const call = (id: string, toolName: string, s: number) => [+ {+ kind: "tool_call",+ id: `tc-${id}`,+ text: "…",+ toolName,+ iteration: s,+ timestamp: at(s),+ },+ {+ kind: "tool_result",+ id: `tr-${id}`,+ text: "OK",+ toolName,+ iteration: s,+ success: true,+ timestamp: at(s),+ },+ ];+ const said = (text: string, s: number) => ({+ kind: "narration",+ id: `n-${s}`,+ text,+ iteration: s,+ timestamp: at(s),+ });+ historyResponse.data.chat_history = [+ {+ sender: "user",+ content: "Apply for it",+ turn_id: "turn-1",+ created_at: at(0),+ },+ {+ sender: "ai",+ content: "Stopped.",+ turn_id: "turn-1",+ created_at: at(30),+ turn_outcome: {+ copilot_turn_id: "turn-1",+ terminal_reason: "completed",+ },+ narrative_payload: {+ turnId: "turn-1",+ turnIndex: 0,+ designStarted: true,+ designEnded: true,+ terminal: "response",+ terminalMessage: "Stopped.",+ narrativeSummary: "Stopped.",+ startedAt: at(0),+ endedAt: at(30),+ draft: { blockCount: 1, blockLabels: ["fill_form"] },+ blocks: [],+ // The ask_user call at 0:02 aged out of the saved activity.+ designActivity: [+ said("Opening the form.", 10),+ ...call("nav", "navigate_browser", 11),+ said("Writing the plan.", 12),+ ...call("plan", "set_work_plan", 13),+ said("Checking the next page.", 14),+ ...call("look", "evaluate", 15),+ ],+ },+ },+ ];+ (historyResponse.data as Record<string, unknown>).work_plan = [+ "Fill in the form",+ ];+ historyResponse.data.question_interactions = [+ {+ interaction_id: "qi-early",+ turn_id: "turn-1",+ tool_call_id: "tc-aged-out",+ parts: [+ {+ part_id: "p1",+ prompt: "Which structure?",+ choices: [{ choice_id: "c-llc", text: "LLC" }],+ },+ ],+ status: "resolved",+ response: {+ answers: [{ part_id: "p1", choice_id: "c-llc", text: null }],+ text: null,+ skipped: false,+ },+ created_at: at(2),+ resolved_at: at(3),+ },+ ];+ await renderChat();+ await screen.findByText("You answered 1 question");+ const fold = document.querySelector<HTMLButtonElement>(+ "[data-activity-fold]",+ )!;+ // Folded, the question asked before every kept step still reads first,+ // while the plan made mid-turn stays below the fold line.+ expect(+ Boolean(+ screen+ .getByText("You answered 1 question")+ .compareDocumentPosition(fold) & Node.DOCUMENT_POSITION_FOLLOWING,+ ),+ ).toBe(true);+ expect(+ Boolean(+ fold.compareDocumentPosition(screen.getByText("Fill in the form")) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ),+ ).toBe(true);+ fireEvent.click(fold);+ const step = (reason: string) =>+ [...document.querySelectorAll("[data-activity-row-id]")].find((row) =>+ row.textContent?.includes(reason),+ )!;+ const precedes = (a: Node, b: Node) =>+ Boolean(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);+ const question = screen.getByText("You answered 1 question");+ const plan = screen.getByText("Fill in the form");+ expect(screen.getAllByText("Fill in the form")).toHaveLength(1);+ expect(precedes(question, step("Opening the form."))).toBe(true);+ expect(precedes(step("Writing the plan."), plan)).toBe(true);+ expect(precedes(plan, step("Checking the next page."))).toBe(true);+ });+});++describe("WorkflowCopilotChat — saved plan attribution", () => {+ it("does not credit an older turn with the plan when a newer turn's steps were trimmed", async () => {+ const at = (s: number) =>+ `2026-07-13T00:${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}Z`;+ const pair = (id: string, toolName: string, s: number) => [+ {+ kind: "tool_call",+ id: `tc-${id}`,+ text: "…",+ toolName,+ iteration: s,+ timestamp: at(s),+ },+ {+ kind: "tool_result",+ id: `tr-${id}`,+ text: "OK",+ toolName,+ iteration: s,+ success: true,+ timestamp: at(s),+ },+ ];+ const turn = (+ id: string,+ start: number,+ reply: string,+ designActivity: unknown[],+ ) => [+ {+ sender: "user",+ content: `Ask ${id}`,+ turn_id: id,+ created_at: at(start),+ },+ {+ sender: "ai",+ content: reply,+ turn_id: id,+ created_at: at(start + 50),+ turn_outcome: { copilot_turn_id: id, terminal_reason: "completed" },+ narrative_payload: {+ turnId: id,+ terminal: "response",+ terminalMessage: reply,+ narrativeSummary: reply,+ startedAt: at(start),+ endedAt: at(start + 50),+ blocks: [],+ designActivity,+ },+ },+ ];+ historyResponse.data.chat_history = [+ ...turn(+ "turn-1",+ 0,+ "First turn done.",+ pair("plan", "set_work_plan", 5),+ ),+ // At the 50-entry cap: this turn's own set_work_plan call may have aged out.+ ...turn(+ "turn-2",+ 100,+ "Second turn done.",+ Array.from({ length: 25 }, (_, n) =>+ pair(`look-${n}`, "evaluate", 101 + n),+ ).flat(),+ ),+ ];+ (historyResponse.data as Record<string, unknown>).work_plan = [+ "Fill in the form",+ ];+ await renderChat();+ const plan = await screen.findByText("Fill in the form");+ const secondReply = screen.getByText("Second turn done.");+ expect(+ Boolean(+ secondReply.compareDocumentPosition(plan) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ),+ ).toBe(true);+ });+});++describe("WorkflowCopilotChat — saved plan clear", () => {+ it("shows a plan cleared by a turn saved without its plan", async () => {+ const at = (s: number) => `2026-07-13T00:00:${String(s).padStart(2, "0")}Z`;+ const planResult = (id: string, s: number) => ({+ kind: "tool_result",+ id: `tr-${id}`,+ text: "OK",+ toolName: "set_work_plan",+ iteration: s,+ success: true,+ timestamp: at(s),+ });+ const aiTurn = (+ id: string,+ start: number,+ reply: string,+ extra: Record<string, unknown>,+ ) => ({+ sender: "ai",+ content: reply,+ turn_id: id,+ created_at: at(start + 5),+ turn_outcome: { copilot_turn_id: id, terminal_reason: "completed" },+ narrative_payload: {+ turnId: id,+ terminal: "response",+ terminalMessage: reply,+ narrativeSummary: reply,+ startedAt: at(start),+ endedAt: at(start + 5),+ blocks: [],+ ...extra,+ },+ });+ historyResponse.data.chat_history = [+ {+ sender: "user",+ content: "Plan it",+ turn_id: "turn-1",+ created_at: at(0),+ },+ aiTurn("turn-1", 0, "Planned.", {+ designActivity: [planResult("plan", 1)],+ workPlan: { toolCallId: "tc-plan", items: ["Fill in the form"] },+ }),+ {+ sender: "user",+ content: "Drop it",+ turn_id: "turn-2",+ created_at: at(10),+ },+ // Saved without its plan; its newest successful call cleared it.+ aiTurn("turn-2", 10, "Cleared.", {+ designActivity: [planResult("clear", 11)],+ }),+ ];+ (historyResponse.data as Record<string, unknown>).work_plan = [];+ await renderChat();+ expect(await screen.findByText("Plan cleared")).toBeTruthy();});});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsxindex 8a3321b69..39781e142 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx@@ -3164,7 +3164,7 @@ describe("WorkflowCopilotChat — question transport", () => {],}),);- const receipt = await screen.findByText("LLC");+ const receipt = await screen.findByText("You answered 1 question");const reply = screen.getByTestId("copilot-terminal-prose");expect(reply.textContent).toContain("Got it, an LLC.");expect(diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsxindex 6b100489d..1bbf1db72 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx@@ -162,7 +162,6 @@ vi.mock("./WorkflowCopilotHistory", () => ({),}));-import { COPILOT_ACK_LINES } from "./NarrativeView";const BOOLEAN_FLAGS: Record<string, boolean> = {WORKFLOW_COPILOT_CODE_BLOCK_MODE: false,CODE_BLOCK_ACCESS: false,@@ -188,18 +187,14 @@ async function submit(value: string) {await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));}+const ACK = "Copilot is working on your request…";+function expectNoAckLines() {- for (const line of COPILOT_ACK_LINES) {- expect(screen.queryByText(line)).toBeNull();- }+ expect(screen.queryByText(ACK)).toBeNull();}-// The placeholder opens on a random line, so assert *some* ack line shows.function expectSomeAckLine() {- const present = COPILOT_ACK_LINES.some(- (line) => screen.queryByText(line) !== null,- );- expect(present).toBe(true);+ expect(screen.getByText(ACK)).toBeTruthy();}async function completeStream(index: number, message: string) {diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsxindex b783a2b86..98bb6afbf 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx@@ -7466,10 +7466,10 @@ describe("WorkflowCopilotChat — g2 review gate", () => {await renderChat();- expect(await screen.findByText("Associated test: completed")).toBeTruthy();+ expect(await screen.findByText("Test run output")).toBeTruthy();const facts = screen.getByTestId("proposal-run-facts");- expect(facts.textContent).toContain("op-metric:");- expect(facts.textContent).toContain("metric: 42");+ expect(facts.textContent).toContain("Metric");+ expect(facts.textContent).toContain("42");expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();});@@ -7491,10 +7491,10 @@ describe("WorkflowCopilotChat — g2 review gate", () => {});const expectReadableObjectOutput = (facts: HTMLElement) => {- expect(facts.textContent).toContain("Associated test: completed");- expect(facts.textContent).toContain("signed_in_url:");+ expect(facts.textContent).toContain("Test run output");+ expect(facts.textContent).toContain("Signed in url");expect(facts.textContent).toContain("https://example.com/usage");- expect(facts.textContent).toContain("visible_page_text:");+ expect(facts.textContent).toContain("Visible page text");expect(facts.textContent).toContain("Select a project");expect(facts.textContent).not.toContain('{"');expect(facts.textContent).not.toContain("\\n");@@ -7525,10 +7525,72 @@ describe("WorkflowCopilotChat — g2 review gate", () => {await renderChat();- expect(await screen.findByText("Associated test: completed")).toBeTruthy();+ expect(await screen.findByText("Test run output")).toBeTruthy();expectReadableObjectOutput(screen.getByTestId("proposal-run-facts"));});+ it("reload shows a task block's extraction under its block name, with bookkeeping behind the full output", async () => {+ historyResponse.data.chat_history = [+ {+ sender: "user",+ content: "check the price",+ created_at: "2026-09-08T12:00:00Z",+ },+ ];+ historyResponse.data.proposed_workflow = proposedWorkflowPayload({+ workflow_definition: {+ parameters: [],+ blocks: [+ {+ label: "extract_price",+ block_type: "task",+ output_parameter: { output_parameter_id: "op_price" },+ },+ ],+ },+ });+ historyResponse.data.proposed_workflow_metadata = {+ owner_turn_id: "turn-price",+ revision: 1,+ canonical_fingerprint: "canonical-1",+ disposition: "review_untested",+ workflow_run_id: "wr-price",+ };+ historyResponse.data.proposed_workflow_run = {+ workflow_run_id: "wr-price",+ status: "completed",+ available: true,+ failure_reason: null,+ outputs: [+ {+ output_parameter_id: "op_price",+ value: {+ task_id: "tsk_price",+ status: "completed",+ extracted_information: { current_price: "12.50", currency: "USD" },+ failure_reason: null,+ errors: [],+ task_screenshot_artifact_ids: ["a_screenshot"],+ },+ },+ ],+ };++ await renderChat();++ const facts = await screen.findByTestId("proposal-run-facts");+ expect(facts.textContent).toContain("Extract Price");+ expect(facts.textContent).toContain("Current price");+ expect(facts.textContent).toContain("12.50");+ expect(facts.textContent).not.toContain("tsk_price");+ expect(facts.textContent).not.toContain("a_screenshot");++ fireEvent.click(+ within(facts).getByRole("button", { name: /Full run output/ }),+ );+ expect(facts.textContent).toContain("tsk_price");+ });+it("reload keeps the exact unavailable-run sentence", async () => {historyResponse.data.proposed_workflow = proposedWorkflowPayload();historyResponse.data.proposed_workflow_metadata = {diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex 419390a25..bf7b5c995 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -180,6 +180,7 @@ import { connectedAccountChoiceLabel } from "./cards/connectedAccountChoiceLabelimport { shouldShowDiffCard } from "./cards/DiffCard";import { ReviewGateCard, getReviewGateVerdict } from "./cards/ReviewGateCard";import { TURN_ROW_INSET } from "./cards/cardLayout";+import { TestRunOutputCard } from "./cards/TestRunOutputCard";import { GoogleReconnectCard } from "./cards/GoogleReconnectCard";import {CredentialCard,@@ -194,11 +195,13 @@ import {NarrativeEvent,RecordedActionSummary,TurnNarrativeState,+ activityMayBeTrimmed,applyNarrativeEvent,hydrateHistoryNarrative,notConfirmedOutcome,parseCredentialPause,parseUtcIsoMs,+ toolCallIdOf,} from "./narrativeState";import { computeFollowSignature, useStickToBottom } from "./useStickToBottom";import { useTurnActivityChange } from "./useTurnActivityChange";@@ -1416,81 +1419,6 @@ const reviewBaselineFromSaveData = (),});-function renderOutputValue(value: unknown): React.ReactNode {- if (value === null || value === undefined || value === "") {- return <span>—</span>;- }- if (typeof value === "string") {- return (- <span className="whitespace-pre-wrap [overflow-wrap:anywhere]">- {value}- </span>- );- }- if (Array.isArray(value)) {- if (value.length === 0) {- return <span>—</span>;- }- return (- <div className="ml-3">- {value.map((item, index) => (- <div key={index}>- <span className="font-medium">{index + 1}.</span>{" "}- {renderOutputValue(item)}- </div>- ))}- </div>- );- }- if (typeof value === "object") {- const entries = Object.entries(value);- if (entries.length === 0) {- return <span>—</span>;- }- return (- <div className="ml-3">- {entries.map(([key, item]) => (- <div key={key}>- <span className="font-medium">{key}:</span>{" "}- {renderOutputValue(item)}- </div>- ))}- </div>- );- }- return <span>{String(value)}</span>;-}--function ProposalRunFactsLine({ facts }: { facts: CopilotProposalRunFacts }) {- if (!facts.available) {- return (- <p- className={`${TURN_ROW_INSET} text-xs text-muted-foreground`}- data-testid="proposal-run-facts"- >- Associated test run unavailable. No other run was substituted.- </p>- );- }- return (- <div- className={`${TURN_ROW_INSET} space-y-1 text-xs text-muted-foreground`}- data-testid="proposal-run-facts"- >- <p>Associated test: {facts.status ?? "status unavailable"}</p>- {facts.failure_reason ? <p>{facts.failure_reason}</p> : null}- {facts.outputs.map((output) => (- <div key={output.output_parameter_id}>- <span className="font-medium text-foreground">- {output.output_parameter_id}:- </span>{" "}- {renderOutputValue(output.value)}- </div>- ))}- </div>- );-}-// eslint-disable-next-line react-refresh/only-export-components -- Recovery survives routed editors.export const canonicalRecoveriesByWorkflow = new Map<string,@@ -9077,13 +9005,41 @@ export function WorkflowCopilotChat({// Each turn's closing plan, so a revision renders in the turn that wrote it and the one it// replaced stays where it was, folded.- const turnPlans = useMemo(- () =>- messages.map((message) =>- message.sender === "ai" ? (message.narrative?.workPlan ?? null) : null,- ),- [messages],- );+ const turnPlans = useMemo(() => {+ const plans = messages.map((message) =>+ message.sender === "ai" ? (message.narrative?.workPlan ?? null) : null,+ );+ // A turn saved without its plan gets the chat's current one when it holds the newest+ // successful set_work_plan call on record. A newer turn with no saved steps, or with steps+ // trimmed at the cap, may have made it, so the search stops there and the plan keeps its+ // chat-level card.+ // An empty chat plan still searches: a turn whose newest call cleared the plan owns that.+ for (let i = messages.length - 1; i >= 0; i--) {+ const message = messages[i]!;+ if (plans[i]) break;+ // Synthetic rows (run lifecycle, status notices) are not turns.+ if (message.sender !== "ai" || message.kind !== undefined) continue;+ if (!message.narrative) break;+ const planCall = [+ ...message.narrative.designActivity,+ ...message.narrative.blocks.flatMap((block) => block.activity),+ ]+ .filter(+ (entry) =>+ entry.kind === "tool_result" &&+ entry.toolName === "set_work_plan" &&+ entry.success === true,+ )+ .pop();+ const toolCallId = planCall && toolCallIdOf(planCall);+ if (toolCallId) {+ plans[i] = { toolCallId, items: workPlan };+ break;+ }+ if (activityMayBeTrimmed(message.narrative)) break;+ }+ return plans;+ }, [messages, workPlan]);const liveTurnPlan =narrative.turnId !== null && narrative.terminal === null? (narrative.workPlan ?? null)@@ -9420,6 +9376,24 @@ export function WorkflowCopilotChat({interaction={interaction}/>);+ // A question renders under the step that asked it, like a plan or credential card.+ const anchoredQuestion = (+ interaction: QuestionInteraction,+ ): AnchoredTurnItem => ({+ key: `question-${interaction.interaction_id}`,+ toolCallId: interaction.tool_call_id,+ at: interaction.created_at,+ node: renderQuestionReceipt(interaction),+ });+ const liveTurnShown =+ narrative.turnId !== null && narrative.terminal === null;+ if (liveTurnShown) {+ liveAnchored.push(+ ...questionInteractions+ .filter((item) => item.turn_id === narrative.turnId)+ .map(anchoredQuestion),+ );+ }// Straight to the answer path rather than through handleSend, whose authoring and YAML-commit// guards would turn an enabled Send into a silent no-op.const sendQuestionTray = (options?: { omitCurrent?: boolean }) =>@@ -9688,9 +9662,10 @@ export function WorkflowCopilotChat({}/>{messages.flatMap((message, index) => {- const turnQuestions = questionInteractions- .filter((item) => item.turn_id === message.narrative?.turnId)- .map(renderQuestionReceipt);+ const turnInteractions = questionInteractions.filter(+ (item) => item.turn_id === message.narrative?.turnId,+ );+ const turnQuestions = turnInteractions.map(renderQuestionReceipt);let questionsPlaced = false;const rendered = (() => {const isLastMessage = index === lastTurnIndex;@@ -9923,6 +9898,7 @@ export function WorkflowCopilotChat({node: autoBoundCard,});}+ anchored.push(...turnInteractions.map(anchoredQuestion));return (<divkey={message.id}@@ -9934,9 +9910,6 @@ export function WorkflowCopilotChat({turn={message.narrative}onBlockSelect={onBlockSelect}workingRowActive={showWorkingRow}- beforeProse={- turnQuestions.length > 0 ? turnQuestions : undefined- }anchored={anchored}/>{message.narrative.outputFiles.length > 0 ? (@@ -10014,7 +9987,10 @@ export function WorkflowCopilotChat({{showReviewGate ? (<div className="space-y-2">{index === gateIndex && pendingProposalRun ? (- <ProposalRunFactsLine facts={pendingProposalRun} />+ <TestRunOutputCard+ facts={pendingProposalRun}+ workflow={proposedWorkflow}+ />) : null}<ReviewGateCardturn={message.narrative}@@ -10105,7 +10081,10 @@ export function WorkflowCopilotChat({isGateOwnerOrLast || feedbackControl ? (<div className="w-full space-y-2">{isGateOwnerOrLast && pendingProposalRun ? (- <ProposalRunFactsLine facts={pendingProposalRun} />+ <TestRunOutputCard+ facts={pendingProposalRun}+ workflow={proposedWorkflow}+ />) : null}{isGateOwnerOrLast ? (<ReviewGateCard@@ -10142,8 +10121,8 @@ export function WorkflowCopilotChat({/>);})();- // A turn's own view places its questions between its activity and its reply; any- // other row lists them after itself, since that row is what asked.+ // A turn's own view places its questions under the step that asked; any other row+ // lists them after itself, since that row is what asked.const rows = questionsPlaced? [rendered]: [rendered, ...turnQuestions];@@ -10177,7 +10156,10 @@ export function WorkflowCopilotChat({{gateHasSubject && !gateOwnerRendersInline ? (<div className="space-y-2">{pendingProposalRun ? (- <ProposalRunFactsLine facts={pendingProposalRun} />+ <TestRunOutputCard+ facts={pendingProposalRun}+ workflow={proposedWorkflow}+ />) : null}<ReviewGateCardpending@@ -10273,6 +10255,7 @@ export function WorkflowCopilotChat({{questionInteractions.filter((item) =>+ !(liveTurnShown && item.turn_id === narrative.turnId) &&!messages.some((message) => message.narrative?.turnId === item.turn_id,),diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.tsxindex 0fe607303..92b636746 100644--- a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionPartsCard.tsx@@ -1,70 +1,117 @@import { CheckIcon } from "@radix-ui/react-icons";+import { cn } from "@/util/utils";import type { QuestionInteraction } from "../workflowCopilotTypes";+import { hasAnswer } from "./questionAnswers";+import { MAX_KEYED_CHOICES } from "./QuestionTray";-// The read-only record of a question. A pending question is answered in the composer's-// QuestionTray; this card is what the transcript shows once it has an outcome.+const TYPED_BUBBLE =+ "max-w-full self-start whitespace-pre-wrap break-words rounded-[10px] border border-border bg-slate-elevation4 dark:border-white/5 px-2.5 py-1.5 text-[12.5px] leading-[1.45] text-foreground";++// The read-only record of a question, laid out like the tray it was answered in. A pending+// question is answered in the composer's QuestionTray; this is what the transcript shows after.export function QuestionPartsCard({interaction,}: {interaction: QuestionInteraction;}) {- const submitted = Object.fromEntries(- (interaction.response?.answers ?? []).map((answer) => [- answer.part_id,- answer,- ]),- );+ const answers = interaction.response?.answers ?? [];+ const submitted = new Map(answers.map((answer) => [answer.part_id, answer]));+ const total = interaction.parts.length;+ const resolved = interaction.status === "resolved";+ const skippedAll = resolved && Boolean(interaction.response?.skipped);+ // A reply sent as a message answers the whole question, not one part of it.+ const repliedWhole =+ resolved && !answers.some(hasAnswer) && interaction.response?.text != null;+ const answered = resolved && !skippedAll;return (<divrole="group"aria-label="Question record"data-interaction-id={interaction.interaction_id}- className="flex min-w-0 flex-col p-2"+ className="flex min-w-0 flex-col">{interaction.parts.map((part, index) => {- const answer = submitted[part.part_id];+ const answer = submitted.get(part.part_id);+ const keyed = part.choices.length <= MAX_KEYED_CHOICES;return (<divkey={part.part_id}data-part-id={part.part_id}- className={`flex min-w-0 flex-col gap-2 px-1 py-2 ${index > 0 ? "border-t border-border" : ""}`}+ className={cn(+ "flex min-w-0 flex-col gap-2 p-3",+ index > 0 && "border-t border-border",+ )}>- <p className="whitespace-pre-wrap break-words text-[13px] leading-relaxed">- {part.prompt}- </p>+ <div className="flex min-w-0 flex-col gap-0.5">+ {total > 1 ? (+ <span+ className={cn(+ "text-[10.5px] font-bold tabular-nums leading-4",+ answered+ ? "text-emerald-700 dark:text-emerald-300"+ : "text-muted-foreground",+ )}+ >+ {index + 1} of {total}+ </span>+ ) : null}+ <p className="whitespace-pre-wrap break-words text-[13px] font-medium leading-normal">+ {part.prompt}+ </p>+ </div>{part.choices.length > 0 ? (<div className="flex flex-wrap gap-1.5">- {part.choices.map((choice) => (- <span- key={choice.choice_id}- data-selected={answer?.choice_id === choice.choice_id}- className="flex max-w-full items-start gap-1.5 whitespace-pre-wrap break-words rounded-md border border-border px-2 py-1 text-xs data-[selected=true]:border-success data-[selected=true]:bg-accent"- >- {answer?.choice_id === choice.choice_id ? (- <CheckIcon className="size-3.5 shrink-0 text-success" />- ) : null}- <span className="min-w-0 break-words">{choice.text}</span>- </span>- ))}+ {part.choices.map((choice, choiceIndex) => {+ const selected = answer?.choice_id === choice.choice_id;+ return (+ <span+ key={choice.choice_id}+ data-selected={selected}+ className={cn(+ "flex max-w-full items-start gap-1.5 rounded-md border py-1 pl-1.5 pr-2.5 text-xs",+ selected+ ? "border-emerald-400/60 bg-emerald-500/15 font-semibold text-emerald-800 dark:text-emerald-200"+ : "border-border text-muted-foreground",+ )}+ >+ {selected ? (+ <>+ <CheckIcon+ aria-hidden+ className="size-4 shrink-0 text-emerald-600 dark:text-emerald-300"+ />+ <span className="sr-only">Selected: </span>+ </>+ ) : keyed ? (+ <kbd+ aria-hidden+ className="h-4 min-w-4 shrink-0 rounded border border-border px-1 text-center font-mono text-[10px] leading-[14px] text-muted-foreground"+ >+ {choiceIndex + 1}+ </kbd>+ ) : null}+ <span className="min-w-0 whitespace-pre-wrap break-words">+ {choice.text}+ </span>+ </span>+ );+ })}</div>) : null}- {interaction.status === "resolved" ? (- <p className="whitespace-pre-wrap break-words text-xs text-muted-foreground">- {answer?.text ??- (answer?.choice_id- ? "Selected"- : part.choices.length > 0- ? "No choice selected"- : "No answer")}- </p>+ {answer?.text ? (+ <p className={TYPED_BUBBLE}>{answer.text}</p>+ ) : answer?.text === "" && answer.choice_id == null ? (+ <p className="text-xs text-muted-foreground">Sent with no text</p>+ ) : answered && !repliedWhole && !hasAnswer(answer) ? (+ <p className="text-xs text-muted-foreground">Skipped</p>) : null}</div>);})}- {interaction.response?.text != null ? (- <p className="whitespace-pre-wrap break-words border-t border-border px-1 py-2 text-sm">- {interaction.response.text}- </p>+ {interaction.response?.text ? (+ <div className="flex border-t border-border p-3">+ <p className={TYPED_BUBBLE}>{interaction.response.text}</p>+ </div>) : null}</div>);diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionReceipt.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionReceipt.test.tsxindex 3545c8a10..a519146c2 100644--- a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionReceipt.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionReceipt.test.tsx@@ -58,12 +58,15 @@ it("hydrates the record from persisted IDs after remounting", () => {const { container } = render(<QuestionReceipt interaction={JSON.parse(JSON.stringify(resolved))} />,);- expect(screen.getByText("CSV · Zip it")).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: /Show questions/ }));+ expect(screen.getByText("You answered 1 of 3 questions")).toBeTruthy();+ expect(screen.queryByText("CSV")).toBeNull();+ fireEvent.click(+ screen.getByRole("button", { name: /You answered 1 of 3 questions/ }),+ );const part = (id: string) =>within(container.querySelector(`[data-part-id="${id}"]`) as HTMLElement);- expect(part("first").getByText("No choice selected")).toBeTruthy();- expect(part("third").getByText("No answer")).toBeTruthy();+ expect(part("first").getByText("Skipped")).toBeTruthy();+ expect(part("third").getByText("Skipped")).toBeTruthy();expect(part("second").getByText("CSV")@@ -71,6 +74,30 @@ it("hydrates the record from persisted IDs after remounting", () => {?.getAttribute("data-selected"),).toBe("true");expect(part("second").getByText("Zip it")).toBeTruthy();+ expect(part("second").getByText("Selected:")).toBeTruthy();+});++it("counts an empty-string answer as answered, as the backend does", () => {+ render(+ <QuestionReceipt+ interaction={{+ ...asked,+ status: "resolved",+ response: {+ answers: [+ { part_id: "first", choice_id: "pdf" },+ { part_id: "second", choice_id: null, text: "" },+ ],+ },+ }}+ />,+ );+ expect(screen.getByText("You answered 2 questions")).toBeTruthy();+ fireEvent.click(+ screen.getByRole("button", { name: /You answered 2 questions/ }),+ );+ expect(screen.getByText("Sent with no text")).toBeTruthy();+ expect(screen.queryByText("Skipped")).toBeNull();});it("keeps skipped, cancelled, and interrupted questions read-only", () => {@@ -83,14 +110,29 @@ it("keeps skipped, cancelled, and interrupted questions read-only", () => {}}/>,);- expect(screen.getByText("Skipped 2 questions")).toBeTruthy();+ expect(screen.getByText("You skipped 2 questions")).toBeTruthy();rerender(<QuestionReceipt interaction={{ ...asked, status: "cancelled" }} />);expect(screen.getByText("Question cancelled")).toBeTruthy();rerender(<QuestionReceipt interaction={{ ...asked, status: "interrupted" }} />,);expect(screen.getByText("Question interrupted")).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: /Show questions/ }));+ fireEvent.click(screen.getByRole("button", { name: /Question interrupted/ }));expect(screen.queryByRole("button", { name: "Send" })).toBeNull();expect(screen.queryByRole("textbox")).toBeNull();});++it("shows a whole-question reply without marking each part skipped", () => {+ render(+ <QuestionReceipt+ interaction={{+ ...asked,+ status: "resolved",+ response: { text: "Use whichever is smaller" },+ }}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: /You replied/ }));+ expect(screen.getByText("Use whichever is smaller")).toBeTruthy();+ expect(screen.queryByText("Skipped")).toBeNull();+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionReceipt.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionReceipt.tsxindex 62c80461b..ef9724871 100644--- a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionReceipt.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionReceipt.tsx@@ -1,35 +1,85 @@import { useState } from "react";import {- CheckIcon,- ChevronDownIcon,ChevronRightIcon,- CrossCircledIcon,- MinusCircledIcon,QuestionMarkCircledIcon,} from "@radix-ui/react-icons";import { cn } from "@/util/utils";+import { parseUtcIsoMs } from "../narrativeState";import type { QuestionInteraction } from "../workflowCopilotTypes";import { QuestionPartsCard } from "./QuestionPartsCard";+import { answeredPartIds } from "./questionAnswers";-function answerSummary(interaction: QuestionInteraction): string {- const byPart = new Map(- (interaction.response?.answers ?? []).map((answer) => [- answer.part_id,- answer,- ]),- );- const pieces = interaction.parts.flatMap((part) => {- const answer = byPart.get(part.part_id);- if (!answer) return [];- const choice = part.choices.find(- (item) => item.choice_id === answer.choice_id,- );- return [choice?.text, answer.text].filter(- (piece): piece is string => piece != null && piece !== "",- );+type Tone = "answered" | "neutral" | "error";++const TONE_CLASSES: Record<Tone, { card: string; dot: string; title: string }> =+ {+ answered: {+ card: "border-emerald-500/40 bg-emerald-500/[0.06]",+ dot: "bg-emerald-500 shadow-[0_0_0_3px_rgba(16,185,129,0.18)]",+ title: "text-emerald-700 dark:text-emerald-300",+ },+ neutral: {+ card: "border-slate-400/30 bg-slate-400/[0.05]",+ dot: "bg-slate-500",+ title: "text-slate-600 dark:text-slate-300",+ },+ error: {+ card: "border-rose-400/35 bg-rose-500/[0.05]",+ dot: "bg-rose-500",+ title: "text-rose-700 dark:text-rose-300",+ },+ };++function questions(count: number): string {+ return count === 1 ? "1 question" : `${count} questions`;+}++function formatAnsweredAt(value: string | null): string | null {+ const ms = parseUtcIsoMs(value);+ if (ms === null) return null;+ return new Date(ms).toLocaleTimeString("en-US", {+ hour: "numeric",+ minute: "2-digit",});- if (interaction.response?.text) pieces.push(interaction.response.text);- return pieces.join(" · ");+}++function receiptHeading(interaction: QuestionInteraction): {+ tone: Tone;+ title: string;+ meta: string | null;+} {+ const total = interaction.parts.length;+ if (interaction.status === "cancelled") {+ return { tone: "neutral", title: "Question cancelled", meta: null };+ }+ if (interaction.status === "interrupted") {+ return { tone: "error", title: "Question interrupted", meta: null };+ }+ const at = formatAnsweredAt(interaction.resolved_at);+ if (interaction.response?.skipped) {+ return {+ tone: "neutral",+ title: `You skipped ${total === 1 ? "the question" : questions(total)}`,+ meta: at,+ };+ }+ const answered = answeredPartIds(interaction).size;+ if (answered === 0) {+ return { tone: "answered", title: "You replied", meta: at };+ }+ if (answered === total) {+ return {+ tone: "answered",+ title: `You answered ${questions(total)}`,+ meta: at,+ };+ }+ const skipped = `${total - answered} skipped`;+ return {+ tone: "answered",+ title: `You answered ${answered} of ${questions(total)}`,+ meta: at ? `${skipped} · ${at}` : skipped,+ };}// Where a question sits in the transcript. While it is pending the answer happens in the@@ -41,7 +91,6 @@ export function QuestionReceipt({}) {const [open, setOpen] = useState(false);const count = interaction.parts.length;- const noun = count === 1 ? "question" : "questions";if (interaction.status === "pending") {return (@@ -60,66 +109,52 @@ export function QuestionReceipt({);}- const skipped =- interaction.status === "resolved" && interaction.response?.skipped;- const summary =- interaction.status === "resolved" ? answerSummary(interaction) : "";- const title =- interaction.status === "cancelled"- ? "Question cancelled"- : interaction.status === "interrupted"- ? "Question interrupted"- : skipped- ? `Skipped ${count === 1 ? "the question" : `${count} questions`}`- : summary || "Response sent";- const detail =- interaction.status === "interrupted"- ? "This question's session ended. Send a new message to continue."- : null;- const Icon =- interaction.status === "resolved" && !skipped- ? CheckIcon- : interaction.status === "interrupted"- ? CrossCircledIcon- : MinusCircledIcon;+ const { tone, title, meta } = receiptHeading(interaction);+ const classes = TONE_CLASSES[tone];return (<divdata-interaction-id={interaction.interaction_id}- className="min-w-0 overflow-hidden rounded-lg border border-border bg-slate-elevation2"+ className={cn("min-w-0 overflow-hidden rounded-lg border", classes.card)}><buttontype="button"aria-expanded={open}onClick={() => setOpen((value) => !value)}- className="flex w-full min-w-0 items-start gap-2 px-3 py-2 text-left text-xs hover:bg-slate-elevation3 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"+ className="flex w-full min-w-0 items-start gap-2 px-3 py-[11px] text-left text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring">- <Icon+ <ChevronRightIconaria-hiddenclassName={cn(- "mt-px size-3.5 shrink-0",- Icon === CheckIcon ? "text-success" : "text-muted-foreground",+ "mt-0.5 size-3.5 shrink-0 text-muted-foreground transition-transform",+ open && "rotate-90",)}/>- <span className="flex min-w-0 flex-1 flex-col gap-0.5">- <span className="whitespace-pre-wrap break-words text-foreground">- {title}+ <span+ aria-hidden+ className={cn("mt-[5px] size-2 shrink-0 rounded-full", classes.dot)}+ />+ <span className="flex min-w-0 flex-1 flex-col gap-0.5 leading-[18px]">+ <span className="min-w-0 break-words">+ <span className={cn("font-semibold", classes.title)}>{title}</span>+ {meta ? (+ <span className="text-muted-foreground"> · {meta}</span>+ ) : null}</span>- {detail ? (- <span className="text-muted-foreground">{detail}</span>+ {interaction.status === "interrupted" ? (+ <span className="text-muted-foreground">+ This question's session ended. Send a new message to continue.+ </span>) : null}- <span className="text-muted-foreground">- {open ? "Hide" : "Show"} {noun}- </span></span>- {open ? (- <ChevronDownIcon className="mt-px size-3.5 shrink-0 text-muted-foreground" />- ) : (- <ChevronRightIcon className="mt-px size-3.5 shrink-0 text-muted-foreground" />- )}</button>{open ? (- <div className="border-t border-border">+ <div+ className={cn(+ "border-t bg-slate-elevation2",+ tone === "answered" ? "border-emerald-500/25" : "border-border",+ )}+ ><QuestionPartsCard interaction={interaction} /></div>) : null}diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionTray.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionTray.tsxindex b527a0b53..92fa2770d 100644--- a/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionTray.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/QuestionTray.tsx@@ -9,7 +9,7 @@ import { cn } from "@/util/utils";import type { QuestionStepper } from "../useQuestionStepper";import type { QuestionInteraction } from "../workflowCopilotTypes";-const MAX_KEYED_CHOICES = 9;+export const MAX_KEYED_CHOICES = 9;// One tray renders at a time, so the composer can name the prompt it is answering.export const QUESTION_PROMPT_ID = "copilot-question-prompt";diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/TestRunOutputCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/TestRunOutputCard.test.tsxnew file mode 100644index 000000000..2e11fbd73--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/TestRunOutputCard.test.tsx@@ -0,0 +1,105 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";++import type { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";++import { TestRunOutputCard } from "./TestRunOutputCard";++const factsWith = (extracted: unknown) => ({+ workflow_run_id: "wr-1",+ status: "completed",+ available: true,+ failure_reason: null,+ outputs: [+ {+ output_parameter_id: "op-1",+ value: {+ task_id: "tsk_hidden",+ status: "completed",+ extracted_information: extracted,+ },+ },+ ],+});++describe("TestRunOutputCard", () => {+ it.each([+ ["an object", { price: "12.50" }, "12.50"],+ ["a list", [{ name: "First row" }, { name: "Second row" }], "Second row"],+ ["a string", "Only one line of text", "Only one line of text"],+ ])(+ "shows an extraction that is %s without opening the raw output",+ (_, extracted, visible) => {+ render(+ <TestRunOutputCard facts={factsWith(extracted)} workflow={null} />,+ );++ const card = screen.getByTestId("proposal-run-facts");+ expect(card.textContent).toContain(visible);+ expect(card.textContent).not.toContain("tsk_hidden");+ },+ );++ it.each([+ ["failed", true],+ ["canceled", false],+ ["terminated", false],+ ["timed_out", false],+ ])("marks a %s run as failed only when it failed", (status, marked) => {+ render(+ <TestRunOutputCard+ facts={{ ...factsWith({ price: "1" }), status }}+ workflow={null}+ />,+ );+ const card = screen.getByTestId("proposal-run-facts");+ expect(card.textContent).toContain(status);+ expect(+ card.querySelector(".text-destructive svg, svg.text-destructive") !==+ null,+ ).toBe(marked);+ });++ it("orders outputs by reading order, a conditional's branch before its merge block", () => {+ const block = (label: string, extra: Record<string, unknown> = {}) => ({+ label,+ block_type: "task",+ next_block_label: null,+ output_parameter: { output_parameter_id: `op-${label}` },+ ...extra,+ });+ // The editor saves branch children after the merge block in the array.+ const workflow = {+ workflow_definition: {+ blocks: [+ block("pick_path", {+ block_type: "conditional",+ next_block_label: "save_total",+ branch_conditions: [{ next_block_label: "read_price" }],+ }),+ block("save_total"),+ block("read_price", { next_block_label: "save_total" }),+ ],+ },+ } as unknown as WorkflowApiResponse;+ const output = (label: string, value: string) => ({+ output_parameter_id: `op-${label}`,+ value: { extracted_information: { [label]: value } },+ });+ render(+ <TestRunOutputCard+ facts={{+ ...factsWith(null),+ outputs: [+ output("save_total", "final"),+ output("read_price", "early"),+ ],+ }}+ workflow={workflow}+ />,+ );+ const text = screen.getByTestId("proposal-run-facts").textContent ?? "";+ // The last block in reading order is the emphasized result, rendered first.+ expect(text.indexOf("final")).toBeLessThan(text.indexOf("early"));+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/TestRunOutputCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/TestRunOutputCard.tsxnew file mode 100644index 000000000..c6b765221--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/TestRunOutputCard.tsx@@ -0,0 +1,246 @@+import React, { useState } from "react";+import {+ ChevronRightIcon,+ CrossCircledIcon,+ ExternalLinkIcon,+} from "@radix-ui/react-icons";++import { Status } from "@/api/types";+import type {+ WorkflowApiResponse,+ WorkflowBlock,+} from "@/routes/workflows/types/workflowTypes";+import { visitWorkflowBlocks } from "../../workflowBlockUtils";+import { humanizeBlockLabel } from "../blockLabel";+import { TURN_ROW_INSET } from "./cardLayout";+import type { CopilotProposalRunFacts } from "../workflowCopilotTypes";++type RunOutput = CopilotProposalRunFacts["outputs"][number];++function isEmptyValue(value: unknown): boolean {+ if (value === null || value === undefined || value === "") return true;+ if (Array.isArray(value)) return value.length === 0;+ if (typeof value === "object") return Object.keys(value).length === 0;+ return false;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function renderOutputValue(value: unknown): React.ReactNode {+ if (isEmptyValue(value)) {+ return <span>—</span>;+ }+ if (typeof value === "string") {+ return (+ <span className="whitespace-pre-wrap [overflow-wrap:anywhere]">+ {value}+ </span>+ );+ }+ if (Array.isArray(value)) {+ return (+ <div className="ml-3">+ {value.map((item, index) => (+ <div key={index}>+ <span className="font-medium">{index + 1}.</span>{" "}+ {renderOutputValue(item)}+ </div>+ ))}+ </div>+ );+ }+ if (isRecord(value)) {+ return (+ <div className="ml-3">+ {Object.entries(value).map(([key, item]) => (+ <div key={key}>+ <span className="font-medium">{key}:</span>{" "}+ {renderOutputValue(item)}+ </div>+ ))}+ </div>+ );+ }+ return <span>{String(value)}</span>;+}++// A task block's output wraps its extraction (an object, list, or string) in+// bookkeeping such as ids and artifact lists; the extraction is the result.+function resultFields(value: unknown): Array<[string, unknown]> {+ if (isRecord(value) && "extracted_information" in value) {+ value = value.extracted_information;+ }+ if (!isRecord(value)) {+ return isEmptyValue(value) ? [] : [["result", value]];+ }+ return Object.entries(value).filter(([, item]) => !isEmptyValue(item));+}++function fieldName(key: string): string {+ const words = key.replace(/_/g, " ").trim();+ return words.length === 0 ? key : words[0]!.toUpperCase() + words.slice(1);+}++function Fields({+ fields,+ emphasized,+}: {+ fields: Array<[string, unknown]>;+ emphasized: boolean;+}) {+ return (+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs">+ {fields.map(([key, item]) => (+ <React.Fragment key={key}>+ <dt className="text-muted-foreground">{fieldName(key)}</dt>+ <dd+ className={`min-w-0 font-mono [overflow-wrap:anywhere] ${+ emphasized ? "text-foreground" : "text-muted-foreground"+ }`}+ >+ {renderOutputValue(item)}+ </dd>+ </React.Fragment>+ ))}+ </dl>+ );+}++function RawOutput({ outputs }: { outputs: RunOutput[] }) {+ const [open, setOpen] = useState(false);+ return (+ <div>+ <button+ type="button"+ aria-expanded={open}+ className="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"+ onClick={() => setOpen((value) => !value)}+ >+ <ChevronRightIcon+ className={`h-3 w-3 transition-transform ${open ? "rotate-90" : ""}`}+ />+ Full run output+ </button>+ {open ? (+ <div className="mt-1.5 space-y-1 text-xs text-muted-foreground">+ {outputs.map((output) => (+ <div key={output.output_parameter_id}>+ <span className="font-medium text-foreground">+ {output.output_parameter_id}:+ </span>{" "}+ {renderOutputValue(output.value)}+ </div>+ ))}+ </div>+ ) : null}+ </div>+ );+}++export function TestRunOutputCard({+ facts,+ workflow,+}: {+ facts: CopilotProposalRunFacts;+ workflow: WorkflowApiResponse | null;+}) {+ if (!facts.available) {+ return (+ <p+ className={`${TURN_ROW_INSET} text-xs text-muted-foreground`}+ data-testid="proposal-run-facts"+ >+ Associated test run unavailable. No other run was substituted.+ </p>+ );+ }++ const blocks: WorkflowBlock[] = [];+ visitWorkflowBlocks(workflow?.workflow_definition.blocks ?? [], (block) => {+ blocks.push(block);+ });+ const blockOrder = (output: RunOutput) => {+ const index = blocks.findIndex(+ (block) =>+ block.output_parameter?.output_parameter_id ===+ output.output_parameter_id,+ );+ return index === -1 ? blocks.length : index;+ };+ const sections = facts.outputs+ .map((output, arrival) => ({+ output,+ arrival,+ order: blockOrder(output),+ fields: resultFields(output.value),+ }))+ .filter((section) => section.fields.length > 0)+ .sort((a, b) => a.order - b.order || a.arrival - b.arrival);+ // A cancel, termination or timeout is not a failure the run found, so only Failed is marked.+ const failed = facts.status === Status.Failed;+ const final = sections[sections.length - 1];+ const earlier = sections.slice(0, -1);+ const blockName = (order: number) => {+ const block = blocks[order];+ return block === undefined ? null : humanizeBlockLabel(block.label);+ };++ return (+ <div+ className="overflow-hidden rounded-[10px] border border-border bg-slate-elevation2"+ data-testid="proposal-run-facts"+ >+ <div className="flex items-center gap-2 px-3 pt-3 text-xs font-semibold text-foreground">+ {failed ? (+ <CrossCircledIcon className="h-3.5 w-3.5 text-destructive" />+ ) : null}+ Test run output+ {facts.status === Status.Completed ? null : (+ <span className="font-normal text-muted-foreground">+ {` · ${facts.status ?? "status unavailable"}`}+ </span>+ )}+ <a+ className="ml-auto flex items-center gap-1 text-[11px] font-normal text-muted-foreground hover:text-foreground"+ href={`/runs/${facts.workflow_run_id}`}+ target="_blank"+ rel="noopener noreferrer"+ >+ View run <ExternalLinkIcon className="h-3 w-3" />+ </a>+ </div>+ <div className="space-y-3 px-3 pb-3 pt-2">+ {facts.failure_reason ? (+ <p className="whitespace-pre-wrap text-xs text-destructive [overflow-wrap:anywhere]">+ {facts.failure_reason}+ </p>+ ) : null}+ {final ? (+ <div className="rounded-md border border-border bg-slate-elevation3 p-2.5">+ {blockName(final.order) ? (+ <div className="mb-1.5 text-[10px] font-bold uppercase tracking-wide text-muted-foreground">+ {blockName(final.order)}+ </div>+ ) : null}+ <Fields fields={final.fields} emphasized />+ </div>+ ) : null}+ {earlier.map((section) => (+ <div key={section.output.output_parameter_id} className="px-0.5">+ {blockName(section.order) ? (+ <div className="mb-1 text-[10px] font-bold uppercase tracking-wide text-muted-foreground">+ {blockName(section.order)}+ </div>+ ) : null}+ <Fields fields={section.fields} emphasized={false} />+ </div>+ ))}+ {facts.outputs.length > 0 ? (+ <RawOutput outputs={facts.outputs} />+ ) : null}+ </div>+ </div>+ );+}diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswers.ts b/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswers.tsnew file mode 100644index 000000000..afaa8189b--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/questionAnswers.ts@@ -0,0 +1,17 @@+import type {+ QuestionAnswer,+ QuestionInteraction,+} from "../workflowCopilotTypes";++// The backend accepts an empty-string text as an answer, so only null means "not answered".+export function hasAnswer(answer: QuestionAnswer | undefined): boolean {+ return answer?.choice_id != null || answer?.text != null;+}++export function answeredPartIds(interaction: QuestionInteraction): Set<string> {+ return new Set(+ (interaction.response?.answers ?? [])+ .filter(hasAnswer)+ .map((answer) => answer.part_id),+ );+}diff --git a/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.test.ts b/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.test.tsindex 511c319c2..d781c0bab 100644--- a/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.test.ts@@ -1,10 +1,11 @@import { describe, expect, it } from "vitest";import {- ACTIVITY_KIND_GLYPH,ActivityLog,+ callRollup,deriveActivityLog,kindOf,+ summarizeFinishedTurn,} from "./copilotActivityLog";import {ActivityEntry,@@ -30,6 +31,10 @@ const entry = (...overrides,});+// Stamps a fixture in the order it happened, one second apart.+const inOrder = (entries: ActivityEntry[]): ActivityEntry[] =>+ entries.map((e, i) => ({ ...e, timestamp: at(i) }));+const block = (overrides: Partial<BlockState> = {}): BlockState => ({workflowRunBlockId: "wrb_1",label: "block_1",@@ -290,9 +295,6 @@ const idsOf = (log: ActivityLog): string[] => log.rows.map((r) => r.id);const labelsPerRow = (log: ActivityLog): string[][] =>log.rows.map((r) => r.blocks.map((b) => b.label));-const glyphsOf = (log: ActivityLog): string[] =>- log.rows.map((r) => (r.kind === null ? "" : ACTIVITY_KIND_GLYPH[r.kind]));-describe("deriveActivityLog", () => {it("keeps a repair loop in happened-order with unique keys", () => {const log = deriveActivityLog(turnWith(repairLoopActivity()));@@ -307,20 +309,21 @@ describe("deriveActivityLog", () => {"author","run",]);- expect(glyphsOf(log)).toEqual(["◎", "⟨⟩", "▷", "◎", "⟨⟩", "▷"]);});it("never moves, re-identifies or re-opens an earlier row as the turn grows", () => {const full = repairLoopActivity();- const finalRows = deriveActivityLog(turnWith(full)).rows;+ const finalRows = deriveActivityLog({+ ...turnWith(full),+ terminal: "response",+ }).rows;for (let k = 1; k <= full.length; k += 1) {const log = deriveActivityLog(turnWith(full.slice(0, k)));- expect(log.rows).toEqual(finalRows.slice(0, k));- expect(glyphsOf(log)).toEqual(- finalRows- .slice(0, k)- .map((r) => (r.kind ? ACTIVITY_KIND_GLYPH[r.kind] : "")),+ expect(log.rows.slice(0, -1)).toEqual(finalRows.slice(0, k - 1));+ // The newest step is the one still being worked on.+ expect({ ...log.rows[log.rows.length - 1]!, live: false }).toEqual(+ finalRows[k - 1],);}});@@ -361,7 +364,6 @@ describe("deriveActivityLog", () => {);expect(log.rows.map((r) => r.kind)).toEqual(["author", "author", "author"]);- expect(glyphsOf(log)).toEqual(["⟨⟩", "⟨⟩", "⟨⟩"]);});it("keeps a failed browse action separate from preceding successful work", () => {@@ -381,7 +383,6 @@ describe("deriveActivityLog", () => {text: "Opening the search form",iteration: 0,activeLabel: "Opening the certificant search",- outcomeLabel: "Opened the certificant search",}),entry({id: "tr-2",@@ -397,87 +398,83 @@ describe("deriveActivityLog", () => {text: "Restoring the results page",iteration: 1,activeLabel: "Restoring access to the certification results",- outcomeLabel: "Restored the certification results",}),]),);expect(log.rows).toHaveLength(2);- expect(log.rows.map((row) => row.label)).toEqual([- "Opened the certificant search",- "Restoring access to the certification results",+ expect(log.rows.map((row) => row.reason)).toEqual([+ "Opening the search form",+ "Restoring the results page",]);expect(log.rows[0]?.entries[0]?.success).toBe(true);expect(log.rows[1]?.entries[0]?.success).toBe(false);});- it("coalesces differently implemented retries of one narrated browse activity", () => {+ it("keeps each narrated retry of one browse activity as its own step, in order", () => {const log = deriveActivityLog(- turnWith([- entry({- id: "tr-1",- kind: "tool_result",- toolName: "navigate_browser",- text: "The browser target was unavailable",- success: false,- iteration: 0,- }),- entry({- id: "n-1",- kind: "narration",- text: "Looking for the certification record",- iteration: 0,- activeLabel: "Searching for the certification record",- outcomeLabel: "Found the certification record",- }),- entry({- id: "tr-2",- kind: "tool_result",- toolName: "get_page_evidence",- text: "The results page did not load",- success: false,- iteration: 1,- }),- entry({- id: "n-2",- kind: "narration",- text: "Trying the search again",- iteration: 1,- activeLabel: "Searching for the certification record",- outcomeLabel: "Found the certification record",- }),- entry({- id: "tc-3",- kind: "tool_call",- toolName: "click_element",- text: "Opening the search form",- iteration: 2,- }),- entry({- id: "n-3",- kind: "narration",- text: "Trying a direct search",- iteration: 2,- activeLabel: "Searching for the certification record",- outcomeLabel: "Found the certification record",- }),- ]),+ turnWith(+ inOrder([+ entry({+ id: "tr-1",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "The browser target was unavailable",+ success: false,+ iteration: 0,+ }),+ entry({+ id: "n-1",+ kind: "narration",+ text: "Looking for the certification record",+ iteration: 0,+ activeLabel: "Searching for the certification record",+ }),+ entry({+ id: "tr-2",+ kind: "tool_result",+ toolName: "get_page_evidence",+ text: "The results page did not load",+ success: false,+ iteration: 1,+ }),+ entry({+ id: "n-2",+ kind: "narration",+ text: "Trying the search again",+ iteration: 1,+ activeLabel: "Searching for the certification record",+ }),+ entry({+ id: "tc-3",+ kind: "tool_call",+ toolName: "click_element",+ text: "Opening the search form",+ iteration: 2,+ }),+ entry({+ id: "n-3",+ kind: "narration",+ text: "Trying a direct search",+ iteration: 2,+ activeLabel: "Searching for the certification record",+ }),+ ]),+ ),);- expect(log.rows).toHaveLength(1);- expect(log.rows[0]).toMatchObject({- id: "1",- label: "Searching for the certification record",+ expect(log.rows.map((row) => row.reason)).toEqual([+ "Looking for the certification record",+ "Trying the search again",+ "Trying a direct search",+ ]);+ expect(log.rows.map((row) => row.live)).toEqual([false, false, true]);+ expect(log.rows[2]).toMatchObject({pending: true,- live: true,- startedAt: at(1),- endedAt: at(3),});- expect(log.rows[0]?.entries).toHaveLength(3);- expect(log.rows[0]?.entries[2]?.attempts).toBe(3);});- it("keeps overlapping browse siblings separate even with the same narrated intent", () => {+ it("keeps overlapping browse siblings separate and opens no line over them while they run", () => {const log = deriveActivityLog(turnWith([entry({@@ -519,9 +516,8 @@ describe("deriveActivityLog", () => {]),);- expect(log.rows).toHaveLength(2);- expect(log.rows.map((row) => row.entries.length)).toEqual([1, 1]);expect(log.rows.map((row) => row.id)).toEqual(["a", "b"]);+ expect(log.rows.map((row) => row.entries.length)).toEqual([1, 1]);});it("keeps browse tools from one iteration folded into one activity", () => {@@ -847,7 +843,10 @@ describe("deriveActivityLog", () => {});it("derives the same rows from a hydrated narrative payload as from the live turn", () => {- const liveRows = deriveActivityLog(turnWith(repairLoopActivity())).rows;+ const liveRows = deriveActivityLog({+ ...turnWith(repairLoopActivity()),+ terminal: "response",+ }).rows;const hydrated = hydrateNarrativeFromPayload({turnId: "turn-1",turnIndex: 0,@@ -859,7 +858,6 @@ describe("deriveActivityLog", () => {const hydratedLog = deriveActivityLog(hydrated!);expect(hydratedLog.rows).toEqual(liveRows);- expect(glyphsOf(hydratedLog)).toEqual(["◎", "⟨⟩", "▷", "◎", "⟨⟩", "▷"]);});it("groups consecutive browse steps into one row and counts them", () => {@@ -885,40 +883,42 @@ describe("deriveActivityLog", () => {expect(log.rows[0]?.entries[2]?.text).toBe("Browse step 2");});- it("attaches a narration to the row owning its iteration, emitting no row of its own", () => {+ it("attaches a lagging narration to the call in flight when it was spoken", () => {const log = deriveActivityLog(- turnWith([- entry({- id: "tr-1",- kind: "tool_result",- toolName: "navigate_browser",- text: "Opened the sign-in page",- success: true,- }),- entry({- id: "tc-2",- kind: "tool_call",- toolName: "update_workflow",- displayLabel: "Saving blocks",- iteration: 1,- }),- entry({- id: "n-1",- kind: "narration",- text: "Checking which fields the sign-in form needs",- iteration: 0,- }),- ]),+ turnWith(+ inOrder([+ entry({+ id: "tr-1",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "Opened the sign-in page",+ success: true,+ }),+ entry({+ id: "tc-2",+ kind: "tool_call",+ toolName: "update_workflow",+ displayLabel: "Saving blocks",+ iteration: 1,+ }),+ entry({+ id: "n-1",+ kind: "narration",+ text: "Checking which fields the sign-in form needs",+ iteration: 0,+ }),+ ]),+ ),);expect(log.rows.map((r) => r.kind)).toEqual(["browse", "author"]);expect(log.rows.every((r) => r.entries.every((e) => e.kind !== "narration")),).toBe(true);- expect(log.rows[0]?.reason).toBe(+ expect(log.rows[0]?.reason).toBeNull();+ expect(log.rows[1]?.reason).toBe("Checking which fields the sign-in form needs",);- expect(log.rows[1]?.reason).toBeNull();});it("attaches an unmatched narration to the nearest preceding row", () => {@@ -971,7 +971,6 @@ describe("deriveActivityLog", () => {text: "Reviewing the visible credential results",iteration: 2,activeLabel: "Reviewing the credential results",- outcomeLabel: "Reviewed the credential results",timestamp: "2026-01-01T00:00:33Z",}),entry({@@ -989,7 +988,6 @@ describe("deriveActivityLog", () => {expect(log.rows).toHaveLength(2);expect(log.rows[0]?.reason).toBeNull();expect(log.rows[1]).toMatchObject({- label: "Reviewing the credential results",reason: "Reviewing the visible credential results",});});@@ -1035,12 +1033,11 @@ describe("deriveActivityLog", () => {expect(log.rows[0]?.reason).toBeNull();expect(log.rows[1]).toMatchObject({- label: "Reviewing the current result",reason: "Checking the current page for the result",});});- it("uses iteration when parallel pending calls have overlapping time spans", () => {+ it("attaches a narration to its own step when parallel calls are both in flight", () => {const log = deriveActivityLog(turnWith([entry({@@ -1070,8 +1067,8 @@ describe("deriveActivityLog", () => {]),);+ expect(log.rows).toHaveLength(2);expect(log.rows[0]).toMatchObject({- label: "Opening the first page",reason: "Still opening the first page",});expect(log.rows[1]?.reason).toBeNull();@@ -1079,206 +1076,219 @@ describe("deriveActivityLog", () => {it("folds a technical recovery substep into the current narrated attempt", () => {const log = deriveActivityLog(- turnWith([- entry({- id: "tr-inspect",- kind: "tool_result",- toolName: "inspect_page_for_composition",- text: "The page could not be inspected",- success: false,- iteration: 3,- }),- entry({- id: "n-3",- kind: "narration",- text: "The result page stopped responding",- iteration: 3,- activeLabel: "Reviewing the credential results",- }),- entry({- id: "tr-evaluate",- kind: "tool_result",- toolName: "evaluate",- text: "The page was unavailable",- success: false,- iteration: 4,- }),- ]),+ turnWith(+ inOrder([+ entry({+ id: "tr-inspect",+ kind: "tool_result",+ toolName: "inspect_page_for_composition",+ text: "The page could not be inspected",+ success: false,+ iteration: 3,+ }),+ entry({+ id: "n-3",+ kind: "narration",+ text: "The result page stopped responding",+ iteration: 3,+ activeLabel: "Reviewing the credential results",+ }),+ entry({+ id: "tr-evaluate",+ kind: "tool_result",+ toolName: "evaluate",+ text: "The page was unavailable",+ success: false,+ iteration: 4,+ }),+ ]),+ ),);expect(log.rows).toHaveLength(1);expect(log.rows[0]).toMatchObject({- label: "Reviewing the credential results",id: "inspect",});expect(log.rows[0]?.entries[1]?.attempts).toBe(2);});- it("starts a new retry row after the prior narrated attempt recovered", () => {+ it("keeps each narrated attempt as its own step", () => {+ const log = deriveActivityLog(+ turnWith(+ inOrder([+ entry({+ id: "tr-failed",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "The page did not open",+ success: false,+ iteration: 0,+ }),+ entry({+ id: "n-failed",+ kind: "narration",+ text: "Trying the page",+ iteration: 0,+ activeLabel: "Opening the page",+ }),+ entry({+ id: "tr-recovered",+ kind: "tool_result",+ toolName: "get_page_evidence",+ text: "Read the page",+ success: true,+ iteration: 1,+ }),+ entry({+ id: "n-recovered",+ kind: "narration",+ text: "The page is available",+ iteration: 1,+ activeLabel: "Opening the page",+ }),+ entry({+ id: "tr-later",+ kind: "tool_result",+ toolName: "click_element",+ text: "The next click failed",+ success: false,+ iteration: 2,+ }),+ entry({+ id: "n-later",+ kind: "narration",+ text: "Trying the next control",+ iteration: 2,+ activeLabel: "Opening the page",+ }),+ ]),+ ),+ );++ expect(log.rows.map((row) => row.entries[0]?.success)).toEqual([+ false,+ true,+ false,+ ]);+ });++ it("keeps a pending attempt live while a later attempt settles", () => {+ const log = deriveActivityLog(+ turnWith(+ inOrder([+ entry({+ id: "tr-first",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "The first attempt failed",+ success: false,+ iteration: 0,+ }),+ entry({+ id: "n-first",+ kind: "narration",+ text: "Trying the search",+ iteration: 0,+ activeLabel: "Searching the page",+ }),+ entry({+ id: "tc-pending",+ kind: "tool_call",+ toolName: "get_page_evidence",+ text: "Inspecting the page",+ iteration: 1,+ }),+ entry({+ id: "n-pending",+ kind: "narration",+ text: "Trying the search again",+ iteration: 1,+ activeLabel: "Searching the page",+ }),+ entry({+ id: "tr-sibling",+ kind: "tool_result",+ toolName: "click_element",+ text: "The sibling attempt failed",+ success: false,+ iteration: 2,+ }),+ entry({+ id: "n-sibling",+ kind: "narration",+ text: "Still trying the search",+ iteration: 2,+ activeLabel: "Searching the page",+ }),+ ]),+ ),+ );++ expect(log.rows).toHaveLength(3);+ expect(log.rows[1]).toMatchObject({ pending: true, live: true });+ expect(log.rows[2]).toMatchObject({ pending: false, live: false });+ expect(log.liveIndex).toBe(1);+ });++ it("renders a narration that arrives before any call as its own line", () => {const log = deriveActivityLog(turnWith([entry({- id: "tr-failed",- kind: "tool_result",- toolName: "navigate_browser",- text: "The page did not open",- success: false,- iteration: 0,- }),- entry({- id: "n-failed",- kind: "narration",- text: "Trying the page",- iteration: 0,- activeLabel: "Opening the page",- }),- entry({- id: "tr-recovered",- kind: "tool_result",- toolName: "get_page_evidence",- text: "Read the page",- success: true,- iteration: 1,- }),- entry({- id: "n-recovered",- kind: "narration",- text: "The page is available",- iteration: 1,- activeLabel: "Opening the page",- }),- entry({- id: "tr-later",- kind: "tool_result",- toolName: "click_element",- text: "The next click failed",- success: false,- iteration: 2,- }),- entry({- id: "n-later",+ id: "n-1",kind: "narration",- text: "Trying the next control",- iteration: 2,- activeLabel: "Opening the page",+ text: "Getting started",+ iteration: 4,}),]),);- expect(log.rows).toHaveLength(2);- const recovered = log.rows[0]?.entries;- const later = log.rows[1]?.entries;- expect(recovered?.[recovered.length - 1]?.success).toBe(true);- expect(later?.[later.length - 1]?.success).toBe(false);+ expect(log.rows).toHaveLength(1);+ expect(log.rows[0]).toMatchObject({+ reason: "Getting started",+ });+ expect(log.rows[0]?.entries).toHaveLength(0);});- it("recomputes pending and live after an out-of-order narrated retry merge", () => {+ it("gives each narrated browse iteration its own step and reason", () => {const log = deriveActivityLog(- turnWith([- entry({- id: "tr-first",- kind: "tool_result",- toolName: "navigate_browser",- text: "The first attempt failed",- success: false,- iteration: 0,- }),- entry({- id: "n-first",- kind: "narration",- text: "Trying the search",- iteration: 0,- activeLabel: "Searching the page",- }),- entry({- id: "tc-pending",- kind: "tool_call",- toolName: "get_page_evidence",- text: "Inspecting the page",- iteration: 1,- }),- entry({- id: "n-pending",- kind: "narration",- text: "Trying the search again",- iteration: 1,- activeLabel: "Searching the page",- }),- entry({- id: "tr-sibling",- kind: "tool_result",- toolName: "click_element",- text: "The sibling attempt failed",- success: false,- iteration: 2,- }),- entry({- id: "n-sibling",- kind: "narration",- text: "Still trying the search",- iteration: 2,- activeLabel: "Searching the page",- }),- ]),- );-- expect(log.rows).toHaveLength(2);- expect(log.rows[0]).toMatchObject({ pending: true, live: true });- expect(log.rows[1]).toMatchObject({ pending: false, live: false });- expect(log.liveIndex).toBe(0);- });-- it("drops a narration with no preceding row rather than rendering one", () => {- const log = deriveActivityLog(- turnWith([- entry({- id: "n-1",- kind: "narration",- text: "Getting started",- iteration: 4,- }),- ]),- );-- expect(log.rows).toHaveLength(0);- });-- it("keeps the latest narration when a merged browse row spans two iterations", () => {- const log = deriveActivityLog(- turnWith([- entry({- id: "tr-1",- kind: "tool_result",- toolName: "navigate_browser",- text: "Opened the sign-in page",- success: true,- iteration: 0,- }),- entry({- id: "n-1",- kind: "narration",- text: "Finding the sign-in form",- iteration: 0,- }),- entry({- id: "tr-2",- kind: "tool_result",- toolName: "get_page_evidence",- text: "Read the form state",- success: true,- iteration: 1,- }),- entry({- id: "n-2",- kind: "narration",- text: "Confirming the form accepts an email",- iteration: 1,- }),- ]),+ turnWith(+ inOrder([+ entry({+ id: "tr-1",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "Opened the sign-in page",+ success: true,+ iteration: 0,+ }),+ entry({+ id: "n-1",+ kind: "narration",+ text: "Finding the sign-in form",+ iteration: 0,+ }),+ entry({+ id: "tr-2",+ kind: "tool_result",+ toolName: "get_page_evidence",+ text: "Read the form state",+ success: true,+ iteration: 1,+ }),+ entry({+ id: "n-2",+ kind: "narration",+ text: "Confirming the form accepts an email",+ iteration: 1,+ }),+ ]),+ ),);- expect(log.rows).toHaveLength(1);- expect(log.rows[0]?.reason).toBe("Confirming the form accepts an email");+ expect(log.rows.map((row) => row.reason)).toEqual([+ "Finding the sign-in form",+ "Confirming the form accepts an email",+ ]);});it("marks only the last unresolved tool call live when two are in flight", () => {@@ -1340,10 +1350,12 @@ describe("deriveActivityLog", () => {expect(log.liveIndex).toBe(0);});- it("leaves no row live once every call resolved and no block is running", () => {- expect(deriveActivityLog(turnWith(repairLoopActivity())).liveIndex).toBe(- -1,- );+ it("keeps the newest step live between calls and nothing live once the turn ends", () => {+ const rows = repairLoopActivity();+ expect(deriveActivityLog(turnWith(rows)).liveIndex).toBe(5);+ expect(+ deriveActivityLog({ ...turnWith(rows), terminal: "response" }).liveIndex,+ ).toBe(-1);});it("does not project an evidence-free drafted block", () => {@@ -1678,7 +1690,7 @@ describe("deriveActivityLog", () => {expect(log.rows).toHaveLength(2);expect(log.rows[1]?.kind).toBe("run");expect(log.rows[1]?.blocks.map((b) => b.label)).toEqual(["block_1"]);- expect(log.liveIndex).toBe(-1);+ expect(log.rows[1]?.live).toBe(false);});it("keeps same-label blocks apart so loop iterations stay distinct", () => {@@ -1767,208 +1779,53 @@ describe("deriveActivityLog", () => {expect(log.rows[1]!.reason).toBe("Saving so the run has steps to execute");});- it("titles a finished row with the outcome tense and a live row with the active one", () => {- const activity = [- entry({- id: "tr-1",- kind: "tool_result",- toolName: "navigate_browser",- text: "Opened the catalogue",- success: true,- iteration: 0,- }),- entry({- id: "n-1",- kind: "narration",- text: "Checking whether the invoices need a login",- iteration: 0,- activeLabel: "Looking for the invoice list",- outcomeLabel: "Found the invoices under Billing History",- }),- ];-- const finished = deriveActivityLog({- ...turnWith(activity),- terminal: "response",- });- expect(finished.rows[0]!.label).toBe(- "Found the invoices under Billing History",- );-- const live = deriveActivityLog(- turnWith([- entry({- id: "tc-1",- kind: "tool_call",- toolName: "navigate_browser",- text: "Opening…",- iteration: 0,- }),- entry({- id: "n-1",- kind: "narration",- text: "Checking whether the invoices need a login",- iteration: 0,- activeLabel: "Looking for the invoice list",- outcomeLabel: "Found the invoices under Billing History",- }),- ]),- );- expect(live.liveIndex).toBe(0);- expect(live.rows[0]!.label).toBe("Looking for the invoice list");- });-- it("keeps a failed row's active label instead of showing its predicted outcome", () => {- const log = deriveActivityLog({- ...turnWith([- entry({- id: "tr-1",- kind: "tool_result",- toolName: "update_and_run_blocks",- text: "The submit button stayed disabled",- success: false,- iteration: 0,- }),- entry({- id: "n-1",- kind: "narration",- text: "Confirming the form can be submitted",- iteration: 0,- activeLabel: "Testing form submission",- outcomeLabel: "Confirmed the form submits successfully",- }),- ]),- terminal: "response",- });-- expect(log.rows[0]!.label).toBe("Testing form submission");- });-- it("uses the outcome label after a retry recovers while preserving its failure", () => {- const log = deriveActivityLog({- ...turnWith([- entry({- id: "tr-1",- kind: "tool_result",- toolName: "navigate_browser",- text: "The page did not open",- success: false,- iteration: 0,- }),- entry({- id: "n-1",- kind: "narration",- text: "Trying the page",- iteration: 0,- activeLabel: "Opening the page",- outcomeLabel: "Opened the page",- }),- entry({- id: "tr-2",- kind: "tool_result",- toolName: "navigate_browser",- text: "The page opened",- success: true,- iteration: 1,- }),- entry({- id: "n-2",- kind: "narration",- text: "The retry reached the page",- iteration: 1,- activeLabel: "Opening the page",- outcomeLabel: "Opened the page after retrying",- }),- ]),- terminal: "response",- });-- expect(log.rows).toHaveLength(1);- expect(log.rows[0]?.label).toBe("Opened the page after retrying");- expect(log.rows[0]?.entries[0]?.text).toBe("The page did not open");- expect(log.rows[0]?.entries[1]?.text).toBe("The page opened");- });-- it.each([- ["stopped", undefined],- ["completed", "evaluating"],- ["completed", "not_demonstrated"],- ] as const)(- "keeps the active label for a non-success %s block with outcome %s",- (state, outcome) => {- const log = deriveActivityLog({- ...turnWith(- [- entry({- id: "tr-run",- kind: "tool_result",- toolName: "run_blocks_and_collect_debug",- text: "The run returned",- success: true,- iteration: 0,- }),- entry({- id: "n-run",- kind: "narration",- text: "Checking the run result",- iteration: 0,- activeLabel: "Checking the workflow",- outcomeLabel: "Confirmed the workflow works",- }),- ],- [block({ state, outcome })],- ),- terminal: "response",- });-- expect(log.rows[0]?.label).toBe("Checking the workflow");- },- );-- it("uses the outcome label only when a block has a successful verdict", () => {+ it("keeps a retry announced between attempts as its own step, preserving the failure", () => {const log = deriveActivityLog({...turnWith(- [+ inOrder([entry({- id: "tr-run",+ id: "tr-1",kind: "tool_result",- toolName: "run_blocks_and_collect_debug",- text: "The run returned",- success: true,+ toolName: "navigate_browser",+ text: "The page did not open",+ success: false,iteration: 0,}),entry({- id: "n-run",+ id: "n-1",kind: "narration",- text: "Checking the run result",+ text: "Trying the page",iteration: 0,- activeLabel: "Checking the workflow",- outcomeLabel: "Confirmed the workflow works",+ activeLabel: "Opening the page",}),- ],- [block({ state: "completed", outcome: "demonstrated" })],+ entry({+ id: "tr-2",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "The page opened",+ success: true,+ iteration: 1,+ }),+ entry({+ id: "n-2",+ kind: "narration",+ text: "The retry reached the page",+ iteration: 1,+ activeLabel: "Opening the page",+ }),+ ]),),terminal: "response",});- expect(log.rows[0]?.label).toBe("Confirmed the workflow works");- });-- it("leaves the row label null when the narrator never spoke for the step", () => {- const log = deriveActivityLog(- turnWith([- entry({- id: "tr-1",- kind: "tool_result",- toolName: "navigate_browser",- text: "Opened the catalogue",- success: true,- }),- ]),- );-- // Null, not empty: the row falls back to its tool-derived title.- expect(log.rows[0]!.label).toBeNull();+ // The narrator spoke between the two attempts, so the retry is its own+ // step and the failure stays where the reader saw it.+ expect(+ log.rows.map((row) => [row.reason, row.entries.map((e) => e.text)]),+ ).toEqual([+ ["Trying the page", ["The page did not open"]],+ ["The retry reached the page", ["The page opened"]],+ ]);});it("pairs a narration that arrived before its own tool_result to that step, not the previous one", () => {@@ -1998,7 +1855,6 @@ describe("deriveActivityLog", () => {text: "Saving so the run has steps",iteration: 1,activeLabel: "Saving the workflow",- outcomeLabel: "Saved 2 blocks",}),entry({id: "tr-1",@@ -2014,20 +1870,18 @@ describe("deriveActivityLog", () => {const browse = log.rows.find((r) => r.kind === "browse")!;const author = log.rows.find((r) => r.kind === "author")!;expect(browse.reason).toBeNull();- expect(browse.label).toBeNull();expect(author.reason).toBe("Saving so the run has steps");});it("keeps a narration that opened the turn, before any row existed", () => {- const log = deriveActivityLog(- turnWith([+ const log = deriveActivityLog({+ ...turnWith([entry({id: "n-0",kind: "narration",text: "Why we start here",iteration: 0,activeLabel: "Opening the catalogue",- outcomeLabel: "Opened the catalogue",}),entry({id: "tr-0",@@ -2038,39 +1892,10 @@ describe("deriveActivityLog", () => {iteration: 0,}),]),- );-- expect(log.rows[0]!.reason).toBe("Why we start here");- expect(log.rows[0]!.label).toBe("Opened the catalogue");- });-- it("keeps the active tense on a step that never returned, even after the turn ended", () => {- // liveIndex is -1 once the turn is terminal, so a row with an unmatched- // call would otherwise be titled as if it had finished.- const log = deriveActivityLog({- ...turnWith([- entry({- id: "tc-1",- kind: "tool_call",- toolName: "update_workflow",- text: "Updating…",- iteration: 0,- }),- entry({- id: "n-1",- kind: "narration",- text: "Saving so the run has steps",- iteration: 0,- activeLabel: "Saving the workflow",- outcomeLabel: "Saved 2 blocks",- }),- ]),terminal: "response",});- expect(log.liveIndex).toBe(-1);- expect(log.rows[0]!.pending).toBe(true);- expect(log.rows[0]!.label).toBe("Saving the workflow");+ expect(log.rows[0]!.reason).toBe("Why we start here");});it("marks a row live while its call is unresolved, and not after the turn ends", () => {@@ -2111,9 +1936,8 @@ describe("deriveActivityLog", () => {);// No unmatched call and no running block, but the turn has not ended: the- // gap between one call returning and the next being made used to leave- // liveIndex at -1, so nothing was open and the log looked idle.- expect(log.liveIndex).toBe(-1);+ // model is between calls, so the newest step is still the live one.+ expect(log.liveIndex).toBe(0);expect(log.focusIndex).toBe(log.rows.length - 1);});@@ -2173,85 +1997,43 @@ describe("deriveActivityLog", () => {expect(log.focusIndex).toBe(log.rows.length - 1);});- it("keeps the title a row was introduced with when a later narration lands", () => {- const log = deriveActivityLog(- turnWith([- entry({- id: "tr-1",- kind: "tool_result",- toolName: "navigate_browser",- text: "Opened the catalogue",- success: true,- iteration: 0,- }),- entry({- id: "n-1",- kind: "narration",- text: "Checking whether the invoices need a login",- iteration: 0,- activeLabel: "Looking for the invoices",- outcomeLabel: "Found the invoices",- }),- entry({- id: "n-2",- kind: "narration",- text: "Now confirming the prices are listed",- iteration: 0,- }),- ]),- );-- // The reason tracks the latest narration, but the title does not: a line- // the user is already reading should not be reworded underneath them.- expect(log.rows[0]!.reason).toBe("Now confirming the prices are listed");- expect(log.rows[0]!.label).toBe("Found the invoices");- });-- it("lets a later narration settle the outcome without renaming the live work", () => {- const rows = (pending: boolean) =>- deriveActivityLog(- turnWith([+ it("never rewrites a step when a later narration lands", () => {+ const log = deriveActivityLog({+ ...turnWith(+ inOrder([entry({- id: "tc-1",- kind: "tool_call",- toolName: "extract_data",+ id: "tr-1",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "Opened the catalogue",+ success: true,iteration: 0,}),entry({id: "n-1",kind: "narration",- text: "Reading the star count",+ text: "Checking whether the invoices need a login",iteration: 0,- activeLabel: "Reading the star count",- outcomeLabel: "Read the star count",+ activeLabel: "Looking for the invoices",}),entry({id: "n-2",kind: "narration",- text: "Confirming the number is current",+ text: "Now confirming the prices are listed",iteration: 0,- activeLabel: "Confirming the number",- outcomeLabel: "Confirmed the star count",}),- ...(pending- ? []- : [- entry({- id: "tr-1",- kind: "tool_result",- toolName: "extract_data",- text: "Extracted",- success: true,- iteration: 0,- }),- ]),]),- ).rows[0]!;+ ),+ terminal: "response",+ });- // Live: the first narration named the work, so the second cannot rename it.- expect(rows(true).label).toBe("Reading the star count");- // Finished: the latest narration is the one that knows how it ended.- expect(rows(false).label).toBe("Confirmed the star count");+ expect(log.rows[0]).toMatchObject({+ reason: "Checking whether the invoices need a login",+ });+ expect(log.rows[1]).toMatchObject({+ reason: "Now confirming the prices are listed",+ entries: [],+ });});it("spans a merged row from its first entry stamp to its last", () => {@@ -2329,3 +2111,379 @@ describe("deriveActivityLog", () => {expect(log.rows[0]!.endedAt).toBeNull();});});++// A browsing turn where the narrator speaks roughly once per call, in the+// order a live stream delivered it (narrations tagged with the iteration they+// explain, one arriving while its call was still in flight).+const narratedBrowsingActivity = (): ActivityEntry[] => {+ const call = (n: number, iteration: number, toolName: string) => [+ entry({ id: `tc-${n}`, kind: "tool_call", iteration, toolName }),+ entry({+ id: `tr-${n}`,+ kind: "tool_result",+ iteration,+ toolName,+ success: true,+ }),+ ];+ const narration = (n: number, iteration: number, activeLabel: string) =>+ entry({+ id: `n-${n}`,+ kind: "narration",+ iteration,+ text: `Reason ${n}`,+ activeLabel,+ });+ const [tc3, tr3] = call(3, 3, "evaluate");+ return [+ ...call(0, 0, "set_work_plan"),+ narration(1, 0, "Checking the quote"),+ ...call(1, 1, "navigate_browser"),+ narration(2, 1, "Opening the quote site"),+ ...call(2, 2, "inspect_page_for_composition"),+ narration(3, 1, "Looking for the price"),+ tc3!,+ narration(4, 3, "Checking the current price"),+ tr3!,+ ...call(4, 4, "navigate_browser"),+ narration(5, 4, "Checking the quote again"),+ ...call(5, 5, "inspect_page_for_composition"),+ ...call(6, 6, "evaluate"),+ ].map((e, i) => ({ ...e, timestamp: at(i) }));+};++describe("deriveActivityLog — narrated browsing", () => {+ it("opens a step for each narration in the order it was spoken", () => {+ const log = deriveActivityLog({+ ...turnWith(narratedBrowsingActivity()),+ terminal: "response",+ });+ // The plan call returned before the first sentence, which is about the+ // navigation after it.+ expect(log.rows.map((row) => row.reason)).toEqual([+ null,+ "Reason 1",+ "Reason 2",+ "Reason 3",+ "Reason 4",+ "Reason 5",+ ]);+ // Calls spoken after a narration join its line; nothing moves back.+ expect(log.rows.map((row) => row.entries.map((e) => e.id))).toEqual([+ ["tr-0"],+ ["tr-1"],+ ["tr-2"],+ ["tr-3"],+ ["tr-4"],+ ["tr-5", "tr-6"],+ ]);+ });++ it("keeps the newest step working between calls until a narration or a later step moves on", () => {+ const activity = narratedBrowsingActivity();+ const outcome = entry({+ id: "n-9",+ kind: "narration",+ iteration: 1,+ text: "Reason 9",+ activeLabel: "Opening the quote site",+ timestamp: "2026-01-01T00:00:05.500Z",+ });+ // The navigation returned, but the model has not started another call.+ const between = deriveActivityLog(turnWith(activity.slice(0, 5)));+ expect(between.rows.map((row) => row.live)).toEqual([false, true]);++ // The narrator names the outcome on a line of its own, so the step above+ // stops spinning instead of loading over the new sentence.+ const next = deriveActivityLog(+ turnWith([...activity.slice(0, 5), outcome]),+ );+ expect(next.rows.map((row) => [row.reason, row.live])).toEqual([+ [null, false],+ ["Reason 1", false],+ ["Reason 9", false],+ ]);+ });+});++// The shape of a captured live browsing turn: narrations arrive seconds after+// the call they describe, tagged with an iteration that trails the work.+const laggingNarrationActivity = (): ActivityEntry[] => {+ const t = (s: number) =>+ new Date(Date.UTC(2026, 0, 1, 0, 0, s)).toISOString();+ const tool = (+ kind: "tool_call" | "tool_result",+ n: number,+ toolName: string,+ s: number,+ ) =>+ entry({+ id: `${kind === "tool_call" ? "tc" : "tr"}-${n}`,+ kind,+ toolName,+ iteration: n,+ success: kind === "tool_result" ? true : undefined,+ timestamp: t(s),+ });+ const said = (n: string, iteration: number, s: number) =>+ entry({+ id: `n-${n}`,+ kind: "narration",+ iteration,+ text: `Reason ${n}`,+ activeLabel: `Intent ${n}`,+ timestamp: t(s),+ });+ return [+ tool("tool_call", 0, "set_work_plan", 3),+ tool("tool_result", 0, "set_work_plan", 4),+ said("a", 0, 6),+ tool("tool_call", 1, "navigate_browser", 7),+ tool("tool_result", 1, "navigate_browser", 63),+ said("b", 1, 66),+ tool("tool_call", 2, "inspect_page_for_composition", 67),+ tool("tool_result", 2, "inspect_page_for_composition", 82),+ said("c", 1, 99),+ tool("tool_call", 3, "evaluate", 118),+ said("d", 3, 130),+ tool("tool_result", 3, "evaluate", 141),+ said("e", 3, 144),+ tool("tool_call", 4, "navigate_browser", 144),+ tool("tool_result", 4, "navigate_browser", 200),+ said("f", 4, 203),+ tool("tool_call", 5, "inspect_page_for_composition", 203),+ tool("tool_result", 5, "inspect_page_for_composition", 215),+ said("g", 4, 218),+ tool("tool_call", 6, "evaluate", 219),+ tool("tool_result", 6, "evaluate", 227),+ ];+};++describe("deriveActivityLog — drafting", () => {+ it("leaves only the drafting row live once the step before it settled", () => {+ const log = deriveActivityLog({+ ...turnWith([+ entry({+ id: "tr-1",+ kind: "tool_result",+ toolName: "navigate_browser",+ text: "Opened the page",+ success: true,+ }),+ ]),+ codegenProgress: { blockLabels: ["open_page"] },+ });++ expect(log.rows.map((row) => row.live)).toEqual([false, true]);+ expect(log.liveIndex).toBe(1);+ });+});++describe("deriveActivityLog — append only", () => {+ it("ends a step at a call whose card renders after it", () => {+ const result = (id: string, toolName: string) =>+ entry({ id, kind: "tool_result", toolName, success: true });+ const log = deriveActivityLog(+ turnWith([+ result("tr-ask", "ask_user"),+ result("tr-schema", "get_block_schema"),+ result("tr-plan", "set_work_plan"),+ result("tr-nav", "navigate_browser"),+ ]),+ );+ expect(log.rows.map((row) => row.entries.map((e) => e.id))).toEqual([+ ["tr-ask"],+ ["tr-schema", "tr-plan"],+ ["tr-nav"],+ ]);+ });++ it("never rewrites or reorders a step once a later one exists", () => {+ const activity = laggingNarrationActivity();+ const shape = (k: number) =>+ deriveActivityLog(turnWith(activity.slice(0, k))).rows.map((row) => ({+ id: row.id,+ reason: row.reason,+ calls: row.entries.map(+ (e) => e.retryRootId ?? e.id.replace(/^t[cr]-/, ""),+ ),+ }));+ for (let k = 2; k <= activity.length; k += 1) {+ const before = shape(k - 1);+ expect(shape(k).slice(0, before.length - 1)).toEqual(before.slice(0, -1));+ }+ // "d" was spoken over a running call: it waits for that call to return,+ // then opens its own line rather than being dropped.+ const returned = activity.findIndex((e) => e.id === "tr-3");+ expect(shape(returned).map((row) => row.reason)).not.toContain("Reason d");+ expect(shape(activity.length).map((row) => row.reason)).toEqual([+ null,+ "Reason a",+ "Reason b",+ "Reason c",+ "Reason d",+ "Reason e",+ "Reason f",+ "Reason g",+ ]);+ });+});++describe("callRollup", () => {+ const call = (id: string, toolName: string, kind: ActivityEntry["kind"]) =>+ entry({ id, kind, toolName, success: true });++ it("names a step by its call kinds in first-appearance order, present tense only while one runs", () => {+ const settled = [+ call("tr-1", "navigate_browser", "tool_result"),+ call("tr-2", "fill_credential_field", "tool_result"),+ call("tr-3", "click", "tool_result"),+ call("tr-4", "set_work_plan", "tool_result"),+ ];+ expect(callRollup(settled)).toBe(+ "2 browser actions, used a saved login, updated its plan",+ );+ expect(+ callRollup([...settled, call("tc-5", "set_work_plan", "tool_call")]),+ ).toBe("2 browser actions, used a saved login, updating its plan");+ expect(+ callRollup([+ call("tr-1", "get_workflow_knowledge", "tool_result"),+ call("tr-2", "add_block", "tool_result"),+ call("tr-3", "edit_block", "tool_result"),+ call("tr-4", "run_blocks_and_collect_debug", "tool_result"),+ ]),+ ).toBe(+ "Looked up guidance, added 1 block, edited 1 block, tested the workflow",+ );+ expect(callRollup([entry({ id: "n-1", kind: "narration" })])).toBeNull();+ });++ it("claims only the writes that succeeded once a step finished", () => {+ const failed = (id: string, toolName: string) =>+ entry({ id, kind: "tool_result", toolName, success: false });+ expect(+ callRollup([+ failed("tr-1", "edit_block"),+ call("tr-2", "edit_block", "tool_result"),+ ]),+ ).toBe("Edited 1 block");+ expect(callRollup([failed("tr-1", "add_block")])).toBe(+ "Tried to add a block",+ );+ expect(callRollup([failed("tr-1", "fill_credential_field")])).toBe(+ "Tried a saved login",+ );+ expect(callRollup([failed("tr-1", "update_workflow")])).toBe(+ "Tried to update the workflow",+ );+ expect(+ callRollup([+ failed("tr-1", "click"),+ entry({+ id: "tr-2",+ kind: "tool_result",+ toolName: "click",+ success: true,+ retryRootId: "tr-1",+ }),+ ]),+ ).toBe("1 browser action");+ });++ it("reads every kind as finished once the turn settled, even with a call left unmatched", () => {+ const cancelled = [+ call("tr-1", "navigate_browser", "tool_result"),+ call("tc-2", "run_blocks_and_collect_debug", "tool_call"),+ ];+ expect(callRollup(cancelled)).toBe(+ "1 browser action, testing the workflow",+ );+ expect(callRollup(cancelled, true)).toBe(+ "1 browser action, tested the workflow",+ );+ });+});++describe("summarizeFinishedTurn", () => {+ const failedRun = (id: string, wrb: string) => ({+ activity: entry({+ id,+ kind: "tool_result",+ toolName: "run_blocks_and_collect_debug",+ success: false,+ }),+ block: block({+ workflowRunBlockId: wrb,+ label: "download_latest_pdf",+ state: "failed",+ startedAt: at(Number(id.replace(/\D/g, ""))),+ }),+ });++ it("counts failed tests, and says fixed only when the facts record a clean run", () => {+ const first = failedRun("tr-2", "wrb_a");+ const retry = entry({+ id: "tr-5",+ kind: "tool_result",+ toolName: "run_blocks_and_collect_debug",+ success: true,+ });+ const turn = turnWith(+ [+ entry({+ id: "tr-1",+ kind: "tool_result",+ toolName: "navigate_browser",+ }),+ first.activity,+ entry({ id: "tr-3", kind: "tool_result", toolName: "edit_block" }),+ retry,+ ],+ [first.block, block({ workflowRunBlockId: "wrb_b", startedAt: at(5) })],+ );+ const { rows } = deriveActivityLog(turn);++ const unconfirmed = summarizeFinishedTurn(rows, null);+ expect(unconfirmed).toMatchObject({+ steps: 4,+ failedTests: 1,+ fixed: false,+ });+ // The newest test passed, so nothing is named as still failing.+ expect(unconfirmed.stillFailing).toEqual([]);++ const fixed = summarizeFinishedTurn(rows, {+ factsAvailable: true,+ authoredBlockCount: 1,+ matchingSourceBlockCount: 1,+ evaluationState: "demonstrated",+ runId: "wr_1",+ runCompleted: true,+ terminalCause: null,+ blocksRunThisTurn: 1,+ ranCleanOnCurrentSource: true,+ });+ expect(fixed.fixed).toBe(true);+ });++ it("names the blocks the newest test left failing", () => {+ const first = failedRun("tr-1", "wrb_a");+ const second = failedRun("tr-3", "wrb_b");+ const { rows } = deriveActivityLog(+ turnWith(+ [+ first.activity,+ entry({ id: "tr-2", kind: "tool_result", toolName: "edit_block" }),+ second.activity,+ ],+ [first.block, second.block],+ ),+ );+ const summary = summarizeFinishedTurn(rows, null);+ expect(summary.failedTests).toBe(2);+ expect(summary.stillFailing.map((b) => b.workflowRunBlockId)).toEqual([+ "wrb_b",+ ]);+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.ts b/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.tsindex ce725639d..63f73bb9c 100644--- a/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.ts@@ -4,25 +4,24 @@ import {AUTHORING_TOOLS,BlockState,RUN_TOOLS,+ ToolCallKind,+ TurnFacts,TurnNarrativeState,condenseActivityEntries,hasObservedBlockEvidence,hasPendingToolCall,isBlockOk,parseUtcIsoMs,+ ranCleanOnCurrentSource,+ toolActivityDisplayLabel,toolCallIdOf,+ toolCallKind,} from "./narrativeState";export type ActivityKind = "browse" | "author" | "run";-export const ACTIVITY_KIND_GLYPH: Record<ActivityKind, string> = {- browse: "◎",- author: "⟨⟩",- run: "▷",-};--// The glyph is aria-hidden, so the kind reaches screen readers as this word-// instead — not every row's own text implies which kind it is.+// Not every row's own text implies which kind it is, so screen readers hear+// the kind as this word.export const ACTIVITY_KIND_WORD: Record<ActivityKind, string> = {browse: "Looked at the page",author: "Wrote code",@@ -41,18 +40,14 @@ export interface ActivityRow {// resolve out of order, so its last entry alone does not answer this.pending: boolean;// The work this row describes is still happening: a call without its result,- // or a block still running, on a turn that has not ended. Drives the ticking- // clock, so it must go false at turn end even if a call never resolved.+ // or a block still running, on a turn that has not ended. It goes false at+ // turn end even if a call never resolved.live: boolean;- // Narrator prose explaining why this step happened. Latest narration wins- // when a merged row spans several iterations.+ // Narrator prose explaining why this step happened; the first narration that+ // names the step keeps it.reason: string | null;- // Narrator-authored title for this step, in the tense matching its state.- // Null when the narrator never spoke for it, leaving the tool-derived label- // as the row's title.- label: string | null;- // First and last server clock reads across this row's entries, so a merged- // row reports the span of the work rather than one entry's instant.+ // First and last server clock reads across this row's entries. A browse+ // retry merges only when it started after the failed attempt ended.startedAt: string | null;endedAt: string | null;// Epoch ms the winning narration arrived live; absent on hydrate.@@ -64,12 +59,12 @@ export interface ActivityRow {export interface ActivityLog {rows: ActivityRow[];- // The one row still working, or -1. The scan keeps the last qualifying row,- // so parallel tool calls and a block left `running` cannot both claim it.+ // The one row showing a loader, or -1: the last row with an unmatched call or+ // a running block, else the newest step while the model works between calls.liveIndex: number;- // Row the reader should be looking at. Distinct from liveIndex: liveness is- // strict (an unmatched call or a running block) and drives tense, while focus- // has to survive the gap between one call returning and the next being made.+ // Row the reader should be looking at. Distinct from liveIndex: focus+ // survives the end of the turn's work, and a trailing sentence waiting for+ // its first call is not where the reader looks.focusIndex: number;}@@ -225,6 +220,7 @@ function coalesceNarratedBrowseRetries(if (previous?.kind !== "browse" ||row.kind !== "browse" ||+ row.reason !== null ||!previousFailed ||!followsFailure ||intent === undefined ||@@ -260,31 +256,82 @@ function coalesceNarratedBrowseRetries(id: previous.id,entries: [...earlierEntries, ...currentEntries],startedAt: previous.startedAt ?? row.startedAt,- reason: row.reason ?? previous.reason,- reasonAt: row.reasonAt ?? previous.reasonAt,+ reason: previous.reason,+ reasonAt: previous.reasonAt,};}rows.splice(0, rows.length, ...coalesced);}-function rowContainsNarrationTime(- row: ActivityRow,- narrationTimestamp: string | undefined,-): boolean {- const narrationMs = parseUtcIsoMs(narrationTimestamp);- if (narrationMs === null || row.entries.length === 0) return false;-- const starts = row.entries- .flatMap((entry) => [entry.activityStartedAt, entry.timestamp])- .map(parseUtcIsoMs)- .filter((value): value is number => value !== null);- if (starts.length === 0) return false;-- const startedMs = Math.min(...starts);- const endedMs = hasPendingToolCall(row.entries)- ? Infinity- : Math.max(...starts);- return narrationMs >= startedMs && narrationMs <= endedMs;+// Condensing moves a call's result to where it arrived, past any narration+// spoken mid-call; holding each narration behind calls that started strictly+// before it keeps live and reload in the same order.+function placeNarrations(entries: ActivityEntry[]): ActivityEntry[] {+ const placed: ActivityEntry[] = [];+ const held: ActivityEntry[] = [];+ for (const entry of entries) {+ if (entry.kind === "narration") {+ held.push(entry);+ continue;+ }+ const startedMs = parseUtcIsoMs(entry.activityStartedAt ?? entry.timestamp);+ while (held.length > 0) {+ const spokenMs = parseUtcIsoMs(held[0]!.timestamp);+ if (startedMs !== null && spokenMs !== null && startedMs < spokenMs) {+ break;+ }+ placed.push(held.shift()!);+ }+ placed.push(entry);+ }+ return [...placed, ...held];+}++// Whether some call in this row was still running when the narration was spoken.+function wasInFlightAt(row: ActivityRow, narration: ActivityEntry): boolean {+ const spokenMs = parseUtcIsoMs(narration.timestamp);+ if (spokenMs === null) return false;+ return row.entries.some((entry) => {+ if (entry.kind !== "tool_call" && entry.kind !== "tool_result") {+ return false;+ }+ const startedMs = parseUtcIsoMs(entry.activityStartedAt ?? entry.timestamp);+ if (startedMs === null || startedMs > spokenMs) return false;+ if (entry.kind === "tool_call") return true;+ const endedMs = parseUtcIsoMs(entry.timestamp);+ return endedMs === null || endedMs >= spokenMs;+ });+}++function reasonOnlyRow(narration: ActivityEntry): ActivityRow {+ return {+ id: `reason-${narration.id}`,+ kind: null,+ entries: [],+ blocks: [],+ codeDiffs: [],+ pending: false,+ live: false,+ reason: narration.text,+ reasonAt: narration.receivedAtMs,+ startedAt: null,+ endedAt: null,+ };+}++// The newest step with calls, unless a narration has opened a line after it.+function newestStepIndex(rows: ActivityRow[]): number {+ for (let i = rows.length - 1; i >= 0; i -= 1) {+ if (isReasonOnlyRow(rows[i]!)) return -1;+ if (rows[i]!.entries.length > 0) return i;+ }+ return -1;+}++export function isReasonOnlyRow(row: ActivityRow): boolean {+ return (+ row.entries.length === 0 && row.blocks.length === 0 && row.reason !== null+ );}// The row holding a tool call's activity, as a row entry or on a block the row ran. -1 when the call@@ -301,19 +348,86 @@ export function rowIndexOfToolCall();}+// A call whose card renders after its row ends that row, so work done after the+// user answered or the plan changed never sits above the card.+const CARD_TOOLS = new Set(["ask_user", "set_work_plan"]);+export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {+ // A cancelled or timed-out turn can terminate with a call still unmatched;+ // nothing is working once the turn is over, so nothing claims the open row.+ const ended = turn.terminal !== null;const rows: ActivityRow[] = [];- const narrations: { entry: ActivityEntry; precedingRow: number }[] = [];- // Both tenses are collected first; which one reads depends on liveIndex,- // which is only known once every row exists.- const labelsByRow = new Map<number, { active?: string; outcome?: string }>();- for (const entry of condenseActivityEntries(turn.designActivity)) {+ // The intent the narrator named for a row, used only to merge the+ // unnarrated browse retries that pursue it.+ const narratedIntent = new Map<ActivityRow, string>();+ const narrate = (row: ActivityRow, narration: ActivityEntry) => {+ row.reason = narration.text;+ row.reasonAt = narration.receivedAtMs;+ if (narration.activeLabel !== undefined) {+ narratedIntent.set(row, narration.activeLabel);+ }+ };+ // A reason, once shown, is never replaced. A narration names a step that has+ // none and is about it; otherwise it opens the next line.+ for (const entry of placeNarrations(+ condenseActivityEntries(turn.designActivity),+ )) {+ const last = rows[rows.length - 1];if (entry.kind === "narration") {- narrations.push({ entry, precedingRow: rows.length - 1 });+ // Iteration is the typed key. The tag can trail the work, though: a+ // narration spoken while the newest call runs describes that call unless+ // the step it is tagged with was itself still running.+ let owner = rows.length - 1;+ while (+ owner >= 0 &&+ !rows[owner]!.entries.some((e) => e.iteration === entry.iteration)+ ) {+ owner -= 1;+ }+ const aboutLast =+ last !== undefined &&+ (owner === rows.length - 1 ||+ (wasInFlightAt(last, entry) &&+ (owner === -1 || !wasInFlightAt(rows[owner]!, entry))));+ const ownerRow = owner >= 0 ? rows[owner] : undefined;+ // A card call is done once it returns, so a sentence after it is about+ // the work that follows, even when tagged with the card call's iteration.+ const tail = last?.entries[last.entries.length - 1];+ const afterCard =+ tail?.kind === "tool_result" && CARD_TOOLS.has(tail.toolName ?? "");+ if (afterCard) {+ const opened = reasonOnlyRow(entry);+ rows.push(opened);+ narrate(opened, entry);+ } else if (last !== undefined && last.reason === null && aboutLast) {+ narrate(last, entry);+ } else if (+ ownerRow !== undefined &&+ ownerRow.reason === null &&+ wasInFlightAt(ownerRow, entry)+ ) {+ narrate(ownerRow, entry);+ } else if (+ !ended &&+ last !== undefined &&+ hasPendingToolCall(last.entries)+ ) {+ // A new line under a running step reads as a new step starting, so a+ // second sentence spoken over its loader waits for the step to settle.+ } else {+ const opened = reasonOnlyRow(entry);+ rows.push(opened);+ narrate(opened, entry);+ }continue;}const kind = kindOf(entry);- const prev = rows[rows.length - 1];+ if (last !== undefined && isReasonOnlyRow(last)) {+ last.kind = kind;+ last.entries.push(...retryEntries(entry));+ continue;+ }+ const prev = last;const previousEntry = prev?.entries[prev.entries.length - 1];const previousEndedMs = parseUtcIsoMs(previousEntry?.timestamp);const runStartedMs = parseUtcIsoMs(@@ -332,7 +446,8 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {kind === "browse" &&prev?.kind === "browse" &&entry.success !== false &&- previousEntry?.success !== false+ previousEntry?.success !== false &&+ !CARD_TOOLS.has(previousEntry?.toolName ?? "")) {prev.entries.push(...retryEntries(entry));continue;@@ -360,79 +475,15 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {pending: false,live: false,reason: null,- label: null,startedAt: null,endedAt: null,});}- // Pair a narration to a result that chronology moved below it, then by the- // closest matching iteration, else to the step it followed. A pending row's- // open-ended time span is not an ownership claim: parallel calls commonly- // overlap, and an older unresolved call must not steal a sibling's prose.- for (const { entry, precedingRow } of narrations) {- // The owning row can sit either side of where the narration landed: a- // narration emitted mid-step precedes its own tool_result, while one- // emitted after a step follows it. Iteration also restarts each- // enforcement pass, so nearest-wins disambiguates a repeated number.- // Pairing a call/result whose narration arrived mid-flight moves its result- // after the narration. Only a later row can be that displaced owner. This- // narrow timestamp rule keeps "Reviewing…" with the inspection it describes- // without letting any older open-ended call capture unrelated narration.- let ownerIdx = -1;- const futureTimeOwners: number[] = [];- for (let i = precedingRow + 1; i < rows.length; i += 1) {- if (rowContainsNarrationTime(rows[i]!, entry.timestamp)) {- futureTimeOwners.push(i);- }- }- if (futureTimeOwners.length === 1) {- ownerIdx = futureTimeOwners[0]!;- } else if (futureTimeOwners.length > 1) {- const matchingIteration = futureTimeOwners.filter((i) =>- rows[i]!.entries.some(- (candidate) => candidate.iteration === entry.iteration,- ),- );- if (matchingIteration.length === 1) {- ownerIdx = matchingIteration[0]!;- }- }- let bestDistance = Infinity;- if (ownerIdx === -1) {- rows.forEach((row, i) => {- if (!row.entries.some((e) => e.iteration === entry.iteration)) return;- const distance = Math.abs(i - precedingRow);- if (distance < bestDistance) {- bestDistance = distance;- ownerIdx = i;- }- });- }- const targetIdx = ownerIdx === -1 ? precedingRow : ownerIdx;- const target = rows[targetIdx];- if (target) {- target.reason = entry.text;- // The reason tracks the latest narration, but the live title normally- // does not: the first narration to reach a row names the work, and a- // later one would rewrite a line the user is already reading. A combined- // write/test row is the exception because its current action genuinely- // advances from writing to testing while preserving one frontier.- const held = labelsByRow.get(targetIdx);- const combinedWriteAndRun =- target.kind === "run" &&- target.entries.some((candidate) => kindOf(candidate) === "author");- labelsByRow.set(targetIdx, {- active: combinedWriteAndRun- ? (entry.activeLabel ?? held?.active)- : (held?.active ?? entry.activeLabel),- outcome: entry.outcomeLabel ?? held?.outcome,- });- target.reasonAt = entry.receivedAtMs;- }- }+ const intentBoundaryRows = new Set<ActivityRow>(+ rows.filter((row) => row.id.startsWith("reason-")),+ );- // Block rows are appended below, so the indices held in labelsByRow stay valid.const runRows = rows.filter((r) => r.kind === "run");const runStartedMs = runStartLookup(turn.designActivity);for (const block of turn.blocks.filter(hasObservedBlockEvidence)) {@@ -452,15 +503,11 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {pending: false,live: false,reason: null,- label: null,startedAt: null,endedAt: null,});}- // A cancelled or timed-out turn can terminate with a call still unmatched;- // nothing is working once the turn is over, so nothing claims the open row.- const ended = turn.terminal !== null;let liveIndex = -1;rows.forEach((row) => {const stamps = row.entries@@ -493,55 +540,19 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {}});- rows.forEach((row, i) => {- const tenses = labelsByRow.get(i);- if (!tenses) return;- // A row still carrying an unmatched call has not finished, whatever- // liveIndex says: it is -1 on a terminated turn, and last-wins when two- // calls run in parallel. A step that never returned cannot show an outcome.- const working = row.pending || i === liveIndex;- // Outcome labels are predictions authored before the step resolves. When- // the attempt fails, keep the narrator's stable intent as the row title;- // the exact failure remains in the row detail instead of letting a stale- // success-shaped outcome replace what Copilot was trying to accomplish.- const terminalEntry = row.entries[row.entries.length - 1];- const cannotUsePredictedOutcome =- (terminalEntry?.kind === "tool_result" &&- terminalEntry.success === false) ||- row.blocks.some((block) => !isBlockOk(block));- row.label =- (working || cannotUsePredictedOutcome- ? tenses.active- : (tenses.outcome ?? tenses.active)) ?? null;- });-- // Narration names the user-facing activity; raw browser operations are its- // technical substeps. Until the narrator declares a new intent, keep those- // substeps under the current active label instead of flashing peer titles- // such as "Inspecting page" and "Opening page" between semantic labels.- let browseIntent: string | null = null;+ // An unnarrated browse row pursues the intent narrated before it, so a retry+ // that switched tools still merges into that attempt; the first attempt keeps+ // its row id so the user's expansion choice survives.+ let browseIntent: string | undefined;const browseIntentByRow = new Map<ActivityRow, string>();- rows.forEach((row, i) => {- if (row.kind !== "browse") {- browseIntent = null;- return;- }- const active = labelsByRow.get(i)?.active;- if (active !== undefined) {- browseIntent = active;- } else if (browseIntent !== null) {- row.label = browseIntent;- }- if (browseIntent !== null) {- browseIntentByRow.set(row, browseIntent);+ for (const row of rows) {+ if (row.kind !== "browse" || intentBoundaryRows.has(row)) {+ browseIntent = undefined;}- });-- // Retries may switch browser tools while pursuing the same narrated intent.- // Tool-level condensation cannot recognize that as one activity, but the- // narrator's explicit active label can: adjacent failed attempts with the- // same label become one row. The first attempt keeps the stable row id so a- // user's expansion choice survives while later attempts update its status.+ if (row.kind !== "browse") continue;+ browseIntent = narratedIntent.get(row) ?? browseIntent;+ if (browseIntent !== undefined) browseIntentByRow.set(row, browseIntent);+ }coalesceNarratedBrowseRetries(rows, browseIntentByRow);liveIndex = -1;rows.forEach((row, i) => {@@ -551,12 +562,15 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {(row.pending || row.blocks.some((block) => block.state === "running"));if (row.live) liveIndex = i;});-// The model is still writing the authoring call's arguments: no tool call is// in flight and no block is running, so nothing above claims the frontier.// The frames are live-only, which is why a terminated turn never shows this// and a reload — whose hydrated turn carries no progress — cannot strand it.const drafting = turn.codegenProgress;+ if (!ended && liveIndex === -1 && drafting === null) {+ liveIndex = newestStepIndex(rows);+ if (liveIndex !== -1) rows[liveIndex]!.live = true;+ }if (!ended && drafting !== null) {rows.push({id: "codegen-progress",@@ -567,21 +581,19 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {pending: false,live: true,reason: null,- label: null,- startedAt: drafting.startedAt,+ startedAt: null,endedAt: null,draftingLabels: drafting.blockLabels,});liveIndex = rows.length - 1;}- // While the model is generating, no row has an unmatched call and no block is- // running, so liveIndex is -1 and nothing would be open — the stretch that- // reads as "one collapsed row and nothing going on". Follow the newest row in- // that gap. The one exception is a contentless draft placeholder appended- // after real live work: it describes what now exists, not what is happening,- // so it cannot hide the row carrying the active call or running block.- const newestIndex = rows.length - 1;+ // Focus follows the newest row, skipping a trailing sentence with no calls+ // yet, and a contentless draft placeholder never hides the live row.+ let newestIndex = rows.length - 1;+ while (newestIndex > 0 && isReasonOnlyRow(rows[newestIndex]!)) {+ newestIndex -= 1;+ }const newest = rows[newestIndex];const newestIsEmptyDraft =newest !== undefined &&@@ -604,3 +616,240 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {return { rows, liveIndex, focusIndex };}++export function callLabel(entry: ActivityEntry): string {+ return entry.displayLabel ?? toolActivityDisplayLabel(entry.toolName);+}++export interface CondensedCall {+ entry: ActivityEntry;+ count: number;+}++// Consecutive settled calls that read the same and returned the same result+// are one line with a count; a failure or a call still running never merges.+export function condenseCalls(entries: ActivityEntry[]): CondensedCall[] {+ const out: CondensedCall[] = [];+ for (const entry of entries) {+ if (entry.kind === "narration") continue;+ const previous = out[out.length - 1];+ if (+ previous !== undefined &&+ entry.kind === "tool_result" &&+ previous.entry.kind === "tool_result" &&+ entry.success !== false &&+ previous.entry.success !== false &&+ entry.toolName === previous.entry.toolName &&+ callLabel(entry) === callLabel(previous.entry) &&+ entry.text === previous.entry.text+ ) {+ previous.count += 1;+ continue;+ }+ out.push({ entry, count: 1 });+ }+ return out;+}++function counted(n: number, one: string, many: string): string {+ return n === 1 ? `1 ${one}` : `${n} ${many}`;+}++// A retry keeps its failed attempts beside it, so a finished step counts only+// the calls that returned a success; one that never did says it tried.+function returnedOk(entry: ActivityEntry): boolean {+ return entry.kind === "tool_result" && entry.success !== false;+}++// A retried call's attempts are one action.+function attemptCount(entries: ActivityEntry[]): number {+ return new Set(entries.map(stableRowId)).size;+}++// Two writes to the same block are one block when their diffs name it.+function blockCount(calls: ActivityEntry[]): number {+ const labels = new Set(+ calls.flatMap((call) => (call.codeDiffs ?? []).map((diff) => diff.label)),+ );+ return labels.size > 0 ? labels.size : attemptCount(calls);+}++function writePhrase(entries: ActivityEntry[], live: boolean): string {+ const parts: string[] = [];+ const blockScoped = (+ tool: string,+ base: string,+ verb: string,+ past: string,+ ) => {+ const calls = entries.filter((entry) => entry.toolName === tool);+ if (calls.length === 0) return 0;+ const ok = calls.filter(returnedOk);+ if (live) {+ const active = calls.filter(+ (entry) => entry.kind === "tool_call" || returnedOk(entry),+ );+ parts.push(+ `${verb} ${counted(Math.max(blockCount(active), 1), "block", "blocks")}`,+ );+ } else if (ok.length > 0) {+ parts.push(`${past} ${counted(blockCount(ok), "block", "blocks")}`);+ } else {+ parts.push(+ `tried to ${base} ${attemptCount(calls) === 1 ? "a block" : "blocks"}`,+ );+ }+ return calls.length;+ };+ const scoped =+ blockScoped("add_block", "add", "adding", "added") ++ blockScoped("edit_block", "edit", "editing", "edited") ++ blockScoped("delete_block", "delete", "deleting", "deleted");+ if (scoped < entries.length) {+ const rest = entries.filter(+ (entry) =>+ !["add_block", "edit_block", "delete_block"].includes(+ entry.toolName ?? "",+ ),+ );+ parts.push(+ live+ ? "updating the workflow"+ : rest.some(returnedOk)+ ? "updated the workflow"+ : "tried to update the workflow",+ );+ }+ return parts.join(", ");+}++function kindPhrase(+ kind: ToolCallKind,+ entries: ActivityEntry[],+ live: boolean,+): string {+ const uses = (name: string) => entries.some((e) => e.toolName === name);+ switch (kind) {+ case "browser":+ return counted(+ attemptCount(entries),+ "browser action",+ "browser actions",+ );+ case "credential":+ if (uses("fill_credential_field")) {+ if (live) return "using a saved login";+ return entries.some(+ (e) => e.toolName === "fill_credential_field" && returnedOk(e),+ )+ ? "used a saved login"+ : "tried a saved login";+ }+ if (uses("request_credential")) {+ return live ? "asking for a login" : "asked for a login";+ }+ return live ? "checking saved logins" : "checked saved logins";+ case "plan":+ return live ? "updating its plan" : "updated its plan";+ case "guidance":+ return live ? "looking up guidance" : "looked up guidance";+ case "write":+ return writePhrase(entries, live);+ case "run":+ if (live) return "testing the workflow";+ return entries.length === 1+ ? "tested the workflow"+ : `tested the workflow ${entries.length} times`;+ case "other": {+ const asks = entries.filter((e) => e.toolName === "ask_user").length;+ const rest = entries.length - asks;+ return [+ asks > 0 ? (live ? "asking you" : "asked you a question") : null,+ rest > 0 ? counted(rest, "other step", "other steps") : null,+ ]+ .filter((part) => part !== null)+ .join(", ");+ }+ }+}++// Names a step by the kinds of call it made, in the order each kind first+// appeared. A kind reads in the present tense while one of its calls is still+// waiting on its result, unless `settled` says the turn is over.+export function callRollup(+ entries: ActivityEntry[],+ settled = false,+): string | null {+ const byKind = new Map<ToolCallKind, ActivityEntry[]>();+ for (const entry of entries) {+ if (entry.kind === "narration" || entry.toolName === undefined) continue;+ const kind = toolCallKind(entry.toolName);+ byKind.set(kind, [...(byKind.get(kind) ?? []), entry]);+ }+ if (byKind.size === 0) return null;+ const text = [...byKind]+ .map(([kind, calls]) =>+ kindPhrase(+ kind,+ calls,+ !settled && calls.some((call) => call.kind === "tool_call"),+ ),+ )+ .join(", ");+ return text.charAt(0).toUpperCase() + text.slice(1);+}++export function failedRowBlocks(row: ActivityRow): BlockState[] {+ return row.blocks.filter((block) => block.state === "failed");+}++// A run row whose every block the run recorded as ok and evaluated; null otherwise.+export function passedBlockCount(row: ActivityRow): number | null {+ if (row.kind !== "run" || row.pending || row.blocks.length === 0) {+ return null;+ }+ const last = row.entries[row.entries.length - 1];+ if (last?.kind === "tool_result" && last.success === false) return null;+ return row.blocks.every(+ (block) => isBlockOk(block) && block.outcome !== "not_evaluated",+ )+ ? row.blocks.length+ : null;+}++function isFailedTest(row: ActivityRow): boolean {+ if (row.kind !== "run") return false;+ if (failedRowBlocks(row).length > 0) return true;+ const lastRun = [...row.entries]+ .reverse()+ .find(+ (entry) =>+ entry.toolName !== undefined && toolCallKind(entry.toolName) === "run",+ );+ return lastRun?.kind === "tool_result" && lastRun.success === false;+}++export interface FinishedTurnSummary {+ steps: number;+ failedTests: number;+ // Every failure was followed by a clean run on the current source.+ fixed: boolean;+ // Blocks the newest test left failing, so a folded turn still names them.+ stillFailing: BlockState[];+}++export function summarizeFinishedTurn(+ rows: ActivityRow[],+ turnFacts: TurnFacts | null,+): FinishedTurnSummary {+ const failedTests = rows.filter(isFailedTest).length;+ const fixed = failedTests > 0 && ranCleanOnCurrentSource(turnFacts);+ const newestRun = [...rows].reverse().find((row) => row.kind === "run");+ return {+ steps: rows.filter((row) => !isReasonOnlyRow(row)).length,+ failedTests,+ fixed,+ stillFailing:+ fixed || newestRun === undefined ? [] : failedRowBlocks(newestRun),+ };+}diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.test.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.test.tsindex 62dc6a077..ea84c03b1 100644--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.test.ts@@ -1,5 +1,12 @@import { describe, expect, it } from "vitest";+import {+ callRollup,+ deriveActivityLog,+ failedRowBlocks,+ passedBlockCount,+ summarizeFinishedTurn,+} from "./copilotActivityLog";import capture from "./narrativeState.hydrationParity.fixture.json";import {ActivityEntry,@@ -37,6 +44,48 @@ function replayLive(): TurnNarrativeState {);}+// Everything a collapsed step line and the folded turn show.+function logLines(+ turn: TurnNarrativeState,+ facts: TurnNarrativeState["turnFacts"],+) {+ const { rows } = deriveActivityLog(turn);+ const fold = summarizeFinishedTurn(rows, facts);+ return {+ rows: rows.map((row) => ({+ id: row.id,+ kind: row.kind,+ reason: row.reason,+ rollup: callRollup(row.entries),+ failed: failedRowBlocks(row).map((b) => b.workflowRunBlockId),+ passed: passedBlockCount(row),+ diff: row.codeDiffs.map((d) => [d.label, d.added, d.removed]),+ })),+ fold: {+ ...fold,+ stillFailing: fold.stillFailing.map((b) => b.workflowRunBlockId),+ },+ };+}++describe("activity log parity across hydration", () => {+ it("renders the same step lines, failure pins and reasons live and after a reload", () => {+ const hydrated = hydrateNarrativeFromPayload(persistedPayload)!;+ const live = logLines(replayLive(), hydrated.turnFacts);++ expect(logLines(hydrated, hydrated.turnFacts)).toEqual(live);+ // The capture exercises each piece, so equality is not vacuous.+ expect(live.rows.some((row) => row.failed.includes("wrb_first"))).toBe(+ true,+ );+ // The capture's retried block ran but was not evaluated, so no row claims it passed.+ expect(live.rows.some((row) => row.kind === "run")).toBe(true);+ expect(live.rows.every((row) => row.passed === null)).toBe(true);+ expect(live.rows.some((row) => row.reason !== null)).toBe(true);+ expect(live.fold.failedTests).toBe(1);+ });+});+describe("activity timestamp parity across hydration", () => {it("preserves observed fail-edit-retry attempts across terminal replacement and hydration", () => {const live = replayLive();diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.tsindex 71c808cf3..3956b73f7 100644--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts@@ -329,10 +329,8 @@ export interface ActivityEntry {toolName?: string;// Product-safe label for rendering tool activity to users.displayLabel?: string;- // activeLabel reads while the step runs; outcomeLabel replaces it once- // finished. Absent when the narrator did not speak for this step.+ // The narrator's intent for the step, used only to group browse retries.activeLabel?: string;- outcomeLabel?: string;// Result success when kind is tool_result.success?: boolean;// Server-computed line delta per code block this write changed. Absent on@@ -405,10 +403,7 @@ export interface TurnNarrativeState {// Live-only drafting progress from codegen_progress, never persisted. Holds// only what the row renders: the frames' cumulative character count changes// on every frame and would re-render the chat for nothing.- codegenProgress: {- blockLabels: string[];- startedAt: string | null;- } | null;+ codegenProgress: { blockLabels: string[] } | null;// Snapshot of the most recent factual run outcome.lastRunOutcome: {verdict: BlockOutcome;@@ -488,6 +483,16 @@ const MAX_DESIGN_ACTIVITY_ENTRIES = 50;// run-block id every iteration, so the block list is unbounded without this.const MAX_BLOCK_ATTEMPTS = 200;+// A saved turn at an activity cap may have dropped its oldest entries, so what it lacks is unknown.+export function activityMayBeTrimmed(narrative: TurnNarrativeState): boolean {+ return (+ narrative.designActivity.length >= MAX_DESIGN_ACTIVITY_ENTRIES ||+ narrative.blocks.some(+ (block) => block.activity.length >= MAX_ACTIVITY_ENTRIES,+ )+ );+}+// Some BE paths emit naive ISO datetimes (no timezone offset), e.g. the// chat-history endpoint serializing SQLAlchemy created_at columns. JS// Date.parse interprets those as local time, producing a multi-hour@@ -754,6 +759,57 @@ const ACTIVITY_TOOL_DISPLAY_LABELS: Record<string, string> = {synthesize_demonstrated_block: "Building a block from the recorded steps",};+// What kind of work a call did, for the activity log's per-step rollup. Keyed+// on the tool name alone; anything unlisted is a browser tool, which is what+// the MCP overlay adds.+export type ToolCallKind =+ | "browser"+ | "credential"+ | "plan"+ | "guidance"+ | "write"+ | "run"+ | "other";++const WRITE_TOOLS = new Set([+ ...AUTHORING_TOOLS,+ "edit_block",+ "add_block",+ "delete_block",+ "synthesize_demonstrated_block",+]);++const TOOL_CALL_KINDS: Record<string, ToolCallKind> = {+ list_credentials: "credential",+ fill_credential_field: "credential",+ request_credential: "credential",+ set_work_plan: "plan",+ get_workflow_knowledge: "guidance",+ ask_user: "other",+ get_block_schema: "other",+ validate_block: "other",+ inspect_current_workflow: "other",+ list_integrations: "other",+ get_organization_usage_quota: "other",+ search_web: "other",+ list_org_workflows: "other",+ get_org_workflow: "other",+ list_workflow_schedules: "other",+ get_workflow_schedule: "other",+ create_workflow_schedule: "other",+ update_workflow_schedule: "other",+ enable_workflow_schedule: "other",+ disable_workflow_schedule: "other",+ cancel_workflow_schedule: "other",+ delete_workflow_schedule: "other",+};++export function toolCallKind(toolName: string): ToolCallKind {+ if (RUN_TOOLS.has(toolName)) return "run";+ if (WRITE_TOOLS.has(toolName)) return "write";+ return TOOL_CALL_KINDS[toolName] ?? "browser";+}+export function toolActivityDisplayLabel(toolName?: string | null): string {if (!toolName) return "Working";return ACTIVITY_TOOL_DISPLAY_LABELS[toolName] ?? "Working";@@ -817,7 +873,6 @@ function buildActivityFromNarration(text: event.narration,iteration: event.iteration,activeLabel: event.active_label ?? undefined,- outcomeLabel: event.outcome_label ?? undefined,id: `n-${event.iteration}-${event.timestamp}`,timestamp: event.timestamp,receivedAtMs,@@ -954,6 +1009,22 @@ export function condenseActivityEntries(previousEndedMs === null ||currentStartedMs === null ||currentStartedMs >= previousEndedMs;+ // Position alone can't tell a sentence spoken between two attempts from one+ // spoken during the retry; the clock can, and an announced retry is its own step.+ const announcedRetry =+ previousEndedMs !== null &&+ currentStartedMs !== null &&+ condensed.slice(lastToolIdx + 1).some((between) => {+ const spokenMs =+ between?.kind === "narration"+ ? parseUtcIsoMs(between.timestamp)+ : null;+ return (+ spokenMs !== null &&+ spokenMs >= previousEndedMs &&+ spokenMs < currentStartedMs+ );+ });if (prevTool &&entry.toolName !== undefined &&@@ -962,7 +1033,8 @@ export function condenseActivityEntries(entry.displayLabel === undefined ||prevTool.displayLabel === entry.displayLabel) &&prevTool.success === false &&- followsPreviousAttempt+ followsPreviousAttempt &&+ !announcedRetry) {const { priorFailures: earlierFailures, ...previousAttempt } = prevTool;condensed[lastToolIdx] = null;@@ -1230,12 +1302,7 @@ export function applyNarrativeEvent(}return {...prev,- codegenProgress: {- blockLabels: merged,- // First frame of the generation wins, so the row's clock times the- // whole draft rather than restarting on each label or each call.- startedAt: drafting?.startedAt ?? event.timestamp ?? null,- },+ codegenProgress: { blockLabels: merged },};}@@ -1548,8 +1615,6 @@ function normalizeActivityEntries(raw: unknown): ActivityEntry[] {typeof o.displayLabel === "string" ? o.displayLabel : undefined,activeLabel:typeof o.activeLabel === "string" ? o.activeLabel : undefined,- outcomeLabel:- typeof o.outcomeLabel === "string" ? o.outcomeLabel : undefined,success: typeof o.success === "boolean" ? o.success : undefined,codeDiffs: parseCodeDiffs(o.codeDiffs),id: o.id,diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.tsindex 6fb03d51f..0cb7d6145 100644--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts@@ -486,8 +486,8 @@ export interface WorkflowCopilotCondensingUpdate {export interface WorkflowCopilotNarrationUpdate {type: "narration";narration: string;- // Narrator-authored row titles. Absent against a backend that predates them,- // so the row falls back to its tool-derived label.+ // The narrator's intent and outcome for the step. The log reads only+ // active_label, to group browse retries under one intent.active_label?: string | null;outcome_label?: string | null;iteration: number;