Skip to content

Commit e25b7ab

Browse files
authored
fix(session-ui): slide the tool group count when it changes (#55617)
1 parent 706a688 commit e25b7ab

5 files changed

Lines changed: 237 additions & 35 deletions

File tree

‎packages/session-ui/component-tests/tool-group.spec.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,31 @@
1+
import type { Locator } from "@playwright/test"
12
import { expect, story } from "../../storybook/playwright/story"
23

4+
// The digits drawn inside the count's clipped width, left to right. Each slot shows whichever visible glyph lines up
5+
// with it, so a slot mid-roll reads "_", and the spare leading zero outside the width is skipped.
6+
const shown = (count: Locator) =>
7+
count.locator('[data-slot="animated-number-value"]').evaluate((value) => {
8+
const clip = value.getBoundingClientRect()
9+
10+
return Array.from(value.querySelectorAll('[data-slot="animated-number-digit"]'), (slot) => ({
11+
slot,
12+
rect: slot.getBoundingClientRect(),
13+
}))
14+
.filter((item) => item.rect.left >= clip.left - 0.5 && item.rect.right <= clip.right + 0.5)
15+
.toSorted((a, b) => a.rect.left - b.rect.left)
16+
.map(
17+
(item) =>
18+
Array.from(item.slot.querySelectorAll("[data-digit]"))
19+
.find(
20+
(glyph) =>
21+
getComputedStyle(glyph).visibility === "visible" &&
22+
Math.abs(glyph.getBoundingClientRect().top - item.rect.top) < 0.5,
23+
)
24+
?.getAttribute("data-digit") ?? "_",
25+
)
26+
.join("")
27+
})
28+
329
for (const reasoningDefaultOpen of [false, true]) {
430
story(
531
`keeps ordered thoughts and tool-only counts with reasoning ${reasoningDefaultOpen ? "expanded" : "collapsed"}`,
@@ -109,6 +135,94 @@ story("summarizes subagents as Agent while retaining their card titles", async (
109135
await expect(group.locator('[data-component="task-tool-title"]')).toHaveText(["General", "Explore"])
110136
})
111137

138+
for (const direction of ["ltr", "rtl"]) {
139+
story(`reads and shows a two-digit count once, in order, in ${direction}`, async ({ mount, page }) => {
140+
const root = await mount("current-tool-group--sticky-header", { globals: { direction } })
141+
const count = root.locator('[data-component="context-tool-group-trigger"] [data-slot="context-tool-group-count"]')
142+
await expect(count).toHaveText("37")
143+
expect(await count.ariaSnapshot()).toBe('- text: "37"')
144+
// The clipped width follows the web font's metrics.
145+
await page.evaluate(() => document.fonts.ready.then(() => undefined))
146+
expect(await shown(count)).toBe("37")
147+
})
148+
}
149+
150+
story("does not animate the count on mount or when its font changes", async ({ mount }) => {
151+
const root = await mount("current-tool-group--sticky-header")
152+
const count = root.locator('[data-component="context-tool-group-trigger"] [data-slot="context-tool-group-count"]')
153+
await expect(count).toHaveText("37")
154+
expect(await count.evaluate((element) => element.getAnimations({ subtree: true }).length)).toBe(0)
155+
156+
// Like a late web font swap or a zoom change: the digit width changes without the count changing.
157+
await count.evaluate((element) => {
158+
element.style.fontSize = "20px"
159+
})
160+
expect(await count.evaluate((element) => element.getAnimations({ subtree: true }).length)).toBe(0)
161+
})
162+
163+
story("settles count changes made while detached, without rolling", async ({ mount }) => {
164+
const root = await mount("current-tool-group--count-rollover")
165+
const count = root.locator('[data-component="context-tool-group-trigger"] [data-slot="context-tool-group-count"]')
166+
await expect(count).toHaveText("9")
167+
168+
// A background session keeps adding tools while its cached timeline is detached.
169+
await root.getByRole("button", { name: "Detach" }).click()
170+
171+
for (let added = 0; added < 12; added++) await root.getByRole("button", { name: "Add read" }).click()
172+
173+
await root.getByRole("button", { name: "Attach" }).click()
174+
175+
await expect(count).toHaveText("21")
176+
expect(await count.evaluate((element) => element.getAnimations({ subtree: true }).length)).toBe(0)
177+
await expect(count.locator('[data-animating="true"]')).toHaveCount(0)
178+
expect(await shown(count)).toBe("21")
179+
})
180+
181+
story("keeps a digit rolling when the count changes again mid-roll", async ({ mount, page }) => {
182+
const root = await mount("current-tool-group--count-rollover")
183+
const count = root.locator('[data-component="context-tool-group-trigger"] [data-slot="context-tool-group-count"]')
184+
// A slow roll keeps the second change inside the first roll on a loaded machine.
185+
await page.addStyleTag({ content: ":root { --tool-motion-odometer-ms: 5000ms }" })
186+
await expect(count).toHaveText("9")
187+
188+
await root.getByRole("button", { name: "Add read" }).click()
189+
await root.getByRole("button", { name: "Add read" }).click()
190+
await expect(count).toHaveText("11")
191+
// 9 -> 10 starts the tens digit rolling; 10 -> 11 leaves it unchanged, so it finishes its roll instead of jumping.
192+
await expect(count.locator('[data-animating="true"]')).toHaveCount(2)
193+
})
194+
195+
story("rolls the leading digit in and out when the count gains or loses a digit", async ({ mount }) => {
196+
const root = await mount("current-tool-group--count-rollover")
197+
const count = root.locator('[data-component="context-tool-group-trigger"] [data-slot="context-tool-group-count"]')
198+
const rolling = count.locator('[data-animating="true"]')
199+
await expect(count).toHaveText("9")
200+
201+
await root.getByRole("button", { name: "Add read" }).click()
202+
// The tens digit rolls in from zero beside the ones digit instead of appearing.
203+
await expect(rolling).toHaveCount(2)
204+
expect(await count.ariaSnapshot()).toBe('- text: "10"')
205+
await expect(rolling).toHaveCount(0)
206+
207+
await root.getByRole("button", { name: "Remove read" }).click()
208+
// The tens digit rolls back to zero before it leaves instead of vanishing.
209+
await expect(rolling).toHaveCount(2)
210+
expect(await count.ariaSnapshot()).toBe('- text: "9"')
211+
await expect(rolling).toHaveCount(0)
212+
await expect(count).toHaveText("9")
213+
})
214+
215+
story("rolls the count and exposes only its current value while rolling", async ({ mount }) => {
216+
const root = await mount("current-tool-group--mixed-reasoning")
217+
const count = root.locator('[data-component="context-tool-group-trigger"] [data-slot="context-tool-group-count"]')
218+
await expect(count).toHaveText("4")
219+
await root.getByRole("button", { name: "Append follow-up read" }).click()
220+
await expect(count.locator('[data-animating="true"]')).toHaveCount(1)
221+
// One read mid-roll: a retrying assertion would pass once the strip hides again.
222+
expect(await count.ariaSnapshot()).toBe('- text: "5"')
223+
await expect(count).toHaveText("5")
224+
})
225+
112226
for (const width of [840, 390]) {
113227
story(`keeps grouped cards inside their trigger bounds at ${width}px`, async ({ mount, page }) => {
114228
await page.setViewportSize({ width, height: 600 })

‎packages/session-ui/src/tools/tool-group.stories.tsx‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,47 @@ export const MixedReasoning = {
109109
},
110110
}
111111

112+
export const CountRollover = {
113+
render: () => {
114+
const [state, setState] = createStore({ open: false, count: 9, attached: true })
115+
116+
const parts = createMemo(() =>
117+
Array.from({ length: state.count }, (_, index) =>
118+
storyTool(`rollover_read_${index}`, "read", "completed", { path: `src/file-${index}.ts` }),
119+
),
120+
)
121+
122+
// Created once, like a cached session timeline: detaching removes it from the page but keeps it updating.
123+
const group = (
124+
<CurrentSessionProviders document={storyDocument(parts())}>
125+
<CurrentContextToolGroup
126+
parts={parts()}
127+
busy={false}
128+
open={state.open}
129+
onOpenChange={(open) => setState("open", open)}
130+
/>
131+
</CurrentSessionProviders>
132+
)
133+
134+
return (
135+
<section class="mx-auto flex w-full max-w-[860px] flex-col gap-4 p-6">
136+
<div class="flex gap-3">
137+
<button type="button" onClick={() => setState("count", (count) => count + 1)}>
138+
Add read
139+
</button>
140+
<button type="button" onClick={() => setState("count", (count) => count - 1)}>
141+
Remove read
142+
</button>
143+
<button type="button" onClick={() => setState("attached", (attached) => !attached)}>
144+
{state.attached ? "Detach" : "Attach"}
145+
</button>
146+
</div>
147+
<Show when={state.attached}>{group}</Show>
148+
</section>
149+
)
150+
},
151+
}
152+
112153
// Mirrors a long exploration turn in a timeline viewport with the session title header above it.
113154
const stickyCommands = [
114155
"git log --oneline 09c318094c..upstream/v2 -- packages/tui/src/plugin/structure.ts packages/tui/src/plugin/render.tsx",
@@ -168,7 +209,7 @@ export const StickyHeader = {
168209
args: { height: 720 },
169210
argTypes: { height: { control: { type: "range", min: 320, max: 1200, step: 20 } } },
170211
render: (args: { height: number }) => {
171-
const [state, setState] = createStore({ open: true, files: {} as Record<string, boolean> })
212+
const [state, setState] = createStore<{ open: boolean; files: Record<string, boolean> }>({ open: true, files: {} })
172213

173214
return (
174215
<section

‎packages/session-ui/src/tools/tool-renderer.tsx‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import { checksum } from "@opencode/util/encode"
3939
import { Tooltip } from "@opencode/ui/tooltip"
4040
import { IconButton } from "@opencode/ui/icon-button"
4141
import { TextShimmer } from "@opencode/ui/text-shimmer"
42+
import { AnimatedNumber } from "@opencode/ui/animated-number"
4243
import { changedFileDiff, patchFileGroups } from "../components/apply-patch-file"
4344
import { animate } from "motion"
4445
import { SessionProgressIndicatorV2 } from "../v2/components/session-progress-indicator-v2"
@@ -497,7 +498,7 @@ export function CurrentContextToolGroup(props: {
497498
if (!names() && !thoughts) {
498499
const text = i18n.t("ui.messagePart.context.updates")
499500

500-
return { text, title: "", before: text, count: "", between: "", after: "" }
501+
return { text, title: "", before: text, count: undefined, between: "", after: "" }
501502
}
502503

503504
const title = names() || i18n.plural("ui.messagePart.context.thought", thoughts)
@@ -509,13 +510,13 @@ export function CurrentContextToolGroup(props: {
509510
const countIndex = before.indexOf(countText)
510511
const after = text.slice(index + title.length).trim()
511512

512-
if (countIndex === -1) return { text, title, before, count: "", between: "", after }
513+
if (countIndex === -1) return { text, title, before, count: undefined, between: "", after }
513514

514515
return {
515516
text,
516517
title,
517518
before: before.slice(0, countIndex).trim(),
518-
count: countText,
519+
count,
519520
between: before.slice(countIndex + countText.length).trim(),
520521
after,
521522
}
@@ -617,7 +618,11 @@ export function CurrentContextToolGroup(props: {
617618
{(before) => <span data-slot="context-tool-group-prefix">{before()}</span>}
618619
</Show>
619620
<Show when={label().count}>
620-
{(count) => <span data-slot="context-tool-group-count">{count()}</span>}
621+
{(count) => (
622+
<span data-slot="context-tool-group-count">
623+
<AnimatedNumber value={count()} />
624+
</span>
625+
)}
621626
</Show>
622627
<Show when={label().between}>
623628
{(between) => <span data-slot="context-tool-group-prefix">{between()}</span>}

‎packages/ui/src/components/animated-number.css‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,23 @@
77

88
[data-slot="animated-number-value"] {
99
display: inline-flex;
10-
flex-direction: row-reverse;
10+
/* Digits keep numeric order in RTL documents. */
11+
direction: ltr;
1112
align-items: baseline;
1213
justify-content: flex-end;
1314
line-height: inherit;
1415
width: var(--animated-number-width, 1ch);
1516
overflow: hidden;
17+
}
18+
19+
[data-slot="animated-number-value"][data-resizing="true"] {
1620
transition: width var(--tool-motion-spring-ms, 560ms) var(--tool-motion-ease, cubic-bezier(0.22, 1, 0.36, 1));
1721
}
1822

1923
[data-slot="animated-number-digit"] {
2024
display: inline-grid;
25+
/* Digits outside the width are clipped at the start edge, not squeezed. */
26+
flex-shrink: 0;
2127
width: 1ch;
2228
height: 1em;
2329
line-height: 1em;
@@ -56,15 +62,22 @@
5662
line-height: 1em;
5763
}
5864

65+
[data-slot="animated-number-static"]::before,
66+
[data-slot="animated-number-cell"]::before {
67+
content: attr(data-digit);
68+
}
69+
5970
[data-slot="animated-number-digit"][data-animating="true"] [data-slot="animated-number-static"] {
6071
visibility: hidden;
6172
}
6273

6374
[data-slot="animated-number-strip"] {
6475
display: inline-flex;
6576
flex-direction: column;
66-
margin-top: calc(var(--animated-number-offset, 10) * -1em);
67-
transition-property: margin-top;
77+
/* Not transform: a composited roll lands on whole pixels, then the digit shifts as it settles. */
78+
position: relative;
79+
top: calc(var(--animated-number-offset, 10) * -1em);
80+
transition-property: top;
6881
transition-duration: var(--animated-number-duration, 560ms);
6982
transition-timing-function: var(--tool-motion-ease, cubic-bezier(0.22, 1, 0.36, 1));
7083
}
@@ -76,7 +89,7 @@
7689
}
7790

7891
@media (prefers-reduced-motion: reduce) {
79-
[data-component="animated-number"] [data-slot="animated-number-value"] {
92+
[data-component="animated-number"] [data-slot="animated-number-value"][data-resizing] {
8093
transition-duration: 0ms;
8194
}
8295

0 commit comments

Comments
 (0)