Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Pin the right rail from rendered panel space, not a ratio estimate (#4762)
Nick Gomez2273d9bd7bf4
diff --git a/.changeset/terminal-column-keeps-its-width.md b/.changeset/terminal-column-keeps-its-width.mdnew file mode 100644index 000000000..59a3c9445--- /dev/null+++ b/.changeset/terminal-column-keeps-its-width.md@@ -0,0 +1,6 @@+---+"@inkeep/open-knowledge": patch+---++Opening the Agents panel beside a right-docked Terminal no longer leaves the Terminal a few pixels+narrow for the rest of the session, which could cost it a readable column.diff --git a/packages/app/package.json b/packages/app/package.jsonindex cebabc313..b81717a6b 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -37,7 +37,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/list-item-drag.e2e.ts 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/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.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/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.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/new-item-shortcut-fast-path.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/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.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/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.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/selection-surface-pane-clip.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/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts",+ "test:e2e": "playwright test tests/stress/list-item-drag.e2e.ts 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/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.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/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.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/new-item-shortcut-fast-path.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/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.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/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.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/selection-surface-pane-clip.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/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/composer-control-alignment.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts tests/stress/agents-panel-reload-visibility.e2e.ts tests/stress/rail-flex-distribution-law.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/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsxindex cbfc945dd..1740f4db2 100644--- a/packages/app/src/components/EditorArea.dom.test.tsx+++ b/packages/app/src/components/EditorArea.dom.test.tsx@@ -207,12 +207,59 @@ let groupLayout: Record<string, number> = {};let groupSetLayoutCalls: Array<Record<string, number>> = [];let panelIsCollapsed = false;let mockGroupPx = 1360;+let mockPanelPercentage: number | null = null;+let mockPanelPx: number | null = null;+let rejectGroupLayoutWrites = false;+let deferPanelGeometryCommit = false;+let committedGroupLayout: Record<string, number> = {};++beforeEach(() => {+ mockPanelPercentage = null;+ mockPanelPx = null;+ rejectGroupLayoutWrites = false;+ deferPanelGeometryCommit = false;+ committedGroupLayout = {};+});++function geometryLayout(): Record<string, number> {+ return deferPanelGeometryCommit ? committedGroupLayout : groupLayout;+}++function mockedPanelWidthPx(element: HTMLElement): number {+ const layout = geometryLayout();+ if (element.id !== '') return ((layout[element.id] ?? 0) / 100) * mockGroupPx;+ const group = element.parentElement;+ if (group == null) return 0;+ let claimedPercentage = 0;+ for (const sibling of group.querySelectorAll<HTMLElement>(':scope > [data-panel]')) {+ if (sibling.id !== '') claimedPercentage += layout[sibling.id] ?? 0;+ }+ return (Math.max(0, 100 - claimedPercentage) / 100) * mockGroupPx;+}++function measureMockedPanel(element: HTMLDivElement | null) {+ if (element == null) return;+ Object.defineProperty(element, 'getBoundingClientRect', {+ configurable: true,+ value: () => {+ const width = mockedPanelWidthPx(element);+ return { width, height: 0, top: 0, left: 0, right: width, bottom: 0, x: 0, y: 0 };+ },+ });+ Object.defineProperty(element, 'offsetWidth', {+ configurable: true,+ get: () => Math.round(mockedPanelWidthPx(element)),+ });+}vi.doMock('react-resizable-panels', () => ({usePanelRef: () => ({current: {collapse: () => {},expand: () => {},- getSize: () => ({ asPercentage: 25, inPixels: mockGroupPx / 4 }),+ getSize: () => ({+ asPercentage: mockPanelPercentage ?? 25,+ inPixels: mockPanelPx ?? mockGroupPx / 4,+ }),isCollapsed: () => panelIsCollapsed,},}),@@ -220,8 +267,16 @@ vi.doMock('react-resizable-panels', () => ({current: {getLayout: () => groupLayout,setLayout: (layout: Record<string, number>) => {- groupLayout = layout;groupSetLayoutCalls.push(layout);+ if (rejectGroupLayoutWrites) return;+ groupLayout = layout;+ if (deferPanelGeometryCommit) {+ queueMicrotask(() => {+ committedGroupLayout = layout;+ });+ } else {+ committedGroupLayout = layout;+ }},},}),@@ -229,7 +284,9 @@ vi.doMock('react-resizable-panels', () => ({vi.doMock('@/components/ui/resizable', () => ({ResizablePanelGroup: ({ children }: { children: ReactNode }) => (- <div data-testid="resizable-group">{children}</div>+ <div data-testid="resizable-group" data-group="true" data-slot="resizable-panel-group">+ {children}+ </div>),ResizablePanel: ({children,@@ -246,7 +303,14 @@ vi.doMock('@/components/ui/resizable', () => ({}) => {if (id != null) railPanelOnResizeById.set(id, onResize ?? null);return (- <div id={id} data-min-size={minSize} data-max-size={maxSize}>+ <div+ id={id}+ data-panel="true"+ data-slot="resizable-panel"+ ref={measureMockedPanel}+ data-min-size={minSize}+ data-max-size={maxSize}+ >{children}</div>);@@ -329,6 +393,8 @@ const { TooltipProvider } = await import('@/components/ui/tooltip');const { emitLocalMenuAction } = await import('@/lib/local-menu-action-bus');const { requestDocPanelTab } = await import('./doc-panel-events');const { AGENTS_COLUMN_ID, TERMINAL_COLUMN_ID } = await import('./editor-area-rail-registry');+const { MAX_RAIL_PIN_EXHAUSTED_REPORTS } = await import('./EditorArea');+const { RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX } = await import('./right-rail-admission');function renderEditorArea() {return render(@@ -812,6 +878,372 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {expect(corrected?.['editor-main']).toBe(100);});+ test('the terminal pin is taken against rendered panel space, not a panel-ratio estimate', async () => {+ setViewportWidth(1900);+ mockGroupPx = 1610;+ docCtx = DOC_LIVE_CTX;+ mockPanelPercentage = (319.51 / 1610) * 100;+ mockPanelPx = 320;+ const view = render(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,+ );+ groupLayout = {+ 'editor-main': 100 - (320 / 1610) * 100 - (740 / 1610) * 100,+ 'doc-panel': (320 / 1610) * 100,+ 'terminal-column': (740 / 1610) * 100,+ 'agents-column': 0,+ };+ groupSetLayoutCalls = [];++ view.rerender(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,+ );+ await act(async () => {});++ const corrected = groupSetLayoutCalls.at(-1);+ expect(corrected).toBeDefined();+ const terminalPercentage = corrected?.['terminal-column'];+ if (terminalPercentage == null) throw new Error('terminal column was not pinned');+ expect((terminalPercentage / 100) * 1610).toBeGreaterThan(739);+ expect(terminalPercentage).toBeCloseTo((740 / 1610) * 100, 3);+ });++ const RAIL_LAYOUT_1610 = {+ 'editor-main': 100 - (320 / 1610) * 100 - (740 / 1610) * 100,+ 'doc-panel': (320 / 1610) * 100,+ 'terminal-column': (740 / 1610) * 100,+ 'agents-column': 0,+ };++ const readExhaustedReports = (warnings: readonly string[]) =>+ warnings+ .map((message) => {+ try {+ return JSON.parse(message) as {+ event?: string;+ trigger?: string;+ stage?: string;+ refusal?: string;+ shortfall?: Record<string, unknown>;+ unaccountedIds?: readonly string[];+ };+ } catch {+ return null;+ }+ })+ .filter((entry) => entry?.event === 'right-rail-pin-exhausted');++ async function withSynchronousFrames(run: () => void) {+ const warnings: string[] = [];+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation((message: unknown) => {+ warnings.push(String(message));+ });+ const realRequestAnimationFrame = globalThis.requestAnimationFrame;+ globalThis.requestAnimationFrame = ((callback: FrameRequestCallback) => {+ callback(0);+ return 0;+ }) as typeof globalThis.requestAnimationFrame;+ try {+ run();+ await act(async () => {});+ } finally {+ globalThis.requestAnimationFrame = realRequestAnimationFrame;+ warnSpy.mockRestore();+ }+ return warnings;+ }++ test('the terminal pin is verified against the write, not the frame the panels still show', async () => {+ setViewportWidth(1900);+ mockGroupPx = 1610;+ docCtx = DOC_LIVE_CTX;+ const view = render(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,+ );+ groupLayout = { ...RAIL_LAYOUT_1610 };+ committedGroupLayout = { ...RAIL_LAYOUT_1610 };+ deferPanelGeometryCommit = true;+ groupSetLayoutCalls = [];++ const warnings = await withSynchronousFrames(() => {+ view.rerender(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,+ );+ });++ const corrected = groupSetLayoutCalls.at(-1);+ expect(corrected).toBeDefined();+ expect(corrected?.['terminal-column']).toBeCloseTo((740 / 1610) * 100, 3);+ expect(readExhaustedReports(warnings)).toEqual([]);+ });++ test('an exhausted terminal pin reports the width the column actually got', async () => {+ setViewportWidth(1900);+ mockGroupPx = 1610;+ docCtx = DOC_LIVE_CTX;+ const strandedTerminalPercentage = 44;+ const view = render(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,+ );+ groupLayout = {+ 'editor-main': 100 - (320 / 1610) * 100 - strandedTerminalPercentage,+ 'doc-panel': (320 / 1610) * 100,+ 'terminal-column': strandedTerminalPercentage,+ 'agents-column': 0,+ };+ rejectGroupLayoutWrites = true;++ const warnings = await withSynchronousFrames(() => {+ view.rerender(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,+ );+ });++ const exhausted = readExhaustedReports(warnings).at(0);+ expect(exhausted).toBeDefined();+ expect(exhausted?.trigger).toBe('rail-column-sync');+ expect(exhausted?.stage).toBe('width-shortfall');+ expect(exhausted?.shortfall?.['terminal-column']).toEqual({+ targetPx: 740,+ renderedPx: expect.closeTo((strandedTerminalPercentage / 100) * 1610, 6),+ });+ });++ test('a second exhausted loop reports its own outcome, not the one before it', async () => {+ setViewportWidth(1900);+ mockGroupPx = 1610;+ docCtx = DOC_LIVE_CTX;+ const view = render(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,+ );+ groupLayout = {+ 'editor-main': 100 - (320 / 1610) * 100 - 44,+ 'doc-panel': (320 / 1610) * 100,+ 'terminal-column': 44,+ 'agents-column': 0,+ };+ rejectGroupLayoutWrites = true;++ const warnings = await withSynchronousFrames(() => {+ view.rerender(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,+ );+ mockGroupPx = 0;+ docCtx = EMPTY_DOC_CTX;+ view.rerender(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,+ );+ });++ const [fromColumnSync, fromDocSlot] = readExhaustedReports(warnings);+ expect(fromColumnSync?.trigger).toBe('rail-column-sync');+ expect(fromColumnSync?.stage).toBe('width-shortfall');+ expect(fromColumnSync?.shortfall?.['terminal-column']).toEqual({+ targetPx: 740,+ renderedPx: expect.closeTo((44 / 100) * 1610, 6),+ });+ expect(fromDocSlot?.trigger).toBe('doc-slot-presence');+ expect(fromDocSlot?.stage).toBe('panel-space-unresolved');+ expect(fromDocSlot?.refusal).toBe('panel-space-empty');+ expect(fromDocSlot?.shortfall).toBeUndefined();+ });++ test('a layout carrying stray ids reports them instead of a bare missing-residual', async () => {+ setViewportWidth(1900);+ mockGroupPx = 1610;+ docCtx = DOC_LIVE_CTX;+ const view = render(+ <EditorArea+ {...baseProps}+ terminalVisible={false}+ terminalPlacement="right"+ agentsVisible={false}+ />,+ );+ groupLayout = { 'editor-main': 50, 'preview-main': 50 };+ groupSetLayoutCalls = [];++ const warnings = await withSynchronousFrames(() => {+ view.rerender(+ <EditorArea+ {...baseProps}+ terminalVisible+ terminalPlacement="right"+ agentsVisible={false}+ />,+ );+ });++ expect(groupSetLayoutCalls).toHaveLength(0);+ const exhausted = readExhaustedReports(warnings).at(0);+ expect(exhausted).toBeDefined();+ expect(exhausted?.trigger).toBe('rail-column-sync');+ expect(exhausted?.stage).toBe('layout-unaccounted');+ expect(exhausted?.unaccountedIds).toEqual(['editor-main', 'preview-main']);+ });++ test('a rail with no room for its floor widths reports the pin it could not place', async () => {+ setViewportWidth(500);+ mockGroupPx = 300;+ docCtx = DOC_LIVE_CTX;+ const view = render(+ <EditorArea+ {...baseProps}+ terminalVisible={false}+ terminalPlacement="right"+ agentsVisible={false}+ />,+ );+ groupLayout = {+ 'editor-main': 60,+ 'doc-panel': 0,+ 'terminal-column': 40,+ 'agents-column': 0,+ };+ groupSetLayoutCalls = [];++ const warnings = await withSynchronousFrames(() => {+ view.rerender(+ <EditorArea+ {...baseProps}+ terminalVisible+ terminalPlacement="right"+ agentsVisible={false}+ />,+ );+ });++ expect(groupSetLayoutCalls).toHaveLength(0);+ const exhausted = readExhaustedReports(warnings).at(0);+ expect(exhausted).toBeDefined();+ expect(exhausted?.trigger).toBe('rail-column-sync');+ expect(exhausted?.stage).toBe('pins-do-not-fit');+ expect(exhausted?.shortfall?.['terminal-column']).toEqual({+ targetPx: RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,+ renderedPx: expect.closeTo((40 / 100) * 300, 6),+ });+ });++ test('a rail short of its floors leaves out the column that is already wide enough', async () => {+ const DOC_PANEL_FLOOR_PX = 300;+ const groupPx = DOC_PANEL_FLOOR_PX + RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - 5;+ const terminalRenderedPx = RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX + 175;+ const docRenderedPx = 40;+ setViewportWidth(700);+ mockGroupPx = groupPx;+ docCtx = DOC_LIVE_CTX;+ const view = render(+ <EditorArea+ {...baseProps}+ terminalVisible={false}+ terminalPlacement="right"+ agentsVisible={false}+ />,+ );+ act(() => emitLocalMenuAction('toggle-doc-panel'));+ groupLayout = {+ 'editor-main': ((groupPx - terminalRenderedPx - docRenderedPx) / groupPx) * 100,+ 'doc-panel': (docRenderedPx / groupPx) * 100,+ 'terminal-column': (terminalRenderedPx / groupPx) * 100,+ 'agents-column': 0,+ };++ const warnings = await withSynchronousFrames(() => {+ view.rerender(+ <EditorArea+ {...baseProps}+ terminalVisible+ terminalPlacement="right"+ agentsVisible={false}+ />,+ );+ });++ const exhausted = readExhaustedReports(warnings).at(0);+ expect(exhausted).toBeDefined();+ expect(exhausted?.trigger).toBe('rail-column-sync');+ expect(exhausted?.stage).toBe('pins-do-not-fit');+ expect(Object.keys(exhausted?.shortfall ?? {})).toEqual(['doc-panel']);+ expect(exhausted?.shortfall?.['doc-panel']).toEqual({+ targetPx: DOC_PANEL_FLOOR_PX,+ renderedPx: expect.closeTo(docRenderedPx, 6),+ });+ });++ test('a pin that can never land stops reporting once the mount has had its say', async () => {+ setViewportWidth(1900);+ mockGroupPx = 1610;+ docCtx = DOC_LIVE_CTX;+ const view = render(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,+ );+ groupLayout = {+ 'editor-main': 100 - (320 / 1610) * 100 - 44,+ 'doc-panel': (320 / 1610) * 100,+ 'terminal-column': 44,+ 'agents-column': 0,+ };+ rejectGroupLayoutWrites = true;++ const warnings = await withSynchronousFrames(() => {+ for (let toggle = 0; toggle < MAX_RAIL_PIN_EXHAUSTED_REPORTS + 3; toggle += 1) {+ view.rerender(+ <EditorArea+ {...baseProps}+ terminalVisible+ terminalPlacement="right"+ agentsVisible={toggle % 2 === 0}+ />,+ );+ }+ });++ expect(+ readExhaustedReports(warnings).filter((report) => report.trigger === 'rail-column-sync')+ .length,+ ).toBe(MAX_RAIL_PIN_EXHAUSTED_REPORTS);+ });++ test('one exhausted trigger does not spend the budget the other trigger needs', async () => {+ setViewportWidth(1900);+ mockGroupPx = 1610;+ docCtx = DOC_LIVE_CTX;+ const view = render(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,+ );+ groupLayout = {+ 'editor-main': 100 - (320 / 1610) * 100 - 44,+ 'doc-panel': (320 / 1610) * 100,+ 'terminal-column': 44,+ 'agents-column': 0,+ };+ rejectGroupLayoutWrites = true;++ const warnings = await withSynchronousFrames(() => {+ for (let toggle = 0; toggle < MAX_RAIL_PIN_EXHAUSTED_REPORTS + 3; toggle += 1) {+ view.rerender(+ <EditorArea+ {...baseProps}+ terminalVisible+ terminalPlacement="right"+ agentsVisible={toggle % 2 === 0}+ />,+ );+ }+ mockGroupPx = 0;+ docCtx = EMPTY_DOC_CTX;+ view.rerender(+ <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,+ );+ });++ const reports = readExhaustedReports(warnings);+ expect(reports.filter((report) => report.trigger === 'rail-column-sync').length).toBe(+ MAX_RAIL_PIN_EXHAUSTED_REPORTS,+ );+ expect(reports.filter((report) => report.trigger === 'doc-slot-presence').length).toBe(1);+ });+test('revealing the agents panel keeps the open doc panel open despite a stale cached layout', async () => {setViewportWidth(1400);docCtx = DOC_LIVE_CTX;diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsxindex f7fafef25..3d81034a3 100644--- a/packages/app/src/components/EditorArea.tsx+++ b/packages/app/src/components/EditorArea.tsx@@ -97,6 +97,15 @@ import {type EditorWorkspacePaneRenderContext,} from './EditorWorkspace';import { shouldPaintOverlay } from './editor-area-overlay';+import {+ describeRailFloorShortfall,+ describeRailWidthShortfall,+ type RailPanelSpaceRefusal,+ type RailPanelSpaceResult,+ type RailWidthShortfall,+ resolveRailPanelSpace,+ resolveRailPanelSpacePx,+} from './editor-area-panel-space';import {AGENTS_COLUMN_ID,accountRailLayout,@@ -211,6 +220,23 @@ const LazyAgentDiffPane = lazy(async () => {return { default: mod.AgentDiffPane };});+export const MAX_RAIL_PIN_EXHAUSTED_REPORTS = 5;++type RailPinOutcome =+ | { readonly stage: 'pinned' }+ | { readonly stage: 'group-missing' }+ | { readonly stage: 'read-failed' }+ | { readonly stage: 'panel-space-unresolved'; readonly refusal: RailPanelSpaceRefusal }+ | { readonly stage: 'layout-unaccounted'; readonly unaccountedIds: readonly string[] }+ | { readonly stage: 'no-residual-panel' }+ | { readonly stage: 'no-pinned-columns' }+ | { readonly stage: 'pins-do-not-fit'; readonly shortfall: Record<string, RailWidthShortfall> }+ | { readonly stage: 'write-failed' }+ | { readonly stage: 'verify-failed' }+ | { readonly stage: 'width-shortfall'; readonly shortfall: Record<string, RailWidthShortfall> };++type RailPinExhaustedTrigger = 'rail-column-sync' | 'doc-slot-presence';+const DOC_PANEL_MIN_WIDTH_PX = 300;const DOC_PANEL_MIN_SIZE = `${DOC_PANEL_MIN_WIDTH_PX}px`;const DOC_PANEL_MAX_SIZE = '600px';@@ -499,17 +525,27 @@ function EditorAreaInner({const docSlotPresentRef = useRef(false);const presenceRepinFrameRef = useRef(0);+ const railPinOutcomeRef = useRef<RailPinOutcome>({ stage: 'group-missing' });+ const railPinExhaustedReportsRef = useRef<Record<RailPinExhaustedTrigger, number>>({+ 'rail-column-sync': 0,+ 'doc-slot-presence': 0,+ });++ const reportRailPinExhausted = useEffectEvent((trigger: RailPinExhaustedTrigger) => {+ if (railPinExhaustedReportsRef.current[trigger] >= MAX_RAIL_PIN_EXHAUSTED_REPORTS) return;+ railPinExhaustedReportsRef.current[trigger] += 1;+ console.warn(+ JSON.stringify({+ event: 'right-rail-pin-exhausted',+ trigger,+ ...railPinOutcomeRef.current,+ }),+ );+ });const groupRef = useGroupRef();function resolveGroupPxWidth(): number | null {- for (const ref of [panelRef, terminalColumnPanelRef, agentsColumnPanelRef]) {- const size = ref.current?.getSize();- if (size != null && size.asPercentage > 1 && size.inPixels > 0) {- return (size.inPixels / size.asPercentage) * 100;- }- }- const el = groupContainerElRef.current;- return el != null && el.offsetWidth > 0 ? el.offsetWidth : null;+ return resolveRailPanelSpacePx(groupContainerElRef.current);}function resolveAdmissionMetrics(): {@@ -611,19 +647,31 @@ function EditorAreaInner({function applyRailLayout(docCollapsed: boolean): boolean {const group = groupRef.current;- if (group == null) return false;- let containerPx: number | null;+ if (group == null) {+ railPinOutcomeRef.current = { stage: 'group-missing' };+ return false;+ }+ let panelSpace: RailPanelSpaceResult;let layout: Record<string, number>;try {- containerPx = resolveGroupPxWidth();+ panelSpace = resolveRailPanelSpace(groupContainerElRef.current);layout = group.getLayout();} catch (error) {+ railPinOutcomeRef.current = { stage: 'read-failed' };reportUnexpectedPanelGroupFailure('apply-rail-layout-read-failed', error);return false;}- if (containerPx == null) return false;+ if (!panelSpace.ok) {+ railPinOutcomeRef.current = { stage: 'panel-space-unresolved', refusal: panelSpace.refusal };+ return false;+ }+ const containerPx = panelSpace.panelSpacePx;const accounting = accountRailLayout(Object.keys(layout));if (!accounting.ok) {+ railPinOutcomeRef.current =+ accounting.unaccountedIds.length === 0+ ? { stage: 'no-residual-panel' }+ : { stage: 'layout-unaccounted', unaccountedIds: accounting.unaccountedIds };if (import.meta.env.DEV) {console.warn(JSON.stringify({@@ -635,7 +683,6 @@ function EditorAreaInner({return false;}const residualId = accounting.residualId;- if (residualId == null) return false;const buildPins = (atFloor: boolean): Record<string, number> => {const pins: Record<string, number> = {};@@ -664,8 +711,17 @@ function EditorAreaInner({return pins;};+ const widthsFrom = (pcts: Record<string, number>) => {+ const widths = new Map<string, number>();+ for (const [id, pct] of Object.entries(pcts)) widths.set(id, (pct / 100) * containerPx);+ return widths;+ };+let pins = buildPins(false);- if (Object.keys(pins).length === 0) return false;+ if (Object.keys(pins).length === 0) {+ railPinOutcomeRef.current = { stage: 'no-pinned-columns' };+ return false;+ }let next = computeStickyRepinLayout({currentLayout: layout,@@ -682,10 +738,18 @@ function EditorAreaInner({residualId,});}- if (next === layout) return true;+ if (next === layout) {+ const shortfall = describeRailFloorShortfall(pins, widthsFrom(layout));+ const pinned = Object.keys(shortfall).length === 0;+ railPinOutcomeRef.current = pinned+ ? { stage: 'pinned' }+ : { stage: 'pins-do-not-fit', shortfall };+ return pinned;+ }try {group.setLayout(next);} catch (error) {+ railPinOutcomeRef.current = { stage: 'write-failed' };reportUnexpectedPanelGroupFailure('apply-rail-layout-write-failed', error);return false;}@@ -693,15 +757,16 @@ function EditorAreaInner({try {readBack = group.getLayout();} catch (error) {+ railPinOutcomeRef.current = { stage: 'verify-failed' };reportUnexpectedPanelGroupFailure('apply-rail-layout-verify-failed', error);return false;}- for (const [id, px] of Object.entries(pins)) {- const pct = readBack[id];- if (pct == null) continue;- if (Math.abs((pct / 100) * containerPx - px) > 1) return false;- }- return true;+ const shortfall = describeRailWidthShortfall(pins, widthsFrom(readBack));+ const pinned = Object.keys(shortfall).length === 0;+ railPinOutcomeRef.current = pinned+ ? { stage: 'pinned' }+ : { stage: 'width-shortfall', shortfall };+ return pinned;}function reclaimHiddenRailColumn(columnId: string, present: boolean, widthPx: number) {@@ -797,11 +862,15 @@ function EditorAreaInner({return applyRailLayout(isCollapsedRef.current);}- // biome-ignore lint/correctness/useExhaustiveDependencies: see above.+ // biome-ignore lint/correctness/useExhaustiveDependencies: syncRailColumns is render-bound but reads only refs, so the mount closure stays current; listing it would restart the retry loop on every renderuseEffect(() => {const frameRef = { id: 0 };const attempt = (attemptsLeft: number) => {- if (syncRailColumns() || attemptsLeft <= 0) return;+ if (syncRailColumns()) return;+ if (attemptsLeft <= 0) {+ reportRailPinExhausted('rail-column-sync');+ return;+ }frameRef.id = requestAnimationFrame(() => attempt(attemptsLeft - 1));};attempt(30);@@ -1195,7 +1264,11 @@ function EditorAreaInner({const docCollapsed = isCollapsedRef.current;const attempt = (attemptsLeft: number) => {presenceRepinFrameRef.current = 0;- if (assertRightRailLayoutRef.current(docCollapsed) || attemptsLeft <= 0) return;+ if (assertRightRailLayoutRef.current(docCollapsed)) return;+ if (attemptsLeft <= 0) {+ reportRailPinExhausted('doc-slot-presence');+ return;+ }presenceRepinFrameRef.current = requestAnimationFrame(() => attempt(attemptsLeft - 1));};attempt(30);diff --git a/packages/app/src/components/editor-area-panel-space.dom.test.tsx b/packages/app/src/components/editor-area-panel-space.dom.test.tsxnew file mode 100644index 000000000..1d15d4187--- /dev/null+++ b/packages/app/src/components/editor-area-panel-space.dom.test.tsx@@ -0,0 +1,351 @@+import { act, cleanup, render } from '@testing-library/react';+import * as ResizablePrimitive from 'react-resizable-panels';+import { afterEach, describe, expect, test } from 'vitest';+import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';+import {+ describeRailFloorShortfall,+ describeRailWidthShortfall,+ findRailPanelGroup,+ resolveRailPanelSpace,+ resolveRailPanelSpacePx,+} from './editor-area-panel-space';+import { RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX } from './right-rail-admission';++const PREFERRED_TERMINAL_WIDTH_PX = 740;+const SPEC_TERMINAL_WIDTH_FLOOR_PX = 739;+const DOC_PANEL_FLOOR_PX = 300;+const SEPARATOR_WIDTH_PX = 1;++function railPanels(group: HTMLElement) {+ return [...group.querySelectorAll<HTMLElement>(':scope > [data-panel]')];+}++function measurePanelsFromFlexGrow(container: HTMLElement, groupBoxPx: number) {+ const group = findRailPanelGroup(container);+ if (group == null) throw new Error('panel group not found');+ const panels = railPanels(group);+ const separatorCount = group.querySelectorAll(':scope > [data-separator]').length;+ const panelSpacePx = groupBoxPx - separatorCount * SEPARATOR_WIDTH_PX;+ const totalGrow = panels.reduce(+ (total, panel) => total + Number.parseFloat(panel.style.flexGrow || '0'),+ 0,+ );+ for (const panel of panels) {+ const grow = Number.parseFloat(panel.style.flexGrow || '0');+ const width = totalGrow === 0 ? 0 : (grow / totalGrow) * panelSpacePx;+ Object.defineProperty(panel, 'getBoundingClientRect', {+ configurable: true,+ value: () => ({ width, height: 0, top: 0, left: 0, right: width, bottom: 0, x: 0, y: 0 }),+ });+ Object.defineProperty(panel, 'offsetWidth', {+ configurable: true,+ get: () => Math.round(width),+ });+ }+ return { panelSpacePx, panels };+}++function stubPanelWidths(container: HTMLElement, widths: readonly number[]) {+ const group = findRailPanelGroup(container);+ if (group == null) throw new Error('panel group not found');+ const panels = railPanels(group);+ if (panels.length !== widths.length) {+ throw new Error(`expected ${widths.length} panels, found ${panels.length}`);+ }+ panels.forEach((panel, index) => {+ const width = widths[index] ?? 0;+ Object.defineProperty(panel, 'getBoundingClientRect', {+ configurable: true,+ value: () => ({ width, height: 0, top: 0, left: 0, right: width, bottom: 0, x: 0, y: 0 }),+ });+ Object.defineProperty(panel, 'offsetWidth', {+ configurable: true,+ get: () => Math.round(width),+ });+ });+}++function buildRailContainer(panelIds: readonly string[]): HTMLElement {+ const container = document.createElement('div');+ const group = document.createElement('div');+ group.setAttribute('data-group', 'true');+ container.append(group);+ for (const id of panelIds) {+ const panel = document.createElement('div');+ panel.setAttribute('data-panel', 'true');+ panel.id = id;+ group.append(panel);+ }+ document.body.append(container);+ return container;+}++afterEach(() => {+ cleanup();+ document.body.replaceChildren();+});++describe('rail panel space is the sum of the panels, not an estimate from one of them', () => {+ test('resolves the exact fractional space a flex container distributes', () => {+ const container = buildRailContainer([+ 'editor-main',+ 'doc-panel',+ 'terminal-column',+ 'agents-column',+ ]);+ const panelSpacePx = 1609.4;+ const shares = [0.29, 0.1988, 0.4598, 0.0514];+ stubPanelWidths(+ container,+ shares.map((share) => share * panelSpacePx),+ );++ expect(resolveRailPanelSpacePx(container)).toBeCloseTo(panelSpacePx, 6);+ expect(resolveRailPanelSpace(container)).toEqual({+ ok: true,+ panelSpacePx: expect.closeTo(panelSpacePx, 6),+ });+ });++ test('a panel whose offsetWidth rounds away from its rendered width does not move the result', () => {+ const container = buildRailContainer(['editor-main', 'doc-panel', 'terminal-column']);+ const widths = [1000.25, 320.4998, PREFERRED_TERMINAL_WIDTH_PX];+ stubPanelWidths(container, widths);++ const docPanel = container.querySelector('#doc-panel');+ if (!(docPanel instanceof HTMLElement)) throw new Error('doc panel not found');+ expect(docPanel.offsetWidth).toBe(320);++ expect(resolveRailPanelSpacePx(container)).toBeCloseTo(+ widths.reduce((total, width) => total + width, 0),+ 6,+ );+ });++ test('a terminal pin taken against the resolved space renders above the spec floor', () => {+ const container = buildRailContainer([+ 'editor-main',+ 'doc-panel',+ 'terminal-column',+ 'agents-column',+ ]);+ const panelSpacePx = 1609.4;+ stubPanelWidths(container, [469.4, 320, PREFERRED_TERMINAL_WIDTH_PX, 80]);++ const resolvedSpacePx = resolveRailPanelSpacePx(container);+ if (resolvedSpacePx == null) throw new Error('panel space did not resolve');+ const renderedWidthPx =+ ((PREFERRED_TERMINAL_WIDTH_PX / resolvedSpacePx) * 100 * panelSpacePx) / 100;++ expect(renderedWidthPx).toBeCloseTo(PREFERRED_TERMINAL_WIDTH_PX, 6);+ expect(renderedWidthPx).toBeGreaterThan(SPEC_TERMINAL_WIDTH_FLOOR_PX);+ });++ test('a nested group inside a panel does not contribute its panels', () => {+ const container = buildRailContainer(['editor-main', 'terminal-column']);+ const editorPanel = container.querySelector('#editor-main');+ if (!(editorPanel instanceof HTMLElement)) throw new Error('editor panel not found');+ const nestedGroup = document.createElement('div');+ nestedGroup.setAttribute('data-group', 'true');+ const nestedPanel = document.createElement('div');+ nestedPanel.setAttribute('data-panel', 'true');+ nestedPanel.id = 'bottom-dock';+ nestedGroup.append(nestedPanel);+ editorPanel.append(nestedGroup);+ stubPanelWidths(container, [900, PREFERRED_TERMINAL_WIDTH_PX]);++ expect(resolveRailPanelSpacePx(container)).toBeCloseTo(1640, 6);+ });++ test('refuses to answer when the container holds no panel group', () => {+ const container = document.createElement('div');+ document.body.append(container);+ expect(resolveRailPanelSpacePx(container)).toBeNull();+ expect(resolveRailPanelSpacePx(null)).toBeNull();+ });+});++describe('a refusal to resolve the panel space names the structure that was missing', () => {+ test('a container with no panel group refuses on the group, present or absent', () => {+ const container = document.createElement('div');+ document.body.append(container);++ expect(resolveRailPanelSpace(container)).toEqual({+ ok: false,+ refusal: 'group-element-missing',+ });+ expect(resolveRailPanelSpace(null)).toEqual({ ok: false, refusal: 'group-element-missing' });+ expect(resolveRailPanelSpacePx(container)).toBeNull();+ });++ test('a panel group holding no panels refuses on the panels, not the group', () => {+ const container = buildRailContainer([]);+ const group = findRailPanelGroup(container);+ if (group == null) throw new Error('panel group not found');++ expect(railPanels(group)).toEqual([]);+ expect(resolveRailPanelSpace(container)).toEqual({ ok: false, refusal: 'panels-unreadable' });+ expect(resolveRailPanelSpacePx(container)).toBeNull();+ });++ test('panels that rendered with no width of their own refuse on the space, not the markup', () => {+ const container = buildRailContainer(['editor-main', 'terminal-column']);+ const group = findRailPanelGroup(container);+ if (group == null) throw new Error('panel group not found');+ stubPanelWidths(container, [0, 0]);++ expect(railPanels(group)).toHaveLength(2);+ expect(resolveRailPanelSpace(container)).toEqual({ ok: false, refusal: 'panel-space-empty' });+ expect(resolveRailPanelSpacePx(container)).toBeNull();+ });+});++describe('a pin that did not land is reported with the width it actually got', () => {+ test('names every pinned column whose width missed its target by more than a pixel', () => {+ const shortfall = describeRailWidthShortfall(+ { 'terminal-column': PREFERRED_TERMINAL_WIDTH_PX, 'agents-column': 400 },+ new Map([+ ['terminal-column', 738.62],+ ['agents-column', 400.38],+ ]),+ );++ expect(Object.keys(shortfall)).toEqual(['terminal-column']);+ expect(shortfall['terminal-column']?.targetPx).toBe(PREFERRED_TERMINAL_WIDTH_PX);+ expect(shortfall['terminal-column']?.renderedPx).toBeCloseTo(738.62, 6);+ });++ test('reports nothing when every pinned column landed', () => {+ expect(+ describeRailWidthShortfall(+ { 'terminal-column': PREFERRED_TERMINAL_WIDTH_PX },+ new Map([+ ['editor-main', 870],+ ['terminal-column', PREFERRED_TERMINAL_WIDTH_PX],+ ]),+ ),+ ).toEqual({});+ });++ test('a pinned column with no width of its own is not reported the way a landed pin is', () => {+ expect(+ describeRailWidthShortfall(+ { 'terminal-column': PREFERRED_TERMINAL_WIDTH_PX },+ new Map([['doc-panel', 320]]),+ ),+ ).toEqual({ 'terminal-column': { targetPx: PREFERRED_TERMINAL_WIDTH_PX, renderedPx: null } });+ });+});++describe('a floor that could not be honoured names only the columns rendered under it', () => {+ test('a column wider than its floor is left out while a column under its floor is named', () => {+ const shortfall = describeRailFloorShortfall(+ {+ 'terminal-column': RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,+ 'doc-panel': DOC_PANEL_FLOOR_PX,+ },+ new Map([+ ['terminal-column', PREFERRED_TERMINAL_WIDTH_PX],+ ['doc-panel', 40],+ ]),+ );++ expect(Object.keys(shortfall)).toEqual(['doc-panel']);+ expect(shortfall['doc-panel']).toEqual({ targetPx: DOC_PANEL_FLOOR_PX, renderedPx: 40 });+ });++ test('a hidden column still holding width is named even though it is over its pin', () => {+ const shortfall = describeRailFloorShortfall(+ {+ 'agents-column': 0,+ 'terminal-column': RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,+ },+ new Map([+ ['agents-column', 400],+ ['terminal-column', PREFERRED_TERMINAL_WIDTH_PX],+ ]),+ );++ expect(Object.keys(shortfall)).toEqual(['agents-column']);+ expect(shortfall['agents-column']).toEqual({ targetPx: 0, renderedPx: 400 });+ });++ test('reports nothing when every column sits within a pixel of the floor it needs', () => {+ expect(+ describeRailFloorShortfall(+ {+ 'terminal-column': RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,+ 'doc-panel': DOC_PANEL_FLOOR_PX,+ },+ new Map([+ ['terminal-column', RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - 0.5],+ ['doc-panel', DOC_PANEL_FLOOR_PX],+ ]),+ ),+ ).toEqual({});+ });+});++describe('the markers the resolver keys on are the ones the panel library guarantees', () => {+ test('a rendered ResizablePanelGroup exposes them, and flex-grow shares drive panel widths', () => {+ const view = render(+ <div data-editor-area-panels="">+ <ResizablePanelGroup orientation="horizontal">+ <ResizablePanel id="editor-main" defaultSize="29%" />+ <ResizableHandle />+ <ResizablePanel id="terminal-column" defaultSize="46%" />+ <ResizableHandle />+ <ResizablePanel id="agents-column" defaultSize="25%" />+ </ResizablePanelGroup>+ </div>,+ );+ const container = view.container.querySelector('[data-editor-area-panels]');+ if (!(container instanceof HTMLElement)) throw new Error('rail container not found');++ const group = findRailPanelGroup(container);+ expect(group).toBe(container.firstElementChild);+ if (group == null) throw new Error('panel group not found');+ expect(railPanels(group).map((panel) => panel.id)).toEqual([+ 'editor-main',+ 'terminal-column',+ 'agents-column',+ ]);++ let measured: ReturnType<typeof measurePanelsFromFlexGrow> | null = null;+ act(() => {+ measured = measurePanelsFromFlexGrow(container, 1612);+ });+ if (measured == null) throw new Error('panels were not measured');+ const { panelSpacePx } = measured;+ expect(panelSpacePx).toBe(1610);++ expect(resolveRailPanelSpacePx(container)).toBeCloseTo(panelSpacePx, 6);+ });++ test('a panel rendered straight from the library still counts toward the panel space', () => {+ const view = render(+ <div data-editor-area-panels="">+ <ResizablePanelGroup orientation="horizontal">+ <ResizablePanel id="editor-main" defaultSize="50%" />+ <ResizableHandle />+ <ResizablePrimitive.Panel id="terminal-column" defaultSize="50%" />+ </ResizablePanelGroup>+ </div>,+ );+ const container = view.container.querySelector('[data-editor-area-panels]');+ if (!(container instanceof HTMLElement)) throw new Error('rail container not found');+ const terminalPanel = container.querySelector('#terminal-column');+ if (!(terminalPanel instanceof HTMLElement)) throw new Error('terminal panel not found');+ expect(terminalPanel.getAttribute('data-slot')).toBeNull();++ let measured: ReturnType<typeof measurePanelsFromFlexGrow> | null = null;+ act(() => {+ measured = measurePanelsFromFlexGrow(container, 1201);+ });+ if (measured == null) throw new Error('panels were not measured');+ const { panelSpacePx } = measured;+ expect(panelSpacePx).toBe(1200);++ expect(resolveRailPanelSpacePx(container)).toBeCloseTo(panelSpacePx, 6);+ });+});diff --git a/packages/app/src/components/editor-area-panel-space.ts b/packages/app/src/components/editor-area-panel-space.tsnew file mode 100644index 000000000..c68b5157a--- /dev/null+++ b/packages/app/src/components/editor-area-panel-space.ts@@ -0,0 +1,108 @@+const GROUP_SELECTOR = ':scope > [data-group]';+const PANEL_SELECTOR = ':scope > [data-panel]';++export function findRailPanelGroup(container: Element | null | undefined): HTMLElement | null {+ const group = container?.querySelector(GROUP_SELECTOR);+ return group instanceof HTMLElement ? group : null;+}++function readRailPanelElements(group: HTMLElement): HTMLElement[] | null {+ const panels: HTMLElement[] = [];+ for (const panel of group.querySelectorAll(PANEL_SELECTOR)) {+ if (!(panel instanceof HTMLElement)) return null;+ panels.push(panel);+ }+ return panels.length === 0 ? null : panels;+}++function readPanelWidthPx(panel: HTMLElement): number | null {+ const { width } = panel.getBoundingClientRect();+ return Number.isFinite(width) && width >= 0 ? width : null;+}++export type RailPanelSpaceRefusal =+ | 'group-element-missing'+ | 'panels-unreadable'+ | 'panel-space-empty';++export type RailPanelSpaceResult =+ | { readonly ok: true; readonly panelSpacePx: number }+ | { readonly ok: false; readonly refusal: RailPanelSpaceRefusal };++/*+ * UPSTREAM([email protected]): this sum stands in for the library's own+ * `calculateAvailableGroupSize`, which `GroupImperativeHandle` exposes no accessor+ * for. That function never runs a selector; it reduces its own `group.panels`+ * registry over each registered panel's `element.offsetWidth`, and that total stays+ * authoritative for the clamp it feeds: the divisor turning the doc panel's px+ * `minSize`/`maxSize` into the percentages `setLayout` validates against. The two+ * totals are not equal. `offsetWidth` rounds per panel, and keeping that rounding+ * out of the rail arithmetic is why this file exists, so what must keep holding is+ * the element set rather than the total. The library requires panel elements to be+ * direct DOM children of their group (`react-resizable-panels.d.ts:212`), which is+ * what lets this selector stand in for its registry, so putting a wrapper between+ * the two drops a panel from this sum.+ */+export function resolveRailPanelSpace(container: Element | null | undefined): RailPanelSpaceResult {+ const group = findRailPanelGroup(container);+ if (group == null) return { ok: false, refusal: 'group-element-missing' };+ const panels = readRailPanelElements(group);+ if (panels == null) return { ok: false, refusal: 'panels-unreadable' };+ let panelSpacePx = 0;+ for (const panel of panels) {+ const widthPx = readPanelWidthPx(panel);+ if (widthPx == null) return { ok: false, refusal: 'panel-space-empty' };+ panelSpacePx += widthPx;+ }+ return panelSpacePx > 0+ ? { ok: true, panelSpacePx }+ : { ok: false, refusal: 'panel-space-empty' };+}++export function resolveRailPanelSpacePx(container: Element | null | undefined): number | null {+ const result = resolveRailPanelSpace(container);+ return result.ok ? result.panelSpacePx : null;+}++export interface RailWidthShortfall {+ readonly targetPx: number;+ readonly renderedPx: number | null;+}++function missesExactTarget(renderedPx: number, targetPx: number): boolean {+ return Math.abs(renderedPx - targetPx) > 1;+}++function collectShortfall(+ targetsPx: Readonly<Record<string, number>>,+ renderedWidths: ReadonlyMap<string, number>,+ isShort: (renderedPx: number, targetPx: number) => boolean,+): Record<string, RailWidthShortfall> {+ const shortfall: Record<string, RailWidthShortfall> = {};+ for (const [id, targetPx] of Object.entries(targetsPx)) {+ const renderedPx = renderedWidths.get(id);+ if (renderedPx == null) {+ shortfall[id] = { targetPx, renderedPx: null };+ continue;+ }+ if (!isShort(renderedPx, targetPx)) continue;+ shortfall[id] = { targetPx, renderedPx };+ }+ return shortfall;+}++export function describeRailWidthShortfall(+ pinnedPx: Readonly<Record<string, number>>,+ renderedWidths: ReadonlyMap<string, number>,+): Record<string, RailWidthShortfall> {+ return collectShortfall(pinnedPx, renderedWidths, missesExactTarget);+}++export function describeRailFloorShortfall(+ floorPx: Readonly<Record<string, number>>,+ renderedWidths: ReadonlyMap<string, number>,+): Record<string, RailWidthShortfall> {+ return collectShortfall(floorPx, renderedWidths, (renderedPx, targetPx) =>+ targetPx === 0 ? missesExactTarget(renderedPx, targetPx) : renderedPx < targetPx - 1,+ );+}diff --git a/packages/app/src/components/editor-area-rail-registry.ts b/packages/app/src/components/editor-area-rail-registry.tsindex c340439bc..4bcd491b2 100644--- a/packages/app/src/components/editor-area-rail-registry.ts+++ b/packages/app/src/components/editor-area-rail-registry.ts@@ -24,12 +24,19 @@ export function findResidualPanelId(layoutIds: Iterable<string>): string | nullreturn count === 1 ? residual : null;}-export interface RailLayoutAccounting {- readonly residualId: string | null;- readonly presentPeers: readonly RightRailPanelId[];- readonly unaccountedIds: readonly string[];- readonly ok: boolean;-}+export type RailLayoutAccounting =+ | {+ readonly ok: true;+ readonly residualId: string;+ readonly presentPeers: readonly RightRailPanelId[];+ readonly unaccountedIds: readonly string[];+ }+ | {+ readonly ok: false;+ readonly residualId: string | null;+ readonly presentPeers: readonly RightRailPanelId[];+ readonly unaccountedIds: readonly string[];+ };export function accountRailLayout(layoutIds: Iterable<string>): RailLayoutAccounting {const ids = [...layoutIds];@@ -38,6 +45,8 @@ export function accountRailLayout(layoutIds: Iterable<string>): RailLayoutAccounconst accounted = new Set<string>(presentPeers);if (residualId != null) accounted.add(residualId);const unaccountedIds = ids.filter((id) => !accounted.has(id));- const ok = residualId != null && unaccountedIds.length === 0;- return { residualId, presentPeers, unaccountedIds, ok };+ if (residualId == null || unaccountedIds.length > 0) {+ return { ok: false, residualId, presentPeers, unaccountedIds };+ }+ return { ok: true, residualId, presentPeers, unaccountedIds };}diff --git a/packages/app/tests/stress/rail-flex-distribution-law.e2e.ts b/packages/app/tests/stress/rail-flex-distribution-law.e2e.tsnew file mode 100644index 000000000..17778c479--- /dev/null+++ b/packages/app/tests/stress/rail-flex-distribution-law.e2e.ts@@ -0,0 +1,117 @@+import type { Page } from '@playwright/test';+import { AGENTS_COLUMN_ID } from '../../src/components/editor-area-rail-registry';+import { expect, test, waitForActiveProviderSynced } from './_helpers';++const RAIL_GROUP_SELECTOR = '[data-editor-area-panels] > [data-group]';+const AGENTS_PANEL_MOUNT = '[data-agents-panel-mount]';+const AGENTS_REVEAL_TAB = '[data-terminal-reveal="right"]';++const VIEWPORT_HEIGHT = 800;+const SWEEP_VIEWPORT_WIDTHS = [1281, 1367, 1451, 1610, 1733] as const;+const PROPORTIONALITY_TOLERANCE_PX = 0.25;+const MIN_RENDERED_RAIL_PANELS = 3;+const BOOT_TIMEOUT_MS = 30_000;+const LAYOUT_SETTLE_TIMEOUT_MS = 10_000;++const DOC_MARKDOWN = `---+title: "Rail flex distribution"+description: "Fixture doc for the rail flex-distribution law"+---++# Rail flex distribution++Body text so the editor column renders real content while the rail is measured.`;++interface RailPanelSample {+ readonly id: string;+ readonly widthPx: number;+ readonly flexGrow: number;+}++async function readRailPanels(page: Page): Promise<RailPanelSample[]> {+ return page.evaluate((selector) => {+ const group = document.querySelector(selector);+ if (group == null) return [];+ return [...group.querySelectorAll<HTMLElement>(':scope > [data-panel]')].map(+ (panel, index) => ({+ id: panel.id === '' ? `panel-${index}` : panel.id,+ widthPx: panel.getBoundingClientRect().width,+ flexGrow: Number.parseFloat(panel.style.flexGrow || '0'),+ }),+ );+ }, RAIL_GROUP_SELECTOR);+}++async function railSpacePx(page: Page): Promise<number> {+ const panels = await readRailPanels(page);+ return panels.reduce((total, panel) => total + panel.widthPx, 0);+}++async function openAgentsColumn(page: Page): Promise<void> {+ const reveal = page.locator(AGENTS_REVEAL_TAB);+ await expect(reveal).toBeVisible({ timeout: BOOT_TIMEOUT_MS });+ await reveal.click();+ await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });+}++test.describe('right rail flex distribution law', () => {+ test('rendered rail widths stay proportional to flex-grow across a viewport sweep', async ({+ page,+ api,+ }) => {+ const docName = `rail-flex-law-${test.info().workerIndex}`;+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);+ await page.setViewportSize({ width: SWEEP_VIEWPORT_WIDTHS[0], height: VIEWPORT_HEIGHT });+ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);+ await openAgentsColumn(page);++ let previousSpacePx = 0;+ let subPixelSplitSamples = 0;++ for (const viewportWidth of SWEEP_VIEWPORT_WIDTHS) {+ await page.setViewportSize({ width: viewportWidth, height: VIEWPORT_HEIGHT });+ await expect+ .poll(() => railSpacePx(page), { timeout: LAYOUT_SETTLE_TIMEOUT_MS })+ .not.toBe(previousSpacePx);+ await page.evaluate(+ () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),+ );++ const panels = await readRailPanels(page);+ const spacePx = panels.reduce((total, panel) => total + panel.widthPx, 0);+ const totalGrow = panels.reduce((total, panel) => total + panel.flexGrow, 0);+ const renderedPanels = panels.filter((panel) => panel.widthPx > 1);+ const agentsPanel = panels.find((panel) => panel.id === AGENTS_COLUMN_ID);+ previousSpacePx = spacePx;++ expect(+ totalGrow,+ `viewport ${viewportWidth}: the rail panels must carry flex-grow for the law to say anything`,+ ).toBeGreaterThan(0);+ expect(+ renderedPanels.length,+ `viewport ${viewportWidth}: the law only constrains a rail that is splitting its space across several rendered panels`,+ ).toBeGreaterThanOrEqual(MIN_RENDERED_RAIL_PANELS);+ expect(+ agentsPanel?.widthPx ?? 0,+ `viewport ${viewportWidth}: the agents column must be open so the sweep measures a px-pinned column beside a residual one`,+ ).toBeGreaterThan(0);++ if (panels.some((panel) => !Number.isInteger(panel.widthPx))) subPixelSplitSamples += 1;++ for (const panel of panels) {+ const modelledPx = (panel.flexGrow / totalGrow) * spacePx;+ expect(+ Math.abs(panel.widthPx - modelledPx),+ `viewport ${viewportWidth}, panel ${panel.id}: the real engine rendered ${panel.widthPx}px, but distributing the rail's ${spacePx}px in proportion to flex-grow ${panel.flexGrow} of ${totalGrow} predicts ${modelledPx}px. The jsdom panel-space tier derives rail widths from exactly this formula, so a divergence here means that model no longer describes the browser and every DOM-tier rail width is measuring a fiction.`,+ ).toBeLessThanOrEqual(PROPORTIONALITY_TOLERANCE_PX);+ }+ }++ expect(+ subPixelSplitSamples,+ 'the sweep must land on at least one sub-pixel rail split, otherwise the law is only pinned where every panel happens to fall on a whole pixel',+ ).toBeGreaterThan(0);+ });+});