Compare commits

..
Author SHA1 Message Date
Mohamed Boudra bd4e817951 fix(plugins): start a Windows bare name directly when the caller passes shell: false
The PATH lookup that finds a .cmd shim ran statSync for every bare name, including git with
shell: false, so a daemon Git refresh did synchronous IO on Windows. An explicit shell: false
now starts the name directly, as on main, and Windows searches PATH itself. The daemon's
git --version probe passes shell: false like its other git commands.
2026-11-25 18:39:14 +01:00
Mohamed Boudra 9f999bd570 test(plugins): classify the internal windows-command entry as server-only 2026-11-25 18:16:38 +01:00
Mohamed Boudra bf10ea8732 fix(plugins): keep a caller's windowsVerbatimArguments on a direct Windows launch
spawnProcess set the flag from its own invocation after the caller's options, so a plugin
that passed windowsVerbatimArguments: true with its own cmd.exe line got Node's quoting.
2026-11-25 18:14:39 +01:00
Mohamed Boudra a8528ad3d2 fix(plugins): start the cmd.exe a Windows caller names
A plugin that passed shell: "D:\Tools\cmd.exe" got the child's ComSpec instead. Only
shell: true and the builtin and script launches now use ComSpec.
2026-11-25 18:09:01 +01:00
Mohamed Boudra 2c661fb076 test(plugins): run the launch wrap reload case in server integration CI
agent-tools.e2e.test.ts is in no CI script, so the case that a plugin reload changing only the
wrap reopens the idle session never ran. The integration run now selects it by name.
2026-11-25 18:04:16 +01:00
Mohamed Boudra 531f6e549d refactor(plugins): share one qntm cmd.exe dialect between process launches and terminals
The SDK process functions and the daemon's terminals each had their own cmd.exe escaper, and
the SDK's quote-region tracker let a set variable such as %PATH% expand inside a quoted
argument to a .cmd or .bat launcher.

Both now build the line with windowsCommandLine and start cmd.exe /d /s /c "<line>" with
verbatim arguments. An argument without a cmd.exe metacharacter stays as given, so builtins
and %1 readers get it unchanged. Any other argument is quoted and caret-escaped the qntm way
(cross-spawn's escape.js), so cmd.exe never sees a quoted region and never expands %NAME%.
A batch script that reads an argument with a quote again gets it escaped twice.

A bare name is found on PATH with PATHEXT without changing the daemon's working directory:
a program starts directly, a .cmd or .bat shim goes through cmd.exe, and an unknown name
goes through cmd.exe as a builtin. A shell other than cmd.exe gets the arguments as given.
Terminals keep turning a prompt's line breaks into spaces; the SDK still refuses them.
2026-11-25 18:01:57 +01:00
Mohamed Boudra e32564f2bc fix(plugins): reopen a session when a plugin reload changes its launch wrap
A plugin refresh compared env, instructions, MCP servers and tools, not
the launch wrap. A reloaded sandbox plugin that changed its wrap left
live sessions running the old one, and a later plugin reused its
recorded output with the old wrap. The wrap now chains between plugins
like env, so it counts for reuse and for a stale launch.

The agent manager wrap tests now fake the plugin sessions runtime: a
refused wrap discards the open, and the running session keeps its tools.
2026-11-25 17:47:16 +01:00
Mohamed Boudra 0258d6752e fix(plugins): quote =, comma and semicolon for a Windows .cmd launch
A batch script splits its arguments at =, comma and semicolon outside
quotes, so a launcher that reads %~1 got --profile=restricted as two
arguments. Quote them for a script; %* forwarders still pass the
argument through unchanged.
2026-11-25 17:37:33 +01:00
Mohamed Boudra de5f139d33 test(plugins): exit the %~1 reader script with 0 on Windows
`set /p` without input exits with errorlevel 1, so execCommand reported the
reader script as failed even though it printed its arguments.
2026-11-25 17:37:33 +01:00
Mohamed Boudra 372c1ba949 fix(plugins): keep plain Windows arguments as given for cmd.exe builtins and %1 readers
Quoting and escaping every argument broke three existing Windows contracts
in server tests. `echo hello` printed `"hello"`, a build script that writes
`%1` wrote the quotes, and a port script that reads `%~1` got `^"` escapes
it cannot remove. A plain argument now stays as given. An argument with
whitespace, a quote, or no text sits inside real cmd.exe quotes, which
`%~1` and the program both remove. A .cmd or .bat target also quotes an
argument with cmd.exe syntax, because the script reads it again for `%*`.
Only text that literal quotes leave outside a quoted region is escaped.
2026-11-25 17:37:33 +01:00
Mohamed Boudra 4dc1730a62 fix(plugins): quote for cmd.exe only when cmd.exe parses a Windows launch
A Windows caller that named its own shell, such as Git Bash, got cmd.exe
escapes in its arguments and a line-break refusal that only cmd.exe needs.
Bash then printed `^"hello^"` for `hello`. A shell the caller names now gets
the command and arguments as given, as it already does on Linux and macOS.
2026-11-25 17:37:33 +01:00
Mohamed Boudra 2581f2af45 fix(plugins): refuse a line break in a Windows cmd.exe launch argument
cmd.exe ends a command at a line break whatever the quoting, so a
multiline argument to a .cmd launch wrap or a bare command name was cut
short, and the text after the break ran as a second command. The SDK now
refuses such an argument before cmd.exe starts. A streamed worktree setup
or teardown command that cannot start now fails as a command, with its
error in stderr, instead of rejecting outside the setup error.
2026-11-25 17:37:33 +01:00
Mohamed Boudra 6973c48d7e test(plugins): check ACP interrupts and skill examples the same way on Windows
Windows ends an ACP child at once, so the overlapping-interrupt test no
longer times the POSIX SIGTERM grace period. It already checks that the
child is gone when both interrupts finish. The skill examples test reads
SKILL.md with the CRLF line endings of a Windows checkout.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 9dd0cbc146 fix(plugins): deliver arguments to Windows commands and .cmd launch wraps unchanged
On real Windows, cmd.exe changed arguments that the SDK passed through it.
`a & b` arrived as `a ^& b`, `"quoted"` lost its quotes, and `%PATH%`
expanded. A .cmd launcher in `C:\Program Files (x86)` could not start,
because its path gained `^(x86^)`. Each argument is now quoted for the
program and every cmd.exe metacharacter is escaped, twice for a .cmd or
.bat file that forwards its arguments with `%*`. The executable path keeps
plain quotes.
2026-11-25 17:37:32 +01:00
Mohamed Boudra f088fa5049 test(plugins): run the plugin SDK and .cmd launch wraps on real Windows
The plugin SDK tests ran only on Ubuntu, so cmd.exe never saw a launch wrap.
A Windows job now runs them, with real .cmd launcher tests for arguments
that cmd.exe reads as syntax. The terminal and worktree wrap test uses a .cmd
launcher in a directory with spaces and parentheses on Windows. The plugin
configuration e2e suite joins the integration run, which it was missing from.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 5dcd1e1e57 fix(opencode): resume a wrapped legacy child session on a server behind its wrap
A legacy OpenCode child session resumed on its parent's registered server, even
when the open selected a wrap, so it ran with the parent's isolation. A wrapped
resume now starts its own server behind the wrap, as v2 does.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 7ba54499d9 fix(opencode): start a wrapped v2 server with the open hook's environment
A wrapped OpenCode v2 session got a dedicated server behind its wrap, but the
server and its launcher started without the hook's env, so a launcher that
reads its profile from that env failed. The runtime now takes a dedicated
launch with both the wrap and the env, as the legacy server manager does.
Session shells still receive the env through the session environment.
2026-11-25 17:37:32 +01:00
Mohamed Boudra cbd5b7a73b fix(opencode): read an imported session behind the import's launch wrap
Importing an OpenCode session read it on the shared server before resuming it
behind the wrap, so a wrapped import with no shared server running started one
outside the wrap. The v2 runtime now looks up and resumes the session on one
wrapped connection, and the legacy runtime reads it on a dedicated server
behind the wrap.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 8e88ce3a56 fix(terminals): send the script ownership change that lands as a terminal snapshot finishes
A terminal subscription coalesces refreshes with a pending flag, but it cleared
the in-flight refresh in a later microtask. A script runtime registered in that
gap set the flag after the last check, so clients kept isScript: false for a
running script. The refresh now clears itself in the same step as its last
check. The extra await in the plugin terminal.create.before wrapper moved
script registration into that gap, which made the Windows integration test fail.
2026-11-25 17:37:32 +01:00
Mohamed Boudra fb59e58ef1 feat(plugins): every built-in provider starts its harness behind a launch wrap
Claude, ACP and custom ACP providers, Pi, OMP, and OpenCode now honor an
agent.open.before wrap alongside Codex and plugin providers, so
supportsLaunchWrap is true for every provider that starts a local harness.

- spawnProcess({ wrap }) in the plugin SDK and applyLaunchWrap in the server
  own the wrapped argv; pty terminals, MCP stdio servers, and worktree
  commands share applyLaunchWrap.
- The wrap also covers stdio MCP servers Paseo hosts for the session and
  terminals an ACP agent asks Paseo to run.
- A wrapped OpenCode session starts a dedicated server behind its wrap (legacy
  and v2 runtimes); an explicitly configured external server fails the open.
- Docs cover provider coverage, what the wrap covers, and the temp directory
  a launcher must keep visible.
- The workspace script ownership e2e test asserts on the started terminal id.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 825fa04467 test(terminals): give script ownership the same 10s wait as the rest of the test
The first wait used the 1s default. On a slow Windows runner the observed
terminal list reports script ownership later than that. The assertion now
prints the observed terminals when it fails.
2026-11-25 17:37:32 +01:00
Mohamed Boudra 8338e77f46 fix(plugins): keep empty launcher arguments on Windows and stop lifecycle hooks at the deadline
A `.cmd` or `.bat` launch dropped an empty argument because cmd.exe saw only
whitespace; it is now quoted as `""` and keeps its position.

Teardown waited for a pending command.run.before hook past its deadline and
then started the command. Hook preparation now races the teardown deadline
and setup's cancel signal, and an aborted preparation never starts the
command.
2026-11-25 17:37:32 +01:00
Mohamed Boudra e5d81304f7 docs(plugins): say where a wrapped harness starts and how to pass the agent's directory 2026-11-25 17:37:32 +01:00
6b0fbfc640 refactor(plugins): one launch wrap for agents, terminals, and worktree commands
terminal.create.before and command.run.before now change only env and a
launch wrap, the same PluginLaunchWrap agent.open.before returns. Paseo
starts the terminal as [...wrap, command, ...args] (the default shell
when there is no command) and a setup or teardown command's shell as
[...wrap, shell, ...shellArgs]. The first hook's wrap wins; a different
one fails the operation. command, args, and the command text are
read-only, so a plugin cannot rewrite what runs.

The terminal wrap is applied in the daemon before the worker, so the
terminal worker protocol is unchanged. resolveDefaultTerminalShell moves
to its own module so the daemon does not load node-pty.

Co-authored-by: CL Kao <clkao@datarecce.io>
Co-authored-by: Josh Bendavid <Josh.Bendavid@cern.ch>
2026-11-25 17:37:32 +01:00
Josh Bendavid b4e4803df2 feat(plugins): hooks for terminal creation and worktree commands, with the workspace id
Applied from getpaseo/paseo#8691 (head 416d70614) onto main.
2026-11-25 17:37:32 +01:00
CL KaoandClaude Opus 5.5 3153f6f94a test(plugins): pin launch-wrap tests to the registration and to spawn attempts
- The Antigravity wrapped-launch test builds its launch from the provider
  registration's own command, as the daemon does, and asserts the exact
  argv, so dropping --disable-telemetry from the registration fails it.
- The ACP missing-launcher test counts every spawn attempt through Node's
  child_process diagnostics channel, so a second attempt with the missing
  launcher or a bare retry fails it.
- Drop the daemon-access sentence from the launch wrap limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:37:32 +01:00
CL KaoandClaude Opus 5.5 ecf8c812cd fix(plugins): keep the wrap prepend internal and test Windows launchers through a seam
- Inline the wrap prepend in the ACP shim and Codex instead of exporting
  applyLaunchWrap from @getpaseo/plugin/server; the author surface and
  boundaries.test.ts stay as upstream.
- spawnProcess and execCommand now share resolveSpawnInvocation, which
  takes the platform. A unit test proves a Windows script wrapper runs
  through cmd.exe with each argument quoted whole, without mocking
  child_process or patching process.platform.
- A wrapped Codex refresh whose provider command is a Windows script
  spawns through the production spawnProcess, with the provider command
  passed to the wrapper as an argument.
- The wrap fixtures in the ACP and Antigravity tests run as Node through
  process.execPath, so they also run on Windows.
- The provider protocol rejects an empty wrap executable.
- The provider registry and plugin clients set supportsLaunchWrap where
  they build the client.
- Docs name the launch wrap in the hook summaries and point provider
  authors at ProviderRegistration.launchWrap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:37:32 +01:00
CL KaoandClaude Opus 5.5 ab4bd6d59d fix(plugins): start Windows script launch wraps through cmd.exe
applyLaunchWrap rejected a Windows .cmd or .bat file on either side of the
wrap, and it did so at spawn time, after a refresh had already closed the
running session. Both wrapped paths spawn through spawnProcess, which runs a
command-script launcher through cmd.exe with each argument quoted, and the
provider command is only an argument to the wrapper. Drop the rejection from
applyLaunchWrap and from the manager's admission check.

Document the wrap in the public hook reference (with
its zh-CN translation), state the Windows launcher rule where the wrap
contract lives, and name wrap in the open-hook diagnostic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:37:22 +01:00
CL KaoandClaude Opus 5.5 2547edefcc feat(plugins): let an open hook wrap the provider's launch command
An agent.open.before result can carry `wrap: [executable, ...args]`. A
supporting provider starts that session's harness as
`[...wrap, command, ...args]`, one direct argv exec with the final hook env.
This lets one sandbox plugin confine every provider that supports wrapping,
instead of one wrapper provider per real provider.

Support is a static provider property, published as optional `launchWrap` on
the provider snapshot entry so an agent.create.before hook can read it with
paseo.providers.snapshot(). Codex and providers that extend it declare it in
the provider contract; plugin providers declare
ProviderRegistration.launchWrap, which runAcpProvider sets for a command.
The declaration travels in the registration metadata, so a provider reports
it before its first connection.

The open fails closed:
- buildLaunchContext rejects a wrapped open with LaunchWrapUnsupportedError
  (code launch_wrap_unsupported) before anything starts when the provider
  does not declare support, when a plugin connection lacks
  session.launch_wrap, or for a Windows command-script wrapper;
- a later hook may omit or repeat the wrap, a different one fails the open;
- the wrap executable must be absolute;
- a missing launcher fails the spawn and is never retried bare;
- a host without this change rejects the unknown `wrap` key.

The wrap is launch-only: history opens keep it, plugin session reopens
reuse it, and it is never stored on the agent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:37:12 +01:00
5c82a2e999 Keep a reloaded plugin's agent tools working for a busy agent (#10106)
* fix(server): keep a restarted plugin's agent tools on live sessions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(app): keep Escape owned by select mode during worktree checks
2026-11-25 22:11:10 +07:00
Mohamed Boudra 307f65d8f7 Stabilize website scene and keyboard language checks (#10808)
* fix(website): stabilize scene and keyboard language checks

Drive scene frames explicitly so sparse browser paints do not consume the test deadline. Let the landing page commit a locale change while its optional plugin count loads.

* test(website): advance the plugin panel crossfade before asserting removal

* test(website): settle native animations during the plugin panel swap

Playwright advances JavaScript frames, while the browser keeps a separate timeline for native animations. Finish the mockup’s finite native animations at the panel checkpoint so either animation path removes the outgoing panel.
2026-11-25 21:06:43 +07:00
Mohamed Boudra 163162e9f3 Teach the current plugin API in the bundled paseo-plugin skill (#10793)
* docs(skills): teach the current plugin API in the paseo-plugin skill

The skill still taught server.on and server.before, a deprecated panel
context, and an older publishing rule. It linked to hook anchors that
moved to the hooks page, and it had no entry for half of the shipped
contributions. Its RPC example imported a contract that the shared file
did not export.

The skill now indexes every public registration and links to the
reference section that owns its contract. It keeps a few complete
examples. Every ts and tsx block in the skill names its file, and the
blocks under each heading must typecheck as one plugin against the SDK,
so an example cannot drift from the API without a failing test.

* docs(skills): match the plugin skill RPC example to the scaffold and run its tests in CI

The RPC example used names that the generated client entry does not import, and it had no client entry. A PR that changed only the skill also skipped the SDK tests that typecheck its examples.

* docs(skills): keep the generated client entry in the plugin skill RPC example

Replacing index.client.tsx with a screen-only entry removed the scaffold's
Greeting sidebar item, which is the only control that opens the screen.

* docs(skills): say that npm plugins declare build for generated files

Paseo installs npm plugins with lifecycle scripts disabled, so a postinstall
step never runs.
2026-11-25 21:04:18 +07:00
Mohamed Boudra 4a6b8ae080 fix(app): keep the sidebar toggle clear of plugin screen titles (#10773)
With the left sidebar collapsed, every content header renders
SidebarMenuToggle in its leading slot. On macOS it is a blank space
under the toggle the window draws beside the traffic lights; on
Windows and Linux it is the toggle itself. The plugin screen header
built its own left side without it, so on macOS the floating toggle
sat on top of the title, and on Windows and Linux the screen had no
toggle to reopen the sidebar.
2026-11-25 20:59:43 +07:00
paseo-bot[bot] 465db78ab6 fix(opencode): clear deleted subagents from the track (#8332)
* fix(opencode): clear deleted subagents from the track

Handle provider deletion events before fetching the missing session, and reconcile removals after complete parent listings so reconnects also clear stale rows. Keep descendant cleanup scoped to the deleted child.

* fix(opencode): retain live subagents skipped during reconnect

* fix(opencode): reconcile skipped subagent descendants

* fix(opencode): restore live subagents after reconnect

A deleted child rejects environment restoration before reconnect can clean up its row. Let the child tracker remove confirmed deletions and continue restoring live descendants.

* fix(opencode): clear deleted subagents after reconnect

Let the OpenCode SDK decode missing-session responses in both runtimes. The child tracker can then remove the stale row and restore the live children when it reconnects.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 13:49:39 +00:00
Mohamed Boudra 30a155127d Redesign agent profiles settings, inspector drawer, and 1-tap composer creation (#10789)
* feat(app): redesign agent profiles settings, inspector drawer, and 1-tap composer creation

Promote Host -> Agent profiles to its own settings section with a searchable 3-column roster and slide-over inspector drawer, eliminate async layout jump when provider options load, and make composer model picker '+' save, select, and toast with Edit and Undo.

- Seed cached host provider catalogs synchronously and retain same-provider controls while refetching so the form no longer collapses and jumps when switching models or modes.
- Keep form session state above drawer/modal framing so resizing across breakpoints preserves unsaved edits, and render the drawer as a right-edge overlay below 1320px pane width so opening a profile never crushes or reflows table rows.
- Reuse Paseo's SearchField, CombinedModelSelector, SettingsCard, SettingsSwitch, SettingsCollapsibleRow, SegmentedControl, ToolbarButton, DismissBackdrop, WindowChromeRegion, and ToastHost across all surfaces.

* fix(app): preserve remounted drafts, guard duplicate, and serialize profile writes

Seed profile FormTextInput fields from the live session draft so drawer-to-modal resizes and collapsible toggles display the values Save will write. Share one confirmDiscardIfDirty guard between editor transitions and Duplicate. Serialize host profile mutations through a per-host queue in useAgentProfiles so overlapping composer quick-creates and Undo compose against the latest stored list.

* fix(app): keep profile editor across compact settings and Remove cancel

Unify compact and desktop Settings detail pane wrappers into SettingsDetailPane so resizing across the 600px compact breakpoint never unmounts HostAgentProfilesPage or drops an active edit session. Remove the premature onClose() call from AgentProfileEditModal's Remove handler so the caller closes the modal only after confirmation and deletion succeed.

* fix(app): allow roster search with docked drawer and guard Settings exits

Pass manageFocus: overlay to useOverlayRegistration in AgentProfileDrawer so slide-over overlays trap focus while docked drawers keep Escape handling and allow typing in roster search. Add a before-leave guard hook in SettingsScreen wired to AgentProfilesPage's confirmDiscardIfDirty so sidebar section switches, host switches, and back navigation prompt before discarding an unsaved profile draft.

* fix(app): guard browser Back and route removal on unsaved profile draft

Add navigation/route-leave-guard so web popstate events are intercepted before Expo Router's createMemoryHistory resets the root navigator, plus beforeRemove handling for native swipe-back and hardware Back. Canceling restores the history entry and keeps both route and draft; confirming replays the exit cleanly.

* fix(app): preserve intervening history on canceled multi-step Back jumps

Track ordered Expo Router history entry IDs in route-leave-guard instead of restoring via pushState. Canceling any Back/Forward traversal now reverts via history.go(delta) without truncating intervening or forward entries, and confirming replays popstate at the browser's exact selected destination.

* fix(app): restore Back-jump URL after reload and compute dirty from resolved defaults

Persist the tab's ordered history entry IDs in sessionStorage and verify the target entry ID when reverting a canceled popstate traversal, so canceling a multi-step Back jump after a page reload always restores the exact editor URL. Move isDirty into profile-form-model against the resolved initial baseline after catalog defaults hydrate so opening an untouched provider-and-model-only profile closes without a discard prompt.

* fix(app): dismiss profile-saved toast when its composer unmounts

Scope the composer's profile-saved toast to the lifetime of useAgentProfileEditor so closing an agent tab dismisses the toast instead of leaving a dead Edit action.

* fix(app): scope save completion close to the editor session that started it

Skip onSaved when useAgentProfileFormSession has unmounted mid-save, and guard handleSavedClose and composer handleSave by session key/request identity so switching to another profile during a slow save never closes the next profile's draft.

* fix(app): unify delayed editor transitions behind a session token

Track a monotonic editor session token in AgentProfilesPage and route delayed open/close transitions (Save completion, Duplicate completion, and async discard confirmation) through applyDelayedEditTarget so a slow Duplicate updates the roster without replacing a newer profile draft.

* fix(app): track draft revision so post-confirm edits veto delayed Duplicate

Add draftRevision to AgentProfileFormState and read isDirty/draftRevision directly from the live form model instead of mirroring a boolean ref. Approve discard for a specific (sessionToken, draftRevision) pair so any edit made after confirming Duplicate advances draftRevision and keeps the newer draft open when the host responds.

* Scope discard approval to each action so failed duplicates stay dirty

* Report agent profile write failures with toast across web and native

* Use usePreventRemove for Settings dirty-draft guard so native stacks block swipe dismiss

* Keep Settings sidebar scroll anchoring intact across font-size reflows
2026-11-25 20:48:38 +07:00
e108fdc792 fix(app): keep the turn footer on plugin-transformed assistant replies (#10795)
* fix(app): preserve turn footer on plugin-transformed assistant replies

Retain sourceMessageId and sourceText when timeline projection replaces an
assistant_message with plugin items, and recognize projected assistant replies
across turn timing, footer layout, fork boundary resolution, and turn copy
(deduplicating split cards by sourceId).

No plugin SDK changes.

Closes #10438

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

* refactor(app): keep the replaced row on plugin timeline cards

Projected plugin rows copied fields from the row they replaced one at a
time (sourceId, sourceKind, sourceMessageId, sourceText), and each copy
missed a footer input: turn stats from #10496 were still dropped for a
transformed reply. Projection now keeps the replaced row as `source`,
and `getAssistantReply` reads the reply through it for turn folding,
timing, copy, fork, and turn stats.

Refs #10438

Co-authored-by: Brandon Elliott <brandon.elliott@vercel.com>

* docs(plugins): note that a replaced reply keeps its turn footer

Refs #10438

* test(app): check the turn duration under a plugin-transformed reply

Refs #10438

---------

Co-authored-by: Brandon Elliott <brandon.elliott@vercel.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-25 20:07:08 +07:00
Mohamed Boudra 732b936fb6 fix(codex): keep configured developer instructions when Paseo adds instructions (#10792)
Codex uses a thread's developerInstructions in place of the
developer_instructions in its config. Paseo now reads the configured
value through config/read and sends it ahead of the agent, daemon, and
plugin instructions on thread/start, thread/resume, and rewind forks.

Closes #10644
2026-11-25 20:00:15 +07:00
Mohamed Boudra 5c97cd5903 chore(ci): move dependency signature audit to release preparation (#10800)
Keep lockfile lint in CI. Review the lockfile diff and audit dependency signatures on the release commit before shipping beta or stable releases.
2026-11-25 13:23:22 +01:00
paseo-bot[bot] 019f87804e test(server): stabilize the busy-loop image decode check (#10762)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 12:09:20 +00:00
Mohamed Boudra 7d425b2efe Mark desktop, web, and mobile in the homepage plugins subtitle (#10799)
Each client the subtitle names has its own color and an icon. The locale
strings tag the three names so each translation places them.
2026-11-25 18:59:47 +07:00
Mohamed Boudra 206229235f fix(hub): let Hub sessions list provider controls (#10794) 2026-11-25 18:36:42 +07:00
Mohamed Boudra 95a755e620 Say that homepage plugins install once and run on every client (#10797)
The plugins subtitle now names the server install and the desktop, web,
and native mobile clients. English and Simplified Chinese.
2026-11-25 18:33:01 +07:00
Mohamed Boudra c1b43ee571 Keep Git watchers responsive during large directory scans (#10788)
* fix(server): avoid event-loop stalls and timeouts during Git watcher scans

Compile file-observer and Git ignore root lists into ancestor-Set matchers so directory scans check direct children in O(1) instead of scanning all ignored roots per entry. Add cooperative time-sliced yielding and mid-directory abort/ignore checks to NativeRecursiveBackend and LinuxBackend directory scans, and enforce the monotonic watcher subscription deadline after Promise.race so late microtask resolutions cannot bypass timeouts.

* fix(server): attach Linux directory watches before scanning entries

Attach the inotify watcher for each newly discovered directory before calling readdir() in LinuxBackend.scan(), so writes that land during readdir() or mid-directory scan yields are captured live rather than missed between the snapshot and post-scan watch attachment.

* fix(server): track Linux directory watch inode identity across replacements

Store each Linux directory watcher with its (dev, ino) identity so watch attachment and scan reconciliation detect when a directory at a watched path is moved aside and replaced. Close stale watchers, rebind to the replacement inode, and re-verify identity after attach, readdir, and scan yields.
2026-11-25 17:48:24 +07:00
Mohamed BoudraandMarcel W. Wysocki b4af7599d5 perf(app): keep overlays and long-running sessions fast (#10778)
A dev window open for a few hours took twice as long to open the sidebar
hover card as a fresh one. Three dependencies produced the cost:

- Unistyles 3.2.4 web rewrote the whole stylesheet on every class add or
  remove. Backport upstream PR jpudysz/react-native-unistyles#1354 (3.8.0):
  classes become CSSOM rule inserts and deletes.
- @gorhom/portal kept all portal state in one context value at the app
  root, so each portal change made React search every mounted fiber. Portal
  state now lives in a store each PortalHost subscribes to. Also backport
  gorhom/react-native-portal#62 so closing one overlay no longer remounts
  later overlays in the same host.
- React 19.2 development builds never cleared their render timings.
  Backport the React 19.3.0 clearMeasures change.

The shared stylesheet e2e helper counts rules inserted, deleted and edited
for the whole interaction, so transient and in-place changes fail the
explorer resize spec.

Supersedes #10605.

Co-authored-by: Marcel W. Wysocki <maci.stgn@gmail.com>
2026-11-25 17:39:10 +07:00
Mohamed Boudra eaadacadb4 fix(app): return the previous pane to its last active tab when splitting or moving (#10716)
Detaching a pane's active tab via splitPane or moveTabToPane previously dropped focusedTabId and fell back to the rightmost remaining tab in the strip, so dragging a file tab out after coming from tab A left the previous pane on tab B instead of putting A and the file side by side.

Track per-pane tab focus recency in memory and route both close and relocate focus transitions through one explicit policy table. Closing a tab keeps its existing parent-then-neighbor order, while splitting or moving a focused tab out of a pane returns the source pane to its most recently focused remaining tab (falling back to a same-pane parent tab and then an adjacent neighbor). Keeping the focus history in memory avoids adding a new key to the strict persisted layout schema.
2026-11-25 17:31:58 +07:00
Arnold HueteandMohamed Boudra b6375b1426 Set Archive on finish from the CLI and MCP (#8479)
Schedules created through the CLI or MCP archived every run's workspace and agent, and only the app's switch could change that. Add --archive-on-finish and --no-archive-on-finish to paseo schedule create and update, and archiveOnFinish to create_schedule and update_schedule. Omitting the option stores nothing, so the default stays on.

A repeated named create_schedule that changes only Archive on finish refreshes the existing schedule instead of creating a duplicate, and keeps the saved value when the request omits it.

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 17:06:48 +07:00
bbe7e2a7fc Keep slow Import Session results and show provider errors (#10516)
* fix: bound import listing and clean up ACP probes

* fix(server): keep the full Import Session deadline

Start ACP probe cleanup when the agent manager stops waiting. Keep the 90-second window for listings that still have time to finish.

Co-authored-by: Chirag Singhal <76880977+chirag127@users.noreply.github.com>

* fix: show import provider errors and retry progress

* fix(server): return Import Session results before probe cleanup finishes

A timely ACP listing was discarded when process shutdown crossed the listing deadline. Return the completed rows and let the adapter finish reclaiming the probe.

* fix(server): preserve timely ACP listing errors during cleanup

A provider error returned within the listing window can still be displayed while its probe shuts down.

* fix(server): preserve timely ACP initialization errors during listing

* test(server): give Worktrunk integration fixtures time to finish

* fix(app): scope Import Session results to the selected host

Co-authored-by: derek <174018435+derek-geekdive@users.noreply.github.com>

* Keep pending session imports tied to their original host

* fix(server): reclaim ACP listing providers after launcher exit

---------

Co-authored-by: Chirag Singhal <76880977+chirag127@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: derek <174018435+derek-geekdive@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 10:03:51 +00:00
Mohamed BoudraandSammy Patenotte d94148a2a8 Let plugins nest dispatched workspaces under the workspace that created them (#10781)
Workspace snapshots now carry parentWorkspace, the ref of the workspace whose agent created this one on the same host, null when the host records no parent. Based on #10330 by Sammy Patenotte.

Co-authored-by: Sammy Patenotte <sammy.patenotte@yahoo.com>
2026-11-25 16:58:02 +07:00
Mohamed BoudraandDhruv Singal 831f2472f3 fix(providers): upgrade Factory Droid to 1.20.0 (#10779)
The catalog launched Factory Droid with `npx -y droid@0.249.0`, which
predates the models Factory added since, including Droid's current
default `gpt-6.2-sol`. Bump the pin to 1.20.0, the version the ACP
registry now publishes for Factory Droid. The registry still distributes
Droid as a pinned npx package with auto-update disabled, so the entry
keeps that shape and stays covered by `npm run acp:version-drift`.

Co-authored-by: Dhruv Singal <170742396+dsingal0@users.noreply.github.com>
2026-11-25 16:45:08 +07:00
Mohamed Boudra 8df6672de1 Add projects from one sheet with Existing, Clone, and New folder tabs (#10767)
* feat(app): add projects from one sheet with Existing, Clone, and New folder tabs

Add project used to start on a method list, so every use cost a step before
typing. The sheet now opens on Existing with the search focused, and Clone and
New folder sit one tab (or Mod+2/3) away, each keeping its own draft. A host
pill appears only when more than one host is online.

Rows are select-then-confirm: a tap or arrow key picks a row and the primary
button (or Enter) commits it, so a scroll-tap on touch never clones or opens
by accident.

The sheet owns its keys through AdaptiveModalSheet's new `keyboard` prop
rather than a child overlay registration, because a child at the same layer
loses to the sheet. Enter leaves a focused button alone (Close, a tab, Add
host) so keyboard users can still activate it.

Inputs focus on open only when a hardware keyboard is present; on a phone the
focus popped the keyboard and the bottom sheet jumped between snap heights on
every tab switch.

Searches keep the previous results while the next request is pending, so the
list no longer flashes to a loading state on each keystroke.

* fix(app): keep Add project results, selection, and submissions tied to their host

Searches now answer only for the host and query they were sent for. With
keepPreviousData, switching host showed the previous host's folders as
settled results, and Open project sent one host's path to the other. A
failed request no longer leaves a spinner, an old query's error no longer
shows while the next one loads, and directory search errors from the host
are shown instead of "No matching folders".

The picked row is stored by id instead of position, so a search refresh
cannot move the selection to a different folder or repository. Focusing a
row picks it, so Enter on a focused row adds that row.

A submission belongs to the open sheet and its host. Closing the sheet or
losing the host abandons it, so a late result neither navigates away from
where the user went nor blocks the next submission.

New folder and Clone default to a parent known to exist (last used, a
recent project's parent, or home) instead of ~/dev, and the Clone preview
drops a trailing .git like the host does. Tabs and rows are locked while a
submission runs, and tabs whose host lacks the capability are read-only.

* fix(app): don't open a stale Add project row, keep drive roots in Location

Enter while a new search is pending no longer opens a row from the
previous search; typed paths and URLs stay usable. Location derived from
a project at a drive or filesystem root keeps the root separator (C:\\, /).

* fix(app): keep Location on a pending search, reject drive-letter folder names

Enter in the Location picker no longer confirms a folder from the
previous search while the new one runs; a typed path still confirms.
Combobox gains remoteSearchPending for this. New folder flags names
like "C:repo" inline, matching the host's rule.

* fix(app): don't swap a dropped Add project pick for the first row

The first row is the default only while the user has not picked one.
When a new answer drops the picked row, nothing is active and the
primary action stays disabled until the user picks again.

* fix(app): keep Add project on the chosen host when it disconnects

The sheet no longer moves the draft to another online host when the
chosen one drops. It stays on that host, shows "<host> is offline", and
blocks submit until the host returns or the user picks another one.

* fix(app): block the native Go key while the Add project host is offline

Each tab's view is gated once, so the footer button, Enter and the
text field's submit key all read the same unavailable submit.

* fix(app): disable Browse while the Add project host is offline

* fix(app): don't default Add project Location to a share's server name

A project at a Windows share root (\\\\server\\share) has no parent folder,
so the default Location falls back to the next project or ~.
2026-11-25 16:28:33 +07:00
Mohamed Boudra feb7882e5c Find agent profiles by searching models, and in the Command Center (#10774)
* feat(app): find agent profiles by searching models and the Command Center

Typing in the model picker used to hide profiles, so a profile could only
be reached by clearing the search. Search now lists matching profiles
above matching models, matched on the profile name and its summary, so
searching a model also finds the profiles built on it.

The Command Center offers the same profiles as "Profile › <name>",
applied through the picker's applyProfile. Profiles are never shown as
selected: applying one writes its values and nothing stays bound to it.

* fix(app): keep profile search results scrollable and profile ids unique

A provider search that matched only profiles rendered them outside the
model list, which owns scrolling in the popover, so matches below the fold
could not be reached. They now go through the list with no model rows.

The daemon stores the profile list as given, so a hand-edited config can
repeat an id. The Command Center registry rejects duplicate ids and threw
while the composer mounted. The picker now keeps the first profile per id,
which is the one applyProfile already resolved.
2026-11-25 16:01:20 +07:00
paseo-bot[bot] cd2e56f1fa Keep Git watcher retries on schedule after reconnect (#10602)
* fix(server): keep watcher retries on schedule after reconnect

A watcher that timed out lost its pending delay when its last observer disconnected. Keep the retry with the watched path so registering the same workspace again uses polling until the scheduled scan.

* fix(server): preserve the scheduled watcher retry deadline

The ordinary recovery delay can exceed the setup-timeout delay when a watcher reports an error before timing out. Retain the scheduled deadline so reopening waits the full interval.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 07:37:02 +00:00
1ff119dc2a feat(app): copy a quote's body with one tap (#10608)
Agents often write drafts as quotes meant to be pasted elsewhere. A plain
quote now has a copy control on web, desktop, Android and iOS. It copies
the quote's body without the `>` markers and with its nested Markdown. A
nested quote, a code block or a Mermaid diagram inside it keeps its own
control. Admonitions get no control.

Web reads the rendered quote at press time, so a streaming quote copies
what it shows, and writes the same two clipboard flavors as selection
copy. A rendered Mermaid diagram copies as the fence it shows, and an
admonition inside a copied quote copies as its `> [!TYPE]` source. Code
blocks and quotes share one copy button with a Copied state and an error
toast when the clipboard refuses the write. On compact layouts the
control is always visible in a band above the quote body. On wide
layouts it shows on hover or focus and the quote keeps a right gutter.

Native code blocks and quotes share one header copy control with the
Lucide Copy glyph. A quote reserves the code block's header band above
its body, so the control never covers text at any font size. Native copy
emits the quote body as written, and a copied fence grows longer than
any fence inside its code.

Supersedes #9429 and #9319. Refs discussion #9303.

Co-authored-by: Pedro Vieira <pedro.vieira@dremio.com>
Co-authored-by: Phieu Dinh <phieu@fiu.one>
2026-11-25 13:36:01 +07:00
Mohamed Boudra 6e6f224e44 Hub login prints a one-click URL, and an uninstalled Muse Code shows as unavailable (#10751)
* fix(cli): print the one-click Hub login URL

`paseo hub login` opened verificationUriComplete in a browser but printed
the bare verificationUri. Over SSH or on a remote host the browser launch
does nothing, so users had to open the bare page and type the code by hand.
Print the URL that carries ?code= and keep the code next to it so the user
can check it matches the Hub approval page.

* fix(providers): report uninstalled plugin providers as unavailable

A fresh host with only Claude Code installed listed Muse Code as an
error ("muse not found on PATH"). The snapshot manager resolves a
provider's catalogue key before it checks availability, and treats any
failure there as an error. For a plugin provider with a command, the key
lookup required a resolved executable and threw when it was missing.

A command that does not resolve has no catalogue identity. Fall back to
the target key so the availability check runs and reports unavailable.

* fix(providers): keep a removed plugin executable off its cached catalogue

The previous fix returned no catalogue key for a missing executable. A
plugin that returns no key asks for a per-workspace catalogue, so after
its executable was removed the next read bound to the catalogue cached
while it was installed and kept reporting ready.

Give a missing executable its own key. Removal now moves the provider to
a fresh catalogue, and its refresh reports unavailable.
2026-11-25 13:30:37 +07:00
Mohamed Boudra 395a5a5f80 Run OpenCode v2 agents with their own MCP servers and env on a shared OpenCode server (#10752)
* refactor(server): share the MCP client connection that providers host

OMP connected MCP servers itself; OpenCode v2 now needs the same client to
host per-session servers. The shared connection also ends Streamable HTTP
sessions explicitly on close, because a stateful server keeps them otherwise.

* fix(opencode): run agent MCP servers and env on shared v2 servers

Agents with MCP servers or a launch environment failed on any OpenCode v2
server Paseo did not start, with "require an isolated server". OpenCode's MCP
configuration is shared by every session in a location, so Paseo answered by
starting a dedicated server, which a reused server cannot do.

Paseo now hosts each session's MCP servers itself and the v2 plugin exposes
their tools only to that session and its descendants, under OpenCode's
`<server>_<tool>` names. The plugin runs OpenCode's permission check before
each call, so preapproved grants still apply; that API exists from OpenCode
2.0.29, and older servers or stale plugins fail at session creation. Launch
env reaches shells through session.environment, which children do not
inherit, so the plugin asks Paseo to adopt each child before its first model
request. No agent gets a dedicated server any more, including on Paseo's own
helper.

A registered service is skipped when the provider env configures the OpenCode
process, so a service.json no longer breaks catalogs and launches for those
setups. An explicit server URL still reports those variables.

Fixes #9669

* fix(opencode): keep user tools, child instructions, and MCP call cleanup on shared servers

- A Paseo MCP tool replaced a same-named tool from the user's own OpenCode
  configuration, and the context hook then removed it from unrelated sessions.
  The plugin now captures that tool when it registers, keeps it for sessions
  without their own Paseo tool, and runs it for them.
- MCP instructions were an instruction entry written when a child was adopted.
  OpenCode loads entries before the context hook runs, so the child's first
  request missed them. The context hook now adds them to every request.
- Structured-only MCP results reached OpenCode with empty content. The bridge
  now adds them as text, as it already does for Paseo tools.
- The bridge listened for the request's `aborted` event, which never fires
  once the body is read, so Stop left the MCP call running. It now aborts when
  the response closes before it finishes.
- Closing an HTTP MCP connection waited on a session DELETE with no deadline.
  It now waits at most two seconds before closing the transport, which aborts
  the DELETE.

* test(server): run daemon OpenCode tests with the bridge the daemon always starts

These tests built the OpenCode v2 client without a bridge, so the client
reported no native Paseo tools and the daemon injected its internal MCP
server instead. OpenCode v2 now hosts agent MCP servers through the bridge
and rejects them without one. The daemon always starts the bridge, so the
tests now do too.

* fix(server): reconnect expired MCP sessions and bound the MCP handshake

- The OpenCode plugin copied a same-named user tool's input schema into the
  shared registration. OpenCode validates arguments against the registration,
  so the agent's own calls failed the user's schema. The registration keeps a
  permissive schema, and the context hook gives each session its own.
- A stateful HTTP MCP server answers 404 after it restarts or expires a
  session, and the SDK kept sending the old session ID. A call that gets 404
  now opens a new session once and retries.
- The SDK times out only the `initialize` request, so a server that never
  answered the `initialized` notification stalled agent creation. The whole
  handshake now has a 10-second deadline.
2026-11-25 13:30:13 +07:00
Mohamed Boudra 12bc84046c Keep iOS chat visible with tall pending cards (#10759)
* fix(app): reveal chat with tall pending cards

The initial scroll can settle inside the footer, where no rows need to be measured. Run the layout readiness check before allowing cached ranges to skip it.

* test(app): cover cached range during initial list placement

Exercise an observed end offset with measured rows in the buffer. Canceling the initial scroll must complete readiness even when the render range is already cached.
2026-11-25 13:24:09 +07:00
paseo-bot[bot]andluke 44d1d6ab29 fix(app): keep long desktop turns virtualized (#8661)
* fix(app): virtualize chat turns that exceed the mounted window

- Desktop web aligns the mounted tail to the current turn, so one long tool run stayed fully mounted and stalled the chat open.
- Cap that rewind at 60 rows for the web virtualizer. A larger minimum still wins, and history paging plus the replica cache still keep a whole turn.

* test(app): read expanded turns across the virtual window

Verify every command remains accessible while scrolling and after older history loads. Requiring all expanded rows in the DOM at once contradicts bounded desktop mounting.

Co-authored-by: luke <luopeihuan@gmail.com>

* Verify older history appears before rechecking turn expansion

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 05:55:20 +00:00
paseo-bot[bot]andOuyang Xingyuan cfcf0dc7d1 fix(server): keep slow direct connections alive during large transfers (#10651)
A direct client sees activity only after a complete WebSocket message arrives. Send large responses in existing transport chunks so the client sees progress while it waits for the full response.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>
2026-11-25 04:02:49 +00:00
Mohamed Boudra 0a856ab7fc Surface E2EE relay and privacy posture on homepage and security docs (#10749)
* docs(website): surface E2EE relay and privacy posture on homepage and security docs

Add a quiet trust strip below the homepage desktop hero mockup (EN and zh-CN) so Paseo's no-telemetry, E2EE relay, open-source, and independent posture is visible before the feature chapters.

Update the public security docs, privacy policy, and SECURITY.md to match the current Noise NK relay handshake, replay protection, daemon.relay.requireProtectedSecurity setting, and pairing-link / daemon-password trust model. Sync README.md, README.zh-CN.md, connectivity docs, and the homepage FAQ connectivity link.

* docs(security): clarify two-sided Noise fallback and Unix key permissions

* docs(security): note daemon restart after enabling requireProtectedSecurity
2026-11-25 09:58:26 +07:00
paseo-bot[bot]andMohamed Boudra ad20814ec8 Restore stopped Claude background subagents as canceled after reopening (#9013)
* fix(claude): restore stopped background subagents as canceled

Resolve task-only replay notifications through the parent launch identity so stopped children keep their recorded outcome after reopening. Preserve transcript order across task and tool notifications.

* test(claude): name replay notification fixture options

* fix(claude): restore all children in grouped task notifications

A session-end notification can contain several task IDs. Apply its outcome to each linked child during transcript replay so every stopped child restores as canceled.

* fix(claude): keep quoted notices from changing replayed child status

Claude marks delivered task notifications with an origin. Require that origin for user records and require a standalone notice for queue records so prompts that quote a notice do not override a recorded outcome.

* fix(claude): keep replay task links tied to subagent results

Ignore unrelated tool results when collecting task identities so echoed launch logs cannot overwrite the link used to restore a stopped child.

---------

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 08:30:08 +07:00
Maarten den BraberandMohamed Boudra 0688ae83fe fix(server): send Claude MCP servers over stdin to keep tokens out of argv (#10698)
* Keep MCP server headers off the Claude Code command line

The Claude Agent SDK defaults to sending MCP servers in one --mcp-config
flag, so the Paseo MCP server's bearer token (and any user MCP server
headers or env) was readable by every local account through ps or
/proc/<pid>/cmdline. Anyone who read it could call the daemon's agent MCP
endpoint.

Set mcpServersDelivery: "initialize" so the SDK sends the servers over
stdin in the initialize request. The SDK only supports that with the
Claude Code bundled with it (2.1.326) or newer, so an older Claude Code,
or a wrapper command that reports no version, keeps the command-line
delivery and the daemon logs a warning once.

A spawn test feeds Paseo's options to the real SDK and checks that the
token reaches stdin and not the launch arguments.

* fix(server): warn about MCP argv delivery only with configured servers

An empty session used the client's one-time warning before any MCP server headers would be passed to the provider. Warn on the first session that configures a server.

* fix(server): detect MCP delivery support on each provider launch

A running daemon kept selecting command-line delivery after the installed provider gained stdin support. Resolve the installed version when building SDK options for a launch with MCP servers.

* fix(server): probe MCP delivery support in the launch environment

Version-selecting wrappers can run a different binary in the workspace. Use the session working directory and environment when probing the configured command.

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 08:30:01 +07:00
paseo-bot[bot] 311728a780 test(plugins): give npm installation cases separate deadlines (#10726)
Install and reload, reviewed updates, and staging cleanup each run against a fresh service. Their npm subprocesses no longer draw from one test's deadline.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 00:23:46 +00:00
cf1a5a9e73 Stop idle plugin sessions from pinging the daemon (#9363)
* fix(server): stop liveness pings on plugin sessions

Every DaemonClient pings its daemon every 10 s to notice a silently dead socket. A plugin's
session runs over its IPC channel (or an in-process queue for built-in plugins), whose loss is
reported directly, and the daemon already exempts plugin sockets from the application lease those
pings renew. The pings only woke both processes: about 2 wakeups a second in an idle daemon with
nine plugins and the built-ins.

DaemonClient gets a livenessHeartbeat option (default on); the plugin host turns it off.
Explicit verification (ensureConnected({ verify: true })) still pings.

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

* fix(server): exit a plugin process when its daemon's channel closes

A plugin host only noticed that its daemon worker had died through the liveness ping: about 11 s
later the ping failed and the process exited with code 1. With the pings off it would not notice
at all and kept running as an orphan.

The plugin process now exits as soon as the IPC channel closes without the plugin closing it
itself. A normal shutdown still closes the channel from the plugin side and lets work in flight
(a provider connection that resolves late) finish.

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

---------

Co-authored-by: Brandon Elliott <923787+Brandon168@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 15:51:30 +00:00
Mohamed BoudraandTaras Kornichuk e06bfbb94c Redesign host picker with configurable auto-detected icons, connection type, and latency (#10702)
Supersedes #5787.

- Add best-effort daemon hardware detection (macOS ioreg/sysctl, Linux containers, WSL, device-tree boards, cloud/VM DMI, SMBIOS chassis) exposed as optional `machineKind` on `server_info` and `/api/status`.
- Add configurable per-host icons in Host Settings -> Appearance (`Auto` plus 9 icons across all 9 locales), keeping `icon` omitted while untouched for rollback compatibility and preserving unknown future icons on disk.
- Redesign `HostPicker` and `HostChooserModal` with resolved host icons, connection type (`Local`, `Tailscale`, `Relay`, `SSH`, `Direct`, `Via`) + endpoint, on-demand round-trip latency, aligned leading and content rails, and full keyboard navigation.
- Update the website host mockup to match.

Co-authored-by: Taras Kornichuk <dread9ko@gmail.com>
2026-11-24 21:52:39 +07:00
paseo-bot[bot] 7bcd598f09 test(terminal): speed up history setup for pressure recovery (#10683)
Windows timed out while the fixture printed 12,050 rows before signaling readiness. Batch the initial writes and keep the live burst and replay assertions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 12:01:34 +00:00
Mohamed Boudra c626bf3707 Skip worktree teardown commands for unapproved cross-repository checkouts (#10694)
* fix(server): skip teardown commands when archiving unapproved checkouts

`archiveByScope` previously treated `assertWorkspaceAutomationAllowed` as optional and did not skip `runWorktreeTeardownCommands` when `untrustedBacking` was already true or when archiving an unrecorded worktree directory. Four callers (`CreateAgentLifecycleDispatch`, `archiveIfSafe`, `paseo-tools` `archive_workspace`, and `handlePaseoWorktreeArchiveRequest`) also omitted `assertWorkspaceAutomationAllowed`, letting `paseo.json` teardown commands run during failed agent creation cleanup, first-turn auto-archive, auto-archive on merge, MCP workspace archive, and worktree archive RPCs.

Make `assertWorkspaceAutomationAllowed` and `isCheckoutUntrusted` required on `ArchiveDependencies`, skip teardown whenever the backing checkout is untrusted, any workspace on the checkout is blocked, or no active workspace record exists, and wire the guard through all archive callers.

* fix(server): scope archive teardown check to active checkout workspaces

`isCheckoutUntrusted` scans all workspace records by path, including previously archived records, so gating teardown on it suppressed `paseo.json` teardown for a fresh approved worktree that reused a previously archived unapproved slug path.

Keep teardown approval scoped to the active workspaces sharing the backing checkout at archive start (the records being archived plus active siblings), drop the null-workspace fallback target for unrecorded worktree-scope archives so they never run teardown or flip `untrustedBacking`, and verify caller wiring reaches `assertWorkspaceAutomationAllowed` directly.

* fix(server): inherit untrustedSource when unarchiving onto an active unapproved checkout

Unarchiving a previously approved workspace onto an existing directory that currently holds an active unapproved checkout left the restored workspace without `untrustedSource`. If the unapproved sibling was archived first, the directory remained on disk and archiving the restored workspace could run teardown commands.

Inherit `untrustedSource` from active workspaces sharing the checkout root in `ensureWorkspaceRecordUnarchived`, while ignoring already-archived historical records so restoring an approved checkout onto a reused path stays approved.

* fix(server): bind automation approval state to checkout worktree metadata

Keeping `untrustedSource` only on workspace records meant a retained unapproved worktree directory could lose its teardown block if its last unapproved workspace was archived and an older approved workspace was unarchived onto that path, while scanning archived records by path blocked fresh worktrees that reused a deleted slug.

Persist `untrustedSource` on the checkout itself in `paseo/worktree.json` when creating or restoring an unapproved worktree, clear it in `clearWorkspaceAutomationBlock` when setup is approved, and read it in both `workspace-archive-service` and `workspace-provisioning-service`. Deleting the worktree removes its metadata automatically, so fresh worktrees reusing the path start clean while retained checkouts keep their block across workspace archives and restores.

* fix(server): backfill worktree metadata when archiving retained unapproved checkouts

Unapproved checkouts created before `paseo/worktree.json` stored `untrustedSource` carry their block only in the workspace record. If archive keeps the directory on disk (such as a retained sibling or nested worktree), backfilling `untrustedSource` into `paseo/worktree.json` before removal ensures the retained checkout keeps its block even after its unapproved workspace record is archived.

* fix(server): never propagate archived untrustedSource onto fresh checkouts

Both archive metadata backfill and directory workspace creation previously consulted already-archived records matching a path, allowing an old archived unapproved record to copy `untrustedSource` onto a fresh approved worktree that reused the same slug path.

Ignore `untrustedSource` on already-archived records during archive target resolution and metadata backfill (only backfill when active workspaces are being archived), and share one `resolveCheckoutUntrustedSource` rule across `createWorkspaceForDirectory` and `ensureWorkspaceRecordUnarchived` that checks `paseo/worktree.json` first and falls back only to active workspaces.

* fix(server): align unarchived workspace approval state with the live checkout

Unarchiving an old unapproved workspace onto a path already owned by an active approved checkout kept the old record's stale `untrustedSource`, causing a later re-archive of that workspace to backfill the block onto the fresh checkout's metadata.

Align `ensureWorkspaceRecordUnarchived` symmetrically with the live checkout: adopt `untrustedSource` from `paseo/worktree.json` or active workspaces on the checkout when present, and drop stale `untrustedSource` when live active workspaces own an approved checkout at that path.

* fix(server): preserve block when opening a pre-upgrade retained checkout

Opening a pre-upgrade retained checkout directory whose last unapproved workspace was already archived before this change has no active workspace on the path and no `untrustedSource` in `paseo/worktree.json`.

In `resolveCheckoutUntrustedSource`, prefer `paseo/worktree.json`, then active workspaces on the checkout when any exist (so a fresh approved worktree at a reused path stays approved), and only when zero active workspaces exist on the directory fall back to the most recently archived record for that path.

* fix(server): share one checkout approval lookup across open and unarchive

* fix(server): resolve checkout approval state only from metadata and active workspaces

* fix(server): keep archive read-only on worktree approval metadata

* fix(server): serialize setup approval with archive checkout lock and backfill retained metadata

* fix(server): fail setup approval before clearing records when worktree metadata write fails
2026-11-24 17:46:23 +07:00
Mohamed Boudra 8b2e14f3d2 Run resolved forge CLI executables directly (#10685)
* fix(server): run resolved forge CLI executables directly

The GitHub, GitLab, and Gitea adapters resolved gh, glab, and tea with findExecutable, then discarded the resolved path and spawned the bare command name. On Windows, spawning an extensionless bare name routes through cmd.exe, which resolves commands against cwd first, expands %VAR% references, and truncates multiline arguments such as gh api graphql queries.

Forward the resolved executablePath from each forge adapter and auth probe into the shared runner, resolve bare binary names inside createForgeCliRunner when omitted, and restrict bare-name PATH discovery in findExecutable to absolute PATH directories.

* fix(server): re-resolve cached forge CLI paths if the binary disappears

Cached CLI path resolvers now support targeted invalidation, and forge adapters plus createForgeCliRunner invalidate and retry once when a previously resolved executable disappears at launch time (ENOENT, or a missing Windows batch launcher). This preserves cached lookups on normal runs while recovering automatically when a user uninstalls or relocates an installation while another copy remains on PATH.

* fix(server): refresh cached forge CLI path on any unlaunchable spawn error

Match executable-resolution's unlaunchable spawn error set (ENOENT, EACCES, ENOEXEC, UNKNOWN) when deciding whether to invalidate and re-resolve a cached forge CLI path, so losing execute permission falls back to another working copy on PATH.
2026-11-24 14:37:28 +07:00
Mohamed Boudra da74f7de1f Offer Push and Pull for a branch whose remote is not named origin (#10679)
* fix(git): offer Push and Pull for a branch whose remote is not origin

A checkout whose only remote has another name, with main tracking that
remote's main, got no Push, Pull or Pull and push. The app gated all three
on hasRemote, which is true only when origin is configured, and the
daemon's pull refused to run without origin.

Neither action needs origin. The daemon now reports where each one goes for
the current branch (pullRemote, pushRemote) and the app offers the actions
from those. One resolver picks the push destination for both the status and
the push, so the offer and the push cannot disagree.

Without origin, Push follows the upstream only when the upstream branch has
the branch's own name and git pushes the branch to that remote. A branch
such as feature tracking upstream/main can be pulled and is not pushed.
With origin, every push goes where it went before.

firstPushRemote stays on the wire for apps that predate pushRemote.

* fix(git): follow Git's own push destination when origin is missing

Without origin, Push compared the upstream's remote with the remote Git
pushes the branch to. That missed a push refspec: with
remote.<upstream>.push set, plain `git push` updates another branch, and
Paseo still updated the upstream. A regular checkout with a push refspec on
branch.<name>.pushRemote was pushed there and stayed ahead of its upstream.

Push now asks Git where `git push` sends the branch (%(push)) and follows
the upstream only when that is the upstream. This also covers
push.default. A Paseo worktree keeps the push refspec Paseo configures for
a PR checkout.

Pull no longer requires a configured upstream before it runs. Git decides,
so a branch with no upstream in a single-branch clone pulls again.

* fix(git): compare the push remote by name when origin is missing

Push compared Git's push destination with the upstream as remote-tracking
refs. Two remotes whose fetch refspecs map onto the same tracking namespace
give the same ref for different repositories, so a branch Git pushes to one
remote was sent to the other. The remote Git pushes to is now compared by
name as well.

* fix(git): leave a matching-mode push to the user when origin is missing

Under push.default=matching, git push sends a branch only when the remote still has it. The checkout's remote-tracking ref can outlive a branch deleted on the remote, so the daemon cannot tell from local metadata that the push would go to the upstream, and its explicit push would recreate the branch. Without origin, Push is now refused in that mode.
2026-11-24 14:37:23 +07:00
Mohamed Boudra 767c1efa03 Show OpenCode Go usage from the login store the installed OpenCode uses (#10678)
* fix(usage): read OpenCode Go logins from the store the installed OpenCode uses

The source treated a `credential` table in opencode.db as proof of OpenCode 2
and then ignored auth.json. OpenCode 1.17.5 and newer creates that table too
and leaves it empty, and OpenCode 2 fills it once when it opens the same data
directory. In both cases the Go key in auth.json was dropped and the source
disappeared.

The source no longer reads OpenCode's database. It asks the installed OpenCode
for its version. OpenCode 2 lists its own logins with
`opencode auth export --standalone`, with its own choice of the active one per
integration. OpenCode 1 keeps logins in auth.json. A failed OpenCode 2 listing
throws, so it never reads as "no login". An auth.json key is not used when
OpenCode 2 is installed, because OpenCode 2 never reads that file after its
one-time import.

`--standalone` matters: without it the command starts OpenCode's background
service and leaves it running.

* chore(usage): request a review of the resolved threads

* fix(usage): keep the OpenCode Go card when the version check is cut off

A version check that reached its timeout was read as OpenCode 1. Discovery then
read auth.json, and a login that only OpenCode 2 has was reported as removed.
A check that is cut off does not show which store OpenCode uses, so discovery
now fails and the daemon keeps the account it already knew.

A missing OpenCode, or one that exits with an error, still reads auth.json:
that file is the only store when OpenCode is not installed.

* fix(usage): recognize OpenCode 2 when the daemon's environment forces colors

With FORCE_COLOR set, OpenCode 2 writes its version with ANSI codes even into
a pipe. The version did not parse, the source took OpenCode for version 1, and
a login that only OpenCode 2 has disappeared. The source now runs OpenCode with
NO_COLOR, which gives plain output for the version and the login listing.

* fix(usage): read the auth.json Go key when OpenCode 2 has no Go login

OpenCode 2 imports auth.json only once. A Go key that is saved in the file
after that import is in no other place, so the card was still missing for
the state in #10659 when the installed OpenCode is 2.x: the credential
listing holds only an unrelated login and the Go key is in auth.json.

The order is now: a login OpenCode 2 can serve Go with wins, so a stale key
in the file never replaces it. Without one, the auth.json key is used. A
failed listing still throws, because it does not show that OpenCode 2 has
no Go login.

* fix(usage): read the auth.json Go key behind an OpenCode 2 login without Go

The auth.json fallback applied only when OpenCode 2 listed neither an
`opencode` nor an `opencode-go` login. With an `opencode` login whose
Console workspace has no Go, the card reported "No active OpenCode Go
subscription" while a working Go key was in auth.json.

The file's key now stands in for a missing `opencode-go` login. The
existing order then decides: the `opencode` login is asked first, and the
Go key is asked only when the Console refuses that login. A temporary
failure still keeps the card on the `opencode` login.
2026-11-24 14:37:18 +07:00
paseo-bot[bot] e03fe0d8e7 test(server): avoid per-file Git work in the diff stream fixture (#10633)
Stage the generated additions so both diff paths can read their patches in bulk while still comparing against HEAD.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 00:01:37 +00:00
Mohamed Boudra ff27da07bf chore(release): reconcile v0.17.4 (#10645) 2026-11-24 06:16:30 +07:00
490 changed files with 36558 additions and 7775 deletions
+1
View File
@@ -56,6 +56,7 @@ sdk:
- "packages/plugin/**"
- "plugin-examples/**"
- "public-docs/plugins/**"
- "skills/paseo-plugin/**"
- "packages/client/**"
- "packages/highlight/**"
- "packages/protocol/**"
+23 -4
View File
@@ -87,10 +87,6 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
run: npx --yes lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
- name: Verify dependency signatures
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
run: npm audit signatures
- name: Lint
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
run: npm run lint
@@ -135,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
-3
View File
@@ -422,7 +422,6 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/headers/screen-header.tsx",
"packages/app/src/components/host-status-dot.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/icons/paseo-logo.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/plan-card.tsx",
@@ -552,9 +551,7 @@
"packages/app/src/components/download-toast.tsx",
"packages/app/src/components/file-explorer-pane.tsx",
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/highlighted-code-block.tsx",
"packages/app/src/components/hosts/host-filter.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/import-session-sheet.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/markdown/fence/mermaid/host.native.tsx",
+1 -1
View File
@@ -48,7 +48,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
- **Multi-provider:** Claude Code, Codex, Copilot, OpenCode, Pi, Antigravity, and Muse Code through the same interface. Pick the right model for each job.
- **Voice control:** Dictate tasks or talk through problems in voice mode. Hands-free when you need it.
- **Cross-device:** iOS, Android, desktop, web, and CLI. Start work at your desk, check in from your phone, script it from the terminal.
- **Privacy-first:** Paseo doesn't have any telemetry, tracking, or forced log-ins.
- **Privacy-first:** No telemetry, tracking, or forced login. Remote access uses an optional end-to-end encrypted relay.
[Run parallel tasks in Paseo](https://paseo.sh/docs/parallel-development): start agents in separate worktrees, review their diffs, run each app, and check it in the built-in browser.
+3 -3
View File
@@ -51,7 +51,7 @@
- **多提供商:** 通过同一个界面使用 Claude Code、Codex、Copilot、OpenCode 和 Pi。为每个任务选择合适的模型。
- **语音控制:** 在语音模式下口述任务或讨论问题。需要免手操作时很方便。
- **跨设备:** 支持 iOS、Android、桌面端、Web 和 CLI。在桌前开始工作,用手机查看进度,也可以从终端脚本化操作。
- **隐私优先:** Paseo 没有遥测、追踪,也不会强制登录。
- **隐私优先**:无遥测、无追踪、不强制登录。远程访问可使用可选的端到端加密中继。
## 赞助商
@@ -93,7 +93,7 @@ npm install -g @getpaseo/cli
paseo
```
终端中会显示一个二维码。你可以从任意客户端连接。这个方式适合服务器和远程机器。
Paseo 启动后会询问是否启用端到端加密中继以进行设备配对。如果拒绝,可以通过 TCP、Tailscale 或其他 VPN 直接连接。这个方式适合服务器和远程机器。
完整安装和配置见:
@@ -140,7 +140,7 @@ Monorepo 包结构速览:
- `packages/app`:Expo 客户端(iOS、Android、Web)
- `packages/cli`:用于 daemon 和 agent 工作流的 `paseo` CLI
- `packages/desktop`:Electron 桌面 app
- `packages/relay`:用于远程连接的 relay 包
- `packages/relay`:daemon 和客户端使用的中继传输与端到端加密包
- `packages/website`:营销站点和文档(`paseo.sh`)
常用命令:
+1 -1
View File
@@ -33,7 +33,7 @@ The relay sees only: IP addresses, timing, message sizes, session IDs, and the p
The daemon requires a valid cryptographic handshake before processing any commands. A compromised relay cannot:
- **Impersonate the daemon to your phone** — Without the daemon's secret key, it cannot derive the shared key, so any traffic it injects fails authenticated decryption on the phone
- **Send commands as you** — The daemon only accepts traffic that decrypts and authenticates under a shared key derived with its own secret key. The phone's keypair is ephemeral per connection, so there is no persistent phone-side secret to steal; protection comes from the daemon's secret key never leaving the daemon.
- **Open a session without pairing** — The daemon's public key is carried only in the pairing offer and is never sent to the relay. With a daemon password configured, the daemon also rejects any relay client that does not send the right password inside the encrypted channel.
- **Read your traffic** — After the handshake every message is encrypted: ChaCha20-Poly1305 in protected mode, XSalsa20-Poly1305 (NaCl box) in legacy mode
- **Forge messages** — Both constructions are authenticated encryption; a tampered message is rejected in either mode
- **Replay old messages** — In protected mode the daemon contributes a fresh ephemeral key to every session and every record carries a strictly increasing counter, so a recorded session cannot be replayed into a new one and a duplicated, reordered, or reflected record closes the session. Legacy mode has neither property: it uses random nonces, and a daemon that still admits legacy clients accepts a recorded legacy transcript (hello, credentials, commands) as a new session. Set `daemon.relay.requireProtectedSecurity: true` to refuse legacy clients once every client you use has updated.
+3 -1
View File
@@ -133,7 +133,9 @@ A configured URL takes precedence even when unreachable; Paseo reports the conne
An explicitly configured server needs the bridge installed separately. Connect once and start a session: the setup error gives the local package directory. Copy that directory to the server's OpenCode global `plugins` directory, then retry. For a server on another machine, set `PASEO_OPENCODE_BRIDGE_PORT` in the Paseo OpenCode provider environment before starting Paseo, and set `PASEO_OPENCODE_BRIDGE_URL` to the URL the OpenCode server can use to reach that port. For example, an SSH reverse tunnel can expose the Paseo loopback port on the OpenCode host. The bridge token is exchanged through the OpenCode connection and is not written into the plugin package.
OpenCode's custom MCP registrations are shared by all sessions in a location. Paseo rejects custom MCP servers and per-agent process environment overrides on a reused server rather than applying them to other sessions or ignoring them. Session identity is applied to each session's shell environment. A Paseo-owned helper supports custom process and MCP settings; it is selected when there is no explicit URL or healthy registered service.
Agent MCP servers and per-agent environment work on a reused server with OpenCode 2.0.29 or newer. Paseo connects each agent's MCP servers itself and shows their tools only to that agent and its subagents. Other agents in the same directory and your own OpenCode sessions do not see them. The agent's environment applies to its shell commands, its subagents, and its stdio MCP servers.
The provider `env` configures the OpenCode process. When it sets variables other than the connection variables above and `XDG_CONFIG_HOME`, `XDG_STATE_HOME`, or `OPENCODE_CONFIG_DIR`, Paseo ignores a registered service and starts its own helper. With an explicit URL, Paseo reports those variables as an error.
---
+6 -6
View File
@@ -575,8 +575,9 @@ where the overrides apply; workspace scripts still find the binary through the r
## Dependency signature audit
The `quality` CI job runs `npm audit signatures`. It verifies every lockfile package's registry
signature and, for packages published with provenance, fetches
The [pre-release dependency checks](release.md#pre-release-dependency-checks) include
`npm audit signatures`. The command verifies registry signatures and, for packages published
with provenance, fetches
`/-/npm/v1/attestations/<name>@<version>` from the registry. Cloudflare caches that document
for a year. An edge that cached it in the seconds before the registry attached the publish
attestation keeps serving a document with only the provenance bundle, and npm fails with:
@@ -587,11 +588,10 @@ npm error <name>@<version> has attestations but no corresponding public key(s) c
```
The same package's registry signature verified a moment earlier with the same keys, so the
key list is intact. The failure names one package, repeats only for that package, and depends
on the Azure region the runner landed in, because each region maps to one Cloudflare colo. A
rerun passes only by landing elsewhere.
key list is intact. The failure names one package and depends on which Cloudflare edge serves
the cached attestation.
To confirm, fetch the URL from several runners and compare `content-length`, the `cf-ray` colo
To confirm, fetch the URL from several regions and compare `content-length`, the `cf-ray` colo
suffix, and the number of `attestations` entries (#7730 has the probe). To fix, remove or
replace that version in the lockfile. If the dependent’s range cannot be changed, pin a clean
version in root `overrides`. Report the URL to npm so they purge it.
+16
View File
@@ -146,6 +146,22 @@ quietly relying on:
The fix for transforms is Gotcha 3. The fix for context is Gotcha 7.
### The portal patch
`patches/@gorhom+portal+1.0.14.patch` moves portal state out of the provider's
context value and into a store each `PortalHost` subscribes to. Upstream keeps
every host's portals in one context value at the app root, so each portal mount,
update and unmount changed that value and React searched every mounted fiber
for consumers. That cost grows with the retained panels: a hover card took
about 3 ms of it in a fresh window and 16 ms after a few hours. With the store,
a portal change renders only its own host.
Do not put per-overlay state in a context that wraps the app for the same
reason. Give the consumers a store to subscribe to.
The patch also keys each portal in its host (upstream PR #62). Without the key,
closing one overlay remounted every later overlay in the same host.
## Gotcha 3 — Keyboard layout and portal anchors
`composer/dock` owns the stationary viewport, bottom-anchored surface, composer
+6 -2
View File
@@ -43,7 +43,11 @@ Math and video are disabled. Task lists and admonitions are enabled; task checkb
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
Code blocks and plain quotes have a copy control in their top trailing corner. Native code blocks use the library's compiled grammars. On native, the code block and quote container views share one control (`HeaderCopyButton` on Android, `ENRMHeaderCopyButton` on iOS). A quote reserves the code block's header band above its body, so the control never covers quote text at any font size. On web, code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override, and quotes use `WebBlockquote` through `renderers.blockquote`. Both use `BlockCopyButton`. On compact layouts the control is always visible, so the web quote reserves a band above its body, as native does. On wide layouts the control appears on hover or focus, so the quote keeps a right gutter instead; a band there would leave an empty strip above every quote.
A quote copies its body without the `>` markers, with its nested Markdown, and reads the content at the time of the press, so a streaming quote copies what it shows. A nested quote or code block keeps its own control. Web quote copy uses the same two clipboard flavors as selection copy: `text/plain` is unescaped Markdown and `text/html` is rendered from escaped Markdown. A rendered Mermaid diagram copies as its fence because its wrapper carries the fence source. Native quote copy serializes the quote's parsed Markdown, so a workspace image copies as its cached file URL, as native selection copy does; native has no map back to the workspace path. A native Mermaid diagram in a quote renders outside it (see [native selection limitations](native-text-selection.md)), so each quote fragment copies only its own text. Admonitions get no control: web renders them with a separate library renderer. On web an admonition inside a copied quote copies as its `> [!TYPE]` source; the fork marks the box and its generated title for this. Selection copy keeps the text it shows, because the cloned range cannot tell a whole callout from part of one. On native, quotes inside list items get no control, because they render as text spans in the item. Web renders them as blocks, so they get one.
Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
The fork also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
@@ -55,4 +59,4 @@ The library determines how incomplete Markdown appears during streaming. Complet
## Verification
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, quote copy (nested quote, code block in a quote, admonition, large font on native), a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
+71 -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
@@ -883,6 +945,13 @@ its Zod schema, and mounts the component inside the normal plugin runtime and er
optional output `id` distinguishes several stable replacements from the same source item; its output
index is the default.
Each replacement keeps a reference to the source row (`source` on the projected stream item), and
turn logic reads a replaced reply through it. A reply split into several cards stays one reply: turn
folding keeps every card visible, and the turn footer hangs under the last card, copies the original
reply text once, forks at its message, and shows its duration and stats. Read the reply with
`getAssistantReply` (`packages/app/src/types/stream.ts`) instead of checking `kind ===
"assistant_message"`.
Transformers run synchronously and must be deterministic. When several transformers match, the
first one that returns a result owns that source item. Plugin and registration ordering is stable.
See `plugin-examples/timeline-items` for the complete contract.
+1 -1
View File
@@ -171,7 +171,7 @@ V2.0.4 also removed the activation endpoint that gated a cold location, and a co
Paseo installs its OpenCode tool bridge through `OPENCODE_CONFIG_CONTENT`. V1 accepts a plugin file; v2 silently skips configured files and requires a package directory with a server entry point. Both versions use the daemon's private loopback bridge for caller-scoped tools. The global manifest must use agent-scoped schemas before a session is bound, because every bridge call executes in an agent session. V2 discovers definitions from each bound session's catalog: plugin-contributed tools can be absent from the global manifest, and an allowlist cannot register a missing definition. Registration is location-wide, so session filtering and caller-scoped execution must remain in place. Bridge context lives only in daemon memory and is removed when the Paseo session closes. The content-addressed plugin artifacts contain no session data or secrets. V2 also needs this plugin when native Paseo tools are disabled: its prompt API has no structured-output format, so the plugin supplies a schema-validated final-answer tool.
An agent with custom environment variables or user-configured MCP servers gets a dedicated OpenCode server. V2 supports session environment, but its MCP configuration remains location-scoped, so separate servers still prevent one agent from changing another agent's MCP setup. Configure custom MCP with `mcp.add`; do not follow it with `mcp.connect`, which only toggles config-backed servers.
No v2 agent gets a dedicated OpenCode server, because a reused server cannot provide one. OpenCode's MCP configuration is location-scoped, so Paseo never calls `mcp.add` for an agent. The daemon connects the agent's MCP servers itself (`v2/session-mcp.ts`), and the v2 plugin exposes their tools under OpenCode's native `<server>_<tool>` names. Each name registers once per location. The plugin's `context` hook gives each session its own definition and removes the tool from other sessions. If the user's own OpenCode configuration registered a tool with the same name first, other sessions keep that tool and its execution. Execution routes to the calling session's root binding. The hook also adds the servers' instructions to each request. OpenCode loads instruction entries before the hook runs, so an entry written when a child is adopted would miss the child's first request. The plugin calls OpenCode's `permission.assert` before each call, so `toolPolicy.preapproved` grants still apply. That API exists from OpenCode 2.0.29. Bind reports `features.mcpTools`, so an older server or a stale plugin fails the session at creation instead of hiding its tools. Per-agent `launch.env` reaches shells through `session.environment`, which child sessions do not inherit. The plugin asks the daemon to adopt each descendant in its first `context` hook, before its first model request.
OpenCode owns user message IDs. Do not pass Paseo-generated IDs to OpenCode prompt APIs; let OpenCode create `msg*` IDs and record the user timeline item from the `message.updated` event.
+33 -11
View File
@@ -17,6 +17,7 @@ A release has exactly two steps. The agent does the first, the user authorizes t
run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag
- push the `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` branch and confirm its `CI` and
`Desktop Packages` runs pass (never wait on `main` CI)
- run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
**Go-ahead** (user says "go ahead"):
@@ -107,6 +108,7 @@ An explicit user instruction can select another base.
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` cancels in-progress
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
6. After go-ahead, run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta). This
publishes to npm and pushes the `v*` tag on the already-verified commit. Because the release
@@ -126,7 +128,9 @@ shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version
as the next unused patch beta, `0.13.4-beta.1`, from the tested beta tag. No `version:all:*` mode
computes that from a prerelease, so run `npm run release:check`, bump with
`npm version 0.13.4-beta.1 --include-workspace-root --no-git-tag-version && git commit -m "chore(release): cut 0.13.4-beta.1"`,
push the release branch for `CI` and `Desktop Packages`, then ship with `npm run release:ship:beta`.
push the release branch for `CI` and `Desktop Packages`, and complete the
[pre-release dependency checks](#pre-release-dependency-checks) before shipping with
`npm run release:ship:beta`.
Record the tested beta tag as its source so its soak still counts for the unchanged content.
## Release inventory
@@ -234,6 +238,7 @@ npm run release:prep:minor
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead and green release-branch checks: publish npm and push the tag.
npm run release:ship
@@ -269,7 +274,8 @@ npm run release:check # Typecheck, build, dry-run pack
npm run version:all:patch
npm run version:all:minor
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
# Wait for CI and Desktop Packages on this branch to pass, then after go-ahead:
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
npm run release:push # Create tag vX.Y.Z on HEAD and push (triggers release workflows)
```
@@ -286,6 +292,7 @@ npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead:
npm run release:ship:beta
@@ -293,7 +300,8 @@ npm run release:ship:beta
# Later, after soak, promote on release/vX.Y.Z:
npm run release:prep:promote
git push -u origin HEAD
# Wait for CI + Desktop Packages to pass, then after go-ahead:
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:ship
```
@@ -329,22 +337,21 @@ Drafts do not appear in GitHub's releases feed. Updater clients continue to see
### Default behavior
`npm run release:prep:patch` or `npm run release:prep:minor` → push release branch → green checks → `npm run release:ship` → tag push → 36h ramp. No extra action needed.
Follow the [standard stable release procedure](#standard-release-stable). The tag push starts
the desktop release workflow, which sets a 36-hour rollout when it publishes the release.
The `rollout_hours` input on `desktop-release.yml` is **only read on `workflow_dispatch`** — tag-push runs always default to 36. To get any other rollout duration on a fresh release, use the post-publish flip below.
### Instant-admit release (rollout_hours=0)
Tag-push runs from `npm run release:ship` always stamp 36 hours. To admit everyone immediately (hotfix, doc-only change, a release you want out fast), ship the release normally, wait for it to publish, then flip the manifests:
Follow the [standard stable release procedure](#standard-release-stable). Wait for Desktop
Release to publish, then update the manifests to admit everyone immediately.
```bash
# 1. Ship the verified release branch (36h ramp from tag push).
npm run release:ship
# 2. Wait for Desktop Release to publish the GitHub Release.
# 1. Wait for Desktop Release to publish the GitHub Release.
gh run watch <desktop-release-run-id> --exit-status
# 3. Flip the published manifests to instant admit.
# 2. Flip the published manifests to instant admit.
gh workflow run desktop-rollout.yml \
-f tag=v0.1.64 \
-f rollout_hours=0
@@ -390,7 +397,8 @@ gh workflow run desktop-release.yml \
-f rollout_hours=6
```
This does **not** apply to fresh releases shipped via `npm run release:ship` — tag-push runs always stamp 36. For a fresh release with a custom ramp, ship normally and then dispatch `desktop-rollout.yml` (same pattern as the instant-admit flow above, with your chosen `rollout_hours`).
For a fresh release with a custom ramp, follow the [instant-admit procedure](#instant-admit-release-rollout_hours0)
and set `rollout_hours` to your chosen duration.
### Releasing during an active rollout
@@ -859,6 +867,18 @@ Bullets within each section (Added, Changed, Fixed) follow this order:
2. **Quality-of-life improvements** — polish, performance, smoother interactions.
3. **Internal/infra changes last** — only include if they have a tangible user benefit (e.g. "faster startup" is user-facing even if the fix was internal).
## Pre-release dependency checks
Run these checks from the repository root on the release commit before shipping a beta or stable release.
Use Linux x64 so the audit includes the platform-specific dependencies that the CI job checked.
1. Review changes to dependency versions, download URLs, and integrity hashes in `git diff <previous-release-tag> HEAD -- package-lock.json`.
2. Install the exact dependencies from the release lockfile with `npm ci`.
3. Run `npm audit signatures`. Investigate failures before shipping. See [Dependency signature audit](development.md#dependency-signature-audit) for help.
Checking signatures and reviewing the lockfile diff reduce the risk of shipping compromised dependencies.
These checks help prevent supply-chain attacks from reaching users through Paseo.
## Pre-release sanity check
Before cutting a **stable** release, the release agent reviews the diff as a last line of defence against shipping bugs. Skip this for betas — the beta itself is the smoke test, and gating each beta on a code review defeats the point of using betas as fast release candidates.
@@ -886,6 +906,7 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before running `release:prep:*`
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:ship:beta` published npm and pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
@@ -909,6 +930,7 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:ship` published npm, updated dist-tags, and pushed the `vX.Y.Z` tag without triggering a second CI run
- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta`
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
+10 -1
View File
@@ -86,7 +86,7 @@ mounts—never at module evaluation time.
## Dynamic Pixel Styles On Web
Avoid feeding changing pixel values such as `{ top, left }`, `{ maxHeight }`, or `{ minWidth }` into the `style` prop of Unistyles-managed React Native components on web. The web runtime hashes each distinct style object by value and appends a CSS rule to `#unistyles-web`; those rules are not reclaimed during the page lifetime, so pointer-driven positioning can turn into steady stylesheet growth.
Avoid feeding changing pixel values such as `{ top, left }`, `{ maxHeight }`, or `{ minWidth }` into the `style` prop of Unistyles-managed React Native components on web. The web runtime hashes each distinct style object by value and inserts a CSS rule into `#unistyles-web` for it, then deletes the rule when the last element using it unmounts. Pointer-driven positioning turns into a rule insert and delete per move.
Use the inline style escape hatch below for high-churn values. Do not split a component into plain/web/native variants just to keep one measured value out of the CSS registry. Raw DOM wrappers are reserved for real DOM infrastructure, such as terminal hosts, virtualized web rows, or third-party drag wrappers.
@@ -224,6 +224,7 @@ Quick confirmation in DevTools console:
```js
[...document.styleSheets]
.flatMap((s) => [...(s.cssRules || [])])
.flatMap((r) => (r.cssRules ? [...r.cssRules] : [r]))
.map((r) => r.cssText)
.filter((t) => t.includes("unistyles") && t.includes("> *"));
```
@@ -366,6 +367,14 @@ colors. Keep this patch until upstream reads the scheme through separate lists.
The desktop browser E2E checks both transition directions in an isolated Electron
process, because Playwright's focus emulation prevents real hidden-page behavior.
The stylesheet patch backports upstream PR #1354 (3.8.0). Unistyles 3.2.4 rewrote
the whole text of `#unistyles-web` whenever a class was added or removed, and
the browser then restyled the entire document: about 5 ms each time, several
times for one hover card. The backport changes one CSSOM rule per class instead.
The tag therefore has no text; read its rules through `sheet.cssRules`. Classes
without a media query sit inside an `@media all` group. Assert on the stylesheet
in E2E with `packages/app/e2e/support/helpers/shared-stylesheet.ts`.
Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in
`patches/` is inert unless that script knows which installed package activates
it.
+230 -207
View File
@@ -5,27 +5,26 @@ import path from "node:path";
import { test, expect } from "../support/fixtures";
import {
addProjectFlow,
chooseAddHostFromProjectFlow,
addProjectFlowBack,
addProjectFlowHost,
addProjectFlowHostTrigger,
addProjectFlowInput,
addProjectFlowMethod,
chooseAddProjectMethod,
expectAddProjectPage,
expectNewWorkspaceForAddedProject,
addProjectFlowSubmit,
chooseAddHostFromProjectFlow,
chooseAddProjectHost,
chooseAddProjectLocation,
chooseAddProjectTab,
expectAddProjectResultVisible,
expectAddProjectTab,
expectNewWorkspaceForAddedProject,
navigateAddProjectResults,
navigateAndDismissAddProject,
watchAddProjectRenderWarnings,
openAddProjectFlow,
openAddProjectHostSelection,
watchAddProjectRenderWarnings,
} from "../support/helpers/add-project-flow";
import { gotoAppShell } from "../support/helpers/app";
import {
disconnectAllHostsAndReload,
addConnectedHostAndReload,
addConnectedHostsAndReload,
addOfflineHostAndReload,
disconnectAllHostsAndReload,
waitForConnectedHost,
} from "../support/helpers/hosts";
import {
@@ -36,6 +35,8 @@ import { expectOpenedProject } from "../support/helpers/project-picker-ui";
import { connectSeedClient } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
const MOD = process.platform === "darwin" ? "Meta" : "Control";
const SECONDARY_HOST_ID = "add-project-flow-secondary";
const SECONDARY_HOST_LABEL = "Secondary Host";
@@ -70,13 +71,14 @@ async function expectProjectHasNoWorkspaces(projectId: string): Promise<void> {
}
}
test.describe("Add Project command-center flow", () => {
test.describe("Add project sheet", () => {
test.describe.configure({ timeout: 180_000 });
test("Add host replaces the project dialog when no hosts are connected", async ({ page }) => {
test("Add host replaces the project sheet when no hosts are connected", async ({ page }) => {
await gotoAppShell(page);
await disconnectAllHostsAndReload(page);
await openAddProjectHostSelection(page);
await page.locator('[data-testid="sidebar-add-project"]:visible').click();
await expect(addProjectFlow(page)).toContainText("No connected hosts");
const originalUrl = page.url();
await chooseAddHostFromProjectFlow(page);
await expect(addProjectFlow(page)).toBeHidden();
@@ -86,22 +88,36 @@ test.describe("Add Project command-center flow", () => {
await expect(page).toHaveURL(originalUrl);
});
test("method selection shows the daemon's available project sources without search", async ({
test("opens on Existing, switches tabs with Mod+1/2/3, keeps each draft, and closes on Escape", async ({
page,
}) => {
const renderWarnings = watchAddProjectRenderWarnings(page);
await gotoAppShell(page);
await openAddProjectFlow(page);
await expect(addProjectFlowMethod(page, "directory-search")).toBeVisible();
await expect(addProjectFlowMethod(page, "github")).toContainText("Clone from GitHub");
await expect(addProjectFlowMethod(page, "new-directory")).toContainText("New directory");
await expect(addProjectFlowInput(page)).toHaveCount(0);
await expect(addProjectFlow(page).getByRole("textbox")).toHaveCount(0);
await expect(page.getByTestId("add-project-flow-page-host")).toHaveCount(0);
await page.keyboard.type("paseo");
await page.keyboard.press(`${MOD}+2`);
await expectAddProjectTab(page, "clone");
await expect(addProjectFlowInput(page)).toBeFocused();
await page.keyboard.type("getpaseo/");
await page.keyboard.press(`${MOD}+3`);
await expectAddProjectTab(page, "new-folder");
await expect(addProjectFlowSubmit(page)).toBeDisabled();
await page.keyboard.press(`${MOD}+1`);
await expectAddProjectTab(page, "existing");
await expect(addProjectFlowInput(page)).toHaveValue("paseo");
await chooseAddProjectTab(page, "clone");
await expect(addProjectFlowInput(page)).toHaveValue("getpaseo/");
await navigateAndDismissAddProject(page);
await expect(addProjectFlow(page)).not.toBeVisible();
expect(renderWarnings).toEqual([]);
});
test("an offline extra host neither appears nor forces host selection", async ({ page }) => {
test("a single connected host shows no host picker, even with an offline host", async ({
page,
}) => {
await gotoAppShell(page);
await addOfflineHostAndReload(page, {
serverId: "add-project-flow-offline",
@@ -110,8 +126,7 @@ test.describe("Add Project command-center flow", () => {
await openAddProjectFlow(page);
await expect(addProjectFlowHost(page, "add-project-flow-offline")).toHaveCount(0);
await expect(addProjectFlowMethod(page, "directory-search")).toBeVisible();
await expect(addProjectFlowHostTrigger(page)).toHaveCount(0);
});
test.describe("with two connected hosts", () => {
@@ -125,73 +140,7 @@ test.describe("Add Project command-center flow", () => {
await secondaryHost?.close();
});
test("keyboard selection chooses the second host", async ({ page }) => {
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
serverId: secondaryHost.serverId,
label: SECONDARY_HOST_LABEL,
port: secondaryHost.port,
});
await waitForConnectedHost(page, {
serverId: SECONDARY_HOST_ID,
endpoint: `localhost:${secondaryHost.port}`,
});
await openAddProjectHostSelection(page);
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await expect(addProjectFlow(page)).toContainText(SECONDARY_HOST_LABEL);
});
test("Escape and Back restore searchable page input before closing at the root", async ({
page,
}) => {
const renderWarnings = watchAddProjectRenderWarnings(page);
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
serverId: secondaryHost.serverId,
label: SECONDARY_HOST_LABEL,
port: secondaryHost.port,
});
await waitForConnectedHost(page, {
serverId: SECONDARY_HOST_ID,
endpoint: `localhost:${secondaryHost.port}`,
});
await openAddProjectHostSelection(page);
await addProjectFlowInput(page).fill("o");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await chooseAddProjectMethod(page, "new-directory");
await expectAddProjectPage(page, "new-directory-parent");
await page.keyboard.press("Escape");
await expectAddProjectPage(page, "method");
await expect(addProjectFlowInput(page)).toHaveCount(0);
await chooseAddProjectMethod(page, "new-directory");
await expectAddProjectPage(page, "new-directory-parent");
await addProjectFlowBack(page).click();
await expectAddProjectPage(page, "method");
await addProjectFlowBack(page).click();
await expectAddProjectPage(page, "host");
await expect(addProjectFlowInput(page)).toHaveValue("o");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await expect(addProjectFlow(page)).toContainText(SECONDARY_HOST_LABEL);
await page.keyboard.press("Escape");
await expectAddProjectPage(page, "host");
await navigateAndDismissAddProject(page);
await expect(addProjectFlow(page)).not.toBeVisible();
expect(renderWarnings).toEqual([]);
});
test("New directory creates a Project on the selected remote host", async ({ page }) => {
test("New folder creates a Project on the host chosen in the sheet", async ({ page }) => {
const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-remote-project-"));
const directoryName = `remote-${randomUUID().slice(0, 8)}`;
const directoryPath = path.join(parentDirectory, directoryName);
@@ -207,18 +156,15 @@ test.describe("Add Project command-center flow", () => {
serverId: SECONDARY_HOST_ID,
endpoint: `localhost:${secondaryHost.port}`,
});
await openAddProjectHostSelection(page);
await addProjectFlowHost(page, SECONDARY_HOST_ID).click();
await expectAddProjectPage(page, "method");
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "new-folder");
await addProjectFlowInput(page).fill(directoryName);
await expect(addProjectFlowMethod(page, "new-directory")).toContainText(
`Create an empty directory on ${SECONDARY_HOST_LABEL}`,
);
await chooseAddProjectMethod(page, "new-directory");
await addProjectFlowInput(page).fill(parentDirectory);
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "new-directory-name");
await page.keyboard.type(directoryName);
await chooseAddProjectHost(page, SECONDARY_HOST_ID);
await expect(addProjectFlowHostTrigger(page)).toContainText(SECONDARY_HOST_LABEL);
await expect(addProjectFlowInput(page)).toHaveValue(directoryName);
await chooseAddProjectLocation(page, parentDirectory);
await addProjectFlowInput(page).focus();
await page.keyboard.press("Enter");
const projectId = await expectOpenedProject(page, directoryName);
@@ -236,57 +182,35 @@ test.describe("Add Project command-center flow", () => {
});
});
test("filtered hosts keep the keyboard-selected row visible", async ({ page }) => {
const hosts: IsolatedHostDaemon[] = [];
test("a host that disconnects keeps its draft and blocks submit instead of moving it", async ({
page,
}) => {
const droppingHost = await startIsolatedHostDaemon("add-project-flow-dropping");
try {
for (let index = 1; index <= 3; index += 1) {
hosts.push(await startIsolatedHostDaemon(`scroll-host-${index}`));
}
await page.setViewportSize({ width: 1280, height: 360 });
await gotoAppShell(page);
await addConnectedHostsAndReload(
page,
hosts.map((host, index) => ({
serverId: host.serverId,
port: host.port,
label: index < 2 ? `Fleet 0${index + 1}` : "Other host",
})),
{ primaryLabel: "Fleet 00" },
await addConnectedHostAndReload(page, {
serverId: droppingHost.serverId,
label: "Dropping Host",
port: droppingHost.port,
});
await waitForConnectedHost(page, {
serverId: droppingHost.serverId,
endpoint: `localhost:${droppingHost.port}`,
});
await openAddProjectFlow(page);
await chooseAddProjectHost(page, droppingHost.serverId);
await addProjectFlowInput(page).fill(homedir());
await droppingHost.close();
await expect(page.getByTestId("add-project-flow-error")).toHaveText(
"Dropping Host is offline",
{ timeout: 30_000 },
);
for (const host of hosts) {
await waitForConnectedHost(page, {
serverId: host.serverId,
endpoint: `localhost:${host.port}`,
});
}
await openAddProjectHostSelection(page);
await expect(
addProjectFlow(page).getByRole("button").filter({ hasText: "Other host" }),
).toBeVisible();
await addProjectFlowInput(page).fill("Fleet");
await expect(addProjectFlowHost(page, hosts[2]!.serverId)).toHaveCount(0);
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Fleet 02");
// Filtering out the first host moves retained rows to new positions.
await addProjectFlowInput(page).fill("scroll-host");
await expect(addProjectFlowHost(page, getServerId())).toHaveCount(0);
await expectAddProjectResultVisible(page, "Fleet 01");
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Other host");
await navigateAddProjectResults(page, "ArrowDown", 1);
await expectAddProjectResultVisible(page, "Fleet 01");
await addProjectFlowInput(page).fill("Fleet");
await expectAddProjectResultVisible(page, "Fleet 00");
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Fleet 02");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await expect(addProjectFlow(page)).toContainText("Fleet 02");
await expect(addProjectFlowHostTrigger(page)).toContainText("Dropping Host");
await expect(addProjectFlowInput(page)).toHaveValue(homedir());
await expect(addProjectFlowSubmit(page)).toBeDisabled();
} finally {
await Promise.all(hosts.map((host) => host.close()));
await droppingHost.close();
}
});
@@ -297,9 +221,6 @@ test.describe("Add Project command-center flow", () => {
await gotoAppShell(page);
await openAddProjectFlow(page);
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "directory-search");
await expect(addProjectFlowInput(page)).toBeFocused();
await page.keyboard.type(projectPickerFixture.fuzzyQuery);
await expect(addProjectFlow(page)).toContainText(projectPickerFixture.projectName, {
timeout: 30_000,
@@ -323,45 +244,32 @@ test.describe("Add Project command-center flow", () => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-scroll-"));
const rowPath = (index: number) =>
path.join(parentDirectory, `scroll-probe-${String(index).padStart(2, "0")}`);
const rowName = (index: number) => path.basename(rowPath(index));
let projectId: string | null = null;
try {
await Promise.all(Array.from({ length: 16 }, (_, index) => mkdir(rowPath(index))));
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}/scroll-probe`);
const results = page.getByTestId("add-project-flow-results");
await expect(results.getByRole("button", { name: /scroll-probe-/ })).toHaveCount(16, {
timeout: 30_000,
});
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await navigateAddProjectResults(page, "ArrowDown", 11);
await expectAddProjectResultVisible(page, rowName(11));
await navigateAddProjectResults(page, "ArrowUp", 12);
await expectAddProjectResultVisible(page, parentDirectory);
await navigateAddProjectResults(page, "ArrowUp", 1);
await expectAddProjectResultVisible(page, rowPath(15));
await expectAddProjectResultVisible(page, rowName(15));
await navigateAddProjectResults(page, "ArrowDown", 1);
await expectAddProjectResultVisible(page, parentDirectory);
await expectAddProjectResultVisible(page, rowName(0));
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}probe`);
await expect(results.getByRole("button")).toHaveCount(16);
await expectAddProjectResultVisible(page, rowPath(0));
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(12));
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
await expect(results.getByRole("button")).toHaveCount(17);
await expectAddProjectResultVisible(page, parentDirectory);
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await navigateAddProjectResults(page, "ArrowDown", 11);
await page.keyboard.press("Enter");
projectId = await expectOpenedProject(page, "scroll-probe-11");
projectId = await expectOpenedProject(page, rowName(11));
await expectNewWorkspaceForAddedProject(page, {
serverId: getServerId(),
projectId,
projectName: "scroll-probe-11",
projectName: rowName(11),
projectPath: rowPath(11),
});
} finally {
@@ -370,28 +278,146 @@ test.describe("Add Project command-center flow", () => {
}
});
test("a complete repository URL remains selectable without a GitHub search result", async ({
test("Enter on a focused result adds that folder, not the one picked before", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-focus-"));
const firstPath = path.join(parentDirectory, "focus-probe-a");
const secondPath = path.join(parentDirectory, "focus-probe-b");
let projectId: string | null = null;
try {
await Promise.all([mkdir(firstPath), mkdir(secondPath)]);
await gotoAppShell(page);
await openAddProjectFlow(page);
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}/focus-probe`);
const results = page.getByTestId("add-project-flow-results");
await expect(results.getByRole("button", { name: /focus-probe-/ })).toHaveCount(2, {
timeout: 30_000,
});
await results.getByRole("button", { name: /focus-probe-b/ }).focus();
await page.keyboard.press("Enter");
projectId = await expectOpenedProject(page, "focus-probe-b");
await expectNewWorkspaceForAddedProject(page, {
serverId: getServerId(),
projectId,
projectName: "focus-probe-b",
projectPath: secondPath,
});
} finally {
if (projectId) await removeCreatedProject(secondPath, projectId);
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("Enter while a new search runs does not open a row from the previous search", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-stale-"));
try {
await mkdir(path.join(parentDirectory, "stale-probe-a"));
await gotoAppShell(page);
await openAddProjectFlow(page);
const prefix = path.basename(parentDirectory);
await addProjectFlowInput(page).fill(`${prefix}/stale-probe`);
const results = page.getByTestId("add-project-flow-results");
await expect(results.getByRole("button", { name: /stale-probe-a/ })).toBeVisible({
timeout: 30_000,
});
await addProjectFlowInput(page).fill(`${prefix}/no-such-folder`);
await page.keyboard.press("Enter");
await expect(addProjectFlow(page).getByText("No matching folders")).toBeVisible({
timeout: 30_000,
});
await expect(addProjectFlow(page)).toBeVisible();
await expect(addProjectFlowSubmit(page)).toBeDisabled();
} finally {
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("a complete repository URL is cloneable without a GitHub search result", async ({
page,
}) => {
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "github");
await chooseAddProjectTab(page, "clone");
const remote = "https://github.invalid/acme/manual.git";
await addProjectFlowInput(page).fill(remote);
await expect(addProjectFlow(page).getByText("manual", { exact: true })).toBeVisible();
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "github-location");
const title = addProjectFlow(page).getByTestId("add-project-flow-title");
await expect(title.getByText("Choose destination", { exact: true })).toBeVisible();
await expect(title.getByText("localhost", { exact: true })).toBeVisible();
await expect(title).not.toContainText("Where should Paseo create");
await addProjectFlowBack(page).click();
await expect(addProjectFlowInput(page)).toHaveValue(remote);
await expect(page.getByTestId("add-project-flow-location")).toContainText("/manual");
await expect(addProjectFlowSubmit(page)).toBeEnabled();
});
test("New directory validates the name, restores parent and name state, then creates a Project", async ({
test("Enter activates a focused button instead of the primary action", async ({ page }) => {
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "clone");
await addProjectFlowInput(page).fill("https://github.invalid/acme/manual.git");
await expect(addProjectFlowSubmit(page)).toBeEnabled();
await addProjectFlow(page).getByRole("button", { name: "Close", exact: true }).focus();
await page.keyboard.press("Enter");
await expect(addProjectFlow(page)).toBeHidden();
});
test("a row picked during a search is not replaced by the answer's first row", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-dropped-pick-"));
try {
await Promise.all([
mkdir(path.join(parentDirectory, "previous-probe")),
mkdir(path.join(parentDirectory, "incoming-probe")),
]);
await gotoAppShell(page);
await openAddProjectFlow(page);
const prefix = path.basename(parentDirectory);
const results = page.getByTestId("add-project-flow-results");
await addProjectFlowInput(page).fill(`${prefix}/previous-probe`);
await expect(results.getByRole("button", { name: /previous-probe/ })).toBeVisible({
timeout: 30_000,
});
await addProjectFlowInput(page).fill(`${prefix}/incoming-probe`);
await page.keyboard.press("ArrowDown");
await expect(results.getByRole("button", { name: /incoming-probe/ })).toBeVisible({
timeout: 30_000,
});
await expect(addProjectFlowSubmit(page)).toBeDisabled();
} finally {
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("Enter in Location while a new search runs keeps the current location", async ({ page }) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-stale-location-"));
try {
await mkdir(path.join(parentDirectory, "stale-probe-a"));
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "new-folder");
const location = page.getByTestId("add-project-flow-location");
const locationBefore = await location.textContent();
await location.click();
const search = page.getByPlaceholder("Search folders or enter a path").last();
const prefix = path.basename(parentDirectory);
await search.fill(`${prefix}/stale-probe`);
await expect(page.getByText(/stale-probe-a/).last()).toBeVisible({ timeout: 30_000 });
await search.fill(`${prefix}/no-such-folder`);
await page.keyboard.press("Enter");
await expect(page.getByText("No matching folders")).toBeVisible({ timeout: 30_000 });
await expect(search).toBeVisible();
await expect(location).toHaveText(locationBefore ?? "");
} finally {
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("New folder validates the name, then creates a Project in the chosen location", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-new-project-"));
@@ -402,27 +428,23 @@ test.describe("Add Project command-center flow", () => {
try {
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "new-directory");
await chooseAddProjectTab(page, "new-folder");
await chooseAddProjectLocation(page, parentDirectory);
await page.keyboard.type(parentDirectory);
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "new-directory-name");
await page.keyboard.type("../invalid");
await page.keyboard.press("Enter");
await addProjectFlowInput(page).fill("../invalid");
const nameError = page.getByTestId("add-project-flow-name-field-error");
await expect(nameError).toHaveText("Use a name without slashes");
await expect(addProjectFlowSubmit(page)).toBeDisabled();
const error = page.getByTestId("add-project-flow-error");
await expect(error).toBeVisible();
await expect(error).toContainText(/name|separator|directory/i);
await expectAddProjectPage(page, "new-directory-name");
await addProjectFlowInput(page).fill("C:repo");
await expect(nameError).toHaveText("Use a name without a drive letter");
await expect(addProjectFlowSubmit(page)).toBeDisabled();
await addProjectFlowInput(page).fill(directoryName);
await addProjectFlowBack(page).click();
await expectAddProjectPage(page, "new-directory-parent");
await expect(addProjectFlowInput(page)).toHaveValue(parentDirectory);
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "new-directory-name");
await expect(addProjectFlowInput(page)).toHaveValue(directoryName);
await page.keyboard.press("Enter");
await expect(nameError).toBeHidden();
await expect(addProjectFlowSubmit(page)).toBeEnabled();
await expect(page.getByTestId("add-project-flow-location")).toContainText(directoryName);
await addProjectFlowSubmit(page).click();
projectId = await expectOpenedProject(page, directoryName);
await expectNewWorkspaceForAddedProject(page, {
@@ -461,10 +483,11 @@ test.describe("Compact Add project context", () => {
await gotoAppShell(page);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
await addProjectFlowInput(page).fill(projectPickerFixture.fuzzyQuery);
await expect(addProjectFlow(page)).toContainText(projectPickerFixture.projectName);
await page.keyboard.press("Enter");
await expect(
page.getByRole("button", { name: new RegExp(projectPickerFixture.projectName) }).first(),
).toBeVisible({ timeout: 30_000 });
await addProjectFlowSubmit(page).click();
const projectId = await expectOpenedProject(page, projectPickerFixture.projectName);
projectPickerFixture.rememberProjectId(projectId);
await expectNewWorkspaceForAddedProject(page, {
@@ -4,10 +4,9 @@ import path from "node:path";
import { expect, test } from "../support/fixtures";
import {
addProjectFlow,
addProjectFlowBack,
addProjectFlowInput,
chooseAddProjectMethod,
expectAddProjectPage,
chooseAddProjectLocation,
chooseAddProjectTab,
expectNewWorkspaceForAddedProject,
openAddProjectFlow,
} from "../support/helpers/add-project-flow";
@@ -39,28 +38,22 @@ test.describe("Add Project GitHub flow", () => {
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "github");
await chooseAddProjectTab(page, "clone");
await addProjectFlowInput(page).fill("getpaseo/paseo");
await expect(addProjectFlow(page).getByText("getpaseo/paseo", { exact: true })).toBeVisible({
timeout: 30_000,
});
await addProjectFlowInput(page).fill("");
await addProjectFlowInput(page).fill(repository.fullName);
const repositoryRow = addProjectFlow(page).getByText(repository.fullName, { exact: true });
await expect(repositoryRow).toBeVisible({ timeout: 30_000 });
await repositoryRow.click();
await expectAddProjectPage(page, "github-location");
await addProjectFlowInput(page).fill(parentDirectory);
await expect(addProjectFlow(page)).toContainText(checkoutPath, { timeout: 30_000 });
await addProjectFlowBack(page).click();
await expectAddProjectPage(page, "github-search");
await expect(repositoryRow).toBeVisible();
await repositoryRow.click();
await expectAddProjectPage(page, "github-location");
await expect(addProjectFlowInput(page)).toHaveValue(parentDirectory);
await chooseAddProjectLocation(page, parentDirectory);
await expect(page.getByTestId("add-project-flow-location")).toContainText(
path.join(path.basename(parentDirectory), repository.name),
);
await addProjectFlowInput(page).focus();
await mkdir(checkoutPath);
await page.keyboard.press("Enter");
@@ -2,8 +2,10 @@ import { expect, test } from "../support/fixtures";
import {
applyProfileFromPicker,
closeModelPicker,
expectAgentProfileNameDraft,
expectComposerDoesNotName,
expectAgentProfilesEmptyPrompt,
expectHostAgentProfiles,
expectProfileEditTooltip,
expectComposerMode,
expectCreateProfileFromModelRow,
@@ -11,13 +13,23 @@ import {
expectModelRowProfileActionBesideRow,
expectModelRowSelected,
expectProfileEditIsPencilOnly,
expectProfileReachableByScrolling,
expectProfileSearchResult,
expectProfileVisibleForProvider,
fillAgentProfileName,
openEditProfileFromModelRow,
openModelPicker,
openAgentProfilesFromEmptyPrompt,
removeOpenModalAgentProfileWithConfirm,
searchModelPicker,
seedAgentProfiles,
selectModelRow,
} from "../support/helpers/agent-profiles";
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
import {
chooseCommandCenterAgentControl,
expectWorkspaceAgentConfiguration,
openCommandCenterForAgent,
} from "../support/helpers/command-center-agent-controls";
import { expectComposerVisible } from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
@@ -139,10 +151,129 @@ test.describe("Agent profiles in the model picker", () => {
await openModelPicker(page);
await expectModelRowProfileActionBesideRow(page, oneMinute);
await expectCreateProfileFromModelRow(page, oneMinute);
await expectComposerModel(page, "Ten second stream");
await openModelPicker(page);
await selectModelRow(page, oneMinute);
await expectComposerModel(page, oneMinute.modelLabel);
await openModelPicker(page);
await selectModelRow(page, { provider: "mock", modelId: "ten-second-stream" });
await expectComposerModel(page, "Ten second stream");
} finally {
await workspace.cleanup();
await seed.restore();
}
});
test("a profile is found by searching the model picker or the command center", async ({
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-search-",
title: "Agent profiles search",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await test.step("searching its name in the model picker lists only the profile", async () => {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await openModelPicker(page);
await searchModelPicker(page, "ui work");
await expectProfileSearchResult(page, { name: PROFILE.name });
});
await test.step("searching its model lists the profile above the model", async () => {
await searchModelPicker(page, "one minute");
await expectProfileSearchResult(page, {
name: PROFILE.name,
model: { provider: "mock", modelId: "one-minute-stream" },
});
await closeModelPicker(page);
});
await test.step("choosing it from the command center applies it", async () => {
await openCommandCenterForAgent(page, workspace);
await chooseCommandCenterAgentControl({
page,
query: "ui work",
choice: `Profile › ${PROFILE.name}`,
});
await expectComposerModel(page, "One minute stream");
await expectComposerMode(page, "Approval test");
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "one-minute-stream",
modeId: "approval-test",
});
});
} finally {
await workspace.cleanup();
await seed.restore();
}
});
test("profile-only search results scroll inside the picker", async ({ page }) => {
const profiles = Array.from({ length: 12 }, (_, index) => ({
id: `agent_profile_e2e_release_${index + 1}`,
name: `Release review ${String(index + 1).padStart(2, "0")}`,
provider: "mock",
model: "one-minute-stream",
}));
const seed = await seedAgentProfiles(profiles);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-search-scroll-",
title: "Agent profiles search scroll",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await openModelPicker(page);
await searchModelPicker(page, "release review");
await expectProfileSearchResult(page, { name: "Release review 01" });
await expectProfileReachableByScrolling(page, "Release review 12");
} finally {
await workspace.cleanup();
await seed.restore();
}
});
test("canceling Remove in the composer profile editor keeps the editor and draft open", async ({
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-remove-cancel-",
title: "Agent profiles remove cancel",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await openModelPicker(page);
await openEditProfileFromModelRow(page, {
provider: "mock",
modelId: "one-minute-stream",
});
await fillAgentProfileName(page, "Draft name");
await test.step("canceling Remove keeps the modal and draft intact", async () => {
await removeOpenModalAgentProfileWithConfirm(page, "dismiss");
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
await expectAgentProfileNameDraft(page, "Draft name");
});
await test.step("confirming Remove deletes the profile and closes the modal", async () => {
await removeOpenModalAgentProfileWithConfirm(page, "accept");
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
timeout: 30_000,
});
await expectHostAgentProfiles([]);
});
} finally {
await workspace.cleanup();
await seed.restore();
@@ -1,19 +1,32 @@
import { test } from "../support/fixtures";
import { expect, test } from "../support/fixtures";
import {
browserBackWithConfirm,
browserHistoryJumpWithConfirm,
createAgentProfile,
createAgentProfileFromEmptyState,
duplicateOpenAgentProfileWithConfirm,
editAgentProfile,
expectAgentProfile,
expectAgentProfileForm,
expectAgentProfileNameDraft,
expectAgentProfileNotesDraft,
expectAgentProfileOrder,
expectAgentProfileTagsGone,
expectHostAgentProfiles,
expectNoAgentProfiles,
fillAgentProfileName,
fillAgentProfileNotes,
moveAgentProfileUp,
openAgentProfileEditor,
openAgentProfileSettings,
openCompactAgentProfileSettings,
openCreateAgentProfileEditor,
removeAgentProfile,
saveOpenAgentProfile,
seedAgentProfiles,
stageLegacyFavoritesForHostMigration,
switchSettingsSectionWithConfirm,
toggleAgentProfileCustomize,
} from "../support/helpers/agent-profiles";
const MOCK_PROVIDER_LABEL = "Mock Load Test";
@@ -125,4 +138,252 @@ test.describe("Agent profiles settings", () => {
await seed.restore();
}
});
test("remounting the profile form keeps draft text across resize and collapsible toggles", async ({
page,
}) => {
const seed = await seedAgentProfiles([
{
id: "agent_profile_e2e_remount",
name: "Original profile",
provider: "mock",
model: "one-minute-stream",
notes: "Original note",
},
]);
try {
await page.setViewportSize({ width: 1680, height: 900 });
await openAgentProfileSettings(page);
await test.step("drawer-to-modal and compact resizes keep the edited name and save it", async () => {
await openAgentProfileEditor(page, "Original profile");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await fillAgentProfileName(page, "Draft rename");
await page.setViewportSize({ width: 1000, height: 900 });
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
await expectAgentProfileNameDraft(page, "Draft rename");
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
await expectAgentProfileNameDraft(page, "Draft rename");
await saveOpenAgentProfile(page);
await expectAgentProfile(page, {
name: "Draft rename",
tags: [MOCK_PROVIDER_LABEL, "One minute stream"],
notes: "Original note",
});
});
await test.step("collapsing and reopening advanced settings keeps the draft note", async () => {
await page.setViewportSize({ width: 1000, height: 900 });
await openCreateAgentProfileEditor(page);
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
await toggleAgentProfileCustomize(page);
await fillAgentProfileNotes(page, "Draft routing note");
await toggleAgentProfileCustomize(page);
await toggleAgentProfileCustomize(page);
await expectAgentProfileNotesDraft(page, "Draft routing note");
});
} finally {
await seed.restore();
}
});
test("duplicating while editing asks before discarding unsaved changes", async ({ page }) => {
const seed = await seedAgentProfiles([
{
id: "agent_profile_e2e_duplicate",
name: "UI work",
provider: "mock",
model: "one-minute-stream",
},
]);
try {
await page.setViewportSize({ width: 1680, height: 900 });
await openAgentProfileSettings(page);
await openAgentProfileEditor(page, "UI work");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await fillAgentProfileName(page, "Draft name");
await test.step("dismissing the prompt keeps the draft and does not create a copy", async () => {
await duplicateOpenAgentProfileWithConfirm(page, "dismiss");
await expectAgentProfileNameDraft(page, "Draft name");
await expectAgentProfileOrder(page, ["UI work"]);
});
await test.step("accepting the prompt creates and opens the copy", async () => {
await duplicateOpenAgentProfileWithConfirm(page, "accept");
await expectAgentProfileOrder(page, ["UI work", "UI work (copy)"]);
await expectAgentProfileNameDraft(page, "UI work (copy)");
});
} finally {
await seed.restore();
}
});
test("docked drawer allows roster search and section switches ask before discarding a draft", async ({
page,
}) => {
const seed = await seedAgentProfiles([
{
id: "agent_profile_e2e_docked_1",
name: "UI work",
provider: "mock",
model: "one-minute-stream",
},
{
id: "agent_profile_e2e_docked_2",
name: "Deep review",
provider: "mock",
model: "five-minute-stream",
},
]);
try {
await page.setViewportSize({ width: 1680, height: 900 });
await openAgentProfileSettings(page);
await openAgentProfileEditor(page, "UI work");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await test.step("typing in roster search works while the docked drawer is open", async () => {
const searchInput = page.getByTestId("agent-profiles-search-input");
await searchInput.click();
await page.keyboard.type("Deep");
await expect(searchInput).toHaveValue("Deep");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await expectAgentProfileOrder(page, ["Deep review"]);
await page.getByTestId("agent-profiles-search-clear").click();
});
await test.step("browser Back asks before discarding a draft and canceling keeps route and draft", async () => {
await fillAgentProfileName(page, "Unsaved browser back edit");
const profilesUrl = page.url();
await browserBackWithConfirm(page, "dismiss");
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await expectAgentProfileNameDraft(page, "Unsaved browser back edit");
});
await test.step("switching Settings sections asks before discarding an edited draft", async () => {
await fillAgentProfileName(page, "Unsaved sidebar edit");
await switchSettingsSectionWithConfirm(page, "Agents", "dismiss");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await expectAgentProfileNameDraft(page, "Unsaved sidebar edit");
await switchSettingsSectionWithConfirm(page, "Agents", "accept");
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
await expect(page.getByTestId("settings-detail-header-title")).toHaveText("Agents");
});
await test.step("confirming browser Back leaves Agent profiles and discards the draft", async () => {
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
await openAgentProfileEditor(page, "UI work");
await fillAgentProfileName(page, "Discard on browser back");
const profilesUrl = page.url();
await browserBackWithConfirm(page, "accept");
await expect(page).not.toHaveURL(profilesUrl, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
});
} finally {
await seed.restore();
}
});
test("canceling a multi-step Back jump keeps intervening browser history and confirming reaches the destination", async ({
page,
}) => {
const seed = await seedAgentProfiles([
{
id: "agent_profile_e2e_multistep",
name: "UI work",
provider: "mock",
model: "one-minute-stream",
},
]);
try {
// Narrow viewport pushes Open project -> Settings -> Agent profiles onto history.
await page.setViewportSize({ width: 390, height: 844 });
await openCompactAgentProfileSettings(page);
const profilesUrl = page.url();
await openAgentProfileEditor(page, "UI work");
await fillAgentProfileName(page, "Unsaved multi-step edit");
await test.step("canceling a two-step Back jump keeps Agent profiles, draft, and Settings in history", async () => {
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
await expectAgentProfileNameDraft(page, "Unsaved multi-step edit");
});
await test.step("canceling a two-step Back jump after reload still restores the Agent profiles URL", async () => {
await page.reload();
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
await openAgentProfileEditor(page, "UI work");
await fillAgentProfileName(page, "Post-reload draft");
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
await expectAgentProfileNameDraft(page, "Post-reload draft");
});
await test.step("confirming a two-step Back jump lands directly on the selected destination", async () => {
await browserHistoryJumpWithConfirm(page, -2, "accept");
await expect(page).toHaveURL(/\/open-project/, { timeout: 15_000 });
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
timeout: 30_000,
});
});
await test.step("forward navigation confirms the intervening Settings entry survived", async () => {
await page.goForward();
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 15_000 });
});
} finally {
await seed.restore();
}
});
test("canceling an untouched provider-and-model-only profile closes without a discard prompt", async ({
page,
}) => {
const seed = await seedAgentProfiles([
{
id: "legacy_favorite:mock:one-minute-stream",
name: "One minute stream",
provider: "mock",
model: "one-minute-stream",
},
]);
let dialogTriggered = false;
const onDialog = async (dialog: { dismiss: () => Promise<void> }) => {
dialogTriggered = true;
await dialog.dismiss();
};
page.on("dialog", onDialog);
try {
await page.setViewportSize({ width: 1680, height: 900 });
await openAgentProfileSettings(page);
await openAgentProfileEditor(page, "One minute stream");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await page.getByTestId("agent-profile-cancel-button").click();
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
expect(dialogTriggered).toBe(false);
} finally {
page.off("dialog", onDialog);
await seed.restore();
}
});
});
@@ -757,6 +757,161 @@ test("pasting an assistant selection preserves literal underscores and authored
}
});
const QUOTE_BODY = [
"Draft for the team: **ship it** with [the notes](https://example.com/notes).",
"",
"> Nested reply.",
"",
"```ts",
"const quoted = 1;",
"```",
"",
"```mermaid",
"flowchart LR",
" Start --> Done",
"```",
"",
"Thanks!",
].join("\n");
const QUOTE_MARKDOWN = [
"Text before the quote.",
"",
...QUOTE_BODY.split("\n").map((line) => (line ? `> ${line}` : ">")),
"",
"> [!NOTE]",
"> Heads up before you paste.",
"",
"Text after the quote.",
].join("\n");
function assistantQuote(page: Page, index: number): Locator {
return assistantMessageBlocks(page).getByRole("blockquote").nth(index);
}
/** A quote's own control is its first, ahead of any nested quote's. */
function quoteCopyControl(quote: Locator): Locator {
return quote.getByRole("button", { name: "Copy quote" }).first();
}
async function copyQuote(quote: Locator): Promise<void> {
await quote.hover();
await quoteCopyControl(quote).click();
await expect(quote.getByRole("button", { name: "Copied" })).toBeVisible();
}
async function pasteIntoPlainAndRichFields(page: Page): Promise<{ plain: Locator; rich: Locator }> {
await page.evaluate(() => {
const fields = document.createElement("div");
fields.style.cssText = "position: fixed; bottom: 0; left: 0; z-index: 10000; background: white";
const plainText = document.createElement("textarea");
plainText.setAttribute("aria-label", "Plain text paste");
const richText = document.createElement("div");
richText.contentEditable = "true";
richText.setAttribute("role", "textbox");
richText.setAttribute("aria-label", "Rich text paste");
fields.append(plainText, richText);
document.body.append(fields);
});
const plain = page.getByRole("textbox", { name: "Plain text paste" });
await plain.focus();
await page.keyboard.press("ControlOrMeta+v");
const rich = page.getByRole("textbox", { name: "Rich text paste" });
await rich.focus();
await page.keyboard.press("ControlOrMeta+v");
return { plain, rich };
}
test("a quote's copy control copies only that quote's body", async ({ context, page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "assistant-quote-copy-",
title: "Assistant quote copy",
initialPrompt: "Render the quote fixture.",
featureValues: { mockAssistantResponse: QUOTE_MARKDOWN },
});
try {
await allowRichClipboard(context);
await agent.client.waitForAgentUpsert(
agent.agentId,
(snapshot) => snapshot.status === "idle",
30_000,
);
await openAgentRoute(page, agent);
const quote = assistantQuote(page, 0);
const nested = assistantQuote(page, 1);
await expect(quote).toContainText("Thanks!");
await test.step("an admonition has no copy control", async () => {
await expect(assistantMessageBlocks(page)).toContainText("Heads up before you paste.");
await expect(
assistantMessageBlocks(page).getByRole("button", { name: "Copy quote" }),
).toHaveCount(2);
});
await test.step("the control appears on hover or keyboard focus", async () => {
const control = quoteCopyControl(quote);
await expect(control).toHaveCSS("opacity", "0");
await quote.hover();
await expect(control).toHaveCSS("opacity", "1");
await page.mouse.move(0, 0);
await expect(control).toHaveCSS("opacity", "0");
await control.focus();
await expect(control).toHaveCSS("opacity", "1");
await control.blur();
});
await test.step("copying the quote takes its body, with a diagram as its fence", async () => {
await expect(quote.getByRole("img", { name: "Diagram" })).toBeVisible({ timeout: 30_000 });
await copyQuote(quote);
const copied = await readRichClipboard(page);
expect(copied.plainText).toBe(QUOTE_BODY);
expect(copied.html).toContain("<strong>ship it</strong>");
expect(copied.html).toContain("<blockquote>");
});
await test.step("the copy pastes as Markdown and as rich text", async () => {
const { plain, rich } = await pasteIntoPlainAndRichFields(page);
await expect(plain).toHaveValue(QUOTE_BODY);
await expect(rich.locator("strong")).toHaveText("ship it");
await expect(rich.getByRole("link", { name: "the notes" })).toHaveAttribute(
"href",
"https://example.com/notes",
);
await expect(rich).not.toContainText("Text before the quote.");
});
await test.step("a nested quote copies only itself", async () => {
await copyQuote(nested);
await expect
.poll(async () => (await readRichClipboard(page)).plainText)
.toBe("Nested reply.");
});
await test.step("a code block in the quote keeps its own copy", async () => {
const code = quote.getByText("const quoted = 1;", { exact: true });
await code.hover();
await quote.getByRole("button", { name: "Copy code" }).first().click();
await expect.poll(() => readPlainClipboard(page)).toBe("const quoted = 1;");
});
await test.step("a phone-sized layout shows the control above the full-width text", async () => {
await page.mouse.move(0, 0);
await page.setViewportSize({ width: 390, height: 844 });
const control = quoteCopyControl(quote);
await expect(control).toHaveCSS("opacity", "1");
const controlBox = await control.boundingBox();
const firstLine = await quote.getByText(/^Draft for the team/).boundingBox();
expect(controlBox && firstLine).toBeTruthy();
// The text starts below the control instead of wrapping short of it.
expect(firstLine!.y).toBeGreaterThanOrEqual(controlBox!.y + controlBox!.height);
expect(firstLine!.x + firstLine!.width).toBeGreaterThan(controlBox!.x);
});
} finally {
await agent.cleanup();
}
});
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
context,
page,
@@ -1,4 +1,5 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { type Locator, type Page } from "@playwright/test";
@@ -498,6 +499,56 @@ test("Changes offers Push for a branch that was never pushed and the push sets i
});
});
test("Changes pushes and pulls a branch whose only remote is not named origin", async ({
page,
}) => {
const workspace = await createWorkspaceWithRemote((repoPath) => {
execFileSync("git", ["remote", "rename", "origin", "doras-mono"], { cwd: repoPath });
// git pull stops on a branch that is both ahead and behind until it is told how to combine them.
execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoPath });
});
await openWorkspaceChangesSurface(page, workspace);
const primary = page.getByTestId("changes-primary-cta");
await test.step("a branch that is ahead offers Push and the push updates the remote", async () => {
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
commitAllWithGit(workspace.repoPath, "Local work");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1]");
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toContain("Local work");
await expectNoGitActionLeft(page);
});
await test.step("a branch that is behind offers Pull and the pull brings the commits in", async () => {
pushTeammateCommits(workspace, ["Teammate one", "Teammate two"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(localBranchSubjects(workspace)).toEqual(
expect.arrayContaining(["Local work", "Teammate one", "Teammate two"]),
);
await expectNoGitActionLeft(page);
});
await test.step("a branch that is ahead and behind pulls and then pushes", async () => {
await writeFile(path.join(workspace.repoPath, "tracked.ts"), "export const tracked = 3;\n");
commitAllWithGit(workspace.repoPath, "More local work");
pushTeammateCommits(workspace, ["Teammate three", "Teammate four"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1, behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await page.getByTestId("changes-primary-cta-caret").click();
await page.getByTestId("changes-menu-pull-and-push").click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toEqual(
expect.arrayContaining(["More local work", "Teammate three", "Teammate four"]),
);
await expectNoGitActionLeft(page);
});
});
test("Changes selects exact local and remote bases and retains the selection after reload", async ({
page,
}, testInfo) => {
@@ -2202,6 +2253,79 @@ function remoteBranchHead(workspace: RemoteWorkspace, branch: string): string |
return line ? (line.split("\t")[0] ?? null) : null;
}
// The branch line of `git status -sb`, such as "## main...origin/main [ahead 1, behind 2]".
function trackingStatus(workspace: RemoteWorkspace): string {
const status = execFileSync("git", ["status", "-sb"], {
cwd: workspace.repoPath,
encoding: "utf8",
});
return status.split("\n")[0] ?? "";
}
// Neither ahead nor behind, which a push reaches only after the remote accepted it.
async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void> {
await expect
.poll(() => trackingStatus(workspace), { timeout: 30_000 })
.toMatch(/^## [^ ]+\.\.\.[^ ]+$/);
}
// A clean main that is in sync with its remote has no git action, so the button is gone.
async function expectNoGitActionLeft(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
}
function localBranchSubjects(workspace: RemoteWorkspace): string[] {
return commitSubjects(workspace.repoPath, "HEAD");
}
function remoteBranchSubjects(workspace: RemoteWorkspace, branch: string): string[] {
return commitSubjects(workspace.remotePath, branch);
}
function commitSubjects(repoPath: string, revision: string): string[] {
const log = execFileSync("git", ["log", "--format=%s", revision], {
cwd: repoPath,
encoding: "utf8",
});
return log.trim().split("\n");
}
// Paseo fetches only origin in the background, so the checkout learns about another remote's
// commits when the user fetches it.
function fetchRemote(workspace: RemoteWorkspace, remoteName: string): void {
execFileSync("git", ["fetch", "--quiet", remoteName], { cwd: workspace.repoPath });
}
// Lands commits on the remote's main from a second clone, as a teammate's push does.
function pushTeammateCommits(workspace: RemoteWorkspace, subjects: string[]): void {
const clonePath = mkdtempSync(path.join(path.dirname(workspace.repoPath), "changes-teammate-"));
try {
execFileSync("git", ["clone", "--quiet", workspace.remotePath, clonePath]);
for (const subject of subjects) {
execFileSync(
"git",
[
"-c",
"user.name=Teammate",
"-c",
"user.email=teammate@paseo.test",
"-c",
"commit.gpgsign=false",
"commit",
"--quiet",
"--allow-empty",
"-m",
subject,
],
{ cwd: clonePath },
);
}
execFileSync("git", ["push", "--quiet", "origin", "HEAD:main"], { cwd: clonePath });
} finally {
rmSync(clonePath, { recursive: true, force: true });
}
}
// Empty until the branch has an upstream.
function branchUpstream(workspace: RemoteWorkspace, branch: string): string {
return execFileSync(
@@ -4,7 +4,7 @@ import { test, expect, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
addProjectFlowInput,
chooseAddProjectMethod,
addProjectFlowSubmit,
openAddProjectFlow,
} from "../support/helpers/add-project-flow";
import { expectOpenedProject } from "../support/helpers/project-picker-ui";
@@ -53,7 +53,6 @@ async function removeProjectFromSidebar(page: Page, projectViewKey: string): Pro
async function addProjectFromPicker(page: Page, projectPath: string): Promise<string> {
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
const input = addProjectFlowInput(page);
await input.fill(projectPath);
@@ -85,7 +84,6 @@ test.describe("Project picker search", () => {
await gotoAppShell(page);
await waitForSidebarProjectListReady(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
const input = addProjectFlowInput(page);
await input.fill(projectPickerFixture.fuzzyQuery);
@@ -93,6 +91,7 @@ test.describe("Project picker search", () => {
const suggestion = page.getByText(projectPickerFixture.projectName, { exact: false }).first();
await expect(suggestion).toBeVisible({ timeout: 30_000 });
await suggestion.click();
await addProjectFlowSubmit(page).click();
const projectId = await expectOpenedProject(page, projectPickerFixture.projectName);
projectPickerFixture.rememberProjectId(projectId);
@@ -104,13 +103,11 @@ test.describe("Project picker search", () => {
await gotoAppShell(page);
await waitForSidebarProjectListReady(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
const input = addProjectFlowInput(page);
await input.fill("paseo-loading-state-no-match");
await expect(page.getByText("Start typing a path", { exact: true })).toHaveCount(0);
await expect(page.getByText("Loading...", { exact: true })).toBeVisible();
await expect(page.getByText("Searching...", { exact: true })).toBeVisible();
});
});
@@ -4,12 +4,15 @@
// never swallow entity tabs or lose the user's focus, and
// 2) splitting a tab out of a pane leaves a New tab behind, and the app must stay
// interactive in the [agent | New | explorer] state.
import { writeFileSync } from "node:fs";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { gotoWorkspace } from "../support/helpers/launcher";
import { seedCorruptedWorkspaceLayout } from "../support/helpers/workspace-layout";
import {
openChangesTreePanel,
openFilesPanel,
waitForWorkspaceTabsVisible,
} from "../support/helpers/workspace-tabs";
@@ -317,3 +320,75 @@ test("reloading a saved hidden generated Explorer recovers a usable workspace",
await gotoWorkspace(page, otherWorkspace.workspaceId);
await expect(draftTabChip(page)).toHaveCount(1);
});
test("dragging a file tab into a split returns the previous pane to the tab you came from", async ({
page,
withWorkspace,
e2eWorkerClient,
}) => {
const workspace = await withWorkspace({ prefix: "split-prev-tab-focus-" });
writeFileSync(path.join(workspace.repoPath, "notes.md"), "# Notes\nhello\n");
const agentA = await e2eWorkerClient.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Agent A",
});
const agentB = await e2eWorkerClient.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Agent B",
});
await gotoWorkspace(page, workspace.workspaceId);
await waitForWorkspaceTabsVisible(page);
const mainPane = page.getByTestId("workspace-pane-main");
await expect(mainPane.getByTestId(`workspace-tab-agent_${agentA.id}`)).toBeVisible({
timeout: 30_000,
});
await expect(mainPane.getByTestId(`workspace-tab-agent_${agentB.id}`)).toBeVisible({
timeout: 30_000,
});
const initialTabs = await mainPane
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-context-"])')
.evaluateAll((els) => els.map((el) => el.getAttribute("data-testid")));
const firstTab = mainPane.getByTestId(initialTabs[0]!);
const secondTab = mainPane.getByTestId(initialTabs[1]!);
// Open FILE while on B so B is the birth parent, then navigate A -> FILE before splitting.
await secondTab.click({ position: { x: 12, y: 13 } });
await expect(secondTab).toHaveAttribute("aria-selected", "true");
await openFilesPanel(page);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText("notes.md", { exact: true })
.click();
const fileTab = mainPane
.locator('[data-testid^="workspace-tab-file_"]:not([data-testid^="workspace-tab-context-"])')
.first();
await expect(fileTab).toBeVisible({ timeout: 15_000 });
await firstTab.click({ position: { x: 12, y: 13 } });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
await fileTab.click({ position: { x: 12, y: 13 } });
await expect(fileTab).toHaveAttribute("aria-selected", "true");
const mainBox = await mainPane.boundingBox();
if (!mainBox) throw new Error("mainPane has no bounding box");
await dragChipTo(page, fileTab, {
x: mainBox.x + mainBox.width * 0.92,
y: mainBox.y + mainBox.height * 0.5,
});
await expect(
page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true }),
).toHaveCount(2, { timeout: 10_000 });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
await expect(secondTab).toHaveAttribute("aria-selected", "false");
});
@@ -1,17 +1,10 @@
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
interface DragMeasurement {
observer: MutationObserver;
stylesheetMutations: number;
}
declare global {
interface Window {
__PASEO_EXPLORER_DRAG_MEASUREMENT__?: DragMeasurement;
}
}
import {
readSharedStylesheetChanges,
rememberSharedStylesheet,
} from "../support/helpers/shared-stylesheet";
async function waitForResizePaint(page: Page): Promise<void> {
await page.evaluate(
@@ -23,23 +16,8 @@ async function waitForResizePaint(page: Page): Promise<void> {
}
async function beginResizeMeasurement(page: Page): Promise<void> {
await page.evaluate(() => {
const stylesheet = document.getElementById("unistyles-web");
if (!stylesheet) throw new Error("Shared stylesheet is missing");
globalThis.__PASEO_RESET_RENDER_PROFILE__!();
const measurement: DragMeasurement = {
stylesheetMutations: 0,
observer: new MutationObserver((records) => {
measurement.stylesheetMutations += records.length;
}),
};
measurement.observer.observe(stylesheet, {
childList: true,
subtree: true,
characterData: true,
});
window.__PASEO_EXPLORER_DRAG_MEASUREMENT__ = measurement;
});
await page.evaluate(() => globalThis.__PASEO_RESET_RENDER_PROFILE__!());
await rememberSharedStylesheet(page);
}
async function previewExplorerResize(page: Page, distance: number) {
@@ -61,16 +39,14 @@ async function previewExplorerResize(page: Page, distance: number) {
await waitForResizePaint(page);
}
const during = (await explorer.boundingBox())!.width;
const measurement = await page.evaluate(() => {
const state = window.__PASEO_EXPLORER_DRAG_MEASUREMENT__!;
state.observer.disconnect();
return {
stylesheetMutations: state.stylesheetMutations,
paneRenders: Object.entries(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {})
const measurement = {
stylesheetChanges: await readSharedStylesheetChanges(page),
paneRenders: await page.evaluate(() =>
Object.entries(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {})
.filter(([id]) => id.startsWith("SplitPaneView:"))
.reduce((sum, [, reasons]) => sum + (reasons.render ?? 0), 0),
};
});
),
};
await page.mouse.up();
await waitForResizePaint(page);
const after = (await explorer.boundingBox())!.width;
@@ -92,7 +68,7 @@ async function expectExplorerWidthSurvivesReload(page: Page, width: number): Pro
await expect.poll(async () => (await explorer.boundingBox())?.width).toBeCloseTo(width, 0);
}
test("Explorer drag previews without rerendering panes or rewriting the shared stylesheet", async ({
test("Explorer drag previews without rerendering panes or changing the shared stylesheet", async ({
page,
withWorkspace,
}) => {
@@ -117,9 +93,9 @@ test("Explorer drag previews without rerendering panes or rewriting the shared s
).toBe(true);
const grown = await previewExplorerResize(page, -100);
const shrunk = await previewExplorerResize(page, 50);
expect(grown.stylesheetMutations).toBe(0);
expect(grown.stylesheetChanges).toEqual({ added: 0, removed: 0, edited: 0, rebuilt: 0 });
expect(grown.paneRenders).toBe(0);
expect(shrunk.stylesheetMutations).toBe(0);
expect(shrunk.stylesheetChanges).toEqual({ added: 0, removed: 0, edited: 0, rebuilt: 0 });
expect(shrunk.paneRenders).toBe(0);
await expectExplorerWidthSurvivesReload(page, shrunk.width);
});
@@ -4,6 +4,7 @@ import {
addConnectedHostAndReload,
chooseHostBadgeDisplay,
chooseHostColor,
chooseHostIcon,
expectHostAppearancePreview,
expectHostBadgeIconOnly,
expectHostBadgeName,
@@ -115,12 +116,21 @@ test("customizes a host badge and preserves its appearance after reload", async
expect(widths.content).toBeLessThanOrEqual(widths.client);
});
await test.step("preview a color and apply it to the sidebar badge", async () => {
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
await openHostAppearanceSettings(page, badge.serverId);
await chooseHostColor(page, "Teal");
await chooseHostIcon(page, "Laptop");
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
await leaveHostAppearanceSettings(page);
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
await page.getByTestId("sidebar-hosts-trigger").click();
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
await expect(hostRow).toBeVisible();
await expect(hostRow).toContainText("Direct");
await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/);
await expect(hostRow).not.toContainText(/agents?/i);
await page.keyboard.press("Escape");
});
await test.step("keep the icon-only preference through reload", async () => {
@@ -145,3 +155,30 @@ test("customizes a host badge and preserves its appearance after reload", async
});
});
});
base(
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
async ({ page }) => {
await gotoAppShell(page);
const trigger = page.getByTestId("sidebar-hosts-trigger");
await expect(trigger).toBeVisible();
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
await trigger.click();
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
await expect(addHostButton).toBeVisible();
await addHostButton.focus();
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
await page.keyboard.press("Escape");
await expect(addConnectionDialog).toBeHidden();
// ArrowDown + Enter must also reach Add host from the host list.
await trigger.click();
await expect(addHostButton).toBeVisible();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
},
);
@@ -4,10 +4,15 @@ import { copyFile, mkdir, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { TestInfo } from "@playwright/test";
import type { FetchRecentProviderSessionsRequestMessage } from "@getpaseo/protocol/messages";
import { expect, test, type Page } from "../support/fixtures";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { addConnectedHostAndReload } from "../support/helpers/hosts";
import { ImportSessionFlow } from "../support/helpers/import-session";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import {
connectNewWorkspaceDaemonClient,
loadSessionMessageReaders,
openProjectViaDaemon,
type OpenedProject,
} from "../support/helpers/new-workspace";
@@ -20,16 +25,22 @@ const SCREENSHOT_DIRECTORY = path.join(
const claudeConfigDirectory = mkdtempSync(path.join(tmpdir(), "paseo-import-flow-claude-"));
const brokenProvider = "broken-acp";
const disabledProviders = {
codex: { enabled: false },
copilot: { enabled: false },
omp: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
antigravity: { enabled: false },
muse: { enabled: false },
};
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
codex: { enabled: false },
copilot: { enabled: false },
omp: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
...disabledProviders,
[brokenProvider]: {
extends: "acp",
label: "Broken ACP",
@@ -136,6 +147,120 @@ test("an open Import Session row keeps its age current", async ({ page }) => {
await expect(row).toContainText("4m ago");
});
test("shows listing failure details beside healthy sessions and retries the failed provider", async ({
page,
}, testInfo) => {
const frames = await loadSessionMessageReaders();
const requests: FetchRecentProviderSessionsRequestMessage[] = [];
const completed = new Set<string>();
page.on("websocket", (socket) => {
socket.on("framesent", ({ payload }) => {
const request = frames.client(payload);
if (request?.type === "fetch_recent_provider_sessions_request") {
requests.push(request);
}
});
socket.on("framereceived", ({ payload }) => {
const response = frames.server(payload);
if (response?.type === "fetch_recent_provider_sessions_response") {
completed.add(response.payload.requestId);
}
});
});
const flow = new ImportSessionFlow(page);
for (const width of [1280, 390]) {
await flow.openWorkspace(scenario.project.workspaceId, { width, height: 844 });
await flow.openGlobally();
await flow.expectProviderError("Broken ACP");
const healthySession = page.getByTestId(
`import-session-session-claude-${scenario.importSessionId}`,
);
await expect(healthySession).toBeVisible();
await page.screenshot({ path: testInfo.outputPath(`listing-failure-${width}.png`) });
await expect(page.getByTestId("import-session-provider-errors")).toContainText(
"missing-agent-command",
);
const requestOffset = requests.length;
await flow.retryProvider(brokenProvider, "Broken ACP");
await expect
.poll(() => requests.slice(requestOffset).map((request) => request.providers))
.toEqual([[brokenProvider]]);
const retriedRequest = requests[requestOffset];
if (!retriedRequest) throw new Error("Retry did not send a provider listing request");
await expect.poll(() => completed.has(retriedRequest.requestId)).toBe(true);
await expect(page.getByTestId(`import-session-retry-${brokenProvider}`)).toBeEnabled();
await expect(page.getByTestId("import-session-provider-errors")).toContainText(
"missing-agent-command",
);
await expect(healthySession).toBeVisible();
await page.screenshot({ path: testInfo.outputPath(`listing-failure-retry-${width}.png`) });
await flow.close();
}
});
test("Import Session keeps listings tied to their host during a switch and a pending import", async ({
page,
}) => {
const secondaryHost = await startIsolatedHostDaemon("import-session-secondary", {
config: {
agents: {
providers: {
...disabledProviders,
claude: { enabled: false },
[brokenProvider]: {
extends: "acp",
label: "Broken ACP",
command: ["missing-secondary-command", "acp"],
},
},
},
},
});
try {
const gate = await installDaemonWebSocketGate(page);
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 1280, height: 844 });
await addConnectedHostAndReload(page, {
serverId: secondaryHost.serverId,
port: secondaryHost.port,
label: "Second import host",
primaryLabel: "First import host",
});
await flow.chooseHostForImport("First import host");
await expect(page.getByText(/missing-agent-command/)).toBeVisible();
await flow.close();
await flow.chooseHostForImport("Second import host");
await expect(page.getByText(/missing-secondary-command/)).toBeVisible();
await expect(page.getByText(/missing-agent-command/)).toHaveCount(0);
await flow.close();
await test.step("returning to the original host omits the session imported during the switch", async () => {
const sessionId = "fixture-root-04";
await flow.chooseHostForImport("First import host");
gate.holdNextClientRequest("import_agent_request");
await flow.startImport(sessionId);
await gate.waitForHeldClientRequest();
await flow.close();
await flow.chooseHostForImport("Second import host");
await flow.expectProviderError("Broken ACP");
gate.releaseHeldClientRequest();
await flow.expectClosed();
await flow.chooseHostForImport("First import host");
await flow.revealSession("fixture-worktree");
await flow.expectSessionUnavailable(sessionId);
await flow.close();
await flow.expectTranscript("Review fixture item 4", "Fixture response 4");
});
} finally {
await secondaryHost.close();
}
});
test("captures the compact import-session journey", async ({ page }, testInfo) => {
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 390, height: 844 });
@@ -378,7 +503,13 @@ async function seedClaudeSessions(input: {
unrelatedDirectory: string;
importSessionId: string;
}): Promise<number> {
const sessions = [
const sessions: {
cwd: string;
id: string;
title: string;
prompt: string;
answer?: string;
}[] = [
{
cwd: input.projectRoot,
id: input.importSessionId,
@@ -403,6 +534,7 @@ async function seedClaudeSessions(input: {
id: `fixture-root-${String(index + 1).padStart(2, "0")}`,
title: `Root session ${String(index + 1).padStart(2, "0")}`,
prompt: index === 7 ? "Investigate invoice rendering" : `Review fixture item ${index + 1}`,
...(index === 3 ? { answer: "Fixture response 4" } : {}),
})),
];
const newest = Date.now() - 60_000;
@@ -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,
}) => {
@@ -55,7 +55,7 @@ import {
import { getServerId } from "../support/helpers/server-id";
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { chooseAddProjectMethod, expectAddProjectPage } from "../support/helpers/add-project-flow";
import { expectAddProjectTab } from "../support/helpers/add-project-flow";
import { seedSavedSettingsHosts } from "../support/helpers/settings";
import {
expectSidebarWorkspaceSelected,
@@ -291,8 +291,7 @@ test.describe("New workspace flow", () => {
await expect(addProject).toContainText(/(?:⌘|Ctrl\+)O/);
await addProject.click();
await expectAddProjectPage(page, "method");
await chooseAddProjectMethod(page, "directory-search");
await expectAddProjectTab(page, "existing");
} finally {
await repo.cleanup();
}
@@ -372,6 +372,25 @@ test.describe("Plugin sidebar items", () => {
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
});
test("a plugin screen keeps the sidebar toggle before its title", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
await runCommand(page, "Open plugin workspaces");
await expect(screenTitle(page)).toHaveText("Workspaces");
await page.keyboard.press("ControlOrMeta+b");
await expect(page.getByTestId("sidebar-global-new-workspace")).not.toBeVisible();
await expect(visibleTestId(page, "menu-button")).toBeVisible();
const toggle = await boxOf(visibleTestId(page, "menu-button"));
const title = await boxOf(screenTitle(page));
expect(toggle.x + toggle.width).toBeLessThanOrEqual(title.x);
await qaScreenshot(page, "plugin-screen-sidebar-collapsed");
await visibleTestId(page, "menu-button").click();
await expect(page.getByTestId("sidebar-global-new-workspace")).toBeVisible();
});
test("a header row's shortcut hint presses the row", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -1,6 +1,12 @@
import { test } from "../support/fixtures";
import { expect, test } from "../support/fixtures";
import {
expectChatHistoryAttachment,
forkMostRecentAssistantTurnToNewTab,
observeForkAttachment,
} from "../support/helpers/assistant-fork";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import {
ASSISTANT_TEXT,
withTimelinePlugin,
viewInlineThinkingExample,
requestPluginTimeline,
@@ -55,3 +61,24 @@ test("inline-thinking example renders a streamed thought through host UI", async
}, info) => {
await viewInlineThinkingExample(page, info);
});
test("plugin-transformed assistant reply keeps copy, fork, and turn duration in its footer", async ({
page,
}, info) => {
const forkAttachment = observeForkAttachment(page);
await withTimelinePlugin(page, info, "assistant", async (agent) => {
await requestPluginTimeline(agent);
await agent.client.waitForFinish(agent.agentId, 30_000);
await expectWholeCompletedCard(page);
const footer = page.getByTestId("turn-footer").last();
await expect(footer).toBeVisible();
await expect(footer.getByRole("button", { name: "Copy turn" })).toBeVisible();
await expect(footer.getByRole("button", { name: "Fork chat from here" })).toBeVisible();
await expect(footer.getByText(/^Worked for /)).toBeVisible();
await forkMostRecentAssistantTurnToNewTab(page);
await expectChatHistoryAttachment(page);
expect(await forkAttachment.waitForText()).toContain(ASSISTANT_TEXT);
});
});
@@ -46,11 +46,7 @@ import {
} from "../support/helpers/project-settings";
import { gotoAppShell } from "../support/helpers/app";
import { openCompactSettings } from "../support/helpers/settings";
import {
addProjectFlowInput,
chooseAddProjectMethod,
openAddProjectFlow,
} from "../support/helpers/add-project-flow";
import { addProjectFlowInput, openAddProjectFlow } from "../support/helpers/add-project-flow";
import { createTempGitRepo } from "../support/helpers/workspace";
import {
buildOpenProjectRoute,
@@ -167,7 +163,6 @@ async function readProjectConfigFile(project: ProjectsSettingsProject): Promise<
async function addProjectFromSidebar(page: Page, projectPath: string): Promise<string> {
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
const input = addProjectFlowInput(page);
await input.fill(projectPath);
@@ -65,8 +65,7 @@ import {
openSettingsHostSection,
removeCurrentHostFromSettings,
openSidebarHostPicker,
sidebarHostSettingsButton,
expectStandaloneSidebarHostSettingsButton,
sidebarHostRowButton,
activateSidebarHostSettingsWithKeyboard,
bindCommandCenterToEnter,
} from "../support/helpers/settings";
@@ -192,17 +191,16 @@ test.describe("Settings sidebar scroll position", () => {
});
test.describe("Settings sidebar navigation", () => {
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
await openWorkspace(page, workspace);
await openSidebarHostPicker(page);
await expectStandaloneSidebarHostSettingsButton(page);
await sidebarHostSettingsButton(page).click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
await bindCommandCenterToEnter(page);
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
await openWorkspace(page, workspace);
@@ -566,7 +564,7 @@ test.describe("Settings — compact master-detail", () => {
await openWorkspace(page, workspace);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await page.getByTestId("sidebar-hosts-trigger").click();
await page.getByRole("button", { name: /Open .* settings/ }).click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
@@ -25,6 +25,10 @@ import { projectEquivalenceViewKey } from "../support/helpers/project-view-key";
import { escapeRegex } from "../support/helpers/regex";
import { openFilesPanel } from "../support/helpers/workspace-tabs";
import { seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
readSharedStylesheetChanges,
rememberSharedStylesheet,
} from "../support/helpers/shared-stylesheet";
const GITHUB_REMOTE_URL = "https://github.com/test-owner/test-repo.git";
@@ -429,6 +433,32 @@ test.describe("Sidebar workspace list", () => {
}
});
test("workspace hover card opens and closes without rebuilding the shared stylesheet", async ({
page,
}) => {
const workspace = await seedWorkspace({ repoPrefix: "sidebar-hover-stylesheet-" });
try {
await gotoAppShell(page);
await waitForSidebarProject(page, path.basename(workspace.repoPath));
await movePointerAwayFromWorkspaceHoverCard(page);
await rememberSharedStylesheet(page);
await openWorkspaceHoverCard(page, workspace.workspaceId);
const opened = await readSharedStylesheetChanges(page);
// The card brings styles nothing else on screen uses, so the stylesheet has to grow.
expect(opened.added).toBeGreaterThan(0);
expect(opened.rebuilt).toBe(0);
await rememberSharedStylesheet(page);
await movePointerAwayFromWorkspaceHoverCard(page);
await expectWorkspaceHoverCardClosed(page);
expect((await readSharedStylesheetChanges(page)).rebuilt).toBe(0);
} finally {
await workspace.cleanup();
}
});
test("workspace hover card closes when the pointer leaves a clicked row", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "sidebar-hover-click-leave-" });
+39 -4
View File
@@ -1,9 +1,11 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import path from "node:path";
import {
expectTimelinePromptVisible,
holdOlderHistoryPages,
scrollTimelineRowIntoView,
userScrollsTimelineToHistoryStart,
waitForTimelineGeometryToSettle,
} from "../support/helpers/timeline-pagination";
import { getActiveTabTestId } from "../support/helpers/launcher";
import type { Page, Locator } from "@playwright/test";
@@ -491,6 +493,39 @@ async function seedWholeTurnHistory() {
return agent;
}
/** Read every command across the scroll window, without requiring offscreen rows to mount. */
async function expectExpandedCommandsReadable(page: Page, count: number) {
const timeline = page.getByTestId("agent-chat-scroll");
const commands = new Set<number>();
await timeline.hover();
await waitForTimelineGeometryToSettle(page);
for (let step = 0; step < count && commands.size < count; step += 1) {
const labels = await timeline
.getByRole("button", { name: /echo stress-\d+/ })
.allTextContents();
for (const label of labels) {
const command = /echo stress-(\d+)/.exec(label);
if (command) commands.add(Number(command[1]));
}
if (commands.size < count) {
await page.mouse.wheel(0, 300);
await waitForTimelineGeometryToSettle(page);
}
}
expect([...commands].sort((a, b) => a - b)).toEqual(
Array.from({ length: count }, (_, index) => index),
);
}
async function returnToExpandedSummary(page: Page, summary: Locator) {
await page.getByTestId("agent-chat-scroll").hover();
for (let step = 0; step < 120 && !(await summary.isVisible()); step += 1) {
await page.mouse.wheel(0, -300);
await waitForTimelineGeometryToSettle(page);
}
await scrollTimelineRowIntoView(page, summary);
}
async function expectInitialFillIsConcealed(page: Page) {
await expect(page.getByTestId("agent-initial-fill")).toBeVisible();
await expect(page.getByTestId("agent-chat-scroll")).toHaveCSS("opacity", "0");
@@ -564,14 +599,14 @@ test("loads complete long turns and preserves expansion while revealing older hi
).toBeVisible();
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
await latest.click();
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120);
await expectExpandedCommandsReadable(page, 120);
await userScrollsTimelineToHistoryStart(page);
await history.expectRequestedPages(3);
history.releasePage(3);
await page.getByTestId("scroll-to-bottom-button").click();
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120);
await expectTimelinePromptVisible(page, "Short 4: emit 1 coalesced agent stream updates");
await expectExpandedCommandsReadable(page, 120);
history.expectNoRepeatedEntries();
await scrollTimelineRowIntoView(page, latest);
await returnToExpandedSummary(page, latest);
await latest.click();
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
} finally {
@@ -15,8 +15,8 @@ press "id=\"model-provider-${PROVIDER_ID}\""
wait "id=\"compact-model-list\"" 3000
# The row's profile action sits inside Android's independent scroll viewport.
press "id=\"model-create-profile-${PROVIDER_ID}-${PROFILE_MODEL_ID}\""
wait "text=\"Add agent profile\"" 5000
# Closing the form keeps the remembered model: the tap did not also select the row.
back
wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000
wait "id=\"model-profile-created-toast\"" 5000
# Undo removes the created profile after selecting the model and closing the picker.
press "id=\"model-profile-created-undo\""
wait "id=\"combined-model-selector\"" 3000
close
@@ -1,73 +1,61 @@
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
export type AddProjectFlowPage =
| "host"
| "method"
| "directory-search"
| "github-search"
| "github-location"
| "new-directory-parent"
| "new-directory-name";
export type AddProjectMethod = "directory-search" | "browse" | "github" | "new-directory";
const METHOD_DESTINATIONS: Record<Exclude<AddProjectMethod, "browse">, AddProjectFlowPage> = {
"directory-search": "directory-search",
github: "github-search",
"new-directory": "new-directory-parent",
};
export type AddProjectTab = "existing" | "clone" | "new-folder";
export function addProjectFlow(page: Page): Locator {
return page.getByTestId("add-project-flow");
}
/** The current tab's search or name field. */
export function addProjectFlowInput(page: Page): Locator {
return page.getByTestId("add-project-flow-input");
}
export function addProjectFlowBack(page: Page): Locator {
return page.getByTestId("add-project-flow-back");
export function addProjectFlowTab(page: Page, tab: AddProjectTab): Locator {
return page.getByTestId(`add-project-flow-tab-${tab}`);
}
export function addProjectFlowHost(page: Page, serverId: string): Locator {
return page.getByTestId(`add-project-flow-host-${serverId}`);
export function addProjectFlowSubmit(page: Page): Locator {
return page.getByTestId("add-project-flow-submit");
}
export function addProjectFlowMethod(page: Page, method: AddProjectMethod): Locator {
return page.getByTestId(`add-project-flow-method-${method}`);
export function addProjectFlowHostTrigger(page: Page): Locator {
return page.getByTestId("add-project-flow-host-trigger");
}
export async function expectAddProjectPage(page: Page, kind: AddProjectFlowPage): Promise<Locator> {
const currentPage = page.getByTestId(`add-project-flow-page-${kind}`);
await expect(currentPage).toBeVisible({ timeout: 30_000 });
return currentPage;
export async function expectAddProjectTab(page: Page, tab: AddProjectTab): Promise<void> {
await expect(addProjectFlowTab(page, tab)).toHaveAttribute("aria-selected", "true", {
timeout: 30_000,
});
}
async function openAddProjectFlowSurface(
page: Page,
expectedPage: "host" | "method",
): Promise<void> {
/** Opens Add project from the sidebar; it starts on Existing with the search focused. */
export async function openAddProjectFlow(page: Page): Promise<void> {
await page.locator('[data-testid="sidebar-add-project"]:visible').click();
await expect(addProjectFlow(page)).toBeVisible({ timeout: 30_000 });
await expectAddProjectPage(page, expectedPage);
}
export async function openAddProjectFlow(page: Page): Promise<void> {
await openAddProjectFlowSurface(page, "method");
}
export async function openAddProjectHostSelection(page: Page): Promise<void> {
await openAddProjectFlowSurface(page, "host");
await expectAddProjectTab(page, "existing");
await expect(addProjectFlowInput(page)).toBeFocused();
}
export async function chooseAddProjectMethod(page: Page, method: AddProjectMethod): Promise<void> {
const option = addProjectFlowMethod(page, method);
await expect(option).toBeVisible();
await option.click();
if (method !== "browse") {
await expectAddProjectPage(page, METHOD_DESTINATIONS[method]);
}
export async function chooseAddProjectTab(page: Page, tab: AddProjectTab): Promise<void> {
await addProjectFlowTab(page, tab).click();
await expectAddProjectTab(page, tab);
}
export async function chooseAddProjectHost(page: Page, serverId: string): Promise<void> {
await addProjectFlowHostTrigger(page).click();
await page.getByTestId(`add-project-flow-host-${serverId}`).click();
}
/** Types a parent directory into the Location picker and uses it as typed. */
export async function chooseAddProjectLocation(page: Page, location: string): Promise<void> {
await page.getByTestId("add-project-flow-location").click();
await page.getByPlaceholder("Search folders or enter a path").last().fill(location);
await page.getByText("Use this folder", { exact: true }).click();
await expect(page.getByTestId("add-project-flow-location")).toContainText(
path.basename(location),
);
}
export async function expectNewWorkspaceForAddedProject(
@@ -114,8 +102,10 @@ export async function expectAddProjectResultVisible(page: Page, text: string): P
.toBe(true);
}
/** Presses Enter on the focused Add host button, which the sheet's own Enter must not swallow. */
export async function chooseAddHostFromProjectFlow(page: Page): Promise<void> {
await page.getByRole("button", { name: /Add host.*No connected hosts/ }).click();
await addProjectFlow(page).getByRole("button", { name: "Add host", exact: true }).focus();
await page.keyboard.press("Enter");
}
export async function navigateAndDismissAddProject(page: Page): Promise<void> {
@@ -142,8 +142,22 @@ export async function openAgentProfileSettings(page: Page): Promise<void> {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, serverId);
await page.getByRole("button", { name: "Agents", exact: true }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agents"));
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
}
/** Reach agent profiles on a compact viewport so Open project -> Settings -> Agent profiles are pushed. */
export async function openCompactAgentProfileSettings(page: Page): Promise<void> {
const serverId = getServerId();
await gotoAppShell(page);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
const settingsButton = page.locator('[data-testid="sidebar-settings"]:visible').first();
await expect(settingsButton).toBeVisible({ timeout: 30_000 });
await settingsButton.click();
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 30_000 });
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
}
@@ -156,7 +170,9 @@ export async function expectNoAgentProfiles(page: Page): Promise<void> {
// ─── Settings: the profile list ────────────────────────────────────────────
export function agentProfileRow(page: Page, name: string): Locator {
return page.locator('[data-testid^="agent-profile-row-"]').filter({ hasText: name });
return page
.locator('[data-testid^="agent-profile-row-"]')
.filter({ has: page.getByText(name, { exact: true }) });
}
export async function expectAgentProfile(
@@ -165,7 +181,9 @@ export async function expectAgentProfile(
): Promise<void> {
const row = agentProfileRow(page, expected.name);
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(row.getByText(expected.tags.join(" · "), { exact: true })).toBeVisible();
for (const tag of expected.tags) {
await expect(row).toContainText(tag);
}
if (expected.notes !== undefined) {
await expect(row.getByText(expected.notes, { exact: true })).toBeVisible();
}
@@ -177,7 +195,7 @@ export async function expectAgentProfileTagsGone(
): Promise<void> {
const row = agentProfileRow(page, input.name);
for (const tag of input.tags) {
await expect(row.getByText(tag, { exact: true })).toHaveCount(0);
await expect(row).not.toContainText(tag);
}
}
@@ -196,12 +214,22 @@ export async function expectAgentProfileOrder(page: Page, names: string[]): Prom
.toEqual(names);
}
async function openRowActionMenu(page: Page, name: string): Promise<void> {
const row = agentProfileRow(page, name);
await row.hover();
const trigger = row.locator('[data-testid^="agent-profile-menu-"]');
await expect(trigger).toBeVisible({ timeout: 15_000 });
await trigger.click();
}
export async function moveAgentProfileUp(page: Page, name: string): Promise<void> {
await agentProfileRow(page, name).getByRole("button", { name: "Move up", exact: true }).click();
await openRowActionMenu(page, name);
await page.getByRole("menuitem", { name: "Move up", exact: true }).click();
}
export async function moveAgentProfileDown(page: Page, name: string): Promise<void> {
await agentProfileRow(page, name).getByRole("button", { name: "Move down", exact: true }).click();
await openRowActionMenu(page, name);
await page.getByRole("menuitem", { name: "Move down", exact: true }).click();
}
/**
@@ -215,12 +243,13 @@ export async function removeAgentProfile(page: Page, name: string): Promise<void
await dialog.accept();
return message;
});
await agentProfileRow(page, name).getByRole("button", { name: "Remove", exact: true }).click();
await openRowActionMenu(page, name);
await page.getByRole("menuitem", { name: "Remove", exact: true }).click();
expect(await dialogMessage).toContain(`Remove "${name}"?`);
await expect(agentProfileRow(page, name)).toHaveCount(0, { timeout: 30_000 });
}
// ─── Settings: the edit modal ──────────────────────────────────────────────
// ─── Settings: the inspector drawer / edit sheet ───────────────────────────
export interface AgentProfileDraft {
name?: string;
@@ -231,62 +260,96 @@ export interface AgentProfileDraft {
notes?: string;
}
function editModal(page: Page): Locator {
return page.getByTestId("agent-profile-edit-modal");
function editSurface(page: Page): Locator {
return page.locator(
'[data-testid="agent-profile-drawer"], [data-testid="agent-profile-edit-modal"]',
);
}
async function chooseSelectFieldOption(
page: Page,
input: { field: "provider" | "model" | "mode" | "thinking"; option: string },
input: { field: "model" | "mode" | "thinking"; option: string },
): Promise<void> {
await editModal(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
await editSurface(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
const option = page
.getByTestId("combobox-desktop-container")
.getByRole("button", { name: input.option, exact: true });
await expect(option).toBeVisible({ timeout: 30_000 });
await option.click();
await expect(
page.getByRole("button", { name: `${capitalize(input.field)} (${input.option})` }),
).toBeVisible({ timeout: 30_000 });
}
function capitalize(value: string): string {
return value.charAt(0).toUpperCase() + value.slice(1);
async function ensureCustomizeExpanded(surface: Locator): Promise<void> {
const toggle = surface.getByTestId("agent-profile-customize-toggle");
if ((await toggle.count()) > 0 && (await toggle.isVisible())) {
await toggle.click();
}
}
async function chooseProfileModel(
page: Page,
input: { provider?: string; model?: string },
): Promise<void> {
await editSurface(page).getByTestId("agent-profile-model-trigger").click();
const container = page.getByTestId("combobox-desktop-container");
await expect(container).toBeVisible({ timeout: 30_000 });
if (input.provider) {
const providerRow = container.getByRole("button", {
name: new RegExp(escapeForRegex(input.provider)),
});
if ((await providerRow.count()) > 0 && (await providerRow.first().isVisible())) {
await providerRow.first().click();
}
}
const targetLabel = input.model ?? input.provider;
if (targetLabel) {
const option = container
.getByRole("button", { name: new RegExp(escapeForRegex(targetLabel)) })
.first();
await expect(option).toBeVisible({ timeout: 30_000 });
await option.click();
}
}
async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promise<void> {
const modal = editModal(page);
const surface = editSurface(page);
// Model first: CombinedModelSelector sets provider + model and auto-suggests defaults.
if (draft.model !== undefined || draft.provider !== undefined) {
await chooseProfileModel(page, { provider: draft.provider, model: draft.model });
}
if (draft.name !== undefined) {
await modal.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
await surface.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
}
// Provider first: it resets every provider-scoped field below it.
if (draft.provider !== undefined) {
await chooseSelectFieldOption(page, { field: "provider", option: draft.provider });
}
// Thinking after model: thinking levels hang off the model, and switching the
// model drops a level the new one does not offer.
if (draft.model !== undefined) {
await chooseSelectFieldOption(page, { field: "model", option: draft.model });
}
if (draft.thinking !== undefined) {
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
if (draft.thinking !== undefined || draft.mode !== undefined || draft.notes !== undefined) {
await ensureCustomizeExpanded(surface);
}
if (draft.mode !== undefined) {
await chooseSelectFieldOption(page, { field: "mode", option: draft.mode });
}
if (draft.thinking !== undefined) {
const thinkingContainer = surface.getByTestId("agent-profile-thinking-field");
const segmentButton = thinkingContainer.getByRole("button", {
name: draft.thinking,
exact: true,
});
if ((await segmentButton.count()) > 0) {
await segmentButton.click();
} else {
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
}
}
if (draft.notes !== undefined) {
await modal.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
await surface.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
}
}
async function saveAgentProfile(page: Page): Promise<void> {
await editModal(page).getByRole("button", { name: "Save", exact: true }).click();
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
await page.getByTestId("agent-profile-save-button").click();
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
}
export async function createAgentProfile(page: Page, draft: AgentProfileDraft): Promise<void> {
await page.getByRole("button", { name: "Add agent profile", exact: true }).click();
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
await page.getByTestId("agent-profiles-add-button").click();
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
await fillAgentProfileForm(page, draft);
await saveAgentProfile(page);
}
@@ -299,7 +362,7 @@ export async function createAgentProfileFromEmptyState(
.getByTestId("agent-profiles-card")
.getByRole("button", { name: "New profile", exact: true })
.click();
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
await fillAgentProfileForm(page, draft);
await saveAgentProfile(page);
}
@@ -309,46 +372,183 @@ export async function editAgentProfile(
name: string,
changes: AgentProfileDraft,
): Promise<void> {
await agentProfileRow(page, name)
.getByRole("button", { name: "Edit profile", exact: true })
.click();
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
await agentProfileRow(page, name).click();
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
await fillAgentProfileForm(page, changes);
await saveAgentProfile(page);
}
/** Opens the modal for a profile purely to read back what it stored. */
export async function openAgentProfileEditor(page: Page, name: string): Promise<void> {
await agentProfileRow(page, name).click();
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
}
export async function openCreateAgentProfileEditor(page: Page): Promise<void> {
await page.getByTestId("agent-profiles-add-button").click();
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
}
export async function fillAgentProfileName(page: Page, name: string): Promise<void> {
await page.getByRole("textbox", { name: "Name", exact: true }).fill(name);
}
export async function expectAgentProfileNameDraft(page: Page, name: string): Promise<void> {
await expect(page.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
}
export async function toggleAgentProfileCustomize(page: Page): Promise<void> {
await page.getByTestId("agent-profile-customize-toggle").click();
}
export async function fillAgentProfileNotes(page: Page, notes: string): Promise<void> {
await page.getByRole("textbox", { name: "When to use", exact: true }).fill(notes);
}
export async function expectAgentProfileNotesDraft(page: Page, notes: string): Promise<void> {
await expect(page.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(notes);
}
export async function saveOpenAgentProfile(page: Page): Promise<void> {
await saveAgentProfile(page);
}
export async function duplicateOpenAgentProfileWithConfirm(
page: Page,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.getByTestId("agent-profile-drawer-more").click();
await page.getByTestId("agent-profile-drawer-duplicate").click();
expect(await dialogMessage).toMatch(/discard|unsaved/i);
}
export async function openEditProfileFromModelRow(
page: Page,
input: { provider: string; modelId: string },
): Promise<void> {
const row = modelRow(page, input);
await row.hover();
const editButton = pickerViewport(page).getByTestId(
`model-edit-profile-${input.provider}-${input.modelId}`,
);
await expect(editButton).toBeVisible({ timeout: 30_000 });
await editButton.click();
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
}
export async function removeOpenModalAgentProfileWithConfirm(
page: Page,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.getByTestId("agent-profile-modal-remove-button").click();
expect(await dialogMessage).toMatch(/remove/i);
}
export async function switchSettingsSectionWithConfirm(
page: Page,
sectionName: string,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.getByRole("button", { name: sectionName, exact: true }).click();
expect(await dialogMessage).toMatch(/discard|unsaved/i);
}
export async function browserBackWithConfirm(
page: Page,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.goBack();
expect(await dialogMessage).toMatch(/discard|unsaved/i);
}
export async function browserHistoryJumpWithConfirm(
page: Page,
delta: number,
decision: "accept" | "dismiss",
): Promise<void> {
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
const message = dialog.message();
if (decision === "accept") {
await dialog.accept();
} else {
await dialog.dismiss();
}
return message;
});
await page.evaluate((step) => window.history.go(step), delta);
expect(await dialogMessage).toMatch(/discard|unsaved/i);
}
/** Opens the inspector for a profile purely to read back what it stored. */
export async function expectAgentProfileForm(
page: Page,
name: string,
expected: { provider?: string; model?: string; mode?: string; notes?: string },
): Promise<void> {
await agentProfileRow(page, name)
.getByRole("button", { name: "Edit profile", exact: true })
.click();
const modal = editModal(page);
await expect(modal).toBeVisible({ timeout: 30_000 });
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
const notesHint = modal.getByTestId("agent-profile-notes-field-hint");
await expect(notesHint).toHaveText(
"Helps agents choose this profile when starting another agent.",
);
await agentProfileRow(page, name).click();
const surface = editSurface(page);
await expect(surface).toBeVisible({ timeout: 30_000 });
await expect(surface.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
const notesHint = surface.getByTestId("agent-profile-notes-field-hint");
await expect(notesHint).toHaveText("Tells agents when to pick this profile");
expect(await notesHint.evaluate((element) => getComputedStyle(element).webkitLineClamp)).not.toBe(
"1",
);
for (const [field, value] of Object.entries(expected)) {
if (field === "notes") {
await expect(modal.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
value,
);
continue;
}
await expect(
modal.getByRole("button", { name: `${capitalize(field)} (${value})` }),
).toBeVisible({ timeout: 30_000 });
if (expected.model) {
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(expected.model);
} else if (expected.provider) {
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(
expected.provider,
);
}
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
if (expected.provider) {
await expect(surface).toContainText(expected.provider);
}
if (expected.mode) {
await expect(surface.getByTestId("agent-profile-mode-trigger")).toContainText(expected.mode);
}
if (expected.notes !== undefined) {
await expect(surface.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
expected.notes,
);
}
await surface.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
}
// ─── The model picker ──────────────────────────────────────────────────────
@@ -449,6 +649,41 @@ async function boxTop(locator: Locator): Promise<number> {
return box.y;
}
export async function searchModelPicker(page: Page, query: string): Promise<void> {
await pickerViewport(page).getByTestId("model-search-input").fill(query);
}
/** A search lists matching profiles first, then the matching models under their own heading. */
export async function expectProfileSearchResult(
page: Page,
input: { name: string; model?: { provider: string; modelId: string } },
): Promise<void> {
const viewport = pickerViewport(page);
const row = profilePickerRow(page, input.name);
await expect(row).toBeVisible({ timeout: 30_000 });
if (!input.model) {
await expect(viewport.getByText("Models", { exact: true })).toHaveCount(0);
return;
}
const matchedModel = modelRow(page, input.model);
await expect(viewport.getByText("Models", { exact: true })).toBeVisible();
await expect(matchedModel).toBeVisible();
expect(await boxTop(row)).toBeLessThan(await boxTop(matchedModel));
}
/** Wheel-scrolls the picker the way a pointer user would until the profile row is on screen. */
export async function expectProfileReachableByScrolling(page: Page, name: string): Promise<void> {
const row = profilePickerRow(page, name);
await expect(row).toBeAttached({ timeout: 30_000 });
const box = await pickerViewport(page).boundingBox();
if (!box) throw new Error("model picker has no layout box");
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await expect(async () => {
await page.mouse.wheel(0, 400);
await expect(row).toBeInViewport({ timeout: 500 });
}).toPass({ timeout: 15_000 });
}
export async function applyProfileFromPicker(page: Page, name: string): Promise<void> {
await profilePickerRow(page, name).click();
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
@@ -500,7 +735,10 @@ export async function expectModelRowProfileActionBesideRow(
await expect(row.getByRole("button")).toHaveCount(0);
}
/** The hover-revealed plus on an unprofiled model row opens a seeded profile form. */
/**
* The hover-revealed plus on an unprofiled model row saves the profile,
* selects the model immediately, closes the picker, and surfaces an Edit / Undo toast.
*/
export async function expectCreateProfileFromModelRow(
page: Page,
input: { provider: string; modelId: string; modelLabel: string },
@@ -513,14 +751,14 @@ export async function expectCreateProfileFromModelRow(
await modelRow(page, input).hover();
await expect(action).toHaveCSS("pointer-events", "auto");
await action.click();
const modal = editModal(page);
await expect(modal).toBeVisible({ timeout: 30_000 });
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(
input.modelLabel,
);
await expect(modal.getByRole("button", { name: `Model (${input.modelLabel})` })).toBeVisible();
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(modal).toHaveCount(0, { timeout: 30_000 });
const toast = page.getByTestId("model-profile-created-toast");
await expect(toast).toBeVisible({ timeout: 30_000 });
await expect(toast).toContainText(input.modelLabel);
// Undo removes the newly saved profile from the toast.
await toast.getByTestId("model-profile-created-undo").click();
await expect(toast).toHaveCount(0, { timeout: 30_000 });
}
export async function selectModelRow(
+10 -1
View File
@@ -132,7 +132,10 @@ export async function waitForConnectedHost(
): Promise<void> {
await page.getByTestId("sidebar-hosts-trigger").click();
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Local daemons render "Local" without repeating localhost:<port>; remote hosts render the endpoint.
await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 });
await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 });
await page.keyboard.press("Escape");
await expect(host).not.toBeVisible();
}
@@ -195,6 +198,12 @@ export async function chooseHostColor(page: Page, colorName: string): Promise<vo
await expect(page.getByRole("button", { name: `Color, ${colorName}` })).toBeVisible();
}
export async function chooseHostIcon(page: Page, iconName: string): Promise<void> {
await page.getByTestId("host-appearance-icon").click();
await page.getByRole("menuitem", { name: iconName, exact: true }).click();
await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible();
}
export async function chooseHostBadgeDisplay(
page: Page,
option: "Name" | "Icon only" | "Hidden",
@@ -137,13 +137,22 @@ export class ImportSessionFlow {
await this.expectProviderError(label);
await expect(this.page.getByRole("progressbar")).toHaveCount(0);
}
async importSession(id: string) {
async startImport(id: string) {
await this.revealSession(id);
await this.page.getByTestId(rowTestId(id)).click();
}
async importSession(id: string) {
await this.startImport(id);
await this.expectClosed();
}
async expectClosed() {
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0, {
timeout: 30_000,
});
}
async expectSessionUnavailable(id: string) {
await expect(this.page.getByTestId(rowTestId(id))).toHaveCount(0);
}
async expectTranscript(userText: string, assistantText: string) {
await expect(this.page.getByTestId("user-message").filter({ visible: true })).toContainText(
userText,
@@ -169,6 +178,13 @@ export class ImportSessionFlow {
await this.page.getByRole("button", { name: "Close", exact: true }).last().click();
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0);
}
async chooseHostForImport(hostLabel: string) {
const panel = await openCommandCenter(this.page);
await panel.getByTestId("command-center-input").fill("import");
await panel.getByText("Import session", { exact: true }).click();
await this.page.getByRole("dialog").getByRole("button", { name: hostLabel }).click();
await this.expectScope(`Sessions on ${hostLabel}`);
}
async expectCommandCenterMatch() {
const panel = await openCommandCenter(this.page);
await panel.getByTestId("command-center-input").fill("import");
@@ -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,
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import { addProjectFlow, addProjectFlowInput, chooseAddProjectMethod } from "./add-project-flow";
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
import { startIsolatedHostDaemon, type IsolatedHostDaemonOptions } from "./isolated-host-daemon";
@@ -122,7 +122,7 @@ export async function skipSetup(page: Page): Promise<void> {
export async function addProjectFromSetup(page: Page, projectPath: string): Promise<void> {
await setupModal(page).getByRole("button", { name: "Add project", exact: true }).click();
await expect(addProjectFlow(page)).toBeVisible({ timeout: 30_000 });
await chooseAddProjectMethod(page, "directory-search");
await expectAddProjectTab(page, "existing");
await addProjectFlowInput(page).fill(projectPath);
await page.keyboard.press("Enter");
await expect(addProjectFlow(page)).toHaveCount(0, { timeout: 30_000 });
+4 -14
View File
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
await page.getByRole("button", { name: "Hosts", exact: true }).click();
}
export function sidebarHostSettingsButton(page: Page) {
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
export function sidebarHostRowButton(page: Page) {
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
}
export async function bindCommandCenterToEnter(page: Page) {
@@ -32,20 +32,10 @@ export async function bindCommandCenterToEnter(page: Page) {
});
}
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
const gear = sidebarHostSettingsButton(page);
await expect(gear).toBeVisible();
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
true,
);
}
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
const host = sidebarHostRowButton(page);
await expect(host).toBeVisible();
await expect(host).toBeFocused();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Tab");
await expect(sidebarHostSettingsButton(page)).toBeFocused();
await page.keyboard.press("Enter");
}
@@ -0,0 +1,151 @@
import type { Page } from "@playwright/test";
/**
* The shared stylesheet is `#unistyles-web`: one rule per generated style class, for the whole app.
* Every change to it makes the browser restyle, and replacing a rule that is still in use restyles
* the entire document. A spec remembers the stylesheet, performs an interaction, and reads back
* everything that happened to it in between, including rules that came and went before the read.
*/
export interface SharedStylesheetChanges {
/** Rules inserted, counting ones deleted again before the read. */
added: number;
/** Rules deleted, counting ones inserted during the interaction. */
removed: number;
/** Rules whose declarations were changed in place. */
edited: number;
/** Rules for classes still in use that were thrown away and created again. */
rebuilt: number;
}
interface SharedStylesheetRule {
rule: CSSRule;
text: string;
}
interface SharedStylesheetWatch {
rules: Map<string, SharedStylesheetRule>;
added: number;
removed: number;
edited: number;
editedRules: Set<CSSRule>;
}
declare global {
interface Window {
__PASEO_SHARED_STYLESHEET_WATCH__?: SharedStylesheetWatch;
}
}
function readSharedStylesheetRules(): Map<string, SharedStylesheetRule> {
const tag = document.getElementById("unistyles-web");
if (!(tag instanceof HTMLStyleElement) || !tag.sheet) {
throw new Error("Shared stylesheet is missing");
}
const rules = new Map<string, SharedStylesheetRule>();
const collect = (list: CSSRuleList, group: string) => {
for (const rule of list) {
if (rule instanceof CSSStyleRule) {
rules.set(`${group}${rule.selectorText}`, { rule, text: rule.cssText });
} else if (rule instanceof CSSMediaRule) {
collect(rule.cssRules, `${rule.conditionText} `);
}
}
};
collect(tag.sheet.cssRules, "");
return rules;
}
// The CSSOM has no mutation events, so the watch wraps the calls that change a stylesheet and
// counts the ones that land in the shared stylesheet, including changes undone before the read.
// Chromium sets named properties such as `style.width` without an accessor the watch can wrap;
// reading the changes compares rule text to catch those. Installed once per page.
function installSharedStylesheetWatch(): void {
const marker = "__PASEO_SHARED_STYLESHEET_WATCHED__";
const flags = window as unknown as Record<string, boolean>;
if (flags[marker]) return;
flags[marker] = true;
const isShared = (sheet: CSSStyleSheet | null | undefined) => {
const tag = document.getElementById("unistyles-web");
return Boolean(sheet) && tag instanceof HTMLStyleElement && sheet === tag.sheet;
};
const watch = () => window.__PASEO_SHARED_STYLESHEET_WATCH__;
const wrapMethod = <Target>(
prototype: object,
name: string,
owner: (target: Target) => CSSStyleSheet | null | undefined,
record: (target: Target) => void,
) => {
const original = Reflect.get(prototype, name) as (...args: unknown[]) => unknown;
Reflect.set(prototype, name, function (this: Target, ...args: unknown[]) {
const result = original.apply(this, args);
if (isShared(owner(this))) record(this);
return result;
});
};
const countAdded = () => {
const current = watch();
if (current) current.added += 1;
};
const countRemoved = () => {
const current = watch();
if (current) current.removed += 1;
};
const countEdited = (style: CSSStyleDeclaration) => {
const current = watch();
if (!current) return;
current.edited += 1;
if (style.parentRule) current.editedRules.add(style.parentRule);
};
const sheetOf = (sheet: CSSStyleSheet) => sheet;
const groupSheet = (group: CSSGroupingRule) => group.parentStyleSheet;
const declarationSheet = (style: CSSStyleDeclaration) => style.parentRule?.parentStyleSheet;
wrapMethod(CSSStyleSheet.prototype, "insertRule", sheetOf, countAdded);
wrapMethod(CSSStyleSheet.prototype, "deleteRule", sheetOf, countRemoved);
wrapMethod(CSSGroupingRule.prototype, "insertRule", groupSheet, countAdded);
wrapMethod(CSSGroupingRule.prototype, "deleteRule", groupSheet, countRemoved);
wrapMethod(CSSStyleDeclaration.prototype, "setProperty", declarationSheet, countEdited);
wrapMethod(CSSStyleDeclaration.prototype, "removeProperty", declarationSheet, countEdited);
const cssText = Object.getOwnPropertyDescriptor(CSSStyleDeclaration.prototype, "cssText");
const setCssText = cssText?.set;
if (!cssText || !setCssText) throw new Error("CSSStyleDeclaration.cssText has no setter");
Object.defineProperty(CSSStyleDeclaration.prototype, "cssText", {
...cssText,
set(this: CSSStyleDeclaration, value: string) {
setCssText.call(this, value);
if (isShared(declarationSheet(this))) countEdited(this);
},
});
}
export async function rememberSharedStylesheet(page: Page): Promise<void> {
await page.evaluate(`(() => {
(${installSharedStylesheetWatch.toString()})();
window.__PASEO_SHARED_STYLESHEET_WATCH__ = {
rules: (${readSharedStylesheetRules.toString()})(),
added: 0,
removed: 0,
edited: 0,
editedRules: new Set(),
};
})()`);
}
export async function readSharedStylesheetChanges(page: Page): Promise<SharedStylesheetChanges> {
return page.evaluate(`(() => {
const watch = window.__PASEO_SHARED_STYLESHEET_WATCH__;
if (!watch) throw new Error("Shared stylesheet was not remembered");
const after = (${readSharedStylesheetRules.toString()})();
let edited = watch.edited;
let rebuilt = 0;
for (const [selector, { rule, text }] of after) {
const before = watch.rules.get(selector);
if (!before) continue;
if (before.rule !== rule) rebuilt += 1;
else if (before.text !== text && !watch.editedRules.has(rule)) edited += 1;
}
return { added: watch.added, removed: watch.removed, edited, rebuilt };
})()`);
}
+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' --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' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -0,0 +1,204 @@
import { useMemo } from "react";
import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { GitHubIcon } from "@/components/icons/github-icon";
import { FormTextInput } from "@/components/ui/form-field";
import { isWeb } from "@/constants/platform";
import type { Theme } from "@/styles/theme";
import { ICON_SIZE } from "@/styles/theme";
import type { AddProjectActions } from "./use-add-project-actions";
import type { AddProjectFlowState, AddProjectHost, GithubRepositoryChoice } from "./model";
import { LocationField } from "./location-field";
import {
buildManualGithubRepositoryChoices,
checkoutName,
joinDirectoryPath,
MANUAL_CHOICE_PREFIX,
} from "./options";
import { ResultList, type ResultRow } from "./result-list";
import { RESULTS_TEST_ID } from "./result-list-id";
import { useGithubRepositorySearch } from "./searches";
import { resolveActiveIndex, type AddProjectTabView } from "./tab-view";
const ThemedGitHubIcon = withUnistyles(GitHubIcon);
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const githubIcon = <ThemedGitHubIcon size={ICON_SIZE.md} uniProps={mutedColor} />;
/**
* The project the query names comes first: the search result that matches it exactly, or else
* the pasted URL or owner/repo as typed.
*/
function buildCloneChoices(
query: string,
found: GithubRepositoryChoice[],
): GithubRepositoryChoice[] {
const normalized = query.trim().toLowerCase();
const isExact = (repository: GithubRepositoryChoice) =>
repository.nameWithOwner.toLowerCase() === normalized ||
repository.cloneUrl.toLowerCase() === normalized;
const exact = found.filter(isExact);
if (exact.length === 0) return [...buildManualGithubRepositoryChoices(query), ...found];
return [...exact, ...found.filter((repository) => !isExact(repository))];
}
/** A choice built from the typed URL or owner/repo rather than from a search answer. */
function isTypedChoice(choice: GithubRepositoryChoice | undefined): boolean {
return choice?.id.startsWith(MANUAL_CHOICE_PREFIX) === true;
}
function cloneEmptyText(host: AddProjectHost, query: string): string {
if (!host.canSearchGithubRepositories) return "Paste a Git URL or owner/repo";
return query.trim() ? "No matching projects" : "Search GitHub or paste a Git URL";
}
export interface CloneTabView extends AddProjectTabView {
location: string;
destination: string;
}
const CLONE_UNAVAILABLE = "Update the host to clone projects";
export function useCloneTab(input: {
state: AddProjectFlowState;
host: AddProjectHost | null;
defaultLocation: string;
actions: AddProjectActions;
}): CloneTabView {
const { state, host, defaultLocation, actions } = input;
const { query } = state.clone;
const canClone = host?.canCloneGithubRepositories === true;
const search = useGithubRepositorySearch({
hostId: state.hostId,
query,
enabled: state.tab === "clone" && canClone && host?.canSearchGithubRepositories === true,
});
const choices = useMemo(
() => (canClone ? buildCloneChoices(query, search.items) : []),
[canClone, query, search.items],
);
const rows = useMemo<ResultRow[]>(
() =>
choices.map((repository) => ({
id: repository.id,
title: repository.cloneProtocol
? `${repository.nameWithOwner} via ${repository.cloneProtocol.toUpperCase()}`
: repository.nameWithOwner,
subtitle: repository.description,
icon: GitHubIcon,
testID: `add-project-flow-repository-${repository.id}`,
})),
[choices],
);
// While the search for new text runs, the rows on screen answer the old text. None of them is
// picked until the new answer arrives or the user picks one, unless it is the typed URL.
const awaitingRows =
search.pending && state.clone.selectedId === null && !isTypedChoice(choices[0]);
const activeIndex = awaitingRows ? -1 : resolveActiveIndex(rows, state.clone.selectedId);
const repository = choices[activeIndex] ?? null;
const location = state.clone.location ?? defaultLocation;
const destination = repository
? joinDirectoryPath(location, checkoutName(repository.nameWithOwner))
: location;
return useMemo<CloneTabView>(() => {
const unavailable = host && canClone ? null : CLONE_UNAVAILABLE;
let notice: AddProjectTabView["notice"] = null;
if (!host || unavailable) notice = { kind: "empty", text: CLONE_UNAVAILABLE };
else if (search.error) notice = { kind: "error", text: search.error };
else if (search.pending) notice = { kind: "pending", text: "Searching..." };
else notice = { kind: "empty", text: cloneEmptyText(host, query) };
return {
rows,
activeIndex,
notice,
unavailable,
location,
destination,
primary: {
label: "Clone project",
submit: repository ? () => actions.clone(repository, location) : null,
},
};
}, [
actions,
activeIndex,
canClone,
destination,
host,
location,
query,
repository,
rows,
search.error,
search.pending,
]);
}
export function CloneTab({
view,
query,
hostId,
recommendedPaths,
disabled,
autoFocus,
onQueryChange,
onSelectRow,
onLocationChange,
}: {
view: CloneTabView;
query: string;
hostId: string | null;
recommendedPaths: string[];
disabled: boolean;
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
autoFocus: boolean;
onQueryChange: (query: string) => void;
onSelectRow: (index: number) => void;
onLocationChange: (location: string) => void;
}) {
const editable = !disabled && !view.unavailable;
return (
<View style={styles.body}>
<FormTextInput
initialValue={query}
onChangeText={onQueryChange}
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
leading={githubIcon}
placeholder="Search GitHub or paste a Git URL"
accessibilityLabel="Search GitHub"
autoFocus={autoFocus}
autoCapitalize="none"
autoCorrect={false}
returnKeyType="go"
editable={editable}
testID="add-project-flow-input"
/>
<ResultList
rows={view.rows}
activeIndex={view.activeIndex}
notice={view.notice}
onSelect={onSelectRow}
disabled={disabled}
testID={RESULTS_TEST_ID}
/>
<LocationField
hostId={hostId}
location={view.location}
destination={view.destination}
recommendedPaths={recommendedPaths}
onChange={onLocationChange}
disabled={!editable}
testID="add-project-flow-location"
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
flex: 1,
minHeight: 0,
gap: theme.spacing[3],
},
}));
@@ -0,0 +1,166 @@
import { useMemo } from "react";
import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Folder, FolderOpen, Search } from "lucide-react-native";
import { buildProjectPickerOptions } from "@/components/project-picker-options";
import { Button } from "@/components/ui/button";
import { FormTextInput } from "@/components/ui/form-field";
import { isWeb } from "@/constants/platform";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { shortenPath } from "@/utils/shorten-path";
import type { AddProjectActions } from "./use-add-project-actions";
import type { AddProjectFlowState, AddProjectHost } from "./model";
import { pathBaseName } from "./options";
import { ResultList, type ResultRow } from "./result-list";
import { RESULTS_TEST_ID } from "./result-list-id";
import { useDirectorySearch } from "./searches";
import { resolveActiveIndex, type AddProjectTabView } from "./tab-view";
const ThemedSearch = withUnistyles(Search);
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const searchIcon = <ThemedSearch size={ICON_SIZE.md} uniProps={mutedColor} />;
export function useExistingTab(input: {
state: AddProjectFlowState;
host: AddProjectHost | null;
recommendedPaths: string[];
actions: AddProjectActions;
}): AddProjectTabView {
const { state, host, recommendedPaths, actions } = input;
const { query } = state.existing;
const canAddProject = host?.canAddProject === true;
const search = useDirectorySearch({
hostId: state.hostId,
query,
// The host answers a blank query with nothing, so only search once there is text.
enabled: state.tab === "existing" && canAddProject && query.trim().length > 0,
});
const paths = useMemo(
() =>
canAddProject
? buildProjectPickerOptions({ recommendedPaths, serverPaths: search.items, query })
: [],
[canAddProject, query, recommendedPaths, search.items],
);
const rows = useMemo<ResultRow[]>(
() =>
paths.map((option) => {
const shortPath = shortenPath(option.path);
return {
id: option.path,
title: option.kind === "path" ? shortPath : pathBaseName(option.path),
subtitle: option.kind === "path" ? "Open this path" : shortPath,
icon: Folder,
testID: `add-project-flow-folder-${encodeURIComponent(option.path)}`,
};
}),
[paths],
);
// While the search for new text runs, the rows on screen answer the old text. None of them is
// picked until the new answer arrives or the user picks one, unless it is the typed path.
const awaitingRows =
search.pending && state.existing.selectedId === null && paths[0]?.kind !== "path";
const activeIndex = awaitingRows ? -1 : resolveActiveIndex(rows, state.existing.selectedId);
const activePath = paths[activeIndex]?.path ?? null;
return useMemo<AddProjectTabView>(() => {
const unavailable = canAddProject ? null : "Update the host to add projects";
let notice: AddProjectTabView["notice"] = null;
if (unavailable) notice = { kind: "empty", text: unavailable };
else if (search.error) notice = { kind: "error", text: search.error };
else if (search.pending) notice = { kind: "pending", text: "Searching..." };
else notice = { kind: "empty", text: query.trim() ? "No matching folders" : "No folders yet" };
return {
rows,
activeIndex,
notice,
unavailable,
primary: {
label: "Open project",
submit: activePath ? () => actions.openFolder(activePath) : null,
},
};
}, [actions, activeIndex, activePath, canAddProject, query, rows, search.error, search.pending]);
}
export function ExistingTab({
view,
query,
canBrowse,
disabled,
autoFocus,
onQueryChange,
onSelectRow,
onBrowse,
}: {
view: AddProjectTabView;
query: string;
canBrowse: boolean;
disabled: boolean;
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
autoFocus: boolean;
onQueryChange: (query: string) => void;
onSelectRow: (index: number) => void;
onBrowse: () => void;
}) {
const editable = !disabled && !view.unavailable;
return (
<View style={styles.body}>
<View style={styles.searchRow}>
<View style={styles.searchField}>
<FormTextInput
initialValue={query}
onChangeText={onQueryChange}
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
leading={searchIcon}
placeholder="Search folders or enter a path"
accessibilityLabel="Search folders"
autoFocus={autoFocus}
autoCapitalize="none"
autoCorrect={false}
returnKeyType="go"
editable={editable}
testID="add-project-flow-input"
/>
</View>
{canBrowse ? (
<Button
variant="secondary"
leftIcon={FolderOpen}
onPress={onBrowse}
disabled={!editable}
testID="add-project-flow-browse"
>
Browse
</Button>
) : null}
</View>
<ResultList
rows={view.rows}
activeIndex={view.activeIndex}
notice={view.notice}
onSelect={onSelectRow}
disabled={disabled}
testID={RESULTS_TEST_ID}
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
flex: 1,
minHeight: 0,
gap: theme.spacing[3],
},
searchRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
searchField: {
flex: 1,
minWidth: 0,
},
}));
@@ -0,0 +1,4 @@
/** Native moves no focus to buttons from a hardware keyboard, so Enter always reaches the sheet. */
export function focusedControlOwnsEnter(): boolean {
return false;
}
@@ -0,0 +1,16 @@
import { RESULTS_TEST_ID } from "./result-list-id";
const ACTIVATES_ON_ENTER =
'button, a[href], [role="button"], [role="link"], [role="tab"], [role="combobox"], [role="menuitem"]';
/**
* Whether the focused element handles Enter itself, such as the Close button, a tab, or the
* Location field. Result rows are buttons too, but focusing a row picks it, so Enter on a row
* runs the primary action for that row.
*/
export function focusedControlOwnsEnter(): boolean {
const active = document.activeElement;
if (!(active instanceof HTMLElement)) return false;
if (active.closest(`[data-testid="${RESULTS_TEST_ID}"]`)) return false;
return active.matches(ACTIVATES_ON_ENTER);
}
+492
View File
@@ -0,0 +1,492 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Folder, FolderPlus, Plus } from "lucide-react-native";
import { AdaptiveModalSheet, type SheetKeyboard } from "@/components/adaptive-modal-sheet";
import { HostStatusDot } from "@/components/host-status-dot";
import { HostPicker } from "@/components/hosts/host-picker";
import { GitHubIcon } from "@/components/icons/github-icon";
import { Button } from "@/components/ui/button";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useAddHost } from "@/hosts/add-host";
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
import { Shortcut } from "@/components/ui/shortcut";
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
import {
useAddProjectFlowStore,
type AddProjectFlowRequest,
} from "@/stores/add-project-flow-store";
import { useRecommendedProjectPaths } from "@/stores/session-store-hooks";
import { formatShortcut } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import { CloneTab, useCloneTab } from "./clone-tab";
import { ExistingTab, useExistingTab } from "./existing-tab";
import { focusedControlOwnsEnter } from "./focused-control";
import {
ADD_PROJECT_KEYS,
addProjectFailure,
applyAvailableAddProjectHosts,
currentAddProjectHost,
selectableAddProjectHosts,
isAddProjectSubmitting,
moveAddProjectActiveIndex,
openAddProjectFlow,
resolveAddProjectKey,
selectAddProjectHost,
selectAddProjectRow,
selectAddProjectTab,
setAddProjectLocation,
setAddProjectQuery,
setNewFolderName,
type AddProjectTab,
} from "./model";
import { NewFolderTab, useNewFolderTab } from "./new-folder-tab";
import { defaultProjectLocation } from "./options";
import type { AddProjectTabView } from "./tab-view";
import { useAddProjectActions } from "./use-add-project-actions";
import { useAddProjectHosts } from "./use-add-project-hosts";
const SNAP_POINTS = ["90%"];
// Tall enough for a search field, six result rows, and the location field, so switching tabs
// never resizes the card.
const DESKTOP_HEIGHT = 560;
// Compact drops the segment icons so the three labels fit a phone's width.
const TABS: {
value: AddProjectTab;
label: string;
key: string;
icon: SegmentedControlOption<AddProjectTab>["icon"];
}[] = [
{
value: "existing",
label: "Existing",
key: "1",
icon: ({ color, size }) => <Folder color={color} size={size} />,
},
{
value: "clone",
label: "Clone",
key: "2",
icon: ({ color, size }) => <GitHubIcon color={color} size={size} />,
},
{
value: "new-folder",
label: "New folder",
key: "3",
icon: ({ color, size }) => <FolderPlus color={color} size={size} />,
},
];
/** `lockedTo` is the tab a running submission belongs to; the others are disabled until it ends. */
function buildTabOptions(
isMac: boolean,
withIcons: boolean,
lockedTo: AddProjectTab | null,
): SegmentedControlOption<AddProjectTab>[] {
const os = isMac ? "mac" : "non-mac";
return TABS.map(
(tab): SegmentedControlOption<AddProjectTab> => ({
value: tab.value,
label: tab.label,
icon: withIcons ? tab.icon : undefined,
tooltip: formatShortcut(["mod", tab.key], os),
testID: `add-project-flow-tab-${tab.value}`,
disabled: lockedTo !== null && tab.value !== lockedTo,
}),
);
}
interface AddProjectFlowProps {
request: AddProjectFlowRequest;
onClose: () => void;
}
/**
* Add project: one sheet with a tab per way to add one. The flow state lives in `./model`; this
* component wires it to the host, the searches, and the keys.
*/
export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
const isCompact = useIsCompactFormFactor();
const isMac = getShortcutOs() === "mac";
const keyboardPresent = useHardwareKeyboardPresent();
const availableHosts = useAddProjectHosts();
const [state, setState] = useState(() =>
openAddProjectFlow({
hosts: availableHosts,
...(request.preferredHostId ? { preferredHostId: request.preferredHostId } : {}),
}),
);
useEffect(() => {
setState((current) => applyAvailableAddProjectHosts(current, availableHosts));
}, [availableHosts]);
const host = currentAddProjectHost(state);
const submitting = isAddProjectSubmitting(state);
const failure = addProjectFailure(state);
const recommendedPaths = useRecommendedProjectPaths(state.hostId);
const rememberedLocation = useAddProjectFlowStore((store) =>
state.hostId ? store.lastLocationByHost[state.hostId] : undefined,
);
const defaultLocation = defaultProjectLocation({
remembered: rememberedLocation,
projectPaths: recommendedPaths,
});
const actions = useAddProjectActions({ hostId: state.hostId, setState, onClose });
// An offline host keeps its drafts, but nothing submits until it is back or the user picks
// another host. Gated here, once, so the footer, Enter and the native Go key all agree.
const offline = host?.online === false;
const existing = blockSubmitWhen(
offline,
useExistingTab({ state, host, recommendedPaths, actions }),
);
const clone = blockSubmitWhen(offline, useCloneTab({ state, host, defaultLocation, actions }));
const newFolder = blockSubmitWhen(
offline,
useNewFolderTab({ state, host, defaultLocation, actions }),
);
const views: Record<AddProjectTab, AddProjectTabView> = {
existing,
clone,
"new-folder": newFolder,
};
const view = views[state.tab];
const selectTab = useCallback(
(tab: AddProjectTab) => setState((current) => selectAddProjectTab(current, tab)),
[],
);
const selectHost = useCallback(
(hostId: string) => setState((current) => selectAddProjectHost(current, hostId)),
[],
);
const changeQuery = useCallback(
(query: string) => setState((current) => setAddProjectQuery(current, query)),
[],
);
const changeLocation = useCallback(
(location: string) => setState((current) => setAddProjectLocation(current, location)),
[],
);
const changeName = useCallback(
(name: string) => setState((current) => setNewFolderName(current, name)),
[],
);
// The key handler reads the latest view without re-registering the overlay on every keystroke.
const viewRef = useRef(view);
viewRef.current = view;
const hasHostRef = useRef(host !== null);
hasHostRef.current = host !== null;
/** Picks the row at `index` of the current tab's list, remembered by its id. */
const selectRow = useCallback((index: number) => {
const row = viewRef.current.rows[index];
if (row) setState((current) => selectAddProjectRow(current, row.id));
}, []);
const keyboard = useMemo<SheetKeyboard>(
() => ({
keys: ADD_PROJECT_KEYS,
onKeyDown: (event: KeyboardInputEvent) => {
// With no host there is nothing to switch to or submit; Enter belongs to Add host.
if (!hasHostRef.current) return false;
const command = resolveAddProjectKey(event, isMac);
if (!command) return false;
const current = viewRef.current;
if (command.kind === "tab") {
selectTab(command.tab);
return true;
}
if (command.kind === "move") {
if (current.rows.length === 0) return false;
selectRow(
moveAddProjectActiveIndex(current.activeIndex, current.rows.length, command.direction),
);
return true;
}
if (!current.primary.submit || focusedControlOwnsEnter()) return false;
current.primary.submit();
return true;
},
}),
[isMac, selectRow, selectTab],
);
const lockedTab = submitting ? state.tab : null;
const tabOptions = useMemo(
() => buildTabOptions(isMac, !isCompact, lockedTab),
[isCompact, isMac, lockedTab],
);
const selectableHosts = useMemo(() => selectableAddProjectHosts(state), [state]);
const header = useMemo(
() => ({
title: "Add project",
titleTestID: "add-project-flow-title",
actions:
selectableHosts.length > 1 && state.hostId ? (
<HostPill
hosts={selectableHosts}
hostId={state.hostId}
onSelect={selectHost}
disabled={submitting}
/>
) : undefined,
}),
[selectHost, selectableHosts, state.hostId, submitting],
);
// On a pointer layout the failure sits left of the button; compact stacks it above a
// full-width button.
const problem = failure ?? (offline && host ? `${host.label} is offline` : null);
const failureLine = problem ? (
<Text style={styles.failure} numberOfLines={2} testID="add-project-flow-error">
{problem}
</Text>
) : null;
const footer = host ? (
<>
{failureLine ?? (isCompact ? null : <KeyHints canMove={view.rows.length > 0} />)}
<Button
variant="default"
onPress={view.primary.submit ?? undefined}
disabled={!view.primary.submit}
loading={submitting}
style={isCompact ? styles.primaryCompact : styles.primary}
testID="add-project-flow-submit"
>
{view.primary.label}
</Button>
</>
) : null;
let body: ReactNode;
if (!host) {
body = <NoHosts onClose={onClose} />;
} else if (state.tab === "existing") {
body = (
<ExistingTab
view={existing}
query={state.existing.query}
canBrowse={host.canBrowse && !offline}
disabled={submitting}
autoFocus={keyboardPresent}
onQueryChange={changeQuery}
onSelectRow={selectRow}
onBrowse={actions.browse}
/>
);
} else if (state.tab === "clone") {
body = (
<CloneTab
view={clone}
query={state.clone.query}
hostId={state.hostId}
recommendedPaths={recommendedPaths}
disabled={submitting}
autoFocus={keyboardPresent}
onQueryChange={changeQuery}
onSelectRow={selectRow}
onLocationChange={changeLocation}
/>
);
} else {
body = (
<NewFolderTab
view={newFolder}
name={state.newFolder.name}
hostId={state.hostId}
recommendedPaths={recommendedPaths}
disabled={submitting}
autoFocus={keyboardPresent}
onNameChange={changeName}
onLocationChange={changeLocation}
/>
);
}
return (
<AdaptiveModalSheet
visible
onClose={onClose}
header={header}
footer={footer}
footerContainerStyle={isCompact ? styles.footerContainerCompact : undefined}
snapPoints={SNAP_POINTS}
desktopHeight={DESKTOP_HEIGHT}
scrollable={false}
keyboard={keyboard}
contentStyle={styles.content}
testID="add-project-flow"
>
{host ? (
<SegmentedControl
options={tabOptions}
value={state.tab}
onValueChange={selectTab}
fill
testID="add-project-flow-tabs"
/>
) : null}
{/* Keyed by tab so each tab's input mounts with its own draft and takes focus. */}
<View key={host ? state.tab : "no-host"} style={styles.tabBody}>
{body}
</View>
</AdaptiveModalSheet>
);
}
function blockSubmitWhen<TabView extends AddProjectTabView>(
blocked: boolean,
view: TabView,
): TabView {
return blocked ? { ...view, primary: { ...view.primary, submit: null } } : view;
}
function hostOptionTestID(serverId: string): string {
return `add-project-flow-host-${serverId}`;
}
function HostPill({
hosts,
hostId,
onSelect,
disabled,
}: {
hosts: { serverId: string; label: string }[];
hostId: string;
onSelect: (hostId: string) => void;
disabled: boolean;
}) {
const anchorRef = useRef<View>(null);
const [open, setOpen] = useState(false);
const openPicker = useCallback(() => setOpen(true), []);
const label = hosts.find((host) => host.serverId === hostId)?.label ?? hostId;
const icon = useMemo(() => <HostStatusDot serverId={hostId} />, [hostId]);
return (
<HostPicker
hosts={hosts}
value={hostId}
onSelect={onSelect}
open={open}
onOpenChange={setOpen}
anchorRef={anchorRef}
searchable={false}
title="Host"
desktopPlacement="bottom-end"
desktopMinWidth={240}
hostOptionTestID={hostOptionTestID}
>
<FieldTrigger
ref={anchorRef}
variant="badge"
label="Host"
accessibilityLabel="Project host"
tooltip="Host"
icon={icon}
value={label}
onPress={openPicker}
disabled={disabled}
testID="add-project-flow-host-trigger"
/>
</HostPicker>
);
}
const MOVE_KEYS = ["↑↓"];
const TAB_KEYS = ["mod", "1–3"];
/** The keys that are not on any control: list movement and tab switching. */
function KeyHints({ canMove }: { canMove: boolean }) {
const keyboardPresent = useHardwareKeyboardPresent();
if (!keyboardPresent) return <View />;
return (
<View style={styles.hints}>
{canMove ? (
<View style={styles.hint}>
<Shortcut keys={MOVE_KEYS} />
<Text style={styles.hintText}>Move</Text>
</View>
) : null}
<View style={styles.hint}>
<Shortcut keys={TAB_KEYS} />
<Text style={styles.hintText}>Switch</Text>
</View>
</View>
);
}
function NoHosts({ onClose }: { onClose: () => void }) {
const addHost = useAddHost();
const handleAddHost = useCallback(() => {
// The project sheet must release its window before the add-host sheet opens.
onClose();
addHost();
}, [addHost, onClose]);
return (
<View style={styles.noHosts}>
<Text style={styles.noHostsText}>No connected hosts</Text>
<Button
variant="secondary"
leftIcon={Plus}
onPress={handleAddHost}
testID="add-project-flow-add-host"
>
Add host
</Button>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
content: {
flex: 1,
minHeight: 0,
},
tabBody: {
flex: 1,
minHeight: 0,
},
footerContainerCompact: {
flexDirection: "column",
alignItems: "stretch",
},
// The message wraps beside the button; the button keeps its width.
failure: {
flexShrink: 1,
minWidth: 0,
color: theme.colors.statusDanger,
fontSize: theme.fontSize.sm,
},
hints: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[4],
},
hint: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
},
hintText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
primary: {
flexShrink: 0,
},
primaryCompact: {
flexShrink: 0,
alignSelf: "stretch",
},
noHosts: {
flex: 1,
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
},
noHostsText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
}));
@@ -0,0 +1,109 @@
import { useCallback, useMemo, useRef, useState } from "react";
import type { View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import { HardDrive } from "lucide-react-native";
import { buildProjectPickerOptions } from "@/components/project-picker-options";
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { shortenPath } from "@/utils/shorten-path";
import { buildSuggestedParentDirectories } from "./options";
import { useDirectorySearch } from "./searches";
const ThemedHardDrive = withUnistyles(HardDrive);
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const locationIcon = <ThemedHardDrive size={ICON_SIZE.md} uniProps={mutedColor} />;
interface LocationFieldProps {
hostId: string | null;
/** The parent directory the project goes into. */
location: string;
/** Where the project ends up, shown on the field so the user rarely needs to open it. */
destination: string;
recommendedPaths: string[];
onChange: (location: string) => void;
disabled: boolean;
testID: string;
}
/** Picks the parent directory for a new project: recent parents, a folder search, or a typed path. */
export function LocationField({
hostId,
location,
destination,
recommendedPaths,
onChange,
disabled,
testID,
}: LocationFieldProps) {
const anchorRef = useRef<View>(null);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const search = useDirectorySearch({ hostId, query, enabled: open && query.trim().length > 0 });
// The same builder as the Existing tab: a typed path first, then matching suggestions and
// folders the host found.
const pickerOptions = useMemo(() => {
const suggestions = [
location,
...buildSuggestedParentDirectories(recommendedPaths).filter((path) => path !== location),
];
return buildProjectPickerOptions({
recommendedPaths: suggestions,
serverPaths: search.items,
query,
});
}, [location, query, recommendedPaths, search.items]);
const options = useMemo<ComboboxOption[]>(
() =>
pickerOptions.map(
(option): ComboboxOption => ({
id: option.path,
label: shortenPath(option.path),
description: option.kind === "path" ? "Use this folder" : undefined,
kind: "directory",
}),
),
[pickerOptions],
);
// Like the Existing tab: while a new search runs, only a typed path is picked for Enter.
const awaitingOptions = search.pending && pickerOptions[0]?.kind !== "path";
const handleOpen = useCallback(() => setOpen(true), []);
const handleOpenChange = useCallback((next: boolean) => {
setOpen(next);
if (!next) setQuery("");
}, []);
return (
<>
<FieldTrigger
ref={anchorRef}
variant="field"
label="Location"
accessibilityLabel="Project location"
icon={locationIcon}
value={shortenPath(destination)}
onPress={handleOpen}
disabled={disabled}
testID={testID}
/>
<Combobox
options={options}
value={location}
onSelect={onChange}
searchable
remoteSearch
remoteSearchPending={awaitingOptions}
onSearchQueryChange={setQuery}
searchPlaceholder="Search folders or enter a path"
emptyText={search.error ?? (search.pending ? "Searching..." : "No matching folders")}
title="Location"
open={open}
onOpenChange={handleOpenChange}
anchorRef={anchorRef}
desktopPlacement="bottom-start"
/>
</>
);
}
+191 -154
View File
@@ -1,153 +1,194 @@
import { describe, expect, it } from "vitest";
import {
backAddProjectPage,
chooseAddProjectHost,
currentAddProjectPage,
applyAvailableAddProjectHosts,
selectableAddProjectHosts,
failAddProjectSubmission,
moveAddProjectActiveIndex,
moveAddProjectSelection,
openAddProjectFlow,
openDirectorySearchPage,
openGithubLocationPage,
openNewDirectoryNamePage,
openNewDirectoryParentPage,
setAddProjectActiveIndex,
setAddProjectPageInput,
setNewDirectoryName,
resolveAddProjectKey,
selectAddProjectHost,
selectAddProjectRow,
selectAddProjectTab,
setAddProjectLocation,
setAddProjectQuery,
setNewFolderName,
startAddProjectSubmission,
type AddProjectHost,
} from "./model";
import {
addProjectMethodEmptyText,
buildAddProjectMethods,
buildCloneLocationOptions,
buildManualGithubRepositoryChoices,
checkoutName,
defaultProjectLocation,
joinDirectoryPath,
parentDirectory,
validateNewFolderName,
} from "./options";
import { resolveActiveIndex } from "./tab-view";
const HOST: AddProjectHost = {
serverId: "host-1",
label: "Local",
online: true,
canAddProject: true,
canBrowse: true,
canCloneGithubRepositories: true,
canSearchGithubRepositories: true,
canCreateDirectory: true,
};
const REMOTE: AddProjectHost = { ...HOST, serverId: "host-2", label: "Remote", canBrowse: false };
const REMOTE_OFFLINE: AddProjectHost = { ...REMOTE, online: false };
describe("Add Project navigation", () => {
it("skips a single connected host without adding it to history", () => {
const state = openAddProjectFlow({ hosts: [HOST] });
const KEY = { key: "", ctrlKey: false, metaKey: false, altKey: false, shiftKey: false };
expect(currentAddProjectPage(state)).toEqual({
kind: "method",
hostId: "host-1",
activeIndex: 0,
error: null,
isSubmitting: false,
});
expect(backAddProjectPage(state)).toBeNull();
describe("Add Project flow", () => {
it("opens on the Existing tab of the preferred host", () => {
const state = openAddProjectFlow({ hosts: [HOST, REMOTE], preferredHostId: "host-2" });
expect(state.tab).toBe("existing");
expect(state.hostId).toBe("host-2");
});
it("restores page input and selection after Back", () => {
const secondHost = { ...HOST, serverId: "host-2", label: "Remote" };
let state = openAddProjectFlow({ hosts: [HOST, secondHost] });
state = setAddProjectPageInput(state, "rem");
state = setAddProjectActiveIndex(state, 1);
state = chooseAddProjectHost(state, secondHost.serverId);
state = openDirectorySearchPage(state, secondHost.serverId);
state = backAddProjectPage(state) ?? state;
state = backAddProjectPage(state) ?? state;
expect(currentAddProjectPage(state)).toEqual({
kind: "host",
query: "rem",
activeIndex: 1,
error: null,
});
it("falls back to the first host, and to no host when none is connected", () => {
expect(openAddProjectFlow({ hosts: [HOST, REMOTE] }).hostId).toBe("host-1");
expect(openAddProjectFlow({ hosts: [] }).hostId).toBeNull();
});
it("wraps keyboard selection in both directions", () => {
it("keeps each tab's input when switching tabs", () => {
let state = openAddProjectFlow({ hosts: [HOST] });
state = setAddProjectQuery(state, "paseo");
state = selectAddProjectTab(state, "clone");
state = setAddProjectQuery(state, "getpaseo/");
state = selectAddProjectTab(state, "new-folder");
state = setNewFolderName(state, "acme-api");
state = selectAddProjectTab(state, "existing");
expect(state.existing.query).toBe("paseo");
expect(state.clone.query).toBe("getpaseo/");
expect(state.newFolder.name).toBe("acme-api");
});
it("switching host keeps typed input but drops host-specific locations and selection", () => {
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
state = setAddProjectQuery(state, "paseo");
state = selectAddProjectRow(state, "/code/paseo");
state = selectAddProjectTab(state, "new-folder");
state = setNewFolderName(state, "acme-api");
state = setAddProjectLocation(state, "~/work");
state = selectAddProjectHost(state, "host-2");
expect(state.hostId).toBe("host-2");
expect(state.existing).toEqual({ query: "paseo", selectedId: null });
expect(state.newFolder).toEqual({ name: "acme-api", location: null });
});
it("locks tab and host while a submission runs, and unlocks with the failure", () => {
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
state = selectAddProjectTab(state, "clone");
state = startAddProjectSubmission(state);
expect(selectAddProjectTab(state, "existing").tab).toBe("clone");
expect(selectAddProjectHost(state, "host-2").hostId).toBe("host-1");
expect(selectAddProjectRow(state, "acme/app")).toBe(state);
expect(startAddProjectSubmission(state)).toBe(state);
state = failAddProjectSubmission(state, "Unable to clone project");
expect(state.submission).toEqual({
status: "failed",
tab: "clone",
message: "Unable to clone project",
});
expect(selectAddProjectTab(state, "existing").submission).toEqual({ status: "idle" });
});
it("clears a failure once the user edits the input or picks another row", () => {
let state = openAddProjectFlow({ hosts: [HOST] });
state = startAddProjectSubmission(state);
state = failAddProjectSubmission(state, "Directory not found");
expect(setAddProjectQuery(state, "~/dev").submission).toEqual({ status: "idle" });
expect(selectAddProjectRow(state, "/code/app").submission).toEqual({ status: "idle" });
});
it("keeps the chosen host and its draft while it is offline, never moving them to another host", () => {
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
state = selectAddProjectHost(state, "host-2");
state = setAddProjectQuery(state, "/srv/app");
const offline = applyAvailableAddProjectHosts(state, [HOST, REMOTE_OFFLINE]);
expect(offline.hostId).toBe("host-2");
expect(offline.existing.query).toBe("/srv/app");
expect(selectableAddProjectHosts(offline).map((host) => host.serverId)).toEqual([
"host-1",
"host-2",
]);
const back = applyAvailableAddProjectHosts(offline, [HOST, REMOTE]);
expect(back.hostId).toBe("host-2");
expect(back.existing.query).toBe("/srv/app");
expect(selectAddProjectHost(offline, "host-1").hostId).toBe("host-1");
});
it("picks only an online host, and another one when the chosen host is removed", () => {
expect(openAddProjectFlow({ hosts: [REMOTE_OFFLINE, HOST] }).hostId).toBe("host-1");
expect(
openAddProjectFlow({ hosts: [REMOTE_OFFLINE, HOST], preferredHostId: "host-2" }).hostId,
).toBe("host-1");
expect(openAddProjectFlow({ hosts: [REMOTE_OFFLINE] }).hostId).toBeNull();
expect(
selectAddProjectHost(openAddProjectFlow({ hosts: [HOST, REMOTE_OFFLINE] }), "host-2").hostId,
).toBe("host-1");
const state = selectAddProjectHost(openAddProjectFlow({ hosts: [HOST, REMOTE] }), "host-2");
expect(applyAvailableAddProjectHosts(state, [HOST]).hostId).toBe("host-1");
expect(applyAvailableAddProjectHosts(openAddProjectFlow({ hosts: [] }), [REMOTE]).hostId).toBe(
"host-2",
);
});
it("keeps the user's pick across a reorder and never swaps a dropped pick for another row", () => {
const rows = [{ id: "/code/beta" }, { id: "/code/alpha" }];
expect(resolveActiveIndex(rows, "/code/alpha")).toBe(1);
expect(resolveActiveIndex(rows, null)).toBe(0);
expect(resolveActiveIndex(rows, "/code/gone")).toBe(-1);
expect(resolveActiveIndex([], null)).toBe(-1);
});
it("wraps keyboard selection at both ends", () => {
expect(moveAddProjectActiveIndex(2, 3, "next")).toBe(0);
expect(moveAddProjectActiveIndex(0, 3, "previous")).toBe(2);
expect(moveAddProjectSelection(0, [true, false, true], "next")).toBe(2);
});
});
describe("Add Project keys", () => {
it("maps Mod+1/2/3 to tabs using the platform's modifier", () => {
expect(resolveAddProjectKey({ ...KEY, key: "2", metaKey: true }, true)).toEqual({
kind: "tab",
tab: "clone",
});
expect(resolveAddProjectKey({ ...KEY, key: "3", ctrlKey: true }, false)).toEqual({
kind: "tab",
tab: "new-folder",
});
expect(resolveAddProjectKey({ ...KEY, key: "1", ctrlKey: true }, true)).toBeNull();
expect(resolveAddProjectKey({ ...KEY, key: "1" }, true)).toBeNull();
});
it("restores a directory name after returning to and reselecting its parent", () => {
let state = openAddProjectFlow({ hosts: [HOST] });
state = openNewDirectoryParentPage(state, HOST.serverId);
state = openNewDirectoryNamePage(state, HOST.serverId, "~/dev");
state = setNewDirectoryName(state, "command-center");
state = backAddProjectPage(state) ?? state;
state = openNewDirectoryNamePage(state, HOST.serverId, "~/dev");
expect(currentAddProjectPage(state)).toMatchObject({
kind: "new-directory-name",
parentPath: "~/dev",
name: "command-center",
it("maps arrows and Enter to list commands", () => {
expect(resolveAddProjectKey({ ...KEY, key: "ArrowDown" }, true)).toEqual({
kind: "move",
direction: "next",
});
});
it("restores the GitHub destination query and active parent when reopening a repository", () => {
const repository = {
id: "repo-1",
nameWithOwner: "getpaseo/paseo",
cloneUrl: "git@github.com:getpaseo/paseo.git",
description: null,
visibility: "public",
updatedAt: null,
};
let state = openAddProjectFlow({ hosts: [HOST] });
state = openGithubLocationPage(state, HOST.serverId, repository);
state = setAddProjectPageInput(state, "~/dev");
state = setAddProjectActiveIndex(state, 2);
state = backAddProjectPage(state) ?? state;
state = openGithubLocationPage(state, HOST.serverId, repository);
expect(currentAddProjectPage(state)).toMatchObject({
kind: "github-location",
query: "~/dev",
activeIndex: 2,
expect(resolveAddProjectKey({ ...KEY, key: "ArrowUp" }, true)).toEqual({
kind: "move",
direction: "previous",
});
expect(resolveAddProjectKey({ ...KEY, key: "Enter" }, true)).toEqual({ kind: "submit" });
expect(resolveAddProjectKey({ ...KEY, key: "Enter", shiftKey: true }, true)).toBeNull();
});
});
describe("Add Project options", () => {
it("hides every mutating method when the host lacks stable project identity", () => {
const outdatedHost = { ...HOST, canAddProject: false };
expect(buildAddProjectMethods(outdatedHost)).toEqual([]);
expect(addProjectMethodEmptyText(outdatedHost)).toBe("Update the host to use Add Project.");
});
it("keeps host-upgrade methods discoverable while hiding local-only Browse", () => {
expect(
buildAddProjectMethods({
...HOST,
canBrowse: false,
canCloneGithubRepositories: false,
canSearchGithubRepositories: false,
canCreateDirectory: false,
}),
).toEqual([
{
id: "directory-search",
label: "Search for directory",
description: "Find a directory on Local",
},
{
id: "github",
label: "Clone from GitHub",
description: "Update this host to clone GitHub repositories",
disabled: true,
},
{
id: "new-directory",
label: "New directory",
description: "Update this host to create directories",
disabled: true,
},
]);
});
it("offers manual URL and protocol-specific owner/repo clone choices", () => {
expect(buildManualGithubRepositoryChoices("git@github.com:getpaseo/paseo.git")).toEqual([
expect.objectContaining({
@@ -163,46 +204,42 @@ describe("Add Project options", () => {
expect(buildManualGithubRepositoryChoices("paseo")).toEqual([]);
});
it("shows final clone paths while retaining parent paths as values", () => {
expect(
buildCloneLocationOptions({
parents: ["~/dev", "~/workspace"],
repositoryName: "paseo",
existingPaths: ["~/workspace/paseo"],
}),
).toEqual([
{
id: "~/dev",
path: "~/dev",
displayPath: "~/dev/paseo",
secondaryText: "Parent directory: ~/dev",
disabled: false,
},
{
id: "~/workspace",
path: "~/workspace",
displayPath: "~/workspace/paseo",
secondaryText: "Already exists",
disabled: true,
},
]);
it("defaults the location to a folder that exists", () => {
expect(defaultProjectLocation({ remembered: undefined, projectPaths: [] })).toBe("~");
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["/code/app"] })).toBe(
"/code",
);
expect(defaultProjectLocation({ remembered: "~/work", projectPaths: ["/code/app"] })).toBe(
"~/work",
);
});
it("shows equivalent absolute-home and tilde destinations only once", () => {
expect(
buildCloneLocationOptions({
parents: ["/Users/moboudra/dev", "~/dev"],
repositoryName: "dotfiles",
existingPaths: [],
}),
).toEqual([
{
id: "/Users/moboudra/dev",
path: "/Users/moboudra/dev",
displayPath: "/Users/moboudra/dev/dotfiles",
secondaryText: "Parent directory: /Users/moboudra/dev",
disabled: false,
},
]);
it("keeps a drive or filesystem root when deriving and joining a location", () => {
expect(parentDirectory("C:\\repo")).toBe("C:\\");
expect(parentDirectory("/repo")).toBe("/");
expect(parentDirectory("\\\\nas\\work")).toBeNull();
expect(parentDirectory("\\\\nas\\work\\app")).toBe("\\\\nas\\work");
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["\\\\nas\\work"] })).toBe(
"~",
);
expect(parentDirectory("/code/app")).toBe("/code");
expect(joinDirectoryPath("C:\\", "new-project")).toBe("C:\\new-project");
expect(joinDirectoryPath("/", "new-project")).toBe("/new-project");
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["C:\\repo"] })).toBe(
"C:\\",
);
});
it("names the checkout the way the host does", () => {
expect(checkoutName("acme/app.git")).toBe("app");
expect(checkoutName("acme/app")).toBe("app");
});
it("rejects folder names that are empty or leave the location", () => {
expect(validateNewFolderName("")).toBe("Enter a folder name");
expect(validateNewFolderName("..")).toBe("Enter a folder name");
expect(validateNewFolderName("../invalid")).toBe("Use a name without slashes");
expect(validateNewFolderName("C:repo")).toBe("Use a name without a drive letter");
expect(validateNewFolderName(" acme-api ")).toBeNull();
});
});
+169 -217
View File
@@ -1,6 +1,7 @@
export interface AddProjectHost {
serverId: string;
label: string;
online: boolean;
canAddProject: boolean;
canBrowse: boolean;
canCloneGithubRepositories: boolean;
@@ -17,42 +18,42 @@ export interface GithubRepositoryChoice {
updatedAt: string | null;
}
interface PageState {
activeIndex: number;
error: string | null;
}
/** The three ways to add a project, in the order the segmented control and Mod+1/2/3 walk them. */
export const ADD_PROJECT_TABS = ["existing", "clone", "new-folder"] as const;
export type AddProjectTab = (typeof ADD_PROJECT_TABS)[number];
interface SearchPageState extends PageState {
interface ListDraft {
query: string;
/**
* The row the user picked, by id, so it stays picked when a search refresh reorders the rows.
* `null`, or an id no longer listed, means the first row.
*/
selectedId: string | null;
}
export type AddProjectPage =
| ({ kind: "host" } & SearchPageState)
| ({ kind: "method"; hostId: string; isSubmitting: boolean } & PageState)
| ({ kind: "directory-search"; hostId: string; isSubmitting: boolean } & SearchPageState)
| ({ kind: "github-search"; hostId: string } & SearchPageState)
| ({
kind: "github-location";
hostId: string;
repository: GithubRepositoryChoice;
isSubmitting: boolean;
} & SearchPageState)
| ({ kind: "new-directory-parent"; hostId: string } & SearchPageState)
| {
kind: "new-directory-name";
hostId: string;
parentPath: string;
name: string;
activeIndex: number;
error: string | null;
isSubmitting: boolean;
};
/** `location: null` means the default parent directory for the current host. */
interface CloneDraft extends ListDraft {
location: string | null;
}
interface NewFolderDraft {
name: string;
location: string | null;
}
export type AddProjectSubmission =
| { status: "idle" }
| { status: "submitting"; tab: AddProjectTab }
| { status: "failed"; tab: AddProjectTab; message: string };
export interface AddProjectFlowState {
hosts: AddProjectHost[];
pages: AddProjectPage[];
newDirectoryNameDrafts: Record<string, string>;
githubLocationDrafts: Record<string, { query: string; activeIndex: number }>;
hostId: string | null;
tab: AddProjectTab;
existing: ListDraft;
clone: CloneDraft;
newFolder: NewFolderDraft;
submission: AddProjectSubmission;
}
export interface OpenAddProjectFlowInput {
@@ -60,214 +61,144 @@ export interface OpenAddProjectFlowInput {
preferredHostId?: string;
}
type SearchPageKind = Extract<AddProjectPage, { query: string }>["kind"];
const IDLE: AddProjectSubmission = { status: "idle" };
function searchPage<TKind extends SearchPageKind>(kind: TKind) {
return { kind, query: "", activeIndex: 0, error: null } as const;
}
function methodPage(hostId: string): AddProjectPage {
return { kind: "method", hostId, activeIndex: 0, error: null, isSubmitting: false };
function pickHostId(hosts: AddProjectHost[], preferredHostId?: string | null): string | null {
const online = hosts.filter((host) => host.online);
const preferred = preferredHostId
? online.find((host) => host.serverId === preferredHostId)
: undefined;
return (preferred ?? online[0])?.serverId ?? null;
}
export function openAddProjectFlow(input: OpenAddProjectFlowInput): AddProjectFlowState {
const preferredHost = input.preferredHostId
? input.hosts.find((host) => host.serverId === input.preferredHostId)
: null;
const onlyHost = input.hosts.length === 1 ? input.hosts[0] : null;
const initialHost = preferredHost ?? onlyHost;
return {
hosts: input.hosts,
pages: initialHost ? [methodPage(initialHost.serverId)] : [searchPage("host")],
newDirectoryNameDrafts: {},
githubLocationDrafts: {},
hostId: pickHostId(input.hosts, input.preferredHostId),
tab: "existing",
existing: { query: "", selectedId: null },
clone: { query: "", selectedId: null, location: null },
newFolder: { name: "", location: null },
submission: IDLE,
};
}
export function currentAddProjectHost(state: AddProjectFlowState): AddProjectHost | null {
return state.hosts.find((host) => host.serverId === state.hostId) ?? null;
}
export function isAddProjectSubmitting(state: AddProjectFlowState): boolean {
return state.submission.status === "submitting";
}
/** The failure to show on the current tab, if the last submission there failed. */
export function addProjectFailure(state: AddProjectFlowState): string | null {
const { submission } = state;
return submission.status === "failed" && submission.tab === state.tab ? submission.message : null;
}
/** The hosts the user can switch to: every online host, plus the current one even while offline. */
export function selectableAddProjectHosts(state: AddProjectFlowState): AddProjectHost[] {
return state.hosts.filter((host) => host.online || host.serverId === state.hostId);
}
/**
* The chosen host stays chosen while it is offline, with its drafts, so a disconnect never sends
* them to another host. A host is picked only when none is chosen or the chosen one was removed.
*/
export function applyAvailableAddProjectHosts(
state: AddProjectFlowState,
hosts: AddProjectHost[],
preferredHostId?: string,
): AddProjectFlowState {
const current = currentAddProjectPage(state);
if (state.pages.length !== 1 || current.kind !== "host") {
return { ...state, hosts };
}
const preferredHost = preferredHostId
? hosts.find((host) => host.serverId === preferredHostId)
: null;
const onlyHost = hosts.length === 1 ? hosts[0] : null;
const initialHost = preferredHost ?? onlyHost;
const stillListed = hosts.some((host) => host.serverId === state.hostId);
if (stillListed) return { ...state, hosts };
return withHost({ ...state, hosts }, pickHostId(hosts));
}
function withHost(state: AddProjectFlowState, hostId: string | null): AddProjectFlowState {
return {
...state,
hosts,
pages: initialHost ? [methodPage(initialHost.serverId)] : state.pages,
hostId,
existing: { ...state.existing, selectedId: null },
clone: { ...state.clone, selectedId: null, location: null },
newFolder: { ...state.newFolder, location: null },
submission: IDLE,
};
}
export function currentAddProjectPage(state: AddProjectFlowState): AddProjectPage {
const page = state.pages[state.pages.length - 1];
if (!page) {
throw new Error("Add Project flow must always contain a page");
export function selectAddProjectHost(
state: AddProjectFlowState,
hostId: string,
): AddProjectFlowState {
if (isAddProjectSubmitting(state) || hostId === state.hostId) return state;
if (!state.hosts.some((host) => host.serverId === hostId && host.online)) return state;
return withHost(state, hostId);
}
export function selectAddProjectTab(
state: AddProjectFlowState,
tab: AddProjectTab,
): AddProjectFlowState {
if (isAddProjectSubmitting(state) || tab === state.tab) return state;
return { ...state, tab, submission: IDLE };
}
/** Sets the search text of the current list tab. */
export function setAddProjectQuery(state: AddProjectFlowState, query: string): AddProjectFlowState {
if (state.tab === "existing") {
return { ...state, existing: { query, selectedId: null }, submission: IDLE };
}
return page;
}
export function updateCurrentAddProjectPage(
state: AddProjectFlowState,
update: (page: AddProjectPage) => AddProjectPage,
): AddProjectFlowState {
const index = state.pages.length - 1;
return {
...state,
pages: state.pages.map((page, pageIndex) => (pageIndex === index ? update(page) : page)),
};
}
export function pushAddProjectPage(
state: AddProjectFlowState,
page: AddProjectPage,
): AddProjectFlowState {
return { ...state, pages: [...state.pages, page] };
}
export function backAddProjectPage(state: AddProjectFlowState): AddProjectFlowState | null {
if (state.pages.length === 1) {
return null;
if (state.tab === "clone") {
return { ...state, clone: { ...state.clone, query, selectedId: null }, submission: IDLE };
}
return { ...state, pages: state.pages.slice(0, -1) };
return state;
}
export function chooseAddProjectHost(
export function setNewFolderName(state: AddProjectFlowState, name: string): AddProjectFlowState {
return { ...state, newFolder: { ...state.newFolder, name }, submission: IDLE };
}
/** Sets the parent directory of the current tab that creates a folder. */
export function setAddProjectLocation(
state: AddProjectFlowState,
hostId: string,
location: string,
): AddProjectFlowState {
return pushAddProjectPage(state, methodPage(hostId));
if (state.tab === "clone") {
return { ...state, clone: { ...state.clone, location }, submission: IDLE };
}
if (state.tab === "new-folder") {
return { ...state, newFolder: { ...state.newFolder, location }, submission: IDLE };
}
return state;
}
export function openDirectorySearchPage(
export function selectAddProjectRow(
state: AddProjectFlowState,
hostId: string,
selectedId: string,
): AddProjectFlowState {
return pushAddProjectPage(state, {
...searchPage("directory-search"),
hostId,
isSubmitting: false,
});
// The row being added stays put until its submission ends; choosing another clears the
// failure of the last one.
if (isAddProjectSubmitting(state)) return state;
if (state.tab === "existing") {
return { ...state, existing: { ...state.existing, selectedId }, submission: IDLE };
}
if (state.tab === "clone") {
return { ...state, clone: { ...state.clone, selectedId }, submission: IDLE };
}
return state;
}
export function openGithubSearchPage(
export function startAddProjectSubmission(state: AddProjectFlowState): AddProjectFlowState {
if (isAddProjectSubmitting(state)) return state;
return { ...state, submission: { status: "submitting", tab: state.tab } };
}
export function failAddProjectSubmission(
state: AddProjectFlowState,
hostId: string,
message: string,
): AddProjectFlowState {
return pushAddProjectPage(state, { ...searchPage("github-search"), hostId });
}
export function openGithubLocationPage(
state: AddProjectFlowState,
hostId: string,
repository: GithubRepositoryChoice,
): AddProjectFlowState {
const draft = state.githubLocationDrafts[githubLocationDraftKey(hostId, repository.id)];
return pushAddProjectPage(state, {
kind: "github-location",
query: draft?.query ?? "",
activeIndex: draft?.activeIndex ?? 0,
error: null,
hostId,
repository,
isSubmitting: false,
});
}
export function openNewDirectoryParentPage(
state: AddProjectFlowState,
hostId: string,
): AddProjectFlowState {
return pushAddProjectPage(state, { ...searchPage("new-directory-parent"), hostId });
}
export function openNewDirectoryNamePage(
state: AddProjectFlowState,
hostId: string,
parentPath: string,
): AddProjectFlowState {
const draftKey = newDirectoryDraftKey(hostId, parentPath);
return pushAddProjectPage(state, {
kind: "new-directory-name",
hostId,
parentPath,
name: state.newDirectoryNameDrafts[draftKey] ?? "",
activeIndex: 0,
error: null,
isSubmitting: false,
});
}
export function setAddProjectPageInput(
state: AddProjectFlowState,
value: string,
): AddProjectFlowState {
const page = currentAddProjectPage(state);
const updated = updateCurrentAddProjectPage(state, (current) => {
if (current.kind === "new-directory-name") {
return { ...current, name: value, activeIndex: 0, error: null };
}
if (current.kind === "method") return current;
return { ...current, query: value, activeIndex: 0, error: null };
});
if (page.kind !== "github-location") return updated;
const draftKey = githubLocationDraftKey(page.hostId, page.repository.id);
return {
...updated,
githubLocationDrafts: {
...updated.githubLocationDrafts,
[draftKey]: { query: value, activeIndex: 0 },
},
};
}
export function setNewDirectoryName(
state: AddProjectFlowState,
value: string,
): AddProjectFlowState {
const page = currentAddProjectPage(state);
if (page.kind !== "new-directory-name") return state;
const draftKey = newDirectoryDraftKey(page.hostId, page.parentPath);
const updated = setAddProjectPageInput(state, value);
return {
...updated,
newDirectoryNameDrafts: {
...updated.newDirectoryNameDrafts,
[draftKey]: value,
},
};
}
function newDirectoryDraftKey(hostId: string, parentPath: string): string {
return `${hostId}\u0000${parentPath}`;
}
function githubLocationDraftKey(hostId: string, repositoryId: string): string {
return `${hostId}\u0000${repositoryId}`;
}
export function setAddProjectActiveIndex(
state: AddProjectFlowState,
activeIndex: number,
): AddProjectFlowState {
const page = currentAddProjectPage(state);
const updated = updateCurrentAddProjectPage(state, (current) => ({ ...current, activeIndex }));
if (page.kind !== "github-location") return updated;
const draftKey = githubLocationDraftKey(page.hostId, page.repository.id);
return {
...updated,
githubLocationDrafts: {
...updated.githubLocationDrafts,
[draftKey]: { query: page.query, activeIndex },
},
};
if (state.submission.status !== "submitting") return state;
return { ...state, submission: { status: "failed", tab: state.submission.tab, message } };
}
export function moveAddProjectActiveIndex(
@@ -283,16 +214,37 @@ export function moveAddProjectActiveIndex(
return next;
}
export function moveAddProjectSelection(
activeIndex: number,
selectable: readonly boolean[],
direction: "next" | "previous",
): number {
if (!selectable.some(Boolean)) return 0;
let next = activeIndex;
for (let count = 0; count < selectable.length; count += 1) {
next = moveAddProjectActiveIndex(next, selectable.length, direction);
if (selectable[next]) return next;
}
return activeIndex;
export interface AddProjectKeyInput {
key: string;
metaKey: boolean;
ctrlKey: boolean;
altKey: boolean;
shiftKey: boolean;
}
export type AddProjectKeyCommand =
| { kind: "tab"; tab: AddProjectTab }
| { kind: "move"; direction: "next" | "previous" }
| { kind: "submit" };
/** Keys the sheet claims besides Escape. Digits only act with the platform's Mod key. */
export const ADD_PROJECT_KEYS = ["Enter", "ArrowUp", "ArrowDown", "1", "2", "3"] as const;
export function resolveAddProjectKey(
input: AddProjectKeyInput,
isMac: boolean,
): AddProjectKeyCommand | null {
const modOnly =
(isMac ? input.metaKey && !input.ctrlKey : input.ctrlKey && !input.metaKey) &&
!input.altKey &&
!input.shiftKey;
const plain = !input.metaKey && !input.ctrlKey && !input.altKey && !input.shiftKey;
const tabIndex = ["1", "2", "3"].indexOf(input.key);
const tab = ADD_PROJECT_TABS[tabIndex];
if (tab && modOnly) return { kind: "tab", tab };
if (!plain) return null;
if (input.key === "ArrowDown") return { kind: "move", direction: "next" };
if (input.key === "ArrowUp") return { kind: "move", direction: "previous" };
if (input.key === "Enter") return { kind: "submit" };
return null;
}
@@ -0,0 +1,114 @@
import { useMemo } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Field, FormTextInput } from "@/components/ui/form-field";
import { isWeb } from "@/constants/platform";
import type { AddProjectActions } from "./use-add-project-actions";
import type { AddProjectFlowState, AddProjectHost } from "./model";
import { LocationField } from "./location-field";
import { joinDirectoryPath, validateNewFolderName } from "./options";
import type { AddProjectTabView } from "./tab-view";
export interface NewFolderTabView extends AddProjectTabView {
location: string;
destination: string;
/** Why the typed name cannot be a folder; null while empty or valid. */
nameError: string | null;
}
export function useNewFolderTab(input: {
state: AddProjectFlowState;
host: AddProjectHost | null;
defaultLocation: string;
actions: AddProjectActions;
}): NewFolderTabView {
const { state, host, defaultLocation, actions } = input;
const { name } = state.newFolder;
const location = state.newFolder.location ?? defaultLocation;
const trimmed = name.trim();
const nameError = trimmed ? validateNewFolderName(name) : null;
// Preview and create only a name that can be created, so the field never shows a path that
// escapes the location.
const previewName = trimmed && !nameError ? trimmed : null;
const canCreate = host?.canCreateDirectory === true;
return useMemo<NewFolderTabView>(
() => ({
rows: [],
activeIndex: 0,
notice: null,
location,
destination: previewName ? joinDirectoryPath(location, previewName) : location,
unavailable: canCreate ? null : "Update the host to create folders",
nameError,
primary: {
label: "Create project",
submit: canCreate && previewName ? () => actions.createFolder(name, location) : null,
},
}),
[actions, canCreate, location, name, nameError, previewName],
);
}
export function NewFolderTab({
view,
name,
hostId,
recommendedPaths,
disabled,
autoFocus,
onNameChange,
onLocationChange,
}: {
view: NewFolderTabView;
name: string;
hostId: string | null;
recommendedPaths: string[];
disabled: boolean;
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
autoFocus: boolean;
onNameChange: (name: string) => void;
onLocationChange: (location: string) => void;
}) {
const editable = !disabled && !view.unavailable;
return (
<View style={styles.body}>
<Field
label="Name"
hint={view.unavailable ?? undefined}
error={view.nameError}
testID="add-project-flow-name-field"
>
<FormTextInput
initialValue={name}
onChangeText={onNameChange}
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
placeholder="my-project"
accessibilityLabel="Folder name"
autoFocus={autoFocus}
autoCapitalize="none"
autoCorrect={false}
returnKeyType="go"
editable={editable}
invalid={Boolean(view.nameError)}
testID="add-project-flow-input"
/>
</Field>
<LocationField
hostId={hostId}
location={view.location}
destination={view.destination}
recommendedPaths={recommendedPaths}
onChange={onLocationChange}
disabled={!editable}
testID="add-project-flow-location"
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
gap: theme.spacing[4],
},
}));
+39 -112
View File
@@ -3,83 +3,7 @@ import {
parseGitHubRemoteUrl,
parseGitRemoteLocation,
} from "@getpaseo/protocol/git-remote";
import { shortenPath } from "@/utils/shorten-path";
import type { AddProjectHost, GithubRepositoryChoice } from "./model";
export type AddProjectMethodId = "directory-search" | "browse" | "github" | "new-directory";
export interface AddProjectMethodOption {
id: AddProjectMethodId;
label: string;
description: string;
disabled?: boolean;
}
export interface AddProjectPathOption {
id: string;
path: string;
displayPath: string;
secondaryText: string | null;
disabled: boolean;
}
export function filterAddProjectHosts(hosts: AddProjectHost[], query: string): AddProjectHost[] {
const normalized = query.trim().toLowerCase();
if (!normalized) return hosts;
return hosts.filter(
(host) =>
host.label.toLowerCase().includes(normalized) ||
host.serverId.toLowerCase().includes(normalized),
);
}
export function buildAddProjectMethods(host: AddProjectHost): AddProjectMethodOption[] {
if (!host.canAddProject) return [];
const options: AddProjectMethodOption[] = [];
options.push({
id: "directory-search",
label: "Search for directory",
description: `Find a directory on ${host.label}`,
});
if (host.canBrowse) {
options.push({
id: "browse",
label: "Browse",
description: "Choose or create a directory in Finder",
});
}
options.push({
id: "github",
label: "Clone from GitHub",
description: githubMethodDescription(host),
disabled: !host.canCloneGithubRepositories,
});
options.push({
id: "new-directory",
label: "New directory",
description: host.canCreateDirectory
? `Create an empty directory on ${host.label}`
: "Update this host to create directories",
disabled: !host.canCreateDirectory,
});
return options;
}
export function addProjectMethodEmptyText(host: AddProjectHost | null): string {
return host?.canAddProject === false
? "Update the host to use Add Project."
: "No matching options";
}
function githubMethodDescription(host: AddProjectHost): string {
if (!host.canCloneGithubRepositories) {
return "Update this host to clone GitHub repositories";
}
if (host.canSearchGithubRepositories) {
return "Search projects available to your GitHub account";
}
return "Enter a GitHub URL or owner/repo";
}
import type { GithubRepositoryChoice } from "./model";
export function pathBaseName(path: string): string {
const trimmed = path.replace(/[\\/]+$/, "");
@@ -87,6 +11,9 @@ export function pathBaseName(path: string): string {
return parts[parts.length - 1] ?? trimmed;
}
/** Starts the id of every choice built from what the user typed. */
export const MANUAL_CHOICE_PREFIX = "manual:";
export function buildManualGithubRepositoryChoices(query: string): GithubRepositoryChoice[] {
const repo = query.trim();
if (!repo) return [];
@@ -97,7 +24,7 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
const remoteName = location ? pathBaseName(location.path).replace(/\.git$/u, "") : repo;
return [
{
id: `manual:${repo}`,
id: `${MANUAL_CHOICE_PREFIX}${repo}`,
nameWithOwner: identity?.repo ?? remoteName,
cloneUrl: repo,
description: "Clone this repository URL",
@@ -110,7 +37,7 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
if (!shorthand) return [];
const nameWithOwner = `${shorthand[1]}/${shorthand[2]}`;
return (["https", "ssh"] as const).map((cloneProtocol) => ({
id: `manual:${cloneProtocol}:${nameWithOwner}`,
id: `${MANUAL_CHOICE_PREFIX}${cloneProtocol}:${nameWithOwner}`,
nameWithOwner,
cloneUrl: nameWithOwner,
cloneProtocol,
@@ -119,18 +46,21 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
}));
}
/** The folder that holds `path`. A root keeps its separator: `C:\repo` gives `C:\`, not `C:`. */
export function parentDirectory(path: string): string | null {
const trimmed = path.replace(/[\\/]+$/, "");
// A share root (\\server\share) has no parent folder; `\\server` alone is not a directory.
if (/^[\\/]{2}[^\\/]+[\\/][^\\/]+$/u.test(trimmed)) return null;
const index = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
if (index < 0) return null;
if (index === 0) return trimmed.slice(0, 1);
return trimmed.slice(0, index);
const parent = trimmed.slice(0, index);
const isRoot = parent === "" || /^[A-Za-z]:$/u.test(parent);
return isRoot ? trimmed.slice(0, index + 1) : parent;
}
export function joinDirectoryPath(parent: string, name: string): string {
const trimmedParent = parent.replace(/[\\/]+$/, "");
const separator = trimmedParent.includes("\\") && !trimmedParent.includes("/") ? "\\" : "/";
return `${trimmedParent}${separator}${name}`;
const separator = parent.includes("\\") && !parent.includes("/") ? "\\" : "/";
return `${parent.replace(/[\\/]+$/, "")}${separator}${name}`;
}
export function buildSuggestedParentDirectories(projectPaths: string[]): string[] {
@@ -149,34 +79,31 @@ export function buildSuggestedParentDirectories(projectPaths: string[]): string[
return [...new Set(values)];
}
export function buildCloneLocationOptions(input: {
parents: string[];
repositoryName: string;
existingPaths: string[];
}): AddProjectPathOption[] {
const existing = new Set(input.existingPaths.map(pathIdentity));
const seen = new Set<string>();
return input.parents.flatMap((parent) => {
const path = joinDirectoryPath(parent, input.repositoryName);
const identity = pathIdentity(path);
if (seen.has(identity)) return [];
seen.add(identity);
const pathExists = existing.has(identity);
return [
{
id: parent,
path: parent,
displayPath: path,
secondaryText: pathExists ? "Already exists" : `Parent directory: ${parent}`,
disabled: pathExists,
},
];
});
/**
* Where a new folder or clone goes when the user has not picked a location on this host: the last
* one used, else the parent of a recent project, else home. Only folders known to exist qualify;
* guesses like `~/dev` stay suggestions in the Location picker.
*/
export function defaultProjectLocation(input: {
remembered: string | undefined;
projectPaths: string[];
}): string {
const projectParent = input.projectPaths
.map(parentDirectory)
.find((parent): parent is string => parent !== null);
return input.remembered ?? projectParent ?? "~";
}
function pathIdentity(path: string): string {
const normalized = shortenPath(path.trim()).replace(/\\/g, "/").replace(/\/+$/u, "");
return /^[A-Za-z]:\//u.test(normalized) || normalized.startsWith("//")
? normalized.toLowerCase()
: normalized;
/** The folder a clone of `nameWithOwner` checks out into; the host drops a trailing `.git`. */
export function checkoutName(nameWithOwner: string): string {
return pathBaseName(nameWithOwner).replace(/\.git$/u, "");
}
export function validateNewFolderName(name: string): string | null {
const trimmed = name.trim();
if (!trimmed || trimmed === "." || trimmed === "..") return "Enter a folder name";
if (/[\\/]/.test(trimmed)) return "Use a name without slashes";
// The host rejects a drive prefix on every platform.
if (/^[A-Za-z]:/u.test(trimmed)) return "Use a name without a drive letter";
return null;
}
@@ -0,0 +1,2 @@
/** The result list's test ID, which the web Enter check also uses to recognise a focused row. */
export const RESULTS_TEST_ID = "add-project-flow-results";
@@ -0,0 +1,243 @@
import { useCallback, useMemo, useRef, type ComponentType, type RefObject } from "react";
import { Check } from "lucide-react-native";
import { Text, View, type ScrollView as NativeScrollView } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { PressHighlight } from "@/components/ui/press-highlight";
import { ScrollView } from "@/components/ui/scroll-view";
import { useRevealActiveItem } from "@/components/ui/scroll-reveal";
import { Shortcut } from "@/components/ui/shortcut";
import { useHardwareKeyboardPresent } from "@/keyboard";
import { settingsStyles } from "@/styles/settings";
import type { Theme } from "@/styles/theme";
type RowIcon = ComponentType<{ size?: number; color?: string }>;
export interface ResultRow {
id: string;
title: string;
subtitle: string | null;
icon: RowIcon;
testID: string;
}
/** What the list says when it has no rows to show. */
export type ResultListNotice =
| { kind: "pending"; text: string }
| { kind: "empty"; text: string }
| { kind: "error"; text: string };
interface ResultListProps {
rows: ResultRow[];
activeIndex: number;
/** Shown in place of the rows when there are none, or above them for an error. */
notice: ResultListNotice | null;
onSelect: (index: number) => void;
disabled?: boolean;
testID: string;
}
const ENTER_KEYS = ["Enter"];
// Fixed line heights make a two-line row the same height on every platform.
const TITLE_LINE_HEIGHT = 18;
const SUBTITLE_LINE_HEIGHT = 16;
function RowGlyph({ icon: Icon, size, color }: { icon: RowIcon; size: number; color?: string }) {
return <Icon size={size} color={color} />;
}
const MutedRowGlyph = withUnistyles(RowGlyph, (theme: Theme) => ({
color: theme.colors.foregroundMuted,
}));
const AccentCheck = withUnistyles(Check, (theme: Theme) => ({ color: theme.colors.accent }));
const ThemedSpinner = withUnistyles(LoadingSpinner, (theme: Theme) => ({
color: theme.colors.foregroundMuted,
}));
/** Enter commits the active row when there is a keyboard; on touch, a check marks the choice. */
function ActiveMark() {
const keyboardPresent = useHardwareKeyboardPresent();
return keyboardPresent ? <Shortcut keys={ENTER_KEYS} /> : <AccentCheck size={16} />;
}
function ResultRowView({
row,
index,
active,
disabled,
activeItemRef,
onActiveLayout,
onSelect,
}: {
row: ResultRow;
index: number;
active: boolean;
disabled: boolean;
activeItemRef: RefObject<View | null>;
onActiveLayout: () => void;
onSelect: (index: number) => void;
}) {
const handlePress = useCallback(() => onSelect(index), [index, onSelect]);
const style = useMemo(
() => [
settingsStyles.row,
styles.row,
index > 0 && settingsStyles.rowBorder,
active && styles.rowActive,
],
[active, index],
);
const accessibilityState = useMemo(() => ({ selected: active, disabled }), [active, disabled]);
return (
<PressHighlight
ref={active ? activeItemRef : undefined}
onLayout={active ? onActiveLayout : undefined}
accessibilityRole="button"
accessibilityState={accessibilityState}
disabled={disabled}
onPress={handlePress}
// Tabbing to a row picks it, so Enter commits the row that has focus.
onFocus={handlePress}
style={style}
highlightStyle={styles.rowActive}
testID={row.testID}
>
<View style={styles.iconSlot}>
<MutedRowGlyph icon={row.icon} size={16} />
</View>
<View style={styles.rowText}>
<Text style={[settingsStyles.rowTitle, styles.rowTitle]} numberOfLines={1}>
{row.title}
</Text>
{row.subtitle ? (
<Text style={styles.rowSubtitle} numberOfLines={1}>
{row.subtitle}
</Text>
) : null}
</View>
{/* Reserved on every row so the active row's mark never shifts its text. */}
<View style={styles.trailingSlot}>{active ? <ActiveMark /> : null}</View>
</PressHighlight>
);
}
/**
* A card of choices with one active row. Arrow keys, taps, and keyboard focus move the active
* row; the sheet's primary action commits it. The list keeps the active row scrolled into view.
*/
export function ResultList({
rows,
activeIndex,
notice,
onSelect,
disabled = false,
testID,
}: ResultListProps) {
const scrollRef = useRef<NativeScrollView>(null);
const listKey = useMemo(() => rows.map((row) => row.id).join("\u0000"), [rows]);
const { activeItemRef, contentRef, onItemLayout, onViewportLayout, onScroll } =
useRevealActiveItem({ activeIndex, listKey, scrollRef });
const showNotice = notice && (rows.length === 0 || notice.kind === "error");
return (
<View style={styles.frame}>
{showNotice ? (
<View style={[settingsStyles.card, styles.noticeCard]} testID={`${testID}-notice`}>
{notice.kind === "pending" ? <ThemedSpinner size={14} /> : null}
<Text
style={notice.kind === "error" ? styles.noticeError : styles.noticeText}
numberOfLines={2}
>
{notice.text}
</Text>
</View>
) : null}
{rows.length > 0 ? (
<View style={[settingsStyles.card, styles.listCard]}>
<ScrollView
ref={scrollRef}
keyboardShouldPersistTaps="always"
onLayout={onViewportLayout}
onScroll={onScroll}
scrollEventThrottle={16}
showsVerticalScrollIndicator={false}
testID={testID}
>
<View ref={contentRef} collapsable={false}>
{rows.map((row, index) => (
<ResultRowView
key={row.id}
row={row}
index={index}
active={index === activeIndex}
disabled={disabled}
activeItemRef={activeItemRef}
onActiveLayout={onItemLayout}
onSelect={onSelect}
/>
))}
</View>
</ScrollView>
</View>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
frame: {
flex: 1,
minHeight: 0,
gap: theme.spacing[3],
},
listCard: {
flexShrink: 1,
minHeight: 0,
},
// Every row is as tall as a two-line row, so rows without a subtitle do not break the rhythm.
row: {
minHeight: theme.spacing[3] * 2 + TITLE_LINE_HEIGHT + SUBTITLE_LINE_HEIGHT,
paddingVertical: theme.spacing[3],
justifyContent: "flex-start",
gap: theme.spacing[3],
},
rowActive: {
backgroundColor: theme.colors.surface2,
},
iconSlot: {
width: 16,
alignItems: "center",
},
rowText: {
flex: 1,
minWidth: 0,
},
rowTitle: {
lineHeight: TITLE_LINE_HEIGHT,
},
rowSubtitle: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
lineHeight: SUBTITLE_LINE_HEIGHT,
},
trailingSlot: {
minWidth: theme.spacing[6],
alignItems: "flex-end",
},
noticeCard: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[4],
},
noticeText: {
flex: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
noticeError: {
flex: 1,
color: theme.colors.statusDanger,
fontSize: theme.fontSize.base,
},
}));
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import { resolveSearch, type SearchAnswer } from "./search-result";
const EMPTY: string[] = [];
function answer(overrides: Partial<SearchAnswer<string>> = {}): SearchAnswer<string> {
return { hostId: "host-1", query: "app", items: ["/code/app"], error: null, ...overrides };
}
function resolve(overrides: Partial<Parameters<typeof resolveSearch<string>>[0]> = {}) {
return resolveSearch<string>({
enabled: true,
hostId: "host-1",
query: "app",
debouncedQuery: "app",
data: answer(),
failed: null,
empty: EMPTY,
...overrides,
});
}
describe("resolveSearch", () => {
it("shows the answer for the current query", () => {
expect(resolve()).toEqual({ items: ["/code/app"], pending: false, error: null });
});
it("keeps the last items while the next query is pending", () => {
expect(resolve({ query: "apps", debouncedQuery: "apps" })).toEqual({
items: ["/code/app"],
pending: true,
error: null,
});
});
it("never shows another host's answer, even for the same query", () => {
expect(resolve({ hostId: "host-2" })).toEqual({ items: [], pending: true, error: null });
});
it("drops the last query's error while the next query is pending", () => {
const failedAnswer = answer({ items: [], error: "Rate limited" });
expect(resolve({ data: failedAnswer })).toEqual({
items: [],
pending: false,
error: "Rate limited",
});
expect(resolve({ data: failedAnswer, query: "apps" })).toEqual({
items: [],
pending: true,
error: null,
});
});
it("shows a failed request only once the user stops typing", () => {
expect(resolve({ data: undefined, failed: "Unable to search" })).toEqual({
items: [],
pending: false,
error: "Unable to search",
});
expect(resolve({ data: undefined, failed: "Unable to search", query: "apps" })).toEqual({
items: [],
pending: true,
error: null,
});
});
it("is idle when disabled", () => {
expect(resolve({ enabled: false })).toEqual({ items: [], pending: false, error: null });
});
});
@@ -0,0 +1,47 @@
/**
* What a search shows while the user types. `items` keep the last results until the current
* query's results arrive, so rows do not flash away on every keystroke.
*/
export interface SearchResult<T> {
items: T[];
/** Results for the current query have not arrived yet. */
pending: boolean;
error: string | null;
}
/** One answer from the host: what it found for `query`, or why it could not search. */
export interface SearchAnswer<T> {
hostId: string | null;
query: string;
items: T[];
error: string | null;
}
/**
* Decides what to show for `query` on `hostId`. An answer from another host never shows. While
* the current query is pending the last items stay, but an old error does not.
*/
export function resolveSearch<T>(input: {
enabled: boolean;
hostId: string | null;
/** What the user typed. */
query: string;
/** The query the last request was sent for; it trails `query` while the user types. */
debouncedQuery: string;
/** The latest answer, which may be for an earlier query or another host. */
data: SearchAnswer<T> | undefined;
/** Why the request for `debouncedQuery` failed, if it did. */
failed: string | null;
empty: T[];
}): SearchResult<T> {
const { enabled, hostId, query, debouncedQuery, data, failed, empty } = input;
if (!enabled) return { items: empty, pending: false, error: null };
if (failed) {
return query === debouncedQuery
? { items: empty, pending: false, error: failed }
: { items: empty, pending: true, error: null };
}
const answer = data?.hostId === hostId ? data : undefined;
if (answer?.query === query) return { items: answer.items, pending: false, error: answer.error };
return { items: answer && !answer.error ? answer.items : empty, pending: true, error: null };
}
@@ -0,0 +1,102 @@
import { useMemo } from "react";
import { useFetchQuery } from "@/data/query";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import type { GithubRepositoryChoice } from "./model";
import { resolveSearch, type SearchResult } from "./search-result";
export type { SearchResult } from "./search-result";
const SEARCH_DEBOUNCE_MS = 250;
const EMPTY_PATHS: string[] = [];
const EMPTY_REPOSITORIES: GithubRepositoryChoice[] = [];
/** Directories on the host matching `query`, debounced while the user types. */
export function useDirectorySearch(input: {
hostId: string | null;
query: string;
enabled: boolean;
}): SearchResult<string> {
const { hostId } = input;
const client = useHostRuntimeClient(hostId ?? "");
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
const enabled = Boolean(client && input.enabled);
const search = useFetchQuery({
queryKey: ["add-project-flow-directories", hostId, debouncedQuery],
queryFn: async () => {
if (!client) throw new Error("Host is unavailable");
const payload = await client.getDirectorySuggestions({
query: debouncedQuery,
includeDirectories: true,
includeFiles: false,
limit: 30,
});
const items =
payload.entries?.flatMap((entry) => (entry.kind === "directory" ? [entry.path] : [])) ?? [];
return { hostId, query: debouncedQuery, items, error: payload.error ?? null };
},
enabled,
dataShape: "list",
retry: false,
staleTimeMs: 15_000,
});
const failed = search.isError ? "Unable to search folders" : null;
return useMemo(
() =>
resolveSearch({
enabled,
hostId,
query: input.query,
debouncedQuery,
data: search.data,
failed,
empty: EMPTY_PATHS,
}),
[debouncedQuery, enabled, failed, hostId, input.query, search.data],
);
}
/** GitHub repositories the host's account can see, matching `query`. */
export function useGithubRepositorySearch(input: {
hostId: string | null;
query: string;
enabled: boolean;
}): SearchResult<GithubRepositoryChoice> {
const { hostId } = input;
const client = useHostRuntimeClient(hostId ?? "");
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
const enabled = Boolean(client && input.enabled);
const search = useFetchQuery({
queryKey: ["add-project-flow-github", hostId, debouncedQuery],
queryFn: async () => {
if (!client) throw new Error("Host is unavailable");
const payload = await client.searchGithubRepositories({ query: debouncedQuery, limit: 30 });
let error: string | null = payload.error ?? null;
if (!error && payload.available === false) error = "GitHub search is unavailable";
return {
hostId,
query: debouncedQuery,
items: error ? EMPTY_REPOSITORIES : payload.repositories,
error,
};
},
enabled,
dataShape: "list",
retry: false,
staleTimeMs: 15_000,
});
const failed = search.isError ? "Unable to search GitHub" : null;
return useMemo(
() =>
resolveSearch({
enabled,
hostId,
query: input.query,
debouncedQuery,
data: search.data,
failed,
empty: EMPTY_REPOSITORIES,
}),
[debouncedQuery, enabled, failed, hostId, input.query, search.data],
);
}
@@ -0,0 +1,29 @@
import type { ResultListNotice, ResultRow } from "./result-list";
/** What the sheet needs from the current tab to drive its keys and its primary button. */
export interface AddProjectTabView {
/** The rows Up and Down walk; empty for a tab without a list. */
rows: ResultRow[];
/** The active row, or -1 when none is: an older search's rows, or a pick the new answer dropped. */
activeIndex: number;
notice: ResultListNotice | null;
/** Why this host cannot do what the tab offers; the tab's fields are read-only while set. */
unavailable: string | null;
primary: {
label: string;
/** Absent when there is nothing to commit yet. */
submit: (() => void) | null;
};
}
/**
* Where the user's pick sits in `rows`. Without a pick, the first row is the default. A pick that
* a new answer dropped is not swapped for another row: nothing is active until the user picks again.
*/
export function resolveActiveIndex(
rows: readonly { id: string }[],
selectedId: string | null,
): number {
if (selectedId === null) return rows.length > 0 ? 0 : -1;
return rows.findIndex((row) => row.id === selectedId);
}
@@ -0,0 +1,182 @@
import { useCallback, useEffect, useRef, type Dispatch, type SetStateAction } from "react";
import { router } from "expo-router";
import type { WorkspaceProjectDescriptorPayload } from "@getpaseo/protocol/messages";
import { pickDirectory } from "@/desktop/pick-directory";
import { getOpenProjectFailureReason, registerProjectDescriptor } from "@/hooks/open-project";
import { useCloneGithubProject, useOpenProject } from "@/hooks/use-open-project";
import { getHostRuntimeStore, useHostRuntimeClient } from "@/runtime/host-runtime";
import { useAddProjectFlowStore } from "@/stores/add-project-flow-store";
import { usePanelStore } from "@/stores/panel-store";
import { useSessionStore } from "@/stores/session-store";
import { buildNewWorkspaceRoute } from "@/utils/host-routes";
import {
failAddProjectSubmission,
startAddProjectSubmission,
type AddProjectFlowState,
type GithubRepositoryChoice,
} from "./model";
/** A failure found before any work starts, shown the same way as one the host reports. */
function rejectSubmission(state: AddProjectFlowState, message: string): AddProjectFlowState {
return failAddProjectSubmission(startAddProjectSubmission(state), message);
}
export interface AddProjectActions {
openFolder: (path: string) => void;
browse: () => void;
clone: (repository: GithubRepositoryChoice, location: string) => void;
/** Expects a name that passed `validateNewFolderName`; the New folder tab only offers those. */
createFolder: (name: string, location: string) => void;
}
/** What a submission's work reports: the project to open, or why it failed. */
type SubmissionOutcome =
| { ok: true; project: WorkspaceProjectDescriptorPayload }
| { ok: false; error: string };
/**
* The three ways a project gets added. Each one records its progress and failure in the flow
* state and, on success, closes the flow and opens a new workspace for the project.
*/
export function useAddProjectActions(input: {
hostId: string | null;
setState: Dispatch<SetStateAction<AddProjectFlowState>>;
onClose: () => void;
}): AddProjectActions {
const { hostId, setState, onClose } = input;
const client = useHostRuntimeClient(hostId ?? "");
const openProject = useOpenProject(hostId);
const cloneGithubProject = useCloneGithubProject(hostId);
const setHasHydratedWorkspaces = useSessionStore((store) => store.setHasHydratedWorkspaces);
const rememberLocation = useAddProjectFlowStore((store) => store.rememberLocation);
// The running submission, if any. It belongs to the open sheet and the host it started on:
// closing the sheet or losing that host abandons it, so a late result neither navigates nor
// blocks the next submission.
const submissionRef = useRef<symbol | null>(null);
useEffect(
() => () => {
submissionRef.current = null;
},
[hostId],
);
/** Runs one submission at a time and opens a new workspace for the project it adds. */
const run = useCallback(
async (serverId: string, work: () => Promise<SubmissionOutcome>, fallbackError: string) => {
if (submissionRef.current) return;
const submission = Symbol("add-project-submission");
submissionRef.current = submission;
const isCurrent = () => submissionRef.current === submission;
setState(startAddProjectSubmission);
let outcome: SubmissionOutcome;
try {
outcome = await work();
} catch (error) {
const message = error instanceof Error && error.message ? error.message : fallbackError;
outcome = { ok: false, error: message };
}
if (!isCurrent()) return;
submissionRef.current = null;
if (!outcome.ok) {
setState((state) => failAddProjectSubmission(state, outcome.error));
return;
}
onClose();
usePanelStore.getState().showMobileAgent();
router.push(
buildNewWorkspaceRoute({
serverId,
projectId: outcome.project.projectId,
sourceDirectory: outcome.project.projectRootPath,
displayName: outcome.project.projectDisplayName,
}),
);
},
[onClose, setState],
);
const openFolder = useCallback(
(path: string) => {
if (!hostId) return;
void run(
hostId,
async () => {
const result = await openProject(path);
if (result.ok) return { ok: true, project: result.project };
if (getOpenProjectFailureReason(result) === "directory_not_found") {
return { ok: false, error: "Folder not found" };
}
return { ok: false, error: result.error ?? "Unable to add project" };
},
"Unable to add project",
);
},
[hostId, openProject, run],
);
// The desktop folder dialog is modal to the window, so nothing else can start while it is open.
const browse = useCallback(() => {
if (!hostId || submissionRef.current) return;
void (async () => {
try {
const path = await pickDirectory();
if (path) openFolder(path);
} catch {
setState((state) => rejectSubmission(state, "Unable to browse for a folder"));
}
})();
}, [hostId, openFolder, setState]);
const clone = useCallback(
(repository: GithubRepositoryChoice, location: string) => {
if (!hostId) return;
void run(
hostId,
async () => {
const result = await cloneGithubProject(
repository.cloneUrl,
location,
repository.cloneProtocol,
);
if (!result.ok) return { ok: false, error: result.error ?? "Unable to clone project" };
rememberLocation(hostId, location);
return { ok: true, project: result.project };
},
"Unable to clone project",
);
},
[cloneGithubProject, hostId, rememberLocation, run],
);
const createFolder = useCallback(
(name: string, location: string) => {
if (!hostId) return;
void run(
hostId,
async () => {
if (!client) return { ok: false, error: "Unable to create folder" };
const payload = await client.createProjectDirectory({
parentPath: location,
name: name.trim(),
});
if (payload.error || !payload.project) {
return { ok: false, error: payload.error ?? "Unable to create folder" };
}
registerProjectDescriptor({
serverId: hostId,
project: payload.project,
upsertProject: (serverId, project) =>
getHostRuntimeStore().acceptProjectSnapshot(serverId, project),
setHasHydratedWorkspaces,
});
rememberLocation(hostId, location);
return { ok: true, project: payload.project };
},
"Unable to create folder",
);
},
[client, hostId, rememberLocation, run, setHasHydratedWorkspaces],
);
return { openFolder, browse, clone, createFolder };
}
@@ -0,0 +1,51 @@
import { useMemo } from "react";
import { getIsElectronRuntime } from "@/constants/layout";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHosts, useHostRuntimeConnectionStatuses } from "@/runtime/host-runtime";
import { useHostFeatureMap } from "@/runtime/host-features";
import { orderHostsLocalFirst } from "@/types/host-connection";
import type { AddProjectHost } from "./model";
/** Every host, whether it is online, and what each can do in Add project, the local host first. */
export function useAddProjectHosts(): AddProjectHost[] {
const hosts = useHosts();
const hostIds = useMemo(() => hosts.map((host) => host.serverId), [hosts]);
const connectionStatuses = useHostRuntimeConnectionStatuses(hostIds);
const projectAddByHost = useHostFeatureMap(hostIds, "projectAdd");
// COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15.
const stableProjectIdentityByHost = useHostFeatureMap(hostIds, "stableProjectIdentity");
// COMPAT(projectGithubClone): added in v0.1.108, remove gate after 2027-01-15.
const githubCloneByHost = useHostFeatureMap(hostIds, "projectGithubClone");
// COMPAT(workspaceGithubRepositorySearch): added in v0.1.108, remove gate after 2027-01-15.
const githubSearchByHost = useHostFeatureMap(hostIds, "workspaceGithubRepositorySearch");
// COMPAT(projectCreateDirectory): added in v0.1.108, remove gate after 2027-01-15.
const createDirectoryByHost = useHostFeatureMap(hostIds, "projectCreateDirectory");
const localServerId = useLocalDaemonServerId();
return useMemo<AddProjectHost[]>(() => {
return orderHostsLocalFirst(hosts, localServerId).map((host) => {
const canAddProject =
projectAddByHost.get(host.serverId) === true &&
stableProjectIdentityByHost.get(host.serverId) === true;
return {
serverId: host.serverId,
label: host.label,
online: connectionStatuses.get(host.serverId) === "online",
canAddProject,
canBrowse: canAddProject && getIsElectronRuntime() && localServerId === host.serverId,
canCloneGithubRepositories: githubCloneByHost.get(host.serverId) === true,
canSearchGithubRepositories: githubSearchByHost.get(host.serverId) === true,
canCreateDirectory: createDirectoryByHost.get(host.serverId) === true,
};
});
}, [
connectionStatuses,
createDirectoryByHost,
githubCloneByHost,
githubSearchByHost,
hosts,
localServerId,
projectAddByHost,
stableProjectIdentityByHost,
]);
}
@@ -1,11 +1,76 @@
import { useCallback, useMemo, useState, type ReactElement } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { Button } from "@/components/ui/button";
import { useToast } from "@/contexts/toast-context";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { confirmDialog } from "@/utils/confirm-dialog";
import { toErrorMessage } from "@/utils/error-messages";
import { AgentProfileEditModal } from "./settings/agent-profile-edit-modal";
import { generateAgentProfileId } from "./internal/profile-id";
import type { AgentProfileSeed, AgentProfileValue } from "./internal/profile-form-model";
import { useAgentProfiles } from "./internal/use-agent-profiles";
import {
buildInstantAgentProfile,
type AgentProfileSeed,
type AgentProfileValue,
} from "./internal/profile-form-model";
import { removeAgentProfileById, useAgentProfiles } from "./internal/use-agent-profiles";
const PROFILE_SAVED_TOAST_DURATION_MS = 6000;
function ProfileSavedToastContent({
name,
onEdit,
onUndo,
}: {
name: string;
onEdit: () => void;
onUndo: () => void;
}): ReactElement {
const { t } = useTranslation();
return (
<View style={styles.toastRow}>
<Text style={styles.toastText} numberOfLines={1}>
{t("modelSelector.profileSaved", { name })}
</Text>
<View style={styles.toastActions}>
<Button
variant="secondary"
size="sm"
onPress={onEdit}
accessibilityLabel={t("modelSelector.editProfileLabel", { name })}
testID="model-profile-created-edit"
>
{t("modelSelector.editProfiles")}
</Button>
<Button
variant="outline"
size="sm"
onPress={onUndo}
accessibilityLabel={t("modelSelector.undoProfileSave")}
testID="model-profile-created-undo"
>
{t("modelSelector.undo")}
</Button>
</View>
</View>
);
}
function createProfileSavedToast(input: {
name: string;
onEdit: () => void;
onUndo: () => void;
}): ReactElement {
return <ProfileSavedToastContent name={input.name} onEdit={input.onEdit} onUndo={input.onUndo} />;
}
export interface AgentProfileEditorControls {
/** Save a profile immediately from a model row with defaults and show an Edit/Undo toast. */
quickCreateFromModel: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
/** Undo an instant creation without a confirmation prompt. */
undoCreate: (profileId: string) => Promise<void>;
/** Open the create form pre-filled with provider, model, and suggested name. */
openCreateFromModel: (seed: AgentProfileSeed) => void;
/** Open the edit form for one profile. */
@@ -23,8 +88,78 @@ type EditorRequest =
* never see `saveProfiles` or construct profile records themselves.
*/
export function useAgentProfileEditor(serverId: string | null): AgentProfileEditorControls {
const { profiles, saveProfiles } = useAgentProfiles(serverId);
const { t } = useTranslation();
const toast = useToast();
const { profiles, mutateProfiles } = useAgentProfiles(serverId);
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
const [request, setRequest] = useState<EditorRequest | null>(null);
const mountedRef = useRef(true);
const dismissSavedToastRef = useRef<(() => void) | null>(null);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
dismissSavedToastRef.current?.();
dismissSavedToastRef.current = null;
};
}, []);
const undoCreate = useCallback(
async (profileId: string): Promise<void> => {
try {
await mutateProfiles((current) => removeAgentProfileById(current, profileId));
} catch (error) {
toast.error(toErrorMessage(error));
}
},
[mutateProfiles, toast],
);
const quickCreateFromModel = useCallback(
async (seed: AgentProfileSeed): Promise<AgentProfile | null> => {
const value = buildInstantAgentProfile({ seed, entries });
const created: AgentProfile = { id: generateAgentProfileId(), ...value };
try {
const written = await mutateProfiles((current) => [...current, created]);
if (!written || !mountedRef.current) {
return written ? created : null;
}
dismissSavedToastRef.current?.();
let dismiss: (() => void) | null = null;
const clearToast = () => {
dismiss?.();
if (dismissSavedToastRef.current === dismiss) {
dismissSavedToastRef.current = null;
}
};
dismiss = toast.show(
createProfileSavedToast({
name: created.name,
onEdit: () => {
clearToast();
setRequest({ mode: "edit", profile: created });
},
onUndo: () => {
clearToast();
void undoCreate(created.id);
},
}),
{
variant: "success",
durationMs: PROFILE_SAVED_TOAST_DURATION_MS,
testID: "model-profile-created-toast",
},
);
dismissSavedToastRef.current = dismiss;
return created;
} catch (error) {
toast.error(toErrorMessage(error));
return null;
}
},
[entries, mutateProfiles, toast, undoCreate],
);
const openCreateFromModel = useCallback((seed: AgentProfileSeed) => {
setRequest({ mode: "create", seed });
@@ -45,15 +180,59 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
const handleSave = useCallback(
async (value: AgentProfileValue) => {
const current = profiles ?? [];
const editing = request?.mode === "edit" ? request.profile : undefined;
const next: AgentProfile[] = editing
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
: [...current, { id: generateAgentProfileId(), ...value }];
await saveProfiles(next);
setRequest(null);
const savedRequest = request;
const editing = savedRequest?.mode === "edit" ? savedRequest.profile : undefined;
const written = await mutateProfiles((current) =>
editing
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
: [...current, { id: generateAgentProfileId(), ...value }],
);
if (!written) {
return;
}
setRequest((current) => (current === savedRequest ? null : current));
},
[profiles, request, saveProfiles],
[mutateProfiles, request],
);
const handleRemove = useCallback(
(profileId: string) => {
const profile = profiles?.find((entry) => entry.id === profileId);
if (!profile) {
return;
}
const confirmAndRemove = async () => {
const confirmed = await confirmDialog({
title: t("settings.host.agentProfiles.removeConfirmTitle"),
message: t("settings.host.agentProfiles.removeConfirmMessage", { name: profile.name }),
confirmLabel: t("settings.host.agentProfiles.remove"),
cancelLabel: t("common.actions.cancel"),
destructive: true,
});
if (!confirmed) {
return;
}
try {
const updated = await mutateProfiles((current) =>
removeAgentProfileById(current, profileId),
);
if (updated) {
setRequest((current) =>
current?.mode === "edit" && current.profile.id === profileId ? null : current,
);
}
} catch (error) {
const detail = toErrorMessage(error);
toast.error(
detail
? `${t("common.errors.unableToSave")}: ${detail}`
: t("common.errors.unableToSave"),
);
}
};
void confirmAndRemove();
},
[mutateProfiles, profiles, t, toast],
);
const element = useMemo(
@@ -66,13 +245,34 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
{...(request?.mode === "create" && request.seed ? { seed: request.seed } : {})}
onClose={close}
onSave={handleSave}
onRemove={handleRemove}
/>
),
[close, handleSave, request, serverId],
[close, handleRemove, handleSave, request, serverId],
);
return useMemo(
() => ({ openCreateFromModel, openEdit, element }),
[openCreateFromModel, openEdit, element],
() => ({ quickCreateFromModel, undoCreate, openCreateFromModel, openEdit, element }),
[element, openCreateFromModel, openEdit, quickCreateFromModel, undoCreate],
);
}
const styles = StyleSheet.create((theme) => ({
toastRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
maxWidth: "100%",
},
toastText: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
toastActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
flexShrink: 0,
},
}));
+7 -3
View File
@@ -8,8 +8,9 @@
* rules, the icon registry, the row and modal chrome) is internal; import from
* `@/agent-profiles`, never a path inside it.
*
* `useAgentProfilePicker` deliberately hands the picker a flat row view model
* and one `applyProfile(id)` callback rather than the profiles themselves: what
* `useAgentProfilePicker` deliberately hands the picker — and the Command Center,
* which offers the same rows — a flat row view model and one `applyProfile(id)`
* callback rather than the profiles themselves: what
* a profile contains, and how it reaches a live agent versus a draft, stays in
* here.
*/
@@ -26,4 +27,7 @@ export {
type DraftAgentProfileControls,
} from "./internal/use-agent-profile-picker";
export { AgentProfileGlyph } from "./internal/agent-profile-glyph";
export { AgentProfilesSection } from "./settings/agent-profiles-section";
export {
AgentProfilesPage,
type AgentProfilesBeforeLeaveGuard,
} from "./settings/agent-profiles-section";
@@ -31,6 +31,7 @@ import {
TestTube,
Wrench,
} from "lucide-react-native";
import { useProviderIcon } from "@/components/provider-icons";
import { identityForeground } from "@/styles/identity-colors";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import {
@@ -108,21 +109,57 @@ export function agentProfileColorMapping(
return COLOR_MAPPINGS[color];
}
function ProviderFallbackIcon({
provider,
serverId,
size,
color = "",
}: {
provider: string;
serverId?: string | null;
size: number;
color?: string;
}) {
const Icon = useProviderIcon(provider, serverId);
return <Icon size={size} color={color} />;
}
const ThemedProviderFallbackIcon = withUnistyles(ProviderFallbackIcon);
/**
* How a profile is drawn everywhere it appears — settings list, model picker,
* and the picker grid's own cells. One component so the three can't drift.
* How a profile is drawn everywhere it appears — settings roster, model picker,
* drawer/sheet header, and the picker grid's own cells. When no custom icon is
* chosen and a provider is known, it falls back to that provider's mark instead
* of repeating identical generic stars across every row.
*/
export function AgentProfileGlyph({
icon,
color,
provider,
serverId,
size = ICON_SIZE.md,
}: {
icon?: string | undefined;
color?: string | undefined;
provider?: string | undefined;
serverId?: string | null | undefined;
size?: number;
}) {
const iconKey = resolveAgentProfileIconKey(icon);
const mapping = COLOR_MAPPINGS[resolveAgentProfileColor(color)];
const Icon = iconKey ? THEMED_ICONS[iconKey] : ThemedDefaultIcon;
return <Icon size={size} uniProps={mapping} />;
if (iconKey) {
const Icon = THEMED_ICONS[iconKey];
return <Icon size={size} uniProps={mapping} />;
}
if (provider) {
return (
<ThemedProviderFallbackIcon
provider={provider}
serverId={serverId}
size={size}
uniProps={mapping}
/>
);
}
return <ThemedDefaultIcon size={size} uniProps={mapping} />;
}
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { selectApplicableProfiles } from "./applicable-profiles";
function profile(id: string, provider: string, name = id): AgentProfile {
return { id, name, provider };
}
describe("selectApplicableProfiles", () => {
it("keeps only profiles naming a provider the composer can run", () => {
const claude = profile("a", "claude");
const codex = profile("b", "codex");
expect(selectApplicableProfiles([claude, codex], ["claude"])).toEqual([claude]);
});
it("keeps the first profile when a stored config repeats an id", () => {
const first = profile("same", "claude", "First");
const second = profile("same", "claude", "Second");
expect(selectApplicableProfiles([first, second], ["claude"])).toEqual([first]);
});
});
@@ -0,0 +1,22 @@
import type { AgentProfile } from "@getpaseo/protocol/messages";
/**
* The profiles a composer can offer: those naming a provider it can run, one
* per id. The daemon stores whatever list it is given, so a hand-edited config
* can repeat an id; the first entry wins, which is also the one `applyProfile`
* resolves, and every surface that keys on the id stays unique.
*/
export function selectApplicableProfiles(
profiles: readonly AgentProfile[],
availableProviders: readonly string[],
): AgentProfile[] {
const available = new Set(availableProviders);
const seenIds = new Set<string>();
const applicable: AgentProfile[] = [];
for (const profile of profiles) {
if (!available.has(profile.provider) || seenIds.has(profile.id)) continue;
seenIds.add(profile.id);
applicable.push(profile);
}
return applicable;
}
@@ -2,6 +2,7 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import { describe, expect, it } from "vitest";
import {
buildControlsRequestKey,
buildInstantAgentProfile,
openAgentProfileForm,
type AgentProfileFormModel,
} from "./profile-form-model";
@@ -70,6 +71,10 @@ function optionValues(options: readonly { value: string }[]): string[] {
return options.map((option) => option.value);
}
function optionIds(options: readonly { id: string }[]): string[] {
return options.map((option) => option.id);
}
const FAST = {
controls: [{ type: "toggle" as const, key: "fast_mode", label: "Fast" }],
options: { fast_mode: false },
@@ -528,16 +533,71 @@ describe("openAgentProfileForm", () => {
});
});
it("draws no controls for the previous model while another model's answer is pending", () => {
it("keeps previous provider controls mounted while another model's answer is pending to prevent layout jank", () => {
const model = openWithCatalog({ mode: "create" });
selectClaude(model);
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
expect(model.getState().controlsResolution).toBe("pending");
expect(model.getState().controlsPending).toBe(true);
expect(model.getState().controls).toHaveLength(1);
// Switching providers clears controls immediately so stale controls never cross providers.
model.setProvider("codex", { label: "Codex" });
expect(model.getState().controls).toEqual([]);
});
it("seeds the catalog synchronously when entries are passed in the initial snapshot", () => {
const model = openAgentProfileForm({
mode: "edit",
profile: { id: "p1", name: "UI work", provider: "claude", model: "claude-opus-5" },
entries: ENTRIES,
});
const state = model.getState();
expect(state.catalogResolution).toBe("complete");
expect(state.providerDisplay).toEqual({ label: "Claude Code" });
expect(state.modelDisplay).toEqual({ label: "Opus 5" });
expect(optionIds(state.unifiedModelOptions)).toEqual([
"claude:claude-opus-5",
"claude:claude-haiku-4-5",
"codex:gpt-5.2-codex",
]);
});
it("updates provider, model, and auto-suggested name together via setProviderModel", () => {
const model = openAgentProfileForm({ mode: "create", entries: ENTRIES });
model.setProviderModel("claude", "claude-opus-5", {
provider: { label: "Claude Code" },
model: { label: "Opus 5" },
});
expect(model.getState().name).toBe("Opus 5");
expect(model.getState().provider).toBe("claude");
expect(model.getState().modelId).toBe("claude-opus-5");
expect(model.getState().modeId).toBe("plan");
expect(model.getState().thinkingOptionId).toBe("think");
// Switching to another model while untouched updates the suggested name.
model.setProviderModel("codex", "gpt-5.2-codex", {
provider: { label: "Codex" },
model: { label: "GPT-5.2 Codex" },
});
expect(model.getState().name).toBe("GPT-5.2 Codex");
expect(model.getState().provider).toBe("codex");
expect(model.getState().modeId).toBe("read-only");
// Once the user types a custom name, changing model preserves it.
model.setName("My Custom Worker");
model.setProviderModel("claude", "claude-haiku-4-5", {
provider: { label: "Claude Code" },
model: { label: "Haiku 4.5" },
});
expect(model.getState().name).toBe("My Custom Worker");
});
it("does not save a toggle once the model that drew it is replaced by one without it", () => {
const model = toggledOnOpus();
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
@@ -643,6 +703,36 @@ describe("openAgentProfileForm", () => {
expect(notifications).toBe(1);
expect(model.getState().name).toBe("a");
});
it("does not treat catalog-prefilled defaults on a minimal profile as an unsaved edit", () => {
const model = openAgentProfileForm({
mode: "edit",
profile: {
id: "legacy_favorite:claude:claude-opus-5",
name: "Opus 5",
provider: "claude",
model: "claude-opus-5",
},
});
expect(model.getState().isDirty).toBe(false);
// Catalog fills in default modeId ("plan") and thinkingOptionId ("think").
model.applyProviderCatalog(ENTRIES);
expect(model.getState().modeId).toBe("plan");
expect(model.getState().thinkingOptionId).toBe("think");
expect(model.getState().isDirty).toBe(false);
// User edit marks dirty and advances draftRevision; a subsequent edit advances it again.
expect(model.getState().draftRevision).toBe(0);
model.setName("Renamed");
expect(model.getState().isDirty).toBe(true);
expect(model.getState().draftRevision).toBe(1);
model.setName("Renamed again");
expect(model.getState().draftRevision).toBe(2);
model.setName("Opus 5");
expect(model.getState().isDirty).toBe(false);
expect(model.getState().draftRevision).toBe(3);
});
});
describe("buildControlsRequestKey", () => {
@@ -657,3 +747,55 @@ describe("buildControlsRequestKey", () => {
);
});
});
describe("buildInstantAgentProfile", () => {
it("builds a concrete profile with provider defaults from a model seed", () => {
expect(
buildInstantAgentProfile({
seed: { provider: "claude", modelId: "claude-opus-5", name: "Opus 5" },
entries: ENTRIES,
}),
).toEqual({
name: "Opus 5",
provider: "claude",
model: "claude-opus-5",
modeId: "plan",
thinkingOptionId: "think",
options: {},
});
});
it("keeps compatible preferred mode and thinking levels and ignores incompatible ones", () => {
expect(
buildInstantAgentProfile({
seed: { provider: "claude", modelId: "claude-opus-5" },
entries: ENTRIES,
preferredModeId: "accept-edits",
preferredThinkingOptionId: "think-hard",
}),
).toEqual({
name: "Opus 5",
provider: "claude",
model: "claude-opus-5",
modeId: "accept-edits",
thinkingOptionId: "think-hard",
options: {},
});
expect(
buildInstantAgentProfile({
seed: { provider: "claude", modelId: "claude-haiku-4-5" },
entries: ENTRIES,
preferredModeId: "unknown-mode",
preferredThinkingOptionId: "think-hard",
}),
).toEqual({
name: "Haiku 4.5",
provider: "claude",
model: "claude-haiku-4-5",
modeId: "plan",
thinkingOptionId: "think",
options: {},
});
});
});
@@ -41,6 +41,16 @@ export interface AgentProfileFormOption {
testID: string;
}
export interface AgentProfileUnifiedModelOption {
id: string;
provider: string;
providerLabel: string;
modelId: string;
label: string;
description?: string;
testID: string;
}
/**
* Pre-fill values for create mode. Only used when `mode === "create"`; edit
* mode always seeds from the stored `profile` and ignores this.
@@ -55,6 +65,8 @@ export interface AgentProfileFormSnapshot {
mode: "create" | "edit";
profile?: AgentProfile;
seed?: AgentProfileSeed;
/** Optional cached host catalog so the first render is already hydrated without a layout flash. */
entries?: readonly ProviderSnapshotEntry[];
}
/**
@@ -97,6 +109,7 @@ export interface AgentProfileFormState {
optionEdits: ProviderOptions;
providerOptions: AgentProfileFormOption[];
unifiedModelOptions: AgentProfileUnifiedModelOption[];
modelOptions: AgentProfileFormOption[];
modeOptions: AgentProfileFormOption[];
thinkingOptions: AgentProfileFormOption[];
@@ -115,10 +128,14 @@ export interface AgentProfileFormState {
catalogResolution: AgentProfileResolutionStatus;
controlsResolution: AgentProfileResolutionStatus;
controlsPending: boolean;
controlsRequest: AgentProfileControlsRequest | null;
controlsRequestKey: string | null;
disclosure: AgentProfileFormDisclosure;
isDirty: boolean;
/** Monotonic counter incremented on every user edit that changes the draft. */
draftRevision: number;
isSubmitting: boolean;
submitError: string | null;
canSubmit: boolean;
@@ -142,6 +159,11 @@ export interface AgentProfileFormModel {
setAppearance: (value: { icon: string; color: string }) => void;
setNotes: (value: string) => void;
setProvider: (providerId: string, display: AgentProfileFormDisplay) => void;
setProviderModel: (
providerId: string,
modelId: string,
displays: { provider: AgentProfileFormDisplay; model: AgentProfileFormDisplay | null },
) => void;
setModel: (modelId: string, display: AgentProfileFormDisplay | null) => void;
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
@@ -224,6 +246,53 @@ function buildProviderOptions(entries: readonly ProviderSnapshotEntry[]): AgentP
);
}
function formatUnifiedModelDescription(providerLabel: string, model: AgentModelDefinition): string {
if (model.description && model.description !== providerLabel) {
return `${providerLabel} · ${model.description}`;
}
if (model.id !== model.label) {
return `${providerLabel} · ${model.id}`;
}
return providerLabel;
}
function buildUnifiedModelOptions(
entries: readonly ProviderSnapshotEntry[],
): AgentProfileUnifiedModelOption[] {
const options: AgentProfileUnifiedModelOption[] = [];
for (const entry of entries) {
if (!entry.enabled) {
continue;
}
const providerLabel = entry.label ?? entry.provider;
const models = filterSelectableModels(entry.models ?? null) ?? [];
if (models.length === 0) {
options.push({
id: `${entry.provider}:`,
provider: entry.provider,
providerLabel,
modelId: "",
label: providerLabel,
...(entry.description ? { description: entry.description } : {}),
testID: `agent-profile-unified-model-${entry.provider}`,
});
continue;
}
for (const model of models) {
options.push({
id: `${entry.provider}:${model.id}`,
provider: entry.provider,
providerLabel,
modelId: model.id,
label: model.label,
description: formatUnifiedModelDescription(providerLabel, model),
testID: `agent-profile-unified-model-${entry.provider}-${model.id}`,
});
}
}
return options;
}
function buildModelOptions(models: readonly AgentModelDefinition[]): AgentProfileFormOption[] {
return models.map((model) =>
formOption({
@@ -385,6 +454,28 @@ export function buildControlsRequestKey(
: scope;
}
function stableOptionsKey(record: ProviderOptions): string {
const keys = Object.keys(record).sort();
if (keys.length === 0) {
return "";
}
return JSON.stringify(keys.map((key) => [key, record[key]]));
}
function formDraftFingerprint(state: AgentProfileFormState): string {
return JSON.stringify([
state.name.trim(),
state.icon,
state.color,
state.provider,
state.modelId,
state.modeId,
state.thinkingOptionId,
state.notes.trim(),
stableOptionsKey(ownOptionsOf(state)),
]);
}
function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | null {
const name = state.name.trim();
const notes = state.notes.trim();
@@ -446,6 +537,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
options: { ...profile.options },
optionEdits: {},
providerOptions: [],
unifiedModelOptions: [],
modelOptions: [],
modeOptions: [],
thinkingOptions: [],
@@ -459,6 +551,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
catalogResolution: "idle",
controlsResolution: "idle",
controlsPending: false,
controlsRequest: null,
controlsRequestKey: null,
disclosure: {
@@ -467,6 +560,8 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
showThinkingField: false,
showControlsField: false,
},
isDirty: false,
draftRevision: 0,
isSubmitting: false,
submitError: null,
canSubmit: false,
@@ -474,17 +569,118 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
};
}
function pickMatchingId(
preferred: string | null | undefined,
options: readonly { id: string }[],
fallback: string,
): string {
const trimmed = preferred?.trim() ?? "";
if (trimmed && options.some((option) => option.id === trimmed)) {
return trimmed;
}
return fallback;
}
/**
* Builds a ready-to-save profile in one tap (for composer model-row `+` creation).
* Resolves defaults from the host catalog and preserves compatible composer mode/thinking
* when provided, so the stored profile is concrete from the moment it is created.
*/
export function buildInstantAgentProfile(input: {
seed: AgentProfileSeed;
entries: readonly ProviderSnapshotEntry[] | undefined;
preferredModeId?: string | null;
preferredThinkingOptionId?: string | null;
}): AgentProfileValue {
const entries = input.entries ?? [];
const entry = findEntry(entries, input.seed.provider);
const models = resolveModels(entries, input.seed.provider);
const modes = resolveModes(entries, input.seed.provider);
const modelId = input.seed.modelId?.trim() || defaultModelId(models);
const effectiveModel = resolveEffectiveModel(models, modelId);
const matchedModel = models.find((candidate) => candidate.id === modelId);
const modeId = pickMatchingId(input.preferredModeId, modes, defaultModeId(entry, modes));
const thinkingOptionId = pickMatchingId(
input.preferredThinkingOptionId,
effectiveModel?.thinkingOptions ?? [],
defaultThinkingOptionId(effectiveModel),
);
const name =
[input.seed.name?.trim(), matchedModel?.label, modelId, entry?.label, input.seed.provider].find(
(candidate): candidate is string => Boolean(candidate),
) ?? input.seed.provider;
return {
name,
provider: input.seed.provider,
...(modelId ? { model: modelId } : {}),
...(modeId ? { modeId } : {}),
...(thinkingOptionId ? { thinkingOptionId } : {}),
options: {},
};
}
function resolveModeLabel(modes: readonly AgentMode[], modeId: string): string | null {
const mode = modes.find((entry) => entry.id === modeId);
return mode ? formatAgentModeLabel(mode) : null;
}
function resolveThinkingLabel(options: readonly AgentSelectOption[], id: string): string | null {
const option = options.find((entry) => entry.id === id);
return option ? formatThinkingOptionLabel(option) : null;
}
function resolveControlsSlice(input: {
next: AgentProfileFormState;
controlsRequestKey: string | null;
controlsScopeKey: string | null;
resolvedControlsKey: string | null;
resolvedScopeKey: string | null;
resolvedProvider: string | null;
resolvedControls: AgentOptionControl[];
resolvedOptions: ProviderOptions;
}): {
controls: AgentOptionControl[];
controlOptions: ProviderOptions;
controlsResolution: AgentProfileResolutionStatus;
} {
const featuresAreCurrent =
input.controlsRequestKey !== null && input.controlsRequestKey === input.resolvedControlsKey;
const controlsApply =
input.controlsScopeKey !== null &&
(input.controlsScopeKey === input.resolvedScopeKey ||
(input.next.provider.length > 0 && input.next.provider === input.resolvedProvider));
const controls = controlsApply ? input.resolvedControls : [];
let controlOptions: ProviderOptions = input.next.options;
if (controlsApply) {
controlOptions = featuresAreCurrent
? input.resolvedOptions
: { ...input.resolvedOptions, ...input.next.optionEdits };
}
return {
controls,
controlOptions,
controlsResolution: resolveControlsStatus(input.controlsRequestKey, featuresAreCurrent),
};
}
export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentProfileFormModel {
let entries: readonly ProviderSnapshotEntry[] = [];
let catalogResolution: AgentProfileResolutionStatus = "idle";
let entries: readonly ProviderSnapshotEntry[] = snapshot.entries ? [...snapshot.entries] : [];
let catalogResolution: AgentProfileResolutionStatus = snapshot.entries ? "complete" : "idle";
let resolvedControlsKey: string | null = null;
let resolvedScopeKey: string | null = null;
let resolvedProvider: string | null = null;
let resolvedControls: AgentOptionControl[] = [];
let resolvedOptions: ProviderOptions = {};
let drawnKeys: ReadonlySet<string> = new Set();
let answeredKeys: ReadonlySet<string> = new Set();
let listeners = new Set<() => void>();
let closed = false;
let hasUserEdited = false;
let draftRevision = 0;
let baselineFingerprint = "";
let autoSuggestedName: string | null =
snapshot.mode === "create" ? (snapshot.seed?.name ?? null) : null;
function derive(incoming: AgentProfileFormState): AgentProfileFormState {
const models = resolveModels(entries, incoming.provider);
@@ -502,24 +698,21 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
const controlsRequest = buildControlsRequest(next);
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
const featuresAreCurrent =
controlsRequestKey !== null && controlsRequestKey === resolvedControlsKey;
// A toggle changes only the options, so the controls stay up while the daemon answers and the
// toggle shows over the last answer. A change of provider, model, mode or thinking draws none
// until its own answer arrives.
const controlsApply = controlsScopeKey !== null && controlsScopeKey === resolvedScopeKey;
const controls = controlsApply ? resolvedControls : [];
let controlOptions: ProviderOptions = next.options;
if (controlsApply) {
controlOptions = featuresAreCurrent
? resolvedOptions
: { ...resolvedOptions, ...next.optionEdits };
}
const controlsResolution = resolveControlsStatus(controlsRequestKey, featuresAreCurrent);
const { controls, controlOptions, controlsResolution } = resolveControlsSlice({
next,
controlsRequestKey,
controlsScopeKey,
resolvedControlsKey,
resolvedScopeKey,
resolvedProvider,
resolvedControls,
resolvedOptions,
});
const withOptions: AgentProfileFormState = {
...next,
providerOptions: buildProviderOptions(entries),
unifiedModelOptions: buildUnifiedModelOptions(entries),
modelOptions: buildModelOptions(models),
modeOptions: buildModeOptions(modes),
thinkingOptions: buildThinkingOptions(thinking),
@@ -538,21 +731,16 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
modeDisplay: refineDisplay(
next.modeDisplay,
next.modeId,
(() => {
const mode = modes.find((entry) => entry.id === next.modeId);
return mode ? formatAgentModeLabel(mode) : null;
})(),
resolveModeLabel(modes, next.modeId),
),
thinkingDisplay: refineDisplay(
next.thinkingDisplay,
next.thinkingOptionId,
(() => {
const option = thinking.find((entry) => entry.id === next.thinkingOptionId);
return option ? formatThinkingOptionLabel(option) : null;
})(),
resolveThinkingLabel(thinking, next.thinkingOptionId),
),
catalogResolution,
controlsResolution,
controlsPending: controlsResolution === "pending",
controlsRequest,
controlsRequestKey,
};
@@ -572,16 +760,40 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
withOptions.provider.length > 0 &&
!withOptions.isSubmitting;
const resolved: AgentProfileFormState = { ...withOptions, disclosure, canSubmit };
return { ...resolved, submitValue: canSubmit ? buildSubmitValue(resolved) : null };
const submitValue = canSubmit ? buildSubmitValue(resolved) : null;
const isDirty =
baselineFingerprint.length > 0 && formDraftFingerprint(resolved) !== baselineFingerprint;
return { ...resolved, isDirty, draftRevision, submitValue };
}
let state: AgentProfileFormState = derive(buildInitialState(snapshot));
baselineFingerprint = formDraftFingerprint(state);
function publish(mutate: (current: AgentProfileFormState) => AgentProfileFormState): void {
function publish(
mutate: (current: AgentProfileFormState) => AgentProfileFormState,
options?: { userEdit?: boolean },
): void {
if (closed) {
return;
}
state = derive(mutate(state));
const previousFingerprint = formDraftFingerprint(state);
if (options?.userEdit) {
hasUserEdited = true;
}
let nextState = derive(mutate(state));
if (options?.userEdit && formDraftFingerprint(nextState) !== previousFingerprint) {
draftRevision += 1;
nextState = { ...nextState, draftRevision };
}
// Catalog hydration fills in missing provider defaults (e.g., default mode on a
// migrated favorite); refresh the clean baseline until the user makes an edit.
if (!hasUserEdited) {
baselineFingerprint = formDraftFingerprint(nextState);
if (nextState.isDirty) {
nextState = { ...nextState, isDirty: false };
}
}
state = nextState;
for (const listener of listeners) {
listener();
}
@@ -610,6 +822,7 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
}
resolvedControlsKey = requestKey;
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
resolvedProvider = state.provider || null;
resolvedControls = [...resolved.controls];
resolvedOptions = resolved.options;
answeredKeys = new Set(resolved.controls.map((control) => control.key));
@@ -622,66 +835,149 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
}
resolvedControlsKey = requestKey;
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
resolvedProvider = state.provider || null;
resolvedControls = [];
resolvedOptions = {};
publish((current) => current);
},
setName: (value) => publish((current) => ({ ...current, name: value })),
setName: (value) =>
publish(
(current) => {
if (value !== autoSuggestedName) {
autoSuggestedName = null;
}
return { ...current, name: value };
},
{ userEdit: true },
),
setAppearance: (value) =>
publish((current) => ({ ...current, icon: value.icon, color: value.color })),
setNotes: (value) => publish((current) => ({ ...current, notes: value })),
publish((current) => ({ ...current, icon: value.icon, color: value.color }), {
userEdit: true,
}),
setNotes: (value) => publish((current) => ({ ...current, notes: value }), { userEdit: true }),
setProvider: (providerId, display) =>
publish((current) => {
if (current.provider === providerId) {
return current;
}
// Everything below the provider is provider-scoped: a model id, mode id,
// thinking id or feature id from the old provider means nothing here.
// Clearing them is enough — `derive` seeds the new provider's defaults.
drawnKeys = new Set();
answeredKeys = new Set();
return {
...current,
provider: providerId,
providerDisplay: display,
modelId: "",
modelDisplay: null,
modeId: "",
modeDisplay: null,
thinkingOptionId: "",
thinkingDisplay: null,
options: {},
optionEdits: {},
};
}),
publish(
(current) => {
if (current.provider === providerId) {
return current;
}
// Everything below the provider is provider-scoped: a model id, mode id,
// thinking id or feature id from the old provider means nothing here.
// Clearing them is enough — `derive` seeds the new provider's defaults.
drawnKeys = new Set();
answeredKeys = new Set();
resolvedProvider = null;
resolvedScopeKey = null;
resolvedControlsKey = null;
resolvedControls = [];
resolvedOptions = {};
return {
...current,
provider: providerId,
providerDisplay: display,
modelId: "",
modelDisplay: null,
modeId: "",
modeDisplay: null,
thinkingOptionId: "",
thinkingDisplay: null,
options: {},
optionEdits: {},
};
},
{ userEdit: true },
),
setProviderModel: (providerId, modelId, displays) =>
publish(
(current) => {
const providerChanged = current.provider !== providerId;
const modelChanged = current.modelId !== modelId;
if (!providerChanged && !modelChanged) {
return current;
}
const suggested = displays.model?.label ?? displays.provider.label;
const shouldAutoName =
current.mode === "create" &&
(current.name.trim().length === 0 ||
(autoSuggestedName !== null && current.name === autoSuggestedName));
const nextName = shouldAutoName ? suggested : current.name;
if (shouldAutoName) {
autoSuggestedName = suggested;
}
if (providerChanged) {
drawnKeys = new Set();
answeredKeys = new Set();
resolvedProvider = null;
resolvedScopeKey = null;
resolvedControlsKey = null;
resolvedControls = [];
resolvedOptions = {};
return {
...current,
name: nextName,
provider: providerId,
providerDisplay: displays.provider,
modelId,
modelDisplay: displays.model,
modeId: "",
modeDisplay: null,
thinkingOptionId: "",
thinkingDisplay: null,
options: {},
optionEdits: {},
};
}
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
const keepsThinking =
current.thinkingOptionId.length > 0 &&
nextThinking.some((option) => option.id === current.thinkingOptionId);
return {
...current,
name: nextName,
modelId,
modelDisplay: displays.model,
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
};
},
{ userEdit: true },
),
setModel: (modelId, display) =>
publish((current) => {
if (current.modelId === modelId) {
return current;
}
// Thinking options are a property of the model, so a level the new model
// does not offer has to go.
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
const keepsThinking =
current.thinkingOptionId.length > 0 &&
nextThinking.some((option) => option.id === current.thinkingOptionId);
return {
...current,
modelId,
modelDisplay: display,
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
};
}),
publish(
(current) => {
if (current.modelId === modelId) {
return current;
}
// Thinking options are a property of the model, so a level the new model
// does not offer has to go.
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
const keepsThinking =
current.thinkingOptionId.length > 0 &&
nextThinking.some((option) => option.id === current.thinkingOptionId);
return {
...current,
modelId,
modelDisplay: display,
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
};
},
{ userEdit: true },
),
setMode: (modeId, display) =>
publish((current) => ({ ...current, modeId, modeDisplay: display })),
publish((current) => ({ ...current, modeId, modeDisplay: display }), { userEdit: true }),
setThinking: (thinkingOptionId, display) =>
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display }), {
userEdit: true,
}),
setOption: (key, value) =>
publish((current) => ({
...current,
optionEdits: { ...current.optionEdits, [key]: value },
})),
publish(
(current) => ({
...current,
optionEdits: { ...current.optionEdits, [key]: value },
}),
{ userEdit: true },
),
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
};
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { buildAgentProfileRosterSummary, formatShortModelLabel } from "./profile-summary";
const formatFeatureCount = (count: number) => `${count} option${count === 1 ? "" : "s"}`;
describe("formatShortModelLabel", () => {
it("keeps plain model names intact with no prefix", () => {
expect(formatShortModelLabel("Claude Opus 4.6")).toEqual({
prefix: null,
name: "Claude Opus 4.6",
});
});
it("splits slash-qualified router model ids into prefix and short name", () => {
expect(formatShortModelLabel("openrouter/moonshotai/kimi-k3.1-pro")).toEqual({
prefix: "openrouter/moonshotai/",
name: "kimi-k3.1-pro",
});
});
it("ignores leading or trailing slashes", () => {
expect(formatShortModelLabel("/leading")).toEqual({ prefix: null, name: "/leading" });
expect(formatShortModelLabel("trailing/")).toEqual({ prefix: null, name: "trailing/" });
});
});
describe("buildAgentProfileRosterSummary", () => {
const entries: ProviderSnapshotEntry[] = [
{
provider: "opencode",
status: "ready",
enabled: true,
label: "OpenCode",
models: [
{
provider: "opencode",
id: "openrouter/moonshotai/kimi-k3.1-pro",
label: "openrouter/moonshotai/kimi-k3.1-pro",
},
],
modes: [{ id: "build", label: "Build" }],
},
];
it("separates short model label from provider/mode/thinking/option details", () => {
const profile: AgentProfile = {
id: "p1",
name: "Kimi fast",
provider: "opencode",
model: "openrouter/moonshotai/kimi-k3.1-pro",
modeId: "build",
thinkingOptionId: "high",
options: { fast_mode: true },
};
const summary = buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount });
expect(summary.providerLabel).toBe("OpenCode");
expect(summary.modelLabel).toBe("kimi-k3.1-pro");
expect(summary.modelPrefix).toBe("openrouter/moonshotai/");
expect(summary.runtimeDetails).toEqual(["OpenCode", "Build", "High", "1 option"]);
});
it("falls back to stored provider id when catalog is unavailable", () => {
const profile: AgentProfile = {
id: "p2",
name: "Offline profile",
provider: "custom-agent",
};
const summary = buildAgentProfileRosterSummary({
profile,
entries: undefined,
formatFeatureCount,
});
expect(summary.providerLabel).toBe("custom-agent");
expect(summary.modelLabel).toBeNull();
expect(summary.runtimeDetails).toEqual(["custom-agent"]);
});
});
@@ -7,6 +7,55 @@ export interface AgentProfileTag {
label: string;
}
export interface ShortModelLabel {
prefix: string | null;
name: string;
}
/**
* Splits slash-qualified routing IDs (e.g. `openrouter/moonshotai/kimi-k3.1-pro`)
* into a quiet prefix and the model's short name so dense roster rows stay readable.
*/
export function formatShortModelLabel(modelIdOrLabel: string): ShortModelLabel {
const trimmed = modelIdOrLabel.trim();
const lastSlash = trimmed.lastIndexOf("/");
if (lastSlash <= 0 || lastSlash >= trimmed.length - 1) {
return { prefix: null, name: trimmed };
}
return {
prefix: trimmed.slice(0, lastSlash + 1),
name: trimmed.slice(lastSlash + 1),
};
}
export interface AgentProfileRosterSummary {
providerLabel: string;
modelLabel: string | null;
modelPrefix: string | null;
runtimeDetails: string[];
allTags: AgentProfileTag[];
}
export function buildAgentProfileRosterSummary(input: {
profile: AgentProfile;
entries: readonly ProviderSnapshotEntry[] | undefined;
formatFeatureCount: (count: number) => string;
}): AgentProfileRosterSummary {
const allTags = buildAgentProfileTags(input);
const providerLabel =
allTags.find((tag) => tag.id === "provider")?.label ?? input.profile.provider;
const rawModel = allTags.find((tag) => tag.id === "model")?.label ?? null;
const shortModel = rawModel ? formatShortModelLabel(rawModel) : null;
const runtimeDetails = allTags.filter((tag) => tag.id !== "model").map((tag) => tag.label);
return {
providerLabel,
modelLabel: shortModel?.name ?? null,
modelPrefix: shortModel?.prefix ?? null,
runtimeDetails,
allTags,
};
}
function findEntry(
entries: readonly ProviderSnapshotEntry[],
provider: string,
@@ -0,0 +1,171 @@
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import { createAgentProfileWriteQueue } from "./profile-write-queue";
function profile(id: string, name = id): AgentProfile {
return { id, name, provider: "claude", model: "claude-opus-5" };
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
describe("createAgentProfileWriteQueue", () => {
it("serializes overlapping appends on the same host so both profiles persist", async () => {
const queue = createAgentProfileWriteQueue();
let stored: AgentProfile[] = [profile("p0")];
const firstGate = deferred<void>();
const writes: string[][] = [];
const write = async (next: AgentProfile[]) => {
writes.push(next.map((entry) => entry.id));
if (writes.length === 1) {
await firstGate.promise;
}
stored = next;
return stored;
};
const first = queue.enqueue("host-a", {
readCurrent: () => stored,
write,
updater: (current) => [...current, profile("p1")],
});
const second = queue.enqueue("host-a", {
readCurrent: () => stored,
write,
updater: (current) => [...current, profile("p2")],
});
// Wait a microtask so the first write is in flight before releasing it.
await Promise.resolve();
expect(writes).toEqual([["p0", "p1"]]);
firstGate.resolve();
await expect(first).resolves.toEqual([profile("p0"), profile("p1")]);
await expect(second).resolves.toEqual([profile("p0"), profile("p1"), profile("p2")]);
expect(writes).toEqual([
["p0", "p1"],
["p0", "p1", "p2"],
]);
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p1", "p2"]);
});
it("removes only the undone profile when Undo overlaps another in-flight save", async () => {
const queue = createAgentProfileWriteQueue();
let stored: AgentProfile[] = [profile("p0"), profile("p1")];
const saveGate = deferred<void>();
const appendSecond = queue.enqueue("host-a", {
readCurrent: () => stored,
write: async (next) => {
await saveGate.promise;
stored = next;
return stored;
},
updater: (current) => [...current, profile("p2")],
});
const undoFirst = queue.enqueue("host-a", {
readCurrent: () => stored,
write: async (next) => {
stored = next;
return stored;
},
updater: (current) => current.filter((entry) => entry.id !== "p1"),
});
saveGate.resolve();
await appendSecond;
await undoFirst;
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p2"]);
});
it("recovers after a rejected write so subsequent mutations still run", async () => {
const queue = createAgentProfileWriteQueue();
let stored: AgentProfile[] = [profile("p0")];
const failing = queue.enqueue("host-a", {
readCurrent: () => stored,
write: async () => {
throw new Error("network blip");
},
updater: (current) => [...current, profile("p1")],
});
const succeeding = queue.enqueue("host-a", {
readCurrent: () => stored,
write: async (next) => {
stored = next;
return stored;
},
updater: (current) => [...current, profile("p2")],
});
await expect(failing).rejects.toThrow("network blip");
await expect(succeeding).resolves.toEqual([profile("p0"), profile("p2")]);
});
it("skips writing when current profiles are unloaded or the updater returns null", async () => {
const queue = createAgentProfileWriteQueue();
let writeCalls = 0;
const unloaded = await queue.enqueue("host-a", {
readCurrent: () => null,
write: async (next) => {
writeCalls += 1;
return next;
},
updater: (current) => [...current, profile("p1")],
});
expect(unloaded).toBeNull();
const noop = await queue.enqueue("host-a", {
readCurrent: () => [profile("p0")],
write: async (next) => {
writeCalls += 1;
return next;
},
updater: () => null,
});
expect(noop).toBeNull();
expect(writeCalls).toBe(0);
});
it("does not block writes to a different host", async () => {
const queue = createAgentProfileWriteQueue();
const hostAGate = deferred<void>();
let hostA: AgentProfile[] = [];
let hostB: AgentProfile[] = [];
const writeA = queue.enqueue("host-a", {
readCurrent: () => hostA,
write: async (next) => {
await hostAGate.promise;
hostA = next;
return hostA;
},
updater: (current) => [...current, profile("a1")],
});
const writeB = await queue.enqueue("host-b", {
readCurrent: () => hostB,
write: async (next) => {
hostB = next;
return hostB;
},
updater: (current) => [...current, profile("b1")],
});
expect(writeB).toEqual([profile("b1")]);
hostAGate.resolve();
await expect(writeA).resolves.toEqual([profile("a1")]);
});
});
@@ -0,0 +1,65 @@
import type { AgentProfile } from "@getpaseo/protocol/messages";
export type AgentProfileListUpdater = (current: readonly AgentProfile[]) => AgentProfile[] | null;
export interface AgentProfileWriteStep {
readCurrent: () => readonly AgentProfile[] | null;
write: (next: AgentProfile[]) => Promise<AgentProfile[]>;
updater: AgentProfileListUpdater;
}
export interface AgentProfileWriteQueue {
enqueue(serverId: string, step: AgentProfileWriteStep): Promise<AgentProfile[] | null>;
}
/** Removes one profile by id, returning `null` if it is already absent so callers skip no-op writes. */
export function removeAgentProfileById(
current: readonly AgentProfile[],
profileId: string,
): AgentProfile[] | null {
const next = current.filter((entry) => entry.id !== profileId);
return next.length === current.length ? null : next;
}
async function runQueuedWrite(
previous: Promise<void>,
step: AgentProfileWriteStep,
): Promise<AgentProfile[] | null> {
await previous;
const current = step.readCurrent();
if (current === null) {
return null;
}
const next = step.updater(current);
if (next === null) {
return null;
}
return step.write(next);
}
/**
* Serializes profile list writes per host so overlapping mutations (rapid composer
* `+` saves, Undo while another save is in flight, split-pane composers) each compute
* their update against the result of the previous write instead of overwriting it.
*/
export function createAgentProfileWriteQueue(): AgentProfileWriteQueue {
const tails = new Map<string, Promise<void>>();
return {
enqueue(serverId, step) {
const previous = tails.get(serverId) ?? Promise.resolve();
const result = runQueuedWrite(previous, step);
const tail = result.then(
() => undefined,
() => undefined,
);
tails.set(serverId, tail);
void tail.finally(() => {
if (tails.get(serverId) === tail) {
tails.delete(serverId);
}
});
return result;
},
};
}
@@ -13,6 +13,7 @@ import {
toAgentConfigApply,
type MaterializedAgentProfile,
} from "./materialize-profile";
import { selectApplicableProfiles } from "./applicable-profiles";
import { buildAgentProfileTags } from "./profile-summary";
import { useAgentProfiles } from "./use-agent-profiles";
@@ -80,8 +81,7 @@ export function useAgentProfilePicker(
if (!isSupported || !profiles) {
return [];
}
const available = new Set(availableProviders);
return profiles.filter((profile) => available.has(profile.provider));
return selectApplicableProfiles(profiles, availableProviders);
}, [availableProviders, isSupported, profiles]);
const formatFeatureCount = useCallback(
@@ -1,8 +1,21 @@
import { useCallback } from "react";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { useCallback, useMemo } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type { AgentProfile, MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { daemonConfigQueryKey } from "@/data/daemon-config";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useSessionStore } from "@/stores/session-store";
import { supportsAgentProfiles } from "./capabilities";
import {
createAgentProfileWriteQueue,
removeAgentProfileById,
type AgentProfileListUpdater,
} from "./profile-write-queue";
const sharedProfileWriteQueue = createAgentProfileWriteQueue();
export { removeAgentProfileById };
export type { AgentProfileListUpdater };
export interface UseAgentProfilesResult {
/** `null` until the daemon config has arrived. */
@@ -11,24 +24,56 @@ export interface UseAgentProfilesResult {
isSupported: boolean;
/** Writes the whole list; there is no per-profile RPC. */
saveProfiles: (next: AgentProfile[]) => Promise<void>;
/**
* Applies a serialized mutation against the latest host profile list so
* overlapping writes compose instead of overwriting each other.
*/
mutateProfiles: (updater: AgentProfileListUpdater) => Promise<AgentProfile[] | null>;
}
export function useAgentProfiles(serverId: string | null): UseAgentProfilesResult {
const { t } = useTranslation();
const queryClient = useQueryClient();
const { config, patchConfig } = useDaemonConfig(serverId);
const queryKey = useMemo(() => daemonConfigQueryKey(serverId), [serverId]);
const isSupported = useSessionStore((state) => {
return supportsAgentProfiles(state.sessions[serverId ?? ""]?.serverInfo?.features);
});
const mutateProfiles = useCallback(
async (updater: AgentProfileListUpdater): Promise<AgentProfile[] | null> => {
if (!serverId) {
return null;
}
return sharedProfileWriteQueue.enqueue(serverId, {
readCurrent: () => {
const cached = queryClient.getQueryData<MutableDaemonConfig>(queryKey);
return cached ? (cached.agentProfiles ?? []) : null;
},
write: async (next) => {
const updated = await patchConfig({ agentProfiles: next });
if (!updated) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
return updated.agentProfiles ?? next;
},
updater,
});
},
[patchConfig, queryClient, queryKey, serverId, t],
);
const saveProfiles = useCallback(
async (next: AgentProfile[]) => {
await patchConfig({ agentProfiles: next });
await mutateProfiles(() => next);
},
[patchConfig],
[mutateProfiles],
);
return {
profiles: config ? (config.agentProfiles ?? []) : null,
isSupported,
saveProfiles,
mutateProfiles,
};
}
@@ -1,14 +1,20 @@
import { useEffect, useState, useSyncExternalStore } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { toErrorMessage } from "@/utils/error-messages";
import {
openAgentProfileForm,
type AgentProfileFormModel,
type AgentProfileFormSnapshot,
type AgentProfileFormState,
type AgentProfileSeed,
type AgentProfileValue,
} from "./profile-form-model";
import { useAgentProfileFormCatalog, useAgentProfileFormControls } from "./use-profile-form-inputs";
/**
* One model per mount. The modal keys its body on mode + profile id, so create
* and edit never share an instance and reopening always starts from the record.
* One model per mount. The sheet or drawer host keys its session on mode + profile id,
* so create and edit never share an instance and reopening always starts from the record.
*/
export function useAgentProfileFormModel(
snapshot: AgentProfileFormSnapshot,
@@ -27,3 +33,78 @@ export function useAgentProfileFormModel(
export function useAgentProfileFormState(model: AgentProfileFormModel): AgentProfileFormState {
return useSyncExternalStore(model.subscribe, model.getState, model.getState);
}
export interface AgentProfileFormSession {
model: AgentProfileFormModel;
state: AgentProfileFormState;
isDirty: boolean;
save: () => Promise<boolean>;
}
/**
* Shared form session used by both the desktop inspector drawer and the modal sheet.
* Lifting this above drawer/modal framing lets responsive switches preserve unsaved edits.
*/
export function useAgentProfileFormSession({
serverId,
mode,
profile,
seed,
onSave,
onSaved,
}: {
serverId: string;
mode: "create" | "edit";
profile?: AgentProfile;
seed?: AgentProfileSeed;
onSave: (value: AgentProfileValue) => Promise<void>;
onSaved: () => void;
}): AgentProfileFormSession {
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
const snapshot = useMemo<AgentProfileFormSnapshot>(
() => ({
mode,
...(profile ? { profile } : {}),
...(seed ? { seed } : {}),
...(entries ? { entries } : {}),
}),
[entries, mode, profile, seed],
);
const model = useAgentProfileFormModel(snapshot);
const state = useAgentProfileFormState(model);
useAgentProfileFormCatalog({ serverId, model });
useAgentProfileFormControls({ serverId, model, state });
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const save = useCallback(async (): Promise<boolean> => {
const value = model.getState().submitValue;
if (!value) {
return false;
}
model.setSubmitError(null);
model.setSubmitting(true);
try {
await onSave(value);
// Only notify completion while this session is still active; switching profiles
// mid-save unmounts this session and must not close the next editor's draft.
if (mountedRef.current) {
onSaved();
}
return true;
} catch (error) {
model.setSubmitError(toErrorMessage(error));
return false;
} finally {
model.setSubmitting(false);
}
}, [model, onSave, onSaved]);
return useMemo(() => ({ model, state, isDirty: state.isDirty, save }), [model, save, state]);
}
@@ -1,16 +1,19 @@
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
import { Pressable, View, type PressableStateCallbackType } from "react-native";
import { View, type PressableStateCallbackType } from "react-native";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Check, ChevronDown } from "lucide-react-native";
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
import {
bySizing,
createControlGeometry,
resolveControlInteractionStyles,
TOUCH_TARGET,
type ControlSize,
} from "@/components/ui/control-geometry";
import { Field } from "@/components/ui/form-field";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { PressHighlight } from "@/components/ui/press-highlight";
import { identityForeground } from "@/styles/identity-colors";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
@@ -37,7 +40,6 @@ const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
const ThemedChevronDown = withUnistyles(ChevronDown);
const ThemedCheck = withUnistyles(Check);
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const onIdentityMapping = (theme: Theme) => ({ color: theme.colors.background });
/**
@@ -56,39 +58,43 @@ function IconCell({
iconKey,
selected,
color,
provider,
serverId,
onSelect,
}: {
iconKey: AgentProfileIconKey | null;
selected: boolean;
color: AgentProfileColor;
provider?: string;
serverId?: string | null;
onSelect: (iconKey: AgentProfileIconKey | null) => void;
}) {
const handlePress = useCallback(() => onSelect(iconKey), [iconKey, onSelect]);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const cellStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.cell,
Boolean(hovered) && styles.cellHovered,
pressed && styles.cellPressed,
selected && styles.cellSelected,
],
[selected],
);
return (
<Pressable
<PressHighlight
onPress={handlePress}
style={cellStyle}
highlightStyle={styles.cellPressed}
accessibilityRole="button"
accessibilityState={accessibilityState}
accessibilityLabel={iconKey ?? "default"}
testID={`agent-profile-icon-cell-${iconKey ?? "default"}`}
>
<AgentProfileGlyph
{...(iconKey ? { icon: iconKey } : {})}
{...(iconKey ? { icon: iconKey } : { provider, serverId })}
color={color}
size={ICON_SIZE.lg}
/>
</Pressable>
</PressHighlight>
);
}
@@ -104,58 +110,54 @@ function ColorCell({
const { t } = useTranslation();
const handlePress = useCallback(() => onSelect(color), [color, onSelect]);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
const swatchStyle = useMemo(
() => [styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)],
[color],
);
const cellStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [styles.colorCell, pressed && styles.cellPressed],
[],
);
return (
<Pressable
<PressHighlight
onPress={handlePress}
style={cellStyle}
style={styles.colorCell}
highlightStyle={styles.cellPressed}
accessibilityRole="button"
accessibilityState={accessibilityState}
accessibilityLabel={colorLabel(t, color)}
testID={`agent-profile-color-cell-${color}`}
>
<View style={swatchStyle}>
<View style={[styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)]}>
{selected ? (
<ThemedCheck
size={ICON_SIZE.sm}
uniProps={color === "none" ? foregroundMutedMapping : onIdentityMapping}
uniProps={color === "none" ? mutedIconColorMapping : onIdentityMapping}
/>
) : null}
</View>
</Pressable>
</PressHighlight>
);
}
/**
* Icon and colour in one popover rather than two fields: the pair is a single
* visual decision, and picking them apart means never seeing the result until
* both are closed. The grid redraws in the chosen colour as you switch colours,
* so the swatch row sits above it.
* Compact clickable icon+color tile that opens the appearance popover without
* requiring a separate labeled field box. Used inline beside the Name input
* and in the inspector drawer header.
*/
export function AgentProfileAppearanceField({
export function AgentProfileIconButton({
label,
icon,
color,
provider,
serverId,
onChange,
size = "md",
variant = "field",
disabled = false,
testID,
triggerTestID,
}: {
label: string;
icon: string;
color: string;
provider?: string;
serverId?: string | null;
onChange: (next: { icon: string; color: string }) => void;
size?: ControlSize;
variant?: "field" | "hero";
disabled?: boolean;
testID?: string;
triggerTestID?: string;
}): ReactElement {
const { t } = useTranslation();
@@ -188,8 +190,10 @@ export function AgentProfileAppearanceField({
const triggerStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.trigger,
size === "sm" ? styles.triggerSm : styles.triggerMd,
styles.triggerIconOnly,
variant === "hero" && styles.triggerHero,
variant !== "hero" && size === "sm" && styles.triggerSm,
variant !== "hero" && size !== "sm" && styles.triggerMd,
variant === "field" && styles.triggerIconOnly,
resolveControlInteractionStyles(
{
controlRest: styles.controlRest,
@@ -200,29 +204,36 @@ export function AgentProfileAppearanceField({
{ hovered: Boolean(hovered), active: pressed || open, disabled },
),
],
[disabled, open, size],
[disabled, open, size, variant],
);
const header = useMemo(() => ({ title: label }), [label]);
return (
<Field label={label} testID={testID}>
<>
<View ref={anchorRef} collapsable={false}>
<Pressable
<PressHighlight
onPress={handleTriggerPress}
disabled={disabled}
style={triggerStyle}
highlightStyle={styles.triggerPressed}
accessibilityRole="button"
accessibilityLabel={`${label} (${colorLabel(t, selectedColor)})`}
testID={triggerTestID}
>
<AgentProfileGlyph
{...(selectedIcon ? { icon: selectedIcon } : {})}
{...(selectedIcon ? { icon: selectedIcon } : { provider, serverId })}
color={selectedColor}
size={ICON_SIZE.md}
size={variant === "hero" ? ICON_SIZE.lg : ICON_SIZE.md}
/>
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</Pressable>
{variant === "hero" ? (
<View style={styles.heroCaretBadge}>
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
</View>
) : (
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
)}
</PressHighlight>
</View>
<Combobox
options={EMPTY_COMBOBOX_OPTIONS}
@@ -251,6 +262,8 @@ export function AgentProfileAppearanceField({
iconKey={null}
selected={selectedIcon === null}
color={selectedColor}
provider={provider}
serverId={serverId}
onSelect={handleIconSelect}
/>
{AGENT_PROFILE_ICON_KEYS.map((key) => (
@@ -265,7 +278,7 @@ export function AgentProfileAppearanceField({
</View>
</View>
</Combobox>
</Field>
</>
);
}
@@ -279,6 +292,8 @@ function identitySwatch(color: Exclude<AgentProfileColor, "none">) {
return styles[IDENTITY_SWATCH_STYLE_KEYS[color]];
}
const HERO_BUTTON_SIZE = bySizing({ touch: TOUCH_TARGET, pointer: 40 });
const styles = StyleSheet.create((theme) => {
const geometry = createControlGeometry(theme);
@@ -292,6 +307,29 @@ const styles = StyleSheet.create((theme) => {
},
triggerSm: { ...geometry.fieldControlSm },
triggerMd: { ...geometry.fieldControlMd },
triggerHero: {
width: HERO_BUTTON_SIZE,
height: HERO_BUTTON_SIZE,
borderRadius: theme.borderRadius.lg,
paddingHorizontal: 0,
position: "relative",
},
triggerPressed: {
backgroundColor: theme.colors.surface3,
},
heroCaretBadge: {
position: "absolute",
right: -theme.spacing[1],
bottom: -theme.spacing[1],
width: theme.spacing[4],
height: theme.spacing[4],
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface1,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.borderAccent,
alignItems: "center",
justifyContent: "center",
},
// The field geometry pads for a line of text. This trigger holds a glyph and
// a chevron, so it keeps the shared height and drops the text-sized inset.
triggerIconOnly: {
@@ -339,7 +377,7 @@ const styles = StyleSheet.create((theme) => {
backgroundColor: theme.colors.surface2,
},
cellPressed: {
opacity: 0.7,
opacity: theme.opacity[50],
},
cellSelected: {
backgroundColor: theme.colors.surface2,
@@ -0,0 +1,503 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { ArrowDown, ArrowUp, Copy, MoreVertical, Trash2, X } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { Button } from "@/components/ui/button";
import { DismissBackdrop } from "@/components/ui/dismiss-backdrop";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
import { ScrollView } from "@/components/ui/scroll-view";
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
import { OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
import {
useAgentProfileFormSession,
type AgentProfileFormSession,
} from "../internal/use-profile-form-model";
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
import { AgentProfileFormFields } from "./agent-profile-form-fields";
export const AGENT_PROFILE_DRAWER_WIDTH = 440;
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedArrowDown = withUnistyles(ArrowDown);
const ThemedMoreVertical = withUnistyles(MoreVertical);
const ThemedCopy = withUnistyles(Copy);
const ThemedTrash2 = withUnistyles(Trash2);
const ThemedX = withUnistyles(X);
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
export interface AgentProfileDrawerProps {
serverId: string;
mode: "create" | "edit";
profile?: AgentProfile;
seed?: AgentProfileSeed;
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
session?: AgentProfileFormSession;
/** Renders as an absolute right-edge slide-over instead of reflowing the roster beside it. */
overlay?: boolean;
canStepPrev?: boolean;
canStepNext?: boolean;
onStepPrev?: () => void;
onStepNext?: () => void;
onClose: () => void;
onSave: (value: AgentProfileValue) => Promise<void>;
onDuplicate?: (profileId: string) => void;
onRemove?: (profileId: string) => void;
}
/**
* Full-height right inspector drawer for creating and editing agent profiles.
* Pinned header + independent scroll + pinned footer prevent vertical re-centering
* when async provider options resolve.
*/
export function AgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
if (props.session) {
return <AgentProfileDrawerContent {...props} session={props.session} />;
}
const key =
props.mode === "edit"
? `drawer-edit:${props.profile?.id ?? ""}`
: `drawer-create:${props.seed?.provider ?? ""}:${props.seed?.modelId ?? ""}`;
return <StandaloneAgentProfileDrawer key={key} {...props} />;
}
function StandaloneAgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
const session = useAgentProfileFormSession({
serverId: props.serverId,
mode: props.mode,
profile: props.profile,
seed: props.seed,
onSave: props.onSave,
onSaved: props.onClose,
});
return <AgentProfileDrawerContent {...props} session={session} />;
}
function DrawerOverflowMenu({
profileName,
disabled,
onDuplicate,
onRemove,
}: {
profileName: string;
disabled: boolean;
onDuplicate?: () => void;
onRemove?: () => void;
}): ReactElement | null {
const { t } = useTranslation();
if (!onDuplicate && !onRemove) {
return null;
}
return (
<DropdownMenu compactMode="sheet">
<ToolbarButton
kind="menu"
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
disabled={disabled}
testID="agent-profile-drawer-more"
>
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<DropdownMenuContent side="bottom" align="end" width={180}>
{onDuplicate ? (
<DropdownMenuItem
leading={duplicateMenuIcon}
onSelect={onDuplicate}
testID="agent-profile-drawer-duplicate"
>
{t("settings.host.agentProfiles.duplicate")}
</DropdownMenuItem>
) : null}
{onDuplicate && onRemove ? <DropdownMenuSeparator /> : null}
{onRemove ? (
<DropdownMenuItem
destructive
leading={removeMenuIcon}
onSelect={onRemove}
testID="agent-profile-drawer-remove"
>
{t("settings.host.agentProfiles.remove")}
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
);
}
function DrawerHeader({
serverId,
mode,
state,
canStepPrev,
canStepNext,
onStepPrev,
onStepNext,
onDuplicate,
onRemove,
onAppearanceChange,
onClose,
}: {
serverId: string;
mode: "create" | "edit";
state: AgentProfileFormSession["state"];
canStepPrev: boolean;
canStepNext: boolean;
onStepPrev?: () => void;
onStepNext?: () => void;
onDuplicate?: () => void;
onRemove?: () => void;
onAppearanceChange: (value: { icon: string; color: string }) => void;
onClose: () => void;
}): ReactElement {
const { t } = useTranslation();
const fallbackTitle =
mode === "edit"
? t("settings.host.agentProfiles.editProfileTitle")
: t("settings.host.agentProfiles.addProfileTitle");
const title = state.name.trim() || fallbackTitle;
const parts = [state.providerDisplay?.label, state.modelDisplay?.label].filter(Boolean);
const subtitle =
parts.length > 0 ? parts.join(" · ") : t("settings.host.agentProfiles.chooseModelPlaceholder");
const showSteppers = mode === "edit" && Boolean(onStepPrev && onStepNext);
return (
<View style={styles.headerChrome}>
<TitlebarDragRegion />
<WindowChromeSafeArea placement="below" />
<View style={styles.header}>
<View style={styles.headerIdentity}>
<AgentProfileIconButton
label={t("settings.host.agentProfiles.iconLabel")}
icon={state.icon}
color={state.color}
provider={state.provider || undefined}
serverId={serverId}
onChange={onAppearanceChange}
variant="hero"
disabled={state.isSubmitting}
triggerTestID="agent-profile-icon-trigger"
/>
<View style={styles.headerText}>
<Text style={styles.headerTitle} numberOfLines={1} testID="agent-profile-drawer-title">
{title}
</Text>
<Text style={styles.headerSubtitle} numberOfLines={1}>
{subtitle}
</Text>
</View>
</View>
<View style={styles.headerActions}>
{showSteppers && onStepPrev && onStepNext ? (
<>
<ToolbarButton
label={t("settings.host.agentProfiles.previousProfile")}
onPress={onStepPrev}
disabled={!canStepPrev || state.isSubmitting}
testID="agent-profile-drawer-prev"
>
<ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<ToolbarButton
label={t("settings.host.agentProfiles.nextProfile")}
onPress={onStepNext}
disabled={!canStepNext || state.isSubmitting}
testID="agent-profile-drawer-next"
>
<ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
</>
) : null}
{mode === "edit" ? (
<DrawerOverflowMenu
profileName={title}
disabled={state.isSubmitting}
onDuplicate={onDuplicate}
onRemove={onRemove}
/>
) : null}
<ToolbarButton
label={t("common.actions.close")}
onPress={onClose}
disabled={state.isSubmitting}
testID="agent-profile-drawer-close"
>
<ThemedX size={ICON_SIZE.md} uniProps={mutedIconColorMapping} />
</ToolbarButton>
</View>
</View>
</View>
);
}
function DrawerFooter({
canSubmit,
isSubmitting,
onClose,
onSave,
}: {
canSubmit: boolean;
isSubmitting: boolean;
onClose: () => void;
onSave: () => void;
}): ReactElement {
const { t } = useTranslation();
return (
<View style={styles.footer}>
<Button
variant="secondary"
onPress={onClose}
disabled={isSubmitting}
testID="agent-profile-cancel-button"
>
{t("common.actions.cancel")}
</Button>
<Button
variant="default"
onPress={onSave}
disabled={!canSubmit}
loading={isSubmitting}
testID="agent-profile-save-button"
>
{t("settings.host.agentProfiles.save")}
</Button>
</View>
);
}
function AgentProfileDrawerContent({
serverId,
mode,
profile,
session,
overlay = false,
canStepPrev = false,
canStepNext = false,
onStepPrev,
onStepNext,
onClose,
onDuplicate,
onRemove,
}: AgentProfileDrawerProps & { session: AgentProfileFormSession }): ReactElement {
const { t } = useTranslation();
const { model, state, save } = session;
const drawerLayer = useOverlayLayer("floating");
const handleOverlayKeyDown = useCallback(
(event: KeyboardInputEvent) => {
if (event.key !== "Escape") {
return false;
}
event.preventDefault();
event.stopPropagation();
if (!state.isSubmitting) {
onClose();
}
return true;
},
[onClose, state.isSubmitting],
);
const setOverlayScope = useOverlayRegistration({
keys: ["Escape"],
active: true,
layer: drawerLayer,
// Only trap focus in slide-over overlay mode; a docked drawer sits beside the
// interactive roster and must let users click and type in roster search.
manageFocus: overlay,
onKeyDown: handleOverlayKeyDown,
});
const handleAppearanceChange = useCallback(
(value: { icon: string; color: string }) => model.setAppearance(value),
[model],
);
const handleSavePress = useCallback(() => {
void save();
}, [save]);
const handleDuplicate = useCallback(() => {
if (profile && onDuplicate) {
onDuplicate(profile.id);
}
}, [onDuplicate, profile]);
const handleRemove = useCallback(() => {
if (profile && onRemove) {
onRemove(profile.id);
}
}, [onRemove, profile]);
const handleBackdropPress = useCallback(() => {
if (!state.isSubmitting) {
onClose();
}
}, [onClose, state.isSubmitting]);
const drawerStyle = useMemo(
() => [styles.drawer, overlay && styles.drawerOverlay, overlay && { zIndex: drawerLayer }],
[drawerLayer, overlay],
);
const overlayHostStyle = useMemo(
() => [styles.overlayHost, { zIndex: drawerLayer }],
[drawerLayer],
);
const drawerPanel = (
<WindowChromeRegion corners="top-right">
<OverlayLayerProvider layer={drawerLayer}>
<View ref={setOverlayScope} style={drawerStyle} testID="agent-profile-drawer">
<DrawerHeader
serverId={serverId}
mode={mode}
state={state}
canStepPrev={canStepPrev}
canStepNext={canStepNext}
onStepPrev={onStepPrev}
onStepNext={onStepNext}
onDuplicate={profile && onDuplicate ? handleDuplicate : undefined}
onRemove={profile && onRemove ? handleRemove : undefined}
onAppearanceChange={handleAppearanceChange}
onClose={onClose}
/>
<ScrollView style={styles.scroll} keyboardShouldPersistTaps="handled">
<View style={styles.scrollContent}>
<AgentProfileFormFields
serverId={serverId}
model={model}
state={state}
showInlineIcon={false}
collapsibleDefaults={false}
/>
</View>
</ScrollView>
<DrawerFooter
canSubmit={state.canSubmit}
isSubmitting={state.isSubmitting}
onClose={onClose}
onSave={handleSavePress}
/>
</View>
</OverlayLayerProvider>
</WindowChromeRegion>
);
if (!overlay) {
return drawerPanel;
}
return (
<View style={overlayHostStyle} pointerEvents="box-none">
<View style={styles.overlayBackdrop} pointerEvents="none" />
<DismissBackdrop label={t("common.actions.close")} onPress={handleBackdropPress} />
{drawerPanel}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
overlayHost: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
flexDirection: "row",
justifyContent: "flex-end",
},
overlayBackdrop: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: theme.colors.background,
opacity: theme.opacity[50],
},
drawer: {
width: AGENT_PROFILE_DRAWER_WIDTH,
flexShrink: 0,
backgroundColor: theme.colors.surface0,
borderLeftWidth: theme.borderWidth[1],
borderLeftColor: theme.colors.borderAccent,
},
drawerOverlay: {
height: "100%",
...theme.shadow.lg,
},
headerChrome: {
position: "relative",
borderBottomWidth: theme.borderWidth[1],
borderBottomColor: theme.colors.border,
},
header: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[3],
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[4],
},
headerIdentity: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
},
headerText: {
flex: 1,
minWidth: 0,
gap: theme.spacing[0.5],
},
headerTitle: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
},
headerSubtitle: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
headerActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
flexShrink: 0,
},
scroll: {
flex: 1,
},
scrollContent: {
padding: theme.spacing[4],
paddingBottom: theme.spacing[8],
},
footer: {
flexDirection: "row",
alignItems: "center",
justifyContent: "flex-end",
gap: theme.spacing[2],
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[3],
borderTopWidth: theme.borderWidth[1],
borderTopColor: theme.colors.border,
backgroundColor: theme.colors.surface0,
},
}));
@@ -1,36 +1,16 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
import { Text, View } from "react-native";
import { View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import type { AgentOptionControl, ProviderOptions } from "@getpaseo/protocol/agent-types";
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { type ControlSize } from "@/components/ui/control-geometry";
import { Field, FormTextInput } from "@/components/ui/form-field";
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
import {
SelectField,
type SelectFieldDisplay,
type SelectFieldOption,
} from "@/components/ui/select-field";
import { Switch } from "@/components/ui/switch";
import { toErrorMessage } from "@/utils/error-messages";
import { AgentProfileAppearanceField } from "./agent-profile-appearance-field";
import type {
AgentProfileFormModel,
AgentProfileFormOption,
AgentProfileSeed,
AgentProfileValue,
} from "../internal/profile-form-model";
import {
useAgentProfileFormCatalog,
useAgentProfileFormControls,
} from "../internal/use-profile-form-inputs";
import {
useAgentProfileFormModel,
useAgentProfileFormState,
useAgentProfileFormSession,
type AgentProfileFormSession,
} from "../internal/use-profile-form-model";
import { AgentProfileFormFields } from "./agent-profile-form-fields";
export interface AgentProfileEditModalProps {
serverId: string;
@@ -38,16 +18,15 @@ export interface AgentProfileEditModalProps {
mode: "create" | "edit";
profile?: AgentProfile;
seed?: AgentProfileSeed;
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
session?: AgentProfileFormSession;
/** Starts create mode with Mode, Thinking, Notes & Options collapsed behind a summary row. */
collapsibleDefaults?: boolean;
onClose: () => void;
onSave: (value: AgentProfileValue) => Promise<void>;
onRemove?: (profileId: string) => void;
}
/**
* Only reachable before the catalog lands. Every select is seeded to a concrete
* id as soon as one exists, and none of them offer an "unset" row.
*/
const UNSET_VALUE = "";
function openKey(props: AgentProfileEditModalProps): string {
if (props.mode === "edit") {
return `edit:${props.profile?.id ?? ""}`;
@@ -57,7 +36,11 @@ function openKey(props: AgentProfileEditModalProps): string {
/**
* Create and edit never share a mounted instance: the body is keyed on mode plus
* profile id, so every open constructs a form model seeded from that record.
* profile id (unless the caller lifts `session`), so every open constructs a form
* model seeded from that record.
*
* Used for editing from the composer model picker and on compact/narrow screens
* where Settings cannot host a slide-over drawer.
*/
export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactElement | null {
const [renderedProps, setRenderedProps] = useState<AgentProfileEditModalProps | null>(() =>
@@ -101,10 +84,24 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
return null;
}
const activeProps = props.visible ? props : renderedProps;
if (activeProps.session) {
return (
<AgentProfileEditModalContent
{...activeProps}
session={activeProps.session}
visible={sheetVisible}
onClose={requestClose}
onDismiss={handleDismiss}
/>
);
}
return (
<OpenAgentProfileEditModal
key={openKey(renderedProps)}
{...renderedProps}
<StandaloneAgentProfileEditModal
key={openKey(activeProps)}
{...activeProps}
visible={sheetVisible}
onClose={requestClose}
onDismiss={handleDismiss}
@@ -112,36 +109,36 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
);
}
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
return options.map((option) => ({
id: option.id,
value: option.value,
label: option.label,
...(option.description ? { description: option.description } : {}),
testID: option.testID,
}));
function StandaloneAgentProfileEditModal(
props: AgentProfileEditModalProps & { onDismiss: () => void },
): ReactElement {
const session = useAgentProfileFormSession({
serverId: props.serverId,
mode: props.mode,
profile: props.profile,
seed: props.seed,
onSave: props.onSave,
onSaved: props.onClose,
});
return <AgentProfileEditModalContent {...props} session={session} />;
}
function OpenAgentProfileEditModal({
function AgentProfileEditModalContent({
serverId,
visible,
mode,
profile,
seed,
session,
collapsibleDefaults,
onClose,
onDismiss,
onSave,
}: AgentProfileEditModalProps & { onDismiss: () => void }): ReactElement {
onRemove,
}: AgentProfileEditModalProps & {
session: AgentProfileFormSession;
onDismiss: () => void;
}): ReactElement {
const { t } = useTranslation();
const controlSize: ControlSize = "md";
const snapshot = useMemo(
() => ({ mode, ...(profile ? { profile } : {}), ...(seed ? { seed } : {}) }),
[mode, profile, seed],
);
const model = useAgentProfileFormModel(snapshot);
const state = useAgentProfileFormState(model);
useAgentProfileFormCatalog({ serverId, model });
useAgentProfileFormControls({ serverId, model, state });
const { model, state, save } = session;
const sheetHeader = useMemo<SheetHeader>(
() => ({
@@ -153,59 +150,9 @@ function OpenAgentProfileEditModal({
[mode, t],
);
const providerOptions = useMemo(
() => toSelectOptions(state.providerOptions),
[state.providerOptions],
);
const modelOptions = useMemo(() => toSelectOptions(state.modelOptions), [state.modelOptions]);
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
const thinkingOptions = useMemo(
() => toSelectOptions(state.thinkingOptions),
[state.thinkingOptions],
);
const handleAppearanceChange = useCallback(
(value: { icon: string; color: string }) => model.setAppearance(value),
[model],
);
const handleProviderChange = useCallback(
(value: string, display: SelectFieldDisplay) => model.setProvider(value, display),
[model],
);
const handleModelChange = useCallback(
(value: string, display: SelectFieldDisplay) => model.setModel(value, value ? display : null),
[model],
);
const handleModeChange = useCallback(
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
[model],
);
const handleThinkingChange = useCallback(
(value: string, display: SelectFieldDisplay) =>
model.setThinking(value, value ? display : null),
[model],
);
const handleSave = useCallback(async () => {
const value = model.getState().submitValue;
if (!value) {
return;
}
model.setSubmitError(null);
model.setSubmitting(true);
try {
await onSave(value);
onClose();
} catch (error) {
model.setSubmitError(toErrorMessage(error));
} finally {
model.setSubmitting(false);
}
}, [model, onClose, onSave]);
const handleSavePress = useCallback(() => {
void handleSave();
}, [handleSave]);
void save();
}, [save]);
const handleCancel = useCallback(() => {
if (state.isSubmitting) {
@@ -214,170 +161,31 @@ function OpenAgentProfileEditModal({
onClose();
}, [onClose, state.isSubmitting]);
return (
<AdaptiveModalSheet
visible={visible}
header={sheetHeader}
onClose={handleCancel}
onDismiss={onDismiss}
desktopMaxWidth={520}
testID="agent-profile-edit-modal"
>
<View style={styles.body}>
<View style={styles.nameRow}>
<View style={styles.iconField}>
<AgentProfileAppearanceField
label={t("settings.host.agentProfiles.iconLabel")}
icon={state.icon}
color={state.color}
onChange={handleAppearanceChange}
const handleRemove = useCallback(() => {
if (!profile || !onRemove) {
return;
}
onRemove(profile.id);
}, [onRemove, profile]);
const footer = useMemo(
() => (
<View style={styles.footer}>
<View style={styles.footerStart}>
{mode === "edit" && profile && onRemove ? (
<Button
variant="outline"
onPress={handleRemove}
disabled={state.isSubmitting}
size={controlSize}
testID="agent-profile-icon-field"
triggerTestID="agent-profile-icon-trigger"
/>
</View>
<View style={styles.nameField}>
<Field
label={t("settings.host.agentProfiles.nameLabel")}
testID="agent-profile-name-field"
testID="agent-profile-modal-remove-button"
>
<FormTextInput
initialValue={seed?.name ?? profile?.name ?? ""}
onChangeText={model.setName}
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
autoCapitalize="none"
autoCorrect={false}
editable={!state.isSubmitting}
size={controlSize}
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
testID="agent-profile-name-input"
/>
</Field>
</View>
{t("settings.host.agentProfiles.remove")}
</Button>
) : null}
</View>
<SelectField
label={t("settings.host.agentProfiles.providerLabel")}
value={state.provider || null}
selectedDisplay={state.providerDisplay}
options={providerOptions}
onChange={handleProviderChange}
placeholder={t("settings.host.agentProfiles.providerPlaceholder")}
emptyText={t("settings.host.agentProfiles.noProviders")}
loading={state.catalogResolution !== "complete"}
disabled={state.isSubmitting}
searchable={providerOptions.length > 6}
title={t("settings.host.agentProfiles.providerLabel")}
size={controlSize}
testID="agent-profile-provider-field"
triggerTestID="agent-profile-provider-trigger"
/>
{state.disclosure.showModelField ? (
<SelectField
label={t("settings.host.agentProfiles.modelLabel")}
value={state.modelId || UNSET_VALUE}
selectedDisplay={state.modelDisplay}
options={modelOptions}
onChange={handleModelChange}
placeholder={t("settings.host.agentProfiles.modelLabel")}
emptyText={t("settings.host.agentProfiles.noModels")}
disabled={state.isSubmitting}
searchable={modelOptions.length > 6}
title={t("settings.host.agentProfiles.modelLabel")}
size={controlSize}
testID="agent-profile-model-field"
triggerTestID="agent-profile-model-trigger"
/>
) : null}
{state.disclosure.showModeField ? (
<SelectField
label={t("settings.host.agentProfiles.modeLabel")}
value={state.modeId || UNSET_VALUE}
selectedDisplay={state.modeDisplay}
options={modeOptions}
onChange={handleModeChange}
placeholder={t("settings.host.agentProfiles.modeLabel")}
emptyText={t("settings.host.agentProfiles.noModes")}
disabled={state.isSubmitting}
searchable={modeOptions.length > 6}
title={t("settings.host.agentProfiles.modeLabel")}
size={controlSize}
testID="agent-profile-mode-field"
triggerTestID="agent-profile-mode-trigger"
/>
) : null}
{state.disclosure.showThinkingField ? (
<SelectField
label={t("settings.host.agentProfiles.thinkingLabel")}
value={state.thinkingOptionId || UNSET_VALUE}
selectedDisplay={state.thinkingDisplay}
options={thinkingOptions}
onChange={handleThinkingChange}
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
disabled={state.isSubmitting}
searchable={thinkingOptions.length > 6}
title={t("settings.host.agentProfiles.thinkingLabel")}
size={controlSize}
testID="agent-profile-thinking-field"
triggerTestID="agent-profile-thinking-trigger"
/>
) : null}
{state.disclosure.showControlsField ? (
<Field
label={t("settings.host.agentProfiles.featuresLabel")}
testID="agent-profile-features-field"
>
<View style={styles.featureCard} testID="agent-profile-features-card">
{state.controls.map((control, index) => (
<AgentProfileControlRow
key={control.key}
control={control}
options={state.controlOptions}
isFirst={index === 0}
disabled={state.isSubmitting}
size={controlSize}
model={model}
/>
))}
</View>
</Field>
) : null}
<Field
label={t("settings.host.agentProfiles.notesLabel")}
hint={t("settings.host.agentProfiles.notesHint")}
testID="agent-profile-notes-field"
>
<FormTextInput
initialValue={profile?.notes ?? ""}
onChangeText={model.setNotes}
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
multiline
numberOfLines={4}
style={styles.notesInput}
editable={!state.isSubmitting}
size={controlSize}
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
testID="agent-profile-notes-input"
/>
</Field>
{state.submitError ? (
<Text style={styles.submitError} testID="agent-profile-submit-error">
{state.submitError}
</Text>
) : null}
<View style={styles.actions}>
<View style={styles.footerEnd}>
<Button
variant="secondary"
style={styles.actionButton}
onPress={handleCancel}
disabled={state.isSubmitting}
testID="agent-profile-cancel-button"
@@ -386,177 +194,65 @@ function OpenAgentProfileEditModal({
</Button>
<Button
variant="default"
style={styles.actionButton}
onPress={handleSavePress}
disabled={!state.canSubmit}
loading={state.isSubmitting}
testID="agent-profile-save-button"
>
{state.isSubmitting
? t("settings.host.agentProfiles.saving")
: t("settings.host.agentProfiles.save")}
{t("settings.host.agentProfiles.save")}
</Button>
</View>
</View>
),
[
handleCancel,
handleRemove,
handleSavePress,
mode,
onRemove,
profile,
state.canSubmit,
state.isSubmitting,
t,
],
);
return (
<AdaptiveModalSheet
visible={visible}
header={sheetHeader}
footer={footer}
onClose={handleCancel}
onDismiss={onDismiss}
desktopMaxWidth={500}
testID="agent-profile-edit-modal"
>
<AgentProfileFormFields
serverId={serverId}
model={model}
state={state}
collapsibleDefaults={collapsibleDefaults ?? mode === "create"}
/>
</AdaptiveModalSheet>
);
}
function AgentProfileControlRow({
control,
options,
isFirst,
disabled,
size,
model,
}: {
control: AgentOptionControl;
options: ProviderOptions;
isFirst: boolean;
disabled: boolean;
size: ControlSize;
model: AgentProfileFormModel;
}): ReactElement {
const rowStyle = useMemo(
() => [styles.featureRow, isFirst ? null : styles.featureRowBorder],
[isFirst],
);
const handleToggle = useCallback(
(value: boolean) => model.setOption(control.key, value),
[control.key, model],
);
const handleSelect = useCallback(
(value: string) => model.setOption(control.key, value),
[control.key, model],
);
const selectOptions = useMemo<SelectFieldOption<string>[]>(
() =>
control.type === "select"
? control.choices.map((choice) => ({
id: choice.value,
value: choice.value,
label: choice.label,
...(choice.description ? { description: choice.description } : {}),
testID: `agent-profile-feature-option-${control.key}-${choice.value}`,
}))
: [],
[control],
);
const selectedValue = control.type === "select" ? readSelectOption(control, options) : null;
const selectedDisplay = useMemo<SelectFieldDisplay | null>(() => {
if (control.type !== "select" || !selectedValue) {
return null;
}
const choice = control.choices.find((candidate) => candidate.value === selectedValue);
return { label: choice?.label ?? selectedValue };
}, [control, selectedValue]);
if (control.type === "select") {
return (
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
<SelectField
label={control.label}
value={selectedValue}
selectedDisplay={selectedDisplay}
options={selectOptions}
onChange={handleSelect}
placeholder={control.label}
emptyText={control.label}
disabled={disabled}
{...(control.description ? { hint: control.description } : {})}
title={control.label}
size={size}
testID={`agent-profile-feature-field-${control.key}`}
triggerTestID={`agent-profile-feature-trigger-${control.key}`}
/>
</View>
);
}
return (
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
<View style={styles.featureMeta}>
<Text style={styles.featureLabel} numberOfLines={1}>
{control.label}
</Text>
{control.description ? (
<Text style={styles.featureDescription} numberOfLines={2}>
{control.description}
</Text>
) : null}
</View>
<Switch
value={readToggleOption(control, options)}
onValueChange={handleToggle}
disabled={disabled}
accessibilityLabel={control.label}
testID={`agent-profile-feature-switch-${control.key}`}
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
gap: theme.spacing[4],
paddingBottom: theme.spacing[2],
},
nameRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
},
// No width: the trigger is a glyph and a chevron, so it sizes to them.
iconField: {
flexShrink: 0,
},
nameField: {
footer: {
flex: 1,
},
featureCard: {
backgroundColor: theme.colors.surface2,
borderRadius: theme.borderRadius.md,
borderWidth: 1,
borderColor: theme.colors.border,
paddingHorizontal: theme.spacing[3],
},
featureRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[3],
paddingVertical: theme.spacing[3],
gap: theme.spacing[2],
},
featureRowBorder: {
borderTopWidth: 1,
borderTopColor: theme.colors.border,
},
featureMeta: {
flex: 1,
gap: theme.spacing[1],
},
featureLabel: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
featureDescription: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
notesInput: {
minHeight: 88,
textAlignVertical: "top",
},
submitError: {
color: theme.colors.statusDanger,
fontSize: theme.fontSize.base,
},
actions: {
footerStart: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginTop: theme.spacing[2],
},
actionButton: {
flex: 1,
footerEnd: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
}));
@@ -0,0 +1,567 @@
import { useCallback, useMemo, useRef, type ReactElement, type ReactNode } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type {
AgentOptionControl,
AgentProvider,
ProviderOptions,
} from "@getpaseo/protocol/agent-types";
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
import { CombinedModelSelector } from "@/components/combined-model-selector";
import {
SettingsCard,
SettingsCollapsibleRow,
SettingsSelect,
SettingsSwitch,
} from "@/components/settings";
import type { ControlSize } from "@/components/ui/control-geometry";
import { Field, FormTextInput } from "@/components/ui/form-field";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import {
SelectField,
SelectFieldTrigger,
type SelectFieldDisplay,
type SelectFieldOption,
} from "@/components/ui/select-field";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { buildSelectableProviderSelectorProviders } from "@/provider-selection/provider-selection";
import { ICON_SIZE } from "@/styles/theme";
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
import type {
AgentProfileFormModel,
AgentProfileFormOption,
AgentProfileFormState,
} from "../internal/profile-form-model";
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const UNSET_VALUE = "";
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
return options.map((option) => ({
id: option.id,
value: option.value,
label: option.label,
...(option.description ? { description: option.description } : {}),
testID: option.testID,
}));
}
function canUseSegmentedThinking(options: readonly AgentProfileFormOption[]): boolean {
return (
options.length >= 2 &&
options.length <= 4 &&
options.every((option) => option.label.trim().length <= 12)
);
}
export interface AgentProfileFormFieldsProps {
serverId: string;
model: AgentProfileFormModel;
state: AgentProfileFormState;
controlSize?: ControlSize;
/** Embeds the icon+color picker beside the Name input (used in sheets; drawer places it in its hero). */
showInlineIcon?: boolean;
/** Collapses Mode, Thinking, Notes, and Options behind a SettingsCollapsibleRow until expanded. */
collapsibleDefaults?: boolean;
}
function ThinkingField({
state,
controlSize,
onSelectChange,
onSegmentChange,
}: {
state: AgentProfileFormState;
controlSize: ControlSize;
onSelectChange: (value: string, display: SelectFieldDisplay) => void;
onSegmentChange: (value: string) => void;
}): ReactElement | null {
const { t } = useTranslation();
const thinkingOptions = useMemo(
() => toSelectOptions(state.thinkingOptions),
[state.thinkingOptions],
);
const segmentedThinkingOptions = useMemo<SegmentedControlOption<string>[]>(
() =>
state.thinkingOptions.map((option) => ({
value: option.value,
label: option.label,
disabled: state.isSubmitting,
testID: option.testID,
})),
[state.isSubmitting, state.thinkingOptions],
);
if (!state.disclosure.showThinkingField) {
return null;
}
if (canUseSegmentedThinking(state.thinkingOptions)) {
return (
<Field
label={t("settings.host.agentProfiles.thinkingLabel")}
testID="agent-profile-thinking-field"
>
<SegmentedControl
options={segmentedThinkingOptions}
value={state.thinkingOptionId || null}
onValueChange={onSegmentChange}
size={controlSize}
testID="agent-profile-thinking-trigger"
/>
</Field>
);
}
return (
<SelectField
label={t("settings.host.agentProfiles.thinkingLabel")}
value={state.thinkingOptionId || UNSET_VALUE}
selectedDisplay={state.thinkingDisplay}
options={thinkingOptions}
onChange={onSelectChange}
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
disabled={state.isSubmitting}
searchable={thinkingOptions.length > 6}
title={t("settings.host.agentProfiles.thinkingLabel")}
size={controlSize}
testID="agent-profile-thinking-field"
triggerTestID="agent-profile-thinking-trigger"
/>
);
}
function AgentProfileControlRow({
control,
options,
disabled,
model,
}: {
control: AgentOptionControl;
options: ProviderOptions;
disabled: boolean;
model: AgentProfileFormModel;
}): ReactElement {
const handleToggle = useCallback(
(value: boolean) => model.setOption(control.key, value),
[control.key, model],
);
const handleSelect = useCallback(
(value: string) => model.setOption(control.key, value),
[control.key, model],
);
const selectOptions = useMemo(
() =>
control.type === "select"
? control.choices.map((choice) => ({ label: choice.label, value: choice.value }))
: [],
[control],
);
if (control.type === "select") {
const selectedValue = readSelectOption(control, options) ?? control.choices[0]?.value ?? "";
return (
<SettingsSelect
label={control.label}
hint={control.description}
value={selectedValue}
options={selectOptions}
onValueChange={handleSelect}
disabled={disabled}
testID={`agent-profile-feature-row-${control.key}`}
/>
);
}
return (
<SettingsSwitch
label={control.label}
hint={control.description}
value={readToggleOption(control, options)}
onValueChange={handleToggle}
disabled={disabled}
testID={`agent-profile-feature-row-${control.key}`}
/>
);
}
function AgentProfileAdvancedFields({
model,
state,
controlSize,
onModeChange,
onThinkingSelectChange,
onThinkingSegmentChange,
}: {
model: AgentProfileFormModel;
state: AgentProfileFormState;
controlSize: ControlSize;
onModeChange: (value: string, display: SelectFieldDisplay) => void;
onThinkingSelectChange: (value: string, display: SelectFieldDisplay) => void;
onThinkingSegmentChange: (value: string) => void;
}): ReactElement {
const { t } = useTranslation();
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
const providerOptionsTitle = state.providerDisplay?.label
? t("settings.host.agentProfiles.providerOptionsLabel", {
provider: state.providerDisplay.label,
})
: t("settings.host.agentProfiles.featuresLabel");
const optionsPendingSpinner = useMemo(
() =>
state.controlsPending ? (
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
) : null,
[state.controlsPending],
);
return (
<>
{state.disclosure.showModeField ? (
<SelectField
label={t("settings.host.agentProfiles.modeLabel")}
value={state.modeId || UNSET_VALUE}
selectedDisplay={state.modeDisplay}
options={modeOptions}
onChange={onModeChange}
placeholder={t("settings.host.agentProfiles.modeLabel")}
emptyText={t("settings.host.agentProfiles.noModes")}
disabled={state.isSubmitting}
searchable={modeOptions.length > 6}
title={t("settings.host.agentProfiles.modeLabel")}
size={controlSize}
testID="agent-profile-mode-field"
triggerTestID="agent-profile-mode-trigger"
/>
) : null}
<ThinkingField
state={state}
controlSize={controlSize}
onSelectChange={onThinkingSelectChange}
onSegmentChange={onThinkingSegmentChange}
/>
<Field
label={t("settings.host.agentProfiles.notesLabel")}
hint={t("settings.host.agentProfiles.notesHint")}
testID="agent-profile-notes-field"
>
<FormTextInput
initialValue={state.notes}
onChangeText={model.setNotes}
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
multiline
numberOfLines={3}
style={styles.notesInput}
editable={!state.isSubmitting}
size={controlSize}
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
testID="agent-profile-notes-input"
/>
</Field>
{state.disclosure.showControlsField ? (
<Field
label={providerOptionsTitle}
trailing={optionsPendingSpinner}
testID="agent-profile-features-field"
>
<View style={state.controlsPending ? styles.featureCardPending : undefined}>
<SettingsCard testID="agent-profile-features-card">
{state.controls.map((control) => (
<AgentProfileControlRow
key={control.key}
control={control}
options={state.controlOptions}
disabled={state.isSubmitting || state.controlsPending}
model={model}
/>
))}
</SettingsCard>
</View>
</Field>
) : null}
</>
);
}
/**
* Shared profile form body used by both the desktop inspector drawer and the modal sheet.
*
* Layout order keeps inputs above async provider options: Model first (using Paseo's
* shared CombinedModelSelector), Name + icon second, Mode & Thinking, "When to use",
* and provider options last so loading options never shift controls above them.
*/
export function AgentProfileFormFields({
serverId,
model,
state,
controlSize = "md",
showInlineIcon = true,
collapsibleDefaults = false,
}: AgentProfileFormFieldsProps): ReactElement {
const { t } = useTranslation();
const nameInputRef = useRef<EditingTextInputHandle>(null);
const { entries, isLoading, isFetching, isRefreshing, refresh } = useProvidersSnapshot(serverId, {
cwd: null,
});
const modelSelectorProviders = useMemo(
() =>
buildSelectableProviderSelectorProviders(entries, {
selectedProvider: state.provider || null,
}),
[entries, state.provider],
);
const modelTriggerLeading = useMemo(
() =>
state.provider ? (
<AgentProfileGlyph provider={state.provider} serverId={serverId} size={ICON_SIZE.sm} />
) : null,
[serverId, state.provider],
);
const renderModelTrigger = useCallback(
({
selectedModelLabel,
disabled,
isOpen,
hovered,
pressed,
}: {
selectedModelLabel: string;
onPress: () => void;
disabled: boolean;
isOpen: boolean;
hovered: boolean;
pressed: boolean;
}): ReactNode => {
const displayLabel =
state.modelDisplay?.label ?? state.providerDisplay?.label ?? selectedModelLabel;
return (
<SelectFieldTrigger
label={displayLabel}
isPlaceholder={!state.provider}
placeholder={t("settings.host.agentProfiles.chooseModelPlaceholder")}
leading={modelTriggerLeading}
disabled={disabled}
active={hovered || pressed || isOpen}
size={controlSize}
testID="agent-profile-model-trigger"
/>
);
},
[
controlSize,
modelTriggerLeading,
state.modelDisplay?.label,
state.provider,
state.providerDisplay?.label,
t,
],
);
const handleAppearanceChange = useCallback(
(value: { icon: string; color: string }) => model.setAppearance(value),
[model],
);
const handleModelSelect = useCallback(
(provider: AgentProvider, modelId: string) => {
const previousName = model.getState().name;
const entry = entries?.find((candidate) => candidate.provider === provider);
const modelDef = entry?.models?.find((candidate) => candidate.id === modelId);
model.setProviderModel(provider, modelId, {
provider: { label: entry?.label ?? provider },
model: modelId ? { label: modelDef?.label ?? modelId } : null,
});
const suggestedName = model.getState().name;
if (suggestedName !== previousName) {
nameInputRef.current?.replaceText(suggestedName);
}
},
[entries, model],
);
const handleRetryProvider = useCallback(
(provider: AgentProvider) => {
void refresh([provider]);
},
[refresh],
);
const handleModeChange = useCallback(
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
[model],
);
const handleThinkingSelectChange = useCallback(
(value: string, display: SelectFieldDisplay) =>
model.setThinking(value, value ? display : null),
[model],
);
const handleThinkingSegmentChange = useCallback(
(value: string) => {
const option = state.thinkingOptions.find((candidate) => candidate.value === value);
model.setThinking(value, option ? { label: option.label } : null);
},
[model, state.thinkingOptions],
);
const hasRuntimeDefaults =
state.disclosure.showModeField ||
state.disclosure.showThinkingField ||
state.disclosure.showControlsField;
const defaultsSummary = useMemo(() => {
const parts: string[] = [];
if (state.modeDisplay?.label) {
parts.push(state.modeDisplay.label);
}
if (state.thinkingDisplay?.label) {
parts.push(state.thinkingDisplay.label);
}
if (state.controls.length > 0) {
parts.push(
state.controls.length === 1
? t("settings.host.agentProfiles.featureCountOne", { count: state.controls.length })
: t("settings.host.agentProfiles.featureCount", { count: state.controls.length }),
);
}
if (!state.notes.trim() && hasRuntimeDefaults) {
parts.push(t("settings.host.agentProfiles.addRoutingNoteShort"));
}
return parts.join(" · ");
}, [
hasRuntimeDefaults,
state.controls.length,
state.modeDisplay?.label,
state.notes,
state.thinkingDisplay?.label,
t,
]);
const collapsibleLabel = hasRuntimeDefaults
? t("settings.host.agentProfiles.customizeSettings")
: t("settings.host.agentProfiles.addRoutingNoteShort");
const advancedFields = (
<AgentProfileAdvancedFields
model={model}
state={state}
controlSize={controlSize}
onModeChange={handleModeChange}
onThinkingSelectChange={handleThinkingSelectChange}
onThinkingSegmentChange={handleThinkingSegmentChange}
/>
);
return (
<View style={styles.body}>
<Field label={t("settings.host.agentProfiles.modelLabel")} testID="agent-profile-model-field">
<CombinedModelSelector
providers={modelSelectorProviders}
selectedProvider={state.provider}
selectedModel={state.modelId}
onSelect={handleModelSelect}
isLoading={isLoading || isFetching}
renderTrigger={renderModelTrigger}
triggerFill
serverId={serverId}
disabled={state.isSubmitting}
onRetryProvider={handleRetryProvider}
isRetryingProvider={isRefreshing}
/>
</Field>
<Field label={t("settings.host.agentProfiles.nameLabel")} testID="agent-profile-name-field">
<View style={styles.nameRow}>
{showInlineIcon ? (
<AgentProfileIconButton
label={t("settings.host.agentProfiles.iconLabel")}
icon={state.icon}
color={state.color}
provider={state.provider || undefined}
serverId={serverId}
onChange={handleAppearanceChange}
disabled={state.isSubmitting}
size={controlSize}
triggerTestID="agent-profile-icon-trigger"
/>
) : null}
<View style={styles.nameInputWrap}>
<FormTextInput
ref={nameInputRef}
initialValue={state.name}
onChangeText={model.setName}
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
autoCapitalize="none"
autoCorrect={false}
editable={!state.isSubmitting}
size={controlSize}
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
testID="agent-profile-name-input"
/>
</View>
</View>
</Field>
{collapsibleDefaults ? (
<SettingsCard>
<SettingsCollapsibleRow
label={collapsibleLabel}
summary={defaultsSummary || undefined}
testID="agent-profile-customize"
>
<View style={styles.collapsibleFields}>{advancedFields}</View>
</SettingsCollapsibleRow>
</SettingsCard>
) : (
advancedFields
)}
{state.submitError ? (
<Text style={styles.submitError} testID="agent-profile-submit-error">
{state.submitError}
</Text>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
gap: theme.spacing[4],
},
nameRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
nameInputWrap: {
flex: 1,
minWidth: 0,
},
collapsibleFields: {
padding: theme.spacing[4],
gap: theme.spacing[4],
},
featureCardPending: {
opacity: theme.opacity[50],
},
notesInput: {
minHeight: theme.spacing[20],
textAlignVertical: "top",
},
submitError: {
color: theme.colors.palette.red[300],
fontSize: theme.fontSize.sm,
},
}));
@@ -1,57 +1,342 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { useCallback, useMemo, useState, type ReactElement } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { ArrowDown, ArrowUp, FileText, Pencil, Trash2 } from "lucide-react-native";
import {
ArrowDown,
ArrowUp,
ArrowUpToLine,
ChevronRight,
Copy,
GripVertical,
MoreVertical,
Pencil,
Trash2,
} from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { Button } from "@/components/ui/button";
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 {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import {
extraMutedIconColorMapping,
foregroundIconColorMapping,
mutedIconColorMapping,
} from "@/components/ui/icon-color";
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useIsCompactFormFactor } from "@/constants/layout";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
import { buildAgentProfileTags } from "../internal/profile-summary";
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 ThemedGripVertical = withUnistyles(GripVertical);
const ThemedMoreVertical = withUnistyles(MoreVertical);
const ThemedChevronRight = withUnistyles(ChevronRight);
const ThemedPencil = withUnistyles(Pencil);
const ThemedCopy = withUnistyles(Copy);
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedArrowDown = withUnistyles(ArrowDown);
const ThemedPencil = withUnistyles(Pencil);
const ThemedArrowUpToLine = withUnistyles(ArrowUpToLine);
const ThemedTrash2 = withUnistyles(Trash2);
const ThemedFileText = withUnistyles(FileText);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const moveUpIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
const moveDownIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
const editIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
const removeIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveColorMapping} />;
const editMenuIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const moveUpMenuIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const moveDownMenuIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
const moveTopMenuIcon = (
<ThemedArrowUpToLine size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
);
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
const HIDDEN_FROM_ASSISTIVE_TECH = {
accessibilityElementsHidden: true,
importantForAccessibility: "no-hide-descendants",
"aria-hidden": true,
} as const;
export interface AgentProfileRowProps {
serverId: string;
profile: AgentProfile;
entries: readonly ProviderSnapshotEntry[] | undefined;
isFirst: boolean;
isLast: boolean;
selected?: boolean;
dragging?: boolean;
/** Stacked layout when narrow or on compact form factors. */
compactLayout?: boolean;
/** Hides the drag handle when showing filtered search results while preserving the rail. */
reorderable?: boolean;
onEdit: (id: string) => void;
onDuplicate: (id: string) => void;
onRemove: (id: string) => void;
onMoveUp: (id: string) => void;
onMoveDown: (id: string) => void;
onMoveToTop: (id: string) => void;
}
function AgentProfileRowMenu({
profileId,
profileName,
isFirst,
isLast,
reorderable,
menuProps,
onEdit,
onDuplicate,
onMoveUp,
onMoveDown,
onMoveToTop,
onRemove,
}: {
profileId: string;
profileName: string;
isFirst: boolean;
isLast: boolean;
reorderable: boolean;
menuProps: { open: boolean; onOpenChange: (open: boolean) => void };
onEdit: () => void;
onDuplicate: () => void;
onMoveUp: () => void;
onMoveDown: () => void;
onMoveToTop: () => void;
onRemove: () => void;
}): ReactElement {
const { t } = useTranslation();
const showReorderItems = reorderable && (!isFirst || !isLast);
return (
<DropdownMenu {...menuProps} compactMode="sheet">
<ToolbarButton
kind="menu"
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
testID={`agent-profile-menu-${profileId}`}
>
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
</ToolbarButton>
<DropdownMenuContent side="bottom" align="end" width={180}>
<DropdownMenuItem
leading={editMenuIcon}
onSelect={onEdit}
testID={`agent-profile-edit-${profileId}`}
>
{t("settings.host.agentProfiles.editProfile")}
</DropdownMenuItem>
<DropdownMenuItem
leading={duplicateMenuIcon}
onSelect={onDuplicate}
testID={`agent-profile-duplicate-${profileId}`}
>
{t("settings.host.agentProfiles.duplicate")}
</DropdownMenuItem>
{showReorderItems ? (
<>
<DropdownMenuSeparator />
{!isFirst ? (
<DropdownMenuItem
leading={moveUpMenuIcon}
onSelect={onMoveUp}
testID={`agent-profile-move-up-${profileId}`}
>
{t("settings.host.agentProfiles.moveUp")}
</DropdownMenuItem>
) : null}
{!isLast ? (
<DropdownMenuItem
leading={moveDownMenuIcon}
onSelect={onMoveDown}
testID={`agent-profile-move-down-${profileId}`}
>
{t("settings.host.agentProfiles.moveDown")}
</DropdownMenuItem>
) : null}
{!isFirst ? (
<DropdownMenuItem
leading={moveTopMenuIcon}
onSelect={onMoveToTop}
testID={`agent-profile-move-top-${profileId}`}
>
{t("settings.host.agentProfiles.moveToTop")}
</DropdownMenuItem>
) : null}
</>
) : null}
<DropdownMenuSeparator />
<DropdownMenuItem
destructive
leading={removeMenuIcon}
onSelect={onRemove}
testID={`agent-profile-remove-${profileId}`}
>
{t("settings.host.agentProfiles.remove")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
function AgentProfileRowContent({
serverId,
profile,
modelLabel,
providerLabel,
runtimeSubline,
fullSummary,
isStacked,
}: {
serverId: string;
profile: AgentProfile;
modelLabel: string | null;
providerLabel: string;
runtimeSubline: string;
fullSummary: string;
isStacked: boolean;
}): ReactElement {
const { t } = useTranslation();
const iconTile = (
<View style={styles.iconTile}>
<AgentProfileGlyph
icon={profile.icon}
color={profile.color}
provider={profile.provider}
serverId={serverId}
size={ICON_SIZE.sm}
/>
</View>
);
if (isStacked) {
return (
<View style={[styles.stackedMain, styles.passThrough]}>
{iconTile}
<View style={styles.stackedContent}>
<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>
{profile.notes ? (
<Text
style={styles.stackedNotesText}
numberOfLines={2}
testID={`agent-profile-notes-${profile.id}`}
>
{profile.notes}
</Text>
) : null}
</View>
</View>
);
}
return (
<View style={[styles.columns, styles.passThrough]}>
<View style={styles.colProfile}>
{iconTile}
<Text style={styles.nameText} numberOfLines={1}>
{profile.name}
</Text>
</View>
<View style={styles.colRuntime}>
<View style={styles.modelLine}>
<AgentProfileGlyph provider={profile.provider} serverId={serverId} size={ICON_SIZE.xs} />
<Text style={styles.modelText} numberOfLines={1}>
{modelLabel ?? providerLabel}
</Text>
</View>
<Text style={styles.runtimeSubtext} numberOfLines={1}>
{runtimeSubline}
</Text>
</View>
<View style={styles.colNotes}>
{profile.notes ? (
<Text
style={styles.notesText}
numberOfLines={2}
testID={`agent-profile-notes-${profile.id}`}
>
{profile.notes}
</Text>
) : (
<Text style={styles.notesEmptyText} numberOfLines={1}>
{t("settings.host.agentProfiles.noRoutingNote")}
</Text>
)}
</View>
</View>
);
}
/**
* Wide roster row (Profile | Model & runtime | When to use) that stacks on narrow panes.
*
* Follows docs/hover.md: hover lives on the outer plain View, tap lives on an
* underlying PressHighlight, and the kebab menu's open state is lifted via
* `useOpenKebabMenuVisibility` so losing hover never unmounts an open menu.
*/
export function AgentProfileRow({
serverId,
profile,
entries,
isFirst,
isLast,
selected = false,
dragging = false,
compactLayout = false,
reorderable = true,
onEdit,
onDuplicate,
onRemove,
onMoveUp,
onMoveDown,
onMoveToTop,
}: AgentProfileRowProps): ReactElement {
const { t } = useTranslation();
const isCompactFormFactor = useIsCompactFormFactor();
const { finePointer, touchScreen } = usePointerCapabilities();
const [isHovered, setIsHovered] = useState(false);
const alwaysShowAffordances = !finePointer || touchScreen || isCompactFormFactor;
const { showKebab, menuProps } = useOpenKebabMenuVisibility(
isHovered || dragging || alwaysShowAffordances,
);
const showRowAffordances = showKebab;
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
const handlePointerLeave = useCallback(() => setIsHovered(false), []);
const handleEdit = useCallback(() => onEdit(profile.id), [onEdit, profile.id]);
const handleDuplicate = useCallback(() => onDuplicate(profile.id), [onDuplicate, profile.id]);
const handleRemove = useCallback(() => onRemove(profile.id), [onRemove, profile.id]);
const handleMoveUp = useCallback(() => onMoveUp(profile.id), [onMoveUp, profile.id]);
const handleMoveDown = useCallback(() => onMoveDown(profile.id), [onMoveDown, profile.id]);
const handleMoveToTop = useCallback(() => onMoveToTop(profile.id), [onMoveToTop, profile.id]);
const formatFeatureCount = useCallback(
(count: number) =>
@@ -60,77 +345,109 @@ export function AgentProfileRow({
: t("settings.host.agentProfiles.featureCount", { count }),
[t],
);
const tags = useMemo(
() => buildAgentProfileTags({ profile, entries, formatFeatureCount }),
const rosterSummary = useMemo(
() => buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount }),
[entries, formatFeatureCount, profile],
);
const summary = useMemo(() => tags.map((tag) => tag.label).join(" · "), [tags]);
const fullSummary = useMemo(
() => rosterSummary.allTags.map((tag) => tag.label).join(" · "),
[rosterSummary.allTags],
);
const runtimeSubline = useMemo(
() => rosterSummary.runtimeDetails.join(" · "),
[rosterSummary.runtimeDetails],
);
const rowStyle = useMemo(
() => [settingsStyles.row, isFirst ? null : settingsStyles.rowBorder, styles.row],
[isFirst],
const isStacked = compactLayout || isCompactFormFactor;
const rowContainerStyle = useMemo(
() => [
styles.row,
!isFirst && settingsStyles.rowBorder,
selected && styles.rowSelected,
(isHovered || menuProps.open) && !selected && styles.rowHovered,
dragging && styles.rowDragging,
],
[dragging, isFirst, isHovered, menuProps.open, selected],
);
const gripVisibilityStyle = useMemo(
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
[showRowAffordances],
);
const kebabVisibilityStyle = useMemo(
() => [styles.kebabSlot, !showRowAffordances && styles.affordanceHidden],
[showRowAffordances],
);
return (
<View style={rowStyle} testID={`agent-profile-row-${profile.id}`}>
<View style={styles.rowMain}>
<View style={styles.iconWrapper}>
<AgentProfileGlyph icon={profile.icon} color={profile.color} size={ICON_SIZE.md} />
<View
style={rowContainerStyle}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
testID={`agent-profile-row-${profile.id}`}
>
<PressHighlight
accessibilityRole="button"
accessibilityLabel={`${profile.name}, ${fullSummary}`}
onPress={handleEdit}
style={styles.pressTarget}
highlightStyle={styles.rowPressed}
testID={`agent-profile-row-press-${profile.id}`}
/>
{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={settingsStyles.rowContent}>
<View style={styles.titleLine}>
<Text style={settingsStyles.rowTitle} numberOfLines={1}>
{profile.name}
</Text>
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
</View>
{profile.notes ? (
<View style={styles.notes}>
<ThemedFileText size={ICON_SIZE.xs} uniProps={mutedColorMapping} />
<Text
style={styles.notesText}
numberOfLines={2}
testID={`agent-profile-notes-${profile.id}`}
>
{profile.notes}
</Text>
</View>
) : null}
) : (
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
)}
<AgentProfileRowContent
serverId={serverId}
profile={profile}
modelLabel={rosterSummary.modelLabel}
providerLabel={rosterSummary.providerLabel}
runtimeSubline={runtimeSubline}
fullSummary={fullSummary}
isStacked={isStacked}
/>
<View style={styles.trailing}>
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
<AgentProfileRowMenu
profileId={profile.id}
profileName={profile.name}
isFirst={isFirst}
isLast={isLast}
reorderable={reorderable}
menuProps={menuProps}
onEdit={handleEdit}
onDuplicate={handleDuplicate}
onMoveUp={handleMoveUp}
onMoveDown={handleMoveDown}
onMoveToTop={handleMoveToTop}
onRemove={handleRemove}
/>
</View>
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevronRight
size={ICON_SIZE.sm}
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
/>
</View>
</View>
<View style={styles.rowActions}>
<Button
variant="ghost"
leftIcon={moveUpIcon}
onPress={handleMoveUp}
disabled={isFirst}
accessibilityLabel={t("settings.host.agentProfiles.moveUp")}
testID={`agent-profile-move-up-${profile.id}`}
/>
<Button
variant="ghost"
leftIcon={moveDownIcon}
onPress={handleMoveDown}
disabled={isLast}
accessibilityLabel={t("settings.host.agentProfiles.moveDown")}
testID={`agent-profile-move-down-${profile.id}`}
/>
<Button
variant="ghost"
leftIcon={editIcon}
onPress={handleEdit}
accessibilityLabel={t("settings.host.agentProfiles.editProfile")}
testID={`agent-profile-edit-${profile.id}`}
/>
<Button
variant="ghost"
leftIcon={removeIcon}
onPress={handleRemove}
accessibilityLabel={t("settings.host.agentProfiles.remove")}
testID={`agent-profile-remove-${profile.id}`}
/>
</View>
</View>
);
@@ -138,47 +455,166 @@ export function AgentProfileRow({
const styles = StyleSheet.create((theme) => ({
row: {
gap: theme.spacing[2],
minHeight: 56,
alignItems: "center",
paddingVertical: theme.spacing[3],
},
rowMain: {
flex: 1,
position: "relative",
flexDirection: "row",
alignItems: "flex-start",
alignItems: "center",
minHeight: ROW_MIN_HEIGHT,
paddingVertical: theme.spacing[3],
paddingLeft: theme.spacing[2],
paddingRight: theme.spacing[4],
gap: theme.spacing[2],
},
iconWrapper: {
width: theme.iconSize.md,
rowHovered: {
backgroundColor: theme.colors.surface2,
},
rowSelected: {
backgroundColor: theme.colors.surface3,
},
selectedIndicator: {
position: "absolute",
left: 0,
top: theme.spacing[2],
bottom: theme.spacing[2],
width: theme.borderWidth[2],
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.accent,
},
rowPressed: {
backgroundColor: theme.colors.surface3,
},
rowDragging: {
backgroundColor: theme.colors.surface2,
},
pressTarget: {
...StyleSheet.absoluteFill,
},
passThrough: {
pointerEvents: "none",
},
gripSlot: {
width: ROSTER_GRIP_WIDTH,
alignItems: "center",
justifyContent: "center",
marginTop: 1,
flexShrink: 0,
},
titleLine: {
gripSpacerCompact: {
width: theme.spacing[2],
flexShrink: 0,
},
gripHandle: {
width: ROSTER_GRIP_WIDTH,
height: GRIP_HANDLE_HEIGHT,
alignItems: "center",
justifyContent: "center",
},
affordanceHidden: {
opacity: 0,
},
iconTile: {
width: theme.spacing[7],
height: theme.spacing[7],
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface2,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
columns: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "baseline",
alignItems: "center",
gap: theme.spacing[4],
},
colProfile: {
width: ROSTER_COL_PROFILE_WIDTH,
flexShrink: 0,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minWidth: 0,
},
summary: {
colRuntime: {
width: ROSTER_COL_RUNTIME_WIDTH,
flexShrink: 0,
gap: theme.spacing[0.5],
minWidth: 0,
},
colNotes: {
flex: 1,
minWidth: 0,
},
nameText: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
modelLine: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
modelText: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
},
runtimeSubtext: {
color: theme.colors.foregroundExtraMuted,
fontSize: theme.fontSize.sm,
},
notesText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
notesEmptyText: {
color: theme.colors.foregroundExtraMuted,
fontSize: theme.fontSize.sm,
},
stackedMain: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[3],
},
stackedContent: {
flex: 1,
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,
fontSize: theme.fontSize.sm,
},
notes: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[1],
marginTop: theme.spacing[1],
},
notesText: {
flex: 1,
color: theme.colors.foregroundMuted,
stackedNotesText: {
color: theme.colors.foregroundExtraMuted,
fontSize: theme.fontSize.sm,
marginTop: theme.spacing[0.5],
},
rowActions: {
trailing: {
width: ROSTER_TRAILING_WIDTH,
flexDirection: "row",
alignItems: "center",
justifyContent: "flex-end",
gap: theme.spacing[1],
flexShrink: 0,
},
kebabSlot: {
alignItems: "center",
justifyContent: "center",
},
// Optical: matches SettingsRowHeader so the chevron sits on the card's trailing rail.
chevron: {
marginRight: -theme.spacing[1],
},
}));
File diff suppressed because it is too large Load Diff
@@ -26,14 +26,22 @@ export function getMountedRecentStreamItems(): number {
export function findMountedWindowStart(input: {
items: StreamItem[];
minMountedCount: number;
// Caps how far turn alignment may rewind. History paging and the replica
// cache omit it and still keep a whole turn.
maxMountedCount?: number;
}): number {
const { items, minMountedCount } = input;
if (items.length <= minMountedCount) {
return 0;
}
const mountedLimit =
input.maxMountedCount === undefined
? items.length
: Math.max(minMountedCount, input.maxMountedCount);
const earliestStart = Math.max(0, items.length - mountedLimit);
let startIndex = Math.max(items.length - minMountedCount, 0);
while (startIndex > 0 && continuesTurn(items[startIndex - 1], items[startIndex])) {
while (startIndex > earliestStart && continuesTurn(items[startIndex - 1], items[startIndex])) {
startIndex -= 1;
}
return startIndex;
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
import type { TurnTiming } from "@/timeline/turn-time";
import type { TimelineItemTransform } from "@/plugins/timeline";
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
import type { StreamItem } from "@/types/stream";
import {
orderHeadForStreamRenderStrategy,
@@ -578,4 +580,40 @@ describe("layoutStream", () => {
expect(footerOwners(layout)).toEqual([]);
},
);
it.each(["web", "android"] as const)(
"attaches the turn footer to the final card of a plugin-split reply on %s",
(platform) => {
const metrics = [{ label: "Model", value: "opus" }];
const first = { ...assistantMessage("a1", 2), turnMetrics: [{ label: "Steps", value: "1" }] };
const latest = { ...assistantMessage("a2", 4), turnMetrics: metrics };
const splitIntoCards: TimelineItemTransform = ({ item, sourceId }) =>
item.type !== "assistant_message"
? undefined
: ["text", "card"].map((part) => ({
type: "plugin",
id: `${sourceId}/${part}`,
pluginId: "genui",
kind: `genui-${part}`,
version: 1,
data: {},
}));
const tail = projectPluginTimelineItems(
[userMessage("u1", 1), first, userMessage("u2", 3), latest],
splitIntoCards,
);
const layout = layoutFor({
platform,
tail,
timingIds: ["genui/a1/card", "genui/a2/card"],
});
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
first.turnMetrics,
);
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
},
);
});
+4 -4
View File
@@ -1,6 +1,6 @@
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import type { TurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
import { getAssistantReply, type StreamItem } from "@/types/stream";
import { getAssistantMessageSpacing, getGapBetweenStreamItems } from "./spacing";
import type { StreamFrameChildOrder, StreamStrategy } from "./strategy";
import { continuesResponse, continuesTurn, isResponseBoundary } from "./turn-membership";
@@ -72,9 +72,9 @@ function createTurnFooterHost(input: {
timingByItemId: Map<string, TurnTiming>;
}): TurnFooterHost {
const turnMetrics =
input.item.kind === "assistant_message" || input.item.kind === "tool_call"
input.item.kind === "tool_call"
? input.item.turnMetrics
: undefined;
: getAssistantReply(input.item)?.turnMetrics;
return {
itemId: input.item.id,
items: input.items,
@@ -109,7 +109,7 @@ function findTurnFooterSource(input: {
if (!item || (laterItem && !continuesResponse(item, laterItem))) {
return toolFallback;
}
if (item.kind === "assistant_message") {
if (getAssistantReply(item)) {
return { item, items, index };
}
laterItem = item;
@@ -2,7 +2,7 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
import React, { act, useSyncExternalStore } from "react";
import { createRoot, type Root } from "react-dom/client";
import { View } from "react-native";
import { afterEach, beforeEach, expect, it } from "vitest";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { disclosureAnchor } from "./native-disclosure-hold";
// The native chat timeline runs on the patched LegendList (patches/@legendapp+list+3.7.1.patch).
@@ -90,7 +90,7 @@ function keyExtractor(item: Row) {
return item.id;
}
function estimateRowSize(item: Row) {
function rowHeight(item: Row) {
return item.height;
}
@@ -289,7 +289,7 @@ it("expands the draw distance of a placed end-anchored list without moving its b
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
recycleItems={false}
getEstimatedItemSize={estimateRowSize}
getEstimatedItemSize={rowHeight}
drawDistance={drawDistance}
alignItemsAtEnd
initialScrollAtEnd
@@ -315,3 +315,96 @@ it("expands the draw distance of a placed end-anchored list without moving its b
expect(expanded?.scroll).toBe(initial?.scroll);
expect(expanded?.positionByKey(lastRow.id)).toBe(lastRowTop);
});
it.each([2, 4])("reveals an end-anchored list with a footer %sx the viewport", async (scale) => {
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
id: `row-${index}`,
height: 40,
}));
const footerHeight = VIEWPORT_HEIGHT * scale;
const listRef = React.createRef<LegendListRef>();
const footer = React.createElement(View, { style: rowStyle(footerHeight) });
const onReady = vi.fn();
act(() => {
root.render(
<LegendList
ref={listRef}
data={rows}
renderItem={renderRow}
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
getEstimatedItemSize={rowHeight}
drawDistance={50}
recycleItems={false}
alignItemsAtEnd
initialScrollAtEnd
ListFooterComponent={footer}
onReady={onReady}
style={LIST_STYLE}
/>,
);
});
await expect
.poll(async () => {
await wait(16);
return onReady.mock.calls.length;
})
.toBe(1);
expect(listRef.current?.getState().scroll).toBe(
rows.length * 40 + footerHeight - VIEWPORT_HEIGHT,
);
});
const END_PADDED_CONTENT_STYLE = { paddingBottom: 125 };
it("reveals buffered rows when the scroll view takes over initial end positioning", () => {
const rowSize = 40;
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
id: `row-${index}`,
height: rowSize,
}));
const listRef = React.createRef<LegendListRef>();
const onReady = vi.fn();
act(() => {
root.render(
<LegendList
ref={listRef}
data={rows}
renderItem={renderRow}
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
getFixedItemSize={rowHeight}
drawDistance={120}
recycleItems={false}
alignItemsAtEnd
initialScrollAtEnd
contentContainerStyle={END_PADDED_CONTENT_STYLE}
onReady={onReady}
style={LIST_STYLE}
/>,
);
});
const list = listRef.current;
if (!list) throw new Error("The list did not mount");
const scroller: unknown = list.getScrollableNode();
if (!(scroller instanceof HTMLElement)) throw new Error("The list has no scroll element");
const endOffset =
rows.length * rowSize + END_PADDED_CONTENT_STYLE.paddingBottom - VIEWPORT_HEIGHT;
act(() => {
// Deliver the scroll view's observed end offset before canceling the list's initial scroll.
// Keep both calls in one task so a later layout pass cannot complete the reveal for them.
scroller.scrollTop = endOffset;
scroller.dispatchEvent(new Event("scroll"));
expect(onReady).not.toHaveBeenCalled();
list.cancelScroll();
});
const state = list.getState();
expect(state.scroll).toBe(endOffset);
expect(state.start).toBeNull();
expect(state.endBuffered).toBe(rows.length - 1);
expect(state.sizeAtIndex(rows.length - 1)).toBe(rowSize);
expect(onReady).toHaveBeenCalledTimes(1);
});
@@ -3,6 +3,7 @@ import type { StreamItem } from "@/types/stream";
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
import { findMountedWindowStart } from "./history-window";
import { buildAgentStreamRenderModel } from "./model";
import { MAX_MOUNTED_WEB_WINDOW_ITEMS } from "./web-virtualization";
function createTimestamp(seed: number): Date {
return new Date(`2026-01-01T00:00:${seed.toString().padStart(2, "0")}.000Z`);
@@ -125,6 +126,30 @@ describe("buildAgentStreamRenderModel", () => {
expect(model.history).not.toContain(head[0]);
});
it("virtualizes a desktop web turn that runs past the mounted cap", () => {
const length = MAX_MOUNTED_WEB_WINDOW_ITEMS + 80;
const tail = Array.from({ length }, (_, index) => ({
...userMessage(`row-${index}`, index % 60),
turnId: "long-run",
}));
const model = buildAgentStreamRenderModel({
isTurnActive: false,
activeTurnStartedAt: null,
tail,
head: [],
platform: "web",
isMobileBreakpoint: false,
});
expect(model.segments.historyMounted).toHaveLength(MAX_MOUNTED_WEB_WINDOW_ITEMS);
expect(model.segments.historyVirtualized).toHaveLength(80);
expect(model.segments.historyMounted[0]?.id).toBe(
`row-${length - MAX_MOUNTED_WEB_WINDOW_ITEMS}`,
);
expect(model.segments.historyVirtualized[0]?.id).toBe("row-0");
});
it("keeps the full committed tail mounted on mobile web", () => {
const tail = [userMessage("u1", 1), assistantMessage("a1", 2)];
const head = [assistantMessage("live-a", 3)];
+5 -1
View File
@@ -2,7 +2,10 @@ import type { ReactNode } from "react";
import { deriveStreamTurnTiming, type StreamTurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
import { findMountedWindowStart, getMountedRecentStreamItems } from "./history-window";
import { getWebPartialVirtualizationThreshold } from "./web-virtualization";
import {
getWebPartialVirtualizationThreshold,
MAX_MOUNTED_WEB_WINDOW_ITEMS,
} from "./web-virtualization";
import { orderHeadForStreamRenderStrategy, orderTailForStreamRenderStrategy } from "./strategy";
import { resolveStreamRenderStrategy } from "./strategy-resolver";
@@ -134,6 +137,7 @@ function splitOrderedTail(params: {
const mountedWindowStart = findMountedWindowStart({
items: orderedTail,
minMountedCount: getMountedRecentStreamItems(),
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
});
const split = {
history: orderedTail,
@@ -28,7 +28,11 @@ function userMessage(id: string, text: string, seed: number): StreamItem {
};
}
function assistantMessage(id: string, text: string, seed: number): StreamItem {
function assistantMessage(
id: string,
text: string,
seed: number,
): Extract<StreamItem, { kind: "assistant_message" }> {
return {
kind: "assistant_message",
id,
@@ -243,4 +247,38 @@ describe("layout strategy edges", () => {
"content-then-footer",
);
});
it.each(PLATFORMS)("copies a reply split into plugin cards once on %s", (platform) => {
const strategy = strategyFor(platform);
const splitReply = assistantMessage("a2", 'Summary\n\n```ui\nCard("Hi", [])\n```', 3);
const card = (part: string): StreamItem => ({
kind: "plugin",
id: `genui/a2/${part}`,
source: splitReply,
timestamp: splitReply.timestamp,
pluginId: "genui",
pluginItemId: `a2/${part}`,
itemKind: `genui-${part}`,
version: 1,
data: {},
});
const items = orderTailForStreamRenderStrategy({
strategy,
streamItems: [
userMessage("u1", "prompt", 1),
assistantMessage("a1", "Before card", 2),
card("text"),
card("card"),
],
});
const startIndex = items.findIndex((item) => item.id === "genui/a2/card");
expect(
collectAssistantResponseContentForStreamRenderStrategy({
strategy,
items,
startIndex,
}),
).toBe(`Before card\n\n${splitReply.text}`);
});
});
+7 -3
View File
@@ -1,6 +1,6 @@
import type { ComponentType, ReactElement, ReactNode, RefObject } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import type { StreamItem } from "@/types/stream";
import { getAssistantReply, type StreamItem } from "@/types/stream";
import type { ReadingRowReplacements } from "./reading-anchor";
import { continuesResponse } from "./turn-membership";
import type { StreamHistoryBoundary, StreamRenderSegments } from "./model";
@@ -185,6 +185,7 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate
},
collectAssistantResponseContent: (items, startIndex) => {
const messages: string[] = [];
const seenReplies = new Set<StreamItem>();
let laterItem: StreamItem | null = null;
for (
let index = startIndex;
@@ -195,8 +196,11 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate
if (!currentItem || (laterItem && !continuesResponse(currentItem, laterItem))) {
break;
}
if (currentItem.kind === "assistant_message") {
messages.push(currentItem.text);
// A transformer can split one reply into several cards; copy the reply once.
const reply = getAssistantReply(currentItem);
if (reply && !seenReplies.has(reply)) {
seenReplies.add(reply);
messages.push(reply.text);
}
laterItem = currentItem;
}
@@ -112,4 +112,63 @@ describe("resolveAssistantTurnForkBoundary", () => {
}),
).toBeUndefined();
});
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 },
};
const card: StreamItem = {
kind: "plugin",
id: "genui/assistant-1/1",
source: reply,
timelineCursor: reply.timelineCursor,
timestamp: reply.timestamp,
pluginId: "genui",
pluginItemId: "assistant-1/1",
itemKind: "genui-block",
version: 1,
data: {},
};
expect(
resolveAssistantTurnForkBoundary({
items: [userMessage("user-1", 1), card],
startIndex: 1,
supportsTimelineCursor: true,
}),
).toEqual({
boundaryCursor: { epoch: "timeline-1", seq: 42 },
boundaryMessageId: "msg-assistant-1",
});
expect(
resolveAssistantTurnForkBoundary({
items: [userMessage("user-1", 1), card],
startIndex: 1,
supportsTimelineCursor: false,
}),
).toEqual({ boundaryMessageId: "msg-assistant-1" });
});
it("ignores plugin cards that did not replace a reply", () => {
const appended: StreamItem = {
kind: "plugin",
id: "plugin/card-1",
timelineCursor: { epoch: "timeline-1", seq: 42 },
timestamp: timestamp(2),
pluginId: "plugin",
pluginItemId: "card-1",
itemKind: "card",
version: 1,
data: {},
};
expect(
resolveAssistantTurnForkBoundary({
items: [userMessage("user-1", 1), appended],
startIndex: 1,
supportsTimelineCursor: true,
}),
).toBeUndefined();
});
});
@@ -1,4 +1,4 @@
import type { StreamItem, TimelinePosition } from "@/types/stream";
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
export type AssistantTurnForkBoundary =
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
@@ -9,15 +9,15 @@ export function resolveAssistantTurnForkBoundary(input: {
startIndex: number;
supportsTimelineCursor: boolean;
}): AssistantTurnForkBoundary | undefined {
const item = input.items[input.startIndex];
if (item?.kind !== "assistant_message") {
const reply = getAssistantReply(input.items[input.startIndex]);
if (!reply) {
return undefined;
}
if (input.supportsTimelineCursor && item.timelineCursor) {
if (input.supportsTimelineCursor && reply.timelineCursor) {
return {
boundaryCursor: item.timelineCursor,
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
boundaryCursor: reply.timelineCursor,
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
};
}
return item.messageId ? { boundaryMessageId: item.messageId } : undefined;
return reply.messageId ? { boundaryMessageId: reply.messageId } : undefined;
}
@@ -16,8 +16,7 @@ function pluginReply(sourceId: string, part = "0"): StreamItem {
return {
kind: "plugin",
id: `math/${sourceId}/${part}`,
sourceId,
sourceKind: "assistant_message",
source: reply(sourceId),
timestamp: at,
pluginId: "math",
pluginItemId: `${sourceId}/${part}`,
@@ -99,10 +98,10 @@ describe("collapseTurns", () => {
expect(result.hostIdByFoldedMessageId.get("intermediate")).toBe("prompt");
});
it.each([undefined, "thought", "tool_call"] as const)(
"does not treat a plugin row with source kind %s as a reply",
(sourceKind) => {
const card = { ...pluginReply("card"), sourceKind };
it.each([undefined, thought("card"), shell("card")])(
"does not treat a plugin row replacing %o as a reply",
(source) => {
const card = { ...pluginReply("card"), source };
const items = [user("prompt"), shell("call"), card];
expect(collapse(items).tail).toEqual(items);
expect(collapse(items).summaryRowsByHostId.size).toBe(0);
@@ -1,6 +1,7 @@
import { isTurnBoundary, isTurnTrigger } from "../turn-membership";
import {
getStreamItemMessageId,
getAssistantReply,
type StreamItem,
type ThoughtItem,
type TimelinePosition,
@@ -103,22 +104,15 @@ function staysVisibleWhenCollapsed(item: StreamItem): boolean {
return isTurnTrigger(item) || item.kind === "compaction";
}
function isAssistantReply(item: StreamItem): boolean {
return (
item.kind === "assistant_message" ||
(item.kind === "plugin" && item.sourceKind === "assistant_message")
);
}
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
for (let index = end - 1; index >= start; index -= 1) {
const item = tail[index]!;
if (!isAssistantReply(item)) continue;
if (!getAssistantReply(item)) continue;
const messageId = getStreamItemMessageId(item);
// A transformer can split one reply into several cards; keep the whole reply visible.
while (index > start) {
const previous = tail[index - 1]!;
if (!isAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break;
if (!getAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break;
index -= 1;
}
return index;
@@ -156,7 +150,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse {
}
const folded = tail.slice(runStart, replyIndex);
const tools = summarizeTurn(folded, input.getGroupedCalls);
if (!hasWork(tools) && !folded.some(isAssistantReply)) {
if (!hasWork(tools) && !folded.some((item) => getAssistantReply(item))) {
output.push(...tail.slice(runStart, runEnd));
return;
}
@@ -150,3 +150,44 @@ describe("turn stats", () => {
expect(host.getBoundingClientRect().height).toBe(without);
});
});
const projectedReply: StreamItem = {
kind: "plugin",
id: "genui/reply/1",
source: {
kind: "assistant_message",
id: "reply",
messageId: "provider-reply-1",
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
timelineCursor: { epoch: "e1", seq: 5 },
timestamp: FRIDAY_NIGHT,
},
timelineCursor: { epoch: "e1", seq: 5 },
timestamp: FRIDAY_NIGHT,
pluginId: "genui",
pluginItemId: "reply/1",
itemKind: "genui-block",
version: 1,
data: {},
};
it("renders copy, fork, and duration for a plugin-projected assistant reply", () => {
const onFork = vi.fn();
act(() =>
root.render(
<CompletedTurnFooterRow
strategy={createNativeStreamStrategy()}
items={[projectedReply]}
timing={COMPLETED_TIMING}
startIndex={0}
supportsTimelineCursor={true}
onForkAssistantTurn={onFork}
/>,
),
);
expect(host.querySelector('[aria-label="Copy turn"]')).not.toBeNull();
expect(host.querySelector('[aria-label="Fork chat from here"]')).not.toBeNull();
expect(host.textContent).toContain("Worked for 26s");
});
@@ -4,7 +4,7 @@ import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { SPACING, type Theme } from "@/styles/theme";
import type { TurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
import { getAssistantReply, type StreamItem } from "@/types/stream";
import {
collectAssistantResponseContentForStreamRenderStrategy,
type StreamStrategy,
@@ -208,7 +208,7 @@ function CompletedTurnFooter({
return (
<View style={stylesheet.turnFooterSlot}>
<AssistantTurnFooter
getContent={items[startIndex]?.kind === "assistant_message" ? getContent : undefined}
getContent={getAssistantReply(items[startIndex]) ? getContent : undefined}
completedAt={timing?.completedAt}
durationMs={timing?.durationMs}
onFork={boundary && onForkAssistantTurn ? handleFork : undefined}
@@ -10,6 +10,7 @@ import {
DEFAULT_WEB_PARTIAL_VIRTUALIZATION_THRESHOLD,
estimateStreamItemHeight,
findMountedWindowStart,
MAX_MOUNTED_WEB_WINDOW_ITEMS,
getWebMountedRecentStreamItems,
getWebPartialVirtualizationThreshold,
splitWebVirtualizedHistory,
@@ -108,6 +109,37 @@ describe("findMountedWindowStart", () => {
}),
).toBe(39);
});
it("keeps a whole turn when the caller does not cap the rewind", () => {
const items = Array.from({ length: MAX_MOUNTED_WEB_WINDOW_ITEMS + 40 }, (_, index) => ({
...toolCall(`t${index}`, index % 60),
turnId: "long",
}));
expect(findMountedWindowStart({ items, minMountedCount: 20 })).toBe(0);
});
it("stops a long turn at the cap and still honors a larger minimum", () => {
const items = Array.from({ length: 200 }, (_, index) => ({
...toolCall(`t${index}`, index % 60),
turnId: "long",
}));
expect(
findMountedWindowStart({
items,
minMountedCount: 20,
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
}),
).toBe(200 - MAX_MOUNTED_WEB_WINDOW_ITEMS);
expect(
findMountedWindowStart({
items,
minMountedCount: 80,
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
}),
).toBe(120);
});
});
describe("splitWebVirtualizedHistory", () => {
@@ -130,6 +162,39 @@ describe("splitWebVirtualizedHistory", () => {
expect(window.mountedEntries[0]?.item.id).toBe("u5");
expect(window.mountedEntries).toHaveLength(50);
});
it("virtualizes the older rows of a turn that is longer than the mounted cap", () => {
const length = MAX_MOUNTED_WEB_WINDOW_ITEMS + 25;
const items = Array.from({ length }, (_, index) => ({
...toolCall(`t${index}`, index % 60),
turnId: "long",
}));
const window = splitWebVirtualizedHistory({
entries: indexEntries(items),
minMountedCount: DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS,
});
expect(window.mountedEntries).toHaveLength(MAX_MOUNTED_WEB_WINDOW_ITEMS);
expect(window.virtualizedEntries).toHaveLength(25);
expect(window.mountedEntries[0]?.item.id).toBe(`t${length - MAX_MOUNTED_WEB_WINDOW_ITEMS}`);
expect(window.virtualizedEntries[0]?.item.id).toBe("t0");
});
it("keeps a turn that fits under the cap mounted together", () => {
const items = Array.from({ length: 40 }, (_, index) => ({
...toolCall(`t${index}`, index),
turnId: "short",
}));
const window = splitWebVirtualizedHistory({
entries: indexEntries(items),
minMountedCount: DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS,
});
expect(window.virtualizedEntries).toHaveLength(0);
expect(window.mountedEntries).toHaveLength(40);
});
});
describe("estimateStreamItemHeight", () => {
@@ -8,6 +8,9 @@ import {
export const DEFAULT_WEB_PARTIAL_VIRTUALIZATION_THRESHOLD = 100;
export const DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS = DEFAULT_MOUNTED_RECENT_STREAM_ITEMS;
// Collapsed tool rows are about 40px, so this stays past a desktop viewport.
// Opening a long run mounts that tail and virtualizes the older rows.
export const MAX_MOUNTED_WEB_WINDOW_ITEMS = 60;
const COLLAPSED_TOOL_SEQUENCE_ROW_HEIGHT_ESTIMATE = 40;
type BottomAnchorE2ETestGlobals = typeof globalThis & {
@@ -87,6 +90,7 @@ export function splitWebVirtualizedHistory(input: {
const startIndex = findMountedWindowStart({
items: input.entries.map((entry) => entry.item),
minMountedCount: input.minMountedCount,
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
});
return {
virtualizedEntries: input.entries.slice(0, startIndex),
@@ -1,5 +1,20 @@
import { afterEach, describe, expect, it } from "vitest";
import { createAssistantSelectionClipboardContent } from "./content.web";
import { createElement as h } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { within } from "@testing-library/dom";
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
import { I18nextProvider } from "react-i18next";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WEB_RENDERERS } from "@/components/markdown/renderers.web";
import type { ToastApi } from "@/components/toast-host";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { i18n } from "@/i18n/i18next";
import {
createAssistantSelectionClipboardContent,
createElementClipboardContent,
} from "./content.web";
import { MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE } from "./markup";
const fixture = `
<div data-testid="assistant-message">
@@ -953,3 +968,158 @@ it("copies a workspace image path instead of its temporary display URL", () => {
"![chart](assets/chart.png)",
);
});
describe("quote copy", () => {
let root: Root | undefined;
let host: HTMLDivElement | undefined;
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
const queryClient = new QueryClient();
afterEach(() => {
const mounted = root;
if (mounted) flushSync(() => mounted.unmount());
root = undefined;
host?.remove();
host = undefined;
});
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
if (!host || !root) {
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
}
const mounted = root;
flushSync(() =>
mounted.render(
h(
QueryClientProvider,
{ client: queryClient },
h(
I18nextProvider,
{ i18n },
h(ToastApiProvider, {
api: toast,
children: h(EnrichedMarkdownText, {
markdown,
flavor: "github",
md4cFlags: { latexMath: false, admonitions: true },
renderers: WEB_RENDERERS,
}),
}),
),
),
),
);
const rendered = host;
await vi.waitFor(() => expect(rendered.textContent).toContain(lastText));
return rendered;
}
it("copies a quote's body with its formatting and without the quote marker", async () => {
const rendered = await renderMarkdown(
"> Hello **team**, see [the PR](https://example.test/pr).\n>\n> - Review\n>\n> > Nested reply",
"Nested reply",
);
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe(
"Hello **team**, see [the PR](https://example.test/pr).\n\n- Review\n\n> Nested reply",
);
expect(content?.html).toContain("<strong>team</strong>");
expect(content?.html).toContain("<blockquote>");
expect(content?.html).not.toContain("Copy quote");
});
it("gives a nested quote its own control that copies only the nested quote", async () => {
const rendered = await renderMarkdown("> Outer\n>\n> > Nested reply", "Nested reply");
const nested = fixtureElement(rendered, "blockquote", 1);
expect(within(rendered).getAllByRole("button", { name: "Copy quote" })).toHaveLength(2);
expect(within(nested).getAllByRole("button", { name: "Copy quote" })).toHaveLength(1);
expect(createElementClipboardContent(nested)?.plainText).toBe("Nested reply");
});
it("copies a code block inside a quote as its fence and keeps the code's own control", async () => {
const rendered = await renderMarkdown("> Run:\n>\n> ```sh\n> npm test\n> ```", "npm test");
const quote = fixtureElement(rendered, "blockquote");
expect(within(quote).getByRole("button", { name: "Copy code" })).toBeTruthy();
expect(createElementClipboardContent(quote)?.plainText).toBe("Run:\n\n```sh\nnpm test\n```");
});
it("copies what a streaming quote shows at the time of the copy", async () => {
const first = await renderMarkdown("> First draft", "First draft");
const quote = fixtureElement(first, "blockquote");
const revised = await renderMarkdown("> First draft, revised", "revised");
expect(fixtureElement(revised, "blockquote")).toBe(quote);
expect(createElementClipboardContent(quote)?.plainText).toBe("First draft, revised");
});
it("copies literal Markdown characters raw in text/plain and escaped in text/html", async () => {
const rendered = await renderMarkdown("> literal \\_word\\_ stays literal", "stays literal");
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe("literal _word_ stays literal");
expect(content?.html).toContain("literal _word_ stays literal");
expect(content?.html).not.toContain("<em>");
});
it("gives an admonition no copy control", async () => {
const rendered = await renderMarkdown("> [!NOTE]\n> Heads up", "Heads up");
expect(within(rendered).queryByRole("button", { name: "Copy quote" })).toBeNull();
});
it("copies a nested admonition as its callout source", async () => {
const rendered = await renderMarkdown(
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
"After",
);
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe("Before\n\n> [!WARNING]\n> Do not deploy.\n\nAfter");
});
it("copies a selection across an admonition as the text it shows, without a callout marker", async () => {
const rendered = await renderMarkdown(
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
"After",
);
rendered.setAttribute("data-testid", "assistant-message");
const body = tokenText(rendered, "Do not deploy.");
expect(
copyBetween([body, "Do not ".length], [tokenText(rendered, "After"), 5])?.plainText,
).toBe("deploy.\n\nAfter");
expect(
copyBetween([tokenText(rendered, "Before"), 0], [tokenText(rendered, "Warning"), 4])
?.plainText,
).toBe("Before\n\nWarn");
expect(
copyBetween([tokenText(rendered, "Before"), 0], [body, "Do not".length])?.plainText,
).not.toContain("[!WARNING]");
});
it("copies a rendered Mermaid diagram as its fence", () => {
const quote = document.createElement("blockquote");
quote.innerHTML = `<p>Before</p><div ${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}="graph TD; A-->B" data-paseo-markdown-language="mermaid"><svg aria-label="diagram"></svg></div><p>After</p>`;
expect(createElementClipboardContent(quote)?.plainText).toBe(
"Before\n\n```mermaid\ngraph TD; A-->B\n```\n\nAfter",
);
});
it("copies nothing from a quote that holds only its control", () => {
const quote = document.createElement("blockquote");
quote.innerHTML = '<button data-paseo-markdown-ignore="true">Copy quote</button>';
expect(createElementClipboardContent(quote)).toBeNull();
});
});
@@ -6,9 +6,12 @@ import {
type MarkdownClipboardContent,
} from "@/utils/rich-clipboard";
import {
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
MARKDOWN_COPY_ALIGN_ATTRIBUTE,
MARKDOWN_COPY_ALT_ATTRIBUTE,
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
MARKDOWN_COPY_IGNORE_ATTRIBUTE,
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE,
@@ -91,6 +94,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
} else {
turndown.escape = (text) => text;
}
// An admonition copies as its `> [!TYPE]` source.
turndown.addRule("admonition", {
filter: (node) => node.hasAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE),
replacement: (content, node) => {
const type = (node as Element)
.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE)!
.toUpperCase();
const body = content.replace(/^\n+|\n+$/g, "");
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
},
});
turndown.addRule("gfmStrikethrough", {
filter: ["del", "s"],
replacement: (content) => `~~${content}~~`,
@@ -120,6 +134,53 @@ function isWebUrl(href: string): boolean {
const markdownTurndown = createTurndown("markdown");
const plainTurndown = createTurndown("plain");
/**
* A fence rendered as something other than its code, such as a Mermaid diagram, carries
* its source in an attribute. Put the code block back so the fence is what gets copied.
*/
function restoreFenceSources(container: Element): void {
for (const region of container.querySelectorAll(`[${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}]`)) {
const source = region.getAttribute(MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE);
if (source === null) continue;
const pre = document.createElement("pre");
const code = document.createElement("code");
const language = region.getAttribute(MARKDOWN_COPY_LANGUAGE_ATTRIBUTE);
if (language) code.className = `language-${language}`;
code.textContent = source;
pre.append(code);
region.replaceWith(pre);
}
}
/**
* Clipboard payload for everything inside `element`, without the element's own syntax:
* a quote's body carries no `>` prefix. Null when there is nothing to copy.
*/
export function createElementClipboardContent(element: Element): MarkdownClipboardContent | null {
const container = document.createElement("div");
container.append(...Array.from(element.childNodes, (child) => child.cloneNode(true)));
const originals = element.querySelectorAll("*");
const copies = container.querySelectorAll("*");
originals.forEach((original, index) => copySemanticAttributes(original, copies[index]!));
restoreFenceSources(container);
restoreAdmonitions(container);
restoreMarkdownElements(container);
return clipboardContentFromMarkup(container);
}
function clipboardContentFromMarkup(container: HTMLElement): MarkdownClipboardContent | null {
const markdown = markdownTurndown.turndown(container).trim();
if (!markdown) {
return null;
}
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
// literal in a rich target.
const plainText = plainTurndown.turndown(container).trim();
const content = createSelectionClipboardContent(markdown, plainText);
return { ...content, html: flattenClipboardListMarkup(content.html) };
}
export function createAssistantSelectionClipboardContent(
selection: Selection | null,
): MarkdownClipboardContent | null {
@@ -145,17 +206,7 @@ export function createAssistantSelectionClipboardContent(
container.append(cloneMarkdownSelection(part.range, part.message));
}
restoreMarkdownElements(container);
const markdown = markdownTurndown.turndown(container).trim();
if (!markdown) {
return null;
}
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
// literal in a rich target.
const plainText = plainTurndown.turndown(container).trim();
const content = createSelectionClipboardContent(markdown, plainText);
return { ...content, html: flattenClipboardListMarkup(content.html) };
return clipboardContentFromMarkup(container);
}
/**
@@ -702,6 +753,28 @@ function numberOrderedListItems(list: Element, start: number): void {
});
}
/**
* The library renders an admonition as a box with a generated title. Keep it a quote
* with its type, so it copies as its callout source rather than as the title's prose.
* Only a whole-element copy does this: a selection cannot tell from its cloned markup
* whether it holds the whole callout, so it copies the text it shows.
*/
function restoreAdmonitions(container: Element): void {
const admonitions = Array.from(
container.querySelectorAll(`[${MARKDOWN_ADMONITION_TYPE_ATTRIBUTE}]`),
);
for (const admonition of admonitions.toReversed()) {
admonition.querySelector(`:scope > [${MARKDOWN_ADMONITION_TITLE_ATTRIBUTE}]`)?.remove();
const quote = document.createElement("blockquote");
quote.setAttribute(
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
admonition.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE) ?? "note",
);
quote.append(...admonition.childNodes);
admonition.replaceWith(quote);
}
}
function unwrapIncompleteTables(container: HTMLElement): void {
for (const table of container.querySelectorAll("table")) {
if (hasUsableTableColumnContract(table)) {

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