Files
apes-sidebar/tests/session-root-poll.spec.tsx
T
Menghuan1918 43742be658 perf(client): 每 tab 轮询收敛为按会话共享,keepMounted 加上界
v0.25 起原生 tab 一律 keepMounted:每个访问过的 body 都是永久的,于是
useSessionRoot 的 5s 轮询、目录 watch 的 socket、侧聊推送都按「挂载过的页签数」
永久复制。真机实测(4 个访问过的 tab、15s 空闲):活着的 5s 表 5 条、
session.cwd 请求 15 次;宿主那个解析器每次未命中要 spawn git 并回扫 4000 条事件。

- use-session-root:重写为模块级按会话引用计数的 store——一条 5s 表,只在 ≥1 个
  可见订阅者时存在;页面隐藏停表;恢复可见/聚焦/取消 park 立刻补刷一次;focus 与
  refresh-files 监听全 store 一份;parked body 保留上次答案。
- 消费点传真实可见性:native body 用 nativeTab.visible,壳用 bottomOpen。
- FileTree/use-dir-watch:已有的 visible 接进目录 watch——parked 或展开集为空时不建
  socket、不重列,恢复时重连并强制补刷一次(宿主按连接持有 ≤64 个 fs.watch 句柄)。
- use-sidechat-push/SideChatView:订阅按可见性门控,lastThreadBySession 加 LRU 并
  合并 localStorage 写入。
- state.bySession 加 LRU 32(当前会话永不淘汰,淘汰前先落盘),getSessionStates()
  不再每次整份复制(syncExpanded 原先每次 store notify 都 O(会话数) 复制),
  新增定向 getSessionState(id);FileTree 的 appsCacheRef 加上界。
2026-10-15 23:05:26 +08:00

223 lines
8.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* The shared session-root store's OWNERSHIP contract.
*
* Every body of every native tab type calls `useSessionRoot`, and the host
* keeps every visited tab body mounted. A per-hook 5 s poller therefore meant
* one `POST /sidebar/api/session.cwd` per live body per tick, and each of
* those lands in the host's `activeWorktreeRootOf` (9.6–44.7 ms and up to four
* real `git` spawns on a cache miss, whose TTL is shorter than this cadence).
* Four behaviours are pinned:
*
* - ONE POLLER: three visible bodies on one session share a single timer and
* issue one request per interval, and the store owns exactly one
* `window.focus` listener however many bodies mount.
* - PARKED IS SILENT: a parked body (`visible: false`) issues nothing, the
* timer stops when the last visible subscriber leaves, and the parked body
* keeps the answer it already resolved.
* - IMMEDIATE RETURN: becoming visible again refreshes at once instead of
* waiting for the next tick.
* - PER SESSION: two sessions get one poller each with no cross-talk, and
* releasing one leaves the other polling.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createElement, type ReactNode } from 'react'
import { act } from 'react-dom/test-utils'
const { sessionCwd } = vi.hoisted(() => ({ sessionCwd: vi.fn() }))
vi.mock('../src/client/api.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
return { ...actual, api: { ...actual.api, sessionCwd } }
})
import { renderRoot, setupReactAct } from './test-utils.ts'
import { useSessionRoot } from '../src/client/use-session-root.ts'
setupReactAct()
type Ctx = Parameters<typeof useSessionRoot>[0]
/**
* The one feed the hook reads: the session list, whose summary cwd is the
* fallback behind the host's answer. `getSnapshot` returns ONE stable object —
* a fresh one per call would make `useSyncExternalStore` re-render forever.
*/
function fakeContext(): Ctx {
const listeners = new Set<() => void>()
const snapshot = { byId: { shared: { cwd: '/summary/shared' } } as Record<string, { cwd: string }> }
return {
sessions: {
list: {
subscribe: (listener: () => void) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
},
getSnapshot: () => snapshot,
},
},
} as unknown as Ctx
}
/** Renders the resolved root, so the parked-keeps-its-answer case is visible. */
function Probe(props: { ctx: Ctx; sessionId: string; visible?: boolean }): ReactNode {
const cwd = useSessionRoot(props.ctx, props.sessionId, { visible: props.visible })
return createElement('span', null, cwd ?? '')
}
/** Three bodies on one session (the native tab stack the host keeps mounted). */
function bodies(ctx: Ctx, sessionId: string, count: number, visible?: boolean): ReactNode {
return createElement(
'div',
null,
...Array.from({ length: count }, (_, index) =>
createElement(Probe, { key: index, ctx, sessionId, visible })),
)
}
/** Let the store's in-flight request settle (inside act — it notifies React). */
async function flush(): Promise<void> {
await act(async () => {
await Promise.resolve()
await Promise.resolve()
})
}
/** Advance the fake clock, letting the store's promises settle inside act. */
async function tick(ms: number): Promise<void> {
await act(async () => { await vi.advanceTimersByTimeAsync(ms) })
}
let mounted: ReturnType<typeof renderRoot> | null = null
afterEach(() => {
mounted?.unmount()
mounted = null
sessionCwd.mockReset()
vi.useRealTimers()
})
describe('the shared session root store', () => {
it('runs ONE poller (and one focus listener) for three visible bodies on one session', async () => {
vi.useFakeTimers()
sessionCwd.mockResolvedValue({ cwd: '/work/shared' })
const ctx = fakeContext()
// The store attaches its window listeners on the first slot of the file,
// so count the DELTA: three bodies must add at most one focus listener
// (the old shape added one per mounted hook).
const spy = vi.spyOn(window, 'addEventListener')
try {
const before = spy.mock.calls.filter(([type]) => type === 'focus').length
mounted = renderRoot(bodies(ctx, 'shared', 3))
await tick(0)
await flush()
// One request for the first visible body, not one per body.
expect(sessionCwd).toHaveBeenCalledTimes(1)
expect(sessionCwd).toHaveBeenCalledWith({ sessionId: 'shared' })
const after = spy.mock.calls.filter(([type]) => type === 'focus').length
expect(after - before).toBeLessThanOrEqual(1)
// The 5 s cadence is the store's, not each body's.
await tick(5_000)
await flush()
expect(sessionCwd).toHaveBeenCalledTimes(2)
await tick(5_000)
await flush()
expect(sessionCwd).toHaveBeenCalledTimes(3)
expect(mounted.container.textContent).toBe('/work/shared/work/shared/work/shared')
} finally {
spy.mockRestore()
}
})
it('issues nothing for a parked body and stops the timer when the last visible one leaves', async () => {
vi.useFakeTimers()
sessionCwd.mockResolvedValue({ cwd: '/work/parked' })
const ctx = fakeContext()
const tree = (visible: boolean): ReactNode => createElement(Probe, { ctx, sessionId: 'parked', visible })
mounted = renderRoot(tree(false))
await tick(0)
await flush()
expect(sessionCwd).toHaveBeenCalledTimes(0)
// Ten minutes parked: no tick, no request.
await tick(600_000)
expect(sessionCwd).toHaveBeenCalledTimes(0)
mounted.rerender(tree(true))
await tick(0)
await flush()
expect(sessionCwd).toHaveBeenCalledTimes(1)
await tick(5_000)
await flush()
expect(sessionCwd).toHaveBeenCalledTimes(2)
// Parking the last visible body takes the timer with it...
mounted.rerender(tree(false))
await tick(600_000)
expect(sessionCwd).toHaveBeenCalledTimes(2)
// ...and the parked body keeps the root it resolved while visible.
expect(mounted.container.textContent).toBe('/work/parked')
})
it('refreshes immediately once when a body becomes visible again', async () => {
vi.useFakeTimers()
sessionCwd.mockResolvedValue({ cwd: '/work/flip' })
const ctx = fakeContext()
const tree = (visible: boolean): ReactNode => createElement(Probe, { ctx, sessionId: 'flip', visible })
mounted = renderRoot(tree(false))
await tick(60_000)
expect(sessionCwd).toHaveBeenCalledTimes(0)
// Un-parked: one immediate refresh, no waiting for the next 5 s tick.
mounted.rerender(tree(true))
await tick(0)
expect(sessionCwd).toHaveBeenCalledTimes(1)
await flush()
expect(mounted.container.textContent).toBe('/work/flip')
// And the cadence starts from that moment.
await tick(4_000)
expect(sessionCwd).toHaveBeenCalledTimes(1)
await tick(1_000)
await flush()
expect(sessionCwd).toHaveBeenCalledTimes(2)
})
it('keeps one poller per session, without cross-talk', async () => {
vi.useFakeTimers()
sessionCwd.mockImplementation((scope: { sessionId: string }) =>
Promise.resolve({ cwd: `/work/${scope.sessionId}` }))
const ctx = fakeContext()
// A stable tree shape: dropping session A's body must not remount session
// B's (a remount would legitimately re-fetch, which is not what this case
// is about).
const both = (withA: boolean): ReactNode => createElement(
'div',
null,
withA ? createElement(Probe, { ctx, sessionId: 'iso-a' }) : null,
createElement(Probe, { ctx, sessionId: 'iso-b' }),
)
mounted = renderRoot(both(true))
await tick(0)
await flush()
expect(sessionCwd.mock.calls.map(([scope]) => scope.sessionId).sort()).toEqual(['iso-a', 'iso-b'])
expect(mounted.container.textContent).toBe('/work/iso-a/work/iso-b')
// One tick each, not four (two sessions x one body each).
await tick(5_000)
await flush()
expect(sessionCwd).toHaveBeenCalledTimes(4)
// Releasing one session leaves the other's timer alone.
mounted.rerender(both(false))
await tick(5_000)
await flush()
const perSession = (id: string): number =>
sessionCwd.mock.calls.filter(([scope]) => scope.sessionId === id).length
expect(perSession('iso-a')).toBe(2)
expect(perSession('iso-b')).toBe(3)
// The dropped body's session is not re-asked, and its neighbour still is.
expect(mounted.container.textContent).toBe('/work/iso-b')
})
})