Acknowledge workspace taps promptly and reduce destination mount work (#9887)

* fix(app): acknowledge accepted workspace taps before navigation

Short taps finish before the delayed hold feedback paints, then navigation occupies JS. Paint accepted feedback on the native UI thread while retaining the existing press cancellation and delay rules.

* fix(app): avoid persistent tint on selected docked workspace rows

* perf(app): reduce workspace mount work and narrow panel subscriptions
This commit is contained in:
Mohamed Boudra authored and GitHub committed 2026-11-19 13:10:12 +07:00
1 parent 9faa3034f1
commit 808766ed7f
30 files changed
+905 -64

No files matched your search

+12 -5
View File
@@ -163,8 +163,16 @@ override a scroll away because they can arrive after the action that requested t
### Draw distance
`drawDistance` is 2000 px on each side of the viewport. A fling over rows that were never measured
blanks the viewport until LegendList renders and measures them. Twelve flings over a chat with a
The native timeline starts with one window-height of draw distance, up to 2000 px. This keeps
nearby rows ready for a fling during placement. Once the chat is placed, history is visible, and
the sidebar has settled, the timeline schedules expansion to 2000 px through two frame callbacks.
The callbacks leave time for the reveal to paint. Verify the actual reveal on the device.
A drag cancels a pending expansion and uses the existing buffer as the window moves. Expansion
resumes when the gesture settles, including momentum. In an Android emulator capture, expanding
the full buffer during the first fling changed the measured content height and returned the chat
to the end mid-fling.
A fling over rows that were never measured blanks the viewport
until LegendList renders and measures them. Twelve flings over a chat with a
15,000 px turn expanded, Android emulator, dev build:
| List | Blank viewport | Janky frames | p50 / p90 / p99 |
@@ -179,9 +187,8 @@ With every turn collapsed, flinging from a cold open into history did not blank
### LegendList patch
`patches/@legendapp+list+3.7.1.patch` carries twelve changes for the timeline. Its header lists
them by purpose, and
[legend-list #593](https://github.com/LegendApp/legend-list/issues/593) reports each upstream.
`patches/@legendapp+list+3.7.1.patch` lists its changes by purpose.
[legend-list #593](https://github.com/LegendApp/legend-list/issues/593) reports the first twelve.
Drop a hunk when the installed LegendList ships its fix.
### Scroll view corrections
@@ -0,0 +1,19 @@
apply plugin: 'com.android.library'
group = 'sh.paseo.pressfeedback'
version = '0.1.0'
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
apply from: expoModulesCorePlugin
applyKotlinExpoModulesCorePlugin()
useCoreDependencies()
useExpoPublishing()
useDefaultAndroidSdkVersions()
android {
namespace "sh.paseo.pressfeedback"
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
@@ -0,0 +1 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,39 @@
package sh.paseo.pressfeedback
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
import expo.modules.kotlin.types.ColorCompat
import expo.modules.kotlin.views.ExpoView
class PaseoPressFeedbackModule : Module() {
override fun definition() = ModuleDefinition {
Name("PaseoPressFeedback")
View(PaseoPressFeedbackView::class) {
Prop("tint") { view: PaseoPressFeedbackView, color: Color -> view.paint.color = ColorCompat.toArgb(color) }
Prop("radius") { view: PaseoPressFeedbackView, radius: Double -> view.radius = radius.toFloat() * view.resources.displayMetrics.density }
Prop("resetKey") { view: PaseoPressFeedbackView, key: String -> view.reset(key) }
AsyncFunction("acknowledge") { view: PaseoPressFeedbackView -> view.acknowledge() }
}
}
}
class PaseoPressFeedbackView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
var radius = 0f
private var acknowledged = false
private var resetKey = ""
init { setWillNotDraw(false); importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO }
fun acknowledge() { acknowledged = true; invalidate() }
fun reset(key: String) {
if (key != resetKey) { resetKey = key; acknowledged = false; invalidate() }
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (acknowledged) canvas.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), radius, radius, paint)
}
}
@@ -0,0 +1,5 @@
{
"platforms": ["android", "ios"],
"android": { "modules": ["sh.paseo.pressfeedback.PaseoPressFeedbackModule"] },
"ios": { "modules": ["PaseoPressFeedbackModule"] }
}
@@ -0,0 +1 @@
export { useWorkspaceRowPress } from "./src/ui";
@@ -0,0 +1,22 @@
Pod::Spec.new do |s|
s.name = 'PaseoPressFeedback'
s.version = '0.1.0'
s.summary = 'Native accepted press feedback for Paseo'
s.description = 'Paints accepted press feedback independently of React commits'
s.license = 'Apache-2.0'
s.author = 'Paseo'
s.homepage = 'https://paseo.sh'
s.platforms = { :ios => '15.1' }
s.swift_version = '5.4'
s.source = { :path => '.' }
s.static_framework = true
s.dependency 'ExpoModulesCore'
s.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES',
'SWIFT_COMPILATION_MODE' => 'wholemodule'
}
s.source_files = "**/*.{h,m,swift}"
end
@@ -0,0 +1,33 @@
import ExpoModulesCore
import UIKit
public class PaseoPressFeedbackModule: Module {
public func definition() -> ModuleDefinition {
Name("PaseoPressFeedback")
View(PaseoPressFeedbackView.self) {
Prop("tint") { (view: PaseoPressFeedbackView, color: UIColor) in view.tint = color }
Prop("radius") { (view: PaseoPressFeedbackView, radius: Double) in view.radius = radius }
Prop("resetKey") { (view: PaseoPressFeedbackView, key: String) in view.reset(key) }
AsyncFunction("acknowledge") { (view: PaseoPressFeedbackView) in view.acknowledge() }
}
}
}
final class PaseoPressFeedbackView: ExpoView {
var tint = UIColor.clear
var radius: Double = 0
private var acknowledged = false
private var resetKey = ""
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
isOpaque = false
isUserInteractionEnabled = false
}
func acknowledge() { acknowledged = true; setNeedsDisplay() }
func reset(_ key: String) {
if key != resetKey { resetKey = key; acknowledged = false; setNeedsDisplay() }
}
override func draw(_ rect: CGRect) {
if acknowledged { tint.setFill(); UIBezierPath(roundedRect: bounds, cornerRadius: radius).fill() }
}
}
@@ -0,0 +1,5 @@
{
"name": "paseo-press-feedback",
"version": "0.1.0",
"private": true
}
@@ -0,0 +1,104 @@
import { expect, it } from "vitest";
import { acceptWorkspaceRowPress, type WorkspaceRowPress } from "./accept";
function rowPress(overrides: Partial<WorkspaceRowPress> = {}) {
const visible: string[] = [];
const press: WorkspaceRowPress = {
cancelled: false,
native: true,
selected: false,
sidebar: "overlay",
target: "agent-list",
acknowledge: () => visible.push("row"),
navigate: () => visible.push("workspace"),
...overrides,
};
return { press, visible };
}
it("acknowledges an accepted row before navigation starts", () => {
const { press, visible } = rowPress();
expect(acceptWorkspaceRowPress(press)).toBe(true);
expect(visible).toEqual(["row", "workspace"]);
});
it("does not acknowledge or navigate after scrolling or a long press claims the touch", () => {
const { press, visible } = rowPress({ cancelled: true });
expect(acceptWorkspaceRowPress(press)).toBe(false);
expect(visible).toEqual([]);
});
it("accepts only the first row while its selection closes the sidebar", () => {
const { press, visible } = rowPress();
press.navigate = () => {
press.target = "agent";
visible.push("workspace B");
};
expect(acceptWorkspaceRowPress(press)).toBe(true);
expect(acceptWorkspaceRowPress(press)).toBe(false);
expect(visible).toEqual(["row", "workspace B"]);
});
it.each([
{
name: "open phone or tablet overlay",
sidebar: "overlay",
target: "agent-list",
native: true,
accepted: true,
},
{ name: "closing overlay", sidebar: "overlay", target: "agent", native: true, accepted: false },
{
name: "explorer covering an overlay",
sidebar: "overlay",
target: "file-explorer",
native: true,
accepted: false,
},
{ name: "docked sidebar", sidebar: "dock", target: "agent", native: true, accepted: true },
{
name: "docked sidebar beside explorer",
sidebar: "dock",
target: "file-explorer",
native: true,
accepted: true,
},
{ name: "hidden sidebar", sidebar: "hidden", target: "agent", native: true, accepted: false },
{
name: "suspended open overlay",
sidebar: "suspended",
target: "agent-list",
native: true,
accepted: true,
},
{
name: "suspended closed overlay",
sidebar: "suspended",
target: "agent",
native: true,
accepted: false,
},
{
name: "web sidebar independent of native panel target",
sidebar: "overlay",
target: "agent",
native: false,
accepted: true,
},
] as const)("uses the panel state for $name", ({ accepted, name: _, ...state }) => {
const { press, visible } = rowPress(state);
expect(acceptWorkspaceRowPress(press)).toBe(accepted);
expect(visible).toEqual(accepted ? ["row", "workspace"] : []);
});
it("does not leave an acknowledgement over an already selected docked row", () => {
const { press, visible } = rowPress({ selected: true, sidebar: "dock", target: "agent" });
expect(acceptWorkspaceRowPress(press)).toBe(true);
expect(visible).toEqual(["workspace"]);
});
it("still acknowledges a selected overlay row before the sidebar leaves", () => {
const { press, visible } = rowPress({ selected: true });
expect(acceptWorkspaceRowPress(press)).toBe(true);
expect(visible).toEqual(["row", "workspace"]);
});
@@ -0,0 +1,20 @@
import type { LeftSidebarPresentation, MobilePanelView } from "@/stores/panel-store";
export interface WorkspaceRowPress {
cancelled: boolean;
native: boolean;
selected: boolean;
sidebar: LeftSidebarPresentation;
target: MobilePanelView;
acknowledge(): void;
navigate(): void;
}
export function acceptWorkspaceRowPress(press: WorkspaceRowPress): boolean {
if (press.cancelled) return false;
if (press.native && press.sidebar !== "dock" && press.target !== "agent-list") return false;
// A selected docked row neither changes selection nor leaves the screen to clear the fill.
if (!press.selected || press.sidebar !== "dock") press.acknowledge();
press.navigate();
return true;
}
@@ -0,0 +1,47 @@
import { requireNativeView } from "expo";
import { type Ref } from "react";
import { usePanelStore } from "@/stores/panel-store";
import { withUnistyles } from "react-native-unistyles";
import { View, StyleSheet, type ViewProps } from "react-native";
export interface RowFeedbackHandle {
acknowledge(): Promise<void>;
}
interface FeedbackProps extends ViewProps {
ref?: Ref<RowFeedbackHandle>;
resetKey: string;
tint?: string;
radius?: number;
}
const NativeFeedback = withUnistyles(requireNativeView<FeedbackProps>("PaseoPressFeedback"));
const mapTheme = (theme: import("@/styles/theme").Theme) => ({
tint: theme.colors.interactionHighlight,
radius: theme.borderRadius.lg,
});
export function RowFeedback({
ref,
selected,
}: {
ref?: Ref<RowFeedbackHandle>;
selected: boolean;
}) {
const revision = usePanelStore((state) => state.mobilePanel.revision);
// Selection takes over the fill; a new panel transition clears it before reopening.
const resetKey = `${selected}:${revision}`;
return (
<View pointerEvents="none" style={styles.overlay}>
<NativeFeedback
ref={ref}
resetKey={resetKey}
pointerEvents="none"
style={styles.fill}
uniProps={mapTheme}
/>
</View>
);
}
const styles = StyleSheet.create({
overlay: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 },
fill: { flex: 1 },
});
@@ -0,0 +1,7 @@
import type { Ref } from "react";
export interface RowFeedbackHandle {
acknowledge(): Promise<void>;
}
export function RowFeedback(_props: { ref?: Ref<RowFeedbackHandle>; selected: boolean }) {
return null;
}
@@ -0,0 +1,38 @@
import { useCallback, useRef, type RefObject } from "react";
import { isNative } from "@/constants/platform";
import { usePanelStore } from "@/stores/panel-store";
import { acceptWorkspaceRowPress } from "../accept";
import { RowFeedback, type RowFeedbackHandle } from "./feedback";
export function useWorkspaceRowPress({
didLongPressRef,
onPress,
selected,
}: {
didLongPressRef?: RefObject<boolean>;
onPress(): void;
selected: boolean;
}) {
const feedback = useRef<RowFeedbackHandle>(null);
const handlePress = useCallback(() => {
const cancelled = didLongPressRef?.current ?? false;
if (didLongPressRef) didLongPressRef.current = false;
const panel = usePanelStore.getState();
acceptWorkspaceRowPress({
cancelled,
native: isNative,
selected,
sidebar: panel.layout.leftSidebar,
target: panel.mobilePanel.target,
// Paint on the native UI thread before navigation occupies JS; never wait for paint.
acknowledge: () => {
void feedback.current?.acknowledge();
},
navigate: onPress,
});
}, [didLongPressRef, onPress, selected]);
return {
onPress: handlePress,
feedback: <RowFeedback ref={feedback} selected={selected} />,
};
}
@@ -0,0 +1,85 @@
import { expect, it } from "vitest";
import { createInitialDrawDistanceExpansion } from "./initial-draw-distance";
function mountInitialBuffer() {
let nextId = 0;
const pending = new Map<number, () => void>();
const expansions: string[] = [];
const buffer = createInitialDrawDistanceExpansion(
{
requestFrame(callback) {
const id = ++nextId;
pending.set(id, callback);
return id;
},
cancelFrame(id) {
pending.delete(id);
},
},
() => expansions.push("full draw distance"),
);
function advanceFrame() {
const callbacks = [...pending.values()];
pending.clear();
for (const callback of callbacks) callback();
}
return { buffer, expansions, advanceFrame };
}
it("requests the full draw distance after two frame callbacks once the reveal is eligible", () => {
const { buffer, expansions, advanceFrame } = mountInitialBuffer();
buffer.schedule();
advanceFrame();
expect(expansions).toEqual([]);
advanceFrame();
expect(expansions).toEqual(["full draw distance"]);
});
it.each([0, 1])(
"leaves initial draw distance in place during a gesture after %i frames",
(elapsed) => {
const { buffer, expansions, advanceFrame } = mountInitialBuffer();
buffer.schedule();
if (elapsed === 1) advanceFrame();
buffer.pauseForScroll();
advanceFrame();
advanceFrame();
expect(expansions).toEqual([]);
buffer.resumeAfterScroll();
advanceFrame();
expect(expansions).toEqual([]);
advanceFrame();
expect(expansions).toEqual(["full draw distance"]);
},
);
it("cancels a covered reveal and schedules again when it is eligible", () => {
const { buffer, expansions, advanceFrame } = mountInitialBuffer();
const cancel = buffer.schedule();
advanceFrame();
cancel();
advanceFrame();
expect(expansions).toEqual([]);
buffer.schedule();
advanceFrame();
advanceFrame();
expect(expansions).toEqual(["full draw distance"]);
});
it("keeps a covered list at its initial draw distance when a gesture ends", () => {
const { buffer, expansions, advanceFrame } = mountInitialBuffer();
buffer.pauseForScroll();
const cover = buffer.schedule();
advanceFrame();
advanceFrame();
expect(expansions).toEqual([]);
cover();
buffer.resumeAfterScroll();
advanceFrame();
advanceFrame();
expect(expansions).toEqual([]);
});
@@ -0,0 +1,50 @@
interface InitialDrawDistanceFrames {
requestFrame(callback: () => void): number;
cancelFrame(id: number): void;
}
export function createInitialDrawDistanceExpansion(
frames: InitialDrawDistanceFrames,
expand: () => void,
) {
let frame: number | null = null;
let eligible = false;
let scrolling = false;
let expanded = false;
function cancel() {
if (frame === null) return;
frames.cancelFrame(frame);
frame = null;
}
function scheduleIfIdle() {
if (!eligible || scrolling || expanded || frame !== null) return;
frame = frames.requestFrame(() => {
frame = frames.requestFrame(() => {
frame = null;
expanded = true;
expand();
});
});
}
return {
schedule() {
eligible = true;
scheduleIfIdle();
return () => {
eligible = false;
cancel();
};
},
pauseForScroll() {
scrolling = true;
cancel();
},
resumeAfterScroll() {
scrolling = false;
scheduleIfIdle();
},
};
}
@@ -40,6 +40,7 @@ function wait(ms: number): Promise<void> {
}
const LIST_STYLE = { flex: 1 };
const ESTIMATED_LIST_SIZE = { width: 300, height: VIEWPORT_HEIGHT };
const rowStyles = new Map<number, { height: number }>();
function rowStyle(height: number) {
@@ -89,6 +90,10 @@ function keyExtractor(item: Row) {
return item.id;
}
function estimateRowSize(item: Row) {
return item.height;
}
function mountList(heldRowId: string) {
const listRef = React.createRef<LegendListRef>();
const maintainVisibleContentPosition = holdOnly(heldRowId);
@@ -264,3 +269,49 @@ it("keeps measured row sizes while the list is not laid out", async () => {
expect(rows.map((row) => list.rowSize(row.id))).toEqual([40, 40, 40]);
});
it("expands the draw distance of a placed end-anchored list without moving its bottom row", async () => {
const rows: Row[] = Array.from({ length: 99 }, (_, index) => ({
id: `row-${index}`,
height: index % 2 === 0 ? 20 : 60,
}));
const lastRow = { id: "last-row", height: 180 };
rows.push(lastRow);
const listRef = React.createRef<LegendListRef>();
function render(drawDistance: number) {
act(() => {
root.render(
<LegendList
ref={listRef}
data={rows}
renderItem={renderRow}
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
recycleItems={false}
getEstimatedItemSize={estimateRowSize}
drawDistance={drawDistance}
alignItemsAtEnd
initialScrollAtEnd
style={LIST_STYLE}
/>,
);
});
}
render(50);
await wait(300);
const initial = listRef.current?.getState();
const lastRowTop = initial?.positionByKey(lastRow.id);
expect(initial?.sizes.get(lastRow.id)).toBe(lastRow.height);
expect(initial?.sizes.size).toBeLessThan(8);
expect(initial?.scroll).toBe(Number(lastRowTop) + lastRow.height - VIEWPORT_HEIGHT);
render(1000);
await wait(150);
const expanded = listRef.current?.getState();
expect(expanded?.sizes.size).toBeGreaterThan(20);
expect(expanded?.scroll).toBe(initial?.scroll);
expect(expanded?.positionByKey(lastRow.id)).toBe(lastRowTop);
});
@@ -9,6 +9,7 @@ import {
useState,
} from "react";
import {
Dimensions,
View,
type LayoutChangeEvent,
type NativeScrollEvent,
@@ -31,6 +32,7 @@ import { useTranslation } from "react-i18next";
import type { StreamItem } from "@/types/stream";
import type { Theme } from "@/styles/theme";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useIsMobilePanelActive } from "@/mobile-panels/provider";
import { shouldAnimateNativeScrollToBottom } from "./native-scroll-animation";
import { useRevisedHistoryRows } from "./history-row-revision";
import { useBottomAnchorController } from "./bottom-anchor-controller";
@@ -43,6 +45,7 @@ import {
} from "./native-disclosure-hold";
import { EndPinnedScrollView } from "./native-end-pin";
import { createNewRowEstimates } from "./new-row-estimates";
import { createInitialDrawDistanceExpansion } from "./initial-draw-distance";
import type {
DisclosureTriggerEdge,
StreamRenderInput,
@@ -132,6 +135,14 @@ function keyExtractor(item: { id: string }): string {
return item.id;
}
function InitialDrawDistanceExpansion({ schedule }: { schedule: () => () => void }) {
const isSidebarActive = useIsMobilePanelActive("agent-list");
useLayoutEffect(() => {
if (!isSidebarActive) return schedule();
}, [schedule, isSidebarActive]);
return null;
}
function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrategy }) {
const {
agentId,
@@ -157,6 +168,16 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
strategy,
} = props;
const isActive = useRetainedPanelActive();
// Keep a screenful in reserve for a fling that starts before the full buffer mounts.
const [drawDistance, setDrawDistance] = useState(() =>
Math.min(Dimensions.get("window").height, NATIVE_STREAM_DRAW_DISTANCE),
);
const [drawDistanceExpansion] = useState(() =>
createInitialDrawDistanceExpansion(
{ requestFrame: requestAnimationFrame, cancelFrame: cancelAnimationFrame },
() => setDrawDistance(NATIVE_STREAM_DRAW_DISTANCE),
),
);
const { t } = useTranslation();
const { renderHistoryMountedRow, renderLiveHeadRow, renderLiveAuxiliary } = renderers;
const listRef = useRef<LegendListRef>(null);
@@ -569,6 +590,9 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
cancelDisclosureHold();
bottomAnchorController.beginUserScroll();
historyStartPagination.rearm();
// The reserve follows the gesture. Expanding the buffer here shifted the measured
// content and returned the viewport to the end during an Android fling.
drawDistanceExpansion.pauseForScroll();
});
useEffect(() => {
@@ -591,6 +615,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
bottomAnchorController.endUserScroll({
isAtEnd: isReleasedAtEndRef.current || isAtEnd(),
});
drawDistanceExpansion.resumeAfterScroll();
});
});
@@ -610,6 +635,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
bottomAnchorController.endUserScroll({
isAtEnd: isReleasedAtEndRef.current || isScrollEventAtEnd(event),
});
drawDistanceExpansion.resumeAfterScroll();
},
);
@@ -732,6 +758,11 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
);
}, [historyStartPaginationState, hasOlderHistory, retryHistoryStart, t]);
const canExpandDrawDistance =
drawDistance < NATIVE_STREAM_DRAW_DISTANCE &&
isActive &&
isListPlaced &&
historyStartPaginationState.visible;
return (
<View style={viewportStyle}>
<LegendList<StreamItem>
@@ -764,11 +795,14 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
recycleItems={false}
alignItemsAtEnd
initialScrollAtEnd
drawDistance={NATIVE_STREAM_DRAW_DISTANCE}
drawDistance={drawDistance}
getEstimatedItemSize={getEstimatedItemSize}
scrollEnabled={scrollEnabled}
showsVerticalScrollIndicator
/>
{canExpandDrawDistance ? (
<InitialDrawDistanceExpansion schedule={drawDistanceExpansion.schedule} />
) : null}
{!historyStartPaginationState.visible ? (
<View pointerEvents="none" testID="agent-initial-fill" style={initialFillStyle}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
@@ -1,3 +1,4 @@
import { useWorkspaceRowPress } from "../../modules/paseo-press-feedback";
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import {
@@ -1091,13 +1092,11 @@ function WorkspaceRowInner({
...dragAttributes
} = dragHandleProps?.attributes ?? {};
const handlePress = useCallback(() => {
if (interaction.didLongPressRef.current) {
interaction.didLongPressRef.current = false;
return;
}
onPress();
}, [interaction.didLongPressRef, onPress]);
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
didLongPressRef: interaction.didLongPressRef,
onPress,
selected,
});
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const isEditingTitle = titleEditor !== null;
@@ -1192,6 +1191,7 @@ function WorkspaceRowInner({
onTogglePin={onTogglePin}
/>
</SidebarWorkspaceRowContent>
{feedback}
</SidebarWorkspaceContextMenu>
</View>
);
@@ -1,3 +1,4 @@
import { useWorkspaceRowPress } from "../../../modules/paseo-press-feedback";
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import {
memo,
@@ -848,13 +849,11 @@ function StatusWorkspaceRowInnerContent({
const startDragPress = dragInteraction?.handlePressIn;
const moveDragPress = dragInteraction?.handleTouchMove;
const endDragPress = dragInteraction?.handlePressOut;
const handlePress = useCallback(() => {
if (didLongPressRef?.current) {
didLongPressRef.current = false;
return;
}
onPress();
}, [didLongPressRef, onPress]);
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
didLongPressRef,
onPress,
selected,
});
return (
<SidebarWorkspaceRowFrame
@@ -967,6 +966,7 @@ function StatusWorkspaceRowInnerContent({
/>
) : null}
</SidebarWorkspaceRowContent>
{feedback}
</SidebarWorkspaceContextMenu>
</View>
);
@@ -0,0 +1,60 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { expect, it } from "vitest";
import { usePanelStore } from "@/stores/panel-store";
import { MobilePanelsProvider, useIsMobilePanelActive } from "./provider";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
it("renders a panel subscriber only when that panel settles or stops being settled", async () => {
const initial = usePanelStore.getState();
const host = document.createElement("div");
document.body.appendChild(host);
const root = createRoot(host);
const explorerStates: boolean[] = [];
function ExplorerSubscriber() {
explorerStates.push(useIsMobilePanelActive("file-explorer"));
return null;
}
function AgentSubscriber() {
const active = useIsMobilePanelActive("agent");
return <span>{active ? "Agent settled" : "Agent covered"}</span>;
}
async function showPanel(target: "agent" | "agent-list" | "file-explorer") {
await act(async () => {
usePanelStore.setState((state) => ({
mobilePanel: { target, revision: state.mobilePanel.revision + 1 },
}));
});
}
try {
await showPanel("agent-list");
await act(async () => {
root.render(
<MobilePanelsProvider>
<ExplorerSubscriber />
<AgentSubscriber />
</MobilePanelsProvider>,
);
});
await showPanel("agent");
expect(host.textContent).toBe("Agent covered");
await expect.poll(() => host.textContent).toBe("Agent settled");
expect(explorerStates).toEqual([false]);
await showPanel("file-explorer");
expect(explorerStates).toEqual([false]);
await expect.poll(() => explorerStates).toEqual([false, true]);
await showPanel("agent");
await expect.poll(() => explorerStates).toEqual([false, true, false]);
} finally {
await act(async () => root.unmount());
host.remove();
usePanelStore.setState(initial, true);
}
});
+22 -16
View File
@@ -13,6 +13,7 @@ import {
type ReactNode,
type RefObject,
} from "react";
import { createStore, useStore } from "zustand";
import { Keyboard, useWindowDimensions } from "react-native";
import type { GestureType } from "react-native-gesture-handler";
import {
@@ -73,7 +74,11 @@ interface FinishGestureInput {
}
const MobilePanelsContext = createContext<MobilePanelsRuntime | null>(null);
const MobilePanelActiveContext = createContext<MobilePanelView>("agent");
function createSettledPanelStore(panel: MobilePanelView) {
return createStore(() => panel);
}
const SettledPanelContext = createContext(createSettledPanelStore("agent"));
/**
* The left sidebar's width: the full window for the compact drawer, the saved sidebar width
@@ -113,7 +118,7 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) {
const leftOpenGestureRef = useRef<GestureType | undefined>(undefined);
const leftCloseGestureRef = useRef<GestureType | undefined>(undefined);
const rightOpenGestureRef = useRef<GestureType | undefined>(undefined);
const [activePanel, setActivePanel] = useState(initialSelection.target);
const [settledPanel] = useState(() => createSettledPanelStore(initialSelection.target));
const setOpenGestureBlocked = useCallback(
(owner: symbol, blocked: boolean) => {
@@ -127,16 +132,19 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) {
[openGesturesBlocked],
);
const publishActivePanel = useCallback((panel: MobilePanelView, revision: number) => {
const selection = usePanelStore.getState().mobilePanel;
if (selection.revision !== revision || selection.target !== panel) {
return;
}
if (isNative && panel !== "agent") {
Keyboard.dismiss();
}
setActivePanel(panel);
}, []);
const publishActivePanel = useCallback(
(panel: MobilePanelView, revision: number) => {
const selection = usePanelStore.getState().mobilePanel;
if (selection.revision !== revision || selection.target !== panel) {
return;
}
if (isNative && panel !== "agent") {
Keyboard.dismiss();
}
settledPanel.setState(panel);
},
[settledPanel],
);
useAnimatedReaction(
() => ({ motionState: motionState.value, position: position.value }),
@@ -279,9 +287,7 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) {
return (
<MobilePanelsContext.Provider value={value}>
<MobilePanelActiveContext.Provider value={activePanel}>
{children}
</MobilePanelActiveContext.Provider>
<SettledPanelContext.Provider value={settledPanel}>{children}</SettledPanelContext.Provider>
</MobilePanelsContext.Provider>
);
}
@@ -301,7 +307,7 @@ export function useLeftPanelWidth(): number {
}
export function useIsMobilePanelActive(panel: MobilePanelView): boolean {
return useContext(MobilePanelActiveContext) === panel;
return useStore(useContext(SettledPanelContext), (settledPanel) => settledPanel === panel);
}
export function useBlockMobilePanelOpenGestures(blocked: boolean): void {
@@ -0,0 +1,94 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { PortalProvider } from "@gorhom/portal";
import { afterEach, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import { WindowLayoutContext } from "@/window-layout/context";
import { WindowLayoutActionsHost } from "@/window-layout";
import { usePanelStore } from "@/stores/panel-store";
import { CompactWorkspaceHeader } from ".";
import { i18n } from "@/i18n/i18next";
import type { WindowLayout } from "@/window-layout";
void i18n;
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
const initialPanel = usePanelStore.getState();
afterEach(async () => {
await act(async () => root.render(null));
usePanelStore.setState(initialPanel, true);
});
const noop = () => {};
const explorerState = { expanded: false };
const geometry: WindowLayout = {
bounds: { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight },
verticalBarEdge: "trailing",
verticalBar: { x: 20, y: 20, width: 44, height: 400 },
divisions: [],
};
it("updates compact header actions on panel changes without rendering the workspace owner", async () => {
let ownerRenders = 0;
function WorkspaceOwner({ focused = true, compact = true }) {
ownerRenders++;
return (
<CompactWorkspaceHeader
isRouteFocused={focused}
isCompact={compact}
serverId="test"
isLoading={false}
title="Workspace"
subtitle="Project"
isSubtitleDistinct
onToggleExplorer={noop}
explorerToggleLabel="Explorer"
explorerToggleAccessibilityState={explorerState}
tabSwitcher={null}
headerVariant="full"
>
<button type="button">Workspace menu</button>
</CompactWorkspaceHeader>
);
}
async function renderWorkspace(focused = true, compact = true) {
await act(async () =>
root.render(
<PortalProvider>
<WindowLayoutContext.Provider value={geometry}>
<WindowLayoutActionsHost />
<WorkspaceOwner focused={focused} compact={compact} />
</WindowLayoutContext.Provider>
</PortalProvider>,
),
);
}
async function showPanel(target: "agent" | "agent-list" | "file-explorer") {
await act(async () =>
usePanelStore.setState((state) => ({
mobilePanel: { ...state.mobilePanel, target, revision: state.mobilePanel.revision + 1 },
})),
);
}
const menu = page.getByRole("button", {
name: "Workspace menu",
exact: true,
includeHidden: true,
});
await showPanel("agent");
await renderWorkspace();
await expect.element(menu).toBeVisible();
const rendersBeforePanelChanges = ownerRenders;
await showPanel("agent-list");
await expect.element(menu).not.toBeVisible();
await showPanel("agent");
await expect.element(menu).toBeVisible();
await showPanel("file-explorer");
await expect.element(menu).not.toBeVisible();
expect(ownerRenders).toBe(rendersBeforePanelChanges);
await renderWorkspace(true, false);
await expect.element(menu).toBeVisible();
await renderWorkspace(false, false);
await expect.element(menu).not.toBeVisible();
});
@@ -1,5 +1,6 @@
import { Fragment, useMemo, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { usePanelStore } from "@/stores/panel-store";
import { CompactHeader } from "@/components/headers/compact-header";
import {
EXPLORER_TOGGLE_KEYS,
@@ -29,7 +30,8 @@ interface CompactWorkspaceHeaderProps {
/** Workspace overflow menu. */
children: ReactNode;
headerVariant: "compact" | "full";
actionsActive: boolean;
isRouteFocused: boolean;
isCompact: boolean;
}
/** The compact header with the workspace's project row and controls. */
@@ -45,7 +47,8 @@ export function CompactWorkspaceHeader({
tabSwitcher,
serverId,
headerVariant,
actionsActive,
isRouteFocused,
isCompact,
}: CompactWorkspaceHeaderProps) {
const { t } = useTranslation();
const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
@@ -89,7 +92,26 @@ export function CompactWorkspaceHeader({
actions={actionsInBar ? undefined : actions}
/>
) : null}
<WindowLayoutActions active={actionsActive}>{actions}</WindowLayoutActions>
<WorkspaceWindowActions isRouteFocused={isRouteFocused} isCompact={isCompact}>
{actions}
</WorkspaceWindowActions>
</IconButtonChromeProvider>
);
}
// Panel changes only affect the portaled controls. Keep their subscription below the
// workspace and header so opening a sidebar does not render the chat or rebuild its actions.
function WorkspaceWindowActions({
isRouteFocused,
isCompact,
children,
}: {
isRouteFocused: boolean;
isCompact: boolean;
children: ReactNode;
}) {
const active = usePanelStore(
(state) => isRouteFocused && (!isCompact || state.mobilePanel.target === "agent"),
);
return <WindowLayoutActions active={active}>{children}</WindowLayoutActions>;
}
@@ -3,7 +3,6 @@ export interface ExplorerFrameProps {
children: ReactNode;
presentation: "overlay" | "dock";
persistenceKey: string;
containerWidth: number;
isOpen: boolean;
isWorkspaceActive: boolean;
surfaceColor?: string;
@@ -0,0 +1,55 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { View } from "react-native";
import { expect, it } from "vitest";
import { MobilePanelsProvider } from "@/mobile-panels/provider";
import { ExplorerFrame } from "./frame";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
const WORKSPACE_STYLE = { flexDirection: "row", height: 200 } as const;
const FILL = { flex: 1 };
it("measures dock allocation independently of the workspace owner", async () => {
const host = document.createElement("div");
host.style.width = "900px";
document.body.appendChild(host);
const root = createRoot(host);
let workspaceRenders = 0;
function Workspace() {
workspaceRenders++;
return (
<View style={WORKSPACE_STYLE}>
<View role="main" style={FILL} />
<ExplorerFrame presentation="dock" isWorkspaceActive isOpen persistenceKey="workspace">
<View role="complementary" style={FILL} />
</ExplorerFrame>
</View>
);
}
function dockWidth() {
return host.querySelector('[role="complementary"]')?.getBoundingClientRect().width;
}
try {
await act(async () => {
root.render(
<MobilePanelsProvider>
<Workspace />
</MobilePanelsProvider>,
);
});
await expect.poll(dockWidth).toBe(320);
const initialRenderCount = workspaceRenders;
const dock = host.querySelector('[role="complementary"]');
host.style.width = "620px";
await expect.poll(dockWidth).toBe(260);
expect(workspaceRenders).toBe(initialRenderCount);
expect(host.querySelector('[role="complementary"]')).toBe(dock);
} finally {
await act(async () => root.unmount());
host.remove();
}
});
@@ -1,5 +1,5 @@
import { useCallback } from "react";
import { View } from "react-native";
import { useCallback, useState } from "react";
import { View, type LayoutChangeEvent } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
FileExplorerCloseGestureContext,
@@ -20,8 +20,12 @@ function ExplorerFrameBase({
isOpen,
isWorkspaceActive,
persistenceKey,
containerWidth,
}: ExplorerFrameProps) {
const [containerWidth, setContainerWidth] = useState(0);
const measureContainer = useCallback(({ nativeEvent }: LayoutChangeEvent) => {
const { width, height } = nativeEvent.layout;
if (width > 0 && height > 0) setContainerWidth(width);
}, []);
const overlay = presentation === "overlay";
const settledOpen = useIsMobilePanelActive("file-explorer");
const active = isWorkspaceActive && (overlay ? settledOpen : isOpen);
@@ -59,10 +63,15 @@ function ExplorerFrameBase({
</View>
</MobilePanelOverlay>
</FileExplorerCloseGestureContext>
<View pointerEvents="none" style={styles.measurement} onLayout={measureContainer} />
</RetainedPanelActivity>
);
}
export const ExplorerFrame = withUnistyles(ExplorerFrameBase, (theme) => ({
surfaceColor: theme.colors.surfaceSidebar,
}));
const styles = StyleSheet.create({ content: { flex: 1, minHeight: 0 } });
const styles = StyleSheet.create({
content: { flex: 1, minHeight: 0 },
// Measure the workspace row even when the dock is closed. The gesture host stays in its slot.
measurement: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 },
});
@@ -13,7 +13,6 @@ import {
import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
import { useWindowLayout, resolveWorkspaceActionPlacement } from "@/window-layout";
import { revealWorkspaceTab } from "@/workspace-tabs/navigation";
import type { LayoutChangeEvent } from "react-native";
import { ExplorerSidebarDock } from "@/screens/workspace/explorer-sidebar";
import { ForgeShorthandProvider } from "@/git/forge-shorthand";
import { ExplorerFrame } from "./explorer-sidebar/frame";
@@ -805,9 +804,7 @@ function WorkspacePanelSurface({
children,
tabIds,
workspaceKey,
onLayout,
}: {
onLayout: (event: LayoutChangeEvent) => void;
workspaceKey: string;
launcher: NewTabLauncher;
children: ReactNode;
@@ -818,9 +815,7 @@ function WorkspacePanelSurface({
<WorkspaceComposerEditingSessionsProvider workspaceKey={workspaceKey} tabIds={tabIds}>
<NewTabLauncherProvider value={launcher}>
<SheetHostScope enabled={!isCompact}>
<View style={styles.threePaneRow} onLayout={onLayout}>
{children}
</View>
<View style={styles.threePaneRow}>{children}</View>
</SheetHostScope>
</NewTabLauncherProvider>
</WorkspaceComposerEditingSessionsProvider>
@@ -1061,7 +1056,6 @@ function WorkspaceScreenContent({
resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
const toast = useToast();
const isMobile = useIsCompactFormFactor();
const workspacePanelActive = usePanelStore((state) => state.mobilePanel.target === "agent");
const canRenderDesktopPaneSplits = supportsDesktopPaneSplits();
const layoutMode = useWorkspaceLayoutStore((state) => state.layoutMode);
const hasMacTrafficLights = useHasWindowChromeObstruction("top-left");
@@ -3463,7 +3457,8 @@ function WorkspaceScreenContent({
return (
<CompactWorkspaceHeader
headerVariant={actionsOnly ? "full" : "compact"}
actionsActive={isRouteFocused && (!isMobile || workspacePanelActive)}
isRouteFocused={isRouteFocused}
isCompact={isMobile}
tabSwitcher={tabSwitcher}
isLoading={isWorkspaceHeaderLoading}
title={workspaceHeaderTitle}
@@ -3524,7 +3519,6 @@ function WorkspaceScreenContent({
workspaceDirectory,
workspaceHeaderSubtitle,
workspaceHeaderTitle,
workspacePanelActive,
],
);
const workspaceCompactHeaderTabs = {
@@ -3710,11 +3704,6 @@ function WorkspaceScreenContent({
</DesktopCenterColumnChrome>
);
const [workspaceViewportWidth, setWorkspaceViewportWidth] = useState(0);
const measureWorkspaceWidth = useCallback(
(event: LayoutChangeEvent) => setWorkspaceViewportWidth(event.nativeEvent.layout.width),
[],
);
const sharedExplorer = useMemo(() => {
if (!workspaceLayout || !explorerSidebarPaneId || !persistenceKey) return null;
const explorerPane = findPaneById(workspaceLayout.root, explorerSidebarPaneId);
@@ -3753,7 +3742,6 @@ function WorkspaceScreenContent({
presentation={isMobile ? "overlay" : "dock"}
isWorkspaceActive={isRouteFocused}
persistenceKey={persistenceKey}
containerWidth={workspaceViewportWidth}
isOpen={isExplorerSidebarShowing && !desktopFocusModeEnabled}
>
{dock}
@@ -3788,7 +3776,6 @@ function WorkspaceScreenContent({
handleReorderTabsInPane,
buildDesktopPaneContentModel,
renderExplorerSidebarHeaderAction,
workspaceViewportWidth,
desktopFocusModeEnabled,
]);
@@ -3846,7 +3833,6 @@ function WorkspaceScreenContent({
isRouteFocused={isRouteFocused}
/>
<WorkspacePanelSurface
onLayout={measureWorkspaceWidth}
launcher={newTabLauncher}
workspaceKey={workspacePanelKey}
tabIds={workspacePanelTabIds}
@@ -74,6 +74,7 @@ export const MoreVertical = StubIcon;
export const MousePointer2 = StubIcon;
export const PackagePlus = StubIcon;
export const PanelLeft = StubIcon;
export const PanelRight = StubIcon;
export const PanelsTopLeft = StubIcon;
export const Paperclip = StubIcon;
export const Pencil = StubIcon;
@@ -132,3 +133,10 @@ export const MicVocal = StubIcon;
export const Scissors = StubIcon;
export const Sparkles = StubIcon;
export const TriangleAlertIcon = StubIcon;
export const ArrowRightToLine = StubIcon;
export const Columns2 = StubIcon;
export const CopyX = StubIcon;
export const Ellipsis = StubIcon;
export const Maximize = StubIcon;
export const Minimize = StubIcon;
export const Rows2 = StubIcon;
+37 -3
View File
@@ -1,5 +1,5 @@
# LegendList 3.7.1 for the native chat timeline (docs/agent-stream-disclosure.md).
# Upstream: https://github.com/LegendApp/legend-list/issues/593 covers every change below.
# Upstream: https://github.com/LegendApp/legend-list/issues/593 covers changes 1–12 below.
# react-native.js and react-native.mjs carry the same hunks; each has a "Paseo patch" comment.
#
# 1. getEstimatedItemSize (react-native.d.ts, getItemSize, LegendListInner props): a per-item
@@ -34,6 +34,8 @@
# of a shrink past the end from the new end, assuming the scroll view clamped first. The app's
# scroll view clamps after the adjustment on both platforms (modules/paseo-scroll), so a
# bottom-edge disclosure collapsing near the end landed at the end instead of in place.
# 13. Recalculate the rendered range when drawDistance changes (LegendListInner). Chat uses
# a small window for initial placement and schedules expansion after initial reveal.
#
# Upgrading: drop each hunk whose fix the new version ships, regenerate with
# `npx patch-package @legendapp/list`, and copy this header back on top.
@@ -54,7 +56,7 @@ index 983e937..970ba51 100644
* Returns a stable item type used for pooling and size estimation.
*/
diff --git a/node_modules/@legendapp/list/react-native.js b/node_modules/@legendapp/list/react-native.js
index eeb3fb0..5ebd8e9 100644
index eeb3fb0..33d6241 100644
--- a/node_modules/@legendapp/list/react-native.js
+++ b/node_modules/@legendapp/list/react-native.js
@@ -1497,7 +1497,15 @@ function getItemSize(ctx, key, index, data, useAverageSize, preferCachedSize, no
@@ -344,8 +346,24 @@ index eeb3fb0..5ebd8e9 100644
getFixedItemSize: useWrapIfItem(getFixedItemSize),
getItemType: useWrapIfItem(getItemType),
hasExternalScroll,
@@ -8549,6 +8618,15 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
doMaintainScrollAtEnd(ctx);
}
}, [!!maintainScrollAtEndConfig]);
+ // Paseo patch: the chat fills its offscreen buffer after its initial reveal.
+ const previousDrawDistance = React2.useRef(drawDistance);
+ React2.useLayoutEffect(() => {
+ if (previousDrawDistance.current !== drawDistance) {
+ previousDrawDistance.current = drawDistance;
+ state.scrollForNextCalculateItemsInView = void 0;
+ calculateItemsInView(ctx);
+ }
+ }, [drawDistance]);
const previousAlwaysRenderIndices = React2.useRef(alwaysRenderIndices);
React2.useLayoutEffect(() => {
const previousPins = previousAlwaysRenderIndices.current;
diff --git a/node_modules/@legendapp/list/react-native.mjs b/node_modules/@legendapp/list/react-native.mjs
index fe5f415..9788ce6 100644
index fe5f415..8219839 100644
--- a/node_modules/@legendapp/list/react-native.mjs
+++ b/node_modules/@legendapp/list/react-native.mjs
@@ -1476,7 +1476,15 @@ function getItemSize(ctx, key, index, data, useAverageSize, preferCachedSize, no
@@ -635,3 +653,19 @@ index fe5f415..9788ce6 100644
getFixedItemSize: useWrapIfItem(getFixedItemSize),
getItemType: useWrapIfItem(getItemType),
hasExternalScroll,
@@ -8528,6 +8597,15 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
doMaintainScrollAtEnd(ctx);
}
}, [!!maintainScrollAtEndConfig]);
+ // Paseo patch: the chat fills its offscreen buffer after its initial reveal.
+ const previousDrawDistance = useRef(drawDistance);
+ useLayoutEffect(() => {
+ if (previousDrawDistance.current !== drawDistance) {
+ previousDrawDistance.current = drawDistance;
+ state.scrollForNextCalculateItemsInView = void 0;
+ calculateItemsInView(ctx);
+ }
+ }, [drawDistance]);
const previousAlwaysRenderIndices = useRef(alwaysRenderIndices);
useLayoutEffect(() => {
const previousPins = previousAlwaysRenderIndices.current;