Fix the review's findings: drag on pointer events, read the window back
Build App / compute-version (pull_request) Successful in 4s
Build App / build-macos (pull_request) Successful in 2m30s
Build App / build-linux (pull_request) Successful in 5m11s
Build App / build-windows (pull_request) Successful in 5m23s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped

Ten findings from the review of the previous commit, all applied.

**The tab drag is now pointer events, not HTML5 drag-and-drop.** Two
independent reasons, either one fatal. Tauri's `dragDropEnabled` blocks
HTML5 drag inside the webview on Windows, and it cannot just be turned
off — `TerminalView` needs Tauri's native drag-drop event, which is the
only one that carries dropped *file paths*. And an HTML5 drag carries a
`DataTransfer`: released over any text field in the app, the default
handler types `term:<uuid>` into it, and in Config that is then saved
with the project. Pointer events have neither problem, and the drag is
measured from the tabs on screen rather than from the event target, so
the marker and the drop agree even over the marker itself. Escape
abandons a drag; a press under 4px stays a click; the click that ends a
drag does not select.

**`Ctrl+Shift+←/→` no longer swallows word-wise selection.** It is bound
on `document` in the capture phase, so in any input — the rename field,
Config, Settings — it was taking the OS's extend-selection chord *and*
silently reordering the strip. Guarded by `inTextField()`, which
excludes xterm's helper textarea: that is an input-method shim, and the
terminal is where the shortcut matters most.

**The pop-out's state is read from the window, never remembered.** The
pane is unmounted whenever another Project Home sub-tab is selected, so
"Keep on top" came back Off over a window still floating on top.
`get_browser_view_popout_state` returns both facts from the window
itself, and the change event carries them. `poppedOut` is tri-state:
until the answer arrives the iframe is not mounted, because guessing
"not popped out" is what flashes a second viewer onto the browser.

Also: `popout::close` and the off-status emit in the supervisor are
behind the same epoch guard as the deregistration above them, so a
supervisor whose teardown outlives a restart can no longer destroy the
*new* session's window; `close()` returns its `destroy()` error instead
of logging it and reporting success, since the pane restores its iframe
on success; the drop marker is `pointer-events-none` and is placed
before the first *visible* tab at or past the slot, so it neither
refuses a drop nor vanishes when a `tabOrder` entry renders nothing; and
the "Keep on top" Toggle's accessible name now matches its visible text.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-11 07:40:51 -07:00
co-authored by Claude Opus 5
parent d73096c937
commit a41d93ea46
14 changed files with 522 additions and 185 deletions
+105 -58
View File
@@ -45,33 +45,22 @@ const S1 = terminalTabKey("s1");
const S2 = terminalTabKey("s2");
/**
* A stand-in for the DataTransfer jsdom doesn't implement. It only has to
* carry the tab key, which is what a drop falls back to reading.
* A pointer event carrying a real `clientX`.
*
* jsdom implements no `PointerEvent`, so Testing Library's synthesized one has
* no coordinates — and the coordinate is the whole point here, since it decides
* which slot the drop lands in. `MouseEvent` has one, and React dispatches on
* the event's type name either way.
*/
function dataTransfer() {
const store: Record<string, string> = {};
return {
effectAllowed: "",
dropEffect: "",
setData: (format: string, value: string) => {
store[format] = value;
},
getData: (format: string) => store[format] ?? "",
};
function pointer(el: Element, type: string, clientX: number) {
fireEvent(el, new MouseEvent(type, { bubbles: true, cancelable: true, clientX, button: 0 }));
}
/**
* A dragover carrying a real `clientX`.
*
* jsdom has no `DragEvent`, so Testing Library's synthesized one is a plain
* `Event` with no pointer coordinates — and the coordinate is the whole point
* here, since it decides which side of a tab the drop lands on. A `MouseEvent`
* has one, and React reads it the same way.
*/
function dragOverAt(el: Element, clientX: number, dt: ReturnType<typeof dataTransfer>) {
const event = new MouseEvent("dragover", { bubbles: true, cancelable: true, clientX });
Object.defineProperty(event, "dataTransfer", { value: dt });
fireEvent(el, event);
/** Press, move past the drag threshold, and release over `endX`. */
function dragTab(el: Element, fromX: number, endX: number) {
pointer(el, "pointerdown", fromX);
pointer(el, "pointermove", endX);
pointer(el, "pointerup", endX);
}
/** Pin a tab's geometry so "past the midpoint" means something in jsdom. */
@@ -80,6 +69,13 @@ function place(el: Element, left: number, width = 100) {
({ left, width, right: left + width, top: 0, bottom: 30, height: 30, x: left, y: 0 }) as DOMRect;
}
/** Lay the strip out as three 100px tabs starting at x=0. */
function laidOut() {
const tabs = screen.getAllByRole("tab");
tabs.forEach((tab, i) => place(tab, i * 100));
return tabs;
}
const order = () => useAppState.getState().tabOrder;
beforeEach(() => {
@@ -95,73 +91,124 @@ beforeEach(() => {
describe("MainTabs reordering", () => {
it("drags a tab to the front", () => {
render(<MainTabs />);
const tabs = screen.getAllByRole("tab");
tabs.forEach((tab, i) => place(tab, i * 100));
const tabs = laidOut();
const dt = dataTransfer();
fireEvent.dragStart(tabs[2], { dataTransfer: dt });
// Left half of the first tab — the marker sits before it.
dragOverAt(tabs[0], 10, dt);
expect(screen.getByTestId("tab-drop-marker")).toBeInTheDocument();
fireEvent.drop(tabs[0], { dataTransfer: dt });
// Left half of the first tab — the tab lands before it.
dragTab(tabs[2], 250, 10);
expect(order()).toEqual([S2, HOME, S1]);
});
it("drops after the tab when the pointer is past its midpoint", () => {
render(<MainTabs />);
const tabs = screen.getAllByRole("tab");
tabs.forEach((tab, i) => place(tab, i * 100));
const tabs = laidOut();
const dt = dataTransfer();
fireEvent.dragStart(tabs[0], { dataTransfer: dt });
dragOverAt(tabs[1], 190, dt);
fireEvent.drop(tabs[1], { dataTransfer: dt });
dragTab(tabs[0], 50, 190);
expect(order()).toEqual([S1, HOME, S2]);
});
it("drops at the end when released past the last tab", () => {
render(<MainTabs />);
const tabs = laidOut();
dragTab(tabs[0], 50, 800);
expect(order()).toEqual([S1, S2, HOME]);
});
it("dragging does not steal the selection", () => {
render(<MainTabs />);
const tabs = screen.getAllByRole("tab");
tabs.forEach((tab, i) => place(tab, i * 100));
const tabs = laidOut();
const dt = dataTransfer();
fireEvent.dragStart(tabs[1], { dataTransfer: dt });
dragOverAt(tabs[2], 290, dt);
fireEvent.drop(tabs[2], { dataTransfer: dt });
dragTab(tabs[1], 150, 290);
expect(order()).toEqual([HOME, S2, S1]);
expect(useAppState.getState().activeTabKey).toBe(HOME);
});
it("shows no drop marker until a drag is under way", () => {
it("shows the drop marker only while a drag is under way", () => {
render(<MainTabs />);
const tabs = laidOut();
expect(screen.queryByTestId("tab-drop-marker")).toBeNull();
pointer(tabs[2], "pointerdown", 250);
pointer(tabs[2], "pointermove", 10);
expect(screen.getByTestId("tab-drop-marker")).toBeInTheDocument();
pointer(tabs[2], "pointerup", 10);
expect(screen.queryByTestId("tab-drop-marker")).toBeNull();
});
it("clears the marker when the drag ends without a drop", () => {
it("abandons the drag on Escape, leaving the order alone", () => {
render(<MainTabs />);
const tabs = screen.getAllByRole("tab");
tabs.forEach((tab, i) => place(tab, i * 100));
const tabs = laidOut();
const dt = dataTransfer();
fireEvent.dragStart(tabs[2], { dataTransfer: dt });
dragOverAt(tabs[0], 10, dt);
fireEvent.dragEnd(tabs[2], { dataTransfer: dt });
pointer(tabs[2], "pointerdown", 250);
pointer(tabs[2], "pointermove", 10);
fireEvent.keyDown(window, { key: "Escape" });
expect(screen.queryByTestId("tab-drop-marker")).toBeNull();
pointer(tabs[2], "pointerup", 10);
expect(order()).toEqual([HOME, S1, S2]);
});
it("treats a press that barely moves as a click, not a drag", () => {
render(<MainTabs />);
const tabs = laidOut();
// Two pixels of tremble, under the threshold.
pointer(tabs[2], "pointerdown", 250);
pointer(tabs[2], "pointermove", 252);
pointer(tabs[2], "pointerup", 252);
fireEvent.click(tabs[2]);
expect(order()).toEqual([HOME, S1, S2]);
expect(useAppState.getState().activeTabKey).toBe(S2);
});
it("does not select the tab it just dropped", () => {
render(<MainTabs />);
const tabs = laidOut();
dragTab(tabs[2], 250, 10);
// The browser fires a click after the pointerup that ended the drag.
fireEvent.click(tabs[2]);
expect(order()).toEqual([S2, HOME, S1]);
expect(useAppState.getState().activeTabKey).toBe(HOME);
});
it("ignores a press that starts on the close button", () => {
render(<MainTabs />);
const tabs = laidOut();
const close = screen.getByRole("button", { name: "Close shell (bash)" });
fireEvent(close, new MouseEvent("pointerdown", { bubbles: true, clientX: 290, button: 0 }));
pointer(tabs[2], "pointermove", 10);
expect(screen.queryByTestId("tab-drop-marker")).toBeNull();
expect(order()).toEqual([HOME, S1, S2]);
});
it("leaves a tab being renamed undraggable, so its text stays selectable", () => {
it("does not drag a tab that is being renamed — that drag selects text", () => {
render(<MainTabs />);
const tabs = screen.getAllByRole("tab");
expect(tabs[1]).toHaveAttribute("draggable", "true");
const tabs = laidOut();
fireEvent.doubleClick(tabs[1]);
expect(screen.getByLabelText("Rename tab")).toBeInTheDocument();
expect(screen.getAllByRole("tab")[1]).toHaveAttribute("draggable", "false");
dragTab(screen.getAllByRole("tab")[1], 150, 10);
expect(order()).toEqual([HOME, S1, S2]);
});
it("carries no drag payload that another element could receive", () => {
// An HTML5 drag would put the tab key in a DataTransfer, and releasing over
// any text field in the app would type `term:…` into it. Pointer events
// have nothing to hand over, and the tabs are not draggable at all.
render(<MainTabs />);
for (const tab of screen.getAllByRole("tab")) {
expect(tab).not.toHaveAttribute("draggable", "true");
}
});
});
+108 -63
View File
@@ -18,6 +18,9 @@ interface ContextMenuState {
y: number;
}
/** Pixels of horizontal travel before a press becomes a drag rather than a click. */
const DRAG_THRESHOLD = 4;
const MODE_BADGE: Record<PermissionMode, { text: string; className: string }> = {
plan: { text: "plan", className: "bg-[var(--bg-tertiary)] text-[var(--text-secondary)]" },
default: { text: "ask", className: "bg-[var(--bg-tertiary)] text-[var(--text-secondary)]" },
@@ -29,9 +32,8 @@ const MODE_BADGE: Record<PermissionMode, { text: string; className: string }> =
* One strip for both main-area tab kinds: Project Home views (⌂) and
* terminals (▣).
*
* Tabs are draggable. The drag is HTML5's, not a pointer-event
* reimplementation, so the OS supplies the drag image and the Escape-to-cancel
* behaviour for free; the only thing tracked here is where the drop would land.
* Tabs are draggable, on pointer events rather than HTML5 drag-and-drop — see
* `pointerProps` for why neither of the two obvious alternatives works.
* `Ctrl+Shift+←/→` does the same thing without a mouse.
*/
export default function MainTabs() {
@@ -53,6 +55,10 @@ export default function MainTabs() {
/** The tab being dragged, and the slot it would drop into. */
const [dragKey, setDragKey] = useState<string | null>(null);
const [dropIndex, setDropIndex] = useState<number | null>(null);
const stripRef = useRef<HTMLDivElement>(null);
/** A press that has not yet moved far enough to be a drag. */
const pending = useRef<{ key: string; startX: number; dragging: boolean } | null>(null);
const suppressClick = useRef(false);
useEffect(() => {
if (!menu) return;
@@ -72,6 +78,20 @@ export default function MainTabs() {
}
}, [renamingId]);
// Escape abandons a drag — the one affordance a pointer-event drag has to
// supply for itself, since the OS is not running this one.
useEffect(() => {
if (!dragKey) return;
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== "Escape") return;
pending.current = null;
setDragKey(null);
setDropIndex(null);
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [dragKey]);
if (tabOrder.length === 0) {
return (
<div className="px-3 text-xs text-[var(--text-secondary)] leading-10">
@@ -152,54 +172,91 @@ export default function MainTabs() {
}${dragging ? " opacity-40" : ""}`;
const endDrag = () => {
pending.current = null;
setDragKey(null);
setDropIndex(null);
};
/**
* Drag props shared by both tab kinds.
* Which slot the pointer is currently over, as an insertion index into
* `tabOrder`.
*
* A tab in rename mode is not draggable: a `draggable` ancestor swallows the
* mouse-drag that selects text inside the input, which would make the rename
* field impossible to select in.
* Measured from the tabs actually on screen rather than from the event's
* target, so the answer is the same whatever the pointer happens to be over —
* including the drop marker itself, and including a `tabOrder` entry whose
* session has already gone and which therefore renders nothing.
*/
const dragProps = (key: string, index: number, renaming: boolean) => ({
draggable: !renaming,
onDragStart: (e: React.DragEvent<HTMLDivElement>) => {
e.dataTransfer.effectAllowed = "move";
// Some platforms refuse to start a drag with an empty payload.
e.dataTransfer.setData("text/plain", key);
setDragKey(key);
setDropIndex(index);
const dropIndexAt = (clientX: number): number => {
const strip = stripRef.current;
if (!strip) return tabOrder.length;
for (const el of strip.querySelectorAll<HTMLElement>("[data-tab-index]")) {
const rect = el.getBoundingClientRect();
if (clientX < rect.left + rect.width / 2) return Number(el.dataset.tabIndex);
}
return tabOrder.length;
};
/**
* Dragging is done with pointer events, not HTML5 drag-and-drop.
*
* Two reasons, both load-bearing. Tauri's `dragDropEnabled` — which the
* terminal needs left on, because only the native drag-drop event carries
* dropped *file paths* — blocks HTML5 drag inside the webview on Windows, so
* an HTML5 implementation is simply dead there. And an HTML5 drag carries a
* `DataTransfer`: released over any text field in the app, the default
* handler types the payload into it.
*/
const pointerProps = (key: string, renaming: boolean) => ({
onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => {
// Left button only, never from the close button, and never while the
// rename input is up — that drag is a text selection.
if (e.button !== 0 || renaming) return;
if ((e.target as HTMLElement).closest("button, input")) return;
pending.current = { key, startX: e.clientX, dragging: false };
e.currentTarget.setPointerCapture?.(e.pointerId);
},
onDragOver: (e: React.DragEvent<HTMLDivElement>) => {
if (!dragKey) return; // not our drag — a file dropped on the strip isn't one
e.preventDefault();
e.dataTransfer.dropEffect = "move";
const rect = e.currentTarget.getBoundingClientRect();
const after = e.clientX > rect.left + rect.width / 2;
setDropIndex(index + (after ? 1 : 0));
onPointerMove: (e: React.PointerEvent<HTMLDivElement>) => {
const drag = pending.current;
if (!drag) return;
// A few pixels of slop, so a click that trembles stays a click.
if (!drag.dragging && Math.abs(e.clientX - drag.startX) < DRAG_THRESHOLD) return;
drag.dragging = true;
setDragKey(drag.key);
setDropIndex(dropIndexAt(e.clientX));
},
onDragEnd: endDrag,
onPointerUp: (e: React.PointerEvent<HTMLDivElement>) => {
const drag = pending.current;
e.currentTarget.releasePointerCapture?.(e.pointerId);
if (!drag?.dragging) {
pending.current = null;
return; // a plain click: leave it to `onClick` to select the tab
}
const to = dropIndexAt(e.clientX);
const from = tabOrder.indexOf(drag.key);
// `to` is a slot in the strip as it looks *now*; `moveTab` places the tab
// after pulling it out, so every slot past its own shifts down one.
if (from !== -1) moveTab(drag.key, to > from ? to - 1 : to);
// The click that follows this pointerup is the drag's, not a selection.
suppressClick.current = true;
endDrag();
},
onPointerCancel: endDrag,
});
/** Drop lands wherever the marker is showing, and only there. */
const onDrop = (e: React.DragEvent<HTMLDivElement>) => {
const key = dragKey ?? e.dataTransfer.getData("text/plain");
if (!key || dropIndex === null) return endDrag();
e.preventDefault();
const from = tabOrder.indexOf(key);
// `dropIndex` is a slot in the strip as it looks *now*; `moveTab` places the
// tab after pulling it out, so every slot past the tab's own shifts down one.
moveTab(key, dropIndex > from ? dropIndex - 1 : dropIndex);
endDrag();
/** A drag in progress swallows the click it ends with. */
const activateTab = (key: string) => {
if (suppressClick.current) {
suppressClick.current = false;
return;
}
setActiveTabKey(key);
};
const dropMarker = (
<div
aria-hidden="true"
data-testid="tab-drop-marker"
className="w-0.5 -mx-px h-full bg-[var(--accent)] flex-shrink-0"
className="w-0.5 -mx-px h-full bg-[var(--accent)] flex-shrink-0 pointer-events-none"
/>
);
@@ -215,14 +272,15 @@ export default function MainTabs() {
role="tab"
aria-selected={active}
tabIndex={0}
onClick={() => setActiveTabKey(key)}
data-tab-index={index}
onClick={() => activateTab(key)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
setActiveTabKey(key);
}
}}
{...dragProps(key, index, false)}
{...pointerProps(key, false)}
className={tabClass(active, dragKey === key)}
>
<span aria-hidden="true" className="text-[var(--text-secondary)]"></span>
@@ -265,7 +323,8 @@ export default function MainTabs() {
role="tab"
aria-selected={active}
tabIndex={0}
onClick={() => setActiveTabKey(terminalTabKey(session.id))}
data-tab-index={index}
onClick={() => activateTab(terminalTabKey(session.id))}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
@@ -277,7 +336,7 @@ export default function MainTabs() {
setMenu({ sessionId: session.id, x: e.clientX, y: e.clientY });
}}
onDoubleClick={() => startRename(session.id)}
{...dragProps(key, index, isRenaming)}
{...pointerProps(key, isRenaming)}
className={tabClass(active, dragKey === key)}
>
<span aria-hidden="true" className="text-[var(--text-secondary)]"></span>
@@ -324,26 +383,22 @@ export default function MainTabs() {
);
};
// The marker goes before the first tab that is *actually on screen* at or
// past the drop slot. Addressing it by raw index would lose it whenever a
// `tabOrder` entry renders nothing — the window between a session ending and
// the store dropping its key — leaving the drag with no visible target.
let markerPending = dragKey !== null && dropIndex !== null;
return (
<div
className="flex items-center h-full"
role="tablist"
aria-label="Open tabs"
onDrop={onDrop}
onDragLeave={(e) => {
// Leaving the strip entirely (not crossing between tabs) parks the
// marker, so a drag aborted outside doesn't leave one behind.
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
setDropIndex(null);
}
}}
>
<div ref={stripRef} className="flex items-center h-full" role="tablist" aria-label="Open tabs">
{tabOrder.map((key, index) => {
const tab = renderTab(key, index);
if (!tab) return null;
const marker = markerPending && index >= (dropIndex ?? 0);
if (marker) markerPending = false;
return (
<Fragment key={key}>
{dragKey !== null && dropIndex === index && dropMarker}
{marker && dropMarker}
{tab}
</Fragment>
);
@@ -351,17 +406,7 @@ export default function MainTabs() {
{/* The empty run after the last tab is a drop target too — it is where
the hand naturally goes to say "put it at the end". */}
<div
className="flex-1 self-stretch"
onDragOver={(e) => {
if (!dragKey) return;
e.preventDefault();
e.dataTransfer.dropEffect = "move";
setDropIndex(tabOrder.length);
}}
>
{dragKey !== null && dropIndex === tabOrder.length && dropMarker}
</div>
<div className="flex-1 self-stretch">{markerPending && dropMarker}</div>
{menu && (() => {
const session = sessions.find((s) => s.id === menu.sessionId);
@@ -15,7 +15,8 @@ const installBrowserViewSupport = vi.fn<() => Promise<BrowserSetupOutcome>>();
const installBrowserViewBrowser = vi.fn<(id: string, b: string) => Promise<BrowserSetupOutcome>>();
const openBrowserViewPopout = vi.fn<(id: string, onTop: boolean) => Promise<void>>();
const closeBrowserViewPopout = vi.fn<(id: string) => Promise<void>>();
const isBrowserViewPopoutOpen = vi.fn<() => Promise<boolean>>();
const getBrowserViewPopoutState =
vi.fn<() => Promise<{ open: boolean; always_on_top: boolean }>>();
const setBrowserViewPopoutAlwaysOnTop = vi.fn<(id: string, onTop: boolean) => Promise<void>>();
const pushToast = vi.fn();
const setContainerProgress = vi.fn();
@@ -28,7 +29,7 @@ vi.mock("../../../lib/tauri-commands", () => ({
installBrowserViewBrowser: (id: string, b: string) => installBrowserViewBrowser(id, b),
openBrowserViewPopout: (id: string, onTop: boolean) => openBrowserViewPopout(id, onTop),
closeBrowserViewPopout: (id: string) => closeBrowserViewPopout(id),
isBrowserViewPopoutOpen: () => isBrowserViewPopoutOpen(),
getBrowserViewPopoutState: () => getBrowserViewPopoutState(),
setBrowserViewPopoutAlwaysOnTop: (id: string, onTop: boolean) =>
setBrowserViewPopoutAlwaysOnTop(id, onTop),
}));
@@ -120,7 +121,7 @@ beforeEach(() => {
storeState.containerProgress = {};
getBrowserViewStatus.mockResolvedValue(OFF);
checkBrowserViewSupport.mockResolvedValue(READY);
isBrowserViewPopoutOpen.mockResolvedValue(false);
getBrowserViewPopoutState.mockResolvedValue({ open: false, always_on_top: false });
openBrowserViewPopout.mockResolvedValue(undefined);
closeBrowserViewPopout.mockResolvedValue(undefined);
setBrowserViewPopoutAlwaysOnTop.mockResolvedValue(undefined);
@@ -406,16 +407,17 @@ describe("BrowserTab", () => {
});
await act(async () => {
fireEvent.click(screen.getByRole("switch", { name: /above other windows/i }));
// The accessible name is the visible text, as with every other Toggle.
fireEvent.click(screen.getByRole("switch", { name: "Keep on top" }));
});
expect(setBrowserViewPopoutAlwaysOnTop).toHaveBeenCalledWith("p1", true);
});
it("keeps a pop-out that outlived the tab, rather than showing an empty pane", async () => {
// The window belongs to the backend, so reopening the tab has to read its
// The window belongs to the backend, so remounting the pane has to read its
// state back — otherwise the pane would render an iframe alongside it.
isBrowserViewPopoutOpen.mockResolvedValue(true);
getBrowserViewPopoutState.mockResolvedValue({ open: true, always_on_top: true });
checkBrowserViewSupport.mockResolvedValue({ ...READY, browsers: ["chromium-1200"] });
getBrowserViewStatus.mockResolvedValue(LIVE);
@@ -423,6 +425,33 @@ describe("BrowserTab", () => {
expect(await screen.findByText(/in its own window/i)).toBeInTheDocument();
expect(screen.queryByTitle(/browser view for/i)).toBeNull();
// The pin is read from the window too — the pane is unmounted every time
// another sub-tab is selected, so remembering it would show Off over a
// window that is still floating on top.
expect(screen.getByRole("switch", { name: "Keep on top" })).toBeChecked();
});
it("never mounts the iframe before the window's state is known", async () => {
// The status and the pop-out state are two separate round trips. If the
// status wins the race, guessing "not popped out" would flash a second
// viewer onto a browser the window is already driving.
checkBrowserViewSupport.mockResolvedValue({ ...READY, browsers: ["chromium-1200"] });
getBrowserViewStatus.mockResolvedValue(LIVE);
let answer: (s: { open: boolean; always_on_top: boolean }) => void = () => {};
getBrowserViewPopoutState.mockReturnValue(
new Promise((resolve) => {
answer = resolve;
}),
);
render(<BrowserTab project={project} active />);
await waitFor(() => expect(screen.getByText("Live")).toBeInTheDocument());
expect(screen.queryByTitle(/browser view for/i)).toBeNull();
await act(async () => {
answer({ open: false, always_on_top: false });
});
expect(await screen.findByTitle("Playwright browser view for api-server")).toBeInTheDocument();
});
it("says why the window wouldnt open instead of pretending it did", async () => {
+34 -19
View File
@@ -15,7 +15,7 @@ import {
getBrowserViewStatus,
installBrowserViewBrowser,
installBrowserViewSupport,
isBrowserViewPopoutOpen,
getBrowserViewPopoutState,
openBrowserViewPopout,
setBrowserViewEnabled,
setBrowserViewPopoutAlwaysOnTop,
@@ -72,8 +72,13 @@ export default function BrowserTab({ project, active }: Props) {
const [job, setJob] = useState<SetupJob>(null);
const [outcome, setOutcome] = useState<BrowserSetupOutcome | null>(null);
const [setupError, setSetupError] = useState<string | null>(null);
/** Whether the view is currently in its own window instead of this pane. */
const [poppedOut, setPoppedOut] = useState(false);
/**
* Whether the view is in its own window instead of this pane, and whether
* that window is pinned. `null` means "not asked yet" — a distinct state from
* "not popped out", because rendering the iframe on a guess is what puts a
* second viewer on the browser.
*/
const [poppedOut, setPoppedOut] = useState<boolean | null>(null);
const [onTop, setOnTop] = useState(false);
const pushToast = useAppState((s) => s.pushToast);
const setContainerProgress = useAppState((s) => s.setContainerProgress);
@@ -112,7 +117,7 @@ export default function BrowserTab({ project, active }: Props) {
listen<BrowserViewPopoutChangedEvent>("browser-view-popout-changed", (event) => {
if (event.payload.project_id === projectId && mounted.current) {
setPoppedOut(event.payload.open);
if (!event.payload.open) setOnTop(false);
setOnTop(event.payload.always_on_top);
}
}).then((un) => {
if (mounted.current) dispose = un;
@@ -123,9 +128,15 @@ export default function BrowserTab({ project, active }: Props) {
useEffect(() => {
if (!active || !running) return;
isBrowserViewPopoutOpen(projectId)
.then((open) => mounted.current && setPoppedOut(open))
.catch(() => {});
getBrowserViewPopoutState(projectId)
.then((s) => {
if (!mounted.current) return;
setPoppedOut(s.open);
setOnTop(s.always_on_top);
})
// Unreachable in practice, but a pane stuck at "not asked yet" would
// never show the view at all — so fail towards the tab.
.catch(() => mounted.current && setPoppedOut(false));
getBrowserViewStatus(projectId)
.then((s) => mounted.current && setStatus(s))
.catch(() => {});
@@ -304,22 +315,21 @@ export default function BrowserTab({ project, active }: Props) {
</span>
)}
<div className="flex-1" />
{live && poppedOut && (
<label className="flex items-center gap-1.5 text-xs text-[var(--text-secondary)]">
{live && poppedOut === true && (
<span className="flex items-center gap-1.5 text-xs text-[var(--text-secondary)]">
Keep on top
<Toggle
checked={onTop}
onChange={toggleOnTop}
label="Keep the browser window above other windows"
/>
</label>
{/* The accessible name matches the visible text, as everywhere else
a Toggle is used — a `<label>` around it would be inert anyway,
since a Toggle renders a button. */}
<Toggle checked={onTop} onChange={toggleOnTop} label="Keep on top" />
</span>
)}
{live && !poppedOut && (
{live && poppedOut === false && (
<Button size="md" onClick={() => setReloadKey((k) => k + 1)}>
Reload
</Button>
)}
{live && (
{live && poppedOut !== null && (
<Button size="md" onClick={poppedOut ? popIn : popOut}>
{poppedOut ? "Put back in tab" : "Open in own window"}
</Button>
@@ -334,7 +344,7 @@ export default function BrowserTab({ project, active }: Props) {
</Button>
</div>
{live && poppedOut ? (
{live && poppedOut === true ? (
// The iframe is unmounted while the window is up, on purpose. Two
// viewers on one browser both work, but both also *drive* it — two
// cursors taking over the same page is not a feature.
@@ -355,7 +365,7 @@ export default function BrowserTab({ project, active }: Props) {
</div>
</div>
</div>
) : live ? (
) : live && poppedOut === false ? (
<iframe
key={reloadKey}
// Loopback only, and the URL carries the one-time session token the
@@ -364,6 +374,11 @@ export default function BrowserTab({ project, active }: Props) {
title={`Playwright browser view for ${project.name}`}
className="flex-1 min-h-0 w-full border-0 bg-[var(--bg-primary)]"
/>
) : live ? (
// Live, but the window's state hasn't come back yet. An instant, and
// deliberately empty: guessing "not popped out" here is what would
// flash a second viewer onto the browser.
<div className="flex-1 min-h-0" />
) : (
<div className="flex-1 min-h-0 overflow-y-auto">
{/* Setup stays on screen while an install is running and after it