mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 17:55:18 +00:00
Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
669a7cfd8a | ||
|
|
18876070ea | ||
|
|
a9856f12b6 | ||
|
|
1c378330bc | ||
|
|
beccad5ede | ||
|
|
573e46cf20 | ||
|
|
793ccc5516 | ||
|
|
31716f33af | ||
|
|
9b9fef944a | ||
|
|
a3c1ca6dba | ||
|
|
49715f0eae | ||
|
|
f44f6990a7 | ||
|
|
7e61452dd4 | ||
|
|
cf9683f066 | ||
|
|
88bc3ee42b | ||
|
|
a5f4cd06a6 | ||
|
|
c228a3acac | ||
|
|
1b6308502f | ||
|
|
9e3107fcb7 | ||
|
|
5033ad0249 | ||
|
|
b7af3da71f | ||
|
|
2789421fbd | ||
|
|
b7b5acf086 | ||
|
|
bf83a03ce9 | ||
|
|
80240eb851 | ||
|
|
0c11263d4d | ||
|
|
28c9806da8 | ||
|
|
a0add767c0 | ||
|
|
25f637e57c | ||
|
|
53fa9524cf | ||
|
|
5a8383d237 | ||
|
|
cf3caefa14 | ||
|
|
c747a58871 | ||
|
|
c36d398829 | ||
|
|
183bc736ec | ||
|
|
c4ce21a237 | ||
|
|
9a2236dac3 | ||
|
|
ecd0dd083e | ||
|
|
10c443a32b | ||
|
|
457d8d6ec5 | ||
|
|
80879eaf7c | ||
|
|
dc85c2bfbc | ||
|
|
5ed1f8d108 | ||
|
|
4178497d3d |
@@ -36,7 +36,6 @@ 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 |
|
||||
@@ -55,6 +54,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
|
||||
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
|
||||
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
|
||||
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
|
||||
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
|
||||
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
|
||||
primed.
|
||||
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
|
||||
see [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
Reload releases the old runtime before resuming its durable session: an idle provider process can
|
||||
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
|
||||
@@ -256,7 +256,8 @@ lifecycle is separate from public workspace visibility and is not a public creat
|
||||
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
|
||||
|
||||
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
|
||||
children.
|
||||
children. The timeline and the provider children stay, so an archived chat reads them without its
|
||||
provider; deleting the agent removes them.
|
||||
|
||||
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
|
||||
|
||||
@@ -352,6 +353,8 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
|
||||
|
||||
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
|
||||
|
||||
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
|
||||
|
||||
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
|
||||
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
|
||||
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
|
||||
|
||||
@@ -94,6 +94,7 @@ workspace for a directory clears it. The store lives in memory and resets on dae
|
||||
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
|
||||
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
|
||||
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
|
||||
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
|
||||
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
|
||||
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
|
||||
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
|
||||
@@ -402,7 +403,7 @@ initializing → idle ⇄ running
|
||||
client-side dedup; the default fetch page is 200 items.
|
||||
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
|
||||
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||
|
||||
@@ -478,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
|
||||
```
|
||||
$PASEO_HOME/
|
||||
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
||||
├── paseo.db # Daemon database (SQLite): agent timelines
|
||||
├── projects/projects.json # Project registry
|
||||
├── projects/workspaces.json # Workspace registry
|
||||
├── projects/icons/ # Custom project icon images
|
||||
|
||||
+41
-1
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
|
||||
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
||||
|
||||
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -53,6 +53,7 @@ $PASEO_HOME/
|
||||
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
|
||||
├── paseo.pid # Daemon PID lock file
|
||||
├── local-credential # Per-run local client credential (mode 0600)
|
||||
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
|
||||
├── daemon.log # Default log file (path configurable)
|
||||
├── agents/
|
||||
│ └── {sanitized-cwd}/
|
||||
@@ -181,6 +182,45 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
---
|
||||
|
||||
## Daemon database
|
||||
|
||||
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
|
||||
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
|
||||
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
|
||||
|
||||
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
|
||||
migration leaves the file as it was. `schema_versions` records each module's version and
|
||||
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
|
||||
for example a dropped or renamed column. An older daemon then refuses to start with
|
||||
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
|
||||
modules they do not know. This matters because the app and the daemon update separately, and a
|
||||
user can run an older daemon on the same `$PASEO_HOME`.
|
||||
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
|
||||
names the path. The daemon does not delete or recreate the file.
|
||||
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
|
||||
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
|
||||
file.
|
||||
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
|
||||
last commits but does not corrupt the file.
|
||||
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
|
||||
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
|
||||
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
|
||||
worker exits, the daemon turns auto-checkpoint back on.
|
||||
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
|
||||
`await` and transactions never interleave.
|
||||
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
|
||||
when the daemon opens the database.
|
||||
|
||||
### Agent timelines
|
||||
|
||||
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
|
||||
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
|
||||
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
|
||||
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
|
||||
every update. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
---
|
||||
|
||||
## 2. Daemon Configuration
|
||||
|
||||
**Path:** `$PASEO_HOME/config.json`
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# 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
|
||||
`SheetVisibleFrame` (used by `CompactSheetBody` and `ComboboxSheetFrame`) and `MenuSheetScrollView`.
|
||||
`CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`.
|
||||
- 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
|
||||
|
||||
@@ -464,10 +464,6 @@ registry property, independent of position. The [hooks reference](../public-docs
|
||||
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
|
||||
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
|
||||
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
|
||||
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
|
||||
the provider process, so a reload must not reopen agents the plugin does not change.
|
||||
|
||||
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
|
||||
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
|
||||
|
||||
+68
-11
@@ -5,15 +5,9 @@ Agent chat delivery has two paths:
|
||||
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
|
||||
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
|
||||
|
||||
The daemon retains projected items in memory. Each source event advances the stream sequence,
|
||||
then replaces the previous tool state or merges into the current text item. Intermediate payloads
|
||||
are never retained for history or catch-up. Provider history is the durable transcript authority
|
||||
and rebuilds the projection when an agent resumes.
|
||||
|
||||
Pagination bounds each read, not total resident history. Active and idle agents retain their
|
||||
projected transcript; archive releases it and later history reads rebuild it from the provider.
|
||||
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
|
||||
must be released after their deltas have been consumed.
|
||||
Pagination bounds each read, not total resident history. Streaming overhead must remain
|
||||
proportional to the retained transcript. Cumulative text snapshots must be released after their
|
||||
deltas have been consumed.
|
||||
|
||||
The invariants are:
|
||||
|
||||
@@ -32,6 +26,50 @@ bounded item is used for runtime timeline rows and live stream events. Provider
|
||||
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
|
||||
again to assistant and reasoning rows the projection merges from many chunks.
|
||||
|
||||
## Owned history
|
||||
|
||||
The daemon owns each agent's history in `AgentTimeline`
|
||||
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
|
||||
child's descriptor and history in a child scope of the same agent. Each source event advances the
|
||||
stream sequence, then replaces the previous tool state or merges into the current text item.
|
||||
Intermediate payloads are never retained for history or catch-up.
|
||||
|
||||
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
|
||||
deleting the agent, or a provider removing one of its own children, deletes history.
|
||||
|
||||
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
|
||||
epoch. See [Rewind retires rows](#rewind-retires-rows).
|
||||
- **Provider history** is imported only into an agent that has no history. After that, resume
|
||||
does not read it. Reload agent and Unarchive require the provider history to start with the
|
||||
same prompt IDs and text in order. They then append whole new turns, starting at the next
|
||||
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Opening a stored agent that has no provider session to resume starts its
|
||||
first session on the same history.
|
||||
- **Delete** removes the agent's history and every child's, retired ones included, before the
|
||||
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
|
||||
user can keep using it and delete it again.
|
||||
|
||||
`epoch` is the stored history's identity, minted once when the history is created.
|
||||
|
||||
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
|
||||
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
|
||||
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
|
||||
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
|
||||
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
|
||||
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
|
||||
closed or archived agent holds no history in memory. Each fetch reads the page from the database
|
||||
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
|
||||
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
|
||||
tests.
|
||||
|
||||
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
|
||||
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
|
||||
judged from the resumed provider history. When that history proves nothing, the rewind stays open
|
||||
and the agent refuses prompts with the unknown-outcome error.
|
||||
|
||||
## Presence is not delivery
|
||||
|
||||
Client heartbeat reports presence:
|
||||
@@ -168,7 +206,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
|
||||
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
|
||||
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
|
||||
that cursor are applied. Already-covered rows are not replayed.
|
||||
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
|
||||
- A true middle gap or epoch change atomically replaces stale canonical history with the
|
||||
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
|
||||
local submissions; it never retains two discontiguous canonical ranges.
|
||||
|
||||
@@ -181,6 +219,24 @@ history replay. The pending approval UI can hide that tool from presentation, bu
|
||||
must retain its position. Creating a new history card on rejection places it after the prompt that
|
||||
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
|
||||
|
||||
## Rewind retires rows
|
||||
|
||||
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
|
||||
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
|
||||
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
|
||||
in the same commit. They leave the listing, keep their history, and drop late provider events.
|
||||
|
||||
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
|
||||
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
|
||||
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
|
||||
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
|
||||
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
|
||||
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
|
||||
|
||||
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
|
||||
a wire epoch that changes with each retirement, so they take the destructive replacement they
|
||||
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
|
||||
|
||||
## Provider child history
|
||||
|
||||
Child transcripts use the same projected-page reconciliation as the main conversation. The client
|
||||
@@ -345,7 +401,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
|
||||
arrived first. Generic reducers and consumers do not reimplement message identity matching.
|
||||
|
||||
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
|
||||
rows because a provider may never echo them. A known epoch change or rewind replaces history and
|
||||
rows because a provider may never echo them. A known epoch change replaces history and
|
||||
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
|
||||
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
|
||||
reset without an existing epoch is destructive because the client has no continuity anchor.
|
||||
@@ -361,6 +417,7 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
|
||||
|
||||
## Relevant code
|
||||
|
||||
- Server owned history: `packages/server/src/server/agent/timeline/`
|
||||
- Server live stream forwarding: `packages/server/src/server/session.ts`
|
||||
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
|
||||
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
||||
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
|
||||
|
||||
Generated
+20
-1
@@ -45,6 +45,9 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -39719,6 +39722,9 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -40646,7 +40652,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40654,6 +40660,9 @@
|
||||
"cross-env": "^10.1.0",
|
||||
"tsx": "^4.6.0",
|
||||
"vitest": "^4.1.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -41101,6 +41110,16 @@
|
||||
"@types/mdurl": "^2"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@vitest/expect": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
|
||||
@@ -169,5 +169,8 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,13 @@ import {
|
||||
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
import {
|
||||
closeWorkspaceAgentTab,
|
||||
fetchAgentArchivedAt,
|
||||
primeAdditionalPage,
|
||||
resetSeededPageState,
|
||||
} from "../support/helpers/archive-tab";
|
||||
|
||||
async function completeSubmittedTurn(
|
||||
page: Page,
|
||||
@@ -48,26 +55,102 @@ async function expectTurnCompletesNormally(
|
||||
await expectAgentIdle(page);
|
||||
}
|
||||
|
||||
async function openAgentOnAnotherClient(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await primeAdditionalPage(page);
|
||||
await resetSeededPageState(page);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
}
|
||||
|
||||
/** The prompts the chat shows, in order, each exactly once. */
|
||||
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect(messages).toHaveCount(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
|
||||
const tabId = `workspace-tab-agent_${agentId}`;
|
||||
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
|
||||
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
|
||||
}
|
||||
|
||||
async function archiveAgentByClosingTab(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await closeWorkspaceAgentTab(page, agent.agentId);
|
||||
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
|
||||
}
|
||||
|
||||
async function unarchiveAgent(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectToast(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
|
||||
const UNSYNCED_RELOAD =
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
|
||||
|
||||
/** The prompts of the whole conversation, after scrolling up through its older pages. */
|
||||
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await messages.count();
|
||||
})
|
||||
.toBe(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
// A row React remounts loses this attribute; one that stays mounted keeps it.
|
||||
async function markMounted(row: Locator): Promise<void> {
|
||||
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
|
||||
}
|
||||
|
||||
async function expectStillMounted(row: Locator): Promise<void> {
|
||||
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
|
||||
}
|
||||
|
||||
test.describe("Agent message rewind", () => {
|
||||
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
|
||||
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
test.setTimeout(150_000);
|
||||
const retainedPrompt = "Keep this completed turn after rewind.";
|
||||
const rewoundPrompt = "Remove this completed turn after rewind.";
|
||||
const nextPrompt = "Continue after the rewind.";
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-roundtrip-",
|
||||
title: "Message rewind roundtrip",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const otherClient = await page.context().newPage();
|
||||
|
||||
try {
|
||||
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
|
||||
await test.step("a second client opens the same chat", async () => {
|
||||
await openAgentOnAnotherClient(otherClient, agent);
|
||||
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
|
||||
});
|
||||
|
||||
await markMounted(retainedMessage);
|
||||
await scrollChatAwayFromBottom(page, {
|
||||
deltaY: -900,
|
||||
minDistanceFromBottom: 300,
|
||||
@@ -76,19 +159,92 @@ test.describe("Agent message rewind", () => {
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
await test.step("the rewind stays pending until the daemon answers", async () => {
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
});
|
||||
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await test.step("the rewound turn leaves without reloading the chat", async () => {
|
||||
await expectPrompts(page, [retainedPrompt]);
|
||||
await expectStillMounted(retainedMessage);
|
||||
expect(rewindCompletion.timelineFetchCount()).toBe(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await expectPrompts(otherClient, [retainedPrompt]);
|
||||
});
|
||||
|
||||
await test.step("the next prompt appears once on both clients", async () => {
|
||||
await completeSubmittedTurn(otherClient, agent, nextPrompt);
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
await expectPrompts(page, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the rewound conversation", async () => {
|
||||
await otherClient.reload();
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await otherClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
const keptPrompt = "Keep this turn through reload and archive.";
|
||||
const rewoundPrompt = "Rewind this turn before reloading.";
|
||||
const nextPrompt = "Continue after the rewind, then reload.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-reload-archive-",
|
||||
title: "Message rewind reload archive",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, keptPrompt);
|
||||
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
await rewindConversation(page, rewound, rewoundPrompt);
|
||||
await expectPrompts(page, [keptPrompt]);
|
||||
await completeSubmittedTurn(page, agent, nextPrompt);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
|
||||
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
|
||||
await reloadAgentFromTabMenu(page, agent.agentId);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
await expectComposerVisible(page);
|
||||
});
|
||||
|
||||
await test.step("the archived chat shows the rewound conversation", async () => {
|
||||
await archiveAgentByClosingTab(page, agent);
|
||||
await openAgentRoute(page, agent);
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("unarchiving keeps the rewound conversation", async () => {
|
||||
await unarchiveAgent(page);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the same conversation", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -45,6 +45,26 @@ const PROFILE = {
|
||||
|
||||
const PROFILE_SUMMARY = "Mock Load Test · One minute stream · Approval test";
|
||||
|
||||
// Isolate this suite to the sole mock provider so it tests single-provider picker
|
||||
// behavior deterministically regardless of which CLIs are installed on the host.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
claude: { enabled: false },
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
hoplite: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
test.describe("Agent profiles in the model picker", () => {
|
||||
test("an empty host still exposes agent profile settings from the picker", async ({ page }) => {
|
||||
const seed = await seedAgentProfiles([]);
|
||||
@@ -69,8 +89,8 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
// A live agent is one provider's process, so the profile has to name that
|
||||
// same provider or the picker will not offer it at all.
|
||||
// With only the mock provider enabled on this host, the picker opens
|
||||
// directly into its models and shows its pinned profile.
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-picker-",
|
||||
title: "Agent profiles picker",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
expectNewWorkspaceControlsEnabled,
|
||||
expectNewWorkspaceProjectSelected,
|
||||
@@ -177,33 +176,6 @@ 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,7 +2,6 @@ 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,
|
||||
@@ -110,27 +109,6 @@ 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,476 @@
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream";
|
||||
import {
|
||||
drillIntoProvider,
|
||||
expectComposerMode,
|
||||
expectComposerModel,
|
||||
openModelPicker,
|
||||
selectModelRow,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
|
||||
import {
|
||||
expectComposerVisible,
|
||||
expectQueuedMessageButton,
|
||||
submitMessage,
|
||||
submitMessageWithButton,
|
||||
} from "../support/helpers/composer";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
|
||||
const DIRECT_PROVIDER = {
|
||||
id: "direct-example",
|
||||
label: "Direct provider example",
|
||||
pluginId: "provider-direct-example",
|
||||
modelId: "example-1",
|
||||
modelLabel: "Example 1",
|
||||
modeLabel: "Build",
|
||||
} as const;
|
||||
|
||||
// Disable external CLIs so the E2E host deterministically exposes only Mock +
|
||||
// the installed Direct provider plugin on both developer machines and CI.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
claude: { enabled: false },
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
hoplite: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
interface PluginInstallDaemonClient {
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
getDaemonConfig(): Promise<{ config: { pluginsEnabled?: boolean } }>;
|
||||
patchDaemonConfig(config: { pluginsEnabled?: boolean }): Promise<unknown>;
|
||||
installDirectoryPlugin(directory: string): Promise<unknown>;
|
||||
removePlugin(pluginId: string): Promise<void>;
|
||||
getProvidersSnapshot(): Promise<{
|
||||
entries: Array<{ provider: string; available?: boolean }>;
|
||||
}>;
|
||||
}
|
||||
|
||||
async function hasDirectProvider(client: PluginInstallDaemonClient): Promise<boolean> {
|
||||
const snapshot = await client.getProvidersSnapshot();
|
||||
return snapshot.entries.some((entry) => entry.provider === DIRECT_PROVIDER.id);
|
||||
}
|
||||
|
||||
async function expectSwitchMarkerCountAfterScroll(page: Page, expected: number): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await page.getByTestId("provider-switch-marker").count();
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(expected);
|
||||
}
|
||||
|
||||
async function captureQaScreenshot(page: Page, fileName: string): Promise<void> {
|
||||
const dir = process.env.PASEO_QA_SCREENSHOT_DIR?.trim();
|
||||
if (!dir) return;
|
||||
await mkdir(dir, { recursive: true });
|
||||
await page.screenshot({ path: path.join(dir, fileName), fullPage: false });
|
||||
}
|
||||
|
||||
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
|
||||
const overflow = await page.evaluate(() => {
|
||||
const doc = document.documentElement;
|
||||
return Math.ceil(doc.scrollWidth - doc.clientWidth);
|
||||
});
|
||||
expect(overflow).toBeLessThanOrEqual(1);
|
||||
}
|
||||
|
||||
async function completeMockTurn(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
prompt: string,
|
||||
): Promise<Locator> {
|
||||
await submitMessage(page, prompt);
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toBeVisible({ timeout: 30_000 });
|
||||
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false");
|
||||
return userMessage;
|
||||
}
|
||||
|
||||
async function completeDirectTurn(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
prompt: string,
|
||||
options?: { useSendButton?: boolean },
|
||||
): Promise<Locator> {
|
||||
if (options?.useSendButton) {
|
||||
await submitMessageWithButton(page, prompt);
|
||||
} else {
|
||||
await submitMessage(page, prompt);
|
||||
}
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toBeVisible({ timeout: 30_000 });
|
||||
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false");
|
||||
return userMessage;
|
||||
}
|
||||
|
||||
async function stageProviderDesktop(
|
||||
page: Page,
|
||||
providerId: string,
|
||||
modelId: string,
|
||||
): Promise<void> {
|
||||
await openModelPicker(page);
|
||||
const picker = page.getByTestId("combobox-desktop-container");
|
||||
const backButton = picker.getByTestId("sheet-header-back");
|
||||
if (await backButton.isVisible()) {
|
||||
await backButton.click();
|
||||
}
|
||||
await drillIntoProvider(page, providerId);
|
||||
await selectModelRow(page, { provider: providerId, modelId });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function stageDirectProviderDesktop(page: Page): Promise<void> {
|
||||
await stageProviderDesktop(page, DIRECT_PROVIDER.id, DIRECT_PROVIDER.modelId);
|
||||
}
|
||||
|
||||
async function stageDirectProviderCompact(page: Page): Promise<void> {
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
const browserViewport = page.getByTestId("agent-controls-model-browser-viewport");
|
||||
await expect(browserViewport).toBeVisible({ timeout: 30_000 });
|
||||
await browserViewport.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`).click();
|
||||
await browserViewport
|
||||
.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`)
|
||||
.click();
|
||||
await expect(browserViewport).toHaveCount(0, { timeout: 30_000 });
|
||||
// Dismiss the outer agent-controls sheet so the composer and banner are ready to submit.
|
||||
await page.getByRole("button", { name: "Close", exact: true }).last().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function rewindConversation(page: Page, userMessage: Locator, prompt: string): Promise<void> {
|
||||
await userMessage.getByText(prompt, { exact: true }).hover();
|
||||
await userMessage.getByRole("button", { name: "Rewind to this message", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Rewind conversation", exact: true }).click();
|
||||
}
|
||||
|
||||
test.describe.serial("Provider switching in chat", () => {
|
||||
let pluginClient: PluginInstallDaemonClient;
|
||||
let pluginFixture: Awaited<ReturnType<typeof copyPluginExample>>;
|
||||
let previousPluginsEnabled: boolean | undefined;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
pluginClient = await connectDaemonClient<PluginInstallDaemonClient>({
|
||||
clientIdPrefix: "provider-switching-e2e",
|
||||
});
|
||||
pluginFixture = await copyPluginExample("provider-direct");
|
||||
previousPluginsEnabled = (await pluginClient.getDaemonConfig()).config.pluginsEnabled;
|
||||
await pluginClient.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await pluginClient.installDirectoryPlugin(pluginFixture.directory);
|
||||
await expect.poll(() => hasDirectProvider(pluginClient), { timeout: 30_000 }).toBe(true);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await pluginClient?.removePlugin(DIRECT_PROVIDER.pluginId).catch(() => undefined);
|
||||
await pluginClient
|
||||
?.patchDaemonConfig({ pluginsEnabled: previousPluginsEnabled })
|
||||
.catch(() => undefined);
|
||||
await pluginClient?.close().catch(() => undefined);
|
||||
await pluginFixture?.cleanup().catch(() => undefined);
|
||||
});
|
||||
|
||||
test("stages, cancels, switches providers, inspects marker, scopes rewind, and survives reload", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const preSwitchPrompt = "First prompt on Mock before switching.";
|
||||
const postSwitchPrompt = "Follow up on Direct provider after switching.";
|
||||
const postRewindPrompt = "Continue on Direct provider after rewinding.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-desktop-",
|
||||
title: "Provider switch desktop",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerMode(page, "Load test");
|
||||
|
||||
const initialUrl = page.url();
|
||||
await completeMockTurn(page, workspace, preSwitchPrompt);
|
||||
|
||||
await test.step("staging updates only draft state and Cancel restores the live provider", async () => {
|
||||
await stageDirectProviderDesktop(page);
|
||||
await expectComposerModel(page, DIRECT_PROVIDER.modelLabel);
|
||||
await expectComposerMode(page, DIRECT_PROVIDER.modeLabel);
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText(
|
||||
DIRECT_PROVIDER.label,
|
||||
);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "desktop-staged-switch.png");
|
||||
|
||||
await page.getByTestId("cancel-staged-provider-switch").click();
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectComposerMode(page, "Load test");
|
||||
});
|
||||
|
||||
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
|
||||
await stageDirectProviderDesktop(page);
|
||||
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
|
||||
|
||||
expect(page.url()).toBe(initialUrl);
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
|
||||
// Clean display text: handoff summary must never leak into the visible user bubble.
|
||||
await expect(switchedMessage).toContainText(postSwitchPrompt);
|
||||
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
|
||||
|
||||
// Direct provider echoes its prompt, proving bounded pre-switch context was attached.
|
||||
const directReply = page
|
||||
.getByTestId("assistant-message")
|
||||
.filter({ hasText: "Echo:" })
|
||||
.last();
|
||||
await expect(directReply).toContainText(preSwitchPrompt);
|
||||
await expect(directReply).toContainText(postSwitchPrompt);
|
||||
|
||||
// Switch marker is visible and expands to show context handoff details.
|
||||
const marker = page.getByTestId("provider-switch-marker");
|
||||
await expect(marker).toBeVisible({ timeout: 30_000 });
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await marker.getByTestId("provider-switch-marker-toggle").click();
|
||||
const details = marker.getByTestId("provider-switch-marker-details");
|
||||
await expect(details).toBeVisible();
|
||||
await expect(details).toContainText("Mock");
|
||||
await expect(details).toContainText(DIRECT_PROVIDER.label);
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "desktop-switched-expanded.png");
|
||||
await marker.getByTestId("provider-switch-marker-toggle").click();
|
||||
await expect(details).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("switching back to Mock enforces segment-scoped rewind and preserves pre-switch turns", async () => {
|
||||
const backToMockPrompt = "Switch back to Mock for segment-scoped rewind.";
|
||||
await stageProviderDesktop(page, "mock", "ten-second-stream");
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText("Mock");
|
||||
|
||||
const backToMockMessage = await completeMockTurn(page, workspace, backToMockPrompt);
|
||||
await expect(backToMockMessage).not.toContainText("<chat-history-summary>");
|
||||
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
// Pre-switch prompts from earlier segments must not expose rewind even though Mock supports it.
|
||||
const preSwitchMessage = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: preSwitchPrompt });
|
||||
await preSwitchMessage.scrollIntoViewIfNeeded();
|
||||
await preSwitchMessage.getByText(preSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
preSwitchMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
const directMessage = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: postSwitchPrompt });
|
||||
await directMessage.scrollIntoViewIfNeeded();
|
||||
await directMessage.getByText(postSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
directMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
// Post-switch prompt on Mock CAN rewind without retiring earlier segments or markers.
|
||||
await backToMockMessage.scrollIntoViewIfNeeded();
|
||||
await rewindConversation(page, backToMockMessage, backToMockPrompt);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: backToMockPrompt }),
|
||||
).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: postSwitchPrompt }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2);
|
||||
|
||||
// Continuing in the now-empty active segment completes cleanly.
|
||||
const retriedMessage = await completeMockTurn(page, workspace, postRewindPrompt);
|
||||
await expect(retriedMessage).not.toContainText("<chat-history-summary>");
|
||||
});
|
||||
|
||||
await test.step("reload preserves the switched provider, markers, and rewind boundary", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerModel(page, "Ten second stream");
|
||||
await expectSwitchMarkerCountAfterScroll(page, 2);
|
||||
const reloadedDirect = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: postSwitchPrompt });
|
||||
await expect(reloadedDirect).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: postRewindPrompt }),
|
||||
).toBeVisible();
|
||||
|
||||
await reloadedDirect.scrollIntoViewIfNeeded();
|
||||
await reloadedDirect.getByText(postSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
reloadedDirect.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("stages a switch mid-turn, queues the prompt, and switches cleanly between turns", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const runningPrompt = "Run a ten-second mock turn first.";
|
||||
const queuedPrompt = "Queued handoff prompt for Direct provider.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-midturn-",
|
||||
title: "Provider switch midturn",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await submitMessage(page, runningPrompt);
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
|
||||
// Stage Direct provider while Mock is actively streaming.
|
||||
await stageDirectProviderDesktop(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
// Submitting queues the prompt instead of racing the live turn.
|
||||
await submitMessage(page, queuedPrompt);
|
||||
await expectQueuedMessageButton(page);
|
||||
|
||||
// Once the mock turn completes, the queue drains and commits the switch.
|
||||
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 45_000 });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(
|
||||
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentIdle(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
|
||||
const preSwitchPrompt = "Compact turn on Mock.";
|
||||
const postSwitchPrompt = "Compact handoff on Direct.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-compact-",
|
||||
title: "Provider switch compact",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await submitMessageWithButton(page, preSwitchPrompt);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
const firstFinish = await workspace.client.waitForFinish(workspace.agentId, 30_000);
|
||||
expect(firstFinish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
|
||||
await stageDirectProviderCompact(page);
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "compact-staged-switch.png");
|
||||
|
||||
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt, {
|
||||
useSendButton: true,
|
||||
});
|
||||
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
|
||||
|
||||
const marker = page.getByTestId("provider-switch-marker");
|
||||
await expect(marker).toBeVisible({ timeout: 30_000 });
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
const toggle = marker.getByTestId("provider-switch-marker-toggle");
|
||||
const toggleBox = await toggle.boundingBox();
|
||||
expect(toggleBox).not.toBeNull();
|
||||
expect((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0)).toBeLessThanOrEqual(390);
|
||||
await toggle.click();
|
||||
await expect(marker.getByTestId("provider-switch-marker-details")).toBeVisible();
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "compact-switched-expanded.png");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectComposerDraft(page, firstPrompt);
|
||||
await expectComposerFocused(page);
|
||||
|
||||
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expectUserMessageVisible(page, replacementPrompt);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -254,7 +254,19 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
await fillComposerDraft(page, preservedDraft);
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
await userMessage(page, replacementPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").last().click();
|
||||
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
|
||||
await selectRewindOption(page, "Rewind files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -265,7 +277,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
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,25 +153,3 @@ 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
|
||||
```
|
||||
|
||||
@@ -1,173 +0,0 @@
|
||||
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`,
|
||||
);
|
||||
@@ -1,54 +0,0 @@
|
||||
#!/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"
|
||||
@@ -31,6 +31,8 @@ export interface RewindCompletionGate {
|
||||
clearTimelineStreamCount(): void;
|
||||
release(): void;
|
||||
timelineStreamCount(): number;
|
||||
/** Timeline reads this page sent since the last clear. */
|
||||
timelineFetchCount(): number;
|
||||
waitForDelayedResponse(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -186,12 +188,20 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
|
||||
};
|
||||
}
|
||||
|
||||
// The rewind response and the timeline change it causes; the change removes the rewound row too.
|
||||
const REWIND_COMPLETION_MESSAGES = new Set([
|
||||
"agent.rewind.response",
|
||||
"agent.timeline.rewind",
|
||||
"agent.timeline.replacement",
|
||||
]);
|
||||
|
||||
export async function holdRewindCompletion(
|
||||
page: Page,
|
||||
agentId: string,
|
||||
): Promise<RewindCompletionGate> {
|
||||
let released = false;
|
||||
let timelineStreamCount = 0;
|
||||
let timelineFetchCount = 0;
|
||||
const delayedForwards: Array<() => void> = [];
|
||||
let resolveDelayedResponse: (() => void) | null = null;
|
||||
const delayedResponse = new Promise<void>((resolve) => {
|
||||
@@ -200,7 +210,16 @@ export async function holdRewindCompletion(
|
||||
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => server.send(message));
|
||||
ws.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
if (
|
||||
sessionMessage?.type === "fetch_agent_timeline_request" &&
|
||||
sessionMessage.agentId === agentId
|
||||
) {
|
||||
timelineFetchCount += 1;
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||
@@ -216,11 +235,11 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
if (
|
||||
!released &&
|
||||
(sessionMessage?.type === "agent.rewind.response" ||
|
||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
||||
sessionMessage &&
|
||||
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||
payload?.agentId === agentId
|
||||
) {
|
||||
// The replacement also signals completion and removes the rewound row/menu.
|
||||
// The rewind also signals completion and removes the rewound row/menu.
|
||||
// Hold it with the response so the pending-state assertion observes a pending rewind.
|
||||
delayedForwards.push(() => ws.send(message));
|
||||
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
|
||||
@@ -233,6 +252,7 @@ export async function holdRewindCompletion(
|
||||
return {
|
||||
clearTimelineStreamCount() {
|
||||
timelineStreamCount = 0;
|
||||
timelineFetchCount = 0;
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
@@ -241,6 +261,7 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
},
|
||||
timelineStreamCount: () => timelineStreamCount,
|
||||
timelineFetchCount: () => timelineFetchCount,
|
||||
waitForDelayedResponse: () => delayedResponse,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -243,14 +243,6 @@ 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,
|
||||
|
||||
@@ -23,7 +23,14 @@ export interface DraftAgentProfileControls {
|
||||
}
|
||||
|
||||
export type AgentProfileApplyTarget =
|
||||
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
|
||||
| {
|
||||
kind: "agent";
|
||||
agentId: string;
|
||||
availableModeIds: readonly string[] | null;
|
||||
currentProvider?: string | null;
|
||||
onApplySameProvider?: () => void;
|
||||
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
|
||||
}
|
||||
| { kind: "draft"; controls: DraftAgentProfileControls };
|
||||
|
||||
/** Everything the model picker renders for one profile. It never sees the profile itself. */
|
||||
@@ -139,6 +146,16 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
target.onStageProviderSwitch &&
|
||||
target.currentProvider &&
|
||||
resolved.provider !== target.currentProvider
|
||||
) {
|
||||
target.onStageProviderSwitch(resolved);
|
||||
return;
|
||||
}
|
||||
|
||||
target.onApplySameProvider?.();
|
||||
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
|
||||
if (!reconciled) {
|
||||
return;
|
||||
|
||||
@@ -17,12 +17,7 @@ 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,
|
||||
ICON_BUTTON_SIZES,
|
||||
mapLayout,
|
||||
TOUCH_TARGET,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -46,16 +41,11 @@ 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 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 GRIP_HANDLE_HEIGHT = bySizing({ touch: TOUCH_TARGET, pointer: 28 });
|
||||
|
||||
const ThemedGripVertical = withUnistyles(GripVertical);
|
||||
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||
@@ -140,7 +130,7 @@ function AgentProfileRowMenu({
|
||||
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
|
||||
testID={`agent-profile-menu-${profileId}`}
|
||||
>
|
||||
<ThemedMoreVertical size={KEBAB_GLYPH_SIZE} uniProps={mutedIconColorMapping} />
|
||||
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<DropdownMenuContent side="bottom" align="end" width={180}>
|
||||
<DropdownMenuItem
|
||||
@@ -241,9 +231,16 @@ function AgentProfileRowContent({
|
||||
<Text style={styles.nameText} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
<Text style={styles.stackedSpecText} numberOfLines={1}>
|
||||
{fullSummary}
|
||||
</Text>
|
||||
<View style={styles.stackedSpecLine}>
|
||||
<AgentProfileGlyph
|
||||
provider={profile.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<Text style={styles.stackedSpecText} numberOfLines={1}>
|
||||
{fullSummary}
|
||||
</Text>
|
||||
</View>
|
||||
{profile.notes ? (
|
||||
<Text
|
||||
style={styles.stackedNotesText}
|
||||
@@ -375,8 +372,8 @@ export function AgentProfileRow({
|
||||
[dragging, isFirst, isHovered, menuProps.open, selected],
|
||||
);
|
||||
|
||||
const gripStyle = useMemo(
|
||||
() => (showRowAffordances ? styles.grip : [styles.grip, styles.affordanceHidden]),
|
||||
const gripVisibilityStyle = useMemo(
|
||||
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
|
||||
[showRowAffordances],
|
||||
);
|
||||
const kebabVisibilityStyle = useMemo(
|
||||
@@ -402,6 +399,22 @@ 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}
|
||||
@@ -412,8 +425,7 @@ export function AgentProfileRow({
|
||||
isStacked={isStacked}
|
||||
/>
|
||||
|
||||
{/* 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={styles.trailing}>
|
||||
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||
<AgentProfileRowMenu
|
||||
profileId={profile.id}
|
||||
@@ -430,27 +442,13 @@ export function AgentProfileRow({
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
</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 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>
|
||||
);
|
||||
}
|
||||
@@ -462,7 +460,8 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
minHeight: ROW_MIN_HEIGHT,
|
||||
paddingVertical: theme.spacing[3],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingLeft: theme.spacing[2],
|
||||
paddingRight: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
rowHovered: {
|
||||
@@ -492,15 +491,19 @@ const styles = StyleSheet.create((theme) => ({
|
||||
passThrough: {
|
||||
pointerEvents: "none",
|
||||
},
|
||||
// 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],
|
||||
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,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
@@ -582,6 +585,12 @@ 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,
|
||||
@@ -600,11 +609,6 @@ 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,6 +44,7 @@ import {
|
||||
AgentProfileRow,
|
||||
ROSTER_COL_PROFILE_WIDTH,
|
||||
ROSTER_COL_RUNTIME_WIDTH,
|
||||
ROSTER_GRIP_WIDTH,
|
||||
ROSTER_TRAILING_WIDTH,
|
||||
} from "./agent-profile-row";
|
||||
|
||||
@@ -89,6 +90,7 @@ 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")}
|
||||
@@ -1028,11 +1030,16 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingLeft: theme.spacing[2],
|
||||
paddingRight: 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,
|
||||
|
||||
@@ -56,6 +56,7 @@ export function ChatFind({
|
||||
agentId,
|
||||
serverId,
|
||||
epoch,
|
||||
rewindSeq,
|
||||
items,
|
||||
viewportRef,
|
||||
revealLoadedMessage,
|
||||
@@ -95,8 +96,8 @@ export function ChatFind({
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
useEffect(() => {
|
||||
model.updateHistory(epoch, items);
|
||||
}, [model, epoch, items]);
|
||||
model.updateHistory(epoch, items, rewindSeq);
|
||||
}, [model, epoch, items, rewindSeq]);
|
||||
useEffect(() => () => model.close(), [model]);
|
||||
useEffect(() => {
|
||||
if (!active) model.close();
|
||||
|
||||
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
|
||||
kind: "assistant_message",
|
||||
text,
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq },
|
||||
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
source.map((item, index) => ({
|
||||
event: { type: "timeline" as const, provider: "claude" as const, item },
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1 },
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
|
||||
})),
|
||||
{ source: "canonical" },
|
||||
);
|
||||
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
},
|
||||
async load(_epoch, seq) {
|
||||
loaded.push(seq);
|
||||
model.updateHistory("epoch", history);
|
||||
model.updateHistory("epoch", history, null);
|
||||
},
|
||||
async reveal(_id, _query, occurrence) {
|
||||
revealed.push(occurrence);
|
||||
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => calls).toEqual(["search"]);
|
||||
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
|
||||
};
|
||||
const model = new ChatFindModel(operations);
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -207,24 +207,160 @@ it("reports a search result that outlived its epoch as a changed history", async
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch-2", [message(1)]);
|
||||
model.updateHistory("epoch-2", [message(1)], null);
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports results that a rewind took messages from as a changed history", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 2, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
|
||||
// Another client rewinds the turn holding the match; the epoch stays.
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a search still receiving pages when a rewind lands between them", async () => {
|
||||
let pages = 0;
|
||||
let releaseSecondPage!: () => void;
|
||||
const secondPage = new Promise<void>((resolve) => {
|
||||
releaseSecondPage = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search(_query, cursor) {
|
||||
pages += 1;
|
||||
if (cursor === undefined)
|
||||
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
|
||||
await secondPage;
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => pages).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
releaseSecondPage();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Next", "next"],
|
||||
["Previous", "previous"],
|
||||
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model[step]();
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a pending Next when a rewind lands before it reveals", async () => {
|
||||
let reveals = 0;
|
||||
let revealSecond!: () => void;
|
||||
const secondReveal = new Promise<void>((resolve) => {
|
||||
revealSecond = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
reveals += 1;
|
||||
if (reveals > 1) await secondReveal;
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.next();
|
||||
await expect.poll(() => reveals).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
revealSecond();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("can load a search location before the initial chat history has arrived", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory(null, []);
|
||||
model.updateHistory(null, [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -260,7 +396,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -297,7 +433,7 @@ it("counts one match per message from a host that reports no counts", async () =
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
|
||||
@@ -76,6 +76,10 @@ export class ChatFindModel {
|
||||
private items: StreamItem[] = [];
|
||||
private epoch: string | null = null;
|
||||
private resultEpoch: string | null = null;
|
||||
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
|
||||
private rewindSeq: number | null = null;
|
||||
/** The latest rewind when the current result set's search started; undefined until a search starts. */
|
||||
private searchedRewindSeq: number | null | undefined = undefined;
|
||||
private locations: Location[] = [];
|
||||
private resolved = new Map<Location, Target>();
|
||||
private current = -1;
|
||||
@@ -113,6 +117,7 @@ export class ChatFindModel {
|
||||
this.cancel();
|
||||
this.locations = [];
|
||||
this.resultEpoch = null;
|
||||
this.searchedRewindSeq = undefined;
|
||||
this.resolved.clear();
|
||||
this.current = -1;
|
||||
this.inMessage = { occurrence: 0, count: 0 };
|
||||
@@ -144,6 +149,7 @@ export class ChatFindModel {
|
||||
});
|
||||
}
|
||||
private async search(signal: AbortSignal) {
|
||||
this.searchedRewindSeq = this.rewindSeq;
|
||||
try {
|
||||
let cursor: number | undefined;
|
||||
do {
|
||||
@@ -168,15 +174,14 @@ export class ChatFindModel {
|
||||
this.fail(error, signal);
|
||||
}
|
||||
}
|
||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
||||
if (
|
||||
this.resultEpoch !== null &&
|
||||
epoch !== null &&
|
||||
epoch !== this.resultEpoch &&
|
||||
this.state.open
|
||||
) {
|
||||
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
|
||||
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
|
||||
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
|
||||
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
|
||||
if ((replaced || rewound) && this.state.open) {
|
||||
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
||||
}
|
||||
this.rewindSeq = rewindSeq;
|
||||
this.epoch = epoch;
|
||||
this.items = items;
|
||||
this.historyListeners.forEach((listener) => listener());
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface ChatFindProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
epoch: string | null;
|
||||
/** The sequence number of the latest rewind applied to this history, if any. */
|
||||
rewindSeq: number | null;
|
||||
items: StreamItem[];
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
revealLoadedMessage(messageId: string): boolean;
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "live prompt",
|
||||
timestamp: new Date(seq),
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||
});
|
||||
rerender({ tail: [loadedPrompt(2)] });
|
||||
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
|
||||
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
|
||||
kind: "assistant_message",
|
||||
text: "chunk",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-1",
|
||||
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "Replaced conversation",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-2",
|
||||
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
];
|
||||
const { result, rerender } = renderHook(
|
||||
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ tail, mountedHistoryMessageIds }) =>
|
||||
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
};
|
||||
const revealLoadedMessage = vi.fn();
|
||||
revealLoadedMessage.mockReturnValue(false);
|
||||
|
||||
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
const source = harness.source();
|
||||
const live = source.head[0];
|
||||
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
|
||||
const present = createStreamPresentation();
|
||||
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
||||
const repointed = rows(
|
||||
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
{
|
||||
id: streamed[0]!.id,
|
||||
text: "Streamed answer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
|
||||
messageId: "provider-message",
|
||||
clientMessageId: "client-message",
|
||||
turnId: "turn-1",
|
||||
timelineCursor: { epoch: "epoch", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||
});
|
||||
const presentMessage = () =>
|
||||
present({
|
||||
|
||||
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
|
||||
const failedTurn = {
|
||||
...assistantMessage("assistant-error", 2),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("includes the provider message id with a supported timeline cursor", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("falls back to the provider message id when timeline cursors are unsupported", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -116,7 +116,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("resolves a fork boundary from the reply a plugin card replaced", () => {
|
||||
const reply = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
const card: StreamItem = {
|
||||
kind: "plugin",
|
||||
@@ -154,7 +154,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
const appended: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "plugin/card-1",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timestamp: timestamp(2),
|
||||
pluginId: "plugin",
|
||||
pluginItemId: "card-1",
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
|
||||
/** The daemon's timeline cursor; the row's anchor stays in the client. */
|
||||
interface TimelineBoundaryCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||
|
||||
export function resolveAssistantTurnForkBoundary(input: {
|
||||
@@ -15,7 +21,7 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
}
|
||||
if (input.supportsTimelineCursor && reply.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: reply.timelineCursor,
|
||||
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
|
||||
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("collapseTurns", () => {
|
||||
it("stands at its host's timeline position, taking a new row when that position lands", () => {
|
||||
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
|
||||
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
|
||||
const cursor = { epoch: "epoch-1", seq: 7 };
|
||||
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
|
||||
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
|
||||
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
|
||||
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
|
||||
|
||||
@@ -101,7 +101,7 @@ function summaryRow(
|
||||
}
|
||||
|
||||
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
|
||||
return isTurnTrigger(item) || item.kind === "compaction";
|
||||
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
|
||||
}
|
||||
|
||||
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
|
||||
|
||||
@@ -159,10 +159,10 @@ const projectedReply: StreamItem = {
|
||||
id: "reply",
|
||||
messageId: "provider-reply-1",
|
||||
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
},
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
pluginId: "genui",
|
||||
pluginItemId: "reply/1",
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
ToolCall,
|
||||
TodoListCard,
|
||||
CompactionMarker,
|
||||
ProviderSwitchMarker,
|
||||
MessageOuterSpacingProvider,
|
||||
type InlinePathTarget,
|
||||
} from "@/components/message";
|
||||
@@ -57,6 +58,7 @@ import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
|
||||
import { useLoadOlderAgentHistory } from "@/hooks/use-load-older-agent-history";
|
||||
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
|
||||
import { returnToTimelineTail } from "./timeline-tail-navigation";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { ToolCallDetailsContent } from "@/components/tool-call-details";
|
||||
@@ -408,6 +410,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
const timelineEpoch = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
|
||||
);
|
||||
const timelineRewindSeq = useSessionStore((state) => {
|
||||
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
|
||||
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
|
||||
});
|
||||
const isTimelineDetached = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
|
||||
);
|
||||
@@ -711,8 +717,15 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
|
||||
const setToolCallGroupExpanded = toolCallExpansion.setGroupExpanded;
|
||||
|
||||
const activeSegmentStartSeq = useSessionStore(
|
||||
(state) =>
|
||||
state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.activeSegmentStartSeq ??
|
||||
0,
|
||||
);
|
||||
|
||||
const renderUserMessageItem = useCallback(
|
||||
(layoutItem: StreamLayoutItem, item: Extract<StreamItem, { kind: "user_message" }>) => {
|
||||
const canRewindPrompt = isPromptInActiveSegment(item.timelineCursor, activeSegmentStartSeq);
|
||||
return (
|
||||
<UserMessage
|
||||
itemId={item.id}
|
||||
@@ -724,7 +737,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
images={item.images}
|
||||
attachments={item.attachments}
|
||||
timestamp={item.timestamp.getTime()}
|
||||
capabilities={context.capabilities}
|
||||
capabilities={canRewindPrompt ? context.capabilities : undefined}
|
||||
client={client}
|
||||
isFirstInGroup={layoutItem.isFirstInUserGroup}
|
||||
isLastInGroup={layoutItem.isLastInUserGroup}
|
||||
@@ -735,7 +748,14 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
},
|
||||
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
|
||||
[
|
||||
activeSegmentStartSeq,
|
||||
context.capabilities,
|
||||
agentId,
|
||||
client,
|
||||
pendingClientMessageIds,
|
||||
resolvedServerId,
|
||||
],
|
||||
);
|
||||
|
||||
const renderAssistantMessageItem = useCallback(
|
||||
@@ -941,6 +961,18 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
|
||||
case "provider_switch":
|
||||
return (
|
||||
<ProviderSwitchMarker
|
||||
serverId={resolvedServerId}
|
||||
fromProvider={item.fromProvider}
|
||||
toProvider={item.toProvider}
|
||||
fromModel={item.fromModel}
|
||||
toModel={item.toModel}
|
||||
context={item.context}
|
||||
/>
|
||||
);
|
||||
|
||||
case "plugin":
|
||||
return (
|
||||
<PluginTimelineItemView agentId={agentId} item={item} serverId={resolvedServerId} />
|
||||
@@ -1166,6 +1198,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -75,6 +75,7 @@ export function estimateStreamItemHeight({
|
||||
case "notification":
|
||||
return 88;
|
||||
case "compaction":
|
||||
case "provider_switch":
|
||||
return 72;
|
||||
default:
|
||||
return 120;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
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({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
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,11 +20,12 @@ 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";
|
||||
@@ -609,9 +610,8 @@ export interface SheetKeyboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
function CompactSheetBody({
|
||||
header,
|
||||
@@ -619,6 +619,7 @@ function CompactSheetBody({
|
||||
onClose,
|
||||
testID,
|
||||
footer,
|
||||
isKeyboardVisible,
|
||||
scrollable,
|
||||
bodyStyle,
|
||||
contentStyle,
|
||||
@@ -629,18 +630,32 @@ function CompactSheetBody({
|
||||
onClose: () => void;
|
||||
testID?: string;
|
||||
footer: ReactNode;
|
||||
isKeyboardVisible: boolean;
|
||||
scrollable: boolean;
|
||||
bodyStyle?: StyleProp<ViewStyle>;
|
||||
contentStyle?: StyleProp<ViewStyle>;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
// 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);
|
||||
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],
|
||||
);
|
||||
return (
|
||||
<SheetVisibleFrame footer={footer} safeAreaInset={scrollable ? "footer" : "frame"}>
|
||||
<SheetVisibleFrame footer={footerView}>
|
||||
{header ? (
|
||||
<SheetHeaderView
|
||||
header={header}
|
||||
@@ -657,12 +672,12 @@ function CompactSheetBody({
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<Animated.View style={[SCROLL_CONTENT_GROW, bodyClearanceStyle]}>
|
||||
<View style={[styles.contentGrow, bodyClearanceStyle]}>
|
||||
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
|
||||
</Animated.View>
|
||||
</View>
|
||||
</ScrollView>
|
||||
) : (
|
||||
<View style={styles.compactStaticContent}>
|
||||
<View style={[styles.compactStaticContent, bodyClearanceStyle]}>
|
||||
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
|
||||
{children}
|
||||
</SheetContent>
|
||||
@@ -695,6 +710,7 @@ 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.
|
||||
@@ -812,6 +828,7 @@ export function AdaptiveModalSheet({
|
||||
onClose={onClose}
|
||||
testID={testID}
|
||||
footer={footerView}
|
||||
isKeyboardVisible={isKeyboardVisible}
|
||||
scrollable={scrollable}
|
||||
bodyStyle={bodyStyle}
|
||||
contentStyle={contentStyle}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
|
||||
@@ -19,6 +20,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const toast = useToast();
|
||||
const [isUnarchiving, setIsUnarchiving] = useState(false);
|
||||
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
|
||||
|
||||
@@ -27,12 +29,15 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
setIsUnarchiving(true);
|
||||
setUnarchiveError(null);
|
||||
try {
|
||||
await client.refreshAgent(agentId);
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
|
||||
}
|
||||
} catch (error) {
|
||||
setUnarchiveError(toErrorMessage(error));
|
||||
setIsUnarchiving(false);
|
||||
}
|
||||
}, [client, isConnected, isUnarchiving, agentId]);
|
||||
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -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/content-drag";
|
||||
import { useContentDrag } from "@/components/ui/scroll-view";
|
||||
import { createDragHold } from "./drag-reorder/drag-hold";
|
||||
import { movedItemKey } from "./drag-reorder/native-drop";
|
||||
import type {
|
||||
|
||||
@@ -232,7 +232,6 @@ export interface HostPickerProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
anchorRef: React.RefObject<View | null>;
|
||||
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
|
||||
includeAllHost?: boolean;
|
||||
includeAddHost?: boolean;
|
||||
onAddHost?: () => void;
|
||||
@@ -255,7 +254,6 @@ export function HostPicker({
|
||||
open,
|
||||
onOpenChange,
|
||||
anchorRef,
|
||||
restoreFocusRef,
|
||||
includeAllHost,
|
||||
includeAddHost,
|
||||
onAddHost,
|
||||
@@ -406,7 +404,6 @@ export function HostPicker({
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
desktopMinWidth={desktopMinWidth}
|
||||
/>
|
||||
|
||||
@@ -55,7 +55,6 @@ 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";
|
||||
@@ -668,7 +667,6 @@ function MobileSidebar({
|
||||
listHeaderComponent={workspacesSectionHeaderElement}
|
||||
/>
|
||||
)}
|
||||
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
|
||||
</SidebarToastRegion>
|
||||
</SidebarViewSlot>
|
||||
|
||||
@@ -924,7 +922,6 @@ function DesktopSidebar({
|
||||
listHeaderComponent={workspacesSectionHeaderElement}
|
||||
/>
|
||||
)}
|
||||
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
|
||||
</SidebarToastRegion>
|
||||
</SidebarViewSlot>
|
||||
|
||||
|
||||
@@ -19,9 +19,11 @@ import {
|
||||
type RewindMode,
|
||||
} from "@/components/rewind";
|
||||
import { TaskListRow } from "@/components/task-list-row";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
@@ -40,13 +42,17 @@ import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import type {
|
||||
AgentCapabilityFlags,
|
||||
AgentMetric,
|
||||
AgentProvider,
|
||||
ProviderSwitchContextSummary,
|
||||
ToolCallDetail,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
Check,
|
||||
CheckSquare,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
CircleDot,
|
||||
Copy,
|
||||
@@ -1487,6 +1493,188 @@ export const CompactionMarker = memo(function CompactionMarker({
|
||||
);
|
||||
});
|
||||
|
||||
const StyledSwitchIcon = withUnistyles(ArrowRightLeft, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const StyledChevronDownIcon = withUnistyles(ChevronDown, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const StyledChevronRightIcon = withUnistyles(ChevronRight, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
export interface ProviderSwitchMarkerProps {
|
||||
serverId?: string | null;
|
||||
fromProvider: AgentProvider;
|
||||
toProvider: AgentProvider;
|
||||
fromModel?: string | null;
|
||||
toModel?: string | null;
|
||||
context: ProviderSwitchContextSummary;
|
||||
}
|
||||
|
||||
const providerSwitchStylesheet = StyleSheet.create((theme) => ({
|
||||
wrapper: {
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
width: "100%",
|
||||
},
|
||||
line: {
|
||||
flex: 1,
|
||||
minWidth: 12,
|
||||
height: 1,
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
triggerButton: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
maxWidth: "85%",
|
||||
},
|
||||
triggerContent: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
gap: theme.spacing[1.5],
|
||||
},
|
||||
triggerText: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
fontFamily: theme.fontFamily.ui,
|
||||
fontSize: 13,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
detailsCard: {
|
||||
alignSelf: "center",
|
||||
maxWidth: 480,
|
||||
width: "100%",
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
detailRow: {
|
||||
fontFamily: theme.fontFamily.ui,
|
||||
fontSize: 12,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
}));
|
||||
|
||||
function resolveProviderSwitchLabel(
|
||||
provider: string,
|
||||
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
|
||||
): string {
|
||||
return entries?.find((entry) => entry.provider === provider)?.label ?? provider;
|
||||
}
|
||||
|
||||
function resolveProviderSwitchModelLabel(
|
||||
provider: string,
|
||||
modelId: string | null | undefined,
|
||||
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
|
||||
): string | null {
|
||||
if (!modelId) return null;
|
||||
const entry = entries?.find((candidate) => candidate.provider === provider);
|
||||
return entry?.models?.find((model) => model.id === modelId)?.label ?? modelId;
|
||||
}
|
||||
|
||||
function formatProviderSwitchEndpoint(providerLabel: string, modelLabel: string | null): string {
|
||||
return modelLabel ? `${providerLabel} (${modelLabel})` : providerLabel;
|
||||
}
|
||||
|
||||
export const ProviderSwitchMarker = memo(function ProviderSwitchMarker({
|
||||
serverId = null,
|
||||
fromProvider,
|
||||
toProvider,
|
||||
fromModel,
|
||||
toModel,
|
||||
context,
|
||||
}: ProviderSwitchMarkerProps) {
|
||||
const { t } = useTranslation();
|
||||
const { entries: providerEntries } = useProvidersSnapshot(serverId);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const handleToggle = useCallback(() => setExpanded((prev) => !prev), []);
|
||||
|
||||
const fromLabel = resolveProviderSwitchLabel(fromProvider, providerEntries);
|
||||
const toLabel = resolveProviderSwitchLabel(toProvider, providerEntries);
|
||||
const fromModelLabel = resolveProviderSwitchModelLabel(fromProvider, fromModel, providerEntries);
|
||||
const toModelLabel = resolveProviderSwitchModelLabel(toProvider, toModel, providerEntries);
|
||||
|
||||
const title = t("message.providerSwitch.switched", {
|
||||
from: fromLabel,
|
||||
to: toLabel,
|
||||
});
|
||||
const contextLine = t("message.providerSwitch.contextSummary", {
|
||||
count: context.includedItems,
|
||||
chars: context.charCount.toLocaleString(),
|
||||
budget: context.budgetChars.toLocaleString(),
|
||||
});
|
||||
const reasonsLine =
|
||||
context.truncated && context.omittedReasons?.length
|
||||
? t("message.providerSwitch.trimmed", {
|
||||
reasons: context.omittedReasons
|
||||
.map((reason) => {
|
||||
if (reason === "tail_window_limit") {
|
||||
return t("message.providerSwitch.reasonTailWindow");
|
||||
}
|
||||
if (reason === "char_budget") {
|
||||
return t("message.providerSwitch.reasonCharBudget");
|
||||
}
|
||||
return reason;
|
||||
})
|
||||
.join(", "),
|
||||
})
|
||||
: null;
|
||||
|
||||
return (
|
||||
<View style={providerSwitchStylesheet.wrapper} testID="provider-switch-marker">
|
||||
<View style={providerSwitchStylesheet.row}>
|
||||
<View style={providerSwitchStylesheet.line} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
style={providerSwitchStylesheet.triggerButton}
|
||||
onPress={handleToggle}
|
||||
accessibilityLabel={title}
|
||||
testID="provider-switch-marker-toggle"
|
||||
>
|
||||
<View style={providerSwitchStylesheet.triggerContent}>
|
||||
<StyledSwitchIcon size={12} />
|
||||
<Text
|
||||
style={providerSwitchStylesheet.triggerText}
|
||||
numberOfLines={1}
|
||||
ellipsizeMode="tail"
|
||||
>
|
||||
{title}
|
||||
</Text>
|
||||
{expanded ? <StyledChevronDownIcon size={12} /> : <StyledChevronRightIcon size={12} />}
|
||||
</View>
|
||||
</Button>
|
||||
<View style={providerSwitchStylesheet.line} />
|
||||
</View>
|
||||
{expanded ? (
|
||||
<View style={providerSwitchStylesheet.detailsCard} testID="provider-switch-marker-details">
|
||||
<Text style={providerSwitchStylesheet.detailRow}>
|
||||
{`${formatProviderSwitchEndpoint(fromLabel, fromModelLabel)} → ${formatProviderSwitchEndpoint(toLabel, toModelLabel)}`}
|
||||
</Text>
|
||||
<Text style={providerSwitchStylesheet.detailRow}>{contextLine}</Text>
|
||||
{reasonsLine ? (
|
||||
<Text style={providerSwitchStylesheet.detailRow}>{reasonsLine}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
interface TodoListCardProps {
|
||||
items: TodoEntry[];
|
||||
activity: TaskActivity;
|
||||
|
||||
@@ -8,15 +8,10 @@ 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";
|
||||
|
||||
// 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);
|
||||
const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView;
|
||||
|
||||
interface PageLayoutProps {
|
||||
title?: string;
|
||||
|
||||
@@ -10,7 +10,11 @@ import { useToast } from "@/contexts/toast-context";
|
||||
import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import { useRewindAgentMutation } from "./use-rewind-agent-mutation";
|
||||
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
|
||||
import {
|
||||
isPromptInActiveSegment,
|
||||
isRewindableMessage,
|
||||
useRewindMenuItems,
|
||||
} from "./use-rewind-capabilities";
|
||||
|
||||
export function RewindCommandCenterRegistration({
|
||||
serverId,
|
||||
@@ -42,10 +46,16 @@ export function RewindCommandCenterRegistration({
|
||||
if (timeline.status !== "synced" || timeline.newer === "available") {
|
||||
return undefined;
|
||||
}
|
||||
return (
|
||||
const candidate =
|
||||
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
|
||||
timeline.items.findLast((item) => item.kind === "user_message")
|
||||
);
|
||||
timeline.items.findLast((item) => item.kind === "user_message");
|
||||
if (
|
||||
!candidate ||
|
||||
!isPromptInActiveSegment(candidate.timelineCursor, timeline.range?.activeSegmentStartSeq)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return candidate;
|
||||
});
|
||||
const { rewindAgent, isPending } = useRewindAgentMutation({
|
||||
serverId,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useRewindComposerRestore } from "./composer-restore";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { hostSupportsFeature } from "@/runtime/host-features";
|
||||
|
||||
interface UseRewindAgentMutationInput {
|
||||
serverId?: string;
|
||||
@@ -42,7 +43,16 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
if (mode !== "files") {
|
||||
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10. A daemon with
|
||||
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
|
||||
// and this client has to read it again.
|
||||
const appliesLive =
|
||||
input.serverId !== undefined &&
|
||||
hostSupportsFeature(
|
||||
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
|
||||
"timelineRewindOperations",
|
||||
);
|
||||
if (mode !== "files" && !appliesLive) {
|
||||
const cursor = input.serverId
|
||||
? useSessionStore
|
||||
.getState()
|
||||
|
||||
@@ -26,6 +26,20 @@ export function isRewindableMessage(messageId: string | undefined, text: string)
|
||||
return Boolean(messageId) && text.trim().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a user prompt belongs to the active provider segment (after the latest provider switch).
|
||||
* Prompts from earlier provider segments cannot be rewound.
|
||||
*/
|
||||
export function isPromptInActiveSegment(
|
||||
timelineCursor: { anchorSeq?: number; seq?: number } | undefined,
|
||||
activeSegmentStartSeq: number | undefined,
|
||||
): boolean {
|
||||
if (!activeSegmentStartSeq || activeSegmentStartSeq <= 0) return true;
|
||||
const anchor = timelineCursor?.anchorSeq ?? timelineCursor?.seq;
|
||||
if (anchor === undefined) return true;
|
||||
return anchor > activeSegmentStartSeq;
|
||||
}
|
||||
|
||||
export function resolveRewindMenuItems(
|
||||
capabilities:
|
||||
| Pick<
|
||||
|
||||
@@ -66,16 +66,12 @@ function heightOf(testID: string): number {
|
||||
return element(testID).getBoundingClientRect().height;
|
||||
}
|
||||
|
||||
function textNode(rowTestID: string, text: string): HTMLElement {
|
||||
const found = [...element(rowTestID).querySelectorAll("div")].find(
|
||||
(node) => node.textContent === text && node.children.length === 0,
|
||||
);
|
||||
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);
|
||||
const title = [...element(rowTestID).querySelectorAll("div")].find(
|
||||
(node) => node.textContent === label && node.children.length === 0,
|
||||
);
|
||||
if (!title) throw new Error(`No title ${label}`);
|
||||
return Number.parseFloat(getComputedStyle(title).fontSize);
|
||||
}
|
||||
|
||||
describe("settings row density", () => {
|
||||
@@ -104,52 +100,4 @@ 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,13 +88,9 @@ 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.passThrough],
|
||||
() => [styles.chevron, expanded && styles.chevronExpanded],
|
||||
[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}
|
||||
@@ -117,7 +113,7 @@ export function SettingsRowHeader({
|
||||
{leading}
|
||||
</View>
|
||||
) : null}
|
||||
<View style={[contentStyle, styles.passThrough]}>
|
||||
<View style={[settingsStyles.rowContent, styles.passThrough]}>
|
||||
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<Text style={layout.title}>{label}</Text>
|
||||
{labelAccessory}
|
||||
@@ -132,15 +128,28 @@ export function SettingsRowHeader({
|
||||
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
|
||||
</View>
|
||||
) : null}
|
||||
<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 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>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -151,32 +160,6 @@ 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
|
||||
@@ -239,30 +222,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
passThrough: {
|
||||
pointerEvents: "none",
|
||||
},
|
||||
// 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: {
|
||||
trailing: {
|
||||
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,17 +101,7 @@ 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,
|
||||
selectSidebarGroupVisibility,
|
||||
} from "@/components/sidebar/sidebar-group-visibility";
|
||||
import {
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
useWorkspaceSelectionPress,
|
||||
} from "@/sidebar-selection";
|
||||
import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility";
|
||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||
import {
|
||||
SidebarWorkspaceRowFrame,
|
||||
@@ -294,7 +284,6 @@ interface WorkspaceRowInnerProps {
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
onCopyBranchName?: () => void;
|
||||
onCopyPath?: () => void;
|
||||
@@ -618,14 +607,12 @@ function WorkspaceRowRightGroup({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
isCreating,
|
||||
isSelectionMode,
|
||||
showShortcutBadge,
|
||||
shortcutNumber,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
archivePendingLabel,
|
||||
archiveShortcutKeys,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
@@ -640,14 +627,12 @@ 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;
|
||||
@@ -675,7 +660,6 @@ function WorkspaceRowRightGroup({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
});
|
||||
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
|
||||
|
||||
@@ -711,7 +695,6 @@ function WorkspaceRowRightGroup({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -1082,7 +1065,6 @@ function WorkspaceRowInner({
|
||||
archiveLabel,
|
||||
archiveStatus = "idle",
|
||||
archivePendingLabel,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onCopyBranchName,
|
||||
onCopyPath,
|
||||
@@ -1097,8 +1079,6 @@ 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,
|
||||
@@ -1111,51 +1091,30 @@ function WorkspaceRowInner({
|
||||
...dragAttributes
|
||||
} = dragHandleProps?.attributes ?? {};
|
||||
|
||||
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef: interaction.didLongPressRef,
|
||||
onPress,
|
||||
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 accessibilityState = useMemo(() => ({ selected }), [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: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
const backdrop = getSidebarRowBackdrop({
|
||||
isDragging,
|
||||
isHighlighted,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered });
|
||||
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
|
||||
return (
|
||||
<View
|
||||
{...dragAttributes}
|
||||
{...(disableDrag ? null : dragHandleProps?.listeners)}
|
||||
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
|
||||
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
||||
style={styles.workspaceRowContainer}
|
||||
{...hoverHandlers}
|
||||
@@ -1172,7 +1131,6 @@ function WorkspaceRowInner({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -1182,18 +1140,17 @@ function WorkspaceRowInner({
|
||||
onTogglePin={onTogglePin}
|
||||
openInFileManagerPath={workspace.workspaceDirectory}
|
||||
disabled={isArchiving}
|
||||
enabled={!isEditingTitle && !isSelectionMode}
|
||||
aria-selected={isSelectionMode ? undefined : selected}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
enabled={!isEditingTitle}
|
||||
aria-selected={selected}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
style={workspaceRowStyle}
|
||||
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
||||
onHighlightChange={setIsHighlighted}
|
||||
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
|
||||
onTouchMove={disableDrag ? undefined : interaction.handleTouchMove}
|
||||
onPressOut={disableDrag ? undefined : interaction.handlePressOut}
|
||||
onPress={isEditingTitle ? undefined : handleRowPress}
|
||||
onPressIn={isEditingTitle ? undefined : interaction.handlePressIn}
|
||||
onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove}
|
||||
onPressOut={isEditingTitle ? undefined : interaction.handlePressOut}
|
||||
onPress={isEditingTitle ? undefined : handlePress}
|
||||
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
||||
>
|
||||
<SidebarWorkspaceRowContent
|
||||
@@ -1206,8 +1163,6 @@ function WorkspaceRowInner({
|
||||
isHovered={isHovered}
|
||||
isLoading={isArchiving || isCreating}
|
||||
isCreating={isCreating}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
||||
@@ -1219,14 +1174,12 @@ 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}
|
||||
@@ -1312,10 +1265,6 @@ 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);
|
||||
@@ -1368,7 +1317,6 @@ 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}
|
||||
@@ -2251,62 +2199,6 @@ 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,9 +3,7 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type MutableRefObject,
|
||||
type ReactNode,
|
||||
@@ -71,15 +69,7 @@ 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";
|
||||
@@ -164,14 +154,6 @@ 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,
|
||||
@@ -182,56 +164,6 @@ 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;
|
||||
@@ -330,8 +262,6 @@ export function SidebarStatusWorkspaceList({
|
||||
<StatusGroupList
|
||||
groups={groups}
|
||||
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
|
||||
expandedGroupKeys={expandedGroupKeys}
|
||||
onToggleGroupWorkspacesExpanded={toggleGroupWorkspacesExpanded}
|
||||
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
||||
shortcutIndex={statusShortcutIndex}
|
||||
showShortcutBadges={showShortcutBadges}
|
||||
@@ -373,8 +303,6 @@ export function SidebarStatusWorkspaceList({
|
||||
function StatusGroupList({
|
||||
groups,
|
||||
collapsedWorkspaceGroupKeys,
|
||||
expandedGroupKeys,
|
||||
onToggleGroupWorkspacesExpanded,
|
||||
projectIconByProjectViewKey,
|
||||
shortcutIndex,
|
||||
showShortcutBadges,
|
||||
@@ -385,8 +313,6 @@ 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;
|
||||
@@ -402,8 +328,6 @@ 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}
|
||||
@@ -425,8 +349,6 @@ const STATUS_GROUP_VISIBILITY = {
|
||||
function StatusGroupRows({
|
||||
group,
|
||||
collapsed,
|
||||
workspacesExpanded,
|
||||
onToggleWorkspacesExpanded,
|
||||
projectIconByProjectViewKey,
|
||||
shortcutIndex,
|
||||
showShortcutBadges,
|
||||
@@ -437,8 +359,6 @@ function StatusGroupRows({
|
||||
}: {
|
||||
group: SidebarWorkspaceGroup;
|
||||
collapsed: boolean;
|
||||
workspacesExpanded: boolean;
|
||||
onToggleWorkspacesExpanded: (groupKey: string) => void;
|
||||
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
||||
shortcutIndex: Map<string, number>;
|
||||
showShortcutBadges: boolean;
|
||||
@@ -448,9 +368,10 @@ function StatusGroupRows({
|
||||
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
|
||||
}) {
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const [workspacesExpanded, setWorkspacesExpanded] = useState(false);
|
||||
const toggleWorkspacesExpanded = useCallback(
|
||||
() => onToggleWorkspacesExpanded(group.key),
|
||||
[group.key, onToggleWorkspacesExpanded],
|
||||
() => setWorkspacesExpanded((current) => !current),
|
||||
[],
|
||||
);
|
||||
const {
|
||||
leadingItem: leadingWorkspace,
|
||||
@@ -748,10 +669,6 @@ 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);
|
||||
@@ -799,7 +716,6 @@ 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}
|
||||
@@ -834,7 +750,6 @@ interface StatusWorkspaceRowInnerProps {
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
onCopyBranchName?: () => void;
|
||||
onCopyPath?: () => void;
|
||||
@@ -884,7 +799,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
archiveLabel,
|
||||
archiveStatus = "idle",
|
||||
archivePendingLabel,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onCopyBranchName,
|
||||
onCopyPath,
|
||||
@@ -906,8 +820,6 @@ 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,
|
||||
@@ -919,35 +831,23 @@ function StatusWorkspaceRowInnerContent({
|
||||
const isDesktop = !isTouchPlatform;
|
||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||
|
||||
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||
const accessibilityState = useMemo(
|
||||
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
|
||||
[isSelectionMode, isBulkSelected, selected],
|
||||
);
|
||||
const accessibilityState = useMemo(() => ({ selected }), [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: handleNavigatePress, feedback } = useWorkspaceRowPress({
|
||||
const { onPress: handlePress, 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;
|
||||
@@ -965,24 +865,18 @@ function StatusWorkspaceRowInnerContent({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
});
|
||||
const workspaceRowStyle = getStatusWorkspaceRowStyle({
|
||||
selected: rowSelected,
|
||||
selected,
|
||||
isHovered,
|
||||
inStatusGroup,
|
||||
isDragging,
|
||||
});
|
||||
const backdrop = getSidebarRowBackdrop({
|
||||
isDragging,
|
||||
isHighlighted,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
|
||||
return (
|
||||
<View
|
||||
{...dragAttributes}
|
||||
{...(disableDrag ? null : dragHandleProps?.listeners)}
|
||||
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
|
||||
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
||||
style={styles.workspaceRowContainer}
|
||||
{...hoverHandlers}
|
||||
@@ -1000,7 +894,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -1010,18 +903,16 @@ function StatusWorkspaceRowInnerContent({
|
||||
onTogglePin={onTogglePin}
|
||||
openInFileManagerPath={workspace.workspaceDirectory}
|
||||
disabled={isArchiving}
|
||||
enabled={!isEditingTitle && !isSelectionMode}
|
||||
aria-selected={isSelectionMode ? undefined : selected}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
enabled={!isEditingTitle}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
style={workspaceRowStyle}
|
||||
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
||||
onHighlightChange={setIsHighlighted}
|
||||
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
|
||||
onTouchMove={disableDrag ? undefined : moveDragPress}
|
||||
onPressOut={disableDrag ? undefined : endDragPress}
|
||||
onPress={isEditingTitle ? undefined : handleRowPress}
|
||||
onPressIn={isEditingTitle ? undefined : startDragPress}
|
||||
onTouchMove={isEditingTitle ? undefined : moveDragPress}
|
||||
onPressOut={isEditingTitle ? undefined : endDragPress}
|
||||
onPress={isEditingTitle ? undefined : handlePress}
|
||||
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
||||
>
|
||||
<SidebarWorkspaceRowContent
|
||||
@@ -1033,8 +924,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
backdrop={backdrop}
|
||||
isHovered={isHovered}
|
||||
isLoading={isArchiving}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
||||
@@ -1057,7 +946,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -1091,7 +979,6 @@ function StatusWorkspaceActionSlot({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -1113,7 +1000,6 @@ function StatusWorkspaceActionSlot({
|
||||
onRename?: () => void;
|
||||
onMarkAsRead?: () => void;
|
||||
onMarkAsUnread?: () => void;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
@@ -1148,7 +1034,6 @@ function StatusWorkspaceActionSlot({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { View } from "react-native";
|
||||
@@ -16,13 +15,7 @@ import Animated, {
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import {
|
||||
TOAST_FADE_MS,
|
||||
ToastViewport,
|
||||
useToastHost,
|
||||
type ToastApi,
|
||||
type ToastState,
|
||||
} from "@/components/toast-host";
|
||||
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
|
||||
|
||||
interface SidebarToastCoverage {
|
||||
@@ -32,10 +25,6 @@ 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.
|
||||
@@ -47,10 +36,9 @@ const SidebarAppToastContext = createContext<ToastApi | null>(null);
|
||||
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 || persistentToast !== null;
|
||||
const toastVisible = toast !== null;
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = active;
|
||||
@@ -84,48 +72,19 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
|
||||
|
||||
return (
|
||||
<View style={styles.region}>
|
||||
<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>
|
||||
<SidebarToastCoverageContext.Provider value={coverage}>
|
||||
<ToastApiProvider api={api}>{children}</ToastApiProvider>
|
||||
</SidebarToastCoverageContext.Provider>
|
||||
<ToastViewport
|
||||
toast={toast}
|
||||
onDismiss={dismiss}
|
||||
placement="sidebar"
|
||||
onBottomCoverageChange={handleCoverageChange}
|
||||
/>
|
||||
</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,10 +1,9 @@
|
||||
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { GestureResponderEvent, PressableStateCallbackType } from "react-native";
|
||||
import type { PressableStateCallbackType } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
Archive,
|
||||
CheckSquare,
|
||||
Circle,
|
||||
CircleCheck,
|
||||
Copy,
|
||||
@@ -57,7 +56,6 @@ 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);
|
||||
@@ -71,7 +69,6 @@ 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} />;
|
||||
@@ -127,7 +124,6 @@ export interface SidebarWorkspaceMenuProps {
|
||||
onRename?: () => void;
|
||||
onMarkAsRead?: () => void;
|
||||
onMarkAsUnread?: () => void;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive: () => void;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
@@ -176,7 +172,6 @@ function SidebarWorkspaceMenuItems({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -272,16 +267,6 @@ 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}
|
||||
@@ -309,7 +294,6 @@ export function SidebarWorkspaceMenu({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -356,7 +340,6 @@ export function SidebarWorkspaceMenu({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -390,7 +373,6 @@ export function SidebarWorkspaceContextMenu({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -444,37 +426,11 @@ 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}
|
||||
@@ -498,7 +454,6 @@ export function SidebarWorkspaceContextMenu({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
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 { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||
import { bySizing } from "@/components/ui/control-geometry";
|
||||
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
|
||||
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import {
|
||||
@@ -41,26 +40,19 @@ 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;
|
||||
@@ -88,7 +80,7 @@ export function SidebarWorkspaceRowFrame({
|
||||
workspace={workspace}
|
||||
prHint={workspace.prHint}
|
||||
isDragging={isDragging}
|
||||
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
|
||||
disabled={contextMenuOpen || isEditingTitle}
|
||||
>
|
||||
{children({
|
||||
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
|
||||
@@ -110,8 +102,6 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered,
|
||||
isLoading,
|
||||
isCreating = false,
|
||||
isSelectionMode = false,
|
||||
isBulkSelected = false,
|
||||
shortcutNumber = null,
|
||||
showShortcutBadge = false,
|
||||
reserveIdleStatusIndicatorSpace = true,
|
||||
@@ -129,8 +119,6 @@ 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. */
|
||||
@@ -149,44 +137,33 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
const workspaceBranchTextStyle = useMemo(
|
||||
() => [
|
||||
styles.workspaceBranchText,
|
||||
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
|
||||
isHovered && styles.workspaceBranchTextHovered,
|
||||
isCreating && styles.workspaceBranchTextCreating,
|
||||
],
|
||||
[isHovered, isBulkSelected, isCreating],
|
||||
[isHovered, 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}>
|
||||
{leadingVisual}
|
||||
{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}
|
||||
/>
|
||||
)}
|
||||
<View style={styles.workspaceContentColumn}>
|
||||
<View style={styles.workspaceTitleRow}>
|
||||
{titleEditor ? (
|
||||
@@ -214,7 +191,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
|
||||
{showShortcutBadge && shortcutNumber !== null ? (
|
||||
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
|
||||
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
|
||||
</View>
|
||||
@@ -223,22 +200,6 @@ 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,
|
||||
@@ -421,7 +382,6 @@ export function resolveTrailingActionVisibility({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode = false,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
trailing: SidebarWorkspaceTrailing;
|
||||
@@ -429,7 +389,6 @@ export function resolveTrailingActionVisibility({
|
||||
isHovered: boolean;
|
||||
isTouchPlatform: boolean;
|
||||
showShortcut: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
}): {
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
@@ -439,11 +398,10 @@ export function resolveTrailingActionVisibility({
|
||||
reserveSlotWidth: boolean;
|
||||
} {
|
||||
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
|
||||
const allowRowActions = hasArchiveAction && !isSelectionMode;
|
||||
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||
const showKebab = Boolean(hasArchiveAction && (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 && !(allowRowActions && isTouchPlatform);
|
||||
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
|
||||
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
|
||||
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
|
||||
return {
|
||||
@@ -456,12 +414,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: allowRowActions || hasTrailing,
|
||||
renderSlot: hasArchiveAction || 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 || (allowRowActions && isTouchPlatform),
|
||||
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -578,25 +536,6 @@ 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,7 +16,6 @@ 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";
|
||||
@@ -29,16 +28,10 @@ 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;
|
||||
@@ -52,7 +45,6 @@ export interface ToastState {
|
||||
nativeMessage: string | null;
|
||||
icon?: ReactNode;
|
||||
variant: ToastVariant;
|
||||
layout?: ToastLayout;
|
||||
durationMs: number | null;
|
||||
testID?: string;
|
||||
onDismiss?: () => void;
|
||||
@@ -81,11 +73,6 @@ 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);
|
||||
@@ -149,7 +136,6 @@ export function useToastHost(): {
|
||||
nativeMessage,
|
||||
icon: options?.icon,
|
||||
variant,
|
||||
layout: options?.layout,
|
||||
durationMs,
|
||||
testID: options?.testID,
|
||||
onDismiss: options?.onDismiss,
|
||||
@@ -177,14 +163,11 @@ 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;
|
||||
@@ -249,10 +232,7 @@ export function ToastViewport({
|
||||
|
||||
const handleSidebarLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
const height = event.nativeEvent.layout.height;
|
||||
if (height > 0) {
|
||||
onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET);
|
||||
}
|
||||
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
|
||||
},
|
||||
[onBottomCoverageChange],
|
||||
);
|
||||
@@ -263,41 +243,28 @@ 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={[
|
||||
animatedStyles.container,
|
||||
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
|
||||
]}
|
||||
style={
|
||||
placement === "sidebar"
|
||||
? animatedStyles.sidebarContainer
|
||||
: [
|
||||
animatedStyles.container,
|
||||
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
|
||||
]
|
||||
}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
|
||||
>
|
||||
<View style={styles.widthBoundary} pointerEvents="box-none" collapsable={false}>
|
||||
<View
|
||||
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
>
|
||||
<View
|
||||
style={animatedStyles.surface}
|
||||
testID={toast.testID ?? "app-toast"}
|
||||
@@ -316,35 +283,6 @@ 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,
|
||||
@@ -372,7 +310,6 @@ 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,
|
||||
@@ -407,7 +344,6 @@ const animatedStyles = NativeStyleSheet.create({
|
||||
bottom: SIDEBAR_TOAST_INSET,
|
||||
zIndex: OVERLAY_Z.toast,
|
||||
alignItems: "center",
|
||||
gap: SIDEBAR_TOAST_INSET,
|
||||
},
|
||||
surface: { alignSelf: "center", maxWidth: "100%" },
|
||||
});
|
||||
@@ -436,12 +372,6 @@ 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,6 +25,7 @@ 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";
|
||||
@@ -145,8 +146,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -1139,22 +1138,31 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
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={styles.footer} dataSet={FOOTER_DATASET}>
|
||||
<View style={footerStyle} dataSet={FOOTER_DATASET}>
|
||||
{footer}
|
||||
</View>
|
||||
) : undefined,
|
||||
[footer],
|
||||
[footer, footerStyle],
|
||||
);
|
||||
return (
|
||||
<SheetVisibleFrame footer={footerView} safeAreaInset="frame">
|
||||
<View style={styles.mobileSheetFrame}>{children}</View>
|
||||
<SheetVisibleFrame footer={footerView}>
|
||||
<View style={frameStyle}>{children}</View>
|
||||
</SheetVisibleFrame>
|
||||
);
|
||||
}
|
||||
@@ -1429,7 +1437,6 @@ export function Combobox({
|
||||
footer,
|
||||
keepOpenOnSelect = false,
|
||||
anchorRef,
|
||||
restoreFocusRef,
|
||||
children,
|
||||
}: ComboboxProps): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
@@ -1721,7 +1728,6 @@ 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;
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,64 +0,0 @@
|
||||
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 handleNativeLongPress = useCallback(
|
||||
const handleLongPress = 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, useBottomSheetSafeAreaPaddingStyle } from "./visible-frame";
|
||||
export { SheetVisibleFrame } from "./visible-frame";
|
||||
export { systemBackPress } from "./back-press";
|
||||
export { SheetHostScope } from "./host-scope";
|
||||
|
||||
+1
-118
@@ -1,8 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getBottomSheetSafeAreaPaddingBottom,
|
||||
getBottomSheetVisibleContentHeight,
|
||||
} from "./visible-frame-layout";
|
||||
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
|
||||
|
||||
describe("getBottomSheetVisibleContentHeight", () => {
|
||||
it("stops subtracting the retained keyboard height after the keyboard hides", () => {
|
||||
@@ -16,120 +13,6 @@ 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 @@
|
||||
export interface BottomSheetVisibleContentHeightInput {
|
||||
interface BottomSheetVisibleContentHeightInput {
|
||||
containerHeight: number;
|
||||
contentPosition: number;
|
||||
lowestDetentPosition?: number;
|
||||
@@ -7,28 +7,6 @@ export 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,
|
||||
@@ -40,29 +18,8 @@ export function getBottomSheetVisibleContentHeight({
|
||||
"worklet";
|
||||
if (containerHeight < 0 || handleHeight < 0) return 0;
|
||||
const position = Math.min(contentPosition, lowestDetentPosition ?? contentPosition);
|
||||
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
|
||||
keyboardHeight,
|
||||
isKeyboardVisible,
|
||||
return Math.max(
|
||||
0,
|
||||
containerHeight - position - handleHeight - (isKeyboardVisible ? keyboardHeight : 0),
|
||||
);
|
||||
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,63 +2,21 @@ 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 { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import {
|
||||
getBottomSheetSafeAreaPaddingBottom,
|
||||
getBottomSheetVisibleContentHeight,
|
||||
} from "./visible-frame-layout";
|
||||
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap. */
|
||||
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,
|
||||
@@ -66,24 +24,10 @@ export function SheetVisibleFrame({
|
||||
contentPosition: animatedPosition.get(),
|
||||
lowestDetentPosition: animatedDetentsState.get().detents?.[0],
|
||||
keyboardHeight: keyboard.heightWithinContainer,
|
||||
isKeyboardVisible,
|
||||
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
|
||||
}),
|
||||
paddingBottom: padFrame
|
||||
? getBottomSheetSafeAreaPaddingBottom({
|
||||
keyboardHeight: keyboard.heightWithinContainer,
|
||||
isKeyboardVisible,
|
||||
safeAreaBottom,
|
||||
})
|
||||
: 0,
|
||||
};
|
||||
}, [
|
||||
animatedDetentsState,
|
||||
animatedKeyboardState,
|
||||
animatedLayoutState,
|
||||
animatedPosition,
|
||||
padFrame,
|
||||
safeAreaBottom,
|
||||
]);
|
||||
}, [animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition]);
|
||||
return (
|
||||
<Animated.View style={[styles.frame, visibleStyle]}>
|
||||
<View style={styles.body}>{children}</View>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { forwardRef, type Ref } from "react";
|
||||
import { createContext, forwardRef, useContext, useMemo, useState, type Ref } from "react";
|
||||
import {
|
||||
ScrollView as NativeScrollView,
|
||||
FlatList as NativeFlatList,
|
||||
@@ -12,13 +12,15 @@ import {
|
||||
type NativeViewGestureHandlerProps,
|
||||
} from "react-native-gesture-handler";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
|
||||
import { withContentDrag } from "./content-drag";
|
||||
import {
|
||||
useAttachSheetContentDrag,
|
||||
useIsInsideBottomSheet,
|
||||
type AttachSheetContentDrag,
|
||||
} from "./bottom-sheet-scope";
|
||||
|
||||
// Both libraries forward to the RN FlatList and ScrollView instances. Their published ref types
|
||||
// Both libraries forward to the RN FlatList instance. 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>> },
|
||||
@@ -28,7 +30,7 @@ const HorizontalFlatList = GestureFlatList as unknown as <Item>(
|
||||
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||
function ScrollView(props, ref) {
|
||||
const inSheet = useIsInsideBottomSheet();
|
||||
if (!inSheet) return <PageScrollView {...props} ref={ref} />;
|
||||
if (!inSheet) return <NativeScrollView {...props} ref={ref} />;
|
||||
if (props.horizontal) {
|
||||
return isNative ? (
|
||||
<GestureScrollView {...props} ref={ref} disallowInterruption />
|
||||
@@ -40,11 +42,42 @@ export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||
},
|
||||
);
|
||||
|
||||
const PageScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(NativeScrollView);
|
||||
/**
|
||||
* 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 SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
|
||||
SheetScroll,
|
||||
useAttachSheetContentDrag,
|
||||
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>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
function SheetAwareFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
AgentSnapshotPayload,
|
||||
ForgeSearchItem,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { StagedProviderSwitch } from "@/composer/provider-switch";
|
||||
import type {
|
||||
AttachmentMetadata,
|
||||
ComposerAttachment,
|
||||
@@ -56,6 +62,20 @@ export interface ComposerSendClient {
|
||||
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
) => Promise<unknown>;
|
||||
switchAgentProvider?: (
|
||||
agentId: string,
|
||||
options: {
|
||||
provider: AgentProvider;
|
||||
model?: string | null;
|
||||
modeId?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
providerOptions?: ProviderOptions;
|
||||
text: string;
|
||||
messageId: string;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
) => Promise<{ agent?: AgentSnapshotPayload }>;
|
||||
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
|
||||
requestId: string;
|
||||
file: {
|
||||
@@ -197,6 +217,8 @@ export interface DispatchComposerAgentMessageInput {
|
||||
submission: MessageSubmissionWriter;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
activeTurnId?: string;
|
||||
stagedProviderSwitch?: StagedProviderSwitch | null;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void;
|
||||
}
|
||||
|
||||
export async function dispatchComposerAgentMessage(
|
||||
@@ -212,13 +234,29 @@ export async function dispatchComposerAgentMessage(
|
||||
timestamp: new Date(),
|
||||
images: wirePayload.images,
|
||||
attachments: wirePayload.attachments,
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
|
||||
? { turnId: input.activeTurnId }
|
||||
: {}),
|
||||
});
|
||||
input.submission.begin(input.agentId, userMessage);
|
||||
try {
|
||||
const imagesData = await input.encodeImages(wirePayload.images);
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
const result = await input.client.switchAgentProvider(input.agentId, {
|
||||
provider: input.stagedProviderSwitch.provider,
|
||||
model: input.stagedProviderSwitch.model,
|
||||
modeId: input.stagedProviderSwitch.modeId,
|
||||
thinkingOptionId: input.stagedProviderSwitch.thinkingOptionId,
|
||||
providerOptions: input.stagedProviderSwitch.providerOptions,
|
||||
text: input.text,
|
||||
messageId: clientMessageId,
|
||||
images: imagesData ?? [],
|
||||
attachments: wirePayload.attachments,
|
||||
});
|
||||
input.onProviderSwitchCommitted?.(result.agent);
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
return;
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
messageId: clientMessageId,
|
||||
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
|
||||
@@ -228,6 +266,9 @@ export async function dispatchComposerAgentMessage(
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
} catch (error) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
if (error instanceof AgentProviderSwitchError && error.agent) {
|
||||
input.onProviderSwitchCommitted?.(error.agent);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,12 +16,20 @@ import { formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
import {
|
||||
buildProviderSelectorProviders,
|
||||
buildSelectableProviderSelectorProviders,
|
||||
buildSelectorProvider,
|
||||
type ProviderSelectorProvider,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import { filterSelectableModels } from "@/provider-selection/model-catalog";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useDraftProviderOptions } from "@/hooks/use-draft-provider-options";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
type StagedProviderSwitch,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "@/composer/provider-switch";
|
||||
import { resolveProviderDefinition } from "@/utils/provider-definitions";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
|
||||
import {
|
||||
@@ -102,6 +110,7 @@ import {
|
||||
type AgentProfilePicker,
|
||||
type AgentProfileSeed,
|
||||
type DraftAgentProfileControls,
|
||||
type MaterializedAgentProfile,
|
||||
} from "@/agent-profiles";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
@@ -1006,6 +1015,148 @@ function useAgentOptionControls(
|
||||
);
|
||||
}
|
||||
|
||||
function resolveActiveStagedSwitch(
|
||||
supportsProviderSwitching: boolean,
|
||||
rawStagedSwitch: StagedProviderSwitch | null,
|
||||
liveProvider: string | undefined,
|
||||
): StagedProviderSwitch | null {
|
||||
if (!supportsProviderSwitching || !rawStagedSwitch || !liveProvider) {
|
||||
return null;
|
||||
}
|
||||
return rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
|
||||
}
|
||||
|
||||
function resolveDraftTargetModelId(
|
||||
modelId: string,
|
||||
preferredModel: string | undefined,
|
||||
nextModels: AgentModelDefinition[] | null,
|
||||
): string | null {
|
||||
if (modelId) return modelId;
|
||||
if (preferredModel) return preferredModel;
|
||||
const defaultModel = nextModels?.find((m) => m.isDefault);
|
||||
return defaultModel?.id ?? nextModels?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function resolveDraftThinkingOptionId(
|
||||
targetModelId: string | null,
|
||||
targetModel: AgentModelDefinition | undefined,
|
||||
thinkingByModel: Record<string, string> | undefined,
|
||||
): string | null {
|
||||
const preferred = targetModelId ? thinkingByModel?.[targetModelId] : undefined;
|
||||
if (preferred) return preferred;
|
||||
return targetModel?.defaultThinkingOptionId ?? targetModel?.thinkingOptions?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function resolveDraftModeId(
|
||||
preferredMode: string | undefined,
|
||||
nextEntry: ReturnType<typeof resolveProviderSnapshotEntry>,
|
||||
): string | null {
|
||||
if (preferredMode) return preferredMode;
|
||||
return nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function buildStagedProviderSwitchDraft(input: {
|
||||
nextProvider: string;
|
||||
modelId: string;
|
||||
snapshotEntries: ReturnType<typeof useProvidersSnapshot>["entries"];
|
||||
providerPreferences: ReturnType<typeof useFormPreferences>["preferences"]["providerPreferences"];
|
||||
}): StagedProviderSwitch {
|
||||
const { nextProvider, modelId, snapshotEntries, providerPreferences } = input;
|
||||
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, nextProvider);
|
||||
const nextModels = filterSelectableModels(nextEntry?.models ?? null);
|
||||
const preferred = providerPreferences?.[nextProvider];
|
||||
const targetModelId = resolveDraftTargetModelId(modelId, preferred?.model, nextModels);
|
||||
const targetModel = nextModels?.find((m) => m.id === targetModelId);
|
||||
return {
|
||||
provider: nextProvider,
|
||||
model: targetModelId,
|
||||
thinkingOptionId: resolveDraftThinkingOptionId(
|
||||
targetModelId,
|
||||
targetModel,
|
||||
preferred?.thinkingByModel,
|
||||
),
|
||||
modeId: resolveDraftModeId(preferred?.mode, nextEntry),
|
||||
providerOptions: preferred?.options ? { ...preferred.options } : {},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentModelSelectionWithStagedSwitch(input: {
|
||||
models: AgentModelDefinition[] | null;
|
||||
agent: AgentControlsSlice;
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
}) {
|
||||
const { models, agent, activeStagedSwitch } = input;
|
||||
return resolveAgentModelSelection({
|
||||
models,
|
||||
runtimeModelId: activeStagedSwitch ? null : agent?.runtimeModelId,
|
||||
configuredModelId: activeStagedSwitch ? activeStagedSwitch.model : agent?.model,
|
||||
runtimeThinkingOptionId: activeStagedSwitch ? null : agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: activeStagedSwitch
|
||||
? activeStagedSwitch.thinkingOptionId
|
||||
: agent?.thinkingOptionId,
|
||||
});
|
||||
}
|
||||
|
||||
function buildStagedDraftOptionsParams(input: {
|
||||
serverId: string;
|
||||
agentCwd: string | null | undefined;
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
getProvider: () => AgentProvider | null;
|
||||
modelId: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
}) {
|
||||
const { serverId, agentCwd, activeStagedSwitch, getProvider, modelId, thinkingOptionId } = input;
|
||||
return {
|
||||
serverId: activeStagedSwitch ? serverId : null,
|
||||
provider: activeStagedSwitch ? activeStagedSwitch.provider : null,
|
||||
getProvider,
|
||||
cwd: agentCwd,
|
||||
modeId: activeStagedSwitch?.modeId ?? null,
|
||||
modelId,
|
||||
thinkingOptionId,
|
||||
initialOptions: activeStagedSwitch?.providerOptions,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentOptionControlsForComposer(input: {
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
stagedControls: ComposerOptionControls | null | undefined;
|
||||
liveOptionControls: ComposerOptionControls;
|
||||
onSetOption: (key: string, value: unknown) => void;
|
||||
}): ComposerOptionControls {
|
||||
const { activeStagedSwitch, stagedControls, liveOptionControls, onSetOption } = input;
|
||||
if (!activeStagedSwitch) {
|
||||
return liveOptionControls;
|
||||
}
|
||||
if (stagedControls) {
|
||||
return { ...stagedControls, onSetOption };
|
||||
}
|
||||
return { controls: [], options: activeStagedSwitch.providerOptions, onSetOption };
|
||||
}
|
||||
|
||||
function resolveControlledAgentControlsProps(input: {
|
||||
effectiveProvider: string | undefined;
|
||||
liveProvider: string;
|
||||
selectedModelId: string | null;
|
||||
selectedThinkingId: string | null;
|
||||
thinkingOptions: AgentControlOption[];
|
||||
supportsProviderSwitching: boolean;
|
||||
handleSelectProviderAndModel: (provider: string, modelId: string) => void;
|
||||
snapshotIsLoading: boolean;
|
||||
selectedProviderIsLoading: boolean;
|
||||
}) {
|
||||
return {
|
||||
provider: input.effectiveProvider ?? input.liveProvider,
|
||||
selectedModelId: input.selectedModelId ?? undefined,
|
||||
selectedThinkingOptionId: input.selectedThinkingId ?? undefined,
|
||||
thinkingOptions: input.thinkingOptions.length > 0 ? input.thinkingOptions : undefined,
|
||||
onSelectProviderAndModel: input.supportsProviderSwitching
|
||||
? input.handleSelectProviderAndModel
|
||||
: undefined,
|
||||
isModelLoading: input.snapshotIsLoading || input.selectedProviderIsLoading,
|
||||
};
|
||||
}
|
||||
|
||||
export const AgentControls = memo(function AgentControls({
|
||||
showToolbar,
|
||||
agentId,
|
||||
@@ -1013,15 +1164,22 @@ export const AgentControls = memo(function AgentControls({
|
||||
onDropdownClose,
|
||||
isCompactLayout,
|
||||
}: AgentControlsProps) {
|
||||
const { updatePreferences } = useFormPreferences();
|
||||
const { preferences, updatePreferences } = useFormPreferences();
|
||||
const agent = useSessionStore(
|
||||
useShallow((state) => selectAgentControlsSlice(state, serverId, agentId)),
|
||||
);
|
||||
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
|
||||
const supportsProviderSwitching = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
|
||||
);
|
||||
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
|
||||
const activeStagedSwitch = resolveActiveStagedSwitch(
|
||||
supportsProviderSwitching,
|
||||
rawStagedSwitch,
|
||||
agent?.provider,
|
||||
);
|
||||
const toast = useToast();
|
||||
const modeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
const liveModeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
|
||||
const {
|
||||
entries: snapshotEntries,
|
||||
@@ -1031,24 +1189,34 @@ export const AgentControls = memo(function AgentControls({
|
||||
refetchIfStale: refetchSnapshotIfStale,
|
||||
} = useProvidersSnapshot(serverId, { cwd: agent?.cwd });
|
||||
|
||||
const effectiveProvider = activeStagedSwitch?.provider ?? agent?.provider;
|
||||
const effectiveProviderRef = useRef<AgentProvider | null>(effectiveProvider ?? null);
|
||||
effectiveProviderRef.current = effectiveProvider ?? null;
|
||||
|
||||
const snapshotSelectedEntry = useMemo(
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, agent?.provider),
|
||||
[snapshotEntries, agent?.provider],
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, effectiveProvider),
|
||||
[snapshotEntries, effectiveProvider],
|
||||
);
|
||||
|
||||
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
|
||||
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
|
||||
|
||||
const agentProviderDefinitions = useMemo(
|
||||
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
|
||||
[agent?.provider, snapshotEntries],
|
||||
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
|
||||
[effectiveProvider, snapshotEntries],
|
||||
);
|
||||
|
||||
const agentProviderModels = useMemo(
|
||||
() => buildAgentProviderModels(agent?.provider, models),
|
||||
[agent?.provider, models],
|
||||
() => buildAgentProviderModels(effectiveProvider, models),
|
||||
[effectiveProvider, models],
|
||||
);
|
||||
const agentModelSelectorProviders = useMemo(() => {
|
||||
if (supportsProviderSwitching && snapshotEntries && snapshotEntries.length > 0) {
|
||||
const selectable = buildSelectableProviderSelectorProviders(snapshotEntries, {
|
||||
selectedProvider: effectiveProvider ?? null,
|
||||
});
|
||||
if (selectable.length > 0) return selectable;
|
||||
}
|
||||
if (snapshotSelectedEntry) {
|
||||
return [buildSelectorProvider(snapshotSelectedEntry)];
|
||||
}
|
||||
@@ -1056,14 +1224,19 @@ export const AgentControls = memo(function AgentControls({
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modelsByProvider: agentProviderModels,
|
||||
});
|
||||
}, [agentProviderDefinitions, agentProviderModels, snapshotSelectedEntry]);
|
||||
}, [
|
||||
agentProviderDefinitions,
|
||||
agentProviderModels,
|
||||
effectiveProvider,
|
||||
snapshotEntries,
|
||||
snapshotSelectedEntry,
|
||||
supportsProviderSwitching,
|
||||
]);
|
||||
|
||||
const modelSelection = resolveAgentModelSelection({
|
||||
const modelSelection = resolveAgentModelSelectionWithStagedSwitch({
|
||||
models,
|
||||
runtimeModelId: agent?.runtimeModelId,
|
||||
configuredModelId: agent?.model,
|
||||
runtimeThinkingOptionId: agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: agent?.thinkingOptionId,
|
||||
agent,
|
||||
activeStagedSwitch,
|
||||
});
|
||||
|
||||
const modelOptions = useMemo<AgentControlOption[]>(() => {
|
||||
@@ -1080,8 +1253,87 @@ export const AgentControls = memo(function AgentControls({
|
||||
const agentProvider = agent?.provider;
|
||||
const activeModelId = modelSelection.activeModelId;
|
||||
|
||||
const stagedModeOptions = useMemo<AgentMode[]>(() => {
|
||||
if (!activeStagedSwitch || !snapshotSelectedEntry?.modes) return [];
|
||||
return snapshotSelectedEntry.modes.map((mode) => ({
|
||||
id: mode.id,
|
||||
label: mode.label,
|
||||
description: mode.description ?? "",
|
||||
}));
|
||||
}, [activeStagedSwitch, snapshotSelectedEntry?.modes]);
|
||||
|
||||
const handleSelectStagedMode = useCallback(
|
||||
(modeId: string) => {
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
modeId,
|
||||
}));
|
||||
},
|
||||
[agentId, serverId],
|
||||
);
|
||||
|
||||
const modeControl = useMemo<AgentModeControlValue | null>(() => {
|
||||
if (!activeStagedSwitch) return liveModeControl;
|
||||
if (stagedModeOptions.length === 0) return null;
|
||||
return {
|
||||
provider: activeStagedSwitch.provider,
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modeOptions: stagedModeOptions,
|
||||
selectedModeId:
|
||||
activeStagedSwitch.modeId ??
|
||||
snapshotSelectedEntry?.defaultModeId ??
|
||||
stagedModeOptions[0]?.id ??
|
||||
null,
|
||||
onSelectMode: handleSelectStagedMode,
|
||||
disabled: !client,
|
||||
};
|
||||
}, [
|
||||
activeStagedSwitch,
|
||||
agentProviderDefinitions,
|
||||
client,
|
||||
handleSelectStagedMode,
|
||||
liveModeControl,
|
||||
snapshotSelectedEntry?.defaultModeId,
|
||||
stagedModeOptions,
|
||||
]);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
|
||||
const getStagedProvider = useCallback(
|
||||
() => (activeStagedSwitch ? effectiveProviderRef.current : null),
|
||||
[activeStagedSwitch],
|
||||
);
|
||||
const stagedDraftOptions = useDraftProviderOptions(
|
||||
buildStagedDraftOptionsParams({
|
||||
serverId,
|
||||
agentCwd: agent?.cwd,
|
||||
activeStagedSwitch,
|
||||
getProvider: getStagedProvider,
|
||||
modelId: modelSelection.activeModelId,
|
||||
thinkingOptionId: modelSelection.selectedThinkingId,
|
||||
}),
|
||||
);
|
||||
|
||||
const handleSelectModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
const nextModel = models?.find((candidate) => candidate.id === modelId);
|
||||
const preferredThinking =
|
||||
preferences.providerPreferences?.[activeStagedSwitch.provider]?.thinkingByModel?.[
|
||||
modelId
|
||||
];
|
||||
const nextThinking =
|
||||
preferredThinking ??
|
||||
nextModel?.defaultThinkingOptionId ??
|
||||
nextModel?.thinkingOptions?.[0]?.id ??
|
||||
null;
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
model: modelId,
|
||||
thinkingOptionId: nextThinking,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1099,23 +1351,121 @@ export const AgentControls = memo(function AgentControls({
|
||||
toast.error(toErrorMessage(error));
|
||||
}
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
const handleSelectCommandCenterModel = useCallback(
|
||||
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
|
||||
[handleSelectModel],
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
models,
|
||||
preferences.providerPreferences,
|
||||
serverId,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
);
|
||||
|
||||
// A running agent is one provider's process, so only that provider's profiles
|
||||
// can apply to it.
|
||||
const profileProviders = useMemo(() => (agentProvider ? [agentProvider] : []), [agentProvider]);
|
||||
const handleSelectProviderAndModel = useCallback(
|
||||
(nextProvider: string, modelId: string) => {
|
||||
if (!agentProvider) return;
|
||||
if (nextProvider === agentProvider) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
const liveModelId = agent?.runtimeModelId ?? agent?.model ?? null;
|
||||
if (modelId && modelId !== liveModelId) {
|
||||
void handleSelectModel(modelId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!supportsProviderSwitching) return;
|
||||
useStagedProviderSwitchStore.getState().stage(
|
||||
serverId,
|
||||
agentId,
|
||||
buildStagedProviderSwitchDraft({
|
||||
nextProvider,
|
||||
modelId,
|
||||
snapshotEntries,
|
||||
providerPreferences: preferences.providerPreferences,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[
|
||||
agent?.model,
|
||||
agent?.runtimeModelId,
|
||||
agentId,
|
||||
agentProvider,
|
||||
handleSelectModel,
|
||||
preferences.providerPreferences,
|
||||
serverId,
|
||||
snapshotEntries,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSelectCommandCenterModel = useCallback(
|
||||
(provider: AgentProvider, modelId: string) => {
|
||||
if (supportsProviderSwitching) {
|
||||
handleSelectProviderAndModel(provider, modelId);
|
||||
return;
|
||||
}
|
||||
void handleSelectModel(modelId);
|
||||
},
|
||||
[handleSelectModel, handleSelectProviderAndModel, supportsProviderSwitching],
|
||||
);
|
||||
|
||||
const handleStageAgentProfileSwitch = useCallback(
|
||||
(resolved: MaterializedAgentProfile) => {
|
||||
if (!supportsProviderSwitching) return;
|
||||
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, resolved.provider);
|
||||
const modeIds = resolveSnapshotModeIds(nextEntry);
|
||||
const validModeId =
|
||||
resolved.modeId && (!modeIds || modeIds.includes(resolved.modeId))
|
||||
? resolved.modeId
|
||||
: (nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, agentId, {
|
||||
provider: resolved.provider,
|
||||
model: resolved.modelId ?? null,
|
||||
modeId: validModeId,
|
||||
thinkingOptionId: resolved.thinkingOptionId ?? null,
|
||||
providerOptions: resolved.options ? { ...resolved.options } : {},
|
||||
});
|
||||
stagedDraftOptions.applyProfile({
|
||||
provider: resolved.provider,
|
||||
options: resolved.options ?? {},
|
||||
});
|
||||
},
|
||||
[agentId, serverId, snapshotEntries, stagedDraftOptions, supportsProviderSwitching],
|
||||
);
|
||||
|
||||
const handleClearStagedSwitchOnProfile = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const profileProviders = useMemo(() => {
|
||||
if (supportsProviderSwitching) {
|
||||
return agentModelSelectorProviders.map((entry) => entry.id);
|
||||
}
|
||||
return agentProvider ? [agentProvider] : [];
|
||||
}, [agentModelSelectorProviders, agentProvider, supportsProviderSwitching]);
|
||||
const profileModeIds = useMemo(
|
||||
() => resolveSnapshotModeIds(snapshotSelectedEntry),
|
||||
[snapshotSelectedEntry],
|
||||
);
|
||||
const profileTarget = useMemo<AgentProfileApplyTarget>(
|
||||
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
|
||||
[agentId, profileModeIds],
|
||||
() => ({
|
||||
kind: "agent",
|
||||
agentId,
|
||||
availableModeIds: profileModeIds,
|
||||
currentProvider: agentProvider,
|
||||
onApplySameProvider: handleClearStagedSwitchOnProfile,
|
||||
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
|
||||
}),
|
||||
[
|
||||
agentId,
|
||||
agentProvider,
|
||||
handleClearStagedSwitchOnProfile,
|
||||
handleStageAgentProfileSwitch,
|
||||
profileModeIds,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
);
|
||||
const agentProfiles = useAgentProfilePicker({
|
||||
serverId,
|
||||
@@ -1128,6 +1478,13 @@ export const AgentControls = memo(function AgentControls({
|
||||
|
||||
const handleSelectThinkingOption = useCallback(
|
||||
(thinkingOptionId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
thinkingOptionId,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1155,11 +1512,28 @@ export const AgentControls = memo(function AgentControls({
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
|
||||
[
|
||||
activeModelId,
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSetOption = useCallback(
|
||||
(key: string, value: unknown) => {
|
||||
if (activeStagedSwitch) {
|
||||
stagedDraftOptions.setOption(key, value);
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
providerOptions: { ...current.providerOptions, [key]: value },
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1181,10 +1555,29 @@ export const AgentControls = memo(function AgentControls({
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
stagedDraftOptions,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
);
|
||||
|
||||
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const agentOptionControls = useMemo<ComposerOptionControls>(
|
||||
() =>
|
||||
resolveAgentOptionControlsForComposer({
|
||||
activeStagedSwitch,
|
||||
stagedControls: stagedDraftOptions.optionControls,
|
||||
liveOptionControls,
|
||||
onSetOption: handleSetOption,
|
||||
}),
|
||||
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
|
||||
);
|
||||
|
||||
// The agent's composer exists apart from this component; while this is mounted, prompt
|
||||
// commands go through the input the user is typing in.
|
||||
@@ -1208,12 +1601,12 @@ export const AgentControls = memo(function AgentControls({
|
||||
() => ({
|
||||
serverId,
|
||||
ownerKey: agentId,
|
||||
provider: agentProvider,
|
||||
provider: effectiveProvider,
|
||||
providerDefinitions: modeProviderDefinitions,
|
||||
profiles: agentProfiles,
|
||||
models: {
|
||||
providers: agentModelSelectorProviders,
|
||||
selectedProvider: agentProvider,
|
||||
selectedProvider: effectiveProvider,
|
||||
selectedModelId: activeModelId,
|
||||
select: handleSelectCommandCenterModel,
|
||||
},
|
||||
@@ -1232,7 +1625,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
client,
|
||||
agentId,
|
||||
agentModelSelectorProviders,
|
||||
agentProvider,
|
||||
effectiveProvider,
|
||||
commandCenterModes,
|
||||
handleSelectCommandCenterModel,
|
||||
handleSelectThinkingOption,
|
||||
@@ -1252,8 +1645,8 @@ export const AgentControls = memo(function AgentControls({
|
||||
);
|
||||
|
||||
const handleModelSelectorOpen = useCallback(() => {
|
||||
refetchSnapshotIfStale(agentProvider);
|
||||
}, [agentProvider, refetchSnapshotIfStale]);
|
||||
refetchSnapshotIfStale(supportsProviderSwitching ? undefined : effectiveProvider);
|
||||
}, [effectiveProvider, refetchSnapshotIfStale, supportsProviderSwitching]);
|
||||
|
||||
const handleRetryModelProvider = useCallback(
|
||||
(provider: AgentProvider) => {
|
||||
@@ -1266,6 +1659,18 @@ export const AgentControls = memo(function AgentControls({
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedControlProps = resolveControlledAgentControlsProps({
|
||||
effectiveProvider,
|
||||
liveProvider: agent.provider,
|
||||
selectedModelId: modelSelection.activeModelId,
|
||||
selectedThinkingId: modelSelection.selectedThinkingId,
|
||||
thinkingOptions,
|
||||
supportsProviderSwitching,
|
||||
handleSelectProviderAndModel,
|
||||
snapshotIsLoading,
|
||||
selectedProviderIsLoading,
|
||||
});
|
||||
|
||||
return (
|
||||
<ComposerModelProvider value={composer}>
|
||||
{commandCenterRegistration}
|
||||
@@ -1273,21 +1678,17 @@ export const AgentControls = memo(function AgentControls({
|
||||
<>
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
provider={agent.provider}
|
||||
{...resolvedControlProps}
|
||||
modelSelectorProviders={agentModelSelectorProviders}
|
||||
modelOptions={modelOptions}
|
||||
selectedModelId={modelSelection.activeModelId ?? undefined}
|
||||
onSelectModel={handleSelectModel}
|
||||
agentProfiles={agentProfiles}
|
||||
onApplyAgentProfile={agentProfiles?.applyProfile}
|
||||
onEditAgentProfiles={handleEditAgentProfiles}
|
||||
onCreateAgentProfile={profileActions.create}
|
||||
onEditAgentProfile={profileActions.edit}
|
||||
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
|
||||
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
|
||||
onSelectThinkingOption={handleSelectThinkingOption}
|
||||
optionControls={agentOptionControls}
|
||||
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
|
||||
onModelSelectorOpen={handleModelSelectorOpen}
|
||||
onRetryModelProvider={handleRetryModelProvider}
|
||||
isRetryingModelProvider={snapshotIsRefreshing}
|
||||
|
||||
@@ -9,6 +9,15 @@ import { useStore } from "zustand";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
useStagedProviderSwitch,
|
||||
} from "@/composer/provider-switch";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { resolveProviderLabel } from "@/utils/provider-definitions";
|
||||
import {
|
||||
View,
|
||||
Pressable,
|
||||
@@ -48,6 +57,7 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
ArrowUp,
|
||||
Square,
|
||||
Pencil,
|
||||
@@ -298,16 +308,29 @@ function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: bo
|
||||
|
||||
const EMPTY_METRICS: AgentMetric[] = [];
|
||||
|
||||
const EMPTY_AGENT_STATE = {
|
||||
provider: null,
|
||||
status: null,
|
||||
contextWindowMaxTokens: null,
|
||||
contextWindowUsedTokens: null,
|
||||
totalCostUsd: null,
|
||||
sessionMetrics: EMPTY_METRICS,
|
||||
model: null,
|
||||
};
|
||||
|
||||
function buildAgentStateSelector(serverId: string, agentId: string) {
|
||||
return (state: ReturnType<typeof useSessionStore.getState>) => {
|
||||
const agent = state.sessions[serverId]?.agents?.get(agentId) ?? null;
|
||||
if (!agent) return EMPTY_AGENT_STATE;
|
||||
const usage = agent.lastUsage;
|
||||
return {
|
||||
status: agent?.status ?? null,
|
||||
contextWindowMaxTokens: agent?.lastUsage?.contextWindowMaxTokens ?? null,
|
||||
contextWindowUsedTokens: agent?.lastUsage?.contextWindowUsedTokens ?? null,
|
||||
totalCostUsd: agent?.lastUsage?.totalCostUsd ?? null,
|
||||
sessionMetrics: agent?.sessionMetrics ?? EMPTY_METRICS,
|
||||
model: agent?.model ?? null,
|
||||
provider: agent.provider ?? null,
|
||||
status: agent.status ?? null,
|
||||
contextWindowMaxTokens: usage?.contextWindowMaxTokens ?? null,
|
||||
contextWindowUsedTokens: usage?.contextWindowUsedTokens ?? null,
|
||||
totalCostUsd: usage?.totalCostUsd ?? null,
|
||||
sessionMetrics: agent.sessionMetrics ?? EMPTY_METRICS,
|
||||
model: agent.model ?? null,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1351,6 +1374,36 @@ function ComposerContentImpl({
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
|
||||
const agentState = useSessionStore(useShallow(buildAgentStateSelector(serverId, agentId)));
|
||||
const supportsProviderSwitching = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
|
||||
);
|
||||
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
|
||||
const stagedSwitch =
|
||||
supportsProviderSwitching &&
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider !== agentState.provider
|
||||
? rawStagedSwitch
|
||||
: null;
|
||||
const { entries: providerSnapshotEntries } = useProvidersSnapshot(serverId, { cwd });
|
||||
const stagedProviderLabel = stagedSwitch
|
||||
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider === agentState.provider
|
||||
) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}
|
||||
}, [agentId, agentState.provider, rawStagedSwitch, serverId]);
|
||||
|
||||
const handleCancelStagedSwitch = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
setSendError(null);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const queuedMessagesRaw = useSessionStore((state) =>
|
||||
state.sessions[serverId]?.queuedMessages?.get(agentId),
|
||||
@@ -1709,6 +1762,12 @@ function ComposerContentImpl({
|
||||
if (!client) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const sessionState = useSessionStore.getState().sessions[serverId];
|
||||
const liveProvider = sessionState?.agents.get(targetAgentId)?.provider;
|
||||
const canSwitch = sessionState?.serverInfo?.features?.providerSwitching === true;
|
||||
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
|
||||
const stagedProviderSwitch =
|
||||
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
@@ -1719,6 +1778,16 @@ function ComposerContentImpl({
|
||||
}),
|
||||
encodeImages,
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
stagedProviderSwitch,
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
clearStagedProviderSwitch(serverId, targetAgentId);
|
||||
if (agent) {
|
||||
getHostRuntimeStore().tryAcceptAgentSnapshot(
|
||||
serverId,
|
||||
normalizeAgentSnapshot(agent, serverId),
|
||||
);
|
||||
}
|
||||
},
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
@@ -1803,7 +1872,7 @@ function ComposerContentImpl({
|
||||
attachments: outgoingAttachments,
|
||||
hasExternalContent,
|
||||
allowEmptySubmit,
|
||||
forceSend,
|
||||
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
|
||||
submitBehavior,
|
||||
isAgentRunning,
|
||||
// Parent-managed submits are still valid submit paths even when the
|
||||
@@ -1845,6 +1914,7 @@ function ComposerContentImpl({
|
||||
queueMessage,
|
||||
setSelectedAttachments,
|
||||
replaceUserInput,
|
||||
stagedSwitch,
|
||||
submitBehavior,
|
||||
submitMessage,
|
||||
t,
|
||||
@@ -2566,6 +2636,31 @@ function ComposerContentImpl({
|
||||
? t("composer.github.searching")
|
||||
: t("composer.github.noResults");
|
||||
|
||||
const stagedSwitchBannerNode = useMemo(() => {
|
||||
if (!stagedSwitch || !stagedProviderLabel) return null;
|
||||
const message = isAgentRunning
|
||||
? t("composer.providerSwitch.switchingAfterTurn", { provider: stagedProviderLabel })
|
||||
: t("composer.providerSwitch.switchingNextMessage", { provider: stagedProviderLabel });
|
||||
return (
|
||||
<View style={styles.stagedSwitchBanner} testID="staged-provider-switch-banner">
|
||||
<View style={styles.stagedSwitchLabelRow}>
|
||||
<ThemedArrowRightLeft size={ICON_SIZE.sm} uniProps={iconForegroundMutedMapping} />
|
||||
<Text style={styles.stagedSwitchText} numberOfLines={1}>
|
||||
{message}
|
||||
</Text>
|
||||
</View>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={handleCancelStagedSwitch}
|
||||
testID="cancel-staged-provider-switch"
|
||||
>
|
||||
{t("common.actions.cancel")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}, [handleCancelStagedSwitch, isAgentRunning, stagedProviderLabel, stagedSwitch, t]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ComposerKeyboardRegistration
|
||||
@@ -2591,6 +2686,7 @@ function ComposerContentImpl({
|
||||
>
|
||||
<View style={inputAreaContentStyle}>
|
||||
{isFullscreen ? null : queueList}
|
||||
{isFullscreen ? null : stagedSwitchBannerNode}
|
||||
{!isFullscreen && sendErrorNode}
|
||||
|
||||
<ComposerAutocompleteBinding
|
||||
@@ -2846,9 +2942,35 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
queueSendButton: {
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
stagedSwitchBanner: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
paddingLeft: theme.spacing[3],
|
||||
paddingRight: theme.spacing[1.5],
|
||||
paddingVertical: theme.spacing[1],
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
stagedSwitchLabelRow: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
stagedSwitchText: {
|
||||
flex: 1,
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
})) as unknown as Record<string, object>;
|
||||
|
||||
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
|
||||
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export {
|
||||
clearStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
type StagedProviderSwitch,
|
||||
} from "./store";
|
||||
@@ -0,0 +1,462 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import { dispatchComposerAgentMessage } from "@/composer/actions";
|
||||
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
|
||||
import { collapseTurns } from "@/agent-stream/turn-collapse/model";
|
||||
import {
|
||||
processAgentStreamEvent,
|
||||
processTimelineResponse,
|
||||
} from "@/timeline/session-stream-reducers";
|
||||
import { ReplicaCache } from "@/runtime/replica-cache";
|
||||
import type { ReplicaRow, ReplicaRowStore } from "@/runtime/replica-cache/row-store";
|
||||
import { HostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ProviderSwitchItem, StreamItem, UserMessageItem } from "@/types/stream";
|
||||
import { getStagedProviderSwitch, useStagedProviderSwitchStore } from "./index";
|
||||
|
||||
function createInMemoryRowStore(): ReplicaRowStore {
|
||||
const rows = new Map<string, ReplicaRow>();
|
||||
const keyOf = (r: { serverId: string; kind: string; id: string }) =>
|
||||
`${r.serverId}:${r.kind}:${r.id}`;
|
||||
return {
|
||||
async open() {},
|
||||
async read(serverId, kinds, ids) {
|
||||
const kindSet = new Set(kinds);
|
||||
const idSet = ids ? new Set(ids) : null;
|
||||
return [...rows.values()].filter(
|
||||
(r) => r.serverId === serverId && kindSet.has(r.kind) && (!idSet || idSet.has(r.id)),
|
||||
);
|
||||
},
|
||||
async readAll() {
|
||||
const byServer = new Map<string, ReplicaRow[]>();
|
||||
for (const row of rows.values()) {
|
||||
const list = byServer.get(row.serverId) ?? [];
|
||||
list.push(row);
|
||||
byServer.set(row.serverId, list);
|
||||
}
|
||||
return [...byServer.entries()].map(([serverId, list]) => ({ serverId, rows: list }));
|
||||
},
|
||||
async apply(changes) {
|
||||
for (const del of changes.deletes) rows.delete(keyOf(del));
|
||||
for (const up of changes.upserts) rows.set(keyOf(up), up);
|
||||
},
|
||||
async deleteHost(serverId) {
|
||||
for (const [k, v] of rows) if (v.serverId === serverId) rows.delete(k);
|
||||
},
|
||||
async renameHost() {},
|
||||
async clear() {
|
||||
rows.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const TS = "2026-11-25T10:00:00.000Z";
|
||||
|
||||
function agentSnapshot(provider: string): AgentSnapshotPayload {
|
||||
return {
|
||||
id: "agent-1",
|
||||
provider,
|
||||
cwd: "/repo",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
createdAt: TS,
|
||||
updatedAt: TS,
|
||||
lastUserMessageAt: null,
|
||||
status: "idle",
|
||||
capabilities: {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: false,
|
||||
supportsMcpServers: false,
|
||||
supportsReasoningStream: false,
|
||||
supportsToolInvocations: true,
|
||||
supportsRewindConversation: true,
|
||||
supportsRewindFiles: false,
|
||||
supportsRewindBoth: false,
|
||||
},
|
||||
currentModeId: null,
|
||||
availableModes: [],
|
||||
pendingPermissions: [],
|
||||
persistence: null,
|
||||
title: null,
|
||||
labels: {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("app provider switching integration", () => {
|
||||
beforeEach(() => {
|
||||
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
|
||||
});
|
||||
|
||||
it("dispatches switchAgentProvider when staged and handles pre-commit vs post-commit failures", async () => {
|
||||
const committed: Array<AgentSnapshotPayload | undefined> = [];
|
||||
const sendAgentMessage = vi.fn().mockResolvedValue(undefined);
|
||||
const switchAgentProvider = vi.fn().mockResolvedValue({ agent: agentSnapshot("codex") });
|
||||
const submission = {
|
||||
begin: vi.fn(),
|
||||
accept: vi.fn(),
|
||||
reject: vi.fn(),
|
||||
};
|
||||
|
||||
const staged = {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: {},
|
||||
};
|
||||
|
||||
// Success path
|
||||
await dispatchComposerAgentMessage({
|
||||
client: {
|
||||
sendAgentMessage,
|
||||
switchAgentProvider,
|
||||
uploadFile: vi.fn(),
|
||||
},
|
||||
agentId: "agent-1",
|
||||
text: "Continue with Codex",
|
||||
attachments: [],
|
||||
encodeImages: async () => [],
|
||||
submission,
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => committed.push(agent),
|
||||
});
|
||||
|
||||
expect(sendAgentMessage).not.toHaveBeenCalled();
|
||||
expect(switchAgentProvider).toHaveBeenCalledTimes(1);
|
||||
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
|
||||
expect(submission.accept).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Pre-commit failure: onProviderSwitchCommitted MUST NOT run
|
||||
committed.length = 0;
|
||||
switchAgentProvider.mockRejectedValueOnce(new Error("Codex CLI unavailable"));
|
||||
await expect(
|
||||
dispatchComposerAgentMessage({
|
||||
client: { sendAgentMessage, switchAgentProvider, uploadFile: vi.fn() },
|
||||
agentId: "agent-1",
|
||||
text: "Retry",
|
||||
attachments: [],
|
||||
encodeImages: async () => [],
|
||||
submission,
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => committed.push(agent),
|
||||
}),
|
||||
).rejects.toThrow("Codex CLI unavailable");
|
||||
expect(committed).toEqual([]);
|
||||
|
||||
// Post-commit start failure (AgentProviderSwitchError with .agent): MUST commit live agent snapshot
|
||||
switchAgentProvider.mockRejectedValueOnce(
|
||||
new AgentProviderSwitchError("Rate limited", agentSnapshot("codex")),
|
||||
);
|
||||
await expect(
|
||||
dispatchComposerAgentMessage({
|
||||
client: { sendAgentMessage, switchAgentProvider, uploadFile: vi.fn() },
|
||||
agentId: "agent-1",
|
||||
text: "Retry 2",
|
||||
attachments: [],
|
||||
encodeImages: async () => [],
|
||||
submission,
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => committed.push(agent),
|
||||
}),
|
||||
).rejects.toThrow("Rate limited");
|
||||
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
|
||||
});
|
||||
|
||||
it("advances activeSegmentStartSeq immediately on live provider_switch events and scopes rewind eligibility", () => {
|
||||
const preSwitchPrompt: UserMessageItem = {
|
||||
kind: "user_message",
|
||||
id: "u1",
|
||||
messageId: "u1",
|
||||
text: "Claude prompt",
|
||||
timestamp: new Date(TS),
|
||||
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
|
||||
};
|
||||
|
||||
const liveResult = processAgentStreamEvent({
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
item: {
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromModel: "sonnet",
|
||||
toModel: "gpt-5.4",
|
||||
fromSessionId: "s1",
|
||||
toSessionId: null,
|
||||
context: { includedItems: 2, truncated: false, charCount: 100, budgetChars: 100_000 },
|
||||
},
|
||||
},
|
||||
seq: 3,
|
||||
epoch: "ep-1",
|
||||
currentTail: [preSwitchPrompt],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "ep-1", startSeq: 1, endSeq: 2 },
|
||||
hasAuthoritativeBaseline: true,
|
||||
timestamp: new Date(TS),
|
||||
});
|
||||
|
||||
expect(liveResult.cursor?.activeSegmentStartSeq).toBe(3);
|
||||
expect(liveResult.tail.some((item) => item.kind === "provider_switch")).toBe(true);
|
||||
|
||||
// Pre-switch prompt (anchor 1 <= 3) is NOT rewindable; post-switch prompt (anchor 4 > 3) IS!
|
||||
expect(
|
||||
isPromptInActiveSegment(
|
||||
preSwitchPrompt.timelineCursor,
|
||||
liveResult.cursor?.activeSegmentStartSeq,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPromptInActiveSegment({ seq: 4, anchorSeq: 4 }, liveResult.cursor?.activeSegmentStartSeq),
|
||||
).toBe(true);
|
||||
|
||||
// Timeline page response also propagates activeSegmentStartSeq
|
||||
const pageResult = processTimelineResponse({
|
||||
payload: {
|
||||
agentId: "agent-1",
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
reset: true,
|
||||
epoch: "ep-1",
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { seq: 1 },
|
||||
endCursor: { seq: 4 },
|
||||
hasNewer: false,
|
||||
hasOlder: false,
|
||||
activeSegmentStartSeq: 3,
|
||||
entries: [
|
||||
{
|
||||
seqStart: 1,
|
||||
seqEnd: 1,
|
||||
provider: "claude",
|
||||
timestamp: TS,
|
||||
item: { type: "user_message", text: "Claude prompt", messageId: "u1" },
|
||||
},
|
||||
{
|
||||
seqStart: 3,
|
||||
seqEnd: 3,
|
||||
provider: "codex",
|
||||
timestamp: TS,
|
||||
item: {
|
||||
type: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
context: { includedItems: 1, truncated: false, charCount: 50, budgetChars: 100_000 },
|
||||
},
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: false,
|
||||
initRequestDirection: "tail",
|
||||
sendingClientMessageIds: [],
|
||||
});
|
||||
|
||||
expect(pageResult.cursor?.activeSegmentStartSeq).toBe(3);
|
||||
});
|
||||
|
||||
it("persists provider_switch items and activeSegmentStartSeq in ReplicaCache and keeps markers visible when turns collapse", async () => {
|
||||
const rowStore = createInMemoryRowStore();
|
||||
const cache = new ReplicaCache(rowStore);
|
||||
cache.setHosts(["srv-1"]);
|
||||
const switchItem: ProviderSwitchItem = {
|
||||
kind: "provider_switch",
|
||||
id: "provider_switch:ep-1:3",
|
||||
timestamp: new Date(TS),
|
||||
timelineCursor: { epoch: "ep-1", seq: 3, anchorSeq: 3 },
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
fromModel: "sonnet",
|
||||
toModel: "gpt-5.4",
|
||||
fromSessionId: "s1",
|
||||
toSessionId: null,
|
||||
context: {
|
||||
includedItems: 2,
|
||||
truncated: true,
|
||||
charCount: 150,
|
||||
budgetChars: 100_000,
|
||||
omittedReasons: ["tail_window_limit"],
|
||||
},
|
||||
};
|
||||
const items: StreamItem[] = [
|
||||
{
|
||||
kind: "user_message",
|
||||
id: "u1",
|
||||
messageId: "u1",
|
||||
text: "Hello",
|
||||
timestamp: new Date(TS),
|
||||
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
switchItem,
|
||||
];
|
||||
|
||||
cache.commitTimeline("srv-1", "agent-1", {
|
||||
agentId: "agent-1",
|
||||
items,
|
||||
range: { epoch: "ep-1", startSeq: 1, endSeq: 3, activeSegmentStartSeq: 3 },
|
||||
hasOlder: false,
|
||||
});
|
||||
await cache.flush();
|
||||
|
||||
const restored = await cache.readTimeline("srv-1", "agent-1");
|
||||
expect(restored?.range?.activeSegmentStartSeq).toBe(3);
|
||||
expect(restored?.items.find((i) => i.kind === "provider_switch")).toMatchObject({
|
||||
kind: "provider_switch",
|
||||
fromProvider: "claude",
|
||||
toProvider: "codex",
|
||||
context: { truncated: true, omittedReasons: ["tail_window_limit"] },
|
||||
});
|
||||
|
||||
// Turn collapse keeps provider_switch visible
|
||||
const collapsed = collapseTurns({
|
||||
tail: [
|
||||
items[0]!,
|
||||
{
|
||||
kind: "tool_call",
|
||||
id: "tc1",
|
||||
timestamp: new Date(TS),
|
||||
payload: {
|
||||
source: "agent",
|
||||
data: {
|
||||
provider: "claude",
|
||||
callId: "c1",
|
||||
name: "read",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "read", filePath: "a.ts" },
|
||||
},
|
||||
},
|
||||
},
|
||||
switchItem,
|
||||
{
|
||||
kind: "assistant_message",
|
||||
id: "a1",
|
||||
text: "Done",
|
||||
timestamp: new Date(TS),
|
||||
},
|
||||
],
|
||||
isLatestTurnOpen: false,
|
||||
expandedHostIds: new Set(),
|
||||
getGroupedCalls: () => undefined,
|
||||
previousSummaryRowsByHostId: new Map(),
|
||||
});
|
||||
expect(collapsed.tail.some((item) => item.kind === "provider_switch")).toBe(true);
|
||||
});
|
||||
|
||||
it("blocks M2 drain while M1's staged provider switch is in-flight, then sends M2 normally to P2", async () => {
|
||||
const serverId = "srv_multi_queue_switch";
|
||||
let resolveSwitch!: (value: { agent: AgentSnapshotPayload }) => void;
|
||||
const switchPromise = new Promise<{ agent: AgentSnapshotPayload }>((resolve) => {
|
||||
resolveSwitch = resolve;
|
||||
});
|
||||
const switchedCalls: string[] = [];
|
||||
const sentCalls: string[] = [];
|
||||
const fakeClient = {
|
||||
switchAgentProvider: vi.fn(async (_agentId: string, opts: { text: string }) => {
|
||||
switchedCalls.push(opts.text);
|
||||
return await switchPromise;
|
||||
}),
|
||||
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
|
||||
sentCalls.push(text);
|
||||
}),
|
||||
uploadFile: vi.fn(),
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient,
|
||||
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_multi_queue_switch",
|
||||
},
|
||||
});
|
||||
const sessionStore = useSessionStore.getState();
|
||||
sessionStore.initializeSession(serverId, fakeClient, 1);
|
||||
useSessionStore.setState((state) => ({
|
||||
sessions: {
|
||||
...state.sessions,
|
||||
[serverId]: {
|
||||
...state.sessions[serverId]!,
|
||||
serverInfo: {
|
||||
serverId,
|
||||
hostname: "localhost",
|
||||
version: "0.18.0",
|
||||
features: { providerSwitching: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
sessionStore.setAgents(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
{
|
||||
...agentSnapshot("claude"),
|
||||
serverId,
|
||||
parentAgentId: null,
|
||||
createdAt: new Date(TS),
|
||||
updatedAt: new Date(TS),
|
||||
lastUserMessageAt: null,
|
||||
lastActivityAt: new Date(TS),
|
||||
attentionTimestamp: null,
|
||||
archivedAt: null,
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
[
|
||||
{ id: "m1", text: "First queued switch prompt", attachments: [] },
|
||||
{ id: "m2", text: "Second queued follow-up", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
// M1 begins switching
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(switchedCalls).toEqual(["First queued switch prompt"]);
|
||||
});
|
||||
|
||||
// Concurrent drain trigger while M1's switch is still in-flight MUST NOT drain M2!
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
expect(sentCalls).toEqual([]);
|
||||
expect(switchedCalls).toHaveLength(1);
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
|
||||
{ id: "m2", text: "Second queued follow-up", attachments: [] },
|
||||
]);
|
||||
|
||||
// M1 switch completes -> staged switch clears -> M2 drains as a plain sendAgentMessage to Codex!
|
||||
resolveSwitch({ agent: agentSnapshot("codex") });
|
||||
await vi.waitFor(() => {
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
|
||||
});
|
||||
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(sentCalls).toEqual(["Second queued follow-up"]);
|
||||
});
|
||||
expect(switchedCalls).toHaveLength(1);
|
||||
sessionStore.clearSession(serverId);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "./index";
|
||||
|
||||
describe("staged provider switch store", () => {
|
||||
beforeEach(() => {
|
||||
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
|
||||
});
|
||||
|
||||
it("stages, patches, and clears per server and agent", () => {
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
store.stage("srv-1", "agent-2", {
|
||||
provider: "opencode",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toEqual({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
|
||||
store.patch("srv-1", "agent-1", (current) => ({
|
||||
...current,
|
||||
thinkingOptionId: "medium",
|
||||
}));
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")?.thinkingOptionId).toBe("medium");
|
||||
|
||||
clearStagedProviderSwitch("srv-1", "agent-1");
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-2")?.provider).toBe("opencode");
|
||||
|
||||
store.clearForServer("srv-1");
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-2")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { create } from "zustand";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
|
||||
export interface StagedProviderSwitch {
|
||||
provider: AgentProvider;
|
||||
model: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
modeId: string | null;
|
||||
providerOptions: ProviderOptions;
|
||||
}
|
||||
|
||||
function stagedKey(serverId: string, agentId: string): string {
|
||||
return `${serverId}:${agentId}`;
|
||||
}
|
||||
|
||||
interface StagedProviderSwitchState {
|
||||
stagedByKey: Map<string, StagedProviderSwitch>;
|
||||
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
|
||||
patch: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
|
||||
) => void;
|
||||
clear: (serverId: string, agentId: string) => void;
|
||||
clearForServer: (serverId: string) => void;
|
||||
}
|
||||
|
||||
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
|
||||
stagedByKey: new Map(),
|
||||
|
||||
stage: (serverId, agentId, draft) =>
|
||||
set((state) => {
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(stagedKey(serverId, agentId), draft);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
patch: (serverId, agentId, updater) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const current = state.stagedByKey.get(key);
|
||||
if (!current) return state;
|
||||
const updated = updater(current);
|
||||
if (updated === current) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(key, updated);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
clear: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
if (!state.stagedByKey.has(key)) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
clearForServer: (serverId) =>
|
||||
set((state) => {
|
||||
const prefix = `${serverId}:`;
|
||||
let changed = false;
|
||||
const next = new Map(state.stagedByKey);
|
||||
for (const key of next.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
next.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? { stagedByKey: next } : state;
|
||||
}),
|
||||
}));
|
||||
|
||||
export function getStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): StagedProviderSwitch | null {
|
||||
return (
|
||||
useStagedProviderSwitchStore.getState().stagedByKey.get(stagedKey(serverId, agentId)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
|
||||
}
|
||||
|
||||
export function useStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): StagedProviderSwitch | null {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => state.stagedByKey.get(stagedKey(serverId, agentId)) ?? null,
|
||||
);
|
||||
}
|
||||
@@ -385,6 +385,16 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
|
||||
});
|
||||
};
|
||||
const onRewind = (message: SessionOutboundMessage) => {
|
||||
if (message.type !== "agent.timeline.rewind") return;
|
||||
const { agentId, epoch, seq, retireFromSeq } = message.payload;
|
||||
sync.applyStreamEvent(agentId, {
|
||||
event: { type: "rewind", retireFromSeq },
|
||||
seq,
|
||||
epoch,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
};
|
||||
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
|
||||
canCheckFreshness: () =>
|
||||
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
|
||||
@@ -395,6 +405,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
update: (message) => {
|
||||
if (message.type === "agent_stream") onStream(message);
|
||||
else if (message.type === "agent.timeline.replacement") onReplacement(message);
|
||||
else if (message.type === "agent.timeline.rewind") onRewind(message);
|
||||
},
|
||||
});
|
||||
return observation;
|
||||
|
||||
@@ -146,41 +146,3 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
|
||||
kind: "assistant_message",
|
||||
id: "canonical-item",
|
||||
text: "Canonical before restart",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
timestamp: new Date("2026-07-27T10:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
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,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function useKeyboardVisibility(_enabled = true): boolean {
|
||||
return false;
|
||||
}
|
||||
@@ -205,6 +205,10 @@ export const ar: TranslationResources = {
|
||||
pasteImageFailed: "تعذر لصق الصورة",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "التبديل إلى {{provider}} في الرسالة التالية",
|
||||
switchingAfterTurn: "سيتم التبديل إلى {{provider}} بعد هذا الدور",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "أرشفة الوكيل الحالي",
|
||||
freshDraft: "أرشفة هذا الوكيل وابدأ مسودة جديدة",
|
||||
@@ -436,6 +440,13 @@ export const ar: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "عمل لمدة {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "تم التبديل من {{from}} إلى {{to}}",
|
||||
contextSummary: "تم نقل {{count}} عنصر ({{chars}} / {{budget}} حرف)",
|
||||
trimmed: "تم الاقتطاع: {{reasons}}",
|
||||
reasonTailWindow: "سجل أقدم خارج النطاق",
|
||||
reasonCharBudget: "حد الأحرف",
|
||||
},
|
||||
compaction: {
|
||||
loading: "الضغط...",
|
||||
auto: "يتم ضغط السياق تلقائيًا",
|
||||
@@ -741,6 +752,8 @@ export const ar: TranslationResources = {
|
||||
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
|
||||
reloadingAgent: "وكيل إعادة التحميل...",
|
||||
reloadedAgent: "وكيل إعادة تحميل",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
|
||||
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
|
||||
failedToCloseAgent: "فشل في إغلاق الوكيل",
|
||||
},
|
||||
@@ -960,8 +973,6 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'الأرشيف "{{workspaceName}}"؟',
|
||||
bulkTitle: "أرشفة {{count}} مساحات عمل؟",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "أرشيف",
|
||||
cancel: "يلغي",
|
||||
uncommittedChanges: "تغييرات غير ملتزم بها",
|
||||
@@ -1371,7 +1382,6 @@ export const ar: TranslationResources = {
|
||||
rename: "إعادة تسمية مساحة العمل",
|
||||
pin: "تثبيت في الأعلى",
|
||||
unpin: "إلغاء التثبيت",
|
||||
select: "تحديد",
|
||||
archive: "أرشيف",
|
||||
archiveWorkspace: "أرشفة مساحة العمل",
|
||||
hideFromSidebar: "إخفاء من الشريط الجانبي",
|
||||
@@ -1390,10 +1400,6 @@ export const ar: TranslationResources = {
|
||||
submit: "إعادة تسمية",
|
||||
invalidBranchName: "اسم الفرع غير صالح",
|
||||
},
|
||||
selection: {
|
||||
count: "تم تحديد {{count}}",
|
||||
exit: "إنهاء التحديد",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "مسار Workspace غير متوفر",
|
||||
pathCopied: "تم نسخ المسار",
|
||||
@@ -1401,9 +1407,7 @@ export const ar: TranslationResources = {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
hideFailed: "فشل في إخفاء مساحة العمل",
|
||||
archiveFailed: "فشل في أرشفة مساحة العمل",
|
||||
archiveMultipleFailed: "فشل في أرشفة {{count}} مساحات عمل",
|
||||
archived: "تمت أرشفة مساحة العمل",
|
||||
archivedCount: "تمت أرشفة {{count}} مساحات عمل",
|
||||
undoArchive: "تراجع",
|
||||
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
|
||||
},
|
||||
|
||||
@@ -203,6 +203,10 @@ export const en = {
|
||||
pasteImageFailed: "Failed to paste image",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Switching to {{provider}} on next message",
|
||||
switchingAfterTurn: "Will switch to {{provider}} after this turn",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Archive the current agent",
|
||||
freshDraft: "Archive this agent and start a fresh draft",
|
||||
@@ -435,6 +439,13 @@ export const en = {
|
||||
turnFooter: {
|
||||
workedFor: "Worked for {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Switched from {{from}} to {{to}}",
|
||||
contextSummary: "{{count}} items transferred ({{chars}} / {{budget}} chars)",
|
||||
trimmed: "Trimmed: {{reasons}}",
|
||||
reasonTailWindow: "older history beyond window",
|
||||
reasonCharBudget: "character budget",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Compacting...",
|
||||
auto: "Context automatically compacted",
|
||||
@@ -740,6 +751,8 @@ export const en = {
|
||||
resumeCommandUnavailable: "Resume command not available",
|
||||
reloadingAgent: "Reloading agent...",
|
||||
reloadedAgent: "Reloaded agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
|
||||
failedToReloadAgent: "Failed to reload agent",
|
||||
failedToCloseAgent: "Failed to close agent",
|
||||
},
|
||||
@@ -971,8 +984,6 @@ export const en = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'Archive "{{workspaceName}}"?',
|
||||
bulkTitle: "Archive {{count}} workspaces?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Archive",
|
||||
cancel: "Cancel",
|
||||
uncommittedChanges: "Uncommitted changes",
|
||||
@@ -1382,7 +1393,6 @@ export const en = {
|
||||
rename: "Rename workspace",
|
||||
pin: "Pin to top",
|
||||
unpin: "Unpin",
|
||||
select: "Select",
|
||||
archive: "Archive",
|
||||
archiveWorkspace: "Archive workspace",
|
||||
hideFromSidebar: "Hide from sidebar",
|
||||
@@ -1401,10 +1411,6 @@ 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",
|
||||
@@ -1412,9 +1418,7 @@ 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",
|
||||
},
|
||||
|
||||
@@ -207,6 +207,10 @@ export const es: TranslationResources = {
|
||||
pasteImageFailed: "No se pudo pegar la imagen",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Cambiando a {{provider}} en el próximo mensaje",
|
||||
switchingAfterTurn: "Se cambiará a {{provider}} después de este turno",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Archivar el agente actual",
|
||||
freshDraft: "Archive este agente y comience un nuevo borrador",
|
||||
@@ -441,6 +445,13 @@ export const es: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "Trabajó durante {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Cambiado de {{from}} a {{to}}",
|
||||
contextSummary: "{{count}} elementos transferidos ({{chars}} / {{budget}} caracteres)",
|
||||
trimmed: "Recortado: {{reasons}}",
|
||||
reasonTailWindow: "historial anterior fuera de la ventana",
|
||||
reasonCharBudget: "límite de caracteres",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Compactando...",
|
||||
auto: "Contexto compactado automáticamente",
|
||||
@@ -748,6 +759,8 @@ export const es: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de reanudación no disponible",
|
||||
reloadingAgent: "Agente de recarga...",
|
||||
reloadedAgent: "Agente recargado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
|
||||
failedToReloadAgent: "No se pudo recargar el agente",
|
||||
failedToCloseAgent: "No se pudo cerrar el agente",
|
||||
},
|
||||
@@ -994,8 +1007,6 @@ 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",
|
||||
@@ -1408,7 +1419,6 @@ 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",
|
||||
@@ -1427,10 +1437,6 @@ 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",
|
||||
@@ -1438,9 +1444,7 @@ 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",
|
||||
},
|
||||
|
||||
@@ -208,6 +208,10 @@ export const fr: TranslationResources = {
|
||||
pasteImageFailed: "Impossible de coller l’image",
|
||||
fileTooLarge: "{{fileName}} est trop volumineux (maximum {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Passage à {{provider}} au prochain message",
|
||||
switchingAfterTurn: "Passage à {{provider}} après ce tour",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Archiver l’agent actuel",
|
||||
freshDraft: "Archiver cet agent et démarrer un nouveau brouillon",
|
||||
@@ -441,6 +445,13 @@ export const fr: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "A travaillé pendant {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Passé de {{from}} à {{to}}",
|
||||
contextSummary: "{{count}} éléments transférés ({{chars}} / {{budget}} caractères)",
|
||||
trimmed: "Tronqué : {{reasons}}",
|
||||
reasonTailWindow: "historique antérieur hors fenêtre",
|
||||
reasonCharBudget: "limite de caractères",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Compaction…",
|
||||
auto: "Contexte compacté automatiquement",
|
||||
@@ -748,6 +759,8 @@ export const fr: TranslationResources = {
|
||||
resumeCommandUnavailable: "Commande de reprise indisponible",
|
||||
reloadingAgent: "Rechargement de l’agent…",
|
||||
reloadedAgent: "Agent rechargé",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
|
||||
failedToReloadAgent: "Impossible de recharger l’agent",
|
||||
failedToCloseAgent: "Impossible de fermer l’agent",
|
||||
},
|
||||
@@ -986,8 +999,6 @@ 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",
|
||||
@@ -1401,7 +1412,6 @@ 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",
|
||||
@@ -1420,10 +1430,6 @@ 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é",
|
||||
@@ -1431,9 +1437,7 @@ 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",
|
||||
},
|
||||
|
||||
@@ -207,6 +207,10 @@ export const ja: TranslationResources = {
|
||||
pasteImageFailed: "画像を貼り付けられませんでした",
|
||||
fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "次のメッセージで {{provider}} に切り替えます",
|
||||
switchingAfterTurn: "このターン終了後に {{provider}} に切り替えます",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "現在のエージェントをアーカイブ",
|
||||
freshDraft: "このエージェントをアーカイブして新しい下書きを開始",
|
||||
@@ -441,6 +445,13 @@ export const ja: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "作業時間 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "{{from}} から {{to}} に切り替えました",
|
||||
contextSummary: "{{count}} 件を引き継ぎました ({{chars}} / {{budget}} 文字)",
|
||||
trimmed: "省略: {{reasons}}",
|
||||
reasonTailWindow: "ウィンドウ外の古い履歴",
|
||||
reasonCharBudget: "文字数上限",
|
||||
},
|
||||
compaction: {
|
||||
loading: "コンテキストを圧縮中...",
|
||||
auto: "コンテキストが自動的に圧縮されました",
|
||||
@@ -748,6 +759,8 @@ export const ja: TranslationResources = {
|
||||
resumeCommandUnavailable: "再開コマンドが利用できません",
|
||||
reloadingAgent: "エージェントを再読み込み中...",
|
||||
reloadedAgent: "エージェントを再読み込みしました",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
|
||||
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
|
||||
failedToCloseAgent: "エージェントを閉じられませんでした",
|
||||
},
|
||||
@@ -974,8 +987,6 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: '"{{workspaceName}}"をアーカイブしますか?',
|
||||
bulkTitle: "{{count}}件のワークスペースをアーカイブしますか?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
|
||||
confirm: "アーカイブ",
|
||||
cancel: "キャンセル",
|
||||
uncommittedChanges: "未コミットの変更",
|
||||
@@ -1386,7 +1397,6 @@ export const ja: TranslationResources = {
|
||||
rename: "ワークスペースの名前を変更",
|
||||
pin: "上部に固定",
|
||||
unpin: "固定解除",
|
||||
select: "選択",
|
||||
archive: "アーカイブ",
|
||||
archiveWorkspace: "ワークスペースをアーカイブ",
|
||||
hideFromSidebar: "サイドバーから非表示",
|
||||
@@ -1405,10 +1415,6 @@ export const ja: TranslationResources = {
|
||||
submit: "名前を変更",
|
||||
invalidBranchName: "無効なブランチ名",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}}件選択中",
|
||||
exit: "選択を終了",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "ワークスペースパスが利用できません",
|
||||
pathCopied: "パスをコピーしました",
|
||||
@@ -1416,9 +1422,7 @@ export const ja: TranslationResources = {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
hideFailed: "ワークスペースの非表示に失敗しました",
|
||||
archiveFailed: "ワークスペースのアーカイブに失敗しました",
|
||||
archiveMultipleFailed: "{{count}}件のワークスペースのアーカイブに失敗しました",
|
||||
archived: "ワークスペースをアーカイブしました",
|
||||
archivedCount: "{{count}}件のワークスペースをアーカイブしました",
|
||||
undoArchive: "元に戻す",
|
||||
undoArchiveFailed: "アーカイブを元に戻せませんでした",
|
||||
},
|
||||
|
||||
@@ -205,6 +205,10 @@ export const ko: TranslationResources = {
|
||||
pasteImageFailed: "이미지를 붙여넣지 못했습니다.",
|
||||
fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "다음 메시지에서 {{provider}}(으)로 전환합니다",
|
||||
switchingAfterTurn: "이 턴이 끝난 후 {{provider}}(으)로 전환합니다",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "현재 에이전트 보관",
|
||||
freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다",
|
||||
@@ -437,6 +441,13 @@ export const ko: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "작업 시간 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "{{from}}에서 {{to}}(으)로 전환됨",
|
||||
contextSummary: "{{count}}개 항목 전달됨 ({{chars}} / {{budget}}자)",
|
||||
trimmed: "생략됨: {{reasons}}",
|
||||
reasonTailWindow: "창 범위를 벗어난 이전 기록",
|
||||
reasonCharBudget: "문자 수 제한",
|
||||
},
|
||||
compaction: {
|
||||
loading: "압축하는 중...",
|
||||
auto: "컨텍스트가 자동으로 압축되었습니다",
|
||||
@@ -743,6 +754,8 @@ export const ko: TranslationResources = {
|
||||
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
|
||||
reloadingAgent: "에이전트 다시 로드 중...",
|
||||
reloadedAgent: "에이전트를 다시 로드했습니다",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
|
||||
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
|
||||
failedToCloseAgent: "에이전트를 닫지 못했습니다",
|
||||
},
|
||||
@@ -967,8 +980,6 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: '"{{workspaceName}}"를 보관하시겠습니까?',
|
||||
bulkTitle: "워크스페이스 {{count}}개를 보관하시겠습니까?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "보관",
|
||||
cancel: "취소",
|
||||
uncommittedChanges: "커밋되지 않은 변경 사항",
|
||||
@@ -1378,7 +1389,6 @@ export const ko: TranslationResources = {
|
||||
rename: "워크스페이스 이름 변경",
|
||||
pin: "상단에 고정",
|
||||
unpin: "고정 해제",
|
||||
select: "선택",
|
||||
archive: "보관",
|
||||
archiveWorkspace: "워크스페이스 보관",
|
||||
hideFromSidebar: "사이드바에서 숨기기",
|
||||
@@ -1397,10 +1407,6 @@ export const ko: TranslationResources = {
|
||||
submit: "이름 변경",
|
||||
invalidBranchName: "잘못된 브랜치 이름",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}}개 선택됨",
|
||||
exit: "선택 종료",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "워크스페이스 경로를 사용할 수 없습니다",
|
||||
pathCopied: "경로가 복사되었습니다",
|
||||
@@ -1408,9 +1414,7 @@ export const ko: TranslationResources = {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
hideFailed: "워크스페이스를 숨기지 못했습니다",
|
||||
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
|
||||
archiveMultipleFailed: "워크스페이스 {{count}}개를 보관하지 못했습니다",
|
||||
archived: "워크스페이스를 보관했습니다",
|
||||
archivedCount: "워크스페이스 {{count}}개를 보관했습니다",
|
||||
undoArchive: "실행 취소",
|
||||
undoArchiveFailed: "보관을 취소하지 못했습니다",
|
||||
},
|
||||
|
||||
@@ -206,6 +206,10 @@ export const ptBR: TranslationResources = {
|
||||
pasteImageFailed: "Falha ao colar a imagem",
|
||||
fileTooLarge: "{{fileName}} é grande demais (máximo {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Trocando para {{provider}} na próxima mensagem",
|
||||
switchingAfterTurn: "Trocará para {{provider}} após este turno",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Arquivar o agente atual",
|
||||
freshDraft: "Arquivar este agente e iniciar um novo rascunho",
|
||||
@@ -440,6 +444,13 @@ export const ptBR: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "Trabalhou por {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Trocado de {{from}} para {{to}}",
|
||||
contextSummary: "{{count}} itens transferidos ({{chars}} / {{budget}} caracteres)",
|
||||
trimmed: "Cortado: {{reasons}}",
|
||||
reasonTailWindow: "histórico anterior além da janela",
|
||||
reasonCharBudget: "limite de caracteres",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Compactando...",
|
||||
auto: "Contexto compactado automaticamente",
|
||||
@@ -746,6 +757,8 @@ export const ptBR: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de retomada indisponível",
|
||||
reloadingAgent: "Recarregando agente...",
|
||||
reloadedAgent: "Agente recarregado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
|
||||
failedToReloadAgent: "Falha ao recarregar agente",
|
||||
failedToCloseAgent: "Falha ao fechar agente",
|
||||
},
|
||||
@@ -984,8 +997,6 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'Arquivar "{{workspaceName}}"?',
|
||||
bulkTitle: "Arquivar {{count}} workspaces?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Arquivar",
|
||||
cancel: "Cancelar",
|
||||
uncommittedChanges: "Alterações sem commit",
|
||||
@@ -1398,7 +1409,6 @@ 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",
|
||||
@@ -1417,10 +1427,6 @@ 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",
|
||||
@@ -1428,9 +1434,7 @@ 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",
|
||||
},
|
||||
|
||||
@@ -207,6 +207,10 @@ export const ru: TranslationResources = {
|
||||
pasteImageFailed: "Не удалось вставить изображение",
|
||||
fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "Переключение на {{provider}} в следующем сообщении",
|
||||
switchingAfterTurn: "Переключение на {{provider}} после этого хода",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "Архивировать текущего агента",
|
||||
freshDraft: "Архивировать этого агента и создать новый черновик",
|
||||
@@ -440,6 +444,13 @@ export const ru: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "Время работы: {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "Переключено с {{from}} на {{to}}",
|
||||
contextSummary: "Передано элементов: {{count}} ({{chars}} / {{budget}} симв.)",
|
||||
trimmed: "Сокращено: {{reasons}}",
|
||||
reasonTailWindow: "более ранняя история вне окна",
|
||||
reasonCharBudget: "лимит символов",
|
||||
},
|
||||
compaction: {
|
||||
loading: "Сжатие контекста...",
|
||||
auto: "Контекст сжат автоматически",
|
||||
@@ -749,6 +760,8 @@ export const ru: TranslationResources = {
|
||||
resumeCommandUnavailable: "Команда возобновления недоступна",
|
||||
reloadingAgent: "Перезагрузка агента...",
|
||||
reloadedAgent: "Агент перезагружен",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
|
||||
failedToReloadAgent: "Не удалось перезагрузить агента",
|
||||
failedToCloseAgent: "Не удалось закрыть агента",
|
||||
},
|
||||
@@ -979,8 +992,6 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: "Архивировать «{{workspaceName}}»?",
|
||||
bulkTitle: "Архивировать рабочие пространства ({{count}})?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Архивировать",
|
||||
cancel: "Отмена",
|
||||
uncommittedChanges: "Незафиксированные изменения",
|
||||
@@ -1391,7 +1402,6 @@ export const ru: TranslationResources = {
|
||||
rename: "Переименовать рабочее пространство",
|
||||
pin: "Закрепить вверху",
|
||||
unpin: "Открепить",
|
||||
select: "Выбрать",
|
||||
archive: "Архивировать",
|
||||
archiveWorkspace: "Архивировать рабочее пространство",
|
||||
hideFromSidebar: "Скрыть на боковой панели",
|
||||
@@ -1410,10 +1420,6 @@ export const ru: TranslationResources = {
|
||||
submit: "Переименовать",
|
||||
invalidBranchName: "Недопустимое имя ветки",
|
||||
},
|
||||
selection: {
|
||||
count: "Выбрано: {{count}}",
|
||||
exit: "Выйти из выбора",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Путь к рабочему пространству недоступен",
|
||||
pathCopied: "Путь скопирован",
|
||||
@@ -1421,9 +1427,7 @@ export const ru: TranslationResources = {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
hideFailed: "Не удалось скрыть рабочее пространство",
|
||||
archiveFailed: "Не удалось архивировать рабочее пространство",
|
||||
archiveMultipleFailed: "Не удалось архивировать рабочие пространства ({{count}})",
|
||||
archived: "Рабочее пространство архивировано",
|
||||
archivedCount: "Архивировано рабочих пространств: {{count}}",
|
||||
undoArchive: "Отменить",
|
||||
undoArchiveFailed: "Не удалось отменить архивацию",
|
||||
},
|
||||
|
||||
@@ -205,6 +205,10 @@ export const zhCN: TranslationResources = {
|
||||
pasteImageFailed: "无法粘贴图片",
|
||||
fileTooLarge: "{{fileName}} is too large (max {{size}})",
|
||||
},
|
||||
providerSwitch: {
|
||||
switchingNextMessage: "下一条消息将切换到 {{provider}}",
|
||||
switchingAfterTurn: "本轮结束后将切换到 {{provider}}",
|
||||
},
|
||||
clientCommands: {
|
||||
archiveAgent: "归档当前 Agent",
|
||||
freshDraft: "归档此 Agent 并开始新的草稿",
|
||||
@@ -436,6 +440,13 @@ export const zhCN: TranslationResources = {
|
||||
turnFooter: {
|
||||
workedFor: "工作了 {{duration}}",
|
||||
},
|
||||
providerSwitch: {
|
||||
switched: "已从 {{from}} 切换到 {{to}}",
|
||||
contextSummary: "已传递 {{count}} 项上下文({{chars}} / {{budget}} 字符)",
|
||||
trimmed: "已裁剪:{{reasons}}",
|
||||
reasonTailWindow: "超出窗口的早期历史",
|
||||
reasonCharBudget: "字符预算限制",
|
||||
},
|
||||
compaction: {
|
||||
loading: "正在压缩...",
|
||||
auto: "上下文已自动压缩",
|
||||
@@ -741,6 +752,8 @@ export const zhCN: TranslationResources = {
|
||||
resumeCommandUnavailable: "恢复命令不可用",
|
||||
reloadingAgent: "正在重新加载 Agent...",
|
||||
reloadedAgent: "已重新加载 Agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
|
||||
failedToReloadAgent: "重新加载 Agent 失败",
|
||||
failedToCloseAgent: "关闭 Agent 失败",
|
||||
},
|
||||
@@ -952,8 +965,6 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: "归档「{{workspaceName}}」?",
|
||||
bulkTitle: "归档 {{count}} 个工作区?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
|
||||
confirm: "归档",
|
||||
cancel: "取消",
|
||||
uncommittedChanges: "未 commit 的变更",
|
||||
@@ -1361,7 +1372,6 @@ export const zhCN: TranslationResources = {
|
||||
rename: "重命名 workspace",
|
||||
pin: "置顶",
|
||||
unpin: "取消置顶",
|
||||
select: "选择",
|
||||
archive: "归档",
|
||||
archiveWorkspace: "归档工作区",
|
||||
hideFromSidebar: "从侧边栏隐藏",
|
||||
@@ -1379,10 +1389,6 @@ export const zhCN: TranslationResources = {
|
||||
submit: "重命名",
|
||||
invalidBranchName: "无效的分支名称",
|
||||
},
|
||||
selection: {
|
||||
count: "已选 {{count}} 项",
|
||||
exit: "退出选择",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Workspace 路径不可用",
|
||||
pathCopied: "路径已复制",
|
||||
@@ -1390,9 +1396,7 @@ export const zhCN: TranslationResources = {
|
||||
hostDisconnected: "Host 未连接",
|
||||
hideFailed: "隐藏 workspace 失败",
|
||||
archiveFailed: "归档工作区失败",
|
||||
archiveMultipleFailed: "归档 {{count}} 个工作区失败",
|
||||
archived: "工作区已归档",
|
||||
archivedCount: "已归档 {{count}} 个工作区",
|
||||
undoArchive: "撤销",
|
||||
undoArchiveFailed: "无法撤销归档",
|
||||
},
|
||||
|
||||
@@ -14,5 +14,3 @@ 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,10 +9,6 @@ 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,29 +3,12 @@ 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: FocusTarget | null;
|
||||
restoreFocus: HTMLElement | null;
|
||||
manageFocus: boolean;
|
||||
}
|
||||
|
||||
@@ -173,7 +156,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
|
||||
entry.manageFocus &&
|
||||
options?.restoreFocus !== false &&
|
||||
entry.restoreFocus &&
|
||||
canRestoreFocusTo(entry.restoreFocus)
|
||||
document.contains(entry.restoreFocus)
|
||||
) {
|
||||
entry.restoreFocus.focus();
|
||||
}
|
||||
@@ -198,7 +181,7 @@ export function useOverlayRegistration({
|
||||
keysRef.current = keys;
|
||||
const layerRef = useRef(layer);
|
||||
const keyHandlerRef = useRef(onKeyDown);
|
||||
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
|
||||
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
|
||||
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
|
||||
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
|
||||
const registeredRef = useRef(false);
|
||||
@@ -210,7 +193,7 @@ export function useOverlayRegistration({
|
||||
keyHandlerRef.current = onKeyDown;
|
||||
if (active && !wasActiveRef.current && typeof document !== "undefined") {
|
||||
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
|
||||
if (isFocusTarget(requestedRestoreTarget)) {
|
||||
if (requestedRestoreTarget instanceof HTMLElement) {
|
||||
capturedRestoreFocusRef.current = requestedRestoreTarget;
|
||||
} else {
|
||||
capturedRestoreFocusRef.current =
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
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,4 +1,3 @@
|
||||
import { AppState } from "react-native";
|
||||
import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract";
|
||||
import {
|
||||
setHardwareKeyboardClaimedShortcuts,
|
||||
@@ -8,14 +7,6 @@ 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,7 +9,6 @@ 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;
|
||||
}
|
||||
@@ -79,9 +78,7 @@ export function createHardwareKeyboardSource(source: HardwareKeySource) {
|
||||
nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())),
|
||||
);
|
||||
});
|
||||
const unsubscribeBlur = source.subscribeBlur?.(() => handlers.blur()) ?? (() => {});
|
||||
return () => {
|
||||
unsubscribeBlur();
|
||||
unsubscribeHardware();
|
||||
unsubscribeFocus();
|
||||
unsubscribeCommandCenter();
|
||||
|
||||
@@ -269,142 +269,4 @@ 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,7 +1,6 @@
|
||||
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";
|
||||
@@ -250,30 +249,19 @@ 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: handleKeyDown,
|
||||
keyDown: pipeline.keyDown,
|
||||
keyUp: handleKeyUp,
|
||||
blur: handleBlur,
|
||||
blur: resetModifiers,
|
||||
commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen,
|
||||
subscribeCommandCenter: (listener) =>
|
||||
useKeyboardShortcutsStore.subscribe((state, previous) => {
|
||||
@@ -282,8 +270,7 @@ export function useKeyboardShortcuts({
|
||||
});
|
||||
return () => {
|
||||
detach();
|
||||
heldModifiers.reset();
|
||||
pipeline.dispose();
|
||||
};
|
||||
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
|
||||
}, [enabled, pipeline, handleKeyUp, resetModifiers]);
|
||||
}
|
||||
|
||||
@@ -197,7 +197,7 @@ describe("plugin timeline projection", () => {
|
||||
kind: "assistant_message",
|
||||
id: "assistant-1",
|
||||
messageId: "provider-msg-1",
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||
turnId: "turn-1",
|
||||
text: 'Summary\n\n```ui\nCard("Hi", [])\n```',
|
||||
timestamp: new Date("2026-01-01T00:00:02.000Z"),
|
||||
@@ -226,13 +226,13 @@ describe("plugin timeline projection", () => {
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/text",
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/card",
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
timelineCursor: { epoch: "e1", seq: 7, anchorSeq: 7 },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -65,6 +65,7 @@ function sourceTimelineItem(item: StreamItem): AgentTimelineItem | null {
|
||||
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
|
||||
};
|
||||
case "plugin":
|
||||
case "provider_switch":
|
||||
case "turn_summary":
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
|
||||
id: "reply",
|
||||
text: "server history",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "e", seq: 1 },
|
||||
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
],
|
||||
head: [],
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user