diff --git a/src/client/JobsDrawer.tsx b/src/client/JobsDrawer.tsx index 8e1b870a..b1483b42 100644 --- a/src/client/JobsDrawer.tsx +++ b/src/client/JobsDrawer.tsx @@ -18,7 +18,7 @@ * Every control is a host primitive (Button / Tag / Switch / StateDot / * TerminalBlock). */ -import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { Button, IconChevronUpOutlineRegular, IconCopyOutlineRegular, IconStopFillRegular, StateDot, Switch, Tag, TerminalBlock, type TagTone, @@ -41,6 +41,63 @@ import css from './tasks-graph.module.css' const JOB_KILL_ARM_MS = 3000 /** The agent count at which the drawer starts collapsed. */ export const JOBS_DRAWER_COLLAPSE_AT = 8 +/** The cadence of a live row's elapsed text. */ +const ELAPSED_TICK_MS = 1_000 + +/** + * Whether the PAGE is hidden (a background browser tab). The drawer's clock + * must not tick for a document nobody is looking at, and it must show the + * truth the moment the page comes back — hence a subscription rather than a + * one-shot read. + */ +function usePageHidden(): boolean { + const [hidden, setHidden] = useState(() => typeof document !== 'undefined' && document.hidden === true) + useEffect(() => { + if (typeof document === 'undefined') return undefined + const sync = (): void => { setHidden(document.hidden === true) } + document.addEventListener('visibilitychange', sync) + return () => { document.removeEventListener('visibilitychange', sync) } + }, []) + return hidden +} + +/** + * One live row's elapsed text. The clock lives HERE — in the span it prints — + * and not in the drawer: `setNow(Date.now())` in the drawer handed React a new + * value every second, so the whole row list was rebuilt once per tick (and a + * parked Tasks tab kept doing it). A memoized span that owns its own second + * re-renders one text node per tick instead, and creates no timer at all while + * the row is settled, the drawer is collapsed (nothing renders it) or the page + * is not really on screen. Leaving and re-entering visibility re-reads the + * clock, so the elapsed time shown on return is current, not the value frozen + * when the tab was parked. + */ +const LiveElapsed = memo(function LiveElapsed(props: { + /** Epoch ms the job started. */ + startedAt: number + /** Settlement time; the duration is final once it is present. */ + finishedAt: number | undefined + /** Whether the registry still holds the job open (drives the clock). */ + live: boolean + /** Whether the page is on screen (a parked tab runs no timer). */ + visible: boolean +}): ReactNode { + const { startedAt, finishedAt, live, visible } = props + const running = live && visible + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + if (!running) return undefined + // The pause may have been long: read the clock before the first tick. + setNow(Date.now()) + const timer = window.setInterval(() => { setNow(Date.now()) }, ELAPSED_TICK_MS) + return () => { window.clearInterval(timer) } + }, [running]) + // The settled expression mirrors the drawer's own: a live row measures from + // now, a settled one from its settlement time (its start when it never + // settled), so a stopped job's duration never keeps growing. + const elapsed = (live ? now : finishedAt ?? startedAt) - startedAt + return <>{formatJobDuration(elapsed, t)} +}) /** The Tag tone of one job status. */ function jobTone(job: SidebarJobView): TagTone { @@ -62,10 +119,14 @@ export interface JobsDrawerProps { onOpenOutput(row: TreeJob, anchor: HTMLElement): void /** The job whose output popover is currently open (row highlight). */ openJobId?: string + /** Whether the page hosting the drawer is really on screen (the native tab's + * own `visible`). Omitted = assume it is: a parked Tasks tab must not keep a + * per-second clock running. */ + visible?: boolean } export function JobsDrawer(props: JobsDrawerProps): ReactNode { - const { rows, agentCount, jobs, onOpenOutput, openJobId } = props + const { rows, agentCount, jobs, onOpenOutput, openJobId, visible = true } = props const autoOpen = agentCount < JOBS_DRAWER_COLLAPSE_AT /** Manual override; undefined = follow the auto rule. */ const [manualOpen, setManualOpen] = useState(undefined) @@ -76,7 +137,9 @@ export function JobsDrawer(props: JobsDrawerProps): ReactNode { const [armedId, setArmedId] = useState(undefined) const [killingId, setKillingId] = useState(undefined) const [killErrorId, setKillErrorId] = useState(undefined) - const [now, setNow] = useState(() => Date.now()) + /** The page's own visibility: the elapsed clocks below are gated on it. */ + const pageHidden = usePageHidden() + const ticking = visible && !pageHidden const liveCount = useMemo( () => rows.reduce((count, row) => count + (isJobLive(row.job) ? 1 : 0), 0), @@ -94,13 +157,6 @@ export function JobsDrawer(props: JobsDrawerProps): ReactNode { return () => { window.clearTimeout(timer) } }, [armedId]) - useEffect(() => { - if (liveCount === 0) return - setNow(Date.now()) - const timer = window.setInterval(() => { setNow(Date.now()) }, 1_000) - return () => { window.clearInterval(timer) } - }, [liveCount]) - const kill = useCallback(async (row: TreeJob): Promise => { if (jobs === undefined) return setKillingId(row.job.id) @@ -145,13 +201,15 @@ export function JobsDrawer(props: JobsDrawerProps): ReactNode { const armed = armedId === job.id const killing = killingId === job.id const killFailed = killErrorId === job.id - const elapsed = live - ? now - job.startedAt - : (job.finishedAt ?? job.startedAt) - job.startedAt - const secondary = [ + // Everything here is row-stable: the ticking duration is the + // elapsed SPAN's own state (see LiveElapsed), so a clock tick never + // rebuilds this list. The accessible name deliberately carries the + // stable half only — a name that changes every second is noise for + // a screen reader, and keeping it here would drag the whole row + // back into the per-second render. + const meta = [ ...(multiOwner ? [row.ownerTitle] : []), ...(job.detail !== undefined && job.detail !== '' ? [job.detail] : []), - formatJobDuration(elapsed, t), ].filter(Boolean).join(' · ') return (
{ onOpenOutput(row, event.currentTarget) }} > @@ -172,7 +230,15 @@ export function JobsDrawer(props: JobsDrawerProps): ReactNode { {job.kind} {job.label} {jobStatusLabel(job.status, t)} - {secondary} + + {meta === '' ? '' : `${meta} · `} + + {/* The terminate column is reserved by EVERY row (settled ones diff --git a/src/client/SubagentView.tsx b/src/client/SubagentView.tsx index 14ba865a..39899c2a 100644 --- a/src/client/SubagentView.tsx +++ b/src/client/SubagentView.tsx @@ -29,7 +29,7 @@ * descendant count is mono micro-type, and the canvas / tree / board / drawer * own their own chrome. */ -import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { useSyncExternalStore } from 'react' import { Button, IconRefreshOutlineRegular, @@ -70,6 +70,7 @@ import { TeamBoard } from './TeamBoard.tsx' import { TaskWindow } from './TaskWindow.tsx' import type { SidebarStore } from './state.ts' import type { WorkflowRunView } from '../workflow-runs.ts' +import type { ProcessActivitySummary } from '../process-activity.ts' import legacy from './SubagentView.module.css' /** Poll cadence of the live "last text + tool call" lines while a child runs. */ @@ -77,6 +78,77 @@ const POLL_MS = 3000 /** Poll cadence of the workflow-run and team views while the page is visible. */ const TELEMETRY_POLL_MS = 5000 +/** The empty live map / run list: ONE identity, so a reset that changes + * nothing (or a poll that returns nothing) never re-renders the page. */ +const NO_LIVE: Readonly> = {} +const NO_RUNS: readonly WorkflowRunView[] = [] + +/** + * Whether two activity summaries say the same thing. Every field the cards + * read is compared — the activity line (`running`, `preparing`, + * `runningDetail`) and the settled tally (`counts`) — and nothing else, so a + * re-serialized but equal summary is not a change. + */ +function sameSummary(left: ProcessActivitySummary | undefined, right: ProcessActivitySummary | undefined): boolean { + if (left === right) return true + if (left === undefined || right === undefined) return false + if (left.running !== right.running || left.preparing !== right.preparing + || left.runningDetail !== right.runningDetail || left.counts.length !== right.counts.length) return false + return left.counts.every((entry, index) => { + const other = right.counts[index]! + return entry.kind === other.kind && entry.count === other.count + }) +} + +/** Whether two children's live views say the same thing (see the card render + * sites for the fields: the running flag, the detail text, the summary). */ +function sameLiveView(left: SidebarChildLiveView | undefined, right: SidebarChildLiveView | undefined): boolean { + if (left === right) return true + if (left === undefined || right === undefined) return false + return left.running === right.running && left.text === right.text + && left.lastEventTime === right.lastEventTime && sameSummary(left.summary, right.summary) +} + +/** + * Whether two `subagents.live` answers are the same map. The route answers with + * a FRESH object graph on every tick; publishing it unconditionally re-derived + * the whole agent tree and the graph layout every 3 s although nothing had + * changed. + */ +function sameLive( + left: Readonly>, + right: Readonly>, +): boolean { + if (left === right) return true + const keys = Object.keys(left) + if (keys.length !== Object.keys(right).length) return false + return keys.every(key => Object.prototype.hasOwnProperty.call(right, key) && sameLiveView(left[key], right[key])) +} + +/** Whether two workflow-run answers are the same list (runs → phases → + * members, field by field). */ +function sameRuns(left: readonly WorkflowRunView[], right: readonly WorkflowRunView[]): boolean { + if (left === right) return true + if (left.length !== right.length) return false + return left.every((run, index) => { + const other = right[index]! + if (run.runId !== other.runId || run.name !== other.name + || run.originSessionId !== other.originSessionId || run.status !== other.status + || run.stopReason !== other.stopReason || run.startedSeq !== other.startedSeq + || run.startedAt !== other.startedAt || run.finishedAt !== other.finishedAt + || run.phases.length !== other.phases.length) return false + return run.phases.every((phase, phaseIndex) => { + const peer = other.phases[phaseIndex]! + if (phase.title !== peer.title || phase.members.length !== peer.members.length) return false + return phase.members.every((member, memberIndex) => { + const mate = peer.members[memberIndex]! + return member.seq === mate.seq && member.label === mate.label && member.phase === mate.phase + && member.childId === mate.childId && member.outcome === mate.outcome + }) + }) + }) +} + /** * The workspace face's "show this conversation" verb. DSH moved child and * session navigation off `ISessions` onto the service that owns the @@ -102,15 +174,32 @@ function useSubagentLive( rootId: string | undefined, active: boolean, ): Readonly> { - const [live, setLive] = useState>({}) + const [live, setLive] = useState>>(NO_LIVE) + /** + * What has been PUBLISHED. An equal answer must not reach React at all: even + * handing `setLive` an updater that returns the previous state lets React + * render the component once ("React may still need to render that specific + * component again before bailing out"), and one render re-derives the whole + * tasks model and the graph layout hanging off it. + */ + const published = useRef>>(NO_LIVE) // A new tree must never inherit another root's live previews. - useEffect(() => { setLive({}) }, [rootId]) + useEffect(() => { + published.current = NO_LIVE + setLive(current => (Object.keys(current).length === 0 ? current : NO_LIVE)) + }, [rootId]) const poll = useCallback(async (signal: AbortSignal): Promise => { if (rootId === undefined) return const result = await api.subagentsLive(rootId, signal) - if (!signal.aborted) setLive(result.live) + if (signal.aborted) return + // The route answers with FRESH objects every tick; publishing them as-is + // re-derived the agent tree (and the graph layout) every 3 s although + // nothing had changed. + if (sameLive(published.current, result.live)) return + published.current = result.live + setLive(current => (sameLive(current, result.live) ? current : result.live)) }, [rootId]) usePolling(rootId !== undefined && active, poll, { intervalMs: POLL_MS, @@ -123,12 +212,22 @@ function useSubagentLive( /** The folded workflow runs of the tree (poll-driven; empty when none). */ function useWorkflowRuns(rootId: string | undefined, active: boolean): readonly WorkflowRunView[] { - const [runs, setRuns] = useState([]) - useEffect(() => { setRuns([]) }, [rootId]) + const [runs, setRuns] = useState(NO_RUNS) + const published = useRef(NO_RUNS) + useEffect(() => { + published.current = NO_RUNS + setRuns(current => (current.length === 0 ? current : NO_RUNS)) + }, [rootId]) const poll = useCallback(async (signal: AbortSignal): Promise => { if (rootId === undefined) return const result = await api.workflowsList(rootId, signal) - if (!signal.aborted) setRuns(result.runs) + if (signal.aborted) return + // Same identity rule as the live map: the run list is a model dependency, + // so an equal answer (the common case — a run's phases only move when an + // event commits) must publish nothing. + if (sameRuns(published.current, result.runs)) return + published.current = result.runs + setRuns(current => (sameRuns(current, result.runs) ? current : result.runs)) }, [rootId]) usePolling(rootId !== undefined && active, poll, { intervalMs: TELEMETRY_POLL_MS, @@ -677,6 +776,10 @@ export function SubagentView(props: { jobs={treeJobs.jobs} observed={observedJob} openJobId={popover?.kind === 'job' ? popover.jobId : undefined} + // The page's own visibility, exactly as the pollers read it: a parked + // Tasks tab keeps the drawer's rows (they are already rendered) but + // runs no per-second clock. + visible={active} onOpenOutput={(row, anchor) => { setPopover(popover?.kind === 'job' && popover.jobId === row.job.id ? null diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index bed2573e..1a87dd11 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -63,6 +63,39 @@ type ViewMode = 'preview' | 'edit' const previewScrollMemory = new Map() const previewScrollKey = (scope: { sessionId: string }, path: string): string => `${scope.sessionId}::${path}` +/** + * How many documents' preview positions are remembered. Since v0.25 every + * visited native tab body stays mounted (the host has no LRU), so this map + * would otherwise grow with every file the session ever previewed; past the + * cap the least recently written document is forgotten and its preview opens + * at the top again — a cosmetic loss, never a wrong document. + */ +export const PREVIEW_SCROLL_CAP = 64 + +/** + * Remember one document's preview offset. The write moves the key to the back + * of the eviction order, so the document forgotten past the cap is the one + * that has gone longest without a scroll. + * + * @param scope - the viewer's scope (its session id is part of the key). + * @param path - the document's absolute path. + * @param top - the preview container's `scrollTop`. + */ +export function rememberPreviewScroll(scope: { sessionId: string }, path: string, top: number): void { + const key = previewScrollKey(scope, path) + previewScrollMemory.delete(key) + previewScrollMemory.set(key, top) + for (const stale of previewScrollMemory.keys()) { + if (previewScrollMemory.size <= PREVIEW_SCROLL_CAP) break + previewScrollMemory.delete(stale) + } +} + +/** The remembered offset of one document (0 = none: open it at the top). */ +export function previewScrollOf(scope: { sessionId: string }, path: string): number { + return previewScrollMemory.get(previewScrollKey(scope, path)) ?? 0 +} + /** Whether two spellings are the SAME document — byte-equal, or equal once * line endings are normalized CRLF/CR → LF. Line endings are not content: * CodeMirror keeps every document with `\n` endings whatever the file used, @@ -169,7 +202,7 @@ export function TextEditor(props: FileViewerProps) { * element, so capture it on scroll and restore after each remount. Seeded * from the module-level per-file memory so a full viewer rebuild * (save-then-switch-to-preview reload) also keeps the position. */ - const previewScrollRef = useRef(previewScrollMemory.get(previewScrollKey(scope, path)) ?? 0) + const previewScrollRef = useRef(previewScrollOf(scope, path)) /** True while a programmatic restore is in flight; raw scroll events caused * by the restore (or by the browser clamping a collapsed reload container * to 0) must not overwrite the remembered position. */ @@ -235,7 +268,7 @@ export function TextEditor(props: FileViewerProps) { // A different file switches the remembered preview scroll position to that // file's own entry (first open: none, so the preview starts at the top). useEffect(() => { - previewScrollRef.current = previewScrollMemory.get(previewScrollKey(scope, path)) ?? 0 + previewScrollRef.current = previewScrollOf(scope, path) }, [scope, path]) // Create the CodeMirror editor once the content is loaded. The view owns @@ -879,7 +912,7 @@ export function TextEditor(props: FileViewerProps) { const el = event.currentTarget if (!restoringRef.current && el.scrollHeight > el.clientHeight) { previewScrollRef.current = el.scrollTop - previewScrollMemory.set(previewScrollKey(scope, path), el.scrollTop) + rememberPreviewScroll(scope, path, el.scrollTop) } if (!anchorThrottleRef.current) { anchorThrottleRef.current = true diff --git a/src/client/changes/GitLens.tsx b/src/client/changes/GitLens.tsx index ea2792b6..253e9a53 100644 --- a/src/client/changes/GitLens.tsx +++ b/src/client/changes/GitLens.tsx @@ -95,6 +95,55 @@ function errorMessage(reason: unknown): string { return reason instanceof Error ? reason.message : String(reason) } +/** + * Whether two inventory listings say the same thing. Every listing pass answers + * with a fresh array of fresh rows, so identity alone would republish on each + * poll; a field-by-field compare is what lets an unchanged silent tick stay + * silent (see `runOnce`). + */ +function sameWorktrees(left: readonly GitWorktree[], right: readonly GitWorktree[]): boolean { + if (left === right) return true + if (left.length !== right.length) return false + return left.every((entry, index) => { + const other = right[index]! + return entry.path === other.path && entry.branch === other.branch + && entry.current === other.current && entry.changes === other.changes + }) +} + +/** + * How many scopes' commit drafts are remembered. The lens is a kept-mounted tab + * body, so this record lives for the page: without a bound, a session that + * walked through many projects would pin one message per project forever. + */ +export const COMMIT_DRAFT_CAP = 32 + +/** + * Write one scope's draft into the record, remembering at most + * {@link COMMIT_DRAFT_CAP} scopes. Re-writing a key moves it to the back, so + * the draft evicted past the cap is the scope typed into longest ago — a typed + * message for another project is never what a commit here submits (the record + * is keyed by scope, and `commit()` reads only its own key). + * + * @param prev - the current record (never mutated). + * @param key - the scope key (session + cwd). + * @param text - the draft (`''` = cleared; the key stays, so it reads back as + * an empty box rather than as a missing one). + * @returns the next record. + */ +export function withCommitDraft( + prev: Record, + key: string, + text: string, +): Record { + const next: Record = { ...prev } + delete next[key] + next[key] = text + const keys = Object.keys(next) + for (const stale of keys.slice(0, Math.max(0, keys.length - COMMIT_DRAFT_CAP))) delete next[stale] + return next +} + /** The pending destructive action (discard / revert / cherry-pick), gated by a confirm dialog. */ interface ConfirmState { title: string @@ -346,12 +395,13 @@ export function GitLens(props: GitLensProps) { * and a staged row, so a draft typed against another project would submit * verbatim under this one. Keyed rather than cleared on a scope swap, so a * kept-mounted tab shows a conversation its own message when it comes back - * (#712). */ + * (#712) — bounded to the newest {@link COMMIT_DRAFT_CAP} scopes, because + * that tab lives for the whole page. */ const [commitDrafts, setCommitDrafts] = useState>({}) const draftKey = `${scope.sessionId}\u0000${scope.cwd ?? ''}` const commitMsg = commitDrafts[draftKey] ?? '' const writeDraft = (text: string): void => { - setCommitDrafts(prev => ({ ...prev, [draftKey]: text })) + setCommitDrafts(prev => withCommitDraft(prev, draftKey, text)) } const [busy, setBusy] = useState(false) /** Whether a commit-message suggestion is being generated host-side (the @@ -503,7 +553,13 @@ export function GitLens(props: GitLensProps) { return } if (signal?.aborted === true || generation !== scopeGen.current) return - setWorktrees(listed) + // Republish the inventory only when it really says something new. Handing + // React a fresh array (and fresh rows) on every 30 s tick re-rendered the + // whole lens — the change trees included — although nothing had changed, + // which is exactly what the "silent" tick below was supposed to avoid. + // Keeping the previous identity when the listing is equal makes the tick + // silent; a new linked checkout or a moved change count still lands. + setWorktrees(previous => (sameWorktrees(previous, listed) ? previous : listed)) const current = listed.find(entry => entry.current) const stillListed = chosenPathRef.current !== undefined && listed.some(entry => entry.path === chosenPathRef.current) diff --git a/src/client/markdown-navigation.ts b/src/client/markdown-navigation.ts index b2d2ab2b..b74cc391 100644 --- a/src/client/markdown-navigation.ts +++ b/src/client/markdown-navigation.ts @@ -472,6 +472,28 @@ function anchorKey(sessionId: string, cwd: string | undefined, path: string): st return `${sessionId}::${normalizeLocalPath(absolute).replace(/\\/g, '/')}` } +/** + * Drop every parked fragment whose TTL ran out. + * + * The TTL is already honoured when a fragment is TAKEN, but a fragment parked + * for a document the reader never opens is never taken — it would sit in the + * map for the page's lifetime (since v0.25 every visited native tab body stays + * mounted, and every cross-file link click parks one entry). Sweeping on WRITE + * is what bounds it: a write is the only event that can add an entry. + * + * @returns how many expired entries were dropped. + */ +export function sweepPendingAnchors(): number { + const now = Date.now() + let dropped = 0 + for (const [key, entry] of pendingAnchors) { + if (now - entry.at <= PENDING_TTL_MS) continue + pendingAnchors.delete(key) + dropped += 1 + } + return dropped +} + /** * Park the fragment a cross-file link wants to land on, for the target * document's own surface to take once it mounts. @@ -487,6 +509,7 @@ export function rememberMarkdownAnchor( fragment: string, ): void { if (fragment === '') return + sweepPendingAnchors() pendingAnchors.set(anchorKey(sessionId, cwd, path), { fragment, at: Date.now() }) } diff --git a/src/client/ops-stream.ts b/src/client/ops-stream.ts index 5be9401b..d4136c6c 100644 --- a/src/client/ops-stream.ts +++ b/src/client/ops-stream.ts @@ -37,7 +37,12 @@ * The stream record outlives its members (only the poller stops): a tab that * becomes visible again re-joins, the leader resumes from the persisted `seq` * cursor, and the missed delta is folded then — so a file the model rewrote - * while the tab was parked is still seen as touched. + * while the tab was parked is still seen as touched. What it does NOT do is + * live for the page: the record map is bounded and least-recently-joined + * first (see {@link STREAM_CAP}). A session evicted after that many newer ones + * re-joins as a FRESH stream, which re-baselines exactly like a page reload + * (see {@link pullStream}) — the only state a returner can lose, and only + * after the bound was actually reached. */ import { useCallback, useEffect, useState, useSyncExternalStore } from 'react' import type { SidebarSessionEvent } from '../context-types.ts' @@ -68,6 +73,17 @@ const IDLE_EVENT_WINDOW = 32 /** Touched paths remembered per session (oldest insertion evicted past this). */ const TOUCH_WINDOW = 256 +/** + * How many session records the store holds. The record already shrinks to what + * a re-join needs once its last member goes ({@link IDLE_EVENT_WINDOW} events + * plus the published touches), but the MAP itself was "alive for the page": + * every session an editor tab had ever watched kept its cursor, baseline and + * touch table forever. A session still inside this window resumes from its + * cursor and folds the delta it missed; the oldest record that nobody is + * watching is what a new mint evicts. + */ +const STREAM_CAP = 32 + /** The op kinds that changed a file's bytes. */ export type FileOpTouchKind = 'write' | 'edit' @@ -140,29 +156,46 @@ interface Stream { cwd: string | undefined } -/** Every session's stream, alive for the page (only its poller stops). */ +/** Every session's stream, bounded by {@link STREAM_CAP} (see `streamOf`). */ const streams = new Map() /** The stream record of one session, created on first use. */ function streamOf(sessionId: string): Stream { - let stream = streams.get(sessionId) - if (stream === undefined) { - stream = { - state: EMPTY_STATE, - listeners: new Set(), - members: new Set(), - leader: undefined, - seq: 0, - primed: false, - events: [], - published: new Set(), - cwd: undefined, + const existing = streams.get(sessionId) + if (existing !== undefined) return existing + // Bound the store before minting: a session nobody is watching is what goes. + // A record WITH members is never evicted — it owns the leader election and + // the members' published state — so the cap is soft while many sessions are + // genuinely open. + if (streams.size >= STREAM_CAP) { + for (const [key, candidate] of streams) { + if (candidate.members.size > 0) continue + streams.delete(key) + if (streams.size < STREAM_CAP) break } - streams.set(sessionId, stream) } + const stream: Stream = { + state: EMPTY_STATE, + listeners: new Set(), + members: new Set(), + leader: undefined, + seq: 0, + primed: false, + events: [], + published: new Set(), + cwd: undefined, + } + streams.set(sessionId, stream) return stream } +/** Move one session's record to the back of the eviction order (LRU). */ +function touchStream(sessionId: string, stream: Stream): void { + if (streams.get(sessionId) !== stream) return + streams.delete(sessionId) + streams.set(sessionId, stream) +} + /** Publish one delta's settled write/edit ops to every member of the stream. */ function publish(stream: Stream, ops: readonly FileOp[]): void { const revision = stream.state.revision + 1 @@ -243,6 +276,9 @@ export function useFileOpStream(scope: SessionScope, enabled: boolean): FileOpSt return } const stream = streamOf(sessionId) + // The session that just joined is the most recently used, so an ACTIVE + // session is never the record a later mint evicts. + touchStream(sessionId, stream) const member: Member = { lead: (value: boolean) => { setLeading(value) } } stream.members.add(member) if (stream.leader === undefined) { diff --git a/src/client/ui/git-status.ts b/src/client/ui/git-status.ts index 7eb6dc13..463958d0 100644 --- a/src/client/ui/git-status.ts +++ b/src/client/ui/git-status.ts @@ -41,6 +41,24 @@ * Bumping the version on every tick re-rendered every consumer — the file * tree's rows included — once per cadence for no reason, which is what the * snapshot identity check above exists to prevent. + * + * Retention: remembering a key is not a lease on memory. The last consumer of + * a slot going away (unmount, a parked tab, a scope change) DROPS the slot — + * snapshot, index and listeners and all — so a long session that walks through + * files, worktrees and cwds cannot grow the map for the page's lifetime. Since + * v0.25 every visited native tab body stays mounted, so there is no host-side + * teardown that would have bounded this for us. + * + * Dropping is invisible to a consumer that still carries the slot object: its + * next render re-mints the key (`slotOf`) and `retain` re-registers that same + * object, so the next retain performs a FRESH fetch rather than serving a + * stale answer (and never mints a second slot for one key — two slots would + * mean two pollers). A slot with a fetch in flight is never dropped mid-flight + * (the answer has to land somewhere); it goes when that fetch settles. As a + * second bound the registry is capped at {@link SLOT_CAP} keys, because a + * consumer that mounts while invisible mints a slot it never retains and never + * releases — eviction only ever takes a slot with no retained consumer and no + * fetch in flight. */ import { useCallback, useEffect, useSyncExternalStore } from 'react' import { api, type GitLineCounts, type GitStatusResult, type SessionScope } from '../api.ts' @@ -224,6 +242,38 @@ const TIER_FACTORS: readonly (number | null)[] = [1, 2, 6, null] const slots = new Map() +/** + * The registry's hard ceiling. The primary rule is release-driven (see + * {@link release}); this cap is the backstop for keys nobody ever released — + * a consumer that mounts while invisible mints its slot without retaining it, + * and only the cap bounds that path. Eviction never touches a slot a consumer + * holds or one with a fetch in flight, so the cap is soft while many slots are + * genuinely live. + */ +const SLOT_CAP = 256 + +/** Whether nothing depends on this slot: no consumer holds the answer and no + * fetch is in flight. */ +function evictable(slot: Slot): boolean { + return slot.visible === 0 && !slot.running +} + +/** Drop one slot from the registry. Identity-checked, so a key that was + * re-minted meanwhile keeps its live entry. */ +function forget(slot: Slot): void { + if (slots.get(slot.key) === slot) slots.delete(slot.key) +} + +/** Make room for one key about to be minted: evict the oldest slots nobody + * holds while the registry is at {@link SLOT_CAP}. Map order is mint order. */ +function trimSlots(): void { + if (slots.size < SLOT_CAP) return + for (const slot of slots.values()) { + if (slots.size < SLOT_CAP) break + if (evictable(slot)) forget(slot) + } +} + /** The automatic cadence of one slot; `null` = no timer (tier 3). */ function intervalOf(slot: Slot): number | null { const factor = TIER_FACTORS[slot.tier] ?? null @@ -235,6 +285,9 @@ function slotOf(scope: SessionScope, worktree: string | undefined): Slot { const key = `${sessionId}\u0000${cwd ?? ''}\u0000${repoRoot ?? ''}\u0000${worktree ?? ''}` const existing = slots.get(key) if (existing !== undefined) return existing + // Bounded before minting: a key no consumer ever released must not push the + // registry past the cap (see SLOT_CAP). + trimSlots() const slot: Slot = { key, sessionId, cwd, repoRoot, worktree, snapshot: null, loading: false, error: false, version: 0, generation: 0, @@ -315,6 +368,9 @@ function fetchSlot(slot: Slot): void { slot.pending = false fetchSlot(slot) } + // The last consumer may have left while this fetch was in flight: the + // slot is dropped now that nothing is pending on it any more. + if (evictable(slot)) forget(slot) }) } @@ -343,6 +399,10 @@ function reschedule(slot: Slot): void { } function retain(slot: Slot, poll: boolean): void { + // Re-register a slot the store forgot while nobody held it: the consumer + // that still carries this object must keep its key (minting a second slot + // for it would mean a second poller on the same scope). + if (!slots.has(slot.key)) slots.set(slot.key, slot) slot.visible += 1 if (poll) slot.pollers += 1 // The answer is fetched for the FIRST consumer whatever kind it is — a @@ -366,6 +426,11 @@ function release(slot: Slot, poll: boolean): void { slot.index = null slot.indexSource = null notify(slot) + // …and drop the slot itself: nobody holds the answer, so the key must not + // be remembered for the rest of the page's life. A fetch in flight keeps + // the slot (its answer has to land somewhere) and the settle path drops it + // then. + if (!slot.running) forget(slot) } } diff --git a/tests/git-status-poll.spec.tsx b/tests/git-status-poll.spec.tsx index 6ad8f2fa..19bccc28 100644 --- a/tests/git-status-poll.spec.tsx +++ b/tests/git-status-poll.spec.tsx @@ -4,7 +4,7 @@ * One fetch here is `git status --untracked-files=all` plus two `--numstat` * diffs, so an automatic poll is real work — and it used to run every 2.5 s for * as long as any consumer was on screen, notified on every tick whether or not - * anything had changed. Four behaviours are pinned: + * anything had changed. Five behaviours are pinned: * * - OWNERSHIP: only a `poll: true` consumer starts the timer. A `poll: false` * consumer (the editor's gutter) reads the shared answer and refreshes on @@ -18,6 +18,11 @@ * - THE LADDER: the baseline is 30 s, a slow round trip drops the slot to * 60 s then 180 s, and a really slow one stops the automatic timer * altogether; a fast answer climbs straight back to the baseline. + * - RETENTION: a slot whose last consumer went away is forgotten, and the + * registry is capped, so a long session cannot pin one snapshot per scope + * it ever visited (v0.25's `keepMounted` means every visited tab body keeps + * walking new scopes). A retained consumer, or a fetch in flight, is never + * evicted. */ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' @@ -33,7 +38,7 @@ vi.mock('../src/client/api.ts', async (importOriginal) => { }) import { renderRoot, setupReactAct } from './test-utils.ts' -import { useGitStatus, type GitStatusView } from '../src/client/ui/git-status.ts' +import { invalidateGitStatus, useGitStatus, type GitStatusView } from '../src/client/ui/git-status.ts' setupReactAct() @@ -246,3 +251,83 @@ describe('the shared git status store cadence', () => { expect(gitStatus).toHaveBeenCalledTimes(1) }) }) + +describe('the shared git status store retention', () => { + /** + * The probe drives a scope that is HIDDEN first: a consumer that mounts while + * invisible mints its slot without ever retaining (and therefore never + * releases) it — the one path only the registry cap can bound. + */ + it('forgets a released slot instead of remembering every scope it ever saw', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(REPO) + // The file tree, the changes page and the editor's gutter mint one slot per + // scope (session + cwd + repo + worktree), and a kept-mounted tab keeps + // walking new scopes for the whole page. Forty of them, one session. + for (let index = 0; index < 40; index++) { + const probe = renderRoot(createElement(Probe, { + scope: { sessionId: 'prune', cwd: `/tmp/p${index}` }, + commits: { value: 0 }, + })) + await tick(0) + await flush() + probe.unmount() + } + expect(gitStatus).toHaveBeenCalledTimes(40) + + // Every consumer released, so the session has no live slot left. That is + // the observable probe: `invalidateGitStatus` re-reads the slots it still + // knows, so a store that remembered the released keys answers with forty + // further fetches (one per remembered scope) instead of none. + await act(async () => { invalidateGitStatus('prune') }) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(40) + }) + + it('re-fetches after the last consumer went away (the snapshot went with the slot)', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(REPO) + const scope = scopeFor('rejoin') + const commits: Counter = { value: 0 } + mounted = renderRoot(createElement(Probe, { scope, commits })) + await tick(0) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(1) + expect(latest?.snapshot).not.toBeNull() + + // Parked: the slot is released (and forgotten), so its snapshot is gone. + mounted.rerender(createElement(Probe, { scope, visible: false, commits })) + await flush() + expect(latest?.snapshot).toBeNull() + + // Coming back must read the truth again, not serve the parked answer. + mounted.rerender(createElement(Probe, { scope, commits })) + await tick(0) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(2) + expect(latest?.snapshot).not.toBeNull() + }) + + it('caps the registry for keys no consumer ever releases', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(REPO) + // 260 distinct hidden scopes of ONE session: each render mints a slot, none + // of them is retained (so nothing releases them) and none fetches. + for (let index = 0; index < 260; index++) { + renderRoot(createElement(Probe, { + scope: { sessionId: 'cap', cwd: `/tmp/c${index}` }, + visible: false, + commits: { value: 0 }, + })).unmount() + } + expect(gitStatus).not.toHaveBeenCalled() + + // The cap keeps at most 256 keys (the constant in ui/git-status.ts): the + // session-wide invalidate can therefore re-read at most that many. Without + // the cap this is 260 — one remembered slot per scope ever mounted. + await act(async () => { invalidateGitStatus('cap') }) + await flush() + expect(gitStatus.mock.calls.length).toBeGreaterThan(0) + expect(gitStatus.mock.calls.length).toBeLessThanOrEqual(256) + }) +}) diff --git a/tests/subagent-jobs-view.spec.tsx b/tests/subagent-jobs-view.spec.tsx index b48a9012..83363a4c 100644 --- a/tests/subagent-jobs-view.spec.tsx +++ b/tests/subagent-jobs-view.spec.tsx @@ -5,8 +5,9 @@ * background-jobs DRAWER — rows pushed by the HOST's client jobs service * (`ctx.jobs`, structurally faked here), output streamed for the one OPEN row * through `observe` (never the model's consuming cursor), the kill button - * needing a two-click confirm and going through the service, and the watch - * released while the page is hidden. + * needing a two-click confirm and going through the service, the watch + * released while the page is hidden, and the elapsed clock that ticks the text + * it prints WITHOUT rebuilding the row list (and not at all while parked). */ // @vitest-environment jsdom import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -23,6 +24,19 @@ import type { SidebarSubagentCatalogEntry, } from '../src/context-types.ts' +/** + * Counts JOBS-DRAWER renders. The real hook only attaches FLIP motion (inert + * under jsdom: there is no Web Animations API), and in the page's default graph + * mode the drawer is the ONLY caller — so a call is exactly one render of the + * component whose body maps the rows. "The row list was rebuilt" is therefore + * observable without a production test seam. + */ +const { drawerRenders } = vi.hoisted(() => ({ drawerRenders: vi.fn() })) + +vi.mock('../src/client/use-auto-animate.ts', () => ({ + useAutoAnimateRef: () => { drawerRenders() }, +})) + /** * A structurally faithful double of the host's client jobs service: a * subscribable snapshot (roster by watched session + observations), a @@ -335,6 +349,66 @@ describe('SubagentView background jobs', () => { unmount() }) + it('ticks the elapsed text without rebuilding the row list', async () => { + vi.useFakeTimers() + // Job times are absolute: put the clock just past `sleep 300`'s start. + vi.setSystemTime(5_000) + const store = makeStore(baseSnapshot()) + const { container, unmount } = await renderPage(store) + /** The live row's rendered duration (the row keeps its own clock). */ + const liveSeconds = (): number => { + const row = container.querySelector('[data-settled="false"]') + return Number(/(\d+)\s*秒/.exec(row?.textContent ?? '')?.[1] ?? Number.NaN) + } + expect(liveSeconds()).toBe(4) + const drawerRendersBefore = drawerRenders.mock.calls.length + + // One second later the clock ticks… + await act(async () => { await vi.advanceTimersByTimeAsync(1_000) }) + expect(liveSeconds()).toBe(5) + // …but only the text it prints re-render: the drawer's own render count is + // untouched, so the rows' map (and every other row with it) was never + // rebuilt. Rebuilding it once per second is what the 1 s `setNow` did. + expect(drawerRenders.mock.calls.length).toBe(drawerRendersBefore) + + // A settled row carries a FINAL duration and no clock of its own: its text + // is the same before and after a tick. + const settledText = (): string => + container.querySelector('[data-settled="true"]')?.textContent ?? '' + const settled = settledText() + await act(async () => { await vi.advanceTimersByTimeAsync(1_000) }) + expect(settledText()).toBe(settled) + unmount() + }) + + it('runs no elapsed clock while the Tasks page is parked', async () => { + vi.useFakeTimers() + vi.setSystemTime(5_000) + const store = makeStore(baseSnapshot()) + // `active: false` is the parked tab: its body stays mounted (the native tab + // is `keepMounted`), so the rows are on screen in the DOM but nobody is + // looking — no clock may run. + const { container, rerender } = await renderPage(store, false) + expect(container.textContent).toContain('sleep 300') + const parked = container.textContent ?? '' + const drawerRendersBefore = drawerRenders.mock.calls.length + await act(async () => { await vi.advanceTimersByTimeAsync(20_000) }) + expect(container.textContent).toBe(parked) + expect(drawerRenders.mock.calls.length).toBe(drawerRendersBefore) + + // Coming back on screen catches the text up at once (the clock is read + // before the first tick, not a second later). 20 s of parked time on a job + // started at 1 s with the clock at 5 s: 4 s + 20 s. + rerender(createElement(SubagentView, { + sessionId: 'root', + active: true, + ctx: makeCtx(store, undefined, jobsFake), + })) + await flushJobs() + const row = container.querySelector('[data-settled="false"]') + expect(Number(/(\d+)\s*秒/.exec(row?.textContent ?? '')?.[1] ?? Number.NaN)).toBe(24) + }) + it('survives the roster emptying while mounted (hook-order regression #300)', async () => { const store = makeStore(baseSnapshot()) const { container, unmount } = await renderPage(store) diff --git a/tests/subagent-live-polling.spec.tsx b/tests/subagent-live-polling.spec.tsx index bea0d7da..42904e5d 100644 --- a/tests/subagent-live-polling.spec.tsx +++ b/tests/subagent-live-polling.spec.tsx @@ -1,17 +1,38 @@ /** * Component-level regression for the Subagent page live preview polling: * one shared `subagents.live` request per refresh, never a per-child - * `subagents.history` call, and never a second in-flight request while a - * slow host is still answering. + * `subagents.history` call, never a second in-flight request while a slow host + * is still answering, and never a re-render for a tick that changed nothing. */ // @vitest-environment jsdom import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createElement } from 'react' +import { Profiler, createElement } from 'react' import { act } from 'react-dom/test-utils' -import { renderRoot } from './test-utils.ts' +import { renderRoot, setupReactAct } from './test-utils.ts' import { SubagentView } from '../src/client/SubagentView.tsx' import type { Context, SidebarSessionList } from '../src/context-types.ts' +setupReactAct() + +/** + * The tasks model is observed through a spy: it is the derived structure the + * polled data feeds (it builds the whole agent tree, and the graph layout is + * memoized on its result), so "the model was not recomputed" is exactly "the + * polled objects kept their identity". + */ +const { modelSpy } = vi.hoisted(() => ({ modelSpy: vi.fn() })) + +vi.mock('../src/client/tasks-model.ts', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + buildTasksModel: (...args: Parameters) => { + modelSpy(...args) + return actual.buildTasksModel(...args) + }, + } +}) + /** A subscribable sessions-list snapshot (mirror of the runtime list feed). */ function makeStore(initial: SidebarSessionList) { let snapshot = initial @@ -266,12 +287,73 @@ describe('SubagentView live polling', () => { const bar = container.querySelector('[data-graph-node="a"] [data-running="true"]') expect(bar?.textContent).toContain('hello') - // The tree is re-rooted under a new ancestor: old rows must not leak. - store.set(reRootedSnapshot()) + // The tree is re-rooted under a new ancestor: old rows must not leak. The + // store notification is an update like any other, so it is flushed inside + // act() (this spec declares the act environment). + await act(async () => { store.set(reRootedSnapshot()) }) await act(async () => { await Promise.resolve() }) expect(liveCalls).toEqual(['root', 'grand']) expect(container.textContent).not.toContain('hello') expect(historySpy).not.toHaveBeenCalled() unmount() }) + + it('re-renders nothing when a poll returns the same data', async () => { + vi.useFakeTimers() + const historySpy = vi.fn() + const liveCalls: string[] = [] + // The route answers with FRESH objects every tick (that is the wire shape); + // the page must publish them only when they say something new. + let answer: Record = { + a: { running: true, summary: { counts: [{ kind: 'read', count: 1 }], runningDetail: 'hello' } }, + } + vi.stubGlobal('fetch', async (url: string | URL | Request, init?: RequestInit) => { + const method = String(url).split('/').pop() + if (method === 'subagents.live') { + const body = JSON.parse(String(init?.body)) as { rootSessionId?: string } + liveCalls.push(body.rootSessionId ?? '') + return jsonResponse({ ok: true, value: { live: answer } }) + } + if (method === 'workflows.list') return jsonResponse({ ok: true, value: { runs: [] } }) + throw new Error(`unexpected fetch ${String(url)}`) + }) + + // Every Profiler commit inside the page's subtree IS one re-render of the + // page — there is no cheaper observable for "nothing was published". + const commits: string[] = [] + const store = makeStore(runningSnapshot()) + const { unmount } = renderRoot( + createElement( + Profiler, + { id: 'tasks', onRender: (_id: string, phase: string) => { commits.push(phase) } }, + createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }), + ), + ) + await act(async () => { await Promise.resolve() }) + expect(liveCalls).toEqual(['root']) + // Let the mount settle completely — the graph's own entrance tween runs on + // rAFs after the live answer lands, and that motion is not what this case + // is about. Both poll cadences are untouched by this (3 s / 5 s). + await act(async () => { await vi.advanceTimersByTimeAsync(1_500) }) + const settledCommits = commits.length + const settledModel = modelSpy.mock.calls.length + expect(settledCommits).toBeGreaterThan(0) + + // One full round of BOTH cadences (3 s live, 5 s telemetry) with identical + // answers: the fresh objects must keep the previous identities, so React + // bails out (no commit at all) and the derived model is not rebuilt. + await act(async () => { await vi.advanceTimersByTimeAsync(5_000) }) + expect(liveCalls.length).toBeGreaterThanOrEqual(2) + expect(commits.length).toBe(settledCommits) + expect(modelSpy.mock.calls.length).toBe(settledModel) + + // A REAL change still lands — and re-derives the model exactly once. + answer = { + a: { running: true, summary: { counts: [{ kind: 'read', count: 1 }], runningDetail: 'hello again' } }, + } + await act(async () => { await vi.advanceTimersByTimeAsync(3_000) }) + expect(commits.length).toBeGreaterThan(settledCommits) + expect(modelSpy.mock.calls.length).toBe(settledModel + 1) + unmount() + }) }) diff --git a/tests/unbounded-caches.spec.ts b/tests/unbounded-caches.spec.ts new file mode 100644 index 00000000..ea686776 --- /dev/null +++ b/tests/unbounded-caches.spec.ts @@ -0,0 +1,266 @@ +/** + * The module-level caches that a kept-mounted page would otherwise grow forever. + * + * v0.25 made every visited native tab body permanent (the host has no LRU), so + * the small maps that used to be bounded by their component's lifetime now live + * for the whole page: the editor's per-file PREVIEW SCROLL memory, the changes + * lens's per-scope COMMIT DRAFTS, the markdown navigation's parked cross-file + * anchors (whose TTL was only ever checked when an anchor was TAKEN — a fragment + * parked for a document nobody opens was never re-checked), and the editor + * ops-stream's per-session record. Each has its own spec-level surface because + * none of them has behaviour to observe otherwise: + * + * - the scroll memory and the draft record are written and read by the + * component through the exported helpers below, so the bound is asserted on + * exactly the function the component calls; + * - the anchor sweep is a no-op for a MISS (an expired entry and an evicted one + * both take as `null`), so its count is the only observable — the sweep the + * WRITE path performs is what the case pins; + * - the ops-stream's bound IS observable: a session still inside it resumes + * from its cursor and publishes what it missed, one evicted past it + * re-baselines (the state a page reload starts from). + */ +// @vitest-environment jsdom +import './browser-globals.ts' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import { act } from 'react-dom/test-utils' +import { renderRoot, setupReactAct } from './test-utils.ts' +import { COMMIT_DRAFT_CAP, withCommitDraft } from '../src/client/changes/GitLens.tsx' +import { PREVIEW_SCROLL_CAP, previewScrollOf, rememberPreviewScroll } from '../src/client/TextEditor.tsx' +import { useFileOpStream, type FileOpStreamState } from '../src/client/ops-stream.ts' +import { + rememberMarkdownAnchor, + sweepPendingAnchors, + takeMarkdownAnchor, +} from '../src/client/markdown-navigation.ts' +import type { SidebarSessionEvent } from '../src/context-types.ts' + +setupReactAct() + +const { changesOps } = vi.hoisted(() => ({ changesOps: vi.fn() })) + +vi.mock('../src/client/api.ts', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, api: { ...actual.api, changesOps: (...args: unknown[]) => changesOps(...args) } } +}) + +/** One `tool/call` event (the shape `extractFileOps` reads). */ +function call(seq: number, name: string, callId: string, args: unknown): SidebarSessionEvent { + return { type: 'tool/call', seq, time: seq, data: { name, callId, arguments: JSON.stringify(args) } } +} + +/** Its settled `tool/result`, in the 0.1.7 first-class tool-message shape. */ +function result(seq: number, callId: string, text: string): SidebarSessionEvent { + return { + type: 'tool/result', + seq, + time: seq, + data: { + message: { + role: 'tool', + source: { kind: 'tool', callId }, + toolCallId: callId, + isError: false, + content: [{ type: 'text', text }], + }, + }, + } +} + +/** The published state of the stream the probe last read. */ +let latestStream: FileOpStreamState | null = null + +/** One mounted editor's view of its session's ops stream. */ +function StreamProbe(props: { sessionId: string; enabled: boolean }) { + latestStream = useFileOpStream({ sessionId: props.sessionId, cwd: '/w' }, props.enabled) + return null +} + +describe('TextEditor preview scroll memory', () => { + it('remembers a position per document and forgets the least recent past the cap', () => { + const scope = { sessionId: 'scroll-spec' } + rememberPreviewScroll(scope, '/w/a.md', 120) + rememberPreviewScroll(scope, '/w/b.md', 240) + expect(previewScrollOf(scope, '/w/a.md')).toBe(120) + expect(previewScrollOf(scope, '/w/b.md')).toBe(240) + // A document never previewed opens at the top. + expect(previewScrollOf(scope, '/w/never.md')).toBe(0) + + // One entry per document is fine; the (cap + 1)-th write is not — the two + // documents above are the least recently written, so they go first. + for (let index = 0; index < PREVIEW_SCROLL_CAP; index++) { + rememberPreviewScroll(scope, `/w/f${index}.md`, index + 1) + } + expect(previewScrollOf(scope, '/w/a.md')).toBe(0) + expect(previewScrollOf(scope, '/w/b.md')).toBe(0) + expect(previewScrollOf(scope, `/w/f${PREVIEW_SCROLL_CAP - 1}.md`)).toBe(PREVIEW_SCROLL_CAP) + + // Re-scrolling a document moves it to the back of the eviction order, so + // the NEXT new document evicts the one behind it instead. + rememberPreviewScroll(scope, '/w/f0.md', 111) + rememberPreviewScroll(scope, '/w/fresh.md', 999) + expect(previewScrollOf(scope, '/w/f0.md')).toBe(111) + expect(previewScrollOf(scope, '/w/f1.md')).toBe(0) + expect(previewScrollOf(scope, '/w/fresh.md')).toBe(999) + }) + + it('keys a position by session as well as by path', () => { + rememberPreviewScroll({ sessionId: 'scroll-a' }, '/w/same.md', 10) + rememberPreviewScroll({ sessionId: 'scroll-b' }, '/w/same.md', 20) + expect(previewScrollOf({ sessionId: 'scroll-a' }, '/w/same.md')).toBe(10) + expect(previewScrollOf({ sessionId: 'scroll-b' }, '/w/same.md')).toBe(20) + }) +}) + +describe('GitLens commit drafts', () => { + it('keeps the newest scopes and drops the ones typed into longest ago', () => { + const key = (index: number): string => `draft-s${index}\u0000/w${index}` + let drafts: Record = {} + for (let index = 0; index < COMMIT_DRAFT_CAP + 5; index++) { + drafts = withCommitDraft(drafts, key(index), `message ${index}`) + } + // The record is bounded… + expect(Object.keys(drafts)).toHaveLength(COMMIT_DRAFT_CAP) + // …and what it dropped is the OLDEST scope, never the newest one. + expect(drafts[key(0)]).toBeUndefined() + expect(drafts[key(COMMIT_DRAFT_CAP + 4)]).toBe(`message ${COMMIT_DRAFT_CAP + 4}`) + + // A rewrite moves its scope to the back: the next new scope evicts another. + drafts = withCommitDraft(drafts, key(5), 'edited') + drafts = withCommitDraft(drafts, 'draft-fresh\u0000/w', 'new message') + expect(drafts[key(5)]).toBe('edited') + expect(drafts[key(6)]).toBeUndefined() + + // Committing clears the draft but keeps its key: the box reads back as an + // empty input, which is what `commitDrafts[draftKey] ?? ''` relies on. + expect(withCommitDraft(drafts, 'draft-fresh\u0000/w', '')['draft-fresh\u0000/w']).toBe('') + }) + + it('never mutates the record it is given', () => { + const before: Record = { 'draft-x\u0000/w': 'typed' } + const after = withCommitDraft(before, 'draft-y\u0000/w', 'other') + expect(before).toEqual({ 'draft-x\u0000/w': 'typed' }) + expect(after).toEqual({ 'draft-x\u0000/w': 'typed', 'draft-y\u0000/w': 'other' }) + }) +}) + +describe('markdown pending anchors', () => { + afterEach(() => { vi.useRealTimers() }) + + it('sweeps the expired entries on every write, not only on a take', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + // Fifty fragments parked for documents the reader never opened: nothing + // ever TAKES them, which is the only moment the TTL used to be checked. + for (let index = 0; index < 50; index++) { + rememberMarkdownAnchor('sweep-spec', '/w', `/w/f${index}.md`, `sec-${index}`) + } + expect(sweepPendingAnchors()).toBe(0) + vi.setSystemTime(1_000 + 16_000) + expect(sweepPendingAnchors()).toBe(50) + + // A second batch expires too — and the WRITE itself is what clears it, so + // no expired entry is left behind for a manual sweep to find. + for (let index = 0; index < 50; index++) { + rememberMarkdownAnchor('sweep-spec', '/w', `/w/g${index}.md`, `sec-${index}`) + } + vi.setSystemTime(1_000 + 32_000) + rememberMarkdownAnchor('sweep-spec', '/w', '/w/late.md', 'late') + expect(sweepPendingAnchors()).toBe(0) + + // The TTL's own semantics are untouched: what was just parked is taken, + // what was parked a minute ago is not. + expect(takeMarkdownAnchor('sweep-spec', '/w', '/w/late.md')).toBe('late') + rememberMarkdownAnchor('sweep-spec', '/w', '/w/stale.md', 'stale') + vi.setSystemTime(1_000 + 60_000) + expect(takeMarkdownAnchor('sweep-spec', '/w', '/w/stale.md')).toBeNull() + }) +}) + +describe('ops-stream session records', () => { + /** The missed delta a returning session must still see (a settled write). */ + const MISSED: SidebarSessionEvent[] = [ + call(3, 'write', 'w2', { file_path: '/w/missed.ts', content: 'y' }), + result(4, 'w2', 'wrote /w/missed.ts'), + ] + + /** Mount one editor of `sessionId` and let its immediate pull settle. */ + async function mountProbe(sessionId: string, enabled = true) { + const mounted = renderRoot(createElement(StreamProbe, { sessionId, enabled })) + await act(async () => { await Promise.resolve(); await Promise.resolve() }) + return mounted + } + + afterEach(() => { + vi.useRealTimers() + changesOps.mockReset() + latestStream = null + }) + + it('keeps a parked session\'s cursor so the delta it missed is still published', async () => { + vi.useFakeTimers() + // `afterSeq` is the stream's own cursor: pull #1 is the BASELINE (an + // unrelated, long-settled write, published to nobody), the pull after the + // parked period carries the write the model did meanwhile. + changesOps.mockImplementation(async (_scope: unknown, afterSeq: number) => ( + afterSeq === 0 + ? { + events: [call(1, 'write', 'w1', { file_path: '/w/old.ts', content: 'x' }), result(2, 'w1', 'wrote')], + lastSeq: 2, + } + : { events: MISSED, lastSeq: 4 } + )) + + const parked = await mountProbe('rejoin') + expect(changesOps).toHaveBeenCalledTimes(1) + // The baseline published nothing (the historical write is not a touch)… + expect(latestStream?.revision).toBe(0) + + // …and while the tab is parked the poller stops, so nothing is pulled. + parked.rerender(createElement(StreamProbe, { sessionId: 'rejoin', enabled: false })) + await act(async () => { await vi.advanceTimersByTimeAsync(10_000) }) + expect(changesOps).toHaveBeenCalledTimes(1) + expect(latestStream?.revision).toBe(0) + + // Coming back resumes from the persisted cursor and folds what was missed: + // the file the model rewrote while the tab was parked IS a touch. + parked.rerender(createElement(StreamProbe, { sessionId: 'rejoin', enabled: true })) + await act(async () => { await Promise.resolve(); await Promise.resolve() }) + expect(changesOps.mock.calls.at(-1)?.[1]).toBe(2) + expect(latestStream?.revision).toBe(1) + expect(latestStream?.touched.get('/w/missed.ts')?.kind).toBe('write') + parked.unmount() + }) + + it('re-baselines a session evicted past the record cap', async () => { + vi.useFakeTimers() + changesOps.mockImplementation(async (_scope: unknown, afterSeq: number) => ( + afterSeq === 0 + ? { + events: [call(1, 'write', 'w1', { file_path: '/w/old.ts', content: 'x' }), result(2, 'w1', 'wrote')], + lastSeq: 2, + } + : { events: MISSED, lastSeq: 4 } + )) + + const parked = await mountProbe('cap-victim') + parked.rerender(createElement(StreamProbe, { sessionId: 'cap-victim', enabled: false })) + parked.unmount() + + // More sessions than the cap (32) join and leave: each one's record is + // newest, so the oldest — the parked session above — is what goes. + for (let index = 0; index < 32; index++) { + const extra = await mountProbe(`cap-other-${index}`) + extra.unmount() + } + + // The evicted session re-joins as a FRESH stream: its first pull is a + // baseline again, so the delta it missed is deliberately not published — + // the same state a page reload starts from. Inside the cap the same + // scenario DOES publish (the case above). + await mountProbe('cap-victim') + expect(changesOps.mock.calls.at(-1)?.[1]).toBe(0) + expect(latestStream?.revision).toBe(0) + }) +})