mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
623eb3685f | ||
|
|
91be92fa69 | ||
|
|
e51bb7b8cd | ||
|
|
050e168974 | ||
|
|
e114e13de2 | ||
|
|
3777cc754b | ||
|
|
7708e1f084 | ||
|
|
ba45634eee | ||
|
|
5c82a2e999 | ||
|
|
60943dde1c | ||
|
|
e52bb6e3c4 |
@@ -131,6 +131,29 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||
|
||||
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
|
||||
sdk-tests-windows:
|
||||
name: sdk-tests (windows-latest)
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: node scripts/npm-retry.mjs ci
|
||||
|
||||
- name: Build plugin SDK
|
||||
run: npm run build:relay && npm run build:client && npm run build:plugin
|
||||
|
||||
- name: Run plugin SDK tests
|
||||
run: npm run test --workspace=@getpaseo/plugin
|
||||
|
||||
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
|
||||
typecheck:
|
||||
name: typecheck
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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`.
|
||||
@@ -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
|
||||
|
||||
@@ -32,10 +32,11 @@ CI does not build native code or run the fork's Robolectric suites. Run `npm run
|
||||
|
||||
Some fork changes are backports. A sync past the upstream version drops them in favour of upstream's code:
|
||||
|
||||
| Fork change | Upstream | Released in |
|
||||
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
|
||||
| Android measurements survive parent clones | [#924](https://github.com/software-mansion/enriched-markdown/pull/924) | after `1.2.0-nightly-20261019-926ef06f0` |
|
||||
| Android nested list items start their text after their own marker | [#1015](https://github.com/software-mansion/enriched-markdown/pull/1015), [#1023](https://github.com/software-mansion/enriched-markdown/pull/1023) (Android) | `1.2.0` |
|
||||
| Fork change | Upstream | Released in |
|
||||
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
|
||||
| Android measurements survive parent clones | [#924](https://github.com/software-mansion/enriched-markdown/pull/924) | after `1.2.0-nightly-20261019-926ef06f0` |
|
||||
| Android long-press drag selection keeps parent intercept disallowed | [#1012](https://github.com/software-mansion/enriched-markdown/pull/1012) | `1.2.0` |
|
||||
| Android nested list items start their text after their own marker | [#1015](https://github.com/software-mansion/enriched-markdown/pull/1015), [#1023](https://github.com/software-mansion/enriched-markdown/pull/1023) (Android) | `1.2.0` |
|
||||
|
||||
## Engine constraints
|
||||
|
||||
|
||||
+60
-2
@@ -462,13 +462,56 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret
|
||||
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
|
||||
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
|
||||
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.
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a
|
||||
[launch wrap](#launch-wrap) 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.
|
||||
|
||||
### Launch wrap
|
||||
|
||||
An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that
|
||||
session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell,
|
||||
except Windows script launchers, which go through cmd.exe like any provider launcher
|
||||
(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must
|
||||
be an absolute path.
|
||||
The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen
|
||||
reuses the wrap it opened with.
|
||||
|
||||
- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the
|
||||
provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an
|
||||
absent field means unsupported, which is also what a host without this feature reports. Core
|
||||
providers declare it in the provider contract table in `provider-registry.ts`; every core provider
|
||||
that starts a local harness declares it, and custom ACP providers and providers that extend a core
|
||||
one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`;
|
||||
`runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the
|
||||
registration metadata, so it is in the snapshot before the provider first connects.
|
||||
- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return
|
||||
the same value. A different value fails the open.
|
||||
- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It
|
||||
throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not
|
||||
declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host
|
||||
that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the
|
||||
spawn; nothing retries the bare command.
|
||||
|
||||
Once an open selects a wrap, a supported provider runs that session's harness through it or fails
|
||||
before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the
|
||||
argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it
|
||||
(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for
|
||||
the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP
|
||||
client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated
|
||||
server instead; an explicitly configured external OpenCode server cannot be wrapped and the open
|
||||
fails. The guarantee does not cover:
|
||||
|
||||
1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap.
|
||||
2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog
|
||||
lookup during create when no model is set.
|
||||
3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's
|
||||
initialize probe included), catalog and session listing, version and update commands, usage
|
||||
queries, and Codex native archive and unarchive.
|
||||
4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped.
|
||||
|
||||
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.
|
||||
Workspace records decide ownership, including explicit non-ownership after recovery. Without a record,
|
||||
@@ -487,6 +530,17 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
|
||||
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
|
||||
`plugin-examples/worktrunk`.
|
||||
|
||||
`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run.
|
||||
|
||||
Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle
|
||||
module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's
|
||||
`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and
|
||||
no previous-version adapter is needed. A default-shell terminal resolves the shell there through
|
||||
`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty.
|
||||
The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not
|
||||
report command completion. A setup or teardown wrap goes in front of the
|
||||
`buildStringCommandShellInvocation` argv.
|
||||
|
||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||
@@ -586,6 +640,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op
|
||||
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
|
||||
no provider reload input.
|
||||
|
||||
Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can
|
||||
run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See
|
||||
[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both.
|
||||
|
||||
For an ACP command, register `runAcpProvider({ id, label, command })` from
|
||||
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
|
||||
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
|
||||
|
||||
+17
-4
@@ -202,10 +202,23 @@ owner wraps cached preparation, network catch-up, accepted timeline application,
|
||||
behind one interface. React supplies transport and projection operations without selecting a cache
|
||||
path or issuing a separate persistence notification.
|
||||
|
||||
Active-agent list reconciliation does not own transcript lifetime. An archived agent's fresh
|
||||
history response can arrive before the active-list response that omits it. Clearing history there
|
||||
would discard accepted rows while the viewed owner still considers them synchronized. Entity
|
||||
deletion clears the transcript; list membership changes do not.
|
||||
The viewed-timeline owner also owns how long a transcript stays in memory. An active agent's
|
||||
transcript stays resident while its chat is hidden, so switching back to it needs no fetch. An
|
||||
archived agent's transcript stays resident only while its chat is shown, for example when it is
|
||||
opened from History. When an agent is archived, or the active list drops it because its workspace
|
||||
was archived, the owner releases the transcript unless the chat is shown. It also releases the
|
||||
transcript when the chat stops being shown. A released chat leaves the opened chats. When it is
|
||||
shown again, it reads the replica cache and catches up again. A history page, live event, or cache
|
||||
read that arrives after the release is dropped.
|
||||
|
||||
The active-list reconciliation does not release transcripts itself. An archived agent's fresh
|
||||
history response can arrive before the active-list response that omits it, while the chat is
|
||||
open in History. Clearing history there would discard rows the user is reading.
|
||||
|
||||
An agent counts as archived when the active list omits it, when its row has an archive timestamp,
|
||||
or when the workspace list omits its workspace. The workspace check matters because a workspace
|
||||
archive can complete while one of its agents keeps a row with no archive timestamp. Until a list
|
||||
first hydrates, it marks no agent as archived. Deleting the agent clears the transcript.
|
||||
|
||||
Removing the host from the registry is the destructive boundary: it stops the runtime and clears the
|
||||
session and host-scoped setup state together.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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],
|
||||
},
|
||||
|
||||
@@ -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";
|
||||
|
||||
+118
-1
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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: "تعذّر التراجع عن الأرشفة",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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: "アーカイブを元に戻せませんでした",
|
||||
},
|
||||
|
||||
@@ -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: "보관을 취소하지 못했습니다",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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: "Не удалось отменить архивацию",
|
||||
},
|
||||
|
||||
@@ -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: "无法撤销归档",
|
||||
},
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
|
||||
@@ -201,15 +201,9 @@ export class AgentStoreProjection {
|
||||
useDraftStore.getState().clearDraftInput({
|
||||
draftKey: buildDraftStoreKey({ serverId: this.serverId, agentId }),
|
||||
});
|
||||
// Only entity deletion destroys the transcript. A filtered active-list
|
||||
// response can arrive after a fresh history response for an archived agent.
|
||||
const store = useSessionStore.getState();
|
||||
const removeKey = withoutAgent(agentId);
|
||||
store.setAgentTimelineCursor(this.serverId, removeKey);
|
||||
store.setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
|
||||
store.setAgentAuthoritativeHistoryApplied(this.serverId, agentId, false);
|
||||
store.setAgentStreamTail(this.serverId, removeKey);
|
||||
store.clearAgentStreamHead(this.serverId, agentId);
|
||||
// Leaving the active list does not release the transcript: an archived chat open in
|
||||
// History stays readable. The viewed timeline owner releases it once nobody shows it.
|
||||
useSessionStore.getState().releaseAgentTimeline(this.serverId, agentId);
|
||||
}
|
||||
|
||||
archive(agentId: string, archivedAt: string): Agent | null {
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
}));
|
||||
@@ -603,6 +603,8 @@ interface SessionStoreActions {
|
||||
message: UserMessageItem,
|
||||
) => boolean;
|
||||
clearAgentStreamHead: (serverId: string, agentId: string) => void;
|
||||
/** Drops every piece of one chat's resident transcript: rows, cursors, paging and sync marks. */
|
||||
releaseAgentTimeline: (serverId: string, agentId: string) => void;
|
||||
setAgentTimelineCursor: (
|
||||
serverId: string,
|
||||
state:
|
||||
@@ -1342,6 +1344,35 @@ export const useSessionStore = create<SessionStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
releaseAgentTimeline: (serverId, agentId) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
if (!session) return prev;
|
||||
const timelineKeys = [
|
||||
"agentStreamTail",
|
||||
"agentStreamHead",
|
||||
"agentTasks",
|
||||
"agentTimelineCursor",
|
||||
"agentTimelineUnsettledTurn",
|
||||
"agentTimelineHasOlder",
|
||||
"agentTimelineHasNewer",
|
||||
"agentTimelineOlderFetchInFlight",
|
||||
"agentHistorySyncGeneration",
|
||||
"agentAuthoritativeHistoryApplied",
|
||||
] as const satisfies readonly (keyof SessionState)[];
|
||||
let next: SessionState | null = null;
|
||||
for (const key of timelineKeys) {
|
||||
const current: Map<string, unknown> = session[key];
|
||||
if (!current.has(agentId)) continue;
|
||||
const without = new Map(current);
|
||||
without.delete(agentId);
|
||||
next = { ...(next ?? session), [key]: without };
|
||||
}
|
||||
if (!next) return prev;
|
||||
return { ...prev, sessions: { ...prev.sessions, [serverId]: next } };
|
||||
});
|
||||
},
|
||||
|
||||
setAgentTimelineCursor: (serverId, state) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
|
||||
@@ -165,6 +165,7 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti
|
||||
const sync = createViewedTimelineSync({
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
prepare: async () => undefined,
|
||||
isArchived: () => false,
|
||||
canCheckFreshness: () => false,
|
||||
applyCurrentTimeline: () => undefined,
|
||||
observe: (agentIds) => {
|
||||
|
||||
@@ -7,9 +7,17 @@ import {
|
||||
} from "@/runtime/replica-cache/row-store-sqlite";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AgentSnapshotPayload,
|
||||
AgentStreamEventPayload,
|
||||
WorkspaceDescriptorPayload,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { FetchAgentsEntry } from "@getpaseo/client/internal/daemon-client";
|
||||
import { AgentDirectoryReplica } from "@/runtime/directory-sync/agent-replica";
|
||||
import { WorkspaceDirectoryReplica } from "@/runtime/directory-sync/workspace-replica";
|
||||
import type { CachedTimeline } from "@/runtime/replica-cache";
|
||||
import {
|
||||
normalizeWorkspaceDescriptor,
|
||||
selectAgentTimelineState,
|
||||
selectAgentTimelineTurnPresentation,
|
||||
selectAgentTurnPresentation,
|
||||
@@ -1802,3 +1810,365 @@ describe("SQLite baseline restoration", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("archived timeline lifetime", () => {
|
||||
const ACTIVE = "active-agent";
|
||||
const OTHER = "other-agent";
|
||||
const ARCHIVED = "archived-agent";
|
||||
/** An agent whose row never got its archive timestamp, in a workspace that was archived. */
|
||||
const IN_ARCHIVED_WORKSPACE = "agent-in-archived-workspace";
|
||||
const WORKSPACE = "workspace";
|
||||
const ARCHIVED_WORKSPACE = "archived-workspace";
|
||||
const openOwners: ViewedTimelineOwner[] = [];
|
||||
afterEach(() => {
|
||||
for (const owner of openOwners.splice(0)) owner.dispose();
|
||||
});
|
||||
|
||||
function agentPayload(
|
||||
id: string,
|
||||
archivedAt?: string,
|
||||
workspaceId: string = WORKSPACE,
|
||||
): AgentSnapshotPayload {
|
||||
return {
|
||||
id,
|
||||
workspaceId,
|
||||
provider: "codex",
|
||||
cwd: "/repo",
|
||||
model: null,
|
||||
createdAt: "2026-07-17T00:00:00.000Z",
|
||||
updatedAt: "2026-07-17T00:01:00.000Z",
|
||||
lastUserMessageAt: null,
|
||||
status: "idle",
|
||||
capabilities: {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: true,
|
||||
supportsMcpServers: true,
|
||||
supportsReasoningStream: true,
|
||||
supportsToolInvocations: true,
|
||||
},
|
||||
currentModeId: null,
|
||||
availableModes: [],
|
||||
pendingPermissions: [],
|
||||
persistence: null,
|
||||
title: id,
|
||||
labels: {},
|
||||
...(archivedAt ? { archivedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function directoryEntry(id: string): FetchAgentsEntry {
|
||||
return {
|
||||
agent: agentPayload(id),
|
||||
project: {
|
||||
projectKey: "/repo",
|
||||
projectName: "repo",
|
||||
checkout: {
|
||||
cwd: "/repo",
|
||||
isGit: false,
|
||||
currentBranch: null,
|
||||
remoteUrl: null,
|
||||
worktreeRoot: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
mainRepoRoot: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function historyPage(agentId: string): TimelineResponsePayload {
|
||||
return {
|
||||
requestId: `tail-${agentId}`,
|
||||
agentId,
|
||||
agent: null,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
reset: false,
|
||||
epoch: "epoch-1",
|
||||
window: { minSeq: 1, maxSeq: 1, nextSeq: 2 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 1 },
|
||||
entries: [
|
||||
{
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: `history of ${agentId}` },
|
||||
timestamp: "2026-08-26T10:00:00.000Z",
|
||||
seqStart: 1,
|
||||
seqEnd: 1,
|
||||
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
|
||||
collapsed: [],
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
hasNewer: false,
|
||||
hasOlder: false,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A host with an active directory and a viewed-timeline owner. Fetches reach the store the
|
||||
* way the host runtime delivers them: the agent row first, then the page, whether or not
|
||||
* the catch-up that asked for it is still current.
|
||||
*/
|
||||
function openHost(
|
||||
activeAgentIds: string[],
|
||||
storage: TimelineReplicaStorage = {
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: () => undefined,
|
||||
},
|
||||
) {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const directory = new AgentDirectoryReplica(
|
||||
SERVER_ID,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
const workspaces = new WorkspaceDirectoryReplica(SERVER_ID);
|
||||
workspaces.commitSnapshot(
|
||||
{
|
||||
workspaces: new Map([[WORKSPACE, normalizeWorkspaceDescriptor(workspaceDescriptor())]]),
|
||||
projects: new Map(),
|
||||
},
|
||||
[],
|
||||
);
|
||||
directory.commitSnapshot(activeAgentIds.map(directoryEntry), []);
|
||||
const fetches: string[] = [];
|
||||
const held = new Map<string, () => void>();
|
||||
const holding = new Set<string>();
|
||||
const replica = createTimelineReplica({
|
||||
serverId: SERVER_ID,
|
||||
storage,
|
||||
prepareAgent: async () => undefined,
|
||||
});
|
||||
const owner: ViewedTimelineOwner = createViewedTimelineOwner({
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => false,
|
||||
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
|
||||
readCursor: () => undefined,
|
||||
fetchPage: async (agentId) => {
|
||||
fetches.push(agentId);
|
||||
if (holding.has(agentId)) {
|
||||
await new Promise<void>((resolve) => held.set(agentId, resolve));
|
||||
}
|
||||
if (agentId === ARCHIVED) {
|
||||
directory.submitTimelineAgent(
|
||||
directory.captureTimeline(agentId),
|
||||
agentPayload(agentId, "2026-09-11T00:00:00.000Z"),
|
||||
);
|
||||
}
|
||||
if (agentId === IN_ARCHIVED_WORKSPACE) {
|
||||
directory.submitTimelineAgent(
|
||||
directory.captureTimeline(agentId),
|
||||
agentPayload(agentId, undefined, ARCHIVED_WORKSPACE),
|
||||
);
|
||||
}
|
||||
owner.applyTimelineResponse(historyPage(agentId));
|
||||
return { hasNewer: false, endCursor: null };
|
||||
},
|
||||
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
||||
reportError: () => undefined,
|
||||
},
|
||||
});
|
||||
owner.setConnected(true);
|
||||
openOwners.push(owner);
|
||||
return {
|
||||
directory,
|
||||
workspaces,
|
||||
owner,
|
||||
fetches,
|
||||
view(agentIds: string[]) {
|
||||
owner.replaceVisibleAgentIds("workspace", agentIds);
|
||||
},
|
||||
hold(agentId: string) {
|
||||
holding.add(agentId);
|
||||
},
|
||||
async deliverHeld(agentId: string) {
|
||||
await expect.poll(() => held.has(agentId)).toBe(true);
|
||||
held.get(agentId)?.();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function workspaceDescriptor(): WorkspaceDescriptorPayload {
|
||||
return {
|
||||
id: WORKSPACE,
|
||||
projectId: "project",
|
||||
projectDisplayName: "project",
|
||||
projectRootPath: "/repo",
|
||||
workspaceDirectory: "/repo",
|
||||
projectKind: "git",
|
||||
workspaceKind: "worktree",
|
||||
name: WORKSPACE,
|
||||
title: WORKSPACE,
|
||||
status: "done",
|
||||
activityAt: null,
|
||||
statusEnteredAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
};
|
||||
}
|
||||
|
||||
function timelineStatus(agentId: string): string {
|
||||
return selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], agentId).status;
|
||||
}
|
||||
|
||||
function residentAgentIds(): string[] {
|
||||
const session = useSessionStore.getState().sessions[SERVER_ID];
|
||||
if (!session) return [];
|
||||
return [
|
||||
...new Set([
|
||||
...session.agentStreamTail.keys(),
|
||||
...session.agentStreamHead.keys(),
|
||||
...session.agentTimelineCursor.keys(),
|
||||
...session.agentAuthoritativeHistoryApplied.keys(),
|
||||
...session.agentTimelineHasOlder.keys(),
|
||||
...session.agentTimelineHasNewer.keys(),
|
||||
...session.agentHistorySyncGeneration.keys(),
|
||||
]),
|
||||
].sort();
|
||||
}
|
||||
|
||||
it("keeps hidden active chats cached and switches back without a fetch", async () => {
|
||||
const host = openHost([ACTIVE, OTHER]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([OTHER]);
|
||||
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
|
||||
host.view([ACTIVE]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(timelineStatus(ACTIVE)).toBe("synced");
|
||||
expect(timelineStatus(OTHER)).toBe("synced");
|
||||
expect(host.fetches).toEqual([ACTIVE, OTHER]);
|
||||
});
|
||||
|
||||
it("releases a hidden chat's timeline when its agent is archived", async () => {
|
||||
const host = openHost([ACTIVE, OTHER]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([OTHER]);
|
||||
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
|
||||
|
||||
host.directory.applyDelta({ kind: "remove", agentId: ACTIVE });
|
||||
|
||||
expect(timelineStatus(ACTIVE)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([OTHER]);
|
||||
});
|
||||
|
||||
it("releases an archived chat's timeline once its tab is no longer shown", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
|
||||
host.directory.archive(ACTIVE, "2026-09-11T00:00:00.000Z");
|
||||
expect(timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([]);
|
||||
|
||||
expect(timelineStatus(ACTIVE)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("releases every timeline of a workspace when the active list drops its agents", async () => {
|
||||
const host = openHost([ACTIVE, OTHER]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([OTHER]);
|
||||
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
|
||||
host.view([]);
|
||||
|
||||
host.directory.commitSnapshot([], []);
|
||||
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("releases hidden timelines of a removed workspace whose agent rows still look active", async () => {
|
||||
const host = openHost([ACTIVE, OTHER]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([OTHER]);
|
||||
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
|
||||
|
||||
host.workspaces.removeWorkspaceSnapshot(WORKSPACE);
|
||||
|
||||
expect(timelineStatus(OTHER)).toBe("synced");
|
||||
expect(residentAgentIds()).toEqual([OTHER]);
|
||||
host.view([]);
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("releases a History chat whose unarchived row belongs to an archived workspace", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.view([IN_ARCHIVED_WORKSPACE]);
|
||||
await expect.poll(() => timelineStatus(IN_ARCHIVED_WORKSPACE)).toBe("synced");
|
||||
|
||||
host.view([]);
|
||||
|
||||
expect(timelineStatus(IN_ARCHIVED_WORKSPACE)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps an archived chat open from History through active-list syncs and releases it on leave", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.view([ARCHIVED]);
|
||||
await expect.poll(() => timelineStatus(ARCHIVED)).toBe("synced");
|
||||
|
||||
host.directory.commitSnapshot([directoryEntry(ACTIVE)], []);
|
||||
host.directory.applyDelta({ kind: "remove", agentId: ARCHIVED });
|
||||
expect(timelineStatus(ARCHIVED)).toBe("synced");
|
||||
|
||||
host.view([]);
|
||||
expect(timelineStatus(ARCHIVED)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
|
||||
host.view([ARCHIVED]);
|
||||
await expect.poll(() => timelineStatus(ARCHIVED)).toBe("synced");
|
||||
expect(host.fetches).toEqual([ARCHIVED, ARCHIVED]);
|
||||
});
|
||||
|
||||
it("ignores a History read that answers after the archived chat was left", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.hold(ARCHIVED);
|
||||
host.view([ARCHIVED]);
|
||||
await expect.poll(() => host.fetches).toEqual([ARCHIVED]);
|
||||
|
||||
host.view([]);
|
||||
await host.deliverHeld(ARCHIVED);
|
||||
|
||||
expect(timelineStatus(ARCHIVED)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not paint a cached archived chat back after it was left", async () => {
|
||||
let finishRead!: () => void;
|
||||
const readStarted = new Promise<void>((resolve) => {
|
||||
finishRead = resolve;
|
||||
});
|
||||
let reading = false;
|
||||
const host = openHost([ACTIVE], {
|
||||
readTimeline: async (_serverId, agentId) => {
|
||||
reading = true;
|
||||
await readStarted;
|
||||
return { ...cachedTimeline(), agentId };
|
||||
},
|
||||
commitTimeline: () => undefined,
|
||||
});
|
||||
host.view([ARCHIVED]);
|
||||
await expect.poll(() => reading).toBe(true);
|
||||
|
||||
host.view([]);
|
||||
finishRead();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(timelineStatus(ARCHIVED)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -208,6 +208,7 @@ class TimelineWorld {
|
||||
},
|
||||
onCatchUpOwed: () => undefined,
|
||||
onCatchUpSettled: () => undefined,
|
||||
isArchived: () => false,
|
||||
prepare: async (agentId) => {
|
||||
this.cacheRequests.push(agentId);
|
||||
this.cacheRequestWaiters.shift()?.(agentId);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
useSessionStore,
|
||||
type AgentTimelineCursorState,
|
||||
type AgentTimelineState,
|
||||
type SessionState,
|
||||
} from "@/stores/session-store";
|
||||
import { useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
@@ -102,6 +103,8 @@ export interface TimelineReplica {
|
||||
timelineUpdated(agentId: string): void;
|
||||
catchUpOwed(agentId: string): void;
|
||||
catchUpSettled(agentId: string): void;
|
||||
/** Forgets a released chat's cached range, so showing it again reads the cache afresh. */
|
||||
release(agentId: string): void;
|
||||
}
|
||||
|
||||
class TimelineReplicaOwner implements TimelineReplica {
|
||||
@@ -187,6 +190,10 @@ class TimelineReplicaOwner implements TimelineReplica {
|
||||
if (this.preparations.has(agentId)) this.settledDuringPreparation.add(agentId);
|
||||
useSessionStore.getState().setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
|
||||
}
|
||||
|
||||
release(agentId: string): void {
|
||||
this.cachedRanges.delete(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
export function createTimelineReplica(input: {
|
||||
@@ -375,6 +382,11 @@ function buildCurrentTimelinePage(
|
||||
|
||||
export interface ViewedTimelineSyncPorts {
|
||||
prepare(agentId: string): Promise<void>;
|
||||
/**
|
||||
* Whether the agent left the active list: it, or its workspace, is archived. A hidden chat
|
||||
* of an archived agent leaves the opened chats, so showing it again reads it afresh.
|
||||
*/
|
||||
isArchived(agentId: string): boolean;
|
||||
replaceDemandedAgentIds(agentIds: string[]): void;
|
||||
/** Whether the daemon answers with each cursor's freshness in the subscribe response. */
|
||||
canCheckFreshness(): boolean;
|
||||
@@ -447,9 +459,17 @@ export interface ViewedTimelineSync extends ViewedTimelineUiBridge {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/** What the timeline owner needs from membership beyond the UI-facing surface. */
|
||||
export interface ViewedTimelineMembership extends ViewedTimelineSync {
|
||||
isVisible(agentId: string): boolean;
|
||||
/** Re-reads `isArchived` for the opened chats, after the active list changed. */
|
||||
archiveChanged(): void;
|
||||
}
|
||||
|
||||
export type ViewedTimelineOwnerPorts = Omit<
|
||||
ViewedTimelineSyncPorts,
|
||||
| "prepare"
|
||||
| "isArchived"
|
||||
| "replaceDemandedAgentIds"
|
||||
| "onCatchUpEnded"
|
||||
| "onCatchUpOwed"
|
||||
@@ -477,8 +497,14 @@ export function createViewedTimelineOwner(input: {
|
||||
ports: ViewedTimelineOwnerPorts;
|
||||
}): ViewedTimelineOwner {
|
||||
const forcedTailReplacements = new Set<string>();
|
||||
const isArchived = (agentId: string) =>
|
||||
isAgentArchived(useSessionStore.getState().sessions[input.serverId], agentId);
|
||||
// Active chats stay resident while hidden so switching back needs no fetch. An archived
|
||||
// chat is resident only while it is shown, as when it is open from History.
|
||||
const isResident = (agentId: string) => sync.isVisible(agentId) || !isArchived(agentId);
|
||||
const sync = createViewedTimelineSync({
|
||||
...input.ports,
|
||||
isArchived,
|
||||
fetchLatestTail: async (agentId) => {
|
||||
forcedTailReplacements.add(agentId);
|
||||
try {
|
||||
@@ -487,7 +513,11 @@ export function createViewedTimelineOwner(input: {
|
||||
forcedTailReplacements.delete(agentId);
|
||||
}
|
||||
},
|
||||
prepare: (agentId) => input.replica.prepare(agentId),
|
||||
prepare: async (agentId) => {
|
||||
await input.replica.prepare(agentId);
|
||||
// A cache read that lands after its archived chat was left paints a chat nobody shows.
|
||||
releaseHiddenArchivedTimelines();
|
||||
},
|
||||
readCursor: (agentId) => input.replica.readCursor(agentId) ?? input.ports.readCursor(agentId),
|
||||
replaceDemandedAgentIds: input.replaceDemandedAgentIds,
|
||||
applyCurrentTimeline: (agentId) => {
|
||||
@@ -514,9 +544,40 @@ export function createViewedTimelineOwner(input: {
|
||||
recoverTimelineGap: (agentId, cursor) => sync.recoverGap(agentId, cursor),
|
||||
onCommitted: (agentId) => input.replica.timelineUpdated(agentId),
|
||||
});
|
||||
const releaseHiddenArchivedTimelines = () => {
|
||||
const session = useSessionStore.getState().sessions[input.serverId];
|
||||
if (!session) return;
|
||||
for (const agentId of selectResidentTimelineAgentIds(session)) {
|
||||
if (isResident(agentId)) continue;
|
||||
streamQueue.flushAgent(agentId);
|
||||
input.replica.release(agentId);
|
||||
useSessionStore.getState().releaseAgentTimeline(input.serverId, agentId);
|
||||
}
|
||||
};
|
||||
// Archiving an agent or its workspace reaches this host as the agent leaving the active list.
|
||||
let observedSession = useSessionStore.getState().sessions[input.serverId];
|
||||
const stopObservingArchive = useSessionStore.subscribe((state) => {
|
||||
const session = state.sessions[input.serverId];
|
||||
const changed =
|
||||
session?.agents !== observedSession?.agents ||
|
||||
session?.agentDetails !== observedSession?.agentDetails ||
|
||||
session?.hasHydratedAgents !== observedSession?.hasHydratedAgents ||
|
||||
session?.workspaces !== observedSession?.workspaces ||
|
||||
session?.hasHydratedWorkspaces !== observedSession?.hasHydratedWorkspaces;
|
||||
observedSession = session;
|
||||
if (!changed) return;
|
||||
sync.archiveChanged();
|
||||
releaseHiddenArchivedTimelines();
|
||||
});
|
||||
return {
|
||||
...sync,
|
||||
replaceVisibleAgentIds(sourceId, agentIds) {
|
||||
sync.replaceVisibleAgentIds(sourceId, agentIds);
|
||||
releaseHiddenArchivedTimelines();
|
||||
},
|
||||
applyTimelineResponse(receivedPayload) {
|
||||
// A read that answers after its archived chat was released must not bring it back.
|
||||
if (!isResident(receivedPayload.agentId)) return;
|
||||
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
|
||||
const accepted = applyAuthoritativeTimelineResponse({
|
||||
serverId: input.serverId,
|
||||
@@ -528,6 +589,7 @@ export function createViewedTimelineOwner(input: {
|
||||
if (accepted) input.replica.timelineUpdated(payload.agentId);
|
||||
},
|
||||
applyStreamEvent(agentId, event) {
|
||||
if (!isResident(agentId)) return;
|
||||
streamQueue.enqueue(agentId, event);
|
||||
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
|
||||
if (turnLiveness.length === 0) return;
|
||||
@@ -539,12 +601,38 @@ export function createViewedTimelineOwner(input: {
|
||||
streamQueue.flushAgent(agentId);
|
||||
},
|
||||
dispose() {
|
||||
stopObservingArchive();
|
||||
streamQueue.dispose({ flush: true });
|
||||
sync.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An agent is archived once the hydrated active list lacks it, its row carries an archive
|
||||
* timestamp, or the hydrated workspace list lacks its workspace. Workspace archive can leave
|
||||
* an agent row without a timestamp. Until a list hydrates, it rules nothing out.
|
||||
*/
|
||||
function isAgentArchived(session: SessionState | undefined, agentId: string): boolean {
|
||||
if (!session?.hasHydratedAgents) return false;
|
||||
const agent = session.agents.get(agentId) ?? session.agentDetails.get(agentId);
|
||||
if (!agent || agent.archivedAt != null) return true;
|
||||
return (
|
||||
session.hasHydratedWorkspaces &&
|
||||
agent.workspaceId !== undefined &&
|
||||
!session.workspaces.has(agent.workspaceId)
|
||||
);
|
||||
}
|
||||
|
||||
function selectResidentTimelineAgentIds(session: SessionState): Set<string> {
|
||||
return new Set([
|
||||
...session.agentStreamTail.keys(),
|
||||
...session.agentStreamHead.keys(),
|
||||
...session.agentTimelineCursor.keys(),
|
||||
...session.agentAuthoritativeHistoryApplied.keys(),
|
||||
]);
|
||||
}
|
||||
|
||||
const MAX_HIDDEN_CATCH_UPS = 2;
|
||||
|
||||
type CatchUpStatus = "running" | "complete" | "error";
|
||||
@@ -608,7 +696,7 @@ function sameAgentIds(left: string[], right: string[]): boolean {
|
||||
return left.length === right.length && left.every((agentId, index) => agentId === right[index]);
|
||||
}
|
||||
|
||||
export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): ViewedTimelineSync {
|
||||
export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): ViewedTimelineMembership {
|
||||
const sources = new Map<string, string[]>();
|
||||
const catchUps = new Map<string, CatchUpState>();
|
||||
const catchUpGenerations = new Map<string, number>();
|
||||
@@ -788,10 +876,12 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
|
||||
const ensureCacheLoaded = (agentId: string): void => {
|
||||
if (loadedCache.has(agentId) || cacheLoads.has(agentId)) return;
|
||||
const load = ports
|
||||
const load: Promise<void> = ports
|
||||
.prepare(agentId)
|
||||
.catch((error) => ports.reportError(error))
|
||||
.finally(() => {
|
||||
// A released chat forgot this load; showing it again starts its own.
|
||||
if (cacheLoads.get(agentId) !== load) return;
|
||||
cacheLoads.delete(agentId);
|
||||
loadedCache.add(agentId);
|
||||
const pending = pendingCatchUps.get(agentId);
|
||||
@@ -1079,10 +1169,29 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
};
|
||||
|
||||
const publishVisibleMembership = () => {
|
||||
commitDesiredMembership(normalizeAgentIds([...openedAgentIds, ...visibleAgentIds()]));
|
||||
const visible = visibleAgentIds();
|
||||
const kept = openedAgentIds.filter(
|
||||
(agentId) => visible.includes(agentId) || !ports.isArchived(agentId),
|
||||
);
|
||||
if (kept.length !== openedAgentIds.length) {
|
||||
for (const agentId of openedAgentIds) {
|
||||
if (kept.includes(agentId)) continue;
|
||||
loadedCache.delete(agentId);
|
||||
cacheLoads.delete(agentId);
|
||||
}
|
||||
openedAgentIds = kept;
|
||||
}
|
||||
commitDesiredMembership(normalizeAgentIds([...openedAgentIds, ...visible]));
|
||||
};
|
||||
|
||||
return {
|
||||
isVisible(agentId) {
|
||||
for (const agentIds of sources.values()) if (agentIds.includes(agentId)) return true;
|
||||
return false;
|
||||
},
|
||||
archiveChanged() {
|
||||
publishVisibleMembership();
|
||||
},
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -58,6 +58,11 @@
|
||||
"types": "./dist/server/lifecycle.d.ts",
|
||||
"source": "./src/server/lifecycle.ts",
|
||||
"default": "./dist/server/lifecycle.js"
|
||||
},
|
||||
"./internal/windows-command": {
|
||||
"types": "./dist/server/process-internal/windows-command.d.ts",
|
||||
"source": "./src/server/process-internal/windows-command.ts",
|
||||
"default": "./dist/server/process-internal/windows-command.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
|
||||
@@ -14,6 +14,7 @@ const entries = {
|
||||
"./server/usage": "server",
|
||||
"./server/acp": "server",
|
||||
"./internal/lifecycle": "server",
|
||||
"./internal/windows-command": "server",
|
||||
"./client": "client",
|
||||
"./client/host": "client",
|
||||
"./client/ui": "client",
|
||||
@@ -392,7 +393,7 @@ describe("lifecycle hook SDK types", () => {
|
||||
it("infers payloads and replacement requests and requires async handlers and new names", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server";
|
||||
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult, PluginLaunchWrap } from "@getpaseo/plugin/server";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
server.addHook("worktree.create.before", async ({ request }) => {
|
||||
@@ -427,6 +428,38 @@ describe("lifecycle hook SDK types", () => {
|
||||
const { metadata, ...withoutMetadata } = request;
|
||||
return withoutMetadata;
|
||||
});
|
||||
server.addHook("agent.create.before", async ({ request }) => {
|
||||
const workspace: string | null = request.workspaceId;
|
||||
// @ts-expect-error The agent's workspace is read-only.
|
||||
request.workspaceId = "wks_other";
|
||||
});
|
||||
// Results built before workspaceId existed still typecheck; the daemon keeps the id.
|
||||
server.addHook("agent.create.before", async ({ request }) => ({ config: request.config, env: request.env }));
|
||||
server.before("agent.create", ({ request }) => ({ config: request.config, env: request.env }));
|
||||
server.addHook("terminal.create.before", async ({ request }) => {
|
||||
const source: "client" | "agent" | "script" | "worktree" = request.source;
|
||||
const input: string | null = request.input;
|
||||
const program: string | null = request.command;
|
||||
// @ts-expect-error The terminal's workspace is read-only.
|
||||
request.workspaceId = "wks_other";
|
||||
// @ts-expect-error The terminal's program is read-only; return a wrap instead.
|
||||
request.command = "/usr/bin/other";
|
||||
const wrap: PluginLaunchWrap = ["/usr/bin/sandbox", "--workspace", request.workspaceId];
|
||||
return { ...request, env: { A: "1" }, wrap };
|
||||
});
|
||||
server.addHook("command.run.before", async ({ request }) => {
|
||||
const workspace: string | null = request.workspaceId;
|
||||
const purpose: "setup" | "teardown" = request.purpose;
|
||||
// @ts-expect-error A command's purpose is read-only.
|
||||
request.purpose = "setup";
|
||||
// @ts-expect-error The configured command is read-only; return a wrap instead.
|
||||
request.command = "wrapper " + request.command;
|
||||
return { ...request, wrap: ["/usr/bin/sandbox"] };
|
||||
});
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
wrap: ["/usr/bin/sandbox", "--workspace", request.workspaceId ?? "none"],
|
||||
}));
|
||||
server.addHook("agent.turn.after", async (event, { paseo, signal }) => {
|
||||
const { agent, outcome } = event;
|
||||
const kind: "completed" | "failed" | "canceled" = outcome.kind;
|
||||
|
||||
@@ -86,6 +86,8 @@ export async function createAcpProviderConnection(
|
||||
emit: () => undefined,
|
||||
});
|
||||
const supportedCapabilities: ProviderCapability[] = [...ADAPTER_CAPABILITIES];
|
||||
// A connector stream has no process of its own to wrap.
|
||||
if (options.command) supportedCapabilities.push("session.launch_wrap");
|
||||
if (probe.agentCapabilities.promptCapabilities?.image) {
|
||||
supportedCapabilities.push("prompt.image");
|
||||
}
|
||||
@@ -333,6 +335,7 @@ async function openSession(
|
||||
boundarySessionId: input.sessionId,
|
||||
cwd: input.config.cwd,
|
||||
env: input.config.env,
|
||||
wrap: input.config.wrap,
|
||||
emit: state.emit,
|
||||
onRetired: () => retireSession(state, input.sessionId),
|
||||
});
|
||||
@@ -375,6 +378,7 @@ interface StartRuntimeOptions {
|
||||
boundarySessionId: string;
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
wrap?: readonly [string, ...string[]];
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
@@ -498,6 +502,7 @@ class AcpRuntime {
|
||||
env: process.env,
|
||||
};
|
||||
child = spawnProcess(launch.command, launch.args, {
|
||||
wrap: options.wrap,
|
||||
cwd: options.cwd,
|
||||
env: { ...launch.env, ...options.env },
|
||||
stdio: "pipe",
|
||||
@@ -511,6 +516,7 @@ class AcpRuntime {
|
||||
>[1];
|
||||
stream = ndJsonStream(output, input);
|
||||
} else {
|
||||
if (options.wrap) throw new Error("An ACP connector cannot run behind a launch wrap");
|
||||
const owned = ownConnectorStream(await options.options.connector());
|
||||
stream = owned.stream;
|
||||
closeConnector = owned.close;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import diagnosticsChannel from "node:diagnostics_channel";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -6166,7 +6168,6 @@ describe("deferTurnOnRunningTools", () => {
|
||||
);
|
||||
|
||||
const childPid = Number((await readFile(pidFile, "utf8")).trim());
|
||||
const startedAt = Date.now();
|
||||
await Promise.all([
|
||||
connection.send({
|
||||
type: "session.interrupt",
|
||||
@@ -6188,8 +6189,8 @@ describe("deferTurnOnRunningTools", () => {
|
||||
(event) => event.type === "request.completed" && event.requestId === "int-2",
|
||||
);
|
||||
|
||||
// Both interrupts waited for the 250ms SIGTERM exit, and process is now dead.
|
||||
expect(Date.now() - startedAt).toBeGreaterThanOrEqual(200);
|
||||
// Both interrupts waited for the process to exit. On POSIX it lives 250ms past SIGTERM, so an
|
||||
// interrupt that returned early would find it alive; Windows ends it at once.
|
||||
expect(() => process.kill(childPid, 0)).toThrow();
|
||||
|
||||
// Canceled turn and session.closed were each emitted exactly once.
|
||||
@@ -7125,3 +7126,187 @@ describe("ACP tool call rows", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("runAcpProvider launch wrap", () => {
|
||||
async function wrapFixture(): Promise<{
|
||||
agent: string;
|
||||
launchLog: string;
|
||||
/** The wrap that runs the recording launcher as Node, tagged so the agent can tell. */
|
||||
wrap: (tag: string) => [string, ...string[]];
|
||||
launches: () => Promise<Array<{ argv: string[]; token: string | null }>>;
|
||||
agentStarts: () => Promise<string[]>;
|
||||
}> {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-acp-wrap-"));
|
||||
temporaryDirectories.push(directory);
|
||||
const launchLog = path.join(directory, "launches.jsonl");
|
||||
const agentLog = path.join(directory, "agent.log");
|
||||
const launcher = path.join(directory, "launcher.cjs");
|
||||
// Consumes two arguments of its own (log path, tag), records what it saw, then runs the rest.
|
||||
await writeFile(
|
||||
launcher,
|
||||
`const { appendFileSync } = require("node:fs");
|
||||
const { spawn } = require("node:child_process");
|
||||
const [log, tag, command, ...args] = process.argv.slice(2);
|
||||
appendFileSync(log, JSON.stringify({ argv: process.argv.slice(2), token: process.env.SESSION_TOKEN ?? null }) + "\\n");
|
||||
const child = spawn(command, args, { stdio: "inherit", env: { ...process.env, WRAPPED_BY: tag } });
|
||||
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
||||
child.on("exit", (code) => process.exit(code ?? 1));
|
||||
`,
|
||||
"utf8",
|
||||
);
|
||||
const agent = path.join(directory, "agent.cjs");
|
||||
await writeFile(
|
||||
agent,
|
||||
`const { appendFileSync } = require("node:fs");
|
||||
const record = (event) => appendFileSync(${JSON.stringify(agentLog)}, event + ":" + (process.env.WRAPPED_BY ?? "bare") + "\\n");
|
||||
const readline = require("node:readline");
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
lines.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") { record("init"); send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } }); }
|
||||
else if (message.method === "session/new") { record("new"); send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-" + Math.random(), modes: null, configOptions: [] } }); }
|
||||
});`,
|
||||
"utf8",
|
||||
);
|
||||
const readLines = async (file: string) =>
|
||||
(await readFile(file, "utf8").catch(() => "")).split("\n").filter(Boolean);
|
||||
return {
|
||||
agent,
|
||||
launchLog,
|
||||
wrap: (tag) => [process.execPath, launcher, launchLog, tag],
|
||||
launches: async () => (await readLines(launchLog)).map((line) => JSON.parse(line)),
|
||||
agentStarts: async () => await readLines(agentLog),
|
||||
};
|
||||
}
|
||||
|
||||
function wrappedOpen(
|
||||
sessionId: string,
|
||||
wrap: readonly [string, ...string[]] | undefined,
|
||||
): Extract<ProviderInput, { type: "session.open" }> {
|
||||
const input = openInput();
|
||||
return {
|
||||
...input,
|
||||
requestId: `open-${sessionId}`,
|
||||
sessionId,
|
||||
config: { ...input.config, env: { SESSION_TOKEN: sessionId }, ...(wrap ? { wrap } : {}) },
|
||||
};
|
||||
}
|
||||
|
||||
async function connectWrapped(command: readonly [string, ...string[]]) {
|
||||
const registration = runAcpProvider({ id: "wrap-acp", label: "Wrap ACP", command });
|
||||
expect(registration.launchWrap).toBe(true);
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.launch_wrap"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
return { connection, events };
|
||||
}
|
||||
|
||||
it("spawns the session as [...wrap, command, ...args] with the session env", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
expect(connection.capabilities).toContain("session.launch_wrap");
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", fixture.wrap("sandbox")));
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
expect(await fixture.launches()).toEqual([
|
||||
{ argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "one" },
|
||||
]);
|
||||
expect(await fixture.agentStarts()).toEqual(["init:bare", "init:sandbox", "new:sandbox"]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes wrap and command arguments that contain spaces as single argv elements", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([
|
||||
process.execPath,
|
||||
fixture.agent,
|
||||
"--profile name with spaces",
|
||||
]);
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", fixture.wrap("tag with spaces")));
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
expect((await fixture.launches())[0]?.argv).toEqual([
|
||||
launchLog,
|
||||
"tag with spaces",
|
||||
process.execPath,
|
||||
fixture.agent,
|
||||
"--profile name with spaces",
|
||||
]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("wraps only the session that selected a wrap on a shared connection", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
try {
|
||||
await connection.send(wrappedOpen("wrapped", fixture.wrap("sandbox")));
|
||||
await connection.send(wrappedOpen("bare", undefined));
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.ready" && event.sessionId === "wrapped",
|
||||
);
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.ready" && event.sessionId === "bare",
|
||||
);
|
||||
expect(await fixture.launches()).toEqual([
|
||||
{ argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "wrapped" },
|
||||
]);
|
||||
expect(
|
||||
(await fixture.agentStarts()).filter((line) => line.startsWith("new:")).sort(),
|
||||
).toEqual(["new:bare", "new:sandbox"]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails the open when the launcher is missing and never starts the bare command", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const missing = path.join(path.dirname(fixture.agent), "missing-launcher");
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
// Node publishes every spawn attempt, a failed one included, before it fills in the fields.
|
||||
const spawned: ChildProcess[] = [];
|
||||
const onSpawn = (message: unknown) =>
|
||||
spawned.push((message as { process: ChildProcess }).process);
|
||||
diagnosticsChannel.subscribe("child_process", onSpawn);
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", [missing, "--profile", "a b"]));
|
||||
expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({
|
||||
requestId: "open-one",
|
||||
error: { message: expect.stringMatching(/ENOENT/u) },
|
||||
});
|
||||
expect(spawned.map((child) => child.spawnargs)).toEqual([
|
||||
[missing, "--profile", "a b", process.execPath, fixture.agent],
|
||||
]);
|
||||
// The only start of the agent is the connection's capability probe, before the open.
|
||||
expect(await fixture.agentStarts()).toEqual(["init:bare"]);
|
||||
expect(events.some((event) => event.type === "session.opened")).toBe(false);
|
||||
} finally {
|
||||
diagnosticsChannel.unsubscribe("child_process", onSpawn);
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not offer launch wrap through a connector", async () => {
|
||||
const { connector } = connectorHarness();
|
||||
const registration = runAcpProvider({ id: "connector-acp", label: "Connector", connector });
|
||||
expect(registration).not.toHaveProperty("launchWrap");
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.launch_wrap"],
|
||||
});
|
||||
expect(connection.capabilities).not.toContain("session.launch_wrap");
|
||||
await connection.close();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -181,6 +181,8 @@ export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistra
|
||||
description: options.description,
|
||||
icon: options.icon,
|
||||
command: options.command,
|
||||
// Each command-based session spawns its own process, so it can run behind that session's wrap.
|
||||
...(hasCommand ? { launchWrap: true } : {}),
|
||||
connect(request) {
|
||||
return createAcpProviderConnection(options, request);
|
||||
},
|
||||
|
||||
@@ -23,6 +23,9 @@ export type {
|
||||
PluginHookWorkspace,
|
||||
PluginHookWorktree,
|
||||
PluginWorktreeCreateRequest,
|
||||
PluginLaunchWrap,
|
||||
PluginTerminalCreateRequest,
|
||||
PluginCommandRunRequest,
|
||||
PluginHookAgent,
|
||||
PluginSessionOpenRequest,
|
||||
PluginTurnOutcome,
|
||||
@@ -32,6 +35,7 @@ export type {
|
||||
} from "./lifecycle.js";
|
||||
|
||||
export { spawnProcess, execCommand, terminateProcess } from "./process.js";
|
||||
export type { SpawnProcessOptions } from "./process.js";
|
||||
|
||||
export { defineAgentTool } from "./agent-tools.js";
|
||||
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
|
||||
|
||||
@@ -68,6 +68,49 @@ export type PluginWorktreeCreateRequest = {
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* A launcher Paseo starts a process behind: the process runs as `[...wrap, command, ...args]`.
|
||||
* The executable is an absolute path on the daemon host. Each element is one argument; no shell
|
||||
* parses them, except that Windows runs a `.cmd` or `.bat` executable through cmd.exe. A later
|
||||
* hook may omit the wrap or return the same one; a different wrap fails the operation.
|
||||
*/
|
||||
export type PluginLaunchWrap = readonly [executable: string, ...args: string[]];
|
||||
|
||||
/** A terminal Paseo is about to create in a workspace. */
|
||||
export interface PluginTerminalCreateRequest {
|
||||
readonly workspaceId: string;
|
||||
readonly cwd: string;
|
||||
/**
|
||||
* `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a
|
||||
* `paseo.json` worktree terminal. `client`: everything else (the app, CLI, SDK, plugins).
|
||||
*/
|
||||
readonly source: "client" | "agent" | "script" | "worktree";
|
||||
readonly name: string | null;
|
||||
/** The program the terminal starts, or `null` for the user's default shell. */
|
||||
readonly command: string | null;
|
||||
readonly args: readonly string[];
|
||||
/** What Paseo types into the shell once it starts: the command of a script or worktree terminal. */
|
||||
readonly input: string | null;
|
||||
/** Environment overrides for the terminal; excludes the daemon's inherited environment. */
|
||||
env: Record<string, string>;
|
||||
/** Start the terminal as `[...wrap, command, ...args]`; with no `command`, the default shell. */
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
/** A `paseo.json` worktree setup or teardown command Paseo is about to run. */
|
||||
export interface PluginCommandRunRequest {
|
||||
/** Null when a worktree is archived by path and no workspace record remains. */
|
||||
readonly workspaceId: string | null;
|
||||
readonly cwd: string;
|
||||
readonly purpose: "setup" | "teardown";
|
||||
/** The command as written in `paseo.json`. Paseo runs it through a shell. */
|
||||
readonly command: string;
|
||||
/** Environment overrides for the command; excludes the daemon's inherited environment. */
|
||||
env: Record<string, string>;
|
||||
/** Start the command's shell as `[...wrap, shell, ...shellArgs]`. */
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
export interface PluginHookAgent {
|
||||
id: string;
|
||||
workspaceId: string | null;
|
||||
@@ -98,6 +141,12 @@ export interface PluginSessionOpenRequest {
|
||||
tools: AgentToolDefinition[];
|
||||
env: Record<string, string>;
|
||||
mcpServers: NonNullable<AgentSessionConfig["mcpServers"]>;
|
||||
/**
|
||||
* Start the provider's harness as `[...wrap, command, ...args]`. Only a provider whose snapshot
|
||||
* entry has `launchWrap: true` applies it; any other provider fails the open. Not saved on the
|
||||
* agent.
|
||||
*/
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
export type PluginTurnOutcome =
|
||||
@@ -138,18 +187,28 @@ export interface PluginHookRequests {
|
||||
env?: Record<string, string>;
|
||||
/** Stored on the new agent. Always present in the payload; return it changed to change it. */
|
||||
metadata?: Record<string, JsonValue>;
|
||||
/** The workspace the agent is created in, which `config.cwd` alone does not identify. */
|
||||
readonly workspaceId: string | null;
|
||||
};
|
||||
"agent.open.before": PluginSessionOpenRequest;
|
||||
"workspace.create.before": Omit<WorkspaceCreateRequest, "type" | "requestId">;
|
||||
"terminal.create.before": PluginTerminalCreateRequest;
|
||||
"command.run.before": PluginCommandRunRequest;
|
||||
}
|
||||
|
||||
/** What a hook may return. An omitted `metadata` stays as it was. */
|
||||
type PluginHookRequestResults = Omit<PluginHookRequests, "agent.open.before"> & {
|
||||
/** What a hook may return. An omitted `metadata` or `workspaceId` stays as it was. */
|
||||
type PluginHookRequestResults = Omit<
|
||||
PluginHookRequests,
|
||||
"agent.open.before" | "agent.create.before"
|
||||
> & {
|
||||
// Read-only fields added after the first SDK stay optional in a result; omitted means unchanged.
|
||||
"agent.open.before": Omit<PluginSessionOpenRequest, "metadata" | "background"> & {
|
||||
readonly background?: boolean;
|
||||
metadata?: Readonly<Record<string, JsonValue>>;
|
||||
};
|
||||
"agent.create.before": Omit<PluginHookRequests["agent.create.before"], "workspaceId"> & {
|
||||
readonly workspaceId?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type PluginHooks = {
|
||||
@@ -217,6 +276,8 @@ export const pluginHookRegistry = {
|
||||
"agent.turn.after": { waits: false },
|
||||
"agent.permission.before": { waits: false },
|
||||
"agent.permission.after": { waits: false },
|
||||
"terminal.create.before": { waits: true },
|
||||
"command.run.before": { waits: true },
|
||||
} as const satisfies Record<keyof PluginHooks, { waits: boolean }>;
|
||||
|
||||
// COMPAT(pluginHookNames): added in v0.14, remove after 2027-04-30
|
||||
|
||||
@@ -1,117 +1,92 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { quoteWindowsArgument, quoteWindowsCommand } from "./windows-command.js";
|
||||
import { findWindowsCommand, quoteWindowsCommand, windowsCommandLine } from "./windows-command.js";
|
||||
|
||||
const program = { commandScript: false } as const;
|
||||
const script = { commandScript: true } as const;
|
||||
|
||||
describe("quoteWindowsCommand", () => {
|
||||
const originalPlatform = process.platform;
|
||||
|
||||
function setPlatform(value: string) {
|
||||
Object.defineProperty(process, "platform", { value, writable: true });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setPlatform(originalPlatform);
|
||||
});
|
||||
|
||||
test("quotes a Windows path with spaces", () => {
|
||||
setPlatform("win32");
|
||||
test("quotes a path with spaces and keeps cmd.exe syntax in it as text", () => {
|
||||
expect(quoteWindowsCommand("C:\\Program Files\\Anthropic\\claude.exe")).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\claude.exe"',
|
||||
);
|
||||
});
|
||||
|
||||
test("does not double-quote an already-quoted path", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand('"C:\\Program Files\\Anthropic\\claude.exe"')).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\claude.exe"',
|
||||
expect(quoteWindowsCommand("C:\\Program Files (x86)\\Tool & Co\\run.cmd")).toBe(
|
||||
'"C:\\Program Files (x86)\\Tool & Co\\run.cmd"',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the command unchanged when there are no spaces", () => {
|
||||
setPlatform("win32");
|
||||
test("leaves a plain or already quoted path as given", () => {
|
||||
expect(quoteWindowsCommand("C:\\nvm4w\\nodejs\\codex")).toBe("C:\\nvm4w\\nodejs\\codex");
|
||||
});
|
||||
|
||||
test("escapes ampersands", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature&bugfix")).toBe("feature^&bugfix");
|
||||
});
|
||||
|
||||
test("escapes pipes", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature|bugfix")).toBe("feature^|bugfix");
|
||||
});
|
||||
|
||||
test("does not double percent signs", () => {
|
||||
setPlatform("win32");
|
||||
// cmd.exe only collapses %% → % inside batch files; on the command line
|
||||
// it stays literal, which corrupts git --format atoms etc.
|
||||
expect(quoteWindowsCommand("100%")).toBe("100%");
|
||||
});
|
||||
|
||||
test("preserves git --format atoms verbatim", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("--format=%(refname)%09%(committerdate:unix)")).toBe(
|
||||
"--format=%^(refname^)%09%^(committerdate:unix^)",
|
||||
);
|
||||
});
|
||||
|
||||
test("escapes carets", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature^bugfix")).toBe("feature^^bugfix");
|
||||
});
|
||||
|
||||
test("escapes multiple metacharacters", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("build&(test|deploy)!<output>")).toBe(
|
||||
"build^&^(test^|deploy^)^!^<output^>",
|
||||
);
|
||||
});
|
||||
|
||||
test("quotes commands with spaces after escaping metacharacters", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("C:\\Program Files\\My Tool&Stuff\\run 100%.cmd")).toBe(
|
||||
'"C:\\Program Files\\My Tool^&Stuff\\run 100%.cmd"',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the command unchanged on non-Windows platforms", () => {
|
||||
setPlatform("darwin");
|
||||
expect(quoteWindowsCommand("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
|
||||
expect(quoteWindowsCommand('"C:\\Program Files\\x.exe"')).toBe('"C:\\Program Files\\x.exe"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("quoteWindowsArgument", () => {
|
||||
const originalPlatform = process.platform;
|
||||
|
||||
function setPlatform(value: string) {
|
||||
Object.defineProperty(process, "platform", { value, writable: true });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setPlatform(originalPlatform);
|
||||
});
|
||||
|
||||
test("quotes a Windows argument with spaces", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument("C:\\Program Files\\Anthropic\\cli.js")).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\cli.js"',
|
||||
describe("windowsCommandLine", () => {
|
||||
test("passes an argument without a cmd.exe metacharacter as given", () => {
|
||||
expect(windowsCommandLine("echo", ["hello", "--flag", "feature/x", "C:\\dir"], program)).toBe(
|
||||
'"echo hello --flag feature/x C:\\dir"',
|
||||
);
|
||||
});
|
||||
|
||||
test("does not double-quote an already-quoted argument", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument('"C:\\Program Files\\Anthropic\\cli.js"')).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\cli.js"',
|
||||
test("quotes and caret-escapes every other argument once, the qntm way", () => {
|
||||
expect(windowsCommandLine("node", ["feature&bugfix", "work profile", ""], program)).toBe(
|
||||
'"node ^"feature^&bugfix^" ^"work^ profile^" ^"^""',
|
||||
);
|
||||
// A caret before each `%` keeps cmd.exe from reading a variable name, inside the quotes too.
|
||||
expect(windowsCommandLine("node", ["%PATH%", "100% of %PATH%"], program)).toBe(
|
||||
'"node ^"^%PATH^%^" ^"100^%^ of^ ^%PATH^%^""',
|
||||
);
|
||||
// Backslashes before the closing quote double, as the program's argv parser expects.
|
||||
expect(windowsCommandLine("node", ["C:\\path with space\\"], program)).toBe(
|
||||
'"node ^"C:\\path^ with^ space\\\\^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the argument unchanged when there are no spaces", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument("--version")).toBe("--version");
|
||||
test("quotes =, comma and semicolon, where a batch script splits its arguments", () => {
|
||||
expect(windowsCommandLine("run.cmd", ["--profile=restricted", "a,b;c"], script)).toBe(
|
||||
'"run.cmd ^"--profile=restricted^" ^"a^,b^;c^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the argument unchanged on non-Windows platforms", () => {
|
||||
setPlatform("darwin");
|
||||
expect(quoteWindowsArgument("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
|
||||
test("escapes an argument with a quote twice for a batch script, which reads it again", () => {
|
||||
expect(windowsCommandLine("node", ['say "hi"'], program)).toBe('"node ^"say^ \\^"hi\\^"^""');
|
||||
expect(windowsCommandLine("run.cmd", ['say "hi"', "a & b"], script)).toBe(
|
||||
'"run.cmd ^^^"say^^^ \\^^^"hi\\^^^"^^^" ^"a^ ^&^ b^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("quotes the command path at the start of the line", () => {
|
||||
expect(windowsCommandLine("C:\\Program Files (x86)\\run.cmd", ["acp"], script)).toBe(
|
||||
'""C:\\Program Files (x86)\\run.cmd" acp"',
|
||||
);
|
||||
});
|
||||
|
||||
test("refuses a line break, which ends a cmd.exe command whatever the quoting", () => {
|
||||
for (const argument of ["line one\nline two", "line one\r\n& calc"]) {
|
||||
expect(() => windowsCommandLine("run.cmd", ["--", argument], script)).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to run.cmd",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("findWindowsCommand", () => {
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
test("finds a bare name on PATH with each PATHEXT extension, whatever the env key case", async () => {
|
||||
const empty = await mkdtemp(path.join(os.tmpdir(), "windows-command-empty-"));
|
||||
const tools = await mkdtemp(path.join(os.tmpdir(), "windows-command-tools-"));
|
||||
roots.push(empty, tools);
|
||||
await writeFile(path.join(tools, "agent.CMD"), "");
|
||||
const env = { Path: `${empty};${tools}`, PathExt: ".EXE;.CMD" };
|
||||
expect(findWindowsCommand("agent", env)).toBe(path.join(tools, "agent.CMD"));
|
||||
expect(findWindowsCommand("echo", env)).toBeUndefined();
|
||||
expect(findWindowsCommand("agent.cmd", env)).toBeUndefined();
|
||||
expect(findWindowsCommand(path.join(tools, "agent"), env)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,46 +1,100 @@
|
||||
import { extname } from "node:path";
|
||||
import { statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
export function isWindowsCommandScript(executablePath: string): boolean {
|
||||
/**
|
||||
* How Paseo starts a program through cmd.exe on Windows: `cmd.exe /d /s /c "<line>"`, with the line
|
||||
* passed verbatim. The SDK process functions and the daemon's terminals share this one dialect.
|
||||
*/
|
||||
|
||||
export function isWindowsCommandScript(
|
||||
executablePath: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): boolean {
|
||||
const extension = extname(executablePath).toLowerCase();
|
||||
return process.platform === "win32" && (extension === ".cmd" || extension === ".bat");
|
||||
}
|
||||
|
||||
function escapeWindowsCmdValue(value: string): string {
|
||||
if (process.platform !== "win32") return value;
|
||||
|
||||
const isQuoted = value.startsWith('"') && value.endsWith('"');
|
||||
const unquoted = isQuoted ? value.slice(1, -1) : value;
|
||||
// Do NOT double `%` here. cmd.exe only collapses `%%` → `%` inside batch
|
||||
// files; on the command line / `cmd /c "..."` `%%` stays literal, which
|
||||
// breaks args like git's `--format=%(refname)` (git treats `%%` as the
|
||||
// escape for a literal `%`, so the format atoms become literals).
|
||||
const escaped = unquoted.replace(/([&|^<>()!])/g, "^$1");
|
||||
|
||||
if (isQuoted || /[\s"]/u.test(unquoted)) {
|
||||
const quoted = escaped
|
||||
.replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`)
|
||||
.replace(/\\+$/u, (slashes) => `${slashes}${slashes}`);
|
||||
return `"${quoted}"`;
|
||||
}
|
||||
|
||||
return escaped;
|
||||
return platform === "win32" && (extension === ".cmd" || extension === ".bat");
|
||||
}
|
||||
|
||||
/**
|
||||
* When spawning with `shell: true` on Windows, the command is passed to
|
||||
* `cmd.exe /d /s /c "command args"`. The `/s` strips outer quotes, so a
|
||||
* command path with spaces (e.g. `C:\Program Files\...`) is split at the
|
||||
* space. Wrapping it in quotes produces the correct `"C:\Program Files\..." args`.
|
||||
* Find a bare command name the way cmd.exe would on `PATH`, trying each `PATHEXT` extension. The
|
||||
* current directory is not searched. Returns undefined for a name with a path or an extension, and
|
||||
* for a name that is not on `PATH`, such as a cmd.exe builtin.
|
||||
*/
|
||||
export function findWindowsCommand(name: string, env: NodeJS.ProcessEnv): string | undefined {
|
||||
if (name.includes("/") || name.includes("\\") || extname(name)) return undefined;
|
||||
const extensions = (readEnv(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
||||
for (const directory of (readEnv(env, "PATH") ?? "").split(";").filter(Boolean)) {
|
||||
for (const extension of extensions) {
|
||||
const candidate = join(directory, name + extension);
|
||||
if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The cmd.exe that runs a command line: the child's `ComSpec`, else the daemon's. */
|
||||
export function windowsCommandShell(env: NodeJS.ProcessEnv): string {
|
||||
return readEnv(env, "ComSpec") ?? readEnv(process.env, "ComSpec") ?? "cmd.exe";
|
||||
}
|
||||
|
||||
// Windows environment names ignore case, and a copied env object keeps whatever case it had.
|
||||
function readEnv(env: NodeJS.ProcessEnv, name: string): string | undefined {
|
||||
const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
|
||||
return key === undefined ? undefined : env[key] || undefined;
|
||||
}
|
||||
|
||||
// The cmd.exe metacharacters, as cross-spawn's `lib/util/escape.js` lists them.
|
||||
const CMD_METACHARACTERS = /([()\][%!^"`<>&|;, *?])/g;
|
||||
// A batch script also splits its arguments at `=` and tab.
|
||||
const NEEDS_ESCAPE = /[()\][%!^"`<>&|;, *?=\t]/u;
|
||||
|
||||
/**
|
||||
* Escape one argument for a `cmd.exe /c` line by the qntm algorithm (https://qntm.org/cmd), the
|
||||
* one cross-spawn's `lib/util/escape.js` implements: quote it for the program's own argv parser,
|
||||
* then put a `^` before every cmd.exe metacharacter, the added quotes included. cmd.exe then sees
|
||||
* no quoted region, so a `%NAME%` never expands, and the program gets the argument unchanged.
|
||||
* `twice` escapes again for a batch script that reads the argument a second time.
|
||||
*/
|
||||
function escapeCmdArgument(argument: string, twice: boolean): string {
|
||||
const quoted = `"${argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`;
|
||||
const escaped = quoted.replace(CMD_METACHARACTERS, "^$1");
|
||||
return twice ? escaped.replace(CMD_METACHARACTERS, "^$1") : escaped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote the program path for the start of a cmd.exe line. Inside the quotes cmd.exe reads `&`, `(`
|
||||
* and `)` as text, so a path such as `C:\Program Files (x86)\...` starts.
|
||||
*/
|
||||
export function quoteWindowsCommand(command: string): string {
|
||||
return escapeWindowsCmdValue(command);
|
||||
if (command.startsWith('"') && command.endsWith('"')) return command;
|
||||
if (command === "" || /[\s()!^"<>&|%;,=]/u.test(command)) return `"${command}"`;
|
||||
return command;
|
||||
}
|
||||
|
||||
/**
|
||||
* `spawn(..., { shell: true })` on Windows also passes argv through `cmd.exe`.
|
||||
* Any argument containing spaces must be quoted or it will be split before the
|
||||
* child process sees it.
|
||||
* The quoted line for `cmd.exe /d /s /c <line>` that starts `command` with `args`.
|
||||
*
|
||||
* - An argument without a metacharacter needs no escape and stays as given, so cmd.exe builtins
|
||||
* and batch scripts that read `%1` get it unchanged.
|
||||
* - Any other argument is escaped once. A batch script that reads it as `%~1` gets it without the
|
||||
* quotes, and one that forwards it with `%*` hands the program the quoted argument, where cmd.exe
|
||||
* reads every metacharacter as text.
|
||||
* - For a batch script (`commandScript`), an argument with a `"` is escaped twice. Its quotes
|
||||
* would otherwise open and close regions when the script reads it again, and leave the
|
||||
* arguments after it outside the quotes.
|
||||
*
|
||||
* cmd.exe ends a command at a line break whatever the quoting, so an argument with one throws.
|
||||
*/
|
||||
export function quoteWindowsArgument(argument: string): string {
|
||||
return escapeWindowsCmdValue(argument);
|
||||
export function windowsCommandLine(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
{ commandScript }: { commandScript: boolean },
|
||||
): string {
|
||||
const escaped = args.map((argument) => {
|
||||
if (/[\r\n]/u.test(argument)) {
|
||||
throw new Error(`cmd.exe cannot pass an argument with a line break to ${command}`);
|
||||
}
|
||||
if (argument !== "" && !NEEDS_ESCAPE.test(argument)) return argument;
|
||||
return escapeCmdArgument(argument, commandScript && argument.includes('"'));
|
||||
});
|
||||
return `"${[quoteWindowsCommand(command), ...escaped].join(" ")}"`;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { execCommand, spawnProcess } from "./index.js";
|
||||
import { resolveSpawnInvocation } from "./process.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
@@ -26,8 +27,8 @@ const argumentsToPreserve = [
|
||||
"feature^bugfix",
|
||||
];
|
||||
|
||||
// A bare extensionless command selects the Windows shell; an absolute node.exe path would
|
||||
// skip that path. The real child checks quoting through the public process capabilities.
|
||||
// A real child checks quoting through the public process capabilities. On Windows the bare name
|
||||
// resolves on PATH to node.exe, which starts directly.
|
||||
test("execCommand delivers shell arguments to the real child unchanged", async () => {
|
||||
const script = await writeArgumentReader();
|
||||
const { stdout } = await execCommand("node", [script, ...argumentsToPreserve]);
|
||||
@@ -51,3 +52,299 @@ test("spawnProcess delivers shell arguments to the real child unchanged", async
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual(argumentsToPreserve);
|
||||
});
|
||||
|
||||
// A Windows environment with an empty PATH, so a bare name is never found on the test host.
|
||||
const windowsEnv = { ComSpec: "C:\\Windows\\System32\\cmd.exe", PATH: "" };
|
||||
|
||||
function onWindows(command: string, args: string[], shell?: boolean | string) {
|
||||
return resolveSpawnInvocation(command, args, shell, "win32", windowsEnv);
|
||||
}
|
||||
|
||||
// A launch wrap prepends a Windows script wrapper to the provider launch; spawnProcess starts it as
|
||||
// one verbatim cmd.exe line.
|
||||
test("a Windows script launch wrap starts as one verbatim cmd.exe line", () => {
|
||||
const wrapped = [
|
||||
"C:\\Program Files\\Sandbox\\run.cmd",
|
||||
"--profile",
|
||||
"work profile",
|
||||
"",
|
||||
"C:\\tools\\agy.cmd",
|
||||
"acp",
|
||||
];
|
||||
expect(onWindows(wrapped[0]!, wrapped.slice(1))).toEqual({
|
||||
command: "C:\\Windows\\System32\\cmd.exe",
|
||||
args: [
|
||||
"/d",
|
||||
"/s",
|
||||
"/c",
|
||||
'""C:\\Program Files\\Sandbox\\run.cmd" --profile ^"work^ profile^" ^"^" C:\\tools\\agy.cmd acp"',
|
||||
],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "linux")).toEqual({
|
||||
command: wrapped[0],
|
||||
args: wrapped.slice(1),
|
||||
shell: false,
|
||||
});
|
||||
});
|
||||
|
||||
// cmd.exe ends a command at a line break, and the text after it would run as a second command.
|
||||
test("a Windows cmd.exe launch refuses an argument with a line break before it starts", () => {
|
||||
for (const argument of ["line one\nline two", "line one\r\n& calc"]) {
|
||||
expect(() => onWindows("C:\\Sandbox\\run.cmd", ["--", argument])).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to C:\\Sandbox\\run.cmd",
|
||||
);
|
||||
expect(() => onWindows("codex", [argument])).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to codex",
|
||||
);
|
||||
}
|
||||
expect(onWindows("C:\\tools\\node.exe", ["a\nb"]).args).toEqual(["a\nb"]);
|
||||
expect(resolveSpawnInvocation("/usr/bin/sandbox", ["a\nb"], undefined, "linux").args).toEqual([
|
||||
"a\nb",
|
||||
]);
|
||||
});
|
||||
|
||||
// Only cmd.exe reads cmd.exe quoting. A shell the caller names parses the line by its own rules.
|
||||
test("a Windows launch quotes for cmd.exe only when cmd.exe parses the command line", () => {
|
||||
// `shell: true` runs the child's ComSpec; a cmd.exe the caller names runs as named.
|
||||
for (const [shell, cmd] of [
|
||||
[true, windowsEnv.ComSpec],
|
||||
["cmd.exe", "cmd.exe"],
|
||||
["D:\\Tools\\CMD.EXE", "D:\\Tools\\CMD.EXE"],
|
||||
] as const) {
|
||||
expect(onWindows("echo", ["hello", "a & b"], shell)).toEqual({
|
||||
command: cmd,
|
||||
args: ["/d", "/s", "/c", '"echo hello ^"a^ ^&^ b^""'],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
}
|
||||
for (const shell of ["bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", "pwsh"]) {
|
||||
expect(onWindows("echo", ["'a & b'", "line\nbreak"], shell)).toEqual({
|
||||
command: "echo",
|
||||
args: ["'a & b'", "line\nbreak"],
|
||||
shell,
|
||||
});
|
||||
}
|
||||
// A program starts directly, and `shell: false` keeps a bare name that is not on PATH direct.
|
||||
expect(onWindows("C:\\tools\\node.exe", ["a & b"])).toEqual({
|
||||
command: "C:\\tools\\node.exe",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
expect(onWindows("missing", ["a & b"], false)).toEqual({
|
||||
command: "missing",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
});
|
||||
|
||||
// The daemon runs git with `shell: false` on hot paths that must not block on synchronous IO, so
|
||||
// an explicit `shell: false` starts a bare name directly and leaves the PATH search to Windows.
|
||||
test("a Windows bare name searches PATH for a script only when the caller allows a shell", async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin-path-shim-"));
|
||||
roots.push(directory);
|
||||
await writeFile(path.join(directory, "tool.CMD"), "");
|
||||
const env = { ...windowsEnv, PATH: directory };
|
||||
expect(resolveSpawnInvocation("tool", ["a & b"], false, "win32", env)).toEqual({
|
||||
command: "tool",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
expect(resolveSpawnInvocation("tool", ["a & b"], undefined, "win32", env)).toEqual({
|
||||
command: windowsEnv.ComSpec,
|
||||
args: ["/d", "/s", "/c", `"${path.join(directory, "tool.CMD")} ^"a^ ^&^ b^""`],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
});
|
||||
|
||||
// Real Git Bash on Windows: the arguments reach Bash as given, without cmd.exe escapes.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"execCommand passes arguments as given to a Windows shell other than cmd.exe",
|
||||
async () => {
|
||||
const bash = path.join(
|
||||
process.env.ProgramFiles ?? "C:\\Program Files",
|
||||
"Git",
|
||||
"bin",
|
||||
"bash.exe",
|
||||
);
|
||||
const { stdout } = await execCommand("printf", ["'%s|'", "hello", "'a & b'"], {
|
||||
shell: bash,
|
||||
});
|
||||
expect(stdout).toBe("hello|a & b|");
|
||||
},
|
||||
);
|
||||
|
||||
// A launch wrap starts its executable with the command and its arguments after the wrap's own.
|
||||
// The caller's shell choice belongs to the unwrapped command, so a wrap ignores it.
|
||||
test("spawnProcess starts a wrap's executable with the command after the wrap arguments", async () => {
|
||||
const launcher = await writeArgumentReader();
|
||||
const child = spawnProcess("harness", ["--flag", ...argumentsToPreserve], {
|
||||
wrap: [process.execPath, launcher, "--sandbox profile"],
|
||||
shell: true,
|
||||
stdio: "pipe",
|
||||
});
|
||||
let stdout = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`Launcher exited with ${code}`));
|
||||
});
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual([
|
||||
"--sandbox profile",
|
||||
"harness",
|
||||
"--flag",
|
||||
...argumentsToPreserve,
|
||||
]);
|
||||
});
|
||||
|
||||
// Arguments that cmd.exe reads as syntax unless they are escaped for it. A `.cmd` launcher reads
|
||||
// its arguments a second time when it forwards them with `%*`.
|
||||
const commandScriptArguments = [
|
||||
...argumentsToPreserve,
|
||||
'say "hi"',
|
||||
'"quoted"',
|
||||
"",
|
||||
"a & b",
|
||||
"(parenthesized) arg",
|
||||
"100% done",
|
||||
"%PATH%",
|
||||
"!bang!",
|
||||
"C:\\path with space\\",
|
||||
'mixed "a & b" quote',
|
||||
"--profile=restricted",
|
||||
"a,b;c",
|
||||
// cmd.exe expands a set variable inside a quoted region, so this checks that none opens.
|
||||
"value with %PATH% inside",
|
||||
'quote "then %PATH%" & more',
|
||||
];
|
||||
|
||||
async function writeCommandScriptLauncher(): Promise<string> {
|
||||
const reader = await writeArgumentReader();
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin wrap (x86) & launcher "));
|
||||
roots.push(directory);
|
||||
const launcher = path.join(directory, "sandbox run.cmd");
|
||||
await writeFile(launcher, `@"${process.execPath}" "${reader}" %*\r\n`);
|
||||
return launcher;
|
||||
}
|
||||
|
||||
async function readStdout(child: ReturnType<typeof spawnProcess>): Promise<string> {
|
||||
let stdout = "";
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stdout?.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`Child exited with ${code}`));
|
||||
});
|
||||
});
|
||||
return stdout;
|
||||
}
|
||||
|
||||
// Real cmd.exe: a `.cmd` launch wrap in a directory with spaces and cmd.exe syntax forwards the
|
||||
// harness command and every argument to the program it starts, unchanged.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a .cmd launch wrap forwards the command and its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const launcher = await writeCommandScriptLauncher();
|
||||
const child = spawnProcess("harness", commandScriptArguments, {
|
||||
wrap: [launcher, "--sandbox profile", 'say "hi"', ""],
|
||||
stdio: "pipe",
|
||||
});
|
||||
expect(JSON.parse(await readStdout(child))).toEqual([
|
||||
"--sandbox profile",
|
||||
'say "hi"',
|
||||
"",
|
||||
"harness",
|
||||
...commandScriptArguments,
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test.runIf(process.platform === "win32")(
|
||||
"execCommand runs a .cmd script with its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const launcher = await writeCommandScriptLauncher();
|
||||
const { stdout } = await execCommand(launcher, commandScriptArguments);
|
||||
expect(JSON.parse(stdout)).toEqual(commandScriptArguments);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a script that reads `%~1` gets each argument as given, without escapes.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a .cmd script that reads its arguments one by one gets each one as given on Windows",
|
||||
async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin script reader "));
|
||||
roots.push(directory);
|
||||
const script = path.join(directory, "read.cmd");
|
||||
// `set /p` without input exits 1, so the script exits 0 on its own.
|
||||
await writeFile(
|
||||
script,
|
||||
'@echo off\r\n<nul set /p "=%~1|%~2|%~3|%~4|%~5|%~6|%~7|%~8|%~9"\r\nexit /b 0\r\n',
|
||||
);
|
||||
const { stdout } = await execCommand(script, [
|
||||
"plain",
|
||||
"with space",
|
||||
"feature&bugfix",
|
||||
"100%",
|
||||
"--profile=restricted",
|
||||
"a,b",
|
||||
"a;b",
|
||||
"value with %PATH% inside",
|
||||
"",
|
||||
]);
|
||||
expect(stdout).toBe(
|
||||
"plain|with space|feature&bugfix|100%|--profile=restricted|a,b|a;b|value with %PATH% inside|",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a bare name is found on PATH like cmd.exe finds it. A `.cmd` shim that forwards
|
||||
// `%*`, as npm writes them, passes every argument on unchanged; a program starts directly.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a bare command name found on PATH gets its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const reader = await writeArgumentReader();
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin bare shim "));
|
||||
roots.push(directory);
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-forward.cmd"),
|
||||
`@"${process.execPath}" "${reader}" %*\r\n`,
|
||||
);
|
||||
// Windows env names ignore case, so drop the inherited `Path` before setting the new one.
|
||||
const inherited = Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "path");
|
||||
const env = {
|
||||
...Object.fromEntries(inherited),
|
||||
PATH: `${directory};${process.env.PATH ?? ""}`,
|
||||
};
|
||||
const shim = await execCommand("paseo-forward", commandScriptArguments, { env });
|
||||
expect(JSON.parse(shim.stdout)).toEqual(commandScriptArguments);
|
||||
const program = await execCommand("node", [reader, ...commandScriptArguments], { env });
|
||||
expect(JSON.parse(program.stdout)).toEqual(commandScriptArguments);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a caller that formats its own cmd.exe line asks Node to pass it verbatim.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"spawnProcess passes a caller's verbatim cmd.exe line unchanged on Windows",
|
||||
async () => {
|
||||
const reader = await writeArgumentReader();
|
||||
const child = spawnProcess(
|
||||
process.env.ComSpec ?? "cmd.exe",
|
||||
["/d", "/s", "/c", `""${process.execPath}" "${reader}" "a b" c"`],
|
||||
{ shell: false, windowsVerbatimArguments: true, stdio: "pipe" },
|
||||
);
|
||||
expect(JSON.parse(await readStdout(child))).toEqual(["a b", "c"]);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -8,10 +8,12 @@ import {
|
||||
import { extname } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import {
|
||||
findWindowsCommand,
|
||||
isWindowsCommandScript,
|
||||
quoteWindowsArgument,
|
||||
quoteWindowsCommand,
|
||||
windowsCommandLine,
|
||||
windowsCommandShell,
|
||||
} from "./process-internal/windows-command.js";
|
||||
import type { PluginLaunchWrap } from "./lifecycle.js";
|
||||
const execFileAsync = promisify(execFile);
|
||||
export interface ExecCommandOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
@@ -20,6 +22,10 @@ export interface ExecCommandOptions {
|
||||
killSignal?: NodeJS.Signals;
|
||||
timeout?: number;
|
||||
maxBuffer?: number;
|
||||
/**
|
||||
* `true` runs the command through cmd.exe on Windows, quoted for it. A shell named here other
|
||||
* than cmd.exe gets the command and arguments as given, on every platform; quote for it.
|
||||
*/
|
||||
shell?: boolean | string;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
@@ -27,47 +33,96 @@ interface ExecCommandResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
function hasPathSeparator(value: string): boolean {
|
||||
return value.includes("/") || value.includes("\\");
|
||||
|
||||
export interface SpawnInvocation {
|
||||
command: string;
|
||||
args: string[];
|
||||
shell: boolean | string;
|
||||
/** The args are one cmd.exe line that Node must pass as given. */
|
||||
windowsVerbatimArguments?: boolean;
|
||||
}
|
||||
|
||||
function shouldUseWindowsShell(
|
||||
function namesCmd(shell: boolean | string | undefined): boolean {
|
||||
return (
|
||||
shell === true || (typeof shell === "string" && /^(?:.*[\\/])?cmd(?:\.exe)?$/iu.test(shell))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How `spawnProcess` and `execCommand` start `command` on `platform`.
|
||||
*
|
||||
* On Windows a bare name is first found on `PATH`, as cmd.exe would find it, unless the caller
|
||||
* passes `shell: false`. A program then starts directly. A `.cmd` or `.bat` script, a name that is not on `PATH` (a cmd.exe builtin), or a
|
||||
* `shell: true` launch runs as `cmd.exe /d /s /c "..."`, quoted by `windowsCommandLine`. A shell
|
||||
* the caller names other than cmd.exe gets the command and arguments as given.
|
||||
*/
|
||||
export function resolveSpawnInvocation(
|
||||
command: string,
|
||||
requestedShell?: boolean | string,
|
||||
): boolean | string {
|
||||
if (isWindowsCommandScript(command)) {
|
||||
return true;
|
||||
args: readonly string[],
|
||||
requestedShell: boolean | string | undefined,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): SpawnInvocation {
|
||||
if (platform !== "win32") return { command, args: [...args], shell: requestedShell ?? false };
|
||||
if (typeof requestedShell === "string" && !namesCmd(requestedShell)) {
|
||||
return { command, args: [...args], shell: requestedShell };
|
||||
}
|
||||
if (requestedShell !== undefined) {
|
||||
return requestedShell;
|
||||
const bareName = !/[\\/]/u.test(command) && !extname(command);
|
||||
// `shell: false` starts a bare name directly, and Windows searches PATH without blocking Node.
|
||||
const found = bareName && requestedShell !== false ? findWindowsCommand(command, env) : undefined;
|
||||
const target = found ?? command;
|
||||
const commandScript = isWindowsCommandScript(target, platform);
|
||||
// Only cmd.exe knows a builtin, so a bare name off `PATH` goes to it unless the caller said no shell.
|
||||
const builtin = bareName && !found && requestedShell === undefined;
|
||||
if (!commandScript && !namesCmd(requestedShell) && !builtin) {
|
||||
return { command: target, args: [...args], shell: false };
|
||||
}
|
||||
return process.platform === "win32" && !hasPathSeparator(command) && !extname(command);
|
||||
// A cmd.exe the caller names runs the line; otherwise the child's ComSpec does.
|
||||
return {
|
||||
command: typeof requestedShell === "string" ? requestedShell : windowsCommandShell(env),
|
||||
args: ["/d", "/s", "/c", windowsCommandLine(target, args, { commandScript })],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
};
|
||||
}
|
||||
|
||||
export interface SpawnProcessOptions extends SpawnOptions {
|
||||
/**
|
||||
* Start `[...wrap, command, ...args]`: the wrap's executable runs the command. `shell` is then
|
||||
* ignored; the wrap's executable runs through cmd.exe only when it is a `.cmd` or `.bat` file.
|
||||
*/
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
/** Launch a CLI with Windows command-script handling and argv quoting. The caller owns env. */
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options: SpawnOptions & { stdio: "pipe" },
|
||||
options: SpawnProcessOptions & { stdio: "pipe" },
|
||||
): ChildProcessWithoutNullStreams;
|
||||
export function spawnProcess(command: string, args: string[], options?: SpawnOptions): ChildProcess;
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: SpawnOptions,
|
||||
options?: SpawnProcessOptions,
|
||||
): ChildProcess;
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: SpawnProcessOptions,
|
||||
): ChildProcess {
|
||||
const spawnOptions = options ?? {};
|
||||
const isWindows = process.platform === "win32";
|
||||
const shell = shouldUseWindowsShell(command, spawnOptions.shell);
|
||||
const { wrap, ...spawnOptions } = options ?? {};
|
||||
const env = options?.env ?? process.env;
|
||||
const invocation = wrap
|
||||
? resolveSpawnInvocation(wrap[0], [...wrap.slice(1), command, ...args], false, undefined, env)
|
||||
: resolveSpawnInvocation(command, args, spawnOptions.shell, undefined, env);
|
||||
|
||||
const shouldQuoteForShell = isWindows && shell !== false;
|
||||
const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command;
|
||||
const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args;
|
||||
|
||||
return spawn(resolvedCommand, resolvedArgs, {
|
||||
return spawn(invocation.command, invocation.args, {
|
||||
...spawnOptions,
|
||||
env: options?.env,
|
||||
shell,
|
||||
shell: invocation.shell,
|
||||
// Paseo's own cmd.exe line is verbatim; a direct launch keeps the caller's choice.
|
||||
windowsVerbatimArguments:
|
||||
invocation.windowsVerbatimArguments ?? spawnOptions.windowsVerbatimArguments,
|
||||
signal: options?.signal,
|
||||
windowsHide: true,
|
||||
});
|
||||
@@ -78,13 +133,15 @@ export async function execCommand(
|
||||
args: string[],
|
||||
options?: ExecCommandOptions,
|
||||
): Promise<ExecCommandResult> {
|
||||
const isWindows = process.platform === "win32";
|
||||
const shell = shouldUseWindowsShell(command, options?.shell);
|
||||
const shouldQuoteForShell = isWindows && shell !== false;
|
||||
const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command;
|
||||
const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args;
|
||||
const invocation = resolveSpawnInvocation(
|
||||
command,
|
||||
args,
|
||||
options?.shell,
|
||||
undefined,
|
||||
options?.env ?? process.env,
|
||||
);
|
||||
|
||||
return execFileAsync(resolvedCommand, resolvedArgs, {
|
||||
return execFileAsync(invocation.command, invocation.args, {
|
||||
cwd: options?.cwd,
|
||||
env: options?.env,
|
||||
encoding: options?.encoding ?? "utf8",
|
||||
@@ -92,7 +149,8 @@ export async function execCommand(
|
||||
killSignal: options?.killSignal,
|
||||
timeout: options?.timeout,
|
||||
maxBuffer: options?.maxBuffer,
|
||||
shell,
|
||||
shell: invocation.shell,
|
||||
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
|
||||
windowsHide: true,
|
||||
}) as Promise<ExecCommandResult>;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ProviderEventSchema,
|
||||
ProviderInputSchema,
|
||||
negotiateProviderCapabilities,
|
||||
requireProviderCapabilities,
|
||||
type ProviderEvent,
|
||||
type ProviderInput,
|
||||
type ProviderMetric,
|
||||
@@ -125,3 +126,38 @@ describe("Provider metrics", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Provider launch wrap", () => {
|
||||
const open = (wrap?: readonly [string, ...string[]]): ProviderInput =>
|
||||
ProviderInputSchema.parse({
|
||||
type: "session.open",
|
||||
requestId: "open",
|
||||
sessionId: "session-1",
|
||||
history: "skip",
|
||||
config: {
|
||||
cwd: "/workspace",
|
||||
env: {},
|
||||
mcpServers: {},
|
||||
settings: {},
|
||||
persist: true,
|
||||
...(wrap ? { wrap } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
it("requires session.launch_wrap only for an open that carries a wrap", () => {
|
||||
expect(() => requireProviderCapabilities([], open(["/bin/sandbox", "a b"]))).toThrow(
|
||||
"session.launch_wrap",
|
||||
);
|
||||
expect(() =>
|
||||
requireProviderCapabilities(["session.launch_wrap"], open(["/bin/sandbox"])),
|
||||
).not.toThrow();
|
||||
expect(() => requireProviderCapabilities([], open())).not.toThrow();
|
||||
});
|
||||
|
||||
it("keeps each wrap element whole and rejects an empty wrap", () => {
|
||||
expect(open(["/bin/sandbox", "a b"])).toMatchObject({
|
||||
config: { wrap: ["/bin/sandbox", "a b"] },
|
||||
});
|
||||
expect(() => open([] as unknown as [string])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ export const PROVIDER_CAPABILITIES = [
|
||||
"session.can_stop_runtime",
|
||||
"session.archive",
|
||||
"session.configure",
|
||||
"session.launch_wrap",
|
||||
"session.list",
|
||||
"session.metrics",
|
||||
"session.persistence",
|
||||
@@ -34,6 +35,12 @@ export interface ProviderRegistration {
|
||||
getCatalogCacheKey?(options: ProviderCatalogOptions): Promise<string | undefined>;
|
||||
/** Default executable and arguments; the daemon resolves overrides before status/connect. */
|
||||
command?: readonly [string, ...string[]];
|
||||
/**
|
||||
* Sessions can run behind an `agent.open.before` wrap: the connection offers `session.launch_wrap`
|
||||
* and spawns each session as `[...config.wrap, command, ...args]`. Paseo publishes it on the
|
||||
* provider snapshot before the first connection.
|
||||
*/
|
||||
launchWrap?: boolean;
|
||||
status?(request: ProviderStatusRequest): Promise<ProviderStatus>;
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -212,6 +219,8 @@ export interface ProviderSessionConfig {
|
||||
providerOptions?: Readonly<Record<string, unknown>>;
|
||||
title?: string;
|
||||
persist: boolean;
|
||||
/** Spawn the session as `[...wrap, command, ...args]`. Sent only with `session.launch_wrap`. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
}
|
||||
|
||||
export interface ProviderConfigChanges {
|
||||
@@ -804,6 +813,7 @@ export function requiredProviderCapabilities(input: ProviderInput): readonly Pro
|
||||
const capabilities: ProviderCapability[] = [];
|
||||
if (input.persistence) capabilities.push("session.persistence");
|
||||
if (input.config.toolPolicy) capabilities.push("permission.tool_policy");
|
||||
if (input.config.wrap) capabilities.push("session.launch_wrap");
|
||||
return capabilities;
|
||||
}
|
||||
case "session.prompt":
|
||||
@@ -907,6 +917,7 @@ const sessionConfigSchema = z
|
||||
providerOptions: z.record(z.string(), z.unknown()).optional(),
|
||||
title: z.string().optional(),
|
||||
persist: z.boolean(),
|
||||
wrap: z.tuple([z.string().min(1)], z.string()).optional(),
|
||||
})
|
||||
.strict();
|
||||
const externalResourceSchema = z
|
||||
|
||||
@@ -5,7 +5,11 @@ import ts from "typescript";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repository = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const skill = readFileSync(path.join(repository, "skills/paseo-plugin/SKILL.md"), "utf8");
|
||||
// A Windows checkout writes CRLF line endings.
|
||||
const skill = readFileSync(
|
||||
path.join(repository, "skills/paseo-plugin/SKILL.md"),
|
||||
"utf8",
|
||||
).replaceAll("\r\n", "\n");
|
||||
const pluginRoot = path.join(repository, "plugin-examples/skill-example");
|
||||
|
||||
interface SkillExample {
|
||||
|
||||
@@ -136,6 +136,8 @@ export interface ProviderSnapshotEntry {
|
||||
/** The page that helps users set up and troubleshoot this provider. */
|
||||
docsUrl?: string;
|
||||
defaultModeId?: string | null;
|
||||
/** The provider can run a session behind an `agent.open.before` wrap. Absent means it cannot. */
|
||||
launchWrap?: boolean;
|
||||
}
|
||||
|
||||
export interface AgentFeatureToggle {
|
||||
|
||||
@@ -50,6 +50,12 @@ describe("provider snapshot message schemas", () => {
|
||||
expect(parsed.source).toBe("custom");
|
||||
});
|
||||
|
||||
test("keeps launch-wrap support and leaves it absent when not reported", () => {
|
||||
const entry = { provider: "codex", status: "loading", label: "Codex" };
|
||||
expect(ProviderSnapshotEntrySchema.parse({ ...entry, launchWrap: true }).launchWrap).toBe(true);
|
||||
expect(ProviderSnapshotEntrySchema.parse(entry)).not.toHaveProperty("launchWrap");
|
||||
});
|
||||
|
||||
test("defaults missing enabled state in providers snapshot response entries", () => {
|
||||
const parsed = GetProvidersSnapshotResponseMessageSchema.parse({
|
||||
type: "get_providers_snapshot_response",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user