Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(composer): stabilize and animate reasoning slider interactions

ZeroYfe259260e4bc
diff --git a/apps/desktop/src/components/settings/AnchoredMenu.tsx b/apps/desktop/src/components/settings/AnchoredMenu.tsx
index 6514908ad..4e8f0d44c 100644
--- a/apps/desktop/src/components/settings/AnchoredMenu.tsx
+++ b/apps/desktop/src/components/settings/AnchoredMenu.tsx
@@ -214,8 +214,8 @@ export function AnchoredMenu({
const onViewportChange = (event: Event) => {
// Scrolling inside the menu cannot move a fixed layer, so skip it rather
// than forcing a layout read on every scroll tick.
- const target = event.target as Node | null;
- if (target && menuRef.current?.contains(target)) return;
+ const target = event.target;
+ if (target instanceof Node && menuRef.current?.contains(target)) return;
updatePosition();
};
window.addEventListener("resize", onViewportChange);
diff --git a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
index f04a55d27..3cb942b06 100644
--- a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
@@ -1,4 +1,3 @@
-import { useEffect, useRef, useState, type CSSProperties } from "react";
import type { TFunction } from "i18next";
import { formatTokenCount, modelIdsMatch } from "@pi-desktop/shared";
import { AnchoredMenu } from "../../../components/settings/AnchoredMenu";
@@ -14,26 +13,10 @@ import {
import { TooltipButton } from "../../../components/ui";
import { composerModelBadges } from "../../../lib/composer-models";
import type { useComposerModelMenu } from "./hooks/useComposerModelMenu";
+import { ThinkingLevelSlider } from "./ThinkingLevelSlider";
type ModelMenuController = ReturnType<typeof useComposerModelMenu>;
-/**
- * Keys the native range input must own while focused. The menu root ignores
- * arrows, but stopping propagation keeps the keys unambiguous — they adjust
- * the level, never drive menu navigation — no matter where focus lands.
- */
-const THINKING_SLIDER_KEYS = new Set([
- "ArrowLeft",
- "ArrowRight",
- "ArrowUp",
- "ArrowDown",
- "Home",
- "End",
- "PageUp",
- "PageDown",
- "Enter",
-]);
-
export type ComposerModelPickerProps = {
t: TFunction;
controller: ModelMenuController;
@@ -82,50 +65,6 @@ export function ComposerModelPicker({
onMenuKeyDown,
} = controller;
- // Slider geometry: one stop per available level, with the fill carried as
- // a CSS custom property so the accent track can follow the native input.
- const thinkingSliderIndex = Math.max(
- thinkingMenuLevels.findIndex((level) => level === thinkingLevel),
- 0,
- );
- // Local drag lead: the native input follows the pointer or arrow key
- // immediately while the store confirmation lands, so a controlled value
- // never snaps back mid-drag. The lead clears once the store confirms.
- const thinkingLevelsKey = thinkingMenuLevels.join("|");
- const [dragThinkingIndex, setDragThinkingIndex] = useState<number | null>(null);
- // Settle pulse: only when a drag commit has just landed (the drag lead goes
- // from set to cleared) do we mark the control settling, which lets the
- // thumb play its overshoot pop once. Opening the menu never settles.
- const [settling, setSettling] = useState(false);
- const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- useEffect(() => {
- setDragThinkingIndex(null);
- }, [thinkingLevelsKey]);
- useEffect(() => {
- if (dragThinkingIndex === null) return;
- if (thinkingMenuLevels[dragThinkingIndex] === thinkingLevel) {
- setDragThinkingIndex(null);
- setSettling(true);
- if (settleTimerRef.current) clearTimeout(settleTimerRef.current);
- settleTimerRef.current = setTimeout(() => setSettling(false), 220);
- }
- }, [dragThinkingIndex, thinkingLevel, thinkingLevelsKey, thinkingMenuLevels]);
- useEffect(
- () => () => {
- if (settleTimerRef.current) clearTimeout(settleTimerRef.current);
- },
- [],
- );
- const thinkingSliderValue = dragThinkingIndex ?? thinkingSliderIndex;
- // The accent fill starts half a column in and its width is a fraction of
- // the full rail width, so i/n reaches exactly the active stop's column
- // center and the thumb's x. (The fill layer is the rail's ::after; its
- // percentage is relative to the full rail width.)
- const thinkingSliderPercent =
- thinkingMenuLevels.length > 1
- ? (thinkingSliderValue / thinkingMenuLevels.length) * 100
- : 0;
-
return (
<AnchoredMenu
className="composer-model-thinking"
@@ -203,78 +142,13 @@ export function ComposerModelPicker({
(issue #417): one drag adjusts the level without entering the
submenu, while the entry itself opens the classic radio list. */}
{thinkingMenuLevels.length > 1 ? (
- <div
- className="composer-thinking-slider"
- data-dragging={dragThinkingIndex !== null ? "true" : undefined}
- data-settling={settling ? "true" : undefined}
- style={{ "--stop-count": thinkingMenuLevels.length } as CSSProperties}
- >
- {/*
- One grid owns the geometry: the dots row and the labels row
- share the same n columns, so the dot, the thumb and the label
- all sit on the same column center for every stop count. The
- range input is the accessible control and overlays the dots
- row only, leaving the labels free to be clicked and hovered.
-
- Motion: while a drag is in flight (data-dragging) the thumb,
- dots and fill track the pointer with no transition so the
- control feels direct; once the store confirms and the drag
- lead clears, the settle transition plays (thumb pop, dot and
- label color, fill slide). See composer-menus.css.
- */}
- <div className="composer-thinking-rail">
- <div className="composer-thinking-dots" aria-hidden="true">
- {thinkingMenuLevels.map((level, index) => (
- <span
- key={level}
- className={`composer-thinking-dot ${thinkingSliderValue === index ? "active" : ""}`}
- />
- ))}
- </div>
- <input
- type="range"
- className="composer-thinking-range"
- min={0}
- max={thinkingMenuLevels.length - 1}
- step={1}
- value={thinkingSliderValue}
- aria-label={t("chat.reasoningLevel")}
- aria-valuetext={thinkingMenuLevels[thinkingSliderValue] ?? thinkingLevel}
- style={
- {
- "--composer-thinking-progress": `${thinkingSliderPercent}%`,
- } as CSSProperties
- }
- onChange={(event) => {
- const index = Number(event.target.value);
- setDragThinkingIndex(index);
- const level = thinkingMenuLevels[index];
- if (level && level !== thinkingLevel) void commitThinkingLevel(level);
- }}
- onKeyDown={(event) => {
- if (THINKING_SLIDER_KEYS.has(event.key)) event.stopPropagation();
- }}
- />
- </div>
- <div className="composer-thinking-ticks" aria-hidden="true">
- {thinkingMenuLevels.map((level, index) => (
- <button
- key={level}
- type="button"
- tabIndex={-1}
- className={`composer-thinking-tick ${thinkingSliderValue === index ? "active" : ""}`}
- title={level}
- onMouseDown={(event) => event.preventDefault()}
- onClick={() => {
- setDragThinkingIndex(index);
- if (level !== thinkingLevel) void commitThinkingLevel(level);
- }}
- >
- {level}
- </button>
- ))}
- </div>
- </div>
+ <ThinkingLevelSlider
+ key={`${selectedProviderId}:${selectedModelId}:${thinkingMenuLevels.join("|")}`}
+ levels={thinkingMenuLevels}
+ level={thinkingLevel}
+ label={t("chat.reasoningLevel")}
+ commit={commitThinkingLevel}
+ />
) : null}
</div>
) : (
diff --git a/apps/desktop/src/features/chat/composer/ThinkingLevelSlider.tsx b/apps/desktop/src/features/chat/composer/ThinkingLevelSlider.tsx
new file mode 100644
index 000000000..a2188b261
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/ThinkingLevelSlider.tsx
@@ -0,0 +1,103 @@
+import { useEffect, useRef, useState, type CSSProperties } from "react";
+import type { SessionThinkingLevel } from "@pi-desktop/shared";
+
+const SLIDER_KEYS = new Set([
+ "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
+ "Home", "End", "PageUp", "PageDown", "Enter",
+]);
+
+type Props = {
+ levels: readonly SessionThinkingLevel[];
+ level: string;
+ label: string;
+ commit: (level: SessionThinkingLevel) => Promise<boolean>;
+};
+
+/** Native input owns interaction; the decorative thumb owns visual motion. */
+export function ThinkingLevelSlider({ levels, level, label, commit }: Props) {
+ const [pendingIndex, setPendingIndex] = useState<number | null>(null);
+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
+ const rail = useRef<HTMLDivElement>(null);
+ const [dragging, setDragging] = useState(false);
+ const pointer = useRef<{ id: number; x: number } | null>(null);
+ const request = useRef(0);
+ const confirmedIndex = Math.max(0, levels.findIndex((candidate) => candidate === level));
+ const index = pendingIndex ?? confirmedIndex;
+
+ useEffect(() => () => { request.current += 1; }, []);
+
+ const select = (next: number) => {
+ const target = levels[next];
+ if (!target || next === index) return;
+ setPendingIndex(next);
+ const revision = ++request.current;
+ // The controller owns error reporting and serial persistence. Only the
+ // latest request may roll back this optimistic visual selection; older
+ // completions must not snap a newer click back to a stale level.
+ void commit(target).then(() => {
+ if (request.current === revision) setPendingIndex(null);
+ });
+ };
+ const finishPointer = () => {
+ pointer.current = null;
+ setDragging(false);
+ };
+
+ return <div
+ className="composer-thinking-slider"
+ data-dragging={dragging ? "true" : undefined}
+ onPointerMove={(event) => {
+ if (event.pointerType === "touch" || !rail.current) return;
+ // The native range covers the decorative dots. Resolve both rows against
+ // the same equal-width columns, including the gap between dot and label.
+ const bounds = rail.current.getBoundingClientRect();
+ const next = Math.floor((event.clientX - bounds.left) / bounds.width * levels.length);
+ setHoveredIndex(next >= 0 && next < levels.length ? next : null);
+ }}
+ onPointerLeave={() => setHoveredIndex(null)}
+ onPointerCancel={() => setHoveredIndex(null)}
+ style={{
+ "--stop-count": levels.length,
+ "--composer-thinking-progress": `${index / levels.length * 100}%`,
+ } as CSSProperties}
+ >
+ <div className="composer-thinking-rail" ref={rail}>
+ <div className="composer-thinking-dots" aria-hidden="true">
+ {levels.map((candidate, stop) => <span key={candidate}
+ data-filled={stop < index ? "true" : undefined}
+ data-hovered={hoveredIndex === stop ? "true" : undefined}
+ className={`composer-thinking-dot ${index === stop ? "active" : ""}`} />)}
+ </div>
+ <span className="composer-thinking-thumb" aria-hidden="true" />
+ <input
+ type="range"
+ className="composer-thinking-range"
+ min={0} max={levels.length - 1} step={1} value={index}
+ aria-label={label} aria-valuetext={levels[index] ?? level}
+ onChange={(event) => select(Number(event.target.value))}
+ onPointerDown={(event) => {
+ if (!event.isPrimary || event.button !== 0) return;
+ pointer.current = { id: event.pointerId, x: event.clientX };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }}
+ onPointerMove={(event) => {
+ const origin = pointer.current;
+ if (origin?.id === event.pointerId && Math.abs(event.clientX - origin.x) > 3) setDragging(true);
+ }}
+ onPointerUp={finishPointer}
+ onPointerCancel={finishPointer}
+ onLostPointerCapture={finishPointer}
+ onKeyDown={(event) => {
+ if (SLIDER_KEYS.has(event.key)) event.stopPropagation();
+ }}
+ />
+ </div>
+ <div className="composer-thinking-ticks" aria-hidden="true">
+ {levels.map((candidate, stop) => <button key={candidate} type="button" tabIndex={-1}
+ data-hovered={hoveredIndex === stop ? "true" : undefined}
+ className={`composer-thinking-tick ${index === stop ? "active" : ""}`}
+ title={candidate} onMouseDown={(event) => event.preventDefault()}
+ onClick={() => select(stop)}>{candidate}</button>)}
+ </div>
+ </div>;
+}
diff --git a/apps/desktop/src/styles/composer-menus.css b/apps/desktop/src/styles/composer-menus.css
index 7b629868c..e2a9fe9f4 100644
--- a/apps/desktop/src/styles/composer-menus.css
+++ b/apps/desktop/src/styles/composer-menus.css
@@ -37,6 +37,8 @@
.composer-model-thinking {
position: relative;
+ /* Keep the label-sized trigger inside its shrinking toolbar slot. */
+ display: flex;
min-width: 0;
flex: 0 1 auto;
}
@@ -120,6 +122,12 @@
color: var(--ds-text-primary) !important;
}
+/* The menu measures this button on release. A press-scale transition would
+ cache a transient anchor rect until the first selection repositions it. */
+.composer-model-thinking-chip:active:not(:disabled) {
+ transform: none;
+}
+
.composer-model-thinking-icon {
display: inline-flex;
flex: 0 0 auto;
@@ -251,6 +259,7 @@
in --thinking-thumb-radius so the formula stays correct if it changes. */
.composer-thinking-slider {
--thinking-thumb-radius: 7px;
+ --thinking-dot-radius: 2px;
--thinking-track-height: 4px;
--thinking-track-center: 7px; /* (18 - 4) / 2 inside the 18px input */
--thinking-inset: calc(100% / (2 * var(--stop-count, 1)) - var(--thinking-thumb-radius));
@@ -273,6 +282,7 @@
.composer-thinking-rail::before,
.composer-thinking-rail::after {
content: "";
+ pointer-events: none;
position: absolute;
top: var(--thinking-track-center);
left: calc(100% / (2 * var(--stop-count, 1)));
@@ -286,8 +296,11 @@
}
.composer-thinking-rail::after {
- width: var(--composer-thinking-progress, 0%);
+ /* Cover the first dot's full rounded cap without moving the target end. */
+ left: calc(100% / (2 * var(--stop-count, 1)) - var(--thinking-dot-radius));
+ width: calc(var(--composer-thinking-progress, 0%) + var(--thinking-dot-radius));
background: var(--ds-accent);
+ transition: width var(--motion-duration-normal) var(--motion-ease-out);
}
/* One dot per stop, centered on the rail at each full-width column center. */
@@ -296,15 +309,14 @@
inset: 0;
display: grid;
grid-template-columns: repeat(var(--stop-count, 1), minmax(0, 1fr));
- gap: 2px;
align-items: center;
pointer-events: none;
}
.composer-thinking-dot {
justify-self: center;
- width: 4px;
- height: 4px;
+ width: calc(2 * var(--thinking-dot-radius));
+ height: calc(2 * var(--thinking-dot-radius));
border-radius: var(--radius-full);
background: var(--ds-text-muted);
opacity: 0.55;
@@ -320,10 +332,19 @@
opacity: 1;
}
+.composer-thinking-dot[data-hovered]:not([data-filled]):not(.active) {
+ position: relative;
+ z-index: 1;
+ background: var(--ds-accent);
+ opacity: 1;
+ transform: scale(1.3);
+}
+
/* The accessible control overlays the rail at full width; the inset padding
moves the thumb stops onto the column centers. Its track stays transparent
so the rail line and dots show through under the thumb. */
.composer-thinking-range {
+ z-index: 3;
-webkit-appearance: none;
appearance: none;
position: absolute;
@@ -352,9 +373,9 @@
width: 14px;
height: 14px;
margin-top: calc((var(--thinking-track-height) - 14px) / 2);
- border: 2px solid var(--ds-bg-elevated-opaque);
+ border: 0;
border-radius: var(--radius-full);
- background: var(--ds-accent);
+ background: transparent;
}
.composer-thinking-range::-moz-range-track {
@@ -363,32 +384,34 @@
}
.composer-thinking-range::-moz-range-thumb {
+ width: 14px;
+ height: 14px;
+ border: 0;
+ border-radius: var(--radius-full);
+ background: transparent;
+}
+
+/* Decoration never changes the native range's hit target or accessible value.
+ Equal-width, gapless columns share the same center formula as the input. */
+.composer-thinking-thumb {
+ z-index: 2;
+ position: absolute;
+ top: 2px;
+ left: calc(100% / (2 * var(--stop-count, 1)) + var(--composer-thinking-progress, 0%));
width: 14px;
height: 14px;
border: 2px solid var(--ds-bg-elevated-opaque);
border-radius: var(--radius-full);
background: var(--ds-accent);
+ transform: translateX(-50%);
+ pointer-events: none;
+ transition: left var(--motion-duration-normal) var(--motion-ease-out);
}
-/* Settle feedback: the thumb plays a single overshoot pop only when a drag
- commit has just landed (data-settling), never while dragging or on open.
- The fill slides between stops whenever the control is not mid-drag. */
-.composer-thinking-slider[data-settling] .composer-thinking-range::-webkit-slider-thumb {
- animation: composer-thinking-thumb-pop var(--motion-duration-normal)
- cubic-bezier(0.34, 1.56, 0.64, 1);
-}
-.composer-thinking-slider[data-settling] .composer-thinking-range::-moz-range-thumb {
- animation: composer-thinking-thumb-pop var(--motion-duration-normal)
- cubic-bezier(0.34, 1.56, 0.64, 1);
-}
-.composer-thinking-slider:not([data-dragging]) .composer-thinking-rail::after {
- transition: width var(--motion-duration-fast) var(--motion-ease-out);
-}
-@keyframes composer-thinking-thumb-pop {
- 0% { transform: scale(1); }
- 40% { transform: scale(1.25); }
- 100% { transform: scale(1); }
+.composer-thinking-slider[data-dragging] .composer-thinking-thumb,
+.composer-thinking-slider[data-dragging] .composer-thinking-rail::after {
+ transition: none;
}
/* Labels form the same full-width n-column grid as the dots, so label i
@@ -397,7 +420,6 @@
.composer-thinking-ticks {
display: grid;
grid-template-columns: repeat(var(--stop-count, 1), minmax(0, 1fr));
- gap: 2px;
}
.composer-thinking-tick {
@@ -415,7 +437,7 @@
transition: color var(--motion-duration-fast) var(--motion-ease-out);
}
-.composer-thinking-tick:hover,
+.composer-thinking-tick[data-hovered],
.composer-thinking-tick:focus-visible {
color: var(--ds-text-primary);
}
@@ -442,13 +464,10 @@
animation: none;
}
- .composer-thinking-range::-webkit-slider-thumb,
- .composer-thinking-range::-moz-range-thumb {
- animation: none;
- }
-
+ .composer-thinking-thumb,
.composer-thinking-rail::after,
- .composer-thinking-dot {
+ .composer-thinking-dot,
+ .composer-thinking-tick {
transition: none;
}
}
diff --git a/apps/desktop/test/composer-model-thinking-menu.test.mjs b/apps/desktop/test/composer-model-thinking-menu.test.mjs
index 18d78ea62..2c6e00893 100644
--- a/apps/desktop/test/composer-model-thinking-menu.test.mjs
+++ b/apps/desktop/test/composer-model-thinking-menu.test.mjs
@@ -4,11 +4,12 @@ import { readFile } from "node:fs/promises";
import test from "node:test";
import { loadStyles } from "./helpers/styles.mjs";
-const [modelMenuSource, pickerSource] = await Promise.all([
+const [modelMenuSource, pickerSource, sliderSource] = await Promise.all([
readComposerModule("hooks/useComposerModelMenu.ts"),
readComposerModule("ComposerModelPicker.tsx"),
+ readComposerModule("ThinkingLevelSlider.tsx"),
]);
-const composerSource = `${modelMenuSource}\n${pickerSource}`;
+const composerSource = `${modelMenuSource}\n${pickerSource}\n${sliderSource}`;
const stylesSource = await loadStyles();
test("Composer uses one model × reasoning popover with a root and in-place submenus", () => {
@@ -36,20 +37,20 @@ test("the menu root carries the reasoning slider under the reasoning entry", ()
assert.match(composerSource, /onClick=\{\(\) => showView\("thinking"\)\}[\s\S]*?className="composer-thinking-slider"/);
assert.match(composerSource, /\{thinkingMenuLevels\.length > 1 \? \(/);
assert.match(composerSource, /className="composer-thinking-slider"/);
- assert.match(composerSource, /"--stop-count": thinkingMenuLevels\.length/);
+ assert.match(sliderSource, /"--stop-count": levels\.length/);
assert.match(composerSource, /type="range"/);
assert.match(composerSource, /className="composer-thinking-range"/);
- assert.match(composerSource, /aria-label=\{t\("chat.reasoningLevel"\)\}/);
- assert.match(composerSource, /aria-valuetext=\{thinkingMenuLevels\[thinkingSliderValue\] \?\? thinkingLevel\}/);
+ assert.match(sliderSource, /aria-label=\{label\}/);
+ assert.match(sliderSource, /aria-valuetext=\{levels\[index\] \?\? level\}/);
assert.match(composerSource, /const commitThinkingLevel = /);
assert.match(composerSource, /if \(!\(await commitThinkingLevel\(level\)\)\) return;/);
- assert.match(composerSource, /if \(level && level !== thinkingLevel\) void commitThinkingLevel\(level\);/);
- assert.match(composerSource, /if \(THINKING_SLIDER_KEYS\.has\(event\.key\)\) event\.stopPropagation\(\);/);
+ assert.match(pickerSource, /commit=\{commitThinkingLevel\}/);
+ assert.match(composerSource, /if \(SLIDER_KEYS\.has\(event\.key\)\) event\.stopPropagation\(\);/);
assert.match(composerSource, /composer-thinking-tick/);
assert.match(composerSource, /createLatestCommitQueue/);
assert.match(composerSource, /thinkingQueueRef\.current\?\.invalidate\(\)/);
- assert.match(pickerSource, /tabIndex=\{-1\}/);
- assert.match(pickerSource, /className="composer-thinking-ticks" aria-hidden="true"/);
+ assert.match(sliderSource, /tabIndex=\{-1\}/);
+ assert.match(sliderSource, /className="composer-thinking-ticks" aria-hidden="true"/);
assert.doesNotMatch(pickerSource, /composer-thinking-tick[\s\S]{0,200}role="menuitemradio"/);
assert.match(stylesSource, /\.composer-thinking-range::-webkit-slider-runnable-track/);
assert.match(stylesSource, /\.composer-thinking-range::-webkit-slider-thumb/);
@@ -63,9 +64,9 @@ test("the reasoning slider aligns each track dot and label to the thumb", () =>
// keyed to --stop-count; the range input overlays the dots row at full
// width and is inset by half a column minus the thumb radius, which moves
// the native thumb's stops onto the same column centers for every n.
- assert.match(pickerSource, /className="composer-thinking-rail"/);
- assert.match(pickerSource, /className="composer-thinking-dots" aria-hidden="true"/);
- assert.match(pickerSource, /className="composer-thinking-ticks" aria-hidden="true"/);
+ assert.match(sliderSource, /className="composer-thinking-rail"/);
+ assert.match(sliderSource, /className="composer-thinking-dots" aria-hidden="true"/);
+ assert.match(sliderSource, /className="composer-thinking-ticks" aria-hidden="true"/);
// Rail, dots and labels all key off --stop-count; the dots and labels are
// full-width grids and the input carries the inset.
diff --git a/docs/project/README.md b/docs/project/README.md
index ad4eb37fd..3f6214541 100644
--- a/docs/project/README.md
+++ b/docs/project/README.md
@@ -1,5 +1,7 @@
# Project Tracking
+- Pending release highlights: [Unreleased changes](unreleased.md)
+
- Historical project board (archived; last refreshed 2026-08-11 for the 0.5.x line): [`BOARD.md`](BOARD.md)
- Documentation/code alignment audit: [2026-07-30 audit](2026-07-30-docs-code-audit.md)
- Plan implementation plan: [`plan-mode-implementation-plan.md`](plan-mode-implementation-plan.md)
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
new file mode 100644
index 000000000..bc12e7a45
--- /dev/null
+++ b/docs/project/unreleased.md
@@ -0,0 +1,12 @@
+# Unreleased changes
+
+- The Composer reasoning slider now moves smoothly to clicked or
+ keyboard-selected levels, follows dragging immediately, and respects
+ reduced-motion settings. Rapid clicks redirect the animation; failed saves
+ restore the confirmed selection. Opening the menu no longer leaves a
+ press-animation offset that jumps on the first selection.
+- The reasoning slider's filled track covers the entire starting dot, so
+ its left cap no longer leaves a gray half-dot exposed.
+- Hovering a reasoning stop or its label highlights the corresponding label.
+ Only unfilled dots brighten and enlarge; filled dots and the current thumb
+ keep their appearance.
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 26157fedc..ac3e4077b 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -2794,6 +2794,21 @@ reasoning-level control.
token, the rest a muted token; the thumb covers the selected dot. Tick
labels are clickable but not tab stops; the range input is the accessible
control.
+ Hovering either a stop or its label highlights the corresponding label.
+ Only unfilled dots brighten and scale to 1.3x; filled stops and the selected
+ thumb have no hover effect. Leaving
+ the slider clears the preview without selecting or persisting a level.
+ A decorative, non-interactive thumb and the filled rail share the range's
+ gapless column geometry. The fill starts at the first dot's outer left edge
+ and ends at the selected thumb's center, covering the starting dot fully.
+ Clicks and keyboard changes move the thumb and
+ fill over `--motion-duration-normal` (200ms); a new click retargets from
+ the current visual position. Native pointer dragging bypasses transitions.
+ Only the requested levels are persisted, never interpolated animation
+ positions. Pending selection is optimistic; failure restores the confirmed
+ level, and stale completions cannot overwrite a newer choice. Reopening
+ starts directly at the current level. Reduced motion disables travel.
+ This replaces the earlier timer-driven settle pulse.
The Model submenu has a search input and sticky provider headings, while
the Reasoning level submenu starts with `Current model <model> supports
these reasoning levels` and lists `omit` then the selected model binding's
@@ -2808,6 +2823,13 @@ reasoning-level control.
to the root without dismissing the menu; slider and tick commits persist
the last pending level while the menu stays where it is. Closing and
reopening always starts at the root.
+- The model/reasoning trigger shrinks within its toolbar slot. Switching
+ reasoning labels, including `off`, must not move the menu horizontally when
+ the toolbar bounds are unchanged. Long model names truncate within the
+ trigger; the menu continues to follow its anchor on viewport changes.
+ This positioning trigger does not scale on pointer press: its measured
+ bounds stay stable while opening, including before the first selection
+ and after closing and reopening the menu.
- Unknown Custom/OpenAI-compatible models remain at `off` until the user
explicitly enables a level in Settings. The menu never auto-infers reasoning
support; after an explicit binding selection it renders the configured level.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index a490b55f6..7b2ac5d17 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -3109,6 +3109,30 @@ identify the platform validation still needed.
5) Open Reasoning level and choose a level from the radio list. 6) Repeat
with a non-reasoning provider and an unknown free-form model id; exercise
Escape, outside click, Up/Down, Enter, Left, and the slider's arrow keys.
+ In both roomy and crowded toolbars, switch `omit`, `low`, `high`, `max`,
+ and `off` without closing the menu: its horizontal position stays stable,
+ and the trigger stays inside its slot, including with a long model name.
+ Moving the anchor and dispatching a viewport resize must reposition the
+ menu without an event-target type error. Automated geometry coverage:
+ `node scripts/e2e-composer-thinking-layout.mjs` (isolated Electron fixture,
+ production React picker and compiled styles; no live providers).
+ Repeat native mouse press/release to open, select the first and subsequent
+ reasoning levels, close, and reopen three times with motion enabled. The
+ menu must retain its opening position on every selection; synthetic DOM
+ `click()` alone does not exercise the trigger's `:active` transition.
+ Hover each dot and its label: the corresponding label highlights. Unfilled
+ dots brighten and enlarge slightly; filled dots and the selected thumb stay unchanged
+ without shifting the menu. Move outside: the preview clears and the selected
+ value remains unchanged. Reduced motion disables hover transitions.
+ Click a non-adjacent level and verify the thumb travels through intermediate
+ positions while the selected value already equals the target. Interrupt
+ travel with another click; the thumb retargets without jumping to the old
+ start, and only the clicked levels are submitted. Check save failure,
+ stale completion, remount, and 3/5/7/8-stop alignment. At each stop, verify
+ the fill covers the first dot's left edge and still ends at the thumb center.
+ Native range dragging
+ follows immediately; arrow keys retain focus and update the selection.
+ With reduced motion enabled, the target is shown without a transition.
- **Expected**: The chip is in the right toolbar with a Bot icon, before the
standalone prompt-enhancement Sparkles action and Send/Abort; Off omits the
level text. The single anchored menu replaces its root
diff --git a/scripts/e2e-composer-thinking-layout.mjs b/scripts/e2e-composer-thinking-layout.mjs
new file mode 100644
index 000000000..8cc0ea670
--- /dev/null
+++ b/scripts/e2e-composer-thinking-layout.mjs
@@ -0,0 +1,163 @@
+#!/usr/bin/env node
+/** Isolated Electron geometry regression; never connects to the user's app or providers. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const desktop = join(root, "apps/desktop");
+const require = createRequire(join(desktop, "package.json"));
+const runtimeRequire = createRequire(join(root, "packages/agent-runtime/package.json"));
+const { build } = runtimeRequire("esbuild");
+const vite = await import(pathToFileURL(require.resolve("vite")).href);
+const { default: tailwind } = await import(pathToFileURL(require.resolve("@tailwindcss/vite")).href);
+const cache = join(root, ".cache/composer-thinking-layout");
+await mkdir(cache, { recursive: true });
+const temp = await mkdtemp(join(cache, "run-"));
+const styles = await vite.build({
+ configFile: false, root: desktop, logLevel: "error", plugins: [tailwind()],
+ build: { write: false, rollupOptions: { input: join(desktop, "src/styles/globals.css") } },
+});
+const outputs = (Array.isArray(styles) ? styles : [styles]).flatMap((result) => result.output);
+const css = outputs.filter((entry) => entry.type === "asset" && entry.fileName.endsWith(".css"));
+assert(css.length > 0, "Production CSS was not compiled");
+await writeFile(join(temp, "styles.css"), css.map((entry) => entry.source).join("\n"));
+await build({
+ entryPoints: [join(root, "scripts/e2e/composer-thinking-layout.tsx")],
+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "iife",
+ jsx: "automatic", define: { "process.env.NODE_ENV": '"production"' },
+ alias: { react: join(desktop, "node_modules/react"), "react-dom": join(desktop, "node_modules/react-dom") },
+ nodePaths: [join(desktop, "node_modules")],
+});
+await writeFile(join(temp, "index.html"), `<!doctype html><html lang="en" data-theme="dark"><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'none'"><link rel="stylesheet" href="styles.css"><body><script src="renderer.js"></script></body></html>`);
+await writeFile(join(temp, "main.cjs"), `
+const {app,BrowserWindow}=require('electron');
+const path=require('node:path');
+app.setPath('userData',path.join(__dirname,'profile'));
+app.setPath('crashDumps',path.join(__dirname,'crashes'));
+app.disableHardwareAcceleration();
+app.whenReady().then(async()=>{
+ const window=new BrowserWindow({show:false,width:1040,height:760,
+ webPreferences:{offscreen:true,backgroundThrottling:false,sandbox:true,contextIsolation:true,nodeIntegration:false}});
+ try {
+ await window.loadFile(path.join(__dirname,'index.html'));
+ const result=await window.webContents.executeJavaScript('globalThis.composerThinkingLayoutProbe()');
+ result.motion=await window.webContents.executeJavaScript('globalThis.thinkingSliderMotionProbe()');
+ if(!result.motion.ok) result.failures.push('Motion: '+result.motion.error);
+ const probe=expression=>window.webContents.executeJavaScript('globalThis.composerThinkingPointerProbe.'+expression);
+ await probe('mount()');
+ const click=async(level)=>{
+ const point=await probe('target('+JSON.stringify(level)+')');
+ window.webContents.sendInputEvent({type:'mouseMove',...point});
+ window.webContents.sendInputEvent({type:'mouseDown',button:'left',clickCount:1,...point});
+ await probe('settle()');
+ if(level===undefined && !(await probe('pressed()'))) throw new Error('Native click did not activate trigger');
+ window.webContents.sendInputEvent({type:'mouseUp',button:'left',clickCount:1,...point});
+ await probe('settle()');
+ };
+ result.pointerCycles=[];
+ for(let cycle=0;cycle<3;cycle++){
+ await click();
+ const opened=await probe('snapshot()');
+ const selections=[];
+ for(const level of ['low','high','omit']){
+ await click(level);
+ const selected=await probe('snapshot()');
+ selections.push(selected);
+ if(selected.level!==level) result.failures.push('Mouse selection did not persist '+level);
+ if(Math.abs(selected.left-opened.left)>0.05 || Math.abs(selected.top-opened.top)>0.05)
+ result.failures.push('Open cycle '+cycle+'/'+level+': menu moved '+(selected.left-opened.left)+'px horizontally, '+(selected.top-opened.top)+'px vertically');
+ }
+ result.pointerCycles.push({opened,selections});
+ await click();
+ }
+ await click();
+ await click('low');
+ const hoverSnapshot=()=>window.webContents.executeJavaScript(\`(() => {
+ const dots=[...document.querySelectorAll('.composer-thinking-dot')];
+ const ticks=[...document.querySelectorAll('.composer-thinking-tick')];
+ const hovered=dots.findIndex(dot=>dot.hasAttribute('data-hovered'));
+ return {hovered, tick:ticks.findIndex(tick=>tick.hasAttribute('data-hovered')),
+ width:hovered<0?0:dots[hovered].getBoundingClientRect().width,
+ halo:hovered<0?'none':getComputedStyle(dots[hovered]).boxShadow,
+ thumbWidth:document.querySelector('.composer-thinking-thumb').getBoundingClientRect().width,
+ thumbHalo:getComputedStyle(document.querySelector('.composer-thinking-thumb')).boxShadow,
+ value:document.querySelector('.composer-thinking-range').getAttribute('aria-valuetext')};
+ })()\`);
+ result.hover=[];
+ for(const stop of [0,1,2,4]){
+ for(const row of ['dot','tick']){
+ const point=await window.webContents.executeJavaScript(\`(() => {
+ const r=document.querySelectorAll('.composer-thinking-\${row}')[\${stop}].getBoundingClientRect();
+ return {x:Math.round(r.left+r.width/2),y:Math.round(r.top+r.height/2)};
+ })()\`);
+ window.webContents.sendInputEvent({type:'mouseMove',...point});
+ await probe('settle()');
+ const hovered=await hoverSnapshot();
+ result.hover.push({stop,row,...hovered});
+ if(hovered.halo!=='none' || hovered.thumbHalo!=='none')
+ result.failures.push('Hover unexpectedly added a halo');
+ if(hovered.hovered!==stop || hovered.tick!==stop || Math.abs(hovered.width-(stop>2?5.2:4))>0.1 || hovered.value!=='low' || Math.abs(hovered.thumbWidth-14)>0.1)
+ result.failures.push('Hover did not link dot and label without selection: '+JSON.stringify({stop,row,...hovered}));
+ }
+ }
+ window.webContents.sendInputEvent({type:'mouseMove',x:5,y:5});
+ await probe('settle()');
+ if((await hoverSnapshot()).hovered!==-1 || (await hoverSnapshot()).tick!==-1)
+ result.failures.push('Hover remained after leaving slider');
+ await click('omit');
+ await probe('focusRange()');
+ window.webContents.sendInputEvent({type:'keyDown',keyCode:'Right'});
+ window.webContents.sendInputEvent({type:'keyUp',keyCode:'Right'});
+ await probe('settle()');
+ if((await probe('snapshot()')).level!=='off' || !(await probe('motionState()')).focused)
+ result.failures.push('Native keyboard selection or input focus was lost');
+ const dragStart=await probe('railTarget(1)');
+ const dragEnd=await probe('railTarget(3)');
+ window.webContents.sendInputEvent({type:'mouseMove',...dragStart});
+ window.webContents.sendInputEvent({type:'mouseDown',button:'left',clickCount:1,...dragStart});
+ window.webContents.sendInputEvent({type:'mouseMove',button:'left',modifiers:['leftButtonDown'],...dragEnd});
+ await probe('frame()');
+ result.drag=await probe('motionState()');
+ result.drag.selection=await probe('snapshot()');
+ if(!result.drag.dragging || result.drag.animations!==0 || Math.abs(result.drag.gap)>0.6 || (await probe('snapshot()')).level!=='high')
+ result.failures.push('Native drag did not follow the pointer immediately');
+ window.webContents.sendInputEvent({type:'mouseUp',button:'left',clickCount:1,...dragEnd});
+ await probe('settle()');
+ if((await probe('motionState()')).dragging) result.failures.push('Drag state survived pointer release');
+ require('node:fs').writeFileSync(path.join(__dirname,'slider.png'),(await window.webContents.capturePage({x:380,y:155,width:350,height:205})).toPNG());
+ window.webContents.debugger.attach('1.3');
+ await window.webContents.debugger.sendCommand('Emulation.setEmulatedMedia',{features:[{name:'prefers-reduced-motion',value:'reduce'}]});
+ await window.webContents.executeJavaScript("document.querySelectorAll('.composer-thinking-tick')[0].click()");
+ await probe('frame()');
+ result.reduced=await probe('motionState()');
+ if(result.reduced.animations!==0 || Math.abs(result.reduced.gap)>0.6 || (await probe('snapshot()')).level!=='omit') result.failures.push('Reduced motion selection did not update immediately');
+ await window.webContents.debugger.sendCommand('Emulation.setEmulatedMedia',{features:[]});
+ window.webContents.debugger.detach();
+ result.ok=result.failures.length===0;
+ console.log('THINKING_LAYOUT_RESULT '+JSON.stringify(result));
+ app.exit(result.ok?0:1);
+ } catch(error) {console.error(String(error));app.exit(1);}
+});
+`);
+const env = { ...process.env };
+delete env.ELECTRON_RUN_AS_NODE;
+const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
+let output = "";
+for (const stream of [child.stdout, child.stderr]) stream.on("data", (data) => { output += data; });
+const timeout = setTimeout(() => child.kill("SIGKILL"), 40_000);
+let code;
+try {
+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });
+} finally { clearTimeout(timeout); }
+const line = output.split(/\r?\n/).find((entry) => entry.startsWith("THINKING_LAYOUT_RESULT "));
+assert(line, `No geometry result (exit ${code}): ${output.slice(-2000)}`);
+const result = JSON.parse(line.slice("THINKING_LAYOUT_RESULT ".length));
+await writeFile(join(temp, "result.json"), JSON.stringify(result, null, 2));
+console.log(JSON.stringify({ ok: result.ok, checks: result.measurements.length, motion: result.motion, drag: result.drag, reduced: result.reduced, failures: result.failures, artifacts: temp }));
+assert.equal(result.ok, true, result.failures.join("\n"));
+assert.equal(code, 0);
diff --git a/scripts/e2e/composer-thinking-layout.tsx b/scripts/e2e/composer-thinking-layout.tsx
new file mode 100644
index 000000000..79224dc88
--- /dev/null
+++ b/scripts/e2e/composer-thinking-layout.tsx
@@ -0,0 +1,170 @@
+import { useRef, useState } from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import { createInstance } from "i18next";
+import type { SessionThinkingLevel } from "@pi-desktop/shared";
+import { ComposerModelPicker } from "../../apps/desktop/src/features/chat/composer/ComposerModelPicker";
+import type { useComposerModelMenu } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu";
+import "./thinking-slider-motion";
+
+const i18n = createInstance();
+const levels: SessionThinkingLevel[] = ["omit", "off", "low", "high", "max"];
+const noop = () => {};
+const host = document.createElement("div");
+document.body.append(host);
+const root = createRoot(host);
+
+function Fixture({ width, crowded, model }: { width: number; crowded: boolean; model: string }) {
+ const [level, setLevel] = useState<SessionThinkingLevel>("omit");
+ const [open, setOpen] = useState(false);
+ const rootMenuRef = useRef<HTMLDivElement>(null);
+ const listRef = useRef<HTMLDivElement>(null);
+ const searchRef = useRef<HTMLInputElement>(null);
+ const controller: ReturnType<typeof useComposerModelMenu> = {
+ open, setOpen, view: "root", query: "", setQuery: noop,
+ modelHighlight: -1, setModelHighlight: noop,
+ thinkingHighlight: -1, setThinkingHighlight: noop,
+ rootMenuRef, modelSearchRef: searchRef, modelListRef: listRef,
+ thinkingListRef: listRef, modelGroups: [], flatModels: [],
+ thinkingMenuLevels: levels, showView: noop,
+ selectModel: async () => {}, selectThinkingLevel: async () => {},
+ commitThinkingLevel: async (next) => { setLevel(next); return true; },
+ onMenuKeyDown: noop, controlsBlocked: false,
+ };
+ return <div className="composer-stack" style={{ width, position: "absolute", top: 300, transition: "none" }}>
+ <div className="composer-shell"><div className="composer-toolbar">
+ {/* Reserve space like other toolbar controls without mocking the picker layout. */}
+ <div className="composer-left" style={{ width: crowded ? 400 : 80 }} />
+ <div className="composer-right">
+ <ComposerModelPicker t={i18n.t} controller={controller} modelLabel={model}
+ thinkingLabel={level} thinkingLevel={level} controlsBlocked={false}
+ onCloseOtherMenus={noop} />
+ <button className="icon-btn icon-btn-square" aria-label="Enhance" />
+ <button className="send-btn" aria-label="Send" />
+ </div>
+ </div></div>
+ </div>;
+}
+
+function element<T extends HTMLElement = HTMLElement>(selector: string): T {
+ const result = document.querySelector<T>(selector);
+ if (!result) throw new Error(`Missing ${selector}`);
+ return result;
+}
+const settle = () => new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+);
+
+declare global {
+ var composerThinkingLayoutProbe: () => Promise<unknown>;
+ var composerThinkingPointerProbe: {
+ mount: () => Promise<void>;
+ target: (level?: string) => { x: number; y: number };
+ settle: () => Promise<void>;
+ frame: () => Promise<void>;
+ snapshot: () => { left: number; top: number; anchorRight: number; level: string | null };
+ pressed: () => boolean;
+ railTarget: (index: number) => { x: number; y: number };
+ focusRange: () => void;
+ motionState: () => { dragging: boolean; gap: number; animations: number; focused: boolean };
+ };
+}
+
+// Native mouse events in Main exercise :active and its release transition;
+// HTMLElement.click() deliberately skips those states and cannot catch this regression.
+globalThis.composerThinkingPointerProbe = {
+ frame: settle,
+ async mount() {
+ flushSync(() => root.render(<Fixture key="pointer" width={768} crowded={false} model="aaaa" />));
+ await settle();
+ },
+ target(level) {
+ const target = level
+ ? [...document.querySelectorAll<HTMLButtonElement>(".composer-thinking-tick")].find((button) => button.textContent === level)
+ : element(".composer-model-thinking-chip");
+ if (!target) throw new Error(`Missing mouse target ${level}`);
+ const rect = target.getBoundingClientRect();
+ return { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2) };
+ },
+ async settle() {
+ await settle();
+ await Promise.all(document.getAnimations().map((animation) => animation.finished));
+ await settle();
+ },
+ snapshot() {
+ const menu = element(".composer-model-thinking-menu").getBoundingClientRect();
+ return { left: menu.left, top: menu.top,
+ anchorRight: element(".composer-model-thinking-chip").getBoundingClientRect().right,
+ level: element(".composer-thinking-range").getAttribute("aria-valuetext") };
+ },
+ pressed: () => element(".composer-model-thinking-chip").matches(":active"),
+ railTarget(index) {
+ const dot = document.querySelectorAll(".composer-thinking-dot")[index].getBoundingClientRect();
+ const range = element(".composer-thinking-range").getBoundingClientRect();
+ return { x: Math.round(dot.left + dot.width / 2), y: Math.round(range.top + range.height / 2) };
+ },
+ focusRange: () => element(".composer-thinking-range").focus(),
+ motionState() {
+ const thumb = element(".composer-thinking-thumb");
+ const visual = thumb.getBoundingClientRect();
+ const dot = element(".composer-thinking-dot.active").getBoundingClientRect();
+ return { dragging: element(".composer-thinking-slider").hasAttribute("data-dragging"),
+ gap: visual.left + visual.width / 2 - dot.left - dot.width / 2,
+ animations: thumb.getAnimations().length,
+ focused: document.activeElement === element(".composer-thinking-range") };
+ },
+};
+globalThis.composerThinkingLayoutProbe = async () => {
+ await i18n.init({ lng: "en", resources: { en: { translation: {
+ chat: { model: "Model", reasoningLevel: "Reasoning level" },
+ } } }, interpolation: { escapeValue: false } });
+ await document.fonts.ready;
+ const cases = [
+ { width: 768, crowded: false, model: "aaaa" },
+ { width: 570, crowded: true, model: "aaaa" },
+ { width: 590, crowded: true, model: "aaaa" },
+ { width: 650, crowded: true, model: "a-very-long-model-name-".repeat(8) },
+ { width: 450, crowded: false, model: "aaaa" },
+ ];
+ const measurements: unknown[] = [];
+ const failures: string[] = [];
+ for (const [index, config] of cases.entries()) {
+ flushSync(() => root.render(<Fixture key={index} {...config} />));
+ element<HTMLButtonElement>(".composer-model-thinking-chip").click();
+ await settle();
+ const menu = element(".composer-model-thinking-menu");
+ await Promise.all(menu.getAnimations().map((animation) => animation.finished));
+ await settle();
+ const initialLeft = menu.getBoundingClientRect().left;
+ const initialTop = menu.getBoundingClientRect().top;
+ for (const level of ["low", "omit", "high", "max", "off", "low"]) {
+ const tick = [...document.querySelectorAll<HTMLButtonElement>(".composer-thinking-tick")]
+ .find((button) => button.textContent === level);
+ if (!tick) throw new Error(`Missing stop ${level}`);
+ tick.click();
+ await settle();
+ const trigger = element(".composer-model-thinking-chip").getBoundingClientRect();
+ const wrapper = element(".composer-model-thinking").getBoundingClientRect();
+ const currentMenu = menu.getBoundingClientRect();
+ const range = element<HTMLInputElement>(".composer-thinking-range");
+ if (range.getAttribute("aria-valuetext") !== level) failures.push(`${index}: selection ${level} did not settle`);
+ if (!menu.classList.contains("is-open")) failures.push(`${index}: selection closed the menu`);
+ if (Math.abs(currentMenu.left - initialLeft) > 0.05) failures.push(`${index}/${level}: menu moved ${currentMenu.left - initialLeft}px`);
+ if (Math.abs(currentMenu.top - initialTop) > 0.05) failures.push(`${index}/${level}: menu moved vertically`);
+ if (Math.abs(trigger.height - 28) > 0.05) failures.push(`${index}/${level}: trigger changed height`);
+ if (trigger.right > wrapper.right + 0.05) failures.push(`${index}/${level}: trigger overflows its wrapper`);
+ measurements.push({ ...config, level, triggerRight: trigger.right, wrapperRight: wrapper.right, menuLeft: currentMenu.left });
+ }
+ // A stable menu must still follow a real anchor move, rather than freeze coordinates.
+ const beforeMove = menu.getBoundingClientRect().left;
+ const beforeAnchor = element(".composer-model-thinking-chip").getBoundingClientRect().right;
+ const stack = element(".composer-stack");
+ stack.style.left = `${stack.getBoundingClientRect().left + 40}px`;
+ window.dispatchEvent(new Event("resize"));
+ await settle();
+ const anchorMove = element(".composer-model-thinking-chip").getBoundingClientRect().right - beforeAnchor;
+ const menuMove = menu.getBoundingClientRect().left - beforeMove;
+ if (Math.abs(anchorMove - 40) > 0.05 || Math.abs(menuMove - anchorMove) > 0.05) failures.push(`${index}: menu moved ${menuMove}px for anchor move ${anchorMove}px`);
+ }
+ return { ok: failures.length === 0, failures, measurements };
+};
diff --git a/scripts/e2e/thinking-slider-motion.tsx b/scripts/e2e/thinking-slider-motion.tsx
new file mode 100644
index 000000000..b9d6c8344
--- /dev/null
+++ b/scripts/e2e/thinking-slider-motion.tsx
@@ -0,0 +1,134 @@
+import { useState } from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import type { SessionThinkingLevel } from "@pi-desktop/shared";
+import { ThinkingLevelSlider } from "../../apps/desktop/src/features/chat/composer/ThinkingLevelSlider";
+
+const levels: SessionThinkingLevel[] = ["omit", "off", "low", "high", "max"];
+type Pending = { level: SessionThinkingLevel; finish: (accepted: boolean) => void };
+
+declare global { var thinkingSliderMotionProbe: () => Promise<unknown>; }
+globalThis.thinkingSliderMotionProbe = async () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ let deferred = false;
+ const pending: Pending[] = [];
+ const requested: SessionThinkingLevel[] = [];
+ const checks: string[] = [];
+ function Fixture({ ladder = levels }: { ladder?: SessionThinkingLevel[] }) {
+ const [level, setLevel] = useState<SessionThinkingLevel>("omit");
+ return <div style={{ width: 286 }}><ThinkingLevelSlider levels={ladder} level={level}
+ label="Reasoning level" commit={async (next) => {
+ requested.push(next);
+ if (deferred) return new Promise<boolean>((resolve) => pending.push({ level: next, finish: (accepted) => {
+ if (accepted) setLevel(next);
+ resolve(accepted);
+ } }));
+ setLevel(next);
+ return true;
+ }} /></div>;
+ }
+ const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ const node = (selector: string) => {
+ const result = host.querySelector<HTMLElement>(selector);
+ if (!result) throw new Error(`Missing ${selector}`);
+ return result;
+ };
+ const center = (element: HTMLElement) => { const r = element.getBoundingClientRect(); return r.left + r.width / 2; };
+ const thumb = () => node(".composer-thinking-thumb");
+ const value = () => node("input").getAttribute("aria-valuetext");
+ const click = (level: string) => {
+ const button = [...host.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent === level);
+ if (!button) throw new Error(`Missing stop ${level}`);
+ flushSync(() => button.click());
+ };
+ const assert = (condition: boolean, message: string) => { if (!condition) throw new Error(message); checks.push(message); };
+ const finish = async () => {
+ for (const animation of host.getAnimations({ subtree: true })) animation.finish();
+ await frame();
+ };
+ const mount = async (key: string, ladder = levels) => {
+ flushSync(() => root.render(<Fixture key={key} ladder={ladder} />));
+ await frame();
+ // Establish the initial rendered position before requesting a transition.
+ center(thumb());
+ };
+ try {
+ await mount("motion");
+ const initial = center(thumb());
+ const end = center(node(".composer-thinking-dot:last-child"));
+ click("max");
+ await frame();
+ const animation = thumb().getAnimations()[0];
+ assert(Boolean(animation), "click creates a thumb transition");
+ animation.pause();
+ animation.currentTime = Number(animation.effect?.getTiming().duration) / 2;
+ const midway = center(thumb());
+ assert(midway > initial + 1 && midway < end - 1, "thumb passes through intermediate positions");
+ assert(value() === "max", "selected value updates before animation completes");
+ click("low");
+ const redirected = center(thumb());
+ assert(Math.abs(redirected - midway) < 1, "rapid click starts from the current visual position");
+ await finish();
+ assert(Math.abs(center(thumb()) - center(node(".composer-thinking-dot.active"))) < 0.6, "redirected thumb lands on the selected dot");
+ assert(requested.join(",") === "max,low", "animation never commits intermediate levels");
+
+ deferred = true;
+ click("high");
+ await finish();
+ assert(value() === "high", "pending save keeps optimistic selection");
+ flushSync(() => pending.shift()?.finish(false));
+ await frame();
+ await finish();
+ assert(value() === "low", "failed save restores the confirmed level");
+ click("high");
+ click("max");
+ flushSync(() => pending.shift()?.finish(false));
+ await frame();
+ assert(value() === "max", "stale failure does not overwrite a newer selection");
+ flushSync(() => pending.shift()?.finish(true));
+ await frame();
+ await finish();
+ assert(value() === "max", "latest successful save settles at its target");
+
+ click("high");
+ click("max");
+ flushSync(() => pending.shift()?.finish(true));
+ await frame();
+ assert(value() === "max", "returning to the confirmed level survives an older successful save");
+ flushSync(() => pending.shift()?.finish(true));
+ await frame();
+ await finish();
+ assert(value() === "max", "return-to-current request settles after the earlier write");
+
+ click("low");
+ await mount("reopened");
+ assert(value() === "omit" && thumb().getAnimations().length === 0, "remount opens at the confirmed position without travel");
+ flushSync(() => pending.shift()?.finish(false));
+ await frame();
+ assert(value() === "omit", "completion after unmount cannot change the new slider");
+ deferred = false;
+ for (const ladder of [levels.slice(0, 3), levels, ["omit", "off", "minimal", "low", "medium", "high", "max"] as SessionThinkingLevel[], ["omit", "off", "minimal", "low", "medium", "high", "xhigh", "max"] as SessionThinkingLevel[]]) {
+ await mount(`ladder-${ladder.length}`, ladder);
+ for (const level of ladder) {
+ click(level);
+ await finish();
+ const tick = [...host.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent === level)!;
+ assert(Math.abs(center(thumb()) - center(tick)) < 0.6, `${ladder.length} stops: ${level} thumb and label align`);
+ const rail = node(".composer-thinking-rail");
+ const fill = getComputedStyle(rail, "::after");
+ const fillLeft = rail.getBoundingClientRect().left + Number.parseFloat(fill.left);
+ const firstDot = node(".composer-thinking-dot").getBoundingClientRect();
+ assert(Math.abs(fillLeft - firstDot.left) < 0.05, `${ladder.length} stops: ${level} fill covers the first dot's left edge`);
+ assert(Math.abs(fillLeft + Number.parseFloat(fill.width) - center(thumb())) < 0.05, `${ladder.length} stops: ${level} fill still ends at the thumb center`);
+ }
+ }
+ return { ok: true, checks };
+ } catch (error) {
+ return { ok: false, checks, error: String(error) };
+ } finally {
+ root.unmount();
+ host.remove();
+ }
+};