Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 5fd6783c19 fix(agents): forward history option through createAgentInternal 2026-11-26 02:47:09 +01:00
Mohamed Boudra 4719186fbb test(server): give the terminal workspace test's cleanup longer on Windows
On Windows the stopped `sleeper` script's process can still hold the project
directory as its working directory when the test removes it, failing cleanup
with EBUSY. rm's retries now wait up to about 5 s for the handle to go.
2026-11-26 02:46:04 +01:00
Mohamed Boudra cd2bfa91a8 fix(timeline): serve an empty older page before a retired first turn in SQLite
The SQLite backend's `before` selection had the same gap as the memory
projection fixed on the base branch: with no active row by the cursor it
returned the first later row as the start of an empty page. It now serves the
empty page, matching the memory backend in the contract and differential tests.
2026-11-26 02:46:04 +01:00
Mohamed Boudra b26f19accd feat(timeline): record the provider that wrote each row
An agent's history can span providers once it switches, so a row served with
the agent's current provider would be rendered as the wrong one. Live writes,
provider history imports, opening notices and subagent rows now store their
provider in the row; the timeline page and replay serve it, falling back to
the agent's provider for rows written before this change. SQLite keeps it in
the row JSON, so the schema is unchanged.
2026-11-26 02:46:04 +01:00
Mohamed Boudra 8aba8bde08 fix(daemon): close paseo.db when startup or shutdown fails
A throw while the daemon assembled itself after opening paseo.db, or from a
shutdown step before the timeline close, left the connection and its WAL open
for the next daemon. `createPaseoDaemon` now owns the database and closes it
when assembly throws, and `stop()` closes it in `finally`.
2026-11-26 02:46:04 +01:00
Mohamed Boudra 29c448ac96 fix(timeline): reset an after cursor that is ahead of the history
A client whose cursor is past the stored history (commits lost in a crash, a
restored paseo.db) kept its cursor on an empty page, then dropped the rows
whose seqs it believed it already had. `fetchTimelinePage` now treats it as a
gap, so the client replaces its history with the tail.
2026-11-26 02:45:19 +01:00
Mohamed Boudra e03503c0de test(server): retry removing the restart test's directories on Windows
Windows reported EBUSY removing the agent directory right after the
second daemon closed. Retry the removal as the test daemon's own
cleanup does.
2026-11-26 02:45:19 +01:00
Mohamed Boudra 16c8a188e0 perf(timeline): read the chat outline's cursor from the head, not a tail page
The prompt index fetched a one-row tail page only for its epoch and
retirement count. A tool call updated after other rows makes that page
cover every row in between, so the outline still decoded tool output.
AgentTimeline.readPrompts returns the prompt rows with the head they
belong to, in one timeline operation.
2026-11-26 02:45:19 +01:00
Mohamed Boudra 325a65acac fix(agents): let an agent keep saving its record after a failed delete
The delete RPC fences the record against writes before closing the agent.
Since a failed history delete now leaves the record in place, the fence
stayed up for the rest of the process, so a later rename reported success
and never reached disk. The fence now ends when the delete aborts.
2026-11-26 02:45:19 +01:00
Mohamed Boudra 3c5654d2ab fix(timeline): keep history on reopen, fail deletes that leave it, read only prompts for the outline
- Opening a stored agent with no provider session ran the fresh-create
  cleanup, which deleted its saved timeline. Now that history survives a
  restart, that open erased it; the record-based open now clears only the
  previous session's runtime state.
- The delete RPC removed the registry record first and swallowed a failed
  history delete, replying agent_deleted while the transcript stayed on
  disk with no record to retry from. History now goes first and a failure
  reaches the client as rpc_error with the agent still listed.
- The chat outline built its prompt index from every active row, which on
  SQLite decodes all replies and tool output. Backends now return the
  active prompt rows, which the rewind and import paths already read.
2026-11-26 02:45:19 +01:00
Mohamed Boudra e531eb1f1a chore(nix): update npm dependency hash for the Node 22.16 types 2026-11-26 02:45:19 +01:00
Mohamed Boudra a462c43de2 fix(timeline): keep stored history private, exact, and off the turn's path
- paseo.db and its WAL files are set to mode 0600 on every open. They
  hold every prompt and reply.
- Internal agents keep their history in memory. Before this change it
  went to paseo.db and outlived a crash, which broke the rule that
  nothing about an internal agent is on disk.
- Text chunks are stored as JSON strings. node:sqlite reads a TEXT
  value only up to its first NUL, and a chunk can end inside a
  surrogate pair.
- A turn's handler now changes the agent's state before any timeline
  write. Before, a failed metrics stamp skipped the turn_completed
  handler, so a turn the provider started stayed running.
- Node 22.13, which has node:sqlite but not isTransaction, is refused
  at open.
- If the checkpoint worker cannot start, the daemon logs it and falls
  back to SQLite's auto-checkpoint. Before, the error reported an
  already committed write as failed.
2026-11-26 02:45:18 +01:00
Mohamed Boudra 511306bd25 test(cli): reopen the idle agent explicitly after a supervisor restart
Fetching an agent's timeline now reads stored history without loading the agent, so the agent stays closed until it is reopened.
2026-11-26 02:44:45 +01:00
Mohamed Boudra eed84c01f1 test(agents): prove a run's caller hears a turn whose record failed 2026-11-26 02:44:45 +01:00
Mohamed Boudra 6d21e28e06 feat(timeline): store agent timelines in paseo.db
Agent history now survives a daemon restart, and closed or archived
agents hold no timeline in memory. A history fetch reads paseo.db and
starts no provider.

The daemon opens one SQLite database at $PASEO_HOME/paseo.db with
node:sqlite. Each schema module owns its tables and migrations, and
records a min_reader_version, so an older daemon refuses a database
it cannot read instead of corrupting it. Node 22.16 is the floor,
because DatabaseSync needs it.

A worker thread runs the WAL checkpoints. A checkpoint syncs the
file, and on the daemon thread it stalled the event loop for up to
119 ms on whichever write crossed the auto-checkpoint threshold. If
the worker exits, the daemon returns to SQLite's auto-checkpoint.

A turn's final event now ends the run even when the timeline fails
to write it. Before this change the error escaped handleStreamEvent
before settleTerminalRun, so the agent stayed running and its waiters
hung. The durable store makes that write fallible, and shutdown made
it fail: settled() rejected after close.
2026-11-26 02:44:45 +01:00
Mohamed Boudra 4b42ae6c17 Merge remote-tracking branch 'origin/main' into plan-provider-switch-sqlite-timelines
# Conflicts:
#	packages/server/src/server/agent/agent-manager.ts
#	packages/server/src/server/agent/providers/opencode/v2/agent.test.ts
2026-11-26 02:42:27 +01:00
paseo-bot[bot] 68d58c8217 fix(app): open slash-prefixed Windows drive links (#7711)
Closes #3290
2026-11-26 08:11:37 +07:00
Mohamed Boudra e51bb7b8cd Keep Android chat long-press selection from leaving the magnifier stuck (#10844)
* fix(app): keep Android chat long-press selection from leaving the magnifier stuck

On Android, long-pressing assistant Markdown prose and dragging vertically showed the system magnifier, then let the parent chat ScrollView steal the gesture and dispatch ACTION_CANCEL. Because AOSP's Editor.SelectionModifierCursorController.onTouchEvent handles ACTION_UP but not ACTION_CANCEL, dismissMagnifier() was never called and the magnifier stayed stuck on screen while scrolling.

The trigger was reallowParentInterceptIfLinkReleased() in the vendored react-native-enriched-markdown package calling parent.requestDisallowInterceptTouchEvent(false) on every non-ACTION_DOWN event whenever no link was active, undoing Editor's disallow-intercept claim on the first ACTION_MOVE.

Backport software-mansion/enriched-markdown#1012 so LinkLongPressMovementMethod owns parent intercept disallow/release only for link/image/code-block presses it initiated, and keep Editor's disallow intact if selection started during the touch before touch slop was exceeded.

* fix(app): release parent intercept when a checkbox gesture cancels on Android

Removing reallowParentInterceptIfLinkReleased() left CheckboxTouchHelper's parent.requestDisallowInterceptTouchEvent(true) uncleared when a swipe starting on a task checkbox exceeded touch slop (such as checkboxes inside quoted lists where BlockquoteContainerView leaves checkbox hit-testing enabled).

Move parent-intercept claim/release into CheckboxTouchHelper symmetrically to LinkLongPressMovementMethod so it releases its own claim on slop exceeded, ACTION_UP, ACTION_CANCEL, or when disabled. Also update the table test to dispatch a horizontal drag through an intact overflowing TableContainerView and add a ScrollView regression test for vertical swipes starting on a checkbox.
2026-11-26 07:45:59 +07:00
paseo-bot[bot] 050e168974 Reduce PTY output in the terminal socket overflow test (#10843)
* test(terminal): reduce PTY output needed to exercise socket overflow

The terminal must finish writing before the stalled controller resumes. Use enough output to force the 4 MiB queue limit while reducing the load on Windows runners.

* test(terminal): assert both markers survive socket overflow

Write the overflow burst to the alternate screen so it does not scroll the startup marker out of the replay window. Use distinct markers to exercise replay across the disconnect.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-26 00:42:29 +00:00
e114e13de2 Let plugins run agents, terminals, and worktree commands behind a sandbox launcher (#10786)
Refs https://github.com/getpaseo/paseo/discussions/8484
Refs https://github.com/getpaseo/paseo/discussions/8017

Co-authored-by: CL Kao <clkao@datarecce.io>
Co-authored-by: Josh Bendavid <Josh.Bendavid@cern.ch>
2026-11-26 01:09:39 +07:00
Mohamed Boudra 3777cc754b Keep mobile sheet footers above the system bar during keyboard transitions (#10827)
* fix(app): keep sheet footer safe-area clearance in lockstep with keyboard transitions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 16:51:40 +01:00
Mohamed Boudra c228a3acac test(website): wait for hydration before submitting a plugin search
`openPlugins` waits only for the server-rendered heading. On WebKit, Enter
could land before hydration attached the search form's handler, so nothing
navigated and the page stayed on /plugins. The two tests that submit right
after opening the directory now wait for hydration first; `openPlugins` itself
stays as it is because a no-JavaScript test uses it.
2026-11-25 16:31:17 +01:00
Mohamed Boudra 1b6308502f fix(timeline): serve an empty older page before a retired first turn
After a rewind of the first prompt and a new turn, a `before` page whose
cursor fell in the retired prefix found no active row before the cursor. The
whole-turn loop then read the row at index -1 and threw, and ordinary paging
returned the first later row's seq as the start, past the page's end.
2026-11-25 16:20:34 +01:00
Mohamed Boudra 9e3107fcb7 test(opencode): read v2 children through the timeline-backed store
The child tests merged from main build a `ProviderSubagentStore` with no
timeline and read `list()` synchronously. On this branch the store keeps
children in the agent's timeline, so it takes one and its reads resolve
asynchronously. Each `apply` queues on the parent's timeline before its first
await, so an awaited `list` observes every event emitted before it.
2026-11-25 16:20:34 +01:00
Mohamed Boudra 60943dde1c Return focus to the prompt after choosing a New Workspace field (#10632)
* fix(app): return focus to the composer after choosing a New Workspace field

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(app): keep Escape owned by select mode during worktree checks
2026-11-25 22:11:10 +07:00
Mohamed Boudra 5033ad0249 Merge origin/main into plan-provider-switch-sqlite-timelines
Conflicts resolved by keeping both intents:
- turn-boundary: main reads the reply through getAssistantReply (plugin
  cards); this branch narrows the fork cursor to epoch and seq.
- codex rewind: this branch's fork-and-verify flow, with main's
  threadDeveloperInstructions() for the developer instructions.
- agent-manager: this branch's ProviderHistoryReconcile type next to
  main's Omit<..., "signal"> query options.
Main's new plugin-card tests gain the anchorSeq this branch's cursors carry.
2026-11-25 16:00:06 +01:00
Mohamed Boudra b7af3da71f fix(timeline): commit confirmed plugin rewind cuts and stream reload turn metrics
Preserve the confirmed at_target cut via RewindAppliedError when plugin session replay fails after session.revert succeeds, so reloading recovers even a first-message rewind. Carry turnMetrics on live timeline events appended by Reload agent so open chats match fresh timeline pages. Fix three async-timeline timing expectations in mcp-server and codex-async-questions tests.
2026-11-24 09:18:19 +01:00
Mohamed Boudra 2789421fbd Merge remote-tracking branch 'origin/main' into plan-provider-switch-sqlite-timelines
# Conflicts:
#	packages/app/e2e/browser/agent-message-rewind.spec.ts
#	packages/app/e2e/browser/rewind-menu.ui-contract.spec.ts
#	packages/app/src/runtime/host-runtime.ts
#	packages/app/src/timeline/session-stream-reducers.test.ts
#	packages/server/src/server/agent/agent-manager.test.ts
#	packages/server/src/server/agent/agent-manager.ts
#	packages/server/src/server/agent/agent-timeline-store-types.ts
#	packages/server/src/server/agent/agent-timeline-store.test.ts
#	packages/server/src/server/agent/agent-timeline-store.ts
#	packages/server/src/server/agent/plugin-provider.ts
#	packages/server/src/server/agent/providers/claude/agent.ts
2026-11-24 09:02:33 +01:00
Mohamed Boudra b7b5acf086 fix(timeline): resolve plugin rewind, id reuse, and startup notice findings
Define plugin session.revert completion as an exact rewind to the supplied token (at_target), allow plugin timeline items to reuse stable ids after a rewind, append session.initialTimeline only when creating a new timeline, and centralize provider-history prompt acknowledgement inside AgentTimeline.
2026-11-24 08:50:13 +01:00
Mohamed Boudra bf83a03ce9 fix(timeline): acknowledge replayed prompts with client IDs 2026-11-18 15:21:47 +01:00
Mohamed Boudra 80240eb851 test(timeline): reload a whole turn after restoring retired children 2026-11-18 15:00:49 +01:00
Mohamed Boudra 0c11263d4d fix(timeline): sync provider history at whole turn boundaries 2026-11-18 14:45:23 +01:00
Mohamed Boudra 28c9806da8 fix(timeline): exclude session status from history comparison 2026-11-18 14:11:13 +01:00
Mohamed Boudra a0add767c0 fix(timeline): reconcile live reconnect notices after updating from main 2026-11-18 13:51:34 +01:00
Mohamed Boudra 25f637e57c Merge remote-tracking branch 'origin/main' into plan-provider-switch-sqlite-timelines
# Conflicts:
#	packages/server/src/server/agent/agent-manager.test.ts
#	packages/server/src/server/agent/agent-manager.ts
#	packages/server/src/server/agent/providers/codex-app-server-agent.ts
#	packages/server/src/server/agent/tools/paseo-tools.ts
2026-11-18 13:35:20 +01:00
Mohamed Boudra 53fa9524cf fix(app): keep rewind invalidation for find results after Next and Previous
The rewind marker of the result set was cleared in cancel(), which also
stops navigation work. Next and Previous call cancel() while keeping the
results, so after one step a remote rewind no longer invalidated them and
the selection could stay on a retired message. The marker now shares the
result set's lifetime and is cleared only when a new query discards it.
2026-11-11 08:51:28 +01:00
Mohamed Boudra 5a8383d237 fix(app): end chat find results when a rewind retires messages
Find validated its results against the timeline epoch only. Capable hosts
rewind in place, so the epoch stays the same and a remote rewind left the
count and selection pointing at retired messages; Next could reveal one.

The replica now records the latest rewind seq per agent, from live rewind
events and from fetched pages carrying retirements. Find treats epoch plus
that seq as the history identity, so a rewind during or after a search
reports the history as changed.
2026-11-11 08:41:00 +01:00
Mohamed Boudra cf3caefa14 fix(server): retire the turns a steered Codex rewind actually removed
Codex rewinds whole native turns. A steered prompt shares its turn with the prompt it joined, so forking before that turn also removes the earlier prompt, and a rollback counted per prompt can remove earlier turns. The session reported at_target, so Paseo kept prompts the provider no longer had. It now reports the cut from the turn index taken before the fork, and an unreported outcome when the fork switched threads but did not finish.
2026-11-11 08:36:58 +01:00
Mohamed Boudra c747a58871 test(app): expect a rewound first prompt to leave the chat in the rewind sheet spec
On main the mock provider's rewind kept the first user message whatever the target, and the chat was rebuilt from that history, so the spec expected the rewound first prompt to stay. The mock now rewinds at the target and the chat retires the rewound turns in place, so rewinding the first prompt empties the chat and returns the prompt to the composer.
2026-11-11 08:26:19 +01:00
Mohamed Boudra c36d398829 perf(server): read the subscription freshness head without fetching the transcript
The freshness check read the head by fetching every row of the agent's history on each subscribe. The timeline head now carries its last committed sequence number, so the check reads only the head.
2026-11-11 04:00:27 +01:00
Mohamed Boudra 183bc736ec test(server): await provider child reads in the replay and pi child tests
These tests came in with the main merge. The child store reads are asynchronous now, so the tests compared a promise with the expected child.
2026-11-11 04:00:11 +01:00
Mohamed Boudra c4ce21a237 test(client): expect the rewind capability in the client hello
The client advertises timeline_rewind_operations since the rewind operations landed, but the hello expectation was never updated.
2026-11-11 03:59:55 +01:00
Mohamed Boudra 9a2236dac3 test(server): give the test session the interface's persistence signature
TestAgentSession.describePersistence had no return type, so TypeScript
inferred a codex-only handle with a UUID session id. The restarted-child test
from 80879eaf7 assigns the resumed AgentPersistenceHandle to it and failed to
typecheck (TS2322). The test double now declares the AgentSession signature,
which also clears the older plugin-provider sites with the same error.
2026-11-10 13:54:12 +01:00
Mohamed Boudra ecd0dd083e fix(server): let an aborted wait end while the provider is starting the turn
10c443a32 made waitForAgentEvent wait for a starting run before reading its
state, but that wait came before the abort listener. A provider start has no
deadline of its own, so a stalled startTurn kept every timed wait (MCP wait,
CLI wait, schedules, finish subscriptions) past its timeout. The start wait
now rejects as soon as the caller's signal aborts.
2026-11-10 13:53:50 +01:00
Mohamed Boudra 10c443a32b fix(server): wait for a starting run to settle before steering or waiting on it
A run's start now awaits the timeline before the provider is called, and a
failed start awaits its timeline writes before the run is cleared. Two
readers raced those windows:

- waitForForegroundStart returned as soon as a start failed, while the failed
  run was still tracked, so a steer send in that window replaced it and
  interrupted the session instead of starting its own turn.
- waitForAgentEvent replayed the idle state from before a starting run and
  finished immediately, so `wait` after a dispatch could return before the
  turn ran.

waitForForegroundStart now resolves only once the turn started or the run is
cleared, as documented, and waitForAgentEvent waits for it before reading the
agent's state. The OMP restored-history test previously finished only through
that early return; its fake now starts the turn it later ends.
2026-11-10 13:47:49 +01:00
Mohamed Boudra 457d8d6ec5 Merge origin/main into plan-provider-switch-sqlite-timelines
Adapts main's changes to the single asynchronous timeline owner:

- The subscribe freshness check (#9175) awaits the loaded timeline head and
  compares the client's cursor against the epoch that client sees, so legacy
  clients compare against their derived epoch after a rewind.
- History reads (#8737) pass purpose "history" when an agent with no stored
  timeline must be loaded; stored history is still read without the provider.
- Background work clears on reload, close and parent delete next to the
  async provider-child cancellation.
- Claude steered-message rewinds (#8372) report an at-target cut. Codex keeps
  main's saved thread id alongside the reported cut.
- Plugin rewinds (#8368) return an unreported outcome; a failed replay after
  the native revert leaves the rewind for the reload to settle rather than a
  retry. Manager-level rewinds target the timeline row's message id.
- Main's tests read the timeline asynchronously, and wait for the provider to
  receive a prompt instead of assuming it arrives in the dispatch tick.
2026-11-10 13:47:17 +01:00
Mohamed Boudra 80879eaf7c fix(timeline): retain child state and recover rewinds on resume
Provider children now live in the parent's timeline next to its history,
so their descriptors, rows and retirements survive close, archive and a
manager rebuilt over the same backend, and deleting the agent removes
them all. Resuming settles a rewind that was still open when the runtime
stopped instead of leaving its rows half-retired.

A stored child's status is only the last report, possibly from provider
history or an earlier runtime. Workspace activity and idle cleanup now
read the children the current runtime reported running, and closing a
runtime cancels only those, so a child stored as running from an earlier
runtime no longer keeps the agent busy or blocks cleanup.
2026-11-10 13:09:38 +01:00
Mohamed Boudra dc85c2bfbc feat(timeline): preserve history across reload and archive
Reload agent used to delete the timeline and replay the provider's
history under a new epoch. That brought back turns the user had rewound
and dropped anything the provider no longer had. Archive deleted the
timeline too.

Paseo's timeline is now the owner of the conversation. Reload agent
keeps it and reconciles the provider's history append-only: turns are
aligned by provider prompt id and compared exactly (prompt text,
assistant and reasoning text, tool calls). When the owned conversation
is a whole-segment prefix of the provider's, the rows after it are
appended as new live rows. Any other difference changes nothing and
agent_refreshed reports historyDiverged, which the app shows as a
warning on Reload agent and Unarchive.

Divergence is deliberately conservative:
- An answer or tool call Paseo saw only partly can never be completed by
  a reload. History rows carry no turn id to update a live row in place.
- A prompt sent with attachments diverges on every reload. Providers
  store the rendered attachment text, and the owned row keeps only the
  typed text. Recording the sent prompt is left to provider handoff work.

Archive now only closes the runtime. Stored history, including provider
children, is read without resuming or even requiring the provider.
Forced provider replacement is removed.

Tradeoff: an archived chat's history stays in memory until the daemon
exits, measured at about 1.1-1.2x its JSON size (about 0.5 MB for a
typical session, about 16 MB for a heavy tool session). Moving
retained history to disk belongs to the persisted backend, not eviction,
which would drop the rewinds this change keeps.
2026-11-10 11:43:10 +01:00
Mohamed Boudra 5ed1f8d108 feat(timeline): apply conversation rewinds without replacing history
Rewinding a prompt used to rotate the timeline epoch, so every open
client refetched and remounted the whole chat. A rewind is now a
retirement: the daemon keeps the rewound turn stored but outside the
conversation, and capable clients remove the rows that started in
[retireFromSeq, seq) in place. Catch-up pages carry the retirements in
their span. Clients without the timeline_rewind_operations capability
get the old replacement shape.

The daemon retires only what the provider actually removed. Providers
report the boundary they kept. A failure known to change nothing keeps
the conversation. Any other failure leaves the rewind open and refuses
prompts until reloading the agent proves the outcome from the
provider's replayed prompts. A recorded cut whose save failed is
committed by the next prompt or the reload, which resumes the rewound
session.

Plugin providers complete session.revert without saying what they
removed. Paseo then reloads the session itself and judges the outcome
from the replay, so a no-op completion is not taken as a cut.

The app anchors each row at the seq it started at, because a late
update moves a row's latest seq into the rewound range. The app also
refuses pages served before the newest retirement it has seen, then
refetches them.

Known limits:
- The automatic plugin settle shows the agent as restoring briefly.
- An empty or mismatched plugin replay leaves the rewind unresolved.
  Fork the chat to recover.
- A plugin's failed revert still needs a manual reload.
- An open rewind lives in memory, so a daemon restart drops it.
2026-11-10 10:16:13 +01:00
Mohamed Boudra 4178497d3d refactor(server): give agent timeline history a single awaitable owner
Agent timeline history had several writers that appended and published
independently, so a persistent backend could not be swapped in without
reordering or losing items. AgentTimeline now owns each agent's history:
one FIFO queue per agent (child agents share the parent's queue) commits
each item and then publishes it, so subscribers never see an item before it
is recorded. Backends may be async, which prepares the SQLite swap.

Terminal turn events wait for queued writes so a finished turn never races
its own last chunks. A subscriber that throws after commit leaves the item
in history. A failed commit surfaces as an agent error ("Conversation
history could not be saved") via the existing lastError/attention path; it
survives the turn's terminal transition and clears on the next run.
2026-11-10 08:11:00 +01:00
325 changed files with 23181 additions and 4491 deletions
+23
View File
@@ -131,6 +131,29 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run typecheck:examples --workspace=@getpaseo/client
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
sdk-tests-windows:
name: sdk-tests (windows-latest)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- name: Install dependencies
run: node scripts/npm-retry.mjs ci
- name: Build plugin SDK
run: npm run build:relay && npm run build:client && npm run build:plugin
- name: Run plugin SDK tests
run: npm run test --workspace=@getpaseo/plugin
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
typecheck:
name: typecheck
+2
View File
@@ -36,6 +36,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | The binding table, per-platform key sources, badges vs routing, iOS `UIKeyCommand` limits |
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
@@ -54,6 +55,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 |
+6 -3
View File
@@ -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
+3 -1
View File
@@ -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
View File
@@ -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`
+34
View File
@@ -0,0 +1,34 @@
# Drag to reorder
A list the user can reorder renders through `DraggableList` from `@/components/draggable-list`. Each row puts a `DraggableListHandle` where its grip is drawn. The Usage cards (`packages/app/src/usage/list.tsx`, `packages/app/src/usage/card.tsx`) and the agent profile roster (`packages/app/src/agent-profiles/settings/`) are the reference.
| Platform | How a drag starts |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Web | dnd-kit pointer drag. With `useDragHandle`, only the handle starts it, and the handle reorders by keyboard. Without it, the whole row starts it. |
| Native | Hold the handle for 180 ms without moving more than 4 px. The list then owns the touch until the finger lifts. |
## The scroll view must host the drag
On native, the hold calls `drag()`, which calls `useContentDrag().setActive(true)` from `@/components/ui/content-drag` on the nearest scroll view. That scroll view stops scrolling until the drag ends. If no scroll view up the tree hosts content drags, `setActive` does nothing. The page scroll then takes the touch as soon as the finger moves past the touch slop, before the list's own pan activates. The row never moves, and the page scrolls instead.
These scroll views host content drags:
- `ScrollView` from `@/components/ui/scroll-view`, inside and outside a sheet.
- `PageLayout`, for a settings page or any other full page.
If you put a reorderable list in another scroll view, such as a third-party keyboard-aware one, wrap it with `withContentDrag` from `@/components/ui/content-drag`. `packages/app/src/components/page-layout/index.tsx` shows the pattern. A plain `ScrollView` from `react-native` breaks the drag.
Inside a sheet, the `ScrollView` also registers the drag gesture with the sheet, so the sheet's pan-to-close waits for it.
## Where the grip goes
The grip hangs in the row's leading padding, absolutely positioned over the full row height. The row's content keeps the same left rail as rows that cannot be reordered, and the grip does not take a column. On a pointer device the grip shows on hover, focus, or while dragging. On touch and compact layouts it always shows, because there is no hover.
## Test with a page that scrolls
A list that fits on the screen does not show the bug, because the page has nothing to scroll. Test on a phone with enough rows that the page scrolls. Then check both directions:
1. Hold the grip and drag a row past two others. The new order is saved.
2. Swipe quickly on a row body. The page scrolls and the order stays the same.
On an Android emulator, `adb shell input swipe` does not hold still long enough to arm the drag. Send `input motionevent DOWN`, wait 500 ms, then send `MOVE` events and `UP`.
+1 -1
View File
@@ -465,7 +465,7 @@ in a tab. An overlay opened from that content and calling `useSafeAreaInsets()`
gets that 0 and draws over the navigation bar.
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
`CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`.
`SheetVisibleFrame` (used by `CompactSheetBody` and `ComboboxSheetFrame`) and `MenuSheetScrollView`.
- An RN `Modal` passes the call site's context straight through, so wrap its content in
`WindowSafeArea` from `@/window-layout` and read the inset below that. It provides the insets of
the whole window, published by `WindowLayoutProvider`. Do not put a `SafeAreaProvider` inside the
+5 -4
View File
@@ -32,10 +32,11 @@ CI does not build native code or run the fork's Robolectric suites. Run `npm run
Some fork changes are backports. A sync past the upstream version drops them in favour of upstream's code:
| Fork change | Upstream | Released in |
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
| Android measurements survive parent clones | [#924](https://github.com/software-mansion/enriched-markdown/pull/924) | after `1.2.0-nightly-20261019-926ef06f0` |
| Android nested list items start their text after their own marker | [#1015](https://github.com/software-mansion/enriched-markdown/pull/1015), [#1023](https://github.com/software-mansion/enriched-markdown/pull/1023) (Android) | `1.2.0` |
| Fork change | Upstream | Released in |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
| Android measurements survive parent clones | [#924](https://github.com/software-mansion/enriched-markdown/pull/924) | after `1.2.0-nightly-20261019-926ef06f0` |
| Android long-press drag selection keeps parent intercept disallowed | [#1012](https://github.com/software-mansion/enriched-markdown/pull/1012) | `1.2.0` |
| Android nested list items start their text after their own marker | [#1015](https://github.com/software-mansion/enriched-markdown/pull/1015), [#1023](https://github.com/software-mansion/enriched-markdown/pull/1023) (Android) | `1.2.0` |
## Engine constraints
+64 -2
View File
@@ -462,8 +462,55 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a
[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
the provider process, so a reload must not reopen agents the plugin does not change.
### Launch wrap
An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that
session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell,
except Windows script launchers, which go through cmd.exe like any provider launcher
(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must
be an absolute path.
The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen
reuses the wrap it opened with.
- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the
provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an
absent field means unsupported, which is also what a host without this feature reports. Core
providers declare it in the provider contract table in `provider-registry.ts`; every core provider
that starts a local harness declares it, and custom ACP providers and providers that extend a core
one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`;
`runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the
registration metadata, so it is in the snapshot before the provider first connects.
- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return
the same value. A different value fails the open.
- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It
throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not
declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host
that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the
spawn; nothing retries the bare command.
Once an open selects a wrap, a supported provider runs that session's harness through it or fails
before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the
argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it
(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for
the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP
client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated
server instead; an explicitly configured external OpenCode server cannot be wrapped and the open
fails. The guarantee does not cover:
1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap.
2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog
lookup during create when no model is set.
3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's
initialize probe included), catalog and session listing, version and update commands, usage
queries, and Codex native archive and unarchive.
4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped.
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
@@ -483,6 +530,17 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
`plugin-examples/worktrunk`.
`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run.
Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle
module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's
`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and
no previous-version adapter is needed. A default-shell terminal resolves the shell there through
`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty.
The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not
report command completion. A setup or teardown wrap goes in front of the
`buildStringCommandShellInvocation` argv.
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
@@ -582,6 +640,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
no provider reload input.
Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can
run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See
[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both.
For an ACP command, register `runAcpProvider({ id, label, command })` from
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
+68 -11
View File
@@ -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
View File
@@ -1 +1 @@
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
+20 -1
View File
@@ -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",
+3
View File
@@ -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();
}
@@ -1,6 +1,7 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
chooseProjectWithKeyboard,
connectNewWorkspaceDaemonClient,
expectNewWorkspaceControlsEnabled,
expectNewWorkspaceProjectSelected,
@@ -176,6 +177,33 @@ test.describe("New workspace entry points", () => {
}
});
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
page,
}) => {
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
try {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openGlobalNewWorkspaceComposer(page);
const composer = page.getByRole("textbox", { name: "Message agent..." });
await page.getByTestId("new-workspace-project-picker-trigger").click();
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
await expect(composer).toBeFocused();
await page.keyboard.press("Control+N");
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
await expect(composer).toBeFocused();
} finally {
await projectA.cleanup();
await projectB.cleanup();
}
});
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
page,
}) => {
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import {
chooseProjectWithKeyboard,
expectNewWorkspaceDraft,
fillNewWorkspaceDraft,
openNewWorkspaceComposer,
@@ -109,6 +110,27 @@ test.describe("New workspace: launching a terminal", () => {
});
});
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
page,
}) => {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: workspace.projectKey,
projectDisplayName: workspace.projectDisplayName,
});
await selectLaunchOption(page, BARE_PROFILE.id);
await expect(terminalPromptInput(page)).toHaveCount(0);
// The read-only command preview has nothing to type into, so the picker
// hands focus back to the field that opened it.
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
await projectTrigger.focus();
await page.keyboard.press("Enter");
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
await expect(projectTrigger).toBeFocused();
});
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
page,
}) => {
@@ -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();
}
@@ -0,0 +1,121 @@
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { getServerId } from "../support/helpers/server-id";
import { seedWorkspace } from "../support/helpers/seed-client";
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
// Cmd on macOS, Ctrl on Windows and Linux: the platform primary modifier the app binds as `mod`.
const MOD = "ControlOrMeta";
type SeededProject = Awaited<ReturnType<typeof seedWorkspace>>;
async function seedProjectWithWorkspaces(count: number) {
const project = await seedWorkspace({ repoPrefix: "sidebar-selection-" });
const workspaceIds = [project.workspaceId];
for (let index = 1; index < count; index += 1) {
const created = await project.client.createWorkspace({
source: { kind: "directory", path: project.repoPath, projectId: project.projectId },
title: `Selection workspace ${index}`,
});
if (!created.workspace) throw new Error(created.error ?? "Failed to seed a workspace");
workspaceIds.push(created.workspace.id);
}
return { project, workspaceIds };
}
/** The seeded rows, in the order the sidebar shows them. */
async function rowsInSidebarOrder(page: Page, workspaceIds: readonly string[]) {
const testIds = workspaceIds.map((id) => `sidebar-workspace-row-${getServerId()}:${id}`);
const rows = page.locator(testIds.map((testId) => `[data-testid="${testId}"]`).join(", "));
await expect(rows).toHaveCount(workspaceIds.length);
const ordered = await rows.evaluateAll((elements) =>
elements.map((element) => element.getAttribute("data-testid") ?? ""),
);
return ordered.map((testId) => page.getByTestId(testId));
}
async function expectChecked(rows: readonly Locator[], checked: readonly boolean[]) {
for (const [index, row] of rows.entries()) {
await expect(row).toHaveAttribute("aria-checked", String(checked[index]));
}
}
async function expectSelectedCount(page: Page, count: number) {
await expect(page.getByTestId("workspace-selection-count")).toHaveText(`${count} selected`);
}
async function exitSelection(page: Page) {
await page.getByTestId("workspace-selection-exit").click();
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
}
/**
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
*/
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
const [first, second, third, fourth] = rows;
await first.click();
await expect(first).toHaveAttribute("aria-selected", "true");
const openWorkspaceUrl = page.url();
await third.click({ modifiers: [MOD] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]);
await fourth.click({ modifiers: [MOD] });
await expectChecked(rows, [false, false, true, true]);
await third.click({ modifiers: [MOD] });
await expectChecked(rows, [false, false, false, true]);
await second.click();
await expectChecked(rows, [false, true, false, true]);
expect(page.url()).toBe(openWorkspaceUrl);
await exitSelection(page);
await second.click({ modifiers: ["Shift"] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, true, false, false]);
await fourth.click({ modifiers: ["Shift"] });
await expectChecked(rows, [false, true, true, true]);
await third.click({ modifiers: ["Shift"] });
await expectChecked(rows, [false, true, true, false]);
await first.click({ modifiers: ["Shift"] });
await expectChecked(rows, [true, true, false, false]);
await fourth.click({ modifiers: [MOD] });
await third.click({ modifiers: ["Shift"] });
await expectChecked(rows, [true, true, true, true]);
expect(page.url()).toBe(openWorkspaceUrl);
await exitSelection(page);
}
test.describe("sidebar workspace selection clicks", () => {
let seeded: { project: SeededProject; workspaceIds: string[] } | null = null;
test.afterEach(async () => {
await seeded?.project.cleanup();
seeded = null;
});
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await selectSidebarStatusGrouping(page);
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
});
@@ -153,3 +153,25 @@ On iPad, replacing the field a second time appends text. For this Settings journ
native clipboard Paste menu, then continue the assertions manually. Dismiss the password keyboard
with Done to submit when the Connect button is below the keyboard. The welcome pairing regression
runs end to end without these adjustments.
## Sheet footer keyboard safe-area clearance
`footer-keyboard.android.sh` records the **Add project** sheet on an Android device or emulator
across repeated keyboard open/dismiss transitions, then runs `assert-sheet-footer-keyboard.mjs`
over every recorded frame. Configure three-button navigation, `show_ime_with_hard_keyboard=1`, and
a visible soft keyboard (such as Gboard) on the test device before running so the script does not
mutate device settings. The assertion checks both settled positions against the navigation bar
height and fails if any frame drops the **Open project** button into the navigation bar or
overshoots above its open-keyboard position.
```sh
ANDROID_SERIAL=emulator-5554 \
packages/app/e2e/mobile/modal-sheet/footer-keyboard.android.sh
```
You can also validate an existing screen recording directly (optionally passing pixel tolerance and
navigation bar height in pixels):
```sh
node packages/app/e2e/mobile/modal-sheet/assert-sheet-footer-keyboard.mjs /path/to/recording.mp4 4 96
```
@@ -0,0 +1,173 @@
import { execFileSync, spawnSync } from "node:child_process";
import process from "node:process";
const [, , videoPath, toleranceArg = "4", navBarHeightArg = "0"] = process.argv;
if (!videoPath) {
throw new Error(
"Usage: node assert-sheet-footer-keyboard.mjs <screenrecord.mp4> [pixel-tolerance] [nav-bar-height-px]",
);
}
const tolerance = Number(toleranceArg);
if (!Number.isFinite(tolerance) || tolerance < 0) {
throw new Error(`Invalid pixel tolerance: ${toleranceArg}`);
}
const navBarHeight = Number(navBarHeightArg);
if (!Number.isFinite(navBarHeight) || navBarHeight < 0) {
throw new Error(`Invalid navigation bar height: ${navBarHeightArg}`);
}
function probeDimensions(filePath) {
const output = execFileSync(
"ffprobe",
[
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height",
"-of",
"csv=s=x:p=0",
filePath,
],
{ encoding: "utf8" },
).trim();
const [width, height] = output.split("x").map(Number);
if (!width || !height) {
throw new Error(`Unable to read video dimensions for ${filePath}: ${output}`);
}
return { width, height };
}
function measureButtonBottomPerFrame(filePath, width, height) {
const centerX = Math.floor(width / 2);
// Decode only the 1px vertical centerline so full-rate recordings fit comfortably in memory.
const result = spawnSync(
"ffmpeg",
[
"-v",
"error",
"-i",
filePath,
"-vf",
`format=rgb24,crop=1:${height}:${centerX}:0`,
"-vsync",
"0",
"-f",
"rawvideo",
"-pix_fmt",
"rgb24",
"-",
],
{ maxBuffer: 64 * 1024 * 1024 },
);
if (result.status !== 0) {
throw new Error(`ffmpeg failed (${result.status}): ${result.stderr?.toString("utf8") ?? ""}`);
}
const buffer = result.stdout;
const frameSize = height * 3;
const frameCount = Math.floor(buffer.length / frameSize);
// Restrict vertical scan below the search field so its green focus ring is excluded.
const scanTop = Math.floor(height * 0.42);
const bottoms = [];
for (let frame = 0; frame < frameCount; frame += 1) {
const frameOffset = frame * frameSize;
let maxY = null;
for (let y = scanTop; y < height; y += 1) {
const offset = frameOffset + y * 3;
const r = buffer[offset];
const g = buffer[offset + 1];
const b = buffer[offset + 2];
// Matches the green primary "Open project" button (both enabled and disabled states).
if (g > 50 && g > r + 15 && g > b + 10) {
maxY = y;
}
}
bottoms.push(maxY);
}
return bottoms;
}
function findSettledValue(values, minRunLength) {
let runValue = null;
let runLength = 0;
for (const value of values) {
if (value !== null && runValue !== null && Math.abs(value - runValue) <= 2) {
runLength += 1;
if (runLength >= minRunLength) return runValue;
} else {
runValue = value;
runLength = value === null ? 0 : 1;
}
}
return null;
}
const { width, height } = probeDimensions(videoPath);
const bottoms = measureButtonBottomPerFrame(videoPath, width, height);
const visibleFrames = bottoms
.map((bottom, frame) => ({ frame, bottom }))
.filter((entry) => entry.bottom !== null);
if (visibleFrames.length < 10) {
throw new Error(
`Expected at least 10 frames with the Open project footer button visible, found ${visibleFrames.length}`,
);
}
// Identify settled resting (keyboard closed, lower on screen) and open (keyboard shown, higher on
// screen) positions by finding stable runs separated by at least 200px of keyboard height.
const minBottom = Math.min(...visibleFrames.map((entry) => entry.bottom));
const maxBottom = Math.max(...visibleFrames.map((entry) => entry.bottom));
const midpoint = (minBottom + maxBottom) / 2;
const closedSettled = findSettledValue(
bottoms.map((y) => (y !== null && y > midpoint ? y : null)),
15,
);
const openSettled = findSettledValue(
bottoms.map((y) => (y !== null && y < midpoint ? y : null)),
15,
);
if (closedSettled === null || openSettled === null || closedSettled - openSettled < 200) {
throw new Error(
`Recording did not capture settled keyboard-closed (${closedSettled}) and keyboard-open (${openSettled}) states`,
);
}
const maxAllowedBottom =
navBarHeight > 0
? Math.min(closedSettled + tolerance, height - navBarHeight)
: closedSettled + tolerance;
const belowNavViolations = visibleFrames.filter((entry) => entry.bottom > maxAllowedBottom);
const overshootViolations = visibleFrames.filter((entry) => entry.bottom < openSettled - tolerance);
if (belowNavViolations.length > 0 || overshootViolations.length > 0) {
const summary = [
`Sheet footer keyboard transition jank detected in ${videoPath}:`,
` settled closed bottom=${closedSettled}px (gap=${height - closedSettled}px), settled open bottom=${openSettled}px (gap=${height - openSettled}px), maxAllowedBottom=${maxAllowedBottom}px`,
];
if (belowNavViolations.length > 0) {
const worst = Math.max(...belowNavViolations.map((entry) => entry.bottom));
summary.push(
` dropped below safe-area clearance on ${belowNavViolations.length} frames (first=f${belowNavViolations[0].frame}, last=f${belowNavViolations.at(-1).frame}, worst bottom=${worst}px, excess=+${worst - maxAllowedBottom}px)`,
);
}
if (overshootViolations.length > 0) {
const worst = Math.min(...overshootViolations.map((entry) => entry.bottom));
summary.push(
` overshot above open keyboard position on ${overshootViolations.length} frames (first=f${overshootViolations[0].frame}, worst bottom=${worst}px, overshoot=-${openSettled - worst}px)`,
);
}
throw new Error(summary.join("\n"));
}
process.stdout.write(
`Sheet footer stayed within bounds across ${bottoms.length} frames (${visibleFrames.length} visible): closed=${closedSettled}px, open=${openSettled}px, maxAllowed=${maxAllowedBottom}px, 0 nav-bar overlap frames, 0 overshoot frames\n`,
);
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
set -euo pipefail
# Verifies that the Add project bottom sheet footer never flashes behind the Android system
# navigation bar on keyboard dismiss or overshoots upward on keyboard open.
#
# Prerequisites (configured on the test device before running):
# - Three-button navigation bar enabled (for example:
# `adb shell cmd overlay enable com.android.internal.systemui.navbar.threebutton`).
# - Software keyboard enabled when a hardware keyboard is attached (`show_ime_with_hard_keyboard=1`)
# and a visible soft keyboard (such as Gboard) selected as the active IME.
# - The Add project sheet already open with a connected host so the Open project footer button is
# visible.
# - `ffmpeg` and `ffprobe` on PATH.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERIAL="${ANDROID_SERIAL:-$(adb devices | awk '/\tdevice$/ {print $1; exit}')}"
OUT_DIR="${SHEET_FOOTER_QA_DIR:-/tmp/paseo-sheet-footer-qa}"
VIDEO_PATH="$OUT_DIR/sheet-footer-keyboard.mp4"
if [ -z "$SERIAL" ]; then
echo "No Android device attached. Set ANDROID_SERIAL or start an emulator." >&2
exit 1
fi
mkdir -p "$OUT_DIR"
# Derive tap coordinates and 3-button navigation bar height (48dp) from the active display metrics.
SIZE_LINE="$(adb -s "$SERIAL" shell wm size | tail -n 1 | tr -d '\r')"
DIMENSIONS="${SIZE_LINE##* }"
WIDTH="${DIMENSIONS%x*}"
HEIGHT="${DIMENSIONS#*x}"
DENSITY_LINE="$(adb -s "$SERIAL" shell wm density | tail -n 1 | tr -d '\r')"
DENSITY="${DENSITY_LINE##* }"
NAV_BAR_PX="${SHEET_FOOTER_NAV_BAR_PX:-$((48 * DENSITY / 160))}"
SEARCH_X=$((WIDTH / 2))
SEARCH_Y=$((HEIGHT * 34 / 100))
adb -s "$SERIAL" shell rm -f /sdcard/sheet-footer-keyboard.mp4
adb -s "$SERIAL" shell screenrecord --time-limit 9 --bit-rate 8000000 /sdcard/sheet-footer-keyboard.mp4 &
REC_PID=$!
sleep 0.8
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
sleep 1.8
adb -s "$SERIAL" shell input keyevent 4
sleep 1.8
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
sleep 1.8
adb -s "$SERIAL" shell input keyevent 4
wait "$REC_PID" || true
adb -s "$SERIAL" pull /sdcard/sheet-footer-keyboard.mp4 "$VIDEO_PATH" >/dev/null
node "$SCRIPT_DIR/assert-sheet-footer-keyboard.mjs" "$VIDEO_PATH" 4 "$NAV_BAR_PX"
@@ -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,6 +243,14 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
await expect(searchInput).toBeFocused();
}
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
const searchInput = page.getByPlaceholder("Search projects");
await expect(searchInput).toBeFocused({ timeout: 30_000 });
await page.keyboard.type(projectName);
await page.keyboard.press("Enter");
await expect(searchInput).toBeHidden({ timeout: 10_000 });
}
export async function expectNewWorkspaceProjectSelected(
page: Page,
projectDisplayName: string,
+1 -1
View File
@@ -40,7 +40,7 @@
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
"build:apk": "npm --prefix ../.. run build:apk",
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -17,7 +17,12 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { DraggableListHandle } from "@/components/draggable-list";
import { useOpenKebabMenuVisibility } from "@/components/sidebar/use-open-kebab-menu-visibility";
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
import {
bySizing,
ICON_BUTTON_SIZES,
mapLayout,
TOUCH_TARGET,
} from "@/components/ui/control-geometry";
import {
DropdownMenu,
DropdownMenuContent,
@@ -41,11 +46,16 @@ import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
/** Shared column & rail geometry consumed by both RosterTableHeader and AgentProfileRow. */
export const ROSTER_COL_PROFILE_WIDTH = 184;
export const ROSTER_COL_RUNTIME_WIDTH = 248;
export const ROSTER_GRIP_WIDTH = bySizing({ touch: 28, pointer: 20 });
export const ROSTER_TRAILING_WIDTH = bySizing({ touch: TOUCH_TARGET + 14, pointer: 42 });
const ROW_MIN_HEIGHT = bySizing({ touch: TOUCH_TARGET + 16, pointer: 56 });
const GRIP_HANDLE_HEIGHT = bySizing({ touch: TOUCH_TARGET, pointer: 28 });
const KEBAB_GLYPH_SIZE = ICON_SIZE.sm;
// The kebab's hitbox is larger than its glyph; it overhangs the row so the glyph sits on the
// card's trailing rail and the hitbox does not make the row taller.
const KEBAB_HITBOX_OVERHANG = bySizing({
touch: (ICON_BUTTON_SIZES.small.touch - KEBAB_GLYPH_SIZE) / 2,
pointer: (ICON_BUTTON_SIZES.small.pointer - KEBAB_GLYPH_SIZE) / 2,
});
const ThemedGripVertical = withUnistyles(GripVertical);
const ThemedMoreVertical = withUnistyles(MoreVertical);
@@ -130,7 +140,7 @@ function AgentProfileRowMenu({
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
testID={`agent-profile-menu-${profileId}`}
>
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
<ThemedMoreVertical size={KEBAB_GLYPH_SIZE} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<DropdownMenuContent side="bottom" align="end" width={180}>
<DropdownMenuItem
@@ -231,16 +241,9 @@ function AgentProfileRowContent({
<Text style={styles.nameText} numberOfLines={1}>
{profile.name}
</Text>
<View style={styles.stackedSpecLine}>
<AgentProfileGlyph
provider={profile.provider}
serverId={serverId}
size={ICON_SIZE.xs}
/>
<Text style={styles.stackedSpecText} numberOfLines={1}>
{fullSummary}
</Text>
</View>
<Text style={styles.stackedSpecText} numberOfLines={1}>
{fullSummary}
</Text>
{profile.notes ? (
<Text
style={styles.stackedNotesText}
@@ -372,8 +375,8 @@ export function AgentProfileRow({
[dragging, isFirst, isHovered, menuProps.open, selected],
);
const gripVisibilityStyle = useMemo(
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
const gripStyle = useMemo(
() => (showRowAffordances ? styles.grip : [styles.grip, styles.affordanceHidden]),
[showRowAffordances],
);
const kebabVisibilityStyle = useMemo(
@@ -399,22 +402,6 @@ export function AgentProfileRow({
{selected ? <View style={styles.selectedIndicator} pointerEvents="none" /> : null}
{reorderable ? (
<View style={gripVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<DraggableListHandle
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
name: profile.name,
})}
style={styles.gripHandle}
testID={`agent-profile-drag-${profile.id}`}
>
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
</DraggableListHandle>
</View>
) : (
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
)}
<AgentProfileRowContent
serverId={serverId}
profile={profile}
@@ -425,7 +412,8 @@ export function AgentProfileRow({
isStacked={isStacked}
/>
<View style={styles.trailing}>
{/* A stacked row opens on tap like the wide one; the kebab alone ends it, on the trailing rail. */}
<View style={isStacked ? styles.trailingStacked : styles.trailing}>
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<AgentProfileRowMenu
profileId={profile.id}
@@ -442,13 +430,27 @@ export function AgentProfileRow({
onRemove={handleRemove}
/>
</View>
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevronRight
size={ICON_SIZE.sm}
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
/>
</View>
{isStacked ? null : (
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevronRight
size={ICON_SIZE.sm}
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
</View>
{reorderable ? (
<DraggableListHandle
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
name: profile.name,
})}
style={gripStyle}
testID={`agent-profile-drag-${profile.id}`}
>
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
</DraggableListHandle>
) : null}
</View>
);
}
@@ -460,8 +462,7 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
minHeight: ROW_MIN_HEIGHT,
paddingVertical: theme.spacing[3],
paddingLeft: theme.spacing[2],
paddingRight: theme.spacing[4],
paddingHorizontal: theme.spacing[4],
gap: theme.spacing[2],
},
rowHovered: {
@@ -491,19 +492,15 @@ const styles = StyleSheet.create((theme) => ({
passThrough: {
pointerEvents: "none",
},
gripSlot: {
width: ROSTER_GRIP_WIDTH,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
gripSpacerCompact: {
width: theme.spacing[2],
flexShrink: 0,
},
gripHandle: {
width: ROSTER_GRIP_WIDTH,
height: GRIP_HANDLE_HEIGHT,
// The grip hangs in the row's leading padding, as on a Usage card, so the icon tile sits on the
// card's rail with or without it and revealing it on hover moves nothing. It takes the padding's
// full height so a finger finds it.
grip: {
position: "absolute",
left: 0,
top: 0,
bottom: 0,
width: theme.spacing[4],
alignItems: "center",
justifyContent: "center",
},
@@ -585,12 +582,6 @@ const styles = StyleSheet.create((theme) => ({
minWidth: 0,
gap: theme.spacing[0.5],
},
stackedSpecLine: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
stackedSpecText: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
@@ -609,6 +600,11 @@ const styles = StyleSheet.create((theme) => ({
gap: theme.spacing[1],
flexShrink: 0,
},
trailingStacked: {
flexShrink: 0,
marginRight: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
marginVertical: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
},
kebabSlot: {
alignItems: "center",
justifyContent: "center",
@@ -44,7 +44,6 @@ import {
AgentProfileRow,
ROSTER_COL_PROFILE_WIDTH,
ROSTER_COL_RUNTIME_WIDTH,
ROSTER_GRIP_WIDTH,
ROSTER_TRAILING_WIDTH,
} from "./agent-profile-row";
@@ -90,7 +89,6 @@ function RosterTableHeader(): ReactElement {
const { t } = useTranslation();
return (
<View style={styles.tableHeader}>
<View style={styles.tableHeaderGripSpacer} />
<View style={styles.tableHeaderColumns}>
<Text style={[styles.tableHeaderText, styles.colProfileHeader]} numberOfLines={1}>
{t("settings.host.agentProfiles.columns.profile")}
@@ -1030,16 +1028,11 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
paddingVertical: theme.spacing[2],
paddingLeft: theme.spacing[2],
paddingRight: theme.spacing[4],
paddingHorizontal: theme.spacing[4],
gap: theme.spacing[2],
borderBottomWidth: theme.borderWidth[1],
borderBottomColor: theme.colors.border,
},
tableHeaderGripSpacer: {
width: ROSTER_GRIP_WIDTH,
flexShrink: 0,
},
tableHeaderColumns: {
flex: 1,
minWidth: 0,
@@ -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"));
@@ -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",
+5
View File
@@ -408,6 +408,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,
);
@@ -1166,6 +1170,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
agentId={agentId}
serverId={resolvedServerId}
epoch={timelineEpoch}
rewindSeq={timelineRewindSeq}
items={findItems}
viewportRef={viewportRef}
revealLoadedMessage={revealLoadedMessage}
@@ -1,4 +1,6 @@
import { describe, expect, it } from "vitest";
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
import { resolveWorkspaceFilePaths } from "@/workspace/file-open";
import {
classifyAssistantFileLink,
normalizeInlinePathTarget,
@@ -611,3 +613,43 @@ describe("encoded filename line markers", () => {
},
);
});
describe("slash-prefixed drive links in Windows workspaces", () => {
it.each([
["/E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
["/E:/demo/repo/docs/my%20file.md#L12", "E:/demo/repo/docs/my file.md", 12],
["/E:/demo/repo/docs/guide.md:12", "E:/demo/repo/docs/guide.md", 12],
["E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
["file:///E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
])("resolves %s to the workspace read target", (href, path, lineStart) => {
const workspaceRoot = "E:\\demo\\repo";
const target = parseAssistantFileLink(href, {
workspaceRoot,
decodeHref: true,
explicitLink: true,
});
expect(target).toMatchObject({ raw: href, path });
expect(target?.lineStart).toBe(lineStart);
expect(resolveFilePreviewReadTarget({ path: target!.path, workspaceRoot })).toEqual({
cwd: workspaceRoot,
path,
});
expect(resolveWorkspaceFilePaths({ path: target!.path, workspaceRoot })).toEqual({
absolutePath: path,
relativePath: path.slice("E:/demo/repo/".length),
});
});
it.each(["/home/demo/repo", undefined])(
"preserves POSIX paths with workspace %s",
(workspaceRoot) => {
expect(
parseAssistantFileLink("/E:/demo/repo/tools/tool.vbs", {
workspaceRoot,
decodeHref: true,
explicitLink: true,
})?.path,
).toBe("/E:/demo/repo/tools/tool.vbs");
},
);
});
+10 -2
View File
@@ -260,7 +260,7 @@ export function parseAssistantFileLink(
return fileUrlTarget;
}
const trimmed = value?.trim();
const trimmed = normalizeWindowsLinkPath(value?.trim(), options.workspaceRoot);
if (!trimmed) {
return null;
}
@@ -271,7 +271,7 @@ export function parseAssistantFileLink(
const inlinePathTarget = parseAssistantInlinePathLink(trimmed, options);
if (inlinePathTarget) {
return inlinePathTarget;
return { ...inlinePathTarget, raw: value };
}
const windowsTarget = parseWindowsFileLink(trimmed, value, options);
@@ -350,6 +350,14 @@ export function isFileLookingAssistantToken(value: string): boolean {
return isPlausibleAssistantLocalPath(path);
}
// A drive-based workspace identifies the target host's path syntax, even when
// the client runs elsewhere. Preserve the same spelling on POSIX hosts.
function normalizeWindowsLinkPath(value: string, workspaceRoot?: string): string {
return /^[A-Za-z]:[\\/]/.test(workspaceRoot?.trim() ?? "") && /^\/[A-Za-z]:[\\/]/.test(value)
? value.slice(1)
: value;
}
function parseWindowsFileLink(
trimmed: string,
raw: string,
@@ -1,48 +0,0 @@
import { describe, expect, it } from "vitest";
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
describe("getCompactSheetSafeAreaPadding", () => {
it("assigns safe clearance to the footer independently of decorative padding", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: false,
hasFooter: true,
safeAreaBottom: 34,
}),
).toEqual({ footerPaddingBottom: 34 });
});
it("assigns safe clearance to the body only without a footer", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: false,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({ contentPaddingBottom: 34 });
});
it("does not add a safe-area band above the compact keyboard", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible: true,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({});
});
it("does not inset desktop sheets", () => {
expect(
getCompactSheetSafeAreaPadding({
isCompact: false,
isKeyboardVisible: false,
hasFooter: false,
safeAreaBottom: 34,
}),
).toEqual({});
});
});
@@ -1,28 +0,0 @@
export interface CompactSheetSafeAreaPaddingInput {
isCompact: boolean;
isKeyboardVisible: boolean;
hasFooter: boolean;
safeAreaBottom: number;
}
export interface CompactSheetSafeAreaPadding {
contentPaddingBottom?: number;
footerPaddingBottom?: number;
}
export function getCompactSheetSafeAreaPadding({
isCompact,
isKeyboardVisible,
hasFooter,
safeAreaBottom,
}: CompactSheetSafeAreaPaddingInput): CompactSheetSafeAreaPadding {
if (!isCompact || isKeyboardVisible || safeAreaBottom <= 0) {
return {};
}
if (hasFooter) {
return { footerPaddingBottom: safeAreaBottom };
}
return { contentPaddingBottom: safeAreaBottom };
}
@@ -20,12 +20,11 @@ import {
IsolatedBottomSheetModal,
SheetVisibleFrame,
type ContextBridge,
useBottomSheetSafeAreaPaddingStyle,
useIsolatedBottomSheetVisibility,
} from "@/components/ui/isolated-bottom-sheet-modal";
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
import { ScrollView } from "@/components/ui/scroll-view";
import { isWeb } from "@/constants/platform";
import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
@@ -610,8 +609,9 @@ export interface SheetKeyboard {
}
/**
* The compact sheet's body. It renders on the far side of the sheet's portal so it reads the
* screen's bottom inset, not the one left where the sheet was opened: inside a sheet tab, none is.
* The compact sheet's body. It renders on the far side of the sheet's portal so `SheetVisibleFrame`
* and `useBottomSheetSafeAreaPaddingStyle` read the screen's bottom inset, not the one left where
* the sheet was opened: inside a sheet tab, none is.
*/
function CompactSheetBody({
header,
@@ -619,7 +619,6 @@ function CompactSheetBody({
onClose,
testID,
footer,
isKeyboardVisible,
scrollable,
bodyStyle,
contentStyle,
@@ -630,32 +629,18 @@ function CompactSheetBody({
onClose: () => void;
testID?: string;
footer: ReactNode;
isKeyboardVisible: boolean;
scrollable: boolean;
bodyStyle?: StyleProp<ViewStyle>;
contentStyle?: StyleProp<ViewStyle>;
children: ReactNode;
}) {
const insets = useSafeAreaInsets();
const { contentPaddingBottom = 0, footerPaddingBottom = 0 } = getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible,
hasFooter: Boolean(footer),
safeAreaBottom: insets.bottom,
});
// Safe-area clearance is a separate layer: it must not replace the caller's
// padding (including an explicit zero), and the footer owns it when present.
const bodyClearanceStyle = { paddingBottom: contentPaddingBottom };
const footerClearanceStyle = useMemo(
() => ({ paddingBottom: footerPaddingBottom }),
[footerPaddingBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerClearanceStyle}>{footer}</View> : null),
[footer, footerClearanceStyle],
);
// Safe-area clearance is owned on the UI thread in lockstep with `SheetVisibleFrame`'s keyboard
// height: `SheetVisibleFrame` pads the frame whenever a footer or non-scrollable body is shown,
// while a scrollable body without a footer pads its scroll content so items scroll behind the
// system bar and still clear it at rest.
const bodyClearanceStyle = useBottomSheetSafeAreaPaddingStyle(scrollable && !footer);
return (
<SheetVisibleFrame footer={footerView}>
<SheetVisibleFrame footer={footer} safeAreaInset={scrollable ? "footer" : "frame"}>
{header ? (
<SheetHeaderView
header={header}
@@ -672,12 +657,12 @@ function CompactSheetBody({
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
<View style={[styles.contentGrow, bodyClearanceStyle]}>
<Animated.View style={[SCROLL_CONTENT_GROW, bodyClearanceStyle]}>
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
</View>
</Animated.View>
</ScrollView>
) : (
<View style={[styles.compactStaticContent, bodyClearanceStyle]}>
<View style={styles.compactStaticContent}>
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
{children}
</SheetContent>
@@ -710,7 +695,6 @@ export function AdaptiveModalSheet({
}: AdaptiveModalSheetProps) {
const { t } = useTranslation();
const isMobile = useIsCompactFormFactor();
const isKeyboardVisible = useKeyboardVisibility(visible);
const resolvedSnapPoints = useMemo(() => snapPoints ?? ["65%", "90%"], [snapPoints]);
const isSheet = isMobile || !isWeb;
// The sheet registers itself; the desktop dialog does not use it.
@@ -828,7 +812,6 @@ export function AdaptiveModalSheet({
onClose={onClose}
testID={testID}
footer={footerView}
isKeyboardVisible={isKeyboardVisible}
scrollable={scrollable}
bodyStyle={bodyStyle}
contentStyle={contentStyle}
@@ -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/scroll-view";
import { useContentDrag } from "@/components/ui/content-drag";
import { createDragHold } from "./drag-reorder/drag-hold";
import { movedItemKey } from "./drag-reorder/native-drop";
import type {
@@ -232,6 +232,7 @@ export interface HostPickerProps {
open: boolean;
onOpenChange: (open: boolean) => void;
anchorRef: React.RefObject<View | null>;
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
includeAllHost?: boolean;
includeAddHost?: boolean;
onAddHost?: () => void;
@@ -254,6 +255,7 @@ export function HostPicker({
open,
onOpenChange,
anchorRef,
restoreFocusRef,
includeAllHost,
includeAddHost,
onAddHost,
@@ -404,6 +406,7 @@ export function HostPicker({
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
restoreFocusRef={restoreFocusRef}
desktopPlacement={desktopPlacement}
desktopMinWidth={desktopMinWidth}
/>
@@ -55,6 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarSelectionHost } from "@/sidebar-selection";
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
@@ -667,6 +668,7 @@ function MobileSidebar({
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
</SidebarToastRegion>
</SidebarViewSlot>
@@ -922,6 +924,7 @@ function DesktopSidebar({
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
</SidebarToastRegion>
</SidebarViewSlot>
@@ -8,10 +8,15 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { BackHeader } from "@/components/headers/back-header";
import { MenuHeader } from "@/components/headers/menu-header";
import { PressHighlight } from "@/components/ui/press-highlight";
import { withContentDrag } from "@/components/ui/content-drag";
import { useIsCompactFormFactor } from "@/constants/layout";
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView;
// Rows on a page drag to reorder, so the page stops scrolling while a drag holds the touch.
const PageScrollView =
Platform.OS === "android"
? withContentDrag(KeyboardAwareScrollView)
: withContentDrag(ScrollView);
interface PageLayoutProps {
title?: string;
@@ -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()
@@ -66,12 +66,16 @@ function heightOf(testID: string): number {
return element(testID).getBoundingClientRect().height;
}
function titleFontSize(rowTestID: string, label: string): number {
const title = [...element(rowTestID).querySelectorAll("div")].find(
(node) => node.textContent === label && node.children.length === 0,
function textNode(rowTestID: string, text: string): HTMLElement {
const found = [...element(rowTestID).querySelectorAll("div")].find(
(node) => node.textContent === text && node.children.length === 0,
);
if (!title) throw new Error(`No title ${label}`);
return Number.parseFloat(getComputedStyle(title).fontSize);
if (!found) throw new Error(`No text ${text}`);
return found;
}
function titleFontSize(rowTestID: string, label: string): number {
return Number.parseFloat(getComputedStyle(textNode(rowTestID, label)).fontSize);
}
describe("settings row density", () => {
@@ -100,4 +104,52 @@ describe("settings row density", () => {
titleFontSize("card-row", "Card row"),
);
});
it("keeps a row with a long summary one line tall on a phone-width card", () => {
container = document.createElement("div");
// A 393pt phone less the sheet's side padding.
container.style.width = "360px";
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<SettingsCard>
<SettingsRow label="Text only" testID="text-row" />
<SettingsCollapsibleRow
label="Customize settings"
summary="Auto mode · Medium · 2 features · Add a note for when to use it"
testID="long-summary"
>
<SettingsRow label="Nested" />
</SettingsCollapsibleRow>
</SettingsCard>,
),
);
expect(heightOf("long-summary-toggle")).toBe(heightOf("text-row"));
});
it("keeps a short summary beside the chevron on a wide card", () => {
container = document.createElement("div");
container.style.width = "680px";
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<SettingsCard>
<SettingsDetailRow
label="Speech to text"
summary="Local"
onPress={openNothing}
testID="short-summary"
/>
</SettingsCard>,
),
);
const row = element("short-summary").getBoundingClientRect();
const summary = textNode("short-summary", "Local").getBoundingClientRect();
// The summary's margin, the chevron and the row's padding: about 40px.
expect(row.right - summary.right).toBeLessThan(48);
});
});
@@ -88,9 +88,13 @@ export function SettingsRowHeader({
const hovered = pointerOver && !disabled;
const rowStyle = useMemo(() => [layout.row, hovered && styles.hovered], [hovered, layout]);
const chevronStyle = useMemo(
() => [styles.chevron, expanded && styles.chevronExpanded],
() => [styles.chevron, expanded && styles.chevronExpanded, styles.passThrough],
[expanded],
);
// A hint can be a sentence, so a hinted row gives the room to the label column and caps the
// summary. A label alone keeps its one-line width and the summary truncates in what is left.
const hinted = Boolean(hint || hintStatus);
const contentStyle = hinted ? settingsStyles.rowContent : styles.labelContent;
return (
<View
style={rowStyle}
@@ -113,7 +117,7 @@ export function SettingsRowHeader({
{leading}
</View>
) : null}
<View style={[settingsStyles.rowContent, styles.passThrough]}>
<View style={[contentStyle, styles.passThrough]}>
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<Text style={layout.title}>{label}</Text>
{labelAccessory}
@@ -128,28 +132,15 @@ export function SettingsRowHeader({
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
</View>
) : null}
<View style={[styles.trailing, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{external ? (
// Drawn the same as a section header's docs link, so the two read as one thing.
<ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel>
) : (
<>
{summary ? (
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
{disabled ? null : (
<View style={chevronStyle}>
<ThemedChevron
size={ICON_SIZE.sm}
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
</>
)}
</View>
<RowTrailing hinted={hinted} external={external} hovered={hovered} summary={summary} />
{external || disabled ? null : (
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevron
size={ICON_SIZE.sm}
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
</View>
);
}
@@ -160,6 +151,32 @@ const HIDDEN_FROM_ASSISTIVE_TECH = {
"aria-hidden": true,
} as const;
/** The summary before the chevron, or the external link label in its place. */
function RowTrailing({
hinted,
external,
hovered,
summary,
}: {
hinted: boolean;
external: boolean;
hovered: boolean;
summary: string | undefined;
}) {
const style = hinted ? styles.hintedTrailing : styles.labelTrailing;
return (
<View style={[style, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{/* Drawn the same as a section header's docs link, so the two read as one thing. */}
{external ? <ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel> : null}
{!external && summary ? (
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
</View>
);
}
/**
* The hint with its status mark. The line keeps the hint's own height in every status, so a row
* does not move when its value arrives or its work starts. A long error is cut to the line; the
@@ -222,10 +239,30 @@ const styles = StyleSheet.create((theme) => ({
passThrough: {
pointerEvents: "none",
},
trailing: {
// The label keeps its one-line width and takes the free space; the summary truncates in what is
// left. Any shrink, even a fraction of a pixel, would wrap the label, so it does not shrink. The
// cap lets a long label wrap before it pushes the chevron off the row. Past the cap, the auto
// margin takes the rest of the row, so the control, summary and chevron stay together at the end.
labelContent: {
flexGrow: 1,
flexShrink: 0,
maxWidth: "75%",
paddingRight: theme.spacing[3],
marginRight: "auto",
},
labelTrailing: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
minWidth: 0,
},
// A hinted row's column grows from zero width, so an unbounded summary would squeeze it to
// nothing and wrap the label one glyph per line. The summary keeps at most half the row.
hintedTrailing: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
maxWidth: "50%",
},
hintLine: {
flexDirection: "row",
@@ -101,7 +101,17 @@ import {
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility";
import {
createWorkspaceVisibilityPolicy,
selectSidebarGroupVisibility,
} from "@/components/sidebar/sidebar-group-visibility";
import {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
useWorkspaceSelectionPress,
} from "@/sidebar-selection";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
SidebarWorkspaceRowFrame,
@@ -284,6 +294,7 @@ interface WorkspaceRowInnerProps {
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onCopyBranchName?: () => void;
onCopyPath?: () => void;
@@ -607,12 +618,14 @@ function WorkspaceRowRightGroup({
isHovered,
isTouchPlatform,
isCreating,
isSelectionMode,
showShortcutBadge,
shortcutNumber,
archiveLabel,
archiveStatus,
archivePendingLabel,
archiveShortcutKeys,
onSelectWorkspace,
onArchive,
onMarkAsRead,
onMarkAsUnread,
@@ -627,12 +640,14 @@ function WorkspaceRowRightGroup({
isHovered: boolean;
isTouchPlatform: boolean;
isCreating: boolean;
isSelectionMode: boolean;
showShortcutBadge: boolean;
shortcutNumber: number | null;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
archiveShortcutKeys?: ShortcutKey[][] | null;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
@@ -660,6 +675,7 @@ function WorkspaceRowRightGroup({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode,
});
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
@@ -695,6 +711,7 @@ function WorkspaceRowRightGroup({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1065,6 +1082,7 @@ function WorkspaceRowInner({
archiveLabel,
archiveStatus = "idle",
archivePendingLabel,
onSelectWorkspace,
onArchive,
onCopyBranchName,
onCopyPath,
@@ -1079,6 +1097,8 @@ function WorkspaceRowInner({
}: WorkspaceRowInnerProps) {
const isCompact = useIsCompactFormFactor();
const [isHighlighted, setIsHighlighted] = useState(false);
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
const isTouchPlatform = platformIsNative || isCompact;
const interaction = useLongPressDragInteraction({
drag,
@@ -1091,30 +1111,51 @@ function WorkspaceRowInner({
...dragAttributes
} = dragHandleProps?.attributes ?? {};
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
didLongPressRef: interaction.didLongPressRef,
onPress,
selected,
});
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
workspaceKey: workspace.workspaceKey,
onNavigate: handleNavigatePress,
onPressIn: interaction.handlePressIn,
});
const rowSelected = isSelectionMode ? isBulkSelected : selected;
const accessibilityState = useMemo(
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
[isSelectionMode, isBulkSelected, selected],
);
const isEditingTitle = titleEditor !== null;
const disableDrag = isEditingTitle || isSelectionMode;
return (
<SidebarWorkspaceRowFrame
workspace={workspace}
isDragging={isDragging}
isEditingTitle={isEditingTitle}
isSelectionMode={isSelectionMode}
>
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered });
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
const workspaceRowStyle = getProjectWorkspaceRowStyle({
isDragging,
selected: rowSelected,
isHovered,
});
const backdrop = getSidebarRowBackdrop({
isDragging,
isHighlighted,
selected: rowSelected,
isHovered,
});
return (
<View
{...dragAttributes}
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
{...(disableDrag ? null : dragHandleProps?.listeners)}
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
style={styles.workspaceRowContainer}
{...hoverHandlers}
@@ -1131,6 +1172,7 @@ function WorkspaceRowInner({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1140,17 +1182,18 @@ function WorkspaceRowInner({
onTogglePin={onTogglePin}
openInFileManagerPath={workspace.workspaceDirectory}
disabled={isArchiving}
enabled={!isEditingTitle}
aria-selected={selected}
accessibilityRole="button"
enabled={!isEditingTitle && !isSelectionMode}
aria-selected={isSelectionMode ? undefined : selected}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
onHighlightChange={setIsHighlighted}
onPressIn={isEditingTitle ? undefined : interaction.handlePressIn}
onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove}
onPressOut={isEditingTitle ? undefined : interaction.handlePressOut}
onPress={isEditingTitle ? undefined : handlePress}
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
onTouchMove={disableDrag ? undefined : interaction.handleTouchMove}
onPressOut={disableDrag ? undefined : interaction.handlePressOut}
onPress={isEditingTitle ? undefined : handleRowPress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
<SidebarWorkspaceRowContent
@@ -1163,6 +1206,8 @@ function WorkspaceRowInner({
isHovered={isHovered}
isLoading={isArchiving || isCreating}
isCreating={isCreating}
isSelectionMode={isSelectionMode}
isBulkSelected={isBulkSelected}
shortcutNumber={shortcutNumber}
showShortcutBadge={showShortcutBadge}
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
@@ -1174,12 +1219,14 @@ function WorkspaceRowInner({
isHovered={isHovered}
isTouchPlatform={isTouchPlatform}
isCreating={isCreating}
isSelectionMode={isSelectionMode}
showShortcutBadge={showShortcutBadge}
shortcutNumber={shortcutNumber}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
archivePendingLabel={archivePendingLabel}
archiveShortcutKeys={archiveShortcutKeys}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
onCopyBranchName={onCopyBranchName}
onCopyPath={onCopyPath}
@@ -1265,6 +1312,10 @@ function WorkspaceRowWithMenu({
archiveController.archive();
}, [archiveController, isArchiving]);
const handleSelectWorkspace = useCallback(() => {
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
}, [workspace.workspaceKey]);
const clipboard = useWorkspaceClipboardActions();
const handleCopyPath = useCallback(() => {
clipboard.copyPath(workspace);
@@ -1317,6 +1368,7 @@ function WorkspaceRowWithMenu({
archiveLabel={t("sidebar.workspace.actions.archive")}
archiveStatus={isArchiving ? "pending" : "idle"}
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
onSelectWorkspace={handleSelectWorkspace}
onArchive={handleArchive}
onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined}
onCopyPath={handleCopyPath}
@@ -2199,6 +2251,62 @@ function ProjectModeList({
selection: selectionEnabled ? activeWorkspaceSelection : null,
expanded: pinnedChatsExpanded,
});
const visibleOrderInputRef = useRef({
pinnedCollapsed,
leadingPinnedChat,
visiblePinnedChats,
unpinnedProjects,
collapsedProjectKeys,
expandedProjectKeys,
selectionEnabled,
activeWorkspaceSelection,
workspaceEntriesByKey,
});
visibleOrderInputRef.current = {
pinnedCollapsed,
leadingPinnedChat,
visiblePinnedChats,
unpinnedProjects,
collapsedProjectKeys,
expandedProjectKeys,
selectionEnabled,
activeWorkspaceSelection,
workspaceEntriesByKey,
};
useEffect(() => {
return registerSidebarVisibleWorkspaceKeysReader(() => {
const current = visibleOrderInputRef.current;
const keys: string[] = [];
if (!current.pinnedCollapsed) {
if (current.leadingPinnedChat) keys.push(current.leadingPinnedChat.workspaceKey);
for (const item of current.visiblePinnedChats) {
keys.push(item.workspaceKey);
}
}
const policy = createWorkspaceVisibilityPolicy<SidebarWorkspacePlacement>(
current.workspaceEntriesByKey,
);
const selection = current.selectionEnabled ? current.activeWorkspaceSelection : null;
for (const project of current.unpinnedProjects) {
if (current.collapsedProjectKeys.has(project.viewKey) || project.workspaces.length === 0) {
continue;
}
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
items: project.workspaces,
selection,
expanded: current.expandedProjectKeys.has(project.viewKey),
policy,
});
if (leadingItem) keys.push(leadingItem.workspaceKey);
for (const item of visibleItems) {
keys.push(item.workspaceKey);
}
}
return keys;
});
}, []);
const nativeScrollGestureProps = useMemo(
() =>
parentGestureRef
@@ -3,7 +3,9 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type MutableRefObject,
type ReactNode,
@@ -69,7 +71,15 @@ import {
} from "@/components/sidebar/sidebar-workspace-menu";
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
import {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
useWorkspaceSelectionPress,
} from "@/sidebar-selection";
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
import type { DraggableListDragHandleProps } from "@/components/draggable-list.types";
@@ -154,6 +164,14 @@ export function SidebarStatusWorkspaceList({
() => setPinnedWorkspacesExpanded((current) => !current),
[],
);
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
const toggleGroupWorkspacesExpanded = useCallback((groupKey: string) => {
setExpandedGroupKeys((current) => {
const next = new Set(current);
if (!next.delete(groupKey)) next.add(groupKey);
return next;
});
}, []);
const {
leadingItem: leadingPinnedWorkspace,
visibleItems: visiblePinnedWorkspaces,
@@ -164,6 +182,56 @@ export function SidebarStatusWorkspaceList({
expanded: pinnedWorkspacesExpanded,
});
const visibleOrderInputRef = useRef({
pinnedCollapsed,
leadingPinnedWorkspace,
visiblePinnedWorkspaces,
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
activeWorkspaceSelection,
});
visibleOrderInputRef.current = {
pinnedCollapsed,
leadingPinnedWorkspace,
visiblePinnedWorkspaces,
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
activeWorkspaceSelection,
};
useEffect(() => {
return registerSidebarVisibleWorkspaceKeysReader(() => {
const current = visibleOrderInputRef.current;
const keys: string[] = [];
if (!current.pinnedCollapsed) {
if (current.leadingPinnedWorkspace) {
keys.push(current.leadingPinnedWorkspace.workspaceKey);
}
for (const item of current.visiblePinnedWorkspaces) {
keys.push(item.workspaceKey);
}
}
for (const group of current.groups) {
if (current.collapsedWorkspaceGroupKeys.has(group.key) || group.rows.length === 0) {
continue;
}
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
items: group.rows,
selection: current.activeWorkspaceSelection,
expanded: current.expandedGroupKeys.has(group.key),
policy: STATUS_GROUP_VISIBILITY,
});
if (leadingItem) keys.push(leadingItem.workspaceKey);
for (const item of visibleItems) {
keys.push(item.workspaceKey);
}
}
return keys;
});
}, []);
const statusShortcutIndex = showShortcutBadges
? shortcutIndexByWorkspaceKey
: EMPTY_SHORTCUT_INDEX;
@@ -262,6 +330,8 @@ export function SidebarStatusWorkspaceList({
<StatusGroupList
groups={groups}
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
expandedGroupKeys={expandedGroupKeys}
onToggleGroupWorkspacesExpanded={toggleGroupWorkspacesExpanded}
projectIconByProjectViewKey={projectIconByProjectViewKey}
shortcutIndex={statusShortcutIndex}
showShortcutBadges={showShortcutBadges}
@@ -303,6 +373,8 @@ export function SidebarStatusWorkspaceList({
function StatusGroupList({
groups,
collapsedWorkspaceGroupKeys,
expandedGroupKeys,
onToggleGroupWorkspacesExpanded,
projectIconByProjectViewKey,
shortcutIndex,
showShortcutBadges,
@@ -313,6 +385,8 @@ function StatusGroupList({
}: {
groups: SidebarWorkspaceGroup[];
collapsedWorkspaceGroupKeys: ReadonlySet<string>;
expandedGroupKeys: ReadonlySet<string>;
onToggleGroupWorkspacesExpanded: (groupKey: string) => void;
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
shortcutIndex: Map<string, number>;
showShortcutBadges: boolean;
@@ -328,6 +402,8 @@ function StatusGroupList({
key={group.key}
group={group}
collapsed={collapsedWorkspaceGroupKeys.has(group.key)}
workspacesExpanded={expandedGroupKeys.has(group.key)}
onToggleWorkspacesExpanded={onToggleGroupWorkspacesExpanded}
projectIconByProjectViewKey={projectIconByProjectViewKey}
shortcutIndex={shortcutIndex}
showShortcutBadges={showShortcutBadges}
@@ -349,6 +425,8 @@ const STATUS_GROUP_VISIBILITY = {
function StatusGroupRows({
group,
collapsed,
workspacesExpanded,
onToggleWorkspacesExpanded,
projectIconByProjectViewKey,
shortcutIndex,
showShortcutBadges,
@@ -359,6 +437,8 @@ function StatusGroupRows({
}: {
group: SidebarWorkspaceGroup;
collapsed: boolean;
workspacesExpanded: boolean;
onToggleWorkspacesExpanded: (groupKey: string) => void;
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
shortcutIndex: Map<string, number>;
showShortcutBadges: boolean;
@@ -368,10 +448,9 @@ function StatusGroupRows({
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
}) {
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const [workspacesExpanded, setWorkspacesExpanded] = useState(false);
const toggleWorkspacesExpanded = useCallback(
() => setWorkspacesExpanded((current) => !current),
[],
() => onToggleWorkspacesExpanded(group.key),
[group.key, onToggleWorkspacesExpanded],
);
const {
leadingItem: leadingWorkspace,
@@ -669,6 +748,10 @@ function StatusWorkspaceRowWithMenu({
archiveController.archive();
}, [archiveController, isArchiving]);
const handleSelectWorkspace = useCallback(() => {
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
}, [workspace.workspaceKey]);
const clipboard = useWorkspaceClipboardActions();
const handleCopyPath = useCallback(() => {
clipboard.copyPath(workspace);
@@ -716,6 +799,7 @@ function StatusWorkspaceRowWithMenu({
archiveLabel={t("sidebar.workspace.actions.archive")}
archiveStatus={isArchiving ? "pending" : "idle"}
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
onSelectWorkspace={handleSelectWorkspace}
onArchive={handleArchive}
onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined}
onCopyPath={handleCopyPath}
@@ -750,6 +834,7 @@ interface StatusWorkspaceRowInnerProps {
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
archivePendingLabel?: string;
onSelectWorkspace?: () => void;
onArchive?: () => void;
onCopyBranchName?: () => void;
onCopyPath?: () => void;
@@ -799,6 +884,7 @@ function StatusWorkspaceRowInnerContent({
archiveLabel,
archiveStatus = "idle",
archivePendingLabel,
onSelectWorkspace,
onArchive,
onCopyBranchName,
onCopyPath,
@@ -820,6 +906,8 @@ function StatusWorkspaceRowInnerContent({
const isCompact = useIsCompactFormFactor();
const isTouchPlatform = platformIsNative || isCompact;
const [isHighlighted, setIsHighlighted] = useState(false);
const isSelectionMode = useIsSidebarSelectionMode();
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
const trailing = useSidebarWorkspaceTrailing();
const {
role: _dragRole,
@@ -831,23 +919,35 @@ function StatusWorkspaceRowInnerContent({
const isDesktop = !isTouchPlatform;
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const rowSelected = isSelectionMode ? isBulkSelected : selected;
const accessibilityState = useMemo(
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
[isSelectionMode, isBulkSelected, selected],
);
const isEditingTitle = titleEditor !== null;
const disableDrag = isEditingTitle || isSelectionMode;
const didLongPressRef = dragInteraction?.didLongPressRef;
const startDragPress = dragInteraction?.handlePressIn;
const moveDragPress = dragInteraction?.handleTouchMove;
const endDragPress = dragInteraction?.handlePressOut;
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
didLongPressRef,
onPress,
selected,
});
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
workspaceKey: workspace.workspaceKey,
onNavigate: handleNavigatePress,
onPressIn: startDragPress,
});
return (
<SidebarWorkspaceRowFrame
workspace={workspace}
isDragging={isDragging}
isEditingTitle={isEditingTitle}
isSelectionMode={isSelectionMode}
>
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
const showShortcut = showShortcutBadge && shortcutNumber !== null;
@@ -865,18 +965,24 @@ function StatusWorkspaceRowInnerContent({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode,
});
const workspaceRowStyle = getStatusWorkspaceRowStyle({
selected,
selected: rowSelected,
isHovered,
inStatusGroup,
isDragging,
});
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
const backdrop = getSidebarRowBackdrop({
isDragging,
isHighlighted,
selected: rowSelected,
isHovered,
});
return (
<View
{...dragAttributes}
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
{...(disableDrag ? null : dragHandleProps?.listeners)}
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
style={styles.workspaceRowContainer}
{...hoverHandlers}
@@ -894,6 +1000,7 @@ function StatusWorkspaceRowInnerContent({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -903,16 +1010,18 @@ function StatusWorkspaceRowInnerContent({
onTogglePin={onTogglePin}
openInFileManagerPath={workspace.workspaceDirectory}
disabled={isArchiving}
enabled={!isEditingTitle}
accessibilityRole="button"
enabled={!isEditingTitle && !isSelectionMode}
aria-selected={isSelectionMode ? undefined : selected}
aria-checked={isSelectionMode ? isBulkSelected : undefined}
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
accessibilityState={accessibilityState}
style={workspaceRowStyle}
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
onHighlightChange={setIsHighlighted}
onPressIn={isEditingTitle ? undefined : startDragPress}
onTouchMove={isEditingTitle ? undefined : moveDragPress}
onPressOut={isEditingTitle ? undefined : endDragPress}
onPress={isEditingTitle ? undefined : handlePress}
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
onTouchMove={disableDrag ? undefined : moveDragPress}
onPressOut={disableDrag ? undefined : endDragPress}
onPress={isEditingTitle ? undefined : handleRowPress}
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
>
<SidebarWorkspaceRowContent
@@ -924,6 +1033,8 @@ function StatusWorkspaceRowInnerContent({
backdrop={backdrop}
isHovered={isHovered}
isLoading={isArchiving}
isSelectionMode={isSelectionMode}
isBulkSelected={isBulkSelected}
shortcutNumber={shortcutNumber}
showShortcutBadge={showShortcutBadge}
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
@@ -946,6 +1057,7 @@ function StatusWorkspaceRowInnerContent({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -979,6 +1091,7 @@ function StatusWorkspaceActionSlot({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -1000,6 +1113,7 @@ function StatusWorkspaceActionSlot({
onRename?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
onSelectWorkspace?: () => void;
onArchive?: () => void;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
@@ -1034,6 +1148,7 @@ function StatusWorkspaceActionSlot({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -5,6 +5,7 @@ import {
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { View } from "react-native";
@@ -15,7 +16,13 @@ import Animated, {
type SharedValue,
} from "react-native-reanimated";
import { StyleSheet } from "react-native-unistyles";
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
import {
TOAST_FADE_MS,
ToastViewport,
useToastHost,
type ToastApi,
type ToastState,
} from "@/components/toast-host";
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
interface SidebarToastCoverage {
@@ -25,6 +32,10 @@ interface SidebarToastCoverage {
}
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
const SidebarPersistentToastContext = createContext<((toast: ToastState | null) => void) | null>(
null,
);
const SidebarAppToastContext = createContext<ToastApi | null>(null);
/**
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
@@ -36,9 +47,10 @@ const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(n
export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) {
const appToast = useToast();
const { api: sidebarToast, toast, dismiss } = useToastHost();
const [persistentToast, setPersistentToast] = useState<ToastState | null>(null);
const activeRef = useRef(active);
const coverageHeight = useSharedValue(0);
const toastVisible = toast !== null;
const toastVisible = toast !== null || persistentToast !== null;
useEffect(() => {
activeRef.current = active;
@@ -72,19 +84,48 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
return (
<View style={styles.region}>
<SidebarToastCoverageContext.Provider value={coverage}>
<ToastApiProvider api={api}>{children}</ToastApiProvider>
</SidebarToastCoverageContext.Provider>
<ToastViewport
toast={toast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
<ToastApiProvider api={api}>
<SidebarAppToastContext.Provider value={appToast}>
<SidebarPersistentToastContext.Provider value={setPersistentToast}>
<SidebarToastCoverageContext.Provider value={coverage}>
{children}
</SidebarToastCoverageContext.Provider>
</SidebarPersistentToastContext.Provider>
</SidebarAppToastContext.Provider>
<ToastViewport
toast={toast}
persistentToast={persistentToast}
onDismiss={dismiss}
placement="sidebar"
onBottomCoverageChange={handleCoverageChange}
/>
</ToastApiProvider>
</View>
);
}
/** Returns the enclosing app-level toast API so sidebar callers can report errors without displacing an active sidebar undo toast. */
export function useSidebarAppToast(): ToastApi {
const fallbackToast = useToast();
return useContext(SidebarAppToastContext) ?? fallbackToast;
}
/**
* Displays a persistent toast in the enclosing `SidebarToastRegion`, stacked below any active
* transient toast so controls stay reachable while a previous toast is up.
*/
export function useSidebarPersistentToast(toast: ToastState | null): void {
const setPersistentToast = useContext(SidebarPersistentToastContext);
useEffect(() => {
setPersistentToast?.(toast);
}, [setPersistentToast, toast]);
useEffect(() => {
return () => {
setPersistentToast?.(null);
};
}, [setPersistentToast]);
}
/**
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
@@ -1,9 +1,10 @@
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { PressableStateCallbackType } from "react-native";
import type { GestureResponderEvent, PressableStateCallbackType } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
Archive,
CheckSquare,
Circle,
CircleCheck,
Copy,
@@ -56,6 +57,7 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
const ThemedMoreVertical = withUnistyles(MoreVertical);
const ThemedCopy = withUnistyles(Copy);
const ThemedArchive = withUnistyles(Archive);
const ThemedCheckSquare = withUnistyles(CheckSquare);
const ThemedCircle = withUnistyles(Circle);
const ThemedPencil = withUnistyles(Pencil);
const ThemedCircleCheck = withUnistyles(CircleCheck);
@@ -69,6 +71,7 @@ const markAsReadLeadingIcon = (
<ThemedCircleCheck size={14} uniProps={foregroundMutedColorMapping} />
);
const markAsUnreadLeadingIcon = <ThemedCircle size={14} uniProps={foregroundMutedColorMapping} />;
const selectLeadingIcon = <ThemedCheckSquare size={14} uniProps={foregroundMutedColorMapping} />;
const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedColorMapping} />;
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
@@ -124,6 +127,7 @@ export interface SidebarWorkspaceMenuProps {
onRename?: () => void;
onMarkAsRead?: () => void;
onMarkAsUnread?: () => void;
onSelectWorkspace?: () => void;
onArchive: () => void;
archiveLabel?: string;
archiveStatus?: "idle" | "pending" | "success";
@@ -172,6 +176,7 @@ function SidebarWorkspaceMenuItems({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -267,6 +272,16 @@ function SidebarWorkspaceMenuItems({
path={openInFileManagerPath}
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
/>
{onSelectWorkspace ? (
<WorkspaceMenuItem
surface={surface}
testID={`sidebar-workspace-menu-select-${workspaceKey}`}
leading={selectLeadingIcon}
onSelect={onSelectWorkspace}
>
{t("sidebar.workspace.actions.select")}
</WorkspaceMenuItem>
) : null}
{onArchive ? (
<WorkspaceMenuItem
surface={surface}
@@ -294,6 +309,7 @@ export function SidebarWorkspaceMenu({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -340,6 +356,7 @@ export function SidebarWorkspaceMenu({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -373,6 +390,7 @@ export function SidebarWorkspaceContextMenu({
onRename,
onMarkAsRead,
onMarkAsUnread,
onSelectWorkspace,
onArchive,
archiveLabel,
archiveStatus,
@@ -426,11 +444,37 @@ export function SidebarWorkspaceContextMenu({
[workspace],
);
const pages = useWorkspaceLabelMenuPages(workspaceTarget);
const checkboxSpaceKeyProps = useMemo(() => {
if (!isWeb || triggerProps.accessibilityRole !== "checkbox" || !triggerProps.onPress) {
return {};
}
const onPress = triggerProps.onPress;
return {
// React Native Web's Pressable activates Space only for role="button", not checkbox.
onKeyDown: (event: {
key?: string;
repeat?: boolean;
target?: unknown;
currentTarget?: unknown;
preventDefault?: () => void;
}) => {
if (triggerProps.disabled) return;
if (event.target !== event.currentTarget) return;
if (event.key === " " || event.key === "Spacebar") {
event.preventDefault?.();
if (!event.repeat) {
onPress(event as unknown as GestureResponderEvent);
}
}
},
};
}, [triggerProps.accessibilityRole, triggerProps.disabled, triggerProps.onPress]);
return (
<ContextMenu open={contextMenuOpen} onOpenChange={onContextMenuOpenChange}>
<ContextMenuTrigger
{...triggerProps}
{...checkboxSpaceKeyProps}
enabledOnMobile={false}
accessibilityLabel={accessibilityLabel ?? rowAccessibilityLabel}
highlightStyle={highlightStyle}
@@ -454,6 +498,7 @@ export function SidebarWorkspaceContextMenu({
onRename={onRename}
onMarkAsRead={onMarkAsRead}
onMarkAsUnread={onMarkAsUnread}
onSelectWorkspace={onSelectWorkspace}
onArchive={onArchive}
archiveLabel={archiveLabel}
archiveStatus={archiveStatus}
@@ -1,7 +1,8 @@
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
import { Text, View, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
import { bySizing } from "@/components/ui/control-geometry";
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
import {
@@ -40,19 +41,26 @@ const needsInputColorMapping = (theme: Theme) => ({
color: theme.colors.surface0,
fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
});
const checkedIconMapping = (theme: Theme) => ({
color: theme.colors.accentForeground,
});
const ThemedCheck = withUnistyles(Check);
const ThemedCircleAlert = withUnistyles(CircleAlert);
export function SidebarWorkspaceRowFrame({
workspace,
isDragging = false,
isEditingTitle = false,
isSelectionMode = false,
children,
}: {
workspace: SidebarWorkspaceEntry;
isDragging?: boolean;
/** Hover would fade the kebab in over the title being edited and open the hover card. */
isEditingTitle?: boolean;
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
isSelectionMode?: boolean;
children: (input: {
isHovered: boolean;
contextMenuOpen: boolean;
@@ -80,7 +88,7 @@ export function SidebarWorkspaceRowFrame({
workspace={workspace}
prHint={workspace.prHint}
isDragging={isDragging}
disabled={contextMenuOpen || isEditingTitle}
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
>
{children({
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
@@ -102,6 +110,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
isHovered,
isLoading,
isCreating = false,
isSelectionMode = false,
isBulkSelected = false,
shortcutNumber = null,
showShortcutBadge = false,
reserveIdleStatusIndicatorSpace = true,
@@ -119,6 +129,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
isHovered: boolean;
isLoading: boolean;
isCreating?: boolean;
isSelectionMode?: boolean;
isBulkSelected?: boolean;
shortcutNumber?: number | null;
showShortcutBadge?: boolean;
/** Keep the empty leading slot when the workspace has no active status. */
@@ -137,33 +149,44 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
const workspaceBranchTextStyle = useMemo(
() => [
styles.workspaceBranchText,
isHovered && styles.workspaceBranchTextHovered,
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
isCreating && styles.workspaceBranchTextCreating,
],
[isHovered, isCreating],
[isHovered, isBulkSelected, isCreating],
);
let leadingVisual: ReactNode;
if (isSelectionMode) {
leadingVisual = (
<WorkspaceSelectionCheckbox checked={isBulkSelected} workspaceKey={workspace.workspaceKey} />
);
} else if (leadingProjectName) {
leadingVisual = (
<ProjectStatusIndicator
iconDataUri={leadingProjectIconDataUri}
displayName={leadingProjectName}
projectViewKey={workspace.projectViewKey}
statusBucket={workspace.statusBucket}
backdrop={backdrop}
loading={isLoading}
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
/>
);
} else {
leadingVisual = (
<WorkspaceStatusIndicator
bucket={workspace.statusBucket}
workspaceKind={workspace.workspaceKind}
loading={isLoading}
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
/>
);
}
return (
<View style={styles.workspaceRowContent}>
<View style={styles.workspaceRowMain}>
{leadingProjectName ? (
<ProjectStatusIndicator
iconDataUri={leadingProjectIconDataUri}
displayName={leadingProjectName}
projectViewKey={workspace.projectViewKey}
statusBucket={workspace.statusBucket}
backdrop={backdrop}
loading={isLoading}
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
/>
) : (
<WorkspaceStatusIndicator
bucket={workspace.statusBucket}
workspaceKind={workspace.workspaceKind}
loading={isLoading}
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
/>
)}
{leadingVisual}
<View style={styles.workspaceContentColumn}>
<View style={styles.workspaceTitleRow}>
{titleEditor ? (
@@ -191,7 +214,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
/>
</View>
</View>
{showShortcutBadge && shortcutNumber !== null ? (
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
</View>
@@ -200,6 +223,22 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
);
});
function WorkspaceSelectionCheckbox({
checked,
workspaceKey,
}: {
checked: boolean;
workspaceKey: string;
}) {
return (
<View style={styles.workspaceStatusDot} testID={`sidebar-workspace-checkbox-${workspaceKey}`}>
<View style={checked ? styles.selectionCheckboxChecked : styles.selectionCheckbox}>
{checked ? <ThemedCheck size={11} strokeWidth={2.5} uniProps={checkedIconMapping} /> : null}
</View>
</View>
);
}
function WorkspaceStatusIndicator({
bucket,
workspaceKind,
@@ -382,6 +421,7 @@ export function resolveTrailingActionVisibility({
isHovered,
isTouchPlatform,
showShortcut,
isSelectionMode = false,
}: {
workspace: SidebarWorkspaceEntry;
trailing: SidebarWorkspaceTrailing;
@@ -389,6 +429,7 @@ export function resolveTrailingActionVisibility({
isHovered: boolean;
isTouchPlatform: boolean;
showShortcut: boolean;
isSelectionMode?: boolean;
}): {
trailingPresentation: SidebarWorkspaceTrailingPresentation;
showKebab: boolean;
@@ -398,10 +439,11 @@ export function resolveTrailingActionVisibility({
reserveSlotWidth: boolean;
} {
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut;
const allowRowActions = hasArchiveAction && !isSelectionMode;
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
// conceal content while retaining its width, so desktop rows do not shift.
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
return {
@@ -414,12 +456,12 @@ export function resolveTrailingActionVisibility({
// row — over an unhovered one the gradient fades to the wrong color. That is also why
// touch, which shows the kebab without ever hovering, never gets one.
showScrim: showKebab && isHovered,
renderSlot: hasArchiveAction || hasTrailing,
renderSlot: allowRowActions || hasTrailing,
// The slot only holds width for something that permanently sits in it. Trailing content
// does; the kebab only does on touch, where there is no hover for it to appear on and so
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
// and the kebab fades in over its tail.
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
};
}
@@ -536,6 +578,25 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
justifyContent: "center",
},
selectionCheckbox: {
width: bySizing({ touch: 18, pointer: 15 }),
height: bySizing({ touch: 18, pointer: 15 }),
borderRadius: theme.borderRadius.sm,
borderWidth: 1.5,
borderColor: theme.colors.borderAccent,
alignItems: "center",
justifyContent: "center",
},
selectionCheckboxChecked: {
width: bySizing({ touch: 18, pointer: 15 }),
height: bySizing({ touch: 18, pointer: 15 }),
borderRadius: theme.borderRadius.sm,
borderWidth: 1.5,
borderColor: theme.colors.accent,
backgroundColor: theme.colors.accent,
alignItems: "center",
justifyContent: "center",
},
statusDotOverlay: {
position: "absolute",
right: 0,
+85 -15
View File
@@ -16,6 +16,7 @@ import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { SPACING, type Theme } from "@/styles/theme";
import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry";
import { useTranslation } from "react-i18next";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
@@ -28,10 +29,16 @@ import {
} from "@/constants/layout";
export type ToastVariant = "default" | "info" | "success" | "warning" | "error";
/**
* `action` tightens vertical and trailing insets around `size="sm"` pill controls and uses a
* concentric corner radius (`controlHeight / 2 + inset`) so buttons nest evenly in the shell.
*/
export type ToastLayout = "default" | "action";
export interface ToastShowOptions {
icon?: ReactNode;
variant?: ToastVariant;
layout?: ToastLayout;
durationMs?: number | null;
nativeAndroid?: boolean;
testID?: string;
@@ -45,6 +52,7 @@ export interface ToastState {
nativeMessage: string | null;
icon?: ReactNode;
variant: ToastVariant;
layout?: ToastLayout;
durationMs: number | null;
testID?: string;
onDismiss?: () => void;
@@ -73,6 +81,11 @@ const TOAST_MAX_WIDTH = 480;
/** How long a toast takes to fade in or out. */
export const TOAST_FADE_MS = 140;
const SIDEBAR_TOAST_INSET = SPACING[2];
const ACTION_TOAST_INSET = SPACING[1.5];
const ACTION_TOAST_RADIUS = mapLayout(
CONTROL_HEIGHTS.sm,
(height) => height / 2 + ACTION_TOAST_INSET,
);
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
const ThemedCheckCircle = withUnistyles(CheckCircle2);
@@ -136,6 +149,7 @@ export function useToastHost(): {
nativeMessage,
icon: options?.icon,
variant,
layout: options?.layout,
durationMs,
testID: options?.testID,
onDismiss: options?.onDismiss,
@@ -163,11 +177,14 @@ export function useToastHost(): {
export function ToastViewport({
toast,
persistentToast = null,
onDismiss,
placement = "app-shell",
onBottomCoverageChange,
}: {
toast: ToastState | null;
/** Sidebar placement: persistent bar (such as select mode) that stays visible below transient toasts. */
persistentToast?: ToastState | null;
/** Called with the ID of the toast that timed out. */
onDismiss: (id: number) => void;
placement?: ToastViewportPlacement;
@@ -232,7 +249,10 @@ export function ToastViewport({
const handleSidebarLayout = useCallback(
(event: LayoutChangeEvent) => {
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
const height = event.nativeEvent.layout.height;
if (height > 0) {
onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET);
}
},
[onBottomCoverageChange],
);
@@ -243,28 +263,41 @@ export function ToastViewport({
const topOffset =
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
if (placement === "sidebar") {
return (
<View
style={animatedStyles.sidebarContainer}
pointerEvents="box-none"
collapsable={false}
onLayout={handleSidebarLayout}
>
<SidebarToastSlot
toast={toast}
onPointerEnter={pauseDismiss}
onPointerLeave={resumeDismiss}
/>
<SidebarToastSlot
toast={persistentToast}
onPointerEnter={noopDismiss}
onPointerLeave={noopDismiss}
/>
</View>
);
}
// Keep the bottom anchor and its contents together while the native exit retains the view.
const content = toast ? (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={
placement === "sidebar"
? animatedStyles.sidebarContainer
: [
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]
}
style={[
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]}
pointerEvents="box-none"
collapsable={false}
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
>
<View
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
pointerEvents="box-none"
collapsable={false}
>
<View style={styles.widthBoundary} pointerEvents="box-none" collapsable={false}>
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
@@ -283,6 +316,35 @@ export function ToastViewport({
return placement === "panel" ? <FloatingHeaderOverlay>{content}</FloatingHeaderOverlay> : content;
}
function SidebarToastSlot({
toast,
onPointerEnter,
onPointerLeave,
}: {
toast: ToastState | null;
onPointerEnter: () => void;
onPointerLeave: () => void;
}) {
if (!toast) return null;
return (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={styles.sidebarWidthBoundary}
pointerEvents="box-none"
collapsable={false}
>
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
accessibilityRole="alert"
>
<ToastCard toast={toast} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave} />
</View>
</Animated.View>
);
}
function ToastCard({
toast,
onPointerEnter,
@@ -310,6 +372,7 @@ function ToastCard({
onPointerLeave={onPointerLeave}
style={[
styles.toast,
toast.layout === "action" ? styles.toastAction : null,
toast.variant === "info" ? styles.toastInfo : null,
toast.variant === "warning" ? styles.toastWarning : null,
toast.variant === "error" ? styles.toastError : null,
@@ -344,6 +407,7 @@ const animatedStyles = NativeStyleSheet.create({
bottom: SIDEBAR_TOAST_INSET,
zIndex: OVERLAY_Z.toast,
alignItems: "center",
gap: SIDEBAR_TOAST_INSET,
},
surface: { alignSelf: "center", maxWidth: "100%" },
});
@@ -372,6 +436,12 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: theme.spacing[3],
...theme.shadow.md,
},
toastAction: {
borderRadius: ACTION_TOAST_RADIUS,
paddingVertical: theme.spacing[1.5],
paddingLeft: theme.spacing[3.5],
paddingRight: theme.spacing[1.5],
},
toastInfo: {
borderColor: theme.colors.palette.blue[300],
},
+10 -16
View File
@@ -25,7 +25,6 @@ import {
} from "react-native";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -146,6 +145,8 @@ export interface ComboboxProps {
/** When true, selecting an option does not close the picker (multi-select mode). */
keepOpenOnSelect?: boolean;
anchorRef: React.RefObject<View | null>;
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
restoreFocusRef?: React.RefObject<unknown>;
children?: ReactNode;
}
@@ -1138,31 +1139,22 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement {
}
/**
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
* one left where the combobox was opened: inside a sheet tab, none is.
* Rendered on the far side of the sheet's portal so `SheetVisibleFrame` clears the screen's
* bottom inset in lockstep with the keyboard, not the inset left where the combobox was opened.
*/
function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children: ReactNode }) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const frameStyle = useMemo(
() => [styles.mobileSheetFrame, { paddingBottom: footer ? 0 : safeAreaBottom }],
[footer, safeAreaBottom],
);
const footerStyle = useMemo(
() => [styles.footer, { paddingBottom: safeAreaBottom }],
[safeAreaBottom],
);
const footerView = useMemo(
() =>
footer ? (
<View style={footerStyle} dataSet={FOOTER_DATASET}>
<View style={styles.footer} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
[footer, footerStyle],
[footer],
);
return (
<SheetVisibleFrame footer={footerView}>
<View style={frameStyle}>{children}</View>
<SheetVisibleFrame footer={footerView} safeAreaInset="frame">
<View style={styles.mobileSheetFrame}>{children}</View>
</SheetVisibleFrame>
);
}
@@ -1437,6 +1429,7 @@ export function Combobox({
footer,
keepOpenOnSelect = false,
anchorRef,
restoreFocusRef,
children,
}: ComboboxProps): ReactElement | null {
const { t } = useTranslation();
@@ -1728,6 +1721,7 @@ export function Combobox({
layer: floatingLayer,
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
restoreFocusRef,
});
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
@@ -0,0 +1,106 @@
import React, { act, Children, useCallback, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { useContentDrag, withContentDrag } from "./content-drag";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
interface FakeScrollProps {
scrollEnabled?: boolean;
children?: ReactNode;
}
/** Stands in for a scroll view: it reports the props a native scroll view would act on. */
function FakeScroll({ scrollEnabled, children }: FakeScrollProps) {
return (
<div
data-testid="scroll"
data-scroll-enabled={String(scrollEnabled)}
data-child-count={Children.toArray(children).length}
>
{children}
</div>
);
}
const DragHostScroll = withContentDrag<FakeScrollProps, unknown>(FakeScroll);
/** A row that holds a drag the way a draggable list does: active from press until release. */
function DragRow() {
const { setActive } = useContentDrag();
const arm = useCallback(() => setActive(true), [setActive]);
const release = useCallback(() => setActive(false), [setActive]);
return (
<>
<button type="button" data-testid="arm" onClick={arm} />
<button type="button" data-testid="release" onClick={release} />
</>
);
}
function mount(node: React.ReactElement) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(node));
}
function scroll(): HTMLElement {
const found = document.querySelector('[data-testid="scroll"]');
if (!(found instanceof HTMLElement)) throw new Error("No scroll view rendered");
return found;
}
function press(testID: string) {
const button = document.querySelector(`[data-testid="${testID}"]`);
if (!(button instanceof HTMLElement)) throw new Error(`No ${testID}`);
act(() => button.click());
}
describe("withContentDrag", () => {
it("stops the scroll while a child drag holds the touch, and resumes after", () => {
mount(
<DragHostScroll>
<DragRow />
</DragHostScroll>,
);
expect(scroll().dataset.scrollEnabled).toBe("true");
press("arm");
expect(scroll().dataset.scrollEnabled).toBe("false");
press("release");
expect(scroll().dataset.scrollEnabled).toBe("true");
});
it("keeps a scroll view the caller disabled disabled after the drag", () => {
mount(
<DragHostScroll scrollEnabled={false}>
<DragRow />
</DragHostScroll>,
);
press("arm");
press("release");
expect(scroll().dataset.scrollEnabled).toBe("false");
});
it("passes the children through as given, so sticky header indices still count them", () => {
mount(
<DragHostScroll>
<div>Intro</div>
<div>Section header</div>
<DragRow />
</DragHostScroll>,
);
expect(scroll().dataset.childCount).toBe("3");
});
});
@@ -0,0 +1,64 @@
import {
createContext,
forwardRef,
useContext,
useMemo,
useState,
type ComponentType,
type Ref,
} from "react";
import type { AttachSheetContentDrag } from "./bottom-sheet-scope";
/**
* What a child that drags inside a scroll view needs to keep the touch: `setActive(true)` stops
* the scroll until the drag ends, so the scroll view cannot take the finger once the drag has
* armed. Inside a sheet the child also registers its drag gesture through `attach` so the sheet's
* pan waits for it; outside a sheet there is no `attach`. Outside any scroll view that hosts
* content drags, `setActive` does nothing.
*/
export interface ContentDrag {
attach: AttachSheetContentDrag | undefined;
setActive: (active: boolean) => void;
}
const ContentDragContext = createContext<ContentDrag | null>(null);
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
export function useContentDrag(): ContentDrag {
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
}
function useNoAttach(): AttachSheetContentDrag | undefined {
return undefined;
}
/**
* Makes a scroll view host content drags: it stops scrolling while a child drag is active. Without
* it, a vertical drag in a row of a scrolling page is taken by the page scroll once the finger
* moves past the touch slop, before the row's drag gesture can activate. A sheet's scroll view
* passes `useAttach` so its children can also register their gesture with the sheet.
*
* The context wraps the scroll view rather than its content, so the scroll view receives its
* children as given: `stickyHeaderIndices` counts them.
*/
export function withContentDrag<P extends { scrollEnabled?: boolean }, T>(
Scroll: ComponentType<P & { ref?: Ref<T> }>,
useAttach: () => AttachSheetContentDrag | undefined = useNoAttach,
) {
return forwardRef<T, P>(function ContentDragScrollView(props, ref) {
const attach = useAttach();
const [dragging, setDragging] = useState(false);
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
// Overriding one prop of `P` keeps it a `P`; TypeScript cannot prove that for a generic.
const scrollProps = {
...props,
scrollEnabled: !dragging && props.scrollEnabled !== false,
} as P;
return (
<ContentDragContext.Provider value={contentDrag}>
<Scroll {...scrollProps} ref={ref} />
</ContentDragContext.Provider>
);
});
}
@@ -150,17 +150,17 @@ export function ContextMenuTrigger({
);
const propsOnLongPress = props.onLongPress;
const handleLongPress = useCallback(
const handleNativeLongPress = useCallback(
(event: GestureResponderEvent) => {
if (isWeb) {
propsOnLongPress?.(event);
return;
}
openAtEvent(event);
propsOnLongPress?.(event);
},
[propsOnLongPress, openAtEvent],
);
// The web menu opens on right-click, not long press. Any onLongPress makes react-native-web cancel
// the click that ends a held press, and only a later press-in clears that, which Ctrl+click never
// gets. So on web, pass the caller's onLongPress through and nothing else.
const handleLongPress = isWeb ? propsOnLongPress : handleNativeLongPress;
const handleContextMenu = useCallback(
(event: unknown) => {
@@ -212,6 +212,6 @@ export function useIsolatedBottomSheetVisibility({
};
}
export { SheetVisibleFrame } from "./visible-frame";
export { SheetVisibleFrame, useBottomSheetSafeAreaPaddingStyle } from "./visible-frame";
export { systemBackPress } from "./back-press";
export { SheetHostScope } from "./host-scope";
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
import {
getBottomSheetSafeAreaPaddingBottom,
getBottomSheetVisibleContentHeight,
} from "./visible-frame-layout";
describe("getBottomSheetVisibleContentHeight", () => {
it("stops subtracting the retained keyboard height after the keyboard hides", () => {
@@ -13,6 +16,120 @@ describe("getBottomSheetVisibleContentHeight", () => {
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: true })).toBe(418);
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: false })).toBe(762);
});
it("ignores non-positive keyboard heights", () => {
const layout = {
containerHeight: 874,
contentPosition: 88,
handleHeight: 24,
keyboardHeight: -10,
isKeyboardVisible: true,
};
expect(getBottomSheetVisibleContentHeight(layout)).toBe(762);
});
});
describe("getBottomSheetSafeAreaPaddingBottom", () => {
it("keeps full safe-area clearance while the keyboard is hidden, even with retained keyboard height", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 344,
isKeyboardVisible: false,
safeAreaBottom: 48,
}),
).toBe(48);
});
it("keeps full safe-area clearance during Gorhom's first-open frame before heightWithinContainer is populated", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 0,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(48);
});
it("drops safe-area clearance to 0 when the keyboard height covers the bottom safe area", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 344,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(0);
});
it("preserves remaining safe-area clearance when keyboard height is smaller than the bottom inset", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 20,
isKeyboardVisible: true,
safeAreaBottom: 48,
}),
).toBe(28);
});
it("returns 0 when there is no bottom safe-area inset", () => {
expect(
getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: 0,
isKeyboardVisible: false,
safeAreaBottom: 0,
}),
).toBe(0);
});
it("holds the invariant that visible frame height + paddingBottom never places the footer inside the bottom safe area across keyboard open/close transitions", () => {
const containerHeight = 1608;
const contentPosition = 161;
const handleHeight = 48;
const safeAreaBottom = 96;
const restingContentBottom = containerHeight - safeAreaBottom;
// Sequence matching real Android/iOS Gorhom keyboard transitions:
// 1. Resting closed
// 2. First open intermediate state (status=SHOWN before heightWithinContainer updates)
// 3. Open settled (heightWithinContainer = 598)
// 4. Close (status=HIDDEN while heightWithinContainer retains 598)
// 5. Partial accessory bar (heightWithinContainer = 40 < safeAreaBottom)
const transitions = [
{ isKeyboardVisible: false, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
{ isKeyboardVisible: true, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
{
isKeyboardVisible: true,
keyboardHeight: 598,
expectedContentBottom: containerHeight - 598,
},
{
isKeyboardVisible: false,
keyboardHeight: 598,
expectedContentBottom: restingContentBottom,
},
{ isKeyboardVisible: true, keyboardHeight: 40, expectedContentBottom: restingContentBottom },
];
for (const step of transitions) {
const height = getBottomSheetVisibleContentHeight({
containerHeight,
contentPosition,
handleHeight,
keyboardHeight: step.keyboardHeight,
isKeyboardVisible: step.isKeyboardVisible,
});
const paddingBottom = getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: step.keyboardHeight,
isKeyboardVisible: step.isKeyboardVisible,
safeAreaBottom,
});
// Inside a border-box frame at `contentPosition + handleHeight`, the bottom of the footer
// sits at `contentPosition + handleHeight + height - paddingBottom`.
const footerBottomY = contentPosition + handleHeight + height - paddingBottom;
expect(footerBottomY).toBe(step.expectedContentBottom);
expect(footerBottomY).toBeLessThanOrEqual(restingContentBottom);
}
});
});
// Below the lowest snap the frame must travel with the sheet, not shrink to the screen edge.
@@ -1,4 +1,4 @@
interface BottomSheetVisibleContentHeightInput {
export interface BottomSheetVisibleContentHeightInput {
containerHeight: number;
contentPosition: number;
lowestDetentPosition?: number;
@@ -7,6 +7,28 @@ interface BottomSheetVisibleContentHeightInput {
isKeyboardVisible: boolean;
}
export interface BottomSheetSafeAreaPaddingInput {
keyboardHeight: number;
isKeyboardVisible: boolean;
safeAreaBottom: number;
}
/**
* Effective keyboard height inside the sheet container.
*
* Gorhom retains `heightWithinContainer` after the keyboard hides, and on first show `status`
* flips to `SHOWN` before its reaction writes `heightWithinContainer`. Treating both states as 0
* keeps frame height and safe-area clearance in lockstep.
*/
export function getBottomSheetEffectiveKeyboardHeight(
keyboardHeight: number,
isKeyboardVisible: boolean,
): number {
"worklet";
if (!isKeyboardVisible || keyboardHeight <= 0) return 0;
return keyboardHeight;
}
export function getBottomSheetVisibleContentHeight({
containerHeight,
contentPosition,
@@ -18,8 +40,29 @@ export function getBottomSheetVisibleContentHeight({
"worklet";
if (containerHeight < 0 || handleHeight < 0) return 0;
const position = Math.min(contentPosition, lowestDetentPosition ?? contentPosition);
return Math.max(
0,
containerHeight - position - handleHeight - (isKeyboardVisible ? keyboardHeight : 0),
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
keyboardHeight,
isKeyboardVisible,
);
return Math.max(0, containerHeight - position - handleHeight - effectiveKeyboardHeight);
}
/**
* Bottom safe-area clearance derived from the same keyboard inset subtracted from
* `SheetVisibleFrame`'s height so both update in one UI-thread commit.
*
* Invariant: `effectiveKeyboardHeight + paddingBottom >= safeAreaBottom`.
*/
export function getBottomSheetSafeAreaPaddingBottom({
keyboardHeight,
isKeyboardVisible,
safeAreaBottom,
}: BottomSheetSafeAreaPaddingInput): number {
"worklet";
if (safeAreaBottom <= 0) return 0;
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
keyboardHeight,
isKeyboardVisible,
);
return Math.max(0, safeAreaBottom - effectiveKeyboardHeight);
}
@@ -2,21 +2,63 @@ import type { ReactNode } from "react";
import { View, StyleSheet } from "react-native";
import { KEYBOARD_STATUS, useBottomSheetInternal } from "@gorhom/bottom-sheet";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
getBottomSheetSafeAreaPaddingBottom,
getBottomSheetVisibleContentHeight,
} from "./visible-frame-layout";
/** Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap. */
/**
* UI-thread bottom safe-area padding synchronized with Gorhom's keyboard state.
* Use this for scrollable sheet bodies without a footer so content scrolls behind the system
* navigation bar while still clearing it at rest and dropping the padding in lockstep with
* `SheetVisibleFrame` when the keyboard opens or closes.
*/
export function useBottomSheetSafeAreaPaddingStyle(enabled = true) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const { animatedKeyboardState } = useBottomSheetInternal();
return useAnimatedStyle(() => {
const keyboard = animatedKeyboardState.get();
return {
paddingBottom: enabled
? getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
safeAreaBottom,
})
: 0,
};
}, [animatedKeyboardState, enabled, safeAreaBottom]);
}
/**
* Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap,
* and frame height + bottom safe-area clearance update together in one UI-thread commit so the
* footer never flashes behind the system navigation bar on keyboard show/hide.
*/
export function SheetVisibleFrame({
children,
footer,
safeAreaInset = "footer",
}: {
children: ReactNode;
footer?: ReactNode;
/**
* Where bottom safe-area clearance is applied:
* - `"footer"` (default): pads the frame whenever `footer` is present.
* - `"frame"`: always pads the frame, with or without a footer.
* - `"none"`: caller owns safe-area clearance.
*/
safeAreaInset?: "footer" | "frame" | "none";
}) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const { animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition } =
useBottomSheetInternal();
const padFrame = safeAreaInset === "frame" || (safeAreaInset === "footer" && Boolean(footer));
const visibleStyle = useAnimatedStyle(() => {
const { containerHeight, handleHeight } = animatedLayoutState.get();
const keyboard = animatedKeyboardState.get();
const isKeyboardVisible = keyboard.status === KEYBOARD_STATUS.SHOWN;
return {
height: getBottomSheetVisibleContentHeight({
containerHeight,
@@ -24,10 +66,24 @@ export function SheetVisibleFrame({
contentPosition: animatedPosition.get(),
lowestDetentPosition: animatedDetentsState.get().detents?.[0],
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
isKeyboardVisible,
}),
paddingBottom: padFrame
? getBottomSheetSafeAreaPaddingBottom({
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible,
safeAreaBottom,
})
: 0,
};
}, [animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition]);
}, [
animatedDetentsState,
animatedKeyboardState,
animatedLayoutState,
animatedPosition,
padFrame,
safeAreaBottom,
]);
return (
<Animated.View style={[styles.frame, visibleStyle]}>
<View style={styles.body}>{children}</View>
+10 -43
View File
@@ -1,4 +1,4 @@
import { createContext, forwardRef, useContext, useMemo, useState, type Ref } from "react";
import { forwardRef, type Ref } from "react";
import {
ScrollView as NativeScrollView,
FlatList as NativeFlatList,
@@ -12,15 +12,13 @@ import {
type NativeViewGestureHandlerProps,
} from "react-native-gesture-handler";
import { isNative } from "@/constants/platform";
import {
useAttachSheetContentDrag,
useIsInsideBottomSheet,
type AttachSheetContentDrag,
} from "./bottom-sheet-scope";
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
import { withContentDrag } from "./content-drag";
// Both libraries forward to the RN FlatList instance. Their published ref types
// Both libraries forward to the RN FlatList and ScrollView instances. Their published ref types
// disagree about getScrollResponder (Gorhom) and include the component function
// in the instance intersection (RNGH); keep that type discrepancy at this boundary.
const SheetScroll = BottomSheetScrollView as unknown as typeof NativeScrollView;
const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
const HorizontalFlatList = GestureFlatList as unknown as <Item>(
props: FlatListProps<Item> & NativeViewGestureHandlerProps & { ref?: Ref<NativeFlatList<Item>> },
@@ -30,7 +28,7 @@ const HorizontalFlatList = GestureFlatList as unknown as <Item>(
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function ScrollView(props, ref) {
const inSheet = useIsInsideBottomSheet();
if (!inSheet) return <NativeScrollView {...props} ref={ref} />;
if (!inSheet) return <PageScrollView {...props} ref={ref} />;
if (props.horizontal) {
return isNative ? (
<GestureScrollView {...props} ref={ref} disallowInterruption />
@@ -42,42 +40,11 @@ export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
},
);
/**
* What a child that drags inside a sheet needs to keep the touch: it registers its drag gesture
* through `attach` so the sheet's pan waits for it, and `setActive(true)` stops the sheet's
* scroll until the drag ends. Outside a sheet scroll there is no `attach` and `setActive` does
* nothing.
*/
export interface ContentDrag {
attach: AttachSheetContentDrag | undefined;
setActive: (active: boolean) => void;
}
const PageScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(NativeScrollView);
const ContentDragContext = createContext<ContentDrag | null>(null);
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
export function useContentDrag(): ContentDrag {
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
}
const SheetScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function SheetScrollView(props, ref) {
const attach = useAttachSheetContentDrag();
const [dragging, setDragging] = useState(false);
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
return (
<BottomSheetScrollView
{...props}
scrollEnabled={!dragging && props.scrollEnabled !== false}
ref={ref}
>
<ContentDragContext.Provider value={contentDrag}>
{props.children}
</ContentDragContext.Provider>
</BottomSheetScrollView>
);
},
const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
SheetScroll,
useAttachSheetContentDrag,
);
function SheetAwareFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
@@ -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,3 +146,41 @@ export async function confirmRiskyWorktreeArchive(
destructive: true,
});
}
export async function confirmRiskyBulkWorktreeArchive(
input: {
totalCount: number;
riskyWorkspaces: readonly WorktreeArchiveConfirmationInput[];
},
labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS,
): Promise<boolean> {
const lines: string[] = [];
let singleRisky: WorktreeArchiveConfirmationInput | null = null;
for (const workspace of input.riskyWorkspaces) {
const reasons = buildWorktreeArchiveRiskReasons(workspace, labels);
if (reasons.length === 0) continue;
singleRisky = workspace;
lines.push(
i18n.t("workspace.git.actions.archiveWarning.bulkWorkspaceReason", {
workspaceName: workspace.workspaceName,
reason: reasons.join(", "),
}),
);
}
if (lines.length === 0) {
return true;
}
if (input.totalCount === 1 && singleRisky) {
return await confirmRiskyWorktreeArchive(singleRisky, labels);
}
return await confirmDialog({
title: i18n.t("workspace.git.actions.archiveWarning.bulkTitle", {
count: input.totalCount,
}),
message: lines.join("\n"),
confirmLabel: labels.confirm,
cancelLabel: labels.cancel,
destructive: true,
});
}
@@ -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"),
},
],
@@ -1,21 +0,0 @@
import { useSyncExternalStore } from "react";
import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
const subscribe = (onStoreChange: () => void) => {
const subscriptions = (["keyboardWillShow", "keyboardDidHide"] as const).map((event) =>
KeyboardEvents.addListener(event, onStoreChange),
);
return () => {
for (const subscription of subscriptions) {
subscription.remove();
}
};
};
export function useKeyboardVisibility(enabled = true): boolean {
return useSyncExternalStore(
subscribe,
() => (enabled ? KeyboardController.isVisible() : false),
() => false,
);
}
@@ -1,3 +0,0 @@
export function useKeyboardVisibility(_enabled = true): boolean {
return false;
}
+11
View File
@@ -741,6 +741,8 @@ export const ar: TranslationResources = {
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
reloadingAgent: "وكيل إعادة التحميل...",
reloadedAgent: "وكيل إعادة تحميل",
reloadedAgentHistoryDiverged:
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
failedToCloseAgent: "فشل في إغلاق الوكيل",
},
@@ -960,6 +962,8 @@ export const ar: TranslationResources = {
},
archiveWarning: {
title: 'الأرشيف "{{workspaceName}}"؟',
bulkTitle: "أرشفة {{count}} مساحات عمل؟",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "أرشيف",
cancel: "يلغي",
uncommittedChanges: "تغييرات غير ملتزم بها",
@@ -1369,6 +1373,7 @@ export const ar: TranslationResources = {
rename: "إعادة تسمية مساحة العمل",
pin: "تثبيت في الأعلى",
unpin: "إلغاء التثبيت",
select: "تحديد",
archive: "أرشيف",
archiveWorkspace: "أرشفة مساحة العمل",
hideFromSidebar: "إخفاء من الشريط الجانبي",
@@ -1387,6 +1392,10 @@ export const ar: TranslationResources = {
submit: "إعادة تسمية",
invalidBranchName: "اسم الفرع غير صالح",
},
selection: {
count: "تم تحديد {{count}}",
exit: "إنهاء التحديد",
},
toasts: {
workspacePathUnavailable: "مسار Workspace غير متوفر",
pathCopied: "تم نسخ المسار",
@@ -1394,7 +1403,9 @@ export const ar: TranslationResources = {
hostDisconnected: "Host غير متصل",
hideFailed: "فشل في إخفاء مساحة العمل",
archiveFailed: "فشل في أرشفة مساحة العمل",
archiveMultipleFailed: "فشل في أرشفة {{count}} مساحات عمل",
archived: "تمت أرشفة مساحة العمل",
archivedCount: "تمت أرشفة {{count}} مساحات عمل",
undoArchive: "تراجع",
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
},
+11
View File
@@ -740,6 +740,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,6 +973,8 @@ export const en = {
},
archiveWarning: {
title: 'Archive "{{workspaceName}}"?',
bulkTitle: "Archive {{count}} workspaces?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Archive",
cancel: "Cancel",
uncommittedChanges: "Uncommitted changes",
@@ -1380,6 +1384,7 @@ export const en = {
rename: "Rename workspace",
pin: "Pin to top",
unpin: "Unpin",
select: "Select",
archive: "Archive",
archiveWorkspace: "Archive workspace",
hideFromSidebar: "Hide from sidebar",
@@ -1398,6 +1403,10 @@ export const en = {
submit: "Rename",
invalidBranchName: "Invalid branch name",
},
selection: {
count: "{{count}} selected",
exit: "Exit selection",
},
toasts: {
workspacePathUnavailable: "Workspace path not available",
pathCopied: "Path copied",
@@ -1405,7 +1414,9 @@ export const en = {
hostDisconnected: "Host is not connected",
hideFailed: "Failed to hide workspace",
archiveFailed: "Failed to archive workspace",
archiveMultipleFailed: "Failed to archive {{count}} workspaces",
archived: "Workspace archived",
archivedCount: "{{count}} workspaces archived",
undoArchive: "Undo",
undoArchiveFailed: "Couldn't undo the archive",
},
+11
View File
@@ -748,6 +748,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,6 +996,8 @@ export const es: TranslationResources = {
},
archiveWarning: {
title: '¿Archivo "{{workspaceName}}"?',
bulkTitle: "¿Archivar {{count}} espacios de trabajo?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Archivo",
cancel: "Cancelar",
uncommittedChanges: "Cambios no confirmados",
@@ -1406,6 +1410,7 @@ export const es: TranslationResources = {
rename: "Cambiar nombre del espacio de trabajo",
pin: "Anclar arriba",
unpin: "Desanclar",
select: "Seleccionar",
archive: "Archivo",
archiveWorkspace: "Archivar espacio de trabajo",
hideFromSidebar: "Ocultar de la barra lateral",
@@ -1424,6 +1429,10 @@ export const es: TranslationResources = {
submit: "Rebautizar",
invalidBranchName: "Nombre de sucursal no válido",
},
selection: {
count: "{{count}} seleccionados",
exit: "Salir de la selección",
},
toasts: {
workspacePathUnavailable: "RutaWorkspaceno disponible",
pathCopied: "Ruta copiada",
@@ -1431,7 +1440,9 @@ export const es: TranslationResources = {
hostDisconnected: "Hostno está conectado",
hideFailed: "No se pudo ocultar el espacio de trabajo",
archiveFailed: "No se pudo archivar el espacio de trabajo",
archiveMultipleFailed: "No se pudieron archivar {{count}} espacios de trabajo",
archived: "Espacio de trabajo archivado",
archivedCount: "{{count}} espacios de trabajo archivados",
undoArchive: "Deshacer",
undoArchiveFailed: "No se pudo deshacer el archivado",
},
+11
View File
@@ -748,6 +748,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,6 +988,8 @@ export const fr: TranslationResources = {
},
archiveWarning: {
title: "Archiver « {{workspaceName}} » ?",
bulkTitle: "Archiver {{count}} espaces de travail ?",
bulkWorkspaceReason: "{{workspaceName}} : {{reason}}",
confirm: "Archiver",
cancel: "Annuler",
uncommittedChanges: "Modifications non commitées",
@@ -1399,6 +1403,7 @@ export const fr: TranslationResources = {
rename: "Renommer l’espace de travail",
pin: "Épingler en haut",
unpin: "Désépingler",
select: "Sélectionner",
archive: "Archiver",
archiveWorkspace: "Archiver l’espace de travail",
hideFromSidebar: "Masquer de la barre latérale",
@@ -1417,6 +1422,10 @@ export const fr: TranslationResources = {
submit: "Renommer",
invalidBranchName: "Nom de branche invalide",
},
selection: {
count: "{{count}} sélectionnés",
exit: "Quitter la sélection",
},
toasts: {
workspacePathUnavailable: "Chemin de l’espace de travail indisponible",
pathCopied: "Chemin copié",
@@ -1424,7 +1433,9 @@ export const fr: TranslationResources = {
hostDisconnected: "L’hôte n’est pas connecté",
hideFailed: "Impossible de masquer l’espace de travail",
archiveFailed: "Impossible d’archiver l’espace de travail",
archiveMultipleFailed: "Impossible d’archiver {{count}} espaces de travail",
archived: "Espace de travail archivé",
archivedCount: "{{count}} espaces de travail archivés",
undoArchive: "Annuler",
undoArchiveFailed: "Impossible d’annuler l’archivage",
},
+11
View File
@@ -748,6 +748,8 @@ export const ja: TranslationResources = {
resumeCommandUnavailable: "再開コマンドが利用できません",
reloadingAgent: "エージェントを再読み込み中...",
reloadedAgent: "エージェントを再読み込みしました",
reloadedAgentHistoryDiverged:
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
failedToCloseAgent: "エージェントを閉じられませんでした",
},
@@ -974,6 +976,8 @@ export const ja: TranslationResources = {
},
archiveWarning: {
title: '"{{workspaceName}}"をアーカイブしますか?',
bulkTitle: "{{count}}件のワークスペースをアーカイブしますか?",
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
confirm: "アーカイブ",
cancel: "キャンセル",
uncommittedChanges: "未コミットの変更",
@@ -1384,6 +1388,7 @@ export const ja: TranslationResources = {
rename: "ワークスペースの名前を変更",
pin: "上部に固定",
unpin: "固定解除",
select: "選択",
archive: "アーカイブ",
archiveWorkspace: "ワークスペースをアーカイブ",
hideFromSidebar: "サイドバーから非表示",
@@ -1402,6 +1407,10 @@ export const ja: TranslationResources = {
submit: "名前を変更",
invalidBranchName: "無効なブランチ名",
},
selection: {
count: "{{count}}件選択中",
exit: "選択を終了",
},
toasts: {
workspacePathUnavailable: "ワークスペースパスが利用できません",
pathCopied: "パスをコピーしました",
@@ -1409,7 +1418,9 @@ export const ja: TranslationResources = {
hostDisconnected: "ホストが接続されていません",
hideFailed: "ワークスペースの非表示に失敗しました",
archiveFailed: "ワークスペースのアーカイブに失敗しました",
archiveMultipleFailed: "{{count}}件のワークスペースのアーカイブに失敗しました",
archived: "ワークスペースをアーカイブしました",
archivedCount: "{{count}}件のワークスペースをアーカイブしました",
undoArchive: "元に戻す",
undoArchiveFailed: "アーカイブを元に戻せませんでした",
},
+11
View File
@@ -743,6 +743,8 @@ export const ko: TranslationResources = {
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
reloadingAgent: "에이전트 다시 로드 중...",
reloadedAgent: "에이전트를 다시 로드했습니다",
reloadedAgentHistoryDiverged:
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
failedToCloseAgent: "에이전트를 닫지 못했습니다",
},
@@ -967,6 +969,8 @@ export const ko: TranslationResources = {
},
archiveWarning: {
title: '"{{workspaceName}}"를 보관하시겠습니까?',
bulkTitle: "워크스페이스 {{count}}개를 보관하시겠습니까?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "보관",
cancel: "취소",
uncommittedChanges: "커밋되지 않은 변경 사항",
@@ -1376,6 +1380,7 @@ export const ko: TranslationResources = {
rename: "워크스페이스 이름 변경",
pin: "상단에 고정",
unpin: "고정 해제",
select: "선택",
archive: "보관",
archiveWorkspace: "워크스페이스 보관",
hideFromSidebar: "사이드바에서 숨기기",
@@ -1394,6 +1399,10 @@ export const ko: TranslationResources = {
submit: "이름 변경",
invalidBranchName: "잘못된 브랜치 이름",
},
selection: {
count: "{{count}}개 선택됨",
exit: "선택 종료",
},
toasts: {
workspacePathUnavailable: "워크스페이스 경로를 사용할 수 없습니다",
pathCopied: "경로가 복사되었습니다",
@@ -1401,7 +1410,9 @@ export const ko: TranslationResources = {
hostDisconnected: "호스트가 연결되어 있지 않습니다",
hideFailed: "워크스페이스를 숨기지 못했습니다",
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
archiveMultipleFailed: "워크스페이스 {{count}}개를 보관하지 못했습니다",
archived: "워크스페이스를 보관했습니다",
archivedCount: "워크스페이스 {{count}}개를 보관했습니다",
undoArchive: "실행 취소",
undoArchiveFailed: "보관을 취소하지 못했습니다",
},
+11
View File
@@ -746,6 +746,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,6 +986,8 @@ export const ptBR: TranslationResources = {
},
archiveWarning: {
title: 'Arquivar "{{workspaceName}}"?',
bulkTitle: "Arquivar {{count}} workspaces?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Arquivar",
cancel: "Cancelar",
uncommittedChanges: "Alterações sem commit",
@@ -1396,6 +1400,7 @@ export const ptBR: TranslationResources = {
rename: "Renomear workspace",
pin: "Fixar no topo",
unpin: "Desafixar",
select: "Selecionar",
archive: "Arquivar",
archiveWorkspace: "Arquivar workspace",
hideFromSidebar: "Ocultar da barra lateral",
@@ -1414,6 +1419,10 @@ export const ptBR: TranslationResources = {
submit: "Renomear",
invalidBranchName: "Nome de branch inválido",
},
selection: {
count: "{{count}} selecionados",
exit: "Sair da seleção",
},
toasts: {
workspacePathUnavailable: "Caminho do workspace indisponível",
pathCopied: "Caminho copiado",
@@ -1421,7 +1430,9 @@ export const ptBR: TranslationResources = {
hostDisconnected: "Host não está conectado",
hideFailed: "Falha ao ocultar workspace",
archiveFailed: "Falha ao arquivar workspace",
archiveMultipleFailed: "Falha ao arquivar {{count}} workspaces",
archived: "Workspace arquivado",
archivedCount: "{{count}} workspaces arquivados",
undoArchive: "Desfazer",
undoArchiveFailed: "Não foi possível desfazer o arquivamento",
},
+11
View File
@@ -749,6 +749,8 @@ export const ru: TranslationResources = {
resumeCommandUnavailable: "Команда возобновления недоступна",
reloadingAgent: "Перезагрузка агента...",
reloadedAgent: "Агент перезагружен",
reloadedAgentHistoryDiverged:
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
failedToReloadAgent: "Не удалось перезагрузить агента",
failedToCloseAgent: "Не удалось закрыть агента",
},
@@ -979,6 +981,8 @@ export const ru: TranslationResources = {
},
archiveWarning: {
title: "Архивировать «{{workspaceName}}»?",
bulkTitle: "Архивировать рабочие пространства ({{count}})?",
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
confirm: "Архивировать",
cancel: "Отмена",
uncommittedChanges: "Незафиксированные изменения",
@@ -1389,6 +1393,7 @@ export const ru: TranslationResources = {
rename: "Переименовать рабочее пространство",
pin: "Закрепить вверху",
unpin: "Открепить",
select: "Выбрать",
archive: "Архивировать",
archiveWorkspace: "Архивировать рабочее пространство",
hideFromSidebar: "Скрыть на боковой панели",
@@ -1407,6 +1412,10 @@ export const ru: TranslationResources = {
submit: "Переименовать",
invalidBranchName: "Недопустимое имя ветки",
},
selection: {
count: "Выбрано: {{count}}",
exit: "Выйти из выбора",
},
toasts: {
workspacePathUnavailable: "Путь к рабочему пространству недоступен",
pathCopied: "Путь скопирован",
@@ -1414,7 +1423,9 @@ export const ru: TranslationResources = {
hostDisconnected: "Хост не подключён",
hideFailed: "Не удалось скрыть рабочее пространство",
archiveFailed: "Не удалось архивировать рабочее пространство",
archiveMultipleFailed: "Не удалось архивировать рабочие пространства ({{count}})",
archived: "Рабочее пространство архивировано",
archivedCount: "Архивировано рабочих пространств: {{count}}",
undoArchive: "Отменить",
undoArchiveFailed: "Не удалось отменить архивацию",
},
+11
View File
@@ -741,6 +741,8 @@ export const zhCN: TranslationResources = {
resumeCommandUnavailable: "恢复命令不可用",
reloadingAgent: "正在重新加载 Agent...",
reloadedAgent: "已重新加载 Agent",
reloadedAgentHistoryDiverged:
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
failedToReloadAgent: "重新加载 Agent 失败",
failedToCloseAgent: "关闭 Agent 失败",
},
@@ -952,6 +954,8 @@ export const zhCN: TranslationResources = {
},
archiveWarning: {
title: "归档「{{workspaceName}}」?",
bulkTitle: "归档 {{count}} 个工作区?",
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
confirm: "归档",
cancel: "取消",
uncommittedChanges: "未 commit 的变更",
@@ -1359,6 +1363,7 @@ export const zhCN: TranslationResources = {
rename: "重命名 workspace",
pin: "置顶",
unpin: "取消置顶",
select: "选择",
archive: "归档",
archiveWorkspace: "归档工作区",
hideFromSidebar: "从侧边栏隐藏",
@@ -1376,6 +1381,10 @@ export const zhCN: TranslationResources = {
submit: "重命名",
invalidBranchName: "无效的分支名称",
},
selection: {
count: "已选 {{count}} 项",
exit: "退出选择",
},
toasts: {
workspacePathUnavailable: "Workspace 路径不可用",
pathCopied: "路径已复制",
@@ -1383,7 +1392,9 @@ export const zhCN: TranslationResources = {
hostDisconnected: "Host 未连接",
hideFailed: "隐藏 workspace 失败",
archiveFailed: "归档工作区失败",
archiveMultipleFailed: "归档 {{count}} 个工作区失败",
archived: "工作区已归档",
archivedCount: "已归档 {{count}} 个工作区",
undoArchive: "撤销",
undoArchiveFailed: "无法撤销归档",
},
+2
View File
@@ -14,3 +14,5 @@ export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
export { useHardwareKeyboardPresent } from "./availability";
export { readPressModifiers } from "./internal/press-modifiers";
export type { PressModifiers } from "./internal/press-modifiers";
@@ -9,6 +9,10 @@ export interface OverlayRegistration {
*/
keys: readonly string[];
onKeyDown(event: KeyboardInputEvent): boolean;
/**
* Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults
* to whatever had focus when the overlay opened.
*/
restoreFocusRef?: RefObject<unknown>;
manageFocus?: boolean;
}
@@ -3,12 +3,29 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays
import type { OverlayRegistration } from "./overlay-contract";
type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean;
/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */
interface FocusTarget {
focus(): void;
}
function isFocusTarget(value: unknown): value is FocusTarget {
return (
typeof value === "object" &&
value !== null &&
typeof (value as Partial<FocusTarget>).focus === "function"
);
}
function canRestoreFocusTo(target: FocusTarget): boolean {
return !(target instanceof HTMLElement) || document.contains(target);
}
interface WebOverlayEntry {
getLayer: () => number;
getKeys: () => readonly string[];
getScope: () => HTMLElement | null;
getKeyHandler: () => WebOverlayKeyHandler;
restoreFocus: HTMLElement | null;
restoreFocus: FocusTarget | null;
manageFocus: boolean;
}
@@ -156,7 +173,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
entry.manageFocus &&
options?.restoreFocus !== false &&
entry.restoreFocus &&
document.contains(entry.restoreFocus)
canRestoreFocusTo(entry.restoreFocus)
) {
entry.restoreFocus.focus();
}
@@ -181,7 +198,7 @@ export function useOverlayRegistration({
keysRef.current = keys;
const layerRef = useRef(layer);
const keyHandlerRef = useRef(onKeyDown);
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const registeredRef = useRef(false);
@@ -193,7 +210,7 @@ export function useOverlayRegistration({
keyHandlerRef.current = onKeyDown;
if (active && !wasActiveRef.current && typeof document !== "undefined") {
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
if (requestedRestoreTarget instanceof HTMLElement) {
if (isFocusTarget(requestedRestoreTarget)) {
capturedRestoreFocusRef.current = requestedRestoreTarget;
} else {
capturedRestoreFocusRef.current =
@@ -0,0 +1,111 @@
import { getShortcutOs } from "@/utils/shortcut-platform";
export type HeldModifierKey = "Shift" | "Meta" | "Control";
export interface HeldModifierKeyEvent {
key: string;
code?: string;
shiftKey: boolean;
metaKey: boolean;
ctrlKey: boolean;
}
export interface HeldModifierTracker {
isDown(key: HeldModifierKey): boolean;
handleKeyDown(event: HeldModifierKeyEvent): void;
handleKeyUp(event: HeldModifierKeyEvent): void;
reset(): void;
}
const MODIFIER_FLAGS = {
Shift: "shiftKey",
Meta: "metaKey",
Control: "ctrlKey",
} as const satisfies Record<HeldModifierKey, keyof HeldModifierKeyEvent>;
const MODIFIER_KEYS = Object.keys(MODIFIER_FLAGS) as HeldModifierKey[];
/**
* Tracks which physical modifier keys are held across DOM and native hardware keyboard streams so
* press handlers that omit modifier flags (native GestureResponderEvent, touch-synthesized clicks)
* can still observe Shift+tap or Cmd+tap from a hardware keyboard.
*/
export function createHeldModifierTracker(): HeldModifierTracker {
const pressedCodes: Record<HeldModifierKey, Set<string>> = {
Shift: new Set(),
Meta: new Set(),
Control: new Set(),
};
// A key reported without a modifier's flag means that modifier's key-up was swallowed.
const clearReleased = (event: HeldModifierKeyEvent) => {
for (const modifier of MODIFIER_KEYS) {
if (event.key !== modifier && !event[MODIFIER_FLAGS[modifier]]) {
pressedCodes[modifier].clear();
}
}
};
return {
isDown: (key) => pressedCodes[key].size > 0,
handleKeyDown(event) {
const modifier = MODIFIER_KEYS.find((key) => key === event.key);
if (modifier) {
pressedCodes[modifier].add(event.code || modifier);
}
clearReleased(event);
},
handleKeyUp(event) {
const modifier = MODIFIER_KEYS.find((key) => key === event.key);
if (modifier) {
pressedCodes[modifier].delete(event.code || modifier);
if (!event[MODIFIER_FLAGS[modifier]]) {
pressedCodes[modifier].clear();
}
}
clearReleased(event);
},
reset() {
for (const modifier of MODIFIER_KEYS) {
pressedCodes[modifier].clear();
}
},
};
}
export const heldModifiers = createHeldModifierTracker();
/**
* Modifiers that accompanied a pointer press. `mod` is the platform primary modifier the shortcut
* layer binds as `mod`: Cmd on macOS/iOS/iPadOS, Ctrl on Windows, Linux and Android. Ctrl on macOS
* is the secondary click, so it never counts as `mod` there.
*/
export interface PressModifiers {
shift: boolean;
mod: boolean;
}
interface PressModifierContext {
isMac: boolean;
held: Pick<HeldModifierTracker, "isDown">;
}
export function readPressModifiers(
event: unknown,
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
): PressModifiers {
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
return {
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
};
}
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): boolean {
if (typeof event !== "object" || event === null) return false;
if (Reflect.get(event, flag) === true) return true;
const nativeEvent = Reflect.get(event, "nativeEvent");
return (
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, flag) === true
);
}
@@ -1,3 +1,4 @@
import { AppState } from "react-native";
import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract";
import {
setHardwareKeyboardClaimedShortcuts,
@@ -7,6 +8,14 @@ import {
import { createHardwareKeyboardSource } from "./native";
const hardwareKeyboard = createHardwareKeyboardSource({
subscribe: subscribeHardwareKeyboard,
subscribeBlur: (onBlur) => {
const subscription = AppState.addEventListener("change", (nextState) => {
if (nextState !== "active") {
onBlur();
}
});
return () => subscription.remove();
},
setOverlayKeys: setHardwareKeyboardOverlayKeys,
setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts,
});
@@ -9,6 +9,7 @@ import {
import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware";
interface HardwareKeySource {
subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void;
subscribeBlur?(handler: () => void): () => void;
setOverlayKeys(keys: readonly string[]): void;
setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void;
}
@@ -78,7 +79,9 @@ export function createHardwareKeyboardSource(source: HardwareKeySource) {
nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())),
);
});
const unsubscribeBlur = source.subscribeBlur?.(() => handlers.blur()) ?? (() => {});
return () => {
unsubscribeBlur();
unsubscribeHardware();
unsubscribeFocus();
unsubscribeCommandCenter();
@@ -269,4 +269,142 @@ describe("hardware source adapter", () => {
expect(claimed).toEqual([]);
releaseFinal();
});
it("forwards native blur events and unsubscribes on detach", async () => {
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
const blurListeners = new Set<() => void>();
let blurCalls = 0;
const detach = createHardwareKeyboardSource({
subscribe: () => () => {},
subscribeBlur(listener) {
blurListeners.add(listener);
return () => {
blurListeners.delete(listener);
};
},
setOverlayKeys() {},
setClaimedShortcuts() {},
}).attach({
keyDown() {},
keyUp() {},
blur() {
blurCalls += 1;
},
commandCenterOpen: () => false,
subscribeCommandCenter: () => () => {},
});
for (const listener of blurListeners) listener();
expect(blurCalls).toBe(1);
detach();
expect(blurListeners.size).toBe(0);
});
});
function modifierKey(
key: string,
code: string,
flags: { shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean } = {},
) {
return { key, code, shiftKey: false, metaKey: false, ctrlKey: false, ...flags };
}
describe("held modifier tracking", () => {
it("tracks left/right Shift holds, self-heals on non-shifted keys, and resets on blur", async () => {
const { createHeldModifierTracker } = await import("./internal/press-modifiers");
const tracker = createHeldModifierTracker();
expect(tracker.isDown("Shift")).toBe(false);
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyDown(modifierKey("Shift", "ShiftRight", { shiftKey: true }));
tracker.handleKeyUp(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyUp(modifierKey("Shift", "ShiftRight"));
expect(tracker.isDown("Shift")).toBe(false);
// Self-heals if a Shift key-up was swallowed by the OS.
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.handleKeyDown(modifierKey("a", "KeyA"));
expect(tracker.isDown("Shift")).toBe(false);
// Clears on blur / backgrounding.
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(tracker.isDown("Shift")).toBe(true);
tracker.reset();
expect(tracker.isDown("Shift")).toBe(false);
});
it("tracks Cmd and Ctrl holds independently of Shift", async () => {
const { createHeldModifierTracker } = await import("./internal/press-modifiers");
const tracker = createHeldModifierTracker();
tracker.handleKeyDown(modifierKey("Meta", "MetaLeft", { metaKey: true }));
tracker.handleKeyDown(modifierKey("Shift", "ShiftLeft", { metaKey: true, shiftKey: true }));
expect([tracker.isDown("Meta"), tracker.isDown("Shift"), tracker.isDown("Control")]).toEqual([
true,
true,
false,
]);
tracker.handleKeyUp(modifierKey("Shift", "ShiftLeft", { metaKey: true }));
expect([tracker.isDown("Meta"), tracker.isDown("Shift")]).toEqual([true, false]);
// A key reported without the Meta flag means its key-up was swallowed.
tracker.handleKeyDown(modifierKey("a", "KeyA"));
expect(tracker.isDown("Meta")).toBe(false);
tracker.handleKeyDown(modifierKey("Control", "ControlRight", { ctrlKey: true }));
expect(tracker.isDown("Control")).toBe(true);
tracker.handleKeyUp(modifierKey("Control", "ControlRight"));
expect(tracker.isDown("Control")).toBe(false);
});
});
describe("press modifiers", () => {
it("reads Shift and the platform primary modifier from a pointer press", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
const mac = { isMac: true, held };
const other = { isMac: false, held };
expect(readPressModifiers({ shiftKey: true }, mac)).toEqual({ shift: true, mod: false });
expect(readPressModifiers({ nativeEvent: { shiftKey: true } }, other)).toEqual({
shift: true,
mod: false,
});
expect(readPressModifiers({ metaKey: true }, mac)).toEqual({ shift: false, mod: true });
expect(readPressModifiers({ ctrlKey: true }, other)).toEqual({ shift: false, mod: true });
// Ctrl+click is the secondary click on macOS, and Windows/Linux have no Cmd.
expect(readPressModifiers({ ctrlKey: true }, mac)).toEqual({ shift: false, mod: false });
expect(readPressModifiers({ metaKey: true }, other)).toEqual({ shift: false, mod: false });
expect(readPressModifiers(null, mac)).toEqual({ shift: false, mod: false });
});
it("falls back to held hardware keys when a native press omits modifiers", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
const responderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { metaKey: true }));
expect(readPressModifiers(responderEvent, { isMac: true, held })).toEqual({
shift: false,
mod: true,
});
expect(readPressModifiers(responderEvent, { isMac: false, held })).toEqual({
shift: false,
mod: false,
});
held.reset();
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
expect(readPressModifiers(responderEvent, { isMac: true, held })).toEqual({
shift: true,
mod: false,
});
});
});
+16 -3
View File
@@ -1,6 +1,7 @@
import { usesDesktopBindings } from "./internal/conventions";
import { createKeyboardPipeline } from "./internal/pipeline";
import { overlays } from "./internal/overlays";
import { heldModifiers } from "./internal/press-modifiers";
import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources";
import type { KeyboardSourceInput } from "./internal/sources/contract";
import type { KeyboardInputEvent } from "./internal/overlays";
@@ -249,19 +250,30 @@ export function useKeyboardShortcuts({
[getContext, getBindings, isCapturing, dispatchMatch, beforeResolve, chordChanged],
);
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
heldModifiers.handleKeyDown(input.event);
return pipeline.keyDown(input);
});
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
heldModifiers.handleKeyUp(event);
const key = event.key ?? "";
if (key === badgeModifierKey) {
setBadgeModifierDown(false);
}
});
const handleBlur = useStableEvent(() => {
heldModifiers.reset();
resetModifiers();
});
useEffect(() => {
if (!enabled) return;
const detach = attachKeyboardSources({
keyDown: pipeline.keyDown,
keyDown: handleKeyDown,
keyUp: handleKeyUp,
blur: resetModifiers,
blur: handleBlur,
commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen,
subscribeCommandCenter: (listener) =>
useKeyboardShortcutsStore.subscribe((state, previous) => {
@@ -270,7 +282,8 @@ export function useKeyboardShortcuts({
});
return () => {
detach();
heldModifiers.reset();
pipeline.dispose();
};
}, [enabled, pipeline, handleKeyUp, resetModifiers]);
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
}
@@ -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",
},
]);
@@ -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: [],
+12 -4
View File
@@ -255,6 +255,7 @@ const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
const ACTIVE_RTT_WINDOW_MS = 60_000;
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
const MAX_STALE_TIMELINE_PAGE_ATTEMPTS = 3;
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
@@ -3128,12 +3129,19 @@ export class HostRuntimeStore {
const directory = this.directorySyncByServer.get(serverId);
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
const page = await directory.fetchTimeline(agentId, request);
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
// A page served before a rewind this client applied is asked for again. Seqs only grow within
// an epoch, so the next page includes the rewind unless another one landed meanwhile.
for (let attempt = 1; ; attempt += 1) {
const page = await directory.fetchTimeline(agentId, request);
if (!owner || useSessionStore.getState().sessions[serverId]?.viewedTimelineSync !== owner) {
return page;
}
owner.flushStreamAgent(agentId);
owner.applyTimelineResponse(page);
if (owner.applyTimelineResponse(page) === "applied") return page;
if (attempt === MAX_STALE_TIMELINE_PAGE_ATTEMPTS) {
throw new Error(`Timeline page for ${agentId} stayed behind a rewind`);
}
}
return page;
}
createViewedTimelineOwner(
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
id: "message-1",
text,
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
};
}
@@ -840,7 +840,7 @@ describe("ReplicaCache", () => {
version: 1,
data: { passed: 4, failed: 0 },
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
};
writer.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
@@ -885,6 +885,32 @@ describe("ReplicaCache", () => {
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("keeps where each cached row started, and refetches a timeline cached without it", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const updatedAfterItStarted: StreamItem = {
...timelineItem(),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 9 },
};
writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items: [updatedAfterItStarted] });
await writer.flush();
expect((await createCache(storage).readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([
updatedAfterItStarted,
]);
const row = requireTimelineRow(storage);
const payload = JSON.parse(row.payload) as {
items: Array<{ timelineCursor?: Record<string, unknown> }>;
};
delete payload.items[0]?.timelineCursor?.anchorSeq;
storage.rows.set(`${row.serverId}:${row.kind}:${row.id}`, {
...row,
payload: JSON.stringify(payload),
});
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("refetches old cached Markdown fragments instead of offering them as whole messages", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -1355,7 +1381,7 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
kind: "tool_call",
id: "delivery",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
payload: {
source: "agent",
data: {
@@ -22,6 +22,7 @@ import {
isUnreconciledLocalUserMessage,
type AgentToolCallData,
type StreamItem,
type TimelinePosition,
} from "@/types/stream";
import type { UnsettledTurn } from "@/timeline/turn-liveness";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
@@ -82,7 +83,15 @@ const IsoDateSchema = z.iso.datetime();
const TimelinePositionSchema = z.strictObject({
epoch: z.string(),
seq: z.number().int().nonnegative(),
// COMPAT(timelineRewindOperations): absent on caches written before rows were anchored, added in
// v0.14.1, remove after 2027-05-10. Such a cache is not restored; the chat loads its tail instead.
anchorSeq: z.number().int().nonnegative().optional(),
});
type StoredTimelinePosition = z.infer<typeof TimelinePositionSchema>;
function isAnchored(position: StoredTimelinePosition | undefined): boolean {
return position === undefined || position.anchorSeq !== undefined;
}
const PluginTimelineDataSchema: z.ZodType<PluginTimelineData> = z.lazy(() =>
z.union([
z.null(),
@@ -423,6 +432,10 @@ function deserializeTimeline(stored: StoredTimeline | null): CachedTimeline | nu
if (!stored) {
return null;
}
// A rewind retires rows by anchor, so an unanchored row could not be retired.
if (!stored.items.every((item) => isAnchored(item.timelineCursor))) {
return null;
}
return {
agentId: stored.agentId,
items: stored.items.map(deserializeTimelineItem),
@@ -539,11 +552,20 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
}
}
function anchoredPosition(position: StoredTimelinePosition | undefined): {
timelineCursor?: TimelinePosition;
} {
if (!position || position.anchorSeq === undefined) return {};
return {
timelineCursor: { epoch: position.epoch, seq: position.seq, anchorSeq: position.anchorSeq },
};
}
function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
if (item.kind === "plugin") {
return {
id: item.id,
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...anchoredPosition(item.timelineCursor),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
kind: item.kind,
@@ -562,7 +584,7 @@ function deserializeBuiltinTimelineItem(
): StreamItem {
const base = {
id: item.id,
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...anchoredPosition(item.timelineCursor),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
};
@@ -1578,9 +1578,18 @@ export function NewWorkspaceScreen({
? t("newWorkspace.refPicker.searching")
: t("newWorkspace.refPicker.noMatchingRefs");
// The prompt is where the user types; when a field's picker closes, focus returns there rather
// than to whatever had focus when the picker opened. A terminal profile that takes no prompt
// shows a read-only command preview, so its pickers keep returning focus to their field.
const composerFocusRef = useRef<{ focus: () => void } | null>(null);
const handleComposerFocusInput = useCallback((focus: () => void) => {
composerFocusRef.current = { focus };
}, []);
const formStack = useNewWorkspaceForm({
isCompact,
isPending,
restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined,
pluginItems: (
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
),
@@ -1682,6 +1691,7 @@ export function NewWorkspaceScreen({
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
error={errorMessage}
/>
) : (
@@ -1712,6 +1722,7 @@ export function NewWorkspaceScreen({
clearDraft={handleClearDraft}
autoFocus
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
error={errorMessage}
@@ -67,6 +67,11 @@ export interface NewWorkspaceFormProps {
isPending: boolean;
/** Plugin fields, drawn after the base ref. */
pluginItems: ReactNode;
/**
* Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without
* one, focus returns to the field that opened the picker.
*/
restoreFocusRef?: RefObject<unknown>;
project: PickerControl & {
options: ComboboxOption[];
projectByOptionId: Map<string, HostProjectListItem>;
@@ -373,7 +378,17 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
*/
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
const { t } = useTranslation();
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
const {
isCompact,
isPending,
pluginItems,
restoreFocusRef,
project,
host,
isolation,
base,
launch,
} = props;
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
const projectPicker = useProjectPicker(project, isPending);
const isolationPicker = useIsolationPicker({
@@ -432,6 +447,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
open={host.openState}
onOpenChange={host.onOpenChange}
anchorRef={host.anchorRef}
restoreFocusRef={restoreFocusRef}
includeAddHost
onAddHost={host.onAddHost}
addHostTestID="new-workspace-host-picker-add-host"
@@ -525,6 +541,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={project.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText="No projects available."
renderOption={projectPicker.renderOption}
footer={projectPicker.footer}
@@ -539,6 +556,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
desktopPlacement="bottom-start"
anchorRef={isolation.anchorRef}
restoreFocusRef={restoreFocusRef}
desktopMinWidth={280}
renderOption={isolationPicker.renderOption}
/>
@@ -555,6 +573,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={440}
anchorRef={base.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={base.emptyText}
toolbar={refPicker.toolbar}
renderOption={refPicker.renderOption}
@@ -571,6 +590,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={worktreePicker.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={t("newWorkspace.worktreePicker.empty")}
renderOption={worktreePicker.renderOption}
/>
@@ -2188,11 +2188,10 @@ function WorkspaceScreenContent({
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
try {
await client.refreshAgent(agentId);
// Send the existing cursor so the server detects the new epoch and
// returns reset:true. Without a cursor, the server returns reset:false
// and the client takes the incremental path, where new-epoch rows are
// dropped against the stale cursor.
const refreshed = await client.refreshAgent(agentId);
// Send the existing cursor: Reload agent keeps the history, so the server
// returns only the rows it added. When the history was imported again
// under a new epoch, the cursor reads as stale and the server resets.
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
@@ -2201,7 +2200,13 @@ function WorkspaceScreenContent({
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
: {}),
});
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
variant: "warning",
});
} else {
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
@@ -0,0 +1,8 @@
export {
registerSidebarVisibleWorkspaceKeysReader,
useIsSidebarSelectionMode,
useIsWorkspaceBulkSelected,
useSidebarSelectionStore,
} from "./internal/selection-store";
export { SidebarSelectionHost } from "./internal/sidebar-selection-host";
export { useWorkspaceSelectionPress } from "./internal/workspace-selection-press";
@@ -0,0 +1,280 @@
import { describe, expect, it, vi } from "vitest";
import type { ToastApi } from "@/components/toast-host";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import {
archiveSelectedWorkspaces,
type BulkArchiveClient,
type BulkArchiveWorkspacesDeps,
} from "./archive-selected";
function makeEntry(
overrides: Partial<SidebarWorkspaceEntry> & { workspaceId: string },
): SidebarWorkspaceEntry {
return {
workspaceKey: `srv:${overrides.workspaceId}`,
serverId: "srv",
projectViewKey: "prj-view",
projectName: "Repo",
projectRootPath: "/repo",
workspaceDirectory: `/repo/${overrides.workspaceId}`,
workspaceDirectoryLabel: overrides.workspaceId,
projectKind: "git",
workspaceKind: "local_checkout",
name: overrides.workspaceId,
title: null,
currentBranch: overrides.workspaceId,
statusBucket: "done",
statusEnteredAt: null,
archivingAt: null,
diffStat: null,
prHint: null,
pinnedAt: null,
background: false,
labels: [],
scripts: [],
hasRunningScripts: false,
archiveHasUncommittedChanges: null,
archiveUnpushedCommitCount: null,
...overrides,
};
}
function createFakeToast(): { toast: ToastApi; errors: string[] } {
const errors: string[] = [];
return {
errors,
toast: {
show: () => () => {},
copied: () => {},
error: (message) => errors.push(message),
},
};
}
function createFakeClient(): BulkArchiveClient {
return {
archiveWorkspace: async () => ({ error: null }),
undoWorkspaceArchive: async () => {},
getCheckoutStatus: async () =>
({
isGit: true,
isDirty: false,
aheadOfOrigin: 0,
}) as Awaited<ReturnType<BulkArchiveClient["getCheckoutStatus"]>>,
};
}
describe("archiveSelectedWorkspaces", () => {
it("archives multiple workspaces with one undo batch and redirects active workspace first", async () => {
const order: string[] = [];
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const confirmRiskyBulkArchive = vi.fn(async () => true);
const deps: BulkArchiveWorkspacesDeps = {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: async () => ({ isDirty: false, aheadOfOrigin: 0 }),
confirmRiskyBulkArchive,
archiveWithUndo: async (input) => {
order.push(
`archive:${input.entries.map((entry) => entry.workspace.workspaceId).join(",")}`,
);
return { failures: [], showPartialFailure: () => false };
},
archiveWithoutUndo: async () => "archived",
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: (workspace) => {
order.push(`redirect:${workspace.workspaceId}`);
},
};
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: () => order.push("exit-selection"),
deps,
});
expect(ok).toBe(true);
expect(errors).toEqual([]);
expect(order).toEqual(["redirect:w1", "redirect:w2", "exit-selection", "archive:w1,w2"]);
expect(confirmRiskyBulkArchive).not.toHaveBeenCalled();
});
it("keeps select mode open when the user cancels a risky worktree confirmation", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const onArchiveStarted = vi.fn();
const archiveWithUndo = vi.fn(async () => ({
failures: [],
showPartialFailure: () => false,
}));
const confirmRiskyBulkArchive = vi.fn(async () => false);
const ok = await archiveSelectedWorkspaces({
workspaces: [
makeEntry({ workspaceId: "w1", workspaceKind: "worktree", name: "feat-wip" }),
makeEntry({ workspaceId: "w2", workspaceKind: "local_checkout", name: "main" }),
],
toast,
onArchiveStarted,
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: async () => ({ isDirty: true, aheadOfOrigin: 1 }),
confirmRiskyBulkArchive,
archiveWithUndo,
archiveWithoutUndo: async () => "archived",
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual([]);
expect(confirmRiskyBulkArchive).toHaveBeenCalledWith({
totalCount: 2,
riskyWorkspaces: [
{
workspaceName: "feat-wip",
diffStat: null,
isDirty: true,
aheadOfOrigin: 1,
},
],
});
expect(onArchiveStarted).not.toHaveBeenCalled();
expect(archiveWithUndo).not.toHaveBeenCalled();
});
it("shows a disconnect error and aborts before archiving when any host is offline", async () => {
const { toast, errors } = createFakeToast();
const onArchiveStarted = vi.fn();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" })],
toast,
onArchiveStarted,
deps: {
getClient: () => null,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: vi.fn(),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual(["Host is not connected"]);
expect(onArchiveStarted).not.toHaveBeenCalled();
});
it("reports multi-workspace failures when more than one archive fails", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{ workspace: { serverId: "srv", workspaceId: "w1" }, error: new Error("boom 1") },
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("boom 2") },
],
showPartialFailure: () => false,
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(errors).toEqual(["Failed to archive 2 workspaces"]);
});
it("keeps Undo open via showPartialFailure instead of replacing it with toast.error on partial failure", async () => {
const client = createFakeClient();
const { toast, errors } = createFakeToast();
const partialErrors: string[] = [];
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("Host offline") },
],
showPartialFailure: (message) => {
partialErrors.push(message);
return true;
},
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => false,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(partialErrors).toEqual(["Host offline"]);
expect(errors).toEqual([]);
});
it("routes a late failure from a superseded batch to fallbackErrorToast so a newer batch keeps its Undo", async () => {
const client = createFakeClient();
const sidebar = createFakeToast();
const app = createFakeToast();
const ok = await archiveSelectedWorkspaces({
workspaces: [makeEntry({ workspaceId: "w1" })],
toast: sidebar.toast,
fallbackErrorToast: app.toast,
onArchiveStarted: vi.fn(),
deps: {
getClient: () => client,
supportsUndo: () => true,
readWorktreeRisk: vi.fn(),
confirmRiskyBulkArchive: vi.fn(),
archiveWithUndo: async () => ({
failures: [
{
workspace: { serverId: "srv", workspaceId: "w1" },
error: new Error("Host timed out"),
},
],
// This batch's own undo window was closed when a newer batch superseded it.
showPartialFailure: () => false,
}),
archiveWithoutUndo: vi.fn(),
hasActiveUndo: () => true,
purgeWorkspaceState: vi.fn(),
redirectActiveWorkspace: vi.fn(),
},
});
expect(ok).toBe(false);
expect(sidebar.errors).toEqual([]);
expect(app.errors).toEqual(["Host timed out"]);
});
});
@@ -0,0 +1,197 @@
import type { ToastApi } from "@/components/toast-host";
import type { CheckoutStatusClient } from "@/git/checkout-status-cache";
import {
confirmRiskyBulkWorktreeArchive,
readWorktreeArchiveRisk,
type WorktreeArchiveConfirmationInput,
} from "@/git/worktree-archive-warning";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
import { i18n } from "@/i18n/i18next";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import {
archiveWorkspacesWithUndo,
hasUndoableWorkspaceArchive,
supportsWorkspaceArchiveUndo,
type UndoableWorkspaceArchiveClient,
} from "@/workspace/archive-undo";
import {
archiveWorkspaceOptimistically,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
export interface BulkArchiveClient extends UndoableWorkspaceArchiveClient, CheckoutStatusClient {}
export interface BulkArchiveWorkspacesDeps {
getClient: (serverId: string) => BulkArchiveClient | null;
supportsUndo: (serverId: string) => boolean;
readWorktreeRisk: typeof readWorktreeArchiveRisk;
confirmRiskyBulkArchive: typeof confirmRiskyBulkWorktreeArchive;
archiveWithUndo: typeof archiveWorkspacesWithUndo;
archiveWithoutUndo: typeof archiveWorkspaceOptimistically;
hasActiveUndo: () => boolean;
purgeWorkspaceState: (workspace: WorkspaceArchiveTarget) => void;
redirectActiveWorkspace: (workspace: WorkspaceArchiveTarget) => void;
}
function defaultPurgeWorkspaceState(workspace: WorkspaceArchiveTarget): void {
const workspaceKey = buildWorkspaceTabPersistenceKey(workspace);
if (workspaceKey) {
useWorkspaceLayoutStore.getState().purgeWorkspace(workspaceKey);
}
}
export function createDefaultBulkArchiveDeps(
getActiveWorkspaceSelection: () => ActiveWorkspaceSelection | null,
): BulkArchiveWorkspacesDeps {
return {
getClient: (serverId) => getHostRuntimeStore().getClient(serverId),
supportsUndo: supportsWorkspaceArchiveUndo,
readWorktreeRisk: readWorktreeArchiveRisk,
confirmRiskyBulkArchive: confirmRiskyBulkWorktreeArchive,
archiveWithUndo: archiveWorkspacesWithUndo,
archiveWithoutUndo: archiveWorkspaceOptimistically,
hasActiveUndo: hasUndoableWorkspaceArchive,
purgeWorkspaceState: defaultPurgeWorkspaceState,
redirectActiveWorkspace: (workspace) => {
redirectIfArchivingActiveWorkspace({
serverId: workspace.serverId,
workspaceId: workspace.workspaceId,
activeWorkspaceSelection: getActiveWorkspaceSelection(),
});
},
};
}
function formatArchiveFailureMessage(failures: ReadonlyArray<{ error: unknown }>): string {
if (failures.length > 1) {
return i18n.t("sidebar.workspace.toasts.archiveMultipleFailed", { count: failures.length });
}
const error = failures[0]?.error;
return error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed");
}
interface ResolvedWorkspaceTarget {
entry: SidebarWorkspaceEntry;
client: BulkArchiveClient;
}
export async function archiveSelectedWorkspaces(input: {
workspaces: readonly SidebarWorkspaceEntry[];
toast: ToastApi;
fallbackErrorToast?: ToastApi;
onArchiveStarted: () => void;
deps: BulkArchiveWorkspacesDeps;
}): Promise<boolean> {
const { workspaces, toast, fallbackErrorToast, onArchiveStarted, deps } = input;
if (workspaces.length === 0) return false;
const resolved: ResolvedWorkspaceTarget[] = [];
for (const entry of workspaces) {
const client = deps.getClient(entry.serverId);
if (!client) {
toast.error(i18n.t("sidebar.workspace.toasts.hostDisconnected"));
return false;
}
resolved.push({ entry, client });
}
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
if (worktrees.length > 0) {
try {
const risks = await Promise.all(
worktrees.map(async ({ entry, client }) => {
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
return {
workspaceName: entry.name,
diffStat: entry.diffStat,
isDirty: risk.isDirty,
aheadOfOrigin: risk.aheadOfOrigin,
} satisfies WorktreeArchiveConfirmationInput;
}),
);
riskyWorkspaces.push(...risks);
} catch (error) {
toast.error(
error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed"),
);
return false;
}
}
if (riskyWorkspaces.length > 0) {
const confirmed = await deps.confirmRiskyBulkArchive({
totalCount: resolved.length,
riskyWorkspaces,
});
if (!confirmed) {
return false;
}
}
// Redirect before optimistic removal hides the active workspace from the session store.
for (const { entry } of resolved) {
deps.redirectActiveWorkspace({ serverId: entry.serverId, workspaceId: entry.workspaceId });
}
onArchiveStarted();
const undoable: ResolvedWorkspaceTarget[] = [];
const legacy: ResolvedWorkspaceTarget[] = [];
for (const item of resolved) {
if (deps.supportsUndo(item.entry.serverId)) {
undoable.push(item);
} else {
legacy.push(item);
}
}
const failures: Array<{ error: unknown }> = [];
let showPartialFailure: (message: string) => boolean = () => false;
await Promise.all([
undoable.length > 0
? (async () => {
const result = await deps.archiveWithUndo({
entries: undoable.map(({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
return {
client,
workspace,
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
};
}),
toast,
});
failures.push(...result.failures);
showPartialFailure = result.showPartialFailure;
})()
: Promise.resolve(),
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
...legacy.map(async ({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
try {
await deps.archiveWithoutUndo({ client, workspace });
deps.purgeWorkspaceState(workspace);
} catch (error) {
failures.push({ error });
}
}),
]);
if (failures.length > 0) {
const errorMessage = formatArchiveFailureMessage(failures);
if (!showPartialFailure(errorMessage)) {
// If a newer batch now owns the sidebar Undo toast, surface this older failure on the
// app-level toast instead of displacing the active Undo window and purging its layouts.
const errorToast = deps.hasActiveUndo() ? (fallbackErrorToast ?? toast) : toast;
errorToast.error(errorMessage);
}
}
return failures.length === 0;
}
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import {
enterWorkspaceSelection,
exitWorkspaceSelection,
INITIAL_WORKSPACE_SELECTION_STATE,
reconcileWorkspaceSelection,
selectWorkspaceRange,
toggleWorkspaceSelection,
} from "./selection-state";
describe("sidebar workspace selection state", () => {
it("enters selection with the clicked workspace as anchor", () => {
const state = enterWorkspaceSelection("ws-2");
expect({
active: state.active,
selected: [...state.selectedKeys],
anchorKey: state.anchorKey,
}).toEqual({
active: true,
selected: ["ws-2"],
anchorKey: "ws-2",
});
});
it("toggles workspaces on plain click without needing Shift", () => {
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3"]);
expect(state.anchorKey).toBe("ws-3");
state = toggleWorkspaceSelection(state, "ws-1");
expect([...state.selectedKeys]).toEqual(["ws-3"]);
expect(state.anchorKey).toBe("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
expect(state.active).toBe(true);
expect([...state.selectedKeys]).toEqual([]);
});
it("selects an inclusive range on Shift+click in either direction while keeping prior picks", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5"];
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
state = selectWorkspaceRange(state, "ws-5", visible);
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3", "ws-4", "ws-5"]);
expect(state.anchorKey).toBe("ws-3");
const backward = selectWorkspaceRange(enterWorkspaceSelection("ws-4"), "ws-2", visible);
expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]);
});
it("replaces the previous Shift range so a closer Shift+click shrinks it, like Finder", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5", "ws-6"];
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-3");
state = selectWorkspaceRange(state, "ws-6", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-3", "ws-4", "ws-5", "ws-6"]);
state = selectWorkspaceRange(state, "ws-4", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-3", "ws-4"]);
// Crossing over the anchor flips the range without dropping the earlier pick.
state = selectWorkspaceRange(state, "ws-2", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-2", "ws-3"]);
expect(state.anchorKey).toBe("ws-3");
});
it("commits the Shift range once a toggle moves the anchor", () => {
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5", "ws-6"];
let state = enterWorkspaceSelection("ws-1");
state = selectWorkspaceRange(state, "ws-3", visible);
state = toggleWorkspaceSelection(state, "ws-5");
// The new anchor is ws-5; shrinking its range must keep ws-1..ws-3.
state = selectWorkspaceRange(state, "ws-6", visible);
state = selectWorkspaceRange(state, "ws-5", visible);
expect([...state.selectedKeys].sort()).toEqual(["ws-1", "ws-2", "ws-3", "ws-5"]);
});
it("falls back to adding the target when the anchor is no longer in the visible list", () => {
const state = selectWorkspaceRange(enterWorkspaceSelection("ws-hidden"), "ws-2", [
"ws-1",
"ws-2",
]);
expect([...state.selectedKeys]).toEqual(["ws-hidden", "ws-2"]);
expect(state.anchorKey).toBe("ws-2");
});
it("reconciles removed workspaces and clears a missing anchor", () => {
let state = enterWorkspaceSelection("ws-1");
state = toggleWorkspaceSelection(state, "ws-2");
const reconciled = reconcileWorkspaceSelection(state, new Set(["ws-1"]));
expect({
active: reconciled.active,
selected: [...reconciled.selectedKeys],
anchorKey: reconciled.anchorKey,
}).toEqual({
active: true,
selected: ["ws-1"],
anchorKey: null,
});
});
it("resets completely on exit", () => {
expect(exitWorkspaceSelection()).toBe(INITIAL_WORKSPACE_SELECTION_STATE);
});
});
@@ -0,0 +1,120 @@
export interface WorkspaceSelectionState {
active: boolean;
selectedKeys: ReadonlySet<string>;
anchorKey: string | null;
/**
* Selection as it stood before the current run of Shift+clicks from `anchorKey`. Each Shift+click
* rebuilds the selection from this base, so a closer Shift+click shrinks the range like Finder.
* Null until the first Shift+click after the anchor moves.
*/
rangeBaseKeys: ReadonlySet<string> | null;
}
const EMPTY_KEYS: ReadonlySet<string> = new Set();
export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = {
active: false,
selectedKeys: EMPTY_KEYS,
anchorKey: null,
rangeBaseKeys: null,
};
export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState {
return {
active: true,
selectedKeys: new Set([workspaceKey]),
anchorKey: workspaceKey,
rangeBaseKeys: null,
};
}
export function toggleWorkspaceSelection(
state: WorkspaceSelectionState,
workspaceKey: string,
): WorkspaceSelectionState {
if (!state.active) {
return enterWorkspaceSelection(workspaceKey);
}
const next = new Set(state.selectedKeys);
if (!next.delete(workspaceKey)) {
next.add(workspaceKey);
}
return {
active: true,
selectedKeys: next,
anchorKey: workspaceKey,
rangeBaseKeys: null,
};
}
export function selectWorkspaceRange(
state: WorkspaceSelectionState,
targetKey: string,
orderedVisibleKeys: readonly string[],
): WorkspaceSelectionState {
if (!state.active) {
return enterWorkspaceSelection(targetKey);
}
const anchorIndex = state.anchorKey ? orderedVisibleKeys.indexOf(state.anchorKey) : -1;
const targetIndex = orderedVisibleKeys.indexOf(targetKey);
if (anchorIndex < 0 || targetIndex < 0) {
const next = new Set(state.selectedKeys);
next.add(targetKey);
return { active: true, selectedKeys: next, anchorKey: targetKey, rangeBaseKeys: null };
}
const rangeBaseKeys = state.rangeBaseKeys ?? state.selectedKeys;
const start = Math.min(anchorIndex, targetIndex);
const end = Math.max(anchorIndex, targetIndex);
const next = new Set(rangeBaseKeys);
for (let index = start; index <= end; index += 1) {
const key = orderedVisibleKeys[index];
if (key !== undefined) {
next.add(key);
}
}
return {
active: true,
selectedKeys: next,
anchorKey: state.anchorKey,
rangeBaseKeys,
};
}
export function reconcileWorkspaceSelection(
state: WorkspaceSelectionState,
availableKeys: ReadonlySet<string>,
): WorkspaceSelectionState {
if (!state.active) return state;
const selectedKeys = keepAvailableKeys(state.selectedKeys, availableKeys);
const rangeBaseKeys = state.rangeBaseKeys
? keepAvailableKeys(state.rangeBaseKeys, availableKeys)
: null;
const anchorKey = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null;
if (
selectedKeys === state.selectedKeys &&
rangeBaseKeys === state.rangeBaseKeys &&
anchorKey === state.anchorKey
) {
return state;
}
return { active: true, selectedKeys, anchorKey, rangeBaseKeys };
}
function keepAvailableKeys(
keys: ReadonlySet<string>,
availableKeys: ReadonlySet<string>,
): ReadonlySet<string> {
for (const key of keys) {
if (!availableKeys.has(key)) {
return new Set([...keys].filter((candidate) => availableKeys.has(candidate)));
}
}
return keys;
}
export function exitWorkspaceSelection(): WorkspaceSelectionState {
return INITIAL_WORKSPACE_SELECTION_STATE;
}

Some files were not shown because too many files have changed in this diff Show More