Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] ddfed6afe9 test(server): reproduce queued steer loss at turn completion
Keep controlled completion timing cases and the passing idle-dispatch control for issue #8679. These diagnostic tests intentionally expose dropped delivery; retry semantics remain a maintainer decision because unavailable steering does not establish whether the provider accepted the message.
2026-11-04 10:21:10 +00:00
Mohamed BoudraandElsa Granger 4991efddf8 feat(app): follow iPhone Duo vertical bars and fold divisions (#8741)
* feat(app): follow system vertical bars and fold divisions

Keep custom navigation controls outside system content areas and use active division regions for temporary panel allocation. Normal sidebar preferences resume when the division disappears.

Co-authored-by: Elsa Granger <zeyugao@outlook.com>

* fix(app): show window actions in the active portal scope

The bottom-sheet provider creates its own portal context. Register the window action host within that context so symbols reach the root host.

Co-authored-by: Elsa Granger <zeyugao@outlook.com>

* fix(app): hide workspace bar actions behind compact panels

Compact panels keep the workspace route focused while covering its content. Hide its portal actions until the workspace panel is active again.

Co-authored-by: Elsa Granger <zeyugao@outlook.com>

* fix(app): continue the sidebar surface across divisions

Keep the fold free of controls while painting it as part of the sidebar, with the shared divider at the workspace edge.

Co-authored-by: Elsa Granger <zeyugao@outlook.com>

* fix(app): omit tab count beside the full tab rail

The full tab rail already exposes navigation. Use the same compact/full header selection for the vertical action list.

Co-authored-by: Elsa Granger <zeyugao@outlook.com>

* fix(app): preserve folded navigation and bar action lifetime

Use resolved sidebar visibility for desktop activity, and keep bar controls mounted while compact panels cover them so pending menu work survives. Carry circular button chrome inside the portal and exercise the rendered boundary in Chromium.

Co-authored-by: Elsa Granger <zeyugao@outlook.com>

* fix(app): own script actions across header placement changes

Keep one script action instance on the workspace screen so pending restarts survive removal of either menu. Pass activity through the bar portal so covered menus close their overlays without taking workflow state with them.

Co-authored-by: Elsa Granger <zeyugao@outlook.com>

* test(app): exercise script ownership through the workspace

Replace synthetic ownership fixtures with a real workspace, script menu and isolated terminal worker. Hold terminal exit until the compact header is removed so moving pending state back into the menu fails the regression. Exercise portal activity with production menu and header controls.

Co-authored-by: Elsa Granger <zeyugao@outlook.com>

---------

Co-authored-by: Elsa Granger <zeyugao@outlook.com>
2026-11-04 11:05:45 +01:00
Mohamed Boudra fcbfb4f0d3 Size controls for touch on iPad and other touch screens (#8748)
* feat(app): size controls for touch on any touch device, not just compact layouts

One gate picks touch or pointer sizing: touch when the layout is compact or
the device has a touch screen. The touch fact is read once, so attaching a
mouse or keyboard to a tablet never shrinks its controls. Stylesheets take
`bySizing({ touch, pointer })`, which resolves to a breakpoint value, so the
existing `{ xs, md }` consumers follow the gate without call-site changes.

Touch values follow the iOS HIG 44pt hit region: controls, icon buttons,
rows, bars and menu rows are 44 on touch; `sm` controls are 32. Glyphs move
to a touch ladder (14/18/20/24). Pointer sizes are unchanged.

Merges duplicated header control heights, density's private icon ladder and
the compact-only icon button sizes into control-geometry.

* feat(app): size the composer for touch through control geometry

The composer toolbar, attach / dictation / realtime / send buttons, context
meter and model triggers take TOOLBAR_CONTROL_SIZES (28 pointer, 44 touch)
instead of private 28 constants. The density budget, button glyphs and the
fullscreen glyph rail offset resolve the same gate, replacing the isWeb /
isNative glyph branches. Track rows join the menu row height.

Desktop geometry is unchanged. On touch the toolbar steps down density
earlier: iPad portrait goes from condensed to tight.

* feat(app): fold composer controls before the model label truncates

The composer toolbar walks one width budget: full, condensed, tight,
compact, then icon-only. Tight keeps the model at its family label;
below that, thinking, mode and features fold into the model control's
sheet (the phone toolbar), and only then does the model drop its label.
A touch iPad in portrait with an attachment now reads
"GPT-6-Astra Medium" instead of "GP…".

The context meter glyph and combobox rows and icons take the density
ladder. Desktop is pixel-identical in the content area.

* refactor(app): keep the sizing gate free of the theme

constants/layout sized its bars through control-geometry, which loads the
theme and runs Platform.select at import. The gate (resolveControlSizing,
bySizing, TOUCH_TARGET) moves to control-sizing.ts with no theme import;
control-geometry re-exports it, so its callers are unchanged.

* test(app): expect touch sizing in the compact Changes and plugin sidebar specs

The compact Changes options button is a 44pt icon button with a 20pt glyph,
and its framed actions trigger is 32 tall. In the compact sidebar the nav
block is capped at half the height, so 44pt rows put the plugin header row
below the cap; the spec scrolls it into view as a user would.

* fix(app): close composer menus when the controls fold or unfold

Folding swaps the toolbar controls for the model sheet. A menu opened on the
separate controls stayed marked open across the fold, so widening the
composer again reopened Thinking without a click.
2026-11-04 11:04:52 +01:00
Monarch MaisuriyaandClaude Opus 5.5 6221b0c8b7 Fork from earlier replies when a plugin card was updated later (#8746)
The fork checkpoint check refused a fork when any projected row spanned the
selected reply. A plugin card re-appended with the same id keeps its first
position and stretches to its latest update, so it spanned every reply in
between, although the fork never copies plugin cards. The check now looks only
at the row kinds the fork copies, taken from the same constant as the copy.

Closes #8745

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:02:25 +00:00
65 changed files with 1926 additions and 583 deletions
+5 -3
View File
@@ -68,9 +68,11 @@ the sidebar. Apply it as `backgroundColor`; setting `opacity` on the control als
`destructive` is filled with `destructive`. It only appears inside a confirm. The button on the page is `outline`; the destructive button is the confirm button inside the dialog.
Controls come in two sizes, defined once in `control-geometry.ts`. The default is the right size almost everywhere — pages, dialogs, forms, settings rows, the setup flow — so don't pass a size. It is 32px tall where a pointer drives it and 44px in the compact layout, so every phone control is a full touch target; the breakpoint, not the caller, makes that choice. `sm` is 28px with `fontSize.sm` labels and is for tight chrome only: toolbars, nested settings rows, dense inline row actions. A `size="sm"` on an ordinary page or dialog is wrong, and so is choosing a size from `useIsCompactFormFactor()`.
Controls come in two sizes, defined once in `control-geometry.ts`. The default is the right size almost everywhere — pages, dialogs, forms, settings rows, the setup flow — so don't pass a size. It is 32px tall where a pointer drives it and 44px where controls are touch-sized, so every touch control meets the iOS HIG's 44pt hit region. `sm` is 28px pointer and 32px touch, with `fontSize.sm` labels, and is for tight chrome only: toolbars, nested settings rows, dense inline row actions. A `size="sm"` on an ordinary page or dialog is wrong, and so is choosing a size from `useIsCompactFormFactor()`.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 in the compact layout, and it reserves its size's control height so a row holding one lines up with a row holding a button. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or the device has a touch screen. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The touch-screen fact is read once at startup (`hasTouchScreen` in `hooks/use-fine-pointer.ts`), so attaching a mouse or keyboard to a tablet never shrinks its controls. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it reserves its size's control height so a row holding one lines up with a row holding a button. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
A `<Pressable>` wrapping a `<Text>` is a sixth variant. It is wrong. `<Button>` accepts `style`, `textStyle`, `leftIcon`, `disabled`, `size`, and `variant`.
@@ -150,7 +152,7 @@ One row off the rail makes the whole card look unconsidered.
Compact-first. The small case is designed; the large case adds chrome around it.
Use `md: 600` for both the compact/wide layout boundary and responsive density, in logical points on native and CSS pixels on web. Do not add a separate density breakpoint. Measured content constraints remain independent: composer controls use `COMPACT_CONTENT_WIDTH` (500), so a narrow pane can keep compact controls inside a wide window.
Use `md: 600` for the compact/wide layout boundary, in logical points on native and CSS pixels on web. Do not add a separate density breakpoint; touch sizing comes from the control sizing gate in [Buttons](#4-buttons). Measured content constraints remain independent: composer controls use `COMPACT_CONTENT_WIDTH` (500), so a narrow pane can keep compact controls inside a wide window.
The settings shell (`packages/app/src/screens/settings-screen.tsx`) and the projects screen (`packages/app/src/screens/projects-screen.tsx`) share the canonical list+detail navigation pattern:
+4 -3
View File
@@ -95,9 +95,10 @@ Provider message IDs are not guaranteed for every displayed item. Paseo-generate
Actions that address a point in chat history, such as Fork, use the daemon timeline `epoch` plus the projected item's `seqEnd`. The app carries that position on the rendered assistant item for both live and fetched history. When adjacent projected chunks merge, the merged item retains the newer chunk's position.
The daemon validates the epoch and locates the projected item at the selected position. A fork
includes projected items through that checkpoint. If an item spans the checkpoint and changed
afterward, the daemon refuses that fork with an actionable error: discarded historical payloads
cannot be reconstructed from sequence metadata. Forking the current context remains available.
includes projected items through that checkpoint. If an item the fork copies spans the checkpoint
and changed afterward, the daemon refuses that fork with an actionable error: discarded historical
payloads cannot be reconstructed from sequence metadata. Plugin cards are not copied, so a card
updated after the checkpoint does not block it. Forking the current context remains available.
## Resume behavior
@@ -928,11 +928,11 @@ test("compact Changes keeps its actions compact and menu-only", async ({ page })
throw new Error("Compact Changes toolbar geometry could not be measured");
}
expect(actionsBox.width).toBe(48);
expect(actionsBox.height).toBe(28);
expect(optionsBox.width).toBe(32);
expect(optionsBox.height).toBe(32);
expect(glyphBox.width).toBe(18);
expect(glyphBox.height).toBe(18);
expect(actionsBox.height).toBe(32);
expect(optionsBox.width).toBe(44);
expect(optionsBox.height).toBe(44);
expect(glyphBox.width).toBe(20);
expect(glyphBox.height).toBe(20);
await expect(actions).not.toContainText("Commit");
await expect(actions.locator("svg")).toHaveCount(2);
@@ -1,5 +1,6 @@
import type { Page, TestInfo } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { pauseWorkspaceTerminalWorker } from "../support/helpers/workspace-setup";
import { seedWorkspace } from "../support/helpers/seed-client";
import { openAgentRoute } from "../support/helpers/mock-agent";
import { getServerId } from "../support/helpers/server-id";
@@ -190,3 +191,49 @@ test("compact header menu runs, shows, and stops workspace scripts", async ({ pa
await workspace.cleanup();
}
});
async function restartScriptAcrossHeaderRemoval(page: Page, terminalId: string) {
await openRunningScriptPage(page, "lint");
const resumeWorker = await pauseWorkspaceTerminalWorker(terminalId);
try {
await menuRow(page, "Restart").click();
await page.setViewportSize({ width: 1280, height: 844 });
await expect(page.getByRole("button", { name: /Switch tabs/ })).toHaveCount(0);
await expect(page.getByTestId("workspace-scripts-button")).toBeVisible();
} finally {
resumeWorker();
}
}
async function expectScriptTerminalReplaced(
workspace: Awaited<ReturnType<typeof openWorkspaceWithScripts>>,
previousId: string,
) {
await expect
.poll(
async () => {
const after = await workspace.client.listTerminals(undefined, undefined, {
workspaceId: workspace.workspaceId,
});
return after.terminals.filter((terminal) => terminal.id !== previousId).length;
},
{ timeout: 15_000 },
)
.toBe(1);
}
test("pending script restart survives removal of the compact header", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await openWorkspaceWithScripts(page);
try {
await runScriptFromScriptsPage(page, "lint");
const before = await workspace.client.listTerminals(undefined, undefined, {
workspaceId: workspace.workspaceId,
});
expect(before.terminals).toHaveLength(1);
await restartScriptAcrossHeaderRemoval(page, before.terminals[0]!.id);
await expectScriptTerminalReplaced(workspace, before.terminals[0]!.id);
} finally {
await workspace.cleanup();
}
});
@@ -5,6 +5,7 @@ import {
recordComposerToolbarFrames,
} from "../support/helpers/composer-control-density";
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
const SETTLE_MS = 1_000;
@@ -92,3 +93,34 @@ test.describe("Composer control density across tab switches", () => {
}
});
});
test.describe("Composer controls folding on a touch device", () => {
test.use({ viewport: { width: 1194, height: 834 }, isMobile: true, hasTouch: true });
test.describe.configure({ timeout: 180_000 });
test("an open menu stays closed after the controls fold and unfold", async ({ page }) => {
const session = await seedMockAgentWorkspace({
repoPrefix: "composer-density-fold-",
title: "Folding chat",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, session);
const thinking = page.getByTestId("agent-thinking-selector").filter({ visible: true });
const thinkingMenu = page.getByTestId("combobox-desktop-container");
await thinking.click();
await expect(thinkingMenu).toBeVisible();
// Still a wide layout, but too narrow for separate controls: they fold into the model control.
await page.setViewportSize({ width: 640, height: 834 });
await expect(thinking).toHaveCount(0);
await page.setViewportSize({ width: 1194, height: 834 });
await expect(thinking).toBeVisible();
await expect(thinkingMenu).toHaveCount(0);
} finally {
await session.cleanup();
}
});
});
@@ -317,7 +317,10 @@ test.describe("Plugin sidebar items", () => {
const compactSync = footerItem(page, SHOWCASE_PLUGIN_ID, "sync");
await expect(compactSync).toBeInViewport();
await expectFooterRow(page, compactSync);
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeInViewport();
// The compact nav block is capped at half the sidebar and scrolls past it.
const compactDeploys = headerRow(page, SHOWCASE_PLUGIN_ID, "deploys");
await compactDeploys.scrollIntoViewIfNeeded();
await expect(compactDeploys).toBeInViewport();
await qaScreenshot(page, "phase2-compact-sidebar");
await qaScreenshot(page, "phase5-compact-footer", sidebarFooter(page));
await compactSync.click();
@@ -6,6 +6,11 @@ env APP_ID=sh.paseo.debug
# Hold past drag arming (180ms), then release.
open "${APP_ID}"
press "label=\"Open menu\""
wait "id=\"sidebar-close\"" 10000
press "id=\"sidebar-close\""
# The close target must clear system controls, including a trailing status column.
wait "label=\"Open menu\"" 5000
press "label=\"Open menu\""
wait "id=\"${WORKSPACE_ROW}\"" 10000
longpress "id=\"${WORKSPACE_ROW}\"" 250
press "id=\"${WORKSPACE_ROW}\""
@@ -1,3 +1,5 @@
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { realpathSync } from "node:fs";
import { expect, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
@@ -380,3 +382,21 @@ export function observeSetupPanelTraffic(page: Page) {
export function setupCommandOutput(detail: { commands: Array<{ log: string }> }): string {
return detail.commands.map((command) => command.log).join("\n");
}
/** Hold this isolated daemon's terminal worker so script exit cannot race a layout change. */
export async function pauseWorkspaceTerminalWorker(terminalId: string): Promise<() => void> {
const home = process.env.E2E_PASEO_HOME;
if (!home) throw new Error("Missing isolated E2E home");
const directory = path.join(home, "terminal-worker");
for (const name of await readdir(directory)) {
if (!name.endsWith(".json")) continue;
const record = JSON.parse(await readFile(path.join(directory, name), "utf8")) as {
pid: number;
terminals: Array<{ id: string }>;
};
if (!record.terminals.some((terminal) => terminal.id === terminalId)) continue;
process.kill(record.pid, "SIGSTOP");
return () => process.kill(record.pid, "SIGCONT");
}
throw new Error(`No isolated terminal worker owns ${terminalId}`);
}
@@ -0,0 +1,4 @@
{
"platforms": ["ios"],
"ios": { "modules": ["PaseoWindowLayoutModule"] }
}
@@ -0,0 +1,15 @@
Pod::Spec.new do |s|
s.name = 'PaseoWindowLayout'
s.version = '0.1.0'
s.summary = 'System window layout geometry for Paseo'
s.description = 'Publishes system bar and division geometry'
s.license = 'Apache-2.0'
s.author = 'Paseo'
s.homepage = 'https://paseo.sh'
s.platforms = { :ios => '16.4' }
s.swift_version = '5.4'
s.source = { :path => '.' }
s.static_framework = true
s.dependency 'ExpoModulesCore'
s.source_files = '**/*.swift'
end
@@ -0,0 +1,110 @@
import ExpoModulesCore
import UIKit
public final class PaseoWindowLayoutModule: Module {
public func definition() -> ModuleDefinition {
Name("PaseoWindowLayout")
View(WindowLayoutView.self) {
Events("onGeometryChange")
}
}
}
final class WindowLayoutView: ExpoView {
let onGeometryChange = EventDispatcher()
private var updateScheduled = false
private var previousPayload: [String: Any]?
private var divisions: [CGRect] = []
private var barGuide: UILayoutGuide?
private var barEdge = "none"
private var measuredBounds = CGRect.zero
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
isUserInteractionEnabled = false
#if compiler(>=6.4)
if #available(iOS 27.1, *) {
registerForTraitChanges(UITraitCollection.systemTraitsAffectingVerticalBarEdge) {
(view: WindowLayoutView, _) in
view.setNeedsUpdateConstraints()
view.scheduleUpdate()
}
}
#endif
}
override func didMoveToWindow() {
super.didMoveToWindow()
previousPayload = nil
setNeedsUpdateConstraints()
scheduleUpdate()
}
override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
setNeedsUpdateConstraints()
scheduleUpdate()
}
override func layoutSubviews() {
super.layoutSubviews()
if bounds != measuredBounds {
measuredBounds = bounds
setNeedsUpdateConstraints()
}
scheduleUpdate()
}
override func updateConstraints() {
#if compiler(>=6.4)
if #available(iOS 27.1, *) {
// UIKit tracks these reads and invalidates constraints when regions change.
divisions = reservedRegions(kind: .division).compactMap { $0.isActive ? $0.frame : nil }
let edge: String
switch traitCollection.verticalBarEdge {
case .leading: edge = "leading"
case .trailing: edge = "trailing"
default: edge = "none"
}
if edge != barEdge {
barEdge = edge
barGuide = edge == "none" ? nil : layoutGuide(
for: .bar(onEdge: edge == "trailing" ? .right : .left, extent: 44)
)
}
}
#endif
super.updateConstraints()
scheduleUpdate()
}
private func scheduleUpdate() {
guard !updateScheduled else { return }
updateScheduled = true
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.updateScheduled = false
self.publish()
}
}
private func publish() {
guard window != nil, bounds.width > 0, bounds.height > 0 else { return }
let bar = barGuide?.layoutFrame
var barPayload: Any = NSNull()
if let bar, bar.width > 0, bar.height > 0 { barPayload = rect(bar) }
let payload: [String: Any] = [
"bounds": rect(bounds),
"verticalBarEdge": barEdge,
"verticalBar": barPayload,
"divisions": divisions.map(rect)
]
guard !NSDictionary(dictionary: payload).isEqual(to: previousPayload ?? [:]) else { return }
previousPayload = payload
onGeometryChange(payload)
}
private func rect(_ frame: CGRect) -> [String: CGFloat] {
["x": frame.minX, "y": frame.minY, "width": frame.width, "height": frame.height]
}
}
+48 -20
View File
@@ -1,4 +1,12 @@
import { useHardwareKeyboardPresent } from "@/keyboard";
import {
WindowLayoutProvider,
WindowLayoutActionsHost,
WindowLayoutSurface,
WindowLayoutDivisionGap,
useWindowLayout,
resolveDesktopDivisionLayout,
} from "@/window-layout";
import { AddHostProvider, AddHostFlowHost } from "@/hosts/add-host";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
@@ -59,6 +67,7 @@ import {
resolveDesktopAppChromeLayout,
resolveDesktopAppContentMinimum,
resolveDesktopSidebarVisibility,
resolveSidebarActivity,
} from "@/components/desktop-sidebar-layout";
import { isNative, isWeb } from "@/constants/platform";
import { HorizontalScrollProvider } from "@/contexts/horizontal-scroll-context";
@@ -355,9 +364,16 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
const isFocusModeEnabled = usePanelStore((state) => state.desktop.focusModeEnabled);
const isDesktopAgentListOpen = usePanelStore((state) => state.desktop.agentListOpen);
const sidebarWidth = usePanelStore((state) => state.sidebarWidth);
const { width: windowWidth } = useWindowDimensions();
const { width: windowWidth, height: windowHeight } = useWindowDimensions();
const insets = useSafeAreaInsets();
const viewportWidth = windowWidth - insets.left - insets.right;
const divisionLayout = resolveDesktopDivisionLayout({
geometry: useWindowLayout(),
windowWidth,
windowHeight,
leftInset: insets.left,
rightInset: insets.right,
});
const cycleTheme = useCallback(() => {
void updateSettings({ theme: getNextThemePreference(settings.theme) });
@@ -418,6 +434,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
isCompactLayout,
isMounted: desktopSidebarMounted,
isOpen: isDesktopAgentListOpen,
divisionLayout,
canShare: canDesktopAppSidebarShare({
contentMinimumWidth: appContentMinimumWidth,
requestedSidebarWidth: sidebarWidth,
@@ -441,18 +458,19 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
if (isWeb) {
themedSidebarChrome = <AppearanceStyleBoundary>{sidebarChrome}</AppearanceStyleBoundary>;
}
const workspaceChromeStyle = useMemo(
() => [rowStyle, !isCompactLayout && { paddingLeft: insets.left, paddingRight: insets.right }],
[insets.left, insets.right, isCompactLayout],
);
const workspaceChrome = (
<View style={workspaceChromeStyle}>
<WindowLayoutSurface compact={isCompactLayout} style={rowStyle}>
<WorkspaceLayoutModePublisher />
{!isCompactLayout ? (
<WindowChromeRegion corners={appChromeLayout.sidebarCorners}>
{themedSidebarChrome}
</WindowChromeRegion>
) : null}
<WindowLayoutDivisionGap
layout={divisionLayout}
sidebarVisible={desktopSidebarVisible}
compact={isCompactLayout}
/>
<WorkspaceExplorerOpenGesture enabled={chromeEnabled && isCompactLayout}>
<WindowChromeRegion
corners={isCompactLayout && chromeEnabled ? "both" : appChromeLayout.contentCorners}
@@ -460,7 +478,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
<View style={flexStyle}>{children}</View>
</WindowChromeRegion>
</WorkspaceExplorerOpenGesture>
</View>
</WindowLayoutSurface>
);
// Native panel gesture hosts outlive appearance keys, like native navigators.
@@ -548,8 +566,7 @@ function SidebarChrome({
}) {
const isCompactLayout = useIsCompactFormFactor();
const isMobileActive = useIsMobilePanelActive("agent-list");
const isDesktopOpen = usePanelStore((state) => state.desktop.agentListOpen);
const active = visible && (isCompactLayout ? isMobileActive : isDesktopOpen);
const active = resolveSidebarActivity(visible, isCompactLayout, isMobileActive);
const hardwareKeyboardPresent = useHardwareKeyboardPresent();
return (
<SidebarModelProvider
@@ -875,20 +892,31 @@ function RuntimeProviders({ children }: { children: ReactNode }) {
// auth, settings, ...) must wrap PortalProvider, not be wrapped by it.
// BottomSheetModalProvider is the exception: Gorhom modals consume portal
// context and need one shared provider for sibling sheets to stack.
function RootOverlayProviders({ children }: { children: ReactNode }) {
return (
<ToastProvider>
<PortalProvider>
<BottomSheetModalProvider>
{children}
<WindowLayoutActionsHost />
</BottomSheetModalProvider>
</PortalProvider>
</ToastProvider>
);
}
function RootProviders({ children }: { children: ReactNode }) {
return (
<KeyboardActionDispatcherProvider>
<WindowChromeProvider>
<KeyboardProvider>
<KeyboardShiftProvider>
<ToastProvider>
<PortalProvider>
<BottomSheetModalProvider>{children}</BottomSheetModalProvider>
</PortalProvider>
</ToastProvider>
</KeyboardShiftProvider>
</KeyboardProvider>
</WindowChromeProvider>
<WindowLayoutProvider>
<WindowChromeProvider>
<KeyboardProvider>
<KeyboardShiftProvider>
<RootOverlayProviders>{children}</RootOverlayProviders>
</KeyboardShiftProvider>
</KeyboardProvider>
</WindowChromeProvider>
</WindowLayoutProvider>
</KeyboardActionDispatcherProvider>
);
}
@@ -13,6 +13,7 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
@@ -292,7 +293,7 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: 0,
},
trigger: {
height: 28,
height: TOOLBAR_CONTROL_HEIGHT,
minWidth: 0,
flexShrink: 1,
flexDirection: "row",
@@ -9,6 +9,7 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import { useHostReportsUsage } from "@/usage";
import type { Theme } from "@/styles/theme";
import { TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { ContextWindowDetails } from "./context-window-details";
import { ContextWindowSheet } from "./context-window-sheet";
import { formatContextPercentage } from "./context-window-meter.utils";
@@ -306,14 +307,14 @@ export function ContextWindowMeter({
const styles = StyleSheet.create((theme) => ({
container: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
containerWithLabel: {
height: 28,
height: TOOLBAR_CONTROL_HEIGHT,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
@@ -1,13 +1,97 @@
import { describe, expect, it } from "vitest";
import {
resolveDesktopDivisionLayout,
resolveWorkspaceActionPlacement,
resolveWorkspaceBarActions,
type WindowLayout,
} from "@/window-layout";
import {
canDesktopAppSidebarShare,
resolveDesktopAppChromeLayout,
resolveDesktopAppContentMinimum,
resolveDesktopSidebarVisibility,
resolveSidebarActivity,
resolveDesktopSidebarWidth,
} from "@/components/desktop-sidebar-layout";
describe("desktop sidebar layout", () => {
const geometry: WindowLayout = {
bounds: { x: 0, y: 0, width: 951, height: 669 },
verticalBarEdge: "trailing",
verticalBar: { x: 875, y: 160, width: 44, height: 450 },
divisions: [{ x: 465, y: 0, width: 21, height: 669 }],
};
it("places workspace action symbols in the reported trailing bar", () => {
expect(resolveWorkspaceActionPlacement(geometry)).toBe("vertical-bar");
expect(resolveWorkspaceActionPlacement(null)).toBe("header");
expect(resolveWorkspaceActionPlacement({ ...geometry, verticalBarEdge: "none" })).toBe(
"header",
);
expect(resolveWorkspaceActionPlacement({ ...geometry, verticalBar: null })).toBe("header");
expect(resolveWorkspaceActionPlacement({ ...geometry, verticalBarEdge: "leading" })).toBe(
"header",
);
});
it("shows the tab count only for the compact header selection", () => {
expect(resolveWorkspaceBarActions("compact")).toEqual(["tab-count", "overflow", "explorer"]);
expect(resolveWorkspaceBarActions("full")).toEqual(["overflow", "explorer"]);
});
it("allocates both panels around a live division without clamping to saved sidebar widths", () => {
const input = {
geometry,
windowWidth: 951,
windowHeight: 669,
leftInset: 0,
rightInset: 84,
};
expect(resolveDesktopDivisionLayout(input)).toEqual({
sidebarWidth: 465,
gap: 21,
contentWidth: 381,
});
expect(
resolveDesktopDivisionLayout({ ...input, geometry: { ...geometry, divisions: [] } }),
).toBeNull();
expect(
resolveDesktopDivisionLayout({ ...input, windowWidth: 669, windowHeight: 951 }),
).toBeNull();
expect(resolveDesktopDivisionLayout({ ...input, geometry: null })).toBeNull();
expect(
resolveDesktopDivisionLayout({
...input,
geometry: { ...geometry, divisions: [{ x: 0, y: 325, width: 951, height: 19 }] },
}),
).toBeNull();
});
it("activates a revealed folded sidebar while preserving closed desktop intent", () => {
expect(resolveSidebarActivity(true, false, false)).toBe(true);
expect(resolveSidebarActivity(false, false, false)).toBe(false);
expect(resolveSidebarActivity(true, true, false)).toBe(false);
expect(resolveSidebarActivity(true, true, true)).toBe(true);
});
it("temporarily reveals navigation for a division without changing the saved closed intent", () => {
const visibility = {
chromeEnabled: true,
isCompactLayout: false,
isMounted: true,
isOpen: false,
canShare: false,
};
expect(
resolveDesktopSidebarVisibility({
...visibility,
divisionLayout: { sidebarWidth: 465, gap: 21, contentWidth: 381 },
}),
).toBe(true);
expect(resolveDesktopSidebarVisibility({ ...visibility, divisionLayout: null })).toBe(false);
expect(visibility.isOpen).toBe(false);
});
it("keeps a retained sidebar hidden while app chrome is suppressed", () => {
expect(
resolveDesktopSidebarVisibility({
@@ -1,6 +1,7 @@
import { EXPLORER_WORKSPACE_MIN_WIDTH } from "@/components/explorer-sidebar-layout";
import { SETTINGS_DESKTOP_SPLIT_MIN_WIDTH } from "@/constants/layout";
import { MAX_SIDEBAR_WIDTH, MIN_SIDEBAR_WIDTH } from "@/stores/panel-store";
import type { DesktopDivisionLayout } from "@/window-layout";
const MIN_DESKTOP_CENTER_WIDTH = 400;
@@ -10,13 +11,13 @@ export function resolveDesktopSidebarVisibility(input: {
isMounted: boolean;
isOpen: boolean;
canShare: boolean;
divisionLayout?: DesktopDivisionLayout | null;
}): boolean {
return (
input.chromeEnabled &&
!input.isCompactLayout &&
input.isMounted &&
input.isOpen &&
input.canShare
(input.divisionLayout != null || (input.isOpen && input.canShare))
);
}
@@ -85,3 +86,11 @@ export function canDesktopAppSidebarShare(input: {
input.contentMinimumWidth
);
}
export function resolveSidebarActivity(
visible: boolean,
compact: boolean,
mobileActive: boolean,
): boolean {
return visible && (!compact || mobileActive);
}
+38 -23
View File
@@ -26,6 +26,7 @@ import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import { resolveDesktopSidebarWidth } from "@/components/desktop-sidebar-layout";
import { useWindowLayout, resolveDesktopDivisionLayout } from "@/window-layout";
import {
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
SIDEBAR_RESIZE_FAIL_OFFSET,
@@ -528,6 +529,7 @@ function MobileSidebar({
insetsBottom,
closeSidebar,
}: MobileSidebarProps) {
const insets = useSafeAreaInsets();
const hasActiveHostFilter = useSidebarViewStore((state) => state.hostFilters.length > 0);
const { gesture: closeGesture, gestureRef: closeGestureRef } = useCloseAgentListGesture();
@@ -542,10 +544,10 @@ function MobileSidebar({
onPress={closeSidebar}
testID="sidebar-close"
nativeID="sidebar-close"
style={styles.mobileCloseButton}
style={styles.mobileCloseButton(insets.right)}
/>
),
[labels.closeSidebar, closeSidebar],
[labels.closeSidebar, closeSidebar, insets.right],
);
const mobileSidebarInsetStyle = useMemo(
@@ -666,13 +668,22 @@ function DesktopSidebar({
const hasActiveHostFilter = useSidebarViewStore((state) => state.hostFilters.length > 0);
const sidebarWidth = usePanelStore((state) => state.sidebarWidth);
const setSidebarWidth = usePanelStore((state) => state.setSidebarWidth);
const { width: windowWidth } = useWindowDimensions();
const { width: windowWidth, height: windowHeight } = useWindowDimensions();
const insets = useSafeAreaInsets();
const viewportWidth = windowWidth - insets.left - insets.right;
const visibleSidebarWidth = resolveDesktopSidebarWidth({
requestedWidth: sidebarWidth,
viewportWidth,
const divisionLayout = resolveDesktopDivisionLayout({
geometry: useWindowLayout(),
windowWidth,
windowHeight,
leftInset: insets.left,
rightInset: insets.right,
});
const visibleSidebarWidth =
divisionLayout?.sidebarWidth ??
resolveDesktopSidebarWidth({
requestedWidth: sidebarWidth,
viewportWidth,
});
const startWidthRef = useRef(visibleSidebarWidth);
const resizeWidth = useSharedValue(visibleSidebarWidth);
@@ -687,6 +698,7 @@ function DesktopSidebar({
const resizeGesture = useMemo(
() =>
Gesture.Pan()
.enabled(divisionLayout === null)
.hitSlop({ left: 8, right: 8, top: 0, bottom: 0 })
.onBegin(() => {
scheduleOnRN(showResizeGrip);
@@ -708,13 +720,14 @@ function DesktopSidebar({
viewportWidth,
});
})
.onEnd(() => {
runOnJS(setSidebarWidth)(resizeWidth.value);
.onEnd((_event, success) => {
if (success) runOnJS(setSidebarWidth)(resizeWidth.value);
})
.onFinalize(() => {
scheduleOnRN(hideResizeGrip);
}),
[
divisionLayout,
hideResizeGrip,
resizeWidth,
setSidebarWidth,
@@ -725,7 +738,7 @@ function DesktopSidebar({
);
const resizeAnimatedStyle = useAnimatedStyle(() => ({
width: resizeWidth.value,
width: divisionLayout?.sidebarWidth ?? resizeWidth.value,
}));
const desktopSidebarStyle = useMemo(
@@ -738,10 +751,10 @@ function DesktopSidebar({
);
const desktopSidebarBorderStyle = useMemo(
() => [
styles.desktopSidebarBorder,
styles.desktopSidebarBorder(divisionLayout !== null),
{ flex: 1, paddingTop: insetsTop, paddingBottom: insets.bottom },
],
[insetsTop, insets.bottom],
[insetsTop, insets.bottom, divisionLayout],
);
const sidebarHeaderGroupStyle = useMemo(
() => [styles.sidebarHeaderGroup, ownsTopLeft && styles.sidebarHeaderGroupBelowChrome],
@@ -812,12 +825,14 @@ function DesktopSidebar({
handleOpenHostSettings={handleOpenHostSettings}
/>
<SidebarResizeHandle
edge="right"
gesture={resizeGesture}
pressed={resizePressed}
testID="left-sidebar-resize-handle"
/>
{divisionLayout === null ? (
<SidebarResizeHandle
edge="right"
gesture={resizeGesture}
pressed={resizePressed}
testID="left-sidebar-resize-handle"
/>
) : null}
</View>
</Animated.View>
);
@@ -883,14 +898,14 @@ const styles = StyleSheet.create((theme) => ({
flex: 1,
minHeight: 0,
},
mobileCloseButton: {
marginRight: theme.spacing[2],
},
desktopSidebarBorder: {
borderRightWidth: 1,
mobileCloseButton: (rightInset: number) => ({
marginRight: theme.spacing[2] + rightInset,
}),
desktopSidebarBorder: (hasDivision: boolean) => ({
borderRightWidth: hasDivision ? 0 : 1,
borderRightColor: theme.colors.border,
backgroundColor: theme.colors.surfaceSidebar,
},
}),
sidebarDragArea: {
position: "relative",
},
@@ -1,7 +1,7 @@
import { createContext, useContext, useMemo, type ReactNode } from "react";
import type { StyleProp, TextStyle, ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { CONTROL_HEIGHTS, type ControlSize } from "@/components/ui/control-geometry";
import { CONTROL_HEIGHTS, mapLayout, type ControlSize } from "@/components/ui/control-geometry";
import { settingsStyles } from "@/styles/settings";
@@ -49,7 +49,7 @@ const styles = StyleSheet.create((theme) => ({
// trailing button line up.
nestedRow: {
paddingVertical: theme.spacing[2],
minHeight: CONTROL_HEIGHTS.sm + theme.spacing[2] * 2,
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height + theme.spacing[2] * 2),
},
nestedText: {
fontSize: theme.fontSize.sm,
@@ -154,6 +154,7 @@ import type { HostBadgeModel } from "@/hosts/appearance";
import { useHostBadges } from "@/hosts/use-host-badges";
import { useSidebarRowItems } from "@/components/sidebar/display-preferences/model";
import { PullRequestStateIcon } from "@/git/pull-request-state-icon";
import { bySizing } from "@/components/ui/control-geometry";
const workspaceKeyExtractor = (workspace: SidebarWorkspacePlacement) => workspace.workspaceKey;
@@ -2737,12 +2738,12 @@ const styles = StyleSheet.create((theme) => ({
marginRight: -6,
},
projectKebabButton: {
// Larger on compact so the kebab is an easy tap target. The negative margins keep its
// dots on the same rail as the 24px desktop box and the row at its 44px height.
width: { xs: 32, md: 24 },
height: { xs: 32, md: 24 },
marginRight: { xs: -4, md: 0 },
marginVertical: { xs: -4, md: 0 },
// Larger on touch so the kebab is an easy tap target. The negative margins keep its
// dots on the same rail as the 24px pointer box and the row at its 44px height.
width: bySizing({ touch: 32, pointer: 24 }),
height: bySizing({ touch: 32, pointer: 24 }),
marginRight: bySizing({ touch: -4, pointer: 0 }),
marginVertical: bySizing({ touch: -4, pointer: 0 }),
borderRadius: theme.borderRadius.md,
alignItems: "center",
justifyContent: "center",
@@ -36,6 +36,7 @@ import {
import { Shortcut } from "@/components/ui/shortcut";
import { OpenInFileManagerMenuItem } from "@/workspace/open-in-file-manager/menu-item";
import { resolveSidebarWorkspaceAccessibilityLabel } from "@/components/sidebar/sidebar-workspace-title";
import { bySizing } from "@/components/ui/control-geometry";
import {
workspaceServiceLabelKey,
type WorkspaceServiceSummary,
@@ -438,18 +439,18 @@ function triggerStyle({ hovered = false }: PressableStateCallbackType & { hovere
const styles = StyleSheet.create((theme) => ({
trigger: {
// Larger on compact so the kebab is an easy tap target.
width: { xs: 32, md: 18 },
height: { xs: 32, md: 18 },
// Larger on touch so the kebab is an easy tap target.
width: bySizing({ touch: 32, pointer: 18 }),
height: bySizing({ touch: 32, pointer: 18 }),
alignItems: "center",
justifyContent: "center",
borderRadius: 4,
marginLeft: 2,
// Center the compact box on the 20px title line it is anchored to.
marginTop: { xs: -6, md: 0 },
// Center the touch box on the 20px title line it is anchored to.
marginTop: bySizing({ touch: -6, pointer: 0 }),
// MoreVertical paints only around the center of its SVG. Keep the padded hit box, but
// pull the painted dots through that unused view-box space onto the trailing-content rail.
marginRight: { xs: -14, md: -7 },
marginRight: bySizing({ touch: -14, pointer: -7 }),
},
triggerHovered: {
backgroundColor: theme.colors.surface2,
+9 -9
View File
@@ -64,6 +64,8 @@ import {
import { FloatingSurface } from "@/components/ui/floating";
import { useDismissKeyboardOnOpen } from "@/components/ui/keyboard-dismiss";
import { getOverlayRoot, OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
import { density, densityIconBox } from "@/styles/density";
import { DensityIcon } from "@/components/ui/density-icon";
import { buildDesktopFrameStyle } from "./combobox-frame-style";
export { buildDesktopFrameStyle } from "./combobox-frame-style";
@@ -203,7 +205,7 @@ export function SearchInput({
return (
<View style={styles.searchInputContainer}>
<Search size={16} color={theme.colors.foregroundMuted} />
<DensityIcon icon={Search} size="md" color="foregroundMuted" />
<AdaptiveTextInput
ref={inputRef}
// @ts-expect-error - outlineStyle is web-only
@@ -250,21 +252,19 @@ export function ComboboxItem({
onPress,
testID,
}: ComboboxItemProps): ReactElement {
const { theme } = useUnistyles();
let leadingContent: ReactElement | null = null;
if (leadingSlot) {
leadingContent = <View style={styles.comboboxItemLeadingSlot}>{leadingSlot}</View>;
} else if (kind === "directory") {
leadingContent = (
<View style={styles.comboboxItemLeadingSlot}>
<Folder size={16} color={theme.colors.foregroundMuted} />
<DensityIcon icon={Folder} size="md" color="foregroundMuted" />
</View>
);
} else if (kind === "file") {
leadingContent = (
<View style={styles.comboboxItemLeadingSlot}>
<File size={16} color={theme.colors.foregroundMuted} />
<DensityIcon icon={File} size="md" color="foregroundMuted" />
</View>
);
}
@@ -308,7 +308,7 @@ export function ComboboxItem({
{selected || trailingSlot ? (
<View style={styles.comboboxItemTrailingContainer}>
<View style={styles.comboboxItemTrailingSlot}>
{selected ? <Check size={16} color={theme.colors.foregroundMuted} /> : null}
{selected ? <DensityIcon icon={Check} size="md" color="foregroundMuted" /> : null}
</View>
{trailingSlot}
</View>
@@ -1682,7 +1682,7 @@ const styles = StyleSheet.create((theme) => ({
comboboxItem: {
flexDirection: "row",
alignItems: "center",
minHeight: 36,
minHeight: density.rowHeight,
gap: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
paddingVertical: theme.spacing[2],
@@ -1713,7 +1713,7 @@ const styles = StyleSheet.create((theme) => ({
opacity: 0.55,
},
comboboxItemTrailingSlot: {
width: 16,
width: densityIconBox("md"),
alignItems: "center",
justifyContent: "center",
},
@@ -1733,7 +1733,7 @@ const styles = StyleSheet.create((theme) => ({
gap: theme.spacing[2],
},
comboboxItemLeadingSlot: {
width: 16,
width: densityIconBox("md"),
alignItems: "center",
justifyContent: "center",
},
@@ -1,11 +1,20 @@
import { describe, expect, it } from "vitest";
import {
ALERT_ICON_SIZE,
bySizing,
CONTROL_HEIGHTS,
controlHeightForLayout,
controlSizingForLayout,
createControlGeometry,
HEADER_CONTROL_HEIGHT,
ICON_BUTTON_SIZES,
iconSizeFor,
resolveControlSizing,
switchGeometryForLayout,
getControlInteractionPhase,
TOOLBAR_CONTROL_HEIGHT,
TOOLBAR_CONTROL_SIZES,
TOUCH_TARGET,
} from "@/components/ui/control-geometry";
import type { Theme } from "@/styles/theme";
@@ -47,6 +56,52 @@ const theme = {
},
} as unknown as Theme;
describe("control sizing gate", () => {
it("is touch-sized in the compact layout or on a touch screen, and pointer-sized otherwise", () => {
expect(resolveControlSizing({ compactLayout: true, touchScreen: true })).toBe("touch");
expect(resolveControlSizing({ compactLayout: true, touchScreen: false })).toBe("touch");
expect(resolveControlSizing({ compactLayout: false, touchScreen: true })).toBe("touch");
expect(resolveControlSizing({ compactLayout: false, touchScreen: false })).toBe("pointer");
});
it("gives a touch screen its touch sizes at every width", () => {
const sizes = { touch: 44, pointer: 32 };
// An iPad: touch-sized in the docked desktop layout too.
expect(bySizing(sizes, true)).toEqual({ xs: 44, md: 44 });
// A mouse-driven window: touch-sized only once it narrows into the compact layout.
expect(bySizing(sizes, false)).toEqual({ xs: 44, md: 32 });
});
it("keeps a device without a touch screen on pointer sizes from md up", () => {
// The unit runtime has no touch screen, which is the desktop that must not change.
expect(controlSizingForLayout(false)).toBe("pointer");
expect(controlSizingForLayout(true)).toBe("touch");
expect(CONTROL_HEIGHTS.md).toEqual({ xs: 44, md: 32 });
expect(CONTROL_HEIGHTS.sm).toEqual({ xs: 32, md: 28 });
expect(HEADER_CONTROL_HEIGHT).toEqual({ xs: 32, md: 26 });
});
it("follows the HIG on touch: a 44pt target, no control under 28pt, larger glyphs", () => {
expect(TOUCH_TARGET).toBe(44);
expect(controlHeightForLayout("md", true)).toBe(TOUCH_TARGET);
expect(ICON_BUTTON_SIZES.large.touch).toBe(TOUCH_TARGET);
expect(ICON_BUTTON_SIZES.small.touch).toBe(TOUCH_TARGET);
// Composer toolbar controls: a full target on touch, unchanged 28 on pointer.
expect(TOOLBAR_CONTROL_SIZES).toEqual({ touch: TOUCH_TARGET, pointer: 28 });
expect(TOOLBAR_CONTROL_HEIGHT).toEqual({ xs: TOUCH_TARGET, md: 28 });
for (const size of ["sm", "md"] as const) {
expect(controlHeightForLayout(size, true)).toBeGreaterThan(
controlHeightForLayout(size, false),
);
expect(controlHeightForLayout(size, false)).toBeGreaterThanOrEqual(28);
}
for (const size of ["xs", "sm", "md", "lg"] as const) {
expect(iconSizeFor(size).touch).toBeGreaterThan(iconSizeFor(size).pointer);
}
});
});
describe("control geometry", () => {
it("keeps resting control borders transparent while preserving border geometry", () => {
const geometry = createControlGeometry(theme);
@@ -98,18 +153,17 @@ describe("control geometry", () => {
const geometry = createControlGeometry(theme);
const borderWidth = theme.borderWidth[1];
expect(geometry.fieldControlSm.minHeight).toBe(28);
expect(
geometry.fieldTextSm.lineHeight +
geometry.fieldControlSm.paddingVertical * 2 +
borderWidth * 2,
).toBe(geometry.fieldControlSm.minHeight);
expect(geometry.fieldControlSm.minHeight).toEqual({ xs: 32, md: 28 });
// The default keeps a 44 touch target in the compact layout and is 32 from the md
// breakpoint up.
expect(geometry.fieldControlMd.minHeight).toEqual({ xs: 44, md: 32 });
expect(geometry.fieldControlMd.paddingVertical).toEqual({ xs: 11, md: 5 });
for (const layout of ["xs", "md"] as const) {
expect(
geometry.fieldTextSm.lineHeight +
geometry.fieldControlSm.paddingVertical[layout] * 2 +
borderWidth * 2,
).toBe(geometry.fieldControlSm.minHeight[layout]);
expect(
geometry.fieldTextMd.lineHeight +
geometry.fieldControlMd.paddingVertical[layout] * 2 +
@@ -125,24 +179,25 @@ describe("control geometry", () => {
expect(geometry.segmentedContainerMd.padding).toBe(0);
expect(geometry.segmentedSegmentSm.borderRadius).toBe(geometry.buttonSm.borderRadius);
expect(geometry.segmentedSegmentMd.borderRadius).toBe(geometry.buttonMd.borderRadius);
expect(geometry.segmentedContainerSm.minHeight).toBe(geometry.buttonSm.minHeight);
expect(geometry.segmentedContainerSm.minHeight).toEqual(geometry.buttonSm.minHeight);
expect(geometry.segmentedContainerMd.minHeight).toEqual(geometry.buttonMd.minHeight);
expect(geometry.segmentedSegmentSm.minHeight).toBe(24);
expect(geometry.segmentedSegmentSm.minHeight).toEqual({ xs: 28, md: 24 });
expect(geometry.segmentedSegmentMd.minHeight).toEqual({ xs: 40, md: 28 });
});
it("keeps one size contract across buttons, fields, and segmented controls", () => {
const geometry = createControlGeometry(theme);
expect(geometry.buttonSm.minHeight).toBe(28);
expect(geometry.buttonSm.minHeight).toEqual({ xs: 32, md: 28 });
expect(geometry.buttonMd.minHeight).toEqual({ xs: 44, md: 32 });
expect(geometry.buttonSm.minHeight).toBe(CONTROL_HEIGHTS.sm);
expect(geometry.buttonSm.minHeight).toEqual(CONTROL_HEIGHTS.sm);
expect(geometry.buttonMd.minHeight).toEqual(CONTROL_HEIGHTS.md);
expect(geometry.fieldControlSm.minHeight).toBe(CONTROL_HEIGHTS.sm);
expect(geometry.fieldControlSm.minHeight).toEqual(CONTROL_HEIGHTS.sm);
expect(geometry.fieldControlMd.minHeight).toEqual(CONTROL_HEIGHTS.md);
expect(controlHeightForLayout("md", true)).toBe(44);
expect(controlHeightForLayout("md", false)).toBe(32);
expect(controlHeightForLayout("sm", true)).toBe(28);
expect(controlHeightForLayout("sm", true)).toBe(32);
expect(controlHeightForLayout("sm", false)).toBe(28);
// Same size name means the same label size on every control kind.
expect(geometry.segmentedLabelSm.fontSize).toBe(12);
@@ -177,13 +232,15 @@ describe("control geometry", () => {
thumbTravel: 18,
reservedHeight: 44,
});
// Tight chrome keeps the pointer-sized switch on every layout.
for (const isCompact of [true, false]) {
expect(switchGeometryForLayout("sm", isCompact)).toMatchObject({
trackWidth: 34,
reservedHeight: 28,
});
}
// Tight chrome keeps the pointer-sized track on every layout and reserves its row's height.
expect(switchGeometryForLayout("sm", true)).toMatchObject({
trackWidth: 34,
reservedHeight: 32,
});
expect(switchGeometryForLayout("sm", false)).toMatchObject({
trackWidth: 34,
reservedHeight: 28,
});
});
it("gives alert title and description one font size and a tight gap per size", () => {
@@ -1,5 +1,14 @@
import type { StyleProp, ViewStyle } from "react-native";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import {
bySizing,
controlSizingForLayout,
mapLayout,
TOUCH_TARGET,
type ControlSizing,
type LayoutValue,
type SizingValue,
} from "./control-sizing";
/**
* Controls come in two sizes. `md` is the default and the right size almost everywhere;
@@ -26,46 +35,78 @@ export interface ControlInteractionStyleMap {
controlDisabled?: StyleProp<ViewStyle>;
}
const SMALL_CONTROL_HEIGHT = 28;
// The default control keeps a full touch target in the compact layout and tightens where a
// pointer drives it.
const DEFAULT_CONTROL_HEIGHT_COMPACT_LAYOUT = 44;
const DEFAULT_CONTROL_HEIGHT_WIDE_LAYOUT = 32;
export const HEADER_CONTROL_HEIGHT = 26;
export {
bySizing,
controlSizingForLayout,
mapLayout,
resolveControlSizing,
TOUCH_TARGET,
type ControlSizing,
type ControlSizingFacts,
type LayoutValue,
type SizingValue,
} from "./control-sizing";
// Touch `md` is the iOS HIG's 44pt default control; touch `sm` stays above its 28pt minimum.
const CONTROL_SIZES = {
sm: { touch: 32, pointer: 28 },
md: { touch: TOUCH_TARGET, pointer: 32 },
} satisfies Record<ControlSize, SizingValue>;
/** Pointer-sized header controls run tighter than `sm` so they fit the 36pt header. */
const POINTER_HEADER_CONTROL_HEIGHT = 26;
const SEGMENTED_INSET = 2;
const CONTROL_FOCUS_RING_WIDTH = 2;
const CONTROL_FOCUS_RING_OFFSET = 1;
const FIELD_TEXT_LINE_HEIGHT_RATIO = 1.4;
/** A Unistyles breakpoint value: one number in the compact layout, another from `md` up. */
// A mapped type, not an interface: Unistyles checks breakpoint objects against an index
// signature, which interfaces never satisfy.
export type LayoutValue = Record<"xs" | "md", number>;
function byLayout(compact: number, wide: number): LayoutValue {
return { xs: compact, md: wide };
}
function mapLayout(value: LayoutValue, map: (height: number) => number): LayoutValue {
return byLayout(map(value.xs), map(value.md));
}
/**
* The height of every button, field, and segmented control of a size. Exported so a row that
* hosts one of those controls can size itself from the same numbers instead of guessing a
* height the control then outgrows. `md` depends on the layout, so it only works inside a
* Unistyles stylesheet.
* height the control then outgrows. Breakpoint values, so they only work inside a Unistyles
* stylesheet.
*/
export const CONTROL_HEIGHTS = {
sm: SMALL_CONTROL_HEIGHT,
md: byLayout(DEFAULT_CONTROL_HEIGHT_COMPACT_LAYOUT, DEFAULT_CONTROL_HEIGHT_WIDE_LAYOUT),
} satisfies Record<ControlSize, number | LayoutValue>;
sm: bySizing(CONTROL_SIZES.sm),
md: bySizing(CONTROL_SIZES.md),
} satisfies Record<ControlSize, LayoutValue>;
/** A framed control in a header row, such as a split button. Touch-sized it is an `sm` control. */
export const HEADER_CONTROL_HEIGHT = bySizing({
touch: CONTROL_SIZES.sm.touch,
pointer: POINTER_HEADER_CONTROL_HEIGHT,
});
/**
* Square icon-only buttons. Touch-sized, every icon button is one touch target; pointer-sized,
* header buttons are larger than toolbar buttons.
*/
export const ICON_BUTTON_SIZES = {
large: { touch: TOUCH_TARGET, pointer: POINTER_HEADER_CONTROL_HEIGHT },
small: { touch: TOUCH_TARGET, pointer: 20 },
} satisfies Record<"large" | "small", SizingValue>;
/**
* A control in a dense toolbar row, such as the composer's: an icon-only square or a labelled
* pill. Touch-sized it is one touch target.
*/
export const TOOLBAR_CONTROL_SIZES = { touch: TOUCH_TARGET, pointer: 28 } satisfies SizingValue;
export const TOOLBAR_CONTROL_HEIGHT = bySizing(TOOLBAR_CONTROL_SIZES);
/**
* Glyph sizes. Pointer glyphs sit beside 13-14pt text; touch glyphs sit beside iOS's 17pt body
* text, so each step is larger.
*/
export type IconSize = keyof typeof ICON_SIZE;
export const TOUCH_ICON_SIZE: Record<IconSize, number> = { xs: 14, sm: 18, md: 20, lg: 24 };
export function iconSizeFor(size: IconSize): SizingValue {
return { touch: TOUCH_ICON_SIZE[size], pointer: ICON_SIZE[size] };
}
/** The height of a control of `size`, for code that has to compute with it outside a stylesheet. */
export function controlHeightForLayout(size: ControlSize, isCompact: boolean): number {
const height = CONTROL_HEIGHTS[size];
if (typeof height === "number") return height;
return isCompact ? height.xs : height.md;
return CONTROL_SIZES[size][controlSizingForLayout(isCompact)];
}
export const controlIconSize: Record<ControlSize, number> = {
@@ -96,7 +137,8 @@ const SWITCH_TOUCH = switchSize(44, 26, 22);
* animation, so the size is resolved to plain numbers here instead of a stylesheet breakpoint.
*/
export function switchGeometryForLayout(size: ControlSize, isCompact: boolean): SwitchGeometry {
const track = size === "md" && isCompact ? SWITCH_TOUCH : SWITCH_POINTER;
const touchSized = controlSizingForLayout(isCompact) === "touch";
const track = size === "md" && touchSized ? SWITCH_TOUCH : SWITCH_POINTER;
return { ...track, reservedHeight: controlHeightForLayout(size, isCompact) };
}
@@ -225,10 +267,8 @@ export function createControlGeometry(theme: Theme) {
const fieldControlSm = {
minHeight: CONTROL_HEIGHTS.sm,
paddingHorizontal: theme.spacing[2],
paddingVertical: fieldVerticalPadding(
CONTROL_HEIGHTS.sm,
fieldTextSmLineHeight,
controlBorderWidth,
paddingVertical: mapLayout(CONTROL_HEIGHTS.sm, (height) =>
fieldVerticalPadding(height, fieldTextSmLineHeight, controlBorderWidth),
),
borderRadius: theme.borderRadius.md,
};
@@ -258,7 +298,7 @@ export function createControlGeometry(theme: Theme) {
},
buttonMd: {
minHeight: CONTROL_HEIGHTS.md,
paddingHorizontal: byLayout(theme.spacing[6], theme.spacing[4]),
paddingHorizontal: bySizing({ touch: theme.spacing[6], pointer: theme.spacing[4] }),
borderRadius: theme.borderRadius.full,
},
// A button with only an icon is a circle of its size's height.
@@ -314,7 +354,7 @@ export function createControlGeometry(theme: Theme) {
padding: 0,
},
segmentedSegmentSm: {
minHeight: CONTROL_HEIGHTS.sm - SEGMENTED_INSET * 2,
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height - SEGMENTED_INSET * 2),
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius.full,
},
@@ -0,0 +1,68 @@
import { hasTouchScreen } from "@/hooks/use-fine-pointer";
// The sizing gate, apart from the control sizes so that low-level modules such as
// `constants/layout` can size by it without loading the theme. Import it through
// `@/components/ui/control-geometry`, which re-exports it.
/**
* Every size comes in a touch value and a pointer value. Touch values follow Apple's Human
* Interface Guidelines for iOS and iPadOS: a 44pt default control and hit region, nothing
* smaller than its 28pt minimum. Pointer values sit one step down the same button ladder.
*/
export type ControlSizing = "touch" | "pointer";
export interface ControlSizingFacts {
/** The layout is below the `md` breakpoint. */
compactLayout: boolean;
/** The device has a touch screen; see `hasTouchScreen`. */
touchScreen: boolean;
}
/**
* The one sizing gate: touch-sized in the compact layout or on any device with a touch screen,
* pointer-sized otherwise. A touch screen keeps touch sizing when a mouse or keyboard is attached.
*/
export function resolveControlSizing({
compactLayout,
touchScreen,
}: ControlSizingFacts): ControlSizing {
if (compactLayout || touchScreen) return "touch";
return "pointer";
}
// Read once, so attaching a mouse or keyboard later never flips the sizing.
const DEVICE_HAS_TOUCH_SCREEN = hasTouchScreen();
/** The sizing on this device for a layout, for code that sizes outside a stylesheet. */
export function controlSizingForLayout(compactLayout: boolean): ControlSizing {
return resolveControlSizing({ compactLayout, touchScreen: DEVICE_HAS_TOUCH_SCREEN });
}
/** A Unistyles breakpoint value: one number in the compact layout, another from `md` up. */
// A mapped type, not an interface: Unistyles checks breakpoint objects against an index
// signature, which interfaces never satisfy.
export type LayoutValue = Record<"xs" | "md", number>;
export type SizingValue = Record<ControlSizing, number>;
/**
* A size as a Unistyles breakpoint value. The compact layout always takes the touch value; from
* `md` up the device decides.
*/
export function bySizing(
sizes: SizingValue,
touchScreen: boolean = DEVICE_HAS_TOUCH_SCREEN,
): LayoutValue {
return {
xs: sizes[resolveControlSizing({ compactLayout: true, touchScreen })],
md: sizes[resolveControlSizing({ compactLayout: false, touchScreen })],
};
}
/** Derives a breakpoint value from another, such as a row as tall as its control plus padding. */
export function mapLayout(value: LayoutValue, map: (height: number) => number): LayoutValue {
return { xs: map(value.xs), md: map(value.md) };
}
/** The smallest touch target, and the size of every touch-sized icon button, row, and bar. */
export const TOUCH_TARGET = 44;
@@ -1,17 +1,24 @@
import { createContext, useCallback, useContext } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import {
bySizing,
controlSizingForLayout,
ICON_BUTTON_SIZES,
TOUCH_ICON_SIZE,
type SizingValue,
} from "@/components/ui/control-geometry";
import { ICON_SIZE } from "@/styles/theme";
export { extraMutedIconColorMapping, mutedIconColorMapping } from "@/components/ui/icon-color";
export type IconButtonChromeSize = "large" | "small";
const SMALL_ICON_BUTTON_SIZE = 20;
/** Width and height of a large icon button on compact layouts. */
export const COMPACT_LARGE_ICON_BUTTON_SIZE = 32;
const COMPACT_SMALL_ICON_BUTTON_SIZE = 32;
// Touch-sized, every icon button is one target with one glyph size.
const GLYPH_SIZES = {
large: { touch: TOUCH_ICON_SIZE.md, pointer: ICON_SIZE.md },
small: { touch: TOUCH_ICON_SIZE.md, pointer: ICON_SIZE.sm },
} satisfies Record<IconButtonChromeSize, SizingValue>;
export interface IconButtonChromeState {
hovered?: boolean;
@@ -22,7 +29,7 @@ export interface IconButtonChromeState {
function resolveIconButtonFrame(size: IconButtonChromeSize, compact: boolean) {
if (size === "large") return styles.large;
return compact ? styles.smallCompact : styles.small;
return controlSizingForLayout(compact) === "touch" ? styles.smallTouch : styles.small;
}
interface IconButtonChromeOptions {
@@ -92,24 +99,17 @@ export function iconButtonChromeFrameStyle(
}
export function iconButtonChromeGlyphSize(size: IconButtonChromeSize, compact = false): number {
if (size === "large") return ICON_SIZE.md;
return compact ? 18 : 14;
return GLYPH_SIZES[size][controlSizingForLayout(compact)];
}
export function smallIconButtonChromeFrameSize(compact = false): number {
return compact ? COMPACT_SMALL_ICON_BUTTON_SIZE : SMALL_ICON_BUTTON_SIZE;
return ICON_BUTTON_SIZES.small[controlSizingForLayout(compact)];
}
const styles = StyleSheet.create((theme) => ({
large: {
width: {
xs: COMPACT_LARGE_ICON_BUTTON_SIZE,
md: HEADER_CONTROL_HEIGHT,
},
height: {
xs: COMPACT_LARGE_ICON_BUTTON_SIZE,
md: HEADER_CONTROL_HEIGHT,
},
width: bySizing(ICON_BUTTON_SIZES.large),
height: bySizing(ICON_BUTTON_SIZES.large),
padding: 0,
borderRadius: theme.borderRadius.md,
alignItems: "center",
@@ -119,8 +119,8 @@ const styles = StyleSheet.create((theme) => ({
outlineColor: "transparent",
},
small: {
width: SMALL_ICON_BUTTON_SIZE,
height: SMALL_ICON_BUTTON_SIZE,
width: ICON_BUTTON_SIZES.small.pointer,
height: ICON_BUTTON_SIZES.small.pointer,
padding: 0,
borderRadius: theme.borderRadius.md,
alignItems: "center",
@@ -129,9 +129,9 @@ const styles = StyleSheet.create((theme) => ({
outlineWidth: 0,
outlineColor: "transparent",
},
smallCompact: {
width: COMPACT_SMALL_ICON_BUTTON_SIZE,
height: COMPACT_SMALL_ICON_BUTTON_SIZE,
smallTouch: {
width: ICON_BUTTON_SIZES.small.touch,
height: ICON_BUTTON_SIZES.small.touch,
padding: 0,
borderRadius: theme.borderRadius.md,
alignItems: "center",
@@ -1,2 +1,5 @@
/** Shared geometry for menu rows and controls that align with them. */
export const MENU_ITEM_HEIGHT = { xs: 40, md: 28 } as const;
import { density } from "@/styles/density";
/** A menu row is a tight row: touch-sized wherever controls are (see `resolveControlSizing`). */
export const MENU_ITEM_HEIGHT = density.tightRowHeight;
@@ -2,6 +2,7 @@ import { forwardRef, useCallback, type ComponentProps } from "react";
import { Text, View, type PressableStateCallbackType } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
import { TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { useComposerControlLayout } from "@/composer/agent-controls/layout-context";
import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
import type { AgentControlIcon } from "@/agent-controls/icons";
@@ -96,7 +97,7 @@ export const AgentControlTrigger = forwardRef<View, AgentControlTriggerProps>(
const styles = StyleSheet.create((theme) => ({
toolbarControl: {
height: 28,
height: TOOLBAR_CONTROL_HEIGHT,
minWidth: 0,
flexShrink: 1,
flexDirection: "row",
@@ -107,7 +108,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: "transparent",
},
toolbarIconOnly: {
width: 28,
width: TOOLBAR_CONTROL_HEIGHT,
flexShrink: 0,
paddingHorizontal: 0,
justifyContent: "center",
@@ -4,7 +4,7 @@ import { StyleSheet, View } from "react-native";
export function ComposerToolbarGlyph({ children, size }: { children: ReactNode; size: number }) {
return (
<View
style={size >= 20 ? styles.native : styles.web}
style={size >= 20 ? styles.touch : styles.pointer}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
pointerEvents="none"
@@ -15,14 +15,14 @@ export function ComposerToolbarGlyph({ children, size }: { children: ReactNode;
}
const styles = StyleSheet.create({
web: {
pointer: {
width: 16,
height: 16,
flexShrink: 0,
alignItems: "center",
justifyContent: "center",
},
native: {
touch: {
width: 20,
height: 20,
flexShrink: 0,
@@ -61,6 +61,8 @@ import {
resolveAgentModelSelection,
} from "@/composer/agent-controls/utils";
import { useIsCompactFormFactor } from "@/constants/layout";
import { controlSizingForLayout, TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { DensityIcon } from "@/components/ui/density-icon";
import { readMeasuredWidth } from "@/hooks/use-container-width";
import { useToast } from "@/contexts/toast-context";
import { toErrorMessage } from "@/utils/error-messages";
@@ -70,11 +72,10 @@ import {
type AgentControlCommandCenterSource,
} from "@/command-center/agent-control-registration";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { isNative } from "@/constants/platform";
import {
composerToolbarGeometry,
resolveComposerControlDensity,
resolveComposerControlPresentation,
resolveComposerToolbarGlyphSize,
type ComposerControlDensity,
type ComposerControlPresentation,
} from "@/composer/agent-controls/layout";
@@ -460,6 +461,10 @@ function buildAgentProviderModels(
return map;
}
function densityFolds(density: ComposerControlDensity): boolean {
return resolveComposerControlPresentation(density).foldControls;
}
function buildOpenChangeHandler(
selector: AgentControlSelector,
setOpenSelector: (next: AgentControlSelector | null) => void,
@@ -503,14 +508,20 @@ function ControlledAgentControls({
modelSelectorServerId = null,
isCompactLayout,
}: ControlledAgentControlsProps) {
const { theme } = useUnistyles();
const { t } = useTranslation();
const isCompactFormFactor = useIsCompactFormFactor();
const isCompact = isCompactLayout ?? isCompactFormFactor;
// Control sizes follow the window layout, as the toolbar's stylesheet does. A narrow pane in a
// wide window (`isCompactLayout`) changes which labels show, never how large a control is.
const toolbarSizing = controlSizingForLayout(isCompactFormFactor);
const toolbarGeometry = useMemo(() => composerToolbarGeometry(toolbarSizing), [toolbarSizing]);
const { fontScale } = useWindowDimensions();
const [activeSheet, setActiveSheet] = useState<ActiveSheet>(null);
const [openSelector, setOpenSelector] = useState<AgentControlSelector | null>(null);
const initialDensity: ComposerControlDensity = isCompact ? "tight" : "full";
// A compact composer always folds its controls into the model sheet; the width budget only
// decides whether the model keeps its label.
const minimumDensity: ComposerControlDensity = isCompact ? "compact" : "full";
const initialDensity = minimumDensity;
const [density, setDensity] = useState<ComposerControlDensity>(initialDensity);
const densityRef = useRef<ComposerControlDensity>(initialDensity);
const availableWidthRef = useRef(0);
@@ -574,10 +585,10 @@ function ControlledAgentControls({
const presentation = useMemo(() => resolveComposerControlPresentation(density), [density]);
const layoutContextValue = useMemo(
() => ({
glyphSize: resolveComposerToolbarGlyphSize(isNative ? "native" : "web"),
glyphSize: toolbarGeometry.glyphSize,
presentation,
}),
[presentation],
[presentation, toolbarGeometry],
);
const updateDensityForWidth = useCallback(
@@ -586,12 +597,20 @@ function ControlledAgentControls({
availableWidth,
currentDensity: densityRef.current,
controls: controlPresence,
geometry: toolbarGeometry,
minimumDensity,
});
if (nextDensity === densityRef.current) return;
// Folding swaps the toolbar controls for the model sheet and back, so whatever menu or
// sheet was open belonged to controls that are gone.
if (densityFolds(nextDensity) !== densityFolds(densityRef.current)) {
setOpenSelector(null);
setActiveSheet(null);
}
densityRef.current = nextDensity;
setDensity(nextDensity);
},
[controlPresence],
[controlPresence, minimumDensity, toolbarGeometry],
);
const handleLayout = useCallback(
@@ -633,10 +652,9 @@ function ControlledAgentControls({
selected={args.selected}
active={args.active}
onPress={args.onPress}
iconColor={theme.colors.foreground}
/>
),
[theme.colors.foreground],
[],
);
const handleOpenChange = useCallback(
@@ -702,8 +720,8 @@ function ControlledAgentControls({
const handleCloseSheet = useCallback(() => {
setActiveSheet(null);
if (!isCompact) onDropdownClose?.();
}, [isCompact, onDropdownClose]);
if (!presentation.foldControls) onDropdownClose?.();
}, [onDropdownClose, presentation.foldControls]);
const handleSelectThinkingAndClose = useCallback(
(thinkingOptionId: string) => {
@@ -734,7 +752,7 @@ function ControlledAgentControls({
return (
<ComposerControlLayoutProvider value={layoutContextValue}>
<View style={styles.container} onLayout={handleLayout}>
{!isCompact ? (
{!presentation.foldControls ? (
<DesktopAgentControlsContent
provider={provider}
providerOptions={providerOptions}
@@ -821,6 +839,7 @@ function ControlledAgentControls({
renderThinkingOption={renderThinkingOption}
modeControl={modeControl}
glyphSize={layoutContextValue.glyphSize}
showLabels={presentation.showModelLabel}
modelSelectorServerId={modelSelectorServerId}
canSwitchProvider={Boolean(onSelectProviderAndModel)}
/>
@@ -1144,6 +1163,7 @@ interface SheetAgentControlsContentProps {
}) => ReactElement;
modeControl?: AgentModeControlValue | null;
glyphSize: number;
showLabels: boolean;
modelSelectorServerId: string | null;
canSwitchProvider: boolean;
}
@@ -1183,6 +1203,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
renderThinkingOption,
modeControl,
glyphSize,
showLabels,
modelSelectorServerId,
canSwitchProvider,
} = props;
@@ -1271,6 +1292,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
isRetryingProvider={isRetryingModelProvider}
serverId={modelSelectorServerId}
glyphSize={glyphSize}
showLabels={showLabels}
canSwitchProvider={canSwitchProvider}
>
{sheetControls}
@@ -1529,15 +1551,16 @@ function ThinkingComboboxOption({
selected,
active,
onPress,
iconColor,
}: {
option: ComboboxOption;
selected: boolean;
active: boolean;
onPress: () => void;
iconColor: string;
}) {
const leadingSlot = useMemo(() => <ThinkingIcon size={16} color={iconColor} />, [iconColor]);
const leadingSlot = useMemo(
() => <DensityIcon icon={ThinkingIcon} size="md" color="foreground" />,
[],
);
return (
<ComboboxItem
label={option.label}
@@ -1953,7 +1976,7 @@ const styles = StyleSheet.create((theme) => ({
overflow: "hidden",
},
modeBadge: {
height: 28,
height: TOOLBAR_CONTROL_HEIGHT,
flexDirection: "row",
alignItems: "center",
backgroundColor: "transparent",
@@ -1971,8 +1994,8 @@ const styles = StyleSheet.create((theme) => ({
flexShrink: 0,
},
modeIconBadge: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: 0,
@@ -1,5 +1,8 @@
import { createContext, useContext, type ReactNode } from "react";
import type { ComposerControlPresentation } from "@/composer/agent-controls/layout";
import {
resolveComposerControlPresentation,
type ComposerControlPresentation,
} from "@/composer/agent-controls/layout";
interface ComposerControlLayoutValue {
glyphSize: number;
@@ -8,12 +11,7 @@ interface ComposerControlLayoutValue {
const DEFAULT_LAYOUT: ComposerControlLayoutValue = {
glyphSize: 16,
presentation: {
showCarets: true,
showThinkingLabel: true,
showModeLabel: true,
aggregateFeatures: false,
},
presentation: resolveComposerControlPresentation("full"),
};
const ComposerControlLayoutContext = createContext(DEFAULT_LAYOUT);
@@ -1,30 +1,42 @@
import { describe, expect, it } from "vitest";
import {
COMPOSER_TOOLBAR_GEOMETRY,
composerToolbarGeometry,
resolveComposerControlDensity,
resolveComposerControlPresentation,
resolveComposerToolbarGlyphSize,
} from "./layout";
const POINTER = composerToolbarGeometry("pointer");
const TOUCH = composerToolbarGeometry("touch");
describe("composer control layout", () => {
it("removes labels in priority order as the toolbar narrows", () => {
it("removes labels, then folds controls, then drops the model label as the toolbar narrows", () => {
expect(resolveComposerControlPresentation("full")).toEqual({
showCarets: true,
showThinkingLabel: true,
showModeLabel: true,
aggregateFeatures: false,
foldControls: false,
showModelLabel: true,
});
expect(resolveComposerControlPresentation("condensed")).toEqual({
expect(resolveComposerControlPresentation("condensed")).toMatchObject({
showCarets: false,
showThinkingLabel: false,
showModeLabel: true,
aggregateFeatures: true,
foldControls: false,
});
expect(resolveComposerControlPresentation("tight")).toEqual({
showCarets: false,
showThinkingLabel: false,
expect(resolveComposerControlPresentation("tight")).toMatchObject({
showModeLabel: false,
aggregateFeatures: true,
foldControls: false,
showModelLabel: true,
});
expect(resolveComposerControlPresentation("compact")).toMatchObject({
foldControls: true,
showModelLabel: true,
});
expect(resolveComposerControlPresentation("iconOnly")).toMatchObject({
foldControls: true,
showModelLabel: false,
});
});
@@ -41,6 +53,7 @@ describe("composer control layout", () => {
resolveComposerControlDensity({
availableWidth: 420,
currentDensity: "full",
geometry: POINTER,
controls,
}),
).toBe("full");
@@ -48,6 +61,7 @@ describe("composer control layout", () => {
resolveComposerControlDensity({
availableWidth: 380,
currentDensity: "full",
geometry: POINTER,
controls,
}),
).toBe("condensed");
@@ -55,6 +69,7 @@ describe("composer control layout", () => {
resolveComposerControlDensity({
availableWidth: 290,
currentDensity: "condensed",
geometry: POINTER,
controls,
}),
).toBe("condensed");
@@ -62,6 +77,7 @@ describe("composer control layout", () => {
resolveComposerControlDensity({
availableWidth: 280,
currentDensity: "condensed",
geometry: POINTER,
controls,
}),
).toBe("tight");
@@ -69,6 +85,7 @@ describe("composer control layout", () => {
resolveComposerControlDensity({
availableWidth: 300,
currentDensity: "tight",
geometry: POINTER,
controls,
}),
).toBe("tight");
@@ -76,6 +93,7 @@ describe("composer control layout", () => {
resolveComposerControlDensity({
availableWidth: 312,
currentDensity: "tight",
geometry: POINTER,
controls,
}),
).toBe("condensed");
@@ -85,6 +103,7 @@ describe("composer control layout", () => {
const base = {
availableWidth: 430,
currentDensity: "condensed" as const,
geometry: POINTER,
};
expect(
@@ -129,6 +148,7 @@ describe("composer control layout", () => {
const base = {
availableWidth: 430,
currentDensity: "full" as const,
geometry: POINTER,
controls: {
hasModel: true,
hasThinking: true,
@@ -154,15 +174,97 @@ describe("composer control layout", () => {
).toBe("condensed");
});
it("gives every toolbar control one shell and one platform glyph envelope", () => {
expect(COMPOSER_TOOLBAR_GEOMETRY).toEqual({
it("gives every toolbar control one shell and one glyph per control sizing", () => {
expect(POINTER).toEqual({
controlSize: 28,
glyphSize: 16,
controlGap: 4,
iconLabelGap: 4,
labelPadding: 8,
caretSize: 14,
});
expect(resolveComposerToolbarGlyphSize("web")).toBe(16);
expect(resolveComposerToolbarGlyphSize("native")).toBe(20);
expect(TOUCH).toMatchObject({ controlSize: 44, glyphSize: 20 });
});
it("budgets touch-sized controls, so a touch toolbar condenses at a width a pointer one fits", () => {
const input = {
availableWidth: 420,
currentDensity: "full" as const,
controls: {
hasModel: true,
hasThinking: true,
hasMode: true,
features: [{ type: "toggle" as const }],
fontScale: 1,
},
};
expect(resolveComposerControlDensity({ ...input, geometry: POINTER })).toBe("full");
expect(resolveComposerControlDensity({ ...input, geometry: TOUCH })).toBe("condensed");
});
describe("touch toolbar on an iPad in portrait, sidebar docked", () => {
// Codex: model, thinking, mode and two toggle features. The measured toolbar is 272 wide
// with an empty draft and 224 once an attachment brings in the send button.
const controls = {
hasModel: true,
hasThinking: true,
hasMode: true,
features: [{ type: "toggle" as const }, { type: "toggle" as const }],
fontScale: 1,
};
it("keeps the model family label with icon-only controls on an empty draft", () => {
expect(
resolveComposerControlDensity({
availableWidth: 272,
currentDensity: "full",
geometry: TOUCH,
controls,
}),
).toBe("tight");
});
it("folds thinking, mode and features into the model control once an attachment narrows it", () => {
expect(
resolveComposerControlDensity({
availableWidth: 224,
currentDensity: "tight",
geometry: TOUCH,
controls,
}),
).toBe("compact");
});
it("drops the model label only after the controls are folded", () => {
expect(
resolveComposerControlDensity({
availableWidth: 120,
currentDensity: "compact",
geometry: TOUCH,
controls,
}),
).toBe("iconOnly");
});
});
it("starts a compact composer at the folded toolbar however wide it is", () => {
const input = {
currentDensity: "compact" as const,
geometry: TOUCH,
minimumDensity: "compact" as const,
controls: {
hasModel: true,
hasThinking: true,
hasMode: true,
features: [],
fontScale: 1,
},
};
expect(resolveComposerControlDensity({ ...input, availableWidth: 600 })).toBe("compact");
// The iPhone toolbar with an attachment: "GPT-6…" beside "Medium" still fits.
expect(resolveComposerControlDensity({ ...input, availableWidth: 159 })).toBe("compact");
expect(resolveComposerControlDensity({ ...input, availableWidth: 120 })).toBe("iconOnly");
});
});
@@ -1,4 +1,23 @@
export type ComposerControlDensity = "full" | "condensed" | "tight";
import {
iconSizeFor,
TOOLBAR_CONTROL_SIZES,
type ControlSizing,
} from "@/components/ui/control-geometry";
/**
* How much of the toolbar shows, widest first. Each step drops something before the next:
* carets and labels, then the mode label, then the thinking, mode and feature controls fold into
* the model control's sheet (`compact`, the phone toolbar), then the model's own label.
*/
export type ComposerControlDensity = "full" | "condensed" | "tight" | "compact" | "iconOnly";
const DENSITY_LADDER: readonly ComposerControlDensity[] = [
"full",
"condensed",
"tight",
"compact",
"iconOnly",
];
export interface ComposerControlPresence {
hasModel: boolean;
@@ -15,27 +34,46 @@ export interface ComposerControlPresentation {
showThinkingLabel: boolean;
showModeLabel: boolean;
aggregateFeatures: boolean;
/** Thinking, mode and features live in the model control's sheet. */
foldControls: boolean;
showModelLabel: boolean;
}
export const COMPOSER_TOOLBAR_GEOMETRY = {
controlSize: 28,
controlGap: 4,
iconLabelGap: 4,
labelPadding: 8,
caretSize: 14,
} as const;
export interface ComposerToolbarGeometry {
controlSize: number;
glyphSize: number;
controlGap: number;
iconLabelGap: number;
labelPadding: number;
caretSize: number;
}
/** The toolbar's measurements under a control sizing; see `resolveControlSizing`. */
export function composerToolbarGeometry(sizing: ControlSizing): ComposerToolbarGeometry {
return {
controlSize: TOOLBAR_CONTROL_SIZES[sizing],
glyphSize: iconSizeFor("md")[sizing],
controlGap: 4,
iconLabelGap: 4,
labelPadding: 8,
caretSize: 14,
};
}
const DENSITY_HYSTERESIS = 12;
/** The model label's narrowest useful width: enough for the model family, such as "GPT-6…". */
const MODEL_FAMILY_LABEL_WIDTH = 56;
/** A thinking label beside the folded model label, such as "Medium". */
const THINKING_LABEL_WIDTH = 48;
function normalizedFontScale(fontScale: number): number {
return Number.isFinite(fontScale) ? Math.max(1, fontScale) : 1;
}
function sumControlWidths(widths: number[]): number {
function sumControlWidths(widths: number[], geometry: ComposerToolbarGeometry): number {
if (widths.length === 0) return 0;
return (
widths.reduce((total, width) => total + width, 0) +
(widths.length - 1) * COMPOSER_TOOLBAR_GEOMETRY.controlGap
widths.reduce((total, width) => total + width, 0) + (widths.length - 1) * geometry.controlGap
);
}
@@ -43,92 +81,173 @@ function estimateLabelWidth(label: string, fontScale: number): number {
return Array.from(label).length * 7 * fontScale;
}
/** A labelled control's fixed chrome: its padding, its glyph, and the gap to its label. */
function labelledChrome(geometry: ComposerToolbarGeometry): number {
return geometry.labelPadding * 2 + geometry.glyphSize + geometry.iconLabelGap;
}
function resolveFeatureControlWidth(
feature: ComposerFeatureControlPresence,
fontScale: number,
geometry: ComposerToolbarGeometry,
): number {
if (feature.type === "toggle") return COMPOSER_TOOLBAR_GEOMETRY.controlSize;
if (feature.type === "toggle") return geometry.controlSize;
return (
COMPOSER_TOOLBAR_GEOMETRY.controlSize +
COMPOSER_TOOLBAR_GEOMETRY.iconLabelGap +
COMPOSER_TOOLBAR_GEOMETRY.labelPadding * 2 +
geometry.controlSize +
geometry.iconLabelGap +
geometry.labelPadding * 2 +
estimateLabelWidth(feature.label, fontScale)
);
}
function resolveCondensedFloor(controls: ComposerControlPresence): number {
function resolveCondensedFloor(
controls: ComposerControlPresence,
geometry: ComposerToolbarGeometry,
): number {
const fontScale = normalizedFontScale(controls.fontScale);
const chrome = labelledChrome(geometry);
const widths: number[] = [];
if (controls.hasModel) widths.push(36 + 60 * fontScale);
if (controls.hasThinking) widths.push(COMPOSER_TOOLBAR_GEOMETRY.controlSize);
if (controls.hasMode) widths.push(36 + 96 * fontScale);
if (controls.features.length > 0) widths.push(COMPOSER_TOOLBAR_GEOMETRY.controlSize);
return sumControlWidths(widths);
if (controls.hasModel) widths.push(chrome + 60 * fontScale);
if (controls.hasThinking) widths.push(geometry.controlSize);
if (controls.hasMode) widths.push(chrome + 96 * fontScale);
if (controls.features.length > 0) widths.push(geometry.controlSize);
return sumControlWidths(widths, geometry);
}
function resolveFullFloor(controls: ComposerControlPresence): number {
function resolveFullFloor(
controls: ComposerControlPresence,
geometry: ComposerToolbarGeometry,
): number {
const fontScale = normalizedFontScale(controls.fontScale);
const chrome = labelledChrome(geometry);
const caret = geometry.caretSize;
const widths: number[] = [];
if (controls.hasModel) widths.push(50 + 70 * fontScale);
if (controls.hasThinking) widths.push(54 + 48 * fontScale);
if (controls.hasMode) widths.push(54 + 96 * fontScale);
if (controls.hasModel) widths.push(chrome + caret + 70 * fontScale);
if (controls.hasThinking) widths.push(chrome + geometry.iconLabelGap + caret + 48 * fontScale);
if (controls.hasMode) widths.push(chrome + geometry.iconLabelGap + caret + 96 * fontScale);
for (const feature of controls.features) {
widths.push(resolveFeatureControlWidth(feature, fontScale));
widths.push(resolveFeatureControlWidth(feature, fontScale, geometry));
}
return sumControlWidths(widths);
return sumControlWidths(widths, geometry);
}
/** Model at its family label, with thinking, mode and features as icon-only squares. */
function resolveTightFloor(
controls: ComposerControlPresence,
geometry: ComposerToolbarGeometry,
): number {
const fontScale = normalizedFontScale(controls.fontScale);
const widths: number[] = [];
if (controls.hasModel) {
widths.push(labelledChrome(geometry) + MODEL_FAMILY_LABEL_WIDTH * fontScale);
}
if (controls.hasThinking) widths.push(geometry.controlSize);
if (controls.hasMode) widths.push(geometry.controlSize);
if (controls.features.length > 0) widths.push(geometry.controlSize);
return sumControlWidths(widths, geometry);
}
/** One model control carrying the model family label and the thinking label. */
function resolveCompactFloor(
controls: ComposerControlPresence,
geometry: ComposerToolbarGeometry,
): number {
const fontScale = normalizedFontScale(controls.fontScale);
const thinkingLabel = controls.hasThinking
? geometry.iconLabelGap + THINKING_LABEL_WIDTH * fontScale
: 0;
return labelledChrome(geometry) + MODEL_FAMILY_LABEL_WIDTH * fontScale + thinkingLabel;
}
function resolveDensityFloor(
density: ComposerControlDensity,
controls: ComposerControlPresence,
geometry: ComposerToolbarGeometry,
): number {
switch (density) {
case "full":
return resolveFullFloor(controls, geometry);
case "condensed":
return resolveCondensedFloor(controls, geometry);
case "tight":
return resolveTightFloor(controls, geometry);
case "compact":
return resolveCompactFloor(controls, geometry);
case "iconOnly":
return 0;
}
}
/**
* The widest density whose floor fits `availableWidth`. Widening past the current density needs
* the floor plus the hysteresis and keeping it tolerates the floor minus it, so a width near a
* floor does not flip back and forth. `minimumDensity` is the widest density allowed.
*/
export function resolveComposerControlDensity(input: {
availableWidth: number;
currentDensity: ComposerControlDensity;
controls: ComposerControlPresence;
geometry: ComposerToolbarGeometry;
minimumDensity?: ComposerControlDensity;
}): ComposerControlDensity {
const fullFloor = resolveFullFloor(input.controls);
const condensedFloor = resolveCondensedFloor(input.controls);
if (input.currentDensity === "full") {
if (input.availableWidth >= fullFloor - DENSITY_HYSTERESIS) return "full";
return input.availableWidth >= condensedFloor ? "condensed" : "tight";
const current = DENSITY_LADDER.indexOf(input.currentDensity);
const first = DENSITY_LADDER.indexOf(input.minimumDensity ?? "full");
for (let step = first; step < DENSITY_LADDER.length; step += 1) {
const density = DENSITY_LADDER[step];
const floor = resolveDensityFloor(density, input.controls, input.geometry);
let required = floor;
if (step < current) required = floor + DENSITY_HYSTERESIS;
if (step === current) required = floor - DENSITY_HYSTERESIS;
if (input.availableWidth >= required) return density;
}
if (input.currentDensity === "condensed") {
if (input.availableWidth >= fullFloor + DENSITY_HYSTERESIS) return "full";
if (input.availableWidth < condensedFloor - DENSITY_HYSTERESIS) return "tight";
return "condensed";
}
if (input.availableWidth >= fullFloor + DENSITY_HYSTERESIS) return "full";
if (input.availableWidth >= condensedFloor + DENSITY_HYSTERESIS) return "condensed";
return "tight";
return "iconOnly";
}
export function resolveComposerControlPresentation(
density: ComposerControlDensity,
): ComposerControlPresentation {
if (density === "full") {
return {
showCarets: true,
showThinkingLabel: true,
showModeLabel: true,
aggregateFeatures: false,
};
}
if (density === "condensed") {
return {
showCarets: false,
showThinkingLabel: false,
showModeLabel: true,
aggregateFeatures: true,
};
}
return {
const PRESENTATIONS: Record<ComposerControlDensity, ComposerControlPresentation> = {
full: {
showCarets: true,
showThinkingLabel: true,
showModeLabel: true,
aggregateFeatures: false,
foldControls: false,
showModelLabel: true,
},
condensed: {
showCarets: false,
showThinkingLabel: false,
showModeLabel: true,
aggregateFeatures: true,
foldControls: false,
showModelLabel: true,
},
tight: {
showCarets: false,
showThinkingLabel: false,
showModeLabel: false,
aggregateFeatures: true,
};
}
foldControls: false,
showModelLabel: true,
},
compact: {
showCarets: false,
showThinkingLabel: true,
showModeLabel: false,
aggregateFeatures: true,
foldControls: true,
showModelLabel: true,
},
iconOnly: {
showCarets: false,
showThinkingLabel: false,
showModeLabel: false,
aggregateFeatures: true,
foldControls: true,
showModelLabel: false,
},
};
export function resolveComposerToolbarGlyphSize(platform: "web" | "native"): number {
return platform === "native" ? 20 : 16;
export function resolveComposerControlPresentation(
density: ComposerControlDensity,
): ComposerControlPresentation {
return PRESENTATIONS[density];
}
@@ -27,6 +27,7 @@ import { showProviderNoticeToast } from "@/utils/provider-notice-toast";
import type { AgentMode } from "@getpaseo/protocol/agent-types";
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
import { getAgentModeIcon, getAgentModeOptionIcon } from "@/agent-controls/icons";
import { DensityIcon } from "@/components/ui/density-icon";
interface ModeComboboxOptionProps {
option: ComboboxOption;
selected: boolean;
@@ -34,7 +35,6 @@ interface ModeComboboxOptionProps {
onPress: () => void;
provider: string;
providerDefinitions: AgentProviderDefinition[];
iconColor: string;
}
function ModeComboboxOption({
@@ -44,12 +44,12 @@ function ModeComboboxOption({
onPress,
provider,
providerDefinitions,
iconColor,
}: ModeComboboxOptionProps) {
const IconComponent = getAgentModeOptionIcon(provider, option.id, providerDefinitions);
const leadingSlot = useMemo(
() => (IconComponent ? <IconComponent size={16} color={iconColor} /> : null),
[IconComponent, iconColor],
() =>
IconComponent ? <DensityIcon icon={IconComponent} size="md" color="foreground" /> : null,
[IconComponent],
);
return (
<ComboboxItem
@@ -171,10 +171,9 @@ export function AgentModeControl({
onPress={args.onPress}
provider={provider}
providerDefinitions={providerDefinitions}
iconColor={theme.colors.foreground}
/>
),
[provider, providerDefinitions, theme.colors.foreground],
[provider, providerDefinitions],
);
const sheetHeader = useMemo<SheetHeader>(
@@ -15,6 +15,7 @@ import { resolveModelSheetOpening } from "@/composer/agent-controls/model-sheet-
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
const SNAP_POINTS = ["80%", "90%"];
const MODEL_LIST_TOP_INSET = 4;
@@ -42,6 +43,8 @@ interface CompactModelSheetProps {
disabled?: boolean;
serverId?: string | null;
glyphSize: number;
/** False when the toolbar is too narrow for labels: the trigger shows the provider glyph only. */
showLabels: boolean;
canSwitchProvider: boolean;
children: ReactNode;
}
@@ -94,6 +97,7 @@ export function CompactModelSheet({
disabled = false,
serverId = null,
glyphSize,
showLabels,
canSwitchProvider,
children,
}: CompactModelSheetProps) {
@@ -229,14 +233,16 @@ export function CompactModelSheet({
open();
}, [close, isOpen, open]);
const iconOnly = !showLabels && hasSelectedProvider;
const triggerStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType) => [
styles.trigger,
iconOnly && styles.triggerIconOnly,
hovered && styles.triggerHovered,
(pressed || isOpen) && styles.triggerPressed,
disabled && styles.triggerDisabled,
],
[disabled, isOpen],
[disabled, iconOnly, isOpen],
);
const mobileRootContent = useMemo(
() => (
@@ -280,16 +286,18 @@ export function CompactModelSheet({
<ModelIcon size={glyphSize} color={styles.providerIcon.color} />
</ComposerToolbarGlyph>
) : null}
<View style={styles.triggerLabels}>
<Text style={styles.triggerText} numberOfLines={1}>
{shortModelLabel(rootBrowser.triggerLabel)}
</Text>
{thinkingLabel ? (
<Text style={styles.triggerThinking} numberOfLines={1}>
{thinkingLabel}
{!iconOnly ? (
<View style={styles.triggerLabels}>
<Text style={styles.triggerText} numberOfLines={1}>
{shortModelLabel(rootBrowser.triggerLabel)}
</Text>
) : null}
</View>
{thinkingLabel ? (
<Text style={styles.triggerThinking} numberOfLines={1}>
{thinkingLabel}
</Text>
) : null}
</View>
) : null}
</ComboboxTrigger>
<AdaptiveModalSheet
@@ -374,7 +382,7 @@ export function CompactModelSheet({
const styles = StyleSheet.create((theme) => ({
trigger: {
height: 28,
height: TOOLBAR_CONTROL_HEIGHT,
minWidth: 0,
flexShrink: 1,
flexDirection: "row",
@@ -384,6 +392,12 @@ const styles = StyleSheet.create((theme) => ({
borderRadius: theme.borderRadius["2xl"],
backgroundColor: "transparent",
},
triggerIconOnly: {
width: TOOLBAR_CONTROL_HEIGHT,
flexShrink: 0,
paddingHorizontal: 0,
justifyContent: "center",
},
triggerHovered: {
backgroundColor: theme.colors.surface2,
},
+14 -14
View File
@@ -31,6 +31,11 @@ import {
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import {
controlSizingForLayout,
iconSizeFor,
TOOLBAR_CONTROL_HEIGHT,
} from "@/components/ui/control-geometry";
import { usePanelStore } from "@/stores/panel-store";
import { useHasFinePointer } from "@/hooks/use-fine-pointer";
import { useShallow } from "zustand/shallow";
@@ -193,10 +198,6 @@ const EMPTY_ATTACHMENT_SCOPE_KEYS: readonly string[] = [];
function noop() {}
const noopCallback = () => {};
function resolveComposerButtonIconSize(): number {
return isWeb ? ICON_SIZE.md : ICON_SIZE.lg;
}
function resolveIsComposerLocked(
submitBehavior: "clear" | "preserve-and-lock",
isSubmitLoading: boolean,
@@ -1281,7 +1282,6 @@ function ComposerContentImpl({
}: ComposerContentProps) {
const mode = resolveComposerInputMode(inputMode);
const { t } = useTranslation();
const buttonIconSize = resolveComposerButtonIconSize();
const client = useHostRuntimeClient(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
const agentDirectoryStatus = useHostRuntimeAgentDirectoryStatus(serverId);
@@ -1310,6 +1310,7 @@ function ComposerContentImpl({
const isCompactFormFactor = useIsCompactFormFactor();
const isCompactLayout = resolveCompactLayout(isCompactLayoutOverride, isCompactFormFactor);
const buttonIconSize = iconSizeFor("md")[controlSizingForLayout(isCompactFormFactor)];
const isDesktopWebBreakpoint = resolveIsDesktopWebBreakpoint(isCompactFormFactor);
const hasFinePointer = useHasFinePointer();
const isDesktopLayout = resolveIsDesktopWebBreakpoint(isCompactLayout);
@@ -2081,7 +2082,6 @@ function ComposerContentImpl({
],
);
const contextWindowMeterGlyphSize = isCompactLayout ? ICON_SIZE.md : buttonIconSize;
const beforeVoiceContent = useMemo(
() =>
hasAgent ? (
@@ -2092,7 +2092,7 @@ function ComposerContentImpl({
maxTokens={agentState.contextWindowMaxTokens}
usedTokens={agentState.contextWindowUsedTokens}
totalCostUsd={agentState.totalCostUsd}
glyphSize={contextWindowMeterGlyphSize}
glyphSize={buttonIconSize}
/>
</View>
) : null,
@@ -2103,7 +2103,7 @@ function ComposerContentImpl({
agentState.contextWindowMaxTokens,
agentState.contextWindowUsedTokens,
agentState.totalCostUsd,
contextWindowMeterGlyphSize,
buttonIconSize,
],
);
@@ -2598,8 +2598,8 @@ const styles = StyleSheet.create((theme: Theme) => ({
gap: theme.spacing[3],
},
cancelButton: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.palette.red[600],
alignItems: "center",
@@ -2612,15 +2612,15 @@ const styles = StyleSheet.create((theme: Theme) => ({
gap: theme.spacing[1],
},
contextWindowMeterSlot: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
flexShrink: 0,
alignItems: "center",
justifyContent: "center",
},
realtimeVoiceButton: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
+18 -11
View File
@@ -27,7 +27,12 @@ import {
} from "react";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
import {
controlSizingForLayout,
iconSizeFor,
TOOLBAR_CONTROL_HEIGHT,
} from "@/components/ui/control-geometry";
import { ArrowUp, Mic, MicOff, CornerDownLeft, Plus, Square } from "lucide-react-native";
import * as Haptics from "expo-haptics";
import { useDictation } from "@/hooks/use-dictation";
@@ -1282,7 +1287,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
const isFullscreen = useComposerFullscreen(editingSession);
const [renderedLines, setRenderedLines] = useState(1);
const maxInputHeight = resolveMaxInputHeight(windowHeight, isCompact);
const buttonIconSize = isWeb ? ICON_SIZE.md : ICON_SIZE.lg;
const controlSizing = controlSizingForLayout(isCompact);
const buttonIconSize = iconSizeFor("md")[controlSizing];
const toast = useToast();
const voice = useVoiceOptional();
const voiceMuteToggleKeys = useShortcutKeys("voice-mute-toggle");
@@ -2235,6 +2241,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
/>
<ComposerInputPresentation
fullscreen={isFullscreen}
controlSizing={controlSizing}
sendIconSize={buttonIconSize}
surface={textSurface}
toolbar={toolbar}
@@ -2384,21 +2391,21 @@ const styles = StyleSheet.create((theme: Theme) => ({
gap: theme.spacing[1],
},
attachButton: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
attachButtonAnchor: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
alignItems: "center",
justifyContent: "center",
},
voiceButton: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
@@ -2407,8 +2414,8 @@ const styles = StyleSheet.create((theme: Theme) => ({
backgroundColor: theme.colors.destructive,
},
sendButton: {
width: 28,
height: 28,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.accent,
alignItems: "center",
@@ -2417,7 +2424,7 @@ const styles = StyleSheet.create((theme: Theme) => ({
},
sendButtonLabeled: {
width: "auto",
minWidth: 28,
minWidth: TOOLBAR_CONTROL_HEIGHT,
paddingHorizontal: theme.spacing[3],
borderRadius: theme.borderRadius.full,
},
@@ -6,14 +6,16 @@ import { Button } from "@/components/ui/button";
import { ComposerFullscreenBody, ComposerFullscreenFooter } from "@/composer/dock";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { isWeb } from "@/constants/platform";
import { ICON_SIZE } from "@/styles/theme";
import {
iconSizeFor,
TOOLBAR_CONTROL_HEIGHT,
TOOLBAR_CONTROL_SIZES,
type ControlSizing,
} from "@/components/ui/control-geometry";
import { StyleSheet } from "react-native-unistyles";
import { useComposerFullscreenExit } from "./fullscreen-exit";
import { resolveGlyphRailOffset } from "./state";
const CONTROL_SIZE = 28;
const FULLSCREEN_GLYPH_SIZE = ICON_SIZE.md;
function keepEditorFocused(event: import("react-native").PointerEvent) {
if (isWeb) event.preventDefault();
}
@@ -27,6 +29,7 @@ function keepEditorFocused(event: import("react-native").PointerEvent) {
*/
export function ComposerInputPresentation({
fullscreen,
controlSizing,
sendIconSize,
surface,
toolbar,
@@ -42,6 +45,8 @@ export function ComposerInputPresentation({
overlay,
}: {
fullscreen: boolean;
/** The sizing the toolbar's stylesheet resolves to; see `resolveControlSizing`. */
controlSizing: ControlSizing;
sendIconSize: number;
surface: ReactNode;
toolbar: ReactNode;
@@ -61,18 +66,19 @@ export function ComposerInputPresentation({
// action (Escape, hardware back) belongs only to the pane the user is in.
const { isActiveComposer } = useComposerKeyboardScope();
const exitScopeRef = useComposerFullscreenExit(fullscreen && isActiveComposer, onExit);
const glyphSize = iconSizeFor("md")[controlSizing];
const railOffset = resolveGlyphRailOffset({
controlSize: CONTROL_SIZE,
controlSize: TOOLBAR_CONTROL_SIZES[controlSizing],
sendIconSize,
glyphIconSize: FULLSCREEN_GLYPH_SIZE,
glyphIconSize: glyphSize,
});
const maximizeIcon = useCallback(
(color: string) => <Maximize2 color={color} size={FULLSCREEN_GLYPH_SIZE} />,
[],
(color: string) => <Maximize2 color={color} size={glyphSize} />,
[glyphSize],
);
const minimizeIcon = useCallback(
(color: string) => <Minimize2 color={color} size={FULLSCREEN_GLYPH_SIZE} />,
[],
(color: string) => <Minimize2 color={color} size={glyphSize} />,
[glyphSize],
);
// The toolbar row bleeds 6px past the input padding; the inline glyph sits on that edge.
const enterStyle = useMemo(() => [styles.enterButton, { right: -6 + railOffset }], [railOffset]);
@@ -141,8 +147,8 @@ const styles = StyleSheet.create((theme) => ({
inline: { flexShrink: 1, position: "relative" },
inlineTextSurface: { flexShrink: 1, position: "relative" },
iconButton: {
width: CONTROL_SIZE,
height: CONTROL_SIZE,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
padding: 0,
borderWidth: 0,
borderRadius: theme.borderRadius.full,
@@ -150,8 +156,8 @@ const styles = StyleSheet.create((theme) => ({
enterButton: {
position: "absolute",
top: 0,
width: CONTROL_SIZE,
height: CONTROL_SIZE,
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
padding: 0,
borderWidth: 0,
borderRadius: theme.borderRadius.full,
+6 -4
View File
@@ -13,6 +13,7 @@ import {
type MenuTriggerState,
} from "@/components/ui/menu";
import { StatusRing } from "@/components/status-ring";
import { bySizing } from "@/components/ui/control-geometry";
import { STATUS_RING_HALO_INSET } from "@/components/status-ring/geometry";
import { isWeb } from "@/constants/platform";
import { getStatusDotColor } from "@/utils/status-dot-color";
@@ -343,16 +344,17 @@ const styles = StyleSheet.create((theme) => {
// The rail every panel row sits on: inset from the panel edge so the fill is a rounded block
// inside it, and tall enough that revealing an action button cannot resize the row.
//
// Compact and desktop differ here and only here. A finger needs the taller row a menu row gets
// on compact; a pointer does not, and the popover keeps its density.
// Touch and pointer sizing differ here and only here. A finger needs the row a menu row gets
// on touch (`MENU_ITEM_HEIGHT` is always its touch value at `xs`); a pointer does not, and the
// popover keeps its density.
const trackRow = {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minHeight: { xs: MENU_ITEM_HEIGHT.xs, md: 32 },
minHeight: bySizing({ touch: MENU_ITEM_HEIGHT.xs, pointer: 32 }),
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: { xs: theme.spacing[2], md: theme.spacing[1] },
paddingVertical: bySizing({ touch: theme.spacing[2], pointer: theme.spacing[1] }),
borderRadius: theme.borderRadius.md,
} as const;
+8 -3
View File
@@ -1,14 +1,19 @@
import { useUnistyles } from "react-native-unistyles";
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-sizing";
import { isWeb } from "@/constants/platform";
export const FOOTER_HEIGHT = 75;
// Shared header inner height (excluding safe area insets and border)
// A bar of icon buttons: touch-sized it is one touch target tall, like an iOS navigation bar.
const BAR_HEIGHT = { touch: TOUCH_TARGET, pointer: 36 };
// Shared header inner height from `md` up (excluding safe area insets and border).
// Used by both agent header (ScreenHeader) and explorer sidebar header
// This ensures both headers have the same visual height
export const HEADER_INNER_HEIGHT = 36;
export const HEADER_INNER_HEIGHT = bySizing(BAR_HEIGHT).md;
export const HEADER_INNER_HEIGHT_MOBILE = 56;
export const WORKSPACE_SECONDARY_HEADER_HEIGHT = 36;
/** The tab rail and pane toolbars under the header. A breakpoint value for stylesheets. */
export const WORKSPACE_SECONDARY_HEADER_HEIGHT = bySizing(BAR_HEIGHT);
export const HEADER_TOP_PADDING_MOBILE = 8;
// Measured composer width; independent of the window's compact/wide breakpoint.
+6 -21
View File
@@ -17,7 +17,7 @@ import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { actionsWithoutPrimary, type GitAction, type GitActions } from "@/git/policy";
import { useGitActionRunner } from "@/git/use-actions";
import { CONTROL_HEIGHTS, HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
interface GitActionsSplitButtonProps {
gitActions: GitActions;
@@ -272,10 +272,7 @@ const styles = StyleSheet.create((theme) => ({
flexShrink: 0,
},
splitButton: {
height: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
height: HEADER_CONTROL_HEIGHT,
flexDirection: "row",
alignItems: "stretch",
borderRadius: theme.borderRadius.md,
@@ -296,10 +293,7 @@ const styles = StyleSheet.create((theme) => ({
xs: 48,
md: 42,
},
height: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
height: HEADER_CONTROL_HEIGHT,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
@@ -330,24 +324,15 @@ const styles = StyleSheet.create((theme) => ({
transform: [{ scale: 0.8 }],
},
splitButtonCaret: {
width: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
width: HEADER_CONTROL_HEIGHT,
alignItems: "center",
justifyContent: "center",
borderLeftWidth: theme.borderWidth[1],
borderLeftColor: theme.colors.borderAccent,
},
iconButton: {
width: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
height: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
width: HEADER_CONTROL_HEIGHT,
height: HEADER_CONTROL_HEIGHT,
alignItems: "center",
justifyContent: "center",
borderRadius: theme.borderRadius.md,
@@ -2,7 +2,7 @@ import React, { type ReactNode } from "react";
import { Pressable, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { CountedCheckPresentation } from "@/git/check-presentation";
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry";
import {
CheckPresentationIcon,
getCheckPresentationTone,
@@ -164,10 +164,10 @@ export const sectionKitStyles = StyleSheet.create((theme) => ({
gap: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
// Fixed, not minHeight plus padding. A row's trailing slot holds an sm Button
// (28pt), which stacked on the vertical padding and made rows with an
// , which stacked on the vertical padding and made rows with an
// "Add to chat" button taller than rows without one. The row is single-line by
// construction, so it declares a height the button fits inside instead.
height: CONTROL_HEIGHTS.sm + theme.spacing[1],
height: mapLayout(CONTROL_HEIGHTS.sm, (height) => height + theme.spacing[1]),
},
checkName: {
fontSize: theme.fontSize.base,
@@ -18,6 +18,16 @@ export function hasFinePointer(): boolean {
return getFinePointerQueryList()?.matches ?? false;
}
/**
* True when the device has a touch screen, even while a mouse or keyboard is attached to it:
* the primary pointer is coarse, or the screen reports touch points. Always true on native.
*/
export function hasTouchScreen(): boolean {
if (!isWeb) return true;
if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
return window.matchMedia("(pointer: coarse)").matches || window.navigator.maxTouchPoints > 0;
}
/**
* Reactive `hasFinePointer()` — re-renders when the user switches between a
* mouse and touch (detachable keyboards, tablet mode).
+2 -2
View File
@@ -656,8 +656,8 @@ const styles = StyleSheet.create((theme) => ({
gap: { xs: theme.spacing[1], md: theme.spacing[2] },
},
headerButton: {
height: { xs: 32, md: HEADER_CONTROL_HEIGHT },
minWidth: { xs: 32, md: HEADER_CONTROL_HEIGHT },
height: HEADER_CONTROL_HEIGHT,
minWidth: HEADER_CONTROL_HEIGHT,
paddingHorizontal: theme.spacing[2],
flexDirection: "row",
alignItems: "center",
+3 -3
View File
@@ -125,7 +125,7 @@ import {
SETTINGS_DESKTOP_SIDEBAR_WIDTH,
useIsCompactFormFactor,
} from "@/constants/layout";
import { densityIconBox, densityIconSize } from "@/styles/density";
import { density, densityIconBox, densityIconSize } from "@/styles/density";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import {
type EnableBuiltInDaemonOption,
@@ -1523,7 +1523,7 @@ const sidebarStyles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
gap: { xs: theme.spacing[3], md: theme.spacing[2] },
minHeight: { xs: 52, md: 28 },
minHeight: { xs: 52, md: density.tightRowHeight.md },
paddingVertical: theme.spacing[1],
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[2] },
borderRadius: { xs: 0, md: theme.borderRadius.lg },
@@ -1549,7 +1549,7 @@ const sidebarStyles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
gap: { xs: theme.spacing[3], md: theme.spacing[2] },
minHeight: { xs: 52, md: 28 },
minHeight: { xs: 52, md: density.tightRowHeight.md },
paddingVertical: theme.spacing[1],
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[2] },
borderRadius: { xs: 0, md: theme.borderRadius.lg },
@@ -1,4 +1,4 @@
import { useMemo, type ReactNode } from "react";
import { Fragment, useMemo, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { CompactHeader } from "@/components/headers/compact-header";
import {
@@ -6,6 +6,13 @@ import {
WorkspaceExplorerToggle,
} from "@/screens/workspace/workspace-explorer-toggle";
import { WorkspaceHeaderProjectRow } from "@/screens/workspace/workspace-header-project-row";
import {
useWindowLayout,
resolveWorkspaceActionPlacement,
resolveWorkspaceBarActions,
WindowLayoutActions,
} from "@/window-layout";
import { IconButtonChromeProvider } from "@/components/ui/icon-button-chrome";
export { MobileWorkspaceTabSwitcher } from "./tab-switcher";
@@ -18,8 +25,11 @@ interface CompactWorkspaceHeaderProps {
onToggleExplorer: () => void;
explorerToggleLabel: string;
explorerToggleAccessibilityState: { expanded: boolean };
/** Tab switcher and workspace menu, before the explorer toggle. */
tabSwitcher: ReactNode;
/** Workspace overflow menu. */
children: ReactNode;
headerVariant: "compact" | "full";
actionsActive: boolean;
}
/** The compact header with the workspace's project row and controls. */
@@ -32,9 +42,13 @@ export function CompactWorkspaceHeader({
explorerToggleLabel,
explorerToggleAccessibilityState,
children,
tabSwitcher,
serverId,
headerVariant,
actionsActive,
}: CompactWorkspaceHeaderProps) {
const { t } = useTranslation();
const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
const projectRow = useMemo(
() => (
<WorkspaceHeaderProjectRow
@@ -45,9 +59,10 @@ export function CompactWorkspaceHeader({
),
[subtitle, isSubtitleDistinct, serverId],
);
const actions = (
<>
{children}
const symbols = {
"tab-count": tabSwitcher,
overflow: children,
explorer: (
<WorkspaceExplorerToggle
onPress={onToggleExplorer}
label={explorerToggleLabel}
@@ -56,17 +71,25 @@ export function CompactWorkspaceHeader({
accessibilityState={explorerToggleAccessibilityState}
mobile
/>
</>
);
),
};
const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => (
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
));
return (
<CompactHeader
navigation="menu"
title={title}
titleTestID="workspace-header-title"
subtitle={projectRow}
loading={isLoading}
actions={actions}
/>
<IconButtonChromeProvider value="header-island">
{headerVariant === "compact" ? (
<CompactHeader
navigation="menu"
title={title}
titleTestID="workspace-header-title"
subtitle={projectRow}
loading={isLoading}
actions={actionsInBar ? undefined : actions}
/>
) : null}
<WindowLayoutActions active={actionsActive}>{actions}</WindowLayoutActions>
</IconButtonChromeProvider>
);
}
@@ -8,3 +8,5 @@ export {
type UseWorkspaceScriptsMenuPagesInput,
type WorkspaceScriptsMenuPages,
} from "./workspace-scripts-menu-pages";
export { useWorkspaceScriptActions } from "./use-workspace-script-actions";
@@ -3,9 +3,9 @@ import * as Clipboard from "expo-clipboard";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { useSessionStore } from "@/stores/session-store";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import { useToast } from "@/contexts/toast-context";
import { useToast } from "@/contexts/toast-api-context";
import {
resolveWorkspaceScriptLink,
type WorkspaceScriptLinkKind,
@@ -34,6 +34,7 @@ export interface WorkspaceScriptActions {
}
export interface UseWorkspaceScriptActionsInput {
client: Pick<DaemonClient, "startWorkspaceScript" | "killTerminal"> | null;
serverId: string;
workspaceId: string;
scripts: WorkspaceDescriptor["scripts"];
@@ -45,10 +46,11 @@ export interface UseWorkspaceScriptActionsInput {
* lists them.
*
* A restart outlives the press that asked for it — the second half waits for the daemon to
* report the script stopped — so mount this with whatever owns the menu, not inside a menu page
* that unmounts when the menu closes.
* report the script stopped — so mount this once with the workspace screen and pass its actions to
* each menu surface. Header placement and menu lifetime must not own pending restarts.
*/
export function useWorkspaceScriptActions({
client,
serverId,
workspaceId,
scripts,
@@ -56,7 +58,6 @@ export function useWorkspaceScriptActions({
}: UseWorkspaceScriptActionsInput): WorkspaceScriptActions {
const { t } = useTranslation();
const toast = useToast();
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const preferredRouteKind = useWorkspaceServiceRoutePreferencesStore(
(state) => state.byServerId[serverId] ?? null,
@@ -8,6 +8,8 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createRoot } from "react-dom/client";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { useWorkspaceScriptActions } from "./use-workspace-script-actions";
import { WorkspaceScriptsButton } from "./workspace-scripts-button";
void testI18n;
@@ -50,7 +52,13 @@ const {
return {
theme: hoistedTheme,
startWorkspaceScriptMock: vi.fn(async () => ({ terminalId: "terminal-script-1" })),
startWorkspaceScriptMock: vi.fn(async () => ({
terminalId: "terminal-script-1",
requestId: "start-1",
workspaceId: "workspace-1",
scriptName: "dev",
error: null,
})),
killTerminalMock: vi.fn(async () => ({
terminalId: "terminal-script-1",
success: true,
@@ -113,20 +121,6 @@ vi.mock("@/workspace-service-routes/store", async () => {
};
});
vi.mock("@/stores/session-store", () => ({
useSessionStore: (selector: (state: unknown) => unknown) =>
selector({
sessions: {
"test-server": {
client: {
startWorkspaceScript: startWorkspaceScriptMock,
killTerminal: killTerminalMock,
},
},
},
}),
}));
vi.mock("@/contexts/toast-context", () => ({
useToast: () => ({ show: vi.fn(), error: vi.fn(), copied: copiedToastMock }),
}));
@@ -237,6 +231,34 @@ interface RenderScriptsOptions {
hideLabels?: boolean;
}
const testToast = { show: () => () => {}, error: () => {}, copied: copiedToastMock };
const scriptClient = {
startWorkspaceScript: startWorkspaceScriptMock,
killTerminal: killTerminalMock,
};
function ScriptsOwner({
scripts,
hideLabels,
}: {
scripts: WorkspaceScriptPayload[];
hideLabels?: boolean;
}) {
const actions = useWorkspaceScriptActions({
client: scriptClient,
serverId: "test-server",
workspaceId: "workspace-1",
scripts,
});
return (
<WorkspaceScriptsButton
actions={actions}
scripts={scripts}
liveTerminalIds={LIVE_TERMINAL_IDS}
hideLabels={hideLabels}
/>
);
}
function renderScripts(
scripts: WorkspaceScriptPayload[],
options: RenderScriptsOptions = {},
@@ -257,13 +279,9 @@ function renderScripts(
function element(nextScripts: WorkspaceScriptPayload[]): ReactElement {
return (
<QueryClientProvider client={queryClient}>
<WorkspaceScriptsButton
serverId="test-server"
workspaceId="workspace-1"
scripts={nextScripts}
liveTerminalIds={LIVE_TERMINAL_IDS}
hideLabels={options.hideLabels}
/>
<ToastApiProvider api={testToast}>
<ScriptsOwner scripts={nextScripts} hideLabels={options.hideLabels} />
</ToastApiProvider>
</QueryClientProvider>
);
}
@@ -28,23 +28,18 @@ import type {
WorkspaceScriptLinkTarget,
} from "@/utils/workspace-script-links";
import type { Theme } from "@/styles/theme";
import { CONTROL_HEIGHTS, HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { extraMutedIconColorMapping } from "@/components/ui/icon-color";
import { ExitCodeBadge, routeLabelKey, ScriptIcon } from "./script-marks";
import { scriptToneColorMapping } from "./script-status";
import {
useWorkspaceScriptActions,
type WorkspaceScriptActions,
} from "./use-workspace-script-actions";
import type { WorkspaceScriptActions } from "./use-workspace-script-actions";
type RowActionIcon = "copy" | "open" | "restart" | "start" | "stop" | "terminal";
interface WorkspaceScriptsButtonProps {
serverId: string;
workspaceId: string;
actions: WorkspaceScriptActions;
scripts: WorkspaceDescriptor["scripts"];
liveTerminalIds?: readonly string[];
onScriptTerminalStarted?: (terminalId: string) => void;
onViewTerminal?: (terminalId: string) => void;
onOpenUrlInBrowserTab?: (url: string) => void;
hideLabels?: boolean;
@@ -448,22 +443,14 @@ function ScriptRow({
}
export function WorkspaceScriptsButton({
serverId,
workspaceId,
actions,
scripts,
liveTerminalIds = [],
onScriptTerminalStarted,
onViewTerminal,
onOpenUrlInBrowserTab,
hideLabels,
}: WorkspaceScriptsButtonProps): ReactElement | null {
const { t } = useTranslation();
const actions = useWorkspaceScriptActions({
serverId,
workspaceId,
scripts,
onScriptTerminalStarted,
});
const liveTerminalIdSet = useMemo(() => new Set(liveTerminalIds), [liveTerminalIds]);
const triggerStyle = useCallback(
@@ -531,10 +518,7 @@ const styles = StyleSheet.create((theme) => ({
flexShrink: 0,
},
splitButton: {
height: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
height: HEADER_CONTROL_HEIGHT,
flexDirection: "row",
alignItems: "stretch",
borderRadius: theme.borderRadius.md,
@@ -18,10 +18,7 @@ import type {
} from "@/utils/workspace-script-links";
import { ExitCodeBadge, routeLabelKey, ScriptIcon } from "./script-marks";
import { scriptToneColorMapping, summarizeScripts, type ScriptsSummary } from "./script-status";
import {
useWorkspaceScriptActions,
type WorkspaceScriptActions,
} from "./use-workspace-script-actions";
import type { WorkspaceScriptActions } from "./use-workspace-script-actions";
type WorkspaceScript = WorkspaceDescriptor["scripts"][number];
@@ -56,11 +53,9 @@ function scriptPageId(scriptName: string): string {
}
export interface UseWorkspaceScriptsMenuPagesInput {
serverId: string;
workspaceId: string;
actions: WorkspaceScriptActions;
scripts: WorkspaceDescriptor["scripts"];
liveTerminalIds: readonly string[];
onScriptTerminalStarted: (terminalId: string) => void;
onViewTerminal: (terminalId: string) => void;
onOpenUrlInBrowserTab: (url: string) => void;
}
@@ -80,25 +75,16 @@ export interface WorkspaceScriptsMenuPages {
* Every script gets a page whether or not it runs, so stopping one from its own page flips that
* page to its stopped state instead of pulling it out from under the user.
*
* The actions live here rather than in a page, so call this from whatever owns the menu: a restart
* finishes after the sheet has closed.
* The workspace screen owns the actions so a restart finishes across menu and header changes.
*/
export function useWorkspaceScriptsMenuPages({
serverId,
workspaceId,
actions,
scripts,
liveTerminalIds,
onScriptTerminalStarted,
onViewTerminal,
onOpenUrlInBrowserTab,
}: UseWorkspaceScriptsMenuPagesInput): WorkspaceScriptsMenuPages {
const { t } = useTranslation();
const actions = useWorkspaceScriptActions({
serverId,
workspaceId,
scripts,
onScriptTerminalStarted,
});
const summary = useMemo(() => summarizeScripts(scripts), [scripts]);
const trigger = useMemo(
@@ -82,6 +82,7 @@ import { buildWorkspaceKeyboardHandlerId } from "@/keyboard/handler-id";
import type { KeyboardActionDefinition } from "@/keyboard/keyboard-action-dispatcher";
import { WorkspaceNewTabMenuContent } from "@/screens/workspace/workspace-new-tab-menu";
import {
paneContentToolbarIconSize,
paneContentToolbarTrailingPadding,
ToolbarButton,
ToolbarControls,
@@ -115,6 +116,8 @@ const TAB_ICON_WIDTH = 14;
const TAB_CONTENT_GAP = 4;
const TAB_DROP_INDICATOR_WIDTH = 4;
const TAB_MODIFIED_DOT_SIZE = 8;
// The tab rail only renders in the wide layout, so the device alone picks its glyph size.
const TAB_RAIL_GLYPH_SIZE = paneContentToolbarIconSize(false);
const TAB_MIN_WIDTH = 64;
const TAB_MAX_WIDTH = 160;
const TAB_CLOSE_BUTTON_RESERVED_WIDTH = 0;
@@ -249,7 +252,7 @@ function WorkspaceNewTabButton({
testID="workspace-new-tab-button"
style={placement === "inline" ? styles.inlineNewTabButton : undefined}
>
<ThemedPlus size={14} uniProps={extraMutedColorMapping} />
<ThemedPlus size={TAB_RAIL_GLYPH_SIZE} uniProps={extraMutedColorMapping} />
</ToolbarButton>
<WorkspaceNewTabMenuContent
serverId={serverId}
@@ -298,11 +301,11 @@ function WorkspacePaneToolbarActions({
const splitDownKeys = useShortcutKeys("workspace-pane-split-down");
const splitActionsVisible = showSplitActions && Boolean(onSplitRight && onSplitDown);
const splitRightLeading = useMemo(
() => <ThemedColumns2 size={14} uniProps={extraMutedColorMapping} />,
() => <ThemedColumns2 size={TAB_RAIL_GLYPH_SIZE} uniProps={extraMutedColorMapping} />,
[],
);
const splitDownLeading = useMemo(
() => <ThemedRows2 size={14} uniProps={extraMutedColorMapping} />,
() => <ThemedRows2 size={TAB_RAIL_GLYPH_SIZE} uniProps={extraMutedColorMapping} />,
[],
);
const splitRightTrailing = useMemo(
@@ -341,9 +344,9 @@ function WorkspacePaneToolbarActions({
onPress={onTogglePaneMaximized}
>
{paneMaximized ? (
<ThemedMinimize size={14} uniProps={extraMutedColorMapping} />
<ThemedMinimize size={TAB_RAIL_GLYPH_SIZE} uniProps={extraMutedColorMapping} />
) : (
<ThemedMaximize size={14} uniProps={extraMutedColorMapping} />
<ThemedMaximize size={TAB_RAIL_GLYPH_SIZE} uniProps={extraMutedColorMapping} />
)}
</ToolbarButton>
) : null}
@@ -354,7 +357,7 @@ function WorkspacePaneToolbarActions({
label={t("workspace.git.actions.moreActions")}
testID="workspace-split-pane-menu"
>
<ThemedEllipsis size={14} uniProps={extraMutedColorMapping} />
<ThemedEllipsis size={TAB_RAIL_GLYPH_SIZE} uniProps={extraMutedColorMapping} />
</ToolbarButton>
<DropdownMenuContent
side="bottom"
@@ -409,7 +412,7 @@ function WorkspaceExitFocusModeButton({
testID="workspace-exit-focus-mode"
onPress={onPress}
>
<ThemedX size={14} uniProps={mutedColorMapping} />
<ThemedX size={TAB_RAIL_GLYPH_SIZE} uniProps={mutedColorMapping} />
</ToolbarButton>
</View>
);
@@ -7,6 +7,7 @@ import {
type InlinePathTarget,
} from "@/assistant-file-links";
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";
@@ -62,7 +63,7 @@ import { SplitContainer } from "@/components/split-container";
import { RetainedPanel } from "@/components/retained-panel";
import { WorkspaceActions } from "@/git/workspace-actions";
import { WorkspaceOpenInEditorButton } from "@/workspace/open-in-editor/button";
import { WorkspaceScriptsButton } from "@/screens/workspace/scripts";
import { WorkspaceScriptsButton, useWorkspaceScriptActions } from "@/screens/workspace/scripts";
import { ImportSessionSheet } from "@/components/import-session-sheet";
import { useNavigateToImportedAgent } from "@/hooks/use-import-session";
import { useToast } from "@/contexts/toast-context";
@@ -502,6 +503,7 @@ function WorkspaceHeaderTitleBar({
onCopyBranchName,
onOpenSetupTab,
}: WorkspaceHeaderTitleBarProps) {
const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
return (
<View style={styles.headerTitleContainer}>
{isLoading ? (
@@ -518,18 +520,20 @@ function WorkspaceHeaderTitleBar({
/>
</View>
)}
<View style={styles.compactHeaderMenuCluster}>
<WorkspaceHeaderMenuDesktop
currentBranchName={currentBranchName}
showWorkspaceSetup={showWorkspaceSetup}
importAgentDisabled={importAgentDisabled}
copyPathDisabled={copyPathDisabled}
onOpenImportSheet={onOpenImportSheet}
onCopyWorkspacePath={onCopyWorkspacePath}
onCopyBranchName={onCopyBranchName}
onOpenSetupTab={onOpenSetupTab}
/>
</View>
{actionsInBar ? null : (
<View style={styles.compactHeaderMenuCluster}>
<WorkspaceHeaderMenuDesktop
currentBranchName={currentBranchName}
showWorkspaceSetup={showWorkspaceSetup}
importAgentDisabled={importAgentDisabled}
copyPathDisabled={copyPathDisabled}
onOpenImportSheet={onOpenImportSheet}
onCopyWorkspacePath={onCopyWorkspacePath}
onCopyBranchName={onCopyBranchName}
onOpenSetupTab={onOpenSetupTab}
/>
</View>
)}
</View>
);
}
@@ -1022,8 +1026,11 @@ function WorkspaceScreenContent({
}: WorkspaceScreenContentProps) {
const { t } = useTranslation();
const _insets = useSafeAreaInsets();
const workspaceActionsInBar =
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");
@@ -1213,6 +1220,13 @@ function WorkspaceScreenContent({
onTerminalCreateQueued: handleTerminalCreateQueued,
onTerminalCreateFailed: handleTerminalCreateFailed,
});
const scriptActions = useWorkspaceScriptActions({
client,
serverId: normalizedServerId,
workspaceId: normalizedWorkspaceId,
scripts: workspaceScripts,
onScriptTerminalStarted: handleScriptTerminalStarted,
});
const { archiveAgent } = useArchiveAgent();
const { checkoutQuery, isCheckoutStatusLoading } = useWorkspaceCheckoutStatus({
@@ -3189,11 +3203,9 @@ function WorkspaceScreenContent({
<PluginHeaderButtons serverId={normalizedServerId} workspaceId={normalizedWorkspaceId} />
{workspaceDescriptor && workspaceDescriptor.scripts.length > 0 ? (
<WorkspaceScriptsButton
serverId={normalizedServerId}
workspaceId={normalizedWorkspaceId}
actions={scriptActions}
scripts={workspaceDescriptor.scripts}
liveTerminalIds={liveTerminalIds}
onScriptTerminalStarted={handleScriptTerminalStarted}
onViewTerminal={handleViewScriptTerminal}
onOpenUrlInBrowserTab={handleOpenUrlInBrowserTab}
hideLabels
@@ -3211,15 +3223,17 @@ function WorkspaceScreenContent({
{workspaceDirectory ? (
<>
<WorkspaceActions serverId={normalizedServerId} cwd={workspaceDirectory} />
<WorkspaceHeaderExplorerToggle
owner={explorerToggleOwner}
onPress={handleToggleExplorerSidebar}
label={explorerSidebarToggleLabel}
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
tooltipKeys={EXPLORER_TOGGLE_KEYS}
style={styles.compactHeaderActionButton}
accessibilityState={explorerSidebarToggleAccessibilityState}
/>
{workspaceActionsInBar ? null : (
<WorkspaceHeaderExplorerToggle
owner={explorerToggleOwner}
onPress={handleToggleExplorerSidebar}
label={explorerSidebarToggleLabel}
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
tooltipKeys={EXPLORER_TOGGLE_KEYS}
style={styles.compactHeaderActionButton}
accessibilityState={explorerSidebarToggleAccessibilityState}
/>
)}
</>
) : null}
</View>
@@ -3231,13 +3245,14 @@ function WorkspaceScreenContent({
workspaceDirectory,
activeFileLocation,
liveTerminalIds,
handleScriptTerminalStarted,
scriptActions,
handleViewScriptTerminal,
handleOpenUrlInBrowserTab,
handleToggleExplorerSidebar,
explorerSidebarToggleLabel,
explorerSidebarToggleAccessibilityState,
explorerToggleOwner,
workspaceActionsInBar,
t,
],
);
@@ -3343,104 +3358,113 @@ function WorkspaceScreenContent({
);
const compactHeaderScripts = useMemo(
() => ({
serverId: normalizedServerId,
workspaceId: normalizedWorkspaceId,
actions: scriptActions,
scripts: workspaceScripts,
liveTerminalIds,
onScriptTerminalStarted: handleScriptTerminalStarted,
onViewTerminal: handleViewScriptTerminal,
onOpenUrlInBrowserTab: handleOpenUrlInBrowserTab,
}),
[
normalizedServerId,
normalizedWorkspaceId,
workspaceScripts,
liveTerminalIds,
handleScriptTerminalStarted,
scriptActions,
handleViewScriptTerminal,
handleOpenUrlInBrowserTab,
],
);
const compactWorkspaceHeader = useMemo(
() =>
isMobile ? (
<CompactWorkspaceHeader
isLoading={isWorkspaceHeaderLoading}
title={workspaceHeaderTitle}
subtitle={workspaceHeaderSubtitle}
isSubtitleDistinct={isWorkspaceHeaderSubtitleDistinct}
serverId={normalizedServerId}
onToggleExplorer={handleToggleExplorerSidebar}
explorerToggleLabel={explorerSidebarToggleLabel}
explorerToggleAccessibilityState={explorerSidebarToggleAccessibilityState}
>
<MobileWorkspaceTabSwitcher
tabs={tabs}
activeTabKey={activeTabKey}
normalizedServerId={normalizedServerId}
normalizedWorkspaceId={normalizedWorkspaceId}
onSelectSwitcherTab={handleSelectSwitcherTab}
createTerminalDisabled={createTerminalDisabled}
onCreateDraftTab={handleCreateDraftTab}
onCreateTerminal={handleCreateTerminal}
onCopyResumeCommand={handleCopyResumeCommand}
onCopyAgentId={handleCopyAgentId}
onCopyTerminalId={handleCopyTerminalId}
onCopyFilePath={handleCopyFilePath}
onReloadAgent={handleReloadAgent}
onRenameTab={handleRenameTab}
onCloseTab={handleCloseTabById}
onCloseTabsAbove={handleCloseTabsToLeft}
onCloseTabsBelow={handleCloseTabsToRight}
onCloseOtherTabs={handleCloseOtherTabs}
/>
<WorkspaceHeaderMenuMobile
normalizedServerId={normalizedServerId}
normalizedWorkspaceId={normalizedWorkspaceId}
scripts={compactHeaderScripts}
currentBranchName={currentBranchName}
showWorkspaceSetup={showWorkspaceSetup}
showCreateBrowserTab={showCreateBrowserTab}
createTerminalDisabled={createTerminalDisabled}
importAgentDisabled={!canOpenImportSheet}
copyPathDisabled={!workspaceDirectory}
onCreateTerminalWithProfile={handleCreateTerminalWithProfile}
onCreateBrowser={handleCreateBrowserTab}
onOpenImportSheet={openImportSheet}
onCopyWorkspacePath={handleCopyWorkspacePath}
onCopyBranchName={handleCopyBranchName}
onOpenSetupTab={handleOpenSetupTab}
/>
</CompactWorkspaceHeader>
) : null,
const workspaceTabSwitcher = useMemo(
() => (
<MobileWorkspaceTabSwitcher
tabs={tabs}
activeTabKey={activeTabKey}
normalizedServerId={normalizedServerId}
normalizedWorkspaceId={normalizedWorkspaceId}
onSelectSwitcherTab={handleSelectSwitcherTab}
createTerminalDisabled={createTerminalDisabled}
onCreateDraftTab={handleCreateDraftTab}
onCreateTerminal={handleCreateTerminal}
onCopyResumeCommand={handleCopyResumeCommand}
onCopyAgentId={handleCopyAgentId}
onCopyTerminalId={handleCopyTerminalId}
onCopyFilePath={handleCopyFilePath}
onReloadAgent={handleReloadAgent}
onRenameTab={handleRenameTab}
onCloseTab={handleCloseTabById}
onCloseTabsAbove={handleCloseTabsToLeft}
onCloseTabsBelow={handleCloseTabsToRight}
onCloseOtherTabs={handleCloseOtherTabs}
/>
),
[
activeTabKey,
createTerminalDisabled,
handleCloseOtherTabs,
handleCloseTabById,
handleCloseTabsToLeft,
handleCloseTabsToRight,
handleCopyAgentId,
handleCopyFilePath,
handleCopyResumeCommand,
handleCopyTerminalId,
handleCreateDraftTab,
handleCreateTerminal,
handleReloadAgent,
handleRenameTab,
handleSelectSwitcherTab,
normalizedServerId,
normalizedWorkspaceId,
tabs,
],
);
const compactWorkspaceHeader = useMemo(
() => (
<CompactWorkspaceHeader
headerVariant={isMobile ? "compact" : "full"}
actionsActive={isRouteFocused && (!isMobile || workspacePanelActive)}
isLoading={isWorkspaceHeaderLoading}
title={workspaceHeaderTitle}
subtitle={workspaceHeaderSubtitle}
isSubtitleDistinct={isWorkspaceHeaderSubtitleDistinct}
serverId={normalizedServerId}
onToggleExplorer={handleToggleExplorerSidebar}
explorerToggleLabel={explorerSidebarToggleLabel}
explorerToggleAccessibilityState={explorerSidebarToggleAccessibilityState}
tabSwitcher={workspaceTabSwitcher}
>
<WorkspaceHeaderMenuMobile
normalizedServerId={normalizedServerId}
normalizedWorkspaceId={normalizedWorkspaceId}
scripts={compactHeaderScripts}
currentBranchName={currentBranchName}
showWorkspaceSetup={showWorkspaceSetup}
showCreateBrowserTab={showCreateBrowserTab}
createTerminalDisabled={createTerminalDisabled}
importAgentDisabled={!canOpenImportSheet}
copyPathDisabled={!workspaceDirectory}
onCreateTerminalWithProfile={handleCreateTerminalWithProfile}
onCreateBrowser={handleCreateBrowserTab}
onOpenImportSheet={openImportSheet}
onCopyWorkspacePath={handleCopyWorkspacePath}
onCopyBranchName={handleCopyBranchName}
onOpenSetupTab={handleOpenSetupTab}
/>
</CompactWorkspaceHeader>
),
[
canOpenImportSheet,
compactHeaderScripts,
createTerminalDisabled,
currentBranchName,
explorerSidebarToggleAccessibilityState,
explorerSidebarToggleLabel,
handleCloseOtherTabs,
handleCloseTabById,
handleCloseTabsToLeft,
handleCloseTabsToRight,
handleCopyAgentId,
handleCopyBranchName,
handleCopyFilePath,
handleCopyResumeCommand,
handleCopyTerminalId,
handleCopyWorkspacePath,
handleCreateBrowserTab,
handleCreateDraftTab,
handleCreateTerminal,
handleCreateTerminalWithProfile,
handleOpenSetupTab,
handleReloadAgent,
handleRenameTab,
handleSelectSwitcherTab,
handleToggleExplorerSidebar,
isMobile,
isRouteFocused,
isWorkspaceHeaderLoading,
isWorkspaceHeaderSubtitleDistinct,
normalizedServerId,
@@ -3448,10 +3472,11 @@ function WorkspaceScreenContent({
openImportSheet,
showCreateBrowserTab,
showWorkspaceSetup,
tabs,
workspaceDirectory,
workspaceHeaderSubtitle,
workspaceHeaderTitle,
workspacePanelActive,
workspaceTabSwitcher,
],
);
const desktopSplitContent = useMemo(() => {
@@ -3559,6 +3584,7 @@ function WorkspaceScreenContent({
</View>
) : (
<View style={styles.centerColumn}>
{compactWorkspaceHeader}
{rendersDesktopSplitContent ? null : renderWorkspaceScreenHeader()}
{shouldRenderDesktopPaneFallback ? (
+22 -19
View File
@@ -1,33 +1,36 @@
import {
bySizing,
iconSizeFor,
TOOLBAR_CONTROL_HEIGHT,
TOUCH_TARGET,
type IconSize,
} from "@/components/ui/control-geometry";
import { isCompactBreakpoint } from "@/constants/layout";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
/**
* Density sizes for surfaces that opt into touch sizing: rows and icons grow on compact
* layouts and keep their desktop sizes from the `md` breakpoint up. Plain theme tokens stay
* desktop-sized everywhere, so a surface migrates by swapping its sizes for these.
* Density sizes for surfaces that opt into touch sizing: rows and icons take their touch sizes
* where controls do (see `resolveControlSizing`) and their pointer sizes elsewhere. Plain theme
* tokens stay pointer-sized everywhere, so a surface migrates by swapping its sizes for these.
*
* Style values are Unistyles breakpoint values, resolved inside `StyleSheet.create`. Icon sizes
* are props, so icons take them through `DensityIcon` or a `densityIconProps` mapping.
*/
export type DensityIconSize = keyof typeof ICON_SIZE;
const COMPACT_ICON_SIZE: Record<DensityIconSize, number> = { xs: 14, sm: 18, md: 20, lg: 24 };
// Compact layouts end where `md` begins; see `isCompactBreakpoint`.
function byLayout<T>(compact: T, desktop: T) {
return { xs: compact, md: desktop };
}
export type DensityIconSize = IconSize;
export const density = {
/** A list row such as a sidebar entry. */
rowHeight: byLayout(44, 36),
/** A row in a tight group, such as the sidebar's navigation rows. */
tightRowHeight: byLayout(36, 28),
rowHeight: bySizing({ touch: TOUCH_TARGET, pointer: 36 }),
/** A row in a tight group, such as the sidebar's navigation rows. Touch-sized it is a full row. */
tightRowHeight: bySizing({ touch: TOUCH_TARGET, pointer: 28 }),
/** A square icon-only button that sits in a row or toolbar. */
iconButton: byLayout(44, 28),
/** The space between two blocks of rich text, such as Markdown paragraphs, code and images. */
blockGap: byLayout(12, 16),
iconButton: TOOLBAR_CONTROL_HEIGHT,
/**
* The space between two blocks of rich text, such as Markdown paragraphs, code and images.
* Reading rhythm, not a touch target, so it follows the layout alone.
*/
blockGap: { xs: 12, md: 16 },
};
/** Resolves a density value for a prop, which Unistyles cannot resolve on its own. */
@@ -37,7 +40,7 @@ export function resolveDensity<T>(rt: { breakpoint?: string }, value: { xs: T; m
/** The width or height of a slot that holds an icon of `size`. */
export function densityIconBox(size: DensityIconSize) {
return byLayout(COMPACT_ICON_SIZE[size], ICON_SIZE[size]);
return bySizing(iconSizeFor(size));
}
export function densityIconSize(rt: { breakpoint?: string }, size: DensityIconSize): number {
@@ -0,0 +1,95 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { PortalProvider } from "@gorhom/portal";
import { afterEach, expect, it, vi } from "vitest";
import { Text } from "react-native";
import { page } from "vitest/browser";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import type { WindowLayout } from "./model";
import { WindowLayoutContext } from "./context";
import { WindowLayoutActions, WindowLayoutActionsHost } from "./actions";
import { WindowLayoutDivisionGap } from "./surface";
import { lightTheme } from "@/styles/theme";
vi.stubGlobal("React", React);
const layout = { sidebarWidth: 465, gap: 21, contentWidth: 381 };
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: [],
};
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
afterEach(() => {
act(() => root.render(null));
});
it("paints the reserved division with the sidebar surface", () => {
act(() =>
root.render(<WindowLayoutDivisionGap layout={layout} sidebarVisible compact={false} />),
);
const gap = container.firstElementChild as HTMLElement;
const expected = document.createElement("div");
expected.style.backgroundColor = lightTheme.colors.surfaceSidebar;
expect(getComputedStyle(gap).backgroundColor).toBe(expected.style.backgroundColor);
expect(getComputedStyle(gap).borderRightWidth).toBe("1px");
expect(gap.getBoundingClientRect().width).toBe(21);
});
const explorerState = { expanded: false };
const noKeys: [] = [];
const noop = () => {};
it("preserves circular explorer chrome and closes a portaled menu when actions become inactive", async () => {
async function renderActions(active: boolean) {
await act(async () =>
root.render(
<PortalProvider>
<WindowLayoutContext.Provider value={geometry}>
<WindowLayoutActionsHost />
<WindowLayoutActions active={active}>
<HeaderToggleButton
onPress={noop}
accessibilityRole="button"
accessibilityLabel="Explorer"
tooltipLabel="Explorer"
tooltipSide="left"
tooltipKeys={noKeys}
accessibilityState={explorerState}
>
<Text>Explorer</Text>
</HeaderToggleButton>
<DropdownMenu>
<DropdownMenuTrigger accessibilityRole="button" accessibilityLabel="Bar menu">
<Text>Menu</Text>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onSelect={noop}>Bar menu item</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</WindowLayoutActions>
</WindowLayoutContext.Provider>
</PortalProvider>,
),
);
}
await renderActions(true);
const explorer = container.querySelector('[aria-label="Explorer"]') as HTMLElement;
expect(getComputedStyle(explorer).borderRadius).toBe(`${lightTheme.borderRadius.full}px`);
await page.getByRole("button", { name: "Bar menu", exact: true }).click();
await expect.element(page.getByRole("menuitem", { name: "Bar menu item" })).toBeVisible();
await renderActions(false);
await expect.poll(() => document.querySelectorAll('[role="menuitem"]').length).toBe(0);
expect(
container.querySelector('[data-testid="workspace-vertical-actions"]')?.getBoundingClientRect()
.height,
).toBe(0);
});
@@ -0,0 +1,50 @@
import type { ReactNode } from "react";
import { Portal, PortalHost } from "@gorhom/portal";
import { StyleSheet, View } from "react-native";
import { RetainedPanelActivity } from "@/components/retained-panel";
import { IconButtonChromeProvider } from "@/components/ui/icon-button-chrome";
import { useWindowLayout } from "./context";
import { resolveWorkspaceActionPlacement } from "./model";
const HOST = "window-layout-actions";
export function WindowLayoutActionsHost() {
return <PortalHost name={HOST} />;
}
/** The native bar guide is in window coordinates, so the host lives at the window root. */
export function WindowLayoutActions({
children,
active,
}: {
children: ReactNode;
active: boolean;
}) {
const layout = useWindowLayout();
if (resolveWorkspaceActionPlacement(layout) !== "vertical-bar" || !layout?.verticalBar) {
return null;
}
const bar = layout.verticalBar;
return (
<Portal hostName={HOST}>
<View
testID="workspace-vertical-actions"
style={[
styles.bar,
{ left: bar.x, top: bar.y, width: bar.width, height: bar.height },
!active && styles.hidden,
]}
pointerEvents="box-none"
>
<RetainedPanelActivity active={active}>
<IconButtonChromeProvider value="header-island">{children}</IconButtonChromeProvider>
</RetainedPanelActivity>
</View>
</Portal>
);
}
const styles = StyleSheet.create({
hidden: { display: "none" },
bar: { position: "absolute", alignItems: "center", gap: 8 },
});
+15
View File
@@ -0,0 +1,15 @@
import { createContext, useContext } from "react";
import { useWindowDimensions } from "react-native";
import type { WindowLayout } from "./model";
export const WindowLayoutContext = createContext<WindowLayout | null>(null);
export function useWindowLayout(): WindowLayout | null {
const layout = useContext(WindowLayoutContext);
const { width, height } = useWindowDimensions();
return layout &&
Math.abs(layout.bounds.width - width) <= 0.5 &&
Math.abs(layout.bounds.height - height) <= 0.5
? layout
: null;
}
@@ -0,0 +1,43 @@
import { useCallback, useState, type ReactNode } from "react";
import { StyleSheet, View, type NativeSyntheticEvent, type ViewProps } from "react-native";
import { requireNativeViewManager } from "expo-modules-core";
import { WindowLayoutContext } from "./context";
import type { WindowLayout } from "./model";
export { useWindowLayout } from "./context";
export { WindowLayoutActions, WindowLayoutActionsHost } from "./actions";
export { WindowLayoutSurface, WindowLayoutDivisionGap } from "./surface";
export {
resolveDesktopDivisionLayout,
resolveWorkspaceActionPlacement,
resolveWorkspaceBarActions,
} from "./model";
export type { DesktopDivisionLayout, WindowLayout, WindowLayoutRect } from "./model";
const GeometryProbe = requireNativeViewManager<
ViewProps & {
onGeometryChange: (event: NativeSyntheticEvent<WindowLayout>) => void;
}
>("PaseoWindowLayout");
export function WindowLayoutProvider({ children }: { children: ReactNode }) {
const [geometry, setGeometry] = useState<WindowLayout | null>(null);
const onGeometryChange = useCallback(
(event: NativeSyntheticEvent<WindowLayout>) => setGeometry(event.nativeEvent),
[],
);
return (
<WindowLayoutContext.Provider value={geometry}>
<View style={styles.root}>
<GeometryProbe
pointerEvents="none"
style={StyleSheet.absoluteFill}
onGeometryChange={onGeometryChange}
/>
{children}
</View>
</WindowLayoutContext.Provider>
);
}
const styles = StyleSheet.create({ root: { flex: 1 } });
+15
View File
@@ -0,0 +1,15 @@
import type { ReactNode } from "react";
export { useWindowLayout } from "./context";
export { WindowLayoutActions, WindowLayoutActionsHost } from "./actions";
export { WindowLayoutSurface, WindowLayoutDivisionGap } from "./surface";
export {
resolveDesktopDivisionLayout,
resolveWorkspaceActionPlacement,
resolveWorkspaceBarActions,
} from "./model";
export type { DesktopDivisionLayout, WindowLayout, WindowLayoutRect } from "./model";
export function WindowLayoutProvider({ children }: { children: ReactNode }) {
return children;
}
+65
View File
@@ -0,0 +1,65 @@
export interface WindowLayoutRect {
x: number;
y: number;
width: number;
height: number;
}
export interface WindowLayout {
bounds: WindowLayoutRect;
verticalBarEdge: "none" | "leading" | "trailing";
verticalBar: WindowLayoutRect | null;
divisions: WindowLayoutRect[];
}
export interface DesktopDivisionLayout {
sidebarWidth: number;
gap: number;
contentWidth: number;
}
export function resolveWorkspaceActionPlacement(
layout: WindowLayout | null,
): "header" | "vertical-bar" {
return layout?.verticalBarEdge === "trailing" && layout.verticalBar !== null
? "vertical-bar"
: "header";
}
export function resolveWorkspaceBarActions(
headerVariant: "compact" | "full",
): readonly ("tab-count" | "overflow" | "explorer")[] {
return headerVariant === "compact"
? ["tab-count", "overflow", "explorer"]
: ["overflow", "explorer"];
}
/** One book-like partition owns allocation; horizontal folds retain the normal flow. */
export function resolveDesktopDivisionLayout(input: {
geometry: WindowLayout | null;
windowWidth: number;
windowHeight: number;
leftInset: number;
rightInset: number;
}): DesktopDivisionLayout | null {
const { geometry, windowWidth, windowHeight, leftInset, rightInset } = input;
if (
!geometry ||
Math.abs(geometry.bounds.width - windowWidth) > 0.5 ||
Math.abs(geometry.bounds.height - windowHeight) > 0.5
)
return null;
const divisions = geometry.divisions.filter(
(frame) =>
frame.width > 0 &&
frame.height > frame.width &&
frame.y < windowHeight &&
frame.y + frame.height > 0,
);
if (divisions.length !== 1) return null;
const division = divisions[0];
const sidebarWidth = division.x - leftInset;
const contentWidth = windowWidth - rightInset - division.x - division.width;
if (sidebarWidth <= 0 || contentWidth <= 0) return null;
return { sidebarWidth, gap: division.width, contentWidth };
}
@@ -0,0 +1,64 @@
import { useMemo, type ReactNode } from "react";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { useWindowLayout } from "./context";
import { resolveWorkspaceActionPlacement, type DesktopDivisionLayout } from "./model";
/** Consume horizontal safe areas once, including compact content beside a vertical bar. */
export function WindowLayoutSurface({
children,
compact,
style,
}: {
children: ReactNode;
compact: boolean;
style: StyleProp<ViewStyle>;
}) {
const insets = useSafeAreaInsets();
const usesBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
const surfaceStyle = useMemo(
() => [
style,
(!compact || usesBar) && { paddingLeft: insets.left, paddingRight: insets.right },
],
[style, compact, usesBar, insets.left, insets.right],
);
const contentInsets = useMemo(
() => (compact && usesBar ? { ...insets, left: 0, right: 0 } : insets),
[compact, usesBar, insets],
);
return (
<View style={surfaceStyle}>
<SafeAreaInsetsContext.Provider value={contentInsets}>
{children}
</SafeAreaInsetsContext.Provider>
</View>
);
}
export function WindowLayoutDivisionGap({
layout,
sidebarVisible,
compact,
}: {
layout: DesktopDivisionLayout | null;
sidebarVisible: boolean;
compact: boolean;
}) {
const style = useMemo(
() => ({
width: layout ? layout.gap + (sidebarVisible ? 0 : layout.sidebarWidth) : 0,
}),
[layout, sidebarVisible],
);
return !compact && layout ? <View style={[styles.divisionGap, style]} /> : null;
}
const styles = StyleSheet.create((theme) => ({
divisionGap: {
backgroundColor: theme.colors.surfaceSidebar,
borderRightWidth: 1,
borderRightColor: theme.colors.border,
},
}));
@@ -27,7 +27,7 @@ import { planWorkspaceOpenTargets } from "@/workspace/open-in-editor/planner";
import type { Theme } from "@/styles/theme";
import { ForgeBrandIcon } from "@/git/forge-icon";
import { getForgePresentation } from "@/git/forge";
import { CONTROL_HEIGHTS, HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { extraMutedIconColorMapping } from "@/components/ui/icon-button-chrome";
interface WorkspaceOpenInEditorButtonProps {
@@ -297,10 +297,7 @@ const styles = StyleSheet.create((theme) => ({
flexShrink: 0,
},
splitButton: {
height: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
height: HEADER_CONTROL_HEIGHT,
flexDirection: "row",
alignItems: "stretch",
borderRadius: theme.borderRadius.md,
@@ -317,10 +314,7 @@ const styles = StyleSheet.create((theme) => ({
position: "relative",
},
splitButtonPrimaryIconOnly: {
width: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
width: HEADER_CONTROL_HEIGHT,
paddingHorizontal: 0,
justifyContent: "center",
position: "relative",
@@ -348,10 +342,7 @@ const styles = StyleSheet.create((theme) => ({
transform: [{ scale: 0.8 }],
},
splitButtonCaret: {
width: {
xs: CONTROL_HEIGHTS.sm,
md: HEADER_CONTROL_HEIGHT,
},
width: HEADER_CONTROL_HEIGHT,
alignItems: "center",
justifyContent: "center",
borderLeftWidth: theme.borderWidth[1],
@@ -1,4 +1,5 @@
import { lightHighlightColors } from "@getpaseo/highlight";
import { lightTheme } from "../src/styles/theme";
const testTheme = {
colorScheme: "light",
@@ -26,6 +27,7 @@ const testTheme = {
surface1: "#fafafa",
surface2: "#f4f4f5",
surface3: "#e4e4e7",
surfaceSidebar: lightTheme.colors.surfaceSidebar,
border: "#e4e4e7",
borderAccent: "#a1a1aa",
palette: {
@@ -454,6 +454,34 @@ second line'`,
).toThrow("Fork from a later completed response");
});
it("forks from a checkpoint when a plugin card was updated after it", () => {
const card = (seq: number, turns: number) =>
row(seq, {
type: "plugin",
id: "memory-receipt",
pluginId: "memorise",
kind: "memory-receipt",
version: 1,
data: { turns },
});
const result = buildAgentForkContextAttachment({
boundaryMessageId: "assistant-1",
rows: [
row(1, { type: "user_message", text: "First question", messageId: "user-1" }),
card(2, 1),
row(3, { type: "assistant_message", text: "First answer.", messageId: "assistant-1" }),
row(4, { type: "user_message", text: "Second question", messageId: "user-2" }),
row(5, { type: "assistant_message", text: "Second answer.", messageId: "assistant-2" }),
card(6, 2),
],
});
expect(result.attachment.text).toContain("[User] First question");
expect(result.attachment.text).toContain("[Assistant] First answer.");
expect(result.attachment.text).not.toContain("Second question");
expect(result.attachment.text).not.toContain("memory-receipt");
});
it("selects a synthetic assistant error by its timeline cursor", () => {
const result = buildAgentForkContextAttachment({
cursorBoundary: {
@@ -13,6 +13,12 @@ const MAX_TOOL_SUMMARY_CHARS = 200;
const MAX_FORK_CONTEXT_CHARS = 100_000;
const MAX_FORK_METADATA_CHARS = 1_000;
const FORK_HISTORY_OMITTED = "[Earlier chat history omitted]\n";
// A fork copies only these kinds, so only they can make a checkpoint stale.
const FORK_CONTEXT_KINDS: readonly AgentTimelineItem["type"][] = [
"user_message",
"assistant_message",
"tool_call",
];
interface ActivityCuratorOptions {
maxItems?: number;
@@ -269,7 +275,14 @@ function selectForkContextRows(input: {
);
}
const boundarySeq = projectedRows[boundaryIndex].seqEnd;
if (projectedRows.some((row) => row.seqStart <= boundarySeq && row.seqEnd > boundarySeq)) {
if (
projectedRows.some(
(row) =>
FORK_CONTEXT_KINDS.includes(row.item.type) &&
row.seqStart <= boundarySeq &&
row.seqEnd > boundarySeq,
)
) {
throw new Error(
"This checkpoint changed after it was created. Fork from a later completed response instead.",
);
@@ -349,7 +362,7 @@ export function buildAgentForkContextAttachment(input: {
const entries = curateProjectedActivityEntries(selected.items, {
maxItems: 0,
labelAssistantMessages: true,
includeKinds: ["user_message", "assistant_message", "tool_call"],
includeKinds: FORK_CONTEXT_KINDS,
includeExternalToolInput: false,
});
const metadata = { agentTitle: input.agentTitle, cwd: input.cwd };
@@ -1,12 +1,13 @@
import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
import {
createAgentMessageDelivery,
prepareAgentMessage,
formatAgentMessage,
formatSystemNotificationPrompt,
} from "./agent-messages/index.js";
import { expect, test, vi, onTestFinished } from "vitest";
import { spawn } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { randomUUID } from "node:crypto";
@@ -1394,6 +1395,103 @@ test("orders a concurrent replacement after a pending accepted steer", async ()
}
});
test.each(["before dispatch", "during fallback", "during provider admission"])(
"diagnostic #8679: retains queued steer when the turn completes %s",
async (timing) => {
const entered = deferred<void>();
const release = deferred<void>();
class CompletingSteerSession extends SteeringTestSession {
override async steerActiveTurn(
prompt: AgentPromptInput,
options: import("./agent-sdk-types.js").SteerActiveTurnOptions,
): Promise<import("./agent-sdk-types.js").SteerResult> {
if (timing === "during provider admission") {
this.pushEvent({
type: "turn_completed",
provider: "codex",
turnId: options.expectedTurnId,
});
return { status: "unavailable" };
}
return super.steerActiveTurn(prompt, options);
}
}
const session = new CompletingSteerSession({ provider: "codex", cwd: process.cwd() });
session.steerResult = "unavailable";
const artifacts = join(process.cwd(), ".artifacts");
mkdirSync(artifacts, { recursive: true });
const workdir = mkdtempSync(join(artifacts, "steer-completion-"));
const manager = new AgentManager({
clients: {
codex: new (class extends TestAgentClient {
override async createSession() {
return session;
}
})(),
},
beforeSteerUnavailableFallback: async () => {
if (timing === "during fallback") {
entered.resolve();
await release.promise;
}
},
logger,
});
let flush = () => {};
const errors: unknown[] = [];
const delivery = createAgentMessageDelivery({
schedule: (_delay, callback) => {
flush = callback;
return () => {};
},
dispatch: async (batch) => {
const result = await startAgentRun(manager, batch.recipientId, batch.prompt, logger, {
activeTurnBehavior: batch.activeTurnBehavior,
replaceRunning: true,
runOptions: { clientMessageId: batch.messageIds[0] },
});
return result.disposition;
},
onError: (error) => {
errors.push(error);
},
});
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
const run = manager.streamAgent(agent.id, "initial");
const consumed = drainAsyncGenerator(run);
await manager.waitForAgentRunStart(agent.id);
const receipt = delivery.enqueue({
recipientId: agent.id,
messageId: "completion-race",
source: { kind: "agent-message", agentId: "sender" },
prompt: "Answer OK after the current turn",
});
expect(receipt.status).toBe("queued");
if (timing !== "before dispatch") flush();
if (timing === "during fallback") await entered.promise;
if (timing !== "during provider admission") {
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" });
}
await consumed;
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
if (timing === "before dispatch") flush();
release.resolve();
await expect(receipt.dispatched).resolves.toBe("turn_started");
expect(errors).toEqual([]);
await manager.waitForAgentRunStart(agent.id);
expect(session.startCount).toBe(2);
} finally {
release.resolve();
await delivery.close();
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
},
);
test("does not replace a newer foreground turn after unavailable steer fallback is admitted", async () => {
const entered = deferred<void>();
const release = deferred<void>();