You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "orangeCatDeveloper (via GitHub)" <gi...@apache.org> on 2026/09/06 00:41:13 UTC
[PR] fix(desktop): keep "return to latest" at the tail [maka]
orangeCatDeveloper opened a new pull request, #4883:
URL: https://github.com/apache/maka/pull/4883
## Summary
Fixes #4882
Clicking **返回最新消息** after paging far back flashed the tail and jumped back to the Turn the reader had been on; fast wheel paging occasionally stalled one page short. Together they are the `transcript-scroll-cost.spec.ts:239` flake on `main`.
Root cause of the jump-back: `ChatView` pinned the scroller to the tail only after `await onClick()` resolved, but the tail batch reaches the store before that. In the gap the unpinned scroller reported the top Turn as the reading anchor, and the `restoreRange` effect (which re-runs on every `messages` change) found it missing from the new range and called `loadAround` on it. The fix pins first: a pinned scroller reports no anchor, so the range that arrives has nothing to be pulled back to.
Root cause of the stall: `loadTranscriptHistory` returned silently while a load was pending. The scroller asks on every reader movement, so the request behind an in-flight load was lost and nothing re-asked. The guard now lives in `transcript-reading-position.ts` as `loadTranscriptHistory`, keeps the last request that arrived mid-flight (`latest` outranks `earlier`) and replays it when the current load settles, still gated on the session and controller being current. Moving it out of `app-shell.tsx` is what the renderer architecture ratchet asks for and leaves the shell smaller.
Overlaps with #4560, which rebuilds this area and removes the notice; that PR clears the anchor in `app-shell.tsx` before the load, which locally still loses the race (the scroller re-reports the anchor 17 ms after the load starts).
## Verification
`apps/desktop`: `npm run typecheck`, renderer ratchet `--write` then `--base $(git merge-base HEAD origin/main)`, `biome check` on the touched files, `@maka/ui` `test:dist` — all pass.
`transcript-scroll-cost.spec.ts -g "paging back" --repeat-each=60 --workers=4`, macOS, `main` 411512bd9 vs this branch:
```
3 failed
17 passed (1.4m) # main, --repeat-each=20
666735 [history] batch hasNewer=false hasOlder=true through=239 frags=20 evicted=220 idsMin=220 idsMax=239
666749 [history] restoreRange loadAround turn=turn-prompt-rail-1 seq=0
666811 [history] batch hasNewer=true hasOlder=false through=239 frags=20 evicted=220 idsMin=0 idsMax=19
60 passed (3.1m) # this branch, --repeat-each=60; 0 restoreRange loads after the tail across 60 runs
```
The instrumented lines are from a throwaway build of `main` with `console.info` in the store, the restore path and the shell; the fix branch is un-instrumented.
## AI use
Select exactly one:
- [ ] No generative tool made a substantive contribution
- [x] Generative tooling made a substantive contribution
Tool(s) and scope: Claude Code — trace analysis, instrumentation, root-cause bisection, and the code change; verified by the author.
## Checklist
- [x] Tests cover the change and fail without it
- [x] Lint, format, typecheck and the affected suites pass locally
Does this PR entail a change in behavior?
- [x] Yes — described under Summary above
- [ ] No
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] fix(desktop): keep "return to latest" at the tail [maka]
Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #4883:
URL: https://github.com/apache/maka/pull/4883#discussion_r3942660646
##########
apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts:
##########
@@ -442,6 +513,119 @@ describe('app shell session UI state controller', () => {
assert.deepEqual(unavailable, { sessionId: 'session', turnId: 'removed' });
});
+ it('starts another Session history load without waiting behind an in-flight load elsewhere', async () => {
+ const scenario = crossSessionGateScenario();
+ const stale = scenario.load('a', { target: 'earlier' });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.deepEqual(scenario.sides.a.calls, ['before']);
+ assert.deepEqual(scenario.pending.a, [true]);
+
+ scenario.switchTo('b');
+ const navigation = scenario.load('b', { target: 'latest' });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.deepEqual(scenario.sides.b.calls, ['latest']);
+ assert.deepEqual(scenario.pending.b, [true]);
+
+ scenario.sides.b.settleLatest();
+ scenario.sides.a.settleBefore();
+ await navigation;
+ await stale;
+ });
+
+ it('leaves the switched-to Session untouched when a stale Session load settles late', async () => {
+ const scenario = crossSessionGateScenario();
+ const stale = scenario.load('a', { target: 'earlier' });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ scenario.switchTo('b');
+ const navigation = scenario.load('b', { target: 'latest' });
+ scenario.sides.b.settleLatest();
+ await navigation;
+ assert.deepEqual(scenario.pending.b, [true, false]);
+ assert.deepEqual(scenario.sides.b.calls, ['latest']);
+
+ scenario.sides.a.settleBefore();
+ await stale;
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.deepEqual(scenario.pending.b, [true, false]);
+ assert.deepEqual(scenario.sides.b.calls, ['latest']);
+ assert.deepEqual(scenario.errors.b, []);
+ });
+
+ it('reports a late history load failure to its own Session alone', async () => {
+ const scenario = crossSessionGateScenario();
+ const stale = scenario.load('a', { target: 'earlier' });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ scenario.switchTo('b');
+ scenario.sides.a.failBefore(new Error('earlier read failed'));
+ await stale;
+ assert.deepEqual(scenario.errors.a, []);
+ assert.deepEqual(scenario.pending.a, [true, false]);
+ assert.deepEqual(scenario.pending.b, []);
+ });
+
+ it('replays the queued latest load once after an in-flight load settles on the same Session', async () => {
+ const scenario = crossSessionGateScenario();
+ const inFlight = scenario.load('a', { target: 'earlier' });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ const queuedEarlier = scenario.load('a', { target: 'earlier', anchorTurnId: 'turn-anchor' });
+ const queuedLatest = scenario.load('a', { target: 'latest' });
+ assert.deepEqual(scenario.sides.a.calls, ['before']);
+
+ scenario.sides.a.settleBefore();
+ await inFlight;
+ assert.deepEqual(scenario.sides.a.calls, ['before', 'latest']);
+ scenario.sides.a.settleLatest();
+ await Promise.allSettled([queuedEarlier, queuedLatest]);
Review Comment:
[P3] Do not use these queued-call promises as evidence that replay completed. `loadTranscriptHistory` returns immediately from the `gate.pending` branch, so both promises are already settled before the first load finishes; this await only happens to follow the replay continuation in today's microtask ordering. Either return a promise tied to the queued replay or await an explicit completion signal before asserting the final pending/callback state.
##########
packages/ui/src/__tests__/return-to-latest-pin.test.tsx:
##########
@@ -0,0 +1,304 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * The return-to-latest command must pin before it loads. An unpinned scroller
+ * reports the Turn it is leaving as the reading anchor, and the restore effect
+ * would pull the arriving range straight back — the bug the 60-run E2E guard
+ * covers, held here as a fast unit so reverting the two-line order goes red
+ * without a browser.
+ */
+
+import assert from 'node:assert/strict';
+import { afterEach, test } from 'node:test';
+import { Fragment, act, createElement, type ReactElement } from 'react';
+import { createRoot } from 'react-dom/client';
+import { parseHTML } from 'linkedom';
+import type { SessionSummary, StoredMessage } from '@maka/core/session';
+import { AstryxLocaleProvider } from '../astryx-i18n.js';
+import { ChatSurfaceLayout } from '../chat-surface-layout.js';
+import { ChatView } from '../chat-view.js';
+import { LocaleProvider } from '../locale-context.js';
+import {
+ TranscriptScrollAuthorityProvider,
+ useTranscriptScrollAuthority,
+ type TranscriptScrollAuthority,
+} from '../transcript-scroll-authority.js';
+
+const originalGlobals = {
+ CSS: globalThis.CSS,
+ document: globalThis.document,
+ Element: globalThis.Element,
+ HTMLElement: globalThis.HTMLElement,
+ IntersectionObserver: globalThis.IntersectionObserver,
+ MutationObserver: globalThis.MutationObserver,
+ Node: globalThis.Node,
+ ResizeObserver: globalThis.ResizeObserver,
+ matchMedia: globalThis.matchMedia,
+ requestAnimationFrame: globalThis.requestAnimationFrame,
+ cancelAnimationFrame: globalThis.cancelAnimationFrame,
+ window: globalThis.window,
+};
+const originalActEnvironment = (globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT?: boolean;
+}).IS_REACT_ACT_ENVIRONMENT;
+
+let mountedRoot: ReturnType<typeof createRoot> | undefined;
+
+afterEach(async () => {
+ if (mountedRoot) await act(() => mountedRoot?.unmount());
+ mountedRoot = undefined;
+ Object.assign(globalThis, {
+ ...originalGlobals,
+ IS_REACT_ACT_ENVIRONMENT: originalActEnvironment,
+ });
+});
+
+const activeSession: SessionSummary = {
+ id: 'session-return',
+ name: '回到最新',
+ isFlagged: false,
+ isArchived: false,
+ labels: [],
+ hasUnread: false,
+ status: 'active',
+ lastMessageAt: 0,
+ backend: 'ai-sdk',
+ llmConnectionId: 'connection-anthropic',
+ llmConnectionSlug: 'anthropic',
+ connectionLocked: false,
+ model: 'claude-sonnet-4-5',
+ permissionMode: 'ask',
+};
+
+const TURN_COUNT = 6;
+
+function turnMessages(): StoredMessage[] {
+ return Array.from({ length: TURN_COUNT }, (_, index): StoredMessage[] => [
+ {
+ type: 'user',
+ id: `user-${index}`,
+ turnId: `turn-${index}`,
+ ts: index * 2,
+ text: `第 ${index} 个问题`,
+ },
+ {
+ type: 'assistant',
+ id: `assistant-${index}`,
+ turnId: `turn-${index}`,
+ ts: index * 2 + 1,
+ text: '答案',
+ modelId: 'claude-sonnet-4-5',
+ },
+ ]).flat();
+}
+
+function deferredClick(): { onClick: () => Promise<void>; release: () => void } {
+ let release!: (value: void) => void;
+ const promise = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ return {
+ onClick: () => promise,
+ release: () => {
+ release();
+ },
+ };
+}
+
+
+interface ReturnToLatestHarness {
+ readonly anchors: Array<string | undefined>;
+ /** The authority `ChatSurfaceLayout` provided, read through a probe child. */
+ readonly authority: TranscriptScrollAuthority;
+ readonly scrollRoot: HTMLElement;
+ readonly scrollButton: HTMLElement;
+ readonly clickEvent: Event;
+ readerScroll(): void;
+}
+
+/**
+ * Renders `ChatView` with a deferred return-to-latest load inside the same
+ * linkedom + act harness `prompt-rail-observer-identity.test.tsx` established.
+ * A probe child publishes the authority so the test can read the pin.
+ */
+function harness(options: { readonly onClick: () => Promise<void> | void }): ReturnToLatestHarness {
+ const { document, window } = parseHTML('<main id="mount"></main>');
+ // linkedom lays nothing out, so every box is zero-sized. The geometry this
+ // test needs is a scroller away from its tail with a Turn visible, which a
+ // constant viewport rectangle plus scrollTop and scrollHeight fields give.
+ const rect = {
+ bottom: 600, height: 600, left: 0, right: 800, top: 0, width: 800, x: 0, y: 0,
+ toJSON: () => ({}),
+ } satisfies DOMRect;
+ window.Element.prototype.getBoundingClientRect = () => rect;
+ class InertResizeObserver {
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+ }
+ class InertIntersectionObserver {
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+ takeRecords(): IntersectionObserverEntry[] {
+ return [];
+ }
+ }
+ Object.assign(globalThis, {
+ CSS: { supports: () => false },
+ document,
+ Element: window.Element,
+ HTMLElement: window.HTMLElement,
+ IntersectionObserver: InertIntersectionObserver,
+ MutationObserver: window.MutationObserver,
+ Node: window.Node,
+ ResizeObserver: InertResizeObserver,
+ matchMedia: () => ({
+ matches: false,
+ addEventListener() {},
+ removeEventListener() {},
+ }),
+ requestAnimationFrame: (callback: FrameRequestCallback) => {
+ callback(0);
+ return 0;
+ },
+ cancelAnimationFrame: () => {},
+ window,
+ IS_REACT_ACT_ENVIRONMENT: true,
+ });
+ const anchors: Array<string | undefined> = [];
+ let authority: TranscriptScrollAuthority | undefined;
+ const AuthorityProbe = (): ReactElement => {
+ authority = useTranscriptScrollAuthority();
+ return createElement(Fragment, null);
+ };
+ const probe = createElement(TranscriptScrollAuthorityProvider, {
Review Comment:
[P3] Observe the authority that `ChatView` actually uses. This probe is mounted as a sibling of `ChatSurfaceLayout`, under its own `TranscriptScrollAuthorityProvider`, while the layout creates a separate provider around the chat. As a result, `view.authority` starts and remains independently pinned, so the assertion at line 275 can pass even if the production pin-before-load ordering regresses. Mount the probe inside the layout-owned provider (or otherwise expose that exact authority) so the assertion observes the state under test.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] fix(desktop): keep "return to latest" at the tail [maka]
Posted by "orangeCatDeveloper (via GitHub)" <gi...@apache.org>.
orangeCatDeveloper commented on code in PR #4883:
URL: https://github.com/apache/maka/pull/4883#discussion_r3942589733
##########
apps/desktop/src/renderer/features/conversation/controller/transcript-reading-position.ts:
##########
@@ -99,6 +99,52 @@ export function refreshTranscriptTurnLandmarks<T>(options: {
};
}
+export interface TranscriptHistoryRequest {
+ readonly target: 'earlier' | 'latest';
+ readonly anchorTurnId?: string;
+}
+
+export interface TranscriptHistoryGate {
+ pending: boolean;
+ queued?: TranscriptHistoryRequest;
+}
+
+export async function loadTranscriptHistory(options: {
+ readonly gate: TranscriptHistoryGate;
+ readonly request: TranscriptHistoryRequest;
+ readonly controller: {
+ loadBefore(maxBytes: number, anchorTurnId?: string): Promise<void>;
+ loadLatest(): Promise<void>;
+ };
+ readonly maxBytes: number;
+ readonly isCurrent: () => boolean;
+ readonly setPending: (pending: boolean) => void;
+ readonly onError: (error: unknown) => void;
+}): Promise<void> {
+ const { gate, request } = options;
+ if (gate.pending) {
+ // The scroller asks on every reader movement; dropping the request behind
+ // an in-flight load strands the reader until they move again.
+ if (request.target === 'latest' || gate.queued?.target !== 'latest') gate.queued = request;
+ return;
+ }
+ gate.pending = true;
+ options.setPending(true);
+ try {
+ if (request.target === 'earlier') {
+ await options.controller.loadBefore(options.maxBytes, request.anchorTurnId);
+ } else await options.controller.loadLatest();
+ } catch (error) {
+ if (options.isCurrent()) options.onError(error);
+ } finally {
+ gate.pending = false;
+ options.setPending(false);
+ const queued = gate.queued;
+ gate.queued = undefined;
+ if (queued && options.isCurrent()) void loadTranscriptHistory({ ...options, request: queued });
Review Comment:
Thanks for the review — and in particular for the deterministic helper-level probe; it matches what we saw locally.
The P2 is fixed by 76692daa8 ("fix(desktop): gate history loads per transcript controller"), pushed as the second commit of this PR. The gate is now keyed per controller (`WeakMap<object, TranscriptHistoryGate>`), so both failures you reproduced are gone:
- B queued while A's load is in flight, then A settles → B's queued request replays through B's own controller/callbacks ("replays a queued load through its own Session callbacks").
- B queued, A settles while B is active → B's gate was never blocked by A in the first place; B's load starts immediately ("starts another Session history load without waiting behind an in-flight load elsewhere").
Same-Session queue semantics from the first commit are unchanged (latest outranks earlier, single replay, no replay after the range is replaced) and are covered by the new cases in `apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts` (27/27 in `dist`).
`transcript-scroll-cost.spec.ts -g "paging back" --repeat-each=60 --workers=4` re-run on 76692daa8: 60 passed.
On `product-sidebar-session-list--project-groups`: we also see it fail only in CI on this PR and can't reproduce it locally; it looks unrelated to this change (the diff touches `app-shell.tsx` import/refs, the gate helper, and desktop tests only). If it persists on `main`, it may warrant its own issue rather than blocking this one.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] fix(desktop): keep "return to latest" at the tail [maka]
Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han merged PR #4883:
URL: https://github.com/apache/maka/pull/4883
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] fix(desktop): keep "return to latest" at the tail [maka]
Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #4883:
URL: https://github.com/apache/maka/pull/4883#discussion_r3942559476
##########
apps/desktop/src/renderer/features/conversation/controller/transcript-reading-position.ts:
##########
@@ -99,6 +99,52 @@ export function refreshTranscriptTurnLandmarks<T>(options: {
};
}
+export interface TranscriptHistoryRequest {
+ readonly target: 'earlier' | 'latest';
+ readonly anchorTurnId?: string;
+}
+
+export interface TranscriptHistoryGate {
+ pending: boolean;
+ queued?: TranscriptHistoryRequest;
+}
+
+export async function loadTranscriptHistory(options: {
+ readonly gate: TranscriptHistoryGate;
+ readonly request: TranscriptHistoryRequest;
+ readonly controller: {
+ loadBefore(maxBytes: number, anchorTurnId?: string): Promise<void>;
+ loadLatest(): Promise<void>;
+ };
+ readonly maxBytes: number;
+ readonly isCurrent: () => boolean;
+ readonly setPending: (pending: boolean) => void;
+ readonly onError: (error: unknown) => void;
+}): Promise<void> {
+ const { gate, request } = options;
+ if (gate.pending) {
+ // The scroller asks on every reader movement; dropping the request behind
+ // an in-flight load strands the reader until they move again.
+ if (request.target === 'latest' || gate.queued?.target !== 'latest') gate.queued = request;
+ return;
+ }
+ gate.pending = true;
+ options.setPending(true);
+ try {
+ if (request.target === 'earlier') {
+ await options.controller.loadBefore(options.maxBytes, request.anchorTurnId);
+ } else await options.controller.loadLatest();
+ } catch (error) {
+ if (options.isCurrent()) options.onError(error);
+ } finally {
+ gate.pending = false;
+ options.setPending(false);
+ const queued = gate.queued;
+ gate.queued = undefined;
+ if (queued && options.isCurrent()) void loadTranscriptHistory({ ...options, request: queued });
Review Comment:
P2: Preserve the queued request's session/controller ownership.
`historyLoadGateRef` is shared across active-session changes, but `gate.queued` stores only the target and anchor. This replay therefore uses the `options` captured by whichever request was already in flight. I reproduced: start `A.loadBefore`, switch to B and queue `latest`, switch back to A, then settle A; the replay calls `A.loadLatest` and never calls B. If B remains active when A settles, B's queued request is discarded by A's `isCurrent()` check instead. That leaves a reachable dead "Return to latest" action or can load the wrong session. Queue the complete invocation/owner (or use/reset a per-session gate) and add a cross-session regression test.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org