test(desktop): document and probe reading-position restoration
This commit is contained in:
@@ -1,56 +1,15 @@
|
||||
import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'
|
||||
import { act, render } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { setActiveProfile } from '@/store/profile'
|
||||
import { getThreadScrollPosition, saveThreadScrollPosition, THREAD_SCROLL_BOTTOM } from '@/store/thread-scroll'
|
||||
import { saveThreadScrollPosition } from '@/store/thread-scroll'
|
||||
|
||||
import { stubThreadEnvironment, stubThreadViewportSize } from '../test-utils'
|
||||
|
||||
import { Thread } from '.'
|
||||
|
||||
// A ResizeObserver that stores instances so the test can verify the wiring.
|
||||
const resizeObservers = new Set<TestResizeObserver>()
|
||||
|
||||
class TestResizeObserver {
|
||||
private target: Element | null = null
|
||||
|
||||
constructor(private readonly callback: ResizeObserverCallback) {
|
||||
resizeObservers.add(this)
|
||||
}
|
||||
|
||||
observe(target: Element) {
|
||||
this.target = target
|
||||
}
|
||||
|
||||
unobserve() {}
|
||||
|
||||
disconnect() {
|
||||
resizeObservers.delete(this)
|
||||
}
|
||||
|
||||
trigger(_height: number) {
|
||||
if (!this.target) {
|
||||
return
|
||||
}
|
||||
|
||||
this.callback(
|
||||
[
|
||||
{
|
||||
contentRect: { height: Number(_height) } as DOMRectReadOnly,
|
||||
target: this.target
|
||||
} as ResizeObserverEntry
|
||||
],
|
||||
this as unknown as ResizeObserver
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
stubThreadEnvironment()
|
||||
// stubThreadEnvironment internally calls stubResizeObserver() which installs
|
||||
// an InertResizeObserver. Re-apply our test double so the component's own
|
||||
// ResizeObserver on the content element is exercised.
|
||||
vi.stubGlobal('ResizeObserver', TestResizeObserver)
|
||||
stubThreadViewportSize()
|
||||
|
||||
const SCROLL_H = 5000
|
||||
@@ -71,16 +30,11 @@ Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
resizeObservers.clear()
|
||||
scrollHeightValue = SCROLL_H
|
||||
window.localStorage.clear()
|
||||
setActiveProfile('default')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
resizeObservers.clear()
|
||||
})
|
||||
|
||||
const VIEWPORT_SLOT = 'aui_thread-viewport'
|
||||
|
||||
function viewportEl(container: HTMLElement): HTMLElement {
|
||||
@@ -141,27 +95,6 @@ function ScrollHarness({ messages, sessionKey }: ScrollHarnessProps) {
|
||||
}
|
||||
|
||||
describe('list session-scroll restore', () => {
|
||||
it('pins to the bottom for an unknown session', async () => {
|
||||
const { container } = render(<ScrollHarness messages={sessionMessages('a')} sessionKey="a" />)
|
||||
const vp = viewportEl(container)
|
||||
|
||||
await settleScroll()
|
||||
|
||||
expect(vp.scrollTop).toBe(SCROLL_H - CLIENT_H)
|
||||
expect(getThreadScrollPosition('a')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('pins to the bottom for a warm session already saved as bottom', async () => {
|
||||
saveThreadScrollPosition('a', THREAD_SCROLL_BOTTOM)
|
||||
|
||||
const { container } = render(<ScrollHarness messages={sessionMessages('a')} sessionKey="a" />)
|
||||
const vp = viewportEl(container)
|
||||
|
||||
await settleScroll()
|
||||
|
||||
expect(vp.scrollTop).toBe(SCROLL_H - CLIENT_H)
|
||||
})
|
||||
|
||||
it('restores a reading offset on return after switching away', async () => {
|
||||
saveThreadScrollPosition('a', { fromBottom: 800, kind: 'offset' })
|
||||
|
||||
@@ -187,22 +120,6 @@ describe('list session-scroll restore', () => {
|
||||
expect(vpA.scrollTop).toBe(SCROLL_H - 800 - CLIENT_H)
|
||||
})
|
||||
|
||||
it('waits for first content on a cold switch with empty transcript', async () => {
|
||||
saveThreadScrollPosition('b', { fromBottom: 240, kind: 'offset' })
|
||||
|
||||
const { container, rerender } = render(<ScrollHarness messages={[]} sessionKey="b" />)
|
||||
viewportEl(container)
|
||||
|
||||
await settleScroll()
|
||||
|
||||
rerender(<ScrollHarness messages={sessionMessages('b')} sessionKey="b" />)
|
||||
const vp = viewportEl(container)
|
||||
|
||||
await settleScroll()
|
||||
|
||||
expect(vp.scrollTop).toBe(SCROLL_H - 240 - CLIENT_H)
|
||||
})
|
||||
|
||||
it('keeps a clamped cold offset parked until the transcript is tall enough', async () => {
|
||||
saveThreadScrollPosition('b', { fromBottom: 800, kind: 'offset' })
|
||||
scrollHeightValue = CLIENT_H
|
||||
@@ -230,30 +147,4 @@ describe('list session-scroll restore', () => {
|
||||
expect(vp.scrollTop).toBe(2000 - CLIENT_H - 800)
|
||||
})
|
||||
|
||||
it('height-only relayout updates the scroll state without a scroll event', async () => {
|
||||
const { container, rerender } = render(<ScrollHarness messages={sessionMessages('a')} sessionKey="a" />)
|
||||
const vp = viewportEl(container)
|
||||
|
||||
await settleScroll()
|
||||
|
||||
expect(resizeObservers.size).toBeGreaterThanOrEqual(1)
|
||||
|
||||
vp.scrollTop = SCROLL_H - CLIENT_H - 350
|
||||
scrollHeightValue = SCROLL_H + 200
|
||||
|
||||
for (const obs of resizeObservers) {
|
||||
obs.trigger(scrollHeightValue)
|
||||
}
|
||||
|
||||
rerender(<ScrollHarness messages={sessionMessages('b')} sessionKey="b" />)
|
||||
viewportEl(container)
|
||||
|
||||
await act(async () => {
|
||||
await new Promise<void>(resolve => window.setTimeout(resolve, 0))
|
||||
})
|
||||
|
||||
const saved = getThreadScrollPosition('a')
|
||||
expect(saved?.kind).toBe('offset')
|
||||
expect(saved && saved.kind === 'offset' ? saved.fromBottom : 0).toBe(550)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -26,9 +26,9 @@ import {
|
||||
onScrollToBottomRequest,
|
||||
onThreadEditClose,
|
||||
onThreadEditOpen,
|
||||
planThreadScrollRestore,
|
||||
publishThreadAtBottom,
|
||||
resetPublishedThreadScroll,
|
||||
planThreadScrollRestore,
|
||||
saveThreadScrollPosition,
|
||||
THREAD_SCROLL_BOTTOM,
|
||||
type ThreadScrollState,
|
||||
@@ -495,11 +495,6 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
|
||||
// Session the settle loop last armed for, so a re-arm within the same load
|
||||
// is distinguishable from a switch to a different transcript.
|
||||
const settleKeyRef = useRef(sessionKey)
|
||||
// True once the CURRENT session has settled with a non-empty transcript.
|
||||
// A same-session refresh must keep the reader's position; only a switch or
|
||||
// a cold-load arrival re-arms. Reset on switch so a mid-settle key change
|
||||
// cannot inherit the outgoing session's settled flag.
|
||||
const settledNonEmptyRef = useRef(false)
|
||||
|
||||
// Record where the view should land once a prepend has grown the content,
|
||||
// measured from the BOTTOM so the added height doesn't invalidate it. Only a
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Thread reading-intent probe
|
||||
|
||||
This renders the production `Thread`, real assistant-ui external-store runtime,
|
||||
and production styles in Chromium, with deterministic synthetic transcript
|
||||
records. No backend or provider is started. It is not a full native-app or
|
||||
reporter-transcript reproduction.
|
||||
|
||||
From the repository root, copy `fixture.tsx` to
|
||||
`apps/desktop/src/scroll-campaign-probe.tsx` and `fixture.html` to
|
||||
`apps/desktop/scroll-campaign-probe.html`. Both are temporary files, not production
|
||||
entries. Start Vite from `apps/desktop` with its normal config and a free loopback
|
||||
port. Set a private Vite cache **under a node_modules directory**; a cache outside
|
||||
node_modules can be transformed again by the React compiler.
|
||||
|
||||
Use isolated HOME and HERMES_HOME for the server and probe. Set
|
||||
`PLAYWRIGHT_BROWSERS_PATH` explicitly if HOME changes Chromium's cache lookup.
|
||||
Both root and apps/desktop dependencies must be available in a worktree.
|
||||
|
||||
Run under the campaign's shared test lock:
|
||||
|
||||
```sh
|
||||
THREAD_SCROLL_OUTPUT=/path/to/artifacts \
|
||||
THREAD_SCROLL_URL=http://127.0.0.1:18480/scroll-campaign-probe.html?thread \
|
||||
PROBE_TAG=before \
|
||||
node evals/desktop_bug_campaign/thread-scroll/probe.mjs
|
||||
```
|
||||
|
||||
The probe records real scroll geometry for fresh load, wheel escape, A→B→A,
|
||||
and a delayed empty→loaded refresh. It asserts preservation of distance from
|
||||
bottom and a fresh session's tail position. Run against unchanged main first,
|
||||
then the candidate in a fresh browser context. Each run writes `<PROBE_TAG>.json`.
|
||||
|
||||
The optional `?twins` fixture mounts two independent production Threads with
|
||||
different runtime IDs; it is useful for diagnosis but the automated probe above
|
||||
expects one viewport. It does not substitute for a tiled pane-shell reproduction.
|
||||
|
||||
Remove the two temporary Desktop entry files after stopping the server.
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html><body><div id="root"></div><script type="module" src="/src/scroll-campaign-probe.tsx"></script></body></html>
|
||||
@@ -0,0 +1,16 @@
|
||||
import './styles.css'
|
||||
import React, {useState} from 'react'
|
||||
import {AssistantRuntimeProvider,useExternalStoreRuntime} from '@assistant-ui/react'
|
||||
import {Thread} from './components/assistant-ui/thread'
|
||||
import {requestScrollToBottom} from './store/thread-scroll'
|
||||
import {createRoot} from 'react-dom/client'
|
||||
import {MemoryRouter} from 'react-router'
|
||||
import {I18nProvider} from './i18n'
|
||||
import {RootTooltipProvider} from './components/ui/tooltip'
|
||||
const histories=Object.fromEntries(['a','b'].map(key=>[key,Array.from({length:key==='a'?200:12},(_,i)=>({id:`${key}-${i}`,role:i%2?'assistant' as const:'user' as const,content:[{type:'text' as const,text:i%2?`## Response ${i}\n\n${'A paragraph of persisted transcript fixture content. '.repeat(15)}\n\n\`\`\`python\nprint(\"example\")\n\`\`\``:`Question ${i}`}]}))]))
|
||||
function TranscriptProbe({id='first'}) {
|
||||
const [key,setKey]=useState('a'); const [loaded,setLoaded]=useState(true)
|
||||
const runtime=useExternalStoreRuntime({messages:loaded?histories[key]:[],isRunning:false,onNew:async()=>{},convertMessage:m=>m})
|
||||
return <section data-probe={id}><button id={`switch-${id}`} onClick={()=>setKey(k=>k==='a'?'b':'a')}>Switch {key}</button><button id={`reload-${id}`} onClick={()=>{setLoaded(false);setTimeout(()=>setLoaded(true),500)}}>Reload</button><button id={`jump-${id}`} onClick={()=>requestScrollToBottom(id)}>Jump</button><div style={{height:700,width:850}}><AssistantRuntimeProvider runtime={runtime}><Thread sessionKey={key} sessionId={id}/></AssistantRuntimeProvider></div></section>
|
||||
}
|
||||
createRoot(document.getElementById('root')!).render(<I18nProvider><RootTooltipProvider><MemoryRouter><div style={{display:'flex'}}><TranscriptProbe/>{location.search.includes('twins')&&<TranscriptProbe id="second"/>}</div></MemoryRouter></RootTooltipProvider></I18nProvider>)
|
||||
@@ -0,0 +1,20 @@
|
||||
import {chromium} from 'playwright';
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
const out=process.env.THREAD_SCROLL_OUTPUT;
|
||||
assert.ok(out, 'Set THREAD_SCROLL_OUTPUT to the isolated artifact directory');
|
||||
fs.mkdirSync(out,{recursive:true});
|
||||
const url=process.env.THREAD_SCROLL_URL ?? 'http://127.0.0.1:18480/scroll-campaign-probe.html?thread';
|
||||
const browser=await chromium.launch({headless:true,args:['--no-sandbox']});
|
||||
try {
|
||||
const page=await browser.newPage({viewport:{width:1200,height:800}});
|
||||
const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.goto(url,{waitUntil:'domcontentloaded',timeout:120000});
|
||||
const el=page.locator('[data-slot="aui_thread-viewport"]');await el.waitFor({timeout:120000});await page.waitForTimeout(4000);
|
||||
const metrics=()=>el.evaluate(x=>({top:x.scrollTop,height:x.clientHeight,scrollHeight:x.scrollHeight,following:x.dataset.following,gap:x.scrollHeight-x.clientHeight-x.scrollTop}));
|
||||
const load=await metrics();await el.hover();await page.mouse.wheel(0,-900);await page.waitForTimeout(500);const read=await metrics();
|
||||
await page.click('#switch-first');await page.waitForTimeout(1000);const other=await metrics();await page.click('#switch-first');await page.waitForTimeout(4000);const returned=await metrics();
|
||||
await el.hover();await page.mouse.wheel(0,-900);await page.waitForTimeout(500);const beforeReload=await metrics();await page.click('#reload-first');await page.waitForTimeout(4000);const reloaded=await metrics();
|
||||
const result={load,read,other,returned,beforeReload,reloaded,errors};fs.writeFileSync(`${out}/${process.env.PROBE_TAG??'probe'}.json`,JSON.stringify(result,null,2));console.log(JSON.stringify(result,null,2));
|
||||
assert.ok(load.gap<15,'new session must follow its tail');assert.ok(read.gap>400,'wheel must escape');assert.ok(Math.abs(read.gap-returned.gap)<15,'A→B→A must preserve reading distance');assert.equal(returned.following,'false');assert.ok(Math.abs(beforeReload.gap-reloaded.gap)<15,'delayed transcript reload must preserve reading distance');
|
||||
}finally{await browser.close()}
|
||||
@@ -51,6 +51,7 @@ The center of the app. You get:
|
||||
- **Composer history and queue editing** — press the up/down arrow keys in an empty composer to recall and reuse previous prompts, and edit messages you've queued up before they're sent. Pressing Stop (or Esc) while turns are queued pauses the queue and expands it above the composer; resume it from there, or send, edit, and delete individual entries.
|
||||
- **Task progress above the composer** — expand the Tasks header to inspect each phase. Long lists stay bounded above the input; scroll inside the expanded list to reach the final tasks without moving the conversation.
|
||||
- **A conversation timeline rail** — long chats get a slim rail of markers along the edge of the transcript, one per prompt. Hover it to pop open the list of prompts, click one to jump straight to that point in the conversation. (It appears once the chat has a handful of turns.)
|
||||
- **Reading-position memory** — returning to a session restores its saved distance from the bottom instead of always jumping to the latest message. Sessions left at the bottom continue following new output. Use **Scroll to bottom** to return to the live edge. Positions are kept in this Desktop installation's local storage; they are not synchronized through the backend.
|
||||
- **Find in page** — press **Cmd/Ctrl+F** to open a find bar that searches the rendered chat transcript. Enter / Shift+Enter (or Cmd/Ctrl+G / Cmd/Ctrl+Shift+G while the bar is open) step through matches; Esc closes it.
|
||||
|
||||
Async cron and delegation completions keep a compact timeline label and render the result body (including job output) as Markdown. Task instructions and delivery envelopes are not shown as report content.
|
||||
|
||||
Reference in New Issue
Block a user