Skip to content

Commit abb0def

Browse files
author
ben
authored
fix(chat): release blank tool panels after App connection (#7055)
* fix(chat): stop retaining blank tool panels with steady layout off * test(chat): verify settled tools release live-step height
1 parent 4e4be21 commit abb0def

5 files changed

Lines changed: 88 additions & 72 deletions

File tree

‎apps/app/src/components/chat/mcp-app-frame.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,6 +1197,8 @@ function EmbeddedMcpAppFrame({ part, origin: surfaceOrigin }: { part: DynamicToo
11971197
if (error) return <McpAppDiagnosticNotice error={error} notice={CHAT_MCP_APP_UNAVAILABLE_NOTICE} onRetry={() => setResolveToken((token) => token + 1)} engine={origin.engine} />
11981198
if (!app || resolvedFor.current !== resolution) return launch && resolvedFor.current !== resolution
11991199
? <McpAppLoading /> : null
1200+
// An empty resource is not a view: do not reserve the default iframe height.
1201+
if (!app.html.trim()) return null
12001202
if (appConnection) return <DashboardConnectionCard toolName={appConnection.toolName} toolCallId={`${part.toolCallId}:app`}
12011203
output={appConnection.output} onConnected={() => { setAppConnection(null); setResolveToken((token) => token + 1) }} />
12021204
return (

‎apps/app/src/components/chat/message-list.tsx‎

Lines changed: 6 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1397,56 +1397,6 @@ function getRenderableMessage(message: UIMessage) {
13971397
return parts.length > 0 ? { ...message, parts } : null;
13981398
}
13991399

1400-
/**
1401-
* Running steps only ever grow. When a finished step folds its live detail
1402-
* before the next step's row arrives, the area briefly got shorter and the
1403-
* chat jumped; holding the tallest height seen during the run keeps it still.
1404-
* The hold ends when the turn folds or the App panel replaces these steps.
1405-
*/
1406-
function LiveSteps({ children, active }: { children: React.ReactNode; active: boolean }) {
1407-
const ref = React.useRef<HTMLDivElement>(null)
1408-
React.useLayoutEffect(() => {
1409-
const element = ref.current
1410-
if (!element) return
1411-
// The hold only protects a running turn from the engine's own shrinks.
1412-
// A finished turn, or a group the person collapsed, may get shorter.
1413-
if (!active || typeof ResizeObserver === "undefined") {
1414-
element.style.minHeight = ""
1415-
return
1416-
}
1417-
let tallest = 0
1418-
const hold = () => {
1419-
element.style.minHeight = ""
1420-
const height = element.getBoundingClientRect().height
1421-
if (height > tallest) tallest = height
1422-
element.style.minHeight = `${tallest}px`
1423-
}
1424-
const release = () => {
1425-
tallest = 0
1426-
element.style.minHeight = ""
1427-
}
1428-
hold()
1429-
const observer = new ResizeObserver(hold)
1430-
for (const child of element.children) observer.observe(child)
1431-
const mutations = new MutationObserver(() => {
1432-
observer.disconnect()
1433-
for (const child of element.children) observer.observe(child)
1434-
hold()
1435-
})
1436-
mutations.observe(element, { childList: true })
1437-
element.addEventListener("pointerdown", release)
1438-
element.addEventListener("keydown", release)
1439-
return () => {
1440-
observer.disconnect()
1441-
mutations.disconnect()
1442-
element.removeEventListener("pointerdown", release)
1443-
element.removeEventListener("keydown", release)
1444-
element.style.minHeight = ""
1445-
}
1446-
}, [active])
1447-
return <div ref={ref} data-live-steps="" className="flex flex-col gap-2">{children}</div>
1448-
}
1449-
14501400
/**
14511401
* steadyLiveTurn: while a turn runs, the chat never gets shorter. When the
14521402
* live turn shrinks (a step folds its detail before the next row arrives) the
@@ -1625,8 +1575,8 @@ function MessageGroup({
16251575
const savedFileActions = React.useMemo(() => isElectronRuntime() && !readOnly ? desktopSavedFileActions(sessionId) : undefined, [readOnly, sessionId])
16261576
const watchingComputer = useComputerSessionHistoryStore(state => Boolean(state.watching[sessionId]))
16271577
// steadyLiveTurn: a running turn keeps its parts in arrival order (no
1628-
// steps/answer split until it finishes) and the list reserves room at its end
1629-
// (LiveTurnReserve) instead of holding the steps area open.
1578+
// steps/answer split until it finishes) and reserves room only at the list's
1579+
// end (LiveTurnReserve). With the flag off, neither area reserves height.
16301580
const steadyLiveTurn = useSteadyLiveTurnStore(state => state.enabled)
16311581
// The skill this turn produced stays in view as its result, even when the
16321582
// steps fold; later updates and shares change this card, not add another.
@@ -1853,11 +1803,11 @@ function MessageGroup({
18531803
</div>
18541804
</CompletedStepRun>
18551805
) : (
1856-
<LiveSteps active={isLiveGroup && !panelLive && !steadyLiveTurn}>
1857-
{/* The App panel replaces ordinary steps. Release their held height
1858-
as they fold away, otherwise an empty rail pushes the panel down. */}
1806+
<div data-live-steps="" className="flex flex-col gap-2">
1807+
{/* Do not hold folded tool content open. Scroll stabilization belongs
1808+
to LiveTurnReserve, behind steadyLiveTurn, below the Working line. */}
18591809
{renderItems(stepItems, 0, panelLive)}
1860-
</LiveSteps>
1810+
</div>
18611811
)
18621812
) : null}
18631813
{creationRuns.map(run => <Message key={`creation-${run.id}`} className="mx-auto flex w-full max-w-3xl flex-col px-2 md:px-10"><AppBuilderStep run={run} startedAt={getMessageCreated(items[0]!.message)} completedAt={getMessageCompleted(lastItem.message)} activity={run === creationRuns.at(-1) ? panelActivity : null} active={creationLive && (run === creationRuns.at(-1) || Boolean(run.preparation && isToolPartInFlight(run.preparation)) || run.builds.some(isToolPartInFlight))} /></Message>)}

‎apps/app/tests/mcp-app-frame.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2103,6 +2103,18 @@ describe("MCP App resolution", () => {
21032103
} finally { await host.dispose() }
21042104
})
21052105

2106+
test.each(["", " \n\t"])("does not mount a blank iframe for an empty App document (%j)", async html => {
2107+
const host = resolutionFixture(true)
2108+
host.resolveSpy.mockResolvedValue({ app: fixture({ html }) })
2109+
try {
2110+
await host.render()
2111+
expect(host.resolveSpy).toHaveBeenCalledTimes(1)
2112+
expect(host.container.querySelector("iframe")).toBeNull()
2113+
expect(host.container.querySelector("[data-mcp-app-resource]")).toBeNull()
2114+
expect(host.container.textContent).toBe("")
2115+
} finally { await host.dispose() }
2116+
})
2117+
21062118
test.each([false, true])("catalog-shaped preserved data uses only standard resource resolution (advertised: %s)", async advertised => {
21072119
const host = resolutionFixture(false)
21082120
if (advertised) host.resolveSpy.mockResolvedValue({ app: fixture() })

‎apps/app/tests/message-list-steady-live-turn.test.tsx‎

Lines changed: 63 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { afterAll, afterEach, expect, test } from "bun:test"
1+
import { afterAll, afterEach, expect, spyOn, test } from "bun:test"
22
import { GlobalRegistrator } from "@happy-dom/global-registrator"
33
import { act, createElement } from "react"
44
import { createRoot, type Root } from "react-dom/client"
@@ -51,13 +51,8 @@ const messages: UIMessage[] = [{
5151
metadata: { opencode: { created: 2 } },
5252
}]
5353

54-
async function renderLiveTurn(steady: boolean, status: "streaming" | "ready" = "streaming") {
55-
useSteadyLiveTurnStore.getState().setEnabled(steady)
56-
const container = document.createElement("div")
57-
document.body.append(container)
58-
const root = createRoot(container)
59-
mounted = { root, container }
60-
await act(async () => root.render(createElement(QueryClientProvider, { client: queryClient,
54+
function liveTurnView(status: "streaming" | "ready", content: UIMessage[] = messages) {
55+
return createElement(QueryClientProvider, { client: queryClient,
6156
children: createElement(DenAuthProvider, { children: createElement(PlatformProvider, {
6257
value: createDefaultPlatform(),
6358
children: createElement(MessageListProvider, {
@@ -67,16 +62,70 @@ async function renderLiveTurn(steady: boolean, status: "streaming" | "ready" = "
6762
onForkAtMessage: () => {}, onEditUserMessage: () => {},
6863
onMcpReconnect: async () => { throw new Error("Unexpected reconnect") },
6964
onMcpReopenAuthorization: async () => {},
70-
children: createElement(MessageList, { messages, status, activityStatus: status === "streaming" ? "responding" : "idle" }),
65+
children: createElement(MessageList, { messages: content, status, activityStatus: status === "streaming" ? "responding" : "idle" }),
7166
}),
72-
}) }) })))
67+
}) }) })
68+
}
69+
70+
async function renderLiveTurn(steady: boolean, status: "streaming" | "ready" = "streaming") {
71+
useSteadyLiveTurnStore.getState().setEnabled(steady)
72+
const container = document.createElement("div")
73+
document.body.append(container)
74+
const root = createRoot(container)
75+
mounted = { root, container }
76+
await act(async () => root.render(liveTurnView(status)))
7377
return container
7478
}
7579

76-
test("off: a running turn is split at its latest text and its steps area holds its height", async () => {
77-
const container = await renderLiveTurn(false)
78-
expect(container.querySelector("[data-live-steps]")).not.toBeNull()
79-
expect(container.querySelector("[data-live-turn-reserve]")).toBeNull()
80+
test("off: a running turn splits at its latest text without holding a blank steps panel open", async () => {
81+
// A tall live tool detail can disappear when the tool settles or the latest
82+
// answer moves. Simulate real layout: happy-dom does not measure content.
83+
const measure = spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
84+
return new DOMRect(0, 0, 600, this.hasAttribute("data-live-steps") ? 900 : 0)
85+
})
86+
try {
87+
const container = await renderLiveTurn(false)
88+
const steps = container.querySelector<HTMLElement>("[data-live-steps]")
89+
expect(steps).not.toBeNull()
90+
expect(steps?.style.minHeight).toBe("")
91+
expect(container.querySelector("[data-live-turn-reserve]")).toBeNull()
92+
// Toggling the rollout must not leave a reserved height on the off path.
93+
await act(async () => useSteadyLiveTurnStore.getState().setEnabled(true))
94+
await act(async () => useSteadyLiveTurnStore.getState().setEnabled(false))
95+
expect(container.querySelector<HTMLElement>("[data-live-steps]")?.style.minHeight).toBe("")
96+
} finally {
97+
measure.mockRestore()
98+
}
99+
})
100+
101+
test("off: settling a tool and advancing the answer releases its old height before the turn ends", async () => {
102+
let height = 900
103+
const measure = spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
104+
return new DOMRect(0, 0, 600, this.hasAttribute("data-live-steps") ? height : 0)
105+
})
106+
try {
107+
const container = await renderLiveTurn(false)
108+
const root = mounted?.root
109+
if (!root) throw new Error("Missing live turn root")
110+
// The same call settles, then the next text changes the steps/answer split.
111+
// Neither transition is a pointer/key event that could release a height hold.
112+
const next: UIMessage[] = messages.map(message => message.role !== "assistant" ? message : {
113+
...message,
114+
parts: message.parts.map(part => part.type === "dynamic-tool" && part.toolCallId === "call_after"
115+
? { ...part, state: "output-available", output: "No conflicts." } : part).concat({ type: "text", text: "Available times are ready." }),
116+
})
117+
height = 40
118+
await act(async () => root.render(liveTurnView("streaming", next)))
119+
expect(container.textContent).toContain("Available times are ready.")
120+
expect(container.querySelector<HTMLElement>("[data-live-steps]")?.style.minHeight).toBe("")
121+
expect(container.querySelector("[data-live-turn-reserve]")).toBeNull()
122+
await act(async () => root.render(liveTurnView("ready", next)))
123+
expect(container.textContent).toContain("Available times are ready.")
124+
expect(container.querySelector("[data-live-steps]")).toBeNull()
125+
expect(container.querySelector("[data-live-turn-reserve]")).toBeNull()
126+
} finally {
127+
measure.mockRestore()
128+
}
80129
})
81130

82131
test("on: a running turn keeps its parts in arrival order, with no steps area to hold open", async () => {

‎docs/features/steady-live-turn/README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,8 @@ up while it runs. The `measure-chat-flicker` skill counts upward jumps.
3636

3737
## Turning it off
3838

39-
Takes effect on the next render: the previous live layout returns. Nothing is
40-
stored; history is unaffected.
39+
Takes effect on the next render: the live turn again splits at its latest text.
40+
The steps area no longer retains its tallest height with either setting, so
41+
folded tool details cannot leave an empty panel between steps and the answer.
42+
Only the feature-on path reserves released room below the Working line.
43+
Nothing is stored; history is unaffected.

0 commit comments

Comments
 (0)