agent-console 1.3.6: keep chat pinned to the bottom on tall virtualized replies (#787)

agent-console 1.3.6: the chat stays stuck to the bottom as virtualized rows measure taller than their estimate, while a reply streams, and when a hidden view becomes visible. Only an upward scroll during a user gesture leaves the bottom, and jump follows rows as they measure. An ACP default model the session skipped is no longer recorded as synced, so the next idle send tries it again.

Reviewed at baf6475e on mote (HOME=$(mktemp -d), Node 22, npm ci --workspaces=false): tsc daemon+web ok; verify:build byte for byte; vitest 73 files, 544 passed, 17 skipped, with chat-scroll-browser run in Chromium 1248 rather than skipped; bun scripts/check.mjs agent-console ok. With origin/main's Chat.tsx and manager.ts put back and app/ rebuilt, the browser test fails (gap 760 > 2) and both new manager tests fail. 1.3.6 is the next version after dist's 1.3.5. Not tried: the real magpie webviews. PR CI green.
This commit is contained in:
qingnian108
2026-11-06 18:53:53 +08:00
committed by GitHub
parent 484b870266
commit 654d3bea1c
16 changed files with 590 additions and 100 deletions
File diff suppressed because one or more lines are too long
+36 -7
View File
@@ -811,6 +811,29 @@ async function scriptLong(ctx) {
} }
emit({ type: "assistant_message", itemId: "L1", text: "\uFF085000 \u4E2A\u589E\u91CF\u5408\u5E76\u540E\u7684\u957F\u6587\uFF09" }); emit({ type: "assistant_message", itemId: "L1", text: "\uFF085000 \u4E2A\u589E\u91CF\u5408\u5E76\u540E\u7684\u957F\u6587\uFF09" });
} }
async function scriptBigReply(ctx) {
const { emit } = ctx;
const slow = ctx.input.text.includes("slow");
const parts = [];
for (let i = 1; i <= 14; i++) {
parts.push(`### \u7B2C ${i} \u90E8\u5206
- \u8981\u70B9 ${i}.a\uFF1A\u8BF4\u660E\u4E00\u4E0B\u8FD9\u91CC\u7684\u6539\u52A8
- \u8981\u70B9 ${i}.b\uFF1A\u4EE5\u53CA\u4E3A\u4EC0\u4E48\u8FD9\u6837\u6539
`);
parts.push("```ts\n" + Array.from({ length: 8 }, (_, k) => `const v${i}_${k} = compute(${i}, ${k}); // line ${k}`).join("\n") + "\n```\n\n");
}
let acc = "";
emit({ type: "assistant_delta", itemId: "B1", text: "" });
for (const p of parts) {
if (ctx.interrupted()) return;
acc += p;
emit({ type: "assistant_delta", itemId: "B1", text: p });
await sleep(slow ? 220 : 5);
}
emit({ type: "assistant_message", itemId: "B1", text: acc });
}
async function scriptExit(_ctx) { async function scriptExit(_ctx) {
await sleep(300); await sleep(300);
throw new MockCrash(); throw new MockCrash();
@@ -825,6 +848,7 @@ function pickScript(text) {
if (t.startsWith("/error")) return scriptError; if (t.startsWith("/error")) return scriptError;
if (t.startsWith("/long")) return scriptLong; if (t.startsWith("/long")) return scriptLong;
if (t.startsWith("/exit")) return scriptExit; if (t.startsWith("/exit")) return scriptExit;
if (t.startsWith("/bigreply")) return scriptBigReply;
if (t.startsWith("/serve")) return scriptServe; if (t.startsWith("/serve")) return scriptServe;
if (t.startsWith("/tools")) return scriptTools; if (t.startsWith("/tools")) return scriptTools;
if (t.startsWith("/bashhint")) return scriptBashHint; if (t.startsWith("/bashhint")) return scriptBashHint;
@@ -5070,8 +5094,10 @@ var init_session3 = __esm({
* Switch model → refresh level options from the new config options it returns → then apply the level (as Paseo does). * Switch model → refresh level options from the new config options it returns → then apply the level (as Paseo does).
* Cursor connects with parameterizedModelPicker: only the base model name is sent (grok-4.6); level / Fast are separate config options. * Cursor connects with parameterizedModelPicker: only the base model name is sent (grok-4.6); level / Fast are separate config options.
*/ */
/** false = the model id was skipped (not in the session's model options and not forced) */
async applySessionModel(model, force = false) { async applySessionModel(model, force = false) {
if (!this.ctx || !this.active) return; if (!this.ctx || !this.active) return false;
let applied = true;
const value = model && this.o.flavor === "cursor" ? model.replace(/\[.*\]$/u, "") : model; const value = model && this.o.flavor === "cursor" ? model.replace(/\[.*\]$/u, "") : model;
if (value) { if (value) {
const modelOption = this.currentConfig().find((o) => o.id === (this.modelConfigId ?? "model")); const modelOption = this.currentConfig().find((o) => o.id === (this.modelConfigId ?? "model"));
@@ -5080,12 +5106,14 @@ var init_session3 = __esm({
await this.setOption(this.modelConfigId ?? "model", value); await this.setOption(this.modelConfigId ?? "model", value);
} else { } else {
log("info", `\u5FFD\u7565 ${this.o.binName} \u7684\u65E0\u6548\u6A21\u578B\uFF1A${value}`); log("info", `\u5FFD\u7565 ${this.o.binName} \u7684\u65E0\u6548\u6A21\u578B\uFF1A${value}`);
applied = false;
} }
} }
if (this.o.flavor === "cursor" && this.cursorFast && this.currentConfig().some((o) => o.id === "fast")) { if (this.o.flavor === "cursor" && this.cursorFast && this.currentConfig().some((o) => o.id === "fast")) {
await this.setOption("fast", "true"); await this.setOption("fast", "true");
} }
await this.applySessionThought(this.o.effort); await this.applySessionThought(this.o.effort);
return applied;
} }
async applyCursorAutoReviewConfig(on) { async applyCursorAutoReviewConfig(on) {
if (this.o.flavor !== "cursor" || !this.ctx || !this.active) return; if (this.o.flavor !== "cursor" || !this.ctx || !this.active) return;
@@ -5290,7 +5318,7 @@ var init_session3 = __esm({
if (this.o.imagesFollowStartModel) { if (this.o.imagesFollowStartModel) {
this.promptCaps = model === this.startModel ? this.initCaps : { ...this.initCaps, image: false }; this.promptCaps = model === this.startModel ? this.initCaps : { ...this.initCaps, image: false };
} }
await this.applySessionModel(model, Boolean(opts?.force)); return this.applySessionModel(model, Boolean(opts?.force));
} }
async setMode(mode2) { async setMode(mode2) {
this.o.mode = mode2; this.o.mode = mode2;
@@ -9561,11 +9589,12 @@ var AgentManager = class {
const sessionModel = model ?? await this.resolveDefaultSessionModel(meta.provider); const sessionModel = model ?? await this.resolveDefaultSessionModel(meta.provider);
await this.threads.patch(threadId, { model, effort }); await this.threads.patch(threadId, { model, effort });
const rt = this.rt(threadId); const rt = this.rt(threadId);
let applied = true;
if (rt.session) { if (rt.session) {
if (model !== null) await rt.session.setModel(sessionModel, { force: true }); if (model !== null) applied = await rt.session.setModel(sessionModel, { force: true });
else await rt.session.setModel(sessionModel); else applied = await rt.session.setModel(sessionModel);
} }
rt.syncedDefaultModel = model ? void 0 : sessionModel; rt.syncedDefaultModel = model ? void 0 : applied === false ? void 0 : sessionModel;
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) }); this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
} }
/** /**
@@ -9595,8 +9624,8 @@ var AgentManager = class {
const current = await this.resolveDefaultSessionModel(meta.provider); const current = await this.resolveDefaultSessionModel(meta.provider);
if (current === (rt.syncedDefaultModel ?? null)) return; if (current === (rt.syncedDefaultModel ?? null)) return;
try { try {
await rt.session.setModel(current); const applied = await rt.session.setModel(current);
rt.syncedDefaultModel = current; if (applied !== false) rt.syncedDefaultModel = current;
} catch (e) { } catch (e) {
log("warn", `thread ${threadId} sync default model failed\uFF1A${String(e)}`); log("warn", `thread ${threadId} sync default model failed\uFF1A${String(e)}`);
} }
File diff suppressed because one or more lines are too long
@@ -653,12 +653,14 @@ export class AgentManager {
const sessionModel = model ?? await this.resolveDefaultSessionModel(meta.provider); const sessionModel = model ?? await this.resolveDefaultSessionModel(meta.provider);
await this.threads.patch(threadId, { model, effort }); await this.threads.patch(threadId, { model, effort });
const rt = this.rt(threadId); const rt = this.rt(threadId);
let applied: boolean | void = true;
if (rt.session) { if (rt.session) {
// Only an explicit user pick may bypass ACP's session/new model validation. // Only an explicit user pick may bypass ACP's session/new model validation.
if (model !== null) await rt.session.setModel(sessionModel, { force: true }); if (model !== null) applied = await rt.session.setModel(sessionModel, { force: true });
else await rt.session.setModel(sessionModel); else applied = await rt.session.setModel(sessionModel);
} }
rt.syncedDefaultModel = model ? undefined : sessionModel; // 1.3.6: a default the session skipped (ACP validation) is not "synced" — the next idle send retries it
rt.syncedDefaultModel = model ? undefined : applied === false ? undefined : sessionModel;
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) }); this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
} }
@@ -692,8 +694,10 @@ export class AgentManager {
const current = await this.resolveDefaultSessionModel(meta.provider); const current = await this.resolveDefaultSessionModel(meta.provider);
if (current === (rt.syncedDefaultModel ?? null)) return; if (current === (rt.syncedDefaultModel ?? null)) return;
try { try {
await rt.session.setModel(current); const applied = await rt.session.setModel(current);
rt.syncedDefaultModel = current; // 1.3.6: ACP may skip a Magpie default that isn't in the session's model options (no blind
// set_config_option). Don't record it as synced then, or later idle sends never retry it.
if (applied !== false) rt.syncedDefaultModel = current;
} catch (e) { } catch (e) {
log("warn", `thread ${threadId} sync default model failed:${String(e)}`); log("warn", `thread ${threadId} sync default model failed:${String(e)}`);
} }
@@ -315,8 +315,10 @@ export class AcpSession implements ProviderSession {
* Switch model → refresh level options from the new config options it returns → then apply the level (as Paseo does). * Switch model → refresh level options from the new config options it returns → then apply the level (as Paseo does).
* Cursor connects with parameterizedModelPicker: only the base model name is sent (grok-4.6); level / Fast are separate config options. * Cursor connects with parameterizedModelPicker: only the base model name is sent (grok-4.6); level / Fast are separate config options.
*/ */
private async applySessionModel(model: string | null, force = false): Promise<void> { /** false = the model id was skipped (not in the session's model options and not forced) */
if (!this.ctx || !this.active) return; private async applySessionModel(model: string | null, force = false): Promise<boolean> {
if (!this.ctx || !this.active) return false;
let applied = true;
const value = model && this.o.flavor === "cursor" ? model.replace(/\[.*\]$/u, "") : model; const value = model && this.o.flavor === "cursor" ? model.replace(/\[.*\]$/u, "") : model;
if (value) { if (value) {
const modelOption = this.currentConfig().find((o) => o.id === (this.modelConfigId ?? "model")); const modelOption = this.currentConfig().find((o) => o.id === (this.modelConfigId ?? "model"));
@@ -328,12 +330,14 @@ export class AcpSession implements ProviderSession {
await this.setOption(this.modelConfigId ?? "model", value); await this.setOption(this.modelConfigId ?? "model", value);
} else { } else {
log("info", `忽略 ${this.o.binName} 的无效模型:${value}`); log("info", `忽略 ${this.o.binName} 的无效模型:${value}`);
applied = false;
} }
} }
if (this.o.flavor === "cursor" && this.cursorFast && this.currentConfig().some((o) => o.id === "fast")) { if (this.o.flavor === "cursor" && this.cursorFast && this.currentConfig().some((o) => o.id === "fast")) {
await this.setOption("fast", "true"); await this.setOption("fast", "true");
} }
await this.applySessionThought(this.o.effort); await this.applySessionThought(this.o.effort);
return applied;
} }
private async applyCursorAutoReviewConfig(on: boolean): Promise<void> { private async applyCursorAutoReviewConfig(on: boolean): Promise<void> {
@@ -565,14 +569,14 @@ export class AcpSession implements ProviderSession {
await notifyP; await notifyP;
} }
async setModel(model: string | null, opts?: { force?: boolean }): Promise<void> { async setModel(model: string | null, opts?: { force?: boolean }): Promise<boolean> {
this.o.model = model; this.o.model = model;
await this.ready(); await this.ready();
if (this.o.imagesFollowStartModel) { if (this.o.imagesFollowStartModel) {
// dsh answered initialize for the model it started on; another model may not take image blocks (it refuses the prompt) // dsh answered initialize for the model it started on; another model may not take image blocks (it refuses the prompt)
this.promptCaps = model === this.startModel ? this.initCaps : { ...this.initCaps, image: false }; this.promptCaps = model === this.startModel ? this.initCaps : { ...this.initCaps, image: false };
} }
await this.applySessionModel(model, Boolean(opts?.force)); return this.applySessionModel(model, Boolean(opts?.force));
} }
async setMode(mode: Mode): Promise<void> { async setMode(mode: Mode): Promise<void> {
@@ -384,6 +384,27 @@ async function scriptLong(ctx: Ctx): Promise<void> {
emit({ type: "assistant_message", itemId: "L1", text: "(5000 个增量合并后的长文)" }); emit({ type: "assistant_message", itemId: "L1", text: "(5000 个增量合并后的长文)" });
} }
// "/bigreply" (1.3.6 scroll e2e): one very long Markdown reply with many code blocks, far taller than the
// 120px row estimate; streamed in chunks ("/bigreply slow" streams it over ~6 s)
async function scriptBigReply(ctx: Ctx): Promise<void> {
const { emit } = ctx;
const slow = ctx.input.text.includes("slow");
const parts: string[] = [];
for (let i = 1; i <= 14; i++) {
parts.push(`### 第 ${i} 部分\n\n- 要点 ${i}.a:说明一下这里的改动\n- 要点 ${i}.b:以及为什么这样改\n\n`);
parts.push("```ts\n" + Array.from({ length: 8 }, (_, k) => `const v${i}_${k} = compute(${i}, ${k}); // line ${k}`).join("\n") + "\n```\n\n");
}
let acc = "";
emit({ type: "assistant_delta", itemId: "B1", text: "" });
for (const p of parts) {
if (ctx.interrupted()) return;
acc += p;
emit({ type: "assistant_delta", itemId: "B1", text: p });
await sleep(slow ? 220 : 5);
}
emit({ type: "assistant_message", itemId: "B1", text: acc });
}
async function scriptExit(_ctx: Ctx): Promise<void> { async function scriptExit(_ctx: Ctx): Promise<void> {
await sleep(300); await sleep(300);
throw new MockCrash(); throw new MockCrash();
@@ -399,6 +420,7 @@ function pickScript(text: string): (ctx: Ctx) => Promise<void> {
if (t.startsWith("/error")) return scriptError; if (t.startsWith("/error")) return scriptError;
if (t.startsWith("/long")) return scriptLong; if (t.startsWith("/long")) return scriptLong;
if (t.startsWith("/exit")) return scriptExit; if (t.startsWith("/exit")) return scriptExit;
if (t.startsWith("/bigreply")) return scriptBigReply;
if (t.startsWith("/serve")) return scriptServe; if (t.startsWith("/serve")) return scriptServe;
if (t.startsWith("/tools")) return scriptTools; if (t.startsWith("/tools")) return scriptTools;
if (t.startsWith("/bashhint")) return scriptBashHint; if (t.startsWith("/bashhint")) return scriptBashHint;
@@ -70,7 +70,11 @@ export interface ProviderSession {
send(input: SendInput): Promise<void>; send(input: SendInput): Promise<void>;
steer?(input: SendInput): Promise<void>; steer?(input: SendInput): Promise<void>;
interrupt(): Promise<void>; interrupt(): Promise<void>;
setModel(model: string | null, opts?: { force?: boolean }): Promise<void>; /**
* Resolves `false` only when the session deliberately skipped the model (ACP: not in the session's
* model options and not forced) — callers must not treat that model as applied. Anything else = applied.
*/
setModel(model: string | null, opts?: { force?: boolean }): Promise<boolean | void>;
setMode(mode: Mode): Promise<void>; setMode(mode: Mode): Promise<void>;
setEffort(effort: string | null): Promise<void>; setEffort(effort: string | null): Promise<void>;
respond(requestId: string, answer: RespondAnswer): void; respond(requestId: string, answer: RespondAnswer): void;
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "@magpie-community/page-agent-console", "name": "@magpie-community/page-agent-console",
"version": "1.3.5", "version": "1.3.6",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@magpie-community/page-agent-console", "name": "@magpie-community/page-agent-console",
"version": "1.3.5", "version": "1.3.6",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@agentclientprotocol/sdk": "2.1.0", "@agentclientprotocol/sdk": "2.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@magpie-community/page-agent-console", "name": "@magpie-community/page-agent-console",
"version": "1.3.5", "version": "1.3.6",
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.", "description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
"author": "qingnian108 (https://github.com/qingnian108)", "author": "qingnian108 (https://github.com/qingnian108)",
"homepage": "https://github.com/qingnian108/magpie-agent-console", "homepage": "https://github.com/qingnian108/magpie-agent-console",
@@ -21,9 +21,10 @@ describe("ACP explicit model pick vs default validation", () => {
}); });
const calls = () => existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").map((x) => JSON.parse(x)) : []; const calls = () => existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").map((x) => JSON.parse(x)) : [];
try { try {
await session.setModel("bogus-unprefixed-model"); // 1.3.6: a skipped default reports false so the manager doesn't mark it synced
expect(await session.setModel("bogus-unprefixed-model")).toBe(false);
expect(calls()).toEqual([]); // Both startup and unchecked defaults are rejected. expect(calls()).toEqual([]); // Both startup and unchecked defaults are rejected.
await session.setModel("magpie/old"); expect(await session.setModel("magpie/old")).toBe(true);
expect(calls().map((c) => c.value)).toEqual(["magpie/old"]); expect(calls().map((c) => c.value)).toEqual(["magpie/old"]);
await session.setModel("magpie/new", { force: true }); await session.setModel("magpie/new", { force: true });
expect(calls().map((c) => c.value)).toEqual(["magpie/old", "magpie/new"]); expect(calls().map((c) => c.value)).toEqual(["magpie/old", "magpie/new"]);
@@ -0,0 +1,208 @@
import { describe, it, expect } from "vitest";
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { spawn } from "node:child_process";
import { chromium } from "playwright-core";
// @ts-expect-error mjs helper
import { findBrowser } from "../../scripts/browser-path.mjs";
const root = join(dirname(fileURLToPath(import.meta.url)), "../..");
const browserPath: string | null = findBrowser();
function buildTallReply(): string {
return [
"现在已经安装并检查完成了,当前状态是正常的。",
"",
"已经完成:",
"- `VoxWeave v0.2.0 Windows x64` 已安装到:`voxweave\\VoxWeave.exe`",
"- VoxWeave 桌面程序正在运行。",
"- 后台服务正在运行,地址是:`127.0.0.1:2994`",
"- RVC 环境自检通过,CUDA 识别到:`NVIDIA GeForce RTX 3070 Ti`",
"",
"```text",
"Python 3.12",
"PyTorch 2.7.1+cu118",
"FFmpeg 8.1.2",
...Array.from({ length: 18 }, (_, i) => `check-step-${i + 1}: status=ready latency=${10 + i}ms`),
"```",
"",
"四个中文女声模型也已经保留并被识别为 `ready`:",
"",
"```text",
"1 女声-可可",
"2 女声-云儿青春",
"3 女声-雅琳御姐",
"4 女声-诗韵",
...Array.from({ length: 16 }, (_, i) => `preset-${i + 1}: D:\\VoxWeave\\models\\voice_${i + 1}.pth`),
"```",
"",
"原始下载文件还保留在项目目录:",
"",
"```text",
...Array.from({ length: 14 }, (_, i) => `D:\\workwork\\变声器\\downloads\\archive_part_${i + 1}.zip`),
"```",
"",
"以上全部验证完毕(BOTTOM_SENTINEL_136)。",
].join("\n");
}
describe.skipIf(!browserPath)("Chat virtual-list scroll to bottom in real Chromium (1.3.6)", () => {
it("opens, recovers from hidden view, streams tall replies, and handles wheel-up + jump cleanly", async () => {
const xdg = mkdtempSync(join(tmpdir(), "ac-scroll-xdg-"));
const projDir = mkdtempSync(join(tmpdir(), "ac-scroll-proj-"));
const dataDir = join(xdg, "magpie", "agent-console");
const projectId = "p_scroll1";
const threadId = "t_scroll1";
const threadDir = join(dataDir, "threads", threadId);
mkdirSync(threadDir, { recursive: true });
const now = Date.now();
writeFileSync(join(dataDir, "settings.json"), JSON.stringify({
v1Migrated: true,
theme: "dark",
lastProjectId: projectId,
lastThreadId: threadId,
}));
writeFileSync(join(dataDir, "projects.json"), JSON.stringify([
{ id: projectId, name: "变声器", path: projDir, createdAt: now },
]));
const events: Record<string, unknown>[] = [];
let seq = 1;
for (let turn = 1; turn <= 6; turn++) {
const turnId = `turn-${turn}`;
events.push({ seq: seq++, ts: now - (20 - turn) * 1000, threadId, turnId, type: "user_message", text: `第 ${turn} 轮问题:现在已经安装好了吗?还是什么情况?你检查一下。` });
events.push({ seq: seq++, ts: now - (20 - turn) * 1000 + 50, threadId, turnId, type: "turn_started", model: "codex/gpt-6.1-terra", mode: "bypassPermissions", effort: "high" });
events.push({
seq: seq++,
ts: now - (20 - turn) * 1000 + 200,
threadId,
turnId,
type: "assistant_message",
itemId: `a-${turn}`,
text: turn === 6 ? buildTallReply() : `第 ${turn} 轮检查汇报:\n\n` + Array.from({ length: 8 }, (_, j) => `- 检查项 ${j + 1}:已就绪`).join("\n"),
});
events.push({ seq: seq++, ts: now - (20 - turn) * 1000 + 400, threadId, turnId, type: "turn_ended", status: "completed", durationMs: 1200 });
}
writeFileSync(join(threadDir, "meta.json"), JSON.stringify({
id: threadId,
projectId,
title: "那你像他们陪,他们那个说什么杂音…",
titleAuto: false,
provider: "mock",
model: null,
mode: "bypassPermissions",
effort: "high",
providerSessionId: null,
status: "idle",
pinned: false,
archived: false,
createdAt: now - 60000,
updatedAt: now,
lastTurnStatus: "completed",
usage: { inputTokens: 1200, outputTokens: 800, cacheReadTokens: 0, costUsd: 0.02 },
seq: seq - 1,
}));
writeFileSync(join(threadDir, "timeline.jsonl"), events.map((e) => JSON.stringify(e)).join("\n") + "\n");
const port = 35400 + Math.floor(Math.random() * 400);
const daemon = spawn(process.execPath, [join(root, "daemon/dist/main.js"), "--port", String(port), "--data", xdg], {
env: { ...process.env, AGENT_CONSOLE_MOCK: "1" },
stdio: ["ignore", "pipe", "pipe"],
});
const launchArgs = process.platform === "linux" && process.getuid?.() === 0 ? ["--no-sandbox"] : [];
const browser = await chromium.launch({ executablePath: browserPath!, headless: true, args: launchArgs });
try {
let token = "";
const readyDeadline = Date.now() + 12000;
while (Date.now() < readyDeadline) {
try {
const dj = JSON.parse(readFileSync(join(dataDir, "daemon.json"), "utf8"));
if (dj.token) { token = dj.token; break; }
} catch {}
await new Promise((r) => setTimeout(r, 150));
}
expect(token.length).toBeGreaterThan(0);
const url = `http://127.0.0.1:${port}/?lang=zh#t=${encodeURIComponent(token)}`;
const page = await browser.newPage({ viewport: { width: 920, height: 860 } });
await page.goto(url, { waitUntil: "domcontentloaded" });
await page.getByText("BOTTOM_SENTINEL_136", { exact: false }).waitFor({ timeout: 10000 });
await page.waitForTimeout(300);
const readMetrics = () => page.evaluate(() => {
const el = document.querySelector(".scroll") as HTMLElement;
return {
scrollTop: el.scrollTop,
scrollHeight: el.scrollHeight,
clientHeight: el.clientHeight,
gap: el.scrollHeight - el.scrollTop - el.clientHeight,
jumpVisible: Boolean(document.querySelector("button.jump")),
};
});
const m1 = await readMetrics();
expect(m1.scrollHeight).toBeGreaterThan(2200);
expect(m1.gap).toBeLessThanOrEqual(2);
expect(m1.jumpVisible).toBe(false);
// Simulate plugin disable -> re-enable while host view starts hidden (0x0 layout), then becomes visible
const hiddenPage = await browser.newPage({ viewport: { width: 920, height: 860 } });
await hiddenPage.addInitScript(() => {
const st = document.createElement("style");
st.id = "__ac_hide";
st.textContent = "html{display:none!important}";
document.documentElement.appendChild(st);
});
await hiddenPage.goto(url, { waitUntil: "domcontentloaded" });
await hiddenPage.waitForFunction(() => document.querySelectorAll(".tl-wrap [data-index]").length > 0, null, { timeout: 10000 });
await hiddenPage.waitForTimeout(250);
await hiddenPage.evaluate(() => document.getElementById("__ac_hide")?.remove());
await hiddenPage.getByText("BOTTOM_SENTINEL_136", { exact: false }).waitFor({ timeout: 10000 });
await hiddenPage.waitForTimeout(300);
const mHidden = await hiddenPage.evaluate(() => {
const el = document.querySelector(".scroll") as HTMLElement;
return { gap: el.scrollHeight - el.scrollTop - el.clientHeight, jumpVisible: Boolean(document.querySelector("button.jump")) };
});
expect(mHidden.gap).toBeLessThanOrEqual(2);
expect(mHidden.jumpVisible).toBe(false);
await hiddenPage.close();
// User wheels upward -> detaches stick and shows .jump (without false .jd dot)
const box = await page.locator(".scroll").boundingBox();
await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2);
await page.mouse.wheel(0, -600);
await page.waitForTimeout(200);
const mUp = await readMetrics();
expect(mUp.gap).toBeGreaterThan(200);
expect(mUp.jumpVisible).toBe(true);
expect(await page.locator("button.jump .jd").count()).toBe(0);
// Clicking .jump lands all the way at the real bottom again
await page.locator("button.jump").click();
await page.waitForTimeout(250);
const mJump = await readMetrics();
expect(mJump.gap).toBeLessThanOrEqual(2);
expect(mJump.jumpVisible).toBe(false);
// Streaming a new tall multi-code-block reply stays pinned to the bottom without row count growing mid-stream
const prevHeight = mJump.scrollHeight;
await page.locator(".cp-ta").fill("/bigreply");
await page.keyboard.press("Enter");
await page.getByText("第 14 部分", { exact: false }).waitFor({ timeout: 15000 });
await page.waitForTimeout(300);
const mStream = await readMetrics();
expect(mStream.scrollHeight).toBeGreaterThan(prevHeight + 1000);
expect(mStream.gap).toBeLessThanOrEqual(2);
expect(mStream.jumpVisible).toBe(false);
} finally {
await browser.close();
daemon.kill("SIGTERM");
rmSync(xdg, { recursive: true, force: true });
rmSync(projDir, { recursive: true, force: true });
}
}, 45000);
});
@@ -455,8 +455,13 @@ describe("AgentManager + Claude crash keeps thread open (resume)", () => {
delete process.env.FAKE_CLAUDE_CRASH_AFTER_DELTA; delete process.env.FAKE_CLAUDE_CRASH_AFTER_DELTA;
await manager.send(threadId, { text: "after-crash" }); await manager.send(threadId, { text: "after-crash" });
await waitFor(async () => (await threads.get(threadId))?.lastTurnStatus === "completed"); // turn_ended patches lastTurnStatus a tick before setStatus("idle"): wait for both
await waitFor(async () => {
const m = await threads.get(threadId);
return m?.lastTurnStatus === "completed" && m?.status === "idle";
});
const meta2 = await threads.get(threadId); const meta2 = await threads.get(threadId);
expect(meta2?.lastTurnStatus).toBe("completed");
expect(meta2?.status).toBe("idle"); expect(meta2?.status).toBe("idle");
expect(meta2?.status).not.toBe("closed"); expect(meta2?.status).not.toBe("closed");
const argvs = readFileSync(logFile, "utf8") const argvs = readFileSync(logFile, "utf8")
@@ -113,4 +113,44 @@ describe("AgentManager Magpie default-model sync", () => {
expect(setModelSpy.mock.calls).toEqual([["hub/model-b"]]); expect(setModelSpy.mock.calls).toEqual([["hub/model-b"]]);
expect((await threads.get(threadId))?.model).toBeNull(); expect((await threads.get(threadId))?.model).toBeNull();
}, 30000); }, 30000);
it("1.3.6: a Magpie default the session skipped (ACP validation) is not marked synced — the next idle send retries it", async () => {
await manager.send(threadId, { text: "hi" });
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
// Magpie enables hub/model-new mid-session and makes it the default; the live session skips it (not forced)
mocks.magpieDefaultModel.mockResolvedValue("hub/model-new");
setModelSpy.mockClear();
setModelSpy.mockResolvedValueOnce(false);
await manager.send(threadId, { text: "second" });
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
expect(setModelSpy.mock.calls).toEqual([["hub/model-new"]]);
// Next idle send must try again (it used to early-return: syncedDefaultModel was already advanced)
setModelSpy.mockClear();
await manager.send(threadId, { text: "third" });
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
expect(setModelSpy.mock.calls).toEqual([["hub/model-new"]]);
// Applied now → synced; a further send doesn't push it again
setModelSpy.mockClear();
await manager.send(threadId, { text: "fourth" });
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
expect(setModelSpy).not.toHaveBeenCalled();
}, 30000);
it("1.3.6: switching back to「默认」when the session skips the resolved default leaves it unsynced for the next send", async () => {
await manager.send(threadId, { text: "hi" });
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
await manager.setModel(threadId, "magpie/explicit");
mocks.magpieDefaultModel.mockResolvedValue("hub/model-new");
setModelSpy.mockClear();
setModelSpy.mockResolvedValueOnce(false);
await manager.setModel(threadId, null);
expect(setModelSpy.mock.calls).toEqual([["hub/model-new"]]);
setModelSpy.mockClear();
await manager.send(threadId, { text: "again" });
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
expect(setModelSpy.mock.calls).toEqual([["hub/model-new"]]);
}, 30000);
}); });
@@ -1,5 +1,5 @@
// Conversation area (§8.6): virtual list, stick-to-bottom, empty state, queue list, Composer. // Conversation area (§8.6): virtual list, stick-to-bottom, empty state, queue list, Composer.
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { isImeComposing } from "../composer/ime"; import { isImeComposing } from "../composer/ime";
import { useVirtualizer } from "@tanstack/react-virtual"; import { useVirtualizer } from "@tanstack/react-virtual";
import { useUi } from "../stores/ui"; import { useUi } from "../stores/ui";
@@ -8,6 +8,7 @@ import { useTimeline } from "../stores/timeline";
import { TimelineRow } from "./Timeline"; import { TimelineRow } from "./Timeline";
import { foldTimeline, TOOL_COLLAPSE_AT } from "../timeline/fold"; import { foldTimeline, TOOL_COLLAPSE_AT } from "../timeline/fold";
import { collectAutoApproved } from "../timeline/autoApproved"; import { collectAutoApproved } from "../timeline/autoApproved";
import { decideOnScroll, newTracker, SCROLL_UP_KEYS } from "../timeline/stick";
import { Composer } from "./Composer"; import { Composer } from "./Composer";
import { QuoteSelect } from "./QuoteSelect"; import { QuoteSelect } from "./QuoteSelect";
import { Icon } from "./Icons"; import { Icon } from "./Icons";
@@ -27,21 +28,34 @@ export function Chat() {
// 1.3 全部自动同意: the daemon's own approvals become one quiet row after their run (collectAutoApproved) // 1.3 全部自动同意: the daemon's own approvals become one quiet row after their run (collectAutoApproved)
const items = useMemo(() => foldTimeline(collectAutoApproved(tl.items), { showThinking: prefs.showThinking }), [tl.items, prefs.showThinking]); const items = useMemo(() => foldTimeline(collectAutoApproved(tl.items), { showThinking: prefs.showThinking }), [tl.items, prefs.showThinking]);
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
const [stick, setStick] = useState(true); const [stick, setStickState] = useState(true);
const [hasNew, setHasNew] = useState(false); const [hasNew, setHasNew] = useState(false);
// 1.3.6: the live stick flag (effects/observers read it synchronously; state only drives the 回到底部 button)
const track = useRef(newTracker());
const setStick = useCallback((v: boolean) => { track.current.stick = v; setStickState(v); }, []);
/** Snap to the real bottom (scrollHeight, which follows the measured rows) */
const toBottom = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
el.scrollTop = el.scrollHeight;
track.current.lastTop = el.scrollTop;
}, []);
const project = projects.find((p) => p.id === ui.currentProjectId) ?? null; const project = projects.find((p) => p.id === ui.currentProjectId) ?? null;
const threadId = ui.currentThreadId; const threadId = ui.currentThreadId;
const thread = threadId ? threads.find((th) => th.id === threadId) ?? null : null; const thread = threadId ? threads.find((th) => th.id === threadId) ?? null : null;
const activeThreadId = const activeThreadId =
project && thread && thread.projectId === project.id ? thread.id : null; project && thread && thread.projectId === project.id ? thread.id : null;
const hasProjects = projects.length > 0;
useEffect(() => { useEffect(() => {
if (activeThreadId) tl.open(activeThreadId); if (activeThreadId) tl.open(activeThreadId);
else tl.close(); else tl.close();
setStick(true); setStick(true);
setHasNew(false); setHasNew(false);
}, [activeThreadId]); // eslint-disable-line react-hooks/exhaustive-deps track.current.pointerDown = false;
track.current.intentAt = -Infinity;
}, [activeThreadId, setStick]); // eslint-disable-line react-hooks/exhaustive-deps
const est = useCallback((i: number) => { const est = useCallback((i: number) => {
const it = items[i]; const it = items[i];
@@ -67,6 +81,10 @@ export function Chat() {
overscan: 8, overscan: 8,
measureElement: (el) => el.getBoundingClientRect().height, measureElement: (el) => el.getBoundingClientRect().height,
}); });
// 1.3.6: while stuck to the bottom, suppress virtual-core's top-anchor clamped scroll adjustments
// so measuring tall rows near the bottom never yanks scrollTop back into the middle of the conversation
virt.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, inst) =>
!track.current.stick && item.end <= (inst.scrollOffset ?? 0) && inst.scrollDirection !== "backward";
// 1.3: the composer's "N/M tasks" pill brings its checklist into view // 1.3: the composer's "N/M tasks" pill brings its checklist into view
useEffect(() => { useEffect(() => {
@@ -74,6 +92,7 @@ export function Chat() {
const key = (e as CustomEvent).detail?.key as string | undefined; const key = (e as CustomEvent).detail?.key as string | undefined;
const idx = key ? items.findIndex((x) => x.key === key) : -1; const idx = key ? items.findIndex((x) => x.key === key) : -1;
if (idx < 0) return; if (idx < 0) return;
setStick(false);
virt.scrollToIndex(idx, { align: "center" }); virt.scrollToIndex(idx, { align: "center" });
requestAnimationFrame(() => { requestAnimationFrame(() => {
const el = scrollRef.current?.querySelector(`[data-todo-key="${CSS.escape(key!)}"]`); const el = scrollRef.current?.querySelector(`[data-todo-key="${CSS.escape(key!)}"]`);
@@ -84,40 +103,98 @@ export function Chat() {
}; };
window.addEventListener("ac-show-item", on); window.addEventListener("ac-show-item", on);
return () => window.removeEventListener("ac-show-item", on); return () => window.removeEventListener("ac-show-item", on);
}, [items, virt]); }, [items, virt, setStick]);
const count = items.length; const count = items.length;
// New rows: follow them when stuck; otherwise light the dot — but not for the snapshot of a just-opened conversation
const seen = useRef<{ thread: string | null; n: number }>({ thread: null, n: 0 });
useEffect(() => {
const prev = seen.current;
const grew = prev.thread === activeThreadId && prev.n > 0 && count > prev.n;
seen.current = { thread: activeThreadId, n: count };
if (track.current.stick) toBottom();
else if (grew) setHasNew(true);
}, [count, activeThreadId, toBottom]);
// 1.3.6: rows are estimated (120px for a reply) and grow when measured or while streaming, with the row
// count unchanged — after every render that may have changed the total size, stay on the real bottom
const totalSize = virt.getTotalSize();
useLayoutEffect(() => {
if (track.current.stick) toBottom();
});
// …and when the content, a row, or the scroller itself resizes (code blocks laid out, a hidden plugin view
// becoming visible, a streaming row growing before the virtualizer re-renders, window/panel/composer resize)
const ro = useRef<ResizeObserver | null>(null);
if (!ro.current && typeof ResizeObserver !== "undefined") {
ro.current = new ResizeObserver(() => { if (track.current.stick) toBottom(); });
}
useEffect(() => () => ro.current?.disconnect(), []);
useEffect(() => { useEffect(() => {
const el = scrollRef.current; const el = scrollRef.current;
if (!el) return; const obs = ro.current;
if (stick) el.scrollTop = el.scrollHeight; if (!el || !obs) return;
else setHasNew(true); obs.observe(el);
}, [count, stick]); const wrap = el.querySelector(".tl-wrap");
if (wrap) obs.observe(wrap);
return () => { obs.unobserve(el); if (wrap) obs.unobserve(wrap); };
}, [activeThreadId, hasProjects]);
const rowRef = useCallback((node: HTMLDivElement | null) => {
virt.measureElement(node);
if (node) ro.current?.observe(node); // detached rows drop out of the observer with their node
}, [virt]);
// 1.3: a send always lands at the bottom, at once (and again after the new row is measured) // 1.3: a send always lands at the bottom, at once (and again after the new row is measured)
useEffect(() => { useEffect(() => {
if (!tl.sentAt) return; if (!tl.sentAt) return;
setStick(true); setStick(true);
setHasNew(false); setHasNew(false);
const el = scrollRef.current; toBottom();
if (!el) return; const raf = requestAnimationFrame(toBottom);
el.scrollTop = el.scrollHeight;
const raf = requestAnimationFrame(() => { el.scrollTop = el.scrollHeight; });
return () => cancelAnimationFrame(raf); return () => cancelAnimationFrame(raf);
}, [tl.sentAt]); }, [tl.sentAt, setStick, toBottom]);
// 1.3.6: only a user gesture may leave the bottom (layout growth fires scroll events too)
const intent = () => { track.current.intentAt = performance.now(); };
const onWheel = (e: React.WheelEvent) => {
intent();
const el = scrollRef.current;
// upward wheel on an overflowing list: leave at once, before the next growth snaps it back
if (e.deltaY < 0 && el && el.scrollHeight > el.clientHeight && track.current.stick) setStick(false);
};
const onKeyDown = (e: React.KeyboardEvent) => {
if (SCROLL_UP_KEYS.has(e.key) || (e.key === " " && e.shiftKey)) intent();
};
const onPointerDown = () => { track.current.pointerDown = true; intent(); };
useEffect(() => {
const up = () => { if (track.current.pointerDown) { track.current.pointerDown = false; intent(); } };
window.addEventListener("pointerup", up);
window.addEventListener("pointercancel", up);
return () => { window.removeEventListener("pointerup", up); window.removeEventListener("pointercancel", up); };
}, []);
const onScroll = () => { const onScroll = () => {
const el = scrollRef.current; const el = scrollRef.current;
if (!el) return; if (!el) return;
const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 60; const was = track.current.stick;
setStick(nearBottom); const now = decideOnScroll(track.current, el, performance.now());
if (nearBottom) setHasNew(false); if (now !== was || now !== stick) setStick(now);
if (now) {
setHasNew(false);
// growth/programmatic move while stuck: back onto the real bottom
if (el.scrollHeight - el.scrollTop - el.clientHeight > 1) toBottom();
}
}; };
// 1.3.6: rows near the bottom may still be unmeasured — jump instantly and keep following as they measure
// (a smooth scroll aimed at today's scrollHeight stopped halfway once those rows grew)
const jump = () => { const jump = () => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
setStick(true); setStick(true);
setHasNew(false); setHasNew(false);
if (items.length > 0) virt.scrollToIndex(items.length - 1, { align: "end" });
toBottom();
let n = 0;
const again = () => { if (!track.current.stick) return; toBottom(); if (++n < 6) requestAnimationFrame(again); };
requestAnimationFrame(again);
}; };
const resend = (text: string, mentions?: { path: string; isDir: boolean }[]) => { const resend = (text: string, mentions?: { path: string; isDir: boolean }[]) => {
@@ -136,7 +213,7 @@ export function Chat() {
if (tl.lastUserText) resend(tl.lastUserText); if (tl.lastUserText) resend(tl.lastUserText);
}; };
if (projects.length === 0) { if (!hasProjects) {
return ( return (
<div className="scroll" ref={scrollRef}> <div className="scroll" ref={scrollRef}>
<WorkspaceEmpty kind="no-projects" /> <WorkspaceEmpty kind="no-projects" />
@@ -176,9 +253,10 @@ export function Chat() {
return ( return (
<> <>
<div className="scroll" ref={scrollRef} onScroll={onScroll}> <div className="scroll" ref={scrollRef} onScroll={onScroll} onWheel={onWheel} onKeyDown={onKeyDown}
onPointerDown={onPointerDown} onTouchStart={intent} onTouchMove={intent}>
<div className="tl-wrap" data-quote-root="chat"> <div className="tl-wrap" data-quote-root="chat">
<div style={{ height: virt.getTotalSize(), position: "relative" }}> <div style={{ height: totalSize, position: "relative" }}>
{virt.getVirtualItems().map((v) => { {virt.getVirtualItems().map((v) => {
const it = items[v.index]; const it = items[v.index];
if (!it) return null; if (!it) return null;
@@ -186,7 +264,7 @@ export function Chat() {
<div <div
key={v.key} key={v.key}
data-index={v.index} data-index={v.index}
ref={virt.measureElement} ref={rowRef}
style={{ position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${v.start}px)` }} style={{ position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${v.start}px)` }}
> >
<TimelineRow it={it} threadId={activeThreadId} onEditResend={resend} <TimelineRow it={it} threadId={activeThreadId} onEditResend={resend}
@@ -0,0 +1,48 @@
import { describe, it, expect } from "vitest";
import { decideOnScroll, newTracker, INTENT_MS } from "./stick";
const m = (scrollTop: number, scrollHeight: number, clientHeight = 800) => ({ scrollTop, scrollHeight, clientHeight });
describe("stick-to-bottom decisions (1.3.6)", () => {
it("layout growth after measuring (scrollHeight jumps, scrollTop unchanged) keeps the view stuck", () => {
const t = newTracker();
// opened: snapped to the estimated bottom (rows at 120px estimates)
expect(decideOnScroll(t, m(1200, 2000), 1000)).toBe(true);
// the long last reply is measured: content grows by 1500px, no user gesture
expect(decideOnScroll(t, m(1200, 3500), 1016)).toBe(true);
expect(t.stick).toBe(true);
});
it("streaming growth and container shrinking never unstick", () => {
const t = newTracker();
decideOnScroll(t, m(1000, 1800), 0);
for (let h = 1900; h < 6000; h += 137) expect(decideOnScroll(t, m(1000, h), 10)).toBe(true);
expect(decideOnScroll(t, m(1000, 1800, 500), 20)).toBe(true); // composer grew / window shrank
});
it("programmatic upward correction without a gesture (virtualizer shrinking an over-estimated row) stays stuck", () => {
const t = newTracker();
decideOnScroll(t, m(3000, 3800), 0);
expect(decideOnScroll(t, m(2700, 3800), 50)).toBe(true);
});
it("an upward user gesture unsticks at once, even while content keeps growing", () => {
const t = newTracker();
decideOnScroll(t, m(3000, 3800), 0);
t.intentAt = 100; // wheel up
expect(decideOnScroll(t, m(2800, 4200), 110)).toBe(false);
// growth afterwards doesn't re-stick it
expect(decideOnScroll(t, m(2800, 5200), 2000)).toBe(false);
// back within 60px of the bottom → stuck again
expect(decideOnScroll(t, m(5200 - 800 - 30, 5200), 2100)).toBe(true);
});
it("dragging the scrollbar up (pointer held) unsticks; an old gesture does not", () => {
const t = newTracker();
decideOnScroll(t, m(3000, 3800), 0);
t.intentAt = 0;
expect(decideOnScroll(t, m(2500, 3800), INTENT_MS + 10)).toBe(true);
t.pointerDown = true;
expect(decideOnScroll(t, m(2000, 3800), INTENT_MS + 20)).toBe(false);
});
});
@@ -0,0 +1,47 @@
// 1.3.6: stick-to-bottom decisions for the conversation scroller, kept DOM-free so they can be unit-tested.
//
// The chat is a virtual list: rows start at an estimated height and grow once measured (a long reply with
// code blocks is far taller than its 120px estimate), and a streaming reply grows without adding rows.
// Growth like that pushes scrollHeight away from scrollTop and fires `scroll` events of its own. It must
// never read as "the user scrolled up". Only a real upward move by the user leaves the bottom.
/** Within this many px of the bottom counts as "at the bottom" (re-sticks, clears the new-messages dot) */
export const STICK_PX = 60;
/** A wheel/touch/key/scrollbar gesture this recent (ms) explains an upward scrollTop change */
export const INTENT_MS = 600;
export interface ScrollMetrics { scrollTop: number; scrollHeight: number; clientHeight: number }
export interface StickTracker {
stick: boolean;
/** scrollTop seen at the previous scroll event / programmatic snap */
lastTop: number;
/** time of the last user scroll gesture (wheel, touch, scroll key, pointer on the scroller) */
intentAt: number;
/** a pointer is held on the scroller (dragging the scrollbar) */
pointerDown: boolean;
}
export const newTracker = (): StickTracker => ({ stick: true, lastTop: 0, intentAt: -Infinity, pointerDown: false });
export const distanceFromBottom = (m: ScrollMetrics): number => m.scrollHeight - m.scrollTop - m.clientHeight;
/**
* A `scroll` event happened: is the view still stuck to the bottom?
* - near the bottom → stuck (whatever moved it there)
* - stuck, and scrollTop did not go up, or went up without a user gesture (layout growth, the virtualizer
* correcting offsets, the container shrinking) → stays stuck; the caller snaps back to the bottom
* - stuck, scrollTop went up during a user gesture → unstuck
*/
export function decideOnScroll(t: StickTracker, m: ScrollMetrics, now: number): boolean {
const up = m.scrollTop < t.lastTop - 1;
t.lastTop = m.scrollTop;
if (distanceFromBottom(m) < STICK_PX) return (t.stick = true);
if (!t.stick) return false;
const userGesture = t.pointerDown || now - t.intentAt < INTENT_MS;
if (up && userGesture) return (t.stick = false);
return true;
}
/** Keys that scroll the conversation up when it has focus */
export const SCROLL_UP_KEYS = new Set(["ArrowUp", "PageUp", "Home"]);