Skip to content

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

fix(chat): keep the outline turn jump out of follow mode

mingkun968f4aef14d1525
diff --git a/apps/desktop/src/components/ConversationMinimap.tsx b/apps/desktop/src/components/ConversationMinimap.tsx
index bdb7d9089..94eb03aac 100644
--- a/apps/desktop/src/components/ConversationMinimap.tsx
+++ b/apps/desktop/src/components/ConversationMinimap.tsx
@@ -39,12 +39,19 @@ export const ConversationMinimap = memo(function ConversationMinimap({
hasEarlier = false,
loadingEarlier = false,
onRevealEarlier,
+ onReleaseFollow,
}: {
scrollRef: RefObject<HTMLDivElement | null>;
messages: UiMessage[];
hasEarlier?: boolean;
loadingEarlier?: boolean;
onRevealEarlier?: () => void;
+ /**
+ * Leaves the transcript's follow mode before a dash scrolls to its turn.
+ * While follow is still pinned, the jump's scroll carries no input gesture,
+ * so the scroller reads it as a layout clamp and re-bottoms the view.
+ */
+ onReleaseFollow?: () => void;
}) {
const { t } = useTranslation();
const [activeId, setActiveId] = useState<string | null>(null);
@@ -266,6 +273,10 @@ export const ConversationMinimap = memo(function ConversationMinimap({
if (!el) return;
const target = getOffsets().find((entry) => entry.id === id);
if (!target) return;
+ // Leaving follow mode is part of the jump, not a side effect: a scroll
+ // with no input gesture behind it is read as a layout clamp, and follow
+ // would re-bottom the transcript before the reader saw the turn.
+ onReleaseFollow?.();
const reduceMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches;
@@ -274,7 +285,7 @@ export const ConversationMinimap = memo(function ConversationMinimap({
behavior: reduceMotion ? "auto" : "smooth",
});
},
- [scrollRef, getOffsets],
+ [scrollRef, getOffsets, onReleaseFollow],
);
/* Dock magnification, applied imperatively so mousemove never re-renders.
diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
index a8398de83..faa7a889e 100644
--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
@@ -133,6 +133,7 @@ function TranscriptBody({
veilPhase,
handleScroll,
revealEarlierHistory,
+ releaseFollow,
jumpToLatest,
disclosureAnchorNotifier,
} = useTranscriptScroll({
@@ -241,6 +242,7 @@ function TranscriptBody({
hasEarlier={hasEarlierHistory}
loadingEarlier={loadingOlder}
onRevealEarlier={revealEarlierHistory}
+ onReleaseFollow={releaseFollow}
/>
) : null}
<div
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
index 4744995f6..0d26f4f0d 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
@@ -117,16 +117,26 @@ export function useTranscriptScroll({
followFrameRef.current = 0;
}, []);
+ /*
+ Leave follow mode. Every reader-driven move inside the transcript starts
+ here: while the scroller is still pinned, a scroll that carries no input
+ gesture is indistinguishable from a layout clamp, so the follow re-bottoms
+ the view one frame later and undoes the move.
+ */
+ const releaseFollow = useCallback(() => {
+ cancelFollowScroll();
+ pinnedRef.current = false;
+ setShowJump(true);
+ }, [cancelFollowScroll]);
+
// A manual disclosure (a tool, thinking or activity title; #324) hands this
// scroller the very title it was toggled from, before the expansion state
// changes. Follow mode is left first — re-bottoming the expansion is exactly
// what dragged the clicked title out of view — and the held position is
// restored from the observer below for every frame of the height transition.
const enterDisclosureReading = useCallback(() => {
- cancelFollowScroll();
- pinnedRef.current = false;
- setShowJump(true);
- }, [cancelFollowScroll]);
+ releaseFollow();
+ }, [releaseFollow]);
const recordScrollPosition = useCallback((top: number) => {
lastScrollTopRef.current = top;
lastLaidOutScrollTopRef.current = top;
@@ -630,9 +640,7 @@ export function useTranscriptScroll({
return;
}
releaseDisclosureAnchor();
- cancelFollowScroll();
- pinnedRef.current = false;
- setShowJump(true);
+ releaseFollow();
const reduceMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches;
@@ -640,7 +648,7 @@ export function useTranscriptScroll({
top: 0,
behavior: reduceMotion ? "auto" : "smooth",
});
- }, [cancelFollowScroll, reachTop, releaseDisclosureAnchor]);
+ }, [reachTop, releaseDisclosureAnchor, releaseFollow]);
const jumpToLatest = useCallback(() => {
releaseDisclosureAnchor();
@@ -740,6 +748,7 @@ export function useTranscriptScroll({
revealEarlierHistory,
scrollToBottom,
jumpToLatest,
+ releaseFollow,
disclosureAnchorNotifier,
};
}
diff --git a/apps/desktop/test/transcript-disclosure-reading.test.mjs b/apps/desktop/test/transcript-disclosure-reading.test.mjs
index a969a1958..3e0fe6886 100644
--- a/apps/desktop/test/transcript-disclosure-reading.test.mjs
+++ b/apps/desktop/test/transcript-disclosure-reading.test.mjs
@@ -86,9 +86,16 @@ test("the transcript restores the held title inside its resize observer", () =>
});
test("holding a disclosure leaves follow without a delayed grab-back", () => {
+ // Leaving follow mode has one definition, shared by the disclosure hold and
+ // every reader-driven jump: no timer and no animation frame, so the hold ends
+ // on real input or an explicit re-pin, never by taking the bottom back later.
assert.match(
transcript,
- /const enterDisclosureReading = useCallback\(\(\) => \{\s*cancelFollowScroll\(\);\s*pinnedRef\.current = false;\s*setShowJump\(true\);/,
+ /const releaseFollow = useCallback\(\(\) => \{\s*cancelFollowScroll\(\);\s*pinnedRef\.current = false;\s*setShowJump\(true\);/,
+ );
+ assert.match(
+ transcript,
+ /const enterDisclosureReading = useCallback\(\(\) => \{\s*releaseFollow\(\);/,
);
assert.match(
transcript,
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index a0a2a705b..32ffbc7e9 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -262,6 +262,23 @@
session IPC contract tests, and real-model desktop acceptance. A local model
fixture or mocked component result is not real-model acceptance evidence.
+### E2E-CONVERSATION-minimap-jump-leaves-follow
+
+- **Preconditions:** One Desktop conversation long enough that the transcript
+ overflows its viewport, opened at the bottom so follow mode is pinned, with
+ the conversation outline (minimap) visible on the transcript's left edge.
+- **Steps:** Click the outline dash of an earlier turn without scrolling the
+ transcript first.
+- **Expected:** The transcript scrolls to that turn and stays there: the turn
+ lands just below the scroller's top edge and the jump-to-latest control
+ appears, because the jump leaves follow mode before it scrolls. A pinned
+ follow must never re-bottom the view one frame after the click. The outline's
+ earlier-history control keeps its existing reveal behavior.
+- **Status:** Automated in `pnpm test:e2e:transcript-minimap-jump`, which mounts
+ the production `ChatTranscript` in a real Chromium page with a synthetic
+ session, clicks an outline dash while follow is pinned, and asserts the
+ scroller's distance from the bottom once the exchange has settled.
+
### E2E-POWER-keep-awake-setting
- **Preconditions:** An isolated desktop profile with the setting absent; no
diff --git a/package.json b/package.json
index a853e0498..719f508fb 100644
--- a/package.json
+++ b/package.json
@@ -34,6 +34,7 @@
"test:e2e:composer-model-selection": "node scripts/e2e-composer-model-selection.mjs",
"test:e2e:composer-paste": "node scripts/e2e-composer-paste.mjs",
"test:e2e:transcript": "node scripts/e2e-transcript-render.mjs",
+ "test:e2e:transcript-minimap-jump": "node scripts/e2e-transcript-minimap-jump.mjs",
"test:e2e:copy-tex": "node scripts/e2e-copy-tex.mjs",
"test:e2e:transcript-disclosure": "node scripts/e2e-transcript-disclosure-anchor.mjs",
"test:e2e:images": "node scripts/e2e-image-generation.mjs && node scripts/e2e-image-generation-ui.mjs && node scripts/e2e-image-chat.mjs",
diff --git a/scripts/e2e-transcript-minimap-jump.mjs b/scripts/e2e-transcript-minimap-jump.mjs
new file mode 100644
index 000000000..824256327
--- /dev/null
+++ b/scripts/e2e-transcript-minimap-jump.mjs
@@ -0,0 +1,136 @@
+#!/usr/bin/env node
+/**
+ * Real React/Chromium regression for E2E-CONVERSATION-minimap-jump-leaves-follow:
+ * a dash click in the conversation outline keeps its target while follow mode
+ * is still pinned.
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const require = createRequire(
+ join(root, "packages/agent-runtime/package.json"),
+);
+const { build } = require("esbuild");
+const { electronBinary } = resolveElectronBinary(root);
+const temp = await mkdtemp(join(tmpdir(), "pi-minimap-jump-"));
+try {
+ await build({
+ entryPoints: [join(root, "scripts/e2e/transcript-minimap-jump.tsx")],
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "iife",
+ jsx: "automatic",
+ define: {
+ "process.env.NODE_ENV": '"production"',
+ "import.meta.env.DEV": "false",
+ },
+ // Styles come from the app's built stylesheet below; the component and its
+ // hook are the real modules under test.
+ loader: { ".css": "empty" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ // The fixture lives outside the desktop package; use its React instance.
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ plugins: [
+ {
+ name: "local-url-assets",
+ setup(build) {
+ build.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({
+ path: join(resolveDir, path.slice(0, -4)),
+ namespace: "local-url-asset",
+ }));
+ build.onLoad(
+ { filter: /.*/, namespace: "local-url-asset" },
+ async ({ path }) => ({
+ contents: await readFile(path),
+ loader: "file",
+ }),
+ );
+ },
+ },
+ ],
+ });
+ // The outline's rail and dashes are styled in the app's own stylesheet, so
+ // the page has to carry the built one rather than a bare document.
+ const renderer = join(root, "apps/desktop/out/renderer");
+ const appHtml = await readFile(join(renderer, "index.html"), "utf8");
+ const css = [...appHtml.matchAll(/href="([^" ]+\.css)"/g)].map(
+ (match) => match[1],
+ );
+ assert(css.length, "Build the app with pnpm build:js before running this check");
+ await cp(join(renderer, "assets"), join(temp, "assets"), { recursive: true });
+ await writeFile(
+ join(temp, "index.html"),
+ `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:"><title>Minimap jump regression</title>${css
+ .map((path) => `<link rel="stylesheet" href="${path}">`)
+ .join("")}<script src="renderer.js"></script>`,
+ );
+ await writeFile(
+ join(temp, "main.cjs"),
+ `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const window = new BrowserWindow({ show: false, width: 1200, height: 720, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ window.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await window.loadFile(path.join(__dirname, "index.html"));
+ await window.webContents.executeJavaScript("window.addEventListener('error', event => console.error(event.error?.stack ?? event.message)); window.addEventListener('unhandledrejection', event => console.error(event.reason?.stack ?? String(event.reason)));");
+ const result = await window.webContents.executeJavaScript("globalThis.transcriptMinimapJumpProbe()");
+ console.log("MINIMAP_JUMP_PROBE " + JSON.stringify(result));
+ app.quit();
+ } catch (error) {
+ console.error("MINIMAP_JUMP_PROBE " + JSON.stringify({ ok: false, error: error?.stack ?? String(error) }));
+ app.exit(1);
+ }
+});
+`,
+ );
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(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"), 45_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((line) => line.startsWith("MINIMAP_JUMP_PROBE "));
+ assert(
+ line,
+ `renderer returned no probe result (exit=${code}): ${output.slice(-2000)}`,
+ );
+ const result = JSON.parse(line.slice("MINIMAP_JUMP_PROBE ".length));
+ console.log("MINIMAP_JUMP_PROBE " + JSON.stringify(result));
+ assert.equal(code, 0, output.slice(-6000));
+ assert.equal(result.ok, true, result.error ?? "minimap jump probe failed");
+ console.log("minimap jump: ok");
+} finally {
+ await rm(temp, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/transcript-minimap-jump.tsx b/scripts/e2e/transcript-minimap-jump.tsx
new file mode 100644
index 000000000..822e3cf41
--- /dev/null
+++ b/scripts/e2e/transcript-minimap-jump.tsx
@@ -0,0 +1,243 @@
+/**
+ * Real React/Chromium regression for the conversation outline's turn jump.
+ *
+ * Clicking a dash scrolls the transcript to that turn. While the transcript is
+ * still in follow mode, the jump's own upward scroll event carries no input
+ * gesture, so the scroller reads it as a layout clamp, re-pins and re-bottoms
+ * one frame later — the click looks ignored. The jump therefore has to leave
+ * follow mode before it scrolls, exactly like the outline's earlier-history
+ * control already does.
+ *
+ * Scenario: E2E-CONVERSATION-minimap-jump-leaves-follow.
+ */
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { en } from "@pi-desktop/i18n";
+import type { SessionSummary, UiMessage } from "@pi-desktop/shared";
+import { ChatTranscript } from "../../apps/desktop/src/features/chat/transcript/ChatTranscript";
+import { api } from "../../apps/desktop/src/lib/api";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+const createdAt = "2026-09-01T00:00:00.000Z";
+const SESSION_ID = "minimap-jump";
+const TURNS = 12;
+
+declare global {
+ var transcriptMinimapJumpProbe: () => Promise<unknown>;
+}
+
+function assert(value: unknown, label: string): asserts value {
+ if (!value) throw new Error(`Minimap jump: ${label}`);
+}
+
+const frame = () =>
+ new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+async function until(
+ predicate: () => boolean,
+ label: string,
+ diagnostic?: () => unknown,
+): Promise<void> {
+ for (let attempt = 0; attempt < 240; attempt++) {
+ if (predicate()) return;
+ await frame();
+ }
+ throw new Error(
+ `Minimap jump never settled: ${label} ${JSON.stringify(diagnostic?.() ?? {})}`,
+ );
+}
+
+function row(id: string, role: UiMessage["role"], content: string): UiMessage {
+ return { id, role, content, createdAt, status: "complete" };
+}
+
+/** Alternating turns, long enough that the transcript overflows one viewport. */
+function transcriptMessages(): UiMessage[] {
+ const messages: UiMessage[] = [];
+ for (let turn = 0; turn < TURNS; turn++) {
+ messages.push(
+ row(`u${turn}`, "user", `Question ${turn}. ${"Synthetic question body. ".repeat(6)}`),
+ );
+ messages.push(
+ row(`a${turn}`, "assistant", `Answer ${turn}. ${"Synthetic answer body. ".repeat(24)}`),
+ );
+ }
+ return messages;
+}
+
+function sessionSummary(): SessionSummary {
+ return {
+ id: SESSION_ID,
+ title: "Minimap jump",
+ mode: "agent",
+ permissionMode: "ask",
+ thinkingLevel: "off",
+ providerId: "fixture",
+ modelId: "fixture",
+ createdAt,
+ updatedAt: createdAt,
+ messageCount: TURNS * 2,
+ };
+}
+
+/** Credential-free production React/store integration for the outline's jump. */
+export async function transcriptMinimapJumpProbe() {
+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });
+ const initial = useAppStore.getState();
+ const originals = {
+ getSession: api.getSession,
+ listSessions: api.listSessions,
+ pendingPlans: api.pendingPlans,
+ listQueuedPrompts: api.listQueuedPrompts,
+ composerCommands: api.composerCommands,
+ summarizeSessionTitle: api.summarizeSessionTitle,
+ };
+ const messages = transcriptMessages();
+ const errors: unknown[] = [];
+ const host = document.createElement("div");
+ host.style.cssText = "position:fixed;inset:0;display:flex;flex-direction:column";
+ document.body.append(host);
+ const root = createRoot(host, {
+ onUncaughtError: (error) => errors.push(error),
+ });
+ const element = <T extends HTMLElement = HTMLElement>(selector: string): T => {
+ const found = host.querySelector<T>(selector);
+ assert(found, `missing ${selector}; render errors: ${errors.map(String)}`);
+ return found;
+ };
+ try {
+ // Only Host reads are fixtures; no running Desktop, native host or provider.
+ api.getSession = async (id) => {
+ assert(id === SESSION_ID, `unexpected session read ${id}`);
+ return {
+ session: {
+ ...sessionSummary(),
+ messages,
+ messageStart: 0,
+ hasMoreBefore: false,
+ },
+ };
+ };
+ api.listSessions = async () => ({ sessions: [sessionSummary()] });
+ api.pendingPlans = async () => ({ plans: [], state: "inactive" });
+ api.listQueuedPrompts = async () => ({ entries: [] });
+ api.composerCommands = async () => ({ commands: [] });
+ api.summarizeSessionTitle = async () => {
+ throw new Error("unexpected auto-title provider request in fixture");
+ };
+ useAppStore.setState({
+ sessions: [sessionSummary()],
+ providers: [],
+ providerModels: {},
+ retainedTranscripts: {},
+ retainedSessionIds: [],
+ sessionHistory: {},
+ sessionCompactions: {},
+ pendingPlans: {},
+ pendingAsks: {},
+ pendingPermissions: {},
+ planningStates: {},
+ agentStatuses: {},
+ latestTurnResults: {},
+ queuedPrompts: {},
+ notifications: [],
+ workspace: undefined,
+ runningSessions: {},
+ isRunning: false,
+ page: "chat",
+ selectingSessionId: undefined,
+ settings: {
+ ...initial.settings,
+ theme: "dark",
+ enterToSend: true,
+ onboardingDismissed: true,
+ smoothStreaming: false,
+ },
+ activeSessionId: SESSION_ID,
+ messages,
+ });
+ flushSync(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <div style={{ position: "relative", display: "flex", flex: 1, minHeight: 0 }}>
+ <ChatTranscript
+ sessionId={SESSION_ID}
+ messages={messages}
+ isRunning={false}
+ />
+ </div>
+ </I18nextProvider>,
+ ),
+ );
+ await frame();
+ await until(
+ () => !host.querySelector('[data-transcript-settling="true"]'),
+ "transcript settles",
+ );
+ await until(
+ () => host.querySelector(".minimap-rail") !== null,
+ "outline mounts",
+ );
+ const scroller = element(".thread-scroll");
+ const distanceFromBottom = () =>
+ scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop;
+ // The transcript mounts pinned to the bottom: that is the state the reported
+ // click happens in.
+ await until(() => Math.abs(distanceFromBottom()) < 2, "follow is pinned");
+ const rail = element(".minimap-rail");
+ const dashes = [
+ ...rail.querySelectorAll<HTMLButtonElement>(".minimap-marker.user"),
+ ];
+ assert(dashes.length >= 2, `outline needs user dashes, saw ${dashes.length}`);
+ const firstTurn = element<HTMLElement>(".message-row.user[data-minimap-id]");
+ const turnTop = () =>
+ firstTurn.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
+ assert(
+ turnTop() < -100,
+ `the first turn has to start above the viewport, saw ${turnTop()}`,
+ );
+ const readout = () => ({
+ distanceFromBottom: distanceFromBottom(),
+ turnTop: turnTop(),
+ scrollTop: scroller.scrollTop,
+ });
+ flushSync(() => dashes[0]!.click());
+ await until(
+ () => distanceFromBottom() > 100,
+ "the jump scrolled away from the bottom",
+ readout,
+ );
+ // The jump lands first; follow mode answers it on the following frames.
+ // Settle that exchange before asserting, or a re-bottom passes as success.
+ for (let index = 0; index < 30; index++) await frame();
+ assert(
+ distanceFromBottom() > 100,
+ `the jump was undone by follow: ${JSON.stringify(readout())}`,
+ );
+ assert(
+ turnTop() > -8 && turnTop() < 96,
+ `the clicked turn is not on screen: ${JSON.stringify(readout())}`,
+ );
+ assert(errors.length === 0, `render errors: ${errors.map(String)}`);
+ return { ok: true, dashes: dashes.length, ...readout() };
+ } catch (error) {
+ return {
+ ok: false,
+ error: error instanceof Error ? (error.stack ?? error.message) : String(error),
+ };
+ } finally {
+ flushSync(() => root.unmount());
+ host.remove();
+ Object.assign(api, originals);
+ useAppStore.setState({
+ sessions: initial.sessions,
+ activeSessionId: initial.activeSessionId,
+ messages: initial.messages,
+ settings: initial.settings,
+ });
+ }
+}
+
+globalThis.transcriptMinimapJumpProbe = transcriptMinimapJumpProbe;