Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 3777cc754b Keep mobile sheet footers above the system bar during keyboard transitions (#10827)
* fix(app): keep sheet footer safe-area clearance in lockstep with keyboard transitions

Bottom sheet visible height and bottom safe-area clearance were owned by two
separate keyboard signals on different threads: SheetVisibleFrame shrunk and
restored height on the UI thread from Gorhom's animatedKeyboardState (driven by
React Native Keyboard events), while AdaptiveModalSheet toggled
footerPaddingBottom on the JS thread from useKeyboardVisibility (driven by
react-native-keyboard-controller's keyboardWillShow and keyboardDidHide).

On keyboard close, SheetVisibleFrame restored full height at animation start
while footerPaddingBottom stayed 0 until keyboardDidHide fired after the
animation ended (~200ms later), leaving the footer visibly behind the system
navigation bar before snapping back up. On Android open, SheetVisibleFrame
shrank before the JS commit cleared safe-area padding, producing a 1-frame
upward overshoot by the nav-bar inset.

Move bottom safe-area clearance into SheetVisibleFrame (and a shared UI-thread
hook for scrollable footerless bodies) using the same effective keyboard height
that sizes the frame, keeping height and paddingBottom atomic in one commit and
removing the now-unused useKeyboardVisibility hook and sheet layout helper.

* test(app): replace JSDOM visible-frame test with Android frame-by-frame regression check

Removes the JSDOM + module-mock test in visible-frame.test.tsx per docs/testing.md
and adds a native Android screenrecord regression runner and frame analyzer under
packages/app/e2e/mobile/modal-sheet/ that verifies every frame of the Add project
footer across keyboard show/hide cycles (catching both the behind-nav-bar drop on
dismiss and the 1-frame upward overshoot on open on the parent commit).

* test(app): check absolute nav-bar clearance and keep device settings untouched in sheet footer QA script
2026-11-26 00:30:55 +07:00
Mohamed Boudra 7708e1f084 Drag agent profiles to reorder on phones, with cleaner rows and a one-line options row (#10824)
* fix(app): drag agent profiles on phones and tidy their rows

On a phone, holding a profile's grip and dragging scrolled the page instead
of moving the row. A native drag arms after a short hold and asks the nearest
scroll view to stop scrolling through the content-drag context, but only the
sheet scroll view provided that context. Usage cards live in a sheet, so they
dragged; agent profiles live on a page, so the page scroll took the touch past
the touch slop before the list's pan activated. Page scroll views now host
content drags too (withContentDrag, used by ScrollView outside a sheet and by
PageLayout). docs/drag-reorder.md records the pattern.

Settings rows with a long summary, such as the profile sheet's options row,
grew several lines tall on a phone: the label column has a zero flex basis, so
the summary squeezed it and the label wrapped. A label-only row now keeps the
label's width and truncates the summary in the remaining space.

Profile rows hang the grip in the leading padding like a Usage card, keep the
kebab on the trailing rail, and drop the repeated provider icon and the
chevron from the stacked phone layout.

* fix(app): keep scroll children intact and summaries beside their chevrons

The content-drag context sat between a scroll view and its children, so a
native scroll view saw one child and stickyHeaderIndices pinned nothing. The
context now wraps the scroll view instead. Content drag gets its own module,
content-drag.tsx, with one withContentDrag for both page and sheet scroll
views, so the browser tests can lock the scroll lock and the child pass-through.

A label-only settings row whose label column reached its 75% cap left the rest
of the row to space-between, which pushed short summaries and controls away
from the chevron on wide pages. The column's auto right margin now takes it.
2026-11-26 00:25:17 +07:00
Mohamed Boudra ba45634eee Select sidebar workspaces with Cmd/Ctrl+click and Finder-style Shift ranges (#10821)
* feat(app): select sidebar workspaces with Cmd/Ctrl+click and Finder-style Shift ranges

Cmd+click on macOS/iOS (Ctrl+click on Windows, Linux and Android) now enters
select mode on the clicked row and toggles rows without opening them, matching
Shift+click entry. The first modifier click selects only the clicked row and
never includes the open workspace, so starting a bulk archive from another row
cannot mark the workspace you are reading.

Shift+click now rebuilds the range from the anchor on every click instead of
only adding to it, so a closer Shift+click shrinks the range and crossing the
anchor flips it. Rows picked before the current Shift run are kept, and a
Cmd/Ctrl or plain click moves the anchor and commits the range.

The primary modifier follows the shortcut layer's `mod` (Meta on mac, Control
elsewhere) because Ctrl+click on macOS is the secondary click. The held-key
tracker now follows Cmd and Ctrl as well as Shift, since native responder
events from a hardware keyboard carry no modifier flags. Both sidebar lists
share one press hook instead of duplicating the routing.

* fix(app): select on the first tap after a scroll or long press in the sidebar

A scroll, swipe, drag, or long-press menu on a workspace row sets the row's
long-press flag, and only the drag interaction's press-in clears it. Modifier
taps and select-mode taps skip that press-in, so the stale flag swallowed the
next Shift/Cmd/Ctrl tap on native hardware keyboards, and the next plain tap
in select mode. Those presses never arm the long-press gesture, so the
selection press hook now clears the flag when it takes the press-in.

* fix(app): keep web context-menu rows clickable after a held press

On web, ContextMenuTrigger always handed react-native-web an onLongPress,
even though the web menu opens on right-click and the handler did nothing
there. With any onLongPress set, react-native-web marks a press held past
the long-press delay as a long press and cancels the click that ends it.
Only the next responder grant clears that mark, and react-native-web grants
none to Ctrl or Alt mousedowns. So a slow click on a sidebar row did not open
it, and on Windows/Linux the next Ctrl+click on that row was dropped too.

On web the trigger now passes only the caller's onLongPress.

* fix(app): stop selecting presses from reading the row's long-press flag

The selection press path cleared and honored the row's long-press flag, but
only the drag interaction's press-in resets that flag. A Ctrl+click on web
gets no press-in, so a flag left by an earlier touch swipe or scroll on the
row swallowed it. Selecting presses never arm the long-press gesture, and a
native long press already cancels the press, so the selection path no longer
reads the flag at all. Navigation keeps its own guard.
2026-11-26 00:20:49 +07:00
5c82a2e999 Keep a reloaded plugin's agent tools working for a busy agent (#10106)
* fix(server): keep a restarted plugin's agent tools on live sessions

A plugin restart (reload, update) gives the plugin a new instance id.
Tools attached to an open session are stamped with the old one, so
getPluginTools filters them out and the agent MCP neither lists nor
serves them ("Tool ... not found"). They came back only when the session
reopened, which happens before a prompt to an idle agent; messages to a
busy agent are steered or replace the run on the stale session, so a
busy agent could go without its plugin tools for as long as it stayed
busy.

The agent MCP now reattaches them before it builds a request's catalog:
AgentManager remembers the request a session opened with, and for
plugins whose instance changed it replays agent.open.before to those
plugins only and keeps only the tools they return. Env and MCP server
changes still wait for the reopen, which is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): keep stopped plugins eligible and guard tool replays

- A plugin that is stopped or mid-restart during an MCP request keeps its old
  attachment, so a later request retries it instead of losing its tools.
- A reopen waits for an in-flight replay, so the replay cannot overwrite the
  reopen's tool definitions inside the plugin process.
- Refreshed tools that collide with a Paseo tool or another plugin's tool are
  dropped for that plugin instead of breaking the agent's whole catalog.

* fix(server): retry a plugin whose tool replay failed

A failed replay is left out of the result like a stopped plugin, so the
agent's next MCP request retries it instead of dropping its tools until the
session reopens. The reopen race test now waits for the replay to reach its
gate before it starts the reopen.

* fix(server): replay a restarted plugin's open once per instance, as refresh

A replay whose hook threw or timed out ran again on every agent MCP
request, so each Paseo tool call waited on the broken plugin. The
runtime now remembers the instance that failed and replays it only
after the next restart.

The replay now arrives with reason "refresh", like the idle reopen the
same restart causes, so plugins no longer see "create" again.

An open waits until no replay is pending before it detaches, and a
replay that outlives its session detaches only the plugins it replayed.

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): keep no replay failure record for a closed agent

The replay takes the agent's record when it starts and writes a failure
into that record. Closing the agent drops it, so a replay that fails
afterwards no longer leaves an entry behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(plugins): say native-tool agents keep launch-time tools until the reopen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): reserve provider-disabled Paseo tool names in a tool replay

A replayed plugin tool named after a Paseo tool that the agent's provider
disables was accepted, and every later agent MCP request then failed on
the plugin collision check. The replay now builds its reserved names with
an all-enabled policy, the same names that check reserves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): reopen only sessions a plugin change affects

A plugin reload bumped one global session-open generation, so every live
agent reopened at its next idle prompt. The reopen closes the provider
session, cancels its subagents and clears background work, even for agents
the plugin never touched.

SessionAttachments now owns what each agent.open.before plugin contributed
to each live session. A refresh reruns only the plugins whose instance
changed, swaps their tools in place, and marks the session stale only when
its launch would differ. This replaces the AgentManager maps, the runtime's
failed-replay record, and the global generation. Native-tool providers
resolve plugin tools by name at call time, so their calls reach the new
instance.

* fix(server): compare plugin refreshes with the running launch

A plugin refresh decided staleness against the last refresh with a sticky
flag, so reverting a tool edit still reopened the session. A failed reopen
also deleted the session's plugin record while the old provider session kept
running, which left it without any plugin tools.

SessionAttachments now keeps the contributions the session launched with as
the baseline and works out staleness against it on every refresh. A failed
rerun or collision is kept on that plugin's contribution. A failed open keeps
the running session's record and marks its plugins for reattach on the next
refresh.

A launch-time native catalog entry now resolves the tool by plugin id and
name, so a different plugin that took the name is never called.

* fix(server): make a plugin open the baseline only once its launch takes over

A reopen whose plugin hooks succeed can still fail launch validation: a
plugin tool that takes a Paseo tool name, or an MCP server on a provider
without MCP support. The open had already replaced the session's record, so
the session lost its plugin tools, or kept a record for a launch that never
ran, and the next idle prompt did not retry.

An interactive open now stays pending until registerSession reports that the
provider launch took over. A launch that fails before then discards the
pending open, and the still-running session keeps its record. Its plugins
attach their tools again on the next refresh, and each idle prompt retries
the reopen.

* fix(server): discard a reload's plugin open on every pre-takeover rejection

resolveProviderLaunchConfig rejects a plugin MCP server that takes a saved
server name after the open is staged, and nothing discarded the staged open.
The reload now resolves and validates its launch config in one scope that
discards the staged open on any rejection, so the running session keeps its
plugin tools and the next idle prompt retries the reopen.

* fix(server): keep a tool name with its owner when a refresh replays every plugin

After a rejected reopen, every plugin replays on the next refresh, and the
collision check gave a contested name to whichever plugin sorted first. A name
now stays with the plugin that has it in the session's record, as long as that
plugin still returns the tool.

* fix(server): rerun a refreshed plugin callback with the agent's current metadata

A plugin reload used to reopen every session, so its callback saw the agent's
current title, workspace, labels, and metadata. A refresh now replays the
recorded open request instead, so a hook that filters on metadata set after
launch kept returning nothing. The refresh now overlays those agent fields,
which plugins cannot change, on the recorded request.

* fix(server): replay the plugin chain in order, hold refreshes over a plugin restart, and roll back every failed launch's plugin open

- A cached plugin contribution is reused only when its instance and the env and instructions it received still match; otherwise the plugin reruns in open order and the composed launch is compared with the running one.
- A plugin reload or source update publishes one settled change: a session refresh waits for the restart instead of reading the stop as removal.
- Create, resume, import, and reopen share one launch boundary: the pending plugin open commits when registerSession admits the agent and is discarded when the launch throws before that.

* fix(server): decide a plugin reopen from the same launch the open builds

The open and the refresh now compose the launch with one function. The staleness check compares which plugin provides each tool, so a native-tool catalog bound to a removed plugin reopens, and a proposed launch with an MCP server name collision counts as changed, so the reopen reports it.

* fix(server): reserve only Paseo's own tool names when a plugin refresh checks collisions

The agent's catalog also lists its plugin tools, so a later plugin rerun by an earlier plugin's edit saw its own tool as taken and lost it. The session owner settles names between plugins from its record. The hooks reference now says an MCP server name collision fails the reopen without hiding tools.

* fix(plugins): let a refreshed plugin's running tool calls finish

The plugin process detached the session's tools at the start of every agent.open.before, which aborted calls already running. Attaching replaces the definitions for later calls; the daemon still detaches before an open that replaces the provider session.

---------

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 16:51:40 +01:00
Mohamed Boudra 60943dde1c Return focus to the prompt after choosing a New Workspace field (#10632)
* fix(app): return focus to the composer after choosing a New Workspace field

A closing picker restored focus to whatever had focus when it opened. Opening
the project picker by clicking its trigger left focus on the trigger after a
keyboard pick, and every later Cmd/Ctrl+N pick captured the trigger again, so
the user had to click back into the prompt.

The New Workspace form now passes the composer as the restore target for its
pickers. The overlay accepts any handle with focus() as a restore target, so
the composer's own retrying focus can be used instead of a raw DOM element.

* fix(app): keep focus on the field when the terminal profile takes no prompt

A terminal profile without a prompt shows a read-only command preview, so there
is nothing to type into. Its pickers now fall back to returning focus to the
field that opened them instead of losing focus to the preview.
2026-11-25 22:14:42 +07:00
Mohamed Boudra e52bb6e3c4 Select multiple sidebar workspaces to archive together (#10798)
* feat(app): select multiple sidebar workspaces to archive together

Let users enter workspace select mode from Shift+click/tap or the row menu, toggle additional rows with plain clicks without holding Shift, extend ranges with Shift+click, and archive all selected workspaces in one batch with a single worktree warning and undo toast.

Tracks live hardware Shift state in the keyboard pipeline (clearing on blur and AppState backgrounding) so Shift+tap and Shift+click also work on native tablets with hardware keyboards where Pressable responder events omit shiftKey. Adds an action layout variant on ToastCard so pill controls inside action toasts share concentric padding and radius.

* fix(app): preserve batch undo and selection ownership during bulk archive

Keep workspace.archive bound for the full lifetime of sidebar select mode so pressing it at 0 selected or during a worktree check does not fall through to archive the open workspace.

On partial archive failures, update the open UndoWindow toast in place with error styling and the failure message instead of calling toast.error, so Undo and Cmd/Ctrl+Z remain available for succeeded workspaces and their layout state is not purged early.

Guard isArchiving cleanup with a per-attempt token so an earlier batch cannot unlock a newer batch's worktree check, and read the active workspace lazily at redirect time rather than capturing it at submission.

* fix(app): stack sidebar selection bar below toasts and protect newer undo

Keep the sidebar selection bar visible alongside active transient toasts (such as Undo or error toasts) by rendering both slots in ToastViewport's sidebar stack instead of hiding the persistent bar while a transient toast is open.

Route late archive errors from a superseded batch to the app-level toast when a newer batch holds an open Undo window, so an older failure does not replace the active Undo toast or purge the newer batch's layout state.

* fix(app): toggle focused sidebar workspace checkboxes with Space on web

React Native Web's Pressable activates Space only for role='button', not role='checkbox'. Handle Space on focused checkbox rows in SidebarWorkspaceContextMenu so keyboard users can toggle rows in either sidebar grouping.

* fix(app): ignore repeated Space keydown on focused workspace checkboxes

* fix(app): keep Escape owned by select mode during worktree checks
2026-11-25 22:11:10 +07:00
85 changed files with 5671 additions and 664 deletions
+1
View File
@@ -36,6 +36,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | The binding table, per-platform key sources, badges vs routing, iOS `UIKeyCommand` limits |
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
+34
View File
@@ -0,0 +1,34 @@
# Drag to reorder
A list the user can reorder renders through `DraggableList` from `@/components/draggable-list`. Each row puts a `DraggableListHandle` where its grip is drawn. The Usage cards (`packages/app/src/usage/list.tsx`, `packages/app/src/usage/card.tsx`) and the agent profile roster (`packages/app/src/agent-profiles/settings/`) are the reference.
| Platform | How a drag starts |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Web | dnd-kit pointer drag. With `useDragHandle`, only the handle starts it, and the handle reorders by keyboard. Without it, the whole row starts it. |
| Native | Hold the handle for 180 ms without moving more than 4 px. The list then owns the touch until the finger lifts. |
## The scroll view must host the drag
On native, the hold calls `drag()`, which calls `useContentDrag().setActive(true)` from `@/components/ui/content-drag` on the nearest scroll view. That scroll view stops scrolling until the drag ends. If no scroll view up the tree hosts content drags, `setActive` does nothing. The page scroll then takes the touch as soon as the finger moves past the touch slop, before the list's own pan activates. The row never moves, and the page scrolls instead.
These scroll views host content drags:
- `ScrollView` from `@/components/ui/scroll-view`, inside and outside a sheet.
- `PageLayout`, for a settings page or any other full page.
If you put a reorderable list in another scroll view, such as a third-party keyboard-aware one, wrap it with `withContentDrag` from `@/components/ui/content-drag`. `packages/app/src/components/page-layout/index.tsx` shows the pattern. A plain `ScrollView` from `react-native` breaks the drag.
Inside a sheet, the `ScrollView` also registers the drag gesture with the sheet, so the sheet's pan-to-close waits for it.
## Where the grip goes
The grip hangs in the row's leading padding, absolutely positioned over the full row height. The row's content keeps the same left rail as rows that cannot be reordered, and the grip does not take a column. On a pointer device the grip shows on hover, focus, or while dragging. On touch and compact layouts it always shows, because there is no hover.
## Test with a page that scrolls
A list that fits on the screen does not show the bug, because the page has nothing to scroll. Test on a phone with enough rows that the page scrolls. Then check both directions:
1. Hold the grip and drag a row past two others. The new order is saved.
2. Swipe quickly on a row body. The page scrolls and the order stays the same.
On an Android emulator, `adb shell input swipe` does not hold still long enough to arm the drag. Send `input motionevent DOWN`, wait 500 ms, then send `MOVE` events and `UP`.
+1 -1
View File
@@ -465,7 +465,7 @@ in a tab. An overlay opened from that content and calling `useSafeAreaInsets()`
gets that 0 and draws over the navigation bar.
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
`CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`.
`SheetVisibleFrame` (used by `CompactSheetBody` and `ComboboxSheetFrame`) and `MenuSheetScrollView`.
- An RN `Modal` passes the call site's context straight through, so wrap its content in
`WindowSafeArea` from `@/window-layout` and read the inset below that. It provides the insets of
the whole window, published by `WindowLayoutProvider`. Do not put a `SafeAreaProvider` inside the
+4
View File
@@ -464,6 +464,10 @@ registry property, independent of position. The [hooks reference](../public-docs
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
the provider process, so a reload must not reopen agents the plugin does not change.
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
@@ -1,6 +1,7 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
chooseProjectWithKeyboard,
connectNewWorkspaceDaemonClient,
expectNewWorkspaceControlsEnabled,
expectNewWorkspaceProjectSelected,
@@ -176,6 +177,33 @@ test.describe("New workspace entry points", () => {
}
});
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
page,
}) => {
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
try {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openGlobalNewWorkspaceComposer(page);
const composer = page.getByRole("textbox", { name: "Message agent..." });
await page.getByTestId("new-workspace-project-picker-trigger").click();
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
await expect(composer).toBeFocused();
await page.keyboard.press("Control+N");
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
await expect(composer).toBeFocused();
} finally {
await projectA.cleanup();
await projectB.cleanup();
}
});
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
page,
}) => {
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import {
chooseProjectWithKeyboard,
expectNewWorkspaceDraft,
fillNewWorkspaceDraft,
openNewWorkspaceComposer,
@@ -109,6 +110,27 @@ test.describe("New workspace: launching a terminal", () => {
});
});
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
page,
}) => {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: workspace.projectKey,
projectDisplayName: workspace.projectDisplayName,
});
await selectLaunchOption(page, BARE_PROFILE.id);
await expect(terminalPromptInput(page)).toHaveCount(0);
// The read-only command preview has nothing to type into, so the picker
// hands focus back to the field that opened it.
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
await projectTrigger.focus();
await page.keyboard.press("Enter");
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
await expect(projectTrigger).toBeFocused();
});
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
page,
}) => {
@@ -0,0 +1,121 @@
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { getServerId } from "../support/helpers/server-id";
import { seedWorkspace } from "../support/helpers/seed-client";
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
// Cmd on macOS, Ctrl on Windows and Linux: the platform primary modifier the app binds as `mod`.
const MOD = "ControlOrMeta";
type SeededProject = Awaited<ReturnType<typeof seedWorkspace>>;
async function seedProjectWithWorkspaces(count: number) {
const project = await seedWorkspace({ repoPrefix: "sidebar-selection-" });
const workspaceIds = [project.workspaceId];
for (let index = 1; index < count; index += 1) {
const created = await project.client.createWorkspace({
source: { kind: "directory", path: project.repoPath, projectId: project.projectId },
title: `Selection workspace ${index}`,
});
if (!created.workspace) throw new Error(created.error ?? "Failed to seed a workspace");
workspaceIds.push(created.workspace.id);
}
return { project, workspaceIds };
}
/** The seeded rows, in the order the sidebar shows them. */
async function rowsInSidebarOrder(page: Page, workspaceIds: readonly string[]) {
const testIds = workspaceIds.map((id) => `sidebar-workspace-row-${getServerId()}:${id}`);
const rows = page.locator(testIds.map((testId) => `[data-testid="${testId}"]`).join(", "));
await expect(rows).toHaveCount(workspaceIds.length);
const ordered = await rows.evaluateAll((elements) =>
elements.map((element) => element.getAttribute("data-testid") ?? ""),
);
return ordered.map((testId) => page.getByTestId(testId));
}
async function expectChecked(rows: readonly Locator[], checked: readonly boolean[]) {
for (const [index, row] of rows.entries()) {
await expect(row).toHaveAttribute("aria-checked", String(checked[index]));
}
}
async function expectSelectedCount(page: Page, count: number) {
await expect(page.getByTestId("workspace-selection-count")).toHaveText(`${count} selected`);
}
async function exitSelection(page: Page) {
await page.getByTestId("workspace-selection-exit").click();
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
}
/**
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
*/
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
const [first, second, third, fourth] = rows;
await first.click();
await expect(first).toHaveAttribute("aria-selected", "true");
const openWorkspaceUrl = page.url();
await third.click({ modifiers: [MOD] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]);
await fourth.click({ modifiers: [MOD] });
await expectChecked(rows, [false, false, true, true]);
await third.click({ modifiers: [MOD] });
await expectChecked(rows, [false, false, false, true]);
await second.click();
await expectChecked(rows, [false, true, false, true]);
expect(page.url()).toBe(openWorkspaceUrl);
await exitSelection(page);
await second.click({ modifiers: ["Shift"] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, true, false, false]);
await fourth.click({ modifiers: ["Shift"] });
await expectChecked(rows, [false, true, true, true]);
await third.click({ modifiers: ["Shift"] });
await expectChecked(rows, [false, true, true, false]);
await first.click({ modifiers: ["Shift"] });
await expectChecked(rows, [true, true, false, false]);
await fourth.click({ modifiers: [MOD] });
await third.click({ modifiers: ["Shift"] });
await expectChecked(rows, [true, true, true, true]);
expect(page.url()).toBe(openWorkspaceUrl);
await exitSelection(page);
}
test.describe("sidebar workspace selection clicks", () => {
let seeded: { project: SeededProject; workspaceIds: string[] } | null = null;
test.afterEach(async () => {
await seeded?.project.cleanup();
seeded = null;
});
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await selectSidebarStatusGrouping(page);
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
});
@@ -153,3 +153,25 @@ On iPad, replacing the field a second time appends text. For this Settings journ
native clipboard Paste menu, then continue the assertions manually. Dismiss the password keyboard
with Done to submit when the Connect button is below the keyboard. The welcome pairing regression
runs end to end without these adjustments.
## Sheet footer keyboard safe-area clearance
`footer-keyboard.android.sh` records the **Add project** sheet on an Android device or emulator
across repeated keyboard open/dismiss transitions, then runs `assert-sheet-footer-keyboard.mjs`
over every recorded frame. Configure three-button navigation, `show_ime_with_hard_keyboard=1`, and
a visible soft keyboard (such as Gboard) on the test device before running so the script does not
mutate device settings. The assertion checks both settled positions against the navigation bar
height and fails if any frame drops the **Open project** button into the navigation bar or
overshoots above its open-keyboard position.
```sh
ANDROID_SERIAL=emulator-5554 \
packages/app/e2e/mobile/modal-sheet/footer-keyboard.android.sh
```
You can also validate an existing screen recording directly (optionally passing pixel tolerance and
navigation bar height in pixels):
```sh
node packages/app/e2e/mobile/modal-sheet/assert-sheet-footer-keyboard.mjs /path/to/recording.mp4 4 96
```
@@ -0,0 +1,173 @@
import { execFileSync, spawnSync } from "node:child_process";
import process from "node:process";
const [, , videoPath, toleranceArg = "4", navBarHeightArg = "0"] = process.argv;
if (!videoPath) {
throw new Error(
"Usage: node assert-sheet-footer-keyboard.mjs <screenrecord.mp4> [pixel-tolerance] [nav-bar-height-px]",
);
}
const tolerance = Number(toleranceArg);
if (!Number.isFinite(tolerance) || tolerance < 0) {
throw new Error(`Invalid pixel tolerance: ${toleranceArg}`);
}
const navBarHeight = Number(navBarHeightArg);
if (!Number.isFinite(navBarHeight) || navBarHeight < 0) {
throw new Error(`Invalid navigation bar height: ${navBarHeightArg}`);
}
function probeDimensions(filePath) {
const output = execFileSync(
"ffprobe",
[
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height",
"-of",
"csv=s=x:p=0",
filePath,
],
{ encoding: "utf8" },
).trim();
const [width, height] = output.split("x").map(Number);
if (!width || !height) {
throw new Error(`Unable to read video dimensions for ${filePath}: ${output}`);
}
return { width, height };
}
function measureButtonBottomPerFrame(filePath, width, height) {
const centerX = Math.floor(width / 2);
// Decode only the 1px vertical centerline so full-rate recordings fit comfortably in memory.
const result = spawnSync(
"ffmpeg",
[
"-v",
"error",
"-i",
filePath,
"-vf",
`format=rgb24,crop=1:${height}:${centerX}:0`,
"-vsync",
"0",
"-f",
"rawvideo",
"-pix_fmt",
"rgb24",
"-",
],
{ maxBuffer: 64 * 1024 * 1024 },
);
if (result.status !== 0) {
throw new Error(`ffmpeg failed (${result.status}): ${result.stderr?.toString("utf8") ?? ""}`);
}
const buffer = result.stdout;
const frameSize = height * 3;
const frameCount = Math.floor(buffer.length / frameSize);
// Restrict vertical scan below the search field so its green focus ring is excluded.
const scanTop = Math.floor(height * 0.42);
const bottoms = [];
for (let frame = 0; frame < frameCount; frame += 1) {
const frameOffset = frame * frameSize;
let maxY = null;
for (let y = scanTop; y < height; y += 1) {
const offset = frameOffset + y * 3;
const r = buffer[offset];
const g = buffer[offset + 1];
const b = buffer[offset + 2];
// Matches the green primary "Open project" button (both enabled and disabled states).
if (g > 50 && g > r + 15 && g > b + 10) {
maxY = y;
}
}
bottoms.push(maxY);
}
return bottoms;
}
function findSettledValue(values, minRunLength) {
let runValue = null;
let runLength = 0;
for (const value of values) {
if (value !== null && runValue !== null && Math.abs(value - runValue) <= 2) {
runLength += 1;
if (runLength >= minRunLength) return runValue;
} else {
runValue = value;
runLength = value === null ? 0 : 1;
}
}
return null;
}
const { width, height } = probeDimensions(videoPath);
const bottoms = measureButtonBottomPerFrame(videoPath, width, height);
const visibleFrames = bottoms
.map((bottom, frame) => ({ frame, bottom }))
.filter((entry) => entry.bottom !== null);
if (visibleFrames.length < 10) {
throw new Error(
`Expected at least 10 frames with the Open project footer button visible, found ${visibleFrames.length}`,
);
}
// Identify settled resting (keyboard closed, lower on screen) and open (keyboard shown, higher on
// screen) positions by finding stable runs separated by at least 200px of keyboard height.
const minBottom = Math.min(...visibleFrames.map((entry) => entry.bottom));
const maxBottom = Math.max(...visibleFrames.map((entry) => entry.bottom));
const midpoint = (minBottom + maxBottom) / 2;
const closedSettled = findSettledValue(
bottoms.map((y) => (y !== null && y > midpoint ? y : null)),
15,
);
const openSettled = findSettledValue(
bottoms.map((y) => (y !== null && y < midpoint ? y : null)),
15,
);
if (closedSettled === null || openSettled === null || closedSettled - openSettled < 200) {
throw new Error(
`Recording did not capture settled keyboard-closed (${closedSettled}) and keyboard-open (${openSettled}) states`,
);
}
const maxAllowedBottom =
navBarHeight > 0
? Math.min(closedSettled + tolerance, height - navBarHeight)
: closedSettled + tolerance;
const belowNavViolations = visibleFrames.filter((entry) => entry.bottom > maxAllowedBottom);
const overshootViolations = visibleFrames.filter((entry) => entry.bottom < openSettled - tolerance);
if (belowNavViolations.length > 0 || overshootViolations.length > 0) {
const summary = [
`Sheet footer keyboard transition jank detected in ${videoPath}:`,
` settled closed bottom=${closedSettled}px (gap=${height - closedSettled}px), settled open bottom=${openSettled}px (gap=${height - openSettled}px), maxAllowedBottom=${maxAllowedBottom}px`,
];
if (belowNavViolations.length > 0) {
const worst = Math.max(...belowNavViolations.map((entry) => entry.bottom));
summary.push(
` dropped below safe-area clearance on ${belowNavViolations.length} frames (first=f${belowNavViolations[0].frame}, last=f${belowNavViolations.at(-1).frame}, worst bottom=${worst}px, excess=+${worst - maxAllowedBottom}px)`,
);
}
if (overshootViolations.length > 0) {
const worst = Math.min(...overshootViolations.map((entry) => entry.bottom));
summary.push(
` overshot above open keyboard position on ${overshootViolations.length} frames (first=f${overshootViolations[0].frame}, worst bottom=${worst}px, overshoot=-${openSettled - worst}px)`,
);
}
throw new Error(summary.join("\n"));
}
process.stdout.write(
`Sheet footer stayed within bounds across ${bottoms.length} frames (${visibleFrames.length} visible): closed=${closedSettled}px, open=${openSettled}px, maxAllowed=${maxAllowedBottom}px, 0 nav-bar overlap frames, 0 overshoot frames\n`,
);
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
set -euo pipefail
# Verifies that the Add project bottom sheet footer never flashes behind the Android system
# navigation bar on keyboard dismiss or overshoots upward on keyboard open.
#
# Prerequisites (configured on the test device before running):
# - Three-button navigation bar enabled (for example:
# `adb shell cmd overlay enable com.android.internal.systemui.navbar.threebutton`).
# - Software keyboard enabled when a hardware keyboard is attached (`show_ime_with_hard_keyboard=1`)
# and a visible soft keyboard (such as Gboard) selected as the active IME.
# - The Add project sheet already open with a connected host so the Open project footer button is
# visible.
# - `ffmpeg` and `ffprobe` on PATH.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERIAL="${ANDROID_SERIAL:-$(adb devices | awk '/\tdevice$/ {print $1; exit}')}"
OUT_DIR="${SHEET_FOOTER_QA_DIR:-/tmp/paseo-sheet-footer-qa}"
VIDEO_PATH="$OUT_DIR/sheet-footer-keyboard.mp4"
if [ -z "$SERIAL" ]; then
echo "No Android device attached. Set ANDROID_SERIAL or start an emulator." >&2
exit 1
fi
mkdir -p "$OUT_DIR"
# Derive tap coordinates and 3-button navigation bar height (48dp) from the active display metrics.
SIZE_LINE="$(adb -s "$SERIAL" shell wm size | tail -n 1 | tr -d '\r')"
DIMENSIONS="${SIZE_LINE##* }"
WIDTH="${DIMENSIONS%x*}"
HEIGHT="${DIMENSIONS#*x}"
DENSITY_LINE="$(adb -s "$SERIAL" shell wm density | tail -n 1 | tr -d '\r')"
DENSITY="${DENSITY_LINE##* }"
NAV_BAR_PX="${SHEET_FOOTER_NAV_BAR_PX:-$((48 * DENSITY / 160))}"
SEARCH_X=$((WIDTH / 2))
SEARCH_Y=$((HEIGHT * 34 / 100))
adb -s "$SERIAL" shell rm -f /sdcard/sheet-footer-keyboard.mp4
adb -s "$SERIAL" shell screenrecord --time-limit 9 --bit-rate 8000000 /sdcard/sheet-footer-keyboard.mp4 &
REC_PID=$!
sleep 0.8
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
sleep 1.8
adb -s "$SERIAL" shell input keyevent 4
sleep 1.8
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
sleep 1.8
adb -s "$SERIAL" shell input keyevent 4
wait "$REC_PID" || true
adb -s "$SERIAL" pull /sdcard/sheet-footer-keyboard.mp4 "$VIDEO_PATH" >/dev/null
node "$SCRIPT_DIR/assert-sheet-footer-keyboard.mjs" "$VIDEO_PATH" 4 "$NAV_BAR_PX"
@@ -243,6 +243,14 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
await expect(searchInput).toBeFocused();
}
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
const searchInput = page.getByPlaceholder("Search projects");
await expect(searchInput).toBeFocused({ timeout: 30_000 });
await page.keyboard.type(projectName);
await page.keyboard.press("Enter");
await expect(searchInput).toBeHidden({ timeout: 10_000 });
}
export async function expectNewWorkspaceProjectSelected(
page: Page,
projectDisplayName: string,
@@ -17,7 +17,12 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { DraggableListHandle } from "@/components/draggable-list";
import { useOpenKebabMenuVisibility } from "@/components/sidebar/use-open-kebab-menu-visibility";
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
import {
bySizing,
ICON_BUTTON_SIZES,
mapLayout,
TOUCH_TARGET,
} from "@/components/ui/control-geometry";
import {
DropdownMenu,
DropdownMenuContent,
@@ -41,11 +46,16 @@ import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
/** Shared column & rail geometry consumed by both RosterTableHeader and AgentProfileRow. */
export const ROSTER_COL_PROFILE_WIDTH = 184;
export const ROSTER_COL_RUNTIME_WIDTH = 248;
export const ROSTER_GRIP_WIDTH = bySizing({ touch: 28, pointer: 20 });
export const ROSTER_TRAILING_WIDTH = bySizing({ touch: TOUCH_TARGET + 14, pointer: 42 });
const ROW_MIN_HEIGHT = bySizing({ touch: TOUCH_TARGET + 16, pointer: 56 });
const GRIP_HANDLE_HEIGHT = bySizing({ touch: TOUCH_TARGET, pointer: 28 });
const KEBAB_GLYPH_SIZE = ICON_SIZE.sm;
// The kebab's hitbox is larger than its glyph; it overhangs the row so the glyph sits on the
// card's trailing rail and the hitbox does not make the row taller.
const KEBAB_HITBOX_OVERHANG = bySizing({
touch: (ICON_BUTTON_SIZES.small.touch - KEBAB_GLYPH_SIZE) / 2,
pointer: (ICON_BUTTON_SIZES.small.pointer - KEBAB_GLYPH_SIZE) / 2,
});
const ThemedGripVertical = withUnistyles(GripVertical);
const ThemedMoreVertical = withUnistyles(MoreVertical);
@@ -130,7 +140,7 @@ function AgentProfileRowMenu({
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
testID={`agent-profile-menu-${profileId}`}
>
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
<ThemedMoreVertical size={KEBAB_GLYPH_SIZE} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<DropdownMenuContent side="bottom" align="end" width={180}>
<DropdownMenuItem
@@ -231,16 +241,9 @@ function AgentProfileRowContent({
<Text style={styles.nameText} numberOfLines={1}>
{profile.name}
</Text>
<View style={styles.stackedSpecLine}>
<AgentProfileGlyph
provider={profile.provider}
serverId={serverId}
size={ICON_SIZE.xs}
/>
<Text style={styles.stackedSpecText} numberOfLines={1}>
{fullSummary}
</Text>
</View>
<Text style={styles.stackedSpecText} numberOfLines={1}>
{fullSummary}
</Text>
{profile.notes ? (
<Text
style={styles.stackedNotesText}
@@ -372,8 +375,8 @@ export function AgentProfileRow({
[dragging, isFirst, isHovered, menuProps.open, selected],
);
const gripVisibilityStyle = useMemo(
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
const gripStyle = useMemo(
() => (showRowAffordances ? styles.grip : [styles.grip, styles.affordanceHidden]),
[showRowAffordances],
);
const kebabVisibilityStyle = useMemo(
@@ -399,22 +402,6 @@ export function AgentProfileRow({
{selected ? <View style={styles.selectedIndicator} pointerEvents="none" /> : null}
{reorderable ? (
<View style={gripVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<DraggableListHandle
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
name: profile.name,
})}
style={styles.gripHandle}
testID={`agent-profile-drag-${profile.id}`}
>
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
</DraggableListHandle>
</View>
) : (
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
)}
<AgentProfileRowContent
serverId={serverId}
profile={profile}
@@ -425,7 +412,8 @@ export function AgentProfileRow({
isStacked={isStacked}
/>
<View style={styles.trailing}>
{/* A stacked row opens on tap like the wide one; the kebab alone ends it, on the trailing rail. */}
<View style={isStacked ? styles.trailingStacked : styles.trailing}>
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<AgentProfileRowMenu
profileId={profile.id}
@@ -442,13 +430,27 @@ export function AgentProfileRow({
onRemove={handleRemove}
/>
</View>
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevronRight
size={ICON_SIZE.sm}
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
/>
</View>
{isStacked ? null : (
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevronRight
size={ICON_SIZE.sm}
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
</View>
{reorderable ? (
<DraggableListHandle
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
name: profile.name,
})}
style={gripStyle}
testID={`agent-profile-drag-${profile.id}`}
>
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
</DraggableListHandle>
) : null}
</View>
);
}
@@ -460,8 +462,7 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
minHeight: ROW_MIN_HEIGHT,
paddingVertical: theme.spacing[3],
paddingLeft: theme.spacing[2],
paddingRight: theme.spacing[4],
paddingHorizontal: theme.spacing[4],
gap: theme.spacing[2],
},
rowHovered: {
@@ -491,19 +492,15 @@ const styles = StyleSheet.create((theme) => ({
passThrough: {
pointerEvents: "none",
},
gripSlot: {
width: ROSTER_GRIP_WIDTH,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
gripSpacerCompact: {
width: theme.spacing[2],
flexShrink: 0,
},
gripHandle: {
width: ROSTER_GRIP_WIDTH,
height: GRIP_HANDLE_HEIGHT,
// The grip hangs in the row's leading padding, as on a Usage card, so the icon tile sits on the
// card's rail with or without it and revealing it on hover moves nothing. It takes the padding's
// full height so a finger finds it.
grip: {
position: "absolute",
left: 0,
top: 0,
bottom: 0,
width: theme.spacing[4],
alignItems: "center",
justifyContent: "center",
},
@@ -585,12 +582,6 @@ const styles = StyleSheet.create((theme) => ({
minWidth: 0,
gap: theme.spacing[0.5],
},
stackedSpecLine: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
stackedSpecText: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
@@ -609,6 +600,11 @@ const styles = StyleSheet.create((theme) => ({
gap: theme.spacing[1],
flexShrink: 0,
},
trailingStacked: {
flexShrink: 0,
marginRight: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
marginVertical: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
},
kebabSlot: {
alignItems: "center",
justifyContent: "center",
@@ -44,7 +44,6 @@ import {
AgentProfileRow,
ROSTER_COL_PROFILE_WIDTH,
ROSTER_COL_RUNTIME_WIDTH,
ROSTER_GRIP_WIDTH,
ROSTER_TRAILING_WIDTH,
} from "./agent-profile-row";
@@ -90,7 +89,6 @@ function RosterTableHeader(): ReactElement {
const { t } = useTranslation();
return (
<View style={styles.tableHeader}>
<View style={styles.tableHeaderGripSpacer} />
<View style={styles.tableHeaderColumns}>
<Text style={[styles.tableHeaderText, styles.colProfileHeader]} numberOfLines={1}>
{t("settings.host.agentProfiles.columns.profile")}
@@ -1030,16 +1028,11 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
paddingVertical: theme.spacing[2],
paddingLeft: theme.spacing[2],
paddingRight: theme.spacing[4],
paddingHorizontal: theme.spacing[4],
gap: theme.spacing[2],
borderBottomWidth: theme.borderWidth[1],
borderBottomColor: theme.colors.border,
},
tableHeaderGripSpacer: {
width: ROSTER_GRIP_WIDTH,
flexShrink: 0,
},
tableHeaderColumns: {
flex: 1,
minWidth: 0,
@@ -1,48 +0,0 @@
import { describe, expect, it } from "vitest";
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
describe("getCompactSheetSafeAreaPadding", () => {
it("assigns safe clearance to the footer independently of decorative padding", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: false,
hasFooter: true,
safeAreaBottom: 34,
}),
).toEqual({ footerPaddingBottom: 34 });
});
it("assigns safe clearance to the body only without a footer", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: false,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({ contentPaddingBottom: 34 });
});
it("does not add a safe-area band above the compact keyboard", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: true,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({});
});
it("does not inset desktop sheets", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: false,
isKeyboardVisible: false,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({});
});
});
@@ -1,28 +0,0 @@
export interface CompactSheetSafeAreaPaddingInput {
isCompact: boolean;
isKeyboardVisible: boolean;
hasFooter: boolean;
safeAreaBottom: number;
}
export interface CompactSheetSafeAreaPadding {
contentPaddingBottom?: number;
footerPaddingBottom?: number;
}
export function getCompactSheetSafeAreaPadding({
isCompact,
isKeyboardVisible,
hasFooter,
safeAreaBottom,
}: CompactSheetSafeAreaPaddingInput): CompactSheetSafeAreaPadding {
if (!isCompact || isKeyboardVisible || safeAreaBottom <= 0) {
return {};
}
if (hasFooter) {
return { footerPaddingBottom: safeAreaBottom };
}
return { contentPaddingBottom: safeAreaBottom };
}
@@ -20,12 +20,11 @@ import {
IsolatedBottomSheetModal,
SheetVisibleFrame,
type ContextBridge,
useBottomSheetSafeAreaPaddingStyle,
useIsolatedBottomSheetVisibility,
} from "@/components/ui/isolated-bottom-sheet-modal";
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
import { ScrollView } from "@/components/ui/scroll-view";
import { isWeb } from "@/constants/platform";
import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
@@ -610,8 +609,9 @@ export interface SheetKeyboard {
}
/**
* The compact sheet's body. It renders on the far side of the sheet's portal so it reads the
* screen's bottom inset, not the one left where the sheet was opened: inside a sheet tab, none is.
* The compact sheet's body. It renders on the far side of the sheet's portal so `SheetVisibleFrame`
* and `useBottomSheetSafeAreaPaddingStyle` read the screen's bottom inset, not the one left where
* the sheet was opened: inside a sheet tab, none is.
*/
function CompactSheetBody({
header,
@@ -619,7 +619,6 @@ function CompactSheetBody({
onClose,
testID,
footer,
isKeyboardVisible,
scrollable,
bodyStyle,
contentStyle,
@@ -630,32 +629,18 @@ function CompactSheetBody({
onClose: () => void;
testID?: string;
footer: ReactNode;
isKeyboardVisible: boolean;
scrollable: boolean;
bodyStyle?: StyleProp<ViewStyle>;
contentStyle?: StyleProp<ViewStyle>;
children: ReactNode;
}) {
const insets = useSafeAreaInsets();
const { contentPaddingBottom = 0, footerPaddingBottom = 0 } = getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible,
hasFooter: Boolean(footer),
safeAreaBottom: insets.bottom,
});
// Safe-area clearance is a separate layer: it must not replace the caller's
// padding (including an explicit zero), and the footer owns it when present.
const bodyClearanceStyle = { paddingBottom: contentPaddingBottom };
const footerClearanceStyle = useMemo(
() => ({ paddingBottom: footerPaddingBottom }),
[footerPaddingBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerClearanceStyle}>{footer}</View> : null),
[footer, footerClearanceStyle],
);
// Safe-area clearance is owned on the UI thread in lockstep with `SheetVisibleFrame`'s keyboard
// height: `SheetVisibleFrame` pads the frame whenever a footer or non-scrollable body is shown,
// while a scrollable body without a footer pads its scroll content so items scroll behind the
// system bar and still clear it at rest.
const bodyClearanceStyle = useBottomSheetSafeAreaPaddingStyle(scrollable && !footer);
return (
<SheetVisibleFrame footer={footerView}>
<SheetVisibleFrame footer={footer} safeAreaInset={scrollable ? "footer" : "frame"}>
{header ? (
<SheetHeaderView
header={header}
@@ -672,12 +657,12 @@ function CompactSheetBody({
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
<View style={[styles.contentGrow, bodyClearanceStyle]}>
<Animated.View style={[SCROLL_CONTENT_GROW, bodyClearanceStyle]}>
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
</View>
</Animated.View>
</ScrollView>
) : (
<View style={[styles.compactStaticContent, bodyClearanceStyle]}>
<View style={styles.compactStaticContent}>
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
{children}
</SheetContent>
@@ -710,7 +695,6 @@ export function AdaptiveModalSheet({
}: AdaptiveModalSheetProps) {
const { t } = useTranslation();
const isMobile = useIsCompactFormFactor();
const isKeyboardVisible = useKeyboardVisibility(visible);
const resolvedSnapPoints = useMemo(() => snapPoints ?? ["65%", "90%"], [snapPoints]);
const isSheet = isMobile || !isWeb;
// The sheet registers itself; the desktop dialog does not use it.
@@ -828,7 +812,6 @@ export function AdaptiveModalSheet({
onClose={onClose}
testID={testID}
footer={footerView}
isKeyboardVisible={isKeyboardVisible}
scrollable={scrollable}
bodyStyle={bodyStyle}
contentStyle={contentStyle}
@@ -15,7 +15,7 @@ import DraggableFlatList, {
} from "react-native-draggable-flatlist";
import type { GestureType } from "react-native-gesture-handler";
import { useUnistyles } from "react-native-unistyles";
import { useContentDrag } from "@/components/ui/scroll-view";
import { useContentDrag } from "@/components/ui/content-drag";
import { createDragHold } from "./drag-reorder/drag-hold";
import { movedItemKey } from "./drag-reorder/native-drop";
import type {
@@ -232,6 +232,7 @@ export interface HostPickerProps {
open: boolean;
onOpenChange: (open: boolean) => void;
anchorRef: React.RefObject<View | null>;
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
includeAllHost?: boolean;
includeAddHost?: boolean;
onAddHost?: () => void;
@@ -254,6 +255,7 @@ export function HostPicker({
open,
onOpenChange,
anchorRef,
restoreFocusRef,
includeAllHost,
includeAddHost,
onAddHost,
@@ -404,6 +406,7 @@ export function HostPicker({
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
restoreFocusRef={restoreFocusRef}
desktopPlacement={desktopPlacement}
desktopMinWidth={desktopMinWidth}
/>
@@ -55,6 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarSelectionHost } from "@/sidebar-selection";
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
@@ -667,6 +668,7 @@ function MobileSidebar({
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
</SidebarToastRegion>
</SidebarViewSlot>
@@ -922,6 +924,7 @@ function DesktopSidebar({
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
</SidebarToastRegion>
</SidebarViewSlot>
@@ -8,10 +8,15 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { BackHeader } from "@/components/headers/back-header";
import { MenuHeader } from "@/components/headers/menu-header";
import { PressHighlight } from "@/components/ui/press-highlight";
import { withContentDrag } from "@/components/ui/content-drag";
import { useIsCompactFormFactor } from "@/constants/layout";
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView;
// Rows on a page drag to reorder, so the page stops scrolling while a drag holds the touch.
const PageScrollView =
Platform.OS === "android"
? withContentDrag(KeyboardAwareScrollView)
: withContentDrag(ScrollView);
interface PageLayoutProps {
title?: string;
@@ -66,12 +66,16 @@ function heightOf(testID: string): number {
return element(testID).getBoundingClientRect().height;
}
function titleFontSize(rowTestID: string, label: string): number {
const title = [...element(rowTestID).querySelectorAll("div")].find(
(node) => node.textContent === label && node.children.length === 0,
function textNode(rowTestID: string, text: string): HTMLElement {
const found = [...element(rowTestID).querySelectorAll("div")].find(
(node) => node.textContent === text && node.children.length === 0,
);
if (!title) throw new Error(`No title ${label}`);
return Number.parseFloat(getComputedStyle(title).fontSize);
if (!found) throw new Error(`No text ${text}`);
return found;
}
function titleFontSize(rowTestID: string, label: string): number {
return Number.parseFloat(getComputedStyle(textNode(rowTestID, label)).fontSize);
}
describe("settings row density", () => {
@@ -100,4 +104,52 @@ describe("settings row density", () => {
titleFontSize("card-row", "Card row"),
);
});
it("keeps a row with a long summary one line tall on a phone-width card", () => {
container = document.createElement("div");
// A 393pt phone less the sheet's side padding.
container.style.width = "360px";
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<SettingsCard>
<SettingsRow label="Text only" testID="text-row" />
<SettingsCollapsibleRow
label="Customize settings"
summary="Auto mode · Medium · 2 features · Add a note for when to use it"
testID="long-summary"
>
<SettingsRow label="Nested" />
</SettingsCollapsibleRow>
</SettingsCard>,
),
);
expect(heightOf("long-summary-toggle")).toBe(heightOf("text-row"));
});
it("keeps a short summary beside the chevron on a wide card", () => {
container = document.createElement("div");
container.style.width = "680px";
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<SettingsCard>
<SettingsDetailRow
label="Speech to text"
summary="Local"
onPress={openNothing}
testID="short-summary"
/>
</SettingsCard>,
),
);
const row = element("short-summary").getBoundingClientRect();
const summary = textNode("short-summary", "Local").getBoundingClientRect();
// The summary's margin, the chevron and the row's padding: about 40px.
expect(row.right - summary.right).toBeLessThan(48);
});
});
@@ -88,9 +88,13 @@ export function SettingsRowHeader({
const hovered = pointerOver && !disabled;
const rowStyle = useMemo(() => [layout.row, hovered && styles.hovered], [hovered, layout]);
const chevronStyle = useMemo(
() => [styles.chevron, expanded && styles.chevronExpanded],
() => [styles.chevron, expanded && styles.chevronExpanded, styles.passThrough],
[expanded],
);
// A hint can be a sentence, so a hinted row gives the room to the label column and caps the
// summary. A label alone keeps its one-line width and the summary truncates in what is left.
const hinted = Boolean(hint || hintStatus);
const contentStyle = hinted ? settingsStyles.rowContent : styles.labelContent;
return (
<View
style={rowStyle}
@@ -113,7 +117,7 @@ export function SettingsRowHeader({
{leading}
</View>
) : null}
<View style={[settingsStyles.rowContent, styles.passThrough]}>
<View style={[contentStyle, styles.passThrough]}>
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<Text style={layout.title}>{label}</Text>
{labelAccessory}
@@ -128,28 +132,15 @@ export function SettingsRowHeader({
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
</View>
) : null}
<View style={[styles.trailing, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{external ? (
// Drawn the same as a section header's docs link, so the two read as one thing.
<ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel>
) : (
<>
{summary ? (
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
{disabled ? null : (
<View style={chevronStyle}>
<ThemedChevron
size={ICON_SIZE.sm}
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
</>
)}
</View>
<RowTrailing hinted={hinted} external={external} hovered={hovered} summary={summary} />
{external || disabled ? null : (
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevron
size={ICON_SIZE.sm}
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
</View>
);
}
@@ -160,6 +151,32 @@ const HIDDEN_FROM_ASSISTIVE_TECH = {
"aria-hidden": true,
} as const;
/** The summary before the chevron, or the external link label in its place. */
function RowTrailing({
hinted,
external,
hovered,
summary,
}: {
hinted: boolean;
external: boolean;
hovered: boolean;
summary: string | undefined;
}) {
const style = hinted ? styles.hintedTrailing : styles.labelTrailing;
return (
<View style={[style, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{/* Drawn the same as a section header's docs link, so the two read as one thing. */}
{external ? <ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel> : null}
{!external && summary ? (
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
</View>
);
}
/**
* The hint with its status mark. The line keeps the hint's own height in every status, so a row
* does not move when its value arrives or its work starts. A long error is cut to the line; the
@@ -222,10 +239,30 @@ const styles = StyleSheet.create((theme) => ({
passThrough: {
pointerEvents: "none",
},
trailing: {
// The label keeps its one-line width and takes the free space; the summary truncates in what is
// left. Any shrink, even a fraction of a pixel, would wrap the label, so it does not shrink. The
// cap lets a long label wrap before it pushes the chevron off the row. Past the cap, the auto
// margin takes the rest of the row, so the control, summary and chevron stay together at the end.
labelContent: {
flexGrow: 1,
flexShrink: 0,
maxWidth: "75%",
paddingRight: theme.spacing[3],
marginRight: "auto",
},
labelTrailing: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
minWidth: 0,
},
// A hinted row's column grows from zero width, so an unbounded summary would squeeze it to
// nothing and wrap the label one glyph per line. The summary keeps at most half the row.
hintedTrailing: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
maxWidth: "50%",
},
hintLine: {
flexDirection: "row",
@@ -101,7 +101,17 @@ import {
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility";
import {
createWorkspaceVisibilityPolicy,
selectSidebarGroupVisibility,
} from "@/components/sidebar/sidebar-group-visibility";
import {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
useWorkspaceSelectionPress,
} from "@/sidebar-selection";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
SidebarWorkspaceRowFrame,
@@ -284,6 +294,7 @@ interface WorkspaceRowInnerProps {
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onCopyBranchName?: () => void;
onCopyPath?: () => void;
@@ -607,12 +618,14 @@ function WorkspaceRowRightGroup({
isHovered,
isTouchPlatform,
isCreating,
isSelectionMode,
showShortcutBadge,
shortcutNumber,
archiveLabel,
archiveStatus,
archivePendingLabel,
archiveShortcutKeys,
onSelectWorkspace,
onArchive,
onMarkAsRead,
onMarkAsUnread,
@@ -627,12 +640,14 @@ function WorkspaceRowRightGroup({
isHovered: boolean;
isTouchPlatform: boolean;
isCreating: boolean;
isSelectionMode: boolean;
showShortcutBadge: boolean;
shortcutNumber: number | null;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
archiveShortcutKeys?: ShortcutKey[][] | null;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
@@ -660,6 +675,7 @@ function WorkspaceRowRightGroup({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode,
});
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
@@ -695,6 +711,7 @@ function WorkspaceRowRightGroup({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1065,6 +1082,7 @@ function WorkspaceRowInner({
archiveLabel,
archiveStatus = "idle",
archivePendingLabel,
onSelectWorkspace,
onArchive,
onCopyBranchName,
onCopyPath,
@@ -1079,6 +1097,8 @@ function WorkspaceRowInner({
}: WorkspaceRowInnerProps) {
const isCompact = useIsCompactFormFactor();
const [isHighlighted, setIsHighlighted] = useState(false);
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
const isTouchPlatform = platformIsNative || isCompact;
const interaction = useLongPressDragInteraction({
drag,
@@ -1091,30 +1111,51 @@ function WorkspaceRowInner({
...dragAttributes
} = dragHandleProps?.attributes ?? {};
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
didLongPressRef: interaction.didLongPressRef,
onPress,
selected,
});
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
workspaceKey: workspace.workspaceKey,
onNavigate: handleNavigatePress,
onPressIn: interaction.handlePressIn,
});
const rowSelected = isSelectionMode ? isBulkSelected : selected;
const accessibilityState = useMemo(
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
[isSelectionMode, isBulkSelected, selected],
);
const isEditingTitle = titleEditor !== null;
const disableDrag = isEditingTitle || isSelectionMode;
return (
<SidebarWorkspaceRowFrame
workspace={workspace}
isDragging={isDragging}
isEditingTitle={isEditingTitle}
isSelectionMode={isSelectionMode}
>
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered });
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
const workspaceRowStyle = getProjectWorkspaceRowStyle({
isDragging,
selected: rowSelected,
isHovered,
});
const backdrop = getSidebarRowBackdrop({
isDragging,
isHighlighted,
selected: rowSelected,
isHovered,
});
return (
<View
{...dragAttributes}
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
{...(disableDrag ? null : dragHandleProps?.listeners)}
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
style={styles.workspaceRowContainer}
{...hoverHandlers}
@@ -1131,6 +1172,7 @@ function WorkspaceRowInner({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1140,17 +1182,18 @@ function WorkspaceRowInner({
onTogglePin={onTogglePin}
openInFileManagerPath={workspace.workspaceDirectory}
disabled={isArchiving}
enabled={!isEditingTitle}
aria-selected={selected}
accessibilityRole="button"
enabled={!isEditingTitle && !isSelectionMode}
aria-selected={isSelectionMode ? undefined : selected}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
onHighlightChange={setIsHighlighted}
onPressIn={isEditingTitle ? undefined : interaction.handlePressIn}
onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove}
onPressOut={isEditingTitle ? undefined : interaction.handlePressOut}
onPress={isEditingTitle ? undefined : handlePress}
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
onTouchMove={disableDrag ? undefined : interaction.handleTouchMove}
onPressOut={disableDrag ? undefined : interaction.handlePressOut}
onPress={isEditingTitle ? undefined : handleRowPress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
<SidebarWorkspaceRowContent
@@ -1163,6 +1206,8 @@ function WorkspaceRowInner({
isHovered={isHovered}
isLoading={isArchiving || isCreating}
isCreating={isCreating}
isSelectionMode={isSelectionMode}
isBulkSelected={isBulkSelected}
shortcutNumber={shortcutNumber}
showShortcutBadge={showShortcutBadge}
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
@@ -1174,12 +1219,14 @@ function WorkspaceRowInner({
isHovered={isHovered}
isTouchPlatform={isTouchPlatform}
isCreating={isCreating}
isSelectionMode={isSelectionMode}
showShortcutBadge={showShortcutBadge}
shortcutNumber={shortcutNumber}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
archivePendingLabel={archivePendingLabel}
archiveShortcutKeys={archiveShortcutKeys}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
onCopyBranchName={onCopyBranchName}
onCopyPath={onCopyPath}
@@ -1265,6 +1312,10 @@ function WorkspaceRowWithMenu({
archiveController.archive();
}, [archiveController, isArchiving]);
const handleSelectWorkspace = useCallback(() => {
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
}, [workspace.workspaceKey]);
const clipboard = useWorkspaceClipboardActions();
const handleCopyPath = useCallback(() => {
clipboard.copyPath(workspace);
@@ -1317,6 +1368,7 @@ function WorkspaceRowWithMenu({
archiveLabel={t("sidebar.workspace.actions.archive")}
archiveStatus={isArchiving ? "pending" : "idle"}
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
onSelectWorkspace={handleSelectWorkspace}
onArchive={handleArchive}
onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined}
onCopyPath={handleCopyPath}
@@ -2199,6 +2251,62 @@ function ProjectModeList({
selection: selectionEnabled ? activeWorkspaceSelection : null,
expanded: pinnedChatsExpanded,
});
const visibleOrderInputRef = useRef({
pinnedCollapsed,
leadingPinnedChat,
visiblePinnedChats,
unpinnedProjects,
collapsedProjectKeys,
expandedProjectKeys,
selectionEnabled,
activeWorkspaceSelection,
workspaceEntriesByKey,
});
visibleOrderInputRef.current = {
pinnedCollapsed,
leadingPinnedChat,
visiblePinnedChats,
unpinnedProjects,
collapsedProjectKeys,
expandedProjectKeys,
selectionEnabled,
activeWorkspaceSelection,
workspaceEntriesByKey,
};
useEffect(() => {
return registerSidebarVisibleWorkspaceKeysReader(() => {
const current = visibleOrderInputRef.current;
const keys: string[] = [];
if (!current.pinnedCollapsed) {
if (current.leadingPinnedChat) keys.push(current.leadingPinnedChat.workspaceKey);
for (const item of current.visiblePinnedChats) {
keys.push(item.workspaceKey);
}
}
const policy = createWorkspaceVisibilityPolicy<SidebarWorkspacePlacement>(
current.workspaceEntriesByKey,
);
const selection = current.selectionEnabled ? current.activeWorkspaceSelection : null;
for (const project of current.unpinnedProjects) {
if (current.collapsedProjectKeys.has(project.viewKey) || project.workspaces.length === 0) {
continue;
}
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
items: project.workspaces,
selection,
expanded: current.expandedProjectKeys.has(project.viewKey),
policy,
});
if (leadingItem) keys.push(leadingItem.workspaceKey);
for (const item of visibleItems) {
keys.push(item.workspaceKey);
}
}
return keys;
});
}, []);
const nativeScrollGestureProps = useMemo(
() =>
parentGestureRef
@@ -3,7 +3,9 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type MutableRefObject,
type ReactNode,
@@ -69,7 +71,15 @@ import {
} from "@/components/sidebar/sidebar-workspace-menu";
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
useWorkspaceSelectionPress,
} from "@/sidebar-selection";
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
import type { DraggableListDragHandleProps } from "@/components/draggable-list.types";
@@ -154,6 +164,14 @@ export function SidebarStatusWorkspaceList({
() => setPinnedWorkspacesExpanded((current) => !current),
[],
);
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
const toggleGroupWorkspacesExpanded = useCallback((groupKey: string) => {
setExpandedGroupKeys((current) => {
const next = new Set(current);
if (!next.delete(groupKey)) next.add(groupKey);
return next;
});
}, []);
const {
leadingItem: leadingPinnedWorkspace,
visibleItems: visiblePinnedWorkspaces,
@@ -164,6 +182,56 @@ export function SidebarStatusWorkspaceList({
expanded: pinnedWorkspacesExpanded,
});
const visibleOrderInputRef = useRef({
pinnedCollapsed,
leadingPinnedWorkspace,
visiblePinnedWorkspaces,
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
activeWorkspaceSelection,
});
visibleOrderInputRef.current = {
pinnedCollapsed,
leadingPinnedWorkspace,
visiblePinnedWorkspaces,
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
activeWorkspaceSelection,
};
useEffect(() => {
return registerSidebarVisibleWorkspaceKeysReader(() => {
const current = visibleOrderInputRef.current;
const keys: string[] = [];
if (!current.pinnedCollapsed) {
if (current.leadingPinnedWorkspace) {
keys.push(current.leadingPinnedWorkspace.workspaceKey);
}
for (const item of current.visiblePinnedWorkspaces) {
keys.push(item.workspaceKey);
}
}
for (const group of current.groups) {
if (current.collapsedWorkspaceGroupKeys.has(group.key) || group.rows.length === 0) {
continue;
}
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
items: group.rows,
selection: current.activeWorkspaceSelection,
expanded: current.expandedGroupKeys.has(group.key),
policy: STATUS_GROUP_VISIBILITY,
});
if (leadingItem) keys.push(leadingItem.workspaceKey);
for (const item of visibleItems) {
keys.push(item.workspaceKey);
}
}
return keys;
});
}, []);
const statusShortcutIndex = showShortcutBadges
? shortcutIndexByWorkspaceKey
: EMPTY_SHORTCUT_INDEX;
@@ -262,6 +330,8 @@ export function SidebarStatusWorkspaceList({
<StatusGroupList
groups={groups}
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
expandedGroupKeys={expandedGroupKeys}
onToggleGroupWorkspacesExpanded={toggleGroupWorkspacesExpanded}
projectIconByProjectViewKey={projectIconByProjectViewKey}
shortcutIndex={statusShortcutIndex}
showShortcutBadges={showShortcutBadges}
@@ -303,6 +373,8 @@ export function SidebarStatusWorkspaceList({
function StatusGroupList({
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
onToggleGroupWorkspacesExpanded,
projectIconByProjectViewKey,
shortcutIndex,
showShortcutBadges,
@@ -313,6 +385,8 @@ function StatusGroupList({
}: {
groups: SidebarWorkspaceGroup[];
collapsedWorkspaceGroupKeys: ReadonlySet<string>;
expandedGroupKeys: ReadonlySet<string>;
onToggleGroupWorkspacesExpanded: (groupKey: string) => void;
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
shortcutIndex: Map<string, number>;
showShortcutBadges: boolean;
@@ -328,6 +402,8 @@ function StatusGroupList({
key={group.key}
group={group}
collapsed={collapsedWorkspaceGroupKeys.has(group.key)}
workspacesExpanded={expandedGroupKeys.has(group.key)}
onToggleWorkspacesExpanded={onToggleGroupWorkspacesExpanded}
projectIconByProjectViewKey={projectIconByProjectViewKey}
shortcutIndex={shortcutIndex}
showShortcutBadges={showShortcutBadges}
@@ -349,6 +425,8 @@ const STATUS_GROUP_VISIBILITY = {
function StatusGroupRows({
group,
collapsed,
workspacesExpanded,
onToggleWorkspacesExpanded,
projectIconByProjectViewKey,
shortcutIndex,
showShortcutBadges,
@@ -359,6 +437,8 @@ function StatusGroupRows({
}: {
group: SidebarWorkspaceGroup;
collapsed: boolean;
workspacesExpanded: boolean;
onToggleWorkspacesExpanded: (groupKey: string) => void;
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
shortcutIndex: Map<string, number>;
showShortcutBadges: boolean;
@@ -368,10 +448,9 @@ function StatusGroupRows({
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
}) {
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const [workspacesExpanded, setWorkspacesExpanded] = useState(false);
const toggleWorkspacesExpanded = useCallback(
() => setWorkspacesExpanded((current) => !current),
[],
() => onToggleWorkspacesExpanded(group.key),
[group.key, onToggleWorkspacesExpanded],
);
const {
leadingItem: leadingWorkspace,
@@ -669,6 +748,10 @@ function StatusWorkspaceRowWithMenu({
archiveController.archive();
}, [archiveController, isArchiving]);
const handleSelectWorkspace = useCallback(() => {
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
}, [workspace.workspaceKey]);
const clipboard = useWorkspaceClipboardActions();
const handleCopyPath = useCallback(() => {
clipboard.copyPath(workspace);
@@ -716,6 +799,7 @@ function StatusWorkspaceRowWithMenu({
archiveLabel={t("sidebar.workspace.actions.archive")}
archiveStatus={isArchiving ? "pending" : "idle"}
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
onSelectWorkspace={handleSelectWorkspace}
onArchive={handleArchive}
onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined}
onCopyPath={handleCopyPath}
@@ -750,6 +834,7 @@ interface StatusWorkspaceRowInnerProps {
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onCopyBranchName?: () => void;
onCopyPath?: () => void;
@@ -799,6 +884,7 @@ function StatusWorkspaceRowInnerContent({
archiveLabel,
archiveStatus = "idle",
archivePendingLabel,
onSelectWorkspace,
onArchive,
onCopyBranchName,
onCopyPath,
@@ -820,6 +906,8 @@ function StatusWorkspaceRowInnerContent({
const isCompact = useIsCompactFormFactor();
const isTouchPlatform = platformIsNative || isCompact;
const [isHighlighted, setIsHighlighted] = useState(false);
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
const trailing = useSidebarWorkspaceTrailing();
const {
role: _dragRole,
@@ -831,23 +919,35 @@ function StatusWorkspaceRowInnerContent({
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const rowSelected = isSelectionMode ? isBulkSelected : selected;
const accessibilityState = useMemo(
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
[isSelectionMode, isBulkSelected, selected],
);
const isEditingTitle = titleEditor !== null;
const disableDrag = isEditingTitle || isSelectionMode;
const didLongPressRef = dragInteraction?.didLongPressRef;
const startDragPress = dragInteraction?.handlePressIn;
const moveDragPress = dragInteraction?.handleTouchMove;
const endDragPress = dragInteraction?.handlePressOut;
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
didLongPressRef,
onPress,
selected,
});
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
workspaceKey: workspace.workspaceKey,
onNavigate: handleNavigatePress,
onPressIn: startDragPress,
});
return (
<SidebarWorkspaceRowFrame
workspace={workspace}
isDragging={isDragging}
isEditingTitle={isEditingTitle}
isSelectionMode={isSelectionMode}
>
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const showShortcut = showShortcutBadge && shortcutNumber !== null;
@@ -865,18 +965,24 @@ function StatusWorkspaceRowInnerContent({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode,
});
const workspaceRowStyle = getStatusWorkspaceRowStyle({
selected,
selected: rowSelected,
isHovered,
inStatusGroup,
isDragging,
});
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
const backdrop = getSidebarRowBackdrop({
isDragging,
isHighlighted,
selected: rowSelected,
isHovered,
});
return (
<View
{...dragAttributes}
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
{...(disableDrag ? null : dragHandleProps?.listeners)}
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
style={styles.workspaceRowContainer}
{...hoverHandlers}
@@ -894,6 +1000,7 @@ function StatusWorkspaceRowInnerContent({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -903,16 +1010,18 @@ function StatusWorkspaceRowInnerContent({
onTogglePin={onTogglePin}
openInFileManagerPath={workspace.workspaceDirectory}
disabled={isArchiving}
enabled={!isEditingTitle}
accessibilityRole="button"
enabled={!isEditingTitle && !isSelectionMode}
aria-selected={isSelectionMode ? undefined : selected}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
onHighlightChange={setIsHighlighted}
onPressIn={isEditingTitle ? undefined : startDragPress}
onTouchMove={isEditingTitle ? undefined : moveDragPress}
onPressOut={isEditingTitle ? undefined : endDragPress}
onPress={isEditingTitle ? undefined : handlePress}
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
onTouchMove={disableDrag ? undefined : moveDragPress}
onPressOut={disableDrag ? undefined : endDragPress}
onPress={isEditingTitle ? undefined : handleRowPress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
<SidebarWorkspaceRowContent
@@ -924,6 +1033,8 @@ function StatusWorkspaceRowInnerContent({
backdrop={backdrop}
isHovered={isHovered}
isLoading={isArchiving}
isSelectionMode={isSelectionMode}
isBulkSelected={isBulkSelected}
shortcutNumber={shortcutNumber}
showShortcutBadge={showShortcutBadge}
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
@@ -946,6 +1057,7 @@ function StatusWorkspaceRowInnerContent({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -979,6 +1091,7 @@ function StatusWorkspaceActionSlot({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -1000,6 +1113,7 @@ function StatusWorkspaceActionSlot({
onRename?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
onSelectWorkspace?: () => void;
onArchive?: () => void;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
@@ -1034,6 +1148,7 @@ function StatusWorkspaceActionSlot({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -5,6 +5,7 @@ import {
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { View } from "react-native";
@@ -15,7 +16,13 @@ import Animated, {
type SharedValue,
} from "react-native-reanimated";
import { StyleSheet } from "react-native-unistyles";
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
import {
TOAST_FADE_MS,
ToastViewport,
useToastHost,
type ToastApi,
type ToastState,
} from "@/components/toast-host";
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
interface SidebarToastCoverage {
@@ -25,6 +32,10 @@ interface SidebarToastCoverage {
}
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
const SidebarPersistentToastContext = createContext<((toast: ToastState | null) => void) | null>(
null,
);
const SidebarAppToastContext = createContext<ToastApi | null>(null);
/**
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
@@ -36,9 +47,10 @@ const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(n
export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) {
const appToast = useToast();
const { api: sidebarToast, toast, dismiss } = useToastHost();
const [persistentToast, setPersistentToast] = useState<ToastState | null>(null);
const activeRef = useRef(active);
const coverageHeight = useSharedValue(0);
const toastVisible = toast !== null;
const toastVisible = toast !== null || persistentToast !== null;
useEffect(() => {
activeRef.current = active;
@@ -72,19 +84,48 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
return (
<View style={styles.region}>
<SidebarToastCoverageContext.Provider value={coverage}>
<ToastApiProvider api={api}>{children}</ToastApiProvider>
</SidebarToastCoverageContext.Provider>
<ToastViewport
toast={toast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
<ToastApiProvider api={api}>
<SidebarAppToastContext.Provider value={appToast}>
<SidebarPersistentToastContext.Provider value={setPersistentToast}>
<SidebarToastCoverageContext.Provider value={coverage}>
{children}
</SidebarToastCoverageContext.Provider>
</SidebarPersistentToastContext.Provider>
</SidebarAppToastContext.Provider>
<ToastViewport
toast={toast}
persistentToast={persistentToast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
</ToastApiProvider>
</View>
);
}
/** Returns the enclosing app-level toast API so sidebar callers can report errors without displacing an active sidebar undo toast. */
export function useSidebarAppToast(): ToastApi {
const fallbackToast = useToast();
return useContext(SidebarAppToastContext) ?? fallbackToast;
}
/**
* Displays a persistent toast in the enclosing `SidebarToastRegion`, stacked below any active
* transient toast so controls stay reachable while a previous toast is up.
*/
export function useSidebarPersistentToast(toast: ToastState | null): void {
const setPersistentToast = useContext(SidebarPersistentToastContext);
useEffect(() => {
setPersistentToast?.(toast);
}, [setPersistentToast, toast]);
useEffect(() => {
return () => {
setPersistentToast?.(null);
};
}, [setPersistentToast]);
}
/**
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
@@ -1,9 +1,10 @@
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { PressableStateCallbackType } from "react-native";
import type { GestureResponderEvent, PressableStateCallbackType } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
Archive,
CheckSquare,
Circle,
CircleCheck,
Copy,
@@ -56,6 +57,7 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
const ThemedMoreVertical = withUnistyles(MoreVertical);
const ThemedCopy = withUnistyles(Copy);
const ThemedArchive = withUnistyles(Archive);
const ThemedCheckSquare = withUnistyles(CheckSquare);
const ThemedCircle = withUnistyles(Circle);
const ThemedPencil = withUnistyles(Pencil);
const ThemedCircleCheck = withUnistyles(CircleCheck);
@@ -69,6 +71,7 @@ const markAsReadLeadingIcon = (
<ThemedCircleCheck size={14} uniProps={foregroundMutedColorMapping} />
);
const markAsUnreadLeadingIcon = <ThemedCircle size={14} uniProps={foregroundMutedColorMapping} />;
const selectLeadingIcon = <ThemedCheckSquare size={14} uniProps={foregroundMutedColorMapping} />;
const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedColorMapping} />;
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
@@ -124,6 +127,7 @@ export interface SidebarWorkspaceMenuProps {
onRename?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
onSelectWorkspace?: () => void;
onArchive: () => void;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
@@ -172,6 +176,7 @@ function SidebarWorkspaceMenuItems({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -267,6 +272,16 @@ function SidebarWorkspaceMenuItems({
path={openInFileManagerPath}
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
/>
{onSelectWorkspace ? (
<WorkspaceMenuItem
surface={surface}
testID={`sidebar-workspace-menu-select-${workspaceKey}`}
leading={selectLeadingIcon}
onSelect={onSelectWorkspace}
>
{t("sidebar.workspace.actions.select")}
</WorkspaceMenuItem>
) : null}
{onArchive ? (
<WorkspaceMenuItem
surface={surface}
@@ -294,6 +309,7 @@ export function SidebarWorkspaceMenu({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -340,6 +356,7 @@ export function SidebarWorkspaceMenu({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -373,6 +390,7 @@ export function SidebarWorkspaceContextMenu({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -426,11 +444,37 @@ export function SidebarWorkspaceContextMenu({
[workspace],
);
const pages = useWorkspaceLabelMenuPages(workspaceTarget);
const checkboxSpaceKeyProps = useMemo(() => {
if (!isWeb || triggerProps.accessibilityRole !== "checkbox" || !triggerProps.onPress) {
return {};
}
const onPress = triggerProps.onPress;
return {
// React Native Web's Pressable activates Space only for role="button", not checkbox.
onKeyDown: (event: {
key?: string;
repeat?: boolean;
target?: unknown;
currentTarget?: unknown;
preventDefault?: () => void;
}) => {
if (triggerProps.disabled) return;
if (event.target !== event.currentTarget) return;
if (event.key === " " || event.key === "Spacebar") {
event.preventDefault?.();
if (!event.repeat) {
onPress(event as unknown as GestureResponderEvent);
}
}
},
};
}, [triggerProps.accessibilityRole, triggerProps.disabled, triggerProps.onPress]);
return (
<ContextMenu open={contextMenuOpen} onOpenChange={onContextMenuOpenChange}>
<ContextMenuTrigger
{...triggerProps}
{...checkboxSpaceKeyProps}
enabledOnMobile={false}
accessibilityLabel={accessibilityLabel ?? rowAccessibilityLabel}
highlightStyle={highlightStyle}
@@ -454,6 +498,7 @@ export function SidebarWorkspaceContextMenu({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1,7 +1,8 @@
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
import { Text, View, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { bySizing } from "@/components/ui/control-geometry";
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
import {
@@ -40,19 +41,26 @@ const needsInputColorMapping = (theme: Theme) => ({
color: theme.colors.surface0,
fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
});
const checkedIconMapping = (theme: Theme) => ({
color: theme.colors.accentForeground,
});
const ThemedCheck = withUnistyles(Check);
const ThemedCircleAlert = withUnistyles(CircleAlert);
export function SidebarWorkspaceRowFrame({
workspace,
isDragging = false,
isEditingTitle = false,
isSelectionMode = false,
children,
}: {
workspace: SidebarWorkspaceEntry;
isDragging?: boolean;
/** Hover would fade the kebab in over the title being edited and open the hover card. */
isEditingTitle?: boolean;
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
isSelectionMode?: boolean;
children: (input: {
isHovered: boolean;
contextMenuOpen: boolean;
@@ -80,7 +88,7 @@ export function SidebarWorkspaceRowFrame({
workspace={workspace}
prHint={workspace.prHint}
isDragging={isDragging}
disabled={contextMenuOpen || isEditingTitle}
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
>
{children({
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
@@ -102,6 +110,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
isHovered,
isLoading,
isCreating = false,
isSelectionMode = false,
isBulkSelected = false,
shortcutNumber = null,
showShortcutBadge = false,
reserveIdleStatusIndicatorSpace = true,
@@ -119,6 +129,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
isHovered: boolean;
isLoading: boolean;
isCreating?: boolean;
isSelectionMode?: boolean;
isBulkSelected?: boolean;
shortcutNumber?: number | null;
showShortcutBadge?: boolean;
/** Keep the empty leading slot when the workspace has no active status. */
@@ -137,33 +149,44 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
const workspaceBranchTextStyle = useMemo(
() => [
styles.workspaceBranchText,
isHovered && styles.workspaceBranchTextHovered,
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
isCreating && styles.workspaceBranchTextCreating,
],
[isHovered, isCreating],
[isHovered, isBulkSelected, isCreating],
);
let leadingVisual: ReactNode;
if (isSelectionMode) {
leadingVisual = (
<WorkspaceSelectionCheckbox checked={isBulkSelected} workspaceKey={workspace.workspaceKey} />
);
} else if (leadingProjectName) {
leadingVisual = (
<ProjectStatusIndicator
iconDataUri={leadingProjectIconDataUri}
displayName={leadingProjectName}
projectViewKey={workspace.projectViewKey}
statusBucket={workspace.statusBucket}
backdrop={backdrop}
loading={isLoading}
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
/>
);
} else {
leadingVisual = (
<WorkspaceStatusIndicator
bucket={workspace.statusBucket}
workspaceKind={workspace.workspaceKind}
loading={isLoading}
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
/>
);
}
return (
<View style={styles.workspaceRowContent}>
<View style={styles.workspaceRowMain}>
{leadingProjectName ? (
<ProjectStatusIndicator
iconDataUri={leadingProjectIconDataUri}
displayName={leadingProjectName}
projectViewKey={workspace.projectViewKey}
statusBucket={workspace.statusBucket}
backdrop={backdrop}
loading={isLoading}
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
/>
) : (
<WorkspaceStatusIndicator
bucket={workspace.statusBucket}
workspaceKind={workspace.workspaceKind}
loading={isLoading}
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
/>
)}
{leadingVisual}
<View style={styles.workspaceContentColumn}>
<View style={styles.workspaceTitleRow}>
{titleEditor ? (
@@ -191,7 +214,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
/>
</View>
</View>
{showShortcutBadge && shortcutNumber !== null ? (
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
</View>
@@ -200,6 +223,22 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
);
});
function WorkspaceSelectionCheckbox({
checked,
workspaceKey,
}: {
checked: boolean;
workspaceKey: string;
}) {
return (
<View style={styles.workspaceStatusDot} testID={`sidebar-workspace-checkbox-${workspaceKey}`}>
<View style={checked ? styles.selectionCheckboxChecked : styles.selectionCheckbox}>
{checked ? <ThemedCheck size={11} strokeWidth={2.5} uniProps={checkedIconMapping} /> : null}
</View>
</View>
);
}
function WorkspaceStatusIndicator({
bucket,
workspaceKind,
@@ -382,6 +421,7 @@ export function resolveTrailingActionVisibility({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode = false,
}: {
workspace: SidebarWorkspaceEntry;
trailing: SidebarWorkspaceTrailing;
@@ -389,6 +429,7 @@ export function resolveTrailingActionVisibility({
isHovered: boolean;
isTouchPlatform: boolean;
showShortcut: boolean;
isSelectionMode?: boolean;
}): {
trailingPresentation: SidebarWorkspaceTrailingPresentation;
showKebab: boolean;
@@ -398,10 +439,11 @@ export function resolveTrailingActionVisibility({
reserveSlotWidth: boolean;
} {
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut;
const allowRowActions = hasArchiveAction && !isSelectionMode;
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
// conceal content while retaining its width, so desktop rows do not shift.
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
return {
@@ -414,12 +456,12 @@ export function resolveTrailingActionVisibility({
// row — over an unhovered one the gradient fades to the wrong color. That is also why
// touch, which shows the kebab without ever hovering, never gets one.
showScrim: showKebab && isHovered,
renderSlot: hasArchiveAction || hasTrailing,
renderSlot: allowRowActions || hasTrailing,
// The slot only holds width for something that permanently sits in it. Trailing content
// does; the kebab only does on touch, where there is no hover for it to appear on and so
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
// and the kebab fades in over its tail.
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
};
}
@@ -536,6 +578,25 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
justifyContent: "center",
},
selectionCheckbox: {
width: bySizing({ touch: 18, pointer: 15 }),
height: bySizing({ touch: 18, pointer: 15 }),
borderRadius: theme.borderRadius.sm,
borderWidth: 1.5,
borderColor: theme.colors.borderAccent,
alignItems: "center",
justifyContent: "center",
},
selectionCheckboxChecked: {
width: bySizing({ touch: 18, pointer: 15 }),
height: bySizing({ touch: 18, pointer: 15 }),
borderRadius: theme.borderRadius.sm,
borderWidth: 1.5,
borderColor: theme.colors.accent,
backgroundColor: theme.colors.accent,
alignItems: "center",
justifyContent: "center",
},
statusDotOverlay: {
position: "absolute",
right: 0,
+85 -15
View File
@@ -16,6 +16,7 @@ import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { SPACING, type Theme } from "@/styles/theme";
import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry";
import { useTranslation } from "react-i18next";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
@@ -28,10 +29,16 @@ import {
} from "@/constants/layout";
export type ToastVariant = "default" | "info" | "success" | "warning" | "error";
/**
* `action` tightens vertical and trailing insets around `size="sm"` pill controls and uses a
* concentric corner radius (`controlHeight / 2 + inset`) so buttons nest evenly in the shell.
*/
export type ToastLayout = "default" | "action";
export interface ToastShowOptions {
icon?: ReactNode;
variant?: ToastVariant;
layout?: ToastLayout;
durationMs?: number | null;
nativeAndroid?: boolean;
testID?: string;
@@ -45,6 +52,7 @@ export interface ToastState {
nativeMessage: string | null;
icon?: ReactNode;
variant: ToastVariant;
layout?: ToastLayout;
durationMs: number | null;
testID?: string;
onDismiss?: () => void;
@@ -73,6 +81,11 @@ const TOAST_MAX_WIDTH = 480;
/** How long a toast takes to fade in or out. */
export const TOAST_FADE_MS = 140;
const SIDEBAR_TOAST_INSET = SPACING[2];
const ACTION_TOAST_INSET = SPACING[1.5];
const ACTION_TOAST_RADIUS = mapLayout(
CONTROL_HEIGHTS.sm,
(height) => height / 2 + ACTION_TOAST_INSET,
);
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
const ThemedCheckCircle = withUnistyles(CheckCircle2);
@@ -136,6 +149,7 @@ export function useToastHost(): {
nativeMessage,
icon: options?.icon,
variant,
layout: options?.layout,
durationMs,
testID: options?.testID,
onDismiss: options?.onDismiss,
@@ -163,11 +177,14 @@ export function useToastHost(): {
export function ToastViewport({
toast,
persistentToast = null,
onDismiss,
placement = "app-shell",
onBottomCoverageChange,
}: {
toast: ToastState | null;
/** Sidebar placement: persistent bar (such as select mode) that stays visible below transient toasts. */
persistentToast?: ToastState | null;
/** Called with the ID of the toast that timed out. */
onDismiss: (id: number) => void;
placement?: ToastViewportPlacement;
@@ -232,7 +249,10 @@ export function ToastViewport({
const handleSidebarLayout = useCallback(
(event: LayoutChangeEvent) => {
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
const height = event.nativeEvent.layout.height;
if (height > 0) {
onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET);
}
},
[onBottomCoverageChange],
);
@@ -243,28 +263,41 @@ export function ToastViewport({
const topOffset =
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
if (placement === "sidebar") {
return (
<View
style={animatedStyles.sidebarContainer}
pointerEvents="box-none"
collapsable={false}
onLayout={handleSidebarLayout}
>
<SidebarToastSlot
toast={toast}
onPointerEnter={pauseDismiss}
onPointerLeave={resumeDismiss}
/>
<SidebarToastSlot
toast={persistentToast}
onPointerEnter={noopDismiss}
onPointerLeave={noopDismiss}
/>
</View>
);
}
// Keep the bottom anchor and its contents together while the native exit retains the view.
const content = toast ? (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={
placement === "sidebar"
? animatedStyles.sidebarContainer
: [
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]
}
style={[
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]}
pointerEvents="box-none"
collapsable={false}
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
>
<View
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
pointerEvents="box-none"
collapsable={false}
>
<View style={styles.widthBoundary} pointerEvents="box-none" collapsable={false}>
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
@@ -283,6 +316,35 @@ export function ToastViewport({
return placement === "panel" ? <FloatingHeaderOverlay>{content}</FloatingHeaderOverlay> : content;
}
function SidebarToastSlot({
toast,
onPointerEnter,
onPointerLeave,
}: {
toast: ToastState | null;
onPointerEnter: () => void;
onPointerLeave: () => void;
}) {
if (!toast) return null;
return (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={styles.sidebarWidthBoundary}
pointerEvents="box-none"
collapsable={false}
>
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
accessibilityRole="alert"
>
<ToastCard toast={toast} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave} />
</View>
</Animated.View>
);
}
function ToastCard({
toast,
onPointerEnter,
@@ -310,6 +372,7 @@ function ToastCard({
onPointerLeave={onPointerLeave}
style={[
styles.toast,
toast.layout === "action" ? styles.toastAction : null,
toast.variant === "info" ? styles.toastInfo : null,
toast.variant === "warning" ? styles.toastWarning : null,
toast.variant === "error" ? styles.toastError : null,
@@ -344,6 +407,7 @@ const animatedStyles = NativeStyleSheet.create({
bottom: SIDEBAR_TOAST_INSET,
zIndex: OVERLAY_Z.toast,
alignItems: "center",
gap: SIDEBAR_TOAST_INSET,
},
surface: { alignSelf: "center", maxWidth: "100%" },
});
@@ -372,6 +436,12 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: theme.spacing[3],
...theme.shadow.md,
},
toastAction: {
borderRadius: ACTION_TOAST_RADIUS,
paddingVertical: theme.spacing[1.5],
paddingLeft: theme.spacing[3.5],
paddingRight: theme.spacing[1.5],
},
toastInfo: {
borderColor: theme.colors.palette.blue[300],
},
+10 -16
View File
@@ -25,7 +25,6 @@ import {
} from "react-native";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -146,6 +145,8 @@ export interface ComboboxProps {
/** When true, selecting an option does not close the picker (multi-select mode). */
keepOpenOnSelect?: boolean;
anchorRef: React.RefObject<View | null>;
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
restoreFocusRef?: React.RefObject<unknown>;
children?: ReactNode;
}
@@ -1138,31 +1139,22 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement {
}
/**
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
* one left where the combobox was opened: inside a sheet tab, none is.
* Rendered on the far side of the sheet's portal so `SheetVisibleFrame` clears the screen's
* bottom inset in lockstep with the keyboard, not the inset left where the combobox was opened.
*/
function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children: ReactNode }) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const frameStyle = useMemo(
() => [styles.mobileSheetFrame, { paddingBottom: footer ? 0 : safeAreaBottom }],
[footer, safeAreaBottom],
);
const footerStyle = useMemo(
() => [styles.footer, { paddingBottom: safeAreaBottom }],
[safeAreaBottom],
);
const footerView = useMemo(
() =>
footer ? (
<View style={footerStyle} dataSet={FOOTER_DATASET}>
<View style={styles.footer} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
[footer, footerStyle],
[footer],
);
return (
<SheetVisibleFrame footer={footerView}>
<View style={frameStyle}>{children}</View>
<SheetVisibleFrame footer={footerView} safeAreaInset="frame">
<View style={styles.mobileSheetFrame}>{children}</View>
</SheetVisibleFrame>
);
}
@@ -1437,6 +1429,7 @@ export function Combobox({
footer,
keepOpenOnSelect = false,
anchorRef,
restoreFocusRef,
children,
}: ComboboxProps): ReactElement | null {
const { t } = useTranslation();
@@ -1728,6 +1721,7 @@ export function Combobox({
layer: floatingLayer,
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
restoreFocusRef,
});
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
@@ -0,0 +1,106 @@
import React, { act, Children, useCallback, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { useContentDrag, withContentDrag } from "./content-drag";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
interface FakeScrollProps {
scrollEnabled?: boolean;
children?: ReactNode;
}
/** Stands in for a scroll view: it reports the props a native scroll view would act on. */
function FakeScroll({ scrollEnabled, children }: FakeScrollProps) {
return (
<div
data-testid="scroll"
data-scroll-enabled={String(scrollEnabled)}
data-child-count={Children.toArray(children).length}
>
{children}
</div>
);
}
const DragHostScroll = withContentDrag<FakeScrollProps, unknown>(FakeScroll);
/** A row that holds a drag the way a draggable list does: active from press until release. */
function DragRow() {
const { setActive } = useContentDrag();
const arm = useCallback(() => setActive(true), [setActive]);
const release = useCallback(() => setActive(false), [setActive]);
return (
<>
<button type="button" data-testid="arm" onClick={arm} />
<button type="button" data-testid="release" onClick={release} />
</>
);
}
function mount(node: React.ReactElement) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(node));
}
function scroll(): HTMLElement {
const found = document.querySelector('[data-testid="scroll"]');
if (!(found instanceof HTMLElement)) throw new Error("No scroll view rendered");
return found;
}
function press(testID: string) {
const button = document.querySelector(`[data-testid="${testID}"]`);
if (!(button instanceof HTMLElement)) throw new Error(`No ${testID}`);
act(() => button.click());
}
describe("withContentDrag", () => {
it("stops the scroll while a child drag holds the touch, and resumes after", () => {
mount(
<DragHostScroll>
<DragRow />
</DragHostScroll>,
);
expect(scroll().dataset.scrollEnabled).toBe("true");
press("arm");
expect(scroll().dataset.scrollEnabled).toBe("false");
press("release");
expect(scroll().dataset.scrollEnabled).toBe("true");
});
it("keeps a scroll view the caller disabled disabled after the drag", () => {
mount(
<DragHostScroll scrollEnabled={false}>
<DragRow />
</DragHostScroll>,
);
press("arm");
press("release");
expect(scroll().dataset.scrollEnabled).toBe("false");
});
it("passes the children through as given, so sticky header indices still count them", () => {
mount(
<DragHostScroll>
<div>Intro</div>
<div>Section header</div>
<DragRow />
</DragHostScroll>,
);
expect(scroll().dataset.childCount).toBe("3");
});
});
@@ -0,0 +1,64 @@
import {
createContext,
forwardRef,
useContext,
useMemo,
useState,
type ComponentType,
type Ref,
} from "react";
import type { AttachSheetContentDrag } from "./bottom-sheet-scope";
/**
* What a child that drags inside a scroll view needs to keep the touch: `setActive(true)` stops
* the scroll until the drag ends, so the scroll view cannot take the finger once the drag has
* armed. Inside a sheet the child also registers its drag gesture through `attach` so the sheet's
* pan waits for it; outside a sheet there is no `attach`. Outside any scroll view that hosts
* content drags, `setActive` does nothing.
*/
export interface ContentDrag {
attach: AttachSheetContentDrag | undefined;
setActive: (active: boolean) => void;
}
const ContentDragContext = createContext<ContentDrag | null>(null);
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
export function useContentDrag(): ContentDrag {
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
}
function useNoAttach(): AttachSheetContentDrag | undefined {
return undefined;
}
/**
* Makes a scroll view host content drags: it stops scrolling while a child drag is active. Without
* it, a vertical drag in a row of a scrolling page is taken by the page scroll once the finger
* moves past the touch slop, before the row's drag gesture can activate. A sheet's scroll view
* passes `useAttach` so its children can also register their gesture with the sheet.
*
* The context wraps the scroll view rather than its content, so the scroll view receives its
* children as given: `stickyHeaderIndices` counts them.
*/
export function withContentDrag<P extends { scrollEnabled?: boolean }, T>(
Scroll: ComponentType<P & { ref?: Ref<T> }>,
useAttach: () => AttachSheetContentDrag | undefined = useNoAttach,
) {
return forwardRef<T, P>(function ContentDragScrollView(props, ref) {
const attach = useAttach();
const [dragging, setDragging] = useState(false);
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
// Overriding one prop of `P` keeps it a `P`; TypeScript cannot prove that for a generic.
const scrollProps = {
...props,
scrollEnabled: !dragging && props.scrollEnabled !== false,
} as P;
return (
<ContentDragContext.Provider value={contentDrag}>
<Scroll {...scrollProps} ref={ref} />
</ContentDragContext.Provider>
);
});
}
@@ -150,17 +150,17 @@ export function ContextMenuTrigger({
);
const propsOnLongPress = props.onLongPress;
const handleLongPress = useCallback(
const handleNativeLongPress = useCallback(
(event: GestureResponderEvent) => {
if (isWeb) {
propsOnLongPress?.(event);
return;
}
openAtEvent(event);
propsOnLongPress?.(event);
},
[propsOnLongPress, openAtEvent],
);
// The web menu opens on right-click, not long press. Any onLongPress makes react-native-web cancel
// the click that ends a held press, and only a later press-in clears that, which Ctrl+click never
// gets. So on web, pass the caller's onLongPress through and nothing else.
const handleLongPress = isWeb ? propsOnLongPress : handleNativeLongPress;
const handleContextMenu = useCallback(
(event: unknown) => {
@@ -212,6 +212,6 @@ export function useIsolatedBottomSheetVisibility({
};
}
export { SheetVisibleFrame } from "./visible-frame";
export { SheetVisibleFrame, useBottomSheetSafeAreaPaddingStyle } from "./visible-frame";
export { systemBackPress } from "./back-press";
export { SheetHostScope } from "./host-scope";
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
import {
getBottomSheetSafeAreaPaddingBottom,
getBottomSheetVisibleContentHeight,
} from "./visible-frame-layout";
describe("getBottomSheetVisibleContentHeight", () => {
it("stops subtracting the retained keyboard height after the keyboard hides", () => {
@@ -13,6 +16,120 @@ describe("getBottomSheetVisibleContentHeight", () => {
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: true })).toBe(418);
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: false })).toBe(762);
});
it("ignores non-positive keyboard heights", () => {
const layout = {
containerHeight: 874,
contentPosition: 88,
handleHeight: 24,
keyboardHeight: -10,
isKeyboardVisible: true,
};
expect(getBottomSheetVisibleContentHeight(layout)).toBe(762);
});
});
describe("getBottomSheetSafeAreaPaddingBottom", () => {
it("keeps full safe-area clearance while the keyboard is hidden, even with retained keyboard height", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 344,
isKeyboardVisible: false,
safeAreaBottom: 48,
}),
).toBe(48);
});
it("keeps full safe-area clearance during Gorhom's first-open frame before heightWithinContainer is populated", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 0,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(48);
});
it("drops safe-area clearance to 0 when the keyboard height covers the bottom safe area", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 344,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(0);
});
it("preserves remaining safe-area clearance when keyboard height is smaller than the bottom inset", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 20,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(28);
});
it("returns 0 when there is no bottom safe-area inset", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 0,
isKeyboardVisible: false,
safeAreaBottom: 0,
}),
).toBe(0);
});
it("holds the invariant that visible frame height + paddingBottom never places the footer inside the bottom safe area across keyboard open/close transitions", () => {
const containerHeight = 1608;
const contentPosition = 161;
const handleHeight = 48;
const safeAreaBottom = 96;
const restingContentBottom = containerHeight - safeAreaBottom;
// Sequence matching real Android/iOS Gorhom keyboard transitions:
// 1. Resting closed
// 2. First open intermediate state (status=SHOWN before heightWithinContainer updates)
// 3. Open settled (heightWithinContainer = 598)
// 4. Close (status=HIDDEN while heightWithinContainer retains 598)
// 5. Partial accessory bar (heightWithinContainer = 40 < safeAreaBottom)
const transitions = [
{ isKeyboardVisible: false, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
{ isKeyboardVisible: true, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
{
isKeyboardVisible: true,
keyboardHeight: 598,
expectedContentBottom: containerHeight - 598,
},
{
isKeyboardVisible: false,
keyboardHeight: 598,
expectedContentBottom: restingContentBottom,
},
{ isKeyboardVisible: true, keyboardHeight: 40, expectedContentBottom: restingContentBottom },
];
for (const step of transitions) {
const height = getBottomSheetVisibleContentHeight({
containerHeight,
contentPosition,
handleHeight,
keyboardHeight: step.keyboardHeight,
isKeyboardVisible: step.isKeyboardVisible,
});
const paddingBottom = getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: step.keyboardHeight,
isKeyboardVisible: step.isKeyboardVisible,
safeAreaBottom,
});
// Inside a border-box frame at `contentPosition + handleHeight`, the bottom of the footer
// sits at `contentPosition + handleHeight + height - paddingBottom`.
const footerBottomY = contentPosition + handleHeight + height - paddingBottom;
expect(footerBottomY).toBe(step.expectedContentBottom);
expect(footerBottomY).toBeLessThanOrEqual(restingContentBottom);
}
});
});
// Below the lowest snap the frame must travel with the sheet, not shrink to the screen edge.
@@ -1,4 +1,4 @@
interface BottomSheetVisibleContentHeightInput {
export interface BottomSheetVisibleContentHeightInput {
containerHeight: number;
contentPosition: number;
lowestDetentPosition?: number;
@@ -7,6 +7,28 @@ interface BottomSheetVisibleContentHeightInput {
isKeyboardVisible: boolean;
}
export interface BottomSheetSafeAreaPaddingInput {
keyboardHeight: number;
isKeyboardVisible: boolean;
safeAreaBottom: number;
}
/**
* Effective keyboard height inside the sheet container.
*
* Gorhom retains `heightWithinContainer` after the keyboard hides, and on first show `status`
* flips to `SHOWN` before its reaction writes `heightWithinContainer`. Treating both states as 0
* keeps frame height and safe-area clearance in lockstep.
*/
export function getBottomSheetEffectiveKeyboardHeight(
keyboardHeight: number,
isKeyboardVisible: boolean,
): number {
"worklet";
if (!isKeyboardVisible || keyboardHeight <= 0) return 0;
return keyboardHeight;
}
export function getBottomSheetVisibleContentHeight({
containerHeight,
contentPosition,
@@ -18,8 +40,29 @@ export function getBottomSheetVisibleContentHeight({
"worklet";
if (containerHeight < 0 || handleHeight < 0) return 0;
const position = Math.min(contentPosition, lowestDetentPosition ?? contentPosition);
return Math.max(
0,
containerHeight - position - handleHeight - (isKeyboardVisible ? keyboardHeight : 0),
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
keyboardHeight,
isKeyboardVisible,
);
return Math.max(0, containerHeight - position - handleHeight - effectiveKeyboardHeight);
}
/**
* Bottom safe-area clearance derived from the same keyboard inset subtracted from
* `SheetVisibleFrame`'s height so both update in one UI-thread commit.
*
* Invariant: `effectiveKeyboardHeight + paddingBottom >= safeAreaBottom`.
*/
export function getBottomSheetSafeAreaPaddingBottom({
keyboardHeight,
isKeyboardVisible,
safeAreaBottom,
}: BottomSheetSafeAreaPaddingInput): number {
"worklet";
if (safeAreaBottom <= 0) return 0;
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
keyboardHeight,
isKeyboardVisible,
);
return Math.max(0, safeAreaBottom - effectiveKeyboardHeight);
}
@@ -2,21 +2,63 @@ import type { ReactNode } from "react";
import { View, StyleSheet } from "react-native";
import { KEYBOARD_STATUS, useBottomSheetInternal } from "@gorhom/bottom-sheet";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
getBottomSheetSafeAreaPaddingBottom,
getBottomSheetVisibleContentHeight,
} from "./visible-frame-layout";
/** Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap. */
/**
* UI-thread bottom safe-area padding synchronized with Gorhom's keyboard state.
* Use this for scrollable sheet bodies without a footer so content scrolls behind the system
* navigation bar while still clearing it at rest and dropping the padding in lockstep with
* `SheetVisibleFrame` when the keyboard opens or closes.
*/
export function useBottomSheetSafeAreaPaddingStyle(enabled = true) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const { animatedKeyboardState } = useBottomSheetInternal();
return useAnimatedStyle(() => {
const keyboard = animatedKeyboardState.get();
return {
paddingBottom: enabled
? getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
safeAreaBottom,
})
: 0,
};
}, [animatedKeyboardState, enabled, safeAreaBottom]);
}
/**
* Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap,
* and frame height + bottom safe-area clearance update together in one UI-thread commit so the
* footer never flashes behind the system navigation bar on keyboard show/hide.
*/
export function SheetVisibleFrame({
children,
footer,
safeAreaInset = "footer",
}: {
children: ReactNode;
footer?: ReactNode;
/**
* Where bottom safe-area clearance is applied:
* - `"footer"` (default): pads the frame whenever `footer` is present.
* - `"frame"`: always pads the frame, with or without a footer.
* - `"none"`: caller owns safe-area clearance.
*/
safeAreaInset?: "footer" | "frame" | "none";
}) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const { animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition } =
useBottomSheetInternal();
const padFrame = safeAreaInset === "frame" || (safeAreaInset === "footer" && Boolean(footer));
const visibleStyle = useAnimatedStyle(() => {
const { containerHeight, handleHeight } = animatedLayoutState.get();
const keyboard = animatedKeyboardState.get();
const isKeyboardVisible = keyboard.status === KEYBOARD_STATUS.SHOWN;
return {
height: getBottomSheetVisibleContentHeight({
containerHeight,
@@ -24,10 +66,24 @@ export function SheetVisibleFrame({
contentPosition: animatedPosition.get(),
lowestDetentPosition: animatedDetentsState.get().detents?.[0],
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
isKeyboardVisible,
}),
paddingBottom: padFrame
? getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible,
safeAreaBottom,
})
: 0,
};
}, [animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition]);
}, [
animatedDetentsState,
animatedKeyboardState,
animatedLayoutState,
animatedPosition,
padFrame,
safeAreaBottom,
]);
return (
<Animated.View style={[styles.frame, visibleStyle]}>
<View style={styles.body}>{children}</View>
+10 -43
View File
@@ -1,4 +1,4 @@
import { createContext, forwardRef, useContext, useMemo, useState, type Ref } from "react";
import { forwardRef, type Ref } from "react";
import {
ScrollView as NativeScrollView,
FlatList as NativeFlatList,
@@ -12,15 +12,13 @@ import {
type NativeViewGestureHandlerProps,
} from "react-native-gesture-handler";
import { isNative } from "@/constants/platform";
import {
useAttachSheetContentDrag,
useIsInsideBottomSheet,
type AttachSheetContentDrag,
} from "./bottom-sheet-scope";
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
import { withContentDrag } from "./content-drag";
// Both libraries forward to the RN FlatList instance. Their published ref types
// Both libraries forward to the RN FlatList and ScrollView instances. Their published ref types
// disagree about getScrollResponder (Gorhom) and include the component function
// in the instance intersection (RNGH); keep that type discrepancy at this boundary.
const SheetScroll = BottomSheetScrollView as unknown as typeof NativeScrollView;
const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
const HorizontalFlatList = GestureFlatList as unknown as <Item>(
props: FlatListProps<Item> & NativeViewGestureHandlerProps & { ref?: Ref<NativeFlatList<Item>> },
@@ -30,7 +28,7 @@ const HorizontalFlatList = GestureFlatList as unknown as <Item>(
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function ScrollView(props, ref) {
const inSheet = useIsInsideBottomSheet();
if (!inSheet) return <NativeScrollView {...props} ref={ref} />;
if (!inSheet) return <PageScrollView {...props} ref={ref} />;
if (props.horizontal) {
return isNative ? (
<GestureScrollView {...props} ref={ref} disallowInterruption />
@@ -42,42 +40,11 @@ export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
},
);
/**
* What a child that drags inside a sheet needs to keep the touch: it registers its drag gesture
* through `attach` so the sheet's pan waits for it, and `setActive(true)` stops the sheet's
* scroll until the drag ends. Outside a sheet scroll there is no `attach` and `setActive` does
* nothing.
*/
export interface ContentDrag {
attach: AttachSheetContentDrag | undefined;
setActive: (active: boolean) => void;
}
const PageScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(NativeScrollView);
const ContentDragContext = createContext<ContentDrag | null>(null);
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
export function useContentDrag(): ContentDrag {
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
}
const SheetScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function SheetScrollView(props, ref) {
const attach = useAttachSheetContentDrag();
const [dragging, setDragging] = useState(false);
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
return (
<BottomSheetScrollView
{...props}
scrollEnabled={!dragging && props.scrollEnabled !== false}
ref={ref}
>
<ContentDragContext.Provider value={contentDrag}>
{props.children}
</ContentDragContext.Provider>
</BottomSheetScrollView>
);
},
const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
SheetScroll,
useAttachSheetContentDrag,
);
function SheetAwareFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
@@ -146,3 +146,41 @@ export async function confirmRiskyWorktreeArchive(
destructive: true,
});
}
export async function confirmRiskyBulkWorktreeArchive(
input: {
totalCount: number;
riskyWorkspaces: readonly WorktreeArchiveConfirmationInput[];
},
labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS,
): Promise<boolean> {
const lines: string[] = [];
let singleRisky: WorktreeArchiveConfirmationInput | null = null;
for (const workspace of input.riskyWorkspaces) {
const reasons = buildWorktreeArchiveRiskReasons(workspace, labels);
if (reasons.length === 0) continue;
singleRisky = workspace;
lines.push(
i18n.t("workspace.git.actions.archiveWarning.bulkWorkspaceReason", {
workspaceName: workspace.workspaceName,
reason: reasons.join(", "),
}),
);
}
if (lines.length === 0) {
return true;
}
if (input.totalCount === 1 && singleRisky) {
return await confirmRiskyWorktreeArchive(singleRisky, labels);
}
return await confirmDialog({
title: i18n.t("workspace.git.actions.archiveWarning.bulkTitle", {
count: input.totalCount,
}),
message: lines.join("\n"),
confirmLabel: labels.confirm,
cancelLabel: labels.cancel,
destructive: true,
});
}
@@ -1,21 +0,0 @@
import { useSyncExternalStore } from "react";
import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
const subscribe = (onStoreChange: () => void) => {
const subscriptions = (["keyboardWillShow", "keyboardDidHide"] as const).map((event) =>
KeyboardEvents.addListener(event, onStoreChange),
);
return () => {
for (const subscription of subscriptions) {
subscription.remove();
}
};
};
export function useKeyboardVisibility(enabled = true): boolean {
return useSyncExternalStore(
subscribe,
() => (enabled ? KeyboardController.isVisible() : false),
() => false,
);
}
@@ -1,3 +0,0 @@
export function useKeyboardVisibility(_enabled = true): boolean {
return false;
}
+9
View File
@@ -960,6 +960,8 @@ export const ar: TranslationResources = {
},
archiveWarning: {
title: 'الأرشيف "{{workspaceName}}"؟',
bulkTitle: "أرشفة {{count}} مساحات عمل؟",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "أرشيف",
cancel: "يلغي",
uncommittedChanges: "تغييرات غير ملتزم بها",
@@ -1369,6 +1371,7 @@ export const ar: TranslationResources = {
rename: "إعادة تسمية مساحة العمل",
pin: "تثبيت في الأعلى",
unpin: "إلغاء التثبيت",
select: "تحديد",
archive: "أرشيف",
archiveWorkspace: "أرشفة مساحة العمل",
hideFromSidebar: "إخفاء من الشريط الجانبي",
@@ -1387,6 +1390,10 @@ export const ar: TranslationResources = {
submit: "إعادة تسمية",
invalidBranchName: "اسم الفرع غير صالح",
},
selection: {
count: "تم تحديد {{count}}",
exit: "إنهاء التحديد",
},
toasts: {
workspacePathUnavailable: "مسار Workspace غير متوفر",
pathCopied: "تم نسخ المسار",
@@ -1394,7 +1401,9 @@ export const ar: TranslationResources = {
hostDisconnected: "Host غير متصل",
hideFailed: "فشل في إخفاء مساحة العمل",
archiveFailed: "فشل في أرشفة مساحة العمل",
archiveMultipleFailed: "فشل في أرشفة {{count}} مساحات عمل",
archived: "تمت أرشفة مساحة العمل",
archivedCount: "تمت أرشفة {{count}} مساحات عمل",
undoArchive: "تراجع",
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
},
+9
View File
@@ -971,6 +971,8 @@ export const en = {
},
archiveWarning: {
title: 'Archive "{{workspaceName}}"?',
bulkTitle: "Archive {{count}} workspaces?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Archive",
cancel: "Cancel",
uncommittedChanges: "Uncommitted changes",
@@ -1380,6 +1382,7 @@ export const en = {
rename: "Rename workspace",
pin: "Pin to top",
unpin: "Unpin",
select: "Select",
archive: "Archive",
archiveWorkspace: "Archive workspace",
hideFromSidebar: "Hide from sidebar",
@@ -1398,6 +1401,10 @@ export const en = {
submit: "Rename",
invalidBranchName: "Invalid branch name",
},
selection: {
count: "{{count}} selected",
exit: "Exit selection",
},
toasts: {
workspacePathUnavailable: "Workspace path not available",
pathCopied: "Path copied",
@@ -1405,7 +1412,9 @@ export const en = {
hostDisconnected: "Host is not connected",
hideFailed: "Failed to hide workspace",
archiveFailed: "Failed to archive workspace",
archiveMultipleFailed: "Failed to archive {{count}} workspaces",
archived: "Workspace archived",
archivedCount: "{{count}} workspaces archived",
undoArchive: "Undo",
undoArchiveFailed: "Couldn't undo the archive",
},
+9
View File
@@ -994,6 +994,8 @@ export const es: TranslationResources = {
},
archiveWarning: {
title: '¿Archivo "{{workspaceName}}"?',
bulkTitle: "¿Archivar {{count}} espacios de trabajo?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Archivo",
cancel: "Cancelar",
uncommittedChanges: "Cambios no confirmados",
@@ -1406,6 +1408,7 @@ export const es: TranslationResources = {
rename: "Cambiar nombre del espacio de trabajo",
pin: "Anclar arriba",
unpin: "Desanclar",
select: "Seleccionar",
archive: "Archivo",
archiveWorkspace: "Archivar espacio de trabajo",
hideFromSidebar: "Ocultar de la barra lateral",
@@ -1424,6 +1427,10 @@ export const es: TranslationResources = {
submit: "Rebautizar",
invalidBranchName: "Nombre de sucursal no válido",
},
selection: {
count: "{{count}} seleccionados",
exit: "Salir de la selección",
},
toasts: {
workspacePathUnavailable: "RutaWorkspaceno disponible",
pathCopied: "Ruta copiada",
@@ -1431,7 +1438,9 @@ export const es: TranslationResources = {
hostDisconnected: "Hostno está conectado",
hideFailed: "No se pudo ocultar el espacio de trabajo",
archiveFailed: "No se pudo archivar el espacio de trabajo",
archiveMultipleFailed: "No se pudieron archivar {{count}} espacios de trabajo",
archived: "Espacio de trabajo archivado",
archivedCount: "{{count}} espacios de trabajo archivados",
undoArchive: "Deshacer",
undoArchiveFailed: "No se pudo deshacer el archivado",
},
+9
View File
@@ -986,6 +986,8 @@ export const fr: TranslationResources = {
},
archiveWarning: {
title: "Archiver « {{workspaceName}} » ?",
bulkTitle: "Archiver {{count}} espaces de travail ?",
bulkWorkspaceReason: "{{workspaceName}} : {{reason}}",
confirm: "Archiver",
cancel: "Annuler",
uncommittedChanges: "Modifications non commitées",
@@ -1399,6 +1401,7 @@ export const fr: TranslationResources = {
rename: "Renommer l’espace de travail",
pin: "Épingler en haut",
unpin: "Désépingler",
select: "Sélectionner",
archive: "Archiver",
archiveWorkspace: "Archiver l’espace de travail",
hideFromSidebar: "Masquer de la barre latérale",
@@ -1417,6 +1420,10 @@ export const fr: TranslationResources = {
submit: "Renommer",
invalidBranchName: "Nom de branche invalide",
},
selection: {
count: "{{count}} sélectionnés",
exit: "Quitter la sélection",
},
toasts: {
workspacePathUnavailable: "Chemin de l’espace de travail indisponible",
pathCopied: "Chemin copié",
@@ -1424,7 +1431,9 @@ export const fr: TranslationResources = {
hostDisconnected: "L’hôte n’est pas connecté",
hideFailed: "Impossible de masquer l’espace de travail",
archiveFailed: "Impossible d’archiver l’espace de travail",
archiveMultipleFailed: "Impossible d’archiver {{count}} espaces de travail",
archived: "Espace de travail archivé",
archivedCount: "{{count}} espaces de travail archivés",
undoArchive: "Annuler",
undoArchiveFailed: "Impossible d’annuler l’archivage",
},
+9
View File
@@ -974,6 +974,8 @@ export const ja: TranslationResources = {
},
archiveWarning: {
title: '"{{workspaceName}}"をアーカイブしますか?',
bulkTitle: "{{count}}件のワークスペースをアーカイブしますか?",
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
confirm: "アーカイブ",
cancel: "キャンセル",
uncommittedChanges: "未コミットの変更",
@@ -1384,6 +1386,7 @@ export const ja: TranslationResources = {
rename: "ワークスペースの名前を変更",
pin: "上部に固定",
unpin: "固定解除",
select: "選択",
archive: "アーカイブ",
archiveWorkspace: "ワークスペースをアーカイブ",
hideFromSidebar: "サイドバーから非表示",
@@ -1402,6 +1405,10 @@ export const ja: TranslationResources = {
submit: "名前を変更",
invalidBranchName: "無効なブランチ名",
},
selection: {
count: "{{count}}件選択中",
exit: "選択を終了",
},
toasts: {
workspacePathUnavailable: "ワークスペースパスが利用できません",
pathCopied: "パスをコピーしました",
@@ -1409,7 +1416,9 @@ export const ja: TranslationResources = {
hostDisconnected: "ホストが接続されていません",
hideFailed: "ワークスペースの非表示に失敗しました",
archiveFailed: "ワークスペースのアーカイブに失敗しました",
archiveMultipleFailed: "{{count}}件のワークスペースのアーカイブに失敗しました",
archived: "ワークスペースをアーカイブしました",
archivedCount: "{{count}}件のワークスペースをアーカイブしました",
undoArchive: "元に戻す",
undoArchiveFailed: "アーカイブを元に戻せませんでした",
},
+9
View File
@@ -967,6 +967,8 @@ export const ko: TranslationResources = {
},
archiveWarning: {
title: '"{{workspaceName}}"를 보관하시겠습니까?',
bulkTitle: "워크스페이스 {{count}}개를 보관하시겠습니까?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "보관",
cancel: "취소",
uncommittedChanges: "커밋되지 않은 변경 사항",
@@ -1376,6 +1378,7 @@ export const ko: TranslationResources = {
rename: "워크스페이스 이름 변경",
pin: "상단에 고정",
unpin: "고정 해제",
select: "선택",
archive: "보관",
archiveWorkspace: "워크스페이스 보관",
hideFromSidebar: "사이드바에서 숨기기",
@@ -1394,6 +1397,10 @@ export const ko: TranslationResources = {
submit: "이름 변경",
invalidBranchName: "잘못된 브랜치 이름",
},
selection: {
count: "{{count}}개 선택됨",
exit: "선택 종료",
},
toasts: {
workspacePathUnavailable: "워크스페이스 경로를 사용할 수 없습니다",
pathCopied: "경로가 복사되었습니다",
@@ -1401,7 +1408,9 @@ export const ko: TranslationResources = {
hostDisconnected: "호스트가 연결되어 있지 않습니다",
hideFailed: "워크스페이스를 숨기지 못했습니다",
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
archiveMultipleFailed: "워크스페이스 {{count}}개를 보관하지 못했습니다",
archived: "워크스페이스를 보관했습니다",
archivedCount: "워크스페이스 {{count}}개를 보관했습니다",
undoArchive: "실행 취소",
undoArchiveFailed: "보관을 취소하지 못했습니다",
},
+9
View File
@@ -984,6 +984,8 @@ export const ptBR: TranslationResources = {
},
archiveWarning: {
title: 'Arquivar "{{workspaceName}}"?',
bulkTitle: "Arquivar {{count}} workspaces?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Arquivar",
cancel: "Cancelar",
uncommittedChanges: "Alterações sem commit",
@@ -1396,6 +1398,7 @@ export const ptBR: TranslationResources = {
rename: "Renomear workspace",
pin: "Fixar no topo",
unpin: "Desafixar",
select: "Selecionar",
archive: "Arquivar",
archiveWorkspace: "Arquivar workspace",
hideFromSidebar: "Ocultar da barra lateral",
@@ -1414,6 +1417,10 @@ export const ptBR: TranslationResources = {
submit: "Renomear",
invalidBranchName: "Nome de branch inválido",
},
selection: {
count: "{{count}} selecionados",
exit: "Sair da seleção",
},
toasts: {
workspacePathUnavailable: "Caminho do workspace indisponível",
pathCopied: "Caminho copiado",
@@ -1421,7 +1428,9 @@ export const ptBR: TranslationResources = {
hostDisconnected: "Host não está conectado",
hideFailed: "Falha ao ocultar workspace",
archiveFailed: "Falha ao arquivar workspace",
archiveMultipleFailed: "Falha ao arquivar {{count}} workspaces",
archived: "Workspace arquivado",
archivedCount: "{{count}} workspaces arquivados",
undoArchive: "Desfazer",
undoArchiveFailed: "Não foi possível desfazer o arquivamento",
},
+9
View File
@@ -979,6 +979,8 @@ export const ru: TranslationResources = {
},
archiveWarning: {
title: "Архивировать «{{workspaceName}}»?",
bulkTitle: "Архивировать рабочие пространства ({{count}})?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Архивировать",
cancel: "Отмена",
uncommittedChanges: "Незафиксированные изменения",
@@ -1389,6 +1391,7 @@ export const ru: TranslationResources = {
rename: "Переименовать рабочее пространство",
pin: "Закрепить вверху",
unpin: "Открепить",
select: "Выбрать",
archive: "Архивировать",
archiveWorkspace: "Архивировать рабочее пространство",
hideFromSidebar: "Скрыть на боковой панели",
@@ -1407,6 +1410,10 @@ export const ru: TranslationResources = {
submit: "Переименовать",
invalidBranchName: "Недопустимое имя ветки",
},
selection: {
count: "Выбрано: {{count}}",
exit: "Выйти из выбора",
},
toasts: {
workspacePathUnavailable: "Путь к рабочему пространству недоступен",
pathCopied: "Путь скопирован",
@@ -1414,7 +1421,9 @@ export const ru: TranslationResources = {
hostDisconnected: "Хост не подключён",
hideFailed: "Не удалось скрыть рабочее пространство",
archiveFailed: "Не удалось архивировать рабочее пространство",
archiveMultipleFailed: "Не удалось архивировать рабочие пространства ({{count}})",
archived: "Рабочее пространство архивировано",
archivedCount: "Архивировано рабочих пространств: {{count}}",
undoArchive: "Отменить",
undoArchiveFailed: "Не удалось отменить архивацию",
},
+9
View File
@@ -952,6 +952,8 @@ export const zhCN: TranslationResources = {
},
archiveWarning: {
title: "归档「{{workspaceName}}」?",
bulkTitle: "归档 {{count}} 个工作区?",
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
confirm: "归档",
cancel: "取消",
uncommittedChanges: "未 commit 的变更",
@@ -1359,6 +1361,7 @@ export const zhCN: TranslationResources = {
rename: "重命名 workspace",
pin: "置顶",
unpin: "取消置顶",
select: "选择",
archive: "归档",
archiveWorkspace: "归档工作区",
hideFromSidebar: "从侧边栏隐藏",
@@ -1376,6 +1379,10 @@ export const zhCN: TranslationResources = {
submit: "重命名",
invalidBranchName: "无效的分支名称",
},
selection: {
count: "已选 {{count}} 项",
exit: "退出选择",
},
toasts: {
workspacePathUnavailable: "Workspace 路径不可用",
pathCopied: "路径已复制",
@@ -1383,7 +1390,9 @@ export const zhCN: TranslationResources = {
hostDisconnected: "Host 未连接",
hideFailed: "隐藏 workspace 失败",
archiveFailed: "归档工作区失败",
archiveMultipleFailed: "归档 {{count}} 个工作区失败",
archived: "工作区已归档",
archivedCount: "已归档 {{count}} 个工作区",
undoArchive: "撤销",
undoArchiveFailed: "无法撤销归档",
},
+2
View File
@@ -14,3 +14,5 @@ export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
export { useHardwareKeyboardPresent } from "./availability";
export { readPressModifiers } from "./internal/press-modifiers";
export type { PressModifiers } from "./internal/press-modifiers";
@@ -9,6 +9,10 @@ export interface OverlayRegistration {
*/
keys: readonly string[];
onKeyDown(event: KeyboardInputEvent): boolean;
/**
* Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults
* to whatever had focus when the overlay opened.
*/
restoreFocusRef?: RefObject<unknown>;
manageFocus?: boolean;
}
@@ -3,12 +3,29 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays
import type { OverlayRegistration } from "./overlay-contract";
type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean;
/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */
interface FocusTarget {
focus(): void;
}
function isFocusTarget(value: unknown): value is FocusTarget {
return (
typeof value === "object" &&
value !== null &&
typeof (value as Partial<FocusTarget>).focus === "function"
);
}
function canRestoreFocusTo(target: FocusTarget): boolean {
return !(target instanceof HTMLElement) || document.contains(target);
}
interface WebOverlayEntry {
getLayer: () => number;
getKeys: () => readonly string[];
getScope: () => HTMLElement | null;
getKeyHandler: () => WebOverlayKeyHandler;
restoreFocus: HTMLElement | null;
restoreFocus: FocusTarget | null;
manageFocus: boolean;
}
@@ -156,7 +173,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
entry.manageFocus &&
options?.restoreFocus !== false &&
entry.restoreFocus &&
document.contains(entry.restoreFocus)
canRestoreFocusTo(entry.restoreFocus)
) {
entry.restoreFocus.focus();
}
@@ -181,7 +198,7 @@ export function useOverlayRegistration({
keysRef.current = keys;
const layerRef = useRef(layer);
const keyHandlerRef = useRef(onKeyDown);
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const registeredRef = useRef(false);
@@ -193,7 +210,7 @@ export function useOverlayRegistration({
keyHandlerRef.current = onKeyDown;
if (active && !wasActiveRef.current && typeof document !== "undefined") {
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
if (requestedRestoreTarget instanceof HTMLElement) {
if (isFocusTarget(requestedRestoreTarget)) {
capturedRestoreFocusRef.current = requestedRestoreTarget;
} else {
capturedRestoreFocusRef.current =
@@ -0,0 +1,111 @@
import { getShortcutOs } from "@/utils/shortcut-platform";
export type HeldModifierKey = "Shift" | "Meta" | "Control";
export interface HeldModifierKeyEvent {
key: string;
code?: string;
shiftKey: boolean;
metaKey: boolean;
ctrlKey: boolean;
}
export interface HeldModifierTracker {
isDown(key: HeldModifierKey): boolean;
handleKeyDown(event: HeldModifierKeyEvent): void;
handleKeyUp(event: HeldModifierKeyEvent): void;
reset(): void;
}
const MODIFIER_FLAGS = {
Shift: "shiftKey",
Meta: "metaKey",
Control: "ctrlKey",
} as const satisfies Record<HeldModifierKey, keyof HeldModifierKeyEvent>;
const MODIFIER_KEYS = Object.keys(MODIFIER_FLAGS) as HeldModifierKey[];
/**
* Tracks which physical modifier keys are held across DOM and native hardware keyboard streams so
* press handlers that omit modifier flags (native GestureResponderEvent, touch-synthesized clicks)
* can still observe Shift+tap or Cmd+tap from a hardware keyboard.
*/
export function createHeldModifierTracker(): HeldModifierTracker {
const pressedCodes: Record<HeldModifierKey, Set<string>> = {
Shift: new Set(),
Meta: new Set(),
Control: new Set(),
};
// A key reported without a modifier's flag means that modifier's key-up was swallowed.
const clearReleased = (event: HeldModifierKeyEvent) => {
for (const modifier of MODIFIER_KEYS) {
if (event.key !== modifier && !event[MODIFIER_FLAGS[modifier]]) {
pressedCodes[modifier].clear();
}
}
};
return {
isDown: (key) => pressedCodes[key].size > 0,
handleKeyDown(event) {
const modifier = MODIFIER_KEYS.find((key) => key === event.key);
if (modifier) {
pressedCodes[modifier].add(event.code || modifier);
}
clearReleased(event);
},
handleKeyUp(event) {
const modifier = MODIFIER_KEYS.find((key) => key === event.key);
if (modifier) {
pressedCodes[modifier].delete(event.code || modifier);
if (!event[MODIFIER_FLAGS[modifier]]) {
pressedCodes[modifier].clear();
}
}
clearReleased(event);
},
reset() {
for (const modifier of MODIFIER_KEYS) {
pressedCodes[modifier].clear();
}
},
};
}
export const heldModifiers = createHeldModifierTracker();
/**
* Modifiers that accompanied a pointer press. `mod` is the platform primary modifier the shortcut
* layer binds as `mod`: Cmd on macOS/iOS/iPadOS, Ctrl on Windows, Linux and Android. Ctrl on macOS
* is the secondary click, so it never counts as `mod` there.
*/
export interface PressModifiers {
shift: boolean;
mod: boolean;
}
interface PressModifierContext {
isMac: boolean;
held: Pick<HeldModifierTracker, "isDown">;
}
export function readPressModifiers(
event: unknown,
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
): PressModifiers {
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
return {
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
};
}
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): boolean {
if (typeof event !== "object" || event === null) return false;
if (Reflect.get(event, flag) === true) return true;
const nativeEvent = Reflect.get(event, "nativeEvent");
return (
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, flag) === true
);
}
@@ -1,3 +1,4 @@
import { AppState } from "react-native";
import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract";
import {
setHardwareKeyboardClaimedShortcuts,
@@ -7,6 +8,14 @@ import {
import { createHardwareKeyboardSource } from "./native";
const hardwareKeyboard = createHardwareKeyboardSource({
subscribe: subscribeHardwareKeyboard,
subscribeBlur: (onBlur) => {
const subscription = AppState.addEventListener("change", (nextState) => {
if (nextState !== "active") {
onBlur();
}
});
return () => subscription.remove();
},
setOverlayKeys: setHardwareKeyboardOverlayKeys,
setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts,
});
@@ -9,6 +9,7 @@ import {
import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware";
interface HardwareKeySource {
subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void;
subscribeBlur?(handler: () => void): () => void;
setOverlayKeys(keys: readonly string[]): void;
setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void;
}
@@ -78,7 +79,9 @@ export function createHardwareKeyboardSource(source: HardwareKeySource) {
nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())),
);
});
const unsubscribeBlur = source.subscribeBlur?.(() => handlers.blur()) ?? (() => {});
return () => {
unsubscribeBlur();
unsubscribeHardware();
unsubscribeFocus();
unsubscribeCommandCenter();
@@ -269,4 +269,142 @@ describe("hardware source adapter", () => {
expect(claimed).toEqual([]);
releaseFinal();
});
it("forwards native blur events and unsubscribes on detach", async () => {
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
const blurListeners = new Set<() => void>();
let blurCalls = 0;
const detach = createHardwareKeyboardSource({
subscribe: () => () => {},
subscribeBlur(listener) {
blurListeners.add(listener);
return () => {
blurListeners.delete(listener);
};
},
setOverlayKeys() {},
setClaimedShortcuts() {},
}).attach({
keyDown() {},
keyUp() {},
blur() {
blurCalls += 1;
},
commandCenterOpen: () => false,
subscribeCommandCenter: () => () => {},
});
for (const listener of blurListeners) listener();
expect(blurCalls).toBe(1);
detach();
expect(blurListeners.size).toBe(0);
});
});
function modifierKey(
key: string,
code: string,
flags: { shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean } = {},
) {
return { key, code, shiftKey: false, metaKey: false, ctrlKey: false, ...flags };
}
describe("held modifier tracking", () => {
it("tracks left/right Shift holds, self-heals on non-shifted keys, and resets on blur", async () => {
const { createHeldModifierTracker } = await import("./internal/press-modifiers");
const tracker = createHeldModifierTracker();
expect(tracker.isDown("Shift")).toBe(false);
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyDown(modifierKey("Shift", "ShiftRight", { shiftKey: true }));
tracker.handleKeyUp(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyUp(modifierKey("Shift", "ShiftRight"));
expect(tracker.isDown("Shift")).toBe(false);
// Self-heals if a Shift key-up was swallowed by the OS.
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyDown(modifierKey("a", "KeyA"));
expect(tracker.isDown("Shift")).toBe(false);
// Clears on blur / backgrounding.
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.reset();
expect(tracker.isDown("Shift")).toBe(false);
});
it("tracks Cmd and Ctrl holds independently of Shift", async () => {
const { createHeldModifierTracker } = await import("./internal/press-modifiers");
const tracker = createHeldModifierTracker();
tracker.handleKeyDown(modifierKey("Meta", "MetaLeft", { metaKey: true }));
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { metaKey: true, shiftKey: true }));
expect([tracker.isDown("Meta"), tracker.isDown("Shift"), tracker.isDown("Control")]).toEqual([
true,
true,
false,
]);
tracker.handleKeyUp(modifierKey("Shift", "ShiftLeft", { metaKey: true }));
expect([tracker.isDown("Meta"), tracker.isDown("Shift")]).toEqual([true, false]);
// A key reported without the Meta flag means its key-up was swallowed.
tracker.handleKeyDown(modifierKey("a", "KeyA"));
expect(tracker.isDown("Meta")).toBe(false);
tracker.handleKeyDown(modifierKey("Control", "ControlRight", { ctrlKey: true }));
expect(tracker.isDown("Control")).toBe(true);
tracker.handleKeyUp(modifierKey("Control", "ControlRight"));
expect(tracker.isDown("Control")).toBe(false);
});
});
describe("press modifiers", () => {
it("reads Shift and the platform primary modifier from a pointer press", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
const mac = { isMac: true, held };
const other = { isMac: false, held };
expect(readPressModifiers({ shiftKey: true }, mac)).toEqual({ shift: true, mod: false });
expect(readPressModifiers({ nativeEvent: { shiftKey: true } }, other)).toEqual({
shift: true,
mod: false,
});
expect(readPressModifiers({ metaKey: true }, mac)).toEqual({ shift: false, mod: true });
expect(readPressModifiers({ ctrlKey: true }, other)).toEqual({ shift: false, mod: true });
// Ctrl+click is the secondary click on macOS, and Windows/Linux have no Cmd.
expect(readPressModifiers({ ctrlKey: true }, mac)).toEqual({ shift: false, mod: false });
expect(readPressModifiers({ metaKey: true }, other)).toEqual({ shift: false, mod: false });
expect(readPressModifiers(null, mac)).toEqual({ shift: false, mod: false });
});
it("falls back to held hardware keys when a native press omits modifiers", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
const responderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { metaKey: true }));
expect(readPressModifiers(responderEvent, { isMac: true, held })).toEqual({
shift: false,
mod: true,
});
expect(readPressModifiers(responderEvent, { isMac: false, held })).toEqual({
shift: false,
mod: false,
});
held.reset();
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(readPressModifiers(responderEvent, { isMac: true, held })).toEqual({
shift: true,
mod: false,
});
});
});
+16 -3
View File
@@ -1,6 +1,7 @@
import { usesDesktopBindings } from "./internal/conventions";
import { createKeyboardPipeline } from "./internal/pipeline";
import { overlays } from "./internal/overlays";
import { heldModifiers } from "./internal/press-modifiers";
import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources";
import type { KeyboardSourceInput } from "./internal/sources/contract";
import type { KeyboardInputEvent } from "./internal/overlays";
@@ -249,19 +250,30 @@ export function useKeyboardShortcuts({
[getContext, getBindings, isCapturing, dispatchMatch, beforeResolve, chordChanged],
);
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
heldModifiers.handleKeyDown(input.event);
return pipeline.keyDown(input);
});
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
heldModifiers.handleKeyUp(event);
const key = event.key ?? "";
if (key === badgeModifierKey) {
setBadgeModifierDown(false);
}
});
const handleBlur = useStableEvent(() => {
heldModifiers.reset();
resetModifiers();
});
useEffect(() => {
if (!enabled) return;
const detach = attachKeyboardSources({
keyDown: pipeline.keyDown,
keyDown: handleKeyDown,
keyUp: handleKeyUp,
blur: resetModifiers,
blur: handleBlur,
commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen,
subscribeCommandCenter: (listener) =>
useKeyboardShortcutsStore.subscribe((state, previous) => {
@@ -270,7 +282,8 @@ export function useKeyboardShortcuts({
});
return () => {
detach();
heldModifiers.reset();
pipeline.dispose();
};
}, [enabled, pipeline, handleKeyUp, resetModifiers]);
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
}
@@ -1578,9 +1578,18 @@ export function NewWorkspaceScreen({
? t("newWorkspace.refPicker.searching")
: t("newWorkspace.refPicker.noMatchingRefs");
// The prompt is where the user types; when a field's picker closes, focus returns there rather
// than to whatever had focus when the picker opened. A terminal profile that takes no prompt
// shows a read-only command preview, so its pickers keep returning focus to their field.
const composerFocusRef = useRef<{ focus: () => void } | null>(null);
const handleComposerFocusInput = useCallback((focus: () => void) => {
composerFocusRef.current = { focus };
}, []);
const formStack = useNewWorkspaceForm({
isCompact,
isPending,
restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined,
pluginItems: (
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
),
@@ -1682,6 +1691,7 @@ export function NewWorkspaceScreen({
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
error={errorMessage}
/>
) : (
@@ -1712,6 +1722,7 @@ export function NewWorkspaceScreen({
clearDraft={handleClearDraft}
autoFocus
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
error={errorMessage}
@@ -67,6 +67,11 @@ export interface NewWorkspaceFormProps {
isPending: boolean;
/** Plugin fields, drawn after the base ref. */
pluginItems: ReactNode;
/**
* Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without
* one, focus returns to the field that opened the picker.
*/
restoreFocusRef?: RefObject<unknown>;
project: PickerControl & {
options: ComboboxOption[];
projectByOptionId: Map<string, HostProjectListItem>;
@@ -373,7 +378,17 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
*/
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
const { t } = useTranslation();
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
const {
isCompact,
isPending,
pluginItems,
restoreFocusRef,
project,
host,
isolation,
base,
launch,
} = props;
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
const projectPicker = useProjectPicker(project, isPending);
const isolationPicker = useIsolationPicker({
@@ -432,6 +447,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
open={host.openState}
onOpenChange={host.onOpenChange}
anchorRef={host.anchorRef}
restoreFocusRef={restoreFocusRef}
includeAddHost
onAddHost={host.onAddHost}
addHostTestID="new-workspace-host-picker-add-host"
@@ -525,6 +541,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={project.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText="No projects available."
renderOption={projectPicker.renderOption}
footer={projectPicker.footer}
@@ -539,6 +556,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
desktopPlacement="bottom-start"
anchorRef={isolation.anchorRef}
restoreFocusRef={restoreFocusRef}
desktopMinWidth={280}
renderOption={isolationPicker.renderOption}
/>
@@ -555,6 +573,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={440}
anchorRef={base.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={base.emptyText}
toolbar={refPicker.toolbar}
renderOption={refPicker.renderOption}
@@ -571,6 +590,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={worktreePicker.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={t("newWorkspace.worktreePicker.empty")}
renderOption={worktreePicker.renderOption}
/>
@@ -0,0 +1,8 @@
export {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "./internal/selection-store";
export { SidebarSelectionHost } from "./internal/sidebar-selection-host";
export { useWorkspaceSelectionPress } from "./internal/workspace-selection-press";
@@ -0,0 +1,280 @@
import { describe, expect, it, vi } from "vitest";
import type { ToastApi } from "@/components/toast-host";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import {
archiveSelectedWorkspaces,
type BulkArchiveClient,
type BulkArchiveWorkspacesDeps,
} from "./archive-selected";
function makeEntry(
overrides: Partial<SidebarWorkspaceEntry> & { workspaceId: string },
): SidebarWorkspaceEntry {
return {
workspaceKey: `srv:${overrides.workspaceId}`,
serverId: "srv",
projectViewKey: "prj-view",
projectName: "Repo",
projectRootPath: "/repo",
workspaceDirectory: `/repo/${overrides.workspaceId}`,
workspaceDirectoryLabel: overrides.workspaceId,
projectKind: "git",
workspaceKind: "local_checkout",
name: overrides.workspaceId,
title: null,
currentBranch: overrides.workspaceId,
statusBucket: "done",
statusEnteredAt: null,
archivingAt: null,
diffStat: null,
prHint: null,
pinnedAt: null,
background: false,
labels: [],
scripts: [],
hasRunningScripts: false,
archiveHasUncommittedChanges: null,
archiveUnpushedCommitCount: null,
...overrides,
};
}
function createFakeToast(): { toast: ToastApi; errors: string[] } {
const errors: string[] = [];
return {
errors,
toast: {
show: () => () => {},
copied: () => {},
error: (message) => errors.push(message),
},
};
}
function createFakeClient(): BulkArchiveClient {
return {
archiveWorkspace: async () => ({ error: null }),
undoWorkspaceArchive: async () => {},
getCheckoutStatus: async () =>
({
isGit: true,
isDirty: false,
aheadOfOrigin: 0,
}) as Awaited<ReturnType<BulkArchiveClient["getCheckoutStatus"]>>,
};
}
describe("archiveSelectedWorkspaces", () => {
it("archives multiple workspaces with one undo batch and redirects active workspace first", async () => {
const order: string[] = [];
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const confirmRiskyBulkArchive = vi.fn(async () => true);
const deps: BulkArchiveWorkspacesDeps = {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: async () => ({ isDirty: false, aheadOfOrigin: 0 }),
confirmRiskyBulkArchive,
archiveWithUndo: async (input) => {
order.push(
`archive:${input.entries.map((entry) => entry.workspace.workspaceId).join(",")}`,
);
return { failures: [], showPartialFailure: () => false };
},
archiveWithoutUndo: async () => "archived",
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: (workspace) => {
order.push(`redirect:${workspace.workspaceId}`);
},
};
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: () => order.push("exit-selection"),
deps,
});
expect(ok).toBe(true);
expect(errors).toEqual([]);
expect(order).toEqual(["redirect:w1", "redirect:w2", "exit-selection", "archive:w1,w2"]);
expect(confirmRiskyBulkArchive).not.toHaveBeenCalled();
});
it("keeps select mode open when the user cancels a risky worktree confirmation", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const onArchiveStarted = vi.fn();
const archiveWithUndo = vi.fn(async () => ({
failures: [],
showPartialFailure: () => false,
}));
const confirmRiskyBulkArchive = vi.fn(async () => false);
const ok = await archiveSelectedWorkspaces({
workspaces: [
makeEntry({ workspaceId: "w1", workspaceKind: "worktree", name: "feat-wip" }),
makeEntry({ workspaceId: "w2", workspaceKind: "local_checkout", name: "main" }),
],
toast,
onArchiveStarted,
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: async () => ({ isDirty: true, aheadOfOrigin: 1 }),
confirmRiskyBulkArchive,
archiveWithUndo,
archiveWithoutUndo: async () => "archived",
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual([]);
expect(confirmRiskyBulkArchive).toHaveBeenCalledWith({
totalCount: 2,
riskyWorkspaces: [
{
workspaceName: "feat-wip",
diffStat: null,
isDirty: true,
aheadOfOrigin: 1,
},
],
});
expect(onArchiveStarted).not.toHaveBeenCalled();
expect(archiveWithUndo).not.toHaveBeenCalled();
});
it("shows a disconnect error and aborts before archiving when any host is offline", async () => {
const { toast, errors } = createFakeToast();
const onArchiveStarted = vi.fn();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" })],
toast,
onArchiveStarted,
deps: {
getClient: () => null,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: vi.fn(),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual(["Host is not connected"]);
expect(onArchiveStarted).not.toHaveBeenCalled();
});
it("reports multi-workspace failures when more than one archive fails", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{ workspace: { serverId: "srv", workspaceId: "w1" }, error: new Error("boom 1") },
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("boom 2") },
],
showPartialFailure: () => false,
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual(["Failed to archive 2 workspaces"]);
});
it("keeps Undo open via showPartialFailure instead of replacing it with toast.error on partial failure", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const partialErrors: string[] = [];
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("Host offline") },
],
showPartialFailure: (message) => {
partialErrors.push(message);
return true;
},
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(partialErrors).toEqual(["Host offline"]);
expect(errors).toEqual([]);
});
it("routes a late failure from a superseded batch to fallbackErrorToast so a newer batch keeps its Undo", async () => {
const client = createFakeClient();
const sidebar = createFakeToast();
const app = createFakeToast();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" })],
toast: sidebar.toast,
fallbackErrorToast: app.toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{
workspace: { serverId: "srv", workspaceId: "w1" },
error: new Error("Host timed out"),
},
],
// This batch's own undo window was closed when a newer batch superseded it.
showPartialFailure: () => false,
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => true,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(sidebar.errors).toEqual([]);
expect(app.errors).toEqual(["Host timed out"]);
});
});
@@ -0,0 +1,197 @@
import type { ToastApi } from "@/components/toast-host";
import type { CheckoutStatusClient } from "@/git/checkout-status-cache";
import {
confirmRiskyBulkWorktreeArchive,
readWorktreeArchiveRisk,
type WorktreeArchiveConfirmationInput,
} from "@/git/worktree-archive-warning";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { i18n } from "@/i18n/i18next";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import {
archiveWorkspacesWithUndo,
hasUndoableWorkspaceArchive,
supportsWorkspaceArchiveUndo,
type UndoableWorkspaceArchiveClient,
} from "@/workspace/archive-undo";
import {
archiveWorkspaceOptimistically,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
export interface BulkArchiveClient extends UndoableWorkspaceArchiveClient, CheckoutStatusClient {}
export interface BulkArchiveWorkspacesDeps {
getClient: (serverId: string) => BulkArchiveClient | null;
supportsUndo: (serverId: string) => boolean;
readWorktreeRisk: typeof readWorktreeArchiveRisk;
confirmRiskyBulkArchive: typeof confirmRiskyBulkWorktreeArchive;
archiveWithUndo: typeof archiveWorkspacesWithUndo;
archiveWithoutUndo: typeof archiveWorkspaceOptimistically;
hasActiveUndo: () => boolean;
purgeWorkspaceState: (workspace: WorkspaceArchiveTarget) => void;
redirectActiveWorkspace: (workspace: WorkspaceArchiveTarget) => void;
}
function defaultPurgeWorkspaceState(workspace: WorkspaceArchiveTarget): void {
const workspaceKey = buildWorkspaceTabPersistenceKey(workspace);
if (workspaceKey) {
useWorkspaceLayoutStore.getState().purgeWorkspace(workspaceKey);
}
}
export function createDefaultBulkArchiveDeps(
getActiveWorkspaceSelection: () => ActiveWorkspaceSelection | null,
): BulkArchiveWorkspacesDeps {
return {
getClient: (serverId) => getHostRuntimeStore().getClient(serverId),
supportsUndo: supportsWorkspaceArchiveUndo,
readWorktreeRisk: readWorktreeArchiveRisk,
confirmRiskyBulkArchive: confirmRiskyBulkWorktreeArchive,
archiveWithUndo: archiveWorkspacesWithUndo,
archiveWithoutUndo: archiveWorkspaceOptimistically,
hasActiveUndo: hasUndoableWorkspaceArchive,
purgeWorkspaceState: defaultPurgeWorkspaceState,
redirectActiveWorkspace: (workspace) => {
redirectIfArchivingActiveWorkspace({
serverId: workspace.serverId,
workspaceId: workspace.workspaceId,
activeWorkspaceSelection: getActiveWorkspaceSelection(),
});
},
};
}
function formatArchiveFailureMessage(failures: ReadonlyArray<{ error: unknown }>): string {
if (failures.length > 1) {
return i18n.t("sidebar.workspace.toasts.archiveMultipleFailed", { count: failures.length });
}
const error = failures[0]?.error;
return error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed");
}
interface ResolvedWorkspaceTarget {
entry: SidebarWorkspaceEntry;
client: BulkArchiveClient;
}
export async function archiveSelectedWorkspaces(input: {
workspaces: readonly SidebarWorkspaceEntry[];
toast: ToastApi;
fallbackErrorToast?: ToastApi;
onArchiveStarted: () => void;
deps: BulkArchiveWorkspacesDeps;
}): Promise<boolean> {
const { workspaces, toast, fallbackErrorToast, onArchiveStarted, deps } = input;
if (workspaces.length === 0) return false;
const resolved: ResolvedWorkspaceTarget[] = [];
for (const entry of workspaces) {
const client = deps.getClient(entry.serverId);
if (!client) {
toast.error(i18n.t("sidebar.workspace.toasts.hostDisconnected"));
return false;
}
resolved.push({ entry, client });
}
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
if (worktrees.length > 0) {
try {
const risks = await Promise.all(
worktrees.map(async ({ entry, client }) => {
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
return {
workspaceName: entry.name,
diffStat: entry.diffStat,
isDirty: risk.isDirty,
aheadOfOrigin: risk.aheadOfOrigin,
} satisfies WorktreeArchiveConfirmationInput;
}),
);
riskyWorkspaces.push(...risks);
} catch (error) {
toast.error(
error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed"),
);
return false;
}
}
if (riskyWorkspaces.length > 0) {
const confirmed = await deps.confirmRiskyBulkArchive({
totalCount: resolved.length,
riskyWorkspaces,
});
if (!confirmed) {
return false;
}
}
// Redirect before optimistic removal hides the active workspace from the session store.
for (const { entry } of resolved) {
deps.redirectActiveWorkspace({ serverId: entry.serverId, workspaceId: entry.workspaceId });
}
onArchiveStarted();
const undoable: ResolvedWorkspaceTarget[] = [];
const legacy: ResolvedWorkspaceTarget[] = [];
for (const item of resolved) {
if (deps.supportsUndo(item.entry.serverId)) {
undoable.push(item);
} else {
legacy.push(item);
}
}
const failures: Array<{ error: unknown }> = [];
let showPartialFailure: (message: string) => boolean = () => false;
await Promise.all([
undoable.length > 0
? (async () => {
const result = await deps.archiveWithUndo({
entries: undoable.map(({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
return {
client,
workspace,
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
};
}),
toast,
});
failures.push(...result.failures);
showPartialFailure = result.showPartialFailure;
})()
: Promise.resolve(),
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
...legacy.map(async ({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
try {
await deps.archiveWithoutUndo({ client, workspace });
deps.purgeWorkspaceState(workspace);
} catch (error) {
failures.push({ error });
}
}),
]);
if (failures.length > 0) {
const errorMessage = formatArchiveFailureMessage(failures);
if (!showPartialFailure(errorMessage)) {
// If a newer batch now owns the sidebar Undo toast, surface this older failure on the
// app-level toast instead of displacing the active Undo window and purging its layouts.
const errorToast = deps.hasActiveUndo() ? (fallbackErrorToast ?? toast) : toast;
errorToast.error(errorMessage);
}
}
return failures.length === 0;
}
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import {
enterWorkspaceSelection,
exitWorkspaceSelection,
INITIAL_WORKSPACE_SELECTION_STATE,
reconcileWorkspaceSelection,
selectWorkspaceRange,
toggleWorkspaceSelection,
} from "./selection-state";
describe("sidebar workspace selection state", () => {
it("enters selection with the clicked workspace as anchor", () => {
const state = enterWorkspaceSelection("ws-2");
expect({
active: state.active,
selected: [...state.selectedKeys],
anchorKey: state.anchorKey,
}).toEqual({
active: true,
selected: ["ws-2"],
anchorKey: "ws-2",
});
});
it("toggles workspaces on plain click without needing Shift", () => {
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3"]);
expect(state.anchorKey).toBe("ws-3");
state = toggleWorkspaceSelection(state, "ws-1");
expect([...state.selectedKeys]).toEqual(["ws-3"]);
expect(state.anchorKey).toBe("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
expect(state.active).toBe(true);
expect([...state.selectedKeys]).toEqual([]);
});
it("selects an inclusive range on Shift+click in either direction while keeping prior picks", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5"];
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
state = selectWorkspaceRange(state, "ws-5", visible);
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3", "ws-4", "ws-5"]);
expect(state.anchorKey).toBe("ws-3");
const backward = selectWorkspaceRange(enterWorkspaceSelection("ws-4"), "ws-2", visible);
expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]);
});
it("replaces the previous Shift range so a closer Shift+click shrinks it, like Finder", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5", "ws-6"];
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
state = selectWorkspaceRange(state, "ws-6", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-3", "ws-4", "ws-5", "ws-6"]);
state = selectWorkspaceRange(state, "ws-4", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-3", "ws-4"]);
// Crossing over the anchor flips the range without dropping the earlier pick.
state = selectWorkspaceRange(state, "ws-2", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-2", "ws-3"]);
expect(state.anchorKey).toBe("ws-3");
});
it("commits the Shift range once a toggle moves the anchor", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5", "ws-6"];
let state = enterWorkspaceSelection("ws-1");
state = selectWorkspaceRange(state, "ws-3", visible);
state = toggleWorkspaceSelection(state, "ws-5");
// The new anchor is ws-5; shrinking its range must keep ws-1..ws-3.
state = selectWorkspaceRange(state, "ws-6", visible);
state = selectWorkspaceRange(state, "ws-5", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-2", "ws-3", "ws-5"]);
});
it("falls back to adding the target when the anchor is no longer in the visible list", () => {
const state = selectWorkspaceRange(enterWorkspaceSelection("ws-hidden"), "ws-2", [
"ws-1",
"ws-2",
]);
expect([...state.selectedKeys]).toEqual(["ws-hidden", "ws-2"]);
expect(state.anchorKey).toBe("ws-2");
});
it("reconciles removed workspaces and clears a missing anchor", () => {
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-2");
const reconciled = reconcileWorkspaceSelection(state, new Set(["ws-1"]));
expect({
active: reconciled.active,
selected: [...reconciled.selectedKeys],
anchorKey: reconciled.anchorKey,
}).toEqual({
active: true,
selected: ["ws-1"],
anchorKey: null,
});
});
it("resets completely on exit", () => {
expect(exitWorkspaceSelection()).toBe(INITIAL_WORKSPACE_SELECTION_STATE);
});
});
@@ -0,0 +1,120 @@
export interface WorkspaceSelectionState {
active: boolean;
selectedKeys: ReadonlySet<string>;
anchorKey: string | null;
/**
* Selection as it stood before the current run of Shift+clicks from `anchorKey`. Each Shift+click
* rebuilds the selection from this base, so a closer Shift+click shrinks the range like Finder.
* Null until the first Shift+click after the anchor moves.
*/
rangeBaseKeys: ReadonlySet<string> | null;
}
const EMPTY_KEYS: ReadonlySet<string> = new Set();
export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = {
active: false,
selectedKeys: EMPTY_KEYS,
anchorKey: null,
rangeBaseKeys: null,
};
export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState {
return {
active: true,
selectedKeys: new Set([workspaceKey]),
anchorKey: workspaceKey,
rangeBaseKeys: null,
};
}
export function toggleWorkspaceSelection(
state: WorkspaceSelectionState,
workspaceKey: string,
): WorkspaceSelectionState {
if (!state.active) {
return enterWorkspaceSelection(workspaceKey);
}
const next = new Set(state.selectedKeys);
if (!next.delete(workspaceKey)) {
next.add(workspaceKey);
}
return {
active: true,
selectedKeys: next,
anchorKey: workspaceKey,
rangeBaseKeys: null,
};
}
export function selectWorkspaceRange(
state: WorkspaceSelectionState,
targetKey: string,
orderedVisibleKeys: readonly string[],
): WorkspaceSelectionState {
if (!state.active) {
return enterWorkspaceSelection(targetKey);
}
const anchorIndex = state.anchorKey ? orderedVisibleKeys.indexOf(state.anchorKey) : -1;
const targetIndex = orderedVisibleKeys.indexOf(targetKey);
if (anchorIndex < 0 || targetIndex < 0) {
const next = new Set(state.selectedKeys);
next.add(targetKey);
return { active: true, selectedKeys: next, anchorKey: targetKey, rangeBaseKeys: null };
}
const rangeBaseKeys = state.rangeBaseKeys ?? state.selectedKeys;
const start = Math.min(anchorIndex, targetIndex);
const end = Math.max(anchorIndex, targetIndex);
const next = new Set(rangeBaseKeys);
for (let index = start; index <= end; index += 1) {
const key = orderedVisibleKeys[index];
if (key !== undefined) {
next.add(key);
}
}
return {
active: true,
selectedKeys: next,
anchorKey: state.anchorKey,
rangeBaseKeys,
};
}
export function reconcileWorkspaceSelection(
state: WorkspaceSelectionState,
availableKeys: ReadonlySet<string>,
): WorkspaceSelectionState {
if (!state.active) return state;
const selectedKeys = keepAvailableKeys(state.selectedKeys, availableKeys);
const rangeBaseKeys = state.rangeBaseKeys
? keepAvailableKeys(state.rangeBaseKeys, availableKeys)
: null;
const anchorKey = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null;
if (
selectedKeys === state.selectedKeys &&
rangeBaseKeys === state.rangeBaseKeys &&
anchorKey === state.anchorKey
) {
return state;
}
return { active: true, selectedKeys, anchorKey, rangeBaseKeys };
}
function keepAvailableKeys(
keys: ReadonlySet<string>,
availableKeys: ReadonlySet<string>,
): ReadonlySet<string> {
for (const key of keys) {
if (!availableKeys.has(key)) {
return new Set([...keys].filter((candidate) => availableKeys.has(candidate)));
}
}
return keys;
}
export function exitWorkspaceSelection(): WorkspaceSelectionState {
return INITIAL_WORKSPACE_SELECTION_STATE;
}
@@ -0,0 +1,83 @@
import { create } from "zustand";
import {
enterWorkspaceSelection,
exitWorkspaceSelection,
INITIAL_WORKSPACE_SELECTION_STATE,
reconcileWorkspaceSelection,
selectWorkspaceRange,
toggleWorkspaceSelection,
type WorkspaceSelectionState,
} from "./selection-state";
type VisibleKeysReader = () => readonly string[];
let visibleKeysReader: VisibleKeysReader = () => [];
/**
* Registers a synchronous reader for the currently rendered sidebar workspace order so Shift+click
* range selection walks only rows on screen without causing re-renders when the order changes.
*/
export function registerSidebarVisibleWorkspaceKeysReader(reader: VisibleKeysReader): () => void {
visibleKeysReader = reader;
return () => {
if (visibleKeysReader === reader) {
visibleKeysReader = () => [];
}
};
}
interface SidebarSelectionStoreState extends WorkspaceSelectionState {
isArchiving: boolean;
enter: (workspaceKey: string) => void;
/** Shift+click selects a range from the anchor; any other press toggles the workspace. */
pressWorkspace: (workspaceKey: string, options: { range: boolean }) => void;
reconcile: (availableKeys: ReadonlySet<string>) => void;
setArchiving: (archiving: boolean) => void;
exit: () => void;
}
export const useSidebarSelectionStore = create<SidebarSelectionStoreState>((set) => ({
...INITIAL_WORKSPACE_SELECTION_STATE,
isArchiving: false,
enter: (workspaceKey) =>
set(() => ({
...enterWorkspaceSelection(workspaceKey),
isArchiving: false,
})),
pressWorkspace: (workspaceKey, { range }) =>
set((state) => {
if (state.isArchiving) return state;
const next = range
? selectWorkspaceRange(state, workspaceKey, visibleKeysReader())
: toggleWorkspaceSelection(state, workspaceKey);
return next === state ? state : { ...next };
}),
reconcile: (availableKeys) =>
set((state) => {
const next = reconcileWorkspaceSelection(state, availableKeys);
return next === state ? state : { ...next };
}),
setArchiving: (isArchiving) => set({ isArchiving }),
exit: () =>
set((state) =>
state.active || state.isArchiving
? { ...exitWorkspaceSelection(), isArchiving: false }
: state,
),
}));
export function useIsSidebarSelectionMode(): boolean {
return useSidebarSelectionStore((state) => state.active);
}
export function useIsWorkspaceBulkSelected(workspaceKey: string): boolean {
return useSidebarSelectionStore((state) => state.active && state.selectedKeys.has(workspaceKey));
}
export function useSidebarSelectionCount(): number {
return useSidebarSelectionStore((state) => (state.active ? state.selectedKeys.size : 0));
}
export function useSidebarSelectionArchiving(): boolean {
return useSidebarSelectionStore((state) => state.isArchiving);
}
@@ -0,0 +1,474 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import React, { act, useCallback } from "react";
import { createRoot, type Root } from "react-dom/client";
import { I18nextProvider } from "react-i18next";
import { Text } from "react-native";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { afterEach, describe, expect, it } from "vitest";
import { userEvent } from "vitest/browser";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarWorkspaceContextMenu } from "@/components/sidebar/sidebar-workspace-menu";
import { ToastProvider, useToast } from "@/contexts/toast-context";
import type { ToastApi } from "@/components/toast-host";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { i18n } from "@/i18n/i18next";
import { dispatchTopOverlayKeyDown } from "@/keyboard";
import {
KeyboardActionDispatcherProvider,
useKeyboardActionDispatcher,
} from "@/keyboard/keyboard-action-dispatcher-context";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
import {
registerSidebarVisibleWorkspaceKeysReader,
SidebarSelectionHost,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
useWorkspaceSelectionPress,
} from "@/sidebar-selection";
import { getShortcutOs } from "@/utils/shortcut-platform";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | null = null;
let container: HTMLDivElement | null = null;
let releaseVisibleKeys: (() => void) | null = null;
function makeEntry(id: string): SidebarWorkspaceEntry {
return {
workspaceKey: `srv:${id}`,
workspaceId: id,
serverId: "srv",
projectViewKey: "prj-view",
projectName: "Repo",
projectRootPath: "/repo",
workspaceDirectory: `/repo/${id}`,
workspaceDirectoryLabel: id,
projectKind: "git",
workspaceKind: "local_checkout",
name: id,
title: null,
currentBranch: id,
statusBucket: "done",
statusEnteredAt: null,
archivingAt: null,
diffStat: null,
prHint: null,
pinnedAt: null,
background: false,
labels: [],
scripts: [],
hasRunningScripts: false,
archiveHasUncommittedChanges: null,
archiveUnpushedCommitCount: null,
};
}
let capturedDispatcher: ReturnType<typeof useKeyboardActionDispatcher> | null = null;
let capturedSidebarToast: ToastApi | null = null;
let fallbackArchiveCount = 0;
function FallbackArchiveProbe() {
capturedDispatcher = useKeyboardActionDispatcher();
useKeyboardActionHandler({
handlerId: "test-global-workspace-archive-fallback",
actions: ["workspace.archive"],
enabled: true,
priority: 0,
handle: () => {
fallbackArchiveCount += 1;
return true;
},
});
return null;
}
function SidebarToastProbe() {
capturedSidebarToast = useToast();
return null;
}
const noop = () => {};
let navigatedKeys: string[] = [];
const rowLongPressRefs = new Map<string, { current: boolean }>();
function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) {
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(entry.workspaceKey);
const handleNavigate = useCallback(() => {
navigatedKeys.push(entry.workspaceKey);
}, [entry.workspaceKey]);
// The row's gesture state, wired the way sidebar rows wire it.
const interaction = useLongPressDragInteraction({ drag: noop, menuController: null });
rowLongPressRefs.set(entry.workspaceKey, interaction.didLongPressRef);
const { onPress, onPressIn } = useWorkspaceSelectionPress({
workspaceKey: entry.workspaceKey,
onNavigate: handleNavigate,
onPressIn: interaction.handlePressIn,
});
return (
<SidebarWorkspaceContextMenu
contextMenuOpen={false}
onContextMenuOpenChange={noop}
workspace={entry}
workspaceKey={entry.workspaceKey}
enabled={!isSelectionMode}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
highlightStyle={undefined}
onPress={onPress}
onPressIn={onPressIn}
testID={`sidebar-workspace-row-${entry.workspaceKey}`}
>
<Text>{entry.name}</Text>
</SidebarWorkspaceContextMenu>
);
}
function mountHost(entries: readonly SidebarWorkspaceEntry[]) {
const entriesByKey = new Map(entries.map((entry) => [entry.workspaceKey, entry]));
releaseVisibleKeys = registerSidebarVisibleWorkspaceKeysReader(() =>
entries.map((entry) => entry.workspaceKey),
);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
container = document.createElement("div");
// Give the sidebar room so the floating selection bar sits below the rows instead of on them.
container.style.cssText = "display:flex;flex-direction:column;width:320px;height:640px;";
document.body.appendChild(container);
root = createRoot(container);
act(() => {
root?.render(
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<SafeAreaProvider>
<KeyboardActionDispatcherProvider>
<FallbackArchiveProbe />
<ToastProvider>
<SidebarToastRegion active>
<SidebarToastProbe />
{entries.map((entry) => (
<SelectableRowProbe key={entry.workspaceKey} entry={entry} />
))}
<SidebarSelectionHost active workspaceEntriesByKey={entriesByKey} />
</SidebarToastRegion>
</ToastProvider>
</KeyboardActionDispatcherProvider>
</SafeAreaProvider>
</I18nextProvider>
</QueryClientProvider>,
);
});
}
afterEach(() => {
capturedDispatcher = null;
capturedSidebarToast = null;
fallbackArchiveCount = 0;
navigatedKeys = [];
rowLongPressRefs.clear();
act(() => {
useSidebarSelectionStore.getState().exit();
});
releaseVisibleKeys?.();
releaseVisibleKeys = null;
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function row(id: string): HTMLElement {
const element = document.querySelector<HTMLElement>(
`[data-testid="sidebar-workspace-row-srv:${id}"]`,
);
if (!element) throw new Error(`Row ${id} is not mounted`);
return element;
}
function selectedIds(): string[] {
const state = useSidebarSelectionStore.getState();
if (!state.active) return [];
return [...state.selectedKeys].map((key) => key.replace("srv:", "")).sort();
}
function markGestureCanceled(id: string) {
const ref = rowLongPressRefs.get(`srv:${id}`);
if (!ref) throw new Error(`Row ${id} is not mounted`);
ref.current = true;
}
/** Holds the primary mouse button on a row past the long-press delay, then releases it. */
async function slowClick(element: HTMLElement) {
const box = element.getBoundingClientRect();
const init = {
bubbles: true,
cancelable: true,
button: 0,
clientX: box.left + box.width / 2,
clientY: box.top + box.height / 2,
};
element.dispatchEvent(new MouseEvent("mousedown", { ...init, buttons: 1 }));
await new Promise((resolve) => setTimeout(resolve, 700));
element.dispatchEvent(new MouseEvent("mouseup", init));
element.dispatchEvent(new MouseEvent("click", init));
}
// Cmd on macOS, Ctrl on Windows and Linux, matching the shortcut layer's `mod`.
const MOD_KEY = getShortcutOs() === "mac" ? "Meta" : "Control";
describe("sidebar workspace row presses", () => {
it("enters select mode on the Cmd/Ctrl+clicked row alone and toggles rows without navigating", async () => {
mountHost(["a", "b", "c", "d"].map(makeEntry));
await userEvent.click(row("a"));
expect(navigatedKeys).toEqual(["srv:a"]);
expect(useSidebarSelectionStore.getState().active).toBe(false);
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["c"]);
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
await userEvent.click(row("d"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["b", "c", "d"]);
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["b", "d"]);
// Plain clicks keep toggling while select mode is on.
await userEvent.click(row("a"));
expect(selectedIds()).toEqual(["a", "b", "d"]);
expect(navigatedKeys).toEqual(["srv:a"]);
});
it("selects on the first modifier or select-mode click after an earlier gesture ended as a long press", async () => {
mountHost(["a", "b"].map(makeEntry));
// A scroll, swipe, drag, or long-press menu leaves the flag set without firing onPress.
// Ctrl+click on Windows/Linux gets no press-in on web, so nothing clears it first.
markGestureCanceled("a");
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a"]);
markGestureCanceled("b");
await userEvent.click(row("b"));
expect(selectedIds()).toEqual(["a", "b"]);
});
it("opens a row on a slow click and still selects it on the next Cmd/Ctrl+click", async () => {
mountHost(["a", "b"].map(makeEntry));
await act(() => slowClick(row("a")));
expect(navigatedKeys).toEqual(["srv:a"]);
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a"]);
});
it("enters select mode on the Shift+clicked row alone, then extends and shrinks the range", async () => {
mountHost(["a", "b", "c", "d", "e", "f"].map(makeEntry));
await userEvent.click(row("b"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["b"]);
await userEvent.click(row("e"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["b", "c", "d", "e"]);
await userEvent.click(row("c"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["b", "c"]);
// Cmd/Ctrl+click moves the anchor; the next Shift range grows from there and keeps b..c.
await userEvent.click(row("f"), { modifiers: [MOD_KEY] });
await userEvent.click(row("e"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["b", "c", "e", "f"]);
expect(navigatedKeys).toEqual([]);
});
});
describe("SidebarSelectionHost", () => {
it("shows a persistent sidebar toast while selecting, updates without Shift, and exits via button or Escape", async () => {
mountHost([makeEntry("a"), makeEntry("b"), makeEntry("c")]);
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).toBeNull();
// Enter select mode via Shift+click on "a", then plain-click "c" without Shift.
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: true });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { range: false });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"2 selected",
);
// Clicking the Exit button leaves select mode and fades the persistent toast out.
const exitButton = document.querySelector<HTMLElement>(
'[data-testid="workspace-selection-exit"]',
);
expect(exitButton).not.toBeNull();
act(() => {
exitButton?.click();
});
expect(useSidebarSelectionStore.getState().active).toBe(false);
await expect
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
.toBeNull();
// Re-enter with Shift+click, then Shift+click "c" for a range of 3, and exit with Escape.
act(() => {
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: true });
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { range: true });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"3 selected",
);
let prevented = false;
act(() => {
const handled = dispatchTopOverlayKeyDown({
key: "Escape",
code: "Escape",
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
preventDefault: () => {
prevented = true;
},
stopPropagation: () => {},
});
expect(handled).toBe(true);
});
expect(prevented).toBe(true);
expect(useSidebarSelectionStore.getState().active).toBe(false);
await expect
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
.toBeNull();
});
it("consumes workspace.archive while in select mode even with zero rows selected or while archiving", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
// Outside select mode, the global fallback receives workspace.archive.
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
});
expect(fallbackArchiveCount).toBe(1);
// Enter select mode then deselect the only row -> 0 selected.
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { range: false });
});
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"0 selected",
);
// The archive shortcut must be absorbed by select mode rather than archiving the open workspace.
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
});
expect(fallbackArchiveCount).toBe(1);
// Same while a worktree safety check is in progress (both archive shortcut and Escape stay owned).
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
useSidebarSelectionStore.getState().setArchiving(true);
});
act(() => {
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
true,
);
expect(
dispatchTopOverlayKeyDown({
key: "Escape",
code: "Escape",
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
repeat: false,
preventDefault: () => {},
stopPropagation: () => {},
}),
).toBe(true);
});
expect(fallbackArchiveCount).toBe(1);
expect(useSidebarSelectionStore.getState().active).toBe(true);
});
it("keeps the selection bar visible when an Undo toast is already displayed in the sidebar", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
let dismissUndo: (() => void) | undefined;
act(() => {
dismissUndo = capturedSidebarToast?.show("Workspace archived", {
durationMs: 6000,
testID: "workspace-archived-toast",
});
});
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
});
// Both the Undo toast and the selection bar (count, Archive, Exit) must remain visible.
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
expect(document.querySelector('[data-testid="workspace-selection-archive"]')).not.toBeNull();
expect(document.querySelector('[data-testid="workspace-selection-exit"]')).not.toBeNull();
act(() => {
dismissUndo?.();
});
});
it("toggles focused workspace checkboxes when pressing Space in select mode", () => {
mountHost([makeEntry("a"), makeEntry("b")]);
act(() => {
useSidebarSelectionStore.getState().enter("srv:a");
});
const rowB = document.querySelector<HTMLElement>('[data-testid="sidebar-workspace-row-srv:b"]');
expect(rowB?.getAttribute("role")).toBe("checkbox");
expect(rowB?.getAttribute("aria-checked")).toBe("false");
act(() => {
rowB?.focus();
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
);
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", repeat: true, bubbles: true, cancelable: true }),
);
});
expect(rowB?.getAttribute("aria-checked")).toBe("true");
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"2 selected",
);
act(() => {
rowB?.dispatchEvent(
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
);
});
expect(rowB?.getAttribute("aria-checked")).toBe("false");
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
"1 selected",
);
});
});
@@ -0,0 +1,157 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import {
useSidebarAppToast,
useSidebarPersistentToast,
} from "@/components/sidebar/sidebar-toast-region";
import type { ToastState } from "@/components/toast-host";
import { useToast } from "@/contexts/toast-context";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { useOverlayRegistration } from "@/keyboard";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { archiveSelectedWorkspaces, createDefaultBulkArchiveDeps } from "./archive-selected";
import {
useIsSidebarSelectionMode,
useSidebarSelectionArchiving,
useSidebarSelectionCount,
useSidebarSelectionStore,
} from "./selection-store";
import { WorkspaceSelectionToast } from "./workspace-selection-toast";
const SELECTION_TOAST_ID = -1;
const ESCAPE_OVERLAY_KEYS = ["Escape"] as const;
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
/**
* Coordinates sidebar workspace select mode: reconciles removed workspaces, binds Escape and
* the archive shortcut, and keeps the persistent selection bar up in `SidebarToastRegion`.
*/
export function SidebarSelectionHost({
active,
workspaceEntriesByKey,
}: {
active: boolean;
workspaceEntriesByKey: ReadonlyMap<string, SidebarWorkspaceEntry>;
}): null {
const toast = useToast();
const appToast = useSidebarAppToast();
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const selectionMode = useIsSidebarSelectionMode();
const selectedCount = useSidebarSelectionCount();
const isArchiving = useSidebarSelectionArchiving();
const entriesRef = useRef(workspaceEntriesByKey);
entriesRef.current = workspaceEntriesByKey;
const activeSelectionRef = useRef(activeWorkspaceSelection);
activeSelectionRef.current = activeWorkspaceSelection;
const archiveAttemptRef = useRef(0);
useEffect(() => {
if (!selectionMode) return;
useSidebarSelectionStore.getState().reconcile(new Set(workspaceEntriesByKey.keys()));
}, [selectionMode, workspaceEntriesByKey]);
useEffect(() => {
if (active) return;
const state = useSidebarSelectionStore.getState();
if (state.active && !state.isArchiving) {
state.exit();
}
}, [active]);
const handleExit = useCallback(() => {
const state = useSidebarSelectionStore.getState();
if (state.isArchiving) return;
state.exit();
}, []);
const handleArchiveSelected = useCallback(() => {
const store = useSidebarSelectionStore.getState();
if (!store.active || store.isArchiving || store.selectedKeys.size === 0) return;
const entries: SidebarWorkspaceEntry[] = [];
for (const key of store.selectedKeys) {
const entry = entriesRef.current.get(key);
if (entry && entry.archivingAt === null) {
entries.push(entry);
}
}
if (entries.length === 0) {
store.exit();
return;
}
const attemptId = archiveAttemptRef.current + 1;
archiveAttemptRef.current = attemptId;
store.setArchiving(true);
void archiveSelectedWorkspaces({
workspaces: entries,
toast,
fallbackErrorToast: appToast,
onArchiveStarted: () => {
useSidebarSelectionStore.getState().exit();
},
deps: createDefaultBulkArchiveDeps(() => activeSelectionRef.current),
}).finally(() => {
if (archiveAttemptRef.current !== attemptId) return;
const current = useSidebarSelectionStore.getState();
if (current.isArchiving) {
current.setArchiving(false);
}
});
}, [appToast, toast]);
useOverlayRegistration({
keys: ESCAPE_OVERLAY_KEYS,
// Keep Escape owned while select mode is active (including during worktree checks) so it
// never falls through to interrupt a running agent in the open workspace; any higher-layer
// confirmation dialog still receives Escape first.
active: selectionMode && active,
layer: 0,
manageFocus: false,
onKeyDown: (event) => {
if (event.key !== "Escape") return false;
event.preventDefault();
handleExit();
return true;
},
});
useKeyboardActionHandler({
handlerId: "sidebar-selection-archive",
actions: WORKSPACE_ARCHIVE_ACTIONS,
// Keep ownership of workspace.archive for the entire lifetime of select mode so pressing it
// at 0 selected or during a worktree check never falls through to archive the open workspace.
enabled: selectionMode && active,
priority: 10,
handle: () => {
handleArchiveSelected();
return true;
},
});
const persistentToast = useMemo<ToastState | null>(() => {
if (!selectionMode || !active) return null;
return {
id: SELECTION_TOAST_ID,
content: (
<WorkspaceSelectionToast
selectedCount={selectedCount}
isArchiving={isArchiving}
onArchive={handleArchiveSelected}
onExit={handleExit}
/>
),
nativeMessage: null,
variant: "default",
layout: "action",
durationMs: null,
testID: "workspace-selection-toast",
};
}, [active, handleArchiveSelected, handleExit, isArchiving, selectedCount, selectionMode]);
useSidebarPersistentToast(persistentToast);
return null;
}
@@ -0,0 +1,59 @@
import { useCallback } from "react";
import type { GestureResponderEvent } from "react-native";
import { readPressModifiers } from "@/keyboard";
import { useSidebarSelectionStore } from "./selection-store";
interface WorkspaceSelectionPressInput {
workspaceKey: string;
/** The row's normal press: open the workspace. */
onNavigate: () => void;
/** The row's normal press-in: start the long-press drag gesture. */
onPressIn?: (event: GestureResponderEvent) => void;
}
/**
* Routes a sidebar workspace row press between navigation and select mode, Finder-style:
* Shift+click selects a range, Cmd+click (Ctrl+click off macOS) toggles one row, and either one
* enters select mode on the clicked row alone. In select mode every press selects, so touch and
* mouse users can keep tapping without a modifier.
*
* Selecting presses never consult the row's long-press flag. They never arm the long-press
* gesture, a native long press already cancels the press, and react-native-web gives Ctrl+click
* no press-in, so a flag left by an earlier scroll or swipe would swallow the click.
*/
export function useWorkspaceSelectionPress({
workspaceKey,
onNavigate,
onPressIn,
}: WorkspaceSelectionPressInput) {
const handlePress = useCallback(
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
const store = useSidebarSelectionStore.getState();
if (!store.active && !modifiers.shift && !modifiers.mod) {
onNavigate();
return;
}
event.preventDefault?.();
store.pressWorkspace(workspaceKey, { range: modifiers.shift });
},
[onNavigate, workspaceKey],
);
const handlePressIn = useCallback(
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
if (modifiers.shift || modifiers.mod) {
// Keep the browser from extending a text selection or starting a drag on modifier clicks.
event.preventDefault?.();
return;
}
if (!useSidebarSelectionStore.getState().active) {
onPressIn?.(event);
}
},
[onPressIn],
);
return { onPress: handlePress, onPressIn: handlePressIn };
}
@@ -0,0 +1,83 @@
import { X } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
import { DensityIcon } from "@/components/ui/density-icon";
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
import type { ShortcutKey } from "@/utils/format-shortcut";
const EXIT_SHORTCUT_CHORD: ShortcutKey[][] = [["Esc"]];
export function WorkspaceSelectionToast({
selectedCount,
isArchiving,
onArchive,
onExit,
}: {
selectedCount: number;
isArchiving: boolean;
onArchive: () => void;
onExit: () => void;
}) {
const { t } = useTranslation();
const exitLabel = t("sidebar.workspace.selection.exit");
return (
<View style={styles.row}>
<Text style={styles.message} numberOfLines={1} testID="workspace-selection-count">
{t("sidebar.workspace.selection.count", { count: selectedCount })}
</Text>
<View style={styles.actions}>
<Button
size="sm"
onPress={onArchive}
disabled={selectedCount === 0}
loading={isArchiving}
testID="workspace-selection-archive"
>
{t("sidebar.workspace.actions.archive")}
</Button>
<ToolbarButton
round
tooltipSide="top"
label={exitLabel}
shortcut={EXIT_SHORTCUT_CHORD}
onPress={onExit}
disabled={isArchiving}
style={styles.exitButton}
testID="workspace-selection-exit"
>
<DensityIcon icon={X} size="sm" color="foregroundMuted" />
</ToolbarButton>
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
row: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[3],
},
message: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
actions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
// Matches the Archive button's sm pill height so the circular hover fill sits concentrically
// in the action toast's trailing corner.
exitButton: {
width: CONTROL_HEIGHTS.sm,
height: CONTROL_HEIGHTS.sm,
},
}));
@@ -1,7 +1,12 @@
export {
archiveWorkspaceWithUndo,
archiveWorkspacesWithUndo,
hasUndoableWorkspaceArchive,
undoLatestWorkspaceArchive,
type UndoableWorkspaceArchiveClient,
type UndoableWorkspaceArchiveEntryInput,
type WorkspaceArchiveBatchFailure,
type WorkspaceArchiveBatchResult,
} from "./internal/undo-window";
export { WorkspaceArchiveUndoShortcutHost } from "./internal/undo-shortcut-host";
export { supportsWorkspaceArchiveUndo } from "./internal/capability";
@@ -8,6 +8,7 @@ import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-stor
import { seedSessionHosts } from "@/test/seed-session";
import {
archiveWorkspaceWithUndo,
archiveWorkspacesWithUndo,
undoLatestWorkspaceArchive,
type UndoableWorkspaceArchiveClient,
} from "@/workspace/archive-undo";
@@ -82,6 +83,9 @@ function createToastHost() {
get shownTestID() {
return shown?.options?.testID ?? null;
},
get shownVariant() {
return shown?.options?.variant ?? null;
},
timeOut: () => shown?.dismiss(),
};
}
@@ -299,3 +303,166 @@ describe("archiveWorkspaceWithUndo", () => {
}).toEqual({ toast: null, undone: false, row: workspace("a") });
});
});
describe("archiveWorkspacesWithUndo", () => {
it("hides every workspace in the batch and undoes all of them together", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
expect(storedWorkspace("a")).toBeUndefined();
expect(storedWorkspace("b")).toBeUndefined();
expect(toast.shownTestID).toBe("workspace-archived-toast");
expect(undoLatestWorkspaceArchive()).toBe(true);
expect({
a: storedWorkspace("a"),
b: storedWorkspace("b"),
undoA: host.undoRequested("a"),
undoB: host.undoRequested("b"),
toast: toast.shownTestID,
}).toEqual({
a: workspace("a"),
b: workspace("b"),
undoA: true,
undoB: true,
toast: null,
});
host.finishArchive("a", { canceled: true });
host.finishArchive("b", { canceled: true });
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
host.finishUndo("a");
host.finishUndo("b");
expect(committed).toEqual([]);
});
it("commits every workspace in the batch when the toast times out", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b");
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
expect(committed).toEqual([]);
toast.timeOut();
expect(committed).toEqual(["a", "b"]);
});
it("restores only the failed workspace on partial failure and keeps undo open when surfacing the error", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b", { error: "busy" });
const { failures, showPartialFailure } = await batch;
expect(failures).toHaveLength(1);
expect(failures[0]?.workspace.workspaceId).toBe("b");
expect(storedWorkspace("a")).toBeUndefined();
expect(storedWorkspace("b")).toEqual(workspace("b"));
// Updating the toast with the partial-failure error must not dismiss Undo or commit "a".
expect(showPartialFailure("busy")).toBe(true);
expect({
toast: toast.shownTestID,
variant: toast.shownVariant,
committed,
}).toEqual({
toast: "workspace-archived-toast",
variant: "error",
committed: [],
});
expect(undoLatestWorkspaceArchive()).toBe(true);
expect({ undoA: host.undoRequested("a"), undoB: host.undoRequested("b") }).toEqual({
undoA: true,
undoB: false,
});
expect(committed).toEqual([]);
});
it("commits surviving workspaces once a partial-failure undo toast times out", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const batch = archiveWorkspacesWithUndo({
entries: [
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "a" },
onArchiveCommitted: () => committed.push("a"),
},
{
client: host.client,
workspace: { serverId: SERVER_ID, workspaceId: "b" },
onArchiveCommitted: () => committed.push("b"),
},
],
toast: toast.api,
});
host.finishArchive("a");
host.finishArchive("b", { error: "busy" });
const { showPartialFailure } = await batch;
expect(showPartialFailure("busy")).toBe(true);
expect(committed).toEqual([]);
toast.timeOut();
expect(committed).toEqual(["a"]);
expect(undoLatestWorkspaceArchive()).toBe(false);
});
});
@@ -17,18 +17,28 @@ export interface UndoableWorkspaceArchiveClient {
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
}
interface UndoWindowInput {
export interface UndoableWorkspaceArchiveEntryInput {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
toast: ToastApi;
hidden: WorkspaceDescriptor | null;
onArchiveCommitted: () => void;
}
interface UndoWindowEntry extends UndoableWorkspaceArchiveEntryInput {
hidden: WorkspaceDescriptor | null;
archived: boolean;
failed: boolean;
committed: boolean;
}
interface UndoWindowInput {
entries: UndoWindowEntry[];
toast: ToastApi;
}
let latest: UndoWindow | null = null;
/**
* One archive's chance to be undone. It opens when the row hides and closes when its toast
* One archive batch's chance to be undone. It opens when the row(s) hide and closes when its toast
* leaves the screen (timeout, replaced by another toast, or undo).
*
* - `open`: undo is offered.
@@ -37,40 +47,78 @@ let latest: UndoWindow | null = null;
*/
class UndoWindow {
phase: "open" | "closed" | "undone" = "open";
private archived = false;
private readonly dismissToast: DismissToast;
private dismissToast: DismissToast = () => {};
private toastToken: object | null = null;
constructor(private readonly input: UndoWindowInput) {
this.dismissToast = input.toast.show(<WorkspaceArchivedToast onUndo={this.undo} />, {
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
testID: "workspace-archived-toast",
onDismiss: this.close,
});
this.showToast({ variant: "default" });
}
/** The host finished the archive. It commits now if undo is no longer offered. */
archiveFinished(): void {
this.archived = true;
if (this.phase === "closed") this.commit();
private showToast(options: { message?: string; variant: "default" | "error" }): void {
const token = {};
this.toastToken = token;
const remainingCount = this.input.entries.filter((entry) => !entry.failed).length;
this.dismissToast = this.input.toast.show(
<WorkspaceArchivedToast
count={remainingCount}
message={options.message}
onUndo={this.undo}
/>,
{
variant: options.variant,
layout: "action",
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
testID: "workspace-archived-toast",
onDismiss: () => {
// Replacing our own toast in place (for example to surface a partial failure) must not
// close the undo window or purge surviving workspaces.
if (this.toastToken !== token) return;
this.close();
},
},
);
}
/** The archive failed on the host, so there is nothing left to undo. */
archiveFailed(): void {
this.close();
this.dismissToast();
/**
* Surfaces a partial-failure message on the active undo toast without dismissing Undo for the
* workspaces that did archive. Returns false once the window is closed, undone, or superseded.
*/
showPartialFailure(message: string): boolean {
if (this.phase !== "open" || latest !== this) return false;
this.showToast({ message, variant: "error" });
return true;
}
/** The host finished archiving this entry. It commits now if undo is no longer offered. */
entryFinished(entry: UndoWindowEntry): void {
entry.archived = true;
if (this.phase === "closed") this.commitEntry(entry);
}
/** The archive failed on the host. Dismisses the toast once every entry has failed. */
entryFailed(entry: UndoWindowEntry): void {
entry.failed = true;
if (this.input.entries.every((item) => item.failed)) {
this.close();
this.dismissToast();
}
}
readonly close = (): void => {
if (this.phase !== "open") return;
this.phase = "closed";
this.release();
if (this.archived) this.commit();
for (const entry of this.input.entries) {
if (entry.archived) this.commitEntry(entry);
}
};
/** Commits unless the workspace is back by now, for example restored from another client. */
private commit(): void {
if (isWorkspaceListed(this.input.workspace)) return;
this.input.onArchiveCommitted();
private commitEntry(entry: UndoWindowEntry): void {
if (entry.committed || entry.failed) return;
if (isWorkspaceListed(entry.workspace)) return;
entry.committed = true;
entry.onArchiveCommitted();
}
readonly undo = (): boolean => {
@@ -78,10 +126,19 @@ class UndoWindow {
this.phase = "undone";
this.release();
this.dismissToast();
void undoWorkspaceArchiveOptimistically(this.input).catch((error: unknown) => {
console.warn("[workspace-archive-undo] undo failed", error);
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
});
const undoable = this.input.entries.filter((entry) => !entry.failed);
void (async () => {
const results = await Promise.allSettled(
undoable.map((entry) => undoWorkspaceArchiveOptimistically(entry)),
);
const failed = results.filter(
(result): result is PromiseRejectedResult => result.status === "rejected",
);
if (failed.length > 0) {
console.warn("[workspace-archive-undo] undo failed", failed[0]?.reason);
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
}
})();
return true;
};
@@ -90,6 +147,75 @@ class UndoWindow {
}
}
export interface WorkspaceArchiveBatchFailure {
workspace: WorkspaceArchiveTarget;
error: unknown;
}
export interface WorkspaceArchiveBatchResult {
failures: WorkspaceArchiveBatchFailure[];
/**
* Updates this batch's live undo toast to show a partial-failure error while keeping Undo active
* for the workspaces that succeeded. Returns false if the undo window is no longer open.
*/
showPartialFailure: (message: string) => boolean;
}
/**
* Archives one or more workspaces together and offers one undo until the toast goes away.
*
* `onArchiveCommitted` runs per workspace once that archive both finished on the host and can no
* longer be undone, and only if the workspace is still gone then. Returns failures for any
* workspace whose archive failed while not undone; those rows are already restored.
*/
export async function archiveWorkspacesWithUndo(input: {
entries: readonly UndoableWorkspaceArchiveEntryInput[];
toast: ToastApi;
}): Promise<WorkspaceArchiveBatchResult> {
if (input.entries.length === 0) {
return { failures: [], showPartialFailure: () => false };
}
const started = input.entries.map((entry) => {
const archive = beginOptimisticWorkspaceArchive(entry);
const windowEntry: UndoWindowEntry = {
...entry,
hidden: archive.hidden,
archived: false,
failed: false,
committed: false,
};
return { windowEntry, done: archive.done };
});
const window = new UndoWindow({
entries: started.map((item) => item.windowEntry),
toast: input.toast,
});
latest = window;
const failures: WorkspaceArchiveBatchFailure[] = [];
await Promise.all(
started.map(async ({ windowEntry, done }) => {
let outcome: Awaited<typeof done>;
try {
outcome = await done;
} catch (error) {
if (window.phase === "undone") return;
window.entryFailed(windowEntry);
failures.push({ workspace: windowEntry.workspace, error });
return;
}
if (outcome === "archived") window.entryFinished(windowEntry);
}),
);
return {
failures,
showPartialFailure: (message) => window.showPartialFailure(message),
};
}
/**
* Archives a workspace and offers to undo it until the toast goes away.
*
@@ -104,19 +230,19 @@ export async function archiveWorkspaceWithUndo(input: {
toast: ToastApi;
onArchiveCommitted: () => void;
}): Promise<void> {
const archive = beginOptimisticWorkspaceArchive(input);
const window = new UndoWindow({ ...input, hidden: archive.hidden });
latest = window;
let outcome: Awaited<typeof archive.done>;
try {
outcome = await archive.done;
} catch (error) {
if (window.phase === "undone") return;
window.archiveFailed();
throw error;
const { failures } = await archiveWorkspacesWithUndo({
entries: [
{
client: input.client,
workspace: input.workspace,
onArchiveCommitted: input.onArchiveCommitted,
},
],
toast: input.toast,
});
if (failures[0]) {
throw failures[0].error;
}
if (outcome === "archived") window.archiveFinished();
}
/** Undoes the most recent archive while its toast is up. Returns false when there is none. */
@@ -6,17 +6,30 @@ import { Button } from "@/components/ui/button";
import { Shortcut } from "@/components/ui/shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
export function WorkspaceArchivedToast({ onUndo }: { onUndo: () => void }) {
export function WorkspaceArchivedToast({
count = 1,
message: customMessage,
onUndo,
}: {
count?: number;
message?: string;
onUndo: () => void;
}) {
const { t } = useTranslation();
const undoKeys = useShortcutKeys("undo-archive-workspace");
const undoShortcut = useMemo(
() => (undoKeys ? <Shortcut chord={undoKeys} style={styles.shortcut} /> : null),
[undoKeys],
);
const message =
customMessage ??
(count === 1
? t("sidebar.workspace.toasts.archived")
: t("sidebar.workspace.toasts.archivedCount", { count }));
return (
<View style={styles.row}>
<Text style={styles.message}>{t("sidebar.workspace.toasts.archived")}</Text>
<Text style={styles.message}>{message}</Text>
<Button
size="sm"
onPress={onUndo}
@@ -34,7 +47,7 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[2],
gap: theme.spacing[3],
},
// Cancels the badge's own inset, which would otherwise add to the button's gap.
shortcut: {
@@ -44,6 +44,7 @@ export const EyeOff = StubIcon;
export const File = StubIcon;
export const FileText = StubIcon;
export const Folder = StubIcon;
export const FolderOpen = StubIcon;
export const FolderPlus = StubIcon;
export const FolderTree = StubIcon;
export const Gift = StubIcon;
@@ -107,6 +108,7 @@ export const SquareSlash = StubIcon;
export const SquareTerminal = StubIcon;
export const Star = StubIcon;
export const Sun = StubIcon;
export const Tag = StubIcon;
export const Terminal = StubIcon;
export const Trash2 = StubIcon;
export const TriangleAlert = StubIcon;
@@ -1,3 +1,4 @@
import type { PluginSessionsRuntime } from "../plugins/agent-tools.js";
import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
import {
prepareAgentMessage,
@@ -679,6 +680,24 @@ async function startAndSteerThroughManager(
return { manager, agentId: agent.id, workdir };
}
/** Plugin sessions whose only plugin appends the given instructions to every open. */
function instructionPluginSessions(instructions: () => string[]): PluginSessionsRuntime {
return {
openSession: async (request) => ({
...request,
appendSystemPrompt: instructions(),
tools: [],
mcpServerOwners: {},
}),
sessionLaunched: () => {},
sessionLaunchFailed: () => {},
refreshSession: async () => ({ stale: false }),
sessionTools: () => [],
closeSession: () => {},
callTool: async () => ({ isError: true, text: "No plugin tools" }),
};
}
test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-"));
const harness = new V2Harness();
@@ -690,13 +709,7 @@ test("OpenCode persistence excludes launch-only instructions from storage and cl
registry: storage,
logger,
appendSystemPrompt: "Daemon instruction",
pluginLifecycle: {
emit: () => {},
before: async (name, request) =>
name === "agent.open.before"
? { ...request, appendSystemPrompt: ["Plugin instruction"] }
: request,
},
pluginSessions: instructionPluginSessions(() => ["Plugin instruction"]),
});
const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, {
workspaceId: undefined,
@@ -16144,11 +16157,7 @@ test("plugin instructions are recomputed for each launch without changing saved
registry: storage,
logger,
appendSystemPrompt: "Daemon",
pluginLifecycle: {
emit: () => {},
before: async (name, request) =>
name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request,
},
pluginSessions: instructionPluginSessions(() => additions),
});
const snapshot = await manager.createAgent(
{ provider: "codex", cwd: workdir, systemPrompt: "Saved" },
+190 -71
View File
@@ -1,4 +1,8 @@
import type { AttachedAgentTool, PluginAgentToolsRuntime } from "../plugins/agent-tools.js";
import type {
AttachedAgentTool,
PluginSessionsRuntime,
SessionOpenAgentFacts,
} from "../plugins/agent-tools.js";
import { ProviderOptionsValidationError } from "./provider-options.js";
import type { AgentToolResult } from "@getpaseo/plugin/server";
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
@@ -203,6 +207,26 @@ async function assertUsableWorkingDirectory(cwd: string): Promise<void> {
}
}
interface ResumeAgentOptions {
createdAt?: Date;
updatedAt?: Date;
lastUserMessageAt?: Date | null;
labels?: Record<string, string>;
metadata?: AgentMetadata;
workspaceId?: string;
owner?: AgentOwner;
background?: boolean;
attention?: AttentionState;
}
interface PluginToolCall {
pluginId: string;
toolName: string;
agentId: string;
input: unknown;
signal?: AbortSignal;
}
interface StopAgentBackgroundWorkOptions {
agentId: string;
itemId: string;
@@ -399,7 +423,7 @@ export interface AgentManagerOptions {
terminalManager?: TerminalManager | null;
mcpBaseUrl?: string;
mcpAuthToken?: string;
pluginAgentTools?: PluginAgentToolsRuntime;
pluginSessions?: PluginSessionsRuntime;
paseoToolsEnabled?: boolean;
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
@@ -937,10 +961,7 @@ export class AgentManager {
private readonly agentStreamCoalescer: AgentStreamCoalescer;
private mcpBaseUrl: string | null;
private readonly mcpAuthToken: string | null;
private sessionOpenGeneration = 0;
private readonly sessionOpenGenerations = new Map<string, number>();
private readonly attachedPluginTools = new Map<string, AttachedAgentTool[]>();
private readonly pluginAgentTools: PluginAgentToolsRuntime | undefined;
private readonly pluginSessions: PluginSessionsRuntime | undefined;
private paseoToolsEnabled = true;
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
private readonly paseoToolPolicies = new Map<string, ProviderPaseoToolsPolicy | undefined>();
@@ -958,7 +979,7 @@ export class AgentManager {
constructor(options: AgentManagerOptions) {
this.pluginLifecycle = options.pluginLifecycle;
this.pluginAgentTools = options.pluginAgentTools;
this.pluginSessions = options.pluginSessions;
this.timelineStore = options.timelineStore ?? new InMemoryAgentTimelineStore();
this.idFactory = options.idFactory ?? (() => randomUUID());
this.registry = options?.registry;
@@ -1063,47 +1084,75 @@ export class AgentManager {
this.paseoToolCatalogFactory = factory;
}
invalidatePluginSessions(): void {
this.sessionOpenGeneration++;
}
/**
* Reopens an idle agent whose plugin attachment changed in a way the running provider session cannot pick up:
* env, instructions, MCP servers, or tool definitions. A plugin change that leaves the agent's launch as it was
* keeps the session, with its background work and subagents.
*/
async reloadStalePluginSession(agentId: string): Promise<void> {
if (!this.needsPluginSessionReload(agentId)) return;
if (!(await this.needsPluginSessionReload(agentId))) return;
await this.trackAgentRegistrationOperation(
this.runLifecycleMutation(agentId, async () => {
if (!this.needsPluginSessionReload(agentId)) return;
if (!(await this.needsPluginSessionReload(agentId))) return;
await this.reloadAgentSessionInternal(agentId);
}),
);
}
private needsPluginSessionReload(agentId: string): boolean {
private async needsPluginSessionReload(agentId: string): Promise<boolean> {
const agent = this.getAgent(agentId);
return (
agent !== null &&
agent.lifecycle !== "closed" &&
this.sessionOpenGenerations.get(agentId) !== this.sessionOpenGeneration &&
!this.hasInFlightRun(agentId)
);
if (!agent || agent.lifecycle === "closed" || this.hasInFlightRun(agentId)) return false;
return (await this.refreshPluginTools(agentId)).stale;
}
getPluginTools(agentId: string): readonly AttachedAgentTool[] {
return (this.attachedPluginTools.get(agentId) ?? []).filter((tool) =>
this.pluginAgentTools?.isToolPluginAvailable(tool.pluginId, tool.pluginInstanceId),
);
return this.pluginSessions?.sessionTools(agentId) ?? [];
}
async executePluginTool(
tool: AttachedAgentTool,
agentId: string,
input: unknown,
signal?: AbortSignal,
): Promise<AgentToolResult> {
/**
* Brings a live session's plugin tools up to date with the running plugins. A plugin restart gives it a new
* instance; only that plugin's open is rerun for the session, without reopening it or interrupting its turn.
*/
async refreshPluginTools(agentId: string): Promise<{ stale: boolean }> {
if (!this.pluginSessions) return { stale: false };
return this.pluginSessions.refreshSession(agentId, {
reservedToolNames: () => this.reservedAgentToolNames(agentId),
agentFacts: () => this.pluginOpenAgentFacts(agentId),
});
}
/** The agent fields a reopen would put in its plugin open request. */
private async pluginOpenAgentFacts(agentId: string): Promise<SessionOpenAgentFacts> {
const agent = this.requireAgent(agentId);
return {
workspaceId: agent.workspaceId ?? null,
title: await this.resolveInitialPersistedTitle(agentId, agent.config, null),
background: agent.background === true,
...agentEntityData(agent),
};
}
/**
* Resolves the plugin's current instance of the tool at call time, so a launch-time catalog reaches a restarted
* plugin and never a different plugin that took the name.
*/
async executePluginTool({
pluginId,
toolName,
agentId,
input,
signal,
}: PluginToolCall): Promise<AgentToolResult> {
const agent = this.getAgent(agentId);
if (!agent || agent.lifecycle === "closed") throw new Error(`Agent is not live: ${agentId}`);
if (!this.pluginAgentTools) throw new Error("Plugin tools are unavailable");
if (!this.pluginSessions) throw new Error("Plugin tools are unavailable");
await this.refreshPluginTools(agentId);
const tool = this.getPluginTools(agentId).find(
(entry) => entry.pluginId === pluginId && entry.name === toolName,
);
if (!tool) return { isError: true, text: `Plugin tool is not available: ${toolName}` };
const record = await this.registry?.get(agentId);
return this.pluginAgentTools.callTool(
return this.pluginSessions.callTool(
tool.pluginId,
tool.pluginInstanceId,
describeHookAgent({ ...agent, title: record?.title ?? agent.config.title }),
@@ -1113,10 +1162,22 @@ export class AgentManager {
);
}
/**
* Paseo's own tool names for the agent, including the ones its provider disables. The catalog also lists the
* agent's plugin tools; the plugin session owner settles those names between plugins itself.
*/
private async reservedAgentToolNames(agentId: string): Promise<ReadonlySet<string>> {
if (!this.paseoToolCatalogFactory) return new Set();
const pluginToolNames = new Set(this.getPluginTools(agentId).map((tool) => tool.name));
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy: {},
});
return new Set([...catalog.tools.keys()].filter((name) => !pluginToolNames.has(name)));
}
private detachPluginTools(agentId: string): void {
this.attachedPluginTools.delete(agentId);
this.sessionOpenGenerations.delete(agentId);
this.pluginAgentTools?.detachTools(agentId);
this.pluginSessions?.closeSession(agentId);
}
getPaseoToolPolicy(agentId: string): ProviderPaseoToolsPolicy | undefined {
@@ -1637,7 +1698,17 @@ export class AgentManager {
);
}
private async createAgentInternal(
private createAgentInternal(
config: AgentSessionConfig,
resolvedAgentId: string,
options: CreateAgentOptions,
): Promise<ManagedAgent> {
return this.launchAgent(resolvedAgentId, () =>
this.createAgentSession(config, resolvedAgentId, options),
);
}
private async createAgentSession(
config: AgentSessionConfig,
resolvedAgentId: string,
options: CreateAgentOptions,
@@ -1758,7 +1829,19 @@ export class AgentManager {
);
}
private async resumeAgentFromPersistenceInternal(
private resumeAgentFromPersistenceInternal(
handle: AgentPersistenceHandle,
overrides: Partial<AgentSessionConfig> | undefined,
agentId: string,
options?: ResumeAgentOptions,
resumeOptions?: AgentResumeSessionOptions,
): Promise<ManagedAgent> {
return this.launchAgent(agentId, () =>
this.resumeAgentSession(handle, overrides, agentId, options, resumeOptions),
);
}
private async resumeAgentSession(
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
agentId?: string,
@@ -1864,18 +1947,23 @@ export class AgentManager {
workspaceId: string;
labels?: Record<string, string>;
}): Promise<ManagedAgent> {
return this.trackAgentRegistrationOperation(this.importProviderSessionInternal(input));
const resolvedAgentId = validateAgentId(this.idFactory(), "importProviderSession");
return this.trackAgentRegistrationOperation(
this.launchAgent(resolvedAgentId, () => this.importAgentSession(input, resolvedAgentId)),
);
}
private async importProviderSessionInternal(input: {
provider: AgentProvider;
providerHandleId: string;
cwd: string;
workspaceId: string;
labels?: Record<string, string>;
}): Promise<ManagedAgent> {
private async importAgentSession(
input: {
provider: AgentProvider;
providerHandleId: string;
cwd: string;
workspaceId: string;
labels?: Record<string, string>;
},
resolvedAgentId: string,
): Promise<ManagedAgent> {
this.assertAcceptingAgentRegistrations();
const resolvedAgentId = validateAgentId(this.idFactory(), "importProviderSession");
this.requireEnabledProvider(input.provider);
const client = await this.requireAvailableClient({ provider: input.provider });
@@ -1971,7 +2059,29 @@ export class AgentManager {
);
}
private async reloadAgentSessionInternal(
private reloadAgentSessionInternal(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean },
): Promise<ManagedAgent> {
return this.launchAgent(agentId, () => this.reopenAgentSession(agentId, overrides, options));
}
/**
* Runs one provider launch: create, resume, import, or reopen. Its plugin open takes over the session once
* `registerSession` admits the agent. A launch that fails before then discards that open, so a session still
* running keeps its plugin tools.
*/
private async launchAgent<T>(agentId: string, launch: () => Promise<T>): Promise<T> {
try {
return await launch();
} catch (error) {
this.pluginSessions?.sessionLaunchFailed(agentId);
throw error;
}
}
private async reopenAgentSession(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean },
@@ -2019,13 +2129,11 @@ export class AgentManager {
metadata: existing.metadata,
},
);
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
if (
Object.keys(stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {}).length > 0 &&
existing.session.capabilities.supportsMcpServers !== true
) {
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
}
const providerLaunchConfig = this.resolveReloadLaunchConfig(
existing,
launchConfig,
launchContext,
);
let session: AgentSession | undefined;
let closedExisting: ManagedAgentClosed | undefined;
@@ -2089,7 +2197,8 @@ export class AgentManager {
throw error;
} finally {
if (!handedToRegistration) {
this.detachPluginTools(agentId);
// The closed agent drops its plugin record; a launch that never closed it leaves the rollback to launchAgent.
if (closedExisting) this.detachPluginTools(agentId);
if (hadPreviousPaseoToolPolicy) {
this.paseoToolPolicies.set(agentId, previousPaseoToolPolicy);
} else {
@@ -2102,6 +2211,23 @@ export class AgentManager {
}
}
/** Validates a reload's launch before it closes the running session. */
private resolveReloadLaunchConfig(
existing: ActiveManagedAgent,
launchConfig: AgentSessionConfig,
launchContext: AgentLaunchContext,
): AgentSessionConfig {
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
const mcpServers = stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {};
if (
Object.keys(mcpServers).length > 0 &&
existing.session.capabilities.supportsMcpServers !== true
) {
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
}
return providerLaunchConfig;
}
private async closeReloadedSession(session: AgentSession, agentId: string): Promise<void> {
let operation = this.reloadedSessionCloses.get(session);
if (!operation) {
@@ -4619,6 +4745,8 @@ export class AgentManager {
this.runtimeCleanupIdentities.set(session, Object.freeze({ openedAt: Date.now() }));
this.agents.set(resolvedAgentId, managed);
registered = true;
// The agent now runs this launch, so its plugin open describes the running session.
this.pluginSessions?.sessionLaunched(resolvedAgentId);
// Initialize previousStatus to track transitions
this.previousStatuses.set(resolvedAgentId, managed.lifecycle);
if (session.initialTimeline?.length) {
@@ -6513,13 +6641,10 @@ export class AgentManager {
metadata?: AgentMetadata;
},
): Promise<AgentLaunchContext> {
// A plugin changing during this open must still make the resulting session stale.
const generation = this.sessionOpenGeneration;
this.detachPluginTools(agentId);
let appendSystemPrompt: string[] | undefined;
let mcpServers: AgentSessionConfig["mcpServers"];
let mcpServerOwners: Record<string, string> | undefined;
if (this.pluginLifecycle) {
if (this.pluginSessions) {
const request = {
agentId,
provider: client.provider,
@@ -6534,10 +6659,9 @@ export class AgentManager {
tools: [],
mcpServers: {},
};
const transformed = await this.pluginLifecycle.before("agent.open.before", request);
const transformed = await this.pluginSessions.openSession(request);
env = transformed.env;
if (request.purpose === "interactive") {
this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]);
appendSystemPrompt = transformed.appendSystemPrompt;
mcpServers = transformed.mcpServers;
mcpServerOwners = transformed.mcpServerOwners;
@@ -6561,18 +6685,13 @@ export class AgentManager {
this.paseoToolCatalogFactory &&
(useNativeTools || this.getPluginTools(agentId).length > 0)
) {
try {
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy,
});
if (useNativeTools) context.paseoTools = catalog;
} catch (error) {
this.detachPluginTools(agentId);
throw error;
}
// Building the catalog checks the plugin tools against Paseo's own names.
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy,
});
if (useNativeTools) context.paseoTools = catalog;
}
this.sessionOpenGenerations.set(agentId, generation);
return context;
}
@@ -28,7 +28,13 @@ export function registerPluginTools(options: {
description: tool.description,
inputSchema: z.fromJSONSchema(tool.inputSchema),
async handler(input, { signal }) {
const result = await agentManager.executePluginTool(tool, callerAgentId, input, signal);
const result = await agentManager.executePluginTool({
pluginId: tool.pluginId,
toolName: tool.name,
agentId: callerAgentId,
input,
signal,
});
return addModelVisibleStructuredContent({
content: result.text === undefined ? [] : [{ type: "text", text: result.text }],
structuredContent: result.structuredContent,
+2 -7
View File
@@ -1047,7 +1047,7 @@ export async function createPaseoDaemon(
const initialAgentManagerState = providerSnapshotManager.getAgentManagerProviderState();
const agentManager = new AgentManager({
pluginLifecycle: pluginRuntime,
pluginAgentTools: pluginRuntime,
pluginSessions: pluginRuntime,
clients: initialAgentManagerState.clients,
providerDefinitions: initialAgentManagerState.providerDefinitions,
registry: agentStorage,
@@ -1068,10 +1068,6 @@ export async function createPaseoDaemon(
const unsubscribePluginProviders =
pluginRuntime.subscribeProviderRegistrations(syncPluginProviders);
const unsubscribePluginSessionChanges = pluginRuntime.subscribeSessionOpenChanges(() => {
agentManager.invalidatePluginSessions();
});
const detachAgentStoragePersistence = attachAgentStoragePersistence(
logger,
agentManager,
@@ -1700,6 +1696,7 @@ export async function createPaseoDaemon(
// state is retained between requests, matching the previous
// `sessionIdGenerator: undefined` transport.
const createAgentMcpSession = async (callerAgentId?: string) => {
if (callerAgentId) await agentManager.refreshPluginTools(callerAgentId);
const agentMcpServer = await createAgentMcpServer(
createAgentToolHostDependencies({
callerAgentId,
@@ -2045,7 +2042,6 @@ export async function createPaseoDaemon(
localCredential = null;
await deleteLocalCredential(config.paseoHome);
unsubscribePluginProviders();
unsubscribePluginSessionChanges();
await pluginRuntime.stopAllPlugins().catch(() => undefined);
await serviceProxy.stopStandalone().catch(() => undefined);
await agentProviderRuntime.shutdown().catch(() => undefined);
@@ -2067,7 +2063,6 @@ export async function createPaseoDaemon(
// that is still open. Plugins themselves are stopped once every session
// they serve has been closed, further down.
unsubscribePluginProviders();
unsubscribePluginSessionChanges();
await hubRelationships.stop();
workspaceReconciliation.dispose();
scriptHealthMonitor.stop();
@@ -1,4 +1,5 @@
import { fileURLToPath } from "node:url";
import { existsSync } from "node:fs";
import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -476,20 +477,31 @@ test("structured tool results get model-visible text when text is omitted", asyn
}
}, 60_000);
test("reloading a plugin retires its old attachments before an agent reopens", async () => {
test("reloading a plugin retires its old attachments, and both the agent MCP and the launch-time catalog reach the new instance", async () => {
const h = await setup(true);
try {
const a = await h.create({ x: "y" });
const mcp = await h.mcp(a.id);
const oldCatalog = h.launches.at(-1)!.context!.paseoTools!;
const launchCatalog = h.launches.at(-1)!.context!.paseoTools!;
expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo");
expect((await launchCatalog.executeTool("plugin_echo", { text: "before" })).isError).not.toBe(
true,
);
await h.client.reloadPlugin("tools-test");
expect((await mcp.listTools()).tools.map((tool) => tool.name)).not.toContain("plugin_echo");
expect(h.daemon.daemon.agentManager.getPluginTools(a.id)).toEqual([]);
expect(await oldCatalog.executeTool("plugin_echo", { text: "retired" })).toMatchObject({
isError: true,
content: [{ type: "text", text: expect.stringContaining("not available") }],
// A native provider keeps the catalog it launched with. Its call reaches the restarted plugin, whose own call
// count starts again.
const result = await launchCatalog.executeTool("plugin_echo", { text: "after restart" });
expect(result.isError).not.toBe(true);
expect(JSON.parse((result.content as { text: string }[])[0].text)).toMatchObject({
input: { text: "after restart" },
calls: 1,
});
expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo");
expect(h.daemon.daemon.agentManager.getPluginTools(a.id).map((tool) => tool.name)).toEqual([
"plugin_echo",
]);
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
}
@@ -611,6 +623,673 @@ test("a busy agent is steered after plugin reload and reopens only at its next i
}
}, 60_000);
const openCounterSource = `
import { z } from "zod";
import { defineAgentTool } from "@getpaseo/plugin/server";
let opens = 0;
const tool = defineAgentTool({
name: "other_opens", description: "How often this plugin saw the session open",
input: z.object({}),
async execute() { return { text: String(opens) }; },
});
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => {
opens++;
return { ...request, tools: [...request.tools, tool] };
});
return () => {};
}
`;
test("a busy agent's MCP lists and calls a restarted plugin's tools without reopening", async () => {
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const h = await setup(false, pluginSource, undefined, {
beforeTurnComplete: async () => blocked,
});
try {
await h.install("other-hook", openCounterSource);
const a = await h.create({ x: "y" });
await h.client.sendMessage(a.id, "busy prompt", { activeTurnBehavior: "steer" });
await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(true);
await h.client.reloadPlugin("tools-test");
await h.client.sendMessage(a.id, "message while busy", { activeTurnBehavior: "steer" });
expect(h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(true);
const mcp = await h.mcp(a.id);
const names = (await mcp.listTools()).tools.map((tool) => tool.name);
expect(names).toContain("plugin_echo");
expect(names).toContain("other_opens");
const result = await mcp.callTool({
name: "plugin_echo",
arguments: { text: "after restart" },
});
expect(result.isError).not.toBe(true);
// The restarted plugin answers: its own call count starts again.
expect(JSON.parse((result.content as { text: string }[])[0].text)).toMatchObject({
agent: { id: a.id },
input: { text: "after restart" },
calls: 1,
});
// Only the restarted plugin saw the replayed open.
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "1" }],
});
expect(h.launches).toHaveLength(1);
expect(h.events.interrupts).toBe(0);
// The plugin's env records the open reason, and the replay's `refresh` differs from the create, so the session
// reopens at its next idle prompt to apply it.
release();
await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(false);
await sendAndFinish(h, a.id, "idle prompt");
expect(h.launches).toHaveLength(2);
} finally {
release();
await h.close();
}
}, 60_000);
function subagentStatuses(h: Awaited<ReturnType<typeof setup>>, agentId: string) {
return h.daemon.daemon.agentManager
.listProviderSubagentActivity()
.filter((subagent) => subagent.parentAgentId === agentId)
.map((subagent) => subagent.status);
}
test("reloading a plugin keeps an agent it does not target on its provider session, with its subagents running", async () => {
const h = await setup();
try {
const b = await h.create();
await sendAndFinish(h, b.id, "Emit a provider child");
expect(subagentStatuses(h, b.id)).toEqual(["running"]);
await h.client.reloadPlugin("tools-test");
await sendAndFinish(h, b.id, "after reload");
expect(h.launches).toHaveLength(1);
expect(subagentStatuses(h, b.id)).toEqual(["running"]);
} finally {
await h.close();
}
}, 60_000);
test("a restarted plugin that attaches the same tools keeps the agent's session, and the new instance answers", async () => {
const h = await setup(false, openCounterSource);
try {
const a = await h.create();
await sendAndFinish(h, a.id, "Emit a provider child");
await h.client.reloadPlugin("tools-test");
await sendAndFinish(h, a.id, "after reload");
expect(h.launches).toHaveLength(1);
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
// The restarted instance counts the one replayed open.
const mcp = await h.mcp(a.id);
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "1" }],
});
} finally {
await h.close();
}
}, 60_000);
test("reverting a plugin's tool edit lets the agent keep its session, with its subagents running", async () => {
const h = await setup(false, openCounterSource);
try {
const a = await h.create();
await sendAndFinish(h, a.id, "Emit a provider child");
const description = async () =>
(await (await h.mcp(a.id)).listTools()).tools.find((tool) => tool.name === "other_opens")
?.description;
await writePluginSource(
h,
"tools-test",
openCounterSource.replace("How often this plugin saw the session open", "Edited"),
);
await h.client.reloadPlugin("tools-test");
expect(await description()).toBe("Edited");
await writePluginSource(h, "tools-test", openCounterSource);
await h.client.reloadPlugin("tools-test");
expect(await description()).toBe("How often this plugin saw the session open");
await sendAndFinish(h, a.id, "after revert");
expect(h.launches).toHaveLength(1);
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
} finally {
await h.close();
}
}, 60_000);
const breakableSource = (arm: string) => `
import { existsSync } from "node:fs";
import { z } from "zod";
import { defineAgentTool } from "@getpaseo/plugin/server";
const tool = defineAgentTool({
name: "breakable_ping", description: "Ping",
input: z.object({}),
async execute() { return { text: "pong" }; },
});
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => {
if (existsSync(${JSON.stringify(arm)})) throw new Error("broken edit");
return { ...request, tools: [...request.tools, tool] };
});
return () => {};
}
`;
test("a reopen that a broken plugin fails keeps the running session's plugin tools, and fixing the plugin restores its own", async () => {
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-breakable-"));
const arm = path.join(scratch, "arm");
const h = await setup(false, openCounterSource);
try {
await h.install("breakable", breakableSource(arm));
const a = await h.create();
await writeFile(arm, "");
await h.client.reloadPlugin("breakable");
const manager = h.daemon.daemon.agentManager;
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow("broken edit");
expect(h.launches).toHaveLength(1);
const broken = await h.mcp(a.id);
expect(await listedToolNames(broken)).not.toContain("breakable_ping");
expect(await broken.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "2" }],
});
await rm(arm);
await h.client.reloadPlugin("breakable");
const fixed = await h.mcp(a.id);
expect(await fixed.callTool({ name: "breakable_ping", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "pong" }],
});
// The fixed plugin attaches what the running session launched with, so no reopen is due.
await manager.reloadStalePluginSession(a.id);
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
await rm(scratch, { recursive: true, force: true });
}
}, 60_000);
const paseoNameClashSource = openCounterSource.replace(
"tools: [...request.tools, tool]",
'tools: [...request.tools, tool, defineAgentTool({ name: "list_agents", description: "clash", input: z.object({}), async execute() { return { text: "clash" }; } })]',
);
test("a reopen that a plugin's Paseo tool name fails is retried, keeps the running session's plugin tools, and fixing the plugin restores its own", async () => {
const h = await setup(false, openCounterSource);
try {
await h.install("unrelated", breakableSource(path.join(h.directory, "never-armed")));
const a = await h.create();
await writePluginSource(h, "tools-test", paseoNameClashSource);
await h.client.reloadPlugin("tools-test");
const manager = h.daemon.daemon.agentManager;
const collision = /list_agents from plugin tools-test collides with Paseo tool/;
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
expect(h.launches).toHaveLength(1);
const broken = await h.mcp(a.id);
expect(await listedToolNames(broken)).not.toContain("other_opens");
expect(await broken.callTool({ name: "breakable_ping", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "pong" }],
});
await writePluginSource(h, "tools-test", openCounterSource);
await h.client.reloadPlugin("tools-test");
expect(
await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} }),
).toMatchObject({ content: [{ type: "text", text: "1" }] });
await manager.reloadStalePluginSession(a.id);
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
}
}, 60_000);
const claimsOtherOpensSource = `
import { z } from "zod";
import { defineAgentTool } from "@getpaseo/plugin/server";
const tool = defineAgentTool({
name: "other_opens", description: "clash",
input: z.object({}),
async execute() { return { text: "clash" }; },
});
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => ({ ...request, tools: [...request.tools, tool] }));
return () => {};
}
`;
test("after a rejected reopen, a tool name stays with the plugin that had it, even when the claimant sorts first", async () => {
const h = await setup(false, openCounterSource);
try {
await h.install("a-claimant", breakableSource(path.join(h.directory, "never-armed")));
const a = await h.create();
await writePluginSource(h, "a-claimant", claimsOtherOpensSource);
await h.client.reloadPlugin("a-claimant");
const manager = h.daemon.daemon.agentManager;
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(
/other_opens from plugin tools-test collides with plugin a-claimant/,
);
expect(h.launches).toHaveLength(1);
const result = await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} });
expect(result.content).not.toEqual([{ type: "text", text: "clash" }]);
expect(manager.getPluginTools(a.id).map((tool) => tool.pluginId)).toEqual(["tools-test"]);
} finally {
await h.close();
}
}, 60_000);
const metadataGatedSource = openCounterSource.replace(
"opens++;",
'opens++;\n if (request.metadata.tools !== "on") return;',
);
test("a plugin reload reruns its callback with the agent's current metadata", async () => {
const h = await setup(false, metadataGatedSource);
try {
const manager = h.daemon.daemon.agentManager;
const a = await h.create();
expect(await listedToolNames(await h.mcp(a.id))).not.toContain("other_opens");
await manager.setMetadata(a.id, { tools: "on" });
await h.client.reloadPlugin("tools-test");
expect(await listedToolNames(await h.mcp(a.id))).toContain("other_opens");
// The session launched without the tool, so it reopens at the next idle prompt.
await sendAndFinish(h, a.id, "after metadata");
expect(h.launches).toHaveLength(2);
} finally {
await h.close();
}
}, 60_000);
const setsXSource = `
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => ({ ...request, env: { ...request.env, X: "yes" } }));
return () => {};
}
`;
const needsXSource = `
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => {
if (request.env.X !== "yes") return;
return { ...request, env: { ...request.env, Y: "yes" } };
});
return () => {};
}
`;
test("a plugin reruns when an earlier plugin changes what it receives, and the session reopens with the composed launch", async () => {
const h = await setup(false, openCounterSource);
try {
await h.install("a-sets-x", setsXSource);
const a = await h.create();
expect(h.launches.at(-1)!.context!.env).toMatchObject({ X: "yes" });
await h.client.disablePlugin("a-sets-x");
await h.install("b-needs-x", needsXSource);
await listedToolNames(await h.mcp(a.id));
await h.client.enablePlugin("a-sets-x");
await listedToolNames(await h.mcp(a.id));
// b-needs-x now sees X and adds Y, which the running session never launched with.
await sendAndFinish(h, a.id, "after re-enable");
expect(h.launches).toHaveLength(2);
expect(h.launches.at(-1)!.context!.env).toMatchObject({ X: "yes", Y: "yes" });
} finally {
await h.close();
}
}, 60_000);
const hintSource = (hint: string) => `
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => ({ ...request, env: { ...request.env, HINT: ${JSON.stringify(hint)} } }));
return () => {};
}
`;
const hintReaderSource = `
import { z } from "zod";
import { defineAgentTool } from "@getpaseo/plugin/server";
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => {
const { HINT: hint, ...env } = request.env;
const tool = defineAgentTool({
name: "read_tool_hint", description: "The hint from the plugin before",
input: z.object({}),
async execute() { return { text: String(hint) }; },
});
return { ...request, env, tools: [...request.tools, tool] };
});
return () => {};
}
`;
test("a later plugin rerun by an earlier plugin's edit keeps its own tool, and the session keeps running", async () => {
const h = await setup(false, openCounterSource);
try {
await h.install("a-hint", hintSource("red"));
await h.install("b-hint-reader", hintReaderSource);
const a = await h.create();
await writePluginSource(h, "a-hint", hintSource("green"));
await h.client.reloadPlugin("a-hint");
expect(
await (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} }),
).toMatchObject({ content: [{ type: "text", text: "green" }] });
// b-hint-reader removes the hint, so the launch is unchanged.
await sendAndFinish(h, a.id, "after hint change");
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
}
}, 60_000);
// The tool waits for the gate file while it answers the first hint.
const slowHintReaderSource = (entered: string, gate: string) => `
import { existsSync, writeFileSync } from "node:fs";
import { z } from "zod";
import { defineAgentTool } from "@getpaseo/plugin/server";
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => {
const { HINT: hint, ...env } = request.env;
const tool = defineAgentTool({
name: "read_tool_hint", description: "The hint from the plugin before",
input: z.object({}),
async execute() {
if (hint === "red") {
writeFileSync(${JSON.stringify(entered)}, "");
while (!existsSync(${JSON.stringify(gate)})) await new Promise((r) => setTimeout(r, 20));
}
return { text: String(hint) };
},
});
return { ...request, env, tools: [...request.tools, tool] };
});
return () => {};
}
`;
test("a refresh that reruns a plugin lets that plugin's running tool call finish", async () => {
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-running-call-"));
const entered = path.join(scratch, "entered");
const gate = path.join(scratch, "gate");
const h = await setup(false, openCounterSource);
try {
await h.install("a-hint", hintSource("red"));
await h.install("b-hint-reader", slowHintReaderSource(entered, gate));
const a = await h.create();
const running = (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} });
await expect.poll(() => existsSync(entered)).toBe(true);
await writePluginSource(h, "a-hint", hintSource("green"));
await h.client.reloadPlugin("a-hint");
expect(
await (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} }),
).toMatchObject({ content: [{ type: "text", text: "green" }] });
await writeFile(gate, "");
expect(await running).toMatchObject({ content: [{ type: "text", text: "red" }] });
} finally {
await h.close();
await rm(scratch, { recursive: true, force: true });
}
}, 60_000);
// Once armed, the module waits for the gate file before it loads, which holds a restart between stop and start.
const gatedStartSource = (arm: string, entered: string, gate: string) =>
openCounterSource.replace(
'import { z } from "zod";',
`import { existsSync, writeFileSync } from "node:fs";
import { z } from "zod";
if (existsSync(${JSON.stringify(arm)})) {
writeFileSync(${JSON.stringify(entered)}, "");
const pause = new Int32Array(new SharedArrayBuffer(4));
while (!existsSync(${JSON.stringify(gate)})) Atomics.wait(pause, 0, 0, 20);
}`,
);
test("an idle prompt during a plugin restart keeps the agent's session, with its subagents running", async () => {
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-restart-gap-"));
const arm = path.join(scratch, "arm");
const entered = path.join(scratch, "entered");
const gate = path.join(scratch, "gate");
const h = await setup(false, gatedStartSource(arm, entered, gate));
try {
const a = await h.create();
await sendAndFinish(h, a.id, "Emit a provider child");
await writeFile(arm, "");
const reloading = h.client.reloadPlugin("tools-test");
await expect.poll(() => existsSync(entered)).toBe(true);
const prompting = sendAndFinish(h, a.id, "during restart");
// Room for a prompt that does not wait for the restart to reopen the session first.
await new Promise((resolve) => setTimeout(resolve, 500));
await writeFile(gate, "");
await reloading;
await prompting;
expect(h.launches).toHaveLength(1);
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
expect(
await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} }),
).toMatchObject({ content: [{ type: "text", text: "1" }] });
} finally {
await h.close();
await rm(scratch, { recursive: true, force: true });
}
}, 60_000);
const impostorSource = `
import { z } from "zod";
import { defineAgentTool } from "@getpaseo/plugin/server";
const tool = defineAgentTool({
name: "plugin_echo", description: "Not the echo the agent was shown",
input: z.object({ text: z.string() }),
async execute() { return { text: "impostor" }; },
});
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => ({ ...request, tools: [...request.tools, tool] }));
return () => {};
}
`;
test("a launch-time catalog never runs another plugin's tool that took the name", async () => {
const h = await setup(true);
try {
await h.create({ x: "y" });
const launchCatalog = h.launches.at(-1)!.context!.paseoTools!;
await h.client.disablePlugin("tools-test");
await h.install("impostor", impostorSource);
expect(await launchCatalog.executeTool("plugin_echo", { text: "hi" })).toMatchObject({
isError: true,
content: [{ type: "text", text: "Plugin tool is not available: plugin_echo" }],
});
} finally {
await h.close();
}
}, 60_000);
async function writePluginSource(h: Awaited<ReturnType<typeof setup>>, id: string, code: string) {
await writeFile(path.join(h.directory, id, "index.server.ts"), code);
}
async function listedToolNames(mcp: Client) {
return (await mcp.listTools()).tools.map((tool) => tool.name);
}
test("an agent MCP request while a plugin is stopped keeps its tools eligible for the restart", async () => {
const h = await setup();
try {
const a = await h.create({ x: "y" });
await h.client.disablePlugin("tools-test");
expect(await listedToolNames(await h.mcp(a.id))).not.toContain("plugin_echo");
await h.client.enablePlugin("tools-test");
expect(await listedToolNames(await h.mcp(a.id))).toContain("plugin_echo");
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
}
}, 60_000);
// Each open names its tool after its count. Once armed, a process's first open marks that it started and waits
// for the gate file.
const gatedOpenSource = (arm: string, entered: string, gate: string) => `
import { existsSync, writeFileSync } from "node:fs";
import { z } from "zod";
import { defineAgentTool } from "@getpaseo/plugin/server";
let opens = 0;
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => {
const open = ++opens;
if (open === 1 && existsSync(${JSON.stringify(arm)})) {
writeFileSync(${JSON.stringify(entered)}, "");
while (!existsSync(${JSON.stringify(gate)})) await new Promise((r) => setTimeout(r, 20));
}
const tool = defineAgentTool({
name: "which_open", description: "open " + open,
input: z.object({}),
async execute() { return { text: "open " + open }; },
});
return { ...request, tools: [...request.tools, tool] };
});
return () => {};
}
`;
test("a reopen during a tool replay keeps the reopen's tool definitions in the plugin", async () => {
const h = await setup();
const arm = path.join(h.directory, "replay-arm");
const entered = path.join(h.directory, "replay-entered");
const gate = path.join(h.directory, "replay-gate");
try {
await h.install("gated", gatedOpenSource(arm, entered, gate));
const a = await h.create();
await writeFile(arm, "");
await h.client.reloadPlugin("gated");
// The restarted process counts from zero, so its first open is the replay. Hold it at the gate.
const replaying = h.mcp(a.id);
await expect.poll(() => existsSync(entered)).toBe(true);
// The restarted plugin attaches the same definition, so only an explicit reload reopens the session here.
const reopening = h.daemon.daemon.agentManager.reloadAgentSession(a.id);
// Room for an unguarded reopen to reach the plugin first. A guarded one waits, so this cannot change the result.
await new Promise((resolve) => setTimeout(resolve, 500));
await writeFile(gate, "");
const mcp = await replaying;
await reopening;
expect(h.launches).toHaveLength(2);
const mcpAfter = await h.mcp(a.id);
expect((await mcpAfter.listTools()).tools.find((t) => t.name === "which_open")).toMatchObject({
description: "open 2",
});
expect(await mcpAfter.callTool({ name: "which_open", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "open 2" }],
});
await mcp.close();
} finally {
await h.close();
}
}, 60_000);
const failingReplaySource = (arm: string, opens: string) =>
pluginSource
.replace(
'import { z } from "zod";',
'import { appendFileSync, existsSync } from "node:fs";\nimport { z } from "zod";',
)
.replace(
'if (request.labels.x !== "y") return;',
`if (request.labels.x !== "y") return;
appendFileSync(${JSON.stringify(opens)}, "o");
if (existsSync(${JSON.stringify(arm)})) throw new Error("replay failed");`,
);
test("a failed tool replay is not repeated for the same plugin instance, and the next restart replays again", async () => {
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-replay-arm-"));
const arm = path.join(scratch, "arm");
const opens = path.join(scratch, "opens");
const openCount = async () => (await readFile(opens, "utf8")).length;
const h = await setup(false, failingReplaySource(arm, opens));
try {
const a = await h.create({ x: "y" });
expect(await openCount()).toBe(1);
await writeFile(arm, "");
await h.client.reloadPlugin("tools-test");
// Connecting and listing send several agent MCP requests. Only the first one replays the open.
const mcp = await h.mcp(a.id);
expect(await listedToolNames(mcp)).toContain("list_agents");
expect(await listedToolNames(mcp)).not.toContain("plugin_echo");
expect(await openCount()).toBe(2);
await mcp.close();
await rm(arm);
await h.client.reloadPlugin("tools-test");
expect(await listedToolNames(await h.mcp(a.id))).toContain("plugin_echo");
expect(await openCount()).toBe(3);
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
await rm(scratch, { recursive: true, force: true });
}
}, 60_000);
const openReasonSource = `
import { z } from "zod";
import { defineAgentTool } from "@getpaseo/plugin/server";
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => ({
...request,
tools: [...request.tools, defineAgentTool({ name: "open_reason", description: request.reason, input: z.object({}), async execute() { return { text: request.reason }; } })],
}));
return () => {};
}
`;
test("a tool replay reaches the restarted plugin with reason refresh", async () => {
const h = await setup(false, openReasonSource);
try {
const a = await h.create();
await h.client.reloadPlugin("tools-test");
const mcp = await h.mcp(a.id);
expect((await mcp.listTools()).tools.find((t) => t.name === "open_reason")).toMatchObject({
description: "refresh",
});
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
}
}, 60_000);
const nameClashSource = (name: string) =>
pluginSource.replace(
"tools: [...request.tools, tool]",
`tools: [...request.tools, tool, defineAgentTool({ name: ${JSON.stringify(name)}, description: "clash", input: z.object({}), async execute() { return { text: "clash" }; } })]`,
);
test.each([
["another plugin's tool", "other_opens", undefined],
["a Paseo tool", "list_agents", undefined],
["a Paseo tool the agent's provider disables", "list_agents", { disabledTools: ["list_agents"] }],
])(
"a restarted plugin whose tools clash with %s leaves the agent's other tools working",
async (_label, name, policy) => {
const h = await setup(false, pluginSource, policy);
try {
await h.install("other-hook", openCounterSource);
const a = await h.create({ x: "y" });
await writePluginSource(h, "tools-test", nameClashSource(name));
await h.client.reloadPlugin("tools-test");
const mcp = await h.mcp(a.id);
const names = await listedToolNames(mcp);
expect(names).toContain("other_opens");
expect(names.includes("list_agents")).toBe(policy === undefined);
expect(names).toContain("get_agent_status");
expect(names).not.toContain("plugin_echo");
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "1" }],
});
expect(h.daemon.daemon.agentManager.getPluginTools(a.id).map((t) => t.pluginId)).toEqual([
"other-hook",
]);
} finally {
await h.close();
}
},
60_000,
);
const reloadRpcSource = pluginSource
.replace("import { z }", 'import { defineRpc } from "@getpaseo/plugin";\nimport { z }')
.replace(
@@ -858,7 +1537,7 @@ test("installing and disabling an MCP plugin reopens idle sessions before their
}
}, 60_000);
test("installing and disabling an MCP plugin never interrupts a running turn", async () => {
test("installing and disabling an MCP plugin during a running turn neither interrupts it nor reopens the session", async () => {
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
@@ -884,8 +1563,9 @@ test("installing and disabling an MCP plugin never interrupts a running turn", a
expect(h.events.interrupts).toBe(0);
release();
await expect.poll(() => manager.hasInFlightRun(a.id)).toBe(false);
// The plugin came and went before the session saw it, so the launch is unchanged.
await sendAndFinish(h, a.id, "idle");
expect(h.launches).toHaveLength(2);
expect(h.launches).toHaveLength(1);
expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined();
} finally {
release();
@@ -972,6 +1652,118 @@ test("session-open MCP servers fail on unsupported providers and leave saved con
}
}, 60_000);
const mcpWithToolSource = openCounterSource.replace(
"return { ...request, tools: [...request.tools, tool] };",
`return { ...request, tools: [...request.tools, tool], mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} } };`,
);
test("a create that fails the MCP check leaves no plugin tools behind for its agent id", async () => {
const h = await setup(false, mcpWithToolSource, undefined, { supportsMcpServers: false });
try {
const manager = h.daemon.daemon.agentManager;
const agentId = "00000000-0000-4000-8000-000000009493";
await expect(
manager.createAgent({ provider: "codex", cwd: h.directory }, agentId, {}),
).rejects.toThrow(/does not support MCP servers.*plugin tools-test/);
expect(manager.getPluginTools(agentId)).toEqual([]);
} finally {
await h.close();
}
}, 60_000);
test("switching a native tool to an equivalent plugin under another id reopens the session, so its catalog reaches the replacement", async () => {
const h = await setup(true, openCounterSource);
try {
const a = await h.create();
await h.client.disablePlugin("tools-test");
await h.install("replacement", openCounterSource);
await sendAndFinish(h, a.id, "after replacement");
expect(h.launches).toHaveLength(2);
// The replacement answers: it saw the refresh and the reopen.
expect(
await h.launches.at(-1)!.context!.paseoTools!.executeTool("other_opens", {}),
).toMatchObject({ content: [{ type: "text", text: "2" }] });
} finally {
await h.close();
}
}, 60_000);
const mcpOnlySource = `
export default function contribute(server) {
server.addHook("agent.open.before", async ({ request }) => ({ ...request, mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} } }));
return () => {};
}
`;
test("a plugin that adds an MCP server name another plugin already uses makes the reopen report the collision", async () => {
const h = await setup(false, mcpOnlySource);
try {
const a = await h.create();
await h.install("duplicate-mcp", mcpOnlySource);
await expect(h.daemon.daemon.agentManager.reloadStalePluginSession(a.id)).rejects.toThrow(
/MCP server company from plugin tools-test collides with plugin duplicate-mcp/,
);
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
}
}, 60_000);
test("a reopen that fails the MCP check is retried, and the running session keeps its plugin tools", async () => {
const h = await setup(false, mcpSource, undefined, { supportsMcpServers: false });
try {
await h.client.disablePlugin("tools-test");
await h.install("unrelated", breakableSource(path.join(h.directory, "never-armed")));
const a = await h.create();
await h.client.enablePlugin("tools-test");
const manager = h.daemon.daemon.agentManager;
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(/does not support MCP/);
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(/does not support MCP/);
expect(h.launches).toHaveLength(1);
expect(
await (await h.mcp(a.id)).callTool({ name: "breakable_ping", arguments: {} }),
).toMatchObject({ content: [{ type: "text", text: "pong" }] });
} finally {
await h.close();
}
}, 60_000);
test("a reopen whose plugin MCP server takes a saved server name is retried, and reverting the plugin restores its tools", async () => {
const h = await setup(false, openCounterSource);
try {
const manager = h.daemon.daemon.agentManager;
const a = await manager.createAgent(
{
provider: "codex",
cwd: h.directory,
mcpServers: { company: companyServer },
},
undefined,
{},
);
await writePluginSource(
h,
"tools-test",
openCounterSource.replace(
"return { ...request, tools: [...request.tools, tool] };",
`return { ...request, tools: [...request.tools, tool], mcpServers: { company: ${JSON.stringify(companyServer)} } };`,
),
);
await h.client.reloadPlugin("tools-test");
const collision = /MCP server 'company' from plugin tools-test collides with agent saved/;
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
await writePluginSource(h, "tools-test", openCounterSource);
await h.client.reloadPlugin("tools-test");
expect(await listedToolNames(await h.mcp(a.id))).toContain("other_opens");
await manager.reloadStalePluginSession(a.id);
expect(h.launches).toHaveLength(1);
} finally {
await h.close();
}
}, 60_000);
test("history opens ignore session-open MCP servers", async () => {
const h = await setup(true, mcpSource);
try {
@@ -27,9 +27,46 @@ export type SessionOpenWireRequest = Omit<PluginSessionOpenRequest, "tools"> & {
tools: AgentToolMetadata[];
};
export interface PluginAgentToolsRuntime {
isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean;
detachTools(agentId: string): void;
export type PluginSessionOpenResult = SessionOpenWireRequest & {
tools: AttachedAgentTool[];
mcpServerOwners: Record<string, string>;
};
/** What an open request says about the agent that can change while its session runs. Plugins cannot change it. */
export type SessionOpenAgentFacts = Pick<
SessionOpenWireRequest,
"workspaceId" | "title" | "background" | "labels" | "metadata"
>;
export interface PluginSessionRefreshOptions {
/** Tool names a refreshed plugin tool must not take, beyond the tools other plugins attached. */
reservedToolNames(): Promise<ReadonlySet<string>>;
/** The agent as it is now, so a rerun callback sees what a reopen would show it. */
agentFacts(): Promise<SessionOpenAgentFacts>;
}
/** What the agent manager asks of plugins about a session: its open, its attached tools, and their calls. */
export interface PluginSessionsRuntime {
/**
* Runs every `agent.open.before` callback for a session open and records what each plugin attached. The result
* replaces the running session's record once `sessionLaunched` reports that its provider launch took over.
*/
openSession(request: SessionOpenWireRequest): Promise<PluginSessionOpenResult>;
/** The provider session launched with the last open's result. */
sessionLaunched(agentId: string): void;
/** The last open's result did not launch; the session still running keeps its tools. */
sessionLaunchFailed(agentId: string): void;
/**
* Reruns the open of only the plugins that changed since the session opened, swaps in their tools, and reports
* whether the session must reopen to apply the rest.
*/
refreshSession(
agentId: string,
options: PluginSessionRefreshOptions,
): Promise<{ stale: boolean }>;
/** The session's tools from running plugin instances. */
sessionTools(agentId: string): readonly AttachedAgentTool[];
closeSession(agentId: string): void;
callTool(
pluginId: string,
pluginInstanceId: string,
+68 -38
View File
@@ -1,4 +1,4 @@
import type { PluginAgentToolsRuntime } from "./agent-tools.js";
import type { PluginSessionsRuntime } from "./agent-tools.js";
import type { PluginLifecycle } from "./lifecycle/index.js";
import path from "node:path";
import { stat, rm } from "node:fs/promises";
@@ -42,10 +42,9 @@ import type { PluginUsageSourceMetadata } from "./plugin-process-protocol.js";
const BUILTIN_PROVIDER_ID_SET: ReadonlySet<string> = new Set(BUILTIN_PROVIDER_IDS);
interface PluginRuntimePort {
subscribeSessionOpenChanges?: PluginRuntime["subscribeSessionOpenChanges"];
sessionAttachments?: PluginRuntime["sessionAttachments"];
isToolPluginAvailable?: PluginRuntime["isToolPluginAvailable"];
callTool?: PluginRuntime["callTool"];
detachTools?: PluginRuntime["detachTools"];
emit?: PluginLifecycle["emit"];
drainEvents?: PluginRuntime["drainEvents"];
before?: PluginLifecycle["before"];
@@ -102,6 +101,11 @@ export class PluginService {
private readonly builtinPlugins: BuiltinPluginLoader;
private readonly logger: pino.Logger;
private readonly errors = new Map<string, string>();
/**
* Restarts in progress. A restart stops the plugin before its replacement starts; a session refresh waits for it,
* so the gap never reads as the plugin's removal. A restart that fails to start reads as one.
*/
private readonly restarts = new Set<Promise<void>>();
private readonly listeners = new Set<(pluginId: string) => void>();
private readonly providers = new Map<string, ProviderRegistration>();
private readonly usageSources: UsageSourceRegistry;
@@ -153,22 +157,33 @@ export class PluginService {
this.runtime.emit?.(name, event);
};
subscribeSessionOpenChanges(listener: () => void): () => void {
return this.runtime.subscribeSessionOpenChanges?.(listener) ?? (() => {});
}
readonly isToolPluginAvailable: PluginAgentToolsRuntime["isToolPluginAvailable"] = (
pluginId,
pluginInstanceId,
) => {
return this.runtime.isToolPluginAvailable?.(pluginId, pluginInstanceId) ?? false;
readonly openSession: PluginSessionsRuntime["openSession"] = async (request) => {
if (this.runtime.sessionAttachments) return this.runtime.sessionAttachments.open(request);
return { ...request, tools: [], mcpServers: {}, mcpServerOwners: {} };
};
readonly detachTools: PluginAgentToolsRuntime["detachTools"] = (agentId) => {
this.runtime.detachTools?.(agentId);
readonly sessionLaunched: PluginSessionsRuntime["sessionLaunched"] = (agentId) => {
this.runtime.sessionAttachments?.launched(agentId);
};
readonly callTool: PluginAgentToolsRuntime["callTool"] = async (
readonly sessionLaunchFailed: PluginSessionsRuntime["sessionLaunchFailed"] = (agentId) => {
this.runtime.sessionAttachments?.launchFailed(agentId);
};
readonly refreshSession: PluginSessionsRuntime["refreshSession"] = async (agentId, options) => {
while (this.restarts.size > 0) await Promise.all(this.restarts);
return (await this.runtime.sessionAttachments?.refresh(agentId, options)) ?? { stale: false };
};
readonly sessionTools: PluginSessionsRuntime["sessionTools"] = (agentId) => {
return this.runtime.sessionAttachments?.tools(agentId) ?? [];
};
readonly closeSession: PluginSessionsRuntime["closeSession"] = (agentId) => {
this.runtime.sessionAttachments?.close(agentId);
};
readonly callTool: PluginSessionsRuntime["callTool"] = async (
pluginId,
pluginInstanceId,
agent,
@@ -176,7 +191,7 @@ export class PluginService {
input,
signal,
) => {
if (!this.isToolPluginAvailable(pluginId, pluginInstanceId) || !this.runtime.callTool)
if (!this.runtime.isToolPluginAvailable?.(pluginId, pluginInstanceId) || !this.runtime.callTool)
return { isError: true, text: `Plugin is not available: ${pluginId}` };
return this.runtime.callTool(pluginId, pluginInstanceId, agent, name, input, signal);
};
@@ -513,8 +528,10 @@ export class PluginService {
throw new Error("Plugins are globally disabled");
}
this.errors.delete(pluginId);
await this.stopPlugin(pluginId);
await this.startExplicit(pluginId, source.path);
await this.restart(async () => {
await this.stopPlugin(pluginId);
await this.startExplicit(pluginId, source.path);
});
this.notify(pluginId);
return this.requireItem(pluginId);
});
@@ -857,6 +874,17 @@ export class PluginService {
for (const listener of this.providerListeners) listener();
}
private async restart(run: () => Promise<void>): Promise<void> {
const restart = run();
const settled = restart.catch(() => {});
this.restarts.add(settled);
try {
await restart;
} finally {
this.restarts.delete(settled);
}
}
private enqueue<T>(operation: () => Promise<T>): Promise<T> {
const result = this.lifecycle.then(operation, operation);
this.lifecycle = result.then(
@@ -897,28 +925,30 @@ export class PluginService {
const shouldActivate =
current.enabled !== false && this.configStore.get().pluginsEnabled === true;
if (shouldActivate) {
if (isRunning) await this.stopPlugin(pluginId);
try {
await this.startExplicit(pluginId, candidate.directory);
} catch (error) {
let recoveryError: unknown;
await this.restart(async () => {
if (isRunning) await this.stopPlugin(pluginId);
try {
this.errors.delete(pluginId);
if (isRunning && this.canPublish(pluginId))
await this.startExplicit(pluginId, source.path);
} catch (restoreError) {
recoveryError = restoreError;
} finally {
await managedSources.discard(candidate);
this.notify(pluginId);
await this.startExplicit(pluginId, candidate.directory);
} catch (error) {
let recoveryError: unknown;
try {
this.errors.delete(pluginId);
if (isRunning && this.canPublish(pluginId))
await this.startExplicit(pluginId, source.path);
} catch (restoreError) {
recoveryError = restoreError;
} finally {
await managedSources.discard(candidate);
this.notify(pluginId);
}
if (recoveryError)
throw new Error(
`Update failed: ${error instanceof Error ? error.message : String(error)}; restoring previous plugin also failed: ${recoveryError instanceof Error ? recoveryError.message : String(recoveryError)}`,
{ cause: error },
);
throw error;
}
if (recoveryError)
throw new Error(
`Update failed: ${error instanceof Error ? error.message : String(error)}; restoring previous plugin also failed: ${recoveryError instanceof Error ? recoveryError.message : String(recoveryError)}`,
{ cause: error },
);
throw error;
}
});
}
const activatedSource = this.configStore.get().plugins?.[pluginId];
if (!activatedSource) {
@@ -34,10 +34,11 @@ export type PluginWireBeforeRequests = Omit<PluginHookRequests, "agent.open.befo
"agent.open.before": SessionOpenWireRequest;
};
/** Daemon-only results; ownership never crosses the plugin process boundary. */
export type PluginBeforeResults = PluginWireBeforeRequests & {
"agent.open.before": SessionOpenWireRequest & { mcpServerOwners?: Record<string, string> };
};
/** Session opens run through the plugin runtime's session attachments, which record each plugin's contribution. */
export type PluginLifecycleBeforeName = Exclude<
keyof PluginWireBeforeRequests,
"agent.open.before"
>;
const worktreeRequestFields = {
repoRoot: z.string(),
@@ -144,10 +145,10 @@ export interface PluginLifecycle {
payload: PluginHookPayload<"worktree.create.after">,
): Promise<void>;
emit<Name extends keyof PluginHookEvents>(name: Name, event: PluginHookEvents[Name]): void;
before<Name extends keyof PluginWireBeforeRequests>(
before<Name extends PluginLifecycleBeforeName>(
name: Name,
request: PluginWireBeforeRequests[Name],
): Promise<PluginBeforeResults[Name]>;
): Promise<PluginWireBeforeRequests[Name]>;
}
export function validateBeforeRequest<Name extends keyof PluginWireBeforeRequests>(
@@ -390,7 +391,8 @@ export class PluginHookHandlers implements PluginLifecycleRegistration {
context: PluginHookContext,
): Promise<SessionOpenWireRequest> {
let request = validateBeforeRequest("agent.open.before", input);
this.agentTools?.detach(request.agentId);
// Attaching replaces the session's definitions for later calls; calls already running finish. The daemon detaches
// the session before an open that replaces the provider session.
let tools: AgentToolDefinition[] = [];
for (const handler of this.handlers.get("agent.open.before") ?? []) {
context.signal.throwIfAborted();
+38 -79
View File
@@ -1,7 +1,7 @@
import { validateWorktreePath } from "../../utils/worktree-path.js";
import type { PluginHookPayload } from "@getpaseo/plugin/server";
import type { PluginWireBeforeRequests, PluginBeforeResults } from "./lifecycle/index.js";
import type { SessionOpenWireRequest, AttachedAgentTool } from "./agent-tools.js";
import type { PluginLifecycleBeforeName, PluginWireBeforeRequests } from "./lifecycle/index.js";
import { SessionAttachments, type SessionOpenPlugin } from "./session-attachments.js";
import type { UsageScope } from "@getpaseo/plugin/server/usage";
import {
ProviderInspectionSchema,
@@ -374,7 +374,8 @@ export class PluginRuntime {
private readonly spawnChild: () => PluginChild;
private sessionHost: PluginPaseoSessionHost | null;
private readonly listeners = new Set<(pluginId: string, error?: string) => void>();
private readonly sessionOpenListeners = new Set<() => void>();
/** What `agent.open.before` plugins attached to each live session. */
readonly sessionAttachments: SessionAttachments;
constructor(
logger: pino.Logger,
@@ -384,6 +385,13 @@ export class PluginRuntime {
this.logger = logger.child({ module: "plugins" });
this.spawnChild = dependencies.spawnChild ?? spawnPluginChild;
this.sessionHost = dependencies.sessionHost ?? null;
this.sessionAttachments = new SessionAttachments(
{
sessionOpenPlugins: () => this.sessionOpenPlugins(),
detachEverywhere: (agentId) => this.detachTools(agentId),
},
this.logger,
);
}
bindPaseoSessionHost(sessionHost: PluginPaseoSessionHost): void {
@@ -397,16 +405,6 @@ export class PluginRuntime {
return () => this.listeners.delete(listener);
}
subscribeSessionOpenChanges(listener: () => void): () => void {
this.sessionOpenListeners.add(listener);
return () => this.sessionOpenListeners.delete(listener);
}
private notifySessionOpenChange(loaded: LoadedPlugin): void {
if (!loaded.hooks.includes("agent.open.before")) return;
for (const listener of this.sessionOpenListeners) listener();
}
async startPlugin(
pluginId: string,
configuredPath: string,
@@ -429,7 +427,6 @@ export class PluginRuntime {
throw new Error(`Plugin start cancelled: ${pluginId}`);
}
this.plugins.set(pluginId, loaded);
this.notifySessionOpenChange(loaded);
this.appendLog(pluginId, "stdout", "[paseo] Plugin ready");
}
@@ -449,7 +446,6 @@ export class PluginRuntime {
clientBundle: bundles.clientBundle ?? "",
});
this.plugins.set(input.id, loaded);
this.notifySessionOpenChange(loaded);
this.appendLog(input.id, "stdout", "[paseo] Plugin ready");
}
@@ -461,7 +457,6 @@ export class PluginRuntime {
const loaded = this.plugins.get(pluginId);
if (!loaded) return false;
this.plugins.delete(pluginId);
this.notifySessionOpenChange(loaded);
this.rejectPending(loaded, `Plugin stopped: ${pluginId}`);
await this.stopPlugin(loaded);
return true;
@@ -752,17 +747,14 @@ export class PluginRuntime {
}
}
async before<Name extends keyof PluginWireBeforeRequests>(
async before<Name extends PluginLifecycleBeforeName>(
name: Name,
input: PluginWireBeforeRequests[Name],
): Promise<PluginBeforeResults[Name]> {
): Promise<PluginWireBeforeRequests[Name]> {
let request = validateBeforeRequest(name, input);
const plugins = [...this.plugins.values()].sort((left, right) => {
return left.id.localeCompare(right.id);
});
const attached: AttachedAgentTool[] = [];
const mcpServers: SessionOpenWireRequest["mcpServers"] = {};
const mcpServerOwners: Record<string, string> = {};
for (const loaded of plugins) {
if (!loaded.hooks.includes(name)) {
continue;
@@ -772,7 +764,7 @@ export class PluginRuntime {
type: "hook",
requestId: randomUUID(),
name,
input: name === "agent.open.before" ? { ...request, tools: [], mcpServers: {} } : request,
input: request,
});
request = await validateBeforeResult(name, request, output);
if (name === "worktree.create.before") {
@@ -782,27 +774,12 @@ export class PluginRuntime {
repoPath: worktree.repoRoot,
});
}
if (name === "agent.open.before") {
const opened = request as SessionOpenWireRequest;
this.collectMcpServers(mcpServers, mcpServerOwners, loaded, opened.mcpServers);
this.collectAgentTools(attached, loaded, opened.tools);
}
} catch (error) {
if (name === "agent.open.before")
this.detachTools((request as SessionOpenWireRequest).agentId);
throw new Error(`Plugin ${loaded.id} ${name} failed: ${describeError(error)}`, {
cause: error,
});
}
}
if (name === "agent.open.before") {
return {
...request,
tools: attached,
mcpServers,
mcpServerOwners,
} as PluginBeforeResults[Name];
}
return request;
}
@@ -927,43 +904,34 @@ export class PluginRuntime {
return output;
}
private collectMcpServers(
servers: SessionOpenWireRequest["mcpServers"],
owners: Record<string, string>,
loaded: LoadedPlugin,
contributions: SessionOpenWireRequest["mcpServers"],
): void {
for (const [name, server] of Object.entries(contributions)) {
if (Object.hasOwn(servers, name)) {
throw new Error(
`MCP server ${name} from plugin ${loaded.id} collides with plugin ${owners[name]}`,
);
}
servers[name] = server;
owners[name] = loaded.id;
}
}
private collectAgentTools(
attached: AttachedAgentTool[],
loaded: LoadedPlugin,
tools: SessionOpenWireRequest["tools"],
): void {
for (const tool of tools) {
const collision = attached.find((entry) => entry.name === tool.name);
if (collision)
throw new Error(
`Agent tool ${tool.name} from plugin ${loaded.id} collides with plugin ${collision.pluginId}`,
);
attached.push({ ...tool, pluginId: loaded.id, pluginInstanceId: loaded.instanceId });
}
}
isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean {
return this.plugins.get(pluginId)?.instanceId === pluginInstanceId;
}
detachTools(agentId: string): void {
private sessionOpenPlugins(): SessionOpenPlugin[] {
return [...this.plugins.values()]
.filter((loaded) => loaded.child && loaded.hooks.includes("agent.open.before"))
.sort((left, right) => left.id.localeCompare(right.id))
.map((loaded) => ({
id: loaded.id,
instanceId: loaded.instanceId,
open: async (input) => {
const output = await this.request(loaded, {
type: "hook",
requestId: randomUUID(),
name: "agent.open.before",
input,
});
return validateBeforeResult("agent.open.before", input, output);
},
detach: (agentId) => {
if (loaded.child)
void send(loaded.child, { type: "tools.detach", agentId }).catch(() => {});
},
}));
}
private detachTools(agentId: string): void {
for (const loaded of this.plugins.values()) {
if (loaded.child) void send(loaded.child, { type: "tools.detach", agentId }).catch(() => {});
}
@@ -1069,7 +1037,6 @@ export class PluginRuntime {
const loaded = [...this.plugins.values()];
this.plugins.clear();
for (const plugin of loaded) {
this.notifySessionOpenChange(plugin);
this.rejectPending(plugin, `Plugin stopped: ${plugin.id}`);
}
await Promise.all(loaded.map((plugin) => this.stopPlugin(plugin)));
@@ -1310,14 +1277,7 @@ export class PluginRuntime {
private handleChildMessage(loaded: LoadedPlugin, message: PluginProcessMessage): void {
if (message.type === "hooks.changed") {
const hadSessionOpen = loaded.hooks.includes("agent.open.before");
loaded.hooks = message.hooks;
if (
this.plugins.get(loaded.id) === loaded &&
hadSessionOpen !== loaded.hooks.includes("agent.open.before")
) {
for (const listener of this.sessionOpenListeners) listener();
}
return;
}
if (message.type === "worktree_manager.changed") {
@@ -1649,7 +1609,6 @@ export class PluginRuntime {
const wasPublished = this.plugins.get(loaded.id) === loaded;
if (wasPublished) {
this.plugins.delete(loaded.id);
this.notifySessionOpenChange(loaded);
}
this.rejectPending(loaded, `Plugin process exited: ${loaded.id}`);
for (const state of loaded.providerConnections.values()) {
@@ -0,0 +1,472 @@
import { isDeepStrictEqual } from "node:util";
import type pino from "pino";
import type {
AttachedAgentTool,
PluginSessionOpenResult,
PluginSessionRefreshOptions,
SessionOpenAgentFacts,
SessionOpenWireRequest,
} from "./agent-tools.js";
/** A running plugin that declares `agent.open.before`. */
export interface SessionOpenPlugin {
id: string;
instanceId: string;
/** Runs this plugin's `agent.open.before` callback and returns its validated result. */
open(input: SessionOpenWireRequest): Promise<SessionOpenWireRequest>;
/** Drops the agent's tool definitions inside this plugin's process. */
detach(agentId: string): void;
}
export interface SessionAttachmentPlugins {
/** The running plugins that declare `agent.open.before`, in the order a session open runs them. */
sessionOpenPlugins(): SessionOpenPlugin[];
/** Every running plugin process, so a closed session leaves no tool definitions behind. */
detachEverywhere(agentId: string): void;
}
/** What one plugin's `agent.open.before` callback was handed and returned for a session. */
interface Contribution {
pluginId: string;
pluginInstanceId: string;
input: SessionOpenWireRequest;
output: SessionOpenWireRequest;
tools: AttachedAgentTool[];
/** The plugin process holds this contribution's tool definitions for the session. */
synced: boolean;
/** Its rerun failed or its tools collided, so its tools stay off until the reopen reports why. */
failed: boolean;
}
interface Attachment {
base: SessionOpenWireRequest;
/** What each plugin contributed to the provider launch the session is running. */
launched: readonly Contribution[];
/** What each plugin contributes now, after the refreshes since that launch. */
contributions: Contribution[];
/** A reopen now would launch the provider differently from the running session. */
stale: boolean;
}
/**
* Owns what `agent.open.before` plugins attached to each live session: the tools Paseo serves to the agent, and the
* record of each plugin's contribution that decides whether a plugin change needs the session to reopen.
*
* A plugin restart gives it a new instance id. `refresh` reruns the open of only the plugins that changed for the
* session, swaps in their tools at once, and marks the session stale only when the provider launch would differ from
* the one it runs. An open becomes the baseline only once its provider launch takes over the session, so a failed open
* or launch leaves the running launch as the baseline. Opens and refreshes of one session run one at a time.
*/
export class SessionAttachments {
private readonly attachments = new Map<string, Attachment>();
/** Interactive opens whose provider launch has not taken over the session yet. */
private readonly pending = new Map<string, Attachment>();
private readonly tails = new Map<string, Promise<unknown>>();
constructor(
private readonly plugins: SessionAttachmentPlugins,
private readonly logger: pino.Logger,
) {}
async open(request: SessionOpenWireRequest): Promise<PluginSessionOpenResult> {
return this.serialize(request.agentId, async () => {
// Each plugin attaches its tools again below, and a plugin that left the chain keeps none. Until the launch
// takes over, the running session's record stays, and its plugins attach again on its next refresh if the
// launch fails.
this.plugins.detachEverywhere(request.agentId);
for (const contribution of this.attachments.get(request.agentId)?.contributions ?? []) {
contribution.synced = false;
}
const base: SessionOpenWireRequest = { ...request, tools: [], mcpServers: {} };
const contributions: Contribution[] = [];
let current = base;
for (const plugin of this.plugins.sessionOpenPlugins()) {
const input: SessionOpenWireRequest = { ...current, tools: [], mcpServers: {} };
try {
const output = await plugin.open(input);
const tools = stampTools(plugin, output.tools);
assertNoToolCollision(contributions, plugin.id, tools);
contributions.push({
pluginId: plugin.id,
pluginInstanceId: plugin.instanceId,
input,
output,
tools,
synced: true,
failed: false,
});
current = output;
} catch (error) {
this.plugins.detachEverywhere(request.agentId);
throw new Error(`Plugin ${plugin.id} agent.open.before failed: ${describeError(error)}`, {
cause: error,
});
}
}
let launch: PluginSessionOpenResult;
try {
launch = composeLaunch(base, contributions);
} catch (error) {
this.plugins.detachEverywhere(request.agentId);
throw error;
}
if (request.purpose === "interactive") {
this.pending.set(request.agentId, {
base,
launched: contributions,
contributions: [...contributions],
stale: false,
});
}
return launch;
});
}
/**
* Brings a live session's tools up to date with the running plugins and reports whether the session must reopen
* to apply the rest. Plugins that did not change since the session opened are not called.
*/
async refresh(
agentId: string,
options: PluginSessionRefreshOptions,
): Promise<{ stale: boolean }> {
const attachment = this.attachments.get(agentId);
// A launch in progress attaches its own tools and takes over once it succeeds.
if (!attachment || this.pending.has(agentId)) return { stale: false };
if (this.isCurrent(attachment)) return { stale: attachment.stale };
return this.serialize(agentId, () => this.reconcile(agentId, options));
}
/** The provider session launched with the last open's result and now runs it. */
launched(agentId: string): void {
const opened = this.pending.get(agentId);
if (!opened) return;
this.pending.delete(agentId);
this.attachments.set(agentId, opened);
}
/** The last open's result never launched. The session that is still running keeps its record. */
launchFailed(agentId: string): void {
// Nothing is pending once a launch took over; its later failures close the session instead.
if (!this.pending.delete(agentId)) return;
this.plugins.detachEverywhere(agentId);
}
/** The session's tools from running plugin instances. */
tools(agentId: string): AttachedAgentTool[] {
const running = new Map(
this.plugins.sessionOpenPlugins().map((plugin) => [plugin.id, plugin.instanceId]),
);
const attachment = this.pending.get(agentId) ?? this.attachments.get(agentId);
return (attachment?.contributions ?? [])
.filter(
(contribution) =>
contribution.synced &&
running.get(contribution.pluginId) === contribution.pluginInstanceId,
)
.flatMap((contribution) => contribution.tools);
}
close(agentId: string): void {
this.pending.delete(agentId);
this.attachments.delete(agentId);
this.plugins.detachEverywhere(agentId);
}
private isCurrent(attachment: Attachment): boolean {
const running = this.plugins.sessionOpenPlugins();
return (
running.length === attachment.contributions.length &&
running.every((plugin, index) => {
const contribution = attachment.contributions[index];
return (
contribution.synced &&
contribution.pluginId === plugin.id &&
contribution.pluginInstanceId === plugin.instanceId
);
})
);
}
private async reconcile(
agentId: string,
options: PluginSessionRefreshOptions,
): Promise<{ stale: boolean }> {
const attachment = this.attachments.get(agentId);
if (!attachment || this.pending.has(agentId)) return { stale: false };
if (this.isCurrent(attachment)) return { stale: attachment.stale };
const recorded = new Map(
attachment.contributions.map((contribution) => [contribution.pluginId, contribution]),
);
// The running plugins in open order, as a reopen would run them. A stopped plugin, or one that no longer declares
// the callback, drops out, and the plugins after it see the chain without it.
let previous = attachment.base;
const contributions: Contribution[] = [];
const replayed: { contribution: Contribution; plugin: SessionOpenPlugin }[] = [];
let facts: SessionOpenAgentFacts | undefined;
for (const plugin of this.plugins.sessionOpenPlugins()) {
const before = recorded.get(plugin.id);
if (before && isReusable(before, plugin, previous)) {
contributions.push(before);
previous = before.output;
continue;
}
facts ??= await options.agentFacts();
const contribution = await this.replay(plugin, {
...previous,
...facts,
tools: [],
mcpServers: {},
});
contributions.push(contribution);
replayed.push({ contribution, plugin });
previous = contribution.output;
}
await this.dropCollidingTools({
agentId,
owners: toolOwners(attachment.contributions),
contributions,
replayed,
options,
});
if (this.attachments.get(agentId) !== attachment) {
// The session closed during the replay. Its close detached every plugin before the replay attached again.
for (const { plugin } of replayed) plugin.detach(agentId);
return { stale: false };
}
attachment.contributions = contributions;
attachment.stale =
contributions.some((contribution) => contribution.failed) ||
!launchesMatch(attachment.base, attachment.launched, contributions);
return { stale: attachment.stale };
}
/** Reruns one plugin's open for a live session, as the reopen the same change would cause. */
private async replay(
plugin: SessionOpenPlugin,
input: SessionOpenWireRequest,
): Promise<Contribution> {
const contribution = (output: SessionOpenWireRequest, failed: boolean): Contribution => ({
pluginId: plugin.id,
pluginInstanceId: plugin.instanceId,
input,
output,
tools: stampTools(plugin, output.tools),
synced: true,
failed,
});
try {
return contribution(await plugin.open({ ...input, reason: "refresh" }), false);
} catch (error) {
// Recorded under the new instance with no tools, so later requests do not wait on it again. The reopen
// reruns the callback and reports its error.
this.logger.warn(
{ err: error, pluginId: plugin.id, agentId: input.agentId },
"Plugin session refresh failed",
);
return contribution(input, true);
}
}
/**
* A replayed plugin whose tool takes a name already in use keeps no tools; the reopen reports the collision. A name
* stays with the plugin that has it in the session's record, whatever the plugin order.
*/
private async dropCollidingTools({
agentId,
owners,
contributions,
replayed,
options,
}: CollisionCheck): Promise<void> {
if (replayed.every(({ contribution }) => contribution.tools.length === 0)) return;
const changed = new Set(replayed.map(({ contribution }) => contribution));
const taken = new Set(await options.reservedToolNames());
for (const contribution of contributions) {
if (!changed.has(contribution)) for (const tool of contribution.tools) taken.add(tool.name);
}
// The previous owner keeps a name only while it still returns that tool.
const ownedElsewhere = (contribution: Contribution, name: string) => {
const owner = owners.get(name);
if (owner === undefined || owner === contribution.pluginId) return false;
return contributions.some(
(other) => other.pluginId === owner && other.tools.some((tool) => tool.name === name),
);
};
for (const contribution of changed) {
const conflict = contribution.tools.find(
(tool) => taken.has(tool.name) || ownedElsewhere(contribution, tool.name),
);
if (conflict) {
this.logger.warn(
{ agentId, pluginId: contribution.pluginId, tool: conflict.name },
"Refreshed plugin tool collides with another agent tool",
);
contribution.tools = [];
contribution.failed = true;
continue;
}
for (const tool of contribution.tools) taken.add(tool.name);
}
}
private serialize<T>(agentId: string, run: () => Promise<T>): Promise<T> {
const previous = this.tails.get(agentId) ?? Promise.resolve();
const next = previous.then(run, run);
const settled = next.then(
() => undefined,
() => undefined,
);
this.tails.set(agentId, settled);
void settled.finally(() => {
if (this.tails.get(agentId) === settled) this.tails.delete(agentId);
});
return next;
}
}
interface CollisionCheck {
agentId: string;
/** Which plugin has each tool name in the session's record before this refresh. */
owners: ReadonlyMap<string, string>;
contributions: Contribution[];
replayed: { contribution: Contribution }[];
options: PluginSessionRefreshOptions;
}
function toolOwners(contributions: readonly Contribution[]): Map<string, string> {
return new Map(
contributions.flatMap((contribution) =>
contribution.tools.map((tool) => [tool.name, contribution.pluginId] as const),
),
);
}
/**
* A recorded contribution stands for the plugin's callback in a reopen while the plugin runs the same instance, holds
* the tools in its process, and would receive the same env and instructions from the plugins before it.
*/
function isReusable(
contribution: Contribution,
plugin: SessionOpenPlugin,
incoming: SessionOpenWireRequest,
): boolean {
return (
contribution.synced &&
contribution.pluginInstanceId === plugin.instanceId &&
isDeepStrictEqual(chainedFields(contribution.input), chainedFields(incoming))
);
}
/** The fields one plugin's callback passes on to the next. Tools and MCP servers are collected per plugin instead. */
function chainedFields(request: SessionOpenWireRequest) {
return { env: request.env, appendSystemPrompt: request.appendSystemPrompt ?? [] };
}
/**
* What the provider launches with when the session opens with these contributions, in open order. Throws when two
* plugins return the same MCP server name.
*/
function composeLaunch(
base: SessionOpenWireRequest,
contributions: readonly Contribution[],
): PluginSessionOpenResult {
const mcpServers: SessionOpenWireRequest["mcpServers"] = {};
const mcpServerOwners: Record<string, string> = {};
for (const contribution of contributions) {
collectMcpServers(
mcpServers,
mcpServerOwners,
contribution.pluginId,
contribution.output.mcpServers,
);
}
return {
...(contributions.at(-1)?.output ?? base),
tools: contributions.flatMap((contribution) => contribution.tools),
mcpServers,
mcpServerOwners,
};
}
/**
* Whether the proposed contributions launch the session as it runs now. A tool's plugin counts, since native-tool
* catalogs dispatch to it; its instance does not. A launch the open would reject never matches, so the reopen
* reports it.
*/
function launchesMatch(
base: SessionOpenWireRequest,
launched: readonly Contribution[],
proposed: readonly Contribution[],
): boolean {
let next: PluginSessionOpenResult;
try {
next = composeLaunch(base, proposed);
} catch {
return false;
}
return isDeepStrictEqual(launchContract(composeLaunch(base, launched)), launchContract(next));
}
function launchContract(launch: PluginSessionOpenResult) {
return {
...chainedFields(launch),
mcpServers: launch.mcpServers,
tools: launch.tools.map(({ pluginId, name, title, description, inputSchema }) => ({
pluginId,
name,
title,
description,
inputSchema,
})),
};
}
function stampTools(
plugin: SessionOpenPlugin,
tools: SessionOpenWireRequest["tools"],
): AttachedAgentTool[] {
return tools.map((tool) => ({
...tool,
pluginId: plugin.id,
pluginInstanceId: plugin.instanceId,
}));
}
function assertNoToolCollision(
contributions: readonly Contribution[],
pluginId: string,
tools: readonly AttachedAgentTool[],
): void {
for (const tool of tools) {
const owner = contributions.find((contribution) =>
contribution.tools.some((entry) => entry.name === tool.name),
);
if (owner) {
throw new Error(
`Agent tool ${tool.name} from plugin ${pluginId} collides with plugin ${owner.pluginId}`,
);
}
}
}
function collectMcpServers(
servers: SessionOpenWireRequest["mcpServers"],
owners: Record<string, string>,
pluginId: string,
contributions: SessionOpenWireRequest["mcpServers"],
): void {
for (const [name, server] of Object.entries(contributions)) {
if (Object.hasOwn(servers, name)) {
throw new Error(
`Plugin ${pluginId} agent.open.before failed: MCP server ${name} from plugin ${pluginId} collides with plugin ${owners[name]}`,
);
}
servers[name] = server;
owners[name] = pluginId;
}
}
function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+32 -2
View File
@@ -498,12 +498,42 @@ target are unaffected.
| Change | When the agent receives it |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Start, stop, or reload a plugin declaring `agent.open.before` | Open sessions become stale. Each reopens before its next idle prompt; a running turn continues without interruption. The next prompt after that reopen reuses the session. |
| Start, stop, or reload a plugin declaring `agent.open.before` | Before the session's next agent tool call or prompt, as described below. |
| Change which agents the callback targets | Run `paseo plugin reload agent-tools` after editing this example, then send the agent a prompt when it is idle. |
| Apply immediately | Call `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`. `requestId` is optional. This reopens the provider session, reruns hooks with `reason: "refresh"`, and interrupts a running turn. |
| Read the current snapshot | Call `await paseo.agents.ref(id).refresh()`. This reads state without reopening the session. |
If an automatic reopen fails, the triggering prompt fails with that error. See the
When a plugin declaring `agent.open.before` starts, stops, or reloads, Paseo reruns that plugin's
callback for each open session, before the session's next agent tool call or prompt. The callback
gets the request it saw at the session's last open, with `reason: "refresh"` and the agent's current
title, workspace, labels, and metadata. A later plugin in the chain also reruns when the env or
instructions it receives change. Other callbacks do not run.
A reload counts as one change. A tool call or prompt during the reload waits for the plugin to
start, so the session does not lose the plugin's tools in between. If the plugin fails to start,
the session continues as if the plugin stopped.
- The tools the callback returns replace its old tools at once, also during a running turn. The new
plugin instance answers the calls.
- If the env, instructions, MCP servers, tool definitions, or the plugin that provides a tool
differ from what the session launched with, the session reopens before its next idle prompt. A running turn continues without interruption.
A callback whose result depends on `reason` always differs from a `create` open. Reverting the
change before that prompt cancels the reopen.
- If nothing differs, the session keeps running with its background work and subagents. A plugin
that does not target the agent leaves it as it is.
- If the callback throws or times out, its tools stay off, and the session reopens before its next
idle prompt. Paseo does not rerun it for the same plugin instance.
- If a returned tool collides with a Paseo tool or another plugin's tool, that plugin's tools stay
off, and the session reopens before its next idle prompt.
- If two plugins return the same MCP server name, both plugins keep their agent tools, but the reopen
before the next idle prompt fails with the collision error.
Agents that receive Paseo tools natively (OpenCode with the bridge, OMP) keep the tool list they
launched with until the reopen. Their calls to a listed tool reach the new instance of the plugin
that attached it, and fail if that plugin no longer attaches it.
If an automatic reopen fails, the triggering prompt fails with that error. The session keeps
running with the tools it had, and each later idle prompt tries the reopen again. See the
[complete agent-tools example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools).
## agent.close.after