Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Persist shared Properties collapse state and preserve scroll (#2831)
sarah9ca0210d989d
diff --git a/.changeset/properties-persist-collapse-scroll.md b/.changeset/properties-persist-collapse-scroll.mdnew file mode 100644index 000000000..0e971ff0b--- /dev/null+++ b/.changeset/properties-persist-collapse-scroll.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++The document Properties section now shows a count of its fields as a badge next to the "Properties" label, and its rows align flush to the left edge of the disclosure. Whether Properties is expanded or collapsed is now a saved preference shared across every open document, so collapsing it on one file collapses it everywhere, and the choice survives navigation between files and reload. Toggling Properties on one document no longer disturbs your scroll position in another: each document remembers its scroll position relative to its body content, so a Properties height change never moves where you were reading.diff --git a/packages/app/package.json b/packages/app/package.jsonindex a0fae7472..3ea5bdafb 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -26,7 +26,7 @@"measure:fuzz": "bash scripts/measure-fuzz.sh","measure:stress": "bash scripts/measure-stress.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-navigation.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-navigation.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsxindex fc819e458..15c38c049 100644--- a/packages/app/src/components/EditorActivityPool.tsx+++ b/packages/app/src/components/EditorActivityPool.tsx@@ -41,6 +41,7 @@ import {Activity,lazy,type ReactNode,+ type RefObject,Suspense,useEffect,useLayoutEffect,@@ -484,12 +485,64 @@ interface ActivityEntryProps {* ends on the first user-scroll-intent signal (wheel / touchstart) or* a 2 s safety timeout.*/+/**+ * Position of `anchor` within `container`'s scroll content (distance from the+ * content top), independent of the current scroll offset. Equals the total+ * height ABOVE the anchor — page header + Properties section. Returns null when+ * either element is missing so callers can skip anchor compensation.+ */+function measureAnchorContentPos(+ container: HTMLElement,+ anchor: HTMLElement | null | undefined,+): number | null {+ if (!anchor) return null;+ const cTop = container.getBoundingClientRect().top;+ const aTop = anchor.getBoundingClientRect().top;+ return aTop - cTop + container.scrollTop;+}++/**+ * Per-document scroll position, stored as a BODY OFFSET (scrollTop minus the+ * above-body anchor height) and keyed by `docName`. Two reasons it lives at+ * module scope, not in a per-instance ref:+ * 1. Survives the editor's REMOUNT on navigate-back — the fresh+ * ScrollPreservingContainer instance re-reads the same value instead of+ * losing it (the per-instance ref was the bug: a remount dropped it and+ * then re-captured churn from the resize).+ * 2. Body-relative — a Properties-panel height change (collapse/expand, even+ * globally on another doc) never invalidates it, because the offset is+ * measured from the top of the body, not the top of the scroller.+ * Restore = currentAnchor + storedOffset, so it always lands on the same body+ * content regardless of the panel's current height.+ *+ * Entries are deliberately kept PAST Activity eviction (so revisiting a+ * pooled-out doc still restores scroll), so there is no per-eviction cleanup —+ * but to keep a very long session from growing the map without bound,+ * `rememberDocScrollOffset` caps it at `MAX_TRACKED_DOC_SCROLL`, dropping the+ * least-recently-written entry (re-insert-on-write makes the order LRU).+ */+const MAX_TRACKED_DOC_SCROLL = 256;+const docScrollBodyOffset = new Map<string, number>();+function rememberDocScrollOffset(docName: string, offset: number): void {+ docScrollBodyOffset.delete(docName); // re-insert last → LRU order for eviction+ docScrollBodyOffset.set(docName, offset);+ if (docScrollBodyOffset.size > MAX_TRACKED_DOC_SCROLL) {+ const oldest = docScrollBodyOffset.keys().next().value;+ if (oldest !== undefined) docScrollBodyOffset.delete(oldest);+ }+}+function ScrollPreservingContainer({isActive,+ docName,initialScrollTop,+ bodyAnchorRef,children,}: {isActive: boolean;+ /** The document this scroller belongs to — the key under which its scroll+ * body-offset persists across remounts (see `docScrollBodyOffset`). */+ docName: string;/*** Seed value for `savedScrollTop` at mount. Used by the warm-skeleton* rename-restore path: when the new ActivityEntry mounts post-rename@@ -501,6 +554,17 @@ function ScrollPreservingContainer({* recovery).*/initialScrollTop?: number;+ /**+ * Ref to a zero-height marker at the TOP of the document body (below the+ * page header + the variable-height Properties section). Scroll is restored+ * relative to this anchor's position within the scroll content, not a raw+ * pixel offset — so a height change ABOVE it while this doc is hidden (the+ * globally-shared Properties panel collapsing on another doc's toggle) does+ * not shift the restored position. Optional: without a captured anchor the+ * restore falls back to the raw saved scrollTop (compensation delta 0), so+ * existing behavior is unchanged whenever nothing above the body moved.+ */+ bodyAnchorRef?: RefObject<HTMLElement | null>;children: ReactNode;}) {const ref = useRef<HTMLDivElement>(null);@@ -508,23 +572,44 @@ function ScrollPreservingContainer({// subsequent re-renders that re-pass a stale or zero `initialScrollTop`// do NOT overwrite a saved value the user has since scrolled away from.const savedScrollTop = useRef<number>(initialScrollTop ?? 0);+ // Anchor position captured at the same instant as `savedScrollTop`, so the+ // pair describes one consistent layout. `null` = never captured (fresh mount+ // / warm rename-restore) → no compensation.+ const savedAnchorPos = useRef<number | null>(null);- // Continuously track scrollTop via scroll listener so we always have the- // latest user position — independent of Activity mode transitions.- // `display:none` zeros scrollTop before any layout effect could read it,- // so we MUST capture via scroll events to have a real value to restore.+ // Mirror `isActive` into a ref so the (once-installed) scroll listener reads+ // the current value. Only a GENUINE user scroll — doc visible, not mid-restore+ // — should record position; the restore's own programmatic writes and the+ // panel-resize churn on reveal fire scroll events too, and recording those was+ // corrupting the saved position (the `799.5` in the diagnostics).+ const isActiveRef = useRef(isActive);+ const isRestoringRef = useRef(false);+ useEffect(() => {+ isActiveRef.current = isActive;+ }, [isActive]);++ // Track scrollTop via a scroll listener so we always have the latest user+ // position — `display:none` zeros scrollTop before any layout effect could+ // read it, so we MUST capture via scroll events.useEffect(() => {const el = ref.current;if (!el) return;const onScroll = () => {- // Only record non-zero values — a content collapse under display:none- // can fire a spurious scroll event with scrollTop=0 that we must NOT- // persist (it would overwrite the real saved value).- if (el.scrollTop > 0) savedScrollTop.current = el.scrollTop;+ // Ignore non-user scroll: hidden (post-reveal churn / spurious 0s) and+ // restore-in-progress (our own writes + panel-resize adjustments).+ if (!isActiveRef.current || isRestoringRef.current) return;+ if (el.scrollTop > 0) {+ savedScrollTop.current = el.scrollTop;+ const anchor = measureAnchorContentPos(el, bodyAnchorRef?.current);+ savedAnchorPos.current = anchor;+ // Persist the body-relative offset per doc so it survives a remount and+ // stays valid across Properties-panel height changes.+ if (anchor !== null) rememberDocScrollOffset(docName, el.scrollTop - anchor);+ }};el.addEventListener('scroll', onScroll, { passive: true });return () => el.removeEventListener('scroll', onScroll);- }, []);+ }, [bodyAnchorRef, docName]);// Restore scrollTop when `isActive` flips to true. Two stages:// 1. Synchronous best-effort write — cheap when content is already@@ -549,8 +634,28 @@ function ScrollPreservingContainer({if (!isActive) return;const el = ref.current;if (!el) return;- const target = savedScrollTop.current;- if (target === 0) return;+ const rawTarget = savedScrollTop.current;++ // Restore keeps the BODY offset — how far into the document body we were+ // scrolled — constant, instead of a raw pixel scrollTop, and recomputes the+ // target from the CURRENT anchor on every apply so it tracks the Properties+ // panel settling to its post-toggle height. Prefer the per-doc offset+ // (`docScrollBodyOffset`) so it survives the editor's remount on+ // navigate-back; fall back to this instance's captured pair, then the raw+ // scroll (fresh mount / warm rename-restore) so existing behavior is intact.+ const sharedOffset = docScrollBodyOffset.get(docName);+ const instanceOffset =+ savedAnchorPos.current !== null ? rawTarget - savedAnchorPos.current : null;+ const bodyOffset: number | null = sharedOffset ?? instanceOffset;+ if (rawTarget === 0 && bodyOffset === null) return; // nothing to restore+ const computeTarget = (): number => {+ if (bodyOffset === null) return rawTarget;+ const anchor = measureAnchorContentPos(el, bodyAnchorRef?.current);+ return anchor === null ? rawTarget : anchor + bodyOffset;+ };+ // Suppress scroll capture while we drive the restore — our own writes and+ // the panel-resize adjustments would otherwise be recorded as user scroll.+ isRestoringRef.current = true;const startTs = performance.now();let phase2Marked = false;@@ -559,6 +664,7 @@ function ScrollPreservingContainer({// lands AND content is sized; do NOT short-circuit: the Suspense// warm-fallback → real-editor swap can still collapse scrollHeight and// re-clamp scrollTop, so Stage 2's poll must remain armed.+ let target = computeTarget();el.scrollTop = target;if (el.scrollTop === target && el.scrollHeight > target) {mark('ok/scroll-restore/phase1-success', {@@ -573,6 +679,7 @@ function ScrollPreservingContainer({const finish = () => {if (done) return;done = true;+ isRestoringRef.current = false; // re-enable user-scroll capturecancelAnimationFrame(raf);clearTimeout(safetyTimer);el.removeEventListener('wheel', onUserInterrupt);@@ -583,6 +690,9 @@ function ScrollPreservingContainer({el.addEventListener('touchstart', onUserInterrupt, { passive: true });const tick = () => {if (done) return;+ // Recompute from the current anchor so the target follows the Properties+ // section as it settles to its post-toggle height (see computeTarget).+ target = computeTarget();if (el.scrollTop !== target && el.scrollHeight > target) {el.scrollTop = target;if (el.scrollTop === target && !phase2Marked) {@@ -623,7 +733,7 @@ function ScrollPreservingContainer({}, 2000);return finish;- }, [isActive]);+ }, [isActive, bodyAnchorRef, docName]);return (<div@@ -803,6 +913,12 @@ function ActivityEntry({return target;});+ // Zero-height marker at the top of the document body (rendered just below the+ // page header + Properties section). ScrollPreservingContainer restores scroll+ // relative to this anchor so a height change above it — the shared Properties+ // panel collapsing while this doc is hidden — doesn't shift the restored spot.+ const bodyAnchorRef = useRef<HTMLDivElement>(null);+// Defer-mount gating for large docs.//// Small/medium docs keep pre-mount-both (precedent #18(b) default): mode swap@@ -958,7 +1074,12 @@ function ActivityEntry({rationale. Hoisting the scroller to EditorArea would make scrollstate cross-document and collapse scrollHeight on hidden-modeeffect cleanup. */}- <ScrollPreservingContainer isActive={isActive} initialScrollTop={warmSnapshot?.scrollTop}>+ <ScrollPreservingContainer+ isActive={isActive}+ docName={entry.docName}+ initialScrollTop={warmSnapshot?.scrollTop}+ bodyAnchorRef={bodyAnchorRef}+ >{recoveryView ? (<ServerRestartRecoveryPanel view={recoveryView} />) : (@@ -1052,6 +1173,11 @@ function ActivityEntry({<PropertyPanel provider={entry.provider} /></>))}+ {/* Body-top anchor for scroll-restore compensation (see+ ScrollPreservingContainer.bodyAnchorRef). Zero height,+ non-interactive — everything above it (page header ++ Properties) is the variable region it measures. */}+ <div ref={bodyAnchorRef} aria-hidden className="h-0" /><div className="relative flex-1">{gate.renderSource ? (<div className={isSourceMode ? 'h-full' : 'ok-mode-hidden h-full'}>diff --git a/packages/app/src/components/PropertyDisclosure.tsx b/packages/app/src/components/PropertyDisclosure.tsxindex 97ed2a7d0..820178c87 100644--- a/packages/app/src/components/PropertyDisclosure.tsx+++ b/packages/app/src/components/PropertyDisclosure.tsx@@ -1,5 +1,6 @@import { ChevronRight } from 'lucide-react';import { type ReactNode, type Ref, useState } from 'react';+import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';import { cn } from '@/lib/utils';@@ -14,7 +15,9 @@ import { cn } from '@/lib/utils';*/export function PropertyDisclosure({title,+ count,className,+ contentClassName,testId,open: openProp,onOpenChange,@@ -22,8 +25,17 @@ export function PropertyDisclosure({ref,}: {title: ReactNode;+ /** Optional item count shown as a badge next to the title. Rendered only when+ * a positive number — 0 and undefined show nothing. */+ count?: number;/** Extra container classes (e.g. vertical padding) merged after the base. */className?: string;+ /** Extra classes on the collapsible content box. The editable document panel+ * pulls it left (negative margin) so its drag-handle gutter overhangs into+ * the page margin and the type-icon column lands flush at the content edge.+ * Must sit on this box, not an inner wrapper — the box's own `overflow-hidden`+ * (collapse animation) would otherwise clip the overhanging handle. */+ contentClassName?: string;/** Forwarded to the container as `data-testid`. */testId?: string;/** Controlled open state. Omit for self-managed (uncontrolled) disclosure. */@@ -51,16 +63,26 @@ export function PropertyDisclosure({<Buttontype="button"variant="ghost"- className="mb-1.5 flex h-auto w-fit items-center gap-1 bg-transparent! px-1 py-0.5 text-base font-medium text-foreground hover:bg-transparent hover:text-foreground"+ className="data-[state=open]:mb-1.5 flex h-auto w-fit items-center gap-1 bg-transparent! tracking-wider px-1 py-0.5 text-sm uppercase font-mono font-medium text-muted-foreground hover:bg-transparent hover:text-foreground space-x-1.5"><ChevronRightdata-expanded={open}className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"/><span>{title}</span>+ {typeof count === 'number' && count > 0 ? (+ <Badge variant="gray" className="tabular-nums normal-case">+ {count}+ </Badge>+ ) : null}</Button></CollapsibleTrigger>- <CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]">+ <CollapsibleContent+ className={cn(+ 'overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]',+ contentClassName,+ )}+ >{children}</CollapsibleContent></Collapsible>diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsxindex 722a17613..e18e10ac7 100644--- a/packages/app/src/components/PropertyPanel.tsx+++ b/packages/app/src/components/PropertyPanel.tsx@@ -40,6 +40,7 @@ import {import { useProperties } from '@/components/PropertyContext';import { PropertyDisclosure } from '@/components/PropertyDisclosure';import { coerceValue, DEFAULT_VALUE_FOR_TYPE } from '@/components/PropertyWidgets';+import { usePropertiesCollapsed } from '@/components/properties-collapsed-store';import { Button } from '@/components/ui/button';import { usePublishFrontmatterSelection } from '@/hooks/use-selection-context';@@ -91,7 +92,13 @@ export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {const orderedKeys = snapshot.keys;const parseError = snapshot.parseError;- const [collapsed, setCollapsed] = useState(false);+ // Collapsed state is a persisted, user-global preference shared LIVE across all+ // mounted panels (see properties-collapsed-store): collapsing on one file+ // collapses the section everywhere, immediately, and survives reload. The live+ // resize of a hidden, scrolled doc is kept scroll-safe by+ // ScrollPreservingContainer's body-top anchor restore. The `setCollapsed(false)`+ // force-expands below (add-property intent) also persist "open"; that's intended.+ const [collapsed, setCollapsed] = usePropertiesCollapsed();const [overrides, setOverrides] = useState<Record<string, FrontmatterType>>({});const [adding, setAdding] = useState<AddDraft | null>(null);const [renaming, setRenaming] = useState<RenameDraft | null>(null);@@ -256,7 +263,7 @@ export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {setAdding({ name: '', type: 'text', value: '', error: null });setCollapsed(false);}- }, [addSignal]);+ }, [addSignal, setCollapsed]);useEffect(() => {return () => clearAddProperty(docName);}, [docName, clearAddProperty]);@@ -384,21 +391,39 @@ export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {if (renderKeys.length === 0 && !adding && !parseError) return null;+ // Flush-left alignment. Sortable rows carry a drag-handle gutter (FrontmatterRow:+ // a `w-4` handle + `gap-1` = 1.25rem) that pushes the type-icon column right of+ // the document content edge. We pull the whole collapsible content left via+ // `--prop-drag-gutter` so the type icons sit flush under the disclosure chevron;+ // the in-flow drag handle overhangs into the page margin — it stays visible+ // because the shift moves the whole `overflow-hidden` box (an inner child would+ // be clipped). The value is tuned slightly ABOVE the raw 1.25rem gutter so the+ // icons land under the chevron GLYPH, which itself sits `px-1` in from the panel+ // edge — hence 1.375rem, not the bare gutter width. Framed children with no+ // gutter (the YAML-error banner, the add-property form) cancel the pull with+ // `PROP_GUTTER_COMPENSATE`.+ const PROP_CONTENT_SHIFT = '[--prop-drag-gutter:1.375rem] -ml-(--prop-drag-gutter)';+ const PROP_GUTTER_COMPENSATE = 'ml-(--prop-drag-gutter)';+return (<FrontmatterBindingProvider binding={binding}><PropertyDisclosureref={panelRef}title={<Trans>Properties</Trans>}+ count={renderKeys.length}testId="property-panel"- className="pt-4 pb-4"+ className="pt-4"+ contentClassName={PROP_CONTENT_SHIFT}open={!collapsed}onOpenChange={(open) => setCollapsed(!open)}>{parseError ? (+ // No drag-handle gutter — cancel the content shift so the banner sits+ // flush instead of hanging into the page margin (see PROP_CONTENT_SHIFT).<divrole="alert"data-testid="property-panel-yaml-error"- className="mb-1 flex items-start gap-1.5 rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-[11px] text-destructive"+ className={`mb-1 ${PROP_GUTTER_COMPENSATE} flex items-start gap-1.5 rounded border border-destructive/30 bg-destructive/5 px-2 py-1.5 text-[11px] text-destructive`}><AlertTriangle className="size-3.5 shrink-0 mt-0.5" /><div>@@ -487,14 +512,18 @@ export function PropertyPanel({ provider, reservedKeys }: PropertyPanelProps) {/>) : null}{adding ? (- <AddPropertyRow- draft={adding}- onChangeName={changeAddName}- onChangeType={changeAddType}- onChangeValue={changeAddValue}- onCommit={commitAdd}- onCancel={cancelAdd}- />+ // No drag-handle gutter — cancel the content shift so the add form+ // sits flush with the rows (see PROP_CONTENT_SHIFT).+ <div className={PROP_GUTTER_COMPENSATE}>+ <AddPropertyRow+ draft={adding}+ onChangeName={changeAddName}+ onChangeType={changeAddType}+ onChangeValue={changeAddValue}+ onCommit={commitAdd}+ onCancel={cancelAdd}+ />+ </div>) : (// Wrapper mirrors FrontmatterRow's flex layout above: an// aria-hidden `w-4` spacer occupies the drag-handle column,diff --git a/packages/app/src/components/ReadonlyPropertyPanel.tsx b/packages/app/src/components/ReadonlyPropertyPanel.tsxindex 7d46a7a37..41a9a7a6c 100644--- a/packages/app/src/components/ReadonlyPropertyPanel.tsx+++ b/packages/app/src/components/ReadonlyPropertyPanel.tsx@@ -40,8 +40,9 @@ export function ReadonlyPropertyPanel({ text }: { text: string }) {return (<PropertyDisclosuretitle={<Trans>Properties</Trans>}+ count={renderKeys.length}testId="readonly-property-panel"- className="pt-4 pb-4"+ className="pt-4">{renderKeys.map((key, idx) => {const value = map[key];diff --git a/packages/app/src/components/RenderedDiffView.tsx b/packages/app/src/components/RenderedDiffView.tsxindex 77bee8277..9fab316eb 100644--- a/packages/app/src/components/RenderedDiffView.tsx+++ b/packages/app/src/components/RenderedDiffView.tsx@@ -78,7 +78,7 @@ export function RenderedDiffView({ diff }: { diff: RenderedDiff }) {content: diff.afterDoc.toJSON(),editorProps: {// Same content-surface padding as the real editor so spacing matches.- attributes: { class: 'pt-4 pb-4' },+ attributes: { class: 'pt-4' },},},[diff],diff --git a/packages/app/src/components/SkillMarkdownViewer.tsx b/packages/app/src/components/SkillMarkdownViewer.tsxindex 003ef792e..e9c43145d 100644--- a/packages/app/src/components/SkillMarkdownViewer.tsx+++ b/packages/app/src/components/SkillMarkdownViewer.tsx@@ -48,7 +48,7 @@ export function SkillMarkdownViewer({ fileName, text }: { fileName: string; textattributes: {// Same content-surface padding as the real editor (TiptapEditor's// `editorProps.attributes.class`) so spacing matches.- class: 'pt-4 pb-4',+ class: 'pt-4',},},},diff --git a/packages/app/src/components/properties-collapsed-store.dom.test.tsx b/packages/app/src/components/properties-collapsed-store.dom.test.tsxnew file mode 100644index 000000000..5e40f6a4d--- /dev/null+++ b/packages/app/src/components/properties-collapsed-store.dom.test.tsx@@ -0,0 +1,59 @@+import { act, cleanup, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ __resetPropertiesCollapsedForTests,+ setPropertiesCollapsed,+ usePropertiesCollapsed,+} from './properties-collapsed-store';++/**+ * The hook is a LIVE view of the shared preference: every mounted panel reflects+ * a toggle from any panel in lockstep (that is the "same across all documents"+ * requirement). The scroll disruption this live resize would otherwise cause on+ * a hidden, scrolled doc is compensated in ScrollPreservingContainer (body-top+ * anchor restore), not by making the state non-live here.+ */+describe('usePropertiesCollapsed (live shared state)', () => {+ beforeEach(() => {+ localStorage.clear();+ __resetPropertiesCollapsedForTests();+ });+ afterEach(() => {+ cleanup();+ localStorage.clear();+ __resetPropertiesCollapsedForTests();+ });++ it('seeds from the persisted preference at mount', () => {+ setPropertiesCollapsed(true); // a prior session/panel persisted "collapsed"+ const { result } = renderHook(() => usePropertiesCollapsed());+ expect(result.current[0]).toBe(true);+ });++ it('updates live when another panel toggles the shared store', () => {+ const { result } = renderHook(() => usePropertiesCollapsed());+ expect(result.current[0]).toBe(false); // default open++ // Another panel (or this one's setter) flips the shared preference.+ act(() => setPropertiesCollapsed(true));+ expect(result.current[0]).toBe(true);+ });++ it('keeps two mounted panels in lockstep', () => {+ const a = renderHook(() => usePropertiesCollapsed());+ const b = renderHook(() => usePropertiesCollapsed());+ expect(a.result.current[0]).toBe(false);+ expect(b.result.current[0]).toBe(false);++ // Toggle via panel A's setter → panel B reflects it too.+ act(() => a.result.current[1](true));+ expect(a.result.current[0]).toBe(true);+ expect(b.result.current[0]).toBe(true);+ });++ it('persists the preference for future mounts', () => {+ const { result } = renderHook(() => usePropertiesCollapsed());+ act(() => result.current[1](true));+ expect(localStorage.getItem('ok-properties-collapsed-v1')).toBe('true');+ });+});diff --git a/packages/app/src/components/properties-collapsed-store.test.ts b/packages/app/src/components/properties-collapsed-store.test.tsnew file mode 100644index 000000000..66ca4607a--- /dev/null+++ b/packages/app/src/components/properties-collapsed-store.test.ts@@ -0,0 +1,93 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ __resetPropertiesCollapsedForTests,+ getPropertiesCollapsed,+ setPropertiesCollapsed,+ subscribePropertiesCollapsed,+} from './properties-collapsed-store';++const STORAGE_KEY = 'ok-properties-collapsed-v1';++/** Minimal in-memory `localStorage` so the persistence path runs without jsdom —+ * the store reads `window.localStorage` behind a `typeof window` guard, so a+ * stub on `globalThis.window` exercises it (mirrors composer-draft-store.test). */+function makeLocalStorage(): Storage {+ const store = new Map<string, string>();+ return {+ get length() {+ return store.size;+ },+ clear: () => store.clear(),+ getItem: (key) => store.get(key) ?? null,+ key: (index) => [...store.keys()][index] ?? null,+ removeItem: (key) => {+ store.delete(key);+ },+ setItem: (key, value) => {+ store.set(key, String(value));+ },+ };+}++let storage: Storage;++beforeEach(() => {+ storage = makeLocalStorage();+ (globalThis as { window?: { localStorage: Storage } }).window = { localStorage: storage };+ __resetPropertiesCollapsedForTests();+});++afterEach(() => {+ __resetPropertiesCollapsedForTests();+ delete (globalThis as Record<string, unknown>).window;+});++describe('properties-collapsed-store', () => {+ it('defaults to open (not collapsed) with nothing persisted', () => {+ expect(getPropertiesCollapsed()).toBe(false);+ });++ it('persists collapsed=true and reads it back after a fresh load', () => {+ setPropertiesCollapsed(true);+ expect(getPropertiesCollapsed()).toBe(true);+ expect(storage.getItem(STORAGE_KEY)).toBe('true');++ // Simulate a new session / fresh mount: drop the in-memory snapshot so the+ // next read re-loads from the (still-populated) storage.+ __resetPropertiesCollapsedForTests();+ expect(getPropertiesCollapsed()).toBe(true);+ });++ it('persists collapsed=false explicitly (not remove-on-open)', () => {+ setPropertiesCollapsed(true);+ setPropertiesCollapsed(false);+ expect(getPropertiesCollapsed()).toBe(false);+ expect(storage.getItem(STORAGE_KEY)).toBe('false');+ });++ it('falls back to the default on a malformed stored value', () => {+ storage.setItem(STORAGE_KEY, 'garbage');+ expect(getPropertiesCollapsed()).toBe(false);+ });++ it('notifies subscribers on change but not on a no-op write', () => {+ const listener = vi.fn();+ const unsubscribe = subscribePropertiesCollapsed(listener);++ setPropertiesCollapsed(true);+ expect(listener).toHaveBeenCalledTimes(1);++ // No-op write (same value) neither notifies nor overwrites storage.+ storage.setItem(STORAGE_KEY, 'sentinel');+ setPropertiesCollapsed(true);+ expect(listener).toHaveBeenCalledTimes(1);+ expect(storage.getItem(STORAGE_KEY)).toBe('sentinel');++ setPropertiesCollapsed(false);+ expect(listener).toHaveBeenCalledTimes(2);++ unsubscribe();+ setPropertiesCollapsed(true);+ expect(listener).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/app/src/components/properties-collapsed-store.ts b/packages/app/src/components/properties-collapsed-store.tsnew file mode 100644index 000000000..a1b821847--- /dev/null+++ b/packages/app/src/components/properties-collapsed-store.ts@@ -0,0 +1,114 @@+/**+ * Persisted, cross-panel "is the Properties section collapsed?" preference.+ *+ * One module-level external store (same pattern as `composer-draft-store.ts` and+ * `selection-context`) so every mounted `PropertyPanel` — several stay alive at+ * once in the pooled `EditorActivityPool` — reflects the collapse toggle LIVE+ * and in lockstep, and the choice survives navigation between files and reload.+ * A single user-global preference (NOT per-doc): collapsing the section on one+ * file collapses it everywhere, immediately.+ *+ * Default is OPEN (`collapsed === false`). Flip `DEFAULT_COLLAPSED` to change the+ * first-run default.+ *+ * Scroll safety: because this is live, toggling on one doc resizes the Properties+ * section on every mounted doc — including hidden, scrolled ones. The Properties+ * section sits above the document body, so that resize would shift a hidden doc's+ * restored scroll position. That is compensated in `ScrollPreservingContainer`+ * (EditorActivityPool), which restores scroll relative to a body-top anchor, not+ * a raw pixel offset — so the live resize here is safe.+ */+import { useSyncExternalStore } from 'react';++const STORAGE_KEY = 'ok-properties-collapsed-v1';+const DEFAULT_COLLAPSED = false;++/** SSR- and privacy-mode-safe storage handle. Mirrors the other client stores. */+function getStorage(): Pick<Storage, 'getItem' | 'setItem'> | null {+ if (typeof window === 'undefined') return null;+ try {+ return window.localStorage;+ } catch {+ return null;+ }+}++/** Lazy-loaded from storage on first read, then kept in memory as the source of+ * truth for the session. */+let state: boolean | null = null;+const listeners = new Set<() => void>();++function load(): boolean {+ const storage = getStorage();+ if (!storage) return DEFAULT_COLLAPSED;+ try {+ const raw = storage.getItem(STORAGE_KEY);+ if (raw === 'true') return true;+ if (raw === 'false') return false;+ return DEFAULT_COLLAPSED;+ } catch {+ return DEFAULT_COLLAPSED;+ }+}++function ensureLoaded(): boolean {+ if (state === null) state = load();+ return state;+}++function persist(collapsed: boolean): void {+ const storage = getStorage();+ if (!storage) return;+ try {+ // Store the value explicitly (not remove-on-open) so it stays unambiguous+ // if `DEFAULT_COLLAPSED` is ever flipped to closed.+ storage.setItem(STORAGE_KEY, collapsed ? 'true' : 'false');+ } catch {+ // quota / privacy mode — the in-memory state is still the source of truth.+ }+}++function notify(): void {+ for (const listener of listeners) listener();+}++/** Current collapsed state. Stable across reads until an actual change, so+ * `useSyncExternalStore` does not churn. */+export function getPropertiesCollapsed(): boolean {+ return ensureLoaded();+}++export function setPropertiesCollapsed(collapsed: boolean): void {+ if (ensureLoaded() === collapsed) return;+ state = collapsed;+ persist(collapsed);+ notify();+}++export function subscribePropertiesCollapsed(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/**+ * `[collapsed, setCollapsed]` over the shared store. Every panel re-renders when+ * any panel toggles. `getServerSnapshot` returns the default so SSR / test+ * harnesses render the open state without touching storage.+ */+export function usePropertiesCollapsed(): readonly [boolean, (collapsed: boolean) => void] {+ const collapsed = useSyncExternalStore(+ subscribePropertiesCollapsed,+ getPropertiesCollapsed,+ () => DEFAULT_COLLAPSED,+ );+ return [collapsed, setPropertiesCollapsed] as const;+}++/** Test-only: drop the in-memory snapshot so the next read re-loads from+ * storage. Production never calls this — the store is a session singleton. */+export function __resetPropertiesCollapsedForTests(): void {+ state = null;+ listeners.clear();+}diff --git a/packages/app/tests/stress/props-toggle-scroll-preserve.e2e.ts b/packages/app/tests/stress/props-toggle-scroll-preserve.e2e.tsnew file mode 100644index 000000000..705f0366e--- /dev/null+++ b/packages/app/tests/stress/props-toggle-scroll-preserve.e2e.ts@@ -0,0 +1,130 @@+/**+ * The Properties collapse state is a LIVE, user-global preference shared across+ * all open documents (properties-collapsed-store). Toggling it on one doc+ * resizes the Properties section on every mounted doc — including hidden,+ * scrolled ones. Because that section sits ABOVE the document body, a naive raw+ * scrollTop restore would land a returning doc at the wrong place.+ *+ * ScrollPreservingContainer compensates by restoring a constant BODY offset+ * (relative to a body-top anchor) and recomputing it each poll frame, so the+ * panel settling to its post-toggle height after reveal doesn't shift the view.+ *+ * This pins the user-visible outcome: scroll A → toggle Properties on B → back+ * to A leaves the SAME body content at the SAME viewport position, while A's+ * panel does reflect the shared collapse (proving the state stayed live).+ */+import type { Page } from '@playwright/test';+import { expect, test, waitForActiveProviderSynced } from './_helpers';++async function openFromSidebar(page: Page, filename: string) {+ const row = page.getByRole('treeitem', { name: filename, exact: true });+ await expect(row).toBeVisible();+ await row.click();+}++const FM = `---+type: daily-note+description: A description+title: Title+date: 2026-07-21+author: sarah+mood: ok+top3: []+gratitude: []+tags: [daily]+---+`;+const FILLER = 'Filler paragraph to force scrollable content. '.repeat(10);+const DOC_A = `${FM}# Doc A Heading\n\n${Array(30).fill(FILLER).join('\n\n')}\n\n## Doc A Bottom Marker\n\nEnd of doc A.`;+const DOC_B = `${FM}# Doc B Heading\n\nDoc B body paragraph.`;++const bodyMarker = (page: Page) =>+ page.locator('.ProseMirror:not(.composer-prosemirror)', { hasText: 'Doc A Bottom Marker' });+const visiblePanel = (page: Page) => page.locator('[data-testid="property-panel"]:visible');++test('Properties toggle on another doc preserves scroll on return (shared + scroll-safe)', async ({+ page,+ api,+}) => {+ await api.seedDocs([+ { name: 'doc-a', markdown: DOC_A },+ { name: 'doc-b', markdown: DOC_B },+ ]);+ await page.goto('/');++ await openFromSidebar(page, 'doc-a.md');+ await waitForActiveProviderSynced(page);+ await expect(bodyMarker(page)).toBeVisible({ timeout: 30_000 });+ await expect(visiblePanel(page)).toBeVisible();+ const panelOpenHeight = await visiblePanel(page).evaluate(+ (el) => el.getBoundingClientRect().height,+ );++ // Scroll doc A into its body and record the body marker's viewport position.+ const scroller = page+ .getByTestId('editor-scroll-container')+ .filter({ hasText: 'Doc A Bottom Marker' });+ await scroller.evaluate((el) => el.scrollTo({ top: 1200, behavior: 'instant' }));+ const markerTopBefore = await bodyMarker(page).evaluate((el) => el.getBoundingClientRect().top);++ // Nav to B, then collapse Properties there — the shared store collapses A too+ // while A is hidden.+ await openFromSidebar(page, 'doc-b.md');+ await waitForActiveProviderSynced(page);+ await expect(+ page.locator('.ProseMirror:not(.composer-prosemirror)', { hasText: 'Doc B Heading' }),+ ).toBeVisible({ timeout: 30_000 });+ await visiblePanel(page)+ .getByRole('button', { name: /properties/i })+ .click();++ // Back to A.+ await openFromSidebar(page, 'doc-a.md');+ await waitForActiveProviderSynced(page);+ await expect(bodyMarker(page)).toBeVisible({ timeout: 30_000 });++ // Shared state held: A's panel collapses to match the toggle. Poll rather than+ // a fixed wait — the collapse and the scroll-restore both settle over a few+ // frames after the doc is revealed.+ await expect+ .poll(() => visiblePanel(page).evaluate((el) => el.getBoundingClientRect().height))+ .toBeLessThan(panelOpenHeight - 100);++ // Scroll-safe: the same body content settles back to the same viewport+ // position (within a few px) despite the Properties height change.+ await expect+ .poll(async () => {+ const top = await bodyMarker(page).evaluate((el) => el.getBoundingClientRect().top);+ return Math.abs(top - markerTopBefore);+ })+ .toBeLessThan(8);++ // Expand direction (anchor moves DOWN, not up): re-open Properties on B, return+ // to A. A's panel grows while hidden; the restore must stay put through the+ // growth too — a sign error that only manifests on expand would surface here.+ await openFromSidebar(page, 'doc-b.md');+ await waitForActiveProviderSynced(page);+ await expect(+ page.locator('.ProseMirror:not(.composer-prosemirror)', { hasText: 'Doc B Heading' }),+ ).toBeVisible({ timeout: 30_000 });+ await visiblePanel(page)+ .getByRole('button', { name: /properties/i })+ .click();++ await openFromSidebar(page, 'doc-a.md');+ await waitForActiveProviderSynced(page);+ await expect(bodyMarker(page)).toBeVisible({ timeout: 30_000 });++ // Shared state held: A's panel is expanded again.+ await expect+ .poll(() => visiblePanel(page).evaluate((el) => el.getBoundingClientRect().height))+ .toBeGreaterThan(panelOpenHeight - 20);++ // Scroll-safe through the expand as well.+ await expect+ .poll(async () => {+ const top = await bodyMarker(page).evaluate((el) => el.getBoundingClientRect().top);+ return Math.abs(top - markerTopBefore);+ })+ .toBeLessThan(8);+});